@rig-c/parts 2.46.0 → 2.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.
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { readFileSync, statSync } from 'node:fs';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { authoredUnitDepths } from './authoredunit.ts';
5
- import { isDoorKey, loadEarlyConfig, turnMovingPartPair, type AssembleConfig, type CharacterConfig, type Cut } from './config.ts';
5
+ import { controlSkeletonOf, isDoorKey, loadEarlyConfig, turnMovingPartPair, type AssembleConfig, type CharacterConfig, type Cut, type Limb } from './config.ts';
6
6
  import type { DepthRunConfig, UserDepthSheet } from './depthsheets.ts';
7
7
  import { PartsError, refuseIfAny } from './errors.ts';
8
8
  import { readWrapperLayers } from './layers.ts';
@@ -11,11 +11,40 @@ import type { AssemblyConfigRecord, PartsFile } from './parts.ts';
11
11
  import { PLATE_RECEIPT_FILE, verifyPlateReceipt } from './plate.ts';
12
12
  import { isSkeletonName } from './skeleton.ts';
13
13
  import { setupPaintingFilePath, type SetupPainting } from './setuppainting.ts';
14
- import { DEFAULT_GROUND, DEFAULT_PROJECT_RULE, type ProjectRule } from './projectrule.ts';
14
+ import { DEFAULT_GROUND, DEFAULT_PROJECT_RULE, type Ground, type ProjectRule } from './projectrule.ts';
15
15
  import { DEFAULT_SEAM_RULE, type SeamRule } from './seamrule.ts';
16
16
  import { readRequirements } from './requirements.ts';
17
17
 
18
- type AssemblySource = Omit<AssembleConfig, 'seethrough'> & Partial<Pick<AssembleConfig, 'seethrough'>> & Pick<CharacterConfig, 'generation'>;
18
+ export type AssemblySource = Omit<AssembleConfig, 'seethrough'> & Partial<Pick<AssembleConfig, 'seethrough'>> & Pick<CharacterConfig, 'generation'>;
19
+
20
+ type ProjectionSource = Omit<AssemblySource, 'key' | 'proposed_rig_scale'>;
21
+
22
+ function assemblyLimb({ segments, split, front }: Limb) {
23
+ return {
24
+ segments,
25
+ ...(split === undefined ? {} : { split }),
26
+ ...(front === undefined ? {} : { front }),
27
+ };
28
+ }
29
+
30
+ export type AssemblyLimb = ReturnType<typeof assemblyLimb>;
31
+
32
+ function assemblyPhysics(constraints: ProjectionSource['constraints']) {
33
+ if (!Array.isArray(constraints)) return undefined;
34
+ return constraints.flatMap(constraint =>
35
+ constraint !== null && typeof constraint === 'object' && !Array.isArray(constraint) &&
36
+ constraint.type === 'physics' && typeof constraint.bone === 'string'
37
+ ? [{ type: 'physics' as const, bone: constraint.bone }]
38
+ : []);
39
+ }
40
+
41
+ function assemblyMotion(motion: ProjectionSource['motion']) {
42
+ const still = motion?.blink?.still;
43
+ if (still == null) return undefined;
44
+ const carriers = Object.fromEntries(Object.entries(still)
45
+ .map(([part, carrier]) => [part, carrier == null ? carrier : { bone: carrier.bone }] as const));
46
+ return { blink: { still: carriers } };
47
+ }
19
48
 
