@rig-c/parts 2.41.0 → 2.43.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/README.md +1 -0
- package/cli.ts +76 -20
- package/docs/AUTHORING.md +366 -53
- package/docs/DEPTH.md +8 -0
- package/docs/STABILITY.md +158 -10
- package/package.json +4 -2
- package/src/behindseams.ts +875 -0
- package/src/build.ts +76 -9
- package/src/check.ts +170 -18
- package/src/checkrow.ts +29 -0
- package/src/configrelocation.ts +25 -0
- package/src/configwrite.ts +20 -2
- package/src/depthworkflow.ts +3 -4
- package/src/meshdraft.ts +10 -10
- package/src/remesh.ts +18 -12
- package/src/requirements.ts +30 -4
- package/src/retune.ts +8 -5
- package/src/runstamp.ts +54 -1
- package/src/turn.ts +5 -0
- package/tools/configwrite.ts +83 -1
- package/tools/edited-part-cli.ts +61 -0
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
|
+
import type { Plate } from '@rig-c/core/plate';
|
|
5
|
+
import type { AttachmentRest, Frame } from '@rig-c/core/render-shared';
|
|
6
|
+
import { seamGridOf, seamsOf, setupCellReader, type SeamCell, type SeamGrid } from '@rig-c/core/seam';
|
|
7
|
+
import { DRAWN_ALPHA } from '@rig-c/core/passthrough';
|
|
8
|
+
import { checkRow } from './checkrow.ts';
|
|
9
|
+
import { seamSourceAttachment, type MotionSeamPair } from './check.ts';
|
|
10
|
+
import type { Problem } from './errors.ts';
|
|
11
|
+
import { BODY_TURN_ANIM, BODY_YAW_DIAL_BONE, PITCH_DIAL_BONE, TURN_BONE, YAW_DIAL_BONE } from './turn.ts';
|
|
12
|
+
|
|
13
|
+
export const BEHIND_SEAM_LINE = 'BEHIND_PART_SEAMS';
|
|
14
|
+
export const UNDECLARED_BEHIND_SEAM_REASON = 'HOLE: no requirements.behind_seams declares an authored threshold T; not measured, never a pass';
|
|
15
|
+
export const BEHIND_SEAM_CODE = 'CHECK_BEHIND_PART_SEAMS';
|
|
16
|
+
export const BEHIND_SEAM_UNMEASURED_CODE = 'CHECK_BEHIND_PART_SEAMS_UNMEASURED';
|
|
17
|
+
|
|
18
|
+
export interface BehindSeams {
|
|
19
|
+
/** Opt in to the rig's declared ranges; never supplies or guesses a range. */
|
|
20
|
+
turn?: true;
|
|
21
|
+
threshold?: number;
|
|
22
|
+
allowance?: number;
|
|
23
|
+
pairs?: Array<{ part: string; neighbour: string; threshold?: number; allowance?: number }>;
|
|
24
|
+
}
|
|
25
|
+
export type BehindSeamsApi = Pick<typeof import('@rig-c/core/render-shared'), 'projector' | 'pageFor' | 'rasterisePiece' | 'renderFrame'>;
|
|
26
|
+
export interface BehindSeamsStockPair {
|
|
27
|
+
pair: string;
|
|
28
|
+
frames: number;
|
|
29
|
+
drawn: number;
|
|
30
|
+
banded: number;
|
|
31
|
+
gapCovered: Array<{ index: number; time: number; cell: number; cells: readonly SeamCell[] }>;
|
|
32
|
+
}
|
|
33
|
+
export interface BehindSeamsFramesInput {
|
|
34
|
+
pairs: readonly MotionSeamPair[];
|
|
35
|
+
setup: Frame | null;
|
|
36
|
+
idle: readonly Frame[];
|
|
37
|
+
rest: readonly AttachmentRest[];
|
|
38
|
+
pages: Map<string, Plate>;
|
|
39
|
+
stock: readonly BehindSeamsStockPair[] | null;
|
|
40
|
+
fps: number;
|
|
41
|
+
turn?: BehindSeamsTurnInput;
|
|
42
|
+
}
|
|
43
|
+
export interface BehindSeamsTurnPose {
|
|
44
|
+
name: string;
|
|
45
|
+
values: Record<string, number>;
|
|
46
|
+
observed_values?: Record<string, number>;
|
|
47
|
+
slider_times?: Record<string, number>;
|
|
48
|
+
}
|
|
49
|
+
export interface BehindSeamsTurnInput {
|
|
50
|
+
poses: BehindSeamsTurnPose[];
|
|
51
|
+
frames: Array<Frame | null>;
|
|
52
|
+
setup: Frame | null;
|
|
53
|
+
rest: readonly AttachmentRest[];
|
|
54
|
+
stock: readonly BehindSeamsStockPair[] | null;
|
|
55
|
+
reason?: string;
|
|
56
|
+
sourceSkeletonSha256?: string;
|
|
57
|
+
poser?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface BehindSeamsTurnPair {
|
|
60
|
+
pair: string;
|
|
61
|
+
parts: [string, string];
|
|
62
|
+
threshold: number | null;
|
|
63
|
+
allowance: number;
|
|
64
|
+
frames: BehindSeamsFrame[];
|
|
65
|
+
sampled_poses: number;
|
|
66
|
+
read_poses: number;
|
|
67
|
+
unmeasured_poses: number;
|
|
68
|
+
motion_opened: { status: BehindSeamsCount['status']; max_px: number };
|
|
69
|
+
standing: { status: BehindSeamsCount['status']; max_px: number };
|
|
70
|
+
}
|
|
71
|
+
export interface BehindSeamsTurnMeasured {
|
|
72
|
+
status: BehindSeamsCount['status'];
|
|
73
|
+
poses: string[];
|
|
74
|
+
pairs: BehindSeamsTurnPair[];
|
|
75
|
+
unmeasured: BehindSeamsMeasured['unmeasured'];
|
|
76
|
+
limitations: string;
|
|
77
|
+
}
|
|
78
|
+
export interface BehindSeamsSample {
|
|
79
|
+
x: number;
|
|
80
|
+
y: number;
|
|
81
|
+
rear_rgb: [number, number, number];
|
|
82
|
+
rear_weight: number;
|
|
83
|
+
contributors: Array<{ slot: string; weight: number }>;
|
|
84
|
+
distances: [number, number] | null;
|
|
85
|
+
counted: boolean;
|
|
86
|
+
}
|
|
87
|
+
export interface BehindSeamsCount {
|
|
88
|
+
status: 'PASS' | 'FAIL' | 'SKIP';
|
|
89
|
+
boundary_cells: number;
|
|
90
|
+
geometric_px: number;
|
|
91
|
+
raw_px: number;
|
|
92
|
+
px: number;
|
|
93
|
+
box: [number, number, number, number] | null;
|
|
94
|
+
max_spatial_run_cells: number;
|
|
95
|
+
samples: BehindSeamsSample[];
|
|
96
|
+
}
|
|
97
|
+
export type BehindSeamsEndpoint = [grid_x: number, grid_y: number, world_x: number, world_y: number, owner: number];
|
|
98
|
+
export interface BehindSeamsUnreadCorridor {
|
|
99
|
+
axis: 'horizontal' | 'vertical';
|
|
100
|
+
/** Spatial order: left/right on a row, top/bottom on a column; owners are not inferred. */
|
|
101
|
+
endpoints: [BehindSeamsEndpoint, BehindSeamsEndpoint];
|
|
102
|
+
cells: Array<[number, number]>;
|
|
103
|
+
cell_count: number;
|
|
104
|
+
}
|
|
105
|
+
export interface BehindSeamsStanding extends BehindSeamsCount {
|
|
106
|
+
/** Distinct grid cells across all unread corridors, including cross-axis intersections. */
|
|
107
|
+
unread_cells?: number;
|
|
108
|
+
/** Omitted, together with unread_cells, when every corridor's endpoints are readable. */
|
|
109
|
+
unread_corridors?: BehindSeamsUnreadCorridor[];
|
|
110
|
+
}
|
|
111
|
+
export interface BehindSeamsFrame {
|
|
112
|
+
animation: 'idle' | 'turn' | null;
|
|
113
|
+
pose?: string;
|
|
114
|
+
values?: Record<string, number>;
|
|
115
|
+
observed_values?: Record<string, number>;
|
|
116
|
+
slider_times?: Record<string, number>;
|
|
117
|
+
index: number;
|
|
118
|
+
time: number;
|
|
119
|
+
behind_slots: string[];
|
|
120
|
+
grid: SeamGrid | null;
|
|
121
|
+
motion_opened: BehindSeamsCount;
|
|
122
|
+
standing: BehindSeamsStanding;
|
|
123
|
+
}
|
|
124
|
+
export interface BehindSeamsHit {
|
|
125
|
+
index: number;
|
|
126
|
+
time: number;
|
|
127
|
+
px: number;
|
|
128
|
+
cell: number;
|
|
129
|
+
area: number;
|
|
130
|
+
box: [number, number, number, number];
|
|
131
|
+
}
|
|
132
|
+
export interface BehindSeamsReading {
|
|
133
|
+
status: 'PASS' | 'FAIL' | 'SKIP';
|
|
134
|
+
frames: BehindSeamsHit[];
|
|
135
|
+
hit_frames: number;
|
|
136
|
+
max_px: number;
|
|
137
|
+
worst: BehindSeamsHit | null;
|
|
138
|
+
spans: Array<{ first: number; last: number; frames: number; seconds: number }>;
|
|
139
|
+
max_run: { frames: number; seconds: number };
|
|
140
|
+
max_spatial_run_cells: number;
|
|
141
|
+
max_spatial_run_world: number;
|
|
142
|
+
}
|
|
143
|
+
export interface BehindSeamsPair {
|
|
144
|
+
animation: 'idle';
|
|
145
|
+
pair: string;
|
|
146
|
+
parts: [string, string];
|
|
147
|
+
declared: string[];
|
|
148
|
+
threshold: number | null;
|
|
149
|
+
allowance: number;
|
|
150
|
+
setup: BehindSeamsFrame | null;
|
|
151
|
+
frames: BehindSeamsFrame[];
|
|
152
|
+
motion_opened: BehindSeamsReading;
|
|
153
|
+
standing: BehindSeamsReading;
|
|
154
|
+
/** Idle counts only; a read frame has both halves available, even when failing. */
|
|
155
|
+
sampled_frames?: number;
|
|
156
|
+
read_frames?: number;
|
|
157
|
+
unmeasured_frames?: number;
|
|
158
|
+
}
|
|
159
|
+
export interface BehindSeamsMeasured {
|
|
160
|
+
status: 'PASS' | 'FAIL' | 'SKIP';
|
|
161
|
+
fps: number;
|
|
162
|
+
pairs: BehindSeamsPair[];
|
|
163
|
+
unmeasured: Array<{ pair: string | null; frame: string; reason: string }>;
|
|
164
|
+
limitations: string;
|
|
165
|
+
turn?: BehindSeamsTurnMeasured;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The orchestration input: only an already gated build and its full stock seam
|
|
169
|
+
* render. Unsupported active worlds/sets must be named, never silently defaulted. */
|
|
170
|
+
export interface BehindSeamsInput {
|
|
171
|
+
build: string;
|
|
172
|
+
rig: Record<string, unknown>;
|
|
173
|
+
pairs: readonly MotionSeamPair[];
|
|
174
|
+
stockDir: string | null;
|
|
175
|
+
fps: number;
|
|
176
|
+
unsupported?: string;
|
|
177
|
+
turnBuild?: { build?: string; reason?: string };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const LIMITATIONS = 'setup and every idle frame; motion uses transported setup-overlap support; standing certifies horizontal and vertical bracketed runs, not all curved or diagonal openings; rear-set attribution is not individual-slot blame; other animations and alternate skins are not measured';
|
|
181
|
+
const record = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
182
|
+
const freeKey = (k: string, v: unknown): boolean => (k.startsWith('x-') && k.length > 2 && record(v)) || ((k === 'note' || k.endsWith('_note')) && typeof v === 'string');
|
|
183
|
+
const keyOf = (a: string, b: string): string => JSON.stringify(a < b ? [a, b] : [b, a]);
|
|
184
|
+
|
|
185
|
+
/** Shape only. Missing T is a valid undeclared reading, never an invented default. */
|
|
186
|
+
export function behindSeamsProblems(value: unknown, at: string): Problem[] {
|
|
187
|
+
const problems: Problem[] = [];
|
|
188
|
+
const bad = (object: string, detail: string): void => { problems.push({ code: 'REQUIREMENTS_FIELD', object, detail }); };
|
|
189
|
+
const block = (v: unknown, where: string, pair: boolean): void => {
|
|
190
|
+
if (!record(v)) { bad(where, `is ${JSON.stringify(v)}; requires a behind_seams record with an authored threshold and optional allowance/pair overrides`); return; }
|
|
191
|
+
for (const k of Object.keys(v)) if (!(pair ? ['part', 'neighbour', 'threshold', 'allowance'] : ['threshold', 'allowance', 'pairs', 'turn']).includes(k) && !freeKey(k, v[k])) bad(`${where}.${k}`, 'is not a field this block reads (threshold, allowance, pairs, turn; pair entries name part and neighbour; note or *_note as a string; x-<name> as a record)');
|
|
192
|
+
if (!pair && 'turn' in v && v.turn !== true) bad(`${where}.turn`, 'requires true to read the rig\'s declared turn range endpoints and corners; omit to retain setup/idle only; no ranges are supplied here');
|
|
193
|
+
if ('threshold' in v && (typeof v.threshold !== 'number' || !Number.isInteger(v.threshold) || v.threshold < 0 || v.threshold > 255)) bad(`${where}.threshold`, `is ${JSON.stringify(v.threshold)}; requires an authored integer from 0 through 255; no threshold is derived from the art`);
|
|
194
|
+
if ('allowance' in v && (typeof v.allowance !== 'number' || !Number.isSafeInteger(v.allowance) || v.allowance < 0)) bad(`${where}.allowance`, `is ${JSON.stringify(v.allowance)}; requires a nonnegative safe integer count of seam cells`);
|
|
195
|
+
if (pair) {
|
|
196
|
+
for (const name of ['part', 'neighbour']) if (typeof v[name] !== 'string' || (v[name] as string).trim().length === 0) bad(`${where}.${name}`, 'requires a nonempty named member of a selected motion seam pair');
|
|
197
|
+
if (typeof v.part === 'string' && v.part === v.neighbour) bad(where, `names the same part ${JSON.stringify(v.part)} twice; two different members are required`);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
block(value, at, false);
|
|
201
|
+
if (record(value) && 'pairs' in value) {
|
|
202
|
+
if (!Array.isArray(value.pairs)) bad(`${at}.pairs`, 'requires an array of {part, neighbour, threshold?, allowance?} overrides');
|
|
203
|
+
else {
|
|
204
|
+
const seen = new Set<string>();
|
|
205
|
+
value.pairs.forEach((p, i) => {
|
|
206
|
+
block(p, `${at}.pairs[${i}]`, true);
|
|
207
|
+
if (record(p) && typeof p.part === 'string' && typeof p.neighbour === 'string') {
|
|
208
|
+
const key = keyOf(p.part, p.neighbour);
|
|
209
|
+
if (seen.has(key)) bad(`${at}.pairs[${i}]`, `duplicates pair ${JSON.stringify(p.part + '|' + p.neighbour)}; reversed members name the same pair`);
|
|
210
|
+
seen.add(key);
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return problems;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const emptyCount = (status: BehindSeamsCount['status'] = 'SKIP'): BehindSeamsCount => ({ status, boundary_cells: 0, geometric_px: 0, raw_px: 0, px: 0, box: null, max_spatial_run_cells: 0, samples: [] });
|
|
219
|
+
type RGB = [number, number, number];
|
|
220
|
+
interface Material { alpha: Float64Array; base: Float64Array; delta: Float64Array }
|
|
221
|
+
const material = (n: number): Material => ({ alpha: new Float64Array(n), base: new Float64Array(n * 3), delta: new Float64Array(n * 3) });
|
|
222
|
+
|
|
223
|
+
/** The official callback supplies straight RGB, after tint, before composite byte rounding.
|
|
224
|
+
* Accumulate deviations from the first colour: a constant colour has exactly zero
|
|
225
|
+
* deviation at every alpha, including T=0. There is no epsilon or unpremultiplication
|
|
226
|
+
* of the callback's already straight colour. */
|
|
227
|
+
function add(m: Material, k: number, rgb: RGB, a: number): void {
|
|
228
|
+
if (m.alpha[k] === 0) for (let c = 0; c < 3; c++) { m.base[3 * k + c] = rgb[c]; m.delta[3 * k + c] = 0; }
|
|
229
|
+
for (let c = 0; c < 3; c++) m.delta[3 * k + c] = m.delta[3 * k + c] * (1 - a) + (rgb[c] - m.base[3 * k + c]) * a;
|
|
230
|
+
m.alpha[k] = a + m.alpha[k] * (1 - a);
|
|
231
|
+
}
|
|
232
|
+
function colour(m: Material, k: number): RGB {
|
|
233
|
+
return [0, 1, 2].map(c => m.base[k * 3 + c] + m.delta[k * 3 + c] / m.alpha[k]) as RGB;
|
|
234
|
+
}
|
|
235
|
+
function distance(m: Material, k: number, to: RGB): number {
|
|
236
|
+
return Math.max(...[0, 1, 2].map(c => Math.abs((m.base[k * 3 + c] - to[c]) + m.delta[k * 3 + c] / m.alpha[k])));
|
|
237
|
+
}
|
|
238
|
+
function spatialRun(mask: ReadonlySet<number>, width: number, height: number): number {
|
|
239
|
+
let longest = 0;
|
|
240
|
+
for (const [length, lines, step, start] of [[width, height, 1, width], [height, width, width, 1]]) for (let l = 0; l < lines; l++) {
|
|
241
|
+
let run = 0;
|
|
242
|
+
for (let j = 0; j < length; j++) { run = mask.has(l * start + j * step) ? run + 1 : 0; longest = Math.max(longest, run); }
|
|
243
|
+
}
|
|
244
|
+
return longest;
|
|
245
|
+
}
|
|
246
|
+
function centre(grid: SeamGrid, k: number): [number, number] {
|
|
247
|
+
return [grid.viewport.minX + (k % grid.viewport.width + 0.5) * grid.cell, grid.viewport.maxY - (Math.floor(k / grid.viewport.width) + 0.5) * grid.cell];
|
|
248
|
+
}
|
|
249
|
+
function counted(count: BehindSeamsCount, cells: ReadonlySet<number>, grid: SeamGrid, allowance: number): void {
|
|
250
|
+
count.px = cells.size;
|
|
251
|
+
count.status = cells.size > allowance ? 'FAIL' : 'PASS';
|
|
252
|
+
count.max_spatial_run_cells = spatialRun(cells, grid.viewport.width, grid.viewport.height);
|
|
253
|
+
for (const k of cells) {
|
|
254
|
+
const [x, y] = centre(grid, k), d = grid.cell / 2;
|
|
255
|
+
if (count.box === null) count.box = [x - d, y - d, x + d, y + d];
|
|
256
|
+
else count.box = [Math.min(count.box[0], x - d), Math.min(count.box[1], y - d), Math.max(count.box[2], x + d), Math.max(count.box[3], y + d)];
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
interface Corridor { endpoints: Array<[number, number]> }
|
|
261
|
+
interface RasterCache { full: Plate; hidden: Plate }
|
|
262
|
+
|
|
263
|
+
function readBehindFrame(api: BehindSeamsApi, input: BehindSeamsFramesInput, pair: MotionSeamPair, frame: Frame, setup: boolean,
|
|
264
|
+
stock: BehindSeamsStockPair | undefined, threshold: number, allowance: number, unread: (frame: string, reason: string) => void,
|
|
265
|
+
cache: Map<Frame, Map<string, RasterCache>>, pose?: BehindSeamsTurnPose): BehindSeamsFrame {
|
|
266
|
+
const label = pose !== undefined ? `turn ${pose.name}` : setup ? 'setup' : `idle frame ${frame.index}`;
|
|
267
|
+
const family = pose !== undefined ? 'BEHIND_PART_SEAMS.turn.pairs[].frames' : setup ? 'BEHIND_PART_SEAMS.pairs[].setup' : 'BEHIND_PART_SEAMS.pairs[].frames';
|
|
268
|
+
const row: BehindSeamsFrame = { ...checkRow(family, 'pair', false, [pair.a, pair.b]), animation: pose !== undefined ? 'turn' : setup ? null : 'idle', index: frame.index, time: frame.time, ...(pose === undefined ? {} : { pose: pose.name, values: { ...pose.values }, ...(pose.observed_values === undefined ? {} : { observed_values: pose.observed_values, slider_times: pose.slider_times }) }), behind_slots: [], grid: null, motion_opened: emptyCount(), standing: emptyCount() };
|
|
269
|
+
const fail = (reason: string): BehindSeamsFrame => { unread(label, reason); return row; };
|
|
270
|
+
if (pair.unread !== undefined) return fail(pair.unread);
|
|
271
|
+
if (frame.attachments === undefined) return fail('draw order/whole attachment geometry is unavailable');
|
|
272
|
+
const order = frame.attachments.map(p => p.slot);
|
|
273
|
+
if (new Set(order).size !== order.length || frame.pieces.some(p => !order.includes(p.slot))) return fail('drawn slots have missing or duplicate whole attachments; actual draw order cannot be read');
|
|
274
|
+
const positions = frame.pieces.map(p => order.indexOf(p.slot));
|
|
275
|
+
if (positions.some((p, i) => i > 0 && p < positions[i - 1])) return fail('fragment order disagrees with whole attachment draw order');
|
|
276
|
+
const ia = order.indexOf(pair.a), ib = order.indexOf(pair.b);
|
|
277
|
+
if (ia < 0 || ib < 0 || !frame.pieces.some(p => p.slot === pair.a) || !frame.pieces.some(p => p.slot === pair.b)) return fail('both named front slots must draw on this frame');
|
|
278
|
+
row.behind_slots = order.slice(0, Math.min(ia, ib)).filter(slot => frame.pieces.some(p => p.slot === slot));
|
|
279
|
+
if (row.behind_slots.length === 0) return fail('no eligible slot is drawn strictly behind both pair members (including every fragment)');
|
|
280
|
+
let grid: SeamGrid | null;
|
|
281
|
+
try { grid = seamGridOf({ a: pair.a, b: pair.b }, input.rest, { ...frame, attachments: frame.attachments }, input.pages); }
|
|
282
|
+
catch (e) { return fail(`native seam grid unavailable: ${e instanceof Error ? e.message : String(e)}`); }
|
|
283
|
+
if (grid === null) return fail('native seamGridOf returned no pair grid');
|
|
284
|
+
row.grid = grid;
|
|
285
|
+
const { viewport, cell } = grid, { width, height } = viewport, n = width * height;
|
|
286
|
+
const A = material(n), B = material(n), project = api.projector(viewport);
|
|
287
|
+
try {
|
|
288
|
+
for (const piece of frame.pieces) if (piece.slot === pair.a || piece.slot === pair.b) {
|
|
289
|
+
api.rasterisePiece(api.pageFor(input.pages, piece), piece, project, viewport, (x, y, r, g, b, alpha) => add(piece.slot === pair.a ? A : B, y * width + x, [r, g, b], alpha / 255));
|
|
290
|
+
}
|
|
291
|
+
const half = DRAWN_ALPHA / 255;
|
|
292
|
+
const low = (k: number): boolean => A.alpha[k] + B.alpha[k] * (1 - A.alpha[k]) < half;
|
|
293
|
+
const owner = (k: number): number => A.alpha[k] >= half ? B.alpha[k] >= half ? 3 : 1 : B.alpha[k] >= half ? 2 : 0;
|
|
294
|
+
const corridors = new Map<number, Corridor>();
|
|
295
|
+
const support = new Set<number>();
|
|
296
|
+
const unreadCells = new Set<number>(), unreadCorridors: BehindSeamsUnreadCorridor[] = [];
|
|
297
|
+
// A measured overlap is support even when the opening population is empty.
|
|
298
|
+
for (let k = 0; k < n; k++) if (owner(k) === 3) support.add(k);
|
|
299
|
+
for (const [length, lines, step, start] of [[width, height, 1, width], [height, width, width, 1]]) for (let l = 0; l < lines; l++) {
|
|
300
|
+
let j = 0;
|
|
301
|
+
while (j < length) {
|
|
302
|
+
const k = l * start + j * step;
|
|
303
|
+
if (!low(k)) {
|
|
304
|
+
if (j > 0) { const prev = k - step; if (!low(prev) && owner(prev) > 0 && owner(prev) < 3 && owner(k) > 0 && owner(k) < 3 && owner(prev) !== owner(k)) { support.add(prev); support.add(k); } }
|
|
305
|
+
j++; continue;
|
|
306
|
+
}
|
|
307
|
+
const first = j;
|
|
308
|
+
while (j < length && low(l * start + j * step)) j++;
|
|
309
|
+
if (first === 0 || j === length) continue; // outer silhouette, never a bracketed opening
|
|
310
|
+
const left = l * start + (first - 1) * step, right = l * start + j * step;
|
|
311
|
+
const a = owner(left), b = owner(right);
|
|
312
|
+
if (a === 0 || b === 0 || a === 3 || b === 3) {
|
|
313
|
+
const endpoint = (at: number, owner: number): BehindSeamsEndpoint => [at % width, Math.floor(at / width), ...centre(grid, at), owner];
|
|
314
|
+
const cells: Array<[number, number]> = [];
|
|
315
|
+
for (let t = first; t < j; t++) {
|
|
316
|
+
const at = l * start + t * step;
|
|
317
|
+
unreadCells.add(at); cells.push(centre(grid, at));
|
|
318
|
+
}
|
|
319
|
+
unreadCorridors.push({ ...checkRow('BEHIND_PART_SEAMS.unread_corridors', 'pair', false, [pair.a, pair.b]),
|
|
320
|
+
axis: step === 1 ? 'horizontal' : 'vertical', endpoints: [endpoint(left, a), endpoint(right, b)], cells, cell_count: cells.length });
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
if (a === b) continue;
|
|
324
|
+
support.add(left); support.add(right);
|
|
325
|
+
const endpoints: [number, number] = a === 1 ? [left, right] : [right, left];
|
|
326
|
+
for (let t = first; t < j; t++) {
|
|
327
|
+
const at = l * start + t * step;
|
|
328
|
+
const c = corridors.get(at) ?? { endpoints: [] };
|
|
329
|
+
c.endpoints.push(endpoints); corridors.set(at, c);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
row.standing.boundary_cells = support.size;
|
|
334
|
+
if (unreadCorridors.length > 0) {
|
|
335
|
+
row.standing.unread_cells = unreadCells.size;
|
|
336
|
+
row.standing.unread_corridors = unreadCorridors;
|
|
337
|
+
}
|
|
338
|
+
let motionReadable = setup;
|
|
339
|
+
const motionCells = new Map<number, SeamCell>();
|
|
340
|
+
if (!setup) {
|
|
341
|
+
if (stock === undefined || stock.frames !== input.idle.length || stock.drawn !== stock.frames || stock.banded !== stock.frames) unread(label, `stock transported setup-overlap support is unavailable on every ${pose === undefined ? 'idle frame' : 'named turn pose'}; motion-opened is not measured`);
|
|
342
|
+
else {
|
|
343
|
+
motionReadable = true;
|
|
344
|
+
const hits = stock.gapCovered.filter(h => h.index === frame.index);
|
|
345
|
+
if (hits.length > 1) { motionReadable = false; unread(label, 'duplicate stock gapCovered hit for this frame'); }
|
|
346
|
+
for (const hit of hits) {
|
|
347
|
+
if (hit.cell !== cell || hit.time !== frame.time) { motionReadable = false; unread(label, 'stock gapCovered grid side or sample time differs from the native posed grid'); continue; }
|
|
348
|
+
for (const c of hit.cells) {
|
|
349
|
+
const x = Math.round((c.x - viewport.minX) / cell - 0.5), y = Math.round((viewport.maxY - c.y) / cell - 0.5), k = y * width + x;
|
|
350
|
+
const actual = centre(grid, k);
|
|
351
|
+
if (x < 0 || x >= width || y < 0 || y >= height || actual[0] !== c.x || actual[1] !== c.y || motionCells.has(k)) {
|
|
352
|
+
motionReadable = false; unread(label, 'stock gapCovered cell is duplicate or not an exact native seam-grid centre'); continue;
|
|
353
|
+
}
|
|
354
|
+
motionCells.set(k, c);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
// Ordinary official full/hidden rendering, both transparent and on the SAME
|
|
360
|
+
// native seam grid. No --seam/--hide combination and no PNG nearest sampling.
|
|
361
|
+
let frameCache = cache.get(frame);
|
|
362
|
+
if (frameCache === undefined) { frameCache = new Map(); cache.set(frame, frameCache); }
|
|
363
|
+
const cacheKey = JSON.stringify([grid, row.behind_slots]);
|
|
364
|
+
let rasters = frameCache.get(cacheKey);
|
|
365
|
+
const behind = new Set(row.behind_slots);
|
|
366
|
+
if (rasters === undefined) {
|
|
367
|
+
rasters = { full: api.renderFrame(frame, input.pages, viewport, [0, 0, 0, 0]), hidden: api.renderFrame({ ...frame, pieces: frame.pieces.filter(p => !behind.has(p.slot)) }, input.pages, viewport, [0, 0, 0, 0]) };
|
|
368
|
+
frameCache.set(cacheKey, rasters);
|
|
369
|
+
}
|
|
370
|
+
const targets = new Set([...corridors.keys(), ...motionCells.keys()]);
|
|
371
|
+
const rear = material(n), weights = new Map<number, Map<string, number>>();
|
|
372
|
+
const surviving = new Set<number>(), underflow = new Set<number>();
|
|
373
|
+
for (const piece of frame.pieces) api.rasterisePiece(api.pageFor(input.pages, piece), piece, project, viewport, (x, y, r, g, b, alpha) => {
|
|
374
|
+
const k = y * width + x;
|
|
375
|
+
if (!targets.has(k)) return;
|
|
376
|
+
const a = alpha / 255, keep = 1 - a;
|
|
377
|
+
const w = weights.get(k) ?? new Map<string, number>();
|
|
378
|
+
for (const [name, weight] of w) {
|
|
379
|
+
const next = weight * keep;
|
|
380
|
+
if (weight > 0 && keep > 0 && next === 0) underflow.add(k);
|
|
381
|
+
w.set(name, next);
|
|
382
|
+
}
|
|
383
|
+
if (behind.has(piece.slot)) {
|
|
384
|
+
add(rear, k, [r, g, b], a); w.set(piece.slot, (w.get(piece.slot) ?? 0) + a); surviving.add(k);
|
|
385
|
+
} else {
|
|
386
|
+
rear.alpha[k] *= keep;
|
|
387
|
+
for (let c = 0; c < 3; c++) rear.delta[k * 3 + c] *= keep;
|
|
388
|
+
// Symbolic survival, independent of transparent output-byte rounding.
|
|
389
|
+
if (alpha === 255) surviving.delete(k);
|
|
390
|
+
}
|
|
391
|
+
weights.set(k, w);
|
|
392
|
+
});
|
|
393
|
+
const sample = (k: number, distances: [number, number] | null, counts: boolean): BehindSeamsSample => {
|
|
394
|
+
const [x, y] = centre(grid, k);
|
|
395
|
+
return { ...checkRow('BEHIND_PART_SEAMS.samples', 'pair', false, [pair.a, pair.b]), x, y, rear_rgb: colour(rear, k), rear_weight: rear.alpha[k],
|
|
396
|
+
contributors: row.behind_slots.filter(slot => (weights.get(k)?.get(slot) ?? 0) > 0).map(slot => ({ ...checkRow('BEHIND_PART_SEAMS.contributors', 'pair', false, [pair.a, pair.b]), slot, weight: weights.get(k)!.get(slot)! })), distances, counted: counts };
|
|
397
|
+
};
|
|
398
|
+
const standingHits = new Set<number>(), motionHits = new Set<number>();
|
|
399
|
+
let standingUnderflow = false;
|
|
400
|
+
for (const [k, corridor] of corridors) {
|
|
401
|
+
if (!surviving.has(k)) continue;
|
|
402
|
+
if (rear.alpha[k] <= 0 || underflow.has(k)) { unread(label, 'positive symbolic rear contribution underflowed its numeric colour weight'); standingUnderflow = true; continue; }
|
|
403
|
+
row.standing.geometric_px++;
|
|
404
|
+
let chosen: [number, number] | null = null, raw = false, qualifies = false;
|
|
405
|
+
for (const [a, b] of corridor.endpoints) {
|
|
406
|
+
const d: [number, number] = [distance(rear, k, colour(A, a)), distance(rear, k, colour(B, b))];
|
|
407
|
+
const r = d[0] > 0 && d[1] > 0, q = d[0] > threshold && d[1] > threshold;
|
|
408
|
+
if (chosen === null || q && !qualifies || r && !raw) chosen = d;
|
|
409
|
+
raw ||= r; qualifies ||= q;
|
|
410
|
+
}
|
|
411
|
+
if (raw) row.standing.raw_px++;
|
|
412
|
+
if (qualifies) standingHits.add(k);
|
|
413
|
+
row.standing.samples.push(sample(k, chosen, qualifies));
|
|
414
|
+
}
|
|
415
|
+
counted(row.standing, standingHits, grid, allowance);
|
|
416
|
+
// Incomplete coverage cannot certify PASS, but cannot hide a measured failure.
|
|
417
|
+
if (support.size === 0 || unreadCorridors.length > 0 || standingUnderflow) {
|
|
418
|
+
if (row.standing.status !== 'FAIL') row.standing.status = 'SKIP';
|
|
419
|
+
if (unreadCorridors.length > 0) unread(label, 'standing endpoints include ambiguous half-alpha owners; unread corridors are not zero');
|
|
420
|
+
else if (support.size === 0) unread(label, 'no A/B boundary support was measured (no overlap, contact or bracketed corridor)');
|
|
421
|
+
}
|
|
422
|
+
for (const k of motionCells.keys()) {
|
|
423
|
+
if (rasters.hidden.data[k * 4 + 3] !== 0 || rasters.full.data[k * 4 + 3] === 0 || !surviving.has(k)) continue;
|
|
424
|
+
// Stock gapCovered already transports the A/B setup-overlap material.
|
|
425
|
+
// setupTop/setupUnder describe the UNTRANSPORTED world centre and must
|
|
426
|
+
// never be used as a rest-visible mask after a common translation.
|
|
427
|
+
const setupAttachments = input.setup?.attachments;
|
|
428
|
+
const setupOrder = setupAttachments?.map(p => p.slot);
|
|
429
|
+
const setupFront = setupOrder === undefined ? -1 : Math.min(setupOrder.indexOf(pair.a), setupOrder.indexOf(pair.b));
|
|
430
|
+
const sameDrawings = [pair.a, pair.b].every(slot => {
|
|
431
|
+
const restDrawing = setupAttachments?.find(a => a.slot === slot), posedDrawing = frame.attachments!.find(a => a.slot === slot);
|
|
432
|
+
return restDrawing !== undefined && restDrawing.attachment === posedDrawing?.attachment && input.setup!.pieces.some(p => p.slot === slot);
|
|
433
|
+
});
|
|
434
|
+
if (!sameDrawings || setupOrder === undefined || setupFront < 0 || row.behind_slots.some(slot => setupOrder.indexOf(slot) < 0 || setupOrder.indexOf(slot) >= setupFront)) {
|
|
435
|
+
motionReadable = false; unread(label, 'stock transported setup-overlap support cannot be bound to the actually drawn setup pair strictly in front of the complete rear set'); continue;
|
|
436
|
+
}
|
|
437
|
+
if (rear.alpha[k] <= 0 || underflow.has(k)) { motionReadable = false; unread(label, 'positive symbolic rear contribution underflowed its numeric colour weight'); continue; }
|
|
438
|
+
motionHits.add(k); row.motion_opened.samples.push(sample(k, null, true));
|
|
439
|
+
}
|
|
440
|
+
row.motion_opened.boundary_cells = motionCells.size;
|
|
441
|
+
row.motion_opened.geometric_px = motionHits.size; row.motion_opened.raw_px = motionHits.size;
|
|
442
|
+
counted(row.motion_opened, motionHits, grid, allowance);
|
|
443
|
+
if (!motionReadable) row.motion_opened.status = 'SKIP';
|
|
444
|
+
return { ...row, ...checkRow(family, 'pair', row.standing.status === 'FAIL' || row.motion_opened.status === 'FAIL', [pair.a, pair.b]) };
|
|
445
|
+
} catch (e) { return fail(`official raster/source reading unavailable: ${e instanceof Error ? e.message : String(e)}`); }
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function reading(frames: readonly BehindSeamsFrame[], kind: 'motion_opened' | 'standing', fps: number, allowance: number, parts: [string, string]): BehindSeamsReading {
|
|
449
|
+
const hits: BehindSeamsHit[] = [];
|
|
450
|
+
let worst: BehindSeamsHit | null = null, spatial = 0, world = 0;
|
|
451
|
+
for (const frame of frames) {
|
|
452
|
+
const r = frame[kind];
|
|
453
|
+
if (frame.grid === null) continue;
|
|
454
|
+
spatial = Math.max(spatial, r.max_spatial_run_cells); world = Math.max(world, r.max_spatial_run_cells * frame.grid.cell);
|
|
455
|
+
if (r.px === 0 || r.box === null) continue;
|
|
456
|
+
const hit: BehindSeamsHit = { ...checkRow('BEHIND_PART_SEAMS.hits', 'pair', r.px > allowance, parts), index: frame.index, time: frame.time, px: r.px, cell: frame.grid.cell, area: r.px * frame.grid.cell ** 2, box: r.box };
|
|
457
|
+
hits.push(hit);
|
|
458
|
+
if (worst === null || hit.px > worst.px) worst = hit;
|
|
459
|
+
}
|
|
460
|
+
const spans: BehindSeamsReading['spans'] = [];
|
|
461
|
+
for (const hit of hits) {
|
|
462
|
+
const prev = spans[spans.length - 1];
|
|
463
|
+
if (prev !== undefined && hit.index === prev.last + 1) { prev.last = hit.index; prev.frames++; prev.seconds = prev.frames / fps; }
|
|
464
|
+
else spans.push({ ...checkRow('BEHIND_PART_SEAMS.spans', 'pair', false, parts), first: hit.index, last: hit.index, frames: 1, seconds: 1 / fps });
|
|
465
|
+
}
|
|
466
|
+
const maxRun = Math.max(0, ...spans.map(s => s.frames));
|
|
467
|
+
return { status: frames.some(f => f[kind].status === 'FAIL') ? 'FAIL' : frames.length === 0 || frames.some(f => f[kind].status === 'SKIP') ? 'SKIP' : 'PASS', frames: hits, hit_frames: hits.length, max_px: worst?.px ?? 0, worst, spans, max_run: { frames: maxRun, seconds: maxRun === 0 ? 0 : maxRun / fps }, max_spatial_run_cells: spatial, max_spatial_run_world: world };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Pure frame-level entry for generated controls. Production supplies the same
|
|
471
|
+
* official frames and the existing full render's stock cells; no second seamsOf. */
|
|
472
|
+
export function measureBehindSeamFrames(api: BehindSeamsApi, input: BehindSeamsFramesInput, declared: BehindSeams, problems: Problem[]): BehindSeamsMeasured {
|
|
473
|
+
const line: BehindSeamsMeasured = { status: 'SKIP', fps: input.fps, pairs: [], unmeasured: [], limitations: LIMITATIONS };
|
|
474
|
+
const cache = new Map<Frame, Map<string, RasterCache>>();
|
|
475
|
+
const selected = new Set(input.pairs.map(p => keyOf(p.a, p.b)));
|
|
476
|
+
const unread = (pair: MotionSeamPair | null, frame: string, reason: string, required: boolean): void => {
|
|
477
|
+
const entry = { ...checkRow('BEHIND_PART_SEAMS.unmeasured', pair === null ? 'rig' : 'pair', required, pair === null ? [] : [pair.a, pair.b]), pair: pair?.pair ?? null, frame, reason: `HOLE: ${reason}` };
|
|
478
|
+
if (line.unmeasured.some(u => u.pair === entry.pair && u.frame === frame && u.reason === entry.reason)) return;
|
|
479
|
+
line.unmeasured.push(entry);
|
|
480
|
+
if (required) problems.push({ code: BEHIND_SEAM_UNMEASURED_CODE, object: `${pair?.pair ?? BEHIND_SEAM_LINE} (${frame})`, detail: `${entry.reason}; a declared required reading cannot pass unmeasured` });
|
|
481
|
+
};
|
|
482
|
+
const start = problems.length;
|
|
483
|
+
const shape = behindSeamsProblems(declared, 'requirements.behind_seams');
|
|
484
|
+
problems.push(...shape);
|
|
485
|
+
if (shape.length > 0) { line.status = 'FAIL'; return line; }
|
|
486
|
+
for (const p of declared.pairs ?? []) if (!selected.has(keyOf(p.part, p.neighbour))) unread(null, 'declaration', `override pair "${p.part}|${p.neighbour}" is not in motionSeamSelection; an override does not create an adjacent pair`, true);
|
|
487
|
+
if (input.pairs.length === 0) unread(null, 'selection', 'no selected motion seam pair; no boundary population was measured', declared.threshold !== undefined);
|
|
488
|
+
const rows = input.pairs.map(pair => {
|
|
489
|
+
const override = declared.pairs?.find(p => keyOf(p.part, p.neighbour) === keyOf(pair.a, pair.b));
|
|
490
|
+
const threshold = override?.threshold ?? declared.threshold ?? null, allowance = override?.allowance ?? declared.allowance ?? 0;
|
|
491
|
+
const stockRows = input.stock?.filter(s => s.pair === pair.pair) ?? [];
|
|
492
|
+
return { pair, threshold, allowance, stock: stockRows.length === 1 ? stockRows[0] : undefined,
|
|
493
|
+
setup: null as BehindSeamsFrame | null, frames: [] as BehindSeamsFrame[] };
|
|
494
|
+
});
|
|
495
|
+
const rate = Number.isFinite(input.fps) && input.fps > 0;
|
|
496
|
+
const cadence = rate && input.idle.every((f, i) => f.index === i && (f.time === i / input.fps || f.time === i * (1 / input.fps)));
|
|
497
|
+
for (const r of rows) {
|
|
498
|
+
if (r.threshold === null) { unread(r.pair, 'declaration', 'no authored threshold T; this pair is SKIP, never a pass', false); continue; }
|
|
499
|
+
if (!rate) unread(r.pair, 'idle', 'frame cadence is unavailable', true);
|
|
500
|
+
if (input.setup === null) unread(r.pair, 'setup', 'actual setup pose is unavailable; idle frame zero is not setup', true);
|
|
501
|
+
if (input.idle.length === 0) unread(r.pair, 'idle', 'no idle frames were read', true);
|
|
502
|
+
else if (!cadence) unread(r.pair, 'idle', 'missing, duplicate or off-cadence idle frame; every frame at the declared fps is required', true);
|
|
503
|
+
}
|
|
504
|
+
// All pairs share a frame's hidden-set cache. Release its native rasters before
|
|
505
|
+
// the next pose: memory grows with one frame, not animation length.
|
|
506
|
+
const observe = (frame: Frame, setup: boolean): void => {
|
|
507
|
+
for (const r of rows) if (r.threshold !== null) {
|
|
508
|
+
const note = (where: string, reason: string): void => unread(r.pair, where, reason, true);
|
|
509
|
+
const value = readBehindFrame(api, input, r.pair, frame, setup, r.stock, r.threshold, r.allowance, note, cache);
|
|
510
|
+
if (setup) r.setup = value;
|
|
511
|
+
else r.frames.push(value);
|
|
512
|
+
}
|
|
513
|
+
cache.clear();
|
|
514
|
+
};
|
|
515
|
+
if (rate && input.setup !== null) observe(input.setup, true);
|
|
516
|
+
if (cadence) for (const frame of input.idle) observe(frame, false);
|
|
517
|
+
for (const r of rows) {
|
|
518
|
+
const { pair, threshold, allowance, setup, frames } = r;
|
|
519
|
+
const parts: [string, string] = [pair.a, pair.b];
|
|
520
|
+
const motion = reading(frames, 'motion_opened', input.fps, allowance, parts), standing = reading(frames, 'standing', input.fps, allowance, parts);
|
|
521
|
+
if ((setup === null || setup.motion_opened.status === 'SKIP') && motion.status !== 'FAIL') motion.status = 'SKIP';
|
|
522
|
+
if ((setup === null || setup.standing.status === 'SKIP') && standing.status !== 'FAIL') standing.status = 'SKIP';
|
|
523
|
+
if (setup?.standing.status === 'FAIL') standing.status = 'FAIL';
|
|
524
|
+
for (const [kind, value] of [['motion_opened', motion], ['standing', standing]] as const) {
|
|
525
|
+
if (value.max_px > allowance || kind === 'standing' && (setup?.standing.px ?? 0) > allowance) {
|
|
526
|
+
const at = kind === 'standing' && (setup?.standing.px ?? 0) > value.max_px ? `setup (${setup!.standing.px} cells)` : `idle frame ${value.worst?.index} (${value.max_px} cells)`;
|
|
527
|
+
problems.push({ code: BEHIND_SEAM_CODE, object: `pair "${pair.pair}" ${kind}`, detail: `${at} exceeds allowance ${allowance}; authored threshold ${threshold}, native seam cells, no one-cell floor or rest mask` });
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const failed = motion.status === 'FAIL' || standing.status === 'FAIL' || line.unmeasured.some(u => u.pair === pair.pair && threshold !== null);
|
|
531
|
+
const readFrames = frames.filter(f => f.motion_opened.status !== 'SKIP' && f.standing.status !== 'SKIP' &&
|
|
532
|
+
(f.standing.unread_corridors?.length ?? 0) === 0 && !line.unmeasured.some(u => u.pair === pair.pair && u.frame === `idle frame ${f.index}`)).length;
|
|
533
|
+
line.pairs.push({ ...checkRow('BEHIND_PART_SEAMS.pairs', 'pair', failed, parts), animation: 'idle', pair: pair.pair, parts, declared: [...pair.declared], threshold, allowance, setup, frames, motion_opened: motion, standing,
|
|
534
|
+
sampled_frames: input.idle.length, read_frames: readFrames, unmeasured_frames: input.idle.length - readFrames });
|
|
535
|
+
}
|
|
536
|
+
line.status = problems.length > start ? 'FAIL' : line.pairs.length === 0 || line.pairs.some(p => p.threshold === null || p.motion_opened.status === 'SKIP' || p.standing.status === 'SKIP') ? 'SKIP' : 'PASS';
|
|
537
|
+
if (declared.turn === true) {
|
|
538
|
+
line.turn = measureBehindTurnFrames(api, input, declared, problems);
|
|
539
|
+
if (line.turn.status === 'FAIL' || problems.length > start) line.status = 'FAIL';
|
|
540
|
+
else if (line.turn.status === 'SKIP' && line.status !== 'FAIL') line.status = 'SKIP';
|
|
541
|
+
}
|
|
542
|
+
return line;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Turn observations are independent t=0 reset samples, never temporal spans. */
|
|
546
|
+
function measureBehindTurnFrames(api: BehindSeamsApi, input: BehindSeamsFramesInput, declared: BehindSeams, problems: Problem[]): BehindSeamsTurnMeasured {
|
|
547
|
+
const turn = input.turn;
|
|
548
|
+
const result: BehindSeamsTurnMeasured = { status: 'SKIP', poses: turn?.poses.map(p => p.name) ?? [], pairs: [], unmeasured: [],
|
|
549
|
+
limitations: 'independent setup-reset turn endpoints and full range corners only; no sweep, idle motion, temporal spans or alternate skins; standing and transported setup-overlap are separate' };
|
|
550
|
+
if (turn?.poser !== undefined) result.limitations += `; poser ${turn.poser}`;
|
|
551
|
+
if (turn?.sourceSkeletonSha256 !== undefined) result.limitations += `; original skeleton sha256 ${turn.sourceSkeletonSha256}`;
|
|
552
|
+
const required = declared.threshold !== undefined || declared.pairs?.some(p => p.threshold !== undefined) === true;
|
|
553
|
+
let mandatoryUnread = false;
|
|
554
|
+
const unread = (pair: MotionSeamPair | null, frame: string, reason: string, mandatory: boolean): void => {
|
|
555
|
+
result.unmeasured.push({ ...checkRow('BEHIND_PART_SEAMS.turn.unmeasured', pair === null ? 'rig' : 'pair', mandatory, pair === null ? [] : [pair.a, pair.b]), pair: pair?.pair ?? null, frame, reason: `HOLE: ${reason}` });
|
|
556
|
+
if (mandatory) mandatoryUnread = true;
|
|
557
|
+
if (mandatory) problems.push({ code: BEHIND_SEAM_UNMEASURED_CODE, object: `${pair?.pair ?? BEHIND_SEAM_LINE} (${frame})`, detail: `HOLE: ${reason}; required turn reading cannot pass unmeasured` });
|
|
558
|
+
};
|
|
559
|
+
if (turn === undefined || turn.poses.length === 0) {
|
|
560
|
+
unread(null, 'turn', turn?.reason ?? 'no declared finite turn dial range; turn is SKIP, never a pass', required);
|
|
561
|
+
result.pairs = input.pairs.map(pair => {
|
|
562
|
+
const override = declared.pairs?.find(p => keyOf(p.part, p.neighbour) === keyOf(pair.a, pair.b));
|
|
563
|
+
return { ...checkRow('BEHIND_PART_SEAMS.turn.pairs', 'pair', required, [pair.a, pair.b]), pair: pair.pair, parts: [pair.a, pair.b],
|
|
564
|
+
threshold: override?.threshold ?? declared.threshold ?? null, allowance: override?.allowance ?? declared.allowance ?? 0,
|
|
565
|
+
frames: [], sampled_poses: 0, read_poses: 0, unmeasured_poses: 0,
|
|
566
|
+
motion_opened: { status: 'SKIP', max_px: 0 }, standing: { status: 'SKIP', max_px: 0 } };
|
|
567
|
+
});
|
|
568
|
+
return result;
|
|
569
|
+
}
|
|
570
|
+
if (turn.reason !== undefined) unread(null, 'turn', turn.reason, required);
|
|
571
|
+
const complete = turn.frames.length === turn.poses.length && new Set(turn.poses.map(p => p.name)).size === turn.poses.length;
|
|
572
|
+
if (!complete) unread(null, 'turn', 'missing or duplicate named turn sample; every preselected endpoint and corner is required', required);
|
|
573
|
+
const frames = turn.frames.filter((f): f is Frame => f !== null);
|
|
574
|
+
const posedInput: BehindSeamsFramesInput = { ...input, setup: turn.setup, idle: frames, rest: turn.rest, stock: turn.stock };
|
|
575
|
+
const cache = new Map<Frame, Map<string, RasterCache>>();
|
|
576
|
+
for (const pair of input.pairs) {
|
|
577
|
+
const override = declared.pairs?.find(p => keyOf(p.part, p.neighbour) === keyOf(pair.a, pair.b));
|
|
578
|
+
const threshold = override?.threshold ?? declared.threshold ?? null, allowance = override?.allowance ?? declared.allowance ?? 0;
|
|
579
|
+
const parts: [string, string] = [pair.a, pair.b];
|
|
580
|
+
const stockRows = turn.stock?.filter(s => s.pair === pair.pair) ?? [];
|
|
581
|
+
const rows: BehindSeamsFrame[] = [];
|
|
582
|
+
if (threshold === null) unread(pair, 'turn declaration', 'no authored threshold T; turn pair is SKIP, never a pass', false);
|
|
583
|
+
else {
|
|
584
|
+
if (turn.setup === null) unread(pair, 'turn setup', 'actual turn setup pose is unavailable', true);
|
|
585
|
+
for (const [index, pose] of turn.poses.entries()) {
|
|
586
|
+
const frame = turn.frames[index];
|
|
587
|
+
if (frame === undefined || frame === null || frame.index !== index || frame.time !== 0) {
|
|
588
|
+
unread(pair, `turn ${pose.name}`, 'preselected turn pose is missing or has the wrong identity; it cannot become zero cells', true);
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
const row = readBehindFrame(api, posedInput, pair, frame, false, stockRows.length === 1 ? stockRows[0] : undefined,
|
|
592
|
+
threshold, allowance, (where, why) => unread(pair, where, why, true), cache, pose);
|
|
593
|
+
rows.push(row); cache.clear();
|
|
594
|
+
for (const kind of ['motion_opened', 'standing'] as const) if (row[kind].status === 'FAIL') problems.push({ code: BEHIND_SEAM_CODE,
|
|
595
|
+
object: `pair "${pair.pair}" turn ${pose.name} ${kind}`, detail: `${row[kind].px} native seam cells exceeds allowance ${allowance}; authored threshold ${threshold}; independent declared turn pose` });
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const read = rows.filter(row => row.motion_opened.status !== 'SKIP' && row.standing.status !== 'SKIP' &&
|
|
599
|
+
!result.unmeasured.some(u => u.pair === pair.pair && u.frame === `turn ${row.pose}`)).length;
|
|
600
|
+
const aggregate = (kind: 'motion_opened' | 'standing'): BehindSeamsTurnPair['standing'] => ({
|
|
601
|
+
status: rows.some(r => r[kind].status === 'FAIL') ? 'FAIL' : complete && rows.length === turn.poses.length && rows.every(r => r[kind].status === 'PASS') ? 'PASS' : 'SKIP',
|
|
602
|
+
max_px: Math.max(0, ...rows.map(r => r[kind].px)),
|
|
603
|
+
});
|
|
604
|
+
const motion = aggregate('motion_opened'), standing = aggregate('standing');
|
|
605
|
+
result.pairs.push({ ...checkRow('BEHIND_PART_SEAMS.turn.pairs', 'pair', motion.status === 'FAIL' || standing.status === 'FAIL' || threshold !== null && read !== turn.poses.length, parts),
|
|
606
|
+
pair: pair.pair, parts, threshold, allowance, frames: rows, sampled_poses: turn.poses.length, read_poses: read, unmeasured_poses: turn.poses.length - read,
|
|
607
|
+
motion_opened: motion, standing });
|
|
608
|
+
}
|
|
609
|
+
if (input.pairs.length === 0) unread(null, 'turn selection', 'no selected seam pair; turn boundary population is unavailable', required);
|
|
610
|
+
result.status = result.pairs.some(p => p.motion_opened.status === 'FAIL' || p.standing.status === 'FAIL') || mandatoryUnread ? 'FAIL'
|
|
611
|
+
: result.pairs.length === 0 || result.pairs.some(p => p.motion_opened.status === 'SKIP' || p.standing.status === 'SKIP') ? 'SKIP' : 'PASS';
|
|
612
|
+
return result;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
interface BehindTurnDial { bone: string; field: 'rotation' | 'x' | 'y'; min: number; max: number; setup: number }
|
|
616
|
+
/** Read emitted declarations, not config defaults, dial-name guesses or animation times. */
|
|
617
|
+
export function behindTurnPlan(rig: Record<string, unknown>): { dials: BehindTurnDial[]; poses: BehindSeamsTurnPose[]; reason?: string } {
|
|
618
|
+
const bones = (Array.isArray(rig.bones) ? rig.bones : []).filter(record);
|
|
619
|
+
const sliders = (Array.isArray(rig.constraints) ? rig.constraints : []).filter(record).filter(c => c.type === 'slider' &&
|
|
620
|
+
([YAW_DIAL_BONE, PITCH_DIAL_BONE, BODY_YAW_DIAL_BONE, TURN_BONE].includes(String(c.bone)) || ['turn', 'tilt', BODY_TURN_ANIM].includes(String(c.animation))));
|
|
621
|
+
const dials: BehindTurnDial[] = [];
|
|
622
|
+
for (const c of sliders) {
|
|
623
|
+
const matched = bones.filter(b => b.name === c.bone), field = c.property === 'rotate' ? 'rotation' : c.property === 'x' ? 'x' : c.property === 'y' ? 'y' : null;
|
|
624
|
+
if (typeof c.bone !== 'string' || matched.length !== 1 || field === null || c.local !== true ||
|
|
625
|
+
typeof c.from !== 'number' || !Number.isFinite(c.from) || typeof c.max !== 'number' || !Number.isFinite(c.max) || c.from >= c.max || dials.some(d => d.bone === c.bone)) {
|
|
626
|
+
return { dials: [], poses: [], reason: `turn slider "${String(c.name)}" has no unique local dial with finite increasing from/max range; no range is invented` };
|
|
627
|
+
}
|
|
628
|
+
const setup = matched[0][field] ?? 0;
|
|
629
|
+
if (typeof setup !== 'number' || !Number.isFinite(setup) || setup < c.from || setup > c.max) return { dials: [], poses: [], reason: `turn dial "${c.bone}" has no finite in-range setup value` };
|
|
630
|
+
dials.push({ bone: c.bone, field, min: c.from, max: c.max, setup });
|
|
631
|
+
}
|
|
632
|
+
if (bones.some(b => b.name === TURN_BONE) && !dials.some(d => d.bone === TURN_BONE)) return { dials: [], poses: [], reason: `legacy dial "${TURN_BONE}" has no declared finite range; no x range is invented` };
|
|
633
|
+
if (dials.length === 0) return { dials, poses: [], reason: 'no declared turn dial; turn is SKIP, never a pass' };
|
|
634
|
+
const poses: BehindSeamsTurnPose[] = [], seen = new Set<string>();
|
|
635
|
+
const add = (values: Record<string, number>): void => {
|
|
636
|
+
const key = JSON.stringify(values);
|
|
637
|
+
if (!seen.has(key)) { seen.add(key); poses.push({ name: dials.map(d => `${d.bone}=${values[d.bone]}`).join(','), values }); }
|
|
638
|
+
};
|
|
639
|
+
const setup = Object.fromEntries(dials.map(d => [d.bone, d.setup]));
|
|
640
|
+
for (const dial of dials) for (const value of [dial.min, dial.max]) add({ ...setup, [dial.bone]: value });
|
|
641
|
+
const corners = (index: number, values: Record<string, number>): void => {
|
|
642
|
+
if (index === dials.length) { add(values); return; }
|
|
643
|
+
const dial = dials[index];
|
|
644
|
+
for (const value of [dial.min, dial.max]) corners(index + 1, { ...values, [dial.bone]: value });
|
|
645
|
+
};
|
|
646
|
+
corners(0, {});
|
|
647
|
+
return { dials, poses };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** One gated copy can carry every selected pose. Motion keys are offsets from
|
|
651
|
+
* setup, so convert planned absolute locals to the public timeline schema. */
|
|
652
|
+
export function behindTurnAnimations(rig: Record<string, unknown>): Record<string, { duration: number; tracks: Array<{ bone: string; property: string; keys: Array<{ t: number; v: number[] }> }> }> {
|
|
653
|
+
const plan = behindTurnPlan(rig);
|
|
654
|
+
return Object.fromEntries(plan.poses.map(pose => [behindTurnAnimationName(pose.name), {
|
|
655
|
+
duration: 0,
|
|
656
|
+
tracks: plan.dials.map(d => ({ bone: d.bone, property: d.field === 'rotation' ? 'rotate' : d.field === 'x' ? 'translatex' : 'translatey',
|
|
657
|
+
keys: [{ t: 0, v: [pose.values[d.bone] - d.setup] }] })),
|
|
658
|
+
}]));
|
|
659
|
+
}
|
|
660
|
+
/** Injective safe encoding of the pose name, including every UTF-16 code unit;
|
|
661
|
+
* no index, truncation or per-pose digest can hide a sample identity. */
|
|
662
|
+
export function behindTurnAnimationName(name: string): string {
|
|
663
|
+
return `_behind_seams_turn_${name.split('').map(c => c.charCodeAt(0).toString(16).padStart(4, '0')).join('')}`;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** Read the throwaway gated copy through the same public facade as idle.
|
|
667
|
+
* No skeleton, model, setup or poser implementation is changed here. */
|
|
668
|
+
function sampleBehindTurn(api: typeof import('@rig-c/core/render-shared'), input: BehindSeamsInput,
|
|
669
|
+
accepted: ReturnType<typeof api.loadCandidate>, acceptedSetup: Frame | null, acceptedPoser: string): BehindSeamsTurnInput {
|
|
670
|
+
const plan = behindTurnPlan(input.rig);
|
|
671
|
+
const empty: BehindSeamsTurnInput = { poses: plan.poses, frames: [], setup: null, rest: [], stock: null };
|
|
672
|
+
if (plan.reason !== undefined) return { ...empty, reason: plan.reason };
|
|
673
|
+
try {
|
|
674
|
+
empty.sourceSkeletonSha256 = createHash('sha256').update(readFileSync(join(input.build, 'skeleton.json'))).digest('hex');
|
|
675
|
+
if (input.turnBuild?.reason !== undefined) throw new Error(input.turnBuild.reason);
|
|
676
|
+
const build = input.turnBuild?.build;
|
|
677
|
+
if (build === undefined) throw new Error('gated turn animation copy is unavailable');
|
|
678
|
+
const skeleton = join(build, 'skeleton.json'), atlas = join(build, 'skeleton.atlas');
|
|
679
|
+
const atlasText = readFileSync(atlas, 'utf8');
|
|
680
|
+
if (atlasText !== readFileSync(join(input.build, 'skeleton.atlas'), 'utf8')) throw new Error('turn copy atlas text differs from accepted build');
|
|
681
|
+
const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText, atlasDir: build, label: 'behind seams turn samples' }, { skeleton, atlas }, undefined);
|
|
682
|
+
if (candidate.pages.size !== accepted.pages.size || [...accepted.pages].some(([name, page]) => {
|
|
683
|
+
const other = candidate.pages.get(name);
|
|
684
|
+
return other === undefined || other.width !== page.width || other.height !== page.height || !Buffer.from(other.data).equals(Buffer.from(page.data));
|
|
685
|
+
})) throw new Error('turn copy decoded atlas pages differ from accepted build');
|
|
686
|
+
const observed = api.throughPoser(candidate.choice, poser => {
|
|
687
|
+
const opts = { geometry: true, texture: true };
|
|
688
|
+
const setup = api.sampleSetupPose(poser, opts)[0] ?? null;
|
|
689
|
+
if (setup === null || JSON.stringify(setup) !== JSON.stringify(acceptedSetup)) throw new Error('turn copy setup geometry differs from accepted build');
|
|
690
|
+
const poses: BehindSeamsTurnPose[] = [];
|
|
691
|
+
const frames = plan.poses.map((pose, index) => {
|
|
692
|
+
const name = behindTurnAnimationName(pose.name);
|
|
693
|
+
const samples = api.sampleAnimation(poser, name, input.fps, { ...opts, channels: true });
|
|
694
|
+
if (samples.length !== 1 || samples[0].time !== 0) throw new Error(`turn ${pose.name}: animation "${name}" does not supply exactly one t=0 sample`);
|
|
695
|
+
const frame = samples[0];
|
|
696
|
+
if (frame.channelError !== undefined || frame.channels === undefined) throw new Error(`turn ${pose.name}: dial channels unavailable`);
|
|
697
|
+
const observed_values: Record<string, number> = {}, slider_times: Record<string, number> = {};
|
|
698
|
+
for (const dial of plan.dials) {
|
|
699
|
+
const property = dial.field === 'rotation' ? 'rotate' : `translate.${dial.field}`;
|
|
700
|
+
const local = frame.channels.filter(c => JSON.stringify(c.path) === JSON.stringify(['bone', dial.bone, property]));
|
|
701
|
+
const want = pose.values[dial.bone];
|
|
702
|
+
// The compiler stores float32 keys; compare at that declared precision.
|
|
703
|
+
if (local.length !== 1 || !Number.isFinite(local[0].value) || Math.fround(local[0].value) !== Math.fround(want)) throw new Error(`turn ${pose.name}: dial "${dial.bone}" did not reach planned local ${want}`);
|
|
704
|
+
observed_values[dial.bone] = local[0].value;
|
|
705
|
+
const slider = (Array.isArray(input.rig.constraints) ? input.rig.constraints : []).filter(record).find(c => c.type === 'slider' && c.bone === dial.bone);
|
|
706
|
+
const times = frame.channels.filter(c => JSON.stringify(c.path) === JSON.stringify(['slider', slider?.name, 'mapped-time']));
|
|
707
|
+
if (times.length !== 1 || !Number.isFinite(times[0].value)) throw new Error(`turn ${pose.name}: slider on "${dial.bone}" has no finite mapped-time observation`);
|
|
708
|
+
slider_times[String(slider!.name)] = times[0].value;
|
|
709
|
+
}
|
|
710
|
+
poses.push({ ...pose, observed_values, slider_times });
|
|
711
|
+
return { ...frame, index, time: 0 };
|
|
712
|
+
});
|
|
713
|
+
const rest = poser.rest(undefined, [setup.attachments ?? [], ...frames.map(f => f.attachments ?? [])]);
|
|
714
|
+
return { poses, frames, setup, rest };
|
|
715
|
+
});
|
|
716
|
+
if (observed.poser !== acceptedPoser) throw new Error(`turn copy poser "${observed.poser}" differs from accepted "${acceptedPoser}"`);
|
|
717
|
+
const { poses, frames, setup, rest } = observed.value;
|
|
718
|
+
const sources = sourceProblems(input.rig, [setup, ...frames]);
|
|
719
|
+
if (sources.length > 0) throw new Error(sources.join('; '));
|
|
720
|
+
const pairs = input.pairs.filter(p => p.unread === undefined);
|
|
721
|
+
const stock = seamsOf(pairs, rest, frames.map(f => ({ ...f, attachments: f.attachments ?? [] })), candidate.pages, {},
|
|
722
|
+
{ cells: setupCellReader(() => setup.pieces, candidate.pages) }).map((read, i) => ({ pair: pairs[i].pair,
|
|
723
|
+
frames: frames.length, drawn: read.drawn, banded: read.banded,
|
|
724
|
+
gapCovered: read.gapCovered.frames.map(hit => ({ index: hit.index, time: hit.time, cell: hit.cell, cells: hit.cells ?? [] })) }));
|
|
725
|
+
return { poses, frames, setup, rest, stock, sourceSkeletonSha256: empty.sourceSkeletonSha256, poser: observed.poser };
|
|
726
|
+
} catch (e) { return { ...empty, reason: `official turn copy unread: ${e instanceof Error ? e.message : String(e)}` }; }
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function jsonAt(path: string): Record<string, unknown> {
|
|
730
|
+
const value: unknown = JSON.parse(readFileSync(path, 'utf8'));
|
|
731
|
+
if (!record(value)) throw new Error('required sidecar is not an object');
|
|
732
|
+
return value;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/** Consume the existing render, including zero-hit pairs. Shape, pose, cadence,
|
|
736
|
+
* world and cell detail are checked before an absent hit can mean zero. */
|
|
737
|
+
function stockOf(dir: string, pairs: readonly MotionSeamPair[], fps: number, setup: Frame, idle: readonly Frame[], rest: readonly AttachmentRest[]): BehindSeamsStockPair[] {
|
|
738
|
+
const sidecar = jsonAt(join(dir, 'frames.json'));
|
|
739
|
+
if (sidecar.spec !== 'rigc-frames/1' || ['skin', 'slots', 'hidden', 'environment', 'preroll', 'physicsMode'].some(k => sidecar[k] !== undefined)) throw new Error('stock full render has an unavailable specification, skin, slot subset, environment, preroll or physics mode');
|
|
740
|
+
const sets = Array.isArray(sidecar.sets) ? sidecar.sets.filter(record).filter(s => s.animation === 'idle') : [];
|
|
741
|
+
if (sets.length !== 1) throw new Error('stock full render requires exactly one idle frame set');
|
|
742
|
+
const set = sets[0];
|
|
743
|
+
if (set.fps !== fps || set.stride !== 1 || set.sampled !== idle.length || set.written !== idle.length || idle.length === 0 || typeof set.dir !== 'string' || isAbsolute(set.dir)) throw new Error('stock idle must have every sampled frame written, stride 1, at the same fps as the official sampled poses');
|
|
744
|
+
const home = resolve(dir, set.dir), rel = relative(resolve(dir), home);
|
|
745
|
+
if (isAbsolute(rel) || /^\.\.(?:[\\/]|$)/.test(rel)) throw new Error('stock idle directory leaves its full-render root');
|
|
746
|
+
const geometry = jsonAt(join(home, 'geometry.json'));
|
|
747
|
+
if (geometry.spec !== 'rigc-geometry/1' || geometry.animation !== 'idle' || geometry.fps !== fps || ['skin', 'environment', 'preroll', 'physicsMode'].some(k => geometry[k] !== undefined) || !record(geometry.setup) || !Array.isArray(geometry.frames)) throw new Error('stock whole attachment geometry is unavailable or belongs to a different pose/world');
|
|
748
|
+
const posed = geometry.frames;
|
|
749
|
+
const different = idle.some((f, i) => { const p: unknown = posed[i]; return !record(p) || p.index !== f.index || p.time !== f.time || JSON.stringify(p.attachments) !== JSON.stringify(f.attachments); });
|
|
750
|
+
if (posed.length !== idle.length || JSON.stringify(geometry.setup.attachments) !== JSON.stringify(setup.attachments) || JSON.stringify(geometry.rest) !== JSON.stringify(rest) || different) throw new Error('official setup/rest/idle geometry or draw order differs from the existing full stock seam render');
|
|
751
|
+
const file = jsonAt(join(home, 'seam.json'));
|
|
752
|
+
if (file.spec !== 'rigc-seam/1' || file.animation !== 'idle' || file.fps !== fps || file.skin !== undefined || !Array.isArray(file.pairs) || file.pairs.length !== pairs.length) throw new Error('stock seam pair order, animation, skin or fps is unavailable');
|
|
753
|
+
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
|
754
|
+
return pairs.map((want, i) => {
|
|
755
|
+
const p: unknown = (file.pairs as unknown[])[i];
|
|
756
|
+
if (!record(p) || p.a !== want.a || p.b !== want.b || !Number.isSafeInteger(p.drawn) || !Number.isSafeInteger(p.banded) || typeof p.drawn !== 'number' || typeof p.banded !== 'number' || p.banded < 0 || p.drawn < p.banded || p.drawn > idle.length || p.status !== (p.banded > 0 ? 'read' : 'skip') || !record(p.gapCovered) || !Array.isArray(p.gapCovered.frames)) throw new Error(`stock pair "${want.pair}" has unavailable drawn/banded/gapCovered evidence`);
|
|
757
|
+
const seen = new Set<number>();
|
|
758
|
+
const gapCovered = p.gapCovered.frames.map((hit: unknown) => {
|
|
759
|
+
if (!record(hit) || !Number.isSafeInteger(hit.index) || typeof hit.index !== 'number' || hit.index < 0 || hit.index >= idle.length || seen.has(hit.index) || !finite(hit.time) || hit.time !== idle[hit.index].time || !finite(hit.cell) || hit.cell <= 0 || !Number.isSafeInteger(hit.px) || typeof hit.px !== 'number' || hit.px <= 0 || !Array.isArray(hit.cells) || hit.cells.length !== hit.px || !Array.isArray(hit.box) || hit.box.length !== 4 || !hit.box.every(finite)) throw new Error(`stock pair "${want.pair}" requires unique complete gapCovered hits and --seam-cells detail`);
|
|
760
|
+
seen.add(hit.index);
|
|
761
|
+
const cells: SeamCell[] = hit.cells.map((c: unknown) => {
|
|
762
|
+
if (!record(c) || !finite(c.x) || !finite(c.y) || !(c.setupTop === null || typeof c.setupTop === 'string' && c.setupTop.length > 0) || !(c.setupUnder === null || typeof c.setupUnder === 'string' && c.setupUnder.length > 0) || c.setupTop === null && c.setupUnder !== null || c.setupTop !== null && c.setupTop === c.setupUnder) throw new Error(`stock pair "${want.pair}" has unread world cell/setup attribution`);
|
|
763
|
+
return { x: c.x, y: c.y, setupTop: c.setupTop, setupUnder: c.setupUnder };
|
|
764
|
+
});
|
|
765
|
+
return { index: hit.index, time: hit.time, cell: hit.cell, cells };
|
|
766
|
+
});
|
|
767
|
+
return { pair: want.pair, frames: idle.length, drawn: p.drawn, banded: p.banded, gapCovered };
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function sourceProblems(rig: Record<string, unknown>, frames: readonly Frame[]): string[] {
|
|
772
|
+
const slots = (Array.isArray(rig.slots) ? rig.slots : []).filter(record);
|
|
773
|
+
const reasons = new Set<string>();
|
|
774
|
+
const seen = new Set<string>();
|
|
775
|
+
for (const frame of frames) for (const piece of frame.pieces) {
|
|
776
|
+
const matches = slots.filter(s => s.name === piece.slot);
|
|
777
|
+
if (matches.length !== 1) { reasons.add(`slot "${piece.slot}" has no unique rig source/order declaration`); continue; }
|
|
778
|
+
if (matches[0].blend !== undefined && matches[0].blend !== 'normal') { reasons.add(`slot "${piece.slot}" uses unsupported blend ${JSON.stringify(matches[0].blend)}; source-over contribution is unmeasured`); continue; }
|
|
779
|
+
const attached = frame.attachments?.filter(a => a.slot === piece.slot) ?? [];
|
|
780
|
+
if (attached.length !== 1 || piece.texture === undefined || piece.texture.artUvs.length !== piece.uvs.length) { reasons.add(`slot "${piece.slot}" has unavailable whole attachment/art-UV source evidence`); continue; }
|
|
781
|
+
const key = JSON.stringify([piece.slot, attached[0].attachment]);
|
|
782
|
+
if (seen.has(key)) continue;
|
|
783
|
+
seen.add(key);
|
|
784
|
+
try { seamSourceAttachment(rig, piece.slot, attached[0].attachment); }
|
|
785
|
+
catch (e) { reasons.add(`slot "${piece.slot}" attachment "${attached[0].attachment}" source unread: ${e instanceof Error ? e.message : String(e)}`); }
|
|
786
|
+
}
|
|
787
|
+
return [...reasons];
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** Production reader. It neither builds nor emits files, and never substitutes
|
|
791
|
+
* its own seam algorithm for the full stock gapCovered result. */
|
|
792
|
+
export function measureBehindSeams(api: typeof import('@rig-c/core/render-shared'), input: BehindSeamsInput, declared: BehindSeams, problems: Problem[]): BehindSeamsMeasured {
|
|
793
|
+
const empty: BehindSeamsFramesInput = { pairs: input.pairs, setup: null, idle: [], rest: [], pages: new Map(), stock: null, fps: input.fps };
|
|
794
|
+
const active = declared.threshold !== undefined || declared.pairs?.some(p => p.threshold !== undefined) === true;
|
|
795
|
+
if (!active) {
|
|
796
|
+
if (declared.turn === true) {
|
|
797
|
+
const plan = behindTurnPlan(input.rig);
|
|
798
|
+
empty.turn = { poses: plan.poses, frames: [], setup: null, rest: [], stock: null,
|
|
799
|
+
reason: plan.reason ?? 'no authored threshold T; turn samples are not measured, never a pass' };
|
|
800
|
+
}
|
|
801
|
+
return measureBehindSeamFrames(api, empty, declared, problems);
|
|
802
|
+
}
|
|
803
|
+
const fail = (reason: string): BehindSeamsMeasured => {
|
|
804
|
+
const line = measureBehindSeamFrames(api, empty, declared, problems);
|
|
805
|
+
line.status = 'FAIL';
|
|
806
|
+
line.unmeasured.push({ ...checkRow('BEHIND_PART_SEAMS.unmeasured', 'rig', true, []), pair: null, frame: 'render/source', reason: `HOLE: ${reason}` });
|
|
807
|
+
problems.push({ code: BEHIND_SEAM_UNMEASURED_CODE, object: BEHIND_SEAM_LINE, detail: `HOLE: ${reason}; required setup and idle cannot pass unmeasured` });
|
|
808
|
+
return line;
|
|
809
|
+
};
|
|
810
|
+
if (input.unsupported !== undefined) return fail(input.unsupported);
|
|
811
|
+
let candidate: ReturnType<typeof api.loadCandidate>;
|
|
812
|
+
let sampled: { setup: Frame | null; idle: Frame[]; rest: AttachmentRest[] };
|
|
813
|
+
let acceptedPoser: string;
|
|
814
|
+
try {
|
|
815
|
+
const skeleton = join(input.build, 'skeleton.json'), atlas = join(input.build, 'skeleton.atlas');
|
|
816
|
+
candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlas, 'utf8'), atlasDir: input.build, label: 'behind-part seams' }, { skeleton, atlas }, undefined);
|
|
817
|
+
const observed = api.throughPoser(candidate.choice, p => {
|
|
818
|
+
const opts = { geometry: true, texture: true };
|
|
819
|
+
const setup = api.sampleSetupPose(p, opts)[0] ?? null;
|
|
820
|
+
const idle = p.animations.some(a => a.name === 'idle') ? api.sampleAnimation(p, 'idle', input.fps, opts) : [];
|
|
821
|
+
const rest = p.rest(undefined, [...(setup?.attachments === undefined ? [] : [setup.attachments]), ...idle.map(f => f.attachments ?? [])]);
|
|
822
|
+
return { setup, idle, rest };
|
|
823
|
+
});
|
|
824
|
+
sampled = observed.value;
|
|
825
|
+
acceptedPoser = observed.poser;
|
|
826
|
+
const sources = sourceProblems(input.rig, [...(sampled.setup === null ? [] : [sampled.setup]), ...sampled.idle]);
|
|
827
|
+
if (sources.length > 0) return fail(sources.join('; '));
|
|
828
|
+
} catch (e) { return fail(`official renderer/source unavailable: ${e instanceof Error ? e.message : String(e)}`); }
|
|
829
|
+
let stock: BehindSeamsStockPair[] | null = null, stockError: string | null = null;
|
|
830
|
+
try {
|
|
831
|
+
if (input.stockDir === null || sampled.setup === null) throw new Error('existing full stock seam render/setup is unavailable');
|
|
832
|
+
stock = stockOf(input.stockDir, input.pairs.filter(p => p.unread === undefined), input.fps, sampled.setup, sampled.idle, sampled.rest);
|
|
833
|
+
} catch (e) { stockError = e instanceof Error ? e.message : String(e); }
|
|
834
|
+
const line = measureBehindSeamFrames(api, { ...sampled, pairs: input.pairs, pages: candidate.pages, stock, fps: input.fps,
|
|
835
|
+
...(declared.turn === true ? { turn: sampleBehindTurn(api, input, candidate, sampled.setup, acceptedPoser) } : {}) }, declared, problems);
|
|
836
|
+
if (stockError !== null) {
|
|
837
|
+
line.status = 'FAIL';
|
|
838
|
+
line.unmeasured.push({ ...checkRow('BEHIND_PART_SEAMS.unmeasured', 'rig', true, []), pair: null, frame: 'stock render', reason: `HOLE: ${stockError}` });
|
|
839
|
+
problems.push({ code: BEHIND_SEAM_UNMEASURED_CODE, object: 'stock full seam render', detail: `HOLE: ${stockError}; unavailable stock coverage cannot become zero motion-opened cells` });
|
|
840
|
+
}
|
|
841
|
+
return line;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/** Null has no JSON/tally effect, but its console declaration is always honest. */
|
|
845
|
+
export function behindSeamLines(line: BehindSeamsMeasured | null): string[] {
|
|
846
|
+
if (line === null) return [`${BEHIND_SEAM_LINE}: SKIP — ${UNDECLARED_BEHIND_SEAM_REASON}`];
|
|
847
|
+
return [
|
|
848
|
+
`${BEHIND_SEAM_LINE}: ${line.status} — ${line.pairs.length} selected pair(s), setup separately and every idle frame at ${line.fps} fps; ${line.limitations}`,
|
|
849
|
+
...line.pairs.flatMap(p => {
|
|
850
|
+
const setup = p.setup;
|
|
851
|
+
const summary = (kind: 'motion_opened' | 'standing'): string => {
|
|
852
|
+
const r = p[kind], w = r.worst;
|
|
853
|
+
return `${BEHIND_SEAM_LINE}: pair "${p.pair}" ${kind} ${r.status} — ${r.hit_frames}/${p.frames.length} idle hit frames, sampled/read/unmeasured ${p.sampled_frames ?? p.frames.length}/${p.read_frames ?? 0}/${p.unmeasured_frames ?? 0}, max_px ${r.max_px}, max_run ${r.max_run.frames} frames (${r.max_run.seconds} s), max_spatial_run_cells ${r.max_spatial_run_cells} (${r.max_spatial_run_world} world units), earliest worst ${w === null ? 'none' : `frame ${w.index} t ${w.time}, cell ${w.cell}, box [${w.box.join(', ')}]`}; threshold ${p.threshold === null ? 'undeclared' : p.threshold}, allowance ${p.allowance}`;
|
|
854
|
+
};
|
|
855
|
+
const setupStanding = setup === null ? '' : setup.standing.px > 0 && setup.standing.status === 'SKIP' ? `${setup.standing.px} cells` : `${setup.standing.status}, ${setup.standing.px} cells`;
|
|
856
|
+
return [summary('motion_opened'), summary('standing'), `${BEHIND_SEAM_LINE}: pair "${p.pair}" setup ${setup === null ? 'SKIP — HOLE: setup not read' : `standing ${setupStanding}; motion_opened ${setup.motion_opened.status}, ${setup.motion_opened.px} cells; behind [${setup.behind_slots.join(', ')}]`}`];
|
|
857
|
+
}),
|
|
858
|
+
...(line.turn === undefined ? [] : [
|
|
859
|
+
`${BEHIND_SEAM_LINE}: turn ${line.turn.status} — ${line.turn.poses.length} preselected endpoint/corner pose(s); ${line.turn.limitations}`,
|
|
860
|
+
...line.turn.pairs.flatMap(p => p.frames.map(f => `${BEHIND_SEAM_LINE}: pair "${p.pair}" turn ${f.pose} — motion_opened ${f.motion_opened.status}, ${f.motion_opened.px} cells; standing ${f.standing.status}, ${f.standing.px} cells; threshold ${p.threshold}, allowance ${p.allowance}`)),
|
|
861
|
+
...line.turn.unmeasured.map(u => `${BEHIND_SEAM_LINE}: ${u.pair === null ? 'rig' : `pair "${u.pair}"`} ${u.frame} SKIP — ${u.reason}`),
|
|
862
|
+
]),
|
|
863
|
+
...line.unmeasured.map(u => {
|
|
864
|
+
const target = u.pair === null ? 'rig' : `pair "${u.pair}"`;
|
|
865
|
+
const pair = u.pair === null ? undefined : line.pairs.find(p => p.pair === u.pair);
|
|
866
|
+
const frame = pair === undefined ? undefined : u.frame === 'setup' ? pair.setup ?? undefined : pair.frames.find(f => `idle frame ${f.index}` === u.frame);
|
|
867
|
+
const corridors = frame?.standing.unread_corridors;
|
|
868
|
+
if (frame !== undefined && frame.standing.px > 0 && corridors !== undefined && corridors.length > 0 && u.reason.includes('unread corridors')) {
|
|
869
|
+
const status = frame.standing.status === 'FAIL' ? `FAIL, ${frame.standing.px} cells` : `${frame.standing.px} cells`;
|
|
870
|
+
return `${BEHIND_SEAM_LINE}: ${target} ${u.frame} standing ${status} — unread corridors: ${corridors.length} (cells ${frame.standing.unread_cells ?? 0}); ${u.reason}`;
|
|
871
|
+
}
|
|
872
|
+
return `${BEHIND_SEAM_LINE}: ${target} ${u.frame} SKIP — ${u.reason}`;
|
|
873
|
+
}),
|
|
874
|
+
];
|
|
875
|
+
}
|