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.
@@ -0,0 +1,3023 @@
1
+ <!DOCTYPE html>
2
+ <!--
3
+ wireface — standalone editor (v011 — color palette · depth fade · jaw extend)
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
+ This editor is a self-contained authoring surface — it ships its own copy of
10
+ the rendering pipeline so it can write/edit/save preset JSON without the
11
+ library being embedded. The runtime in `wireface.js` consumes the JSON it
12
+ produces. A future revision will refactor the editor to consume the library
13
+ directly via createWireface().setRenderConfig().
14
+ -->
15
+ <html lang="en">
16
+ <head>
17
+ <meta charset="UTF-8" />
18
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
19
+ <title>WIREFACE v011 — color palette · depth fade · jaw extend</title>
20
+
21
+ <link rel="preconnect" href="https://fonts.googleapis.com">
22
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
23
+ <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
24
+
25
+ <style>
26
+ :root {
27
+ --bg: #000000;
28
+ --fg: #f4f4f0;
29
+ --dim: #6a6a64;
30
+ --accent: #f5e663;
31
+ --grid: #1a1a18;
32
+ --panel: rgba(8, 8, 8, 0.78);
33
+ --border: rgba(244, 244, 240, 0.12);
34
+ --border-bright: rgba(244, 244, 240, 0.35);
35
+ --mono: 'IBM Plex Mono', 'JetBrains Mono', ui-monospace, monospace;
36
+ }
37
+
38
+ * { box-sizing: border-box; margin: 0; padding: 0; }
39
+ html, body { width: 100%; height: 100%; overflow: hidden; background: var(--bg); color: var(--fg); font-family: var(--mono); font-weight: 300; -webkit-font-smoothing: antialiased; }
40
+
41
+ #renderCanvas { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; touch-action: none; outline: none; cursor: grab; }
42
+ #renderCanvas:active { cursor: grabbing; }
43
+
44
+ /* subtle scanlines + vignette */
45
+ .veil { position: fixed; inset: 0; pointer-events: none; z-index: 5; }
46
+ .veil.scan { background: repeating-linear-gradient(0deg, rgba(255,255,255,0.012) 0px, rgba(255,255,255,0.012) 1px, transparent 1px, transparent 3px); mix-blend-mode: overlay; }
47
+ .veil.vig { background: radial-gradient(ellipse at center, transparent 50%, rgba(0,0,0,0.55) 100%); }
48
+
49
+ /* ─── overlay grid ─── */
50
+ .overlay { position: fixed; inset: 0; pointer-events: none; z-index: 10; padding: 18px; display: grid; grid-template-columns: 320px 1fr 360px; grid-template-rows: auto 1fr auto; gap: 14px; }
51
+ .overlay > * { pointer-events: auto; }
52
+
53
+ /* ─── header ─── */
54
+ header { grid-column: 1 / -1; display: flex; align-items: baseline; justify-content: space-between; gap: 24px; padding: 4px 6px; }
55
+ header .brand { display: flex; align-items: baseline; gap: 14px; }
56
+ header .mark { font-family: var(--mono); font-weight: 600; letter-spacing: 0.18em; font-size: 13px; color: var(--fg); }
57
+ header .mark::before { content: '◣'; color: var(--accent); margin-right: 8px; }
58
+ header .sub { font-size: 10px; color: var(--dim); letter-spacing: 0.12em; text-transform: uppercase; }
59
+ header .sub::before { content: '/ '; color: var(--accent); }
60
+ header .meta { font-size: 10px; color: var(--dim); letter-spacing: 0.16em; text-transform: uppercase; display: flex; gap: 18px; }
61
+ header .meta b { color: var(--fg); font-weight: 400; }
62
+
63
+ /* ─── panels ─── */
64
+ .panel { background: var(--panel); border: 1px solid var(--border); backdrop-filter: blur(8px); padding: 14px 14px 12px; font-size: 11px; }
65
+ .panel h3 { font-size: 10px; font-weight: 500; letter-spacing: 0.22em; text-transform: uppercase; color: var(--dim); margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
66
+ .panel h3 .num { font-family: var(--mono); color: var(--accent); font-size: 9px; letter-spacing: 0.05em; }
67
+
68
+ /* left column */
69
+ #left { grid-column: 1; grid-row: 2; display: flex; flex-direction: column; gap: 14px; overflow: hidden; }
70
+ #right { grid-column: 3; grid-row: 2; display: flex; flex-direction: column; gap: 14px; overflow-y: auto; overflow-x: hidden; padding-right: 4px; }
71
+ #bottom { grid-column: 1 / -1; grid-row: 3; }
72
+
73
+ /* channel sliders */
74
+ .chan-list { overflow-y: auto; max-height: 100%; padding-right: 4px; }
75
+ .chan-list::-webkit-scrollbar { width: 4px; }
76
+ .chan-list::-webkit-scrollbar-track { background: transparent; }
77
+ .chan-list::-webkit-scrollbar-thumb { background: var(--border-bright); }
78
+
79
+ .chan-group { margin-bottom: 14px; }
80
+ .chan-group .label { font-size: 9px; letter-spacing: 0.18em; text-transform: uppercase; color: var(--dim); margin-bottom: 6px; padding-left: 2px; }
81
+ .chan-group .label::after { content: ''; display: inline-block; width: 6px; height: 1px; background: var(--accent); margin-left: 8px; vertical-align: middle; }
82
+
83
+ .chan { display: grid; grid-template-columns: 88px 1fr 36px 18px; gap: 8px; align-items: center; padding: 3px 0; font-size: 10px; }
84
+ .chan-name { font-weight: 400; color: var(--fg); letter-spacing: 0.04em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; opacity: 0.85; }
85
+ .chan-bar { position: relative; height: 14px; background: rgba(255,255,255,0.04); border: 1px solid var(--border); cursor: pointer; }
86
+ .chan-bar .fill { position: absolute; left: 0; top: 0; bottom: 0; background: linear-gradient(90deg, var(--fg) 0%, var(--accent) 100%); transition: width 0.05s linear; }
87
+ .chan-bar .live { position: absolute; right: 2px; top: 1px; bottom: 1px; width: 2px; background: var(--accent); opacity: 0; }
88
+ .chan-bar.active .live { opacity: 1; }
89
+ .chan-val { font-size: 10px; color: var(--dim); text-align: right; font-variant-numeric: tabular-nums; }
90
+
91
+ /* per-channel gain knob — bipolar dial that scales how much that channel
92
+ contributes to mesh deformation. marker at top (0deg) = 1x (default),
93
+ full counter-clockwise (-135deg) = mute, full clockwise (+135deg) ≈ 4x. */
94
+ .knob { width: 16px; height: 16px; border-radius: 50%; border: 1px solid var(--border-bright); position: relative; cursor: ns-resize; background: rgba(255,255,255,0.02); flex-shrink: 0; touch-action: none; }
95
+ .knob:hover { border-color: var(--fg); }
96
+ .knob.gained { border-color: var(--accent); }
97
+ .knob-marker { position: absolute; left: calc(50% - 0.75px); top: 1px; width: 1.5px; height: 6px; background: var(--fg); transform-origin: 50% 7px; transform: rotate(0deg); pointer-events: none; }
98
+ .knob.gained .knob-marker { background: var(--accent); }
99
+
100
+ /* presets list inside SESSION panel */
101
+ .preset-list { display: flex; flex-direction: column; gap: 4px; max-height: 180px; overflow-y: auto; padding-right: 2px; margin-top: 4px; }
102
+ .preset-list:empty::before { content: 'no presets yet — hit save'; font-size: 9px; color: var(--dim); padding: 6px 4px; letter-spacing: 0.08em; }
103
+ .preset-item { display: grid; grid-template-columns: 1fr 18px 18px; gap: 4px; align-items: center; padding: 5px 6px; background: rgba(255,255,255,0.02); border: 1px solid var(--border); font-size: 10px; cursor: pointer; transition: background 0.1s; }
104
+ .preset-item:hover { background: rgba(255,235,59,0.08); border-color: var(--accent); }
105
+ .preset-item .pname { color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: 0.04em; }
106
+ .preset-item .picon { color: var(--dim); text-align: center; cursor: pointer; font-size: 11px; line-height: 1; }
107
+ .preset-item .picon:hover { color: var(--accent); }
108
+ .preset-item .picon.del:hover { color: #ff5050; }
109
+
110
+ /* color picker rows — native input[type=color] in our chrome */
111
+ .color-row { display: grid; grid-template-columns: 92px 1fr 36px; gap: 10px; align-items: center; padding: 3px 0; font-size: 10px; }
112
+ .color-row .ctl-name { font-weight: 400; color: var(--fg); letter-spacing: 0.04em; opacity: 0.85; }
113
+ .color-row input[type=color] { width: 100%; height: 18px; border: 1px solid var(--border-bright); background: transparent; cursor: pointer; padding: 1px; }
114
+ .color-row input[type=color]::-webkit-color-swatch-wrapper { padding: 0; }
115
+ .color-row input[type=color]::-webkit-color-swatch { border: none; }
116
+ .color-row .ctl-val { font-size: 10px; color: var(--dim); text-align: right; font-variant-numeric: tabular-nums; }
117
+
118
+ /* buttons */
119
+ button, .btn { font-family: var(--mono); font-size: 10px; font-weight: 400; letter-spacing: 0.16em; text-transform: uppercase; background: transparent; color: var(--fg); border: 1px solid var(--border-bright); padding: 9px 12px; cursor: pointer; transition: all 0.12s; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
120
+ button:hover, .btn:hover { background: var(--fg); color: var(--bg); border-color: var(--fg); }
121
+ button:disabled { opacity: 0.3; cursor: not-allowed; }
122
+ button:disabled:hover { background: transparent; color: var(--fg); border-color: var(--border-bright); }
123
+ button.primary { background: var(--accent); color: var(--bg); border-color: var(--accent); }
124
+ button.primary:hover { background: var(--fg); border-color: var(--fg); }
125
+ button.recording { border-color: #ff3838; color: #ff3838; animation: pulse 1.2s infinite; }
126
+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
127
+
128
+ .btn-row { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
129
+ .btn-row.three { grid-template-columns: repeat(3, 1fr); }
130
+ .btn-row.full { grid-template-columns: 1fr; }
131
+
132
+ /* file drop */
133
+ .file-input { position: relative; }
134
+ .file-input input { position: absolute; opacity: 0; pointer-events: none; }
135
+ .file-name { font-size: 10px; color: var(--dim); margin-top: 6px; padding: 4px 6px; border-left: 2px solid var(--accent); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
136
+
137
+ /* mood pills */
138
+ .mood-row { display: flex; flex-wrap: wrap; gap: 4px; }
139
+ .mood-row button { padding: 6px 9px; font-size: 9px; flex: 1; min-width: 0; }
140
+ .mood-row button.on { background: var(--accent); color: var(--bg); border-color: var(--accent); }
141
+
142
+ /* render config sliders */
143
+ .ctl { display: grid; grid-template-columns: 78px 1fr 32px; gap: 8px; align-items: center; padding: 4px 0; font-size: 10px; }
144
+ .ctl-name { color: var(--fg); opacity: 0.78; letter-spacing: 0.04em; white-space: nowrap; }
145
+ .ctl-bar { position: relative; height: 14px; background: rgba(255,255,255,0.04); border: 1px solid var(--border); cursor: pointer; }
146
+ .ctl-bar .fill { position: absolute; left: 0; top: 0; bottom: 0; background: linear-gradient(90deg, rgba(245,230,99,0.25), rgba(245,230,99,0.6)); }
147
+ .ctl-val { font-size: 10px; color: var(--dim); text-align: right; font-variant-numeric: tabular-nums; }
148
+ .seg-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; margin-top: 6px; }
149
+ .seg-row button { padding: 6px 4px; font-size: 9px; }
150
+ .seg-row button.on { background: var(--accent); color: var(--bg); border-color: var(--accent); }
151
+ .toggle-row { display: flex; align-items: center; justify-content: space-between; padding: 6px 0; font-size: 10px; color: var(--fg); opacity: 0.85; }
152
+ .toggle { width: 28px; height: 14px; background: rgba(255,255,255,0.06); border: 1px solid var(--border); position: relative; cursor: pointer; }
153
+ .toggle::after { content: ''; position: absolute; top: 1px; left: 1px; width: 10px; height: 10px; background: var(--dim); transition: all 0.15s; }
154
+ .toggle.on { background: rgba(245,230,99,0.2); border-color: var(--accent); }
155
+ .toggle.on::after { left: 15px; background: var(--accent); }
156
+
157
+ /* timeline */
158
+ #bottom { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 12px 16px; background: var(--panel); border: 1px solid var(--border); backdrop-filter: blur(8px); }
159
+ .transport { display: flex; gap: 6px; align-items: center; }
160
+ .transport button { padding: 8px 10px; min-width: 38px; font-size: 11px; }
161
+ #timeline { position: relative; height: 28px; background: rgba(255,255,255,0.03); border: 1px solid var(--border); cursor: pointer; }
162
+ #timeline .progress { position: absolute; left: 0; top: 0; bottom: 0; background: linear-gradient(90deg, rgba(245,230,99,0.18), rgba(245,230,99,0.4)); width: 0%; }
163
+ #timeline .head { position: absolute; top: -2px; bottom: -2px; width: 1px; background: var(--accent); box-shadow: 0 0 6px var(--accent); transform: translateX(-50%); pointer-events: none; }
164
+ #timeline .ticks { position: absolute; inset: 0; background-image: repeating-linear-gradient(90deg, transparent 0, transparent 49px, var(--border) 49px, var(--border) 50px); }
165
+ .time-readout { font-size: 11px; font-variant-numeric: tabular-nums; color: var(--fg); letter-spacing: 0.08em; min-width: 110px; text-align: right; }
166
+ .time-readout .dim { color: var(--dim); }
167
+
168
+ /* status indicator */
169
+ .status { display: flex; align-items: center; gap: 6px; font-size: 9px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--dim); }
170
+ .status .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--dim); }
171
+ .status.live .dot { background: var(--accent); box-shadow: 0 0 8px var(--accent); animation: pulse 1.2s infinite; }
172
+ .status.rec .dot { background: #ff3838; box-shadow: 0 0 8px #ff3838; animation: pulse 1.2s infinite; }
173
+
174
+ /* corner crosshairs */
175
+ .crosshair { position: fixed; width: 14px; height: 14px; border: 1px solid var(--border-bright); pointer-events: none; z-index: 6; }
176
+ .crosshair.tl { top: 16px; left: 16px; border-right: 0; border-bottom: 0; }
177
+ .crosshair.tr { top: 16px; right: 16px; border-left: 0; border-bottom: 0; }
178
+ .crosshair.bl { bottom: 16px; left: 16px; border-right: 0; border-top: 0; }
179
+ .crosshair.br { bottom: 16px; right: 16px; border-left: 0; border-top: 0; }
180
+
181
+ /* coord readout */
182
+ .coord { position: fixed; bottom: 100px; right: 24px; font-size: 9px; color: var(--dim); letter-spacing: 0.1em; text-transform: uppercase; pointer-events: none; z-index: 6; text-align: right; line-height: 1.6; }
183
+ .coord b { color: var(--fg); font-weight: 400; }
184
+
185
+ /* slim layout when narrow */
186
+ @media (max-width: 1100px) {
187
+ .overlay { grid-template-columns: 280px 1fr; }
188
+ #right { display: none; }
189
+ }
190
+ </style>
191
+ </head>
192
+ <body>
193
+
194
+ <canvas id="renderCanvas"></canvas>
195
+
196
+ <div class="veil scan"></div>
197
+ <div class="veil vig"></div>
198
+
199
+ <div class="crosshair tl"></div>
200
+ <div class="crosshair tr"></div>
201
+ <div class="crosshair bl"></div>
202
+ <div class="crosshair br"></div>
203
+
204
+ <div class="coord">
205
+ <div>FRAME <b id="coord-frame">0000</b></div>
206
+ <div>FPS <b id="coord-fps">60</b></div>
207
+ <div>CH <b id="coord-ch">30</b> ACTIVE <b id="coord-active">0</b></div>
208
+ <div>TRI <b id="coord-tris">000</b> VERT <b id="coord-verts">000</b></div>
209
+ <div>ANCHOR <b id="coord-anchor">00/00</b></div>
210
+ </div>
211
+
212
+ <div class="overlay">
213
+
214
+ <header>
215
+ <div class="brand">
216
+ <div class="mark">WIREFACE</div>
217
+ <div class="sub">v011 · palette · jaw extend · iris</div>
218
+ </div>
219
+ <div class="meta">
220
+ <span>BLEND <b>Oculus·15</b></span>
221
+ <span>SHAPE <b>ARKit·15</b></span>
222
+ <span class="status" id="status"><span class="dot"></span><span id="status-text">idle</span></span>
223
+ </div>
224
+ </header>
225
+
226
+ <!-- LEFT: channels -->
227
+ <div id="left">
228
+ <div class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
229
+ <h3>channels <span class="num" id="ch-count">30</span></h3>
230
+ <div class="chan-list" id="chan-list"></div>
231
+ </div>
232
+ </div>
233
+
234
+ <!-- RIGHT: controls -->
235
+ <div id="right">
236
+ <div class="panel">
237
+ <h3>audio source <span class="num">01</span></h3>
238
+ <div class="btn-row full" style="margin-bottom: 6px;">
239
+ <label class="btn file-input">
240
+ load .mp3 / .wav
241
+ <input type="file" id="audio-file" accept="audio/*">
242
+ </label>
243
+ </div>
244
+ <div class="file-name" id="audio-name">no file loaded — using built-in test tone</div>
245
+ <div class="toggle-row">
246
+ <span>loop audio</span>
247
+ <div class="toggle on" data-toggle="loopAudio"></div>
248
+ </div>
249
+ </div>
250
+
251
+ <div class="panel">
252
+ <h3>moods <span class="num">07</span></h3>
253
+ <div class="mood-row">
254
+ <button data-mood="neutral" class="on">neutral</button>
255
+ <button data-mood="happy">happy</button>
256
+ <button data-mood="sad">sad</button>
257
+ <button data-mood="angry">angry</button>
258
+ <button data-mood="fear">fear</button>
259
+ <button data-mood="surprise">surpr</button>
260
+ <button data-mood="sleep">sleep</button>
261
+ </div>
262
+ </div>
263
+
264
+ <div class="panel">
265
+ <h3>view <span class="num">04</span></h3>
266
+ <div class="btn-row">
267
+ <button data-view="front">front</button>
268
+ <button data-view="three-q">3/4</button>
269
+ <button data-view="profile">profile</button>
270
+ <button data-view="orbit">orbit</button>
271
+ </div>
272
+ </div>
273
+
274
+ <div class="panel">
275
+ <h3>render <span class="num">mesh</span></h3>
276
+
277
+ <div class="ctl"><div class="ctl-name">cols</div><div class="ctl-bar" data-rcfg="meshCols" data-min="5" data-max="21" data-step="2"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="meshCols">7</div></div>
278
+ <div class="ctl"><div class="ctl-name">rows</div><div class="ctl-bar" data-rcfg="meshRows" data-min="7" data-max="25" data-step="2"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="meshRows">9</div></div>
279
+ <div class="ctl"><div class="ctl-name">nose</div><div class="ctl-bar" data-rcfg="scaleNose" data-min="0.4" data-max="2.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="scaleNose">1.00</div></div>
280
+ <div class="ctl"><div class="ctl-name">eyes</div><div class="ctl-bar" data-rcfg="scaleEyes" data-min="0.4" data-max="2.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="scaleEyes">1.00</div></div>
281
+ <div class="ctl"><div class="ctl-name">mouth</div><div class="ctl-bar" data-rcfg="scaleMouth" data-min="0.4" data-max="2.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="scaleMouth">1.00</div></div>
282
+ <div class="ctl"><div class="ctl-name">react</div><div class="ctl-bar" data-rcfg="reactivity" data-min="0" data-max="0.6" data-step="0.02"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="reactivity">0.25</div></div>
283
+ <div class="ctl"><div class="ctl-name">spread</div><div class="ctl-bar" data-rcfg="spread" data-min="0.5" data-max="2.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="spread">1.00</div></div>
284
+ <div class="ctl"><div class="ctl-name">mouth ⊘</div><div class="ctl-bar" data-rcfg="mouthHoleSize" data-min="0.4" data-max="2.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="mouthHoleSize">1.00</div></div>
285
+ <div class="ctl"><div class="ctl-name">eye depth</div><div class="ctl-bar" data-rcfg="eyeDepth" data-min="0" data-max="5" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="eyeDepth">1.00</div></div>
286
+ <div class="ctl"><div class="ctl-name">line ━</div><div class="ctl-bar" data-rcfg="lineThickness" data-min="0.4" data-max="3.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="lineThickness">1.00</div></div>
287
+ <div class="ctl"><div class="ctl-name">lip y-amp</div><div class="ctl-bar" data-rcfg="lipVertAmp" data-min="0.5" data-max="4.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="lipVertAmp">1.60</div></div>
288
+ <div class="ctl"><div class="ctl-name">lip close</div><div class="ctl-bar" data-rcfg="lipPressForce" data-min="0" data-max="3" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="lipPressForce">1.00</div></div>
289
+
290
+ <div class="seg-row">
291
+ <button data-mode="wire" class="on">wire</button>
292
+ <button data-mode="edges">edges</button>
293
+ <button data-mode="shaded">shaded</button>
294
+ </div>
295
+
296
+ <div class="toggle-row">
297
+ <span>mouth puncture</span>
298
+ <div class="toggle on" data-toggle="mouthHole"></div>
299
+ </div>
300
+ <div class="toggle-row">
301
+ <span>mouth anchor</span>
302
+ <div class="toggle on" data-toggle="mouthAnchor"></div>
303
+ </div>
304
+ <div class="toggle-row">
305
+ <span>eye puncture</span>
306
+ <div class="toggle" data-toggle="eyeHoles"></div>
307
+ </div>
308
+ <div class="toggle-row">
309
+ <span>eye anchor</span>
310
+ <div class="toggle" data-toggle="eyeAnchor"></div>
311
+ </div>
312
+ <div class="toggle-row">
313
+ <span>overlay → mesh</span>
314
+ <div class="toggle on" data-toggle="overlayTracksMesh"></div>
315
+ </div>
316
+ <div class="toggle-row">
317
+ <span>flip face 180°</span>
318
+ <div class="toggle on" data-toggle="flipFace"></div>
319
+ </div>
320
+ <div class="toggle-row">
321
+ <span>show mesh</span>
322
+ <div class="toggle on" data-toggle="meshVisible"></div>
323
+ </div>
324
+ <div class="toggle-row">
325
+ <span>fragment (oval clip)</span>
326
+ <div class="toggle" data-toggle="fragment"></div>
327
+ </div>
328
+ <div class="toggle-row">
329
+ <span>minimal lines</span>
330
+ <div class="toggle on" data-toggle="minimal"></div>
331
+ </div>
332
+ <div class="toggle-row">
333
+ <span>glow / highlights</span>
334
+ <div class="toggle" data-toggle="glow"></div>
335
+ </div>
336
+ <div class="toggle-row">
337
+ <span>pupils</span>
338
+ <div class="toggle" data-toggle="pupils"></div>
339
+ </div>
340
+
341
+ <div class="label" style="font-size:9px;letter-spacing:0.18em;text-transform:uppercase;color:var(--dim);margin-top:14px;margin-bottom:6px;">moods</div>
342
+ <div class="ctl"><div class="ctl-name">mood time</div><div class="ctl-bar" data-rcfg="moodTransitionTime" data-min="0.05" data-max="5.0" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="moodTransitionTime">0.60</div></div>
343
+
344
+ <div class="label" style="font-size:9px;letter-spacing:0.18em;text-transform:uppercase;color:var(--dim);margin-top:14px;margin-bottom:6px;">jaw + growth</div>
345
+ <div class="ctl"><div class="ctl-name">jaw extend</div><div class="ctl-bar" data-rcfg="jawExtend" data-min="0" data-max="3" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="jawExtend">0.00</div></div>
346
+ <div class="ctl"><div class="ctl-name">mouth grow</div><div class="ctl-bar" data-rcfg="mouthGrow" data-min="0" data-max="1.5" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="mouthGrow">0.00</div></div>
347
+
348
+ <div class="label" style="font-size:9px;letter-spacing:0.18em;text-transform:uppercase;color:var(--dim);margin-top:14px;margin-bottom:6px;">colors</div>
349
+ <div class="color-row"><div class="ctl-name">base</div><input type="color" id="color-base" value="#ffffff"><div class="ctl-val" id="color-base-val">FFF</div></div>
350
+ <div class="color-row"><div class="ctl-name">depth fade</div><input type="color" id="color-fade" value="#000000"><div class="ctl-val" id="color-fade-val">000</div></div>
351
+ <div class="ctl"><div class="ctl-name">fade ░░</div><div class="ctl-bar" data-rcfg="depthFade" data-min="0" data-max="1" data-step="0.02"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="depthFade">0.00</div></div>
352
+ <div class="color-row"><div class="ctl-name">line</div><input type="color" id="color-line" value="#ffffff"><div class="ctl-val" id="color-line-val">FFF</div></div>
353
+ <div class="color-row"><div class="ctl-name">brow</div><input type="color" id="color-brow" value="#ffffff"><div class="ctl-val" id="color-brow-val">FFF</div></div>
354
+ <div class="color-row"><div class="ctl-name">pupil</div><input type="color" id="color-pupil" value="#ffffff"><div class="ctl-val" id="color-pupil-val">FFF</div></div>
355
+ <div class="color-row"><div class="ctl-name">iris</div><input type="color" id="color-iris" value="#000000"><div class="ctl-val" id="color-iris-val">000</div></div>
356
+ <div class="ctl"><div class="ctl-name">iris ⊙</div><div class="ctl-bar" data-rcfg="irisSize" data-min="1" data-max="4" data-step="0.05"><div class="fill"></div></div><div class="ctl-val" data-rcfg-val="irisSize">1.60</div></div>
357
+ </div>
358
+
359
+ <div class="panel">
360
+ <h3>session <span class="num">i/o</span></h3>
361
+ <div class="btn-row" style="margin-bottom: 6px;">
362
+ <button id="btn-record">● record</button>
363
+ <button id="btn-export" disabled>↓ export json</button>
364
+ </div>
365
+ <div class="btn-row">
366
+ <label class="btn file-input">
367
+ ↑ import json
368
+ <input type="file" id="json-file" accept="application/json,.json">
369
+ </label>
370
+ <button id="btn-clear">clear track</button>
371
+ </div>
372
+ <div class="file-name" id="track-info">no track recorded</div>
373
+
374
+ <div class="label" style="font-size:9px;letter-spacing:0.18em;text-transform:uppercase;color:var(--dim);margin-top:14px;margin-bottom:4px;">presets</div>
375
+ <div class="btn-row" style="margin-bottom: 4px;">
376
+ <button id="btn-preset-save">+ save preset</button>
377
+ <button id="btn-preset-export-all" disabled>↓ export all</button>
378
+ </div>
379
+ <div class="btn-row full" style="margin-bottom: 4px;">
380
+ <label class="btn file-input">
381
+ ↑ import preset(s)
382
+ <input type="file" id="preset-file" accept="application/json,.json">
383
+ </label>
384
+ </div>
385
+ <div class="preset-list" id="preset-list"></div>
386
+ </div>
387
+ </div>
388
+
389
+ <!-- BOTTOM: transport -->
390
+ <div id="bottom">
391
+ <div class="transport">
392
+ <button id="btn-play">▶ play</button>
393
+ <button id="btn-stop">■ stop</button>
394
+ </div>
395
+ <div id="timeline">
396
+ <div class="ticks"></div>
397
+ <div class="progress" id="progress"></div>
398
+ <div class="head" id="playhead" style="left: 0%"></div>
399
+ </div>
400
+ <div class="time-readout"><span id="t-cur">00:00.00</span><span class="dim"> / <span id="t-tot">00:00.00</span></span></div>
401
+ </div>
402
+
403
+ </div>
404
+
405
+ <script>
406
+ /* Try CDNs in sequence so a temporary outage doesn't kill the app.
407
+ Pinned to babylonjs@9 — bumped from 8.20 alongside the v1.0 release of
408
+ the wireface library (which itself targets Babylon v9 features incl. GlowLayer). */
409
+ (function loadBabylon() {
410
+ const sources = [
411
+ 'https://cdn.jsdelivr.net/npm/babylonjs@9/babylon.js',
412
+ 'https://unpkg.com/babylonjs@9/babylon.js',
413
+ 'https://cdnjs.cloudflare.com/ajax/libs/babylonjs/9.5.0/babylon.min.js',
414
+ ];
415
+ let i = 0;
416
+ function tryNext() {
417
+ if (i >= sources.length) {
418
+ document.body.insertAdjacentHTML('afterbegin',
419
+ '<div style="position:fixed;inset:0;display:grid;place-items:center;background:#000;color:#f4f4f0;font-family:monospace;z-index:99999;padding:24px;text-align:center;">' +
420
+ '<div><div style="color:#f5e663;letter-spacing:.2em;margin-bottom:12px">⚠ BABYLON.JS FAILED TO LOAD</div>' +
421
+ '<div style="font-size:11px;color:#888">All CDNs unreachable. Check your network/firewall.</div></div></div>');
422
+ return;
423
+ }
424
+ const s = document.createElement('script');
425
+ s.src = sources[i++];
426
+ s.onload = () => {
427
+ if (typeof window.BABYLON !== 'undefined' && window.BABYLON.Engine) {
428
+ try {
429
+ bootWireface();
430
+ } catch (err) {
431
+ console.error('WIREFACE boot error:', err);
432
+ console.error(err.stack);
433
+ document.body.insertAdjacentHTML('afterbegin',
434
+ '<div style="position:fixed;top:0;left:0;right:0;background:#300;color:#faa;font-family:monospace;font-size:11px;padding:10px 14px;z-index:99999;border-bottom:1px solid #600;">' +
435
+ '<b>BOOT ERROR:</b> ' + (err.message || err) + ' &nbsp;·&nbsp; <span style="color:#888">see console for stack</span></div>');
436
+ }
437
+ } else {
438
+ tryNext();
439
+ }
440
+ };
441
+ s.onerror = tryNext;
442
+ document.head.appendChild(s);
443
+ }
444
+ tryNext();
445
+ })();
446
+
447
+ function bootWireface() {
448
+ /* ═══════════════════════════════════════════════════════════════════════════
449
+ WIREFACE — viseme channel sequencer
450
+ ─────────────────────────────────────────────────────────────────────────
451
+ 30 named channels, 0-1 weights, sampled at 60Hz. Drives parametric
452
+ wireframe face geometry. Live audio FFT estimates visemes in real time.
453
+ Recordings export as compact JSON event tracks (MIDI-style).
454
+ ═════════════════════════════════════════════════════════════════════════ */
455
+
456
+ const BABYLON = window.BABYLON;
457
+
458
+ /* ─── 1. CHANNEL DEFINITIONS ─────────────────────────────────────────────
459
+ Each channel is a named 0-1 (or -1..1) float. Grouped by part.
460
+ These are the "MIDI channels" the user records and exports. */
461
+
462
+ const CHANNELS = {
463
+ /* mouth — Oculus visemes (15) */
464
+ viseme_sil: { group: 'mouth', range: [0,1], def: 1.0 },
465
+ viseme_PP: { group: 'mouth', range: [0,1], def: 0 },
466
+ viseme_FF: { group: 'mouth', range: [0,1], def: 0 },
467
+ viseme_TH: { group: 'mouth', range: [0,1], def: 0 },
468
+ viseme_DD: { group: 'mouth', range: [0,1], def: 0 },
469
+ viseme_kk: { group: 'mouth', range: [0,1], def: 0 },
470
+ viseme_CH: { group: 'mouth', range: [0,1], def: 0 },
471
+ viseme_SS: { group: 'mouth', range: [0,1], def: 0 },
472
+ viseme_nn: { group: 'mouth', range: [0,1], def: 0 },
473
+ viseme_RR: { group: 'mouth', range: [0,1], def: 0 },
474
+ viseme_aa: { group: 'mouth', range: [0,1], def: 0 },
475
+ viseme_E: { group: 'mouth', range: [0,1], def: 0 },
476
+ viseme_I: { group: 'mouth', range: [0,1], def: 0 },
477
+ viseme_O: { group: 'mouth', range: [0,1], def: 0 },
478
+ viseme_U: { group: 'mouth', range: [0,1], def: 0 },
479
+
480
+ /* mouth shape modifiers — ARKit-style */
481
+ jawOpen: { group: 'jaw', range: [0,1], def: 0 },
482
+ mouthSmile: { group: 'jaw', range: [-1,1], def: 0 }, // negative = frown
483
+ mouthPucker: { group: 'jaw', range: [0,1], def: 0 },
484
+
485
+ /* eyes */
486
+ eyeBlinkLeft: { group: 'eyes', range: [0,1], def: 0 },
487
+ eyeBlinkRight: { group: 'eyes', range: [0,1], def: 0 },
488
+ eyeLookH: { group: 'eyes', range: [-1,1], def: 0 }, // -1 left, +1 right
489
+ eyeLookV: { group: 'eyes', range: [-1,1], def: 0 }, // -1 down, +1 up
490
+ eyeSquint: { group: 'eyes', range: [0,1], def: 0 },
491
+
492
+ /* brows */
493
+ browInnerUp: { group: 'brows', range: [0,1], def: 0 },
494
+ browOuterUp: { group: 'brows', range: [-1,1], def: 0 },
495
+ browDown: { group: 'brows', range: [0,1], def: 0 },
496
+
497
+ /* nose */
498
+ noseSneer: { group: 'nose', range: [0,1], def: 0 },
499
+
500
+ /* head pose */
501
+ headRotateX: { group: 'head', range: [-1,1], def: 0 },
502
+ headRotateY: { group: 'head', range: [-1,1], def: 0 },
503
+ headRotateZ: { group: 'head', range: [-1,1], def: 0 },
504
+ };
505
+ const CHANNEL_NAMES = Object.keys(CHANNELS);
506
+
507
+ /* live state — every channel's current value */
508
+ const state = {};
509
+ const stateTarget = {}; // smoothed-toward target
510
+ CHANNEL_NAMES.forEach(n => { state[n] = CHANNELS[n].def; stateTarget[n] = CHANNELS[n].def; });
511
+
512
+ /* manual overrides (when user drags a slider, lock value) */
513
+ const manualLock = {};
514
+
515
+ /* ─── 2. VISEME → MOUTH-PARAM PRESETS ────────────────────────────────────
516
+ Each viseme defines (open, width, round, smile, lipPress, jaw) deltas
517
+ that get weighted-summed at runtime. Numbers feel-tuned. */
518
+
519
+ const VISEME_PARAMS = {
520
+ sil: { open: 0.00, width: 0.00, round: 0.00, smile: 0.00, lipPress: 0.30, jaw: 0.00 },
521
+ PP: { open: 0.00, width: 0.00, round: 0.20, smile: 0.00, lipPress: 0.95, jaw: 0.00 },
522
+ FF: { open: 0.10, width: 0.05, round: 0.00, smile: 0.05, lipPress: 0.55, jaw: 0.10 },
523
+ TH: { open: 0.20, width: 0.15, round: 0.00, smile: 0.00, lipPress: 0.10, jaw: 0.18 },
524
+ DD: { open: 0.28, width: 0.25, round: 0.00, smile: 0.05, lipPress: 0.05, jaw: 0.25 },
525
+ kk: { open: 0.32, width: 0.20, round: 0.00, smile: 0.00, lipPress: 0.05, jaw: 0.30 },
526
+ CH: { open: 0.32, width: 0.00, round: 0.55, smile: 0.00, lipPress: 0.10, jaw: 0.25 },
527
+ SS: { open: 0.18, width: 0.45, round: 0.00, smile: 0.20, lipPress: 0.20, jaw: 0.10 },
528
+ nn: { open: 0.18, width: 0.18, round: 0.00, smile: 0.00, lipPress: 0.30, jaw: 0.18 },
529
+ RR: { open: 0.35, width: 0.00, round: 0.50, smile: 0.00, lipPress: 0.05, jaw: 0.25 },
530
+ aa: { open: 0.85, width: 0.45, round: 0.00, smile: 0.00, lipPress: 0.00, jaw: 0.85 },
531
+ E: { open: 0.50, width: 0.65, round: 0.00, smile: 0.20, lipPress: 0.00, jaw: 0.45 },
532
+ I: { open: 0.28, width: 0.85, round: 0.00, smile: 0.30, lipPress: 0.00, jaw: 0.18 },
533
+ O: { open: 0.55, width: 0.00, round: 0.75, smile: 0.00, lipPress: 0.00, jaw: 0.45 },
534
+ U: { open: 0.35, width: -0.15, round: 0.95, smile: 0.00, lipPress: 0.05, jaw: 0.25 },
535
+ };
536
+
537
+ /* compute aggregated mouth params from current viseme weights */
538
+ function computeMouthParams() {
539
+ // weighted average. Total weight clamps at 1; if visemes don't sum to 1,
540
+ // remainder goes to 'sil' implicitly (since sil=zeros, this just damps).
541
+ let totalW = 0;
542
+ const out = { open: 0, width: 0, round: 0, smile: 0, lipPress: 0, jaw: 0 };
543
+ for (const v of Object.keys(VISEME_PARAMS)) {
544
+ const w = state['viseme_' + v] || 0;
545
+ if (w <= 0) continue;
546
+ totalW += w;
547
+ const p = VISEME_PARAMS[v];
548
+ out.open += p.open * w; out.width += p.width * w; out.round += p.round * w;
549
+ out.smile += p.smile * w; out.lipPress += p.lipPress * w; out.jaw += p.jaw * w;
550
+ }
551
+ // also additively layer ARKit-style modifiers
552
+ out.smile += state.mouthSmile; // -1..1 — symmetric add
553
+ out.round += state.mouthPucker * 0.6;
554
+ out.open += state.jawOpen * 0.6;
555
+ out.jaw += state.jawOpen * 0.7;
556
+ // clamp
557
+ for (const k in out) out[k] = Math.max(-1, Math.min(1.2, out[k]));
558
+ return out;
559
+ }
560
+
561
+ /* ─── 3. BABYLON SCENE ──────────────────────────────────────────────────── */
562
+
563
+ const canvas = document.getElementById('renderCanvas');
564
+ const engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true, antialias: true });
565
+ const scene = new BABYLON.Scene(engine);
566
+ scene.clearColor = new BABYLON.Color4(0, 0, 0, 1);
567
+
568
+ /* camera — orbit around the face */
569
+ const camera = new BABYLON.ArcRotateCamera('cam', -Math.PI/2, Math.PI/2, 4.4, new BABYLON.Vector3(0, 0, 0), scene);
570
+ /* attachControl in sandboxed iframes (e.g. Claude artifacts, restrictive
571
+ embeds) throws because navigator.getGamepads() is permission-blocked.
572
+ Stub it for the duration of attachControl so input-manager init can
573
+ complete and mouse/keyboard still work. */
574
+ {
575
+ const origGP = navigator.getGamepads ? navigator.getGamepads.bind(navigator) : null;
576
+ let restored = false;
577
+ try {
578
+ Object.defineProperty(navigator, 'getGamepads', { value: () => [], configurable: true });
579
+ } catch (e) { /* ignore — not all browsers allow override */ }
580
+ try {
581
+ camera.attachControl(true);
582
+ } catch (e) {
583
+ console.warn('[wireface] camera.attachControl partial:', e.message);
584
+ }
585
+ try {
586
+ if (origGP) Object.defineProperty(navigator, 'getGamepads', { value: origGP, configurable: true });
587
+ restored = true;
588
+ } catch (e) {}
589
+ }
590
+ camera.lowerRadiusLimit = 2.5;
591
+ camera.upperRadiusLimit = 8;
592
+ camera.wheelDeltaPercentage = 0.01;
593
+ camera.angularSensibilityX = 1500;
594
+ camera.angularSensibilityY = 1500;
595
+ camera.minZ = 0.1;
596
+
597
+ /* lights — bright key + rim, white emissive lines do most of the work */
598
+ const hemi = new BABYLON.HemisphericLight('hemi', new BABYLON.Vector3(0, 1, 0), scene);
599
+ hemi.intensity = 0.4;
600
+ hemi.diffuse = new BABYLON.Color3(0.95, 0.95, 1.0);
601
+
602
+ const key = new BABYLON.DirectionalLight('key', new BABYLON.Vector3(-0.4, -0.6, -0.7), scene);
603
+ key.intensity = 0.9;
604
+ key.diffuse = new BABYLON.Color3(1, 1, 0.95);
605
+
606
+ const rim = new BABYLON.PointLight('rim', new BABYLON.Vector3(0, 0.5, 3), scene);
607
+ rim.intensity = 0.6;
608
+ rim.diffuse = new BABYLON.Color3(0.85, 0.9, 1);
609
+
610
+ /* render configuration — declared early so scene-init can read defaults */
611
+ const renderConfig = {
612
+ meshCols: 7, // grid cols (odd → keeps centerline vertices for symmetry)
613
+ meshRows: 9, // grid rows
614
+ scaleNose: 1.0,
615
+ scaleEyes: 1.0,
616
+ scaleMouth: 1.0,
617
+ reactivity: 0.25, // Laplacian neighbor coupling factor [0,1]
618
+ spread: 1.0, // global multiplier on all blendshape radii
619
+ mode: 'wire', // 'wire' | 'edges' | 'shaded'
620
+ pupils: false,
621
+ meshVisible: true,
622
+ minimal: true, // v010: now ON by default — overlay is the "thick line" answer for the WebGL line-width limitation
623
+ fragment: false,
624
+ glow: false,
625
+ flipFace: true,
626
+ loopAudio: true,
627
+ // v006:
628
+ mouthHole: true, // cut a real puncture at the mouth (for lip-sync visibility)
629
+ mouthHoleSize: 1.0, // multiplier on mouth puncture ellipse radii [0.4, 2.0]
630
+ eyeHoles: false, // cut eye-socket punctures (optional)
631
+ eyeDepth: 1.0, // multiplier on warpToFace eye recess [0, 2.5]
632
+ // v007:
633
+ mouthAnchor: true, // drive mouth-ring mesh vertices directly from lip-curve formula
634
+ eyeAnchor: false, // drive eye-ring mesh vertices from lid-arc formula
635
+ lineThickness: 1.0, // multiplier on minimal-line tube radius [0.4, 3.0]
636
+ // v008:
637
+ lipVertAmp: 1.6, // amplify vertical lip motion (closure + opening) [0.5, 4.0]
638
+ lipPressForce: 1.0, // extra closing pressure for PP/FF/MM phonetics [0, 3]
639
+ overlayTracksMesh: true, // brow/nose/eye overlay positions follow mesh deformation
640
+ // v010:
641
+ moodTransitionTime: 0.6, // seconds for mood blend transitions [0.05, 5.0]
642
+ lineColor: '#ffffff', // minimal-line overlay tube color (mouth/eye/brow/nose)
643
+ pupilColor: '#ffffff', // pupil sphere color
644
+ // v011:
645
+ baseColor: '#ffffff', // mesh wireframe / face emissive base color
646
+ fadeColor: '#000000', // back-of-mesh color to fade to (depth gradient)
647
+ depthFade: 0.0, // 0 = no fade, 1 = full fade to fadeColor at deepest z [0, 1]
648
+ irisColor: '#000000', // iris ring color (visible behind pupil)
649
+ irisSize: 1.6, // iris radius multiplier on pupil radius [1, 4]
650
+ browColor: '#ffffff', // brow tube color separate from lineColor
651
+ jawExtend: 0.0, // z-forward push of lower face when jaw opens [0, 3]
652
+ mouthGrow: 0.0, // extra scaling of mouth region as it opens [0, 1.5]
653
+ };
654
+
655
+ /* per-channel gain knobs — multiplier applied to each channel value when
656
+ it's read by the displacement code. Default 1.0 = unchanged. Knob slider
657
+ value k ∈ [-2, +2] maps to gain = 2^k (so k=0 → 1×, k=+1 → 2×, k=-1 → 0.5×). */
658
+ const channelGains = {}; // channel name → multiplier
659
+ const channelGainSliders = {}; // channel name → slider position k (for UI)
660
+
661
+ /* mood transition state — current displayed weights lerp toward target on
662
+ each tick rather than snapping. moodTargetWeights set by mood-button click,
663
+ moodCurrentWeights animated in updateFace. */
664
+ const MOOD_NAMES = ['neutral','happy','sad','angry','fear','surprise','sleep'];
665
+ const moodTargetWeights = {};
666
+ const moodCurrentWeights = {};
667
+ for (const m of MOOD_NAMES) { moodTargetWeights[m] = 0; moodCurrentWeights[m] = 0; }
668
+ moodTargetWeights.neutral = 1; moodCurrentWeights.neutral = 1;
669
+
670
+ /* glow layer for the bloom on lines — toggleable via renderConfig.glow */
671
+ const glow = new BABYLON.GlowLayer('glow', scene, { mainTextureFixedSize: 1024, blurKernelSize: 32 });
672
+ glow.intensity = renderConfig.glow ? 0.85 : 0;
673
+
674
+ /* ─── 4. FACE MESH (single connected low-poly surface) ─────────────────
675
+ Strategy: build a parametric grid of vertices on a face-shaped surface.
676
+ Every blendshape is a (uv-center, direction, radius) tuple — vertices
677
+ near the center receive proportional displacement via gaussian falloff.
678
+ Optional Laplacian smoothing pass propagates deformations to neighbors,
679
+ so brows pull on cheeks, mouth opens drag the chin, etc.
680
+ */
681
+
682
+ const V = (x, y, z) => new BABYLON.Vector3(x, y, z);
683
+ const faceRoot = new BABYLON.TransformNode('faceRoot', scene);
684
+
685
+ /* materials */
686
+ const faceMat = new BABYLON.StandardMaterial('faceMat', scene);
687
+ faceMat.diffuseColor = new BABYLON.Color3(0.05, 0.05, 0.07);
688
+ faceMat.emissiveColor = new BABYLON.Color3(0.012, 0.012, 0.020);
689
+ faceMat.specularColor = new BABYLON.Color3(0.20, 0.22, 0.28);
690
+ faceMat.specularPower = 48;
691
+ faceMat.backFaceCulling = false;
692
+ // v011: respect per-vertex colors when ColorKind is set (depth-fade gradient)
693
+ faceMat.useVertexColor = true;
694
+
695
+ /* bright wireframe material — used in 'wire' mode (every edge bright) */
696
+ const wireMat = new BABYLON.StandardMaterial('wireMat', scene);
697
+ wireMat.emissiveColor = new BABYLON.Color3(1, 1, 1);
698
+ wireMat.disableLighting = true;
699
+ wireMat.wireframe = true;
700
+ wireMat.backFaceCulling = false;
701
+ wireMat.alpha = 1;
702
+ // v011: vertex colors are the primary line color in wire mode
703
+ wireMat.useVertexColor = true;
704
+ wireMat.emissiveColor = new BABYLON.Color3(1, 1, 1); // multiplied with vertex color
705
+
706
+ /* ─── 4a. parametric warp: grid (u,v) → face surface (x,y,z) ────────────
707
+ Uses an elliptical taper so the silhouette is oval, not rectangular.
708
+ Then layers feature bumps (eye sockets, brow ridge, nose, mouth, cheeks). */
709
+ function warpToFace(u, v) {
710
+ const xRel = (u - 0.5) * 2; // -1..1 left to right
711
+ const yRel = (0.5 - v) * 2; // 1..-1 top to bottom
712
+
713
+ // strong elliptical taper — the boundary of the grid maps to an oval
714
+ const yNorm = yRel * 0.95;
715
+ const ovalT = Math.max(0, 1 - yNorm * yNorm);
716
+ const widthAtY = Math.sqrt(ovalT) * 0.80;
717
+ let x = xRel * widthAtY;
718
+
719
+ // y stays linear; chin extends + forehead squashes
720
+ let y = yRel * 1.0;
721
+ if (yRel < -0.4) y = -0.4 + (yRel + 0.4) * 1.55;
722
+ if (yRel > 0.7) y = 0.7 + (yRel - 0.7) * 0.45;
723
+
724
+ // base z bulge — quadratic falloff from center
725
+ let z = (1 - xRel*xRel * 0.55 - yRel*yRel * 0.55) * 0.22;
726
+ if (z < -0.05) z = -0.05;
727
+
728
+ // eye sockets recess (small but visible)
729
+ const eyeY = 0.30;
730
+ const eyeL_d = ((xRel + 0.45) / 0.30) ** 2 + ((yRel - eyeY) / 0.18) ** 2;
731
+ const eyeR_d = ((xRel - 0.45) / 0.30) ** 2 + ((yRel - eyeY) / 0.18) ** 2;
732
+ const eyeRecess = 0.045 * renderConfig.eyeDepth;
733
+ z -= eyeRecess * Math.exp(-eyeL_d);
734
+ z -= eyeRecess * Math.exp(-eyeR_d);
735
+
736
+ // brow ridge bumps forward
737
+ const brow_d = (xRel / 0.7) ** 2 + ((yRel - 0.55) / 0.10) ** 2;
738
+ z += 0.045 * Math.exp(-brow_d);
739
+
740
+ // nose — the dominant z bump
741
+ const nose_d = (xRel / 0.18) ** 2 + ((yRel - 0.05) / 0.40) ** 2;
742
+ z += 0.22 * Math.exp(-nose_d);
743
+
744
+ // mouth area pushed slightly forward
745
+ const mouth_d = (xRel / 0.55) ** 2 + ((yRel + 0.45) / 0.20) ** 2;
746
+ z += 0.06 * Math.exp(-mouth_d);
747
+
748
+ // cheekbones
749
+ const cheekL_d = ((xRel + 0.55) / 0.30) ** 2 + ((yRel - 0.05) / 0.28) ** 2;
750
+ const cheekR_d = ((xRel - 0.55) / 0.30) ** 2 + ((yRel - 0.05) / 0.28) ** 2;
751
+ z += 0.04 * Math.exp(-cheekL_d);
752
+ z += 0.04 * Math.exp(-cheekR_d);
753
+
754
+ return V(x, y, z);
755
+ }
756
+
757
+ /* ─── 4a-bis. mouth center constants — hoisted so anchor code in rebuildMesh
758
+ can use them. The lip-target formula below is shared by both the mesh
759
+ anchor pass AND the minimal-line beziers, so they animate identically. */
760
+ const mouthCenterUV = warpToFace(0.50, 0.69);
761
+ const mouthBaseHW = 0.27;
762
+
763
+ /* compute precise lip target position for a vertex at normalized horizontal
764
+ position xRel ∈ [-1, +1] (corner-to-corner), upper or lower lip. */
765
+ function lipTarget(xRel, isUpper, p) {
766
+ const cx = mouthCenterUV.x, cy = mouthCenterUV.y, cz = mouthCenterUV.z;
767
+ const hw = mouthBaseHW * (1 + p.width * 0.40) * (1 - p.round * 0.40);
768
+
769
+ const vAmp = renderConfig.lipVertAmp; // global vertical motion scale
770
+ const closeF = renderConfig.lipPressForce; // PP/MM/FF closing pressure scale
771
+
772
+ const sep = p.open * 0.16 * vAmp;
773
+ // FIX: lipPress now genuinely COMPRESSES — upper moves DOWN, lower moves UP
774
+ const compress = p.lipPress * 0.012 * vAmp * closeF;
775
+ const jawDrop = p.jaw * 0.09 * vAmp;
776
+ const smileLift = p.smile * 0.05;
777
+ const roundFwd = p.round * 0.07;
778
+
779
+ let cp;
780
+ // natural lip thickness dip reduces when lips are pressed — at full PP/MM
781
+ // closure both upper and lower beziers converge near the centerline.
782
+ const upperDip = 0.007 * (1 - p.lipPress * 0.55);
783
+ const lowerDip = 0.022 * (1 - p.lipPress * 0.55);
784
+ if (isUpper) {
785
+ // upperY is below baseline by `compress` (upper lip pushed down when pressed)
786
+ const upperY = cy + sep / 2 - compress + smileLift * 0.4;
787
+ cp = [
788
+ [-1.00, cy + smileLift, -roundFwd * 0.5],
789
+ [-0.45, upperY + 0.012, 0.012],
790
+ [ 0.00, upperY - upperDip, 0.018 + roundFwd],
791
+ [ 0.45, upperY + 0.012, 0.012],
792
+ [ 1.00, cy + smileLift, -roundFwd * 0.5],
793
+ ];
794
+ } else {
795
+ // lowerY is above baseline by `compress` (lower lip pushed up when pressed)
796
+ const lowerY = cy - sep / 2 + compress - jawDrop;
797
+ cp = [
798
+ [-1.00, cy + smileLift, -roundFwd * 0.5],
799
+ [-0.50, lowerY - 0.005, 0.014],
800
+ [ 0.00, lowerY - lowerDip, 0.022 + roundFwd * 1.1],
801
+ [ 0.50, lowerY - 0.005, 0.014],
802
+ [ 1.00, cy + smileLift, -roundFwd * 0.5],
803
+ ];
804
+ }
805
+ // piecewise-linear interp between control points
806
+ xRel = Math.max(-1, Math.min(1, xRel));
807
+ let i = 0;
808
+ while (i < cp.length - 1 && xRel > cp[i + 1][0]) i++;
809
+ i = Math.min(i, cp.length - 2);
810
+ const t = (xRel - cp[i][0]) / (cp[i + 1][0] - cp[i][0]);
811
+ const yT = cp[i][1] * (1 - t) + cp[i + 1][1] * t;
812
+ const zO = cp[i][2] * (1 - t) + cp[i + 1][2] * t;
813
+ return V(cx + xRel * hw, yT, cz + zO);
814
+ }
815
+
816
+ /* ─── 4b. blendshape definitions (in uv space) ──────────────────────────
817
+ Each blendshape: { uv: [u, v], dir: V(dx, dy, dz), radius: r }
818
+ Falloff is gaussian; radius is in uv-distance units. */
819
+ const SHAPES = {
820
+ // mouth — driven by computeMouthParams() output (open/width/round/smile/lipPress/jaw)
821
+ mouth_jaw_drop: { uv:[0.50, 0.78], dir: V( 0.00,-0.20,-0.02), radius: 0.28 },
822
+ mouth_open_lower: { uv:[0.50, 0.71], dir: V( 0.00,-0.10, 0.00), radius: 0.16 },
823
+ mouth_open_upper: { uv:[0.50, 0.66], dir: V( 0.00, 0.04, 0.00), radius: 0.13 },
824
+ mouth_smile_L: { uv:[0.32, 0.69], dir: V(-0.06, 0.07,-0.02), radius: 0.13 },
825
+ mouth_smile_R: { uv:[0.68, 0.69], dir: V( 0.06, 0.07,-0.02), radius: 0.13 },
826
+ mouth_frown_L: { uv:[0.32, 0.69], dir: V( 0.02,-0.07, 0.00), radius: 0.13 },
827
+ mouth_frown_R: { uv:[0.68, 0.69], dir: V(-0.02,-0.07, 0.00), radius: 0.13 },
828
+ mouth_round_L: { uv:[0.32, 0.69], dir: V( 0.07, 0.00, 0.03), radius: 0.13 },
829
+ mouth_round_R: { uv:[0.68, 0.69], dir: V(-0.07, 0.00, 0.03), radius: 0.13 },
830
+ mouth_round_top: { uv:[0.50, 0.66], dir: V( 0.00,-0.02, 0.04), radius: 0.12 },
831
+ mouth_round_bot: { uv:[0.50, 0.71], dir: V( 0.00, 0.02, 0.04), radius: 0.12 },
832
+ mouth_press_top: { uv:[0.50, 0.66], dir: V( 0.00,-0.025, 0.00), radius: 0.12 },
833
+ mouth_press_bot: { uv:[0.50, 0.71], dir: V( 0.00, 0.025, 0.00), radius: 0.12 },
834
+ mouth_width_L: { uv:[0.32, 0.69], dir: V(-0.05, 0.00, 0.00), radius: 0.13 },
835
+ mouth_width_R: { uv:[0.68, 0.69], dir: V( 0.05, 0.00, 0.00), radius: 0.13 },
836
+
837
+ // eyes
838
+ eye_blink_L_up: { uv:[0.30, 0.36], dir: V( 0.00,-0.05,-0.02), radius: 0.08 },
839
+ eye_blink_L_lo: { uv:[0.30, 0.45], dir: V( 0.00, 0.03, 0.00), radius: 0.08 },
840
+ eye_blink_R_up: { uv:[0.70, 0.36], dir: V( 0.00,-0.05,-0.02), radius: 0.08 },
841
+ eye_blink_R_lo: { uv:[0.70, 0.45], dir: V( 0.00, 0.03, 0.00), radius: 0.08 },
842
+ eye_squint_L: { uv:[0.30, 0.42], dir: V( 0.00,-0.015, 0.00), radius: 0.10 },
843
+ eye_squint_R: { uv:[0.70, 0.42], dir: V( 0.00,-0.015, 0.00), radius: 0.10 },
844
+
845
+ // brows
846
+ brow_inner_L: { uv:[0.42, 0.25], dir: V( 0.00, 0.06, 0.02), radius: 0.10 },
847
+ brow_inner_R: { uv:[0.58, 0.25], dir: V( 0.00, 0.06, 0.02), radius: 0.10 },
848
+ brow_outer_L: { uv:[0.20, 0.27], dir: V( 0.00, 0.05, 0.00), radius: 0.12 },
849
+ brow_outer_R: { uv:[0.80, 0.27], dir: V( 0.00, 0.05, 0.00), radius: 0.12 },
850
+ brow_down_L: { uv:[0.30, 0.27], dir: V( 0.00,-0.05, 0.00), radius: 0.14 },
851
+ brow_down_R: { uv:[0.70, 0.27], dir: V( 0.00,-0.05, 0.00), radius: 0.14 },
852
+
853
+ // nose
854
+ nose_sneer_L: { uv:[0.42, 0.55], dir: V( 0.00, 0.03, 0.02), radius: 0.08 },
855
+ nose_sneer_R: { uv:[0.58, 0.55], dir: V( 0.00, 0.03, 0.02), radius: 0.08 },
856
+ };
857
+
858
+ /* ─── 4c. mesh state ────────────────────────────────────────────────────── */
859
+ let mesh = null;
860
+ let baseVertices = [];
861
+ let baseUVs = [];
862
+ let triIndices = [];
863
+ let adjacency = [];
864
+ let _dispBuf = null; // reused per-frame displacement buffer
865
+ let _posBuf = null;
866
+ let _normBuf = null;
867
+ let _colBuf = null; // v011: per-vertex RGBA for depth-fade gradient
868
+ let _zMin = 0, _zMax = 0; // mesh z bounds, set in rebuildMesh, used by depth-fade pass
869
+ let _baseRGB = [1, 1, 1]; // parsed renderConfig.baseColor (0-1)
870
+ let _fadeRGB = [0, 0, 0]; // parsed renderConfig.fadeColor (0-1)
871
+ let _dirtyBaseColor = false; // set by color picker to trigger one-shot repaint when fade is off
872
+
873
+ function hex2rgb(hex) {
874
+ const h = hex.replace('#', '');
875
+ return [
876
+ parseInt(h.slice(0, 2), 16) / 255,
877
+ parseInt(h.slice(2, 4), 16) / 255,
878
+ parseInt(h.slice(4, 6), 16) / 255,
879
+ ];
880
+ }
881
+
882
+ /* anchor rings — vertices driven directly from feature-curve formulas.
883
+ Populated by identifyAnchorRings() at mesh build time. */
884
+ let mouthRingVerts = []; // [{ idx, isUpper, xRel, weight, baselineTarget }]
885
+ let eyeRingVerts = []; // [{ idx, side, isUpper, xRel, weight, baselineTarget }]
886
+
887
+ const NEUTRAL_MOUTH = { open: 0, width: 0, round: 0, smile: 0, lipPress: 0.30, jaw: 0 };
888
+ const NEUTRAL_EYE_BLINK = 0;
889
+ const NEUTRAL_EYE_SQUINT = 0;
890
+
891
+ function rebuildMesh() {
892
+ if (mesh) { mesh.dispose(); mesh = null; }
893
+
894
+ const cols = renderConfig.meshCols;
895
+ const rows = renderConfig.meshRows;
896
+
897
+ baseVertices = [];
898
+ baseUVs = [];
899
+ triIndices = [];
900
+
901
+ // grid vertices
902
+ for (let r = 0; r < rows; r++) {
903
+ for (let c = 0; c < cols; c++) {
904
+ const u = c / (cols - 1);
905
+ const v = r / (rows - 1);
906
+ baseUVs.push({ u, v });
907
+ baseVertices.push(warpToFace(u, v));
908
+ }
909
+ }
910
+
911
+ // fragment mode: clip triangles whose UV centroid falls outside an oval
912
+ // (matches the silhouette of warpToFace, but cuts the corners cleanly)
913
+ function inOval(u, v) {
914
+ const xRel = (u - 0.5) * 2;
915
+ const yRel = (0.5 - v) * 2;
916
+ return (xRel * xRel) / 0.85 + (yRel * yRel) / 1.05 < 1.0;
917
+ }
918
+ const clip = renderConfig.fragment;
919
+
920
+ // mouth puncture: skip triangles whose centroid lies inside an ellipse
921
+ // around the mouth. Vertices stay (they form the boundary), so when visemes
922
+ // pull them apart, the hole grows and the lip-line ring stays attached.
923
+ const mouthHoleRU = 0.18 * renderConfig.mouthHoleSize; // u-axis radius
924
+ const mouthHoleRV = 0.075 * renderConfig.mouthHoleSize; // v-axis radius
925
+ const mouthCU = 0.50, mouthCV = 0.69;
926
+ const cutMouth = renderConfig.mouthHole;
927
+
928
+ // eye sockets puncture (optional)
929
+ const eyeRU = 0.085, eyeRV = 0.045;
930
+ const eyeLU = 0.30, eyeLV = 0.40;
931
+ const eyeRU2 = 0.70, eyeRV2 = 0.40;
932
+ const cutEyes = renderConfig.eyeHoles;
933
+
934
+ // triangulate quads, alternating diagonals for visual variety
935
+ function maybeAdd(a, b, c) {
936
+ const cu = (baseUVs[a].u + baseUVs[b].u + baseUVs[c].u) / 3;
937
+ const cv = (baseUVs[a].v + baseUVs[b].v + baseUVs[c].v) / 3;
938
+
939
+ if (clip && !inOval(cu, cv)) return;
940
+
941
+ if (cutMouth) {
942
+ const du = (cu - mouthCU) / mouthHoleRU;
943
+ const dv = (cv - mouthCV) / mouthHoleRV;
944
+ if (du * du + dv * dv < 1) return;
945
+ }
946
+ if (cutEyes) {
947
+ const lu = (cu - eyeLU) / eyeRU, lv = (cv - eyeLV) / eyeRV;
948
+ if (lu * lu + lv * lv < 1) return;
949
+ const ru = (cu - eyeRU2) / eyeRU, rv = (cv - eyeRV2) / eyeRV;
950
+ if (ru * ru + rv * rv < 1) return;
951
+ }
952
+ triIndices.push(a, b, c);
953
+ }
954
+ for (let r = 0; r < rows - 1; r++) {
955
+ for (let c = 0; c < cols - 1; c++) {
956
+ const i00 = r * cols + c;
957
+ const i10 = r * cols + (c + 1);
958
+ const i01 = (r + 1) * cols + c;
959
+ const i11 = (r + 1) * cols + (c + 1);
960
+ if ((r + c) % 2 === 0) {
961
+ maybeAdd(i00, i10, i11); maybeAdd(i00, i11, i01);
962
+ } else {
963
+ maybeAdd(i00, i10, i01); maybeAdd(i10, i11, i01);
964
+ }
965
+ }
966
+ }
967
+
968
+ adjacency = computeAdjacency(triIndices, baseVertices.length);
969
+
970
+ // build the Babylon mesh
971
+ mesh = new BABYLON.Mesh('face', scene);
972
+ mesh.parent = faceRoot;
973
+
974
+ const N = baseVertices.length;
975
+ _posBuf = new Float32Array(N * 3);
976
+ _normBuf = new Float32Array(N * 3);
977
+ _colBuf = new Float32Array(N * 4); // RGBA per vertex for depth-fade gradient
978
+ _dispBuf = new Array(N);
979
+ // record approximate z bounds of the rest mesh — used to remap depth fade
980
+ _zMin = +Infinity; _zMax = -Infinity;
981
+ for (let i = 0; i < N; i++) {
982
+ _posBuf[3*i ] = baseVertices[i].x;
983
+ _posBuf[3*i+1] = baseVertices[i].y;
984
+ _posBuf[3*i+2] = baseVertices[i].z;
985
+ if (baseVertices[i].z < _zMin) _zMin = baseVertices[i].z;
986
+ if (baseVertices[i].z > _zMax) _zMax = baseVertices[i].z;
987
+ _dispBuf[i] = V(0, 0, 0);
988
+ _colBuf[4*i] = 1; _colBuf[4*i+1] = 1; _colBuf[4*i+2] = 1; _colBuf[4*i+3] = 1;
989
+ }
990
+ BABYLON.VertexData.ComputeNormals(_posBuf, triIndices, _normBuf);
991
+
992
+ const vd = new BABYLON.VertexData();
993
+ vd.positions = Array.from(_posBuf);
994
+ vd.indices = triIndices;
995
+ vd.normals = Array.from(_normBuf);
996
+ vd.colors = Array.from(_colBuf);
997
+ vd.applyToMesh(mesh, true); // updatable=true
998
+
999
+ applyRenderMode();
1000
+ applyFaceFlip();
1001
+ applyMeshVisibility();
1002
+ identifyAnchorRings();
1003
+ updateGeometryCounter();
1004
+ }
1005
+
1006
+ /* identify ring vertices for mouth + eye anchor passes, and cache their
1007
+ baseline targets so neutral state produces zero displacement. */
1008
+ function identifyAnchorRings() {
1009
+ mouthRingVerts = [];
1010
+ eyeRingVerts = [];
1011
+
1012
+ // ── mouth ring ──
1013
+ const mRU = 0.18 * renderConfig.mouthHoleSize;
1014
+ const mRV = 0.075 * renderConfig.mouthHoleSize;
1015
+ const mCU = 0.50, mCV = 0.69;
1016
+ for (let i = 0; i < baseUVs.length; i++) {
1017
+ const du = (baseUVs[i].u - mCU) / mRU;
1018
+ const dv = (baseUVs[i].v - mCV) / mRV;
1019
+ const d2 = du * du + dv * dv;
1020
+ if (d2 < 4) {
1021
+ const isUpper = baseUVs[i].v < mCV;
1022
+ const xRel = Math.max(-1, Math.min(1, du));
1023
+ // weight peaks at the ring (d2=1), fades to 0 at d2=0 and d2>=4
1024
+ let weight;
1025
+ if (d2 <= 1) weight = d2; // ramp up from 0..1 in interior
1026
+ else weight = (4 - d2) / 3; // ramp down 1..0 outside
1027
+ weight = Math.max(0, Math.min(1, weight));
1028
+ mouthRingVerts.push({ idx: i, isUpper, xRel, weight,
1029
+ baselineTarget: lipTarget(xRel, isUpper, NEUTRAL_MOUTH) });
1030
+ }
1031
+ }
1032
+
1033
+ // ── eye rings ──
1034
+ const eyeRingDef = [
1035
+ { side: 'L', cu: 0.30, cv: 0.40, ru: 0.085, rv: 0.045, hw: 0.10, hh: 0.040 },
1036
+ { side: 'R', cu: 0.70, cv: 0.40, ru: 0.085, rv: 0.045, hw: 0.10, hh: 0.040 },
1037
+ ];
1038
+ for (const e of eyeRingDef) {
1039
+ for (let i = 0; i < baseUVs.length; i++) {
1040
+ const du = (baseUVs[i].u - e.cu) / e.ru;
1041
+ const dv = (baseUVs[i].v - e.cv) / e.rv;
1042
+ const d2 = du * du + dv * dv;
1043
+ if (d2 < 4) {
1044
+ const isUpper = baseUVs[i].v < e.cv;
1045
+ const xRel = Math.max(-1, Math.min(1, du));
1046
+ let weight;
1047
+ if (d2 <= 1) weight = d2;
1048
+ else weight = (4 - d2) / 3;
1049
+ weight = Math.max(0, Math.min(1, weight));
1050
+ const center = warpToFace(e.cu, e.cv);
1051
+ eyeRingVerts.push({
1052
+ idx: i, side: e.side, isUpper, xRel, weight,
1053
+ eyeDef: { center, hw: e.hw, hh: e.hh },
1054
+ baselineTarget: eyeLidTargetFor(xRel, isUpper,
1055
+ { center, hw: e.hw, hh: e.hh },
1056
+ NEUTRAL_EYE_BLINK, NEUTRAL_EYE_SQUINT)
1057
+ });
1058
+ }
1059
+ }
1060
+ }
1061
+
1062
+ // expose count
1063
+ const el = document.getElementById('coord-anchor');
1064
+ if (el) el.textContent = String(mouthRingVerts.length).padStart(2, '0') + '/' +
1065
+ String(eyeRingVerts.length).padStart(2, '0');
1066
+ }
1067
+
1068
+ /* eye lid target — same formula the bezier uses, evaluated at one xRel. */
1069
+ function eyeLidTargetFor(xRel, isUpper, eyeDef, blink, squint) {
1070
+ // a in [0, π], xRel = -1 → a=0 (left corner), xRel=+1 → a=π (right)
1071
+ const a = ((xRel + 1) / 2) * Math.PI;
1072
+ const x = eyeDef.center.x + Math.cos(Math.PI - a) * eyeDef.hw;
1073
+ const baseY = eyeDef.center.y + (isUpper ? 1 : -1) * Math.sin(a) * eyeDef.hh;
1074
+ const y = baseY * (1 - blink) + eyeDef.center.y * blink;
1075
+ const squintShift = squint * 0.012;
1076
+ const yWithSquint = y + (isUpper ? -squintShift : squintShift * 0.5);
1077
+ const z = eyeDef.center.z + 0.018 + Math.sin(a) * 0.012;
1078
+ return V(x, yWithSquint, z);
1079
+ }
1080
+
1081
+ /* v011: push lower-face vertices forward (positive z) when the jaw opens.
1082
+ Creates a stylized "stretched / extended jaw" look that exaggerates speech.
1083
+ Weight ramps up below v=0.55 (mid-face) and reaches max at chin (v=1.0). */
1084
+ function applyJawExtension(disp) {
1085
+ const amt = renderConfig.jawExtend;
1086
+ if (amt < 0.001) return;
1087
+ const open = state.jawOpen || 0;
1088
+ if (open < 0.001) return;
1089
+ const push = open * amt * 0.10;
1090
+ for (let i = 0; i < baseUVs.length; i++) {
1091
+ const v = baseUVs[i].v;
1092
+ if (v < 0.55) continue;
1093
+ const w = Math.min(1, (v - 0.55) / 0.45);
1094
+ disp[i].z += push * w;
1095
+ }
1096
+ }
1097
+
1098
+ /* v011: scale the region around the mouth outward (XY) and slightly forward (Z)
1099
+ proportional to how open the mouth currently is. Gives a "growing talking
1100
+ mouth" effect on top of the regular lip motion. */
1101
+ function applyMouthGrow(disp) {
1102
+ const amt = renderConfig.mouthGrow;
1103
+ if (amt < 0.001) return;
1104
+ const p = computeMouthParams();
1105
+ const openness = p.open;
1106
+ if (openness < 0.001) return;
1107
+ const scale = openness * amt;
1108
+ const r = 0.25; // UV radius of effect
1109
+ const r2 = r * r;
1110
+ const cu = 0.50, cv = 0.69;
1111
+ for (let i = 0; i < baseUVs.length; i++) {
1112
+ const du = baseUVs[i].u - cu;
1113
+ const dv = baseUVs[i].v - cv;
1114
+ const d2 = du*du + dv*dv;
1115
+ if (d2 > r2) continue;
1116
+ const w = 1 - Math.sqrt(d2 / r2); // tent weight, 1 at center → 0 at radius
1117
+ const base = baseVertices[i];
1118
+ disp[i].x += (base.x - mouthCenterUV.x) * scale * w * 0.40;
1119
+ disp[i].y += (base.y - mouthCenterUV.y) * scale * w * 0.40;
1120
+ disp[i].z += scale * w * 0.05;
1121
+ }
1122
+ }
1123
+
1124
+ /* apply mouth anchor — drives ring vertices to match the lip-curve formula */
1125
+ function applyMouthAnchors(disp) {
1126
+ if (!renderConfig.mouthAnchor) return;
1127
+ const p = computeMouthParams();
1128
+ for (const v of mouthRingVerts) {
1129
+ const target = lipTarget(v.xRel, v.isUpper, p);
1130
+ const dx = target.x - v.baselineTarget.x;
1131
+ const dy = target.y - v.baselineTarget.y;
1132
+ const dz = target.z - v.baselineTarget.z;
1133
+ const w = v.weight;
1134
+ disp[v.idx].x = disp[v.idx].x * (1 - w) + dx * w;
1135
+ disp[v.idx].y = disp[v.idx].y * (1 - w) + dy * w;
1136
+ disp[v.idx].z = disp[v.idx].z * (1 - w) + dz * w;
1137
+ }
1138
+ }
1139
+
1140
+ /* apply eye anchor — drives eye ring vertices to match the lid-arc formula */
1141
+ function applyEyeAnchors(disp) {
1142
+ if (!renderConfig.eyeAnchor) return;
1143
+ const blinkL = state.eyeBlinkLeft;
1144
+ const blinkR = state.eyeBlinkRight;
1145
+ const squint = state.eyeSquint;
1146
+ for (const v of eyeRingVerts) {
1147
+ const blink = v.side === 'L' ? blinkL : blinkR;
1148
+ const target = eyeLidTargetFor(v.xRel, v.isUpper, v.eyeDef, blink, squint);
1149
+ const dx = target.x - v.baselineTarget.x;
1150
+ const dy = target.y - v.baselineTarget.y;
1151
+ const dz = target.z - v.baselineTarget.z;
1152
+ const w = v.weight;
1153
+ disp[v.idx].x = disp[v.idx].x * (1 - w) + dx * w;
1154
+ disp[v.idx].y = disp[v.idx].y * (1 - w) + dy * w;
1155
+ disp[v.idx].z = disp[v.idx].z * (1 - w) + dz * w;
1156
+ }
1157
+ }
1158
+
1159
+ function applyFaceFlip() {
1160
+ faceRoot.rotation.y = renderConfig.flipFace ? Math.PI : 0;
1161
+ }
1162
+
1163
+ function applyMeshVisibility() {
1164
+ if (mesh) mesh.isVisible = renderConfig.meshVisible;
1165
+ }
1166
+
1167
+ function updateGeometryCounter() {
1168
+ const triCount = triIndices.length / 3;
1169
+ const vertCount = baseVertices.length;
1170
+ const el = document.getElementById('coord-tris');
1171
+ if (el) el.textContent = String(triCount).padStart(3, '0');
1172
+ const elV = document.getElementById('coord-verts');
1173
+ if (elV) elV.textContent = String(vertCount).padStart(3, '0');
1174
+ }
1175
+
1176
+ function computeAdjacency(indices, nVerts) {
1177
+ const adj = Array.from({ length: nVerts }, () => new Set());
1178
+ for (let i = 0; i < indices.length; i += 3) {
1179
+ const a = indices[i], b = indices[i+1], c = indices[i+2];
1180
+ adj[a].add(b); adj[a].add(c);
1181
+ adj[b].add(a); adj[b].add(c);
1182
+ adj[c].add(a); adj[c].add(b);
1183
+ }
1184
+ return adj.map(s => Array.from(s));
1185
+ }
1186
+
1187
+ function applyRenderMode() {
1188
+ if (!mesh) return;
1189
+ if (mesh._edgesRenderer) mesh.disableEdgesRendering();
1190
+ const w = renderConfig.lineThickness;
1191
+
1192
+ switch (renderConfig.mode) {
1193
+ case 'wire':
1194
+ // GL_LINES wireframe — draws straight from the live position buffer,
1195
+ // so mesh deformation just works every frame for free. Width is locked
1196
+ // to 1px on virtually all WebGL drivers (the spec allows 1.0 only),
1197
+ // so the lineThickness slider can't change wire-mode stroke width.
1198
+ // Thick wire is what the 'edges' mode below is for.
1199
+ mesh.material = wireMat;
1200
+ wireMat.wireframe = true;
1201
+ wireMat.alpha = 1.0;
1202
+ break;
1203
+ case 'edges':
1204
+ // enableEdgesRendering builds a SEPARATE static line geometry from
1205
+ // the mesh — it does NOT auto-refresh when vertices move. We rebuild
1206
+ // it once per frame inside updateFace() so deformation stays visible.
1207
+ // edgesWidth respects the lineThickness slider.
1208
+ mesh.material = faceMat;
1209
+ faceMat.alpha = 1.0;
1210
+ faceMat.wireframe = false;
1211
+ mesh.enableEdgesRendering(0.9999);
1212
+ mesh.edgesWidth = 4 * w;
1213
+ mesh.edgesColor = new BABYLON.Color4(1, 1, 1, 1);
1214
+ break;
1215
+ case 'shaded':
1216
+ // Raw lit mesh, no wireframe at all.
1217
+ mesh.material = faceMat;
1218
+ faceMat.alpha = 1.0;
1219
+ faceMat.wireframe = false;
1220
+ break;
1221
+ }
1222
+ }
1223
+
1224
+ /* ─── 4d. apply a single blendshape to displacement array ─────────────── */
1225
+ function applyShape(disp, shape, weight, spread) {
1226
+ if (Math.abs(weight) < 0.001) return;
1227
+ const cu = shape.uv[0], cv = shape.uv[1];
1228
+ const r = shape.radius * spread;
1229
+ const r2 = r * r;
1230
+ const dx = shape.dir.x * weight;
1231
+ const dy = shape.dir.y * weight;
1232
+ const dz = shape.dir.z * weight;
1233
+ const cutoff = r2 * 4;
1234
+ for (let i = 0; i < baseUVs.length; i++) {
1235
+ const du = baseUVs[i].u - cu;
1236
+ const dv = baseUVs[i].v - cv;
1237
+ const d2 = du*du + dv*dv;
1238
+ if (d2 > cutoff) continue;
1239
+ const f = Math.exp(-d2 / r2);
1240
+ if (f < 0.005) continue;
1241
+ disp[i].x += dx * f;
1242
+ disp[i].y += dy * f;
1243
+ disp[i].z += dz * f;
1244
+ }
1245
+ }
1246
+
1247
+ /* ─── 4e. compose all morphs from current channel state ───────────────── */
1248
+ function computeMorphs(disp) {
1249
+ const spread = renderConfig.spread;
1250
+
1251
+ // mouth (visemes → 6 mouth params → multiple shapes)
1252
+ const m = computeMouthParams();
1253
+ applyShape(disp, SHAPES.mouth_jaw_drop, m.jaw, spread);
1254
+ applyShape(disp, SHAPES.mouth_open_lower, m.open, spread);
1255
+ applyShape(disp, SHAPES.mouth_open_upper, m.open * 0.4, spread);
1256
+ if (m.smile > 0) {
1257
+ applyShape(disp, SHAPES.mouth_smile_L, m.smile, spread);
1258
+ applyShape(disp, SHAPES.mouth_smile_R, m.smile, spread);
1259
+ } else if (m.smile < 0) {
1260
+ applyShape(disp, SHAPES.mouth_frown_L, -m.smile, spread);
1261
+ applyShape(disp, SHAPES.mouth_frown_R, -m.smile, spread);
1262
+ }
1263
+ applyShape(disp, SHAPES.mouth_round_L, m.round, spread);
1264
+ applyShape(disp, SHAPES.mouth_round_R, m.round, spread);
1265
+ applyShape(disp, SHAPES.mouth_round_top, m.round, spread);
1266
+ applyShape(disp, SHAPES.mouth_round_bot, m.round, spread);
1267
+ applyShape(disp, SHAPES.mouth_press_top, m.lipPress, spread);
1268
+ applyShape(disp, SHAPES.mouth_press_bot, m.lipPress, spread);
1269
+ if (m.width > 0) {
1270
+ applyShape(disp, SHAPES.mouth_width_L, m.width, spread);
1271
+ applyShape(disp, SHAPES.mouth_width_R, m.width, spread);
1272
+ }
1273
+
1274
+ // eyes
1275
+ applyShape(disp, SHAPES.eye_blink_L_up, state.eyeBlinkLeft, spread);
1276
+ applyShape(disp, SHAPES.eye_blink_L_lo, state.eyeBlinkLeft, spread);
1277
+ applyShape(disp, SHAPES.eye_blink_R_up, state.eyeBlinkRight, spread);
1278
+ applyShape(disp, SHAPES.eye_blink_R_lo, state.eyeBlinkRight, spread);
1279
+ applyShape(disp, SHAPES.eye_squint_L, state.eyeSquint, spread);
1280
+ applyShape(disp, SHAPES.eye_squint_R, state.eyeSquint, spread);
1281
+
1282
+ // brows
1283
+ applyShape(disp, SHAPES.brow_inner_L, state.browInnerUp, spread);
1284
+ applyShape(disp, SHAPES.brow_inner_R, state.browInnerUp, spread);
1285
+ if (state.browOuterUp >= 0) {
1286
+ applyShape(disp, SHAPES.brow_outer_L, state.browOuterUp, spread);
1287
+ applyShape(disp, SHAPES.brow_outer_R, state.browOuterUp, spread);
1288
+ } else {
1289
+ applyShape(disp, SHAPES.brow_down_L, -state.browOuterUp * 0.6, spread);
1290
+ applyShape(disp, SHAPES.brow_down_R, -state.browOuterUp * 0.6, spread);
1291
+ }
1292
+ applyShape(disp, SHAPES.brow_down_L, state.browDown, spread);
1293
+ applyShape(disp, SHAPES.brow_down_R, state.browDown, spread);
1294
+
1295
+ // nose
1296
+ applyShape(disp, SHAPES.nose_sneer_L, state.noseSneer, spread);
1297
+ applyShape(disp, SHAPES.nose_sneer_R, state.noseSneer, spread);
1298
+ }
1299
+
1300
+ /* ─── 4f. Laplacian smoothing — propagate deformations to neighbors ──── */
1301
+ function couple(disp, factor) {
1302
+ const N = disp.length;
1303
+ // store original to avoid in-place feedback
1304
+ const ox = new Float32Array(N), oy = new Float32Array(N), oz = new Float32Array(N);
1305
+ for (let i = 0; i < N; i++) { ox[i] = disp[i].x; oy[i] = disp[i].y; oz[i] = disp[i].z; }
1306
+ for (let i = 0; i < N; i++) {
1307
+ const nbrs = adjacency[i];
1308
+ if (nbrs.length === 0) continue;
1309
+ let sx = 0, sy = 0, sz = 0;
1310
+ for (const j of nbrs) { sx += ox[j]; sy += oy[j]; sz += oz[j]; }
1311
+ sx /= nbrs.length; sy /= nbrs.length; sz /= nbrs.length;
1312
+ disp[i].x = ox[i] * (1 - factor) + sx * factor;
1313
+ disp[i].y = oy[i] * (1 - factor) + sy * factor;
1314
+ disp[i].z = oz[i] * (1 - factor) + sz * factor;
1315
+ }
1316
+ }
1317
+
1318
+ /* ─── 4g. local feature scales (post-process: scale around feature centers) ─── */
1319
+ const FEATURE_CENTERS = [
1320
+ { name: 'nose', uv: [0.50, 0.50], radiusUV: 0.16, get scale() { return renderConfig.scaleNose; } },
1321
+ { name: 'eyeL', uv: [0.30, 0.40], radiusUV: 0.11, get scale() { return renderConfig.scaleEyes; } },
1322
+ { name: 'eyeR', uv: [0.70, 0.40], radiusUV: 0.11, get scale() { return renderConfig.scaleEyes; } },
1323
+ { name: 'mouth', uv: [0.50, 0.70], radiusUV: 0.18, get scale() { return renderConfig.scaleMouth; } },
1324
+ ];
1325
+
1326
+ function applyFeatureScales(disp) {
1327
+ for (const f of FEATURE_CENTERS) {
1328
+ const s = f.scale;
1329
+ if (Math.abs(s - 1) < 0.001) continue;
1330
+ const center = warpToFace(f.uv[0], f.uv[1]);
1331
+ const r2 = f.radiusUV * f.radiusUV;
1332
+ const cutoff = r2 * 4;
1333
+ for (let i = 0; i < baseUVs.length; i++) {
1334
+ const du = baseUVs[i].u - f.uv[0];
1335
+ const dv = baseUVs[i].v - f.uv[1];
1336
+ const d2 = du*du + dv*dv;
1337
+ if (d2 > cutoff) continue;
1338
+ const w = Math.exp(-d2 / r2);
1339
+ const ox = baseVertices[i].x - center.x;
1340
+ const oy = baseVertices[i].y - center.y;
1341
+ const oz = baseVertices[i].z - center.z;
1342
+ const k = (s - 1) * w;
1343
+ disp[i].x += ox * k;
1344
+ disp[i].y += oy * k;
1345
+ disp[i].z += oz * k;
1346
+ }
1347
+ }
1348
+ }
1349
+
1350
+ /* ─── 4h. optional pupils + iris (visual aid for look direction) ──────── */
1351
+ let pupilMat = null, pupilL = null, pupilR = null;
1352
+ let irisMat = null, irisL = null, irisR = null;
1353
+
1354
+ function rebuildPupils() {
1355
+ if (pupilL) { pupilL.dispose(); pupilL = null; }
1356
+ if (pupilR) { pupilR.dispose(); pupilR = null; }
1357
+ if (irisL) { irisL.dispose(); irisL = null; }
1358
+ if (irisR) { irisR.dispose(); irisR = null; }
1359
+ if (!renderConfig.pupils) return;
1360
+ if (!pupilMat) {
1361
+ pupilMat = new BABYLON.StandardMaterial('pupilMat', scene);
1362
+ pupilMat.emissiveColor = new BABYLON.Color3(1, 1, 1);
1363
+ pupilMat.disableLighting = true;
1364
+ pupilMat.backFaceCulling = false;
1365
+ }
1366
+ if (!irisMat) {
1367
+ irisMat = new BABYLON.StandardMaterial('irisMat', scene);
1368
+ irisMat.emissiveColor = new BABYLON.Color3(0, 0, 0);
1369
+ irisMat.disableLighting = true;
1370
+ irisMat.backFaceCulling = false;
1371
+ }
1372
+ // iris (larger disc behind pupil) — sits slightly closer to face (smaller z offset)
1373
+ const irisR_size = 0.035 * renderConfig.irisSize;
1374
+ irisL = BABYLON.MeshBuilder.CreateDisc('irisL', { radius: irisR_size, tessellation: 24 }, scene);
1375
+ irisR = BABYLON.MeshBuilder.CreateDisc('irisR', { radius: irisR_size, tessellation: 24 }, scene);
1376
+ irisL.material = irisR.material = irisMat;
1377
+ irisL.parent = irisR.parent = faceRoot;
1378
+ // pupil in front
1379
+ pupilL = BABYLON.MeshBuilder.CreateDisc('pupilL', { radius: 0.035, tessellation: 14 }, scene);
1380
+ pupilR = BABYLON.MeshBuilder.CreateDisc('pupilR', { radius: 0.035, tessellation: 14 }, scene);
1381
+ pupilL.material = pupilR.material = pupilMat;
1382
+ pupilL.parent = pupilR.parent = faceRoot;
1383
+ }
1384
+
1385
+ function updatePupils() {
1386
+ if (!pupilL || !pupilR) return;
1387
+ const lookH = state.eyeLookH * 0.05;
1388
+ const lookV = state.eyeLookV * 0.035;
1389
+ const eyeL = warpToFace(0.30, 0.40);
1390
+ const eyeR = warpToFace(0.70, 0.40);
1391
+ // iris — slightly behind pupil and shifted less by gaze (iris doesn't follow gaze fully)
1392
+ if (irisL && irisR) {
1393
+ irisL.position.set(eyeL.x + lookH * 0.6, eyeL.y + lookV * 0.6, eyeL.z + 0.045);
1394
+ irisR.position.set(eyeR.x + lookH * 0.6, eyeR.y + lookV * 0.6, eyeR.z + 0.045);
1395
+ }
1396
+ pupilL.position.set(eyeL.x + lookH, eyeL.y + lookV, eyeL.z + 0.05);
1397
+ pupilR.position.set(eyeR.x + lookH, eyeR.y + lookV, eyeR.z + 0.05);
1398
+ const blink = (state.eyeBlinkLeft + state.eyeBlinkRight) * 0.5;
1399
+ pupilL.isVisible = pupilR.isVisible = blink < 0.85;
1400
+ if (irisL && irisR) irisL.isVisible = irisR.isVisible = blink < 0.85;
1401
+ }
1402
+
1403
+ /* ─── 4i. per-frame face update ──────────────────────────────────────── */
1404
+ /* per-frame raw-state cache for gain sandwich */
1405
+ const _stateRawSnap = {};
1406
+
1407
+ function updateFace() {
1408
+ if (!mesh) return;
1409
+
1410
+ /* apply per-channel gains: stash raw values, multiply state in place.
1411
+ All downstream displacement reads (computeMouthParams, applyShape,
1412
+ updatePupils, updateMinimal, head pose) get the gained values for free
1413
+ without refactoring 30+ call sites. We restore at the end so the channel
1414
+ bar display elsewhere still reads raw values. */
1415
+ for (let i = 0; i < CHANNEL_NAMES.length; i++) {
1416
+ const ch = CHANNEL_NAMES[i];
1417
+ _stateRawSnap[ch] = state[ch];
1418
+ state[ch] = state[ch] * (channelGains[ch] || 1);
1419
+ }
1420
+
1421
+ // reset displacement buffer
1422
+ for (let i = 0; i < _dispBuf.length; i++) {
1423
+ _dispBuf[i].x = _dispBuf[i].y = _dispBuf[i].z = 0;
1424
+ }
1425
+
1426
+ computeMorphs(_dispBuf);
1427
+ if (renderConfig.reactivity > 0) couple(_dispBuf, renderConfig.reactivity);
1428
+ applyFeatureScales(_dispBuf);
1429
+ applyJawExtension(_dispBuf); // v011: z-forward push of lower face on jaw open
1430
+ applyMouthGrow(_dispBuf); // v011: scale mouth region outward proportional to openness
1431
+ applyMouthAnchors(_dispBuf);
1432
+ applyEyeAnchors(_dispBuf);
1433
+
1434
+ // write final positions
1435
+ for (let i = 0; i < baseVertices.length; i++) {
1436
+ _posBuf[3*i ] = baseVertices[i].x + _dispBuf[i].x;
1437
+ _posBuf[3*i+1] = baseVertices[i].y + _dispBuf[i].y;
1438
+ _posBuf[3*i+2] = baseVertices[i].z + _dispBuf[i].z;
1439
+ }
1440
+ mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, _posBuf);
1441
+
1442
+ /* depth-fade: lerp each vertex's color from baseColor (front) → fadeColor (back)
1443
+ by its z position. Only updates the GPU buffer when depthFade is non-zero
1444
+ (idle case stays cheap). The mesh material reads useVertexColor so wireframe
1445
+ lines pick up these colors automatically. */
1446
+ if (renderConfig.depthFade > 0.001 && _baseRGB && _fadeRGB) {
1447
+ const zRange = (_zMax - _zMin) || 1;
1448
+ const f = renderConfig.depthFade;
1449
+ for (let i = 0; i < baseVertices.length; i++) {
1450
+ // currentZ from already-updated _posBuf
1451
+ const z = _posBuf[3*i + 2];
1452
+ // t: 0 at front (max z), 1 at back (min z)
1453
+ const t = Math.max(0, Math.min(1, (_zMax - z) / zRange)) * f;
1454
+ _colBuf[4*i ] = _baseRGB[0] * (1 - t) + _fadeRGB[0] * t;
1455
+ _colBuf[4*i+1] = _baseRGB[1] * (1 - t) + _fadeRGB[1] * t;
1456
+ _colBuf[4*i+2] = _baseRGB[2] * (1 - t) + _fadeRGB[2] * t;
1457
+ _colBuf[4*i+3] = 1;
1458
+ }
1459
+ mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, _colBuf);
1460
+ } else if (_dirtyBaseColor && _baseRGB) {
1461
+ // depth fade off but base color changed — repaint all vertices to flat base
1462
+ for (let i = 0; i < baseVertices.length; i++) {
1463
+ _colBuf[4*i ] = _baseRGB[0];
1464
+ _colBuf[4*i+1] = _baseRGB[1];
1465
+ _colBuf[4*i+2] = _baseRGB[2];
1466
+ _colBuf[4*i+3] = 1;
1467
+ }
1468
+ mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, _colBuf);
1469
+ _dirtyBaseColor = false;
1470
+ }
1471
+
1472
+ // recompute normals only when shaded faces are visible
1473
+ if (renderConfig.mode === 'edges' || renderConfig.mode === 'shaded') {
1474
+ BABYLON.VertexData.ComputeNormals(_posBuf, triIndices, _normBuf);
1475
+ mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, _normBuf);
1476
+ }
1477
+ // NOTE: 'edges' mode uses Babylon's enableEdgesRendering, which builds a
1478
+ // SEPARATE static line geometry — it does NOT update when the mesh deforms.
1479
+ // Refreshing it every frame would hammer the GPU (dispose+recreate buffers
1480
+ // per frame), so we don't. Use 'wire' mode for live deformation; 'edges'
1481
+ // is for thick-line rendering of static or near-static poses.
1482
+
1483
+ updatePupils();
1484
+ if (renderConfig.minimal) updateMinimal();
1485
+
1486
+ // head pose drives the parent transform
1487
+ faceRoot.rotation.x = state.headRotateX * 0.35;
1488
+ faceRoot.rotation.y = state.headRotateY * 0.50;
1489
+ faceRoot.rotation.z = state.headRotateZ * 0.30;
1490
+
1491
+ /* restore raw state — bar display, recording, etc. should see un-gained values */
1492
+ for (let i = 0; i < CHANNEL_NAMES.length; i++) {
1493
+ state[CHANNEL_NAMES[i]] = _stateRawSnap[CHANNEL_NAMES[i]];
1494
+ }
1495
+ }
1496
+
1497
+ rebuildMesh();
1498
+ rebuildPupils();
1499
+
1500
+ /* ─── 4j. minimal feature lines overlay ─────────────────────────────────
1501
+ v002-style precise curves for the mouth, eyes, brows, nose. Updates from
1502
+ the same channel state as the mesh so deformations stay synchronized.
1503
+ Toggleable via renderConfig.minimal. */
1504
+
1505
+ const minimalMat = new BABYLON.StandardMaterial('minimalMat', scene);
1506
+ minimalMat.emissiveColor = new BABYLON.Color3(1, 1, 1);
1507
+ minimalMat.disableLighting = true;
1508
+ minimalMat.specularColor = new BABYLON.Color3(0, 0, 0);
1509
+
1510
+ /* v011: separate material for brow tubes so they can have a distinct color
1511
+ from the rest of the minimal-line overlay. Same render properties otherwise. */
1512
+ const browMat = new BABYLON.StandardMaterial('browMat', scene);
1513
+ browMat.emissiveColor = new BABYLON.Color3(1, 1, 1);
1514
+ browMat.disableLighting = true;
1515
+ browMat.specularColor = new BABYLON.Color3(0, 0, 0);
1516
+
1517
+ const minimalGroup = new BABYLON.TransformNode('minimal', scene);
1518
+ minimalGroup.parent = faceRoot;
1519
+
1520
+ /* sample the current mesh displacement at any (u, v) by tent-weighted
1521
+ average of nearby vertices' _dispBuf values. Lets the overlay track
1522
+ the deformed mesh — when the mouth pulls the chin down, nose & brow
1523
+ anchors above also follow proportionally. */
1524
+ function sampleDispAtUV(u, v) {
1525
+ if (!_dispBuf) return V(0, 0, 0);
1526
+ const r2 = 0.06 * 0.06; // UV radius for sampling
1527
+ let totalW = 0, sx = 0, sy = 0, sz = 0;
1528
+ for (let i = 0; i < baseUVs.length; i++) {
1529
+ const du = baseUVs[i].u - u;
1530
+ const dv = baseUVs[i].v - v;
1531
+ const d2 = du*du + dv*dv;
1532
+ if (d2 < r2) {
1533
+ const w = 1 - Math.sqrt(d2 / r2); // tent weight
1534
+ totalW += w;
1535
+ sx += _dispBuf[i].x * w;
1536
+ sy += _dispBuf[i].y * w;
1537
+ sz += _dispBuf[i].z * w;
1538
+ }
1539
+ }
1540
+ if (totalW === 0) {
1541
+ // fallback: nearest single vertex
1542
+ let best = 0, bestD2 = Infinity;
1543
+ for (let i = 0; i < baseUVs.length; i++) {
1544
+ const du = baseUVs[i].u - u, dv = baseUVs[i].v - v;
1545
+ const d2 = du*du + dv*dv;
1546
+ if (d2 < bestD2) { bestD2 = d2; best = i; }
1547
+ }
1548
+ return V(_dispBuf[best].x, _dispBuf[best].y, _dispBuf[best].z);
1549
+ }
1550
+ return V(sx/totalW, sy/totalW, sz/totalW);
1551
+ }
1552
+
1553
+ /* deformed face point: warpToFace base + current mesh displacement. */
1554
+ function deformedPoint(u, v) {
1555
+ const base = warpToFace(u, v);
1556
+ if (!renderConfig.overlayTracksMesh) return base;
1557
+ const disp = sampleDispAtUV(u, v);
1558
+ return V(base.x + disp.x, base.y + disp.y, base.z + disp.z);
1559
+ }
1560
+
1561
+ /* smooth Catmull-Rom curve through control points, fixed sample count */
1562
+ function smoothPath(controls, samples = 18) {
1563
+ const cp = [controls[0], ...controls, controls[controls.length-1]];
1564
+ const out = [];
1565
+ for (let i = 0; i < cp.length - 3; i++) {
1566
+ const p0 = cp[i], p1 = cp[i+1], p2 = cp[i+2], p3 = cp[i+3];
1567
+ const segs = (i === cp.length - 4) ? samples : samples - 1;
1568
+ for (let s = 0; s <= segs; s++) {
1569
+ const t = s / samples;
1570
+ const t2 = t*t, t3 = t2*t;
1571
+ out.push(V(
1572
+ 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),
1573
+ 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),
1574
+ 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)
1575
+ ));
1576
+ }
1577
+ }
1578
+ return out;
1579
+ }
1580
+
1581
+ function makeTube(name, points, radius, instance) {
1582
+ const r = instance ? radius : radius * renderConfig.lineThickness;
1583
+ const opts = { path: points, radius: r, tessellation: 6, updatable: true };
1584
+ if (instance) opts.instance = instance;
1585
+ const tube = BABYLON.MeshBuilder.CreateTube(name, opts, scene);
1586
+ if (!instance) {
1587
+ tube.material = minimalMat;
1588
+ tube.parent = minimalGroup;
1589
+ }
1590
+ return tube;
1591
+ }
1592
+
1593
+ /* mouth: upper + lower lip beziers driven by the same lipTarget()
1594
+ formula the mesh anchor uses, so they stay perfectly in sync */
1595
+ let mouthUpperMesh, mouthLowerMesh;
1596
+
1597
+ function mouthLipPaths() {
1598
+ const p = computeMouthParams();
1599
+ // 5 sample points across the lip (corners + 2 peaks + center), then
1600
+ // smooth them into a Catmull-Rom curve.
1601
+ const upperXR = [-1.0, -0.45, 0.0, 0.45, 1.0];
1602
+ const lowerXR = [-1.0, -0.5, 0.0, 0.5, 1.0];
1603
+ const upper = smoothPath(upperXR.map(x => lipTarget(x, true, p)), 18);
1604
+ const lower = smoothPath(lowerXR.map(x => lipTarget(x, false, p)), 18);
1605
+ return { upper, lower };
1606
+ }
1607
+
1608
+ /* eyes: upper + lower lid arcs, driven by blink + squint + look */
1609
+ const eyeData = [
1610
+ { side: 'L', uv: [0.30, 0.40], hw: 0.10, hh: 0.040 },
1611
+ { side: 'R', uv: [0.70, 0.40], hw: 0.10, hh: 0.040 },
1612
+ ];
1613
+ let eyeMeshes = [];
1614
+
1615
+ function eyePath(eye, isUpper) {
1616
+ const blink = eye.side === 'L' ? state.eyeBlinkLeft : state.eyeBlinkRight;
1617
+ const squint = state.eyeSquint;
1618
+ const center = deformedPoint(eye.uv[0], eye.uv[1]); // ← tracks mesh
1619
+ const N = 12;
1620
+ const pts = [];
1621
+ const squintShift = squint * 0.012;
1622
+ for (let i = 0; i <= N; i++) {
1623
+ const t = i / N;
1624
+ const a = t * Math.PI;
1625
+ const x = center.x + Math.cos(Math.PI - a) * eye.hw;
1626
+ const baseY = center.y + (isUpper ? 1 : -1) * Math.sin(a) * eye.hh;
1627
+ const y = baseY * (1 - blink) + center.y * blink;
1628
+ const yWithSquint = y + (isUpper ? -squintShift : squintShift * 0.5);
1629
+ const z = center.z + 0.018 + Math.sin(a) * 0.012;
1630
+ pts.push(V(x, yWithSquint, z));
1631
+ }
1632
+ return pts;
1633
+ }
1634
+
1635
+ /* brows: 3-point bezier per brow, driven by browInner/Outer/Down channels */
1636
+ const browData = [
1637
+ { side: 'L', uv: [0.27, 0.27] },
1638
+ { side: 'R', uv: [0.73, 0.27] },
1639
+ ];
1640
+ let browMeshes = [];
1641
+
1642
+ function browPath(brow) {
1643
+ const center = deformedPoint(brow.uv[0], brow.uv[1]); // ← tracks mesh
1644
+ const sign = brow.side === 'L' ? -1 : 1;
1645
+ const innerLift = state.browInnerUp * 0.085 - state.browDown * 0.05;
1646
+ const outerLift = (state.browOuterUp >= 0 ? state.browOuterUp : 0) * 0.07 - state.browDown * 0.05;
1647
+ const innerX = center.x + sign * (-0.10);
1648
+ const midX = center.x;
1649
+ const outerX = center.x + sign * 0.10;
1650
+ const innerY = center.y + innerLift;
1651
+ const midY = center.y + (innerLift + outerLift) * 0.5 + 0.005;
1652
+ const outerY = center.y + outerLift - 0.005;
1653
+ const z = center.z + 0.018;
1654
+ return smoothPath([V(innerX, innerY, z), V(midX, midY, z + 0.01), V(outerX, outerY, z)], 12);
1655
+ }
1656
+
1657
+ /* nose: simple bridge + 2 nostril arcs */
1658
+ let noseBridgeMesh = null, noseLeftMesh = null, noseRightMesh = null;
1659
+ function nosePaths() {
1660
+ const flair = state.noseSneer * 0.025;
1661
+ const top = deformedPoint(0.50, 0.40); // ← tracks mesh
1662
+ const tip = deformedPoint(0.50, 0.55); // ← tracks mesh
1663
+ const bridge = smoothPath([
1664
+ V(top.x, top.y - 0.02, top.z + 0.02),
1665
+ V(top.x - 0.005, (top.y + tip.y) * 0.5, (top.z + tip.z) * 0.5 + 0.05),
1666
+ V(tip.x, tip.y + 0.03, tip.z + 0.05),
1667
+ ], 14);
1668
+ const baseY = tip.y + 0.01;
1669
+ const leftN = smoothPath([
1670
+ V(tip.x, baseY, tip.z + 0.05),
1671
+ V(tip.x - 0.06 - flair, baseY - 0.03, tip.z + 0.02),
1672
+ V(tip.x - 0.04, baseY - 0.05, tip.z + 0.005),
1673
+ V(tip.x - 0.01, baseY - 0.02, tip.z + 0.03),
1674
+ ], 10);
1675
+ const rightN = smoothPath([
1676
+ V(tip.x, baseY, tip.z + 0.05),
1677
+ V(tip.x + 0.06 + flair, baseY - 0.03, tip.z + 0.02),
1678
+ V(tip.x + 0.04, baseY - 0.05, tip.z + 0.005),
1679
+ V(tip.x + 0.01, baseY - 0.02, tip.z + 0.03),
1680
+ ], 10);
1681
+ return { bridge, leftN, rightN };
1682
+ }
1683
+
1684
+ /* (re)build all minimal-line tubes — used at startup AND when the
1685
+ line-thickness slider changes (tube radius is fixed at creation). */
1686
+ function rebuildMinimalLines() {
1687
+ if (mouthUpperMesh) { mouthUpperMesh.dispose(); mouthUpperMesh = null; }
1688
+ if (mouthLowerMesh) { mouthLowerMesh.dispose(); mouthLowerMesh = null; }
1689
+ for (const em of eyeMeshes) { em.upper.dispose(); em.lower.dispose(); }
1690
+ eyeMeshes = [];
1691
+ for (const bm of browMeshes) bm.mesh.dispose();
1692
+ browMeshes = [];
1693
+ if (noseBridgeMesh) { noseBridgeMesh.dispose(); noseBridgeMesh = null; }
1694
+ if (noseLeftMesh) { noseLeftMesh.dispose(); noseLeftMesh = null; }
1695
+ if (noseRightMesh) { noseRightMesh.dispose(); noseRightMesh = null; }
1696
+
1697
+ const { upper, lower } = mouthLipPaths();
1698
+ mouthUpperMesh = makeTube('mouth_u', upper, 0.010);
1699
+ mouthLowerMesh = makeTube('mouth_l', lower, 0.010);
1700
+
1701
+ for (const eye of eyeData) {
1702
+ const u = makeTube('eye_' + eye.side + '_u', eyePath(eye, true), 0.0085);
1703
+ const l = makeTube('eye_' + eye.side + '_l', eyePath(eye, false), 0.0085);
1704
+ eyeMeshes.push({ eye, upper: u, lower: l });
1705
+ }
1706
+
1707
+ for (const brow of browData) {
1708
+ const m = makeTube('brow_' + brow.side, browPath(brow), 0.011);
1709
+ m.material = browMat; // v011: brow color is separate from line color
1710
+ browMeshes.push({ brow, mesh: m });
1711
+ }
1712
+
1713
+ const np = nosePaths();
1714
+ noseBridgeMesh = makeTube('nose_b', np.bridge, 0.009);
1715
+ noseLeftMesh = makeTube('nose_l', np.leftN, 0.0085);
1716
+ noseRightMesh = makeTube('nose_r', np.rightN, 0.0085);
1717
+ }
1718
+
1719
+ rebuildMinimalLines();
1720
+
1721
+ function updateMinimal() {
1722
+ // mouth
1723
+ const mp = mouthLipPaths();
1724
+ makeTube('', mp.upper, 0.010, mouthUpperMesh);
1725
+ makeTube('', mp.lower, 0.010, mouthLowerMesh);
1726
+ // eyes
1727
+ for (const em of eyeMeshes) {
1728
+ makeTube('', eyePath(em.eye, true), 0.0085, em.upper);
1729
+ makeTube('', eyePath(em.eye, false), 0.0085, em.lower);
1730
+ }
1731
+ // brows
1732
+ for (const bm of browMeshes) {
1733
+ makeTube('', browPath(bm.brow), 0.011, bm.mesh);
1734
+ }
1735
+ // nose
1736
+ const np = nosePaths();
1737
+ makeTube('', np.bridge, 0.009, noseBridgeMesh);
1738
+ makeTube('', np.leftN, 0.0085, noseLeftMesh);
1739
+ makeTube('', np.rightN, 0.0085, noseRightMesh);
1740
+ }
1741
+
1742
+ function applyMinimalVisibility() {
1743
+ minimalGroup.setEnabled(renderConfig.minimal);
1744
+ }
1745
+ applyMinimalVisibility();
1746
+
1747
+
1748
+ /* ─── 5. CHANNEL SMOOTHING ──────────────────────────────────────────────
1749
+ Each frame, lerp state[ch] toward stateTarget[ch]. Different channels
1750
+ have different responsiveness. Visemes snap fast; brows are slower. */
1751
+
1752
+ const SMOOTH = {
1753
+ default: 0.35,
1754
+ eyeBlinkLeft: 0.55, eyeBlinkRight: 0.55,
1755
+ // visemes need to be peppy for lip-sync
1756
+ ...Object.fromEntries(Object.keys(VISEME_PARAMS).map(v => ['viseme_' + v, 0.45])),
1757
+ browInnerUp: 0.18, browOuterUp: 0.18, browDown: 0.18,
1758
+ headRotateX: 0.10, headRotateY: 0.10, headRotateZ: 0.10,
1759
+ eyeLookH: 0.25, eyeLookV: 0.25,
1760
+ };
1761
+
1762
+ function smoothChannels(dt) {
1763
+ for (const ch of CHANNEL_NAMES) {
1764
+ if (manualLock[ch]) { state[ch] = stateTarget[ch]; continue; }
1765
+ const k = SMOOTH[ch] || SMOOTH.default;
1766
+ const a = 1 - Math.exp(-k * dt * 30);
1767
+ state[ch] = state[ch] + (stateTarget[ch] - state[ch]) * a;
1768
+ }
1769
+ }
1770
+
1771
+ /* ─── 6. AUDIO + LIVE LIP-SYNC ──────────────────────────────────────────
1772
+ Web Audio AnalyserNode → frequency bins → estimated visemes.
1773
+
1774
+ Approach (lightweight formant heuristics):
1775
+ - low-freq energy (200-700 Hz) → O / U / aa (open back vowels)
1776
+ - mid-freq energy (700-2000 Hz) → aa / E
1777
+ - hi-mid energy (2000-4500) → E / I (front vowels)
1778
+ - high energy (4500-9000) → SS, FF, CH (sibilants/fricatives)
1779
+ - overall amplitude → jawOpen + viseme intensity
1780
+ - silence floor → viseme_sil
1781
+ */
1782
+
1783
+ let audioCtx = null;
1784
+ let audioBuffer = null;
1785
+ let audioSource = null;
1786
+ let analyser = null;
1787
+ let freqData = null;
1788
+ let timeData = null;
1789
+ let isPlaying = false;
1790
+ let playStartCtxTime = 0;
1791
+ let playStartOffset = 0;
1792
+ let pausedAt = 0;
1793
+ let audioDuration = 0;
1794
+ let audioName = 'test-tone';
1795
+
1796
+ function ensureAudioCtx() {
1797
+ if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
1798
+ return audioCtx;
1799
+ }
1800
+
1801
+ async function loadAudioFile(file) {
1802
+ ensureAudioCtx();
1803
+ const arr = await file.arrayBuffer();
1804
+ audioBuffer = await audioCtx.decodeAudioData(arr);
1805
+ audioDuration = audioBuffer.duration;
1806
+ audioName = file.name;
1807
+ document.getElementById('audio-name').textContent = file.name + ' · ' + audioDuration.toFixed(2) + 's';
1808
+ document.getElementById('t-tot').textContent = formatTime(audioDuration * 1000);
1809
+ pausedAt = 0;
1810
+ }
1811
+
1812
+ /* simple test-tone buffer so the UI does something on first load */
1813
+ function buildTestTone() {
1814
+ ensureAudioCtx();
1815
+ const dur = 4, sr = audioCtx.sampleRate;
1816
+ const buf = audioCtx.createBuffer(1, sr * dur, sr);
1817
+ const ch = buf.getChannelData(0);
1818
+ // Lightly modulated tone, just enough to make the FFT do *something*.
1819
+ for (let i = 0; i < ch.length; i++) {
1820
+ const t = i / sr;
1821
+ const freq = 220 + Math.sin(t * 1.4) * 80;
1822
+ ch[i] = Math.sin(2 * Math.PI * freq * t) * 0.3 * (0.6 + 0.4 * Math.sin(t * 6));
1823
+ }
1824
+ audioBuffer = buf;
1825
+ audioDuration = dur;
1826
+ document.getElementById('t-tot').textContent = formatTime(dur * 1000);
1827
+ }
1828
+
1829
+ function startPlayback(fromOffset = 0) {
1830
+ if (!audioBuffer) buildTestTone();
1831
+ ensureAudioCtx();
1832
+ if (audioCtx.state === 'suspended') audioCtx.resume();
1833
+
1834
+ if (audioSource) try { audioSource.stop(); } catch {}
1835
+ audioSource = audioCtx.createBufferSource();
1836
+ audioSource.buffer = audioBuffer;
1837
+ audioSource.loop = !!renderConfig.loopAudio;
1838
+
1839
+ if (!analyser) {
1840
+ analyser = audioCtx.createAnalyser();
1841
+ analyser.fftSize = 1024;
1842
+ analyser.smoothingTimeConstant = 0.55;
1843
+ freqData = new Uint8Array(analyser.frequencyBinCount);
1844
+ timeData = new Uint8Array(analyser.fftSize);
1845
+ }
1846
+ audioSource.connect(analyser);
1847
+ analyser.connect(audioCtx.destination);
1848
+ audioSource.start(0, fromOffset);
1849
+ playStartCtxTime = audioCtx.currentTime;
1850
+ playStartOffset = fromOffset;
1851
+ isPlaying = true;
1852
+ setStatus('live', 'playing · live FFT');
1853
+ audioSource.onended = () => {
1854
+ if (isPlaying) {
1855
+ isPlaying = false;
1856
+ pausedAt = 0;
1857
+ setStatus('idle', 'idle');
1858
+ document.getElementById('btn-play').textContent = '▶ play';
1859
+ }
1860
+ };
1861
+ }
1862
+
1863
+ function stopPlayback() {
1864
+ if (audioSource) try { audioSource.stop(); } catch {}
1865
+ isPlaying = false;
1866
+ pausedAt = 0;
1867
+ setStatus('idle', 'idle');
1868
+ document.getElementById('btn-play').textContent = '▶ play';
1869
+ }
1870
+
1871
+ function getPlaybackTime() {
1872
+ if (!isPlaying) return pausedAt;
1873
+ return playStartOffset + (audioCtx.currentTime - playStartCtxTime);
1874
+ }
1875
+
1876
+ /* compute viseme weights from frequency data this frame */
1877
+ function analyzeAudioFrame() {
1878
+ if (!analyser) return;
1879
+ analyser.getByteFrequencyData(freqData);
1880
+
1881
+ const sr = audioCtx.sampleRate;
1882
+ const binHz = sr / analyser.fftSize;
1883
+
1884
+ function bandEnergy(loHz, hiHz) {
1885
+ const lo = Math.max(0, Math.floor(loHz / binHz));
1886
+ const hi = Math.min(freqData.length - 1, Math.ceil(hiHz / binHz));
1887
+ let sum = 0, n = 0;
1888
+ for (let i = lo; i <= hi; i++) { sum += freqData[i]; n++; }
1889
+ return n > 0 ? (sum / n) / 255 : 0;
1890
+ }
1891
+
1892
+ const eLow = bandEnergy(80, 700); // F1 vowels low
1893
+ const eMid = bandEnergy(700, 1800); // F1 vowels mid
1894
+ const eHi = bandEnergy(1800, 3500); // F2 front vowels
1895
+ const eSib = bandEnergy(4000, 9000); // sibilants/fricatives
1896
+ const eAir = bandEnergy(9000, 15000); // FF / SS air
1897
+
1898
+ // overall RMS-ish from time-domain (cheap)
1899
+ analyser.getByteTimeDomainData(timeData);
1900
+ let sum = 0;
1901
+ for (let i = 0; i < timeData.length; i++) {
1902
+ const v = (timeData[i] - 128) / 128;
1903
+ sum += v * v;
1904
+ }
1905
+ const rms = Math.sqrt(sum / timeData.length); // 0..~0.5
1906
+
1907
+ const speechActive = rms > 0.012;
1908
+
1909
+ // reset all viseme targets toward 0 (will be overwritten below)
1910
+ for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1911
+
1912
+ if (!speechActive) {
1913
+ stateTarget.viseme_sil = 1;
1914
+ stateTarget.jawOpen = 0;
1915
+ return;
1916
+ }
1917
+
1918
+ // amplitude → mouth open
1919
+ const amp = Math.min(1, rms * 4.5);
1920
+ stateTarget.jawOpen = amp * 0.7;
1921
+
1922
+ // Heuristic viseme allocation. Sum should not exceed ~1.2.
1923
+ // Hi sibilance dominates: that's an SS or FF
1924
+ if (eSib > 0.35 && eSib > eMid) {
1925
+ stateTarget.viseme_SS = Math.min(1, eSib * 1.3);
1926
+ stateTarget.viseme_FF = Math.min(0.6, eAir * 1.2);
1927
+ }
1928
+ // Front vowel: high mid-hi balance
1929
+ else if (eHi > eLow * 1.2 && eHi > 0.25) {
1930
+ if (eHi > eMid) {
1931
+ stateTarget.viseme_I = Math.min(1, eHi * 1.4);
1932
+ } else {
1933
+ stateTarget.viseme_E = Math.min(1, eMid * 1.3);
1934
+ }
1935
+ }
1936
+ // Back rounded vowel: low dominant, mid weak
1937
+ else if (eLow > eHi * 1.3 && eLow > 0.25) {
1938
+ if (eMid > eLow * 0.65) {
1939
+ stateTarget.viseme_O = Math.min(1, eLow * 1.2);
1940
+ } else {
1941
+ stateTarget.viseme_U = Math.min(1, eLow * 1.2);
1942
+ }
1943
+ }
1944
+ // Open vowel: balanced low+mid energy
1945
+ else if (eMid > 0.2 && eLow > 0.2) {
1946
+ stateTarget.viseme_aa = Math.min(1, (eLow + eMid) * 0.6);
1947
+ }
1948
+ // Default: a hint of E
1949
+ else {
1950
+ stateTarget.viseme_E = Math.min(0.6, amp);
1951
+ }
1952
+
1953
+ // small filler of sil so things never look possessed
1954
+ stateTarget.viseme_sil = Math.max(0, 1 - amp * 1.3);
1955
+ }
1956
+
1957
+ /* ─── 7. IDLE MICRO-MOVEMENTS ───────────────────────────────────────────
1958
+ Auto blinks, slight head bob, brow micro-shifts. Always layered, but
1959
+ suppressed when user is dragging a slider for that channel. */
1960
+
1961
+ let nextBlink = 1.5 + Math.random() * 3;
1962
+ let blinkUntil = 0;
1963
+ let elapsedSec = 0;
1964
+
1965
+ function idleAnimate(dt) {
1966
+ elapsedSec += dt;
1967
+
1968
+ const trackCh = (trackPlaying && importedTrack && importedTrack.channels) ? importedTrack.channels : null;
1969
+ const drivenByTrack = (ch) => trackCh && trackCh[ch] && trackCh[ch].length > 0;
1970
+
1971
+ // blinks — only auto-blink if eyeBlink isn't being driven externally
1972
+ if (!drivenByTrack('eyeBlinkLeft') && !drivenByTrack('eyeBlinkRight')) {
1973
+ if (elapsedSec > nextBlink && elapsedSec > blinkUntil) {
1974
+ blinkUntil = elapsedSec + 0.16;
1975
+ nextBlink = elapsedSec + 2.5 + Math.random() * 4.5;
1976
+ }
1977
+ if (elapsedSec < blinkUntil) {
1978
+ const phase = (blinkUntil - elapsedSec) / 0.16;
1979
+ const v = 1 - Math.abs(phase - 0.5) * 2;
1980
+ if (!manualLock.eyeBlinkLeft) stateTarget.eyeBlinkLeft = v;
1981
+ if (!manualLock.eyeBlinkRight) stateTarget.eyeBlinkRight = v;
1982
+ } else {
1983
+ if (!manualLock.eyeBlinkLeft && stateTarget.eyeBlinkLeft > 0 && stateTarget.eyeBlinkLeft < 0.05) stateTarget.eyeBlinkLeft = 0;
1984
+ if (!manualLock.eyeBlinkRight && stateTarget.eyeBlinkRight > 0 && stateTarget.eyeBlinkRight < 0.05) stateTarget.eyeBlinkRight = 0;
1985
+ }
1986
+ }
1987
+
1988
+ // slow head bob — skip if track drives it
1989
+ if (!manualLock.headRotateY && !drivenByTrack('headRotateY'))
1990
+ stateTarget.headRotateY = Math.sin(elapsedSec * 0.31) * 0.08 + Math.sin(elapsedSec * 0.13 + 1.3) * 0.05;
1991
+ if (!manualLock.headRotateX && !drivenByTrack('headRotateX'))
1992
+ stateTarget.headRotateX = Math.sin(elapsedSec * 0.21 + 0.5) * 0.05;
1993
+ if (!manualLock.headRotateZ && !drivenByTrack('headRotateZ'))
1994
+ stateTarget.headRotateZ = Math.sin(elapsedSec * 0.17 + 2.1) * 0.04;
1995
+
1996
+ // eye darts — occasional saccade
1997
+ if (Math.random() < 0.005) {
1998
+ if (!manualLock.eyeLookH && !drivenByTrack('eyeLookH')) stateTarget.eyeLookH = (Math.random() - 0.5) * 1.2;
1999
+ if (!manualLock.eyeLookV && !drivenByTrack('eyeLookV')) stateTarget.eyeLookV = (Math.random() - 0.5) * 0.8;
2000
+ }
2001
+ }
2002
+
2003
+ /* ─── 8. RECORDING / EXPORT ─────────────────────────────────────────────
2004
+ Sample all channel state[] at fixed rate. Compress to event lists.
2005
+ Format: { channels: { name: [[t_ms, value], ...] } }
2006
+ */
2007
+
2008
+ let recording = false;
2009
+ let recordStartMs = 0;
2010
+ let captureBuffer = []; // [{t, snapshot}]
2011
+ const captureFps = 60;
2012
+ let lastCaptureMs = -Infinity;
2013
+
2014
+ function startRecording() {
2015
+ recording = true;
2016
+ captureBuffer = [];
2017
+ recordStartMs = performance.now();
2018
+ setStatus('rec', 'recording');
2019
+ document.getElementById('btn-record').classList.add('recording');
2020
+ document.getElementById('btn-record').textContent = '■ stop rec';
2021
+ document.getElementById('btn-export').disabled = true;
2022
+ }
2023
+
2024
+ function stopRecording() {
2025
+ recording = false;
2026
+ document.getElementById('btn-record').classList.remove('recording');
2027
+ document.getElementById('btn-record').textContent = '● record';
2028
+ document.getElementById('btn-export').disabled = captureBuffer.length === 0;
2029
+ document.getElementById('track-info').textContent =
2030
+ captureBuffer.length + ' samples · ' + (captureBuffer.length ? (captureBuffer[captureBuffer.length-1].t/1000).toFixed(2) + 's' : '0s');
2031
+ setStatus(isPlaying ? 'live' : 'idle', isPlaying ? 'playing · live FFT' : 'idle');
2032
+ }
2033
+
2034
+ function captureFrame() {
2035
+ if (!recording) return;
2036
+ const now = performance.now() - recordStartMs;
2037
+ if (now - lastCaptureMs < 1000 / captureFps) return;
2038
+ lastCaptureMs = now;
2039
+ const snap = {};
2040
+ for (const ch of CHANNEL_NAMES) snap[ch] = +state[ch].toFixed(3);
2041
+ captureBuffer.push({ t: Math.round(now), snap });
2042
+ }
2043
+
2044
+ /* compress raw samples → event list per channel. Keeps only events where
2045
+ linear interpolation from the last kept event to the next would fail to
2046
+ approximate intermediate samples within tolerance. MIDI-style sparse
2047
+ keyframes with implicit linear ramps. */
2048
+ function compressTrackChannel(samples, ch, tol) {
2049
+ if (samples.length === 0) return [];
2050
+ if (samples.length === 1) return [[samples[0].t, samples[0].snap[ch]]];
2051
+
2052
+ const events = [[samples[0].t, samples[0].snap[ch]]];
2053
+ let anchor = 0; // index of last KEPT sample
2054
+
2055
+ for (let i = 1; i < samples.length; i++) {
2056
+ const t0 = samples[anchor].t, v0 = samples[anchor].snap[ch];
2057
+ const ti = samples[i].t, vi = samples[i].snap[ch];
2058
+ let ok = true;
2059
+ for (let j = anchor + 1; j < i; j++) {
2060
+ const tj = samples[j].t, vj = samples[j].snap[ch];
2061
+ const interp = v0 + (vi - v0) * (tj - t0) / (ti - t0);
2062
+ if (Math.abs(interp - vj) > tol) { ok = false; break; }
2063
+ }
2064
+ if (!ok) {
2065
+ // emit i-1 (the last good point), restart line from there
2066
+ const prev = samples[i-1];
2067
+ events.push([prev.t, prev.snap[ch]]);
2068
+ anchor = i - 1;
2069
+ }
2070
+ }
2071
+ // always emit the final sample
2072
+ const last = samples[samples.length - 1];
2073
+ if (events[events.length-1][0] !== last.t) events.push([last.t, last.snap[ch]]);
2074
+ return events;
2075
+ }
2076
+
2077
+ function compressTrack(samples, tol = 0.012) {
2078
+ const out = {};
2079
+ for (const ch of CHANNEL_NAMES) out[ch] = compressTrackChannel(samples, ch, tol);
2080
+ return out;
2081
+ }
2082
+
2083
+ function exportTrack() {
2084
+ if (captureBuffer.length === 0) return;
2085
+ const compressed = compressTrack(captureBuffer);
2086
+ const totalEvents = Object.values(compressed).reduce((s, ev) => s + ev.length, 0);
2087
+ const payload = {
2088
+ format: 'wireface-v1',
2089
+ duration_ms: captureBuffer[captureBuffer.length - 1].t,
2090
+ audio_ref: audioName,
2091
+ fps_capture: captureFps,
2092
+ interpolation: 'linear',
2093
+ channels: compressed,
2094
+ metadata: {
2095
+ created: new Date().toISOString(),
2096
+ source: 'live_audio_fft',
2097
+ total_events: totalEvents,
2098
+ total_samples: captureBuffer.length,
2099
+ compression_ratio: (totalEvents / (captureBuffer.length * CHANNEL_NAMES.length)).toFixed(3),
2100
+ channel_definitions: Object.fromEntries(
2101
+ CHANNEL_NAMES.map(n => [n, { group: CHANNELS[n].group, range: CHANNELS[n].range }])
2102
+ ),
2103
+ },
2104
+ };
2105
+ const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
2106
+ const url = URL.createObjectURL(blob);
2107
+ const a = document.createElement('a');
2108
+ a.href = url;
2109
+ a.download = (audioName.replace(/\.[^.]+$/, '') || 'wireface') + '.track.json';
2110
+ a.click();
2111
+ URL.revokeObjectURL(url);
2112
+ }
2113
+
2114
+ /* ─── playback of imported tracks ─────────────────────────────────────── */
2115
+ let importedTrack = null;
2116
+ let trackPlayStart = 0;
2117
+ let trackPlaying = false;
2118
+
2119
+ /* ─── Kokoro / HeadTTS / Oculus15 phoneme-aligned format ───────────────
2120
+ { audio, duration, phoneme_alphabet: "Oculus15",
2121
+ visemes: [{v, t, d}], words: [...], emotions: [{e, t, d}] }
2122
+ Convert to wireface-v1 channel events. Each viseme gets a square pulse
2123
+ (anchor-0, on, hold, off) so linear interp produces clean transitions. */
2124
+
2125
+ const VISEMES_OCULUS = ['sil','PP','FF','TH','DD','kk','CH','SS','nn','RR','aa','E','I','O','U'];
2126
+
2127
+ const EMO_DELTAS = {
2128
+ neutral: {},
2129
+ happy: { browOuterUp: 0.40, mouthSmile: 0.60, eyeSquint: 0.20 },
2130
+ sad: { browInnerUp: 0.60, browDown: 0.15, mouthSmile: -0.40 },
2131
+ angry: { browDown: 0.65, browOuterUp: -0.35, mouthSmile: -0.30, noseSneer: 0.40 },
2132
+ fear: { browInnerUp: 0.65, browOuterUp: 0.55, mouthSmile: -0.20 },
2133
+ surprise: { browInnerUp: 0.50, browOuterUp: 0.75, jawOpen: 0.30 },
2134
+ disgust: { browDown: 0.30, noseSneer: 0.65, mouthSmile: -0.20 },
2135
+ };
2136
+
2137
+ function convertKokoroToWireface(k) {
2138
+ const channels = {};
2139
+ // initialize every viseme channel with leading 0 (or 1 for sil)
2140
+ for (const v of VISEMES_OCULUS) channels['viseme_' + v] = [[0, v === 'sil' ? 1 : 0]];
2141
+
2142
+ // group viseme events into ranges, merging consecutive same-viseme entries
2143
+ const ranges = {}; // { 'TH': [[startMs, endMs], ...] }
2144
+ for (const ev of (k.visemes || [])) {
2145
+ const start = Math.round(ev.t * 1000);
2146
+ const end = Math.round((ev.t + ev.d) * 1000);
2147
+ if (!ranges[ev.v]) ranges[ev.v] = [];
2148
+ const last = ranges[ev.v][ranges[ev.v].length - 1];
2149
+ if (last && last[1] === start) last[1] = end;
2150
+ else ranges[ev.v].push([start, end]);
2151
+ }
2152
+
2153
+ // emit square pulses per range
2154
+ for (const v of VISEMES_OCULUS) {
2155
+ if (!ranges[v]) continue;
2156
+ const ch = 'viseme_' + v;
2157
+ for (const [start, end] of ranges[v]) {
2158
+ // anchor "still off" at start-1 if we were at 0 before
2159
+ const lastEv = channels[ch][channels[ch].length - 1];
2160
+ if (start > 1 && lastEv[1] !== 1) channels[ch].push([start - 1, lastEv[1]]);
2161
+ channels[ch].push([start, 1]);
2162
+ if (end - start > 2) channels[ch].push([end - 1, 1]); // hold
2163
+ channels[ch].push([end, 0]);
2164
+ }
2165
+ }
2166
+
2167
+ // emotions → brow / smile / sneer baselines (held, smooth ramps)
2168
+ const allEmoCh = new Set();
2169
+ Object.values(EMO_DELTAS).forEach(d => Object.keys(d).forEach(k => allEmoCh.add(k)));
2170
+ for (const ch of allEmoCh) channels[ch] = [[0, 0]];
2171
+ for (const ev of (k.emotions || [])) {
2172
+ const start = Math.round(ev.t * 1000);
2173
+ const settings = EMO_DELTAS[ev.e] || {};
2174
+ for (const ch of allEmoCh) {
2175
+ const target = settings[ch] || 0;
2176
+ const last = channels[ch][channels[ch].length - 1];
2177
+ if (last[1] !== target) channels[ch].push([start, target]);
2178
+ }
2179
+ }
2180
+ // return all emotion channels to 0 at end
2181
+ if ((k.emotions || []).length) {
2182
+ const lastEmo = k.emotions[k.emotions.length - 1];
2183
+ const endMs = Math.round((lastEmo.t + lastEmo.d) * 1000);
2184
+ for (const ch of allEmoCh) {
2185
+ const last = channels[ch][channels[ch].length - 1];
2186
+ if (last[1] !== 0) channels[ch].push([endMs, 0]);
2187
+ }
2188
+ }
2189
+
2190
+ // count events for metadata
2191
+ let totalEvents = 0;
2192
+ for (const c in channels) totalEvents += channels[c].length;
2193
+
2194
+ return {
2195
+ format: 'wireface-v1',
2196
+ duration_ms: Math.round(k.duration * 1000),
2197
+ audio_ref: k.audio || null,
2198
+ fps_capture: 0,
2199
+ interpolation: 'linear',
2200
+ channels: channels,
2201
+ metadata: {
2202
+ created: new Date().toISOString(),
2203
+ source: 'phoneme_alignment',
2204
+ converted_from: 'oculus15_kokoro',
2205
+ voice: k.voice,
2206
+ engine: k.engine,
2207
+ language: k.language,
2208
+ total_events: totalEvents,
2209
+ viseme_count: (k.visemes || []).length,
2210
+ words: k.words || null, // preserve for future subtitle support
2211
+ },
2212
+ };
2213
+ }
2214
+
2215
+ async function importTrack(file) {
2216
+ const text = await file.text();
2217
+ const data = JSON.parse(text);
2218
+
2219
+ let track;
2220
+ let formatLabel;
2221
+ if (data.format === 'wireface-v1') {
2222
+ track = data;
2223
+ formatLabel = 'wireface-v1';
2224
+ } else if (data.phoneme_alphabet === 'Oculus15' || (data.visemes && Array.isArray(data.visemes) && data.visemes[0] && 'v' in data.visemes[0])) {
2225
+ track = convertKokoroToWireface(data);
2226
+ formatLabel = 'kokoro/oculus15';
2227
+ } else {
2228
+ throw new Error('unrecognized JSON format — expected wireface-v1 or Oculus15 viseme track');
2229
+ }
2230
+
2231
+ importedTrack = track;
2232
+ document.getElementById('track-info').textContent =
2233
+ formatLabel + ' · ' + (importedTrack.duration_ms/1000).toFixed(2) + 's · ' +
2234
+ Object.keys(importedTrack.channels || {}).length + ' channels';
2235
+ document.getElementById('t-tot').textContent = formatTime(importedTrack.duration_ms);
2236
+ }
2237
+
2238
+ function playTrack() {
2239
+ if (!importedTrack) return;
2240
+ trackPlaying = true;
2241
+ trackPlayStart = performance.now();
2242
+ setStatus('live', 'playing track');
2243
+ }
2244
+
2245
+ function evalTrack(tMs) {
2246
+ if (!importedTrack || !importedTrack.channels) return;
2247
+ for (const ch in importedTrack.channels) {
2248
+ if (!(ch in stateTarget)) continue;
2249
+ if (manualLock[ch]) continue;
2250
+ const events = importedTrack.channels[ch];
2251
+ if (!events.length) continue;
2252
+ if (tMs <= events[0][0]) { stateTarget[ch] = events[0][1]; continue; }
2253
+ if (tMs >= events[events.length-1][0]) { stateTarget[ch] = events[events.length-1][1]; continue; }
2254
+ // binary search for surrounding events
2255
+ let lo = 0, hi = events.length - 1;
2256
+ while (hi - lo > 1) {
2257
+ const mid = (lo + hi) >> 1;
2258
+ if (events[mid][0] <= tMs) lo = mid; else hi = mid;
2259
+ }
2260
+ const [t0, v0] = events[lo], [t1, v1] = events[hi];
2261
+ const a = (tMs - t0) / (t1 - t0);
2262
+ stateTarget[ch] = v0 + (v1 - v0) * a;
2263
+ }
2264
+ }
2265
+
2266
+ /* ─── 9. UI BINDINGS ───────────────────────────────────────────────────── */
2267
+
2268
+ const groupOrder = ['mouth', 'jaw', 'eyes', 'brows', 'nose', 'head'];
2269
+ const groupLabels = { mouth: 'mouth · oculus visemes', jaw: 'jaw + lips', eyes: 'eyes', brows: 'brows', nose: 'nose', head: 'head pose' };
2270
+
2271
+ const chanList = document.getElementById('chan-list');
2272
+ const chanRefs = {};
2273
+
2274
+ for (const g of groupOrder) {
2275
+ const grp = document.createElement('div');
2276
+ grp.className = 'chan-group';
2277
+ const lbl = document.createElement('div');
2278
+ lbl.className = 'label';
2279
+ lbl.textContent = groupLabels[g];
2280
+ grp.appendChild(lbl);
2281
+ for (const ch of CHANNEL_NAMES) {
2282
+ if (CHANNELS[ch].group !== g) continue;
2283
+ const row = document.createElement('div');
2284
+ row.className = 'chan';
2285
+ const name = document.createElement('div');
2286
+ name.className = 'chan-name';
2287
+ name.textContent = ch.replace('viseme_', 'vis·').replace('Rotate', '·');
2288
+ name.title = ch;
2289
+ const bar = document.createElement('div');
2290
+ bar.className = 'chan-bar';
2291
+ const fill = document.createElement('div');
2292
+ fill.className = 'fill';
2293
+ const live = document.createElement('div');
2294
+ live.className = 'live';
2295
+ bar.appendChild(fill);
2296
+ bar.appendChild(live);
2297
+ const val = document.createElement('div');
2298
+ val.className = 'chan-val';
2299
+ val.textContent = '0.00';
2300
+
2301
+ /* per-channel gain knob */
2302
+ const knob = document.createElement('div');
2303
+ knob.className = 'knob';
2304
+ knob.title = ch + ' gain — drag vertically · double-click to reset';
2305
+ const marker = document.createElement('div');
2306
+ marker.className = 'knob-marker';
2307
+ knob.appendChild(marker);
2308
+
2309
+ row.appendChild(name);
2310
+ row.appendChild(bar);
2311
+ row.appendChild(val);
2312
+ row.appendChild(knob);
2313
+ grp.appendChild(row);
2314
+ chanRefs[ch] = { fill, val, bar, knob };
2315
+
2316
+ /* knob drag handler — vertical drag changes the gain slider in [-2, +2].
2317
+ Gain multiplier is 2^k so knob center is unity, full left ≈ 1/4×, full
2318
+ right ≈ 4×. Double-click resets to 0 (no gain). */
2319
+ channelGains[ch] = 1.0;
2320
+ channelGainSliders[ch] = 0;
2321
+ let knobDragging = false, knobStartY = 0, knobStartK = 0;
2322
+ function applyKnob(ch, k) {
2323
+ k = Math.max(-2, Math.min(2, k));
2324
+ channelGainSliders[ch] = k;
2325
+ channelGains[ch] = Math.pow(2, k);
2326
+ marker.style.transform = `rotate(${k * 67.5}deg)`;
2327
+ knob.classList.toggle('gained', Math.abs(k) > 0.01);
2328
+ }
2329
+ knob.addEventListener('pointerdown', e => {
2330
+ knobDragging = true; knobStartY = e.clientY; knobStartK = channelGainSliders[ch];
2331
+ knob.setPointerCapture(e.pointerId); e.preventDefault();
2332
+ });
2333
+ knob.addEventListener('pointermove', e => {
2334
+ if (!knobDragging) return;
2335
+ const dy = knobStartY - e.clientY; // up = positive
2336
+ applyKnob(ch, knobStartK + dy * 0.02); // 200px drag = full range
2337
+ });
2338
+ knob.addEventListener('pointerup', () => { knobDragging = false; });
2339
+ knob.addEventListener('dblclick', () => applyKnob(ch, 0));
2340
+ chanRefs[ch].applyKnob = applyKnob;
2341
+
2342
+ /* drag-to-set */
2343
+ const range = CHANNELS[ch].range;
2344
+ let dragging = false;
2345
+ function setFromX(clientX) {
2346
+ const r = bar.getBoundingClientRect();
2347
+ const t = Math.max(0, Math.min(1, (clientX - r.left) / r.width));
2348
+ const v = range[0] + (range[1] - range[0]) * t;
2349
+ stateTarget[ch] = v;
2350
+ state[ch] = v;
2351
+ manualLock[ch] = true;
2352
+ }
2353
+ bar.addEventListener('pointerdown', e => {
2354
+ dragging = true;
2355
+ bar.setPointerCapture(e.pointerId);
2356
+ setFromX(e.clientX);
2357
+ });
2358
+ bar.addEventListener('pointermove', e => {
2359
+ if (dragging) setFromX(e.clientX);
2360
+ });
2361
+ bar.addEventListener('pointerup', e => {
2362
+ dragging = false;
2363
+ // unlock after a moment so audio analysis resumes
2364
+ setTimeout(() => { manualLock[ch] = false; }, 1200);
2365
+ });
2366
+ }
2367
+ chanList.appendChild(grp);
2368
+ }
2369
+
2370
+ document.getElementById('ch-count').textContent = String(CHANNEL_NAMES.length).padStart(2, '0');
2371
+ document.getElementById('coord-ch').textContent = String(CHANNEL_NAMES.length).padStart(2, '0');
2372
+
2373
+ /* moods — preset weight sets */
2374
+ const MOODS = {
2375
+ neutral: { browInnerUp: 0, browOuterUp: 0, browDown: 0, mouthSmile: 0, eyeSquint: 0 },
2376
+ happy: { browOuterUp: 0.4, mouthSmile: 0.7, eyeSquint: 0.25 },
2377
+ sad: { browInnerUp: 0.7, browDown: 0.2, mouthSmile: -0.5, eyeBlinkLeft: 0.15, eyeBlinkRight: 0.15 },
2378
+ angry: { browInnerUp: 0, browOuterUp: -0.4, browDown: 0.7, mouthSmile: -0.4, noseSneer: 0.5, eyeSquint: 0.4 },
2379
+ fear: { browInnerUp: 0.7, browOuterUp: 0.5, mouthSmile: -0.3, eyeBlinkLeft: -0.2, eyeBlinkRight: -0.2 },
2380
+ surprise:{ browInnerUp: 0.6, browOuterUp: 0.8, jawOpen: 0.5, mouthSmile: 0 },
2381
+ sleep: { eyeBlinkLeft: 1, eyeBlinkRight: 1, browDown: 0.3, mouthSmile: 0 },
2382
+ };
2383
+
2384
+ /* channels driven by mood blend (audio drives visemes & jawOpen separately) */
2385
+ const MOOD_CHANNELS = ['browInnerUp', 'browOuterUp', 'browDown', 'mouthSmile',
2386
+ 'eyeSquint', 'noseSneer', 'eyeBlinkLeft', 'eyeBlinkRight'];
2387
+
2388
+ /* per-frame mood crossfade — lerps moodCurrentWeights → moodTargetWeights
2389
+ over moodTransitionTime, then computes effective stateTarget for each
2390
+ mood-affected channel as the weighted sum across all moods. */
2391
+ function updateMoodBlend(dt) {
2392
+ const T = Math.max(0.05, renderConfig.moodTransitionTime);
2393
+ const halflife = T / 4; // ~95% reached in T seconds
2394
+ const a = 1 - Math.pow(0.5, dt / halflife);
2395
+ for (const m of MOOD_NAMES) {
2396
+ moodCurrentWeights[m] += (moodTargetWeights[m] - moodCurrentWeights[m]) * a;
2397
+ }
2398
+ for (const ch of MOOD_CHANNELS) {
2399
+ let target = 0;
2400
+ for (const m of MOOD_NAMES) {
2401
+ target += (MOODS[m][ch] || 0) * moodCurrentWeights[m];
2402
+ }
2403
+ stateTarget[ch] = target;
2404
+ }
2405
+ }
2406
+
2407
+ /* mood click → set target weights (current weights crossfade in updateMoodBlend) */
2408
+ let activeMood = 'neutral';
2409
+ document.querySelectorAll('[data-mood]').forEach(btn => {
2410
+ btn.addEventListener('click', () => {
2411
+ const m = btn.dataset.mood;
2412
+ if (!MOODS[m]) return;
2413
+ activeMood = m;
2414
+ for (const k of MOOD_NAMES) moodTargetWeights[k] = (k === m) ? 1 : 0;
2415
+ document.querySelectorAll('[data-mood]').forEach(b => b.classList.remove('on'));
2416
+ btn.classList.add('on');
2417
+ });
2418
+ });
2419
+
2420
+ /* views */
2421
+ const VIEWS = {
2422
+ front: { alpha: -Math.PI/2, beta: Math.PI/2, radius: 4.4 },
2423
+ 'three-q':{ alpha: -Math.PI/2 - 0.6, beta: Math.PI/2 - 0.15, radius: 4.0 },
2424
+ profile: { alpha: 0, beta: Math.PI/2, radius: 4.6 },
2425
+ orbit: null,
2426
+ };
2427
+ let orbiting = false;
2428
+ document.querySelectorAll('[data-view]').forEach(btn => {
2429
+ btn.addEventListener('click', () => {
2430
+ const v = VIEWS[btn.dataset.view];
2431
+ if (v) {
2432
+ orbiting = false;
2433
+ animateCamera(v.alpha, v.beta, v.radius);
2434
+ } else {
2435
+ orbiting = true;
2436
+ }
2437
+ });
2438
+ });
2439
+
2440
+ function animateCamera(targetAlpha, targetBeta, targetRadius, durMs = 800) {
2441
+ const startAlpha = camera.alpha, startBeta = camera.beta, startRadius = camera.radius;
2442
+ const t0 = performance.now();
2443
+ function step() {
2444
+ const t = Math.min(1, (performance.now() - t0) / durMs);
2445
+ const e = t < 0.5 ? 2*t*t : 1 - Math.pow(-2*t + 2, 2) / 2; // easeInOutQuad
2446
+ camera.alpha = startAlpha + (targetAlpha - startAlpha) * e;
2447
+ camera.beta = startBeta + (targetBeta - startBeta) * e;
2448
+ camera.radius = startRadius + (targetRadius - startRadius) * e;
2449
+ if (t < 1) requestAnimationFrame(step);
2450
+ }
2451
+ step();
2452
+ }
2453
+
2454
+ /* ─── render config panel ───────────────────────────────────────────── */
2455
+ function setRcfgVal(key, val) {
2456
+ const def = document.querySelector(`[data-rcfg="${key}"]`);
2457
+ if (!def) return;
2458
+ const min = parseFloat(def.dataset.min);
2459
+ const max = parseFloat(def.dataset.max);
2460
+ const step = parseFloat(def.dataset.step) || 0.01;
2461
+ let v = Math.max(min, Math.min(max, val));
2462
+ v = Math.round(v / step) * step;
2463
+ // for integer-step (cols/rows), keep odd if step is 2
2464
+ if (step === 2) v = Math.round(v); if (v % 2 === 0 && step === 2) v += 1;
2465
+ renderConfig[key] = v;
2466
+ // update fill bar
2467
+ const fill = def.querySelector('.fill');
2468
+ fill.style.width = ((v - min) / (max - min) * 100) + '%';
2469
+ // update value label
2470
+ const lbl = document.querySelector(`[data-rcfg-val="${key}"]`);
2471
+ if (lbl) lbl.textContent = (step >= 1) ? String(Math.round(v)) : v.toFixed(2);
2472
+ // side-effects
2473
+ if (key === 'meshCols' || key === 'meshRows' || key === 'eyeDepth' || key === 'mouthHoleSize') rebuildMesh();
2474
+ if (key === 'lineThickness') {
2475
+ rebuildMinimalLines();
2476
+ // edges renderer width is mutable; just nudge it without dispose/recreate
2477
+ if (mesh && mesh._edgesRenderer) mesh.edgesWidth = 4 * renderConfig.lineThickness;
2478
+ }
2479
+ // re-baseline anchor rings when lip-shape params change so the
2480
+ // (target - baseline) delta the anchor uses stays consistent with the
2481
+ // user's intent.
2482
+ if (key === 'lipVertAmp' || key === 'lipPressForce') {
2483
+ if (typeof identifyAnchorRings === 'function') identifyAnchorRings();
2484
+ }
2485
+ // v011: iris size requires recreating the iris discs at the new radius
2486
+ if (key === 'irisSize') {
2487
+ if (typeof rebuildPupils === 'function') rebuildPupils();
2488
+ }
2489
+ // v011: when depth fade returns to ~0, force one repaint to flat base color
2490
+ if (key === 'depthFade' && renderConfig.depthFade < 0.001) {
2491
+ _dirtyBaseColor = true;
2492
+ }
2493
+ }
2494
+
2495
+ /* color pickers — line + pupil + v011: base / fade / iris / brow */
2496
+ function applyLineColor(hex) {
2497
+ renderConfig.lineColor = hex;
2498
+ if (typeof minimalMat !== 'undefined' && minimalMat) {
2499
+ minimalMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
2500
+ }
2501
+ const lbl = document.getElementById('color-line-val');
2502
+ if (lbl) lbl.textContent = hex.replace('#', '').toUpperCase().slice(0, 3);
2503
+ }
2504
+ function applyPupilColor(hex) {
2505
+ renderConfig.pupilColor = hex;
2506
+ if (typeof pupilMat !== 'undefined' && pupilMat) {
2507
+ pupilMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
2508
+ }
2509
+ const lbl = document.getElementById('color-pupil-val');
2510
+ if (lbl) lbl.textContent = hex.replace('#', '').toUpperCase().slice(0, 3);
2511
+ }
2512
+ function applyBaseColor(hex) {
2513
+ renderConfig.baseColor = hex;
2514
+ _baseRGB = hex2rgb(hex);
2515
+ _dirtyBaseColor = true;
2516
+ // sync emissive on materials so vertex-color * emissive doesn't darken
2517
+ // unexpectedly when the picker is at non-white. With useVertexColor on,
2518
+ // shaded modes multiply; we want the picker to be the dominant signal.
2519
+ if (wireMat) wireMat.emissiveColor = new BABYLON.Color3(_baseRGB[0], _baseRGB[1], _baseRGB[2]);
2520
+ if (mesh && mesh._edgesRenderer) mesh.edgesColor = new BABYLON.Color4(_baseRGB[0], _baseRGB[1], _baseRGB[2], 1);
2521
+ const lbl = document.getElementById('color-base-val');
2522
+ if (lbl) lbl.textContent = hex.replace('#', '').toUpperCase().slice(0, 3);
2523
+ }
2524
+ function applyFadeColor(hex) {
2525
+ renderConfig.fadeColor = hex;
2526
+ _fadeRGB = hex2rgb(hex);
2527
+ _dirtyBaseColor = true;
2528
+ const lbl = document.getElementById('color-fade-val');
2529
+ if (lbl) lbl.textContent = hex.replace('#', '').toUpperCase().slice(0, 3);
2530
+ }
2531
+ function applyIrisColor(hex) {
2532
+ renderConfig.irisColor = hex;
2533
+ if (typeof irisMat !== 'undefined' && irisMat) {
2534
+ irisMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
2535
+ }
2536
+ const lbl = document.getElementById('color-iris-val');
2537
+ if (lbl) lbl.textContent = hex.replace('#', '').toUpperCase().slice(0, 3);
2538
+ }
2539
+ function applyBrowColor(hex) {
2540
+ renderConfig.browColor = hex;
2541
+ if (typeof browMat !== 'undefined' && browMat) {
2542
+ browMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
2543
+ }
2544
+ const lbl = document.getElementById('color-brow-val');
2545
+ if (lbl) lbl.textContent = hex.replace('#', '').toUpperCase().slice(0, 3);
2546
+ }
2547
+ {
2548
+ const wires = [
2549
+ ['color-line', 'lineColor', applyLineColor],
2550
+ ['color-pupil', 'pupilColor', applyPupilColor],
2551
+ ['color-base', 'baseColor', applyBaseColor],
2552
+ ['color-fade', 'fadeColor', applyFadeColor],
2553
+ ['color-iris', 'irisColor', applyIrisColor],
2554
+ ['color-brow', 'browColor', applyBrowColor],
2555
+ ];
2556
+ for (const [id, key, fn] of wires) {
2557
+ const el = document.getElementById(id);
2558
+ if (!el) continue;
2559
+ el.value = renderConfig[key];
2560
+ el.addEventListener('input', () => fn(el.value));
2561
+ fn(el.value);
2562
+ }
2563
+ }
2564
+
2565
+ document.querySelectorAll('[data-rcfg]').forEach(bar => {
2566
+ const key = bar.dataset.rcfg;
2567
+ // initialize bar fill from current renderConfig value
2568
+ setRcfgVal(key, renderConfig[key]);
2569
+
2570
+ let dragging = false;
2571
+ function setFromX(clientX) {
2572
+ const r = bar.getBoundingClientRect();
2573
+ const t = Math.max(0, Math.min(1, (clientX - r.left) / r.width));
2574
+ const min = parseFloat(bar.dataset.min);
2575
+ const max = parseFloat(bar.dataset.max);
2576
+ setRcfgVal(key, min + (max - min) * t);
2577
+ }
2578
+ bar.addEventListener('pointerdown', e => { dragging = true; bar.setPointerCapture(e.pointerId); setFromX(e.clientX); });
2579
+ bar.addEventListener('pointermove', e => { if (dragging) setFromX(e.clientX); });
2580
+ bar.addEventListener('pointerup', e => { dragging = false; });
2581
+ });
2582
+
2583
+ document.querySelectorAll('[data-mode]').forEach(btn => {
2584
+ btn.addEventListener('click', () => {
2585
+ document.querySelectorAll('[data-mode]').forEach(b => b.classList.remove('on'));
2586
+ btn.classList.add('on');
2587
+ renderConfig.mode = btn.dataset.mode;
2588
+ applyRenderMode();
2589
+ });
2590
+ });
2591
+
2592
+ document.querySelectorAll('[data-toggle]').forEach(t => {
2593
+ const key = t.dataset.toggle;
2594
+ // sync initial visual state from renderConfig
2595
+ if (renderConfig[key]) t.classList.add('on'); else t.classList.remove('on');
2596
+
2597
+ t.addEventListener('click', () => {
2598
+ renderConfig[key] = !renderConfig[key];
2599
+ t.classList.toggle('on', renderConfig[key]);
2600
+ switch (key) {
2601
+ case 'pupils': rebuildPupils(); break;
2602
+ case 'glow': glow.intensity = renderConfig.glow ? 0.85 : 0; break;
2603
+ case 'fragment': rebuildMesh(); break;
2604
+ case 'mouthHole': rebuildMesh(); break;
2605
+ case 'eyeHoles': rebuildMesh(); break;
2606
+ case 'flipFace': applyFaceFlip(); break;
2607
+ case 'meshVisible': applyMeshVisibility(); break;
2608
+ case 'minimal': applyMinimalVisibility(); break;
2609
+ case 'mouthAnchor': /* takes effect next frame */ break;
2610
+ case 'eyeAnchor': /* takes effect next frame */ break;
2611
+ case 'overlayTracksMesh': /* takes effect next frame */ break;
2612
+ case 'loopAudio':
2613
+ if (audioSource) audioSource.loop = !!renderConfig.loopAudio;
2614
+ break;
2615
+ }
2616
+ });
2617
+ });
2618
+
2619
+ /* file inputs */
2620
+ document.getElementById('audio-file').addEventListener('change', async e => {
2621
+ const f = e.target.files[0];
2622
+ if (!f) return;
2623
+ await loadAudioFile(f);
2624
+ });
2625
+
2626
+ document.getElementById('json-file').addEventListener('change', async e => {
2627
+ const f = e.target.files[0];
2628
+ if (!f) return;
2629
+ await importTrack(f);
2630
+ });
2631
+
2632
+ /* ─── 9b. PRESET SYSTEM ────────────────────────────────────────────────────
2633
+ localStorage-backed snapshots of the entire renderer state. Each preset
2634
+ captures: renderConfig, channelGains, current mood, audio filename hint,
2635
+ line/pupil colors. Audio files themselves cannot be persisted across
2636
+ sessions (browser security blocks programmatic file access), but the
2637
+ filename is remembered so the user can re-load the matching audio. */
2638
+
2639
+ const PRESET_INDEX_KEY = 'wireface_preset_index';
2640
+ const PRESET_KEY = id => 'wireface_preset_' + id;
2641
+
2642
+ function shortGuid() {
2643
+ // 6-char base36 — collision-resistant enough for personal use
2644
+ return Math.floor(Math.random() * 0x7fffffff).toString(36).slice(0, 6);
2645
+ }
2646
+
2647
+ function readPresetIndex() {
2648
+ try { return JSON.parse(localStorage.getItem(PRESET_INDEX_KEY) || '[]'); }
2649
+ catch (_) { return []; }
2650
+ }
2651
+ function writePresetIndex(arr) {
2652
+ localStorage.setItem(PRESET_INDEX_KEY, JSON.stringify(arr));
2653
+ }
2654
+
2655
+ function snapshotPreset() {
2656
+ return {
2657
+ version: 'wireface-v010',
2658
+ createdAt: new Date().toISOString(),
2659
+ renderConfig: { ...renderConfig },
2660
+ channelGains: { ...channelGains },
2661
+ channelGainSliders: { ...channelGainSliders },
2662
+ activeMood,
2663
+ moodTargetWeights: { ...moodTargetWeights },
2664
+ audioName,
2665
+ lineColor: renderConfig.lineColor,
2666
+ pupilColor: renderConfig.pupilColor,
2667
+ };
2668
+ }
2669
+
2670
+ function applyPreset(p) {
2671
+ if (!p || !p.renderConfig) return;
2672
+ // Apply renderConfig values via setRcfgVal so UI bars update + side-effects fire.
2673
+ for (const k of Object.keys(p.renderConfig)) {
2674
+ if (typeof renderConfig[k] === 'undefined') { renderConfig[k] = p.renderConfig[k]; continue; }
2675
+ if (typeof p.renderConfig[k] === 'number') {
2676
+ const slider = document.querySelector(`[data-rcfg="${k}"]`);
2677
+ if (slider) setRcfgVal(k, p.renderConfig[k]);
2678
+ else renderConfig[k] = p.renderConfig[k];
2679
+ } else {
2680
+ renderConfig[k] = p.renderConfig[k];
2681
+ }
2682
+ }
2683
+ // toggles
2684
+ document.querySelectorAll('[data-toggle]').forEach(t => {
2685
+ const k = t.dataset.toggle;
2686
+ if (renderConfig[k]) t.classList.add('on'); else t.classList.remove('on');
2687
+ });
2688
+ // render mode
2689
+ document.querySelectorAll('[data-mode]').forEach(b => b.classList.toggle('on', b.dataset.mode === renderConfig.mode));
2690
+ applyRenderMode();
2691
+ applyMeshVisibility(); applyMinimalVisibility();
2692
+ // colors
2693
+ if (p.lineColor) {
2694
+ const lc = document.getElementById('color-line'); if (lc) lc.value = p.lineColor;
2695
+ applyLineColor(p.lineColor);
2696
+ }
2697
+ if (p.pupilColor) {
2698
+ const pc = document.getElementById('color-pupil'); if (pc) pc.value = p.pupilColor;
2699
+ applyPupilColor(p.pupilColor);
2700
+ }
2701
+ // v011 colors
2702
+ if (p.renderConfig && p.renderConfig.baseColor) {
2703
+ const el = document.getElementById('color-base'); if (el) el.value = p.renderConfig.baseColor;
2704
+ applyBaseColor(p.renderConfig.baseColor);
2705
+ }
2706
+ if (p.renderConfig && p.renderConfig.fadeColor) {
2707
+ const el = document.getElementById('color-fade'); if (el) el.value = p.renderConfig.fadeColor;
2708
+ applyFadeColor(p.renderConfig.fadeColor);
2709
+ }
2710
+ if (p.renderConfig && p.renderConfig.irisColor) {
2711
+ const el = document.getElementById('color-iris'); if (el) el.value = p.renderConfig.irisColor;
2712
+ applyIrisColor(p.renderConfig.irisColor);
2713
+ }
2714
+ if (p.renderConfig && p.renderConfig.browColor) {
2715
+ const el = document.getElementById('color-brow'); if (el) el.value = p.renderConfig.browColor;
2716
+ applyBrowColor(p.renderConfig.browColor);
2717
+ }
2718
+ // channel gains (knobs)
2719
+ if (p.channelGainSliders) {
2720
+ for (const ch of CHANNEL_NAMES) {
2721
+ const k = p.channelGainSliders[ch] || 0;
2722
+ if (chanRefs[ch] && chanRefs[ch].applyKnob) chanRefs[ch].applyKnob(ch, k);
2723
+ }
2724
+ }
2725
+ // mood
2726
+ if (p.activeMood && MOODS[p.activeMood]) {
2727
+ activeMood = p.activeMood;
2728
+ for (const k of MOOD_NAMES) moodTargetWeights[k] = (k === activeMood) ? 1 : 0;
2729
+ document.querySelectorAll('[data-mood]').forEach(b => b.classList.toggle('on', b.dataset.mood === activeMood));
2730
+ }
2731
+ // audio name hint
2732
+ if (p.audioName && p.audioName !== audioName) {
2733
+ const t = document.getElementById('audio-name');
2734
+ if (t) t.textContent = p.audioName + ' (re-load to play)';
2735
+ }
2736
+ }
2737
+
2738
+ function refreshPresetList() {
2739
+ const list = document.getElementById('preset-list');
2740
+ if (!list) return;
2741
+ const idx = readPresetIndex();
2742
+ list.innerHTML = '';
2743
+ document.getElementById('btn-preset-export-all').disabled = idx.length === 0;
2744
+ for (const entry of idx) {
2745
+ const item = document.createElement('div');
2746
+ item.className = 'preset-item';
2747
+ item.title = 'click row to load · ↓ download · × delete';
2748
+ const name = document.createElement('div');
2749
+ name.className = 'pname';
2750
+ name.textContent = entry.name;
2751
+ const dl = document.createElement('div');
2752
+ dl.className = 'picon'; dl.textContent = '↓'; dl.title = 'download';
2753
+ const del = document.createElement('div');
2754
+ del.className = 'picon del'; del.textContent = '×'; del.title = 'delete';
2755
+ item.appendChild(name); item.appendChild(dl); item.appendChild(del);
2756
+ list.appendChild(item);
2757
+
2758
+ name.addEventListener('click', () => {
2759
+ const raw = localStorage.getItem(PRESET_KEY(entry.id));
2760
+ if (!raw) return;
2761
+ try { applyPreset(JSON.parse(raw)); } catch (e) { console.warn('preset load failed', e); }
2762
+ });
2763
+ dl.addEventListener('click', e => {
2764
+ e.stopPropagation();
2765
+ const raw = localStorage.getItem(PRESET_KEY(entry.id));
2766
+ if (!raw) return;
2767
+ const blob = new Blob([raw], { type: 'application/json' });
2768
+ const url = URL.createObjectURL(blob);
2769
+ const a = document.createElement('a');
2770
+ a.href = url; a.download = `wireface_${entry.name}.json`;
2771
+ a.click();
2772
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
2773
+ });
2774
+ del.addEventListener('click', e => {
2775
+ e.stopPropagation();
2776
+ localStorage.removeItem(PRESET_KEY(entry.id));
2777
+ writePresetIndex(idx.filter(x => x.id !== entry.id));
2778
+ refreshPresetList();
2779
+ });
2780
+ }
2781
+ }
2782
+
2783
+ document.getElementById('btn-preset-save').addEventListener('click', () => {
2784
+ const id = shortGuid();
2785
+ const name = (audioName && audioName !== 'test-tone' ? audioName.split('.')[0].slice(0, 12) : 'preset') + '_' + id;
2786
+ const snap = snapshotPreset();
2787
+ snap.id = id; snap.name = name;
2788
+ localStorage.setItem(PRESET_KEY(id), JSON.stringify(snap));
2789
+ const idx = readPresetIndex();
2790
+ idx.unshift({ id, name, createdAt: snap.createdAt });
2791
+ writePresetIndex(idx);
2792
+ refreshPresetList();
2793
+ });
2794
+
2795
+ document.getElementById('btn-preset-export-all').addEventListener('click', () => {
2796
+ const idx = readPresetIndex();
2797
+ const all = idx.map(e => {
2798
+ try { return JSON.parse(localStorage.getItem(PRESET_KEY(e.id))); }
2799
+ catch (_) { return null; }
2800
+ }).filter(Boolean);
2801
+ const blob = new Blob([JSON.stringify(all, null, 2)], { type: 'application/json' });
2802
+ const url = URL.createObjectURL(blob);
2803
+ const a = document.createElement('a');
2804
+ a.href = url; a.download = `wireface_presets_${Date.now()}.json`;
2805
+ a.click();
2806
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
2807
+ });
2808
+
2809
+ document.getElementById('preset-file').addEventListener('change', async e => {
2810
+ const f = e.target.files[0];
2811
+ if (!f) return;
2812
+ try {
2813
+ const text = await f.text();
2814
+ const data = JSON.parse(text);
2815
+ const arr = Array.isArray(data) ? data : [data];
2816
+ const idx = readPresetIndex();
2817
+ for (const p of arr) {
2818
+ const id = shortGuid();
2819
+ const name = (p.name || 'imported') + '_' + id;
2820
+ p.id = id; p.name = name;
2821
+ localStorage.setItem(PRESET_KEY(id), JSON.stringify(p));
2822
+ idx.unshift({ id, name, createdAt: p.createdAt || new Date().toISOString() });
2823
+ }
2824
+ writePresetIndex(idx);
2825
+ refreshPresetList();
2826
+ } catch (err) {
2827
+ console.warn('preset import failed', err);
2828
+ }
2829
+ e.target.value = '';
2830
+ });
2831
+
2832
+ refreshPresetList();
2833
+
2834
+ /* transport */
2835
+ document.getElementById('btn-play').addEventListener('click', () => {
2836
+ const playBtn = document.getElementById('btn-play');
2837
+ const isCurrentlyPlaying = isPlaying || trackPlaying;
2838
+
2839
+ if (isCurrentlyPlaying) {
2840
+ // pause everything
2841
+ if (isPlaying) { pausedAt = getPlaybackTime(); stopPlayback(); }
2842
+ if (trackPlaying) trackPlaying = false;
2843
+ playBtn.textContent = '▶ play';
2844
+ return;
2845
+ }
2846
+
2847
+ // start
2848
+ const hasRealAudio = audioName !== 'test-tone';
2849
+ if (hasRealAudio) {
2850
+ startPlayback(pausedAt || 0);
2851
+ if (importedTrack) playTrack();
2852
+ } else if (importedTrack) {
2853
+ playTrack(); // silent track playback
2854
+ } else {
2855
+ startPlayback(0); // play the test tone so something demos
2856
+ }
2857
+ playBtn.textContent = '⏸ pause';
2858
+ });
2859
+
2860
+ document.getElementById('btn-stop').addEventListener('click', () => {
2861
+ stopPlayback();
2862
+ trackPlaying = false;
2863
+ pausedAt = 0;
2864
+ });
2865
+
2866
+ /* timeline scrub */
2867
+ const timeline = document.getElementById('timeline');
2868
+ timeline.addEventListener('click', e => {
2869
+ const r = timeline.getBoundingClientRect();
2870
+ const t = (e.clientX - r.left) / r.width;
2871
+ const dur = audioDuration || (importedTrack ? importedTrack.duration_ms / 1000 : 0);
2872
+ if (dur === 0) return;
2873
+ pausedAt = t * dur;
2874
+ if (isPlaying) {
2875
+ stopPlayback();
2876
+ startPlayback(pausedAt);
2877
+ document.getElementById('btn-play').textContent = '⏸ pause';
2878
+ }
2879
+ });
2880
+
2881
+ /* recording */
2882
+ document.getElementById('btn-record').addEventListener('click', () => {
2883
+ if (recording) stopRecording(); else startRecording();
2884
+ });
2885
+ document.getElementById('btn-export').addEventListener('click', exportTrack);
2886
+ document.getElementById('btn-clear').addEventListener('click', () => {
2887
+ captureBuffer = [];
2888
+ importedTrack = null;
2889
+ document.getElementById('track-info').textContent = 'no track recorded';
2890
+ document.getElementById('btn-export').disabled = true;
2891
+ });
2892
+
2893
+ /* status helpers */
2894
+ function setStatus(cls, text) {
2895
+ const s = document.getElementById('status');
2896
+ s.classList.remove('live', 'rec', 'idle');
2897
+ s.classList.add(cls);
2898
+ document.getElementById('status-text').textContent = text;
2899
+ }
2900
+
2901
+ function formatTime(ms) {
2902
+ const s = Math.floor(ms / 1000);
2903
+ const cs = Math.floor((ms % 1000) / 10);
2904
+ const mm = Math.floor(s / 60);
2905
+ const ss = s % 60;
2906
+ return String(mm).padStart(2, '0') + ':' + String(ss).padStart(2, '0') + '.' + String(cs).padStart(2, '0');
2907
+ }
2908
+
2909
+ /* ─── 10. RENDER LOOP ──────────────────────────────────────────────────── */
2910
+
2911
+ let lastT = performance.now();
2912
+ let frameNum = 0;
2913
+ let fpsAcc = 0, fpsCount = 0, fpsLast = lastT;
2914
+ let renderErrors = 0;
2915
+
2916
+ engine.runRenderLoop(() => {
2917
+ try {
2918
+ const now = performance.now();
2919
+ const dt = Math.min(0.05, (now - lastT) / 1000);
2920
+ lastT = now;
2921
+
2922
+ /* idle micro-animations */
2923
+ idleAnimate(dt);
2924
+
2925
+ /* live audio analysis */
2926
+ if (isPlaying) analyzeAudioFrame();
2927
+
2928
+ /* track playback driving */
2929
+ if (trackPlaying && importedTrack) {
2930
+ const t = now - trackPlayStart;
2931
+ if (t > importedTrack.duration_ms) {
2932
+ trackPlaying = false;
2933
+ setStatus('idle', 'idle');
2934
+ } else {
2935
+ evalTrack(t);
2936
+ }
2937
+ }
2938
+
2939
+ /* mood blend → channel targets (smooth crossfade between mood weights) */
2940
+ updateMoodBlend(dt);
2941
+
2942
+ /* smooth toward targets */
2943
+ smoothChannels(dt);
2944
+
2945
+ /* drive geometry */
2946
+ updateFace();
2947
+
2948
+ /* orbit mode */
2949
+ if (orbiting) camera.alpha += dt * 0.3;
2950
+
2951
+ /* recording */
2952
+ captureFrame();
2953
+
2954
+ /* render */
2955
+ scene.render();
2956
+
2957
+ /* UI updates — throttled */
2958
+ frameNum++;
2959
+ if (frameNum % 2 === 0) updateChannelUI();
2960
+ if (frameNum % 8 === 0) updateTransportUI();
2961
+
2962
+ /* fps */
2963
+ fpsCount++;
2964
+ if (now - fpsLast > 500) {
2965
+ const fps = Math.round((fpsCount * 1000) / (now - fpsLast));
2966
+ document.getElementById('coord-fps').textContent = fps;
2967
+ fpsCount = 0;
2968
+ fpsLast = now;
2969
+ }
2970
+ document.getElementById('coord-frame').textContent = String(frameNum).padStart(4, '0');
2971
+ } catch (err) {
2972
+ renderErrors++;
2973
+ if (renderErrors < 5 || renderErrors % 60 === 0) {
2974
+ console.error('[wireface] render frame error #' + renderErrors + ':', err);
2975
+ }
2976
+ }
2977
+ });
2978
+
2979
+ function updateChannelUI() {
2980
+ let active = 0;
2981
+ for (const ch of CHANNEL_NAMES) {
2982
+ const v = state[ch];
2983
+ const range = CHANNELS[ch].range;
2984
+ const t = (v - range[0]) / (range[1] - range[0]);
2985
+ const r = chanRefs[ch];
2986
+ if (!r) continue;
2987
+ r.fill.style.width = (t * 100).toFixed(1) + '%';
2988
+ r.val.textContent = v.toFixed(2);
2989
+ const isActive = Math.abs(v - CHANNELS[ch].def) > 0.05;
2990
+ r.bar.classList.toggle('active', isActive);
2991
+ if (isActive) active++;
2992
+ }
2993
+ document.getElementById('coord-active').textContent = String(active).padStart(2, '0');
2994
+ }
2995
+
2996
+ function updateTransportUI() {
2997
+ const dur = audioDuration || (importedTrack ? importedTrack.duration_ms / 1000 : 0);
2998
+ let cur = 0;
2999
+ if (isPlaying) cur = getPlaybackTime();
3000
+ else if (trackPlaying) cur = (performance.now() - trackPlayStart) / 1000;
3001
+ else cur = pausedAt;
3002
+ document.getElementById('t-cur').textContent = formatTime(cur * 1000);
3003
+ if (dur > 0) {
3004
+ const pct = Math.min(100, (cur / dur) * 100);
3005
+ document.getElementById('progress').style.width = pct + '%';
3006
+ document.getElementById('playhead').style.left = pct + '%';
3007
+ }
3008
+ }
3009
+
3010
+ window.addEventListener('resize', () => engine.resize());
3011
+
3012
+ /* boot */
3013
+ buildTestTone(); // make sure transport has *something* to play
3014
+ setStatus('idle', 'idle · drag a face channel to lock');
3015
+
3016
+ /* expose for debugging */
3017
+ window.WIREFACE = { state, stateTarget, CHANNELS, VISEME_PARAMS, captureBuffer, scene, camera };
3018
+
3019
+ } // end bootWireface
3020
+ </script>
3021
+
3022
+ </body>
3023
+ </html>