20
49
  export interface AssemblyRules {
21
50
  seam?: SeamRule;
@@ -68,19 +97,253 @@ function canonical(value: unknown, authoredKeys = false): unknown {
68
97
  return value;
69
98
  }
70
99
 
71
- function movingPairs(cfg: AssemblySource, names: readonly string[]): Array<[string, string]> {
100
+ // Each value below is exposed to assembly through the same entry that declares
101
+ // its digest. A shared binding names digest fields produced by another entry.
102
+ interface ReadingContext extends ReturnType<typeof digestFiles>, Required<AssemblyRules> {
103
+ ground: Ground;
104
+ hasHeadRun: boolean;
105
+ bones: unknown;
106
+ basePairs: Array<[string, string]>;
107
+ physicsPairs: Array<[string, string]>;
108
+ limbs: unknown[];
109
+ hybridWidths: ReadonlyMap<string, Array<{ set: string | null; width?: number }>>;
110
+ setup: SetupPainting | undefined;
111
+ setupImage: (declaration: SetupPainting['figure_mask'] | SetupPainting['backdrop'], field: string) => unknown;
112
+ authoredDepths: () => unknown;
113
+ }
114
+
115
+ type ReadDigest = (ctx: ReadingContext) => unknown;
116
+ type DigestBindings = Readonly<Record<string, ReadDigest>>;
117
+ type Exemption = { readonly issue: number; readonly reason: string };
118
+ type ProjectionEntry<T> =
119
+ | { value: T; bindings: DigestBindings; shared?: never; exemption?: never }
120
+ | { value: T; bindings?: never; shared: readonly string[]; exemption?: never }
121
+ | { value: T; bindings?: never; shared?: never; exemption: Exemption };
122
+
123
+ function bound<T>(value: T, read: (value: T, ctx: ReadingContext) => unknown = value => value): ProjectionEntry<T> {
124
+ return { value, bindings: { '': ctx => read(value, ctx) } };
125
+ }
126
+
127
+ function named<T>(value: T, bindings: DigestBindings): ProjectionEntry<T> {
128
+ return { value, bindings };
129
+ }
130
+
131
+ function shared<T>(value: T, ...fields: string[]): ProjectionEntry<T> {
132
+ return { value, shared: fields };
133
+ }
134
+
135
+ function exempt<T>(value: T, issue: number, reason: string): ProjectionEntry<T> {
136
+ return { value, exemption: { issue, reason } };
137
+ }
138
+
139
+ type EntryGroup = Readonly<Record<string, ProjectionEntry<unknown>>>;
140
+ type Projected<G extends EntryGroup> = { [K in keyof G]: G[K]['value'] };
141
+
142
+ function projected<G extends EntryGroup>(group: G): Projected<G> {
143
+ return Object.fromEntries(Object.entries(group).map(([key, entry]) => [key, entry.value])) as Projected<G>;
144
+ }
145
+
146
+ function nonempty<T>(value: T[] | undefined): T[] | undefined {
147
+ return value?.length ? value : undefined;
148
+ }
149
+
150
+ function projectionEntries(cfg: ProjectionSource) {
151
+ // Follow-up #1393 covers effective requirements/receipt inputs. CLI
152
+ // requirements values are read outside this config view. Only selected values
153
+ // can be exemptions in the projection, such as the editor receipt ledger below.
154
+ const a = cfg.assemble;
155
+ // These fields used to enter the digest through the enumerable assemble spread.
156
+ const authored = <K extends keyof typeof a>(key: K) => {
157
+ const enumerable = Object.prototype.propertyIsEnumerable.call(a, key);
158
+ return bound(a[key], value => enumerable ? value : undefined);
159
+ };
160
+ const assemble = {
161
+ seam: bound(a.seam, (_, ctx) => ctx.seam),
162
+ project: bound(a.project, (_, ctx) => ctx.project),
163
+ ground: bound(a.ground, (_, ctx) => ctx.ground),
164
+ rig_scale: authored('rig_scale'),
165
+ plan: authored('plan'),
166
+ extend_below_crop: bound(a.extend_below_crop, nonempty),
167
+ extend_painting: authored('extend_painting'),
168
+ edge_splits: authored('edge_splits'),
169
+ patches: bound(a.patches, nonempty),
170
+ cuts: bound(a.cuts, (value, ctx) => ctx.cuts(value, 'assemble.cuts')),
171
+ keep_under_occluders: bound(a.keep_under_occluders, nonempty),
172
+ require_hidden_extent: bound(a.require_hidden_extent, nonempty),
173
+ head_face_underfill: bound(a.head_face_underfill, (value, ctx) => ctx.hasHeadRun && value === true ? true : undefined),
174
+ yield_refused: bound(a.yield_refused, value => value === false ? undefined : value),
175
+ stage_map: exempt(a.stage_map, 1393, 'Selects a report sidecar without changing the assembly manifest.'),
176
+ editor_receipts: exempt(a.editor_receipts, 946, 'The legacy config digest omits the validation ledger and its receipt policy.'),
177
+ edited_parts: bound(a.edited_parts, (edited, { base, file }) => edited?.receipts.length ? {
178
+ receipts: edited.receipts.map((receipt, i) => ({
179
+ ...receipt,
180
+ file: file(resolve(base, edited.dir, receipt.file), `assemble.edited_parts.receipts[${i}].file`),
181
+ })),
182
+ } : undefined),
183
+ occluders: bound(a.occluders, (items, { file, plate }) => items?.length ? items.map((item, i) => ({
184
+ ...item,
185
+ image: file(item.image, `assemble.occluders[${i}].image`),
186
+ plate: plate(item.plate, `assemble.occluders[${i}].plate`),
187
+ grow: item.grow === 0 ? undefined : item.grow,
188
+ guard: item.guard === 0 ? undefined : item.guard,
189
+ })) : undefined),
190
+ take: named(a.take, {
191
+ '': ({ base, file, run }) => a.take?.length ? a.take.map((take, i) => {
192
+ const field = `assemble.take[${i}]`;
193
+ const reference = 'reference' in take ? take.reference : undefined;
194
+ return {
195
+ ...take,
196
+ run_dir: run(take.run_dir, `${field}.run_dir`),
197
+ st_input: file(take.st_input, `${field}.st_input`),
198
+ // Keep whole-layer metadata in the original take digest.
199
+ meta: 'tags' in take ? file(resolve(base, take.run_dir, 'meta.json'), `${field}.run_dir`) : undefined,
200
+ reference: reference !== undefined && 'painting' in reference
201
+ ? { ...reference, painting: file(reference.painting, `${field}.reference.painting`) } : reference,
202
+ };
203
+ }) : undefined,
204
+ ...Object.fromEntries((a.take ?? []).flatMap((take, i) => {
205
+ if (!('occluder' in take)) return [];
206
+ const field = `assemble.take[${i}].meta`;
207
+ const digest: ReadDigest = ({ base, file }) => file(resolve(base, take.run_dir, 'meta.json'), field);
208
+ return [[field, digest]];
209
+ })),
210
+ }),
211
+ alternates: bound(a.alternates, (items, { file, run, cuts }) => items?.length ? items.map((set, i) => ({
212
+ ...set,
213
+ source: file(set.source, `assemble.alternates[${i}].source`),
214
+ full: run(set.full, `assemble.alternates[${i}].full`),
215
+ head: run(set.head, `assemble.alternates[${i}].head`),
216
+ skeleton: file(set.skeleton, `assemble.alternates[${i}].skeleton`),
217
+ cuts: cuts(set.cuts, `assemble.alternates[${i}].cuts`),
218
+ layers: Object.keys(set.layers ?? {}).length === 0 ? undefined : set.layers,
219
+ })) : undefined),
220
+ };
221
+ const st = cfg.seethrough;
222
+ const seethrough = st == null ? undefined : {
223
+ resolution: bound(st.resolution),
224
+ head_box: bound(st.head_box, (value, ctx) => ctx.hasHeadRun ? value : undefined),
225
+ arm_split: bound(st.arm_split),
226
+ };
227
+ const skeleton = cfg.generation?.control?.skeleton;
228
+ const latent = cfg.generation?.latent;
229
+ // Look up the resolved pose on the original loader object before projecting.
230
+ const root = {
231
+ bones: bound(cfg.bones, (_, ctx) => ctx.bones),
232
+ constraints: named(assemblyPhysics(cfg.constraints), {
233
+ 'constraints.physics': ctx => nonempty(ctx.physicsPairs),
234
+ }),
235
+ depth: bound(cfg.depth, (value, ctx) => value === undefined ? undefined : ({
236
+ ...value,
237
+ full: ctx.depthRun(value.full, 'depth.full'),
238
+ head: ctx.depthRun(value.head, 'depth.head'),
239
+ })),
240
+ keySkeleton: named(controlSkeletonOf(cfg), {
241
+ 'generation.control.skeleton': ctx => skeleton === undefined ? undefined : {
242
+ latent,
243
+ ...(isSkeletonName(skeleton) ? { builtin: skeleton } : { file: ctx.file(skeleton, 'generation.control.skeleton') }),
244
+ },
245
+ }),
246
+ limbs: named(cfg.limbs == null ? undefined : Object.fromEntries(
247
+ Object.entries(cfg.limbs).map(([name, limb]) => [name, assemblyLimb(limb)] as const),
248
+ ), {
249
+ limbs: ctx => nonempty(ctx.limbs),
250
+ 'limbs.hybrid_width': ctx => ctx.hybridWidths.size === 0 ? undefined : [...ctx.hybridWidths],
251
+ }),
252
+ motion_seams: bound(cfg.motion_seams),
253
+ requirements: named(cfg.requirements, {
254
+ 'requirements.setup_painting': ctx => ctx.setup === undefined ? undefined : {
255
+ ...ctx.setup,
256
+ figure_mask: ctx.setupImage(ctx.setup.figure_mask, 'figure_mask'),
257
+ backdrop: ctx.setupImage(ctx.setup.backdrop, 'backdrop'),
258
+ },
259
+ }),
260
+ scene: bound(cfg.scene === undefined ? undefined : true),
261
+ // Turn, meshes and regions reach existing carrier helpers as aggregates.
262
+ // Their digest bindings cover the current derived effects. The guard
263
+ // cannot attribute a new read inside those aggregates to a digest.
264
+ turn: named(cfg.turn, {
265
+ turn: ctx => nonempty(ctx.basePairs),
266
+ 'depth.authored_units': ctx => ctx.authoredDepths(),
267
+ }),
268
+ meshes: shared(cfg.meshes, 'turn', 'constraints.physics', 'depth.authored_units'),
269
+ regions: shared(cfg.regions, 'turn', 'constraints.physics', 'depth.authored_units'),
270
+ motion: shared(assemblyMotion(cfg.motion), 'depth.authored_units'),
271
+ };
272
+ return { assemble, seethrough, root };
273
+ }
274
+
275
+ // Keep the validator's input permissive so it can name malformed entries at
276
+ // runtime, including entries planted in tests. The live entries use the union above.
277
+ type ProjectionRow = Readonly<Partial<{
278
+ value: unknown;
279
+ bindings: DigestBindings;
280
+ shared: readonly string[];
281
+ exemption: Exemption;
282
+ }>>;
283
+
284
+ function bindingName(path: string, name: string): string {
285
+ return name === '' ? path : name;
286
+ }
287
+
288
+ export function assemblyProjectionProblems(rows: Readonly<Record<string, ProjectionRow>>): string[] {
289
+ const problems: string[] = [];
290
+ const boundNames = new Set<string>();
291
+ for (const [path, entry] of Object.entries(rows)) {
292
+ for (const name of Object.keys(entry.bindings ?? {})) {
293
+ const field = bindingName(path, name);
294
+ if (boundNames.has(field)) problems.push(`config.${field} has duplicate assembly digest bindings`);
295
+ boundNames.add(field);
296
+ }
297
+ }
298
+ for (const [path, entry] of Object.entries(rows)) {
299
+ const field = `config.${path}`;
300
+ if (entry.exemption !== undefined) {
301
+ if (!Object.hasOwn(entry, 'value')) problems.push(`${field} has an exemption but is not projected`);
302
+ if (boundNames.has(path) || entry.shared?.length || Object.keys(entry.bindings ?? {}).length) {
303
+ problems.push(`${field} has an exemption and a digest binding`);
304
+ }
305
+ } else if (Object.keys(entry.bindings ?? {}).length === 0 && !entry.shared?.length) {
306
+ problems.push(`${field} is projected without a digest binding or exemption`);
307
+ }
308
+ for (const name of entry.shared ?? []) {
309
+ if (!boundNames.has(name)) problems.push(`${field} names missing digest binding config.${name}`);
310
+ }
311
+ }
312
+ return problems;
313
+ }
314
+
315
+ export function projectAssemblyConfig(source: ProjectionSource) {
316
+ const { assemble, seethrough, root } = projectionEntries(source);
317
+ const rows: Readonly<Record<string, ProjectionRow>> = {
318
+ ...Object.fromEntries(Object.entries(assemble).map(([key, entry]) => [`assemble.${key}`, entry])),
319
+ ...root,
320
+ ...Object.fromEntries(Object.entries(seethrough ?? {}).map(([key, entry]) => [`seethrough.${key}`, entry])),
321
+ };
322
+ const problems = assemblyProjectionProblems(rows);
323
+ if (problems.length > 0) throw new Error(problems.join('\n'));
324
+ return {
325
+ config: {
326
+ assemble: projected(assemble),
327
+ seethrough: seethrough === undefined ? undefined : projected(seethrough),
328
+ ...projected(root),
329
+ },
330
+ rows,
331
+ // The loader refuses unknown assemble keys. The public reader also accepts
332
+ // inline configs, whose extra enumerable fields were historically hashed.
333
+ legacyFields: Object.entries(source.assemble).filter(([key]) => !Object.hasOwn(assemble, key) && !isDoorKey(key)),
334
+ };
335
+ }
336
+
337
+ type AssemblyProjection = ReturnType<typeof projectAssemblyConfig>;
338
+ export type AssemblyView = AssemblyProjection['config'];
339
+
340
+ function movingPairs(cfg: AssemblyView, names: readonly string[]): Array<[string, string]> {
72
341
  const moves = turnMovingPartPair(cfg);
73
342
  if (moves === null) return [];
74
343
  return names.flatMap((a, i) => names.slice(i + 1).filter(b => moves(a, b)).map((b): [string, string] => [a, b]));
75
344
  }
76
345
 
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));
346
+ function digestFiles(base: string) {
84
347
  const file = (path: string | undefined, field: string): string | undefined =>
85
348
  path === undefined ? undefined : sha256(fileBytes(resolve(base, path), field));
86
349
  const run = (path: string | undefined, field: string): unknown =>
@@ -100,7 +363,15 @@ export function readAssemblyConfig(
100
363
  layers: value.layers === undefined ? undefined : Object.fromEntries(Object.entries(value.layers)
101
364
  .map(([name, layer]) => [name, sheet(layer, `${field}.layers.${name}.image`)])),
102
365
  });
