@rig-c/parts 1.33.0 → 1.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/turn.ts CHANGED
@@ -109,8 +109,6 @@ export const FACE_DEFORM_FRACTIONS = {
109
109
  tilt_topknot_y: 0.5,
110
110
  /** Forehead bang forward parallax per degree of yaw (`W/deg`; `-3.50 px` at `+15°` on `W = 106`). */
111
111
  turn_bang_parallax_x: -(3.5 / 15) / 106,
112
- /** Share of the cheek yaw horizontal field carried by lower `hair_back` (`0.90×` of `dxCheek`). */
113
- turn_hair_back_cheek_x: 0.9,
114
112
  /** Rear bun counter-parallax per degree of yaw (`W/deg`; `+8.00 px` at `+15°` on `W = 106`). */
115
113
  turn_bun_counter_x: 8.0 / 15 / 106,
116
114
  /** Rear hairpin counter-parallax per degree of yaw (`W/deg`; `+6.00 px` at `+15°` on `W = 106`). */
@@ -144,7 +142,6 @@ export const FACE_DEFORM_RANGES: Readonly<Record<FaceDeformKey, readonly [number
144
142
  tilt_ear_y: [0, 1.5],
145
143
  tilt_topknot_y: [0, 1.5],
146
144
  turn_bang_parallax_x: [-0.015, 0],
147
- turn_hair_back_cheek_x: [0, 1.5],
148
145
  turn_bun_counter_x: [0, 0.02],
149
146
  turn_hairpin_counter_x: [0, 0.02],
150
147
  turn_ear_x: [0, 1.5],
@@ -184,14 +181,75 @@ export const FACE_RATED_BAND = { yaw: FACE_RATED_YAW_BAND, pitch: FACE_RATED_PIT
184
181
  */
185
182
  export const EAR_DEPTH_RANGE: readonly [number, number] = [-50, 0];
186
183
 
187
- /** `config.turn`: the pivot depth, each carried part's See-through `depth_median`, optional rated band, and optional face surface deform overrides. */
184
+ /** Default part names belonging to the `head` subtree when computing the head-only turn pivot (issue #478). */
185
+ export const DEFAULT_HEAD_TURN_PARTS: readonly string[] = [
186
+ 'face',
187
+ 'nose',
188
+ 'mouth',
189
+ 'eyewhite_r',
190
+ 'eyewhite_l',
191
+ 'iris_r',
192
+ 'iris_l',
193
+ 'irides_r',
194
+ 'irides_l',
195
+ 'lash_r',
196
+ 'lash_l',
197
+ 'eyelash_r',
198
+ 'eyelash_l',
199
+ 'brow_r',
200
+ 'brow_l',
201
+ 'eyebrow_r',
202
+ 'eyebrow_l',
203
+ 'ear_r',
204
+ 'ear_l',
205
+ 'ears',
206
+ 'hair_front',
207
+ 'hair_back',
208
+ 'hairpin',
209
+ 'headwear',
210
+ 'bun',
211
+ 'topknot',
212
+ ];
213
+
214
+ /** `config.turn`: the pivot depth, each carried part's See-through `depth_median`, optional head-only pivot override, optional curved-surface cylinder radius, optional rated band, and optional face surface deform overrides. */
188
215
  export interface TurnSpec {
189
216
  pivot: number;
190
217
  depths: Record<string, number>;
218
+ head?: { pivot?: number; radius?: number };
219
+ surface?: { radius?: number };
220
+ radius?: number;
191
221
  band?: number | { yaw?: number; pitch?: number };
192
222
  deform?: Partial<FaceDeformFractions>;
193
223
  }
194
224
 
225
+ /**
226
+ * Issue #479: the cylinder radius `R` (in rig px) for the curved-surface face
227
+ * yaw projection — `spec.surface.radius`, `spec.radius`, or `spec.head.radius`
228
+ * when declared, defaulting to half the face plate's opaque width (`W / 2`).
229
+ */
230
+ export function turnSurfaceRadius(spec: TurnSpec | null | undefined, W: number): number {
231
+ const r = spec?.surface?.radius ?? spec?.radius ?? spec?.head?.radius;
232
+ return typeof r === 'number' && Number.isFinite(r) && r > 0 ? r : W / 2;
233
+ }
234
+
235
+ /**
236
+ * Issue #479: horizontal displacement `Δx` of a point at rest offset `x`
237
+ * (`hx - X0`) on a vertical cylinder of radius `radius` turned by `deg`
238
+ * degrees of yaw (`θ = deg · π / 180`), with the rotated surface angle clamped
239
+ * to the visible limb `[-π/2, π/2]`. At the leading limb (`u = -sign(deg)`),
240
+ * `Δx = 0` so the leading outline holds fixed; across the interior (`|u| < 1`),
241
+ * points slide toward the leading side (`-radius · sin θ` at `x = 0`), widening
242
+ * the trailing cheek and foreshortening the leading cheek.
243
+ */
244
+ export function cylinderYawDx(x: number, deg: number, radius: number): number {
245
+ if (deg === 0 || !(radius > 0)) return 0;
246
+ const theta = (deg * Math.PI) / 180;
247
+ const u = Math.max(-1, Math.min(1, x / radius));
248
+ const phi0 = Math.asin(u);
249
+ const phi1 = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, phi0 - theta));
250
+ return radius * (Math.sin(phi1) - u);
251
+ }
252
+
195
253
  /** One carried part: its depth and the fraction of the control's offset it travels. */
196
254
  export interface TurnFraction {
197
255
  part: string;
@@ -238,6 +296,48 @@ export function turnPivot(rows: ReadonlyArray<{ depth: number; area: number }>):
238
296
  return a > 0 ? pyRound(ad / a, TURN_PLACES) : null;
239
297
  }
240
298
 
299
+ /**
300
+ * Issue #478: the head-only turn pivot — either `spec.head.pivot` when
301
+ * declared, or the `opaque_px`-weighted mean of `spec.depths` restricted to the
302
+ * `head` subtree parts (`headParts`). Neck and torso parts are excluded so a
303
+ * front-heavy body does not pull the head's rotation axis forward of the skull.
304
+ */
305
+ export function headTurnPivot(
306
+ spec: TurnSpec,
307
+ headParts: ReadonlySet<string> = new Set(DEFAULT_HEAD_TURN_PARTS),
308
+ partAreas?: Readonly<Record<string, number>>,
309
+ ): number | null {
310
+ if (typeof spec.head?.pivot === 'number' && Number.isFinite(spec.head.pivot)) {
311
+ return pyRound(spec.head.pivot, TURN_PLACES);
312
+ }
313
+ const headEntries = Object.entries(spec.depths).filter(([part, d]) => headParts.has(part) && typeof d === 'number' && Number.isFinite(d));
314
+ const entries = headEntries.length > 0 ? headEntries : Object.entries(spec.depths).filter(([, d]) => typeof d === 'number' && Number.isFinite(d));
315
+ return turnPivot(entries.map(([part, depth]) => ({ depth, area: partAreas?.[part] ?? 1 })));
316
+ }
317
+
318
+ /**
319
+ * Issue #478: a head-mounted part's turn fraction `(headPivot − depth) / (headPivot − headNearest)`
320
+ * about the head-only pivot. Parts behind `headPivot` (`hair_back`, rear `hairpin`)
321
+ * receive a negative fraction and move opposite to the face and irises.
322
+ */
323
+ export function headTurnFraction(
324
+ spec: TurnSpec,
325
+ part: string,
326
+ headParts: ReadonlySet<string> = new Set(DEFAULT_HEAD_TURN_PARTS),
327
+ partAreas?: Readonly<Record<string, number>>,
328
+ ): number | null {
329
+ const depth = spec.depths[part];
330
+ if (typeof depth !== 'number' || !Number.isFinite(depth)) return null;
331
+ const pivot = headTurnPivot(spec, headParts, partAreas);
332
+ const headDepths: Record<string, number> = {};
333
+ for (const [p, d] of Object.entries(spec.depths)) {
334
+ if (headParts.has(p) && typeof d === 'number' && Number.isFinite(d)) headDepths[p] = d;
335
+ }
336
+ const nearest = turnNearest(Object.keys(headDepths).length > 0 ? headDepths : spec.depths);
337
+ if (pivot === null || nearest === null || !(pivot > nearest.depth)) return null;
338
+ return turnFraction(pivot, nearest.depth, depth);
339
+ }
340
+
241
341
  /** The leaf bone that carries `part`'s share of `bone` under the turn: an identity child of `bone`, so it follows everything `bone` does. */
242
342
  export function turnTwin(part: string, bone: string): string {
243
343
  return `${TURN_BONE}_${part}_${bone}`;
@@ -277,7 +377,10 @@ export function evalPitchFaceSurface(
277
377
 
278
378
  /**
279
379
  * Evaluate the yaw (`turn`) surface deformation field `(dx, dy)` in `head`
280
- * space at `(hx, hy)` for `deg` degrees of yaw.
380
+ * space at `(hx, hy)` for `deg` degrees of yaw (issue #479: cylinder projection
381
+ * of radius `radius`, default `W / 2`, with lower-face jaw taper so the leading
382
+ * jaw edge holds and the trailing cheek widens; `flatYawTable: true` restores
383
+ * the flat yaw table for the Bar 4 negative control or explicit fraction overrides).
281
384
  */
282
385
  export function evalYawFaceSurface(
283
386
  hx: number,
@@ -288,16 +391,28 @@ export function evalYawFaceSurface(
288
391
  X0: number,
289
392
  Y0: number,
290
393
  f: Readonly<FaceDeformFractions> = FACE_DEFORM_FRACTIONS,
394
+ radius?: number,
395
+ flatYawTable = false,
291
396
  ): [number, number] {
292
397
  if (deg === 0) return [0, 0];
293
398
  const s = Math.sign(deg);
294
399
  const ux = Math.max(-1.35, Math.min(1.35, (hx - X0) / (W / 2)));
295
400
  const uy = Math.max(-1.35, Math.min(1.35, (hy - Y0) / (H / 2)));
296
- const uLead = Math.min(1.2, Math.max(0, -s * ux));
297
- const uTrail = Math.min(1.2, Math.max(0, s * ux));
298
- const fracXPerDeg = unmult(f.turn_mid_x) + unmult(f.turn_lead_compress_x) * Math.pow(uLead, 1.2) + unmult(f.turn_trail_shift_x) * Math.pow(uTrail, 1.2);
299
401
  const fracYPerDeg = unmult(f.turn_cheek_arch_y) * (-s * ux) * Math.max(0, 1 - Math.abs(uy));
300
- return [FACE_DEFORM_MULT * deg * W * fracXPerDeg, FACE_DEFORM_MULT * deg * H * fracYPerDeg];
402
+ const dy = FACE_DEFORM_MULT * deg * H * fracYPerDeg;
403
+ if (flatYawTable) {
404
+ const uLead = Math.min(1.2, Math.max(0, -s * ux));
405
+ const uTrail = Math.min(1.2, Math.max(0, s * ux));
406
+ const fracXPerDeg = unmult(f.turn_mid_x) + unmult(f.turn_lead_compress_x) * Math.pow(uLead, 1.2) + unmult(f.turn_trail_shift_x) * Math.pow(uTrail, 1.2);
407
+ return [FACE_DEFORM_MULT * deg * W * fracXPerDeg, dy];
408
+ }
409
+ const R = radius !== undefined && radius > 0 ? radius : W / 2;
410
+ const rawDx = cylinderYawDx(hx - X0, deg, R);
411
+ const absUx = Math.abs((hx - X0) / (W / 2));
412
+ const tOutline = Math.max(0, Math.min(1, (absUx - 0.7) / (1.0 - 0.7)));
413
+ const wOutline = 1 - tOutline * tOutline * (3 - 2 * tOutline);
414
+ const dx = rawDx * wOutline;
415
+ return [dx, dy];
301
416
  }
302
417
 
303
418
  export interface FaceSurfaceDeformOptions {
@@ -318,6 +433,30 @@ export interface FaceSurfaceDeformOptions {
318
433
  * transform constraints holding the dial bones to `[-15, 15]` and `[-12, 12]`.
319
434
  */
320
435
  hasAlternateFaceSet?: boolean;
436
+ /** Issue #478: `config.turn` holding `pivot`, `depths` and optional `head.pivot` / `radius`. */
437
+ turn?: TurnSpec | null;
438
+ /** Issue #478: each part's `opaque_px` from `parts.json` for weighting the head-only pivot. */
439
+ partAreas?: Readonly<Record<string, number>>;
440
+ /**
441
+ * Issue #478: when true, refuse by `CONFIG_TURN_REQUIRED` if `turn` is absent
442
+ * or missing `depths` for attached `face`, `hair_front`, or `hair_back`.
443
+ */
444
+ requireTurn?: boolean;
445
+ /**
446
+ * Issue #478 Bar 4 negative control: when true, flip the back-layer fraction
447
+ * sign so `hair_back` and `hairpin` move with the face instead of against it.
448
+ */
449
+ flipBackLayerSignMutant?: boolean;
450
+ /**
451
+ * Issue #479: explicit cylinder radius override in rig px (defaults to
452
+ * `turnSurfaceRadius(turn, W)` = `W / 2`).
453
+ */
454
+ surfaceRadius?: number;
455
+ /**
456
+ * Issue #479 Bar 4 negative control: when true, restore the flat yaw table
457
+ * instead of the cylinder projection.
458
+ */
459
+ flatYawTableMutant?: boolean;
321
460
  }
322
461
 
323
462
  interface DeformWeight {
@@ -418,8 +557,8 @@ function buildFaceGrid(width: number, height: number): { points: Array<[number,
418
557
  * Promote the `face` region on `head` to a 5×5 grid mesh and populate the
419
558
  * `tilt` and `turn` slider animations with the Set B ×2.5 face and hair mesh
420
559
  * deform timelines, feature field-sampled tracks (#468) and ear/topknot tracks
421
- * (issue #436). When `motion` holds neither `tilt` nor `turn` with slider
422
- * `derive` keys, neither `rig` nor `motion` is touched.
560
+ * (issues #436, #477, #478). When `motion` holds neither `tilt` nor `turn` with
561
+ * slider `derive` keys, neither `rig` nor `motion` is touched.
423
562
  */
424
563
  export function applyFaceSurfaceDeform(
425
564
  rig: {
@@ -443,8 +582,44 @@ export function applyFaceSurfaceDeform(
443
582
  (rawTurn?.tracks?.some((tr) => tr.keys?.some((k) => k.derive !== undefined)) ?? false);
444
583
  if (!hasDerive) return;
445
584
 
446
- // Issue #477: refuse an out-of-range ear derive.depth by name before touching rig or motion.
447
- const earProblems: Problem[] = [];
585
+ const isOpts =
586
+ options !== undefined &&
587
+ options !== null &&
588
+ ('imageWidth' in options ||
589
+ 'imageHeight' in options ||
590
+ 'opaqueWidth' in options ||
591
+ 'opaqueHeight' in options ||
592
+ 'overrides' in options ||
593
+ 'hasAlternateFaceSet' in options ||
594
+ 'turn' in options ||
595
+ 'partAreas' in options ||
596
+ 'requireTurn' in options ||
597
+ 'flipBackLayerSignMutant' in options ||
598
+ 'surfaceRadius' in options ||
599
+ 'flatYawTableMutant' in options);
600
+ const opts: FaceSurfaceDeformOptions = isOpts ? (options as FaceSurfaceDeformOptions) : { overrides: options as Readonly<Partial<FaceDeformFractions>> | null | undefined };
601
+
602
+ // Issue #477 & #478: refuse an out-of-range ear derive.depth or missing config.turn by name before touching rig or motion.
603
+ const preProblems: Problem[] = [];
604
+ if (opts.requireTurn === true) {
605
+ if (opts.turn === undefined || opts.turn === null) {
606
+ preProblems.push({
607
+ code: 'CONFIG_TURN_REQUIRED',
608
+ object: 'config.turn',
609
+ detail: 'is absent and required when motion.animations_from carries a turn or tilt slider animation with derive keys; copy the turn block propose drafted into config.turn so the head pivot and each head part\'s depth are declared',
610
+ });
611
+ } else {
612
+ for (const reqPart of ['face', 'hair_front', 'hair_back'] as const) {
613
+ if (rig.skins.default[reqPart]?.[reqPart] !== undefined && !(reqPart in opts.turn.depths)) {
614
+ preProblems.push({
615
+ code: 'CONFIG_TURN_REQUIRED',
616
+ object: `config.turn.depths.${reqPart}`,
617
+ detail: `is absent and required when motion.animations_from carries a turn or tilt slider animation with derive keys and "${reqPart}" is attached; include "${reqPart}"'s See-through depth_median in config.turn.depths so the head pivot and fraction are defined`,
618
+ });
619
+ }
620
+ }
621
+ }
622
+ }
448
623
  const [earLo, earHi] = EAR_DEPTH_RANGE;
449
624
  for (const [animName, anim] of [
450
625
  ['tilt', rawTilt],
@@ -458,7 +633,7 @@ export function applyFaceSurfaceDeform(
458
633
  const d = k.derive?.depth;
459
634
  if (typeof d === 'number') {
460
635
  if (d < earLo || d > earHi) {
461
- earProblems.push({
636
+ preProblems.push({
462
637
  code: 'CONFIG_TURN_EAR_DEPTH_RANGE',
463
638
  object: `animations.${animName}.tracks[${ti}].keys[${ki}].derive.depth`,
464
639
  detail: `is ${d}; an ear depth in [${earLo}, ${earHi}] (at or behind the head pivot) is required`,
@@ -467,7 +642,7 @@ export function applyFaceSurfaceDeform(
467
642
  } else if (d !== undefined && typeof d === 'object') {
468
643
  for (const [member, val] of Object.entries(d)) {
469
644
  if (typeof val === 'number' && (val < earLo || val > earHi)) {
470
- earProblems.push({
645
+ preProblems.push({
471
646
  code: 'CONFIG_TURN_EAR_DEPTH_RANGE',
472
647
  object: `animations.${animName}.tracks[${ti}].keys[${ki}].derive.depth.${member}`,
473
648
  detail: `is ${val}; an ear depth in [${earLo}, ${earHi}] (at or behind the head pivot) is required`,
@@ -478,24 +653,21 @@ export function applyFaceSurfaceDeform(
478
653
  });
479
654
  });
480
655
  }
481
- refuseIfAny(earProblems);
656
+ refuseIfAny(preProblems);
482
657
 
483
658
  const tiltAnim = rawTilt === undefined ? undefined : structuredClone(rawTilt);
484
659
  const turnAnim = rawTurn === undefined ? undefined : structuredClone(rawTurn);
485
660
  if (tiltAnim !== undefined) motion.animations.tilt = tiltAnim;
486
661
  if (turnAnim !== undefined) motion.animations.turn = turnAnim;
487
662
 
488
- const isOpts =
489
- options !== undefined &&
490
- options !== null &&
491
- ('imageWidth' in options ||
492
- 'imageHeight' in options ||
493
- 'opaqueWidth' in options ||
494
- 'opaqueHeight' in options ||
495
- 'overrides' in options ||
496
- 'hasAlternateFaceSet' in options);
497
- const opts: FaceSurfaceDeformOptions = isOpts ? (options as FaceSurfaceDeformOptions) : { overrides: options as Readonly<Partial<FaceDeformFractions>> | null | undefined };
498
663
  const f = resolveFaceDeformFractions(opts.overrides);
664
+ const hasFlatYawOverride =
665
+ opts.overrides !== undefined &&
666
+ opts.overrides !== null &&
667
+ (opts.overrides.turn_mid_x !== undefined ||
668
+ opts.overrides.turn_lead_compress_x !== undefined ||
669
+ opts.overrides.turn_trail_shift_x !== undefined);
670
+ const useFlatYaw = opts.flatYawTableMutant === true || hasFlatYawOverride;
499
671
 
500
672
  // Issue #472: when no alternate face set is declared, clamp dial bones to the single-plate rated band (±15° yaw, ±12° pitch).
501
673
  if (!opts.hasAlternateFaceSet && Array.isArray(rig.constraints)) {
@@ -592,8 +764,8 @@ export function applyFaceSurfaceDeform(
592
764
  sumY += w[0]?.y ?? 0;
593
765
  }
594
766
  if (faceAtt.weights.length > 0) {
595
- faceRegX = Math.round(sumX / faceAtt.weights.length);
596
- faceRegY = Math.round(sumY / faceAtt.weights.length);
767
+ faceRegX = Math.round((sumX / faceAtt.weights.length) * 2) / 2;
768
+ faceRegY = Math.round((sumY / faceAtt.weights.length) * 2) / 2;
597
769
  }
598
770
  }
599
771
 
@@ -601,9 +773,13 @@ export function applyFaceSurfaceDeform(
601
773
  const H = opts.opaqueHeight ?? faceH - 8;
602
774
  const X0 = faceRegX;
603
775
  const Y0 = faceRegY - 1;
776
+ const cylRadius =
777
+ opts.surfaceRadius !== undefined && Number.isFinite(opts.surfaceRadius) && opts.surfaceRadius > 0
778
+ ? opts.surfaceRadius
779
+ : turnSurfaceRadius(opts.turn, W);
604
780
 
605
781
  const boneOrder = new Map<string, number>(rig.bones.map((b, i) => [b.name, i]));
606
- for (const slotName of ['hair_front', 'hair_back']) {
782
+ for (const slotName of ['hair_front', 'hair_back', 'hairpin']) {
607
783
  const slotObj = rig.skins.default[slotName];
608
784
  const att = slotObj?.[slotName];
609
785
  if (att !== undefined && 'type' in att) {
@@ -701,18 +877,34 @@ export function applyFaceSurfaceDeform(
701
877
  };
702
878
 
703
879
  const getBoneDeltaAtTime = (tracks: readonly SliderTrack[], t: number, boneName: string): [number, number] => {
704
- const baseBone = boneName.replace(/^turn_[^_]+_/, '');
705
- const driver = mapParent[baseBone] ?? baseBone;
880
+ const drivers = new Set<string>();
881
+ let cur: string | undefined = boneName;
882
+ const visited = new Set<string>();
883
+ while (cur !== undefined && !visited.has(cur) && cur !== 'head' && cur !== 'turn_face_head' && cur !== 'root') {
884
+ visited.add(cur);
885
+ if (!cur.startsWith('turn_')) {
886
+ drivers.add(mapParent[cur] ?? cur);
887
+ }
888
+ cur = boneMap.get(cur)?.parent;
889
+ }
890
+ if (drivers.size === 0) {
891
+ const stripped = boneName.replace(/^turn_[^_]+_/, '');
892
+ if (stripped !== 'head' && stripped !== 'root') {
893
+ drivers.add(mapParent[stripped] ?? stripped);
894
+ }
895
+ }
706
896
  let dx = 0;
707
897
  let dy = 0;
708
- for (const tr of tracks) {
709
- const inGroup = tr.group !== undefined && (motion.groups?.[tr.group]?.includes(driver) ?? false);
710
- if (tr.bone !== driver && !inGroup) continue;
711
- const key = tr.keys.find((k) => Math.abs(k.t - t) < 1e-6);
712
- if (key === undefined) continue;
713
- const val = evalDeriveKey(driver, key);
714
- if (tr.property === 'translatex') dx = val;
715
- if (tr.property === 'translatey') dy = val;
898
+ for (const driver of drivers) {
899
+ for (const tr of tracks) {
900
+ const inGroup = tr.group !== undefined && (motion.groups?.[tr.group]?.includes(driver) ?? false);
901
+ if (tr.bone !== driver && !inGroup) continue;
902
+ const key = tr.keys.find((k) => Math.abs(k.t - t) < 1e-6);
903
+ if (key === undefined) continue;
904
+ const val = evalDeriveKey(driver, key);
905
+ if (tr.property === 'translatex') dx += val;
906
+ if (tr.property === 'translatey') dy += val;
907
+ }
716
908
  }
717
909
  return [dx, dy];
718
910
  };
@@ -732,10 +924,14 @@ export function applyFaceSurfaceDeform(
732
924
  const faceVerts = getMeshSetup(faceMesh);
733
925
  const hairFrontAtt = rig.skins.default.hair_front?.hair_front;
734
926
  const hairBackAtt = rig.skins.default.hair_back?.hair_back;
927
+ const hairpinAtt = rig.skins.default.hairpin?.hairpin;
735
928
  const hairFrontVerts = hairFrontAtt !== undefined && 'type' in hairFrontAtt ? getMeshSetup(hairFrontAtt) : null;
736
929
  const hairBackVerts = hairBackAtt !== undefined && 'type' in hairBackAtt ? getMeshSetup(hairBackAtt) : null;
930
+ const hairpinVerts = hairpinAtt !== undefined && 'type' in hairpinAtt && !boneMap.has('hairpin') ? getMeshSetup(hairpinAtt) : null;
737
931
 
738
932
  const hyCrown = Y0 + (67 / 128) * H;
933
+ const hyCrownStart = Y0 + (24 / 128) * H;
934
+ const hyCrownZero = Y0 + (48 / 128) * H;
739
935
  const hyBunSpan = (85 / 128) * H;
740
936
  const hyBangBottom = Y0 - (68 / 128) * H;
741
937
  const hyBangSpan = (130 / 128) * H;
@@ -901,57 +1097,39 @@ export function applyFaceSurfaceDeform(
901
1097
  { t: 3.0, deg: 30 },
902
1098
  ]
903
1099
  : (refTurnTrack?.keys ?? []).map((k) => ({ t: k.t, deg: k.derive?.degrees ?? 0 }));
904
- const turnDeform: DeformTimelineEntry[] = [
905
- {
906
- slot: 'face',
907
- attachment: 'face',
908
- keys: turnKeys.map(({ t, deg }) =>
909
- deg === 0 ? { t } : { t, vertices: expandToDeform(faceVerts, (v) => evalYawFaceSurface(v.hx, v.hy, deg, W, H, X0, Y0, f)) },
910
- ),
911
- },
912
- ];
913
- if (hairFrontVerts !== null) {
914
- turnDeform.push({
915
- slot: 'hair_front',
916
- attachment: 'hair_front',
917
- keys: turnKeys.map(({ t, deg }) =>
918
- deg === 0
919
- ? { t }
920
- : {
921
- t,
922
- vertices: expandToDeform(hairFrontVerts, (v) => {
923
- const [dxSurf, dySurf] = evalYawFaceSurface(v.hx, v.hy, deg, W, H, X0, Y0, f);
924
- const [bx, by] = getVertexBoneDelta(v, origTurnTracks, t);
925
- const uBang = Math.max(0, Math.min(1, (v.hy - hyTurnBangBottom) / hyTurnBangSpan));
926
- const bangParallaxX = (deg / 15) * pyRound(f.turn_bang_parallax_x * 15 * W, 8) * uBang;
927
- return [bangParallaxX + dxSurf - bx, dySurf - by];
928
- }),
929
- },
930
- ),
931
- });
932
- }
933
- if (hairBackVerts !== null) {
934
- turnDeform.push({
935
- slot: 'hair_back',
936
- attachment: 'hair_back',
937
- keys: turnKeys.map(({ t, deg }) =>
938
- deg === 0
939
- ? { t }
940
- : {
941
- t,
942
- vertices: expandToDeform(hairBackVerts, (v) => {
943
- const [bx, by] = getVertexBoneDelta(v, origTurnTracks, t);
944
- const [dxCheek, dyCheek] = evalYawFaceSurface(v.hx, v.hy, deg, W, H, X0, Y0, f);
945
- const uBun = Math.max(0, Math.min(1, (v.hy - hyCrown) / hyBunSpan));
946
- const bunCounterX = FACE_DEFORM_MULT * (deg / 15) * pyRound((f.turn_bun_counter_x * 15 * W) / FACE_DEFORM_MULT, 8);
947
- const targetDx = (1 - uBun) * (dxCheek * f.turn_hair_back_cheek_x) + uBun * bunCounterX;
948
- return [targetDx - bx, (1 - uBun) * dyCheek - by];
949
- }),
950
- },
951
- ),
952
- });
953
- }
954
1100
  const refTurnKeys = refTurnTrack?.keys ?? [];
1101
+
1102
+ // Issue #478: compute head-subtree turn fractions about the head-only pivot.
1103
+ const headParts = new Set<string>(DEFAULT_HEAD_TURN_PARTS);
1104
+
1105
+ const backSign = opts.flipBackLayerSignMutant === true ? -1 : 1;
1106
+ const rawBackFrac = opts.turn != null ? headTurnFraction(opts.turn, 'hair_back', headParts, opts.partAreas) : null;
1107
+ const rawHairpinFrac = opts.turn != null ? headTurnFraction(opts.turn, 'hairpin', headParts, opts.partAreas) : null;
1108
+ const hairpinRidesBack =
1109
+ hairpinAtt !== undefined &&
1110
+ 'type' in hairpinAtt &&
1111
+ hairpinAtt.weights.some((infls) => infls.some((w) => w.bone.includes('hairback_')));
1112
+
1113
+ const dxFaceCenterAt = (deg: number): number => FACE_DEFORM_MULT * deg * W * unmult(f.turn_mid_x);
1114
+ const dxBunAt = (deg: number): number =>
1115
+ backSign * FACE_DEFORM_MULT * (deg / 15) * pyRound((f.turn_bun_counter_x * 15 * W) / FACE_DEFORM_MULT, 8);
1116
+ const dxBackAt = (deg: number): number => {
1117
+ if (rawBackFrac !== null) {
1118
+ return backSign * rawBackFrac * dxFaceCenterAt(deg);
1119
+ }
1120
+ return dxBunAt(deg);
1121
+ };
1122
+ const dxHairpinAt = (deg: number): number => {
1123
+ if (rawHairpinFrac !== null && rawHairpinFrac < 0) {
1124
+ return backSign * rawHairpinFrac * dxFaceCenterAt(deg);
1125
+ }
1126
+ if (hairpinRidesBack && rawBackFrac !== null) {
1127
+ const ratio = f.turn_bun_counter_x > 0 ? f.turn_hairpin_counter_x / f.turn_bun_counter_x : 0.75;
1128
+ return dxBackAt(deg) * ratio;
1129
+ }
1130
+ return backSign * FACE_DEFORM_MULT * (deg / 15) * pyRound((f.turn_hairpin_counter_x * 15 * W) / FACE_DEFORM_MULT, 8);
1131
+ };
1132
+
955
1133
  const earMembers = motion.groups?.ears ?? ['ear_r', 'ear_l'].filter((b) => boneMap.has(b));
956
1134
  const hasAuthoredEarTurnTx = turnAnim.tracks.some(
957
1135
  (tr) => tr.property === 'translatex' && (tr.group === 'ears' || tr.bone === 'ear_r' || tr.bone === 'ear_l'),
@@ -975,18 +1153,42 @@ export function applyFaceSurfaceDeform(
975
1153
  const dFrac = zRef > 0 ? z / zRef : 1;
976
1154
  const ux = Math.max(-1, Math.min(1, (bx - X0) / (W / 2)));
977
1155
  const effDeg = deg * (1 + (dFrac - 1) * Math.max(0, 1 - ux * ux));
978
- const [dxL] = evalYawFaceSurface(bx - featRx, by, effDeg, W, H, X0, Y0, f);
979
- const [dxR] = evalYawFaceSurface(bx + featRx, by, effDeg, W, H, X0, Y0, f);
1156
+ const [dxL] = evalYawFaceSurface(bx - featRx, by, effDeg, W, H, X0, Y0, f, cylRadius, useFlatYaw);
1157
+ const [dxR] = evalYawFaceSurface(bx + featRx, by, effDeg, W, H, X0, Y0, f, cylRadius, useFlatYaw);
980
1158
  const rawDelta = (dxR - dxL) / (2 * featRx);
981
1159
  const isTrailing = s * (bx - X0) > featRx * 0.5;
982
- const sx = isTrailing ? 1 + Math.abs(rawDelta) : Math.max(0.2, 1 + rawDelta);
983
- const dx = isTrailing
984
- ? (s > 0 ? dxR - featRx * (sx - 1) : dxL + featRx * (sx - 1))
985
- : 0.5 * (dxL + dxR);
1160
+ let sx: number;
1161
+ if (!useFlatYaw && isTrailing) {
1162
+ const cylL = cylinderYawDx(bx - X0 - featRx * 0.5, effDeg, cylRadius);
1163
+ const cylR = cylinderYawDx(bx - X0 + featRx * 0.5, effDeg, cylRadius);
1164
+ sx = 1 + Math.abs((cylR - cylL) / featRx);
1165
+ } else {
1166
+ sx = isTrailing ? 1 + Math.abs(rawDelta) : Math.max(0.2, 1 + rawDelta);
1167
+ }
1168
+ sx = pyRound(sx, 4);
1169
+ let dx: number;
1170
+ if (useFlatYaw) {
1171
+ dx = isTrailing
1172
+ ? (s > 0 ? dxR - featRx * (sx - 1) : dxL + featRx * (sx - 1))
1173
+ : 0.5 * (dxL + dxR);
1174
+ } else {
1175
+ const [dxCenter] = evalYawFaceSurface(bx, by, effDeg, W, H, X0, Y0, f, cylRadius, false);
1176
+ if (Math.abs(deg) > FACE_RATED_YAW_BAND) {
1177
+ const [plateLeftDx] = evalYawFaceSurface(X0 - W / 2, by, deg, W, H, X0, Y0, f, cylRadius, false);
1178
+ const [plateRightDx] = evalYawFaceSurface(X0 + W / 2, by, deg, W, H, X0, Y0, f, cylRadius, false);
1179
+ const plateMinX = X0 - W / 2 + plateLeftDx;
1180
+ const plateMaxX = X0 + W / 2 + plateRightDx;
1181
+ const minDx = Math.ceil((plateMinX - bx + featRx * sx - 1e-9) * 10000) / 10000;
1182
+ const maxDx = Math.floor((plateMaxX - bx - featRx * sx + 1e-9) * 10000) / 10000;
1183
+ dx = Math.max(minDx, Math.min(maxDx, dxCenter));
1184
+ } else {
1185
+ dx = dxCenter;
1186
+ }
1187
+ }
986
1188
  if (tr.property === 'translatex') {
987
1189
  vMap[bname] = [pyRound(dx, 4)];
988
1190
  } else {
989
- vMap[bname] = [pyRound(sx, 4)];
1191
+ vMap[bname] = [sx];
990
1192
  }
991
1193
  }
992
1194
  return { t: k.t, v: vMap };
@@ -1024,15 +1226,15 @@ export function applyFaceSurfaceDeform(
1024
1226
  keys: refTurnKeys.map((k) => {
1025
1227
  const deg = k.derive?.degrees ?? 0;
1026
1228
  if (deg === 0) return { t: k.t, v: [0] };
1027
- const [dxCheekEdge] = evalYawFaceSurface(earHx, hyEar, deg, W, H, X0, Y0, f);
1229
+ const [dxCheekEdge] = evalYawFaceSurface(earHx, hyEar, deg, W, H, X0, Y0, f, cylRadius, useFlatYaw);
1028
1230
  return { t: k.t, v: [pyRound(dxCheekEdge * f.turn_ear_x, 4)] };
1029
1231
  }),
1030
1232
  });
1031
1233
  }
1032
1234
  }
1033
- for (const [tkBone, tkFrac] of [
1034
- ['bun_ctl', f.turn_bun_counter_x],
1035
- ['hairpin', f.turn_hairpin_counter_x],
1235
+ for (const [tkBone, evalTkDx] of [
1236
+ ['bun_ctl', dxBunAt],
1237
+ ['hairpin', dxHairpinAt],
1036
1238
  ] as const) {
1037
1239
  if (!boneMap.has(tkBone)) continue;
1038
1240
  turnAnim.tracks.push({
@@ -1041,11 +1243,111 @@ export function applyFaceSurfaceDeform(
1041
1243
  keys: refTurnKeys.map((k) => {
1042
1244
  const deg = k.derive?.degrees ?? 0;
1043
1245
  if (deg === 0) return { t: k.t, v: [0] };
1044
- const tkPx = pyRound((tkFrac * 15 * W) / FACE_DEFORM_MULT, 8);
1045
- return { t: k.t, v: [pyRound(FACE_DEFORM_MULT * (deg / 15) * tkPx, 4)] };
1246
+ return { t: k.t, v: [pyRound(evalTkDx(deg), 4)] };
1046
1247
  }),
1047
1248
  });
1048
1249
  }
1250
+ // Issue #478: cloth chain roots parented to head on hair_back follow hair_back's counter-parallax fraction.
1251
+ for (const b of rig.bones) {
1252
+ if (b.parent === 'head' && b.name.startsWith('hairback_') && b.name.endsWith('_0')) {
1253
+ if (turnAnim.tracks.some((tr) => tr.bone === b.name && tr.property === 'translatex')) continue;
1254
+ turnAnim.tracks.push({
1255
+ bone: b.name,
1256
+ property: 'translatex',
1257
+ keys: refTurnKeys.map((k) => {
1258
+ const deg = k.derive?.degrees ?? 0;
1259
+ if (deg === 0) return { t: k.t, v: [0] };
1260
+ return { t: k.t, v: [pyRound(dxBackAt(deg), 4)] };
1261
+ }),
1262
+ });
1263
+ }
1264
+ }
1265
+
1266
+ const turnDeform: DeformTimelineEntry[] = [
1267
+ {
1268
+ slot: 'face',
1269
+ attachment: 'face',
1270
+ keys: turnKeys.map(({ t, deg }) =>
1271
+ deg === 0 ? { t } : { t, vertices: expandToDeform(faceVerts, (v) => evalYawFaceSurface(v.hx, v.hy, deg, W, H, X0, Y0, f, cylRadius, useFlatYaw)) },
1272
+ ),
1273
+ },
1274
+ ];
1275
+ if (hairFrontVerts !== null) {
1276
+ turnDeform.push({
1277
+ slot: 'hair_front',
1278
+ attachment: 'hair_front',
1279
+ keys: turnKeys.map(({ t, deg }) =>
1280
+ deg === 0
1281
+ ? { t }
1282
+ : {
1283
+ t,
1284
+ vertices: expandToDeform(hairFrontVerts, (v) => {
1285
+ const [dxSurf, dySurf] = evalYawFaceSurface(v.hx, v.hy, deg, W, H, X0, Y0, f, cylRadius, useFlatYaw);
1286
+ const [bx, by] = getVertexBoneDelta(v, turnAnim.tracks, t);
1287
+ const uBang = Math.max(0, Math.min(1, (v.hy - hyTurnBangBottom) / hyTurnBangSpan));
1288
+ const bangParallaxX = (deg / 15) * pyRound(f.turn_bang_parallax_x * 15 * W, 8) * uBang;
1289
+ const hyFrontCrownStart = Y0 + (36 / 128) * H;
1290
+ const hyFrontCrownZero = Y0 + (60 / 128) * H;
1291
+ const tCrown = Math.max(0, Math.min(1, (v.hy - hyFrontCrownStart) / (hyFrontCrownZero - hyFrontCrownStart)));
1292
+ const wCrown = 1 - tCrown * tCrown * (3 - 2 * tCrown);
1293
+ const absUx = Math.abs((v.hx - X0) / (W / 2));
1294
+ const tLat = Math.max(0, Math.min(1, (absUx - 0.96) / (1.28 - 0.96)));
1295
+ const wLat = 1 - tLat * tLat * (3 - 2 * tLat);
1296
+ return [(bangParallaxX + dxSurf) * wCrown * wLat - bx, dySurf * wCrown * wLat - by];
1297
+ }),
1298
+ },
1299
+ ),
1300
+ });
1301
+ }
1302
+ if (hairBackVerts !== null) {
1303
+ turnDeform.push({
1304
+ slot: 'hair_back',
1305
+ attachment: 'hair_back',
1306
+ keys: turnKeys.map(({ t, deg }) =>
1307
+ deg === 0
1308
+ ? { t }
1309
+ : {
1310
+ t,
1311
+ vertices: expandToDeform(hairBackVerts, (v) => {
1312
+ const [bx, by] = getVertexBoneDelta(v, turnAnim.tracks, t);
1313
+ const [, dyCheek] = evalYawFaceSurface(v.hx, v.hy, deg, W, H, X0, Y0, f, cylRadius, useFlatYaw);
1314
+ const uBun = Math.max(0, Math.min(1, (v.hy - hyCrown) / hyBunSpan));
1315
+ const wBun =
1316
+ (v.boneWeights.bun ?? 0) +
1317
+ (v.boneWeights.bun_ctl ?? 0) +
1318
+ (v.boneWeights.turn_hair_back_bun ?? 0) +
1319
+ (v.boneWeights.turn_hair_back_bun_ctl ?? 0);
1320
+ const wTopBun = Math.max(uBun, wBun);
1321
+ const tCrown = Math.max(0, Math.min(1, (v.hy - hyCrownStart) / (hyCrownZero - hyCrownStart)));
1322
+ const wCrown = 1 - tCrown * tCrown * (3 - 2 * tCrown);
1323
+ const tCraniumY = Math.max(0, Math.min(1, (v.hy - (Y0 - (24 / 128) * H)) / ((32 / 128) * H)));
1324
+ const absUx = Math.abs((v.hx - X0) / (W / 2));
1325
+ const tLat = Math.max(0, Math.min(1, (absUx - 0.55) / (0.95 - 0.55)));
1326
+ const wLatCranium = 1 - tCraniumY * (tLat * tLat * (3 - 2 * tLat));
1327
+ const targetDx = (1 - wTopBun) * (dxBackAt(deg) * wCrown * wLatCranium) + wTopBun * dxBunAt(deg);
1328
+ return [targetDx - bx, (1 - wTopBun) * dyCheek * wCrown - by];
1329
+ }),
1330
+ },
1331
+ ),
1332
+ });
1333
+ }
1334
+ if (hairpinVerts !== null) {
1335
+ turnDeform.push({
1336
+ slot: 'hairpin',
1337
+ attachment: 'hairpin',
1338
+ keys: turnKeys.map(({ t, deg }) =>
1339
+ deg === 0
1340
+ ? { t }
1341
+ : {
1342
+ t,
1343
+ vertices: expandToDeform(hairpinVerts, (v) => {
1344
+ const [bx, by] = getVertexBoneDelta(v, turnAnim.tracks, t);
1345
+ return [dxHairpinAt(deg) - bx, -by];
1346
+ }),
1347
+ },
1348
+ ),
1349
+ });
1350
+ }
1049
1351
  turnAnim.deform = turnDeform;
1050
1352
  }
1051
1353
  }