@rig-c/parts 2.45.0 → 2.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/assemble.ts CHANGED
@@ -4882,7 +4882,8 @@ function cutLimbs(
4882
4882
  const art = (x: number, y: number): boolean => x >= 0 && y >= 0 && x < W && y < H && own[y * W + x] === li && source.r.data[(y * W + x) * 4 + 3] > OPAQUE_ALPHA_ABOVE;
4883
4883
  const run = limbRun(line, art, [0, 0, W - 1, H - 1]);
4884
4884
  if (run === null && emptyTargets?.has(sg.hybrid.part)) return;
4885
- const width = sg.hybrid.width ?? (run === null ? 0 : 2 * halfWidthAbout(run));
4885
+ const measuredWidth = run === null ? 0 : 2 * halfWidthAbout(run);
4886
+ const width = sg.hybrid.width ?? measuredWidth;
4886
4887
  const upper = places.get(segs[k - 1].bone) as BonePlace;
4887
4888
  const lower = places.get(sg.bone) as BonePlace;
4888
4889
  const reach = (p: readonly number[]): number => Math.abs((p[0] - line.at[0]) * line.axis[0] + (p[1] - line.at[1]) * line.axis[1]);
@@ -4923,7 +4924,11 @@ function cutLimbs(
4923
4924
  if (along < width / 2) { rasters[loAt].data.fill(0, p * 4, p * 4 + 4); regions[loAt].data[p] = 0; }
4924
4925
  }
4925
4926
  const base = parts[loAt].record;
4926
- const geometry = { upper: segs[k - 1].bone, width, radius: (base.cap as CapRecord).radius, at: [...line.at] as [number, number], axis: [...line.axis] as [number, number] };
4927
+ const geometry = {
4928
+ upper: segs[k - 1].bone, width, measured_width: measuredWidth,
4929
+ radius: (base.cap as CapRecord).radius,
4930
+ at: [...line.at] as [number, number], axis: [...line.axis] as [number, number],
4931
+ };
4927
4932
  delete base.cap;
4928
4933
  base.hybrid = { part: sg.hybrid.part, ...geometry };
4929
4934
  capFrom[loAt] = null;
@@ -0,0 +1,267 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { authoredUnitDepths } from './authoredunit.ts';
5
+ import { isDoorKey, loadEarlyConfig, turnMovingPartPair, type AssembleConfig, type CharacterConfig, type Cut } from './config.ts';
6
+ import type { DepthRunConfig, UserDepthSheet } from './depthsheets.ts';
7
+ import { PartsError, refuseIfAny } from './errors.ts';
8
+ import { readWrapperLayers } from './layers.ts';
9
+ import { bonePlaces } from './limbs.ts';
10
+ import type { AssemblyConfigRecord, PartsFile } from './parts.ts';
11
+ import { PLATE_RECEIPT_FILE, verifyPlateReceipt } from './plate.ts';
12
+ import { isSkeletonName } from './skeleton.ts';
13
+ import { setupPaintingFilePath, type SetupPainting } from './setuppainting.ts';
14
+ import { DEFAULT_GROUND, DEFAULT_PROJECT_RULE, type ProjectRule } from './projectrule.ts';
15
+ import { DEFAULT_SEAM_RULE, type SeamRule } from './seamrule.ts';
16
+ import { readRequirements } from './requirements.ts';
17
+
18
+ type AssemblySource = Omit<AssembleConfig, 'seethrough'> & Partial<Pick<AssembleConfig, 'seethrough'>> & Pick<CharacterConfig, 'generation'>;
19
+
20
+ export interface AssemblyRules {
21
+ seam?: SeamRule;
22
+ project?: ProjectRule;
23
+ }
24
+
25
+ export function effectiveAssemblyRules(config: AssemblyRules, overrides: AssemblyRules = {}): Required<AssemblyRules> {
26
+ return { seam: overrides.seam ?? config.seam ?? DEFAULT_SEAM_RULE, project: overrides.project ?? config.project ?? DEFAULT_PROJECT_RULE };
27
+ }
28
+
29
+ const sha256 = (text: string | Uint8Array): string => createHash('sha256').update(text).digest('hex');
30
+
31
+ function fileBytes(path: string, field: string): Buffer {
32
+ try {
33
+ if (statSync(path).isFile()) return readFileSync(path);
34
+ } catch {
35
+ // Give callers the same named refusal for missing and unreadable files.
36
+ }
37
+ throw new PartsError([{ code: 'CONFIG_FILE_PRESENT', object: `config.${field}`, detail: `names ${path}; a readable file is required` }]);
38
+ }
39
+
40
+ function layerRunDigest(path: string, field: string): unknown {
41
+ if (/\.psd$/i.test(path)) return sha256(fileBytes(path, field));
42
+ const run = readWrapperLayers(path);
43
+ return {
44
+ manifest: sha256(fileBytes(run.source, field)),
45
+ // Wrapper layers always retain a file. PSD files are handled above.
46
+ layers: [...run.layers, ...run.hidden].map(layer => sha256(fileBytes(layer.file!, field))),
47
+ };
48
+ }
49
+
50
+ function plateDigest(path: string, field: string): string {
51
+ const receipt = resolve(path, PLATE_RECEIPT_FILE);
52
+ const bytes = fileBytes(receipt, field);
53
+ refuseIfAny(verifyPlateReceipt(receipt));
54
+ return sha256(bytes);
55
+ }
56
+
57
+ // These maps use authored part, bone or layer names as keys, independently
58
+ // of the loader's metadata spelling for structural fields.
59
+ const authoredKeyMaps = new Set(['layers', 'tips', 'drawn', 'base_anchor']);
60
+
61
+ function canonical(value: unknown, authoredKeys = false): unknown {
62
+ if (Array.isArray(value)) return value.map(entry => canonical(entry));
63
+ if (value !== null && typeof value === 'object') {
64
+ const fields = value as Record<string, unknown>;
65
+ const keys = Object.keys(fields).filter(key => authoredKeys || !isDoorKey(key)).sort();
66
+ return Object.fromEntries(keys.map(key => [key, canonical(fields[key], !authoredKeys && authoredKeyMaps.has(key))]));
67
+ }
68
+ return value;
69
+ }
70
+
71
+ function movingPairs(cfg: AssemblySource, names: readonly string[]): Array<[string, string]> {
72
+ const moves = turnMovingPartPair(cfg);
73
+ if (moves === null) return [];
74
+ return names.flatMap((a, i) => names.slice(i + 1).filter(b => moves(a, b)).map((b): [string, string] => [a, b]));
75
+ }
76
+
77
+ /** Config values consumed by assembly, evaluated against the assembled names and run shape. */
78
+ export function readAssemblyConfig(
79
+ cfg: AssemblySource, parts: PartsFile, configPath: string, overrides?: AssemblyRules,
80
+ ): AssemblyConfigRecord {
81
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, overrides);
82
+ const ground = project === 'visible' ? cfg.assemble.ground ?? DEFAULT_GROUND : DEFAULT_GROUND;
83
+ const base = dirname(resolve(configPath));
84
+ const file = (path: string | undefined, field: string): string | undefined =>
85
+ path === undefined ? undefined : sha256(fileBytes(resolve(base, path), field));
86
+ const run = (path: string | undefined, field: string): unknown =>
87
+ path === undefined ? undefined : layerRunDigest(resolve(base, path), field);
88
+ const plate = (path: string | undefined, field: string): string | undefined =>
89
+ path === undefined ? undefined : plateDigest(resolve(base, path), field);
90
+ const cuts = (entries: Cut[] | undefined, field: string): unknown => entries?.length
91
+ ? entries.map((cut, i) => ({
92
+ ...cut,
93
+ under: typeof cut.under === 'string' ? file(cut.under, `${field}[${i}].under`)
94
+ : cut.under === undefined ? undefined : { plate: plate(cut.under.plate, `${field}[${i}].under.plate`) },
95
+ }))
96
+ : undefined;
97
+ const sheet = (value: UserDepthSheet, field: string): unknown => ({ ...value, image: file(value.image, field) });
98
+ const depthRun = (value: DepthRunConfig | undefined, field: string): unknown => value === undefined ? undefined : ({
99
+ atlas: value.atlas === undefined ? undefined : sheet(value.atlas, `${field}.atlas.image`),
100
+ layers: value.layers === undefined ? undefined : Object.fromEntries(Object.entries(value.layers)
101
+ .map(([name, layer]) => [name, sheet(layer, `${field}.layers.${name}.image`)])),
102
+ });
103
+ const skeleton = cfg.generation?.control?.skeleton;
104
+ const requirementsPath = ground === 'busy' && cfg.requirements !== undefined
105
+ ? resolve(base, cfg.requirements) : undefined;
106
+ const setup = requirementsPath === undefined ? undefined : readRequirements(requirementsPath).setup_painting;
107
+ const setupImage = (declaration: SetupPainting['figure_mask'] | SetupPainting['backdrop'], field: string) =>
108
+ declaration === undefined ? undefined : {
109
+ ...declaration,
110
+ path: sha256(fileBytes(setupPaintingFilePath(requirementsPath!, declaration.path), `requirements.setup_painting.${field}.path`)),
111
+ };
112
+ const edited = cfg.assemble.edited_parts;
113
+ const names = [...new Set([
114
+ ...parts.parts.map(part => part.name),
115
+ ...(parts.alternates ?? []).flatMap(set => set.records.map(part => part.name)),
116
+ ...(cfg.assemble.cuts ?? []).map(cut => cut.into),
117
+ ...(cfg.assemble.patches ?? []).map(patch => patch.name),
118
+ ...cfg.assemble.plan.map(([name]) => name),
119
+ ])].sort();
120
+ const basePairs = movingPairs({ ...cfg, constraints: undefined }, names);
121
+ const baseSet = new Set(basePairs.map(pair => JSON.stringify(pair)));
122
+ const physicsPairs = movingPairs(cfg, names).filter(pair => !baseSet.has(JSON.stringify(pair)));
123
+ const { resolution, head_box, arm_split } = cfg.seethrough ?? {};
124
+ const hasHeadRun = Object.keys(parts.ghost_px).some(name => name.startsWith('head:'));
125
+ const frontParts = new Set((cfg.assemble.alternates ?? []).flatMap(set => set.front ?? []));
126
+ const bands = [
127
+ { name: null, records: parts.parts },
128
+ ...(parts.alternates ?? []).map(({ name, records }) => ({ name, records })),
129
+ ];
130
+ const hybridWidths = new Map<string, Array<{ set: string | null; width?: number }>>();
131
+ const limbs = Object.entries(cfg.limbs ?? {}).map(([name, { segments, split, front }]) => {
132
+ const activeFront = front?.parts.filter(part => frontParts.has(part)) ?? [];
133
+ const resolvedSegments = segments.map(({ hybrid, ...declared }, i) => {
134
+ const segment = { ...declared, cap: file(declared.cap, `limbs.${name}.segments[${i}].cap`) };
135
+ if (hybrid === undefined) return segment;
136
+ hybridWidths.set(hybrid.part, bands.flatMap(({ name: set, records }) => {
137
+ const band = records.find(record => record.name === hybrid.part)?.limb?.band;
138
+ return band === undefined ? [] : [{ set, width: hybrid.width ?? band.measured_width }];
139
+ }));
140
+ return { ...segment, hybrid: { part: hybrid.part } };
141
+ });
142
+ return [name, {
143
+ segments: resolvedSegments,
144
+ split,
145
+ front: front !== undefined && activeFront.length > 0 ? { parts: activeFront, after: front.after } : undefined,
146
+ }] as const;
147
+ });
148
+ const limbBones = new Set(limbs.flatMap(([, limb]) => limb.segments.map(segment => segment.bone)));
149
+ const alternateBones = new Set((cfg.assemble.alternates ?? []).flatMap(set => Object.keys(set.tips ?? {})));
150
+ const posesAlternate = limbs.length > 0 && cfg.assemble.alternates?.some(set => set.drawn !== undefined || set.skeleton !== undefined);
151
+ const geometry = limbBones.size === 0 && alternateBones.size === 0 ? [] : [...bonePlaces(cfg.bones ?? [])]
152
+ .filter(([name]) => limbBones.has(name) || alternateBones.has(name));
153
+ // Alternate skeleton and drawn registration also use the hierarchy.
154
+ const bones = posesAlternate ? cfg.bones : geometry.length === 0 ? undefined : geometry;
155
+ const assemble = {
156
+ ...cfg.assemble,
157
+ ground,
158
+ project,
159
+ seam,
160
+ extend_below_crop: cfg.assemble.extend_below_crop?.length ? cfg.assemble.extend_below_crop : undefined,
161
+ patches: cfg.assemble.patches?.length ? cfg.assemble.patches : undefined,
162
+ cuts: cuts(cfg.assemble.cuts, 'assemble.cuts'),
163
+ keep_under_occluders: cfg.assemble.keep_under_occluders?.length ? cfg.assemble.keep_under_occluders : undefined,
164
+ require_hidden_extent: cfg.assemble.require_hidden_extent?.length ? cfg.assemble.require_hidden_extent : undefined,
165
+ head_face_underfill: hasHeadRun && cfg.assemble.head_face_underfill === true ? true : undefined,
166
+ yield_refused: cfg.assemble.yield_refused === true ? true : undefined,
167
+ stage_map: undefined,
168
+ editor_receipts: undefined,
169
+ edited_parts: edited?.receipts.length ? {
170
+ receipts: edited.receipts.map((receipt, i) => ({
171
+ ...receipt,
172
+ file: file(resolve(base, edited.dir, receipt.file), `assemble.edited_parts.receipts[${i}].file`),
173
+ })),
174
+ } : undefined,
175
+ occluders: cfg.assemble.occluders?.length ? cfg.assemble.occluders.map((item, i) => ({
176
+ ...item,
177
+ image: file(item.image, `assemble.occluders[${i}].image`),
178
+ plate: plate(item.plate, `assemble.occluders[${i}].plate`),
179
+ grow: item.grow === 0 ? undefined : item.grow,
180
+ guard: item.guard === 0 ? undefined : item.guard,
181
+ })) : undefined,
182
+ take: cfg.assemble.take?.length ? cfg.assemble.take.map((take, i) => {
183
+ const field = `assemble.take[${i}]`;
184
+ const reference = 'reference' in take ? take.reference : undefined;
185
+ return {
186
+ ...take,
187
+ run_dir: run(take.run_dir, `${field}.run_dir`),
188
+ st_input: file(take.st_input, `${field}.st_input`),
189
+ meta: 'tags' in take ? file(resolve(base, take.run_dir, 'meta.json'), `${field}.run_dir`) : undefined,
190
+ reference: reference !== undefined && 'painting' in reference
191
+ ? { ...reference, painting: file(reference.painting, `${field}.reference.painting`) } : reference,
192
+ };
193
+ }) : undefined,
194
+ alternates: cfg.assemble.alternates?.length ? cfg.assemble.alternates.map((set, i) => ({
195
+ ...set,
196
+ source: file(set.source, `assemble.alternates[${i}].source`),
197
+ full: run(set.full, `assemble.alternates[${i}].full`),
198
+ head: run(set.head, `assemble.alternates[${i}].head`),
199
+ skeleton: file(set.skeleton, `assemble.alternates[${i}].skeleton`),
200
+ cuts: cuts(set.cuts, `assemble.alternates[${i}].cuts`),
201
+ layers: Object.keys(set.layers ?? {}).length === 0 ? undefined : set.layers,
202
+ })) : undefined,
203
+ };
204
+ const inputs = {
205
+ ...Object.fromEntries(Object.entries(assemble).filter(([key]) => !isDoorKey(key)).map(([key, value]) => [`assemble.${key}`, value])),
206
+ bones,
207
+ 'constraints.physics': physicsPairs.length === 0 ? undefined : physicsPairs,
208
+ 'depth.authored_units': cfg.depth === undefined ? undefined : [...authoredUnitDepths(cfg)].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
209
+ depth: cfg.depth === undefined ? undefined : {
210
+ ...cfg.depth,
211
+ full: depthRun(cfg.depth.full, 'depth.full'),
212
+ head: depthRun(cfg.depth.head, 'depth.head'),
213
+ },
214
+ 'generation.control.skeleton': skeleton === undefined ? undefined : {
215
+ latent: cfg.generation?.latent,
216
+ ...(isSkeletonName(skeleton) ? { builtin: skeleton } : { file: file(skeleton, 'generation.control.skeleton') }),
217
+ },
218
+ limbs: limbs.length === 0 ? undefined : limbs,
219
+ 'limbs.hybrid_width': hybridWidths.size === 0 ? undefined : [...hybridWidths],
220
+ motion_seams: cfg.motion_seams,
221
+ 'requirements.setup_painting': setup === undefined ? undefined : {
222
+ ...setup,
223
+ figure_mask: setupImage(setup.figure_mask, 'figure_mask'),
224
+ backdrop: setupImage(setup.backdrop, 'backdrop'),
225
+ },
226
+ scene: cfg.scene === undefined ? undefined : true,
227
+ 'seethrough.resolution': resolution,
228
+ 'seethrough.head_box': hasHeadRun ? head_box : undefined,
229
+ 'seethrough.arm_split': arm_split,
230
+ turn: basePairs.length === 0 ? undefined : basePairs,
231
+ };
232
+ const fields = Object.entries(inputs).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
233
+ .flatMap(([name, value]) => value === undefined ? [] : [{ name, sha256: sha256(JSON.stringify(canonical(value))) }]);
234
+ return { sha256: assemblyFieldDigest(fields), fields };
235
+ }
236
+
237
+ export function assemblyFieldDigest(fields: AssemblyConfigRecord['fields']): string {
238
+ return sha256(JSON.stringify(fields.map(({ name, sha256 }) => [name, sha256])));
239
+ }
240
+
241
+ export function assemblyConfigReading(configPath: string, parts: PartsFile): AssemblyConfigRecord {
242
+ return readAssemblyConfig(loadEarlyConfig(configPath, 'assemble'), parts, configPath);
243
+ }
244
+
245
+ export function changedAssemblyFields(previous: AssemblyConfigRecord, current: AssemblyConfigRecord): string[] {
246
+ if (previous.sha256 === current.sha256) return [];
247
+ const before = new Map(previous.fields.map(row => [row.name, row.sha256]));
248
+ const after = new Map(current.fields.map(row => [row.name, row.sha256]));
249
+ return [...new Set([...before.keys(), ...after.keys()])].sort().filter(name => before.get(name) !== after.get(name));
250
+ }
251
+
252
+ export function assemblyConfigChanges(configPath: string, parts: PartsFile): string[] {
253
+ if (parts.assembly_config === undefined) return [];
254
+ return changedAssemblyFields(parts.assembly_config, assemblyConfigReading(configPath, parts));
255
+ }
256
+
257
+ export function assemblyChangeDetail(changes: readonly string[]): string {
258
+ return `assembly config changed at ${changes.map(name => `config.${name}`).join(', ')}; re-run assemble from the current config`;
259
+ }
260
+
261
+ export function refuseStaleAssembly(configPath: string, parts: PartsFile, loaded?: AssemblySource, overrides?: AssemblyRules): void {
262
+ if (parts.assembly_config === undefined) return;
263
+ const cfg = loaded ?? loadEarlyConfig(configPath, 'assemble', overrides?.project);
264
+ const current = readAssemblyConfig(cfg, parts, configPath, overrides);
265
+ const changes = changedAssemblyFields(parts.assembly_config, current);
266
+ if (changes.length > 0) throw new PartsError([{ code: 'ASSEMBLY_CONFIG_STALE', object: configPath, detail: assemblyChangeDetail(changes) }]);
267
+ }
package/src/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { changedAssemblyFields, effectiveAssemblyRules, readAssemblyConfig, refuseStaleAssembly, type AssemblyRules } from './assembly-reading.ts';
1
2
  import { editedPartFrontColourLines, readEditedParts } from './editedparts.ts';
