@rig-c/parts 1.68.0 → 1.70.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/rig.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { baseAnchorProblems, orderedBaseAnchor, baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
1
2
  import { padDepthSheet, padTurnDepthSheet, depthSheetProblems, type PartDepthReference } from './depthsheets.ts';
2
3
  import { explicitBoneNames, explicitSlotBones, explicitWeightRows, regionBone } from './config.ts';
3
4
  import { explicitAttachment, type ExplicitMeshReport } from './explicitmesh.ts';
@@ -138,7 +139,7 @@ import { explicitAttachment, type ExplicitMeshReport } from './explicitmesh.ts';
138
139
  */
139
140
  import { type AutoSpec, type BoneEntry, type InfluenceMeshSpec, type WeightRule, type CharacterConfig, type ConfigConstraint, type ConfigStop, CONSTRAINT_FOLLOWS, constraintForRig, contourRegionsOf, type ContourSpec, DEFAULT_BUST_BONE_L, DEFAULT_BUST_BONE_R, type Point, type RibsSpec, ROOT_BONE, stopForRig, turnRidersByBone, weightsABone } from './config.ts';
140
141
  import { type BoneTransform, computeExactFrameTransforms, cropToSpineY, normaliseDegrees, paintingToSetupPoint, toBoneLocal, toWorld } from './coords.ts';
141
- import { type Problem, refuseIfAny } from './errors.ts';
142
+ import { type Problem, refuseIfAny, PartsError } from './errors.ts';
142
143
  import { recordedFocusProblems } from './setfocus.ts';
143
144
  import { eyeLineDegrees } from './headframe.ts';
144
145
  import type { RigBoneInherit, RigStop } from 'rig-c/src/rig.ts';
@@ -174,9 +175,12 @@ import { edgeLength } from './length.ts';
174
175
  import { skeletonLimbJoints } from './limbs.ts';
175
176
  import { coalesceLimbSlots } from './limbslots.ts';
176
177
  import { layoutAlias, placeLimbLayouts, type LayoutPlan } from './limblayout.ts';
177
- import { artCoverage, ART_ALPHA, latticeCells, latticeMesh, latticeStray, ONE_LOOP_PASSES } from './mesh.ts';
178
+ import { artCoverage, ART_ALPHA, latticeCells, latticeMesh, latticeStray, ONE_LOOP_PASSES, type LatticeMesh } from './mesh.ts';
178
179
  import { bindFaceSurfaceDeform, BLINK, blinkHoldMisses, blinkSpan, CONTROL_SUFFIX, controlledBones, IDLE_FPS, idleMotion, type MotionSpec, moveKeysToControls } from './motion.ts';
179
180
  import { type PartRecord, type AlternateSetMap, FRONT_SUFFIX, PAINTING_RUN, type PartsFile, readFrom, tagOf } from './parts.ts';
181
+ import { waistPairs, waistBand, waistInfluences } from './waist.ts';
182
+ import { preserveWaistRest, refineWaistMesh, remapWaistDeforms, storedWorld, waistBottomMesh, waistBottomLayoutOf, type WaistMapping } from './waistmesh.ts';
183
+ import { pivotWaistMesh, sharedWaistCopy, type WaistPivotRequest } from './waistmesh.ts';
180
184
  import { readTag } from './tags.ts';
181
185
  import { EYE_GROUP_TAGS } from './propose.ts';
182
186
  import { alphaAbove, crop, pad, type Raster } from './raster/index.ts';
@@ -1286,7 +1290,7 @@ function limbBandShares(p: PartRecord, point: Point): Influence[] | null {
1286
1290
  return [{ bone: h.upper, weight: 1 - lower }, { bone: (p.limb as NonNullable<typeof p.limb>).bone, weight: lower }].filter((q) => q.weight > 0);
1287
1291
  }
1288
1292
 
1289
- export function buildRig(
1293
+ export function buildWaistPairSource(
1290
1294
  cfg: CharacterConfig,
1291
1295
  parts: PartsFile,
1292
1296
  images: ReadonlyMap<string, Raster>,
@@ -1321,11 +1325,27 @@ export function buildRig(
1321
1325
  const CX = W / 2;
1322
1326
  const byPart = new Map(parts.parts.map((p) => [p.name, p]));
1323
1327
 
1328
+ const configuredAlts = cfg.assemble.alternates ?? cfg.alternates ?? [];
1329
+ const anchorRegions = new Set(Object.keys(cfg.regions).filter(n => !(n in cfg.meshes)));
1330
+ for (const a of configuredAlts) {
1331
+ if (a.base_anchor === undefined) continue;
1332
+ const covered = new Set((a.parts ?? parts.parts.map(p => p.name)).filter(n => !(a.hides ?? []).includes(n)));
1333
+ problems.push(...baseAnchorProblems(a.base_anchor, `config alternate set "${a.name}".base_anchor`, covered, new Set((cfg.assemble.patches ?? []).map(p => p.name)), anchorRegions, 'RIG_ALT_BASE_ANCHOR'));
1334
+ }
1335
+ for (const a of parts.alternates ?? []) {
1336
+ if (a.base_anchor !== undefined) problems.push(...baseAnchorProblems(a.base_anchor, `parts.json alternate set "${a.name}".base_anchor`, new Set(a.records.map(p => p.name)), new Set(a.records.filter(p => p.from.startsWith('painting:')).map(p => p.name)), anchorRegions, 'RIG_ALT_BASE_ANCHOR'));
1337
+ }
1338
+ // Direct callers need the same shape checks as serialized readers. Collect
1339
+ // both sides before any canonical ordering can inspect their axes or pairs.
1340
+ refuseIfAny(problems);
1324
1341
  for (const a of parts.alternates ?? []) {
1342
+ const configured = configuredAlts.find(c => c.name === a.name)?.base_anchor;
1343
+ if (JSON.stringify(configured === undefined ? null : orderedBaseAnchor(configured)) !== JSON.stringify(a.base_anchor === undefined ? null : orderedBaseAnchor(a.base_anchor))) fail('RIG_ALT_BASE_ANCHOR_MATCH_CONFIG', `alternate set "${a.name}" base_anchor`, 'config and parts.json declare different base anchors; re-run assemble before rig');
1325
1344
  problems.push(...recordedFocusProblems(a, `parts.json alternate set "${a.name}".focus`, parts.rig_size, parts.scale_rig_per_source));
1326
1345
  }
1327
1346
  for (const a of cfg.assemble.alternates ?? cfg.alternates ?? []) {
1328
1347
  const record = parts.alternates?.find((p) => p.name === a.name);
1348
+ if (a.base_anchor !== undefined && record === undefined) fail('RIG_ALT_BASE_ANCHOR_MATCH_CONFIG', `alternate set "${a.name}" base_anchor`, 'has no assembled set; re-run assemble before rig');
1329
1349
  if ((a.focus !== undefined || record?.focus !== undefined)
1330
1350
  && JSON.stringify(a.focus) !== JSON.stringify(record?.focus)) {
1331
1351
  fail('CONFIG_SET_FOCUS', `config.assemble alternate set "${a.name}".focus`, 'does not match the assembled painting point; re-run assemble after changing or removing focus');
@@ -1868,6 +1888,18 @@ export function buildRig(
1868
1888
 
1869
1889
  const loopPasses: Record<string, number> = {};
1870
1890
  const autoMotion: AutoMotionCase[] = [];
1891
+ const waistTargets = new Map<string, WaistMapping>();
1892
+ const waistLayouts = new Map<string, { slot: string; lm: LatticeMesh; origin: [number, number] }>();
1893
+ const waistRegions = new Map<string, { slot: string; region: RegionAttachment; origin: [number, number]; size: [number, number]; bones: RigBone[] }>();
1894
+ const waistOld = (lm: LatticeMesh, file: string, w: number, h: number, ox: number, oy: number, segsAt: (y: number) => readonly Segment[], r: number, limits: InfluenceLimits, exponent: number, frames: ReadonlyMap<string, BoneTransform>): MeshAttachment => ({
1895
+ type: 'mesh', image: file, width: w, height: h, triangles: lm.triangles, hull: lm.hull,
1896
+ uvs: lm.vertices.flatMap(([x, y]) => [pyRound(x / w, 6), pyRound(y / h, 6)]),
1897
+ weights: lm.vertices.map(([x, y]) => {
1898
+ const shares = influences([x + ox, y + oy], segsAt(y + oy), r, limits, exponent);
1899
+ const rounded = limits.floor === 'continuous' ? roundShares(shares) : latticeShares(shares);
1900
+ return rounded.map(({ bone, weight }) => { const p = toBoneLocal(frames.get(bone) as BoneTransform, spineX(x + ox), spineY(y + oy)); return { bone, x: places(p[0]), y: places(p[1]), weight }; });
1901
+ }),
1902
+ });
1871
1903
  // A region's centre in its bone's setup frame; on a turned bone the image
1872
1904
  // is turned back by the bone's world rotation, so it is drawn upright.
1873
1905
  const region = (image: string, bone: string, cx: number, cy: number): RegionAttachment => {
@@ -1912,6 +1944,9 @@ export function buildRig(
1912
1944
  if (torso.length === 0) return () => segs;
1913
1945
  return (wy: number): Segment[] => (wy < hipBone.y ? torso : segs);
1914
1946
  };
1947
+ const waist = cfg.waist === undefined ? { pairs: new Map<string, import('./waist.ts').WaistPair>(), problems: [] } : waistPairs(parts.parts.filter((p) => p.name === cfg.waist!.top || p.name === cfg.waist!.bottom), cfg, meshSegments, B);
1948
+ problems.push(...waist.problems);
1949
+ refuseIfAny(problems);
1915
1950
  // A contour mesh (issue #84): `src/contour.ts` over the padded image, every refusal collected with the others;
1916
1951
  // the weights by `src/localweights.ts`; slot, uvs, bind positions and by-name weights written as the lattice's.
1917
1952
  // The config's region numbers are rig px; the part image's are rig px less (p.x − PAD, p.y − PAD) — a
@@ -2445,12 +2480,14 @@ export function buildRig(
2445
2480
  const cyLow = st.row + (p.h - r) / 2;
2446
2481
  const cyUp = p.y + r / 2;
2447
2482
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cyLow) };
2483
+ waistRegions.set(p.name, { slot: p.name, region: skin[p.name][p.name] as RegionAttachment, origin: [p.x - PAD, st.row - PAD], size: [lower.width, lower.height], bones });
2448
2484
  skin[still] = { [still]: region(stillFile, sb.name, cx, cyUp) };
2449
2485
  addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name }, { name: still, bone: sb.name, attachment: still });
2450
2486
  continue;
2451
2487
  }
2452
2488
  const cy = p.y + p.h / 2;
2453
2489
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cy) };
2490
+ waistRegions.set(p.name, { slot: p.name, region: skin[p.name][p.name] as RegionAttachment, origin: [p.x - PAD, p.y - PAD], size: [img.width, img.height], bones });
2454
2491
  addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name });
