@rig-c/parts 1.70.1 → 1.71.1

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/rig.ts CHANGED
@@ -187,7 +187,7 @@ import { alphaAbove, crop, pad, type Raster } from './raster/index.ts';
187
187
  import { pyRound } from './round.ts';
188
188
  import { boneHeat, type HeatDust, heatInfluences, HEAT_LIMITS, heatRow, type HeatRow, latticeSilhouette, tracedSilhouette } from './heat.ts';
189
189
  import type { PosePoints } from './skeleton.ts';
190
- import { applyFaceSurfaceDeform, buildDepth25DTurn, FACE_RATED_BAND, FACESHIFT_BONE, PITCH_DIAL_BONE, REAR_SHIFT_BONE, resolveTurnGrid, TURN_BONE, TURN_CARRIER_TAG, TURN_GRID_MAX_TRIANGLES_PER_SLOT, TURN_GRID_MAX_TRIANGLES_TOTAL, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnSurfaceBone, turnTwin, YAW_DIAL_BONE } from './turn.ts';
190
+ import { applyFaceSurfaceDeform, BODY_REAR_SHIFT_BONE, BODY_YAW_DIAL_BONE, BODYSHIFT_BONE, buildDepth25DTurn, FACE_RATED_BAND, FACESHIFT_BONE, PITCH_DIAL_BONE, REAR_SHIFT_BONE, resolveTurnGrid, TURN_BONE, TURN_CARRIER_TAG, TURN_GRID_MAX_TRIANGLES_PER_SLOT, TURN_GRID_MAX_TRIANGLES_TOTAL, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnRole, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnSurfaceBone, turnTwin, turnUnitBone, YAW_DIAL_BONE } from './turn.ts';
191
191
  import { DISTANCE_EXPONENT, type FloorForm, type Influence, influences, type InfluenceLimits, type MeshInfluences, meshLimits, type Segment } from './weights.ts';
192
192
 
193
193
  /** Transparent pixels added round every part image — the reference's `PAD`. */
@@ -1537,6 +1537,18 @@ export function buildWaistPairSource(
1537
1537
  if (!B.has(s.against)) fail('RIG_NAME_RESOLVES', `${at}.against`, `names the bone "${s.against}", which config.bones does not declare`);
1538
1538
  });
1539
1539
  }