2
3
  import { SOURCE_COVER_FILE, sourceCoverReport, type SourceCoverSet } from './sourcecover.ts';
3
4
  import { STAGE_MAP_FILE } from './provenance.ts';
@@ -6,7 +7,6 @@ import { readSetupFigureMask } from './setupfiguremask.ts';
6
7
  import { EDGE_RESIDUAL_FILE, edgeResidualLines } from './edgeresidual.ts';
7
8
  import { SUPPORT_DOMAINS_FILE, writeSupportDomains } from './supportdomains.ts';
8
9
  import { COINCIDE_LINE, supportLines } from './coincide.ts';
9
- import { DEFAULT_SEAM_RULE } from './seamrule.ts';
10
10
  import { DEFAULT_PROJECT_RULE } from './projectrule.ts';
11
11
  import { type PaintingAllocationReading, type PaintingAllocationEvent, EDGE_CONTRAST, PAINTING_ALLOCATION_FILE, PAINTING_EDGE_COVERAGE_TRANSFER } from './paintingedges.ts';
12
12
  import { SETUP_PAINTING_LINE, setupPaintingLines } from './setuppainting.ts';
@@ -108,7 +108,7 @@ import { CONTROL_SUFFIX, withAnimations } from './motion.ts';
108
108
  import type { PaletteError } from './palette.ts';
