@rig-c/parts 1.69.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
@@ -139,7 +139,7 @@ import { explicitAttachment, type ExplicitMeshReport } from './explicitmesh.ts';
139
139
  */
140
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';
141
141
  import { type BoneTransform, computeExactFrameTransforms, cropToSpineY, normaliseDegrees, paintingToSetupPoint, toBoneLocal, toWorld } from './coords.ts';
142
- import { type Problem, refuseIfAny } from './errors.ts';
142
+ import { type Problem, refuseIfAny, PartsError } from './errors.ts';
143
143
  import { recordedFocusProblems } from './setfocus.ts';
144
144
  import { eyeLineDegrees } from './headframe.ts';
145
145
  import type { RigBoneInherit, RigStop } from 'rig-c/src/rig.ts';
@@ -175,9 +175,12 @@ import { edgeLength } from './length.ts';
175
175
  import { skeletonLimbJoints } from './limbs.ts';
176
176
  import { coalesceLimbSlots } from './limbslots.ts';
177
177
  import { layoutAlias, placeLimbLayouts, type LayoutPlan } from './limblayout.ts';
178
- 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';
179
179
  import { bindFaceSurfaceDeform, BLINK, blinkHoldMisses, blinkSpan, CONTROL_SUFFIX, controlledBones, IDLE_FPS, idleMotion, type MotionSpec, moveKeysToControls } from './motion.ts';
180
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';
181
184
  import { readTag } from './tags.ts';
182
185
  import { EYE_GROUP_TAGS } from './propose.ts';
183
186
  import { alphaAbove, crop, pad, type Raster } from './raster/index.ts';
@@ -1287,7 +1290,7 @@ function limbBandShares(p: PartRecord, point: Point): Influence[] | null {
1287
1290
  return [{ bone: h.upper, weight: 1 - lower }, { bone: (p.limb as NonNullable<typeof p.limb>).bone, weight: lower }].filter((q) => q.weight > 0);
1288
1291
  }
1289
1292
 
1290
- export function buildRig(
1293
+ export function buildWaistPairSource(
1291
1294
  cfg: CharacterConfig,
1292
1295
  parts: PartsFile,
1293
1296
  images: ReadonlyMap<string, Raster>,
@@ -1885,6 +1888,18 @@ export function buildRig(
1885
1888
 
1886
1889
  const loopPasses: Record<string, number> = {};
1887
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
+ });
1888
1903
  // A region's centre in its bone's setup frame; on a turned bone the image
1889
1904
  // is turned back by the bone's world rotation, so it is drawn upright.
1890
1905
  const region = (image: string, bone: string, cx: number, cy: number): RegionAttachment => {
@@ -1929,6 +1944,9 @@ export function buildRig(
1929
1944
  if (torso.length === 0) return () => segs;
1930
1945
  return (wy: number): Segment[] => (wy < hipBone.y ? torso : segs);
1931
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);
1932
1950
  // A contour mesh (issue #84): `src/contour.ts` over the padded image, every refusal collected with the others;
1933
1951
  // the weights by `src/localweights.ts`; slot, uvs, bind positions and by-name weights written as the lattice's.
1934
1952
  // The config's region numbers are rig px; the part image's are rig px less (p.x − PAD, p.y − PAD) — a
@@ -2462,12 +2480,14 @@ export function buildRig(
2462
2480
  const cyLow = st.row + (p.h - r) / 2;
2463
2481
  const cyUp = p.y + r / 2;
2464
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 });
2465
2484
  skin[still] = { [still]: region(stillFile, sb.name, cx, cyUp) };
2466
2485
  addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name }, { name: still, bone: sb.name, attachment: still });
2467
2486
  continue;
2468
2487
  }
2469
2488
  const cy = p.y + p.h / 2;
2470
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 });
2471
2491
  addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name });
2472
2492
  continue;
2473
2493
  }
