@rig-c/parts 1.52.0 → 1.54.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/docs/STABILITY.md CHANGED
@@ -191,7 +191,7 @@ every number) are AUTHORING §3's tables, and the loader refuses any other by na
191
191
 
192
192
  | file | written by | what is stable |
193
193
  | --- | --- | --- |
194
- | `parts.json`, `parts/<name>.png` | `assemble`, `build` | one record per part: `from` (`<run>:<tag>` with a See-through v3 tag, `<run>:author:<label>` for a layer the author made — issue #256, read by no role rule — or `painting:<name>` for a patch), `cut_from` on a cut's piece only (the plan part it was cut from, issue #230), `limb` on a limb segment's part only (issue #349: `name`, `segment`, `of`, `bone`, and below a joint `joint`, `range` when the config segment declares one (issue #360), and `cap` — `at`, `width`, `radius`, `box`, `layer_px`, `image_px` with a cap image, `image_layer` after it when that image was a hidden-art layer — issue #359, `<run>:<layer>:hidden` — `missing_px`, `short_px` (`left`, `right`) after it only when `missing_px` is above 0 (issue #557, additive), then `shape` and `upper_px` under the segment's `cap_shape` — `upper_px` without the shape only when the upper segment gave a pixel (issue #557, additive) — and `edge`, `feather_radius` and `feathered_px` under its `edge`, and `cut_band`, `cut_offset`, `cut_at`, `cut_crossed`, `joint_crossed`, `band_px` and `stroke_luma_max` (when the band has a split) under its `cut_band`, issue #360), the box `x`, `y`, `w`, `h` (rig px), the pixel counts `src/parts.ts` documents (`opaque_px`, `visible_px`, `occluded_px`, `projected_core_px`, `source_px_taken`, `visible_not_projected_px`, `refused_drift_px`, `merged_px`, `seam_override_px`, and `fringe_pushed_back` when not empty); `rig_size`, `scale_rig_per_source`, `ghost_px`, `recomposite`, and `scene` (`figure_alpha_above`, `figure_px`, `figure_mask`) under `config.scene` only, with the figure's mask `figure_rig.png` beside the recomposite (issue #242); `single_run_pad` (`file_size`, `side`, `left`, `top`) last, only for one run whose file is not the `seethrough.resolution` square (issue #366) |
194
+ | `parts.json`, `parts/<name>.png` | `assemble`, `build` | one record per part: `from` (`<run>:<tag>` with a See-through v3 tag, `<run>:author:<label>` for a layer the author made — issue #256, read by no role rule — or `painting:<name>` for a patch), `cut_from` on a cut's piece only (the plan part it was cut from, issue #230), `limb` on a limb segment's part only (issue #349: `name`, `segment`, `of`, `bone`, and below a joint `joint`, `range` when the config segment declares one (issue #360), and `cap` — `at`, `width`, `radius`, `box`, `layer_px`, `image_px` with a cap image, `image_layer` after it when that image was a hidden-art layer — issue #359, `<run>:<layer>:hidden` — `missing_px`, `short_px` (`left`, `right`) after it only when `missing_px` is above 0 (issue #557, additive), then `shape` and `upper_px` under the segment's `cap_shape` — `upper_px` without the shape only when the upper segment gave a pixel (issue #557, additive) — and after them `lower_px`, `lower_kept_px` and `lower_missing_px` under `cap_shape: "ball"` (issue #579, additive), and `edge`, `feather_radius` and `feathered_px` under its `edge`, and `cut_band`, `cut_offset`, `cut_at`, `cut_crossed`, `joint_crossed`, `band_px` and `stroke_luma_max` (when the band has a split) under its `cut_band`, issue #360), the box `x`, `y`, `w`, `h` (rig px), the pixel counts `src/parts.ts` documents (`opaque_px`, `visible_px`, `occluded_px`, `projected_core_px`, `source_px_taken`, `visible_not_projected_px`, `refused_drift_px`, `merged_px`, `seam_override_px`, and `fringe_pushed_back` when not empty); `rig_size`, `scale_rig_per_source`, `ghost_px`, `recomposite`, and `scene` (`figure_alpha_above`, `figure_px`, `figure_mask`) under `config.scene` only, with the figure's mask `figure_rig.png` beside the recomposite (issue #242); `single_run_pad` (`file_size`, `side`, `left`, `top`) last, only for one run whose file is not the `seethrough.resolution` square (issue #366) |
195
195
  | `rig/rig.json`, `rig/motion.json`, `rig/images/` | `rig`, `build`, `compose` | rig-c's rig spec and motion spec, `spec` `rigc-rig/1` and `rigc-motion/1`: the format is rig-c's, and this package writes only what rig-c's parser accepts; a bone carries `inherit` only where config.bones declares one, rig-c's mode name as written (issue #348) |
196
196
  | `rig/mesh_report.json` | `rig`, `build` | one row per mesh: `part`, `vertices`, `triangles`, `hull`, `bones` (the sorted names the attachment's weights bind in the written `rig.json`, in every mode — since 1.49.1 (issue #536) a rig with `turn` or `stops` names the twins and `<link>_d` bones there, where the row named the segment bones they replace: a fix of a wrong name, not a format change; a rig with neither writes the bytes it wrote), `max_influences`, `mean_influences`, `art_coverage`, then `grid` (a lattice); `mode` "contour" with `params`, `contour`, `regions` (`params.maxEdge` and `contour.outlineCut` only when the mesh declares `contour.maxEdge`; `params.bridges` and `contour.bridges` — `islands`, `units`, `joins`, and `faint` only when an island was left out as faint — only when it declares `contour.bridges`); or `mode` "influence" with `influence` (as declared), `reach` (`farthest`, `at`, `nearest`, `capped`, `widest`) and `lattice` (rig-c's `SegmentsLatticeReport`: `cols`, `rows`, `artCells`, `keptCells`, `passes`, `islands`) (issue #378); or `mode` "auto" with `settings`, `source`, `result`, `residuals`, `worst_residual`, `worst_region`, `motion_amplitude`, `termination`, `weights`, `regions`, `deformation`, `quality_report` (rig-c's `mesh-quality-report/1` document whole), `motion_report`, and, only when they apply, `stray_cleared` (after `source`, when `source.stray` is declared), `skinning_residual` and `replay` (`AutoMeshReport` in `src/rig.ts`); in every mode, `exponent` when the mesh declares one (after `grid`, or after `mode`); `influences`, as declared, when a lattice or contour mesh declares it (after `exponent`, or where `exponent` would be); `stray` and `stray_cleared` when a lattice mesh declares `stray` (after `influences`, or where `influences` would be); `ribs` when a contour or auto mesh declares them (after `exponent`, or after `mode`), and then `contour.ribs` (`source.contour.ribs` in the automatic mode) |
197
197
  | `check/check.json` and the rest of `check/` | `check`, `build`, `compose` | the reference's fields in its order (`gate_spine_html_green`, `rigc_entry`, `pack_mode`, `environment` after it under `--environment` only (issue #538, additive: `path` as given, `sha256`, `steps`), `loop_max_diff`, the seam figures — `seam_mean`, `seam_px_over_40`, `seam_px_over_80` and, from issue #216, `seam_frame_scale`, the frame scale the bar divides the count by), `loop_physics` after `loop_max_diff` when the rig declares a physics constraint, `seam_border` after the seam figures when `parts.json` declares a scene (issue #242), `seam_pairs` after the seam figures when the seam bar fails or `--seam-pairs` asks (each row's picture under `check/seam/`; `--keep-stills` leaves the setup-pose still and its `frames.json` under `check/setup_still/`), then the judgement lines (`BREATH_VISIBLE`, `BLINK_NO_HOLE`, `CHAIN_LAG`, `TIP_OVER_ROOT`, `STILL_REGIONS_DARK`, `TEXTURE_STRETCH`), `ANIMATIONS_DO_NOT_FOLD` after them when `motion.json` holds an animation, the idle included — on every rig with an idle since issue #333 (issues #320, #363: `status`, `animations`, `fps`, `physics_left_out`, `folding` — each `animation`, `slot`, `attachment`, `frames`, `worst_frame`, `worst_triangles`, `triangles`, `physics_on`, `physics_off`, `physics_constraints`, `declared`, `line` — `folding_undeclared`, `declared_not_folding`, `bar`), `FEET_STAY_LEVEL` after it when a `footwear` part rides a bone that hangs from another and `motion.json` holds an animation (issue #348: `status`, `reason` on a SKIP only, `animations`, `fps`, `physics_left_out`, `bar_degrees`, `bar`, `feet` — each `part`, `bone`, `hangs_from`, `status`, `frames_posed`, `worst`), `LIMB_ONE_BONE` after it (and after `STRESS_OFF_CHAIN` where that is written) when `parts.json` holds a limb segment's part (issue #349: `status`, `parts` — each `part`, `limb`, `bone`, `status`, `others`), `SEAM_OVER_RANGE` after it when a limb record carries a `range` (issue #360: `status`, `frame_scale`, `physics_left_out`, `bar` — `mean`, `rig_px_over_40`, `level` — and `joints`, each `part`, `limb`, `segment`, `joint`, `bone`, `range`, `at`, `radius`, `under_px`, `status`, `poses` — each `degrees`, `status`, `mean`, `px_over_40`, `px_over_80`, `rig_px_over_40`, and `step_px` (`left`, `right`) only on a joint whose cap record carries `short_px` (issue #557, additive) — and `unread` on a joint not read), `SEAM_OVER_MOTION` after it when `parts.json` holds a limb segment or `--requirements` a `seam` (issue #493, a warning and not a bar: `status` — `WARN`, `CLEAR` or `SKIP` — `reason` on a SKIP only, `fps`, `floor`, `pairs` — each `pair`, `a`, `b`, `declared`, and `unread` on a pair not read — `animations`, `warnings`, `rows` — each `pair`, `animation`, `status`, `drawn`, `banded`, `opens`, `px`, `max_px`, `under_floor`), `CLOTH_SETTLES` after it when the rig declares a physics constraint and has an idle (issue #501, a warning and not a bar: `status` — `WARN` or `CLEAR` — `fps`, `frames`, `duration`, `floor_rig_px_per_s`, `floor`, `levers`, `warnings`, `rows` — each `tip`, `root`, `links`, `point`, `settles_at`, `max_rig_px_per_s`, `min_rig_px_per_s`), `RECOMPOSITE_HOLES` (its first figure `declared_scene` when `parts.json` declares a scene), `SETUP_POSE_VS_SOURCE`, `skipped`, a `requirements` block under `--requirements` (or `build`'s `config.requirements`) — `file` first from issue #556, additive: `path` as typed or declared, `sha256`, `keys` — and `PASS`; `check/build/skeleton.json`, `.atlas` and `.png` are the packed artifact rig-c writes |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/parts",
3
- "version": "1.52.0",
3
+ "version": "1.54.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/assemble.ts CHANGED
@@ -345,6 +345,218 @@ export interface AssembleInput {
345
345
  keySkeleton?: ControlSkeleton;
346
346
  /** `assemble.head_face_underfill` (issue #492): composite `full:face` under `head:face` on the head canvas to fill transparent bare-skin holes. */
347
347
  headFaceUnderfill?: boolean;
348
+ /**
349
+ * Issue #587: rig pixels taken out of named parts once the cuts and the limbs are made, before the fringe pass and
350
+ * every figure a part's record holds — each entry clears `part`'s pixels (alpha, colour and region) where `mask` is
351
+ * 1, and {@link AssembleResult.excluded} counts the ones above `OPAQUE_ALPHA_ABOVE` it took, in entry order (a pixel
352
+ * an earlier entry cleared is not counted again). The set build passes {@link setExclusions}. An entry naming a part
353
+ * this run did not make clears nothing and counts 0. Absent or empty: nothing changes.
354
+ */
355
+ exclude?: readonly SetExclusion[];
356
+ /**
357
+ * Issue #588: the parts a limb takes on which a subset set names one limb side ({@link setIslandSources}). On each
358
+ * that holds more than one island, every limb segment part cut from it keeps the island its joints fall on and
359
+ * loses the rest ({@link AssembleResult.islands}), once the limbs are cut and before `exclude`. Absent or empty:
360
+ * nothing changes.
361
+ */
362
+ limbIslands?: readonly string[];
363
+ }
364
+
365
+ /** One base part's cover over one of a subset set's limb parts (issue #587): `part` loses its pixels where `mask` is 1. */
366
+ export interface SetExclusion {
367
+ /** The set's part (a limb segment's `part`). */
368
+ part: string;
369
+ /** The base part drawn in front of it that the set does not replace. */
370
+ under: string;
371
+ /** Rig pixels where `under` covers at setup: its PNG's alpha above `OPAQUE_ALPHA_ABOVE`, at its parts.json x, y. */
372
+ mask: Mask;
373
+ }
374
+
375
+ /** What one {@link SetExclusion} took (issue #587): `px` pixels of `part` with alpha above `OPAQUE_ALPHA_ABOVE`, under `under`. */
376
+ export interface ExcludedCount {
377
+ part: string;
378
+ under: string;
379
+ px: number;
380
+ }
381
+
382
+ /**
383
+ * Issue #587: what a subset set's limb parts may not take from the set's painting.
384
+ *
385
+ * ⚖️ Invariant: for each of `segmentParts` (the set's limb segment parts, in the order given), one entry per base part
386
+ * drawn after that part in the base's draw order (`base`, the base build's placed parts, which is parts.json's order)
387
+ * whose name is not in `replaced` (the set's covered parts and its hides) and which covers at least one rig pixel: the
388
+ * pixels where that base part's PNG has alpha above `OPAQUE_ALPHA_ABOVE` (the `op=` count's threshold), placed at its
389
+ * parts.json x, y. The set's attachment is drawn in the base slot's place, so a base part drawn after that slot is
390
+ * drawn over the set's art as well, and what the set's painting shows there is that base part, which the base already
391
+ * draws. The set's painting is on the base's canvas (`ASSEMBLE_ALT_CANVAS_SIZE`) at the base's rig_scale, so a rig
392
+ * pixel is the same pixel in both; a skeleton set is held to the base's torso within the registration bar
393
+ * (`ASSEMBLE_ALT_SKELETON_REGISTERED`) and is not moved. A part with no base part in front of it gets no entry.
394
+ */
395
+ export function setExclusions(base: readonly PlacedPart[], W: number, H: number, segmentParts: readonly string[], replaced: ReadonlySet<string>): SetExclusion[] {
396
+ const out: SetExclusion[] = [];
397
+ for (const part of segmentParts) {
398
+ const at = base.findIndex((q) => q.record.name === part);
399
+ if (at < 0) continue;
400
+ for (const { record, image } of base.slice(at + 1)) {
401
+ if (replaced.has(record.name)) continue;
402
+ const mask = newMask(W, H);
403
+ let any = false;
404
+ for (let y = 0; y < image.height; y++) {
405
+ for (let x = 0; x < image.width; x++) {
406
+ const rx = record.x + x;
407
+ const ry = record.y + y;
408
+ if (rx < 0 || ry < 0 || rx >= W || ry >= H || image.data[(y * image.width + x) * 4 + 3] <= OPAQUE_ALPHA_ABOVE) continue;
409
+ mask.data[ry * W + rx] = 1;
410
+ any = true;
411
+ }
412
+ }
413
+ if (any) out.push({ part, under: record.name, mask });
414
+ }
415
+ }
416
+ return out;
417
+ }
418
+
419
+ /**
420
+ * What one limb segment part kept of a layer that holds more than one island (issue #588): the layer's island count,
421
+ * the joints the kept island lies under, and the part's pixels (alpha above `OPAQUE_ALPHA_ABOVE`) on it and on the
422
+ * islands dropped.
423
+ */
424
+ export interface IslandCount {
425
+ part: string;
426
+ /** The part the limb took (the segment's `from`). */
427
+ of: string;
428
+ islands: number;
429
+ joints: Array<{ bone: string; at: [number, number] }>;
430
+ kept: number;
431
+ dropped: number;
432
+ }
433
+
434
+ /**
435
+ * Issue #588: the parts a subset set's limbs take on which the set names one limb side — every `from` of `setLimbs`
436
+ * (in their order, each once) that more of `limbs` (the config's) take than of `setLimbs`. In the base build every
437
+ * limb that takes a part shares its pixels by the nearest polyline, so each limb gets its own side; a set that carries
438
+ * fewer of them puts every pixel of the part on the limbs it carries, both legs of a two-leg layer on one leg.
439
+ */
440
+ export function setIslandSources(limbs: Readonly<Record<string, Limb>>, setLimbs: Readonly<Record<string, Limb>>): string[] {
441
+ const takes = (all: Readonly<Record<string, Limb>>, src: string): number => Object.values(all).filter((l) => l.segments.some((sg) => sg.from === src)).length;
442
+ const froms = [...new Set(Object.values(setLimbs).flatMap((l) => l.segments.map((sg) => sg.from)))];
443
+ return froms.filter((src) => takes(limbs, src) > takes(setLimbs, src));
444
+ }
445
+
446
+ /** The rig pixels whose square holds the point `[x, y]` (a pixel's centre is at `x + 0.5`): one, two on an edge, four on a corner. */
447
+ function pixelsAt(at: readonly [number, number], W: number, H: number): number[] {
448
+ const along = (v: number, n: number): number[] => (Number.isInteger(v) ? [v - 1, v] : [Math.floor(v)]).filter((i) => i >= 0 && i < n);
449
+ const out: number[] = [];
450
+ for (const y of along(at[1], H)) for (const x of along(at[0], W)) out.push(y * W + x);
451
+ return out;
452
+ }
453
+
454
+ /**
455
+ * Issue #588: on each of `sources` that holds more than one island, keep in every limb segment part cut from it the
456
+ * island its joints fall on, and clear the rest (alpha, colour and region).
457
+ *
458
+ * ⚖️ Invariant: an island is an 8-connected component of the part's pixels with alpha above `OPAQUE_ALPHA_ABOVE` —
459
+ * the ghost clean-up's own rule (`cleanGhosts`); a pixel at or below it is on no island and is kept. A segment's joints are its bone's origin and, when a
460
+ * segment follows it, the next segment's bone's origin (a bone's tip is no joint: the limb ends there), placed by
461
+ * `bones` — the set's bones, posed or placed as its cut. A joint is on the island of a pixel whose square holds the
462
+ * point; with 8-connectivity the pixels that share a point are one island, so a joint is on one island or on none.
463
+ * Every joint of a segment on one island is required: a joint on none (`ASSEMBLE_ALT_LIMB_ISLAND`, the joint and the
464
+ * islands named) or a segment whose joints fall on two names no island to keep, and is refused rather than guessed.
465
+ * A source with one island is left as cut and counted nowhere, so a set whose layer holds its one leg writes what it
466
+ * wrote before. A pixel the limbs wrote where the source is transparent (a `cap_shape: "ball"` lower half from the
467
+ * cap image) is on no island and kept.
468
+ */
469
+ function keepJointIslands(
470
+ sources: readonly string[],
471
+ limbs: Readonly<Record<string, Limb>>,
472
+ bones: readonly BoneEntry[],
473
+ parts: readonly LimbPart[],
474
+ pieces: readonly Built[],
475
+ sourceOf: (name: string) => Built | null,
476
+ W: number,
477
+ H: number,
478
+ ): { counts: IslandCount[]; problems: Problem[] } {
479
+ const counts: IslandCount[] = [];
480
+ const problems: Problem[] = [];
481
+ const places = bonePlaces(bones);
482
+ for (const src of sources) {
483
+ const b = sourceOf(src);
484
+ if (b === null) continue;
485
+ const m = newMask(W, H);
486
+ for (let p = 0; p < W * H; p++) m.data[p] = b.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE ? 1 : 0;
487
+ const cc = connectedComponents(m, 8);
488
+ const n = cc.count - 1;
489
+ if (n < 2) continue;
490
+ // Numbered by area, largest first, then by the box's top row and left column: a function of the pixels, not of a scan.
491
+ const order = cc.stats.slice(1).sort((a, c) => c.area - a.area || a.top - c.top || a.left - c.left);
492
+ const numberOf = new Map(order.map((st, i) => [st.label, i + 1]));
493
+ const islandText = (label: number): string => {
494
+ const st = cc.stats[label];
495
+ return `island ${numberOf.get(label)} (${st.area} px at ${st.left},${st.top} ${st.width}x${st.height})`;
496
+ };
497
+ const all = order.map((st) => islandText(st.label)).join(', ');
498
+ parts.forEach((q, i) => {
499
+ if (q.of !== src) return;
500
+ const segs = limbs[q.limb].segments;
501
+ const object = `config.limbs.${q.limb}.segments[${q.segment}] (part "${q.part}")`;
502
+ const jointBones = [segs[q.segment].bone, ...(q.segment + 1 < segs.length ? [segs[q.segment + 1].bone] : [])];
503
+ const joints = jointBones.map((bone) => {
504
+ const at = (places.get(bone) as BonePlace).at;
505
+ const labels = [...new Set(pixelsAt(at, W, H).map((p) => cc.labels[p]).filter((l) => l > 0))];
506
+ return { bone, at: [pyRound(at[0], 3), pyRound(at[1], 3)] as [number, number], labels };
507
+ });
508
+ const where = (j: (typeof joints)[number]): string => `"${j.bone}"'s origin at [${j.at.join(', ')}]`;
509
+ const off = joints.find((j) => j.labels.length === 0);
510
+ if (off !== undefined) {
511
+ problems.push({
512
+ code: 'ASSEMBLE_ALT_LIMB_ISLAND',
513
+ object,
514
+ detail: `takes "${src}", which holds ${n} islands (8-connected, alpha above ${OPAQUE_ALPHA_ABOVE}): ${all}; the set names one of the limbs that take "${src}", so the segment keeps the island its joints fall on, and its joint ${where(off)} is on none of them — no pixel touching the point has alpha above ${OPAQUE_ALPHA_ABOVE}; a bone origin on its limb's art is required (move the bone onto the joint), or a layer that holds this limb alone`,
515
+ });
516
+ return;
517
+ }
518
+ const on = [...new Set(joints.flatMap((j) => j.labels))];
519
+ if (on.length > 1) {
520
+ problems.push({
521
+ code: 'ASSEMBLE_ALT_LIMB_ISLAND',
522
+ object,
523
+ detail: `takes "${src}", which holds ${n} islands (8-connected, alpha above ${OPAQUE_ALPHA_ABOVE}): ${all}; the set names one of the limbs that take "${src}", so the segment keeps the island its joints fall on, and they fall on ${on.length}: ${joints.map((j) => `${where(j)} on ${islandText(j.labels[0])}`).join(', ')}; every joint of a segment on one island is required — one stroke of art from joint to joint, or a layer that holds this limb alone`,
524
+ });
525
+ return;
526
+ }
527
+ const keep = on[0];
528
+ const piece = pieces[i];
529
+ let kept = 0;
530
+ let dropped = 0;
531
+ for (let p = 0; p < W * H; p++) {
532
+ const a = piece.r.data[p * 4 + 3];
533
+ const l = cc.labels[p];
534
+ if (a === 0 || l === 0) continue;
535
+ if (l === keep) {
536
+ if (a > OPAQUE_ALPHA_ABOVE) kept++;
537
+ continue;
538
+ }
539
+ if (a > OPAQUE_ALPHA_ABOVE) dropped++;
540
+ piece.r.data.fill(0, p * 4, p * 4 + 4);
541
+ if (piece.region !== null) piece.region.data[p] = 0;
542
+ }
543
+ counts.push({ part: q.part, of: src, islands: n, joints: joints.map((j) => ({ bone: j.bone, at: j.at })), kept, dropped });
544
+ });
545
+ }
546
+ return { counts, problems };
547
+ }
548
+
549
+ /** One `LINT` line per {@link IslandCount} (issue #588), in `config.limbs` order. */
550
+ export function islandLines(set: string, counts: readonly IslandCount[]): string[] {
551
+ return counts.map(
552
+ (c) =>
553
+ ` LINT set "${set}" ${c.part}: ${c.of} holds ${c.islands} islands (8-connected, alpha above ${OPAQUE_ALPHA_ABOVE}), kept the one under ${c.joints.map((j) => `${j.bone} [${j.at.join(', ')}]`).join(' and ')} (${c.kept} px), dropped ${c.islands - 1} (${c.dropped} px)`,
554
+ );
555
+ }
556
+
557
+ /** One `LINT` line per {@link ExcludedCount} that took a pixel (issue #587); none for a count of 0. */
558
+ export function excludedLines(set: string, counts: readonly ExcludedCount[]): string[] {
559
+ return counts.filter((c) => c.px > 0).map((c) => ` LINT set "${set}" ${c.part}: ${c.px} px under ${c.under} excluded`);
348
560
  }
349
561
 
350
562
  /** The derived numbers of the two runs' geometry. */
@@ -2755,17 +2967,26 @@ export function shortCapLint(j: LimbCount['joints'][number]): string | null {
2755
2967
  ...(k.image_px === undefined ? [] : [`${k.image_px} px from ${k.image_layer === undefined ? 'the cap image' : `the hidden-art layer ${k.image_layer}`}`]),
2756
2968
  `${k.layer_px} px from "${j.part}"'s layer`,
2757
2969
  `${k.upper_px ?? 0} px from "${j.upper}"`,
2970
+ // Issue #579: under cap_shape "ball", the lower half's written and kept pixels.
2971
+ ...(k.shape === 'ball' ? [`on the lower side ${k.lower_px ?? 0} px written, ${k.lower_kept_px ?? 0} px left as painted`] : []),
2758
2972
  ].join(', ');
2973
+ const lowerMiss = k.lower_missing_px ?? 0;
2974
+ const which =
2975
+ lowerMiss === 0
2976
+ ? `${n} px of the disc on the upper side of the cut, where ${where}`
2977
+ : lowerMiss === n
2978
+ ? `${n} px of the disc on the lower side of the cut (cap_shape "ball"), where "${j.part}"'s layer is transparent and no cap image gives a pixel`
2979
+ : `${n} px of the disc, ${n - lowerMiss} on the upper side of the cut, where ${where}, and ${lowerMiss} on the lower side (cap_shape "ball"), where "${j.part}"'s layer is transparent and no cap image gives a pixel`;
2759
2980
  const half = j.half ?? 0;
2760
2981
  const disc =
2761
- k.shape === 'disc' || j.shortInHalf === undefined
2982
+ k.shape !== undefined || j.shortInHalf === undefined
2762
2983
  ? ''
2763
2984
  : j.shortInHalf === 0
2764
2985
  ? `; under cap_shape "disc" the disc is the half-width about the joint, ${half} px, and none of them lies within it`
2765
2986
  : `; under cap_shape "disc" the disc is the half-width about the joint, ${half} px, and ${j.shortInHalf} of them lie within it`;
2766
2987
  return (
2767
2988
  ` LINT "${j.part}" cap at [${k.at[0]}, ${k.at[1]}] (limb "${j.limb}", joint "${j.joint}", radius ${k.radius} px): short_px left ${k.short_px.left}, right ${k.short_px.right}: ` +
2768
- `no layer gives them — ${n} px of the disc on the upper side of the cut, where ${where}; the rest of the disc is filled, ${filled}${disc}`
2989
+ `no layer gives them — ${which}; the rest of the disc is filled, ${filled}${disc}`
2769
2990
  );
2770
2991
  }
2771
2992
 
@@ -2787,15 +3008,21 @@ export function limbLines(counts: readonly LimbCount[]): string[] {
2787
3008
  const radius =
2788
3009
  k.shape === undefined
2789
3010
  ? `a disc of radius ${k.radius} px (the limb ${k.width} px across the joint line)`
2790
- : `a disc of radius ${k.radius} px (cap_shape "disc": the joint's distance to the nearer side of the limb, ${k.width} px across the joint line)`;
3011
+ : `a disc of radius ${k.radius} px (cap_shape "${k.shape}": the joint's distance to the nearer side of the limb, ${k.width} px across the joint line)`;
3012
+ // Issue #579: the ball's lower half, counted apart; the missing pixels the line names on the upper side are that side's.
3013
+ const lowerMiss = k.lower_missing_px ?? 0;
3014
+ const upperMiss = k.missing_px - lowerMiss;
3015
+ const paintThem = `paint them into a ${k.box[2]}x${k.box[3]} image whose pixel (i, j) is rig pixel (${k.box[0]} + i, ${k.box[1]} + j), and name it in the segment's "cap"`;
2791
3016
  const shaped = [
3017
+ ...(k.shape === 'ball'
3018
+ ? [
3019
+ `cap_shape "ball": on the lower side of the line ${k.lower_px ?? 0} px written into "${j.part}" from ${k.image_px === undefined ? 'a cap image (none is named)' : k.image_layer === undefined ? 'the cap image' : `the hidden-art layer ${k.image_layer}`} where its layer is transparent (alpha 0), ${k.lower_kept_px ?? 0} px left as painted, ${lowerMiss === 0 ? 'none missing' : `${lowerMiss} px missing — the layer is transparent there and no cap image gives a pixel, and the tool invents none: ${paintThem}`}`,
3020
+ ]
3021
+ : []),
2792
3022
  ...(k.edge === undefined ? [] : [`edge "feather": ${k.feathered_px ?? 0} px of "${j.upper}" faded across the ${k.feather_radius ?? 0} px about the joint that "${j.part}" covers at every turn`]),
2793
3023
  ...(k.cut_band === undefined ? [] : [cutPhrase(k, j.upper, j.part)]),
2794
3024
  ];
2795
- const miss =
2796
- k.missing_px === 0
2797
- ? 'none missing'
2798
- : `${k.missing_px} px missing — the layer has no pixel there (hidden in the painting, or past the limb's outline), and the tool invents none: paint them into a ${k.box[2]}x${k.box[3]} image whose pixel (i, j) is rig pixel (${k.box[0]} + i, ${k.box[1]} + j), and name it in the segment's "cap"`;
3025
+ const miss = upperMiss === 0 ? 'none missing' : `${upperMiss} px missing — the layer has no pixel there (hidden in the painting, or past the limb's outline), and the tool invents none: ${paintThem}`;
2799
3026
  out.push(
2800
3027
  ` limb cap: "${j.limb}" joint "${j.joint}" at [${k.at[0]}, ${k.at[1]}], on "${j.part}": ${radius}, box [${k.box.join(', ')}] — on the upper side of the line ${from}, ${miss}${shaped.map((q) => `; ${q}`).join('')}`,
2801
3028
  );
@@ -3161,13 +3388,15 @@ function cutLimbs(
3161
3388
  // The width to 3 places (src/round.ts): a measured length, and a radius the line and the record print as read.
3162
3389
  const w3 = pyRound(run[1] - run[0] + 1, 3);
3163
3390
  // Issue #360: under cap_shape "disc" the radius is the half-width about the joint (src/limbs.ts), to 3 places as well.
3164
- const disc = sg.cap_shape === 'disc';
3391
+ // Issue #579: cap_shape "ball" is that disc and its upper half, and its lower half too (below).
3392
+ const ball = sg.cap_shape === 'ball';
3393
+ const disc = sg.cap_shape === 'disc' || ball;
3165
3394
  const half = halfWidthAbout(run);
3166
3395
  if (disc && half <= 0) {
3167
3396
  problems.push({
3168
3397
  code: 'ASSEMBLE_LIMB_JOINT_ON_ART',
3169
3398
  object,
3170
- detail: `the joint, "${sg.bone}"'s origin at [${line.at.join(', ')}], lies on the edge of the limb's art along its joint line — the run of art reaches ${pyRound(run[1] + 0.5, 3)} px from it one way and ${pyRound(0.5 - run[0], 3)} px the other — so cap_shape "disc" has no half-width about it; a bone origin inside the limb's art is required — move the bone onto the joint`,
3399
+ detail: `the joint, "${sg.bone}"'s origin at [${line.at.join(', ')}], lies on the edge of the limb's art along its joint line — the run of art reaches ${pyRound(run[1] + 0.5, 3)} px from it one way and ${pyRound(0.5 - run[0], 3)} px the other — so cap_shape "${String(sg.cap_shape)}" has no half-width about it; a bone origin inside the limb's art is required — move the bone onto the joint`,
3171
3400
  });
3172
3401
  return;
3173
3402
  }
@@ -3210,11 +3439,32 @@ function cutLimbs(
3210
3439
  let shortLeft = 0;
3211
3440
  let shortRight = 0;
3212
3441
  let shortInHalf = 0;
3442
+ // Issue #579: the ball's lower half — written from the image where the lower piece's pixel is transparent, kept
3443
+ // where the piece has a pixel, missing where neither gives one.
3444
+ let lowerPx = 0;
3445
+ let lowerKept = 0;
3446
+ let lowerMissing = 0;
3213
3447
  for (let y = Math.max(0, box[1]); y < Math.min(H, box[1] + box[3]); y++) {
3214
3448
  for (let x = Math.max(0, box[0]); x < Math.min(W, box[0] + box[2]); x++) {
3215
- if (!inDisc(line.at, radius, x, y) || pastJoint(cut, x, y)) continue;
3449
+ if (!inDisc(line.at, radius, x, y)) continue;
3216
3450
  const p = y * W + x;
3217
3451
  const u = img === null ? -1 : ((y - box[1]) * img.width + (x - box[0])) * 4;
3452
+ if (pastJoint(cut, x, y)) {
3453
+ if (!ball) continue;
3454
+ // Transparent is alpha 0, the reading the upper half's fill gives a layer's and the image's pixel: no pixel the
3455
+ // lower piece paints, however faint, changes.
3456
+ if (lower.data[p * 4 + 3] > 0) lowerKept++;
3457
+ else if (img !== null && img.data[u + 3] > 0) {
3458
+ lower.data.set(img.data.subarray(u, u + 4), p * 4);
3459
+ lowerPx++;
3460
+ } else {
3461
+ lowerMissing++;
3462
+ missing++;
3463
+ if (jointOffsets(line, x, y).across >= 0) shortLeft++;
3464
+ else shortRight++;
3465
+ }
3466
+ continue;
3467
+ }
3218
3468
  if (img !== null && img.data[u + 3] > 0) {
3219
3469
  lower.data.set(img.data.subarray(u, u + 4), p * 4);
3220
3470
  imagePx++;
@@ -3235,8 +3485,14 @@ function cutLimbs(
3235
3485
  }
3236
3486
  }
3237
3487
  }
3238
- if (img !== null && imagePx === 0 && hidden === null) {
3239
- problems.push({ code: 'ASSEMBLE_LIMB_CAP_EMPTY', object: `${object}.cap`, detail: `${String(sg.cap)} is transparent over every one of the cap's pixels; an image that gives at least one is required — to keep the layer's cap, drop cap` });
3488
+ if (img !== null && imagePx + lowerPx === 0 && hidden === null) {
3489
+ problems.push({
3490
+ code: 'ASSEMBLE_LIMB_CAP_EMPTY',
3491
+ object: `${object}.cap`,
3492
+ detail: ball
3493
+ ? `${String(sg.cap)} gives none of the cap's pixels: it is transparent over the disc's upper half and over every pixel of its lower half where "${sg.part}"'s layer is transparent (cap_shape "ball", issue #579); an image that gives at least one is required — to keep the layer's cap, drop cap`
3494
+ : `${String(sg.cap)} is transparent over every one of the cap's pixels; an image that gives at least one is required — to keep the layer's cap, drop cap`,
3495
+ });
3240
3496
  return;
3241
3497
  }
3242
3498
  // Issue #360: under edge "feather", the upper piece fades out across the cap, over the lower's opaque pixels only.
@@ -3278,7 +3534,13 @@ function cutLimbs(
3278
3534
  ...(hidden === null ? {} : { image_layer: hidden.layer }),
3279
3535
  missing_px: missing,
3280
3536
  ...(missing === 0 ? {} : { short_px: { left: shortLeft, right: shortRight } }),
3281
- ...(disc ? { shape: 'disc' as const, upper_px: upperPx } : upperPx === 0 ? {} : { upper_px: upperPx }),
3537
+ ...(ball
3538
+ ? { shape: 'ball' as const, upper_px: upperPx, lower_px: lowerPx, lower_kept_px: lowerKept, lower_missing_px: lowerMissing }
3539
+ : disc
3540
+ ? { shape: 'disc' as const, upper_px: upperPx }
3541
+ : upperPx === 0
3542
+ ? {}
3543
+ : { upper_px: upperPx }),
3282
3544
  ...(sg.edge === 'feather' ? { edge: 'feather' as const, feather_radius: band, feathered_px: featheredPx } : {}),
3283
3545
  ...(placed === undefined
3284
3546
  ? {}
@@ -3332,6 +3594,10 @@ export interface AssembleResult {
3332
3594
  projectRule: ProjectRule;
3333
3595
  /** Issue #492: head-canvas pixels filled by `config.assemble.head_face_underfill: true` when > 0. */
3334
3596
  headFaceUnderfillPx?: number;
3597
+ /** Issue #587: what each `exclude` entry took, in entry order; empty without one. */
3598
+ excluded: ExcludedCount[];
3599
+ /** Issue #588: what each limb segment part cut from a `limbIslands` part of more than one island kept; empty otherwise. */
3600
+ islands: IslandCount[];
3335
3601
  }
3336
3602
 
3337
3603
  /** A hidden-art layer of a run (issue #359) and what read it: `cuts[i].under`, or a limb segment's cap; none is said. */
@@ -3834,12 +4100,13 @@ export function assemble(input: AssembleInput): AssembleResult {
3834
4100
  }
3835
4101
  }
3836
4102
  // Issue #349: the limbs, after the cuts (a limb may take a cut's piece, and a cut's under image fills its base first).
3837
- const lim = cutLimbs(input.limbs ?? {}, input.bones ?? [], input.caps ?? new Map(), W, H, (name) => {
4103
+ const limbSource = (name: string): Built | null => {
3838
4104
  const pi = plan.findIndex((e) => e[0] === name);
3839
4105
  if (pi >= 0) return built[pi];
3840
4106
  const ci = cuts.findIndex((q) => q.into === name);
3841
4107
  return ci >= 0 ? pieces[ci] : null;
3842
- }, opaqueOf, mergedIn, count, (name) => hiddenArt.get(name) ?? null, (layer, by) => hiddenUses.get(layer)?.push(by));
4108
+ };
4109
+ const lim = cutLimbs(input.limbs ?? {}, input.bones ?? [], input.caps ?? new Map(), W, H, limbSource, opaqueOf, mergedIn, count, (name) => hiddenArt.get(name) ?? null, (layer, by) => hiddenUses.get(layer)?.push(by));
3843
4110
  // Issue #564: and the cap a run's own layer fills above its upper joint, read once the limbs are cut.
3844
4111
  if (bands !== null) refuseIfAny(limbBands(cuts, pieces, input.limbs ?? {}, input.bones ?? [], W, H, (l, k) => lim.parts.find((q) => q.limb === l && q.segment === k)?.record.cap).problems);
3845
4112
  const limbPieces = lim.pieces;
@@ -3847,6 +4114,31 @@ export function assemble(input: AssembleInput): AssembleResult {
3847
4114
  const pieceAt = (d: { plan: number } | { cut: number } | { limb: number }): { name: string; b: Built } =>
3848
4115
  'plan' in d ? { name: plan[d.plan][0], b: built[d.plan] as Built } : 'cut' in d ? { name: cuts[d.cut].into, b: pieces[d.cut] as Built } : { name: lim.parts[d.limb].part, b: limbPieces[d.limb] as Built };
3849
4116
 
4117
+ // Issue #588: a set that names one limb side keeps, in each part cut from a layer of more than one island, the island its joints fall on.
4118
+ const islandKept = (input.limbIslands ?? []).length === 0 ? { counts: [], problems: [] } : keepJointIslands(input.limbIslands ?? [], input.limbs ?? {}, input.bones ?? [], lim.parts, limbPieces, limbSource, W, H);
4119
+ refuseIfAny(islandKept.problems);
4120
+
4121
+ // Issue #587: a set's limb part loses the pixels a base part it does not replace covers, before anything is counted.
4122
+ const excluded: ExcludedCount[] = [];
4123
+ for (const ex of input.exclude ?? []) {
4124
+ const d = order.find((q) => !('patch' in q) && pieceAt(q).name === ex.part);
4125
+ const b = d === undefined || 'patch' in d ? null : pieceAt(d).b;
4126
+ let px = 0;
4127
+ if (b !== null) {
4128
+ if (b.region === null) {
4129
+ b.region = newMask(W, H);
4130
+ b.region.data.fill(1);
4131
+ }
4132
+ for (let p = 0; p < W * H; p++) {
4133
+ if (ex.mask.data[p] === 0 || b.r.data[p * 4 + 3] === 0) continue;
4134
+ if (b.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) px++;
4135
+ b.r.data.fill(0, p * 4, p * 4 + 4);
4136
+ b.region.data[p] = 0;
4137
+ }
4138
+ }
4139
+ excluded.push({ part: ex.part, under: ex.under, px });
4140
+ }
4141
+
3850
4142
  // Step 4b: push back a fringe the painting shows another part through, over
3851
4143
  // the plan parts still uncropped and the patches, in draw order.
3852
4144
  const stack: PlacedPart[] = order.map((d) => {
@@ -4008,6 +4300,8 @@ export function assemble(input: AssembleInput): AssembleResult {
4008
4300
  seamRule,
4009
4301
  projectRule,
4010
4302
  ...(headFacePrep.underfillPx > 0 ? { headFaceUnderfillPx: headFacePrep.underfillPx } : {}),
4303
+ excluded,
4304
+ islands: islandKept.counts,
4011
4305
  };
4012
4306
  }
4013
4307
 
package/src/build.ts CHANGED
@@ -44,7 +44,7 @@ import { createHash } from 'node:crypto';
44
44
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
45
45
  import { dirname, join, resolve } from 'node:path';
46
46
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
47
- import { assemble, type AssembleResult, cutLines, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, holeKindsLine, holeLines, measureRecomposite, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine } from './assemble.ts';
47
+ import { assemble, type AssembleResult, cutLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, holeKindsLine, holeLines, measureRecomposite, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine } from './assemble.ts';
48
48
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
49
49
  import { residualClause } from './autoenvelope.ts';
50
50
  import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, type ReplayCandidate, runComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
@@ -159,6 +159,19 @@ export interface AssembleStageInput {
159
159
  * selftest's control that shows a foreshortened segment refused under it.
160
160
  */
161
161
  altPlacement?: 'skeleton' | 'angles';
162
+ /**
163
+ * What a subset set's limb parts take under a base part the set does not replace (issue #587): `"base"` (the
164
+ * default, the only one the CLI runs) excludes the pixels that base part covers at setup ({@link setExclusions});
165
+ * `"none"` takes them, the rule before #587 — kept for the selftest's control that shows the count go red under it.
166
+ */
167
+ setExclusion?: 'base' | 'none';
168
+ /**
169
+ * What a subset set's limb parts keep of a layer of more than one island when the set names one limb side (issue
170
+ * #588): `"joints"` (the default, the only one the CLI runs) the island the segment's joints fall on
171
+ * ({@link setIslandSources}); `"all"` every island, the rule before #588 — kept for the selftest's control that
172
+ * shows the island count go red under it.
173
+ */
174
+ setIslands?: 'joints' | 'all';
162
175
  }
163
176
 
164
177
  /** Where the assemble stage writes: `parts.json`, the directory of part PNGs, the recomposite, and its error map. */
@@ -314,7 +327,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
314
327
  }
315
328
 
316
329
  const altProblems: Problem[] = [];
317
- const altBuilt: Array<{ record: AlternatePartsRecord; images: Array<{ name: string; image: Raster }> }> = [];
330
+ const altBuilt: Array<{ record: AlternatePartsRecord; images: Array<{ name: string; image: Raster }>; excluded: ExcludedCount[]; islands: IslandCount[] }> = [];
318
331
  const baseSlots = result.parts.parts.map((p) => p.name);
319
332
  for (const alt of mergedAlts) {
320
333
  if (alt.source === undefined || alt.full === undefined) {
@@ -502,6 +515,14 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
502
515
  altBones = poseBoneEntriesForDrawn(fields.bones, limbDrawn);
503
516
  }
504
517
  }
518
+ // Issue #587: a subset set's limb part takes nothing a base part it does not replace covers at setup.
519
+ const [exW, exH] = result.parts.rig_size;
520
+ const altExclude =
521
+ alt.parts === undefined || input.setExclusion === 'none'
522
+ ? []
523
+ : setExclusions(result.images, exW, exH, Object.values(altLimbs).flatMap((l) => l.segments.map((sg) => sg.part)), new Set([...coveredSet, ...hidesSet]));
524
+ // Issue #588: a subset set that names one limb side keeps, of a layer that holds more than one island, the one its joints fall on.
525
+ const altIslands = alt.parts === undefined || input.setIslands === 'all' ? [] : setIslandSources(fields.limbs ?? {}, altLimbs);
505
526
  let altRes: ReturnType<typeof assemble>;
506
527
  try {
507
528
  altRes = assemble({
@@ -522,6 +543,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
522
543
  ...(fields.headFaceUnderfill === undefined ? {} : { headFaceUnderfill: fields.headFaceUnderfill }),
523
544
  seamRule: input.seam,
524
545
  projectRule: input.project,
546
+ ...(altExclude.length === 0 ? {} : { exclude: altExclude }),
547
+ ...(altIslands.length === 0 ? {} : { limbIslands: altIslands }),
525
548
  });
526
549
  } catch (err) {
527
550
  if (err instanceof PartsError) {
@@ -569,6 +592,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
569
592
  ...(altRegistration === undefined ? {} : { registration: altRegistration }),
570
593
  },
571
594
  images: keptImages,
595
+ excluded: altRes.excluded,
596
+ islands: altRes.islands,
572
597
  });
573
598
  }
574
599
  refuseIfAny(altProblems);
@@ -630,6 +655,9 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
630
655
  if (result.figures.uncoveredErrorPx > 0) log(holeKindsLine(result.holeKinds, scene));
631
656
  for (const u of result.uncovered) log(uncoveredLine(u, scene));
632
657
  for (const d of result.drift) log(driftLine(d));
658
+ // Issue #588: per subset set, one line per limb part cut from a layer of more than one island, then (issue #587) one
659
+ // per limb part and base part over it that took a pixel. None otherwise.
660
+ for (const b of altBuilt) for (const l of [...islandLines(b.record.name, b.islands), ...excludedLines(b.record.name, b.excluded)]) log(l);
633
661
  log(`wrote ${outs.partsJson}, ${result.images.length} PNG(s) in ${outs.partsDir}, ${outs.recomposite}, ${outs.errorMap} (uncovered error px red, covered error px blue, the painting grey)${figurePath === null ? '' : `, ${figurePath} (the figure, white, the recomposite was read inside)`}`);
634
662
  return result;
635
663
  }