109
109
  import { type LayerSet, readLayers } from './layers.ts';
110
110
  import { placeBoneEntriesForSkeleton, poseBoneEntriesForDrawn, REGISTER_OFFSET_BAR, REGISTER_SCALE_BAR, registeredWithinBar, registerSkeleton, SKELETON_LIMB_BONES, skeletonDrawnLength, skeletonLimbJoints } from './limbs.ts';
111
- import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type OccluderPlateRecord, type PartRecord, partImageReference, depthImageReference, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
111
+ import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type OccluderPlateRecord, type PartRecord, partImageReference, depthImageReference, readParts, readPartsManifest, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
112
112
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
113
113
  import type { Raster } from './raster/types.ts';
114
114
  import { type Mask, newMask } from './raster/types.ts';
@@ -392,8 +392,7 @@ export interface EmitFillMasksInput {
392
392
 
393
393
  export function emitFillMasksStage(input: EmitFillMasksInput, log: Log): Array<{ into: string; path: string; sha256: string; opaquePx: number }> {
394
394
  const cfg = loadEarlyConfig(input.config, 'assemble', input.project);
395
- const seam = input.seam ?? cfg.assemble.seam ?? DEFAULT_SEAM_RULE;
396
- const project = input.project ?? cfg.assemble.project ?? DEFAULT_PROJECT_RULE;
395
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, input);
397
396
  const src = readSource(input.source);
398
397
  const read = readRuns(input.full, input.head);
399
398
  const takenRuns = applyTakenLayers(read, src, cfg, input.config);
@@ -512,8 +511,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
512
511
  // regions and motion, so it requires only what it reads (issue #20).
513
512
  const cfg = loadEarlyConfig(input.config, 'assemble', input.project);
514
513
  const supportDeclarations = JSON.stringify(cfg.assemble.cuts ?? []);
515
- const seam = input.seam ?? cfg.assemble.seam ?? DEFAULT_SEAM_RULE;
516
- const project = input.project ?? cfg.assemble.project ?? DEFAULT_PROJECT_RULE;
514
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, input);
517
515
  const requirements = cfg.assemble.ground === 'busy' && project === 'visible'