@@ -2521,14 +2541,18 @@ export function buildRig(
2521
2541
  // silhouette are built over; absent, `art` is `allArt` itself and nothing downstream moves.
2522
2542
  const stray = mesh.stray === undefined ? null : latticeStray(allArt, mesh.stray);
2523
2543
  const art = stray === null ? allArt : stray.art;
2524
- 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]);
2525
2551
  if ('code' in lm) {
2526
2552
  problems.push(lm);
2527
2553
  continue;
2528
2554
  }
2529
2555
  loopPasses[p.name] = lm.passes;
2530
- const ox = p.x - PAD;
2531
- const oy = p.y - PAD;
2532
2556
  // issue #161: under rule "heat", the field over the lattice's art (alpha above 8) with its holes filled.
2533
2557
  // issue #303: an island no bone reaches is worded against the lattice's own `stray` when it is dust.
2534
2558
  const dust = (): HeatDust => {
@@ -2556,7 +2580,8 @@ export function buildRig(
2556
2580
  const wy = vy0 + oy;
2557
2581
  const vSegs = segsAt(wy);
2558
2582
  const hybrid = limbBandShares(p, [wx, wy]);
2559
- 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; }
2560
2585
  if (shares.length === 0) {
2561
2586
  // issue #284: a declared cut that keeps no bone (nothingKeptProblem says when that can be).
2562
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 }) };
@@ -2569,6 +2594,7 @@ export function buildRig(
2569
2594
  problems.push(nothingKeptProblem(p.name, limits.floor, emptied, emptiedMore));
2570
2595
  continue;
2571
2596
  }
2597
+ if (rawShares.length !== lm.vertices.length) continue; // named waist binding problems already collected
2572
2598
  const allChainLinks = new Set([...chains.values()].flat());
2573
2599
  const forkCounts = new Map<string, number>();
2574
2600
  for (const sp of mesh.segments) {
@@ -2577,7 +2603,7 @@ export function buildRig(
2577
2603
  const par = links !== undefined && links.length > 0 ? (B.get(links[0])?.parent ?? null) : null;
2578
2604
  if (par !== null && allChainLinks.has(par)) forkCounts.set(par, (forkCounts.get(par) ?? 0) + 1);
2579
2605
  }
2580
- 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);
2581
2607
  const finalShares = heldFork ? smoothForkShares(rawShares, lm.triangles) : rawShares;
