Skip to main content

animsmith_core/scale/
mod.rs

1//! Format-neutral scale plan and proof contracts (DESIGN.md Appendix D).
2//!
3//! This module owns the two distinct scale operations Appendix D defines —
4//! [`ScaleOperation::WholeDocumentLinearUnits`] and
5//! [`ScaleOperation::RestBindUniformScale`] — plus their shared pure
6//! planning, candidate construction, and proof layer. It deliberately
7//! consumes and returns only format-neutral facts: an already-loaded
8//! [`Document`] and a [`ScaleCapabilityFacts`] projection that a format
9//! frontend (for example `animsmith-gltf`'s raw capability preflight)
10//! builds from its own source-specific inventory. This module does not
11//! accept paths, glTF/ufbx types, config parsers, or publication policy,
12//! and it does not itself decide CLI selectors, evidence schemas, or
13//! artifact/evidence publication — those are producer concerns layered on
14//! top.
15//!
16//! The public vocabulary and entrypoints continue to resolve through this
17//! facade. Private implementation modules own numeric leaves, validation,
18//! planning/replay, reference construction, and proof respectively; proof's
19//! residual recorder is nested under proof so its paired maximum/count state
20//! cannot be mutated outside that implementation boundary.
21//!
22//! [`ScaleOperation::RestBindUniformScale`] selects by raw, format-neutral
23//! source identity — `source_skin_index` and `source_root_node_index` — not
24//! by normalized [`crate::model::BoneId`] or mesh-instance ordinal.
25//! Resolving those selectors, and classifying the affected domain's affine
26//! shape, walks [`crate::model::SceneAssets::source_skeleton`]: the only
27//! place a full (possibly sheared) authored local matrix survives, since
28//! [`crate::model::Bone::rest`] is a lossy TRS decomposition that can never
29//! look sheared even when the source was.
30//!
31//! [`plan_scale`] is pure and fail-closed: it never mutates its input and
32//! returns a typed [`ScaleError`] for every unsupported affine domain,
33//! incomplete closure, incomplete capability, invalid selector, invalid
34//! factor. An internal reference builder constructs analytic candidates for
35//! fixtures and calibration; production format frontends instead rewrite
36//! exact source bytes and wrap the emitted reload with
37//! [`ScaleCandidate::from_document`]. [`prove_scale`] independently re-derives
38//! the plan's claims from the source and candidate documents and reports the observed
39//! residual maxima against the fixed [`ScaleTolerancePolicy::APPENDIX_D_V6`]
40//! tolerance identity.
41//!
42//! Those residuals are the producer evidence record of §D.6, which is why
43//! two properties of this module are contracts rather than implementation
44//! details. Every typed [`ScaleProofObligation`] is declared only when
45//! the planned document carries the evidence for it. Candidate construction
46//! and proof re-derive that structural inventory and report a stale plan as
47//! [`ScaleError::PlanDocumentMismatch`]; a counterpart missing inside an
48//! inventory-matched walk is [`ScaleError::MissingProofEvidence`]. Neither
49//! case becomes a zero residual — a record asserting `0.0` for something
50//! nothing checked would be false, not merely incomplete. The two
51//! observed-factor fields §D.6 asks for are both recorded, together with
52//! [`ScaleProof::observed_factor_divergence`] between them, so the record
53//! states their relationship instead of leaving a consumer to guess which to
54//! trust. Rest/bind derives them independently from raw and normalized state;
55//! whole-document conversion records its declared factor in both because it
56//! has no source factor to measure.
57
58use crate::model::{
59    AffineDomainViolation, BoneId, Document, DocumentShapeError, Interpolation, Property,
60    SourceInverseBindAccessorStatus, SourceSkeletonCoverage,
61};
62#[cfg(test)]
63use crate::model::{
64    Clip, MeshInstanceShapeViolation, Skeleton, TrackValues, Transform, mat4_is_finite,
65};
66#[cfg(test)]
67use glam::{Mat3, Mat4, Vec4};
68#[cfg(test)]
69use std::collections::BTreeMap;
70use std::collections::BTreeSet;
71
72mod assembly_basis;
73mod numeric;
74mod planning;
75mod proof;
76mod reference;
77mod validation;
78
79pub use assembly_basis::{
80    ASSEMBLY_SCALE_BASIS_VERSION, AssemblyScaleBasis, AssemblyScaleCompatibilityBasis,
81    AssemblyScaleCompatibilityError, AssemblyScaleNamedNode,
82    AssemblyScaleNamedSelectorResolutionError, AssemblyScaleResolvedNamedSelector,
83    AssemblyScaleSelectorRequest, AssemblyScaleSkinlessClipBasis, AssemblyScaleSourceNode,
84    AssemblyScaleSourceRest, AssemblyScaleTargetPath, assembly_scale_basis,
85    assembly_scale_compatibility_basis, rebase_assembly_scale_skinless_clip,
86    require_assembly_scale_compatibility, require_assembly_scale_compatibility_with_selectors,
87    resolve_assembly_scale_named_selector,
88};
89pub use planning::plan_scale;
90use planning::validate_plan_document_inventory;
91pub use proof::{ScaleProof, ScaleProofResidual, prove_scale};
92pub use reference::ScaleCandidate;
93
94#[cfg(test)]
95use proof::{
96    BoundsAccumulator, SkinSlot, accumulate_skinned_bounds, check_residual, check_sampling_budget,
97    observed_factor_from_source, per_sample_work_units, skin_influence_magnitude, world_at_time,
98};
99
100#[cfg(test)]
101use numeric::{
102    column_operand_magnitude, largest_entry, mat4_abs, product_operand_magnitude,
103    scale_translation_only, translation_composition_rounding_base,
104};
105#[cfg(test)]
106use planning::classify_affine;
107#[cfg(any(test, feature = "fixtures"))]
108pub(crate) use reference::build_scale_candidate;
109#[cfg(test)]
110use reference::{build_rest_bind, build_whole_document};
111#[cfg(test)]
112use validation::{
113    WorldBonePose, WorldPose, affected_skin_instance_indices, child_translation_rounding_magnitude,
114    instance_bind, rest_world_pose, source_node_index_map, validate_scale_input,
115};
116#[cfg(test)]
117use validation::{
118    affected_skin_classification_steps, derive_rest_bind_plan_domain,
119    reset_affected_skin_classification_steps, resolve_rest_bind_skin, rest_bind_affected_closure,
120    source_world_matrix, world_rests,
121};
122
123// --- Tolerance policy ----------------------------------------------------
124
125/// Fixed Appendix D tolerance identity and thresholds. Classification and
126/// proof share this one versioned policy and compute in `f64`, narrowing
127/// only at the writer model boundary. There is exactly one supported
128/// instance, [`ScaleTolerancePolicy::APPENDIX_D_V6`]: a policy change is a
129/// new policy identity, not a runtime knob.
130///
131/// The superseded v5 identity is deliberately not retained as an alias:
132///
133/// ```compile_fail
134/// use animsmith_core::ScaleTolerancePolicy;
135///
136/// let _ = ScaleTolerancePolicy::APPENDIX_D_V5;
137/// ```
138#[derive(Debug, Clone, Copy, PartialEq)]
139#[non_exhaustive]
140pub struct ScaleTolerancePolicy {
141    /// Stable policy identity recorded in producer evidence.
142    pub id: &'static str,
143    /// Relative orthogonality tolerance for rejecting shear.
144    pub relative_orthogonality: f64,
145    /// Relative tolerance for equal-length affine columns (uniform scale).
146    pub equal_axis: f64,
147    /// Relative tolerance for one common factor across an affected domain.
148    ///
149    /// This is the normative input band: it is what an operator's declared
150    /// factor is judged against, and
151    /// [`Self::postcondition_unit_scale_residual`] is derived from it so that
152    /// a plan this band accepts is guaranteed to produce a candidate that
153    /// satisfies the unit-scale postcondition.
154    pub common_factor: f64,
155    /// `abs(det) <= singular_determinant_relative * product(axis_lengths)`
156    /// classifies a linear part as singular.
157    pub singular_determinant_relative: f64,
158    /// Absolute term of the scalar/vector comparison tolerance.
159    pub scalar_absolute: f64,
160    /// Relative term of the scalar/vector comparison tolerance.
161    pub scalar_relative: f64,
162    /// Maximum shortest-path rotation residual, in radians.
163    pub rotation_residual_radians: f64,
164    /// Maximum postcondition unit-scale residual, measured **per axis**
165    /// (L-infinity) as `max(|scale_axis - 1|)` — not as an L2 norm over the
166    /// three axes.
167    ///
168    /// The norm is normative, and it is the same dimensionless per-axis
169    /// relative quantity [`Self::common_factor`] and [`Self::equal_axis`]
170    /// measure, so the input band and this postcondition are directly
171    /// commensurable (DESIGN.md Appendix D §D.1). This value is *derived*
172    /// from [`Self::common_factor`] rather than declared independently: see
173    /// [`Self::APPENDIX_D_V6`] for the composition argument and
174    /// [`Self::UNIT_SCALE_BANDS`] for the multiplier.
175    pub postcondition_unit_scale_residual: f64,
176    /// Maximum sampled proof work [`prove_scale`] will perform, in
177    /// per-sample-time work units.
178    ///
179    /// Total work is `sample_time_count * per_sample_work_units`, where the
180    /// per-sample cost counts every pass the sampled obligations actually
181    /// make — bones, skin slots, and skinned vertices, each once per document
182    /// side. See the private `per_sample_work_units` for the exact formula
183    /// and for why the slot term cannot be folded into either of the other
184    /// two. A
185    /// document above this budget is refused with
186    /// [`ScaleError::ProofSamplingBudgetExceeded`] *before* any sampling
187    /// runs; proof never silently samples a subset.
188    ///
189    /// This is part of the versioned policy identity, not a per-run flag —
190    /// DESIGN.md Appendix D §D.6/§D.7 forbid per-run tolerance knobs, and a
191    /// budget that changed per run would make two evidence records carrying
192    /// the same policy id describe different amounts of checking.
193    pub proof_sample_work_budget: u64,
194    /// How many binary32 ulps of *operand* magnitude an obligation that
195    /// compares `f32`-rounded arithmetic may deviate by, on top of
196    /// [`Self::scalar_absolute`] and [`Self::scalar_relative`].
197    ///
198    /// The term this multiplies is **absolute**, not relative: it is
199    /// `f32_rounding_ulps * magnitude * f32::EPSILON` where `magnitude` is
200    /// the largest quantity the compared arithmetic passed through, not the
201    /// quantity being compared. Where the compared value *is* that largest
202    /// quantity the term adds `4 * 2^-23 = 4.77e-7` of it — twenty times
203    /// less than [`Self::scalar_relative`] already allows — so it cannot
204    /// loosen the obligations it applies to in their own regime.
205    ///
206    /// It exists for the regime where the two diverge. A rotation can make
207    /// the compared quantity orders of magnitude smaller than the operands
208    /// it was computed from while it still carries those operands' absolute
209    /// rounding error: a bound component near zero on a mesh 4000 units
210    /// across, a near-identity `W * B` whose translation column cancelled two
211    /// 3190-magnitude terms, or a world translation whose parent chain
212    /// cancelled two of them one composition earlier. A purely relative band
213    /// is then derived from the small number and the error from the large
214    /// one, and [`prove_scale`] refuses a correct candidate that
215    /// [`plan_scale`] accepted. See [`Self::APPENDIX_D_V6`] for the
216    /// measurement this count comes from and DESIGN.md Appendix D §D.1 for
217    /// which magnitude each obligation takes it from.
218    ///
219    /// The count is only as meaningful as that magnitude. Two revisions of
220    /// this policy have now found the *base* wrong rather than the count too
221    /// small — first the skinned extent alone, which missed the `W * B`
222    /// composition, then `abs(W) * abs(B)` alone, which missed what `W`'s own
223    /// parent chain had already cancelled — and in both the measured excess
224    /// was hundreds of thousands of ulps, not a factor of two. A residual
225    /// above this count is evidence about the base before it is evidence
226    /// about the count.
227    pub f32_rounding_ulps: u32,
228}
229
230impl ScaleTolerancePolicy {
231    /// How many [`Self::common_factor`] bands
232    /// [`Self::postcondition_unit_scale_residual`] is derived from.
233    ///
234    /// Three of them are analytic and one is float headroom; see
235    /// [`Self::APPENDIX_D_V6`].
236    pub const UNIT_SCALE_BANDS: f64 = 4.0;
237
238    /// The only supported tolerance policy: DESIGN.md Appendix D, version 6.
239    ///
240    /// Version 6 supersedes `appendix-d-v5`, which superseded v4, v3, v2 and
241    /// v1. Each identity change is a change of *meaning*, not a retune:
242    ///
243    /// 1. [`Self::postcondition_unit_scale_residual`] is a per-axis
244    ///    (L-infinity) residual derived from [`Self::common_factor`], instead
245    ///    of v1's independently declared `1e-5` L2 norm over three axes. Under
246    ///    v1 the two were incommensurable, and a source whose observed factor
247    ///    had relative error `e` produced a postcondition residual of
248    ///    `sqrt(3) * e`, so every `e` in `(5.77e-6, 1e-5]` was accepted by
249    ///    [`plan_scale`] and then rejected by [`prove_scale`].
250    /// 2. [`Self::proof_sample_work_budget`] bounds the sampled proof work a
251    ///    document may demand.
252    /// 3. [`Self::f32_rounding_ulps`] is new in v3, and adds an absolute
253    ///    `f32`-rounding term to the five obligations that compare
254    ///    `f32`-rounded arithmetic against a base that a rotation can make
255    ///    arbitrarily smaller than the operands the arithmetic ran on —
256    ///    [`ProofResidualKind::Bounds`], [`ProofResidualKind::SkinMatrix`],
257    ///    [`ProofResidualKind::UnaffectedInverseBind`],
258    ///    [`ProofResidualKind::RestTranslation`], and
259    ///    [`ProofResidualKind::Trajectory`]. Without it [`plan_scale`] accepts
260    ///    and [`prove_scale`] refuses a correct candidate whenever
261    ///    `magnitude / component` is large.
262    /// 4. v4 widens finite non-negative weight normalization and accumulation
263    ///    to binary64, makes the Bounds magnitude a weight-proportional
264    ///    combination of each influence's transform and slot-composition
265    ///    provenance, and removes v3's blended-point L2 stage. Bounds residuals
266    ///    are per axis, and the normalized blend is already bounded by those
267    ///    weighted operands.
268    /// 5. v5 makes parent-chain translation provenance additive per composed
269    ///    link, in binary64, instead of taking a depth-independent maximum.
270    ///    Each spatial row carries the new local contribution plus a parent
271    ///    term capped by `contribution / EPSILON`. This provisions the smaller
272    ///    of one parent-scale ulp and losing the entire contribution, so zero
273    ///    and underflowed descendants cannot charge the same translated parent
274    ///    repeatedly. Only the three spatial output rows participate; the
275    ///    affine homogeneous row contributes zero under this cap. The same
276    ///    recurrence constructs rest and sampled poses, and its result reaches
277    ///    RestTranslation, Trajectory, SkinMatrix and Bounds through their
278    ///    existing consumers.
279    /// 6. v6 changes only the association of the shared affine axis-length
280    ///    mean: the three finite widened lengths are sorted ascending before
281    ///    the ordinary sum and division by three. This removes authored-column
282    ///    order from the classifier, planning, and proof witness without
283    ///    changing any numeric threshold, the v5 parent-chain provenance
284    ///    recurrence, or the evidence schema.
285    ///
286    /// `postcondition_unit_scale_residual` is
287    /// `UNIT_SCALE_BANDS * common_factor = 4e-5`, rounded up to the next
288    /// power of two, `2^-14 = 6.103515625e-5`. That value is also
289    /// `512 * 2^-23`, and so lies on the binary32 mantissa grid the
290    /// composed-scale measurement lives on. Landing on that grid is what
291    /// makes §D.1's inclusive "at most" reachable for this obligation: the
292    /// measured residual near unit magnitude is always an integer multiple of
293    /// `2^-23`, so a bound off that grid could never be met with equality and
294    /// would be an exclusive bound wearing an inclusive name.
295    ///
296    /// The four bands are:
297    ///
298    /// - one for [`ScaleError::FactorMismatch`], which binds the domain's
299    ///   observed common factor `s_0` to the caller's declared factor
300    ///   `s_declared`;
301    /// - one for [`ScaleError::MixedFactor`], which binds each affected node's
302    ///   observed factor `s_i` to `s_0`;
303    /// - one for [`AffineDomainViolation::NonUniformScale`], which binds each
304    ///   individual *axis* of node `i` to `s_i`; and
305    /// - one reserved as headroom for the `f32` world-matrix composition and
306    ///   decomposition that produces the measured composed scale.
307    ///
308    /// The first three compose, and the third is easy to miss: `s_i` is the
309    /// *average* of node `i`'s three world axis lengths (the affine
310    /// classifier returns that average), while the postcondition measures an
311    /// individual
312    /// axis, and the equal-axis check permits each axis its own further band
313    /// away from that average. The candidate's composed scale on axis `k` of
314    /// node `i` is `axis_ik / s_declared`, and each of the three bands is
315    /// stated relative to `max` of its operands, so each contributes at most
316    /// `c / (1 - c)` when re-expressed relative to the smaller one. The
317    /// analytic worst case is therefore `(1 - c)^-3 - 1 = 3.00006e-5` for
318    /// `c = 1e-5`.
319    ///
320    /// Three bands rounded up (`2^-15 = 3.0517578125e-5`) would leave that
321    /// worst case only `4` binary32 ulps of room — `2^-15 - 3.00006e-5 =
322    /// 5.17e-7 = 4.34 * 2^-23` — which is not headroom for a float
323    /// measurement, it is a rounding artefact. A fourth band makes the
324    /// reserved-headroom claim above true rather than aspirational, and it
325    /// does not blunt the obligation: every build defect this check exists to
326    /// catch — a dropped rebase, a factor applied twice, a stale no-op — is
327    /// `>= 1e-3`, so `6.1e-5` still leaves better than a `16x` detection
328    /// margin.
329    pub const APPENDIX_D_V6: Self = Self {
330        id: "appendix-d-v6",
331        relative_orthogonality: 1e-5,
332        equal_axis: 1e-5,
333        common_factor: 1e-5,
334        singular_determinant_relative: 1e-6,
335        scalar_absolute: 1e-6,
336        scalar_relative: 1e-5,
337        rotation_residual_radians: 1e-5,
338        // 2^-14, exactly: four `common_factor` bands rounded up onto the
339        // binary32 mantissa grid (`= 512 * 2^-23`).
340        postcondition_unit_scale_residual: 6.103_515_625e-5,
341        // DESIGN.md Appendix D §D.1 owns the exact charge and released
342        // resource boundary. docs/scale-calibration.md records the historical
343        // populations and machine-local timings that selected this value.
344        proof_sample_work_budget: 400_000_000,
345        // Empirically calibrated, not an analytic bound. The checked-in
346        // `calibrate_f32_rounding_ulps` sweep can be regenerated with
347        //
348        //   cargo test -p animsmith-core --release --lib \
349        //       calibrate_f32_rounding_ulps -- --ignored --nocapture
350        //
351        // docs/scale-calibration.md owns the exact populations, measured
352        // demands, historical alternatives, and cost discussion. DESIGN.md
353        // Appendix D §D.1 owns the shipped recurrence and refusal semantics.
354        f32_rounding_ulps: 4,
355    };
356
357    /// The expected ceiling on [`ScaleProof::observed_factor_divergence`]:
358    /// [`Self::common_factor`] plus
359    /// [`Self::postcondition_unit_scale_residual`], `7.103515625e-5` under
360    /// [`Self::APPENDIX_D_V6`].
361    ///
362    /// For rest/bind, [`ScalePlan::observed_factor`] and
363    /// [`ScaleProof::observed_factor`] are independent witnesses measured from
364    /// genuinely different state — the raw source projection composed through
365    /// `parent_source_node_index`, and the normalized skeleton composed
366    /// through `world_rest_matrices`. Their independence is the point. For
367    /// whole-document conversion both fields are the declared factor, so their
368    /// divergence is exactly zero. For rest/bind, the sum comes from:
369    ///
370    /// - planning binds its witness to the caller's declared factor within
371    ///   [`Self::common_factor`], or refuses with
372    ///   [`ScaleError::FactorMismatch`]; and
373    /// - for a candidate the internal reference builder produced from the
374    ///   source
375    ///   under proof, that candidate's composed root scale is the proof
376    ///   witness divided by the declared factor, so the unit-scale
377    ///   postcondition binds the proof witness to the declared factor within
378    ///   [`Self::postcondition_unit_scale_residual`].
379    ///
380    /// The two bands are not stated the same way, and the sum is a ceiling
381    /// only up to that difference. Planning's is relative to the `max` of its
382    /// two operands, exactly as this divergence is. The postcondition's is not
383    /// a relative band on the two witnesses at all: it is an absolute
384    /// L-infinity deviation from `1` on the *candidate's* composed scale, and
385    /// that candidate's scale is the proof witness rebased by the declared
386    /// factor — so what it bounds is `|proved - declared|` as a fraction of
387    /// the declared factor, not as a fraction of `max(planned, proved)`.
388    ///
389    /// **Reported, not enforced, and expected rather than proved.** Nothing
390    /// refuses a document for exceeding this. The second step above holds for
391    /// a candidate this module built from the source it is being proved
392    /// against, which [`prove_scale`] deliberately does not require, and it
393    /// costs the binary32 rounding of the rebase on the way — so the sum is
394    /// the ceiling the design guarantees, not a bound proved to the last ulp.
395    /// A divergence beyond it means the two witnesses were composed from state
396    /// that does not agree — most often differing *stored* transforms, since
397    /// [`crate::model::SourceNodeAsset::local_rest`] and
398    /// [`crate::model::Bone::rest`] are separately stored descriptions of the
399    /// same rest pose. It is not evidence of disagreeing parent chains: under
400    /// [`crate::model::SourceSkeletonCoverage::Complete`] coverage the two
401    /// chains are required to describe the same tree, and every entry point in
402    /// this module refuses a document where they do not.
403    ///
404    /// Derived from two bands this policy already declares rather than
405    /// introduced as a third, so it adds no tolerance and no policy identity —
406    /// and a consumer of the evidence record does not have to sum two
407    /// separate policy fields to know what the recorded divergence means.
408    pub fn observed_factor_divergence_ceiling(&self) -> f64 {
409        self.common_factor + self.postcondition_unit_scale_residual
410    }
411
412    /// `abs_error <= scalar_absolute + scalar_relative * max(abs(before), abs(after))`.
413    ///
414    /// Every proof call site must pass the actual before/after magnitudes of
415    /// the specific residual being checked — never a proxy such as the
416    /// plan's declared factor — so a residual near a large coordinate gets a
417    /// correspondingly looser absolute tolerance than one near a small
418    /// coordinate.
419    pub fn scalar_tolerance(&self, before: f64, after: f64) -> f64 {
420        self.scalar_absolute + self.scalar_relative * before.abs().max(after.abs())
421    }
422
423    /// [`Self::scalar_tolerance`] plus [`Self::f32_rounding_ulps`] binary32
424    /// ulps of `magnitude`.
425    ///
426    /// `magnitude` is the largest quantity the compared `f32` arithmetic
427    /// passed through — never the quantity being compared, which is what
428    /// `before`/`after` already carry. The two coincide for a comparison
429    /// whose operands are its own magnitude, and diverge without limit for
430    /// one whose result was made small by cancellation; DESIGN.md Appendix D
431    /// §D.1 names the magnitude each obligation takes.
432    ///
433    /// The added term is absolute in `magnitude` and so cannot widen a
434    /// comparison relative to its own operands: at `magnitude ==
435    /// max(before, after)` it is `f32_rounding_ulps * 2^-23 = 4.77e-7` of
436    /// them, against the `1e-5` [`Self::scalar_relative`] already allows.
437    pub fn f32_rounded_tolerance(&self, before: f64, after: f64, magnitude: f64) -> f64 {
438        self.scalar_tolerance(before, after)
439            + f64::from(self.f32_rounding_ulps) * magnitude.abs() * f64::from(f32::EPSILON)
440    }
441
442    /// `abs(a - b) <= tolerance * max(abs(a), abs(b))`.
443    ///
444    /// Genuinely relative, per DESIGN.md Appendix D §D.1: the orthogonality,
445    /// equal-axis, and common-factor tolerances are declared *relative*
446    /// `1e-5`, so the comparison base is the operands' own magnitude and
447    /// nothing else. Flooring that base at `1.0` — as an earlier revision did
448    /// — silently converts these into absolute tolerances for every operand
449    /// below unit magnitude, which is exactly the regime these operations
450    /// exist for: at a common factor of `0.01` a `1.0` floor accepts `1e-3`
451    /// relative error, `100x` the declared policy, and lets `plan_scale`
452    /// accept a plan whose candidate then fails its own unit-scale
453    /// postcondition.
454    ///
455    /// There is **no** floor on the comparison base — not `1.0`, and not
456    /// [`Self::scalar_absolute`] either. A `scalar_absolute` floor is a
457    /// smaller version of the same defect and breaks the same closure
458    /// property, just further down: below `1e-6` the band stops tracking the
459    /// operands and freezes at the constant `1e-5 * 1e-6 = 1e-11`, which is a
460    /// *relative* band of `1e-11 / abs(s)` and therefore widens without limit
461    /// as `s` shrinks. It crosses
462    /// [`Self::postcondition_unit_scale_residual`] at
463    /// `s = 1e-11 / 2^-14 = 1e-11 * 16384 = 1.6384e-7` (`3.2768e-7` against
464    /// the tighter `2^-15` bound an earlier revision declared — halving the
465    /// postcondition bound doubles the crossing point, because the crossing
466    /// point is inversely proportional to it), so every declared factor
467    /// below that had a band of accepted plans whose candidates then failed
468    /// the unit-scale postcondition — at `s = 1e-9` the band admits `1e-2`
469    /// relative error, `1000x` the declared policy.
470    ///
471    /// Nothing needs the floor for the degenerate `a == b == 0` case either:
472    /// that compares `0.0 <= 0.0`, which holds. (Both call sites have already
473    /// proved their operands strictly positive in any case — a declared
474    /// factor by `planning::plan_rest_bind`'s range check, an observed one by
475    /// [`planning::classify_affine`].)
476    fn relative(&self, tolerance: f64, a: f64, b: f64) -> bool {
477        (a - b).abs() <= tolerance * a.abs().max(b.abs())
478    }
479}
480
481// --- Capability projection ------------------------------------------------
482
483/// Whether a format-neutral capability projection covers the whole source.
484///
485/// A projection built from an incomplete or partially-inspected source must
486/// report [`ScaleCapabilityCoverage::Unavailable`]: an absent flag is not
487/// evidence the underlying domain is absent from the source.
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
489pub enum ScaleCapabilityCoverage {
490    /// The projection cannot vouch for the complete source domain.
491    #[default]
492    Unavailable,
493    /// Every documented domain in the source was inspected.
494    Complete,
495}
496
497/// Format-neutral capability facts a frontend projects from its raw source
498/// inventory before any scale plan or candidate exists.
499///
500/// This is deliberately coarser than a format's own raw capability
501/// manifest (for example `animsmith_gltf::GltfCapabilityManifest`): it only
502/// carries the flags this module's planning needs to fail closed on an
503/// unsupported domain, per DESIGN.md Appendix D §D.4. A frontend projects
504/// its richer, format-specific manifest down to these flags.
505#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
506#[non_exhaustive]
507pub struct ScaleCapabilityFacts {
508    /// Whether the projection covers the complete source domain.
509    pub coverage: ScaleCapabilityCoverage,
510    /// A morph target is present.
511    pub morphs_present: bool,
512    /// Static or animated morph weights are present.
513    pub morph_weights_present: bool,
514    /// The format adapter owns exact preservation of every present morph
515    /// payload for whole-document conversion.
516    ///
517    /// Presence alone is never permission: this witness is set only after a
518    /// raw adapter has validated its operation-specific write set and proof.
519    pub whole_document_morphs_preservable: bool,
520    /// A camera is present.
521    pub cameras_present: bool,
522    /// A punctual light is present.
523    pub lights_present: bool,
524    /// GPU-instancing data is present.
525    pub instancing_present: bool,
526    /// An extension is not covered by a registered length-field handler.
527    pub unregistered_extensions_present: bool,
528    /// Non-null application-specific extras are present.
529    pub extras_present: bool,
530    /// A JSON/source member outside the modeled schema was ignored.
531    pub unknown_source_members_present: bool,
532    /// A non-triangle-list primitive is present.
533    pub non_triangle_primitives_present: bool,
534    /// A vertex attribute outside the normalized writer subset is present.
535    pub unsupported_vertex_attributes_present: bool,
536    /// A secondary skin-influence set is present.
537    pub secondary_skin_influences_present: bool,
538    /// An inverse-bind accessor is missing, empty, mismatched, or unreadable.
539    pub inverse_bind_issues_present: bool,
540    /// A scale-bearing source layout cannot be safely bounded or rewritten.
541    pub unsafe_accessor_layout_present: bool,
542    /// An external (non-embedded) resource is referenced.
543    pub external_resources_present: bool,
544}
545
546impl ScaleCapabilityFacts {
547    /// A capability projection declaring complete coverage and no
548    /// unsupported domain for either operation.
549    ///
550    /// This operation-agnostic query stays conservative for callers that do
551    /// not yet have an operation in hand. Planning uses
552    /// [`Self::is_supported_for`] so a format adapter that owns raw morph
553    /// preservation can admit morphs for whole-document conversion without
554    /// weakening the rest/bind boundary.
555    pub fn is_supported(&self) -> bool {
556        self.common_domains_supported() && !self.morphs_present && !self.morph_weights_present
557    }
558
559    /// Whether this complete projection is supported for `operation`.
560    ///
561    /// Morph targets are deliberately operation-specific. A
562    /// whole-document format adapter may scale raw `POSITION` deltas and
563    /// preserve dimensionless weights outside [`crate::Document`]; rest/bind
564    /// still refuses every morph because its raw preservation proof has not
565    /// been defined. All other capability domains retain the same refusal for
566    /// both operations.
567    pub fn is_supported_for(&self, operation: ScaleOperation) -> bool {
568        self.common_domains_supported()
569            && match operation {
570                ScaleOperation::WholeDocumentLinearUnits { .. } => {
571                    (!self.morphs_present && !self.morph_weights_present)
572                        || self.whole_document_morphs_preservable
573                }
574                ScaleOperation::RestBindUniformScale { .. } => {
575                    !self.morphs_present && !self.morph_weights_present
576                }
577            }
578    }
579
580    fn common_domains_supported(&self) -> bool {
581        self.coverage == ScaleCapabilityCoverage::Complete
582            && !self.cameras_present
583            && !self.lights_present
584            && !self.instancing_present
585            && !self.unregistered_extensions_present
586            && !self.extras_present
587            && !self.unknown_source_members_present
588            && !self.non_triangle_primitives_present
589            && !self.unsupported_vertex_attributes_present
590            && !self.secondary_skin_influences_present
591            && !self.inverse_bind_issues_present
592            && !self.unsafe_accessor_layout_present
593            && !self.external_resources_present
594    }
595}
596
597// --- Operation and request -------------------------------------------------
598
599/// The two distinct scale operations DESIGN.md Appendix D §D.1 defines.
600///
601/// Neither variant infers its factor or applicability from mesh bounds,
602/// character height, joint lengths, inverse-bind magnitude, filename, or an
603/// asset category. The caller names the operation and declares or accepts
604/// the exact factor [`plan_scale`] validates.
605#[derive(Debug, Clone, Copy, PartialEq)]
606#[non_exhaustive]
607pub enum ScaleOperation {
608    /// Whole-document linear-unit conversion: every represented length is
609    /// converted by the declared finite positive `factor`.
610    WholeDocumentLinearUnits {
611        /// Declared finite positive conversion factor `q`.
612        factor: f64,
613    },
614    /// Rest/bind hierarchy reparameterization: removes one compensating
615    /// inherited scale from a restricted skinned hierarchy.
616    ///
617    /// Both selectors are raw, format-neutral source identity — a source
618    /// node/skin array index, per DESIGN.md Appendix D §D.7 — not a
619    /// normalized [`BoneId`] or mesh-instance ordinal. [`plan_scale`]
620    /// resolves them through [`crate::model::SceneAssets::source_skeleton`].
621    RestBindUniformScale {
622        /// Stable source-skin-array index selecting the skin whose joints
623        /// anchor the affected domain.
624        source_skin_index: usize,
625        /// Stable source-node-array index of the scaled ancestor root.
626        source_root_node_index: usize,
627        /// Caller-declared expected common factor `s`. Planning measures
628        /// the source's observed rest-world factor and rejects a mismatch
629        /// rather than inferring `s` from geometry.
630        expected_factor: f64,
631    },
632}
633
634/// Pure planning input: the operation, the document to plan against, and a
635/// format-neutral capability projection of the raw source.
636#[derive(Debug, Clone, Copy)]
637pub struct ScaleRequest<'a> {
638    /// Selected operation and its declared parameters.
639    pub operation: ScaleOperation,
640    /// Document to plan against.
641    pub document: &'a Document,
642    /// Format-neutral capability projection of the raw source.
643    pub capability: &'a ScaleCapabilityFacts,
644}
645
646// --- Errors ----------------------------------------------------------------
647
648/// Typed, fail-closed rejection from [`plan_scale`], reference candidate
649/// construction, or [`prove_scale`].
650#[derive(Debug, Clone, Copy, PartialEq, thiserror::Error)]
651#[non_exhaustive]
652pub enum ScaleError {
653    /// The whole-document conversion factor is not finite and positive.
654    #[error("scale factor must be finite and positive, got {factor}")]
655    InvalidFactor {
656        /// The rejected factor.
657        factor: f64,
658    },
659    /// The declared rest/bind expected factor is not finite and positive.
660    #[error("rest/bind expected factor must be finite and positive, got {factor}")]
661    InvalidExpectedFactor {
662        /// The rejected factor.
663        factor: f64,
664    },
665    /// A declared factor (or a factor derived from it, such as the rest/bind
666    /// reciprocal `1 / expected_factor`) is finite and positive in `f64` but
667    /// has no usable `f32` image at the writer model boundary: it either
668    /// overflows to infinity or flushes a nonzero factor to zero.
669    ///
670    /// This is deliberately a distinct variant from
671    /// [`ScaleError::InvalidFactor`] / [`ScaleError::InvalidExpectedFactor`],
672    /// whose message would be an outright lie here — `1e-50` *is* finite and
673    /// positive; what it is not is representable once the model narrows to
674    /// `f32`. Rejecting it at plan time is what stops a build from silently
675    /// multiplying every translation, mesh `POSITION`, and inverse-bind
676    /// translation by `0.0f32` and handing the annihilated document to a
677    /// proof that then signs off on it, because `0 == 0 * 0` within any
678    /// tolerance.
679    #[error(
680        "factor {factor} (derived from declared factor {declared}) is not representable at the f32 writer model boundary: it narrows to {narrowed}"
681    )]
682    FactorNotRepresentable {
683        /// The declared factor the caller supplied.
684        declared: f64,
685        /// The declared factor, or the reciprocal derived from it, that
686        /// failed to narrow. Equal to `declared` when the declared factor
687        /// itself failed.
688        factor: f64,
689        /// The unusable `f32` image of `factor`.
690        narrowed: f32,
691    },
692    /// `source_root_node_index` is not a source node in the document's
693    /// source skeleton.
694    #[error(
695        "source root node index {source_root_node_index} is not a source node in the document's source skeleton"
696    )]
697    InvalidRootSelector {
698        /// The rejected source-node index.
699        source_root_node_index: usize,
700    },
701    /// `source_skin_index` is not a skin in the document's source skeleton,
702    /// or the skin declares no joints.
703    #[error(
704        "source skin index {source_skin_index} is not a skin in the document's source skeleton, or has no joints"
705    )]
706    InvalidSkinSelector {
707        /// The rejected source-skin index.
708        source_skin_index: usize,
709    },
710    /// The capability projection is unavailable or declares an unsupported
711    /// domain.
712    #[error("capability projection is incomplete or declares unsupported domain(s)")]
713    IncompleteCapability,
714    /// `document.assets.source_skeleton` does not declare complete coverage.
715    #[error(
716        "document.assets.source_skeleton coverage is not complete: rest/bind planning requires a format-neutral source-node/source-skin projection"
717    )]
718    IncompleteSourceSkeleton,
719    /// A selected root, selected skin joint, or terminal affected source row
720    /// did not normalize to a document skeleton bone. Unprojected rows are
721    /// otherwise accepted only when they are strict connectors between
722    /// projected rows.
723    #[error("source node {source_node_index} did not normalize to a document skeleton bone")]
724    SourceNodeNotNormalized {
725        /// The unnormalized source-node index.
726        source_node_index: usize,
727    },
728    /// A raw source-node rest transform is non-finite.
729    #[error("source node {source_node_index} has a non-finite raw rest transform")]
730    NonFiniteSourceTransform {
731        /// The source node with the non-finite transform.
732        source_node_index: usize,
733    },
734    /// A transform composed during scale planning, candidate construction,
735    /// or proof is non-finite. Entry-time skeleton rest failures are reported
736    /// through [`ScaleError::InvalidDocumentShape`].
737    #[error("node {node} has a non-finite rest transform")]
738    NonFiniteTransform {
739        /// The node with the non-finite transform.
740        node: BoneId,
741    },
742    /// A runtime scale walk encountered a parent that cannot be resolved.
743    /// Entry-time skeleton topology failures are reported through
744    /// [`ScaleError::InvalidDocumentShape`].
745    #[error("node {node} has invalid parent {parent}")]
746    InvalidParent {
747        /// The node with an invalid parent.
748        node: BoneId,
749        /// The invalid parent index.
750        parent: BoneId,
751    },
752    /// A plan or document reference a bone index outside
753    /// `document.skeleton.bones` for the document actually supplied.
754    ///
755    /// This guards every boundary where a [`ScalePlan`] built from one
756    /// document could be replayed against a different one: [`ScalePlan`]
757    /// has no public constructor other than [`plan_scale`], but
758    /// reference candidate construction and [`prove_scale`] each take the
759    /// document to operate on as a separate argument and must not trust that
760    /// it still matches the plan's shape.
761    #[error("bone index {index} is out of range for this document")]
762    BoneIndexOutOfRange {
763        /// The out-of-range index.
764        index: usize,
765    },
766    /// A plan replayed against a document derives a different write or proof
767    /// inventory than it did when planned.
768    ///
769    /// Plans may be reused across numerically different documents, but only
770    /// while re-deriving the supplied source's structural planning inventory
771    /// selects the same complete domain. Otherwise a stale affected-node list
772    /// or evidence flag could leave newly introduced payload outside every
773    /// proof walk.
774    #[error("plan does not describe the supplied document: {reason}")]
775    PlanDocumentMismatch {
776        /// Stable machine-readable mismatch kind.
777        reason: &'static str,
778    },
779    /// The affected closure could not be completed.
780    #[error("affected domain closure is not complete: {reason}")]
781    IncompleteClosure {
782        /// Stable machine-readable reason.
783        reason: &'static str,
784    },
785    /// Unskinned geometry is attached inside the affected closure.
786    #[error("node {node} carries unskinned geometry inside the affected closure")]
787    UnsupportedUnskinnedGeometry {
788        /// The node carrying unskinned geometry.
789        node: BoneId,
790    },
791    /// A node's rest-world linear part is outside the supported affine class.
792    #[error(
793        "node {node} rest-world linear part is not orientation-preserving positive uniform scale ({reason:?})"
794    )]
795    InvalidAffineDomain {
796        /// The rejected node.
797        node: BoneId,
798        /// Stable machine-readable violation kind.
799        reason: AffineDomainViolation,
800    },
801    /// The declared `expected_factor` does not match the source's observed
802    /// common factor.
803    #[error("declared expected factor {expected} does not match observed source factor {observed}")]
804    FactorMismatch {
805        /// Declared expected factor.
806        expected: f64,
807        /// Observed source factor.
808        observed: f64,
809    },
810    /// One node's effective factor differs from the domain's common factor.
811    #[error("node {node} effective factor {observed} differs from common factor {expected}")]
812    MixedFactor {
813        /// The domain's common factor.
814        expected: f64,
815        /// The node's observed factor.
816        observed: f64,
817        /// The node with the mismatched factor.
818        node: BoneId,
819    },
820    /// A proof residual exceeded the fixed tolerance policy.
821    #[error("proof residual {observed} for {kind:?} exceeds tolerance {tolerance}")]
822    ProofResidualExceeded {
823        /// Which proof obligation failed.
824        kind: ProofResidualKind,
825        /// Observed residual.
826        observed: f64,
827        /// Tolerance the residual exceeded.
828        tolerance: f64,
829    },
830    /// The document's sampled proof work exceeds
831    /// [`ScaleTolerancePolicy::proof_sample_work_budget`].
832    ///
833    /// Raised by [`prove_scale`] *before* any sample time is evaluated, so a
834    /// document whose key count and vertex count multiply out beyond the
835    /// versioned policy's budget is refused outright rather than proved
836    /// against a silently truncated subset of its sample times. The budget is
837    /// a property of the policy identity recorded in evidence, not a per-run
838    /// flag.
839    #[error(
840        "proof sampling work {work} ({sample_times} sample times x {per_sample_cost} work units) exceeds the {policy_id} budget {budget}"
841    )]
842    ProofSamplingBudgetExceeded {
843        /// The tolerance-policy identity whose budget was exceeded.
844        policy_id: &'static str,
845        /// Distinct sample times the plan's obligations would evaluate,
846        /// summed over every clip.
847        sample_times: u64,
848        /// Work units one sample time costs: `bone_count` plus the vertex
849        /// count of every skinned instance inside the affected closure.
850        per_sample_cost: u64,
851        /// `sample_times * per_sample_cost`, saturating.
852        work: u64,
853        /// The policy's [`ScaleTolerancePolicy::proof_sample_work_budget`].
854        budget: u64,
855    },
856    /// The plan's typed obligation ledger declared a claim provable, but
857    /// [`prove_scale`] could not find the evidence to check it (for example
858    /// a clip or track present in `source` with no counterpart in
859    /// `candidate`). This is a distinct failure from
860    /// [`ScaleError::ProofResidualExceeded`]: the claim was never checked at
861    /// all, so proof must fail rather than silently report a zero residual.
862    #[error("proof obligation {kind:?} could not find expected evidence ({detail})")]
863    MissingProofEvidence {
864        /// Which proof obligation was left unchecked.
865        kind: ProofResidualKind,
866        /// Stable machine-readable reason.
867        detail: &'static str,
868    },
869    /// The shared model shape required by strict mutating operations is
870    /// malformed. [`Document`] is publicly mutable, so planning, building,
871    /// and proof validate each supplied snapshot independently.
872    #[error(transparent)]
873    InvalidDocumentShape(#[from] DocumentShapeError),
874    /// No inverse-bind evidence exists for a skin joint: the owning mesh
875    /// instance declares an empty `skin_ibms` (falling back to the bone's
876    /// own [`crate::model::Bone::inverse_bind`]) and that bone also has no
877    /// inverse-bind matrix. Identity is never substituted for genuinely
878    /// missing evidence — only for a source skin whose complete-coverage
879    /// [`crate::model::SourceSkinAsset::inverse_bind_accessor`] proves the
880    /// format-defined identity default with
881    /// [`crate::model::SourceInverseBindAccessorStatus::Absent`] (checked
882    /// internally by this module's private inverse-bind resolution).
883    #[error("no inverse-bind evidence for skin joint {node}")]
884    MissingInverseBind {
885        /// The joint with no inverse-bind evidence.
886        node: BoneId,
887    },
888    /// A mesh primitive is malformed independently of any skin: a non-finite
889    /// base `POSITION`.
890    ///
891    /// Checked at every public entry point, on the candidate as well as the
892    /// input, because base `POSITION` is a rewritten domain: without it a
893    /// whole-document build with an overflowing factor returns a document
894    /// full of non-finite vertices as `Ok`.
895    #[error("mesh {mesh_index} primitive {primitive_index} is invalid ({reason})")]
896    InvalidMeshPrimitive {
897        /// Index into `document.assets.meshes` of the offending mesh.
898        mesh_index: usize,
899        /// Index into that mesh's `primitives` of the offending primitive.
900        primitive_index: usize,
901        /// Stable machine-readable reason.
902        reason: &'static str,
903    },
904    /// A primary skin-weight attribute contains a finite negative value.
905    ///
906    /// Skin weights are coefficients of a convex blend, never signed affine
907    /// coefficients. Refusing this at the shared scale-input boundary keeps
908    /// planning, candidate construction, and proof on that one semantic
909    /// domain and gives evidence consumers a stable kind without requiring
910    /// them to parse a [`ScaleError::InvalidMeshPrimitive`] reason string.
911    #[error(
912        "mesh {mesh_index} primitive {primitive_index} vertex {vertex_index} primary skin influence {influence_index} has a negative weight"
913    )]
914    NegativeSkinWeight {
915        /// Index into `document.assets.meshes`.
916        mesh_index: usize,
917        /// Index into that mesh's `primitives`.
918        primitive_index: usize,
919        /// Vertex carrying the rejected weight tuple.
920        vertex_index: usize,
921        /// Component within the primary four-influence tuple.
922        influence_index: usize,
923    },
924    /// A skinned primitive is malformed: `joints`/`weights` shorter than
925    /// `positions`, a non-finite position or weight, a joint-influence slot
926    /// outside the owning instance's `skin_joints`, or a skinned result that
927    /// is not finite.
928    ///
929    /// The last case reports two distinct `reason`s. A skinned position that
930    /// left the `f32` range is `"skinned_magnitude_overflow"`: the document's
931    /// geometry does not fit the arithmetic this proof runs in. A `NaN` is
932    /// `"non_finite_result"`: an input that survived every finiteness check
933    /// above is degenerate in some other way. Both fail closed; neither is
934    /// bounded by a magnitude domain, because skinning accumulates a dot
935    /// product per axis and where that overflows depends on the rotation
936    /// rather than on the magnitude of the result.
937    #[error("instance {instance_index} primitive {primitive_index} is invalid ({reason})")]
938    InvalidSkinnedPrimitive {
939        /// Index into `document.assets.instances` of the owning instance.
940        instance_index: usize,
941        /// Index into the owning mesh's `primitives` of the offending
942        /// primitive.
943        primitive_index: usize,
944        /// Stable machine-readable reason.
945        reason: &'static str,
946    },
947    /// `candidate`'s skeleton/source-projection, clip/track/instance/mesh/
948    /// primitive structure does not match `source`'s, or an exact unchanged
949    /// semantic value differs. This includes a changed parent or source-node
950    /// projection, a changed world-rest affine outside a rest/bind closure, a
951    /// missing or extra clip, track, instance, mesh, or primitive, a track
952    /// whose identity, interpolation, times, or value shape disagrees with
953    /// its source counterpart, or a mesh instance whose identity — the node
954    /// it hangs off, the source node it came from, the mesh it draws, or the
955    /// joints it binds — disagrees with its source counterpart. Proof pairs
956    /// source and candidate structure by identity or index, which requires
957    /// this parity to hold. For rest/bind this also covers an admitted static
958    /// connector local that changed bits or a projected successor whose raw
959    /// local is not the independently derived bridged rebase. An extra,
960    /// missing, re-parented, relocated, or otherwise rewritten unchanged
961    /// value is never silently ignored.
962    #[error("candidate document structure does not match source ({reason})")]
963    CandidateStructureMismatch {
964        /// Stable machine-readable reason.
965        reason: &'static str,
966    },
967}
968
969/// Which proof obligation produced a [`ScaleError::ProofResidualExceeded`]
970/// or [`ScaleError::MissingProofEvidence`].
971#[derive(Debug, Clone, Copy, PartialEq, Eq)]
972#[non_exhaustive]
973pub enum ProofResidualKind {
974    /// Rest-world translation residual.
975    RestTranslation,
976    /// Rest-world rotation residual.
977    RestRotation,
978    /// Postcondition unit-scale residual.
979    UnitScale,
980    /// Transform-only attachment full-affine residual (an off-origin point
981    /// transformed through the expected and actual world matrix), per
982    /// DESIGN.md Appendix D §D.2/§D.6.
983    TransformOnlyAffine,
984    /// Per-element animation-track value residual, checked directly against
985    /// each domain's analytic expectation: a rewritten translation element
986    /// (value *or* cubic tangent) against `before * multiplier`, and every
987    /// retained rotation/scale element against `before` itself.
988    ///
989    /// Distinct from [`Self::KeyTranslation`], which samples the *composed*
990    /// track at key times: sampling proves what an evaluator would read, but
991    /// only a direct element comparison proves both that rewritten domains
992    /// received their declared multiplier and that domains this plan declares
993    /// untouched really are untouched.
994    TrackValue,
995    /// Base mesh `POSITION` residual, per vertex, against this operation's
996    /// analytic expectation (`before * q` for whole-document conversion,
997    /// `before` for rest/bind reparameterization).
998    MeshPosition,
999    /// Keyframe-time translation residual.
1000    KeyTranslation,
1001    /// Cubic-segment interior-time translation residual.
1002    CubicInterior,
1003    /// Sampled world-space trajectory residual.
1004    Trajectory,
1005    /// Skin-matrix (`W * B`) residual.
1006    SkinMatrix,
1007    /// Skinned mesh bounds residual.
1008    Bounds,
1009    /// Effective inverse-bind residual for a skin slot *outside* the affected
1010    /// closure — a skin neither operation touches, whose binds must therefore
1011    /// come through unchanged.
1012    ///
1013    /// Slots inside the closure are covered, more strongly, by
1014    /// [`Self::SkinMatrix`]: that obligation compares the composed `W * B`,
1015    /// which is what actually deforms a vertex. Outside the closure there is
1016    /// no rebase to compose against, so each slot is compared through the
1017    /// model's inverse-bind fallback chain.
1018    UnaffectedInverseBind,
1019    /// The factor [`prove_scale`] re-derived from the documents it was given.
1020    /// Only ever reported as [`ScaleError::MissingProofEvidence`]: it names a
1021    /// source whose scaled root the proof could not resolve, never a residual.
1022    ObservedFactor,
1023}
1024
1025// --- Plan --------------------------------------------------------------
1026
1027/// The structural semantic operation a rewritten field receives.
1028///
1029/// No variant stores a resolved factor or expected value. Candidate
1030/// construction and proof independently resolve the selected operation's
1031/// numeric arithmetic from the field identity and topology.
1032#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1033#[non_exhaustive]
1034pub enum ScaleRewriteRule {
1035    /// A whole-document linear-unit length field.
1036    WholeDocumentLength,
1037    /// A rest/bind field governed by the target node's parent-basis factor.
1038    RestBindParentBasis,
1039    /// A rest/bind field governed by the local `s_parent / s_node` rebase.
1040    RestBindLocalScale,
1041    /// A rest/bind inverse bind governed by its joint's node-basis factor.
1042    RestBindNodeBasis,
1043    /// A projected source-local rest, optionally bridged through connectors.
1044    RestBindSourceLocal {
1045        /// The immediate connector tail below the projected parent, if any.
1046        connector_tail: Option<usize>,
1047    },
1048}
1049
1050/// Whether a modeled field is preserved exactly or analytically rewritten.
1051#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1052#[non_exhaustive]
1053pub enum ScaleFieldDisposition {
1054    /// The field is outside the core builder's write set.
1055    ///
1056    /// This is ownership, not a universal normalized-artifact equality
1057    /// promise: format frontends may independently re-derive normalized
1058    /// bones, binds, tracks, or meshes within the established residual
1059    /// policy. Authored raw source-local fields copied by the core builder are
1060    /// additionally checked bit-exact by [`prove_scale`].
1061    PreserveExact,
1062    /// The field is in the write set and receives the stated semantic rule.
1063    Rewrite(ScaleRewriteRule),
1064}
1065
1066/// One normalized bone-rest field.
1067#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1068#[non_exhaustive]
1069pub enum ScaleBoneRestField {
1070    /// Local translation.
1071    Translation,
1072    /// Local rotation.
1073    Rotation,
1074    /// Local scale.
1075    Scale,
1076}
1077
1078/// One authored source-node rest field or component group.
1079#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1080#[non_exhaustive]
1081pub enum ScaleSourceRestField {
1082    /// TRS translation.
1083    Translation,
1084    /// TRS rotation.
1085    Rotation,
1086    /// TRS scale.
1087    Scale,
1088    /// Matrix linear columns.
1089    MatrixLinear,
1090    /// Matrix translation column.
1091    MatrixTranslation,
1092    /// Matrix homogeneous row.
1093    MatrixHomogeneous,
1094}
1095
1096/// The exact container-level target of one field disposition.
1097#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1098#[non_exhaustive]
1099pub enum ScaleFieldTarget {
1100    /// One normalized bone-rest field.
1101    BoneRest {
1102        /// Normalized bone identity.
1103        bone: BoneId,
1104        /// Rest field.
1105        field: ScaleBoneRestField,
1106    },
1107    /// One authored source-node rest field.
1108    SourceNodeRest {
1109        /// Raw source-node identity.
1110        source_node_index: usize,
1111        /// Rest field or component group.
1112        field: ScaleSourceRestField,
1113    },
1114    /// One animation track's stored values.
1115    AnimationValues {
1116        /// Clip position in the normalized document.
1117        clip_index: usize,
1118        /// Track position inside the clip.
1119        track_index: usize,
1120        /// Target normalized bone.
1121        bone: BoneId,
1122        /// Animated property.
1123        property: Property,
1124    },
1125    /// One bone convenience inverse bind.
1126    BoneInverseBind {
1127        /// Normalized bone identity.
1128        bone: BoneId,
1129    },
1130    /// One logical instance inverse-bind slot.
1131    InstanceInverseBind {
1132        /// Instance position in the normalized document.
1133        instance_index: usize,
1134        /// Slot position inside the instance skin.
1135        slot: usize,
1136        /// Joint named by the slot.
1137        joint: BoneId,
1138    },
1139    /// One primitive's complete base-position array.
1140    MeshPositions {
1141        /// Mesh position in the normalized document.
1142        mesh_index: usize,
1143        /// Primitive position inside the mesh.
1144        primitive_index: usize,
1145    },
1146    /// One primitive's preserved normal array.
1147    MeshNormals {
1148        /// Mesh position in the normalized document.
1149        mesh_index: usize,
1150        /// Primitive position inside the mesh.
1151        primitive_index: usize,
1152    },
1153}
1154
1155/// One exact semantic field row in a compiled scale plan.
1156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1157#[non_exhaustive]
1158pub struct ScaleFieldPlan {
1159    target: ScaleFieldTarget,
1160    disposition: ScaleFieldDisposition,
1161    element_count: usize,
1162}
1163
1164impl ScaleFieldPlan {
1165    /// The exact container-level field target.
1166    pub fn target(&self) -> ScaleFieldTarget {
1167        self.target
1168    }
1169
1170    /// Whether and how the target is rewritten.
1171    pub fn disposition(&self) -> ScaleFieldDisposition {
1172        self.disposition
1173    }
1174
1175    /// Number of stored elements covered by the container row.
1176    pub fn element_count(&self) -> usize {
1177        self.element_count
1178    }
1179}
1180
1181/// One numeric-value-free payload-shape row used by stale-plan replay.
1182///
1183/// Rows include empty containers and structural identities/counts, but never
1184/// key times or stored floating-point values, so intentional numeric replay
1185/// against an identically shaped document remains supported.
1186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1187#[non_exhaustive]
1188pub enum ScalePayloadShapeRow {
1189    /// Top-level normalized collection counts.
1190    Document {
1191        /// Skeleton bone count.
1192        bone_count: usize,
1193        /// Authoritative source-skeleton node count; zero under unavailable
1194        /// coverage.
1195        source_node_count: usize,
1196        /// Whether the source projection claims complete coverage.
1197        source_coverage: SourceSkeletonCoverage,
1198        /// Clip count.
1199        clip_count: usize,
1200        /// Mesh-instance count.
1201        instance_count: usize,
1202        /// Mesh count.
1203        mesh_count: usize,
1204    },
1205    /// One normalized topology row.
1206    Bone {
1207        /// Normalized bone identity.
1208        bone: BoneId,
1209        /// Normalized parent identity.
1210        parent: Option<BoneId>,
1211    },
1212    /// One source skin's complete structural inventory.
1213    SourceSkin {
1214        /// Raw source-skin identity.
1215        source_skin_index: usize,
1216        /// Explicit source skeleton root.
1217        skeleton_root_source_node_index: Option<usize>,
1218        /// Declared joint count.
1219        joint_count: usize,
1220        /// Attachment count.
1221        attachment_count: usize,
1222        /// Inverse-bind accessor status.
1223        inverse_bind_status: SourceInverseBindAccessorStatus,
1224        /// Declared inverse-bind accessor count.
1225        inverse_bind_declared_count: Option<usize>,
1226        /// Number of readable matrices retained.
1227        inverse_bind_matrix_count: usize,
1228    },
1229    /// One ordered source-skin joint identity.
1230    SourceSkinJoint {
1231        /// Raw source-skin identity.
1232        source_skin_index: usize,
1233        /// Joint slot.
1234        slot: usize,
1235        /// Raw source-node identity.
1236        source_node_index: usize,
1237    },
1238    /// One ordered source-skin attachment identity.
1239    SourceSkinAttachment {
1240        /// Raw source-skin identity.
1241        source_skin_index: usize,
1242        /// Attachment position.
1243        attachment_index: usize,
1244        /// Raw attachment node identity.
1245        source_node_index: usize,
1246        /// Raw mesh identity, when declared.
1247        source_mesh_index: Option<usize>,
1248    },
1249    /// One clip, including an empty clip.
1250    Clip {
1251        /// Clip position.
1252        clip_index: usize,
1253        /// Track count.
1254        track_count: usize,
1255    },
1256    /// One track's structural identity and arities.
1257    Track {
1258        /// Clip position.
1259        clip_index: usize,
1260        /// Track position.
1261        track_index: usize,
1262        /// Target bone.
1263        bone: BoneId,
1264        /// Animated property.
1265        property: Property,
1266        /// Interpolation mode.
1267        interpolation: Interpolation,
1268        /// Number of key times, without storing their numeric values.
1269        key_count: usize,
1270        /// Number of stored value elements.
1271        value_count: usize,
1272    },
1273    /// One mesh instance, including an unskinned instance.
1274    Instance {
1275        /// Instance position.
1276        instance_index: usize,
1277        /// Normalized attachment node.
1278        node: BoneId,
1279        /// Raw source-node attachment identity.
1280        source_node_index: usize,
1281        /// Mesh identity.
1282        mesh: usize,
1283        /// Logical joint-slot count.
1284        joint_count: usize,
1285        /// Stored instance inverse-bind count.
1286        inverse_bind_count: usize,
1287    },
1288    /// One logical joint slot, preserving slot order and identity.
1289    InstanceJoint {
1290        /// Instance position.
1291        instance_index: usize,
1292        /// Slot position.
1293        slot: usize,
1294        /// Joint identity.
1295        joint: BoneId,
1296    },
1297    /// One mesh, including an empty mesh.
1298    Mesh {
1299        /// Mesh position.
1300        mesh_index: usize,
1301        /// Stable source mesh identity.
1302        source_mesh_index: usize,
1303        /// Primitive count.
1304        primitive_count: usize,
1305    },
1306    /// One primitive's modeled shape.
1307    Primitive {
1308        /// Mesh position.
1309        mesh_index: usize,
1310        /// Primitive position.
1311        primitive_index: usize,
1312        /// Base-position count.
1313        position_count: usize,
1314        /// Preserved normal count.
1315        normal_count: usize,
1316        /// Primary joint-tuple count read by skin/bounds proof.
1317        joint_count: usize,
1318        /// Primary weight-tuple count read by skin/bounds proof.
1319        weight_count: usize,
1320    },
1321}
1322
1323/// One typed proof claim kind derived from the plan's validated inventory.
1324///
1325/// Exact members are not duplicated here: inspect [`ScalePlan::affected_nodes`],
1326/// [`ScalePlan::transform_only_attachments`], and the field, payload, and
1327/// topology rows exposed by [`ScalePlan::ledger`].
1328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1329#[non_exhaustive]
1330pub enum ScaleProofObligation {
1331    /// Preserve normalized parents and complete source projection topology.
1332    ExactTopology,
1333    /// Preserve clip, track, instance, skin, mesh, and primitive identities.
1334    ExactPayloadIdentity,
1335    /// Preserve exact world rest for the nodes outside a rest/bind closure.
1336    ExactUnchangedWorldRest,
1337    /// Prove affected rest-world translation and orientation.
1338    RestWorld,
1339    /// Prove affected rest-world facts and the nested unit-scale postcondition.
1340    RestWorldAndUnitScale,
1341    /// Probe complete expected affines of transform-only attachments.
1342    TransformOnlyAffine,
1343    /// Compare all rewritten and preserved animation values.
1344    TrackValues,
1345    /// Compare all rewritten and preserved base positions.
1346    MeshPositions,
1347    /// Compare affected translation tracks at their key times.
1348    KeyTranslations,
1349    /// Compare affected translation tracks at bounded cubic interior times.
1350    CubicInteriors,
1351    /// Compare sampled world-space trajectories.
1352    Trajectories,
1353    /// Run the one shared affected-skin walk producing skin and bounds results.
1354    SkinAndBounds,
1355    /// Check rewritten inverse-bind slots.
1356    AffectedInverseBinds,
1357    /// Check preserved inverse-bind slots outside the closure.
1358    UnaffectedInverseBinds,
1359    /// Preserve connector locals and check bridged projected successors.
1360    ExactConnectorProjection,
1361}
1362
1363/// A projected source row's role in a rest/bind topology.
1364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1365#[non_exhaustive]
1366pub enum ScaleProjectedRole {
1367    /// Selected scaled root.
1368    Root,
1369    /// Selected skin joint other than the root.
1370    Joint,
1371    /// Affected non-joint attachment or path node.
1372    TransformOnly,
1373}
1374
1375/// The typed kind of one canonical rest/bind source-topology row.
1376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1377#[non_exhaustive]
1378pub enum ScaleSourceNodeKind {
1379    /// A source node projected into the normalized skeleton.
1380    Projected {
1381        /// Normalized bone identity.
1382        bone: BoneId,
1383        /// Root, joint, or transform-only role.
1384        role: ScaleProjectedRole,
1385        /// Nearest projected parent in source identity space.
1386        projected_parent: Option<usize>,
1387        /// Immediate connector tail below that projected parent, if any.
1388        incoming_connector_tail: Option<usize>,
1389    },
1390    /// A static unprojected connector preserved exactly.
1391    Connector,
1392    /// A source row outside a rest/bind domain, or any row in a
1393    /// whole-document plan where connector roles are not applicable.
1394    OutsideDomain {
1395        /// Normalized projection identity, if one exists.
1396        bone: Option<BoneId>,
1397    },
1398}
1399
1400/// One row in the canonical source-keyed rest/bind topology.
1401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1402#[non_exhaustive]
1403pub struct ScaleSourceTopologyRow {
1404    source_node_index: usize,
1405    parent_source_node_index: Option<usize>,
1406    kind: ScaleSourceNodeKind,
1407}
1408
1409#[derive(Debug, Clone, PartialEq, Eq)]
1410struct ScaleLedger {
1411    field_rows: Vec<ScaleFieldPlan>,
1412    payload_shapes: Vec<ScalePayloadShapeRow>,
1413    obligations: Vec<ScaleProofObligation>,
1414}
1415
1416#[derive(Debug, Clone, PartialEq)]
1417struct WholeDocumentParams {
1418    factor: f64,
1419}
1420
1421#[derive(Debug, Clone, PartialEq)]
1422struct RestBindParams {
1423    source_skin_index: usize,
1424    source_root_node_index: usize,
1425    expected_factor: f64,
1426    transform_only_attachments: Vec<BoneId>,
1427}
1428
1429#[derive(Debug, Clone, PartialEq)]
1430enum ScaleCompiledPlan {
1431    WholeDocument(WholeDocumentParams),
1432    RestBind(RestBindParams),
1433}
1434
1435/// Read-only view of one compiled plan's exact domain, field, topology, and
1436/// proof-obligation ledger.
1437///
1438/// The view has no constructor and cannot be converted back into a
1439/// [`ScalePlan`]; only [`plan_scale`] can compile an authoritative ledger.
1440#[derive(Debug, Clone, Copy)]
1441pub struct ScalePlanLedger<'a> {
1442    plan: &'a ScalePlan,
1443}
1444
1445impl<'a> ScalePlanLedger<'a> {
1446    fn ledger(self) -> &'a ScaleLedger {
1447        &self.plan.ledger
1448    }
1449
1450    /// Exact container-level modeled field rows in deterministic source order.
1451    pub fn field_rows(self) -> std::slice::Iter<'a, ScaleFieldPlan> {
1452        self.ledger().field_rows.iter()
1453    }
1454
1455    /// Numeric-value-free payload-shape rows, including empty containers.
1456    pub fn payload_shapes(self) -> std::slice::Iter<'a, ScalePayloadShapeRow> {
1457        self.ledger().payload_shapes.iter()
1458    }
1459
1460    /// Typed proof obligations derived from the same field and payload inventory.
1461    pub fn obligations(self) -> std::slice::Iter<'a, ScaleProofObligation> {
1462        self.ledger().obligations.iter()
1463    }
1464
1465    /// Canonical source-keyed topology for the complete modeled projection.
1466    pub fn source_topology(self) -> std::slice::Iter<'a, ScaleSourceTopologyRow> {
1467        self.plan.source_topology.iter()
1468    }
1469}
1470
1471impl ScaleSourceTopologyRow {
1472    /// Raw source-node identity.
1473    pub fn source_node_index(&self) -> usize {
1474        self.source_node_index
1475    }
1476
1477    /// Authoritative raw parent identity.
1478    pub fn parent_source_node_index(&self) -> Option<usize> {
1479        self.parent_source_node_index
1480    }
1481
1482    /// Whether this row is projected or is a preserved connector.
1483    pub fn kind(&self) -> ScaleSourceNodeKind {
1484        self.kind
1485    }
1486}
1487
1488/// Pure, typed plan returned by [`plan_scale`].
1489///
1490/// Planning never mutates its input document; it only inspects it. Reference
1491/// candidate construction from an accepted plan is a distinct, separately
1492/// fallible fixture step.
1493///
1494/// Every field is private: a [`ScalePlan`] can only be produced by
1495/// [`plan_scale`], so an external caller cannot hand-construct or mutate one
1496/// into a state whose `affected_nodes` disagree with `operation`'s
1497/// selectors. Read plan contents through the accessor methods.
1498#[derive(Debug, Clone, PartialEq)]
1499#[non_exhaustive]
1500pub struct ScalePlan {
1501    tolerance_policy: ScaleTolerancePolicy,
1502    observed_factor: f64,
1503    affected_nodes: Vec<BoneId>,
1504    source_topology: Vec<ScaleSourceTopologyRow>,
1505    ledger: ScaleLedger,
1506    compiled: ScaleCompiledPlan,
1507}
1508
1509impl ScalePlan {
1510    /// Echoed operation and its declared parameters.
1511    pub fn operation(&self) -> ScaleOperation {
1512        match &self.compiled {
1513            ScaleCompiledPlan::WholeDocument(plan) => ScaleOperation::WholeDocumentLinearUnits {
1514                factor: plan.factor,
1515            },
1516            ScaleCompiledPlan::RestBind(plan) => ScaleOperation::RestBindUniformScale {
1517                source_skin_index: plan.source_skin_index,
1518                source_root_node_index: plan.source_root_node_index,
1519                expected_factor: plan.expected_factor,
1520            },
1521        }
1522    }
1523
1524    /// The fixed tolerance policy this plan and its proof share.
1525    pub fn tolerance_policy(&self) -> ScaleTolerancePolicy {
1526        self.tolerance_policy
1527    }
1528
1529    /// Affected normalized-node closure, in ascending bone-id order.
1530    ///
1531    /// For [`ScaleOperation::WholeDocumentLinearUnits`] this is every node
1532    /// in the document. For [`ScaleOperation::RestBindUniformScale`] this is
1533    /// the closed connected hierarchy of DESIGN.md Appendix D §D.2: the
1534    /// scaled ancestor, every selected skin joint and the normalized paths
1535    /// between them, and every descendant transform-only attachment. Raw
1536    /// source-only connector rows on those paths are not normalized nodes
1537    /// and therefore do not appear in this list.
1538    pub fn affected_nodes(&self) -> &[BoneId] {
1539        &self.affected_nodes
1540    }
1541
1542    /// Descendant nodes in [`Self::affected_nodes`] that carry no skin —
1543    /// the "transform-only child" case of DESIGN.md Appendix D §D.2/§D.3.
1544    /// Always empty for [`ScaleOperation::WholeDocumentLinearUnits`].
1545    pub fn transform_only_attachments(&self) -> &[BoneId] {
1546        match &self.compiled {
1547            ScaleCompiledPlan::WholeDocument(_) => &[],
1548            ScaleCompiledPlan::RestBind(plan) => &plan.transform_only_attachments,
1549        }
1550    }
1551
1552    /// The one common factor `s` (or `q` for whole-document conversion)
1553    /// applied across [`Self::affected_nodes`].
1554    ///
1555    /// This is always the factor the *caller declared*, never the one
1556    /// measured from the source: reference construction applies exactly this
1557    /// value, and [`prove_scale`] states every analytic expectation in terms
1558    /// of it. [`Self::observed_factor`] reports the measured
1559    /// counterpart, and the two are separate numbers on purpose — DESIGN.md
1560    /// Appendix D §D.6 requires producer evidence to record both.
1561    pub fn common_factor(&self) -> f64 {
1562        match &self.compiled {
1563            ScaleCompiledPlan::WholeDocument(plan) => plan.factor,
1564            ScaleCompiledPlan::RestBind(plan) => plan.expected_factor,
1565        }
1566    }
1567
1568    /// The factor this plan *observed* in the source, as distinct from the
1569    /// caller-declared [`Self::common_factor`] the build applies.
1570    ///
1571    /// For [`ScaleOperation::RestBindUniformScale`] this is the rest-world
1572    /// uniform factor measured at the scaled root of DESIGN.md Appendix D
1573    /// §D.2 — the average of its rest-world linear part's three column
1574    /// lengths, the same quantity the domain classification returns. It is
1575    /// within [`ScaleTolerancePolicy::common_factor`] of
1576    /// [`Self::common_factor`] (planning rejects it otherwise with
1577    /// [`ScaleError::FactorMismatch`]) but is generally not equal to it: a
1578    /// source authored at `0.010_000_02` is accepted against a declared
1579    /// `0.01`, and both numbers belong in evidence.
1580    ///
1581    /// For [`ScaleOperation::WholeDocumentLinearUnits`] this equals
1582    /// [`Self::common_factor`] exactly, because there is nothing to measure.
1583    /// That operation's factor is *declared*, not observed: §D.1 states that
1584    /// a whole-document conversion "changes physical size", is "appropriate
1585    /// only when the source was authored in a different linear unit", and
1586    /// that neither operation "may infer its factor or applicability from
1587    /// mesh bounds, character height, joint lengths, inverse-bind magnitude,
1588    /// filename, or an asset category". A source authored in centimetres and
1589    /// one authored in metres are numerically identical documents, so no
1590    /// measurement of either could distinguish them; the declared factor is
1591    /// the only fact there is, and reporting it here keeps the evidence
1592    /// contract uniform across the two operations rather than leaving a hole
1593    /// a consumer would have to special-case.
1594    pub fn observed_factor(&self) -> f64 {
1595        self.observed_factor
1596    }
1597
1598    /// Validate this plan's complete structural inventory against `document`.
1599    ///
1600    /// This re-derives and exactly compares the affected domain, canonical
1601    /// source topology, transform-only attachments, payload shapes, field
1602    /// dispositions, and proof obligations. Numeric source values are not
1603    /// compared, so a document with the same structural ledger remains a
1604    /// valid replay source, but the replay document must still satisfy the
1605    /// finite-value and nonnegative-weight scale-input requirements.
1606    ///
1607    /// # Errors
1608    ///
1609    /// Returns [`ScaleError::PlanDocumentMismatch`] when the re-derived
1610    /// inventory differs, or the corresponding planning/input error when
1611    /// `document` cannot produce a valid inventory for this operation.
1612    pub fn validate_document_inventory(&self, document: &Document) -> Result<(), ScaleError> {
1613        validate_plan_document_inventory(document, self)
1614    }
1615
1616    /// Inspect the exact read-only topology, field, and obligation ledger.
1617    pub fn ledger(&self) -> ScalePlanLedger<'_> {
1618        ScalePlanLedger { plan: self }
1619    }
1620
1621    /// Resolve the effective multiplier for one animation track's stored
1622    /// values from this compiled plan.
1623    ///
1624    /// This is the assembly compatibility boundary from Appendix D §D.5: a
1625    /// producer can fingerprint the exact target-basis factor without
1626    /// reproducing rest/bind arithmetic outside the shared plan. Values and
1627    /// CUBICSPLINE tangents use the same multiplier because both occupy the
1628    /// track's one typed field row.
1629    ///
1630    /// # Errors
1631    ///
1632    /// Returns [`ScaleError::PlanDocumentMismatch`] when the document or
1633    /// requested track no longer matches the compiled ledger.
1634    pub fn animation_value_factor(
1635        &self,
1636        document: &Document,
1637        clip_index: usize,
1638        track_index: usize,
1639    ) -> Result<f64, ScaleError> {
1640        validate_plan_document_inventory(document, self)?;
1641        let row = self
1642            .field_rows()
1643            .iter()
1644            .find(|row| {
1645                matches!(
1646                    row.target(),
1647                    ScaleFieldTarget::AnimationValues {
1648                        clip_index: candidate_clip,
1649                        track_index: candidate_track,
1650                        ..
1651                    } if candidate_clip == clip_index && candidate_track == track_index
1652                )
1653            })
1654            .ok_or(ScaleError::PlanDocumentMismatch {
1655                reason: "compiled_animation_row_missing",
1656            })?;
1657        let ScaleFieldTarget::AnimationValues { bone, property, .. } = row.target() else {
1658            unreachable!("the selected row is an animation row")
1659        };
1660        self.animation_target_factor_unchecked(document, bone, property)
1661    }
1662
1663    /// Resolve the effective multiplier for an animation target basis.
1664    ///
1665    /// Unlike [`Self::animation_value_factor`], this accepts a semantic target
1666    /// rather than an existing track row. Character assembly uses it to
1667    /// compare a base skeleton with independently supplied clip files before
1668    /// any channel is copied or remapped. All factor arithmetic remains owned
1669    /// by the compiled plan.
1670    ///
1671    /// # Errors
1672    ///
1673    /// Returns [`ScaleError::PlanDocumentMismatch`] when `document` no longer
1674    /// matches the plan or the target is outside its skeleton.
1675    pub fn animation_target_factor(
1676        &self,
1677        document: &Document,
1678        bone: BoneId,
1679        property: Property,
1680    ) -> Result<f64, ScaleError> {
1681        validate_plan_document_inventory(document, self)?;
1682        self.animation_target_factor_unchecked(document, bone, property)
1683    }
1684
1685    pub(in crate::scale) fn animation_target_factor_unchecked(
1686        &self,
1687        document: &Document,
1688        bone: BoneId,
1689        property: Property,
1690    ) -> Result<f64, ScaleError> {
1691        let affected = self.affected_set();
1692        let node_factor = if affected.contains(&bone) {
1693            self.common_factor()
1694        } else {
1695            1.0
1696        };
1697        let parent_factor = document
1698            .skeleton
1699            .bones
1700            .get(bone)
1701            .ok_or(ScaleError::BoneIndexOutOfRange { index: bone })?
1702            .parent
1703            .filter(|parent| affected.contains(parent))
1704            .map_or(1.0, |_| self.common_factor());
1705        Ok(match (self.operation(), property) {
1706            (ScaleOperation::WholeDocumentLinearUnits { .. }, Property::Translation) => {
1707                self.common_factor()
1708            }
1709            (ScaleOperation::WholeDocumentLinearUnits { .. }, _) => 1.0,
1710            (ScaleOperation::RestBindUniformScale { .. }, Property::Translation) => parent_factor,
1711            (ScaleOperation::RestBindUniformScale { .. }, Property::Scale) => {
1712                parent_factor / node_factor
1713            }
1714            (ScaleOperation::RestBindUniformScale { .. }, Property::Rotation) => 1.0,
1715        })
1716    }
1717
1718    fn affected_set(&self) -> BTreeSet<BoneId> {
1719        self.affected_nodes().iter().copied().collect()
1720    }
1721
1722    fn field_rows(&self) -> &[ScaleFieldPlan] {
1723        &self.ledger.field_rows
1724    }
1725
1726    fn obligations(&self) -> &[ScaleProofObligation] {
1727        &self.ledger.obligations
1728    }
1729}
1730
1731#[cfg(test)]
1732mod tests;