518
516
  ? buildRequirements(input.requirements, cfg.requirements, input.config) : null;
519
517
  const src = readSource(input.source);
@@ -1071,6 +1069,14 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1071
1069
  result.parts.alternates = altBuilt.map((b) => b.record);
1072
1070
  }
1073
1071
 
1072
+ const reading = readAssemblyConfig(cfg, result.parts, input.config, { seam, project });
1073
+ let previousAssembly = undefined;
1074
+ if (existsSync(outs.partsJson)) {
1075
+ try { previousAssembly = readPartsManifest(outs.partsJson).assembly_config; }
1076
+ catch (error) { if (!(error instanceof PartsError)) throw error; }
1077
+ }
1078
+ result.parts.assembly_config = reading;
1079
+
1074
1080
  const allocationPath = join(dirname(outs.partsJson), PAINTING_ALLOCATION_FILE);
1075
1081
  let previousAllocationFiles: string[] = [];
1076
1082
  if (existsSync(allocationPath)) {
@@ -1099,6 +1105,10 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1099
1105
  sha256: createHash('sha256').update(paintingBytes).digest('hex'), resample: 'lanczos3-rgb-opaque' };
1100
1106
  writeFileSync(join(dirname(outs.partsJson), PAINTING_IN_RIG_FILE), paintingBytes);