103
- const skeleton = cfg.generation?.control?.skeleton;
366
+ return { base, file, run, plate, cuts, depthRun };
367
+ }
368
+
369
+ function readingContext(cfg: AssemblyView, parts: PartsFile, configPath: string, overrides?: AssemblyRules): ReadingContext {
370
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, overrides);
371
+ const ground = project === 'visible' ? cfg.assemble.ground ?? DEFAULT_GROUND : DEFAULT_GROUND;
372
+ const base = dirname(resolve(configPath));
373
+ const files = digestFiles(base);
374
+ const { file } = files;
104
375
  const requirementsPath = ground === 'busy' && cfg.requirements !== undefined
105
376
  ? resolve(base, cfg.requirements) : undefined;
106
377
  const setup = requirementsPath === undefined ? undefined : readRequirements(requirementsPath).setup_painting;
@@ -109,7 +380,6 @@ export function readAssemblyConfig(
109
380
  ...declaration,
110
381
  path: sha256(fileBytes(setupPaintingFilePath(requirementsPath!, declaration.path), `requirements.setup_painting.${field}.path`)),
111
382
  };
112
- const edited = cfg.assemble.edited_parts;
113
383
  const names = [...new Set([
114
384
  ...parts.parts.map(part => part.name),
115
385
  ...(parts.alternates ?? []).flatMap(set => set.records.map(part => part.name)),
@@ -120,7 +390,6 @@ export function readAssemblyConfig(
120
390
  const basePairs = movingPairs({ ...cfg, constraints: undefined }, names);
121
391
  const baseSet = new Set(basePairs.map(pair => JSON.stringify(pair)));
122
392
  const physicsPairs = movingPairs(cfg, names).filter(pair => !baseSet.has(JSON.stringify(pair)));
123
- const { resolution, head_box, arm_split } = cfg.seethrough ?? {};
124
393
  const hasHeadRun = Object.keys(parts.ghost_px).some(name => name.startsWith('head:'));
125
394
  const frontParts = new Set((cfg.assemble.alternates ?? []).flatMap(set => set.front ?? []));
126
395
  const bands = [
@@ -152,84 +421,30 @@ export function readAssemblyConfig(
152
421
  .filter(([name]) => limbBones.has(name) || alternateBones.has(name));
153
422
  // Alternate skeleton and drawn registration also use the hierarchy.
154
423
  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,
424
+ return {
425
+ ...files, seam, project, ground, setup, setupImage, hasHeadRun,
426
+ basePairs, physicsPairs, bones, limbs, hybridWidths,
427
+ authoredDepths: () => cfg.depth === undefined ? undefined
428
+ : [...authoredUnitDepths(cfg)].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
231
429
  };
232
- const fields = Object.entries(inputs).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
430
+ }
431
+
432
+ /** Config values consumed by assembly, evaluated against the assembled names and run shape. */
433
+ export function readAssemblyConfig(
434
+ cfg: AssemblySource, parts: PartsFile, configPath: string, overrides?: AssemblyRules,
435
+ ): AssemblyConfigRecord {
436
+ return readProjectedAssemblyConfig(projectAssemblyConfig(cfg), parts, configPath, overrides);
437
+ }
438
+
439
+ export function readProjectedAssemblyConfig(
440
+ projection: AssemblyProjection, parts: PartsFile, configPath: string, overrides?: AssemblyRules,
441
+ ): AssemblyConfigRecord {
442
+ const ctx = readingContext(projection.config, parts, configPath, overrides);
443
+ const inputs: Array<[string, unknown]> = projection.legacyFields.map(([key, value]) => [`assemble.${key}`, value]);
444
+ for (const [path, entry] of Object.entries(projection.rows)) {
445
+ for (const [name, read] of Object.entries(entry.bindings ?? {})) inputs.push([bindingName(path, name), read(ctx)]);
446
+ }
447
+ const fields = inputs.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
233
448
  .flatMap(([name, value]) => value === undefined ? [] : [{ name, sha256: sha256(JSON.stringify(canonical(value))) }]);
234
449
  return { sha256: assemblyFieldDigest(fields), fields };
235
450
  }
@@ -238,6 +453,10 @@ export function assemblyFieldDigest(fields: AssemblyConfigRecord['fields']): str
238
453
  return sha256(JSON.stringify(fields.map(({ name, sha256 }) => [name, sha256])));
239
454
  }
240
455
 
456
+ export function isSplitTakeMetadataField(name: string): boolean {
457
+ return /^assemble\.take\[(?:0|[1-9][0-9]*)\]\.meta$/.test(name);
458
+ }
459
+
241
460
  export function assemblyConfigReading(configPath: string, parts: PartsFile): AssemblyConfigRecord {
242
461
  return readAssemblyConfig(loadEarlyConfig(configPath, 'assemble'), parts, configPath);
243
462
  }
@@ -259,9 +478,16 @@ export function assemblyChangeDetail(changes: readonly string[]): string {
259
478
  }
260
479
 
261
480
  export function refuseStaleAssembly(configPath: string, parts: PartsFile, loaded?: AssemblySource, overrides?: AssemblyRules): void {
262
- if (parts.assembly_config === undefined) return;
481
+ const previous = parts.assembly_config;
482
+ if (previous === undefined) return;
263
483
  const cfg = loaded ?? loadEarlyConfig(configPath, 'assemble', overrides?.project);
264
484
  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) }]);
485
+ const changes = changedAssemblyFields(previous, current);
486
+ if (changes.length === 0) return;
487
+ const recorded = new Set(previous.fields.map(({ name }) => name));
488
+ const predatesSplitMetadata = changes.every(name => isSplitTakeMetadataField(name) && !recorded.has(name));
489
+ const detail = predatesSplitMetadata
490
+ ? `assembly reading changed at ${changes.map(name => `config.${name}`).join(', ')}; the recorded stamp predates split-take donor metadata binding. Re-run assemble once with the same config`
491
+ : assemblyChangeDetail(changes);
492
+ throw new PartsError([{ code: 'ASSEMBLY_CONFIG_STALE', object: configPath, detail }]);
267
493
  }
