rig-parts 2.57.0 → 2.59.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
@@ -579,6 +579,7 @@ and do not certify visibility. See the
579
579
  | `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`, `--owners`, `--help` (`-h`); exactly one of `--out`, `--verify` (issues #1005, #1291; exhaustive native error inventory, `rig-parts-diff-components/1` by default and `rig-parts-diff-components/2` with `--owners`, and byte-bound reader for both) |
580
580
  | `diff-drafts` | `--left`, `--right`, `--out`; optional `--help` (`-h`) (issue #1369; draft-to-draft assemble comparison, `rig-parts-draft-diff/1`) |
581
581
  | `depth-prepare` | `--parts`, `--config`, `--out`; optional `--help` (`-h`) (issue #897; separate numeric-depth recipe) |
582
+ | `depth-map` | `--array`, `--input`, `--kind` (`depth` or `normals`), `--part`, `--out`; optional `--padding` (`LEFT,TOP,RIGHT,BOTTOM`), `--help` (`-h`) (issue #1573; NumPy array to input-frame numeric map) |
582
583
  | `depth-bind` | `--map`, `--input`, `--part`; optional `--help` (`-h`) (issue #1284; exclusive receipt creation from current file bytes) |
583
584
  | `depth-apply` | `--parts`, `--manifest`, `--config`, `--rig-config`, `--out`; optional `--groups` (a comma-separated list of the recipe's groups to apply, issue #1449), `--help` (`-h`) (issue #897; original character config is read-only) |
584
585
  | `layers` | one positional path: a wrapper directory, a `layers.json` or a `.psd` (a file literally named `-h` is reached as `./-h`); with it, optional `--export` (a directory to write the wrapper form into, issue #359); or `--template` with `--canvas` and no path; or a positional head run with `--full`, `--source`, `--config` together for `PLAN_HEAD_GARMENT_OVERLAP` (issue #826); or `--help` (`-h`) |
@@ -790,7 +791,7 @@ part name, `[i]` an entry of a list):
790
791
  - **turn.unitDepths.<part>** — a calibrated world depth in rig pixels (issue #763)
791
792
  - **turn.body**, when an object — required: `roles`, `pivot` (when `turn.pivot` is absent); optional: `bone`, `slider`, `counter`, `grid`, `unitDepths`, `boundaryDepths` (issue #787)
792
793
  - **turn.body.roles.<part>** — `"surface"`, `"unit"` or `"rear"` (issue #787)
793
- - **turn.body.unitDepths.<part>** — a calibrated world depth in rig pixels (issue #787)
794
+ - **turn.body.unitDepths.<part>** — a calibrated world depth in rig pixels; body yaw uses `-(pivot + z - zRef) * sin(a)` ([Unit depth precedence](AUTHORING.md#unit-depth-precedence))
794
795
  - **turn.deform.<key>** — a per-degree fraction or coupling share (FACE_DEFORM_FRACTIONS, issue #436)
795
796
  - **turn.band**, when an object — optional: `yaw`, `pitch` (issue #472)
796
797
  - **turn.surface**, when an object — optional: `radius` (issue #479)
@@ -1437,8 +1438,9 @@ the spec. A key added, removed or redefined is a new spec version.
1437
1438
 
1438
1439
  ### Run record (`check-run.json` and `build-run.json`, spec `rig-run/2`)
1439
1440
 
1440
- `check` writes `<out>/check-run.json` and `build` writes `<out>/build-run.json`
1441
- (issue #1541) whenever the run completed its check report, green or not. The names
1441
+ `check` writes `<out>/check-run.json` whenever the run completed its check report,
1442
+ green or not (issue #1541). `build` originally wrote `<out>/build-run.json` in this
1443
+ format. Its current contract is [the build run record](#build-run-record-build-runjson-spec-rig-run3). The names
1442
1444
  cannot be a `run.json`: `rig` and `assemble` write `rig-run/1` as `run.json`, and
1443
1445
  rigc writes its own `run.json` in a packed build directory (`check/build/`). Neither
1444
1446
  file is in `check.json`, and no byte comparison this package makes reads them.
@@ -1461,9 +1463,9 @@ file is in `check.json`, and no byte comparison this package makes reads them.
1461
1463
  Key order is fixed as shown: `spec`, `package`, `command`, `started_at`,
1462
1464
  `finished_at`, `config` (`build` only; `check` reads no config), `outputs`, `argv`.
1463
1465
  `package` and the two times (`SOURCE_DATE_EPOCH` included) are as in `rig-run/1`.
1464
- `config` is the config's `sha256` and its path relative to the real `--out`
1465
- directory, with the config's directory resolved through its links and the file's
1466
- own name kept: a config given through a link is recorded by the link's name.
1466
+ `config` is the config's `sha256` and its path relative to `--out`, using the
1467
+ same directory spelling rule as `argv` below. A config given through a link is
1468
+ recorded by the link's name.
1467
1469
  `outputs` lists every file under the paths the run cleared and wrote —
1468
1470
  for `check`, the report files its `wrote` line names and the directories it names
1469
1471
  (`build/`, `idle_frames/`, …); for `build`, the paths it clears before it starts —
@@ -1475,23 +1477,121 @@ any `-run.json`. Two runs of the same inputs from the same layout differ only in
1475
1477
  `argv` is the command to re-run, then the options as given — not the defaults the
1476
1478
  run used — in the order of the command's flag table (`check --help` lists it):
1477
1479
  valued flags first, a repeated `--alt` in the order given, then the switches
1478
- present. Every path is written relative to the `--out` directory with `/`
1479
- separators: both taken from the working directory, the `--out` directory and the
1480
- path's directory resolved through their links, and the path's own name kept (a path
1481
- given through a link is written by the link's name, as `config.path` is);
1482
- `--out` itself is `.`; a path that cannot be written that way (another Windows drive)
1483
- is written as given. These arguments reproduce the check with the same package
1484
- version, run from the --out directory. When `--out` was given through a link, the
1485
- replay's `build/skeleton.json`, `build/skeleton.model.json` and `check.json` can
1486
- differ from the first run's: rigc spells the skeleton's `images` path from the `--out`
1487
- it is handed without resolving links (rig-c/core#1773). Every other output and key
1488
- matches. A switch's default is not written, so a later
1480
+ present. Each path and `--out` are taken from the working directory. On POSIX,
1481
+ the `--out` directory and the path's directory are resolved through their links.
1482
+ On Windows, both directories keep their supplied spelling. The path keeps its
1483
+ own name and is written relative to `--out` with `/` separators. `--out` itself
1484
+ is `.`. A path on another Windows drive is written as given. These arguments
1485
+ reproduce the check when run from the `--out` directory with the same package
1486
+ version. A switch's default is not written, so a later
1489
1487
  version that changed it would replay differently; that is why the version is in
1490
1488
  `package`. The record is written after the report, in place, and is never a reason to refuse
1491
1489
  the check; a run killed while writing it can leave a partial record, and no other
1492
1490
  file.
1493
1491
 
1494
- `rig-run/2` is stable on the same terms as `rig-run/1`.
1492
+ `rig-run/2` is stable on the same terms as `rig-run/1`. The `check` record retains
1493
+ the same format and bytes for the same files, invocation, version and times.
1494
+
1495
+ ### Build run record (`build-run.json`, spec `rig-run/3`)
1496
+
1497
+ `build` writes `<out>/build-run.json` when its check report completes, including a
1498
+ report with failing bars. Issue #1556 advances `spec` to `rig-run/3` and adds
1499
+ `inputs` between `config` and `outputs`. The fixed key order is `spec`, `package`,
1500
+ `command`, `started_at`, `finished_at`, `config`, `inputs`, `outputs`, `argv`.
1501
+ The other fields and the write timing follow the `rig-run/2` build contract above.
1502
+
1503
+ This example shows a build with full and head layer directories and one alternate tuple.
1504
+ The version and digests are illustrative, and the output list is abbreviated.
1505
+
1506
+ ```json
1507
+ {
1508
+ "spec": "rig-run/3",
1509
+ "package": { "name": "@rig-c/parts", "version": "2.57.0" },
1510
+ "command": "build",
1511
+ "started_at": "2026-11-25T00:00:00.000Z",
1512
+ "finished_at": "2026-11-25T00:00:01.000Z",
1513
+ "config": {
1514
+ "path": "../config.json",
1515
+ "sha256": "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
1516
+ },
1517
+ "inputs": [
1518
+ {
1519
+ "role": "source",
1520
+ "path": "../painting.png",
1521
+ "sha256": "112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00"
1522
+ },
1523
+ {
1524
+ "role": "full",
1525
+ "path": "../layers/full/layers.json",
1526
+ "sha256": "2233445566778899aabbccddeeff00112233445566778899aabbccddeeff0011"
1527
+ },
1528
+ {
1529
+ "role": "head",
1530
+ "path": "../layers/head/layers.json",
1531
+ "sha256": "33445566778899aabbccddeeff00112233445566778899aabbccddeeff001122"
1532
+ },
1533
+ {
1534
+ "role": "alt[0].source",
1535
+ "path": "../side/painting.png",
1536
+ "sha256": "445566778899aabbccddeeff00112233445566778899aabbccddeeff00112233"
1537
+ },
1538
+ {
1539
+ "role": "alt[0].full",
1540
+ "path": "../side/full/layers.json",
1541
+ "sha256": "5566778899aabbccddeeff00112233445566778899aabbccddeeff0011223344"
1542
+ },
1543
+ {
1544
+ "role": "alt[0].head",
1545
+ "path": "../side/head/layers.json",
1546
+ "sha256": "66778899aabbccddeeff00112233445566778899aabbccddeeff001122334455"
1547
+ }
1548
+ ],
1549
+ "outputs": [
1550
+ {
1551
+ "path": "check/check.json",
1552
+ "sha256": "778899aabbccddeeff00112233445566778899aabbccddeeff00112233445566"
1553
+ }
1554
+ ],
1555
+ "argv": [
1556
+ "build", "--config", "../config.json", "--source", "../painting.png",
1557
+ "--full", "../layers/full", "--head", "../layers/head", "--out", ".",
1558
+ "--alt", "side=../side/painting.png:../side/full:../side/head"
1559
+ ]
1560
+ }
1561
+ ```
1562
+
1563
+ Each entry has keys `role`, `path`, `sha256` in that order. The array follows this
1564
+ order regardless of where each flag appears in `argv`.
1565
+
1566
+ | Order | Role | CLI input | File hashed |
1567
+ | --- | --- | --- | --- |
1568
+ | 1 | `source` | `--source` | Painting PNG |
1569
+ | 2 | `full` | `--full` | `<dir>/layers.json` for a directory, or the supplied manifest or PSD |
1570
+ | 3 | `head` | `--head` | `<dir>/layers.json` for a directory, or the supplied manifest or PSD |
1571
+ | 4 | `requirements` | `--requirements` | Requirements JSON |
1572
+ | 5 | `environment` | `--environment` | Environment schedule JSON |
1573
+ | 6 | `wind-band` | `--wind-band` | Wind-band spec JSON |
1574
+ | For each `--alt` in CLI order, first | `alt[i].source` | Tuple source | Alternate painting PNG |
1575
+ | For each `--alt` in CLI order, second | `alt[i].full` | Tuple full | `<dir>/layers.json` for a directory, or the supplied manifest or PSD |
1576
+ | For each `--alt` in CLI order, third | `alt[i].head` | Tuple head | `<dir>/layers.json` for a directory, or the supplied manifest or PSD |
1577
+
1578
+ `i` is zero-based and counts the `--alt` occurrences. Entries for optional flags
1579
+ or tuple members appear only when supplied. The array inventories CLI file
1580
+ inputs. References declared only inside the config and files referenced by a
1581
+ layer manifest are outside this inventory. `config` binds `--config` separately,
1582
+ and `--out` is the output root.
1583
+
1584
+ The run-record writer reads and hashes the raw bytes on disk of the file named by
1585
+ `path` after the check report completes. Keep input files and link targets unchanged
1586
+ from the start of the build until it exits so these digests describe the bytes the
1587
+ stages read.
1588
+
1589
+ Each path uses the shared `--out` link rule. On POSIX the output directory and
1590
+ the file's parent directory resolve through links, and the final filename is kept,
1591
+ including when that filename is a link. On Windows the path is rebased as spelled. Relative
1592
+ paths use `/` separators. A file on another Windows drive is recorded by its
1593
+ file path as given, with `layers.json` appended when the argument names a directory.
1594
+ The paths are relative to the build's `--out` root.
1495
1595
 
1496
1596
  ## Environment
1497
1597
 
@@ -2147,9 +2247,40 @@ field is absent without the flag, so those reports keep their bytes, and
2147
2247
  `relief` is an explicit rig-pixel value, not an implicit width multiplier.
2148
2248
  Part-width and head-referenced calibrations are authored recipe choices;
2149
2249
  changing a calibration requires preparing its recipe again. Compare the same
2150
- provider maps and preserve their provenance. Each report row names the part,
2151
- declared relief, group `zScale` and clipping over original alpha>=128 support;
2152
- it remains a measurement rather than a shape-quality gate.
2250
+ provider maps and preserve their provenance. The additive `DEPTH_APPLY_CLIPPED`
2251
+ refusal applies before any output write, including for previously accepted
2252
+ clipped recipes, regardless of map binding receipt presence. Every original
2253
+ part pixel with alpha >= 128 must satisfy
2254
+ `0 < z < zScale` before encoding. The clip fraction divides the number of
2255
+ supported pixels at or beyond either boundary by the total supported pixel
2256
+ count.
2257
+
2258
+ For upper clipping the refusal gives the smallest binary64 group `zScale`
2259
+ strictly above the maximum original supported depth in the group. For each
2260
+ part with lower clipping it gives the minimum authored median (the next
2261
+ binary64 value above the maximum negated relief offset over that part's
2262
+ support) and its difference from the previous authored median. When both
2263
+ boundaries clip, the refusal includes both remedies. If a required value has
2264
+ no finite binary64 representation, the refusal directs the author to revise
2265
+ the calibration. A median adjustment may require recomputing the group scale.
2266
+
2267
+ `rig-parts-depth-report/1` keeps its existing keys. Each successful row names
2268
+ the part, declared relief, group `zScale` and a zero `clipFraction` over the
2269
+ original alpha >= 128 support. Shape quality is assessed separately.
2270
+
2271
+ `depth-map` (issue #1573) is an additive minor-version command. It accepts
2272
+ C-order NumPy `.npy` 1.0, 2.0, and 3.0 arrays with little-endian `float32` or
2273
+ `float64` data. Depth accepts `(H, W)` or `(H, W, 1)`. Normals accept
2274
+ `(H, W, 3)` with signed XYZ components in image axes (X right, Y down).
2275
+ Declared array-edge padding is cropped before mean pooling with independent
2276
+ positive integral X and Y factors derived from the prepared PNG dimensions.
2277
+ Pooled normals are normalized to unit length. The command refuses retained
2278
+ nonfinite samples, retained zero normals, and pooled zero normals by pixel.
2279
+ `--out` must name a new file in an existing writable directory. The command
2280
+ writes only the `rig-parts-map/1` JSON at the PNG dimensions and prints the
2281
+ next `depth-bind` command with its arguments quoted for a POSIX shell.
2282
+ Hand-authored `rig-parts-map/1` maps continue through
2283
+ the same bind and apply stages. See [Convert a NumPy array](DEPTH.md#convert-a-numpy-array).
2153
2284
 
2154
2285
  The requirements file's `fps` becomes optional when no declared measurement
2155
2286
  reads that rate (issue #965, additive for readers). Measurements in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "2.57.0",
3
+ "version": "2.59.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
  "exports": {
@@ -75,7 +75,7 @@
75
75
  },
76
76
  "dependencies": {
77
77
  "ag-psd": "^31.0.2",
78
- "@rig-c/core": "3.8.1"
78
+ "@rig-c/core": "3.9.2"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@esotericsoftware/spine-core": "4.3.13",
package/src/build.ts CHANGED
@@ -2952,7 +2952,7 @@ export interface BuildRunners {
2952
2952
  scratch: string;
2953
2953
  }
2954
2954
 
2955
- /** The `rig-run/2` record `build` writes beside its outputs (issue #1541); cleared with them, so a refused build leaves none. */
2955
+ /** The `rig-run/3` record `build` writes beside its outputs after the check report (issues #1541, #1556). */
2956
2956
  export const BUILD_RUN_FILE = 'build-run.json';
2957
2957
  /** Every path `build` writes under `--out`, relative — and so every path it clears first. */
2958
2958
  export const BUILD_OWNS: readonly string[] = ['parts', 'parts.json', SOURCE_COVER_FILE, PAINTING_IN_RIG_FILE, 'recomposite_rig.png', ERROR_MAP_FILE, 'rig', 'check', 'idle.gif', 'idle.png', 'idle-indexed.png', BUILD_RUN_FILE];
@@ -2961,8 +2961,11 @@ export const BUILD_OWNS_FILES: readonly string[] = [CUT_MATERIAL_SOURCES, EDGE_R
2961
2961
 
2962
2962
  function resetBuildOutput(out: string): void {
2963
2963
  makeOutDir(out);
2964
- for (const p of BUILD_OWNS) rmSync(join(out, p), { recursive: true, force: true });
2965
- for (const p of BUILD_OWNS_FILES) rmSync(join(out, p), { force: true });
2964
+ // Bun on Windows returned EINVAL removing a relative path through a junction (BU1556C).
2965
+ // Resolve the spelling against cwd so the path is absolute and keeps the junction.
2966
+ const cleanupOut = sep === '\\' ? resolve(out) : out;
2967
+ for (const p of BUILD_OWNS) rmSync(join(cleanupOut, p), { recursive: true, force: true });
2968
+ for (const p of BUILD_OWNS_FILES) rmSync(join(cleanupOut, p), { force: true });
2966
2969
  }
2967
2970
 
2968
2971
  /** Only selects when cleanup occurs; the real config loader still decides validity. */
package/src/depthmaps.ts CHANGED
@@ -149,7 +149,9 @@ export function integrateNormals(map: NumericMap, art: Raster, at: string): Norm
149
149
  }
150
150
 
151
151
  export interface MapSheetReading { levels: number; clipFraction: number; reliefRigPixels: number; rawMedian: number; rawP5: number; rawP95: number }
152
- export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number, relief: number, near: 'black' | 'white', zScale: number, at: string): { sheet: Raster; reading: MapSheetReading } {
152
+ export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number, relief: number, near: 'black' | 'white', zScale: number, at: string): {
153
+ sheet: Raster; reading: MapSheetReading; maxZ: number; minOffset: number; clipsLow: boolean;
154
+ } {
153
155
  const support = alphaSupport(art), values: number[] = [];
154
156
  for (let i = 0; i < support.length; i++) if (support[i]) values.push(data[i]);
155
157
  if (!values.length) return depthMapFail('DEPTH_MAP_SUPPORT', at, 'has no alpha>=128 pixels; a part with declared support is required');
@@ -158,13 +160,21 @@ export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number,
158
160
  if (![med, lo, hi, spread].every(Number.isFinite)) return depthMapFail('DEPTH_MAP_FORMAT', at, 'normalization overflows finite arithmetic; provide finite representable median and percentile spread');
159
161
  if (spread === 0 && relief !== 0) return depthMapFail('DEPTH_MAP_SPREAD', at, `p5=p95=${lo} but relief=${relief}; a nonflat map or explicit relief 0 is required`);
160
162
  const sheet = newRaster(art.width, art.height), seeds = newRaster(art.width, art.height), levels = new Set<number>(); let clipped = 0;
163
+ let maxZ = -Infinity, minOffset = Infinity, clipsLow = false;
161
164
  for (let i = 0; i < support.length; i++) {
162
- const z = median + relief * (spread === 0 ? 0 : (data[i] - med) / spread), unit = Math.max(0, Math.min(1, near === 'white' ? z / zScale : 1 - z / zScale));
165
+ const offset = relief * (spread === 0 ? 0 : (data[i] - med) / spread);
166
+ const z = median + offset, unit = Math.max(0, Math.min(1, near === 'white' ? z / zScale : 1 - z / zScale));
163
167
  if (!Number.isFinite(z) && support[i]) return depthMapFail('DEPTH_MAP_FORMAT', at, `world depth at support pixel ${i} overflows; declare representable median/relief and raw numbers`);
164
168
  // Uint8ClampedArray implements ties-to-even, as numpy.round does.
165
169
  sheet.data[i * 4] = unit * 255; sheet.data[i * 4 + 1] = sheet.data[i * 4 + 2] = sheet.data[i * 4]; sheet.data[i * 4 + 3] = 255;
166
170
  seeds.data[i * 4 + 3] = support[i] ? 255 : 0;
167
- if (support[i]) { levels.add(sheet.data[i * 4]); if (z <= 0 || z >= zScale) clipped++; }
171
+ if (support[i]) {
172
+ levels.add(sheet.data[i * 4]);
173
+ maxZ = Math.max(maxZ, z);
174
+ minOffset = Math.min(minOffset, offset);
175
+ if (z <= 0) clipsLow = true;
176
+ if (z <= 0 || z >= zScale) clipped++;
177
+ }
168
178
  }
169
- return { sheet: extendDepthSilhouette(sheet, seeds), reading: { levels: levels.size, clipFraction: clipped / values.length, reliefRigPixels: relief, rawMedian: med, rawP5: lo, rawP95: hi } };
179
+ return { sheet: extendDepthSilhouette(sheet, seeds), reading: { levels: levels.size, clipFraction: clipped / values.length, reliefRigPixels: relief, rawMedian: med, rawP5: lo, rawP95: hi }, maxZ, minOffset, clipsLow };
170
180
  }
@@ -28,6 +28,14 @@ interface PreparedPart { part: string; crop: number[]; sourceSha256: string; inp
28
28
  interface Prepared { spec: 'rig-parts-depth-inputs/1'; partsSha256: string; recipeSha256: string; background: number; alpha: number; parts: PreparedPart[] }
29
29
  const hash = (bytes: Uint8Array | string): string => createHash('sha256').update(bytes).digest('hex');
30
30
  const text = (raw: unknown): string => JSON.stringify(raw, null, 2) + '\n';
31
+ /** The next binary64 value above a finite, nonnegative depth bound. */
32
+ function aboveDepthBound(bound: number): number {
33
+ if (bound === 0) return Number.MIN_VALUE;
34
+ const bits = new DataView(new ArrayBuffer(8));
35
+ bits.setFloat64(0, bound);
36
+ bits.setBigUint64(0, bits.getBigUint64(0) + 1n);
37
+ return bits.getFloat64(0);
38
+ }
31
39
  function object(raw: unknown, at: string): Obj {
32
40
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return fail('DEPTH_RECIPE', at, 'requires an object with the documented fields');
33
41
  return raw as Obj;
@@ -272,6 +280,8 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
272
280
  refuseStaleAssembly(outConfig, file, relocatedConfig);
273
281
  const warnings: string[] = [];
274
282
  const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
283
+ const groupMaxZ = new Map<string, number>();
284
+ const clipped: { name: string; group: string; fraction: number; clipsHigh: boolean; median: number; minMedian?: number }[] = [];
275
285
  // Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
276
286
  // Symlink inputs would obscure ownership and can escape this assembled directory.
277
287
  const retained = new Map<string, Uint8Array>();
@@ -314,13 +324,32 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
314
324
  if (map.channels !== 1) fail('DEPTH_MAP_FORMAT', name, 'depth requires one floating-point channel');
315
325
  values = floatBox(map.data, map.width, map.height, art.width, art.height);
316
326
  }
317
- const { sheet, reading } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name), image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
327
+ const { sheet, reading, maxZ, minOffset, clipsLow } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name);
328
+ groupMaxZ.set(declaration.group, Math.max(groupMaxZ.get(declaration.group) ?? -Infinity, maxZ));
329
+ if (reading.clipFraction > 0) {
330
+ clipped.push({ name, group: declaration.group, fraction: reading.clipFraction, clipsHigh: maxZ >= g.zScale, median: declaration.median,
331
+ ...(clipsLow ? { minMedian: aboveDepthBound(-minOffset) } : {}) });
332
+ continue;
333
+ }
334
+ const image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
318
335
  if (file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
319
336
  writes.set(image, sheetBytes);
320
337
  if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path);
321
338
  rec.depth = { image, near: g.near, zScale: g.zScale, sources: [{ from: p.from, image: basename(declaration.map), sha256: hash(mapBytes), crop: [0, 0, art.width, art.height], reading: depthReading(sheet, art, null) }] };
322
339
  rows.push({ part: name, group: declaration.group, source: declaration.source, frame: declaration.frame, sourceSha256: prepared.sourceSha256, mapSha256: hash(mapBytes), inputSha256: prepared.inputSha256, sheetSha256: hash(sheetBytes), median: declaration.median, relief: declaration.relief, near: g.near, zScale: g.zScale, pivot: g.pivot, ...reading, sign: normal?.sign ?? 1, ...(normal === undefined ? {} : { integration: { stride: 2, iterations: normal.iterations, residual: normal.residual, coreMinusRim: normal.coreMinusRim, maxIterations: 3000, atol: 1e-6, btol: 1e-6 } }) });
323
340
  }
341
+ if (clipped.length) throw new PartsError(clipped.map(({ name, group, fraction, clipsHigh, median, minMedian }) => {
342
+ const details = [`clip=${fraction} in group "${group}"`];
343
+ if (clipsHigh) {
344
+ const maxZ = groupMaxZ.get(group)!;
345
+ const required = aboveDepthBound(maxZ);
346
+ details.push(Number.isFinite(required) ? `required zScale=${required} (group max z=${maxZ})` : `no finite zScale exceeds group max z=${maxZ}; revise median or relief`);
347
+ }
348
+ if (minMedian !== undefined) {
349
+ details.push(Number.isFinite(minMedian) ? `required median=${minMedian} (rise ${minMedian - median} rig px)` : 'no finite median clears z<=0; reduce relief');
350
+ }
351
+ return { code: 'DEPTH_APPLY_CLIPPED', object: `part "${name}"`, detail: details.join('; ') };
352
+ }));
324
353
  // A replacement must share near/zScale with every retained part in its actual group.
325
354
  for (const [name, g] of Object.entries(recipe.groups)) {
326
355
  if (!applied(name)) continue;
@@ -0,0 +1,206 @@
1
+ /** Convert a raw NumPy model array to the prepared image's numeric map grid. */
2
+ import { depthMapFail as fail, type NumericMap } from './depthmaps.ts';
3
+
4
+ const MAGIC = [0x93, 0x4e, 0x55, 0x4d, 0x50, 0x59]; // \x93NUMPY
5
+
6
+ function readHeader(header: string, at: string): { shape: number[]; itemBytes: 4 | 8 } {
7
+ const malformed = (): never => fail('DEPTH_ARRAY_FORMAT', at,
8
+ 'malformed NumPy header; required a dictionary with exactly descr, fortran_order and shape, followed by a newline');
9
+ if (!header.endsWith('\n')) return malformed();
10
+ const body = header.slice(0, -1);
11
+ let offset = 0;
12
+ const skipSpace = (): void => {
13
+ while (body[offset] === ' ' || body[offset] === '\t') offset++;
14
+ };
15
+ const take = (token: RegExp): RegExpExecArray | null => {
16
+ skipSpace();
17
+ token.lastIndex = offset;
18
+ const match = token.exec(body);
19
+ if (match !== null) offset = token.lastIndex;
20
+ return match;
21
+ };
22
+ const expect = (token: RegExp): RegExpExecArray => take(token) ?? malformed();
23
+ const quoted = (): string => {
24
+ const match = expect(/'([^'\\\r\n]*)'|"([^"\\\r\n]*)"/y);
25
+ return match[1] ?? match[2];
26
+ };
27
+ expect(/\{/y);
28
+ let descr: string | undefined, order: string | undefined, shape: number[] | undefined;
29
+ while (take(/\}/y) === null) {
30
+ const key = quoted();
31
+ expect(/:/y);
32
+ if (key === 'descr' && descr === undefined) descr = quoted();
33
+ else if (key === 'fortran_order' && order === undefined) order = expect(/True|False/y)[0];
34
+ else if (key === 'shape' && shape === undefined) {
35
+ shape = [];
36
+ expect(/\(/y);
37
+ if (take(/\)/y) === null) {
38
+ do {
39
+ shape.push(Number(expect(/-?(?:0|[1-9][0-9]*)/y)[0]));
40
+ if (take(/,/y) !== null) continue;
41
+ if (shape.length === 1) return malformed(); // A one-element tuple needs its comma.
42
+ expect(/\)/y);
43
+ break;
44
+ } while (take(/\)/y) === null);
45
+ }
46
+ } else return malformed();
47
+ if (take(/,/y) === null) {
48
+ expect(/\}/y);
49
+ break;
50
+ }
51
+ }
52
+ skipSpace();
53
+ if (offset !== body.length || descr === undefined || order === undefined || shape === undefined) return malformed();
54
+ if (descr !== '<f4' && descr !== '<f8') return fail('DEPTH_ARRAY_FORMAT', at,
55
+ `dtype ${JSON.stringify(descr)}; required little-endian float32 (<f4) or float64 (<f8)`);
56
+ if (order !== 'False') return fail('DEPTH_ARRAY_FORMAT', at, `fortran_order=${order}; required False (C order)`);
57
+ return { shape, itemBytes: descr === '<f4' ? 4 : 8 };
58
+ }
59
+
60
+ function readArray(bytes: Uint8Array, kind: 'depth' | 'normals', at: string) {
61
+ if (!MAGIC.every((byte, i) => bytes[i] === byte) || bytes.length < 8) return fail('DEPTH_ARRAY_FORMAT', at,
62
+ `found ${bytes.length} bytes without a complete NumPy magic/version prefix; required a NumPy .npy file`);
63
+ const major = bytes[6], minor = bytes[7];
64
+ if ((major !== 1 && major !== 2 && major !== 3) || minor !== 0) return fail('DEPTH_ARRAY_FORMAT', at,
65
+ `NumPy version ${major}.${minor}; required 1.0, 2.0 or 3.0`);
66
+ const prefix = major === 1 ? 10 : 12;
67
+ if (bytes.length < prefix) return fail('DEPTH_ARRAY_FORMAT', at,
68
+ `found ${bytes.length} bytes; required ${prefix} for the NumPy ${major}.0 prefix and header length`);
69
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
70
+ const length = major === 1 ? view.getUint16(8, true) : view.getUint32(8, true);
71
+ const start = prefix + length;
72
+ if (start > bytes.length) return fail('DEPTH_ARRAY_FORMAT', at,
73
+ `header declares ${length} bytes; found ${bytes.length - prefix} bytes after the prefix`);
74
+ let header: string;
75
+ try {
76
+ // The supported keys, primitive dtypes and tuple grammar are ASCII in every version.
77
+ header = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes.subarray(prefix, start));
78
+ } catch {
79
+ return fail('DEPTH_ARRAY_FORMAT', at, 'header contains invalid text; required the NumPy dictionary for a primitive floating-point array');
80
+ }
81
+ const { shape, itemBytes } = readHeader(header, at);
82
+ const [height, width, planes] = shape;
83
+ const channels = kind === 'depth' ? 1 : 3;
84
+ const shapeMatches = kind === 'depth' ? shape.length === 2 || (shape.length === 3 && planes === 1) : shape.length === 3 && planes === 3;
85
+ if (!shapeMatches || !shape.every(n => Number.isSafeInteger(n) && n > 0)) return fail('DEPTH_ARRAY_SHAPE', at,
86
+ `shape (${shape.join(',')}) for ${kind}; required ${kind === 'depth' ? '(H,W) or (H,W,1)' : '(H,W,3)'} with positive safe integer dimensions`);
87
+ const expected = BigInt(height) * BigInt(width) * BigInt(channels) * BigInt(itemBytes);
88
+ const found = bytes.length - start;
89
+ if (BigInt(found) !== expected) return fail('DEPTH_ARRAY_FORMAT', at,
90
+ `payload has ${found} bytes; shape (${shape.join(',')}) and dtype require exactly ${expected}`);
91
+ const value = itemBytes === 4
92
+ ? (index: number) => view.getFloat32(start + index * itemBytes, true)
93
+ : (index: number) => view.getFloat64(start + index * itemBytes, true);
94
+ return { width, height, channels, value } as const;
95
+ }
96
+
97
+ function cropPadding(raw: string | undefined): [left: number, top: number, right: number, bottom: number] {
98
+ if (raw === undefined) return [0, 0, 0, 0];
99
+ const values = raw.split(',');
100
+ const [left, top, right, bottom] = values.map(Number);
101
+ if (values.length !== 4 || values.some(value => !/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)))) {
102
+ return fail('DEPTH_ARRAY_PADDING', 'depth-map --padding',
103
+ `found ${JSON.stringify(raw)}; required four nonnegative safe integers LEFT,TOP,RIGHT,BOTTOM`);
104
+ }
105
+ return [left, top, right, bottom];
106
+ }
107
+
108
+ function unpaddedExtent(extent: number, before: number, after: number): number {
109
+ return extent - before - after;
110
+ }
111
+
112
+ const magnitude = (value: bigint): bigint => value < 0n ? -value : value;
113
+
114
+ /** A finite binary64 value is an integer multiple of the smallest subnormal (2^-1074). */
115
+ function floatUnits(value: number, bits: DataView): bigint {
116
+ bits.setFloat64(0, value);
117
+ const high = bits.getUint32(0), low = bits.getUint32(4);
118
+ const exponent = (high >>> 20) & 0x7ff;
119
+ const fraction = (BigInt(high & 0xfffff) << 32n) | BigInt(low);
120
+ const units = exponent === 0 ? fraction : ((1n << 52n) | fraction) << BigInt(exponent - 1);
121
+ return (high >>> 31) === 0 ? units : -units;
122
+ }
123
+
124
+ /** Divide exact units, rounding once to binary64 (nearest, ties to even). */
125
+ function meanOfUnits(sum: bigint, count: bigint): number {
126
+ if (sum === 0n) return 0;
127
+ const abs = magnitude(sum);
128
+ const shift = Math.max(0, (abs / count).toString(2).length - 53);
129
+ const divisor = count << BigInt(shift);
130
+ const quotient = abs / divisor, twiceRemainder = (abs % divisor) * 2n;
131
+ const roundUp = twiceRemainder > divisor || (twiceRemainder === divisor && quotient % 2n !== 0n);
132
+ const value = Number(roundUp ? quotient + 1n : quotient) * 2 ** (shift - 1074);
133
+ return sum < 0n ? -value : value;
134
+ }
135
+
136
+ function normalize(x: number, y: number, z: number): [number, number, number] {
137
+ const scale = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
138
+ const nx = x / scale, ny = y / scale, nz = z / scale;
139
+ const length = Math.sqrt(nx * nx + ny * ny + nz * nz);
140
+ return [nx / length, ny / length, nz / length];
141
+ }
142
+
143
+ export function modelArrayMap(bytes: Uint8Array, image: { width: number; height: number }, kind: string,
144
+ padding: string | undefined, at: string): NumericMap {
145
+ if (kind !== 'depth' && kind !== 'normals') return fail('DEPTH_ARRAY_KIND', 'depth-map --kind',
146
+ `found ${JSON.stringify(kind)}; required depth or normals`);
147
+ const [left, top, right, bottom] = cropPadding(padding);
148
+ const array = readArray(bytes, kind, at);
149
+ const retainedWidth = unpaddedExtent(array.width, left, right), retainedHeight = unpaddedExtent(array.height, top, bottom);
150
+ if (retainedWidth <= 0 || retainedHeight <= 0) return fail('DEPTH_ARRAY_PADDING', at,
151
+ `padding ${left},${top},${right},${bottom} leaves ${retainedWidth}x${retainedHeight} of raw ${array.width}x${array.height}; required a nonempty crop`);
152
+ const { width, height } = image;
153
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 ||
154
+ retainedWidth % width !== 0 || retainedHeight % height !== 0) return fail('DEPTH_ARRAY_SIZE', at,
155
+ `retained ${retainedWidth}x${retainedHeight}, prepared PNG ${width}x${height}; required a positive integer pooling factor on each axis`);
156
+ const stepX = retainedWidth / width, stepY = retainedHeight / height;
157
+ const { channels, value } = array;
158
+ const data: number[] = [];
159
+ const single = stepX === 1 && stepY === 1;
160
+ const count = BigInt(stepX) * BigInt(stepY), bits = new DataView(new ArrayBuffer(8));
161
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
162
+ const rawLeft = left + x * stepX, rawTop = top + y * stepY;
163
+ let sumX = 0n, sumY = 0n, sumZ = 0n;
164
+ for (let sy = rawTop; sy < rawTop + stepY; sy++) for (let sx = rawLeft; sx < rawLeft + stepX; sx++) {
165
+ const index = (sy * array.width + sx) * channels;
166
+ const vx = value(index);
167
+ if (channels === 1) {
168
+ if (!Number.isFinite(vx)) return fail('DEPTH_ARRAY_NONFINITE', at,
169
+ `raw pixel (${sx},${sy}) has depth ${vx}; required a finite value`);
170
+ if (single) data.push(vx);
171
+ else sumX += floatUnits(vx, bits);
172
+ continue;
173
+ }
174
+ const vy = value(index + 1), vz = value(index + 2);
175
+ if (!Number.isFinite(vx) || !Number.isFinite(vy) || !Number.isFinite(vz) || (vx === 0 && vy === 0 && vz === 0)) {
176
+ return fail('DEPTH_ARRAY_NORMAL', at,
177
+ `raw pixel (${sx},${sy}) has normal [${vx},${vy},${vz}]; required a finite nonzero XYZ vector`);
178
+ }
179
+ if (single) data.push(...normalize(vx, vy, vz));
180
+ else {
181
+ sumX += floatUnits(vx, bits);
182
+ sumY += floatUnits(vy, bits);
183
+ sumZ += floatUnits(vz, bits);
184
+ }
185
+ }
186
+ if (single) continue;
187
+ if (channels === 1) data.push(meanOfUnits(sumX, count));
188
+ else {
189
+ const scale = [sumX, sumY, sumZ].map(magnitude).reduce((a, b) => a > b ? a : b);
190
+ if (scale === 0n) return fail('DEPTH_ARRAY_NORMAL', at,
191
+ `output pixel (${x},${y}) has pooled normal [0,0,0]; required a nonzero pooled XYZ vector`);
192
+ // The tile count cancels in normalization. Scale the exact sums before rounding,
193
+ // so a subnormal residual or an overflowing sum can still give a direction.
194
+ data.push(...normalize(meanOfUnits(sumX << 1074n, scale), meanOfUnits(sumY << 1074n, scale), meanOfUnits(sumZ << 1074n, scale)));
195
+ }
196
+ }
197
+ return { spec: 'rig-parts-map/1', width, height, channels, data };
198
+ }
199
+
200
+ /** JSON accepts signed zero even though JSON.stringify emits 0 for either sign. */
201
+ export function serializeModelArrayMap(map: NumericMap): string {
202
+ if (!map.data.some(value => Object.is(value, -0))) return JSON.stringify(map) + '\n';
203
+ const { data, ...header } = map;
204
+ const values = data.map(value => Object.is(value, -0) ? '-0' : String(value)).join(',');
205
+ return `${JSON.stringify(header).slice(0, -1)},"data":[${values}]}\n`;
206
+ }
package/src/neckdraft.ts CHANGED
@@ -75,9 +75,9 @@ export function draftIndependentNeck(input: { config: CharacterConfig; source: R
75
75
  if (surf?.record.depth === undefined || surf.depthImage === undefined) return refuse('PROPOSE_NECK_DEPTH_INPUT', `turn.body surface "${surface ?? '(none)'}"`, 'the first declared body surface or its scalar depth sheet is missing; declare a body surface and assemble its config.depth input');
76
76
  const zNeck = sampleUnitPartDepth(scalar, art, ref);
77
77
  const zRef = sampleUnitPartDepth(extendDepthSilhouette(surf.depthImage, surf.image), surf.image, surf.record.depth);
78
- const value = pyRound(pivot + zNeck - zRef, 4);
79
- body.unitDepths = { ...unitDepths, [part]: value };
78
+ const projectedDepth = pyRound(pivot + zNeck - zRef, 4);
79
+ body.unitDepths = { ...unitDepths, [part]: zNeck };
80
80
  notes.push(`neck: "${part}" takes full:neck; sibling bone "${unit}" under "${carrier}", one rigid segment from neck to head; reassembled with the CLI defaults seam=near-white/project=core (source rules are not recorded in parts.json); turn.body.roles.${part} = unit (no head role)`);
81
- notes.push(`neck depth: turn.body.unitDepths.${part} = ${value} = round4(body pivot ${pivot} + neck world median ${zNeck} - first body surface "${surface}" world median ${zRef}); median over ${population}, sheet "${ref.image}", near=${ref.near}, zScale=${ref.zScale}; levelToDepthZ applies the declared polarity, not depth_median`);
81
+ notes.push(`neck depth: turn.body.unitDepths.${part} = neck world median ${zNeck}; projected depth ${projectedDepth} = round4(body pivot ${pivot} + neck world median ${zNeck} - first body surface "${surface}" world median ${zRef}); median over ${population}, sheet "${ref.image}", near=${ref.near}, zScale=${ref.zScale}; levelToDepthZ applies the declared polarity, not depth_median`);
82
82
  return { config: cfg, assembled, notes };
83
83
  }