rig-parts 1.46.0 → 1.47.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/cli.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  import { spawnSync } from 'node:child_process';
15
15
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
16
16
  import { tmpdir } from 'node:os';
17
- import { basename, dirname, extname, join } from 'node:path';
17
+ import { basename, dirname, extname, join, resolve } from 'node:path';
18
18
  import { DEFAULT_PROJECT_RULE, DEFAULT_SEAM_RULE, HOLES_LISTED, PROJECT_RULES, type ProjectRule, proposeFields, proposePlan, proposeSinglePlan, SEAM_RULES, type SeamRule } from './src/assemble.ts';
19
19
  import { type AlternateCliInput, assembleStage, build, checkStage, ERROR_MAP_FILE, loopStage, readRuns, readSource, rigStage, suppliedCheckFlag } from './src/build.ts';
20
20
  import { ACCEPTABLE_BARS, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, findRigc, PACK_SHAPES, rigcRunnerAt, type PackShape, PAGE_EDGES, type PageEdges, PARTS_HOME_SENTENCE, RIGC_GEOMETRY_VERSION, rigcRanClause, type RigcRunner, NO_PARTS_SENTENCE, SEAM_MEAN_BAR, SOURCE_SENTENCE, SEAM_PX_BAR, SEAM_PX_LEVEL, SPINEBOY_YARDSTICK, TEXTURE_STRETCH_CEILING } from './src/check.ts';