1101
1107
  writeParts(outs.partsJson, result.parts);
1108
+ if (previousAssembly !== undefined) {
1109
+ const changes = changedAssemblyFields(previousAssembly, reading);
1110
+ if (changes.length > 0) log(`note: reassembled parts after changes to ${changes.map(name => `config.${name}`).join(', ')}`);
1111
+ }
1102
1112
  writeFileSync(join(dirname(outs.partsJson), SOURCE_COVER_FILE), JSON.stringify(sourceCoverReport(sourceCoverSets), null, 2) + '\n');
1103
1113
  const stageMapPath = join(dirname(outs.partsJson), STAGE_MAP_FILE);
1104
1114
  if (result.stageMap === undefined) rmSync(stageMapPath, { force: true });
@@ -1466,6 +1476,7 @@ export function contourBodyTurnRemedies(lines: readonly string[], cfg: Character
1466
1476
  }
1467
1477
 
1468
1478
  export interface RigStageInput {
1479
+ assemblyRules?: AssemblyRules;
1469
1480
  config: string;
1470
1481
  /** The directory holding parts.json and parts/<name>.png. */
1471
1482
  parts: string;
@@ -1855,9 +1866,10 @@ export interface RigInputs {
1855
1866
  * `src/meshstats.ts`) both start here, so the two read the same config, the same parts and the same images, and a
1856
1867
  * PNG that is missing is left out of the map for `buildRig` to refuse by name (`RIG_PNG_PRESENT`).
1857
1868
  */
1858
- export function readRigInputs(config: string, partsDir: string): RigInputs {
1869
+ export function readRigInputs(config: string, partsDir: string, assemblyRules?: AssemblyRules): RigInputs {
1859
1870
  const { config: cfg, animations: from } = loadConfigAndAnimations(config);
1860
1871
  const parts = readParts(join(partsDir, 'parts.json'));
1872
+ refuseStaleAssembly(config, parts, cfg, assemblyRules);
1861
1873
  const images = new Map<string, Raster>();
1862
1874
  const depthProblems: Problem[] = [];
1863
1875
  for (const p of parts.parts) {
@@ -1892,7 +1904,7 @@ export function rigOutputTexts(r: RigOutput, animations: Parameters<typeof withA
1892
1904
 
1893
1905
  export function rigStage(input: RigStageInput, rigc: RigcRunner, scratch: string, log: Log): RigOutput {
1894
1906
  const pageSize = parsePageSize(input.pageSize);
1895
- const { cfg, from, parts, images } = readRigInputs(input.config, input.parts);
1907
+ const { cfg, from, parts, images } = readRigInputs(input.config, input.parts, input.assemblyRules);
1896
1908
  const first = buildRig(cfg, parts, images, undefined, input.idleKeys ?? DEFAULT_IDLE_KEYS, input.reduce);
1897
1909
  const textsOf = (r: RigOutput): Array<[string, string]> => rigOutputTexts(r, from === null ? null : from.table);
1898
1910
  const firstTexts = textsOf(first);
@@ -2062,6 +2074,7 @@ export function rigStage(input: RigStageInput, rigc: RigcRunner, scratch: string
2062
2074
  // ---------------------------------------------------------------------------
2063
2075
 
2064
2076
  export interface CheckStageInput {
2077
+ assemblyRules?: AssemblyRules;
2065
2078
  /** The directory holding rig.json and motion.json. */
2066
2079
  rig: string;
2067
2080
  /**
@@ -2346,7 +2359,7 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
2346
2359
  const entryLine = versionLines.find((l) => l.startsWith('entry:'));
2347
2360
  log(` ${rigcIdentity(bin, v)}${entryLine === undefined ? '' : `; ${entryLine}`}`);
2348
2361
  const mode: PackMode = { pageEdges: input.pageEdges ?? DEFAULT_PAGE_EDGES, packShape: input.packShape ?? DEFAULT_PACK_SHAPE, ...(pageSize === undefined ? {} : { pageSize }) };
2349
- const r = runCheck(input.rig, input.out, rigc, input.parts, mode, input.source, input.requirements, input.seamPairs === true, input.keepStills === true, input.set, input.allSets === true, input.environment, input.requirementsAs, input.config, input.windBand, input.noExtremes === true, input.supportSource, input.supportFigure);
2362
+ const r = runCheck(input.rig, input.out, rigc, input.parts, mode, input.source, input.requirements, input.seamPairs === true, input.keepStills === true, input.set, input.allSets === true, input.environment, input.requirementsAs, input.config, input.windBand, input.noExtremes === true, input.supportSource, input.supportFigure, input.assemblyRules);
2350
2363
  if (r.figures.environment !== undefined) log(` ${environmentLine(r.figures.environment)}`);
2351
2364
  log(` gate rig-play (rigc ${packedBuildLabel(mode)}), verbatim:`);
2352
2365
  for (const l of r.gateHtml) log(l);
@@ -2899,6 +2912,7 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2899
2912
  // cannot be measured without it; a build without that declaration hands it nothing, as before, and writes the same bytes.
2900
2913
  let paintingForCheck: string | null = null;
2901
2914
  let supportFigure: Mask | undefined;
2915
+ let assemblyRules: Required<AssemblyRules>;
2902
2916
  try {
2903
2917
  pageSize = parsePageSize(input.pageSize);
2904
2918
  // build runs rig next, which needs the whole config, so the full loader is
@@ -2908,8 +2922,8 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2908
2922
  // Issue #556: the flag, or the config's declaration when there is none; both naming other bytes is refused here.
2909
2923
  // Issue #607: the bytes this read parsed are the ones check.json's config record hashes, under the path as typed.
2910
2924
  const loaded = loadConfigWithBytes(input.config);
2911
- const seam = input.seam ?? loaded.config.assemble.seam ?? DEFAULT_SEAM_RULE;
2912
- const project = input.project ?? loaded.config.assemble.project ?? DEFAULT_PROJECT_RULE;
2925
+ assemblyRules = effectiveAssemblyRules(loaded.config.assemble, input);
2926
+ const { seam, project } = assemblyRules;
2913
2927
  log(`rig-parts build: ${input.config} -> ${out}, seam rule ${seam}, projection rule ${project}, page edges ${input.pageEdges}, pack shape ${input.packShape ?? DEFAULT_PACK_SHAPE}${idleKeys === DEFAULT_IDLE_KEYS ? '' : `, idle keys ${idleKeys}`}${input.loop ? `, with the idle loop${input.leadIn === undefined ? '' : ` after a lead-in of ${input.leadIn} period(s)`}` : ''}`);
2914
2928
  configRecord = inputFileRecord(loaded.bytes, input.config);
2915
2929
  req = buildRequirements(input.requirements, loaded.config.requirements, input.config);
@@ -2930,14 +2944,14 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2930
2944
  }
2931
2945
 
2932
2946
  try {
2933
- stages.rig({ config: input.config, parts: out, out: join(out, 'rig'), idleKeys, pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), command: 'build' }, run.rig, run.scratch, prefixed('rig'));
2947
+ stages.rig({ config: input.config, assemblyRules, parts: out, out: join(out, 'rig'), idleKeys, pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), command: 'build' }, run.rig, run.scratch, prefixed('rig'));
2934
2948
  } catch (err) {
2935
2949
  return refused('rig', err);
2936
2950
  }
2937
2951
 
2938
2952
  let report: CheckReport;
2939
2953
  try {
2940
- report = stages.check({ rig: join(out, 'rig'), parts: out, supportSource: input.source, ...(supportFigure === undefined ? {} : { supportFigure }), out: join(out, 'check'), pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(req === null ? {} : { requirements: req.read, requirementsAs: req.recorded }), ...(paintingForCheck === null ? {} : { source: paintingForCheck }), seamPairs: input.seamPairs === true, keepStills: input.keepStills === true, noExtremes: input.noExtremes === true, ...(input.set === undefined ? {} : { set: input.set }), allSets: input.allSets === true, ...(input.environment === undefined ? {} : { environment: input.environment }), ...(input.windBand === undefined ? {} : { windBand: input.windBand }), ...(configRecord === null ? {} : { config: configRecord }) }, run.check, run.checkBin, prefixed('check'));
2954
+ report = stages.check({ rig: join(out, 'rig'), assemblyRules, parts: out, supportSource: input.source, ...(supportFigure === undefined ? {} : { supportFigure }), out: join(out, 'check'), pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(req === null ? {} : { requirements: req.read, requirementsAs: req.recorded }), ...(paintingForCheck === null ? {} : { source: paintingForCheck }), seamPairs: input.seamPairs === true, keepStills: input.keepStills === true, noExtremes: input.noExtremes === true, ...(input.set === undefined ? {} : { set: input.set }), allSets: input.allSets === true, ...(input.environment === undefined ? {} : { environment: input.environment }), ...(input.windBand === undefined ? {} : { windBand: input.windBand }), ...(configRecord === null ? {} : { config: configRecord }) }, run.check, run.checkBin, prefixed('check'));
2941
2955
  } catch (err) {
2942
2956
  return refused('check', err);
2943
2957
  }
package/src/check.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { refuseStaleAssembly, type AssemblyRules } from './assembly-reading.ts';
1
2
  import { checkRow, checkSlotRow, checkSlotParts, serializeCheckRows } from './checkrow.ts';
2
3
  import { readSetupFigureMask } from './setupfiguremask.ts';
3
4
  import { readSetupBackdrop } from './setupbackdrop.ts';
@@ -6791,7 +6792,7 @@ function renderExtremes(build: string, out: string, animations: readonly string[
6791
6792
  * MEASURABLE is a problem. Without it nothing here reads, writes or prints
6792
6793
  * anything it did not before.
6793
6794
  */
6794
- export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, partsHome?: string, mode: PackMode = DEFAULT_PACK_MODE, source?: string, requirements?: string, seamPairsAsked = false, keepStills = false, set?: string, allSets = false, environment?: string, requirementsAs: string | undefined = requirements, config?: InputFileRecord, windBand?: string, noExtremes = false, supportSource?: string, supportFigure?: Mask): CheckReport {
6795
+ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, partsHome?: string, mode: PackMode = DEFAULT_PACK_MODE, source?: string, requirements?: string, seamPairsAsked = false, keepStills = false, set?: string, allSets = false, environment?: string, requirementsAs: string | undefined = requirements, config?: InputFileRecord, windBand?: string, noExtremes = false, supportSource?: string, supportFigure?: Mask, assemblyRules?: AssemblyRules): CheckReport {
6795
6796
  const pageSize = parsePageSize(mode.pageSize);
6796
6797
  let inp: CheckInputs;
6797
6798
  let reqFile: RequirementsFile | null = null;
@@ -6808,6 +6809,11 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6808
6809
  return null;
6809
6810
  }
6810
6811
  };
6812
+ const readInputs = (): CheckInputs => {
6813
+ const inputs = readCheckInputs(rigDir, partsHome, source, set, allSets);
6814
+ if (config !== undefined && inputs.parts !== null) refuseStaleAssembly(config.path, inputs.parts, undefined, assemblyRules);
6815
+ return inputs;
6816
+ };
6811
6817
  let setupBackdrop: Raster | undefined;
6812
6818
  let setupFigureMask: Uint8Array | undefined;
6813
6819
  // Issue #538: the schedule is read once, first, by rigc's own reader; refused, nothing is built or written.
@@ -6815,12 +6821,12 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6815
6821
  // Issue #590: the steady-wind band spec is read and resolved before anything is built or written.
6816
6822
  const wb = windBand === undefined ? null : take(() => readWindBand(windBand));
6817
6823
  if (requirements === undefined) {
6818
- const got = take(() => readCheckInputs(rigDir, partsHome, source, set, allSets));
6824
+ const got = take(readInputs);
6819
6825
  if (got !== null && wb !== null) take(() => resolveWindBand(wb, got));
6820
6826
  refuseIfAny(refused);
6821
6827
  inp = got as CheckInputs;
6822
6828
  } else {
6823
- const got = take(() => readCheckInputs(rigDir, partsHome, source, set, allSets));
6829
+ const got = take(readInputs);
6824
6830
  reqFile = take(() => readRequirements(requirements));
6825
6831
  if (got === null || reqFile === null) {
6826
6832
  if (got !== null && wb !== null) take(() => resolveWindBand(wb, got));
@@ -6,9 +6,56 @@ function object(value: unknown): value is Record<string, unknown> {
6
6
  return value !== null && typeof value === 'object' && !Array.isArray(value);
7
7
  }
8
8
 
9
+ // The public reference inventory predates assembly fingerprinting. Writers
10
+ // must also preserve these config-relative assembly inputs at their new base.
11
+ function relocateAssemblyFiles(raw: unknown, relocate: (value: string) => string): void {
12
+ const fields = (entry: unknown, keys: readonly string[]): void => {
13
+ if (!object(entry)) return;
14
+ for (const key of keys) {
15
+ const value = entry[key];
16
+ if (typeof value === 'string' && value !== '' && !isAbsolute(value)) entry[key] = relocate(value);
17
+ }
18
+ };
19
+ const entries = (value: unknown): Record<string, unknown>[] => Array.isArray(value) ? value.filter(object) : [];
20
+ const cuts = (value: unknown): void => {
21
+ for (const cut of entries(value)) {
22
+ fields(cut, ['under']);
23
+ fields(cut.under, ['plate']);
24
+ }
25
+ };
26
+ if (!object(raw)) return;
27
+ if (object(raw.assemble)) {
28
+ cuts(raw.assemble.cuts);
29
+ for (const alt of entries(raw.assemble.alternates)) {
30
+ fields(alt, ['source', 'full', 'head', 'skeleton']);
31
+ cuts(alt.cuts);
32
+ }
33
+ for (const take of entries(raw.assemble.take)) {
34
+ fields(take, ['run_dir', 'st_input']);
35
+ fields(take.reference, ['painting']);
36
+ }
37
+ }
38
+ if (object(raw.limbs)) {
39
+ for (const limb of Object.values(raw.limbs).filter(object)) {
40
+ for (const segment of entries(limb.segments)) fields(segment, ['cap']);
41
+ }
42
+ }
43
+ if (object(raw.depth)) {
44
+ for (const run of [raw.depth.full, raw.depth.head].filter(object)) {
45
+ fields(run.atlas, ['image']);
46
+ if (object(run.layers)) for (const layer of Object.values(run.layers)) fields(layer, ['image']);
47
+ }
48
+ }
49
+ }
50
+
9
51
  /** Preserve the public reference inventory while giving writers canonical edited-part paths. */
10
52
  export function relocateConfigReferences(raw: unknown, configDir: string, out: string, mode: 'relative' | 'absolute'): void {
53
+ const pathAt = (value: string): string => {
54
+ const target = resolve(configDir, value);
55
+ return mode === 'relative' ? relative(resolve(out), target) || '.' : target;
56
+ };
11
57
  const refs = configFileReferences(raw);
58
+ relocateAssemblyFiles(raw, pathAt);
12
59
  const assemble = object(raw) ? raw.assemble : undefined;
13
60
  const edited = object(assemble) ? assemble.edited_parts : undefined;
14
61
  // Do not repair invalid dirs or replace the loader's existing relative-only refusals.
@@ -19,7 +66,6 @@ export function relocateConfigReferences(raw: unknown, configDir: string, out: s
19
66
  for (const ref of refs) {
20
67
  if (ref.at.startsWith('assemble.edited_parts.receipts[')) continue;
21
68
  if (mode === 'absolute' && isAbsolute(ref.value)) continue;
22
- const target = resolve(configDir, ref.value);
23
- ref.set(mode === 'relative' ? relative(resolve(out), target) : target);
69
+ ref.set(pathAt(ref.value));
24
70
  }
25
71
  }
@@ -14,7 +14,7 @@ import type { CharacterConfig } from './config.ts';
14
14
  import { orderedEditedPartReceipt, type EditedPartReceipt } from './editedparts.ts';
15
15
  import type { Proposal, PROPOSAL_CONFIG_SECTIONS } from './propose.ts';
16
16
  import { PartsError } from './errors.ts';
17
- import { parseConfig, parseProposalSections } from './config.ts';
17
+ import { parseConfig, parseEarlyConfig, parseProposalSections } from './config.ts';
18
18
  import type { ConfigEdit } from './meshdraft.ts';
19
19
 
20
20
  export type ConfigJson = null | boolean | number | string | ConfigJson[] | ConfigObject;
@@ -88,15 +88,17 @@ function changes(before: ConfigObject, after: ConfigObject, parent = ''): Config
88
88
  return result;
89
89
  }
90
90
 
91
- /** The caller validates the returned candidate through its existing config door before saving it. */
92
- export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): ConfigWriteResult {
91
+ /** The caller validates the returned candidate through its existing config door before saving it.
92
+ * Receipt patches can also read a source config through the assembly door.
93
+ */
94
+ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch, receiptDoor: 'full' | 'assemble' = 'full'): ConfigWriteResult {
93
95
  if (!object(raw)) return refuse('config', 'is not an object; an existing config JSON object is required');
94
96
  const before = clone(raw, 'config') as ConfigObject;
95
97
  const config = clone(before, 'config') as ConfigObject;
96
98
  const edits: ConfigEdit[] = [];
97
99
  switch (patch.kind) {
98
100
  case 'edited-part-receipt': {
99
- const checked = parseConfig(before);
101
+ const checked = receiptDoor === 'assemble' ? parseEarlyConfig(before, 'assemble') : parseConfig(before);
100
102
  const spec = checked.assemble.edited_parts;
101
103
  if (spec === undefined) throw new PartsError([{ code: 'EDITED_PART_BLOCK', object: 'config.assemble.edited_parts', detail: 'has no assemble.edited_parts; declare {dir, receipts: []} before recording an edited part' }]);
102
104
  const { part } = patch.receipt;