@@ -1,5 +1,5 @@
1
1
  /** Fully explicit unit consumers may omit their unused scalar transport (#877). */
2
- import type { MeshSpec, Motion, RegionSpec, TurnSpec } from './config.ts';
2
+ import type { BlinkStill, MeshSpec, RegionSpec, TurnSpec } from './config.ts';
3
3
  import { turnUnitBone } from './turn.ts';
4
4
 
5
5
  export interface AuthoredUnitDepth {
@@ -12,7 +12,7 @@ export function authoredUnitDepths(cfg: {
12
12
  turn?: TurnSpec;
13
13
  regions?: Record<string, RegionSpec>;
14
14
  meshes?: Record<string, MeshSpec>;
15
- motion?: Pick<Motion, 'blink'>;
15
+ motion?: { blink?: { still?: Record<string, Pick<BlinkStill, 'bone'>> } };
16
16
  }): ReadonlyMap<string, AuthoredUnitDepth> {
17
17
  const out = new Map<string, AuthoredUnitDepth>();
18
18
  const turn = cfg.turn;
package/src/build.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { changedAssemblyFields, effectiveAssemblyRules, readAssemblyConfig, refuseStaleAssembly, type AssemblyRules } from './assembly-reading.ts';
1
+ import { changedAssemblyFields, effectiveAssemblyRules, projectAssemblyConfig, readProjectedAssemblyConfig, type AssemblyLimb, refuseStaleAssembly, type AssemblyRules } from './assembly-reading.ts';
2
2
  import { editedPartFrontColourLines, readEditedParts } from './editedparts.ts';
3
3
  import { SOURCE_COVER_FILE, sourceCoverReport, type SourceCoverSet } from './sourcecover.ts';
4
4
  import { STAGE_MAP_FILE } from './provenance.ts';
@@ -70,7 +70,7 @@ import { createHash } from 'node:crypto';
70
70
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
71
71
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
72
72
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
73
- import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, ERROR_LIMIT, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figureMaskLines, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
73
+ import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, ERROR_LIMIT, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figureMaskLines, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, projectedStageFields, stageFields, uncoveredLine, underBox } from './assemble.ts';
74
74
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
75
75
  import { residualClause } from './autoenvelope.ts';
76
76
  import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, prepareComparison, type ReplayCandidate, runComparison, runPreparedComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
@@ -98,7 +98,7 @@ import {
98
98
  untestedIntervals,
99
99
  } from './autoreplay.ts';
100
100
  import { besideIdleLine, checkSummaryLine, inputFileRecord, type InputFileRecord, CLOTH_LINE, type ClothLine, clothWarnText, figureOpeningLines, frameRuns, MOTION_SEAM_LINE, type MotionSeamLine, type MotionSeamPlant, motionSeamRequiredLine, motionSeamWarnText, motionJointContactLines, FOLD_LINE, type FoldsLine, LEVEL_LINE, type LevelLine, LIMB_LINE, type LimbLine, STRESS_LINE, SWEEP_LINE, type SweepLine, buildGateLines, causeLines, environmentLine, IDLE_FPS, IDLE_MAX_PX, maxRgbDiff, REQUIREMENTS_DIR, type CheckReport, type PackLine, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, GATE_PROFILE, JUDGEMENT_LINES, type JudgementLine, packedBuildArgs, packedBuildLabel, type PackMode, parsePageSize, readCheckEnvironment, readWindBand, type PackShape, type PageEdges, readFrameSet, rigcFailed, rigcIdentity, rigcRanClause, REPORTED_LINES, type ReportedLine, type RigcRunner, runCheck, SEAM_DIR, SEAM_MEAN_BAR, seamPairText, seamRigPxText, SOURCE_LINE, SEAM_PX_BAR, SEAM_PX_LEVEL, SEAM_PX_LEVEL_HIGH, SPINEBOY_YARDSTICK, STILL_DIR, WIND_BAND_LINE, windBandLines } from './check.ts';
101
- import { type CharacterConfig, type Cut, type Extend, type Limb, loadConfigAndAnimations, loadConfigWithBytes, loadEarlyConfig, type Patch, type PlanEntry } from './config.ts';
101
+ import { type CharacterConfig, type Cut, type Extend, loadConfigAndAnimations, loadConfigWithBytes, loadEarlyConfig, type Patch, type PlanEntry } from './config.ts';
102
102
  import { coreCompileGuideLine, failLine, foldName, PartsError, type Problem, refuseIfAny } from './errors.ts';
103
103
  import { editedConfigImages, editedRunImages, missingReceipts, readEditorReceipts } from './editreceipt.ts';
104
104
  import { untracedPartSources } from './partsource.ts';
@@ -237,6 +237,7 @@ export interface AssembleOutputs {
237
237
 
238
238
  /** The error map's file name beside a recomposite: `recomposite_rig.png` -> `recomposite_error_rig.png`. */
239
239
  export const ERROR_MAP_FILE = 'recomposite_error_rig.png';
240
+ const ASSEMBLE_YIELD_NOTHING = 'ASSEMBLE_YIELD_NOTHING';
240
241
 
241
242
  /**
242
243
  * One line per part whose fringe `pushBackFringe` cleared (issue #119), in
@@ -439,7 +440,7 @@ export function emitFillMasksStage(input: EmitFillMasksInput, log: Log): Array<{
439
440
  * (`ASSEMBLE_LIMB_CAP_PRESENT`), or a file that does not decode as a PNG
440
441
  * (`ASSEMBLE_LIMB_CAP_DECODES`). The stage holds the image to the cap's box.
441
442
  */
442
- export function readCaps(configPath: string, limbs: Readonly<Record<string, Limb>>): Map<string, Raster> {
443
+ export function readCaps(configPath: string, limbs: Readonly<Record<string, AssemblyLimb>>): Map<string, Raster> {
443
444
  const problems: Problem[] = [];
444
445
  const out = new Map<string, Raster>();
445
446
  for (const [l, limb] of Object.entries(limbs)) {
@@ -503,13 +504,17 @@ function sourceCoverSet(result: AssembleResult, set: string | null, painting: st
503
504
 
504
505
  /** Read, assemble, and write only after every refusal has had its chance. Throws a PartsError on a refusal, having written nothing. */
505
506
  export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs, log: Log): AssembleResult {
507
+ // Flag-only figure masks and the region-take tolerance are effective
508
+ // inputs outside the legacy config reading.
506
509
  const requirementsFile = input.requirements === undefined ? null : readRequirements(input.requirements);
507
510
  const materialAsked = requirementsFile?.cut_material !== undefined;
508
511
  // Issue #944: the pinhole bar is measured only when the requirements file declares it required.
509
512
  const pinholesAsked = requirementsFile !== null && pinholesRequired(requirementsFile);
510
513
  // The early door: assemble runs before propose has drafted bones, meshes,
511
514
  // regions and motion, so it requires only what it reads (issue #20).
512
- const cfg = loadEarlyConfig(input.config, 'assemble', input.project);
515
+ const projection = projectAssemblyConfig(loadEarlyConfig(input.config, 'assemble', input.project));
516
+ // The assemble loader requires seethrough before projection.
517
+ const cfg = { ...projection.config, seethrough: projection.config.seethrough! };
513
518
  const supportDeclarations = JSON.stringify(cfg.assemble.cuts ?? []);
514
519
  const { seam, project } = effectiveAssemblyRules(cfg.assemble, input);
515
520
  const requirements = cfg.assemble.ground === 'busy' && project === 'visible'
@@ -524,7 +529,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
524
529
  const takenRuns = applyTakenLayers(read, src, cfg, input.config);
525
530
  const runs = applyTakenRegions(takenRuns, src, cfg, input.config, requirementsFile?.setup_painting, receipts, input.source);
526
531
  for (const note of runs.notes) log(note.startsWith('WARN ') ? note : `note: ${note}`);
527
- const fields = stageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
532
+ const fields = projectedStageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
528
533
  const setupPainting = requirements === null || fields.ground !== 'busy' || project !== 'visible' ? undefined
529
534
  : readRequirements(requirements.read).setup_painting;
530
535
  const figureSupport = setupPainting === undefined ? undefined
@@ -607,6 +612,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
607
612
  });
608
613
  }
609
614
 
615
+ const scopedYield = typeof fields.yieldRefused === 'object' ? fields.yieldRefused : [];
616
+ const yieldedParts = new Set(result.yieldReadings?.filter(row => row.yielded > 0).map(row => row.part));
610
617
  const altProblems: Problem[] = [];
611
618
  const allocationReports: Array<{ file: string; report: { set: string; coverageTransfers: PaintingAllocationReading['coverageTransfers'] } & Record<string, unknown> }> = [];
612
619
  const altBuilt: Array<{ record: AlternatePartsRecord; images: Array<{ name: string; image: Raster }>; excluded: ExcludedCount[]; islands: IslandCount[]; splits: SplitCount[]; capSplits: SplitCount[]; depthClamps: AssembleResult['depthClamps'] }> = [];
@@ -713,7 +720,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
713
720
  for (const sg of limb.segments) if (sg.hybrid !== undefined) { coveredSet.add(sg.hybrid.part); generatedBands.push(sg.hybrid.part); }
714
721
  }
715
722
  let rawCuts = alt.cuts !== undefined ? alt.cuts : fields.cuts.filter((c) => coveredSet.has(c.into) && coveredSet.has(c.from)).map((c) => ({ ...c, under: undefined }));
716
- let altLimbs: Record<string, Limb> = {};
723
+ let altLimbs: Record<string, AssemblyLimb> = {};
717
724
  if (fields.limbs !== undefined) {
718
725
  for (const [ln, limb] of Object.entries(fields.limbs)) {
719
726
  if (limb.segments.every((sg) => coveredSet.has(sg.part))) {
@@ -780,7 +787,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
780
787
  const originalIslands = alt.parts === undefined || input.setIslands === 'all' ? [] : setIslandSources(fields.limbs ?? {}, originalAltLimbs);
781
788
  const altIslands = alternateLayerIslands(originalIslands, selectedLayers.groups);
782
789
  // Issue #609: the limbs of those layers the set does not carry — the other leg of a two-leg layer.
783
- const otherLimbs: Record<string, Limb> =
790
+ const otherLimbs: Record<string, AssemblyLimb> =
784
791
  input.setSplit === 'connectivity'
785
792
  ? {}
786
793
  : Object.fromEntries(Object.entries(fields.limbs ?? {}).filter(([ln, l]) => !(ln in altLimbs) && l.segments.some((sg) => originalIslands.includes(sg.from))));
@@ -935,6 +942,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
935
942
  }
936
943
  throw err;
937
944
  }
945
+ for (const row of altRes.yieldReadings ?? []) if (row.yielded > 0) yieldedParts.add(row.part);
938
946
  const altMaskProblems = verifyUnderPlateMasks(altRes, altCuts, altUnderPlates, `${alt.at}.cuts`);
939
947
  if (altMaskProblems.length > 0) {
940
948
  altProblems.push(...altMaskProblems);
@@ -1069,7 +1077,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1069
1077
  result.parts.alternates = altBuilt.map((b) => b.record);
1070
1078
  }
1071
1079
 
1072
- const reading = readAssemblyConfig(cfg, result.parts, input.config, { seam, project });
1080
+ const reading = readProjectedAssemblyConfig(projection, result.parts, input.config, { seam, project });
1073
1081
  let previousAssembly = undefined;
1074
1082
  if (existsSync(outs.partsJson)) {
1075
1083
  try { previousAssembly = readPartsManifest(outs.partsJson).assembly_config; }
@@ -1224,6 +1232,9 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1224
1232
  if (result.figureMask !== undefined) for (const l of figureMaskLines(result.figureMask, scene)) log(l);
1225
1233
  log(pinholesLine(pinholes, altBuilt.map((b) => b.record.name)));
1226
1234
  for (const d of result.drift) log(driftLine(d));
1235
+ for (const part of scopedYield) {
1236
+ if (!yieldedParts.has(part)) log(`${ASSEMBLE_YIELD_NOTHING}: part ${JSON.stringify(part)} — no eligible projection refusal to yield in the base or alternate sets`);
1237
+ }
1227
1238
  for (const d of result.softOcclusion ?? []) log(softOcclusionLine(d));
1228
1239
  for (const line of result.cropClipped ?? []) log(line);
1229
1240
  // Issue #588: per subset set, one line per limb part cut from a layer of more than one island, then (issue #587) one
@@ -1242,7 +1253,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1242
1253
  * base parts at alpha above `OPAQUE_ALPHA_ABOVE`, at their `parts.json` x, y.
1243
1254
  */
1244
1255
  function otherLimbsOf(
1245
- limbs: Readonly<Record<string, Limb>>,
1256
+ limbs: Readonly<Record<string, AssemblyLimb>>,
1246
1257
  setPlaced: ReadonlySet<string>,
1247
1258
  bones: readonly BoneEntry[],
1248
1259
  base: ReadonlyArray<{ record: PartRecord; image: Raster }>,