2582
2608
  for (const [vi, [vx0, vy0]] of lm.vertices.entries()) {
2583
2609
  const wx = vx0 + ox;
@@ -2593,6 +2619,12 @@ export function buildRig(
2593
2619
  const uvs: number[] = [];
2594
2620
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2595
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
+ }
2596
2628
  addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2597
2629
  meshReport.push({
2598
2630
  part: p.name,
@@ -2763,6 +2795,7 @@ export function buildRig(
2763
2795
  if (mesh === undefined) {
2764
2796
  const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
2765
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 });
2766
2799
  continue;
2767
2800
  }
2768
2801
  if ('explicit' in mesh) {
@@ -2774,7 +2807,8 @@ export function buildRig(
2774
2807
  const baseAtt = skin[p.name]?.[p.name];
2775
2808
  const baseBones = baseAtt !== undefined && 'type' in baseAtt ? new Set((baseAtt.weights ?? []).flatMap((v) => v.map((e) => e.bone))) : null;
2776
2809
  const filteredSegs = baseBones !== null && baseBones.size > 0 ? fullSegs.filter((s) => baseBones.has(s.bone)) : fullSegs;
2777
- 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;
2778
2812
  if (drawn !== undefined) {
2779
2813
  const movePt = (bone: string, pt0: Point): Point => {
2780
2814
  const m0 = world.get(bone) as BoneTransform;
@@ -2802,6 +2836,7 @@ export function buildRig(
2802
2836
  return explicit || end === undefined ? s : { ...s, b: [end[0], end[1]] };
2803
2837
  });
2804
2838
  }
2839
+ waistSegs = segs;
2805
2840
  // Select against final endpoints, retaining each original entry's
2806
2841
  // tuple/named provenance through the preceding pose and base filters.
2807
2842
  if (drawn !== undefined) {
@@ -2816,20 +2851,26 @@ export function buildRig(
2816
2851
  const art = stray === null ? allArt : stray.art;
2817
2852
  const grid = 'grid' in mesh ? mesh.grid : 28;
2818
2853
  const r = 'r' in mesh ? mesh.r : 80;
2819
- 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]);
2820
2862
  if ('code' in lm) {
2863
+ if (band !== null) { problems.push(lm); continue; }
2821
2864
  skin[skinSlot][attName] = altRegion(file, segs[0].bone, p.x + p.w / 2, p.y + p.h / 2);
2822
2865
  continue;
2823
2866
  }
2824
- const ox = p.x - PAD;
2825
- const oy = p.y - PAD;
2826
2867
  const w = img.width;
2827
2868
  const h = img.height;
2828
2869
  const limits: InfluenceLimits = meshLimits('influences' in mesh ? mesh.influences : undefined);
2829
2870
  const segsAt = dressSegsAt(p, segs);
2830
2871
  const exponent = ('exponent' in mesh ? mesh.exponent : undefined) ?? DISTANCE_EXPONENT;
2831
2872
  let touchesArt: boolean[] | null = null;
2832
- if (drawn !== undefined && limits.maxInfluences === 1) {
2873
+ if (band === null && drawn !== undefined && limits.maxInfluences === 1) {
2833
2874
  const lc = latticeCells(art, grid);
2834
2875
  touchesArt = lm.vertices.map(([vx0, vy0]) => {
2835
2876
  const ii = Math.round(vx0 / grid);
@@ -2850,12 +2891,14 @@ export function buildRig(
2850
2891
  const wy = vy0 + oy;
2851
2892
  const vSegs = segsAt(wy);
2852
2893
  const hybrid = limbBandShares(p, [wx, wy]);
2853
- let shares = hybrid ?? influences([wx, wy], vSegs, r, limits, exponent);
2854
- 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) {
2855
2897
  shares = influences([wx, wy], vSegs, Infinity, { maxInfluences: 1, minWeight: 0 }, exponent);
2856
2898
  }
2857
2899
  rawShares.push(hybrid !== null || limits.floor === 'continuous' ? roundShares(shares) : latticeShares(shares));
2858
2900
  }
2901
+ if (rawShares.length !== lm.vertices.length) continue;
2859
2902
  if (touchesArt !== null) {
2860
2903
  let firstArtBone: string | null = null;
2861
2904
  for (let vi = 0; vi < lm.vertices.length; vi++) {
@@ -2883,6 +2926,12 @@ export function buildRig(
2883
2926
  const uvs: number[] = [];
2884
2927
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2885
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
+ }
2886
2935
  }
2887
2936
  if (alt.base_anchor !== undefined) {
2888
2937
  const baseRegions = new Map<string, AnchorRegion>(), altRegions = new Map<string, AnchorRegion>();
@@ -2931,6 +2980,51 @@ export function buildRig(
2931
2980
  sets: setEntries,
2932
2981
  };
2933
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)]));
2934
3028
  const hasAlternateFaceSet = sets !== undefined && Object.values(sets.sets).some((e) => Object.hasOwn(e.slots, 'face'));
2935
3029
  // Read every base/alternate binding before rebinds; publish only the slot
2936
3030
  // permutation below, after stops/turn have used the original enumeration.
@@ -3183,6 +3277,8 @@ export function buildRig(
3183
3277
  });
3184
3278
  }
3185
3279
  bindFaceSurfaceDeform(motion, (merged) => {
3280
+ if (cfg.waist !== undefined) refuseSharedWaistMotion(merged, cfg.waist.top, cfg.waist.bone);
3281
+ remapWaistDeforms(merged, waistTargets, waistRegionTargets, waistBindingsBeforeRebind);
3186
3282
  expandSetAttachmentKeys(rig, sets, merged);
3187
3283
  if (cfg.turn?.roles !== undefined) {
3188
3284
  buildDepth25DTurn(rig, merged, {
@@ -3622,3 +3718,70 @@ export function flattenRig(rig: RigSpec, sense: 1 | -1 = 1): RigSpec {
3622
3718
  }
3623
3719
  return flat;
3624
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
+ }