2455
2492
  continue;
2456
2493
  }
@@ -2504,14 +2541,18 @@ export function buildRig(
2504
2541
  // silhouette are built over; absent, `art` is `allArt` itself and nothing downstream moves.
2505
2542
  const stray = mesh.stray === undefined ? null : latticeStray(allArt, mesh.stray);
2506
2543
  const art = stray === null ? allArt : stray.art;
2507
- const lm = latticeMesh(p.name, art, mesh.grid, maxLoopPasses);
2544
+ const ox = p.x - PAD;
2545
+ const oy = p.y - PAD;
2546
+ const pair = waist.pairs.get(p.name);
2547
+ const band = pair === undefined ? null : waistBand(pair, art, (B.get(pair.upper) as Bone).y - oy);
2548
+ if (band !== null && 'code' in band) { problems.push(band); continue; }
2549
+ const originalLm = latticeMesh(p.name, art, mesh.grid, maxLoopPasses);
2550
+ const lm = band === null || 'code' in originalLm ? originalLm : refineWaistMesh(originalLm, [band.anchor, band.plateau, band.hem]);
2508
2551
  if ('code' in lm) {
2509
2552
  problems.push(lm);
2510
2553
  continue;
2511
2554
  }
2512
2555
  loopPasses[p.name] = lm.passes;
2513
- const ox = p.x - PAD;
2514
- const oy = p.y - PAD;
2515
2556
  // issue #161: under rule "heat", the field over the lattice's art (alpha above 8) with its holes filled.
2516
2557
  // issue #303: an island no bone reaches is worded against the lattice's own `stray` when it is dust.
2517
2558
  const dust = (): HeatDust => {
@@ -2539,7 +2580,8 @@ export function buildRig(
2539
2580
  const wy = vy0 + oy;
2540
2581
  const vSegs = segsAt(wy);
2541
2582
  const hybrid = limbBandShares(p, [wx, wy]);
2542
- const shares = hybrid ?? (heat === null ? influences([wx, wy], vSegs, mesh.r, limits, mesh.exponent ?? DISTANCE_EXPONENT) : heatInfluences(heat, [vx0, vy0], limits));
2583
+ const shares = hybrid ?? (band !== null ? waistInfluences([wx, wy], vy0, band, vSegs, mesh.r, limits, mesh.exponent ?? DISTANCE_EXPONENT) : heat === null ? influences([wx, wy], vSegs, mesh.r, limits, mesh.exponent ?? DISTANCE_EXPONENT) : heatInfluences(heat, [vx0, vy0], limits));
2584
+ if ('code' in shares) { problems.push(shares); continue; }
2543
2585
  if (shares.length === 0) {
2544
2586
  // issue #284: a declared cut that keeps no bone (nothingKeptProblem says when that can be).
2545
2587
  if (emptied === null) emptied = { vertex: vi, at: [wx, wy], capped: heat === null ? influences([wx, wy], vSegs, mesh.r, { maxInfluences: limits.maxInfluences, minWeight: 0 }, mesh.exponent ?? DISTANCE_EXPONENT) : heatInfluences(heat, [vx0, vy0], { maxInfluences: limits.maxInfluences, minWeight: 0 }) };
@@ -2552,6 +2594,7 @@ export function buildRig(
2552
2594
  problems.push(nothingKeptProblem(p.name, limits.floor, emptied, emptiedMore));
2553
2595
  continue;
2554
2596
  }
2597
+ if (rawShares.length !== lm.vertices.length) continue; // named waist binding problems already collected
2555
2598
  const allChainLinks = new Set([...chains.values()].flat());
2556
2599
  const forkCounts = new Map<string, number>();
2557
2600
  for (const sp of mesh.segments) {
@@ -2560,7 +2603,7 @@ export function buildRig(
2560
2603
  const par = links !== undefined && links.length > 0 ? (B.get(links[0])?.parent ?? null) : null;
2561
2604
  if (par !== null && allChainLinks.has(par)) forkCounts.set(par, (forkCounts.get(par) ?? 0) + 1);
2562
2605
  }
2563
- const heldFork = heat === null && mesh.r >= mesh.grid && mesh.influences === undefined && [...forkCounts.values()].some((c) => c >= 2);
2606
+ const heldFork = band === null && heat === null && mesh.r >= mesh.grid && mesh.influences === undefined && [...forkCounts.values()].some((c) => c >= 2);
2564
2607
  const finalShares = heldFork ? smoothForkShares(rawShares, lm.triangles) : rawShares;
2565
2608
  for (const [vi, [vx0, vy0]] of lm.vertices.entries()) {
2566
2609
  const wx = vx0 + ox;
@@ -2576,6 +2619,12 @@ export function buildRig(
2576
2619
  const uvs: number[] = [];
2577
2620
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2578
2621
  skin[p.name] = { [p.name]: { type: 'mesh', image: file, width: w, height: h, uvs, triangles: lm.triangles, hull: lm.hull, weights } };
2622
+ if (band !== null && !('code' in originalLm)) {
2623
+ const att = skin[p.name][p.name] as MeshAttachment;
2624
+ const old = waistOld(originalLm, file, w, h, ox, oy, segsAt, mesh.r, limits, mesh.exponent ?? DISTANCE_EXPONENT, world);
2625
+ waistTargets.set(`default/${p.name}/${p.name}`, preserveWaistRest(old, originalLm, att, lm, storedWorld(bones), band.anchor));
2626
+ waistLayouts.set(p.name, { slot: p.name, lm, origin: [ox, oy] });
2627
+ }
2579
2628
  addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2580
2629
  meshReport.push({
2581
2630
  part: p.name,
@@ -2746,6 +2795,7 @@ export function buildRig(
2746
2795
  if (mesh === undefined) {
2747
2796
  const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
2748
2797
  skin[skinSlot][attName] = altRegion(file, bone.name, p.x + p.w / 2, p.y + p.h / 2);
2798
+ waistRegions.set(attName, { slot: skinSlot, region: skin[skinSlot][attName] as RegionAttachment, origin: [p.x - PAD, p.y - PAD], size: [img.width, img.height], bones: posedBones ?? bones });
2749
2799
  continue;
2750
2800
  }
2751
2801
  if ('explicit' in mesh) {
@@ -2757,7 +2807,8 @@ export function buildRig(
2757
2807
  const baseAtt = skin[p.name]?.[p.name];
2758
2808
  const baseBones = baseAtt !== undefined && 'type' in baseAtt ? new Set((baseAtt.weights ?? []).flatMap((v) => v.map((e) => e.bone))) : null;
2759
2809
  const filteredSegs = baseBones !== null && baseBones.size > 0 ? fullSegs.filter((s) => baseBones.has(s.bone)) : fullSegs;
2760
- let segs = filteredSegs.length > 0 ? filteredSegs : fullSegs;
2810
+ let segs = waist.pairs.has(p.name) ? fullSegs : filteredSegs.length > 0 ? filteredSegs : fullSegs;
2811
+ let waistSegs = segs;
2761
2812
  if (drawn !== undefined) {
2762
2813
  const movePt = (bone: string, pt0: Point): Point => {
2763
2814
  const m0 = world.get(bone) as BoneTransform;
@@ -2785,6 +2836,7 @@ export function buildRig(
2785
2836
  return explicit || end === undefined ? s : { ...s, b: [end[0], end[1]] };
2786
2837
  });
2787
2838
  }
2839
+ waistSegs = segs;
2788
2840
  // Select against final endpoints, retaining each original entry's
2789
2841
  // tuple/named provenance through the preceding pose and base filters.
2790
2842
  if (drawn !== undefined) {
@@ -2799,20 +2851,26 @@ export function buildRig(
2799
2851
  const art = stray === null ? allArt : stray.art;
2800
2852
  const grid = 'grid' in mesh ? mesh.grid : 28;
2801
2853
  const r = 'r' in mesh ? mesh.r : 80;
2802
- const lm = latticeMesh(attName, art, grid, maxLoopPasses);
2854
+ const ox = p.x - PAD;
2855
+ const oy = p.y - PAD;
2856
+ const pair = waist.pairs.get(p.name);
2857
+ const band = pair === undefined ? null : waistBand(pair, art, cropToSpineY((altWorld.get(pair.upper) as BoneTransform).worldY, H) - oy);
2858
+ if (band !== null && 'code' in band) { problems.push(band); continue; }
2859
+ if (band !== null) segs = waistSegs;
2860
+ const originalLm = latticeMesh(attName, art, grid, maxLoopPasses);
2861
+ const lm = band === null || 'code' in originalLm ? originalLm : refineWaistMesh(originalLm, [band.anchor, band.plateau, band.hem]);
2803
2862
  if ('code' in lm) {
2863
+ if (band !== null) { problems.push(lm); continue; }
2804
2864
  skin[skinSlot][attName] = altRegion(file, segs[0].bone, p.x + p.w / 2, p.y + p.h / 2);
2805
2865
  continue;
2806
2866
  }
2807
- const ox = p.x - PAD;
2808
- const oy = p.y - PAD;
2809
2867
  const w = img.width;
2810
2868
  const h = img.height;
2811
2869
  const limits: InfluenceLimits = meshLimits('influences' in mesh ? mesh.influences : undefined);
2812
2870
  const segsAt = dressSegsAt(p, segs);
2813
2871
  const exponent = ('exponent' in mesh ? mesh.exponent : undefined) ?? DISTANCE_EXPONENT;
2814
2872
  let touchesArt: boolean[] | null = null;
2815
- if (drawn !== undefined && limits.maxInfluences === 1) {
2873
+ if (band === null && drawn !== undefined && limits.maxInfluences === 1) {
2816
2874
  const lc = latticeCells(art, grid);
2817
2875
  touchesArt = lm.vertices.map(([vx0, vy0]) => {
2818
2876
  const ii = Math.round(vx0 / grid);
@@ -2833,12 +2891,14 @@ export function buildRig(
2833
2891
  const wy = vy0 + oy;
2834
2892
  const vSegs = segsAt(wy);
2835
2893
  const hybrid = limbBandShares(p, [wx, wy]);
2836
- let shares = hybrid ?? influences([wx, wy], vSegs, r, limits, exponent);
2837
- if (shares.length === 0) {
2894
+ let shares = hybrid ?? (band === null ? influences([wx, wy], vSegs, r, limits, exponent) : waistInfluences([wx, wy], vy0, band, vSegs, r, limits, exponent));
2895
+ if ('code' in shares) { problems.push(shares); continue; }
2896
+ if (shares.length === 0 && band === null) {
2838
2897
  shares = influences([wx, wy], vSegs, Infinity, { maxInfluences: 1, minWeight: 0 }, exponent);
2839
2898
  }
2840
2899
  rawShares.push(hybrid !== null || limits.floor === 'continuous' ? roundShares(shares) : latticeShares(shares));
2841
2900
  }
2901
+ if (rawShares.length !== lm.vertices.length) continue;
2842
2902
  if (touchesArt !== null) {
2843
2903
  let firstArtBone: string | null = null;
2844
2904
  for (let vi = 0; vi < lm.vertices.length; vi++) {
@@ -2866,6 +2926,28 @@ export function buildRig(
2866
2926
  const uvs: number[] = [];
2867
2927
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2868
2928
  skin[skinSlot][attName] = { type: 'mesh', image: file, width: w, height: h, uvs, triangles: lm.triangles, hull: lm.hull, weights };
2929
+ if (band !== null && !('code' in originalLm)) {
2930
+ const att = skin[skinSlot][attName] as MeshAttachment;
2931
+ const old = waistOld(originalLm, file, w, h, ox, oy, segsAt, r, limits, exponent, altWorld);
2932
+ waistTargets.set(`default/${skinSlot}/${attName}`, preserveWaistRest(old, originalLm, att, lm, storedWorld(posedBones ?? bones), band.anchor));
2933
+ waistLayouts.set(attName, { slot: skinSlot, lm, origin: [ox, oy] });
2934
+ }
2935
+ }
2936
+ if (alt.base_anchor !== undefined) {
2937
+ const baseRegions = new Map<string, AnchorRegion>(), altRegions = new Map<string, AnchorRegion>();
2938
+ for (const p of alt.records) {
2939
+ if (cfg.meshes[p.name] !== undefined || cfg.regions[p.name] === undefined) continue;
2940
+ const bone = regionBone(cfg.regions[p.name]), slot = altFront.has(p.name) ? `${p.name}${FRONT_SUFFIX}` : p.name;
2941
+ const original = skin[p.name]?.[p.name], art = skin[slot]?.[`${alt.name}_${p.name}`];
2942
+ if (original !== undefined && !('type' in original)) baseRegions.set(p.name, { bone, x: original.x, y: original.y });
2943
+ if (art !== undefined && !('type' in art)) altRegions.set(p.name, { bone, x: art.x, y: art.y });
2944
+ }
2945
+ const moves = baseAnchorMoves(alt.base_anchor, baseRegions, altRegions, altWorld);
2946
+ for (const [name, move] of moves) {
2947
+ const slot = altFront.has(name) ? `${name}${FRONT_SUFFIX}` : name;
2948
+ const attachment = skin[slot][`${alt.name}_${name}`] as RegionAttachment;
2949
+ skin[slot][`${alt.name}_${name}`] = { ...attachment, x: places(attachment.x + move.local[0]), y: places(attachment.y + move.local[1]) };
2950
+ }
2869
2951
  }
2870
2952
  const slotMap: Record<string, string> = {};
2871
2953
  for (const [slotName, att] of Object.entries(alt.slots)) slotMap[slotName] = att;
@@ -2882,6 +2964,7 @@ export function buildRig(
2882
2964
  const coversFace = Object.hasOwn(slotMap, 'face');
2883
2965
  setEntries[alt.name] = {
2884
2966
  slots: slotMap,
2967
+ ...(alt.base_anchor === undefined ? {} : { base_anchor: orderedBaseAnchor(alt.base_anchor) }),
2885
2968
  ...(alt.focus === undefined ? {} : { focus: paintingToSetupPoint(alt.focus, alt.focus_source_size as [number, number], parts.rig_size) }),
2886
2969
  ...(hideList.length > 0 ? { hides: hideList } : {}),
2887
2970
  ...(drawn === undefined ? {} : { drawn }),
@@ -2897,6 +2980,51 @@ export function buildRig(
2897
2980
  sets: setEntries,
2898
2981
  };
2899
2982
  }
2983
+ refuseIfAny(problems);
2984
+ // The bottom follows the explicitly selected top attachment, including subset/alternate sets.
2985
+ // Derived attachment names are local to the existing slot/set contract, never a new config field.
2986
+ const waistRegionTargets = new Set<string>();
2987
+ const freeAttachment = (slot: string, prefix: string): string => { let n = prefix; while (skin[slot][n] !== undefined) n += '_'; return n; };
2988
+ for (const pair of waist.pairs.values()) {
2989
+ const convert = (topSlot: string, topName: string, bottomSlot: string, bottomName: string, destination: string): void => {
2990
+ const layout = waistLayouts.get(topName), source = waistRegions.get(bottomName);
2991
+ if (layout === undefined || source === undefined || layout.slot !== topSlot || source.slot !== bottomSlot) { fail('RIG_WAIST_SET_BINDING', `pair "${pair.top}"/"${pair.bottom}"`, `attachments "${topName}"/"${bottomName}" do not carry their declared mesh/region source geometry`); return; }
2992
+ const top = skin[topSlot][topName] as MeshAttachment;
2993
+ const bottom = waistBottomMesh(top, layout.lm, layout.origin, source.region, source.origin, source.size, pair.lower, source.bones);
2994
+ skin[bottomSlot][destination] = bottom;
2995
+ if (bottomSlot === pair.bottom && destination === pair.bottom) {
2996
+ const driver = cfg.meshes[pair.top];
2997
+ const image = outImages.find(([name])=> name === bottom.image)?.[1];
2998
+ const shape = waistBottomLayoutOf(bottom);
2999
+ if (driver !== undefined && 'grid' in driver && image !== undefined && shape !== undefined) meshReport.push({ part:pair.bottom,vertices:bottom.weights.length,triangles:bottom.triangles.length/3,hull:bottom.hull,bones:[...new Set(bottom.weights.flatMap((ws)=>ws.map((w)=>w.bone)))].sort(),max_influences:Math.max(...bottom.weights.map((ws)=>ws.length)),mean_influences:pyRound(bottom.weights.reduce((n,ws)=>n+ws.length,0)/bottom.weights.length,2),art_coverage:pyRound(artCoverage(shape,alphaAbove(image,ART_ALPHA)),5),grid:driver.grid });
3000
+ }
3001
+ waistRegionTargets.add(`default/${bottomSlot}/${destination}`);
3002
+ };
3003
+ convert(pair.top, pair.top, pair.bottom, pair.bottom, pair.bottom);
3004
+ for (const [setName, entry] of Object.entries(sets?.sets ?? {})) {
3005
+ const selected = (part: string): { slot: string; attachment: string } | null => {
3006
+ const front = `${part}${FRONT_SUFFIX}`;
3007
+ if (entry.slots[front] !== undefined && !entry.hides?.includes(front)) return { slot: front, attachment: entry.slots[front] };
3008
+ return entry.hides?.includes(part) ? null : { slot: part, attachment: entry.slots[part] ?? part };
3009
+ };
3010
+ const top = selected(pair.top), bottom = selected(pair.bottom);
3011
+ if (bottom === null) continue;
3012
+ if (top === null) {
3013
+ const source = waistRegions.get(bottom.attachment);
3014
+ if (source !== undefined) {
3015
+ const name = freeAttachment(bottom.slot, `${setName}_${pair.bottom}_rigid`);
3016
+ skin[bottom.slot][name] = source.region; entry.slots[bottom.slot] = name;
3017
+ }
3018
+ continue;
3019
+ }
3020
+ if (top.slot === pair.top && top.attachment === pair.top && bottom.slot === pair.bottom && bottom.attachment === pair.bottom) continue;
3021
+ const destination = bottom.attachment === pair.bottom ? freeAttachment(bottom.slot, `${setName}_${pair.bottom}_waist`) : bottom.attachment;
3022
+ convert(top.slot, top.attachment, bottom.slot, bottom.attachment, destination);
3023
+ entry.slots[bottom.slot] = destination;
3024
+ }
3025
+ }
3026
+ refuseIfAny(problems);
3027
+ const waistBindingsBeforeRebind = new Map([...waistTargets].map(([name, map]) => [name, JSON.stringify(map.current.weights)]));
2900
3028
  const hasAlternateFaceSet = sets !== undefined && Object.values(sets.sets).some((e) => Object.hasOwn(e.slots, 'face'));
2901
3029
  // Read every base/alternate binding before rebinds; publish only the slot
2902
3030
  // permutation below, after stops/turn have used the original enumeration.
@@ -3149,6 +3277,8 @@ export function buildRig(
3149
3277
  });
3150
3278
  }
3151
3279
  bindFaceSurfaceDeform(motion, (merged) => {
3280
+ if (cfg.waist !== undefined) refuseSharedWaistMotion(merged, cfg.waist.top, cfg.waist.bone);
3281
+ remapWaistDeforms(merged, waistTargets, waistRegionTargets, waistBindingsBeforeRebind);
3152
3282
  expandSetAttachmentKeys(rig, sets, merged);
3153
3283
  if (cfg.turn?.roles !== undefined) {
3154
3284
  buildDepth25DTurn(rig, merged, {
@@ -3588,3 +3718,70 @@ export function flattenRig(rig: RigSpec, sense: 1 | -1 = 1): RigSpec {
3588
3718
  }
3589
3719
  return flat;
3590
3720
  }
3721
+
3722
+ /** Explicit candidate stage: preserve the ordinary builder and all original topwear bytes. */
3723
+ export function withWaistPivot(output: RigOutput, request: WaistPivotRequest): RigOutput {
3724
+ const old = output.rig.skins.default[request.bottom]?.[request.bottom];
3725
+ const top = output.rig.skins.default[request.top]?.[request.top];
3726
+ const oldLm = old !== undefined && 'type' in old ? waistBottomLayoutOf(old) : undefined;
3727
+ const bottomImage = output.images.find(([name]) => name === old?.image)?.[1];
3728
+ const topImage = output.images.find(([name]) => name === top?.image)?.[1];
3729
+ if (old === undefined || !('type' in old) || top === undefined || !('type' in top) || oldLm === undefined || topImage === undefined || bottomImage === undefined) throw new PartsError([{ code: 'RIG_WAIST_PIVOT_SOURCE', object: 'waist candidate', detail: `paired mesh source/layout/images "${request.top}"/"${request.bottom}" required from the original builder` }]);
3730
+ if (output.rig.constraints?.length || output.turn !== null || output.rig.stops !== undefined) throw new PartsError([{ code: 'RIG_WAIST_PIVOT_FRAME', object: 'waist candidate', detail: 'requires the original unconstrained, unturned, unstopped source graph; no existing graph is rewritten' }]);
3731
+ const pivot = pivotWaistMesh(old, oldLm, alphaAbove(topImage, ART_ALPHA), alphaAbove(bottomImage, ART_ALPHA), output.rig.bones, request);
3732
+ return { ...output, rig: { ...output.rig, bones: [...output.rig.bones, pivot.bone], constraints: [pivot.constraint],
3733
+ invariants: { ...output.rig.invariants, detached: [...(output.rig.invariants?.detached ?? []), { bone: request.lower, notUnder: request.bone, why: 'explicit rotation-only waist follows the original lower frame without driving its source' }] },
3734
+ skins: { default: { ...output.rig.skins.default, [request.bottom]: { ...output.rig.skins.default[request.bottom], [request.bottom]: pivot.mesh } } } },
3735
+ meshReport: output.meshReport.map((row) => row.part !== request.bottom ? row : { ...row, vertices: pivot.mesh.weights.length, triangles: pivot.mesh.triangles.length / 3, hull: pivot.mesh.hull, bones: [request.bone, request.lower].sort(), max_influences: Math.max(...pivot.mesh.weights.map((ws) => ws.length)), mean_influences: pyRound(pivot.mesh.weights.reduce((n, ws) => n + ws.length, 0) / pivot.mesh.weights.length, 2) }) };
3736
+ }
3737
+
3738
+ /** Explicit supplied-output stage. The bottom, existing graph, art and motion remain identical. */
3739
+ export function withWaistSharedCopy<T extends Pick<RigOutput, 'rig' | 'motion' | 'images' | 'meshReport'>>(output: T, request: WaistPivotRequest): T {
3740
+ const top=output.rig.skins.default[request.top]?.[request.top],bottom=output.rig.skins.default[request.bottom]?.[request.bottom];
3741
+ const topImage=output.images.find(([name])=>name===top?.image)?.[1],bottomImage=output.images.find(([name])=>name===bottom?.image)?.[1];
3742
+ const refuse=(code:string,detail:string):never=>{throw new PartsError([{code,object:'shared waist copy',detail}]);};
3743
+ if(top===undefined||!('type'in top)||bottom===undefined||!('type'in bottom)||!topImage||!bottomImage)refuse('RIG_WAIST_COPY_SOURCE',`original paired meshes and images "${request.top}"/"${request.bottom}" required`);
3744
+ const W=output.rig.bones.find(b=>b.name===request.bone),c=output.rig.constraints?.find(c=>c.name===request.constraint),props=c?.properties as Record<string,{to?:Record<string,unknown>}>|undefined;
3745
+ if(!W||W.parent!==request.upper||!c||output.rig.constraints?.length!==1||c.type!=='transform'||c.source!==request.lower||JSON.stringify(c.bones)!==JSON.stringify([request.bone])||!props?.rotate?.to?.rotate||Object.keys(props).join()!=='rotate'||Object.keys(props.rotate.to).join()!=='rotate'||(c.mixRotate??1)!==1||['mixX','mixY','mixScaleX','mixScaleY','mixShearY'].some(k=>(c[k]??0)!==0)||c.localSource===true||c.localTarget===true||c.additive===true||output.rig.stops!==undefined)refuse('RIG_WAIST_COPY_FRAME','requires the existing upper-parented, world rotate-only waist frame; no graph or motion rewrite');
3746
+ refuseSharedWaistMotion(output.motion, request.top, request.bone);
3747
+ const copy=sharedWaistCopy(top as MeshAttachment,alphaAbove(topImage!,ART_ALPHA),alphaAbove(bottomImage!,ART_ALPHA),output.rig.bones,request);
3748
+ return {...output,rig:{...output.rig,skins:{...output.rig.skins,default:{...output.rig.skins.default,[request.top]:{...output.rig.skins.default[request.top],[request.top]:copy.mesh}}}},meshReport:output.meshReport.map(row=>row.part!==request.top?row:{...row,vertices:copy.mesh.weights.length,triangles:copy.mesh.triangles.length/3,hull:copy.mesh.hull,bones:[...new Set(copy.mesh.weights.flatMap(ws=>ws.map(w=>w.bone)))].sort(),max_influences:Math.max(...copy.mesh.weights.map(ws=>ws.length)),mean_influences:pyRound(copy.mesh.weights.reduce((sum,ws)=>sum+ws.length,0)/copy.mesh.weights.length,2)})};
3749
+ }
3750
+
3751
+ /** Reuse the accepted pair, pivot and shared-copy stages only on an explicit declaration. */
3752
+ export function buildRig(...input: Parameters<typeof buildWaistPairSource>): RigOutput {
3753
+ const [cfg, parts] = input;
3754
+ const declaration = cfg.waist;
3755
+ if (declaration === undefined) return buildWaistPairSource(...input);
3756
+ const refuse = (detail: string): never => { throw new PartsError([{ code: 'RIG_WAIST_DECLARATION', object: 'config.waist', detail }]); };
3757
+ const top = parts.parts.find((p) => p.name === declaration.top), bottom = parts.parts.find((p) => p.name === declaration.bottom);
3758
+ if (top === undefined || bottom === undefined || tagOf(top.from) !== 'topwear' || tagOf(bottom.from) !== 'bottomwear') refuse(`requires topwear mesh "${declaration.top}" and rigid bottomwear "${declaration.bottom}" with matching source provenance`);
3759
+ if (parts.alternates?.length || cfg.assemble.alternates?.length || top!.limb !== undefined || bottom!.limb !== undefined) refuse('the accepted construction requires one base drawing pair without alternate or limb-owned replacements');
3760
+ const source = buildWaistPairSource(...input);
3761
+ const paired = source.rig.skins.default[declaration.bottom]?.[declaration.bottom];
3762
+ if (paired === undefined || !('type' in paired) || waistBottomLayoutOf(paired) === undefined) refuse(`the declared pair "${declaration.top}"/"${declaration.bottom}" did not produce a shared two-bone distance field`);
3763
+ const binding = regionBone(cfg.regions[declaration.bottom]);
3764
+ const meshSpec = cfg.meshes[declaration.top];
3765
+ const named = meshSpec?.segments.map((segment) => typeof segment === 'string' ? segment : segment[0]);
3766
+ if (binding !== declaration.lower || named === undefined || named.length !== 2 || !named.includes(declaration.lower) || !named.includes(declaration.upper)) refuse(`requires exactly the declared upper/lower segment bones "${declaration.upper}"/"${declaration.lower}" and the bottom bound to lower`);
3767
+ const request: WaistPivotRequest = { ...declaration, topOrigin: [top!.x - PAD, top!.y - PAD], bottomOrigin: [bottom!.x - PAD, bottom!.y - PAD], canvas: parts.rig_size };
3768
+ return withWaistSharedCopy(withWaistPivot(source, request), request);
3769
+ }
3770
+
3771
+ /** Imported tracks cannot silently change the accepted shared frame or its old-topology deforms. */
3772
+ function refuseSharedWaistMotion(motion: MotionSpec, top: string, bone: string): void {
3773
+ const refuse = (code: string, detail: string): never => { throw new PartsError([{ code, object: 'shared waist copy', detail }]); };
3774
+ const record=(v:unknown):v is Record<string,unknown>=>typeof v==='object'&&v!==null&&!Array.isArray(v);
3775
+ for(const [animation,entry]of Object.entries(motion.animations)){
3776
+ const value:unknown=entry;
3777
+ if(record(value)&&Array.isArray(value.deform))for(const track of value.deform){
3778
+ if(!record(track)||String(track.skin??'default')!=='default'||track.slot!==top||track.attachment!==top||!Array.isArray(track.keys))continue;
3779
+ for(const key of track.keys)if(record(key)&&(key.transform!==undefined||(key.vertices!==undefined&&key.vertices!==null&&(!Array.isArray(key.vertices)||key.vertices.some(v=>typeof v!=='number'||!Number.isFinite(v)||v!==0)))))refuse('RIG_WAIST_COPY_DEFORM',`animation "${animation}" top deform at ${String(key.t)} has no proved per-bone transfer into the new waist support; retain its original numeric field or supply a representable composition`);
3780
+ }
3781
+ }
3782
+
3783
+ for (const [animation, entry] of Object.entries(motion.animations)) {
3784
+ const value: unknown = entry;
3785
+ if (record(value) && Array.isArray(value.tracks) && value.tracks.some((track) => record(track) && track.bone === bone)) refuse('RIG_WAIST_MOTION', `animation "${animation}" drives generated waist bone "${bone}"; original tracks must retain their authored targets`);
3786
+ }
3787
+ }
package/src/waist.ts ADDED
@@ -0,0 +1,71 @@
1
+ /** The explicit two-bone top/bottom waist driver; no anatomical name matching. */
2
+ import { regionBone, type CharacterConfig, type Point } from './config.ts';
3
+ import type { Problem } from './errors.ts';
4
+ import { ART_ALPHA } from './mesh.ts';
5
+ import { tagOf, type PartsFile } from './parts.ts';
6
+ import type { Mask } from './raster/types.ts';
7
+ import { capAndFloor, influences, type Influence, type InfluenceLimits, type Segment } from './weights.ts';
8
+
9
+ export interface WaistPair { top: string; bottom: string; lower: string; upper: string }
10
+
11
+ /** Only a unique, explicitly bound pair enables the correction. Other mesh modes keep their contract. */
12
+ export function waistPairs(
13
+ parts: PartsFile['parts'], cfg: Pick<CharacterConfig, 'meshes' | 'regions'>,
14
+ segments: ReadonlyMap<string, readonly Segment[]>, bones: ReadonlyMap<string, { parent: string | null }>,
15
+ ): { pairs: Map<string, WaistPair>; problems: Problem[] } {
16
+ const pairs = new Map<string, WaistPair>(), problems: Problem[] = [];
17
+ const bottoms = parts.filter((p) => tagOf(p.from) === 'bottomwear' && cfg.meshes[p.name] === undefined && cfg.regions[p.name] !== undefined);
18
+ for (const p of parts) {
19
+ const mesh = cfg.meshes[p.name];
20
+ if (p.limb?.band !== undefined || tagOf(p.from) !== 'topwear' || mesh === undefined || !('grid' in mesh) || (mesh.rule ?? 'distance') !== 'distance') continue;
21
+ const names = [...new Set((segments.get(p.name) ?? []).map((s) => s.bone))];
22
+ if (names.length !== 2) continue;
23
+ const candidates: WaistPair[] = [];
24
+ for (const bottom of bottoms) {
25
+ const lower = regionBone(cfg.regions[bottom.name]);
26
+ if (!names.includes(lower)) continue;
27
+ const upper = names.find((n) => n !== lower) as string;
28
+ let ancestor = bones.get(upper)?.parent ?? null;
29
+ while (ancestor !== null && ancestor !== lower) ancestor = bones.get(ancestor)?.parent ?? null;
30
+ if (ancestor === lower) candidates.push({ top: p.name, bottom: bottom.name, lower, upper });
31
+ }
32
+ if (candidates.length > 1) problems.push({ code: 'RIG_WAIST_PAIR', object: `mesh "${p.name}"`, detail: `has ${candidates.length} eligible rigid bottomwear partners (${candidates.map((c) => c.bottom).join(', ')}); one explicit binding pair is required, never the first part` });
33
+ else if (candidates.length === 1) pairs.set(p.name, candidates[0]);
34
+ }
35
+ const byBottom = new Map<string, WaistPair[]>();
36
+ for (const pair of pairs.values()) byBottom.set(pair.bottom, [...(byBottom.get(pair.bottom) ?? []), pair]);
37
+ for (const [bottom, owners] of byBottom) if (owners.length > 1) {
38
+ problems.push({ code: 'RIG_WAIST_PAIR', object: `region "${bottom}"`, detail: `has ${owners.length} eligible topwear drivers (${owners.map((p) => p.top).join(', ')}); a shared bottom cannot choose the first field` });
39
+ for (const pair of owners) pairs.delete(pair.top);
40
+ }
41
+ return { pairs, problems };
42
+ }
43
+
44
+ export interface WaistBand { pair: WaistPair; anchor: number; hem: number; plateau: number }
45
+
46
+ /** Painted hem is the last alpha>8 row; one source texel above it begins H-only support. */
47
+ export function waistBand(pair: WaistPair, art: Mask, anchor: number): WaistBand | Problem {
48
+ let hem = -1;
49
+ for (let y = 0; y < art.height; y++) for (let x = 0; x < art.width; x++) if (art.data[y * art.width + x] !== 0) hem = y;
50
+ const plateau = hem - 1;
51
+ if (hem < 0 || !Number.isFinite(anchor) || anchor >= plateau) return {
52
+ code: 'RIG_WAIST_HEIGHT', object: `mesh "${pair.top}"`,
53
+ detail: `upper bone "${pair.upper}" anchor is image row ${anchor}, painted hem is ${hem} (last alpha > ${ART_ALPHA} row); the anchor must be strictly above its H-only plateau at row ${plateau}, one source texel before an existing painted hem`,
54
+ };
55
+ return { pair, anchor, hem, plateau };
56
+ }
57
+
58
+ /** Apply the existing cap/floor ONCE to the height driver; upper vertices use the unchanged distance call. */
59
+ export function waistInfluences(
60
+ at: Point, imageY: number, band: WaistBand,
61
+ segments: readonly Segment[], radius: number, limits: InfluenceLimits, exponent: number,
62
+ ): Influence[] | Problem {
63
+ if (imageY <= band.anchor) return influences(at, segments, radius, limits, exponent);
64
+ const t = Math.min(1, (imageY - band.anchor) / (band.plateau - band.anchor));
65
+ const uncut = influences(at, segments, radius, { maxInfluences: Number.MAX_SAFE_INTEGER, minWeight: 0 }, exponent);
66
+ const lower = uncut.find((w) => w.bone === band.pair.lower);
67
+ if (lower === undefined || !uncut.some((w) => w.bone === band.pair.upper)) return { code: 'RIG_WAIST_BINDING', object: `mesh "${band.pair.top}"`, detail: `distance shares name [${uncut.map((w) => w.bone).join(', ')}]; the declared pair "${band.pair.upper}"/"${band.pair.lower}" is required before height transfer` };
68
+ const h = lower.weight + (1 - lower.weight) * t;
69
+ // Keep the segment declaration's first-appearance order for an exact cap tie.
70
+ return capAndFloor([...new Set(segments.map((s) => s.bone))].map((bone) => [bone, bone === band.pair.lower ? h : 1 - h] as const), limits);
71
+ }