1540
+ if (cfg.turn?.roles !== undefined) {
1541
+ for (const part of Object.keys(cfg.turn.roles)) {
1542
+ if (!byPart.has(part)) fail('RIG_PART_PRESENT', `config.turn.roles.${part}`, `names the part "${part}", which is not in parts.json; ${where(part)}`);
1543
+ else if (!(part in cfg.meshes) && !(part in cfg.regions)) fail('RIG_NAME_RESOLVES', `config.turn.roles.${part}`, `names "${part}", which neither config.meshes nor config.regions attaches`);
1544
+ }
1545
+ }
1546
+ if (cfg.turn?.body !== undefined) {
1547
+ for (const part of Object.keys(cfg.turn.body.roles)) {
1548
+ if (!byPart.has(part)) fail('RIG_PART_PRESENT', `config.turn.body.roles.${part}`, `names the part "${part}", which is not in parts.json; ${where(part)}`);
1549
+ else if (!(part in cfg.meshes) && !(part in cfg.regions)) fail('RIG_NAME_RESOLVES', `config.turn.body.roles.${part}`, `names "${part}", which neither config.meshes nor config.regions attaches`);
1550
+ }
1551
+ }
1540
1552
  for (const p of parts.parts) {
1541
1553
  const inM = p.name in cfg.meshes;
1542
1554
  const inR = p.name in cfg.regions;
@@ -1636,16 +1648,21 @@ export function buildWaistPairSource(
1636
1648
  moveKeysToControls(motion, controls);
1637
1649
  // Parents first: a depth-first walk over the table in insertion order, each
1638
1650
  // bone after its parent — which puts every control directly above its bone.
1639
- const ordered: Bone[] = [];
1640
- const done = new Set<string>();
1641
- const visit = (n: string): void => {
1642
- if (done.has(n)) return;
1643
- const b = B.get(n) as Bone;
1644
- if (b.parent !== null) visit(b.parent);
1645
- done.add(n);
1646
- ordered.push(b);
1651
+ const orderParentsFirst = <T extends { name: string; parent?: string | null }>(table: ReadonlyMap<string, T>): T[] => {
1652
+ const out: T[] = [];
1653
+ const done = new Set<string>();
1654
+ const visit = (n: string): void => {
1655
+ if (done.has(n)) return;
1656
+ const b = table.get(n);
1657
+ if (b === undefined) return;
1658
+ if (b.parent !== null && b.parent !== undefined) visit(b.parent);
1659
+ done.add(n);
1660
+ out.push(b);
1661
+ };
1662
+ for (const n of table.keys()) visit(n);
1663
+ return out;
1647
1664
  };
1648
- for (const n of B.keys()) visit(n);
1665
+ const ordered = orderParentsFirst(B);
1649
1666
 
1650
1667
  const spineX = (x: number): number => x - CX;
1651
1668
  const spineY = (y: number): number => cropToSpineY(y, H);
@@ -1878,8 +1895,9 @@ export function buildWaistPairSource(
1878
1895
  return;
1879
1896
  }
1880
1897
  const art = images.get(part);
1898
+ const isTurnPart = cfg.turn?.roles?.[part] !== undefined || cfg.turn?.body?.roles?.[part] !== undefined;
1881
1899
  const image =
1882
- cfg.turn?.roles?.[part] !== undefined && art !== undefined && art.width === scalar.width && art.height === scalar.height
1900
+ isTurnPart && art !== undefined && art.width === scalar.width && art.height === scalar.height
1883
1901
  ? padTurnDepthSheet(scalar, art, PAD)
1884
1902
  : padDepthSheet(scalar, PAD);
1885
1903
  outImages.push([reference.image, image]);
@@ -2413,29 +2431,46 @@ export function buildWaistPairSource(
2413
2431
  }
2414
2432
  }
2415
2433
 
2434
+ const isHeadSurface = cfg.turn?.roles?.[p.name] === 'surface';
2435
+ const isBodySurface = cfg.turn?.body?.roles?.[p.name] === 'surface';
2436
+ if (isHeadSurface || isBodySurface) {
2437
+ const roleField = isHeadSurface ? `config.turn.roles.${p.name}` : `config.turn.body.roles.${p.name}`;
2438
+ if (cfg.meshes[p.name] !== undefined) {
2439
+ fail(
2440
+ 'CONFIG_TURN_SURFACE_REGION',
2441
+ roleField,
2442
+ `declares "${p.name}" as "surface", and config.meshes.${p.name} also declares a mesh for "${p.name}"; a 2.5D turn "surface" part must be attached in config.regions so the rig stage can promote it to a depth-backed grid mesh`,
2443
+ );
2444
+ continue;
2445
+ }
2446
+ if (p.depth === undefined || scalar === undefined) {
2447
+ fail(
2448
+ 'RIG_TURN_SURFACE_DEPTH_REQUIRED',
2449
+ roleField,
2450
+ `declares role "surface" for "${p.name}", which requires a depth sheet in parts.json; run assemble with config.depth or provide "${p.name}_depth.png"`,
2451
+ );
2452
+ continue;
2453
+ }
2454
+ }
2455
+
2416
2456
  const mesh = cfg.meshes[p.name];
2417
2457
  if (mesh === undefined) {
2418
- if (cfg.turn?.roles?.[p.name] === 'surface') {
2419
- if (p.depth === undefined || scalar === undefined) {
2420
- fail(
2421
- 'RIG_TURN_SURFACE_DEPTH_REQUIRED',
2422
- `config.turn.roles.${p.name}`,
2423
- `declares role "surface" for "${p.name}", which requires a depth sheet in parts.json; run assemble with config.depth or provide "${p.name}_depth.png"`,
2424
- );
2425
- continue;
2426
- }
2427
- const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
2458
+ if (isHeadSurface || isBodySurface) {
2459
+ const [cols, rows] = isHeadSurface
2460
+ ? resolveTurnGrid(cfg.turn!, p.name)
2461
+ : resolveTurnGrid(cfg.turn!.body!, p.name, cfg.turn);
2428
2462
  const triCount = 2 * (cols - 1) * (rows - 1);
2463
+ const gridField = isHeadSurface ? `config.turn.grid (${p.name})` : `config.turn.body.grid (${p.name})`;
2429
2464
  if (triCount > TURN_GRID_MAX_TRIANGLES_PER_SLOT) {
2430
2465
  fail(
2431
2466
  'RIG_TURN_GRID_BUDGET',
2432
- `config.turn.grid (${p.name})`,
2467
+ gridField,
2433
2468
  `specifies a ${cols}x${rows} grid (${triCount} triangles), which exceeds the per-slot budget of ${TURN_GRID_MAX_TRIANGLES_PER_SLOT} triangles`,
2434
2469
  );
2435
2470
  continue;
2436
2471
  }
2437
2472
  const surfBone = turnSurfaceBone(p.name);
2438
- const { sources: _sources, ...coreDepth } = p.depth;
2473
+ const { sources: _sources, ...coreDepth } = p.depth!;
2439
2474
  const gridAtt: Omit<MeshAttachment, 'uvs' | 'triangles' | 'hull' | 'weights'> = {
2440
2475
  type: 'mesh',
2441
2476
  image: file,
@@ -3076,135 +3111,491 @@ export function buildWaistPairSource(
3076
3111
  // ---- the turn control (issue #251) -------------------------------------
3077
3112
  // Only when the config has `turn`: every other build adds nothing here, so no byte moves.
3078
3113
  if (cfg.turn !== undefined) refuseIfAny(turnRiderProblems(cfg.turn, cfg, parts.parts));
3079
- const turned = cfg.turn === undefined || cfg.turn.roles !== undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, rebound, skin, cfg.constraints ?? [], declaredFront, slotFamilies, stops, turnOrderByDeclaration);
3114
+ const turned = cfg.turn === undefined || cfg.turn.roles !== undefined || cfg.turn.depths === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, rebound, skin, cfg.constraints ?? [], declaredFront, slotFamilies, stops, turnOrderByDeclaration);
3080
3115
  for (const row of turned?.rows ?? []) for (const t of row.twins) layoutAlias(explicitLayout.plan, t.bone, t.twin);
3081
3116
  const finalSlots = frontSlots.length === 0 ? explicitLayout.slots : spliceFrontSlots(explicitLayout.slots, frontSlots, frontTargets, slotFamilies);
3082
3117
  let generatedMeshBudget: { meshSlots: number; meshTriangles: number } | null = null;
3083
- if (cfg.turn?.roles !== undefined) {
3084
- const roles = cfg.turn.roles;
3118
+ if (cfg.turn?.roles !== undefined || cfg.turn?.body !== undefined) {
3085
3119
  let totalGridTriangles = 0;
3086
- const headIdx = bones.findIndex((b) => b.name === 'head');
3087
- if (headIdx === -1) {
3088
- fail('RIG_TURN_HEAD_BONE', 'config.turn.roles', 'requires a declared "head" bone in config.bones to parent the 2.5D turn carriers');
3089
- } else {
3090
- const headTransform = world.get('head') as BoneTransform;
3091
- const headTurnDeg = turn.get('head') ?? 0;
3092
- const surfBones: RigBone[] = [];
3093
- for (const p of parts.parts) {
3094
- if (roles[p.name] !== 'surface' || cfg.meshes[p.name] !== undefined) continue;
3095
- const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
3096
- totalGridTriangles += 2 * (cols - 1) * (rows - 1);
3097
- const cx = p.x + p.w / 2;
3098
- const cy = p.y + p.h / 2;
3099
- const [lx, ly] = toBoneLocal(headTransform, spineX(cx), spineY(cy));
3100
- const rot = places(normaliseDegrees(-headTurnDeg));
3101
- surfBones.push({
3102
- name: turnSurfaceBone(p.name),
3103
- parent: FACESHIFT_BONE,
3104
- x: places(lx),
3105
- y: places(ly),
3106
- ...(rot === 0 ? {} : { rotation: rot }),
3107
- });
3108
- }
3109
- if (totalGridTriangles > TURN_GRID_MAX_TRIANGLES_TOTAL) {
3110
- fail(
3111
- 'RIG_TURN_GRID_BUDGET',
3112
- 'config.turn.grid',
3113
- `allocates ${totalGridTriangles} total grid triangles across surface slots, which exceeds the total budget of ${TURN_GRID_MAX_TRIANGLES_TOTAL} triangles`,
3114
- );
3115
- }
3116
- const hasRear = Object.values(roles).includes('rear');
3117
- const carriers: RigBone[] = [
3118
- { name: FACESHIFT_BONE, parent: 'head', x: 0, y: 0 },
3119
- ...(hasRear ? [{ name: REAR_SHIFT_BONE, parent: 'head', x: 0, y: 0 }] : []),
3120
- ...surfBones,
3121
- ];
3122
- bones.splice(headIdx + 1, 0, ...carriers);
3123
- const existingNames = new Set(bones.map((b) => b.name));
3124
- if (!existingNames.has(YAW_DIAL_BONE)) bones.push({ name: YAW_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
3125
- if (!existingNames.has(PITCH_DIAL_BONE)) bones.push({ name: PITCH_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
3126
-
3127
- const boneByName = new Map(bones.map((b) => [b.name, b]));
3128
- const slotByName = new Map(finalSlots.map((s) => [s.name, s]));
3129
- const reparentFromHead = (boneName: string, targetParent: string): void => {
3130
- const b = boneByName.get(boneName);
3131
- if (b !== undefined && b.parent === 'head') b.parent = targetParent;
3132
- };
3133
- const rebindPartToCarrier = (part: string, carrierBone: string): void => {
3134
- const sl = slotByName.get(part);
3135
- if (sl !== undefined && sl.bone === 'head') sl.bone = carrierBone;
3136
- const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3137
- if (stillSl !== undefined) {
3138
- if (stillSl.bone === 'head') stillSl.bone = carrierBone;
3139
- else reparentFromHead(stillSl.bone, carrierBone);
3120
+ const slotByName = new Map(finalSlots.map((s) => [s.name, s]));
3121
+
3122
+ if (cfg.turn.roles !== undefined) {
3123
+ const roles = cfg.turn.roles;
3124
+ const headIdx = bones.findIndex((b) => b.name === 'head');
3125
+ if (headIdx === -1) {
3126
+ fail('RIG_TURN_HEAD_BONE', 'config.turn.roles', 'requires a declared "head" bone in config.bones to parent the 2.5D turn carriers');
3127
+ } else {
3128
+ const headTransform = world.get('head') as BoneTransform;
3129
+ const headTurnDeg = turn.get('head') ?? 0;
3130
+ const surfBones: RigBone[] = [];
3131
+ const unitMeshBones: RigBone[] = [];
3132
+ for (const p of parts.parts) {
3133
+ if (roles[p.name] === 'unit' && cfg.meshes[p.name] !== undefined) {
3134
+ unitMeshBones.push({ name: turnUnitBone(p.name), parent: FACESHIFT_BONE, x: 0, y: 0 });
3135
+ continue;
3136
+ }
3137
+ if (roles[p.name] !== 'surface') continue;
3138
+ const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
3139
+ totalGridTriangles += 2 * (cols - 1) * (rows - 1);
3140
+ const cx = p.x + p.w / 2;
3141
+ const cy = p.y + p.h / 2;
3142
+ const [lx, ly] = toBoneLocal(headTransform, spineX(cx), spineY(cy));
3143
+ const rot = places(normaliseDegrees(-headTurnDeg));
3144
+ surfBones.push({
3145
+ name: turnSurfaceBone(p.name),
3146
+ parent: FACESHIFT_BONE,
3147
+ x: places(lx),
3148
+ y: places(ly),
3149
+ ...(rot === 0 ? {} : { rotation: rot }),
3150
+ });
3140
3151
  }
3141
- const atts = skin[part] ?? {};
3142
- for (const att of Object.values(atts)) {
3143
- if (!('type' in att) || att.weights === undefined) continue;
3144
- for (const row of att.weights) {
3145
- for (const w of row) {
3146
- if (w.bone === 'head') {
3147
- w.bone = carrierBone;
3148
- } else {
3149
- // Find the ancestor of w.bone that hangs directly under head and reparent it to carrierBone.
3150
- let cur = boneByName.get(w.bone);
3151
- while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && cur.parent !== carrierBone) {
3152
- cur = boneByName.get(cur.parent);
3152
+ const hasRear = Object.values(roles).includes('rear');
3153
+ const carriers: RigBone[] = [
3154
+ { name: FACESHIFT_BONE, parent: 'head', x: 0, y: 0 },
3155
+ ...(hasRear ? [{ name: REAR_SHIFT_BONE, parent: 'head', x: 0, y: 0 }] : []),
3156
+ ...surfBones,
3157
+ ...unitMeshBones,
3158
+ ];
3159
+ bones.splice(headIdx + 1, 0, ...carriers);
3160
+ const existingNames = new Set(bones.map((b) => b.name));
3161
+ if (!existingNames.has(YAW_DIAL_BONE)) bones.push({ name: YAW_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
3162
+ if (!existingNames.has(PITCH_DIAL_BONE)) bones.push({ name: PITCH_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
3163
+
3164
+ const boneByName = new Map(bones.map((b) => [b.name, b]));
3165
+ const headCarriers = new Set<string>(carriers.map((b) => b.name));
3166
+ const assertNotHeadTurnCarrier = (boneName: string, targetParent: string): void => {
3167
+ if (headCarriers.has(boneName)) {
3168
+ throw new Error(`turn invariant violated: turn carrier "${boneName}" must never be reparented (target "${targetParent}")`);
3169
+ }
3170
+ };
3171
+ const reparentFromHead = (boneName: string, targetParent: string): void => {
3172
+ assertNotHeadTurnCarrier(boneName, targetParent);
3173
+ const b = boneByName.get(boneName);
3174
+ if (b !== undefined && b.parent === 'head') b.parent = targetParent;
3175
+ };
3176
+ const rebindPartToCarrier = (part: string, carrierBone: string): void => {
3177
+ const sl = slotByName.get(part);
3178
+ if (sl !== undefined && sl.bone === 'head') sl.bone = carrierBone;
3179
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3180
+ if (stillSl !== undefined) {
3181
+ if (stillSl.bone === 'head') stillSl.bone = carrierBone;
3182
+ else reparentFromHead(stillSl.bone, carrierBone);
3183
+ }
3184
+ for (const slotEntry of finalSlots) {
3185
+ if (slotEntry.name !== part && !slotEntry.name.startsWith(`${part}__island`)) continue;
3186
+ if (slotEntry.bone === 'head') slotEntry.bone = carrierBone;
3187
+ const atts = skin[slotEntry.name] ?? {};
3188
+ for (const att of Object.values(atts)) {
3189
+ if (!('type' in att) || att.weights === undefined) continue;
3190
+ for (const row of att.weights) {
3191
+ for (const w of row) {
3192
+ if (w.bone === 'head') {
3193
+ w.bone = carrierBone;
3194
+ } else {
3195
+ let cur = boneByName.get(w.bone);
3196
+ while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && !headCarriers.has(cur.parent)) {
3197
+ cur = boneByName.get(cur.parent);
3198
+ }
3199
+ if (cur !== undefined && cur.parent === 'head') {
3200
+ assertNotHeadTurnCarrier(cur.name, carrierBone);
3201
+ cur.parent = carrierBone;
3202
+ }
3203
+ }
3153
3204
  }
3154
- if (cur !== undefined && cur.parent === 'head') cur.parent = carrierBone;
3155
3205
  }
3156
3206
  }
3157
3207
  }
3158
- }
3159
- };
3208
+ };
3160
3209
 
3161
- for (const [part, role] of Object.entries(roles)) {
3162
- if (role === 'unit') {
3163
- if (cfg.regions[part] !== undefined) {
3164
- const bName = regionBone(cfg.regions[part]);
3165
- if (bName === 'head') {
3166
- const sl = slotByName.get(part);
3167
- if (sl !== undefined) sl.bone = FACESHIFT_BONE;
3168
- } else {
3169
- reparentFromHead(bName, FACESHIFT_BONE);
3210
+ const headUnitRootOwner = new Map<string, { part: string; bone: string; rootLabel: string }>();
3211
+ const rebindUnitMeshToHeadCarrier = (part: string): void => {
3212
+ const unitBone = turnUnitBone(part);
3213
+ const bound: string[] = [];
3214
+ const addBound = (bName: string): void => {
3215
+ if (!bound.includes(bName)) bound.push(bName);
3216
+ };
3217
+ for (const sl of finalSlots) {
3218
+ if (sl.name !== part && !sl.name.startsWith(`${part}__island`)) continue;
3219
+ const atts = skin[sl.name] ?? {};
3220
+ let hasWeights = false;
3221
+ for (const att of Object.values(atts)) {
3222
+ if ('type' in att && att.weights !== undefined && att.weights.length > 0) {
3223
+ hasWeights = true;
3224
+ for (const row of att.weights) {
3225
+ for (const w of row) addBound(w.bone);
3226
+ }
3227
+ }
3170
3228
  }
3171
- const st = stills[part];
3172
- if (st !== undefined) reparentFromHead(st.bone, FACESHIFT_BONE);
3173
- } else if (cfg.meshes[part] !== undefined) {
3174
- rebindPartToCarrier(part, FACESHIFT_BONE);
3229
+ if (!hasWeights) addBound(sl.bone);
3175
3230
  }
3176
- } else if (role === 'rear' && hasRear) {
3177
- if (cfg.regions[part] !== undefined) {
3178
- const bName = regionBone(cfg.regions[part]);
3179
- if (bName === 'head') {
3180
- const sl = slotByName.get(part);
3181
- if (sl !== undefined) sl.bone = REAR_SHIFT_BONE;
3182
- } else {
3183
- reparentFromHead(bName, REAR_SHIFT_BONE);
3231
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3232
+ if (stillSl !== undefined) addBound(stillSl.bone);
3233
+ const uncarried: string[] = [];
3234
+ const sharedRoots = new Set<string>();
3235
+ let hasShared = false;
3236
+ for (const bName of bound) {
3237
+ if (bName === 'head' || bName === unitBone) continue;
3238
+ let cur = boneByName.get(bName);
3239
+ while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && !headCarriers.has(cur.parent)) {
3240
+ cur = boneByName.get(cur.parent);
3241
+ }
3242
+ if (cur === undefined || cur.parent === undefined || (cur.parent !== 'head' && !headCarriers.has(cur.parent)) || headCarriers.has(cur.name)) {
3243
+ uncarried.push(bName);
3244
+ continue;
3245
+ }
3246
+ const rootLabel = cur.name.endsWith(CONTROL_SUFFIX) ? cur.name.slice(0, -CONTROL_SUFFIX.length) : cur.name;
3247
+ const owner = headUnitRootOwner.get(cur.name);
3248
+ if (owner !== undefined && owner.part !== part) {
3249
+ hasShared = true;
3250
+ if (!sharedRoots.has(cur.name)) {
3251
+ sharedRoots.add(cur.name);
3252
+ const sharedDetail =
3253
+ owner.bone === bName
3254
+ ? `bone "${bName}"${bName === owner.rootLabel ? '' : ` (under "${owner.rootLabel}")`}`
3255
+ : `chain root "${owner.rootLabel}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${bName}")`;
3256
+ fail(
3257
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3258
+ `config.turn.roles.${part}`,
3259
+ `declares "${part}" as "unit", and config.meshes.${part} shares ${sharedDetail} with "unit" mesh "${owner.part}" (config.turn.roles.${owner.part}); each "unit" mesh reparents its bound chain root under its own "<part>_unit" carrier, so two "unit" meshes cannot share a bone or chain under "head"`,
3260
+ );
3261
+ }
3262
+ } else if (owner === undefined) {
3263
+ headUnitRootOwner.set(cur.name, { part, bone: bName, rootLabel });
3264
+ }
3265
+ }
3266
+ if (uncarried.length > 0) {
3267
+ fail(
3268
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3269
+ `config.turn.roles.${part}`,
3270
+ `declares "${part}" as "unit", and config.meshes.${part} binds bone(s) ${uncarried.map((b) => `"${b}"`).join(', ')} outside the "head" subtree, which cannot be carried by "${unitBone}" under "${FACESHIFT_BONE}"; bind a head "unit" mesh only to "head" or bones and chains under "head"`,
3271
+ );
3272
+ return;
3273
+ }
3274
+ if (hasShared) return;
3275
+ rebindPartToCarrier(part, unitBone);
3276
+ };
3277
+
3278
+ for (const [part, role] of Object.entries(roles)) {
3279
+ if (role === 'unit') {
3280
+ if (cfg.regions[part] !== undefined) {
3281
+ const bName = regionBone(cfg.regions[part]);
3282
+ if (bName === 'head') {
3283
+ const sl = slotByName.get(part);
3284
+ if (sl !== undefined) sl.bone = FACESHIFT_BONE;
3285
+ } else {
3286
+ reparentFromHead(bName, FACESHIFT_BONE);
3287
+ }
3288
+ const st = stills[part];
3289
+ if (st !== undefined) reparentFromHead(st.bone, FACESHIFT_BONE);
3290
+ } else if (cfg.meshes[part] !== undefined) {
3291
+ rebindUnitMeshToHeadCarrier(part);
3292
+ }
3293
+ } else if (role === 'rear' && hasRear) {
3294
+ if (cfg.regions[part] !== undefined) {
3295
+ const bName = regionBone(cfg.regions[part]);
3296
+ if (bName === 'head') {
3297
+ const sl = slotByName.get(part);
3298
+ if (sl !== undefined) sl.bone = REAR_SHIFT_BONE;
3299
+ } else {
3300
+ reparentFromHead(bName, REAR_SHIFT_BONE);
3301
+ }
3302
+ } else if (cfg.meshes[part] !== undefined) {
3303
+ rebindPartToCarrier(part, REAR_SHIFT_BONE);
3184
3304
  }
3185
- } else if (cfg.meshes[part] !== undefined) {
3186
- rebindPartToCarrier(part, REAR_SHIFT_BONE);
3187
3305
  }
3188
3306
  }
3189
3307
  }
3308
+ }
3309
+
3310
+ if (cfg.turn.body !== undefined) {
3311
+ const bodySpec = cfg.turn.body;
3312
+ const bodyRoles = bodySpec.roles;
3313
+ const bodyRoot = bodySpec.bone ?? (bones.some((b) => b.name === 'chest') ? 'chest' : 'hip');
3314
+ const bodyIdx = bones.findIndex((b) => b.name === bodyRoot);
3315
+ if (bodyIdx === -1) {
3316
+ fail('RIG_TURN_HEAD_BONE', 'config.turn.body', `requires a declared "${bodyRoot}" bone in config.bones to parent the 2.5D body turn carriers`);
3317
+ } else {
3318
+ const bodyTransform = world.get(bodyRoot) as BoneTransform;
3319
+ const bodyTurnDeg = turn.get(bodyRoot) ?? 0;
3320
+ const surfBones: RigBone[] = [];
3321
+ const unitMeshBones: RigBone[] = [];
3322
+ for (const p of parts.parts) {
3323
+ if (bodyRoles[p.name] === 'unit' && cfg.meshes[p.name] !== undefined) {
3324
+ unitMeshBones.push({ name: turnUnitBone(p.name), parent: BODYSHIFT_BONE, x: 0, y: 0 });
3325
+ continue;
3326
+ }
3327
+ if (bodyRoles[p.name] !== 'surface') continue;
3328
+ const [cols, rows] = resolveTurnGrid(bodySpec, p.name, cfg.turn);
3329
+ totalGridTriangles += 2 * (cols - 1) * (rows - 1);
3330
+ const cx = p.x + p.w / 2;
3331
+ const cy = p.y + p.h / 2;
3332
+ const [lx, ly] = toBoneLocal(bodyTransform, spineX(cx), spineY(cy));
3333
+ const rot = places(normaliseDegrees(-bodyTurnDeg));
3334
+ surfBones.push({
3335
+ name: turnSurfaceBone(p.name),
3336
+ parent: BODYSHIFT_BONE,
3337
+ x: places(lx),
3338
+ y: places(ly),
3339
+ ...(rot === 0 ? {} : { rotation: rot }),
3340
+ });
3341
+ }
3342
+ const hasRear = Object.values(bodyRoles).includes('rear');
3343
+ const carriers: RigBone[] = [
3344
+ { name: BODYSHIFT_BONE, parent: bodyRoot, x: 0, y: 0 },
3345
+ ...(hasRear ? [{ name: BODY_REAR_SHIFT_BONE, parent: bodyRoot, x: 0, y: 0 }] : []),
3346
+ ...surfBones,
3347
+ ...unitMeshBones,
3348
+ ];
3349
+ bones.splice(bodyIdx + 1, 0, ...carriers);
3350
+ const bodyDialBone = bodySpec.slider ?? BODY_YAW_DIAL_BONE;
3351
+ if (!bones.some((b) => b.name === bodyDialBone)) {
3352
+ bones.push({ name: bodyDialBone, parent: ROOT_BONE, x: 0, y: 0 });
3353
+ }
3354
+
3355
+ const boneByName = new Map(bones.map((b) => [b.name, b]));
3356
+ const bodyCarriers = new Set<string>(carriers.map((b) => b.name));
3357
+ const assertNotBodyTurnCarrier = (boneName: string, targetParent: string): void => {
3358
+ if (bodyCarriers.has(boneName)) {
3359
+ throw new Error(`turn invariant violated: turn carrier "${boneName}" must never be reparented (target "${targetParent}")`);
3360
+ }
3361
+ };
3362
+ const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip', `${bodyRoot}${CONTROL_SUFFIX}`, `chest${CONTROL_SUFFIX}`, `hip${CONTROL_SUFFIX}`]);
3363
+ const headExclusion = new Set<string>(['head', `head${CONTROL_SUFFIX}`, 'neck', `neck${CONTROL_SUFFIX}`, FACESHIFT_BONE, REAR_SHIFT_BONE]);
3364
+ const reparentFromTorso = (boneName: string, targetParent: string): void => {
3365
+ assertNotBodyTurnCarrier(boneName, targetParent);
3366
+ if (torsoRoots.has(boneName) || headExclusion.has(boneName)) return;
3367
+ let cur = boneByName.get(boneName);
3368
+ while (
3369
+ cur !== undefined &&
3370
+ cur.parent !== undefined &&
3371
+ !torsoRoots.has(cur.parent) &&
3372
+ !bodyCarriers.has(cur.parent) &&
3373
+ !headExclusion.has(cur.parent)
3374
+ ) {
3375
+ cur = boneByName.get(cur.parent);
3376
+ }
3377
+ if (cur !== undefined && cur.parent !== undefined && torsoRoots.has(cur.parent) && !torsoRoots.has(cur.name) && !headExclusion.has(cur.name)) {
3378
+ assertNotBodyTurnCarrier(cur.name, targetParent);
3379
+ const oldParent = cur.parent;
3380
+ if (oldParent !== bodyRoot) {
3381
+ const oldTr = world.get(oldParent);
3382
+ if (oldTr !== undefined) {
3383
+ const [wx, wy] = toWorld(oldTr, cur.x, cur.y);
3384
+ const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3385
+ cur.x = places(lx);
3386
+ cur.y = places(ly);
3387
+ }
3388
+ }
3389
+ cur.parent = targetParent;
3390
+ }
3391
+ };
3392
+ const rebindBodyPartToCarrier = (part: string, carrierBone: string): void => {
3393
+ const sl = slotByName.get(part);
3394
+ if (sl !== undefined && torsoRoots.has(sl.bone)) sl.bone = carrierBone;
3395
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3396
+ if (stillSl !== undefined) {
3397
+ if (torsoRoots.has(stillSl.bone)) stillSl.bone = carrierBone;
3398
+ else reparentFromTorso(stillSl.bone, carrierBone);
3399
+ }
3400
+ for (const slotEntry of finalSlots) {
3401
+ if (slotEntry.name !== part && !slotEntry.name.startsWith(`${part}__island`)) continue;
3402
+ if (torsoRoots.has(slotEntry.bone)) slotEntry.bone = carrierBone;
3403
+ const atts = skin[slotEntry.name] ?? {};
3404
+ for (const att of Object.values(atts)) {
3405
+ if (!('type' in att) || att.weights === undefined) continue;
3406
+ for (const row of att.weights) {
3407
+ for (const w of row) {
3408
+ if (torsoRoots.has(w.bone)) {
3409
+ if (w.bone !== bodyRoot) {
3410
+ const oldTr = world.get(w.bone);
3411
+ if (oldTr !== undefined) {
3412
+ const [wx, wy] = toWorld(oldTr, w.x, w.y);
3413
+ const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3414
+ w.x = places(lx);
3415
+ w.y = places(ly);
3416
+ }
3417
+ }
3418
+ w.bone = carrierBone;
3419
+ } else {
3420
+ reparentFromTorso(w.bone, carrierBone);
3421
+ }
3422
+ }
3423
+ }
3424
+ }
3425
+ }
3426
+ };
3427
+
3428
+ const bodyUnitRootOwner = new Map<string, { part: string; bone: string; rootLabel: string }>();
3429
+ const rebindBodyUnitMeshToCarrier = (part: string): void => {
3430
+ const unitBone = turnUnitBone(part);
3431
+ const bound: string[] = [];
3432
+ const addBound = (bName: string): void => {
3433
+ if (!bound.includes(bName)) bound.push(bName);
3434
+ };
3435
+ for (const sl of finalSlots) {
3436
+ if (sl.name !== part && !sl.name.startsWith(`${part}__island`)) continue;
3437
+ const atts = skin[sl.name] ?? {};
3438
+ let hasWeights = false;
3439
+ for (const att of Object.values(atts)) {
3440
+ if ('type' in att && att.weights !== undefined && att.weights.length > 0) {
3441
+ hasWeights = true;
3442
+ for (const row of att.weights) {
3443
+ for (const w of row) addBound(w.bone);
3444
+ }
3445
+ }
3446
+ }
3447
+ if (!hasWeights) addBound(sl.bone);
3448
+ }
3449
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3450
+ if (stillSl !== undefined) addBound(stillSl.bone);
3451
+ const uncarried: string[] = [];
3452
+ const sharedRoots = new Set<string>();
3453
+ let hasShared = false;
3454
+ for (const bName of bound) {
3455
+ if (headExclusion.has(bName)) {
3456
+ uncarried.push(bName);
3457
+ continue;
3458
+ }
3459
+ if (torsoRoots.has(bName) || bName === unitBone) continue;
3460
+ let cur = boneByName.get(bName);
3461
+ while (
3462
+ cur !== undefined &&
3463
+ cur.parent !== undefined &&
3464
+ !torsoRoots.has(cur.parent) &&
3465
+ !bodyCarriers.has(cur.parent) &&
3466
+ !headExclusion.has(cur.parent)
3467
+ ) {
3468
+ cur = boneByName.get(cur.parent);
3469
+ }
3470
+ if (
3471
+ cur === undefined ||
3472
+ cur.parent === undefined ||
3473
+ (!torsoRoots.has(cur.parent) && !bodyCarriers.has(cur.parent)) ||
3474
+ torsoRoots.has(cur.name) ||
3475
+ headExclusion.has(cur.name) ||
3476
+ bodyCarriers.has(cur.name)
3477
+ ) {
3478
+ uncarried.push(bName);
3479
+ continue;
3480
+ }
3481
+ const rootLabel = cur.name.endsWith(CONTROL_SUFFIX) ? cur.name.slice(0, -CONTROL_SUFFIX.length) : cur.name;
3482
+ const owner = bodyUnitRootOwner.get(cur.name);
3483
+ if (owner !== undefined && owner.part !== part) {
3484
+ hasShared = true;
3485
+ if (!sharedRoots.has(cur.name)) {
3486
+ sharedRoots.add(cur.name);
3487
+ const sharedDetail =
3488
+ owner.bone === bName
3489
+ ? `bone "${bName}"${bName === owner.rootLabel ? '' : ` (under "${owner.rootLabel}")`}`
3490
+ : `chain root "${owner.rootLabel}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${bName}")`;
3491
+ fail(
3492
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3493
+ `config.turn.body.roles.${part}`,
3494
+ `declares "${part}" as "unit", and config.meshes.${part} shares ${sharedDetail} with "unit" mesh "${owner.part}" (config.turn.body.roles.${owner.part}); each "unit" mesh reparents its bound chain root under its own "<part>_unit" carrier, so two "unit" meshes cannot share a bone or chain under "${bodyRoot}"`,
3495
+ );
3496
+ }
3497
+ } else if (owner === undefined) {
3498
+ bodyUnitRootOwner.set(cur.name, { part, bone: bName, rootLabel });
3499
+ }
3500
+ }
3501
+ if (uncarried.length > 0) {
3502
+ fail(
3503
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3504
+ `config.turn.body.roles.${part}`,
3505
+ `declares "${part}" as "unit", and config.meshes.${part} binds bone(s) ${uncarried.map((b) => `"${b}"`).join(', ')} outside the "${bodyRoot}" torso subtree, which cannot be carried by "${unitBone}" under "${BODYSHIFT_BONE}"; bind a body "unit" mesh only to the torso root or bones and chains under it`,
3506
+ );
3507
+ return;
3508
+ }
3509
+ if (hasShared) return;
3510
+ rebindBodyPartToCarrier(part, unitBone);
3511
+ };
3190
3512
 
3191
- let meshSlots = 0;
3192
- let meshTriangles = 0;
3193
- for (const atts of Object.values(skin)) {
3194
- let slotHasMesh = false;
3195
- for (const att of Object.values(atts)) {
3196
- if (!('type' in att)) continue;
3197
- slotHasMesh = true;
3198
- const tris =
3199
- att.generator?.kind === 'grid'
3200
- ? 2 * (att.generator.cols - 1) * (att.generator.rows - 1)
3201
- : (att.triangles?.length ?? 0) / 3;
3202
- if (tris > meshTriangles) meshTriangles = tris;
3513
+ for (const [part, role] of Object.entries(bodyRoles)) {
3514
+ if (role === 'unit') {
3515
+ if (cfg.regions[part] !== undefined) {
3516
+ const bName = regionBone(cfg.regions[part]);
3517
+ if (torsoRoots.has(bName)) {
3518
+ const sl = slotByName.get(part);
3519
+ if (sl !== undefined) sl.bone = BODYSHIFT_BONE;
3520
+ if (bName !== bodyRoot) {
3521
+ const oldTr = world.get(bName);
3522
+ if (oldTr !== undefined) {
3523
+ for (const att of Object.values(skin[part] ?? {})) {
3524
+ if (!('type' in att)) {
3525
+ const [wx, wy] = toWorld(oldTr, att.x, att.y);
3526
+ const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3527
+ att.x = places(lx);
3528
+ att.y = places(ly);
3529
+ }
3530
+ }
3531
+ }
3532
+ }
3533
+ } else {
3534
+ reparentFromTorso(bName, BODYSHIFT_BONE);
3535
+ }
3536
+ const st = stills[part];
3537
+ if (st !== undefined) reparentFromTorso(st.bone, BODYSHIFT_BONE);
3538
+ } else if (cfg.meshes[part] !== undefined) {
3539
+ rebindBodyUnitMeshToCarrier(part);
3540
+ }
3541
+ } else if (role === 'rear' && hasRear) {
3542
+ if (cfg.regions[part] !== undefined) {
3543
+ const bName = regionBone(cfg.regions[part]);
3544
+ if (torsoRoots.has(bName)) {
3545
+ const sl = slotByName.get(part);
3546
+ if (sl !== undefined) sl.bone = BODY_REAR_SHIFT_BONE;
3547
+ if (bName !== bodyRoot) {
3548
+ const oldTr = world.get(bName);
3549
+ if (oldTr !== undefined) {
3550
+ for (const att of Object.values(skin[part] ?? {})) {
3551
+ if (!('type' in att)) {
3552
+ const [wx, wy] = toWorld(oldTr, att.x, att.y);
3553
+ const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3554
+ att.x = places(lx);
3555
+ att.y = places(ly);
3556
+ }
3557
+ }
3558
+ }
3559
+ }
3560
+ } else {
3561
+ reparentFromTorso(bName, BODY_REAR_SHIFT_BONE);
3562
+ }
3563
+ } else if (cfg.meshes[part] !== undefined) {
3564
+ rebindBodyPartToCarrier(part, BODY_REAR_SHIFT_BONE);
3565
+ }
3566
+ }
3203
3567
  }
3204
- if (slotHasMesh) meshSlots++;
3205
3568
  }
3206
- generatedMeshBudget = { meshSlots, meshTriangles };
3207
3569
  }
3570
+
3571
+ if (cfg.turn.roles !== undefined || cfg.turn.body !== undefined) {
3572
+ bones.splice(0, bones.length, ...orderParentsFirst(new Map(bones.map((b) => [b.name, b]))));
3573
+ }
3574
+
3575
+ if (totalGridTriangles > TURN_GRID_MAX_TRIANGLES_TOTAL) {
3576
+ fail(
3577
+ 'RIG_TURN_GRID_BUDGET',
3578
+ 'config.turn.grid',
3579
+ `allocates ${totalGridTriangles} total grid triangles across surface slots, which exceeds the total budget of ${TURN_GRID_MAX_TRIANGLES_TOTAL} triangles`,
3580
+ );
3581
+ }
3582
+
3583
+ let meshSlots = 0;
3584
+ let meshTriangles = 0;
3585
+ for (const atts of Object.values(skin)) {
3586
+ let slotHasMesh = false;
3587
+ for (const att of Object.values(atts)) {
3588
+ if (!('type' in att)) continue;
3589
+ slotHasMesh = true;
3590
+ const tris =
3591
+ att.generator?.kind === 'grid'
3592
+ ? 2 * (att.generator.cols - 1) * (att.generator.rows - 1)
3593
+ : (att.triangles?.length ?? 0) / 3;
3594
+ if (tris > meshTriangles) meshTriangles = tris;
3595
+ }
3596
+ if (slotHasMesh) meshSlots++;
3597
+ }
3598
+ generatedMeshBudget = { meshSlots, meshTriangles };
3208
3599
  }
3209
3600
  // issue #536: every row names the bones the emitted attachment binds, read once the turn and the stops have
3210
3601
  // rebound the weights; a rig with neither rebinds nothing, so this reads back the names each row already holds.
@@ -3265,7 +3656,7 @@ export function buildWaistPairSource(
3265
3656
  for (const [bName, bEntry] of B) {
3266
3657
  boneLandmarks.set(bName, [bEntry.x, bEntry.y]);
3267
3658
  }
3268
- if (cfg.turn?.roles !== undefined) {
3659
+ if (cfg.turn?.roles !== undefined || cfg.turn?.body !== undefined) {
3269
3660
  buildDepth25DTurn(rig, motion, {
3270
3661
  turn: cfg.turn,
3271
3662
  parts: parts.parts,
@@ -3280,7 +3671,7 @@ export function buildWaistPairSource(
3280
3671
  if (cfg.waist !== undefined) refuseSharedWaistMotion(merged, cfg.waist.top, cfg.waist.bone);
3281
3672
  remapWaistDeforms(merged, waistTargets, waistRegionTargets, waistBindingsBeforeRebind);
3282
3673
  expandSetAttachmentKeys(rig, sets, merged);
3283
- if (cfg.turn?.roles !== undefined) {
3674
+ if (cfg.turn?.roles !== undefined || cfg.turn?.body !== undefined) {
3284
3675
  buildDepth25DTurn(rig, merged, {
3285
3676
  turn: cfg.turn,
3286
3677
  parts: parts.parts,
@@ -3290,7 +3681,8 @@ export function buildWaistPairSource(
3290
3681
  boneLandmarks,
3291
3682
  hasAlternateFaceSet,
3292
3683
  });
3293
- } else {
3684
+ }
3685
+ if (cfg.turn?.roles === undefined && (cfg.turn === undefined || cfg.turn.body === undefined || cfg.turn.depths !== undefined)) {
3294
3686
  applyFaceSurfaceDeform(rig, merged, {
3295
3687
  imageWidth: faceImg?.width,
3296
3688
  imageHeight: faceImg?.height,