@@ -29,7 +29,8 @@ import { depthSkipLine, exportLayers, figuresPhrase, hiddenLayerLine, implausibl
29
29
  import { checkImageSize, choosePerson, KEYPOINTS_SPEC, loadKeypoints, type RigJoints, toRigJoints } from './src/keypoints.ts';
30
30
  import { basisLines, branchSqueezeLine, checkProposal, compare, compareLines, DEFAULT_GRID_RULE, draftTurn, drawLandmarks, FIGURE_GRID_DIVISOR, FRINGE_STEP_PX, GRID_RULES, type GridRule, HIP_MIN_FRACTION, type DraftLintFinding, lint, lintLine, type PartSet, proposeWithBasis, readPartSet, serializeProposal, withTurn, WRIST_ON_PART_PX } from './src/propose.ts';
31
31
  import { BASIS_FILE, BASIS_SPEC, basisFile, basisLine, coverageLines, serializeBasis } from './src/diagnostics.ts';
32
- import { BEND_DEGREES, BEND_WORST_SHARE, DUST_MAX_PX, DUST_MAX_SHARE, IDLE_BOUND_PX, MESH_DRAFT_REPORT, MESH_DRAFT_SPEC, meshDraftStage, MORE_TRIANGLES_FLAG, TOLERANCE_FIGURE_DIVISOR } from './src/meshdraft.ts';
32
+ import { BEND_DEGREES, BEND_WORST_SHARE, DUST_MAX_PX, DUST_MAX_SHARE, IDLE_BOUND_PX, MESH_DRAFT_REPORT, MESH_DRAFT_SPEC, meshDraftStage, MORE_TRIANGLES_FLAG, relativeConfigPaths, TOLERANCE_FIGURE_DIVISOR } from './src/meshdraft.ts';
33
+ import { clothConfigEdits, editPaths, writtenClothConfig } from './src/clothconfig.ts';
33
34
  import { PROVENANCE_FILE, REMESH_SPEC, remeshStage } from './src/remesh.ts';
34
35
  import { RETUNE_FILE, RETUNE_SPEC, retuneStage } from './src/retune.ts';
35
36
  import { checkPainting } from './src/paintcheck.ts';
@@ -225,6 +226,22 @@ usage:
225
226
  a LINT line names each drafted radius and both figures. Without --cloth
226
227
  nothing changes.
227
228
 
229
+ rig-parts propose … --cloth <config.json> [--write-config <out.json>]
230
+ Also write the --cloth config's own text with what the recipe drafts
231
+ spliced in (issue #537), the way mesh-draft writes its config, so that
232
+ rig --config <out.json> builds it. What is spliced is measured: the
233
+ same parts drafted again without the recipe, and each config section
234
+ that differs — bones and constraints whole (a hand-added bone does not
235
+ survive), meshes.<part>, regions.<part> and motion.tracks entry by
236
+ entry; a section the input lacks is inserted; every other byte as
237
+ read. The text is written as stated, so a relative path in it
238
+ resolves against <out.json>'s directory (a note names each when that
239
+ is not the input's). Only with --cloth and not with --from-config
240
+ (usage errors); refused, before anything is written, when <out.json>
241
+ exists or is a file this run writes (PROPOSE_WRITE_CONFIG_FRESH), or
242
+ when the spliced text does not parse to the config with the sections
243
+ set, naming the first key that moved (PROPOSE_WRITE_CONFIG_SPLICE).
244
+
228
245
  rig-parts propose --parts <dir> --source <painting.png> --out <dir> --from-config <config.json>
229
246
  Draw the config's CURRENT bones instead (<out>/render/landmarks_config.png
230
247
  and _head) and LINT them (by the joints too, given --keypoints), with the
@@ -861,7 +878,7 @@ const TAKES = {
861
878
  layers: { valued: ['--export', '--template', '--canvas'], switches: [] },
862
879
  sheet: { valued: ['--source', '--layers', '--out', '--cell', '--cols'], switches: [] },
863
880
  rig: { valued: ['--config', '--parts', '--out', '--idle-keys', '--page-edges', '--pack-shape'], switches: [] },
864
- propose: { valued: ['--parts', '--source', '--out', '--from-config', '--compare', '--full', '--head', '--canvas', '--keypoints', '--person', '--wrist-snap', '--grid-rule', '--cloth'], switches: ['--head-box', '--no-back-hair'] },
881
+ propose: { valued: ['--parts', '--source', '--out', '--from-config', '--compare', '--full', '--head', '--canvas', '--keypoints', '--person', '--wrist-snap', '--grid-rule', '--cloth', '--write-config'], switches: ['--head-box', '--no-back-hair'] },
865
882
  compare: { valued: ['--left', '--right', '--map'], switches: [] },
866
883
  check: { valued: ['--rig', '--out', '--parts', '--source', '--page-edges', '--pack-shape', '--requirements', '--set'], switches: ['--seam-pairs', '--keep-stills', '--all-sets'] },
867
884
  loop: { valued: ['--frames', '--out'], switches: ['--palette'] },
@@ -1258,6 +1275,16 @@ function cmdPropose(args: string[]): number {
1258
1275
  // Issue #364: the cloth and hair recipe, read from a config's cloth block; without it nothing changes.
1259
1276
  const clothArg = flags.get('--cloth');
1260
1277
  if (clothArg !== undefined && flags.has('--from-config')) return usage('--cloth drafts trees while proposing; --from-config proposes nothing');
1278
+ // Issue #537: the --cloth config's own text with what its recipe drafts spliced in, beside proposal.json.
1279
+ const writeArg = flags.get('--write-config');
1280
+ if (writeArg !== undefined && flags.has('--from-config')) return usage('--write-config writes what the recipe drafts into its config; --from-config proposes nothing');
1281
+ if (writeArg !== undefined && clothArg === undefined) return usage('--write-config writes the --cloth config with what its recipe drafts spliced in; give --cloth <config.json>');
1282
+ if (writeArg !== undefined) {
1283
+ const ours = ['proposal.json', BASIS_FILE].map((f) => resolve(out, f));
1284
+ if (existsSync(writeArg) || ours.includes(resolve(writeArg))) {
1285
+ throw new PartsError([{ code: 'PROPOSE_WRITE_CONFIG_FRESH', object: writeArg, detail: existsSync(writeArg) ? 'exists; the config is written to a new file, never over the --cloth config or an earlier one' : `is a file this run writes under ${out}; name another file` }]);
1286
+ }
1287
+ }
1261
1288
  const cloth = clothArg === undefined ? null : loadClothConfig(clothArg).cloth;
1262
1289
  const partsDir = existsSync(partsArg) && statSync(partsArg).isFile() ? dirname(partsArg) : partsArg;
1263
1290
  if (!existsSync(source)) {
@@ -1295,6 +1322,15 @@ function cmdPropose(args: string[]): number {
1295
1322
  : withTurn(drafted, draftTurn(P, { ...(fullRun === undefined ? {} : { full: readLayers(fullRun) }), ...(headRun === undefined ? {} : { head: readLayers(headRun) }) }, drafted));
1296
1323
  // Emit only after green: a proposal the config loader would refuse is not written, nor a basis record that does not hold to it.
1297
1324
  checkProposal(P, prop);
1325
+ // Issue #537: the sections the recipe moves, measured against the same parts drafted without it, spliced before anything is written.
1326
+ const written =
1327
+ writeArg === undefined || clothArg === undefined
1328
+ ? null
1329
+ : (() => {
1330
+ const edits = clothConfigEdits(drafted, proposeWithBasis(P, joints, wristSnap, gridRule, null).proposal);
1331
+ const text = readFileSync(clothArg, 'utf8');
1332
+ return { at: writeArg, text: writtenClothConfig(clothArg, text, edits), paths: editPaths(edits), relative: relativeConfigPaths(dirname(resolve(clothArg)), JSON.parse(text) as Record<string, unknown>) };
1333
+ })();
1298
1334
  const bfile = basisFile(P, prop, basis, cfg === null || cmpPath === undefined ? null : { where: cmpPath, config: cfg });
1299
1335
  const img = drawLandmarks(P, painting, prop.bones, 'PROPOSAL - CORRECT ME');
1300
1336
  mkdirSync(render, { recursive: true });
@@ -1302,10 +1338,20 @@ function cmdPropose(args: string[]): number {
1302
1338
  writeFileSync(join(out, BASIS_FILE), serializeBasis(bfile));
1303
1339
  writePng(join(render, 'landmarks.png'), img.full);
1304
1340
  if (img.head !== null) writePng(join(render, 'landmarks_head.png'), img.head);
1341
+ if (written !== null) {
1342
+ mkdirSync(dirname(written.at), { recursive: true });
1343
+ writeFileSync(written.at, written.text);
1344
+ }
1305
1345
  console.log(`wrote proposal.json (${prop.bones.length} bone entries, ${Object.keys(prop.meshes).length} meshes) and render/landmarks.png (+_head) under ${out}`);
1306
1346
  for (const n of prop.notes) console.log(`note: ${n}`);
1307
1347
  printLint(P, prop, joints, draftLint);
1308
1348
  console.log(basisLine(bfile, out));
1349
+ if (written !== null && clothArg !== undefined) {
1350
+ console.log(`wrote ${written.at}: ${clothArg}'s text with ${written.paths.join(', ')} spliced in from the draft; every other byte as read`);
1351
+ if (written.relative.length > 0 && dirname(resolve(written.at)) !== dirname(resolve(clothArg))) {
1352
+ console.log(`note: ${written.relative.map((r) => `${r.at} "${r.value}"`).join(', ')} written as stated; the loader resolves each against the directory the config sits in, ${dirname(written.at)} for ${written.at}, not ${dirname(clothArg)}; put the config beside ${clothArg} or rewrite them`);
1353
+ }
1354
+ }
1309
1355
  if (cfg !== null) for (const l of compareLines(compare(prop.bones, cfg.bones))) console.log(l);
1310
1356
  return EXIT_OK;
1311
1357
  } catch (err) {
package/docs/AUTHORING.md CHANGED
@@ -128,7 +128,7 @@ read by no CPU stage).
128
128
  | `stops` | rig (handed to rig-c as `rig.json`'s `stops`, and moves slots, mesh weights and child bones on stopped links onto `<link>_d`); `propose --from-config` (`LINT stop on <chain> …`) | **authored**, optional (issues #404, #447): `[{chain, links?, against, at, inward, outward, lower?: {inward, outward}}]` — rig-c's leg stops (`RigStop`, rig-c 2.56.0, `rig-c/src/stop.ts`). `chain` is a chain `bones` declares (`CONFIG_NAME_RESOLVES`, `RIG_NAME_RESOLVES`); `links`, optional, is a non-empty list of links of that chain (`CONFIG_NAME_RESOLVES`, `CONFIG_FIELD_TYPE`), or absent for every link of `chain` in chain order; `against` is a bone `bones` declares, a chain link as `<chain><i>` (`CONFIG_NAME_RESOLVES`, `RIG_NAME_RESOLVES`); `at` is `[x, y]` in `against`'s local space, as rig-c's stop takes it (`CONFIG_FIELD_TYPE`): since each chain link (`leg_r0`, `leg_r1`) is turned to point along its segment (`+x` from origin to next link or tip, `+y` 90° counter-clockwise in Spine world), `at: [d, n]` sits `d` px from `against`'s origin toward its end and `n` px perpendicular to it; `inward`, `outward` and `lower.inward`, `lower.outward` are finite numbers (`CONFIG_FIELD_TYPE`). Every other stop rule — non-negative bounds, each stopped link written by a constraint, `against` not under the stopped chain, the aim not degenerate, `\|rest\| + outward <= 180°` (`RIG_STOP_BOUNDS`) — is rigc's to accept or refuse at the rig stage's gate, in rigc's words (`RIG_RIGC_GREEN`). **Rising-limb / prone geometry (issue #447):** rig-c's `expandStops` aims `<chain>_rest` from `links[0]`'s setup origin at `<chain>_touch` (`at` in `against`'s local frame) and clamps `<link>_d` inside `[rest − inward, rest + outward]`; Spine wraps rotation at `±180°`, so `\|rest\| + outward <= 180°` is required (`RIG_STOP_BOUNDS`). Whenever `<chain>_touch` lies **above** `links[0]`'s root in rig pixels (`ty < y0`, i.e. higher Spine `y` — e.g. stopping a hanging cloth chain against a rising shin `leg_<s1>` in a prone or kneeling pose where the knee sits below `links[0]` and the ankle above it, so positive `at[0]` walks upward along the shin past `links[0]`'s root), `rest` lands in the upper half-plane (`\|rest\| > 90°`) and `\|rest\| + outward` exceeds `180°`. Stop against the descending thigh (`leg_<s0>`), set `links` to start at a link whose root sits above `<chain>_touch`, or omit the stop when the rising shin sits outside the hanging chain's sweep; `propose --from-config` prints `LINT stop on <chain> …` with the exact coordinates and angles when `<chain>_touch` lies above `links[0]`'s root or `\|rest\| + outward > 180°`. For every stopped link `<link>`, the rig stage moves any slot on `<link>`, any mesh weight on `<link>`, and any bone whose parent is `<link>` (a branched cloth tree's branches hanging from `<trunk_last>`, before `--idle-keys ctl` adds `<bone>_ctl` and before `turn` adds `turn_<part>_<bone>`) onto `<link>_d`, the drawn link bone rig-c's `expandStops` creates at `<link>`'s setup frame to carry the clamped rotation. Absent, `rig.json` carries no `stops` and no byte of any output moves |
129
129
  | `turn` | rig (adds the turn control) | **proposed** only with `propose --full`/`--head` (issue #251), then corrected: `{pivot, depths, deform?, band?, radius?, surface?: {radius?}, head?: {pivot?, radius?}}`. `depths` holds, per part, the See-through layer's `depth_median` the part came from (larger = further back), read from the run the part was assembled from; a `painting:` patch has none and is not carried. A rider (issue #271) — a part from an `eyewhite`, `irides`, `eyelash`, `eyebrow`, `nose` or `mouth` layer — is drafted at the `face` part's depth, 0.001 nearer when parts.json draws it after the face and 0.001 further when before: See-through makes no depth of its own for the eye group (it cuts them from one depth map of the combined eyes) and clamps nose and mouth to the face's median − 0.001, and the two runs' own medians for these layers disagreed by up to 0.47 and swapped their order against the face. Every other layer — ears, headwear and earwear included — keeps its own median, unless it rides another part's bone. With no `face` part, or more than one, the riders keep their own and a note says so. A rider by bone (issue #535) — a part every *ownable* bone of which (a chain link, or a bone no other bone hangs from; `head`, `chest` and any bone with a child are shared and never count on their own) is *hosted* by another carried part, the host of a bone being the carried part that binds it (its region's bone; a mesh's `segments`, `contour` and `auto` regions' bones) with the most `opaque_px`, the earlier in parts.json on a tie, and which hosts no bone itself — is drafted at its host's depth, 0.001 nearer when drawn after the host and 0.001 further when before, and a note names the host, the bones and its own median: a pin, clip or ornament on the back hair's links travels with the back hair, not with its own layer's depth. `propose` reads the proposal's own `bones`, `meshes` and `regions`; the face riders are read by their tag first and never by their bones. A part bound to two hosts' bones rides neither and a note says so. In the rig stage, an authored depth on a rider by bone whose fraction differs from its host's by more than 0.1 of the dial (`TURN_RIDER_APART`, a share of `pivot − nearest`) is refused (`CONFIG_TURN_RIDER_DEPTH`); the host is read off `parts.json`'s `opaque_px`, so the config loader cannot see it. One note lists each part's depth and where it came from; a carrier the other run places more than 10 % of `pivot − nearest` away gets a note naming both values and the run read — the two runs are not reconciled. `pivot` is the depth that stays put; `propose` drafts the mean of the parts' depths weighted by `opaque_px`, the one depth at which the painted pixels' centroid does not slide under the dial. The rig stage adds a bone `turn` under `root` at its origin that nothing keys — its local x is the dial, in rig px — and carries each part by `(pivot − depth) / (pivot − nearest depth)` of it: the nearest part all of it, a part behind the pivot the other way, a part at the pivot not at all. Each part rides leaf twins (`turn_<part>_<bone>`, an identity child of every bone its slot and weights bind) moved by one `transform` constraint (`turn_<part>`, after the config's own); the idle's keys, the `<bone>_ctl` controls and a physics constraint stay on the bones, and the dial moves none of them. Optional `deform` (`Partial<FaceDeformFractions>`, issue #436) overrides the Set B ×2.5 face surface deformation table (`FACE_DEFORM_FRACTIONS`, checked against `FACE_DEFORM_RANGES` by `CONFIG_TURN_DEFORM_RANGE`); when `applyFaceSurfaceDeform` runs on a rig whose `motion` carries `tilt` or `turn` slider `derive` keys, it requires `config.turn` (`CONFIG_TURN_REQUIRED`, issue #478; `propose --full`/`--head` drafts it), promotes `face` on `head` (or `turn_face_head` when `turn` is declared) to the uneven 5×5 grid mesh, keys `face`, `hair_front` and `hair_back` deform timelines and ear/topknot tracks from `evalPitchFaceSurface` and `evalYawFaceSurface`, and samples the same deform field across each `features` member's rest span (`featRx = (24 / 106) · W`, `featRy = (12 / 128) · H`) with its depth fraction `z / zRef` as the field's angle input and chord foreshortening (`scalex` narrowing on the leading side and widening on the trailing side, `scaley` on pitch) so every feature's bounding box stays inside the deformed face plate across the rated band (issue #468). On yaw (`issue #479`), `evalYawFaceSurface` evaluates a **cylinder projection** (`cylinderYawDx`: `Δx(x, θ, R) = R · (sin(clamp(arcsin(clamp(x / R, −1, 1)) − θ, −π/2, π/2)) − clamp(x / R, −1, 1))`) of radius `R` (`turnSurfaceRadius`: `turn.surface.radius ?? turn.radius ?? turn.head.radius`, positive rig px checked by `CONFIG_FIELD_TYPE`, defaulting to half the face plate's opaque width `W / 2`) tapered by a cubic Hermite outline weight (`wOutline = 1` for `\|ux\| <= 0.7`, reaching `0` at `\|ux\| = 1.0`) so features slide across a fixed outline (`iris` shift within `±2%` of `cylinderYawDx`), the trailing cheek strip widens (`>= 1.54×` at `±15°`), and the leading jaw edge holds fixed (`0 px` shift) unless explicit horizontal `turn.deform` overrides (`turn_mid_x`, `turn_lead_compress_x`, `turn_trail_shift_x`) request the flat yaw table. On yaw (`issue #478`), `applyFaceSurfaceDeform` also derives a **head-only pivot** (`headTurnPivot`: `turn.head.pivot` when authored, otherwise the `opaque_px`-weighted mean of `depths[part]` across the head parts `DEFAULT_HEAD_TURN_PARTS` — `face`, `hair_front`, `hair_back`, `ear_r`, `ear_l`, `hairpin` — from `parts.json`, falling back to `turn.pivot`) so a forward torso or arm in `turn.depths` does not pull the head's rotation axis in front of `face`: `hair_back` (`depth_median > headPivot`, negative `headTurnFraction`) and `hairpin` behind `headPivot` translate opposite to the face's turn (`dx = s · turn_face_center_x · W · (headPivot − depth) / (headPivot − nearestHeadDepth)`), emerging on the trailing side to compensate for the leading-cheek foreshortening and keeping the combined head silhouette width near-constant across `±15°` without any same-sign `turn_hair_back_cheek_x` term. Optional `band` (`number` or `{yaw?, pitch?}`, positive degrees, issue #472) declares the rig's rated face turn band (default `FACE_RATED_BAND`: `yaw <= 15°`, `pitch <= 12°`); declaring a `turn.band` or a `motion.animations_from` `turn`/`tilt` `derive.degrees` above `±15°` yaw or `±12°` pitch without an `assemble.alternates` entry that replaces `face` is refused (`CONFIG_FACE_BAND_EXCEEDED`), and on a single-plate rig `applyFaceSurfaceDeform` adds self-targeting transform constraints `yaw_clamp` (`[-15, 15]`) and `pitch_clamp` (`[-12, 12]`) ahead of the slider constraints so driving `yaw` or `pitch` beyond the rated band clamps at the boundary. At rest: with `turn` declared, no pixel differs by more than 1 level at dial 0 (not byte-identical; the cause is float noise in the identity child bones, and the constraints add nothing); without `turn`, byte-identical. Neither `pivot` nor `depths` has a default (`CONFIG_FIELD_PRESENT`); `pivot` and `head.pivot` must lie behind the nearest part (`CONFIG_TURN_PIVOT_BEHIND_NEAREST`). Absent, no control is added and no byte of any output moves |
130
130
  | `scene` | assemble (the recomposite, its holes and the figure's mask); check, through `parts.json`'s `scene` block (`RECOMPOSITE_HOLES`, the seam) | **authored**, optional; `propose` writes none (issue #242). `{}` declares the painting a scene: the figure and its surroundings in one image, See-through's full run holding only the figure. With it, `assemble` reads the recomposite figures, the hole list and the `uncovered:` lines inside the figure — the rig pixels where any full-run layer's alpha is above 8 (`OPAQUE_ALPHA_ABOVE`, the cut every layer's painted pixels are read by) — each line starting `inside the figure (config.scene: …, <n> of <m> rig px)`; writes that figure as `figure_rig.png` (white on black) beside the recomposite, and a `scene` block in `parts.json`; flags error pixels on the error map inside it only (outside, the painting grey); and `check` leaves out of the seam every frame pixel whose composite sample reaches the painting's outermost row or column, saying how many (`seam_border` in `check.json`, and on the seam line). It takes no field: the figure and its threshold are derived. A key in it other than a record or an annotation is `CONFIG_KEY_KNOWN`. Absent, no byte of any output moves |
131
- | `cloth` | `propose --cloth` only; no other stage reads it, so it moves no byte of any build | **authored**, optional (issue #364): one recipe per tag, `{"bottomwear": {…}, "back hair": {…}, "front hair": {…}}`, each `{chains, links, wind, gravity, split?, length_ratio?, strength?, damping?, alternate_damping?, translate?, swing?, part?, influence?}`. `influence` (issue #518) — `{across, max, shape, radius?}`: the parts this recipe meshes are drafted in the influence mode (`meshes.<part>.influence` above) at their lattice's cell, with `across`, `max` and `shape` as declared (each required — the reading behind the radius did not vary them) and `radius` as declared or, absent, drafted as the farthest vertex's distance plus 3 cells (the `influence.radius` row); without it the parts keep their lattice. `chains` — trees across the piece (for `back hair`, per side of the eye axis), a whole number, 1 or more; `links` — links from root to tip on every path, 1 or more; `split` — `{at, into}`: the first `at` links are the trunk, which forks into `into` (2 or more) branches; `at` below `links` (`CONFIG_CLOTH_SPLIT_BEFORE_TIP`); `length_ratio` — a path's last link over its first, above 0, default 0.5; `strength` — `{trunk, branch, edge}`, each above 0 and below the spring's stability bound (`CONFIG_CLOTH_SPRING_STABLE`), default 100 / 100 / 50; `damping` — in [0, 1], absent: rig-c's default; `alternate_damping` — the odd trees' damping, in [0, 1], beside `damping` and different from it (`CONFIG_CLOTH_ALTERNATE_DIFFERS`); `wind`, `gravity` — `[root, tip]`, each 0 or more, tip at or above root (`CONFIG_CLOTH_RESPONSE_GROWS_TO_TIP`); `translate` — the x and y mix of a dangling end's flutter, above 0 and at most 1; `swing` — `bottomwear` only, `{scales}`, one positive scale per tree (`CONFIG_CLOTH_SWING_SCALE_PER_TREE`); `part` — `bottomwear` only (`CONFIG_CLOTH_PART_ON_BOTTOMWEAR`), a non-empty part or cut-piece name: the `topwear` part that holds a skirt See-through returned inside it (a dress), or its skirt piece cut by `assemble.cuts`, which takes the skirt's trees (issue #402, *A skirt inside topwear* below; the part is checked by `propose`, `PROPOSE_CLOTH_PART`). The two defaults are the recipe's own, measured on its synthetic fixture (the recipe below). The recipe below says what each field drafts |
131
+ | `cloth` | `propose --cloth` only; no other stage reads it, so it moves no byte of any build | **authored**, optional (issue #364): one recipe per tag, `{"bottomwear": {…}, "back hair": {…}, "front hair": {…}}`, each `{chains, links, wind, gravity, split?, length_ratio?, strength?, damping?, alternate_damping?, translate?, swing?, part?, influence?}`. `influence` (issue #518) — `{across, max, shape, radius?}`: the parts this recipe meshes are drafted in the influence mode (`meshes.<part>.influence` above) at their lattice's cell, with `across`, `max` and `shape` as declared (each required — the reading behind the radius did not vary them) and `radius` as declared or, absent, drafted as the farthest vertex's distance plus 3 cells (the `influence.radius` row); without it the parts keep their lattice. `chains` — trees across the piece (for `back hair`, per side of the eye axis), a whole number, 1 or more; `links` — links from root to tip on every path, 1 or more; `split` — `{at, into}`: the first `at` links are the trunk, which forks into `into` (2 or more) branches; `at` below `links` (`CONFIG_CLOTH_SPLIT_BEFORE_TIP`); `length_ratio` — a path's last link over its first, above 0, default 0.5; `strength` — `{trunk, branch, edge}`, each above 0 and below the spring's stability bound (`CONFIG_CLOTH_SPRING_STABLE`), default 100 / 100 / 50; `damping` — in [0, 1], absent: rig-c's default; `alternate_damping` — the odd trees' damping, in [0, 1], beside `damping` and different from it (`CONFIG_CLOTH_ALTERNATE_DIFFERS`); `wind`, `gravity` — `[root, tip]`, each 0 or more, tip at or above root (`CONFIG_CLOTH_RESPONSE_GROWS_TO_TIP`); `translate` — the x and y mix of a dangling end's flutter, above 0 and at most 1; `swing` — `bottomwear` only, `{scales}`, one positive scale per tree (`CONFIG_CLOTH_SWING_SCALE_PER_TREE`); `part` — `bottomwear` only (`CONFIG_CLOTH_PART_ON_BOTTOMWEAR`), a non-empty part or cut-piece name: the `topwear` part that holds a skirt See-through returned inside it (a dress), or its skirt piece cut by `assemble.cuts`, which takes the skirt's trees (issue #402, *A skirt inside topwear* below; the part is checked by `propose`, `PROPOSE_CLOTH_PART`). The two defaults are the recipe's own, measured on its synthetic fixture (the recipe below). The recipe below says what each field drafts. The config written: `propose --cloth <config.json> --write-config <out.json>` (issue #537) writes this config's own text back with the sections the recipe drafts spliced in — `bones` and `constraints` whole, `meshes.<part>`, `regions.<part>` and `motion.tracks` entry by entry — and every other byte as read (*The config written*, under the recipe below) |
132
132
  | `proposed_rig_scale` | assemble, rig, build, `propose --from-config`/`--compare` | **proposed** by `propose` (issue #354): `parts.json`'s `scale_rig_per_source`, the `assemble.rig_scale` the rig sections (`bones`, `meshes`, `limbs`, `motion`) were drafted at. Held equal to `assemble.rig_scale` when present (`CONFIG_PROPOSED_RIG_SCALE`; 0, negative or not a number: `CONFIG_FIELD_TYPE`). Absent on a hand-authored config, where no byte of any output moves |
133
133
 
134
134
  **One drawing, one band; beyond it, another drawing (issue #472).** A single front-facing
@@ -1643,6 +1643,33 @@ idle key: the drafted idle keys none of the trees. A recipe that drafts nothing
1643
1643
  its tag on no part, or `back hair` that ends above the shoulders (a bun) — is refused,
1644
1644
  `PROPOSE_CLOTH_DRAFTED`.
1645
1645
 
1646
+ **The config written (issue #537).** `propose --cloth <config.json> --write-config
1647
+ <out.json>` writes, beside `proposal.json`, the `--cloth` config's own text with what the
1648
+ recipe drafts spliced in, the way `mesh-draft` writes its config: `rig --config <out.json>`
1649
+ builds it, and an editor that changes a recipe rebuilds through it rather than merging
1650
+ the proposal itself. What is spliced is measured on each run, not listed: the same parts
1651
+ are drafted again without the recipe, and each config section whose value differs is
1652
+ the recipe's. An object section is spliced entry by entry — `meshes.<part>` and
1653
+ `regions.<part>` for each part the recipe moved (a part it takes from `regions` into
1654
+ `meshes` leaves `regions`), `motion.tracks` and nothing else under `motion`, so
1655
+ `duration`, `blink` and `animations_from` keep their bytes — and `bones` and
1656
+ `constraints` whole: **the drafted array replaces the input's**, so a bone or a
1657
+ constraint added by hand does not survive a `--write-config`, as a hand-edited lattice
1658
+ does not survive `mesh-draft`. Every other byte is the input's; a section the input
1659
+ lacks (a config holding only `key` and `cloth`) is inserted. On the selftest's cloth
1660
+ fixture (CL201 prints the figures) the recipe moves `bones`, `meshes.hair_back`,
1661
+ `meshes.hair_front`, `meshes.skirt`, `motion.tracks` and `constraints`; `limbs` is not
1662
+ moved on the public `wind` example with its keypoints, whose tracked config the flag
1663
+ wrote back byte for byte (measured once, when the flag landed). The text is written as stated: a relative path in it
1664
+ (`motion.animations_from`, `generation.control.skeleton`) resolves against the directory
1665
+ the written config sits in, so the out path belongs beside the input, and when it is not
1666
+ a note names each such path. Refused before anything is written: `--write-config`
1667
+ without `--cloth` or beside `--from-config` (`USAGE`), an out path that exists or that
1668
+ the run writes itself (`PROPOSE_WRITE_CONFIG_FRESH`), and a text whose splice does not
1669
+ parse to the config with the sections set — a key stated twice
1670
+ (`PROPOSE_WRITE_CONFIG_SPLICE`); a recipe that drafts nothing is
1671
+ `PROPOSE_CLOTH_DRAFTED` as without the flag.
1672
+
1646
1673
  **A skirt inside topwear (issue #402).** The recipe finds a skirt by the `bottomwear`
1647
1674
  tag alone. When See-through returns the skirt inside `topwear` (a dress), nothing is
1648
1675
  tagged `bottomwear`, and the proposer does not pick the dress by its shape: with
@@ -2850,6 +2877,8 @@ says why each requirement exists and what breaks without it.
2850
2877
  | <a id="PROPOSE_LIMB_PARTS"></a>`PROPOSE_LIMB_PARTS` | `parts.json` holds a standalone or incomplete limb part `config.limbs` cut at its joints (issues #349, #440) that cannot be reassembled into the source part `of` (a missing segment or `cap` record, or `of` still present beside the limb parts); a complete `assemble` output with `config.limbs` reconstructs its pre-limb parts in the same run | `--parts` a complete `assemble` output (every segment of each limb, with its `cap` record) or a build assembled with `config.limbs` left out; `propose --from-config` reads the config's bones on either build |
2851
2878
  | <a id="PROPOSE_CLOTH_DRAFTED"></a>`PROPOSE_CLOTH_DRAFTED` | with `--cloth` (issue #364): the config's `cloth` block holds a recipe for a tag the proposer drafts no chain on — no part has that tag, or every `back hair` part ends above the shoulders (a bun bone, no chain). A `bottomwear` recipe with no `bottomwear` part names every `topwear` part shaped like a skirt (issue #402) | leave that recipe out, or assemble the layer it is for, or declare the named part in `cloth.bottomwear.part` |
2852
2879
  | <a id="PROPOSE_CLOTH_PART"></a>`PROPOSE_CLOTH_PART` | with `--cloth` (issues #402, #437): `cloth.bottomwear.part` (a string) names no part, a part or cut piece whose source is not `topwear` (a `bottomwear` part takes the recipe by its tag already), or a target whose box ends above the hip + 0.25 face heights, the topwear rule's waist line; or `cloth.<tag>.parts` (or `part` as a list, issue #437) names a part not in `parts.json`, a part no link of the drafted tree crosses (`spanCrosses == 0`), or parts out of root-to-tip depth order along the chain | name the `topwear` part or its cut skirt piece that holds the skirt (or leave `part` out), or list only parts in `parts.json` that the drafted tree links cross in root-to-tip order |
2880
+ | <a id="PROPOSE_WRITE_CONFIG_FRESH"></a>`PROPOSE_WRITE_CONFIG_FRESH` | with `--write-config` (issue #537): the out path exists, or is a file the run writes itself (`proposal.json`, `basis.json` under `--out`); the config is written to a new file, never over the `--cloth` config or an earlier one | name a file that does not exist yet, beside the `--cloth` config |
2881
+ | <a id="PROPOSE_WRITE_CONFIG_SPLICE"></a>`PROPOSE_WRITE_CONFIG_SPLICE` | with `--write-config` (issue #537): the `--cloth` config's text with the drafted sections spliced in does not parse to that config with them set, and the message names the first key that moved — the text states a key twice, so the splice lands on the first and the parse keeps the last | state each key once in the `--cloth` config |
2853
2882
  | <a id="PROPOSE_CLOTH_BACK_HAIR_CHAINS"></a>`PROPOSE_CLOTH_BACK_HAIR_CHAINS` | with `--cloth` (issues #390, #445, #461): `cloth."back hair".chains` exceeds what the narrower side's opaque width at the eye-line root row holds at the part's mesh grid (`max(1, min(floor(w_r / grid), floor(w_l / grid)))`), or places a tree root outside the 15 px dilated art mask of the `back hair` part (e.g. an inner twin-tail root over the face where the hair has no pixel); the message names the part, each side's root-row width, the grid spacing, and any off-art root with its pixel alpha | lower `cloth."back hair".chains` to at most the max fit named in the message, or omit `chains` so `propose --cloth` derives the tree count per visible hair mass on each side from its root-row width |
2854
2883
  | <a id="PROPOSE_ACCESSORY_BODY"></a>`PROPOSE_ACCESSORY_BODY` | an accessory has nothing above its pendant rows to hang its bone on | that part's plan entry, or author its bones by hand |
2855
2884
  | <a id="PROPOSE_TURN_RUN_GIVEN"></a><a id="PROPOSE_TURN_LAYER_PRESENT"></a><a id="PROPOSE_TURN_DEPTH_PRESENT"></a>`PROPOSE_TURN_RUN_GIVEN`, `PROPOSE_TURN_LAYER_PRESENT`, `PROPOSE_TURN_DEPTH_PRESENT` | with `--full`/`--head` (issue #251): a part came from a run whose layers were not given, the run given holds no layer of the part's tag, or its layer carries no `depth_median` while another part's layer carries one; a run with no depth on any part's layer (a PSD, or an export of one) is not refused — the turn is skipped, and the note says `turn: SKIP` and names the run (issue #359) | give the run the parts were assembled from, as the wrapper's `layers.json` |
package/docs/STABILITY.md CHANGED
@@ -53,7 +53,7 @@ defaults are the help's too, and none is guessed from the art.
53
53
  | `comfy` | `seethrough`: `--image`, `--out`; optional `--resolution`, `--steps`, `--seed`, `--prefix`, `--offload`, `--lama`, `--nf4`, `--host`, `--wait`, `--timeout`, `--poll` |
54
54
  | `assemble` | `--propose-plan` with `--source`, `--full`, `--config`, optional `--head`; or `--source`, `--full`, `--config`, `--out`, optional `--head` (without it, one run: issue #359), `--seam` (near-white, silhouette), `--project` (core, visible), `--alt` (repeatable `<name>=<source>:<full>[:<head>]`, issue #454) |
55
55
  | `propose` | `--head-box` with `--full`, `--canvas`; optional `--no-back-hair` |
56
- | `propose` | `--parts`, `--source`, `--out`; optional `--compare` or `--from-config` (one of them), `--keypoints`, `--person` and `--wrist-snap` (each with `--keypoints`), `--full`, `--head` (the turn control's depths; not with `--from-config`), `--grid-rule` (`figure` or `part`, the drafted lattice's spacing; not with `--from-config`), `--cloth` (a config whose `cloth` block is the recipe, issue #364; not with `--from-config`) |
56
+ | `propose` | `--parts`, `--source`, `--out`; optional `--compare` or `--from-config` (one of them), `--keypoints`, `--person` and `--wrist-snap` (each with `--keypoints`), `--full`, `--head` (the turn control's depths; not with `--from-config`), `--grid-rule` (`figure` or `part`, the drafted lattice's spacing; not with `--from-config`), `--cloth` (a config whose `cloth` block is the recipe, issue #364; not with `--from-config`), `--write-config` (a new file, with `--cloth` and not with `--from-config`, issue #537 — additive: without it nothing `propose` writes changes) |
57
57
  | `compare` | `--left`, `--right`; optional `--map` |
58
58
  | `rig` | `--config`, `--parts`, `--out`; optional `--idle-keys` (ctl, direct), `--page-edges` (pot, free), `--pack-shape` (rect, polygon) |
59
59
  | `check` | `--rig`, `--out`; optional `--parts`, `--source`, `--page-edges`, `--pack-shape`, `--requirements`, `--seam-pairs`, `--keep-stills`, `--set` or `--all-sets` (issue #454) |
@@ -198,6 +198,7 @@ every number) are AUTHORING §3's tables, and the loader refuses any other by na
198
198
  | the template `.psd` | `layers --template` | one empty layer per name `templateLayerNames` (`src/layers.ts`) holds, bottom first; the same canvas writes the same bytes |
199
199
  | `proposal.json`, `render/landmarks*.png` | `propose` | the config's four rig sections, `constraints` with `--cloth` (issue #364: a physics constraint per tree link named `<bone>_physics`, a dangling end's `<bone>_translate`, and a skirt swing's transforms `<swing>_<tree>`), `turn` with `--full`/`--head`, `proposed_rig_scale` (issue #354), and `notes` |
200
200
  | `basis.json` | `propose` | spec `spine-parts-basis/1` |
201
+ | the `--write-config` file | `propose --cloth … --write-config` | the `--cloth` config read, byte for byte, but for the sections the recipe drafts (issue #537): `bones` and `constraints` whole, and `meshes.<part>`, `regions.<part>` and `motion.tracks` for each entry the recipe moves, measured against the same parts drafted without it; a section the input lacks is inserted |
201
202
  | `config.json`, `mesh_draft.json` | `mesh-draft` | `config.json` is the config read, byte for byte, but for each drafted part's `meshes` entry; `mesh_draft.json` is spec `rig-parts-mesh-draft/1`: `rules`, `lattice_check`, `draft_check`, `figure_overdraw`, and per lattice part `part`, `mode`, `lattice`, `candidate` (with `bridges` — `units`, `joins` of `span` and `area_px2`, `area_px2`, `overdraw`, and `faint` only when an island was left out as faint — only when the candidate is a bridged one, issue #326), `delta` (under `--more-triangles` only), `readings`, `gate` (each line's `reading`, `pass`, `text`, `margin`), `note`; and `not_compared` (issue #307), only when the config holds an `auto` or `contour` entry: per such entry, in config order, `part`, `mode` and `note` — the part was neither drafted nor compared, and a config of lattices alone writes no such key |
202
203
  | `rig.json`, `motion.json`, `mesh_report.json`, `images/`, `remesh.json` | `remesh` | the input revision's files, `rig.json` and `mesh_report.json` with the part's attachment and row replaced (under `--delta` the row is the input's with its counts, `bones` and influences recomputed and `mode` "delta"), every other file byte for byte; `remesh.json` is spec `rig-parts-remesh/1`: `request` (`part`, `mesh`, `mesh_sha256`, `idle_keys`, `page_edges`, `pack_shape`; under `--delta`, issue #526: `part`, `delta` — the mesh edit as read — `delta_sha256`, `ops`, `applied` — `moved`, `added`, `removed`, `constrained` — `idle_keys`, `page_edges`, `pack_shape`), `versions` (`parts`, `rigc`), `input` (`rig` — `path`, `bytes`, `sha256` per file — `config_sha256`, `parts_json_sha256`), `baseline` (`reproduced`, `not_compared`; under `--delta` `reproduced` holds one sentence: no config is built, the input is the baseline), `target` (`before`, `after`: `vertices`, `triangles`, `hull`), `preserved` (`identical`, `spliced`), `revision` (per file as `input.rig`), `check` (`input`, `revision`: `pass`, `measured`, `not_met`, `skipped`, `physics`; `scope`) |
203
204
  | `rig.json`, `motion.json`, `mesh_report.json`, `images/`, `retune.json` | `retune` | the input revision's files, `rig.json` with `constraints` and `invariants.detached` replaced and `motion.json` with `animations.idle` replaced by the config's build, every other file byte for byte; `retune.json` is spec `rig-parts-retune/1`: `request` (`idle_keys`, `page_edges`, `pack_shape`), `versions` (`parts`, `rigc`), `input` (`rig` — `path`, `bytes`, `sha256` per file — `config_sha256`, `parts_json_sha256`), `held` (`compared`, `not_compared`), `changed` (`constraints` — each `name`, `type`, `fields` — `added`, `removed`, `idle`: `tracks_changed`, `duration` as before and after), `preserved` (`identical`, `spliced`), `revision` (per file as `input.rig`), `check` (`input`, `revision`: `pass`, `measured`, `not_met`, `skipped`, `physics`; `scope`) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "1.46.0",
3
+ "version": "1.47.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": {
@@ -0,0 +1,67 @@
1
+ /**
2
+ * `propose --cloth … --write-config <out.json>` (issue #537): the `--cloth` config's own text with the sections the
3
+ * recipe drafts spliced in, the way `mesh-draft` writes its config ({@link splicedEdits}). The producer is the one
4
+ * writer of its own config; a reviewer that edits a recipe rebuilds through it.
5
+ *
6
+ * What is spliced is measured, not listed: the same parts drafted twice, once with the recipe and once without it
7
+ * (`cloth: null`), and each config section of the proposal ({@link PROPOSAL_CONFIG_SECTIONS}) whose value differs
8
+ * between the two is drafted ({@link clothConfigEdits}). An object section (`meshes`, `regions`, `motion`) is
9
+ * spliced entry by entry — `meshes.<part>` and `regions.<part>` for each part the recipe moved, `motion.tracks` and
10
+ * not the author's `animations_from` — and an array section (`bones`, `constraints`) whole: the drafted array
11
+ * replaces the input's, so a bone the author added by hand does not survive a write. A section the recipe does not
12
+ * move keeps the input's bytes.
13
+ */
14
+
15
+ import { PartsError } from './errors.ts';
16
+ import { type ConfigEdit, splicedEdits } from './meshdraft.ts';
17
+ import { PROPOSAL_CONFIG_SECTIONS, type Proposal } from './propose.ts';
18
+
19
+ function isPlain(v: unknown): v is Record<string, unknown> {
20
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
21
+ }
22
+
23
+ /**
24
+ * The edits that turn a config holding the draft without the recipe (`plain`) into one holding the draft with it
25
+ * (`drafted`): for each config section whose value differs, an object section entry by entry (an entry the recipe
26
+ * removed, such as a part it took from `regions` into `meshes`, is removed) and any other section whole.
27
+ */
28
+ export function clothConfigEdits(drafted: Proposal, plain: Proposal): ConfigEdit[] {
29
+ const edits: ConfigEdit[] = [];
30
+ const d = drafted as unknown as Record<string, unknown>;
31
+ const p = plain as unknown as Record<string, unknown>;
32
+ for (const section of PROPOSAL_CONFIG_SECTIONS) {
33
+ const a = p[section];
34
+ const b = d[section];
35
+ if (JSON.stringify(a) === JSON.stringify(b)) continue;
36
+ if (isPlain(a) && isPlain(b)) {
37
+ for (const k of [...Object.keys(b), ...Object.keys(a).filter((k) => !(k in b))]) {
38
+ if (JSON.stringify(a[k]) !== JSON.stringify(b[k])) edits.push({ path: [section, k], value: b[k] });
39
+ }
40
+ } else edits.push({ path: [section], value: b });
41
+ }
42
+ return edits;
43
+ }
44
+
45
+ /**
46
+ * The config `--write-config` writes: `text` (the `--cloth` config at `where`) with {@link clothConfigEdits} spliced
47
+ * in. Refused, `PROPOSE_WRITE_CONFIG_SPLICE`, when the spliced text does not parse to the input with those edits
48
+ * made — the text states a key twice, so the edit lands on one and the parse keeps the other.
49
+ */
50
+ export function writtenClothConfig(where: string, text: string, edits: readonly ConfigEdit[]): string {
51
+ const r = splicedEdits(text, edits);
52
+ if (r.moved !== null) {
53
+ throw new PartsError([
54
+ {
55
+ code: 'PROPOSE_WRITE_CONFIG_SPLICE',
56
+ object: where,
57
+ detail: `the drafted sections spliced into this text do not parse to the config with them set: ${r.moved} moved (the text states a key twice, so the splice lands on the first and the parse keeps the last); state each key once`,
58
+ },
59
+ ]);
60
+ }
61
+ return r.text;
62
+ }
63
+
64
+ /** The paths the edits name, dotted, in order: what the write line prints. */
65
+ export function editPaths(edits: readonly ConfigEdit[]): string[] {
66
+ return edits.map((e) => e.path.join('.'));
67
+ }
package/src/meshdraft.ts CHANGED
@@ -483,8 +483,11 @@ export function partsNamed(p: Problem, among: readonly string[], seams: { draft:
483
483
  // the config written: the input's own text, with the drafted entries spliced in
484
484
  // ---------------------------------------------------------------------------
485
485
 
486
- /** Where a JSON value starts and ends in a text, by a path of object keys. Throws when the path does not resolve. */
487
- export function jsonValueSpan(text: string, path: readonly string[]): { start: number; end: number } {
486
+ /**
487
+ * Where a JSON value starts and ends in a text, by a path of object keys, and (for a non-empty path) where the key
488
+ * naming it starts (`key`, its opening quote). Throws when the path does not resolve.
489
+ */
490
+ export function jsonValueSpan(text: string, path: readonly string[]): { start: number; end: number; key?: number } {
488
491
  let i = 0;
489
492
  const ws = (): void => {
490
493
  while (i < text.length && /\s/.test(text[i])) i++;
@@ -530,22 +533,27 @@ export function jsonValueSpan(text: string, path: readonly string[]): { start: n
530
533
  }
531
534
  while (i < text.length && !/[\s,}\]]/.test(text[i])) i++;
532
535
  };
533
- const find = (depth: number): { start: number; end: number } => {
536
+ let keyAt: number | undefined;
537
+ const find = (depth: number): { start: number; end: number; key?: number } => {
534
538
  ws();
535
539
  if (depth === path.length) {
536
540
  const start = i;
537
541
  skip();
538
- return { start, end: i };
542
+ return keyAt === undefined ? { start, end: i } : { start, end: i, key: keyAt };
539
543
  }
540
544
  if (text[i] !== '{') throw new Error(`jsonValueSpan: ${path.slice(0, depth).join('.') || 'the document'} is not an object`);
541
545
  i++;
542
546
  for (;;) {
543
547
  ws();
544
548
  if (text[i] === '}') throw new Error(`jsonValueSpan: no key "${path[depth]}" at ${path.slice(0, depth).join('.') || 'the top'}`);
549
+ const at = i;
545
550
  const key = str();
546
551
  ws();
547
552
  i++; // ':'
548
- if (key === path[depth]) return find(depth + 1);
553
+ if (key === path[depth]) {
554
+ keyAt = at;
555
+ return find(depth + 1);
556
+ }
549
557
  skip();
550
558
  ws();
551
559
  if (text[i] === ',') i++;
@@ -554,25 +562,111 @@ export function jsonValueSpan(text: string, path: readonly string[]): { start: n
554
562
  return find(0);
555
563
  }
556
564
 
565
+ /** One edit {@link splicedEdits} makes: the value at `path` set (replaced, or inserted when absent), or, `undefined`, removed. */
566
+ export interface ConfigEdit {
567
+ path: readonly string[];
568
+ value: unknown;
569
+ }
570
+
571
+ /** The span at `path`, or null where the path does not resolve (a key absent, or a step that is not an object). */
572
+ function spanOrNull(text: string, path: readonly string[]): { start: number; end: number; key?: number } | null {
573
+ try {
574
+ return jsonValueSpan(text, path);
575
+ } catch {
576
+ return null;
577
+ }
578
+ }
579
+
580
+ /** The white space a line starts with, for the line `at` lies on. */
581
+ function indentAt(text: string, at: number): string {
582
+ const lineStart = text.lastIndexOf('\n', at) + 1;
583
+ return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? '';
584
+ }
585
+
586
+ /** One edit on `text`; every byte it does not name is the input's. */
587
+ function spliceOne(text: string, path: readonly string[], value: unknown): string {
588
+ const at = spanOrNull(text, path);
589
+ if (value === undefined) {
590
+ if (at === null || at.key === undefined) return text;
591
+ // The member and one comma beside it: the one before it, or (the first member) the one after it.
592
+ let before = at.key - 1;
593
+ while (before >= 0 && /\s/.test(text[before])) before--;
594
+ if (text[before] === ',') return `${text.slice(0, before)}${text.slice(at.end)}`;
595
+ let after = at.end;
596
+ while (after < text.length && /\s/.test(text[after])) after++;
597
+ if (text[after] === ',') {
598
+ after++;
599
+ while (after < text.length && /\s/.test(text[after])) after++;
600
+ return `${text.slice(0, at.key)}${text.slice(after)}`;
601
+ }
602
+ return `${text.slice(0, at.key)}${text.slice(at.end)}`;
603
+ }
604
+ if (at !== null) {
605
+ const body = JSON.stringify(value, null, 2).split('\n').join(`\n${indentAt(text, at.start)}`);
606
+ return `${text.slice(0, at.start)}${body}${text.slice(at.end)}`;
607
+ }
608
+ const parentPath = path.slice(0, -1);
609
+ const parent = spanOrNull(text, parentPath);
610
+ // A parent the text lacks is inserted whole, holding this one member.
611
+ if (parent === null) return spliceOne(text, parentPath, { [path[path.length - 1]]: value });
612
+ if (text[parent.start] !== '{') throw new Error(`splicedEdits: ${parentPath.join('.') || 'the document'} is not an object`);
613
+ const indent = `${indentAt(text, parent.start)} `;
614
+ const member = `"${path[path.length - 1]}": ${JSON.stringify(value, null, 2).split('\n').join(`\n${indent}`)}`;
615
+ let last = parent.end - 2;
616
+ while (last > parent.start && /\s/.test(text[last])) last--;
617
+ if (last === parent.start) return `${text.slice(0, parent.start + 1)}\n${indent}${member}\n${indentAt(text, parent.start)}${text.slice(parent.end - 1)}`;
618
+ return `${text.slice(0, last + 1)},\n${indent}${member}${text.slice(last + 1)}`;
619
+ }
620
+
621
+ /** The first path, depth first in the intended document's key order, where `got` and `want` differ. */
622
+ function firstMoved(got: unknown, want: unknown, path: readonly string[]): string | null {
623
+ const plain = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
624
+ if (plain(got) && plain(want)) {
625
+ for (const k of [...Object.keys(want), ...Object.keys(got).filter((k) => !(k in want))]) {
626
+ const m = firstMoved(got[k], want[k], [...path, k]);
627
+ if (m !== null) return m;
628
+ }
629
+ return null;
630
+ }
631
+ return JSON.stringify(got) === JSON.stringify(want) ? null : path.join('.') || 'the document';
632
+ }
633
+
557
634
  /**
558
- * The config written: `text` with `meshes.<part>` replaced for every part in `drafted`, each entry as
559
- * `JSON.stringify(entry, null, 2)` indented to the line its key starts on. Every other byte is the input's, so a
560
- * config with nothing drafted is written byte for byte as read, and a part that keeps its lattice keeps its text.
561
- * The result is parsed and held to the intended document before it is returned.
635
+ * The input's own text with each edit made in order: a value present is replaced, as `JSON.stringify(value, null, 2)`
636
+ * indented to the line it starts on; one absent is inserted as the last member of its object (an absent parent
637
+ * inserted with it); `undefined` removes the member. Every other byte is the input's. The result is parsed and held
638
+ * to the intended document — the input parsed with the same edits made on it — and `moved` names the first path
639
+ * where it is not (a key the text states twice is the way it is not: the edit lands on the first, the parse keeps the
640
+ * last); null when it is.
562
641
  */
563
- export function splicedConfig(text: string, drafted: ReadonlyMap<string, unknown>): string {
564
- const spans = [...drafted.keys()].map((part) => ({ part, ...jsonValueSpan(text, ['meshes', part]) })).sort((a, b) => b.start - a.start);
642
+ export function splicedEdits(text: string, edits: readonly ConfigEdit[]): { text: string; moved: string | null } {
565
643
  let out = text;
566
- for (const s of spans) {
567
- const lineStart = out.lastIndexOf('\n', s.start) + 1;
568
- const indent = /^\s*/.exec(out.slice(lineStart, s.start))?.[0] ?? '';
569
- const body = JSON.stringify(drafted.get(s.part), null, 2).split('\n').join(`\n${indent}`);
570
- out = `${out.slice(0, s.start)}${body}${out.slice(s.end)}`;
644
+ for (const e of edits) out = spliceOne(out, e.path, e.value);
645
+ const want = JSON.parse(text) as Record<string, unknown>;
646
+ for (const e of edits) {
647
+ let o = want;
648
+ for (const k of e.path.slice(0, -1)) {
649
+ if (typeof o[k] !== 'object' || o[k] === null) o[k] = {};
650
+ o = o[k] as Record<string, unknown>;
651
+ }
652
+ const last = e.path[e.path.length - 1];
653
+ if (e.value === undefined) delete o[last];
654
+ else o[last] = e.value;
571
655
  }
572
- const want = JSON.parse(text) as { meshes: Record<string, unknown> };
573
- for (const [part, entry] of drafted) want.meshes[part] = entry;
574
- if (JSON.stringify(JSON.parse(out)) !== JSON.stringify(want)) throw new Error('splicedConfig: the spliced text does not parse to the intended config');
575
- return out;
656
+ return { text: out, moved: firstMoved(JSON.parse(out), want, []) };
657
+ }
658
+
659
+ /**
660
+ * The config written: `text` with `meshes.<part>` replaced for every part in `drafted`, each entry as
661
+ * `JSON.stringify(entry, null, 2)` indented to the line its key starts on ({@link splicedEdits}). Every other byte is
662
+ * the input's, so a config with nothing drafted is written byte for byte as read, and a part that keeps its lattice
663
+ * keeps its text. The result is parsed and held to the intended document before it is returned.
664
+ */
665
+ export function splicedConfig(text: string, drafted: ReadonlyMap<string, unknown>): string {
666
+ for (const part of drafted.keys()) jsonValueSpan(text, ['meshes', part]);
667
+ const r = splicedEdits(text, [...drafted].map(([part, entry]) => ({ path: ['meshes', part], value: entry })));
668
+ if (r.moved !== null) throw new Error('splicedConfig: the spliced text does not parse to the intended config');
669
+ return r.text;
576
670
  }
577
671
 
578
672
  /** A path in a config the loader resolves against the config's directory, and how to set it. */