Skip to main content

rlx_core/render/scenes/particles/
family.rs

1//! The attractor families and their projection bases — the ODE/map math,
2//! **GPU-free** (Plan 0061 Phase 6).
3//!
4//! Nothing here imports `wgpu`. That is the point of the split rather than a
5//! coincidence: which figure a family draws, and which plane it is viewed on, is
6//! arithmetic that a unit test can exercise without a device.
7
8// Hot-path panic-denial pragma (Plan 0002 Phase 2; render/ is scanned by the
9// hygiene guard).
10#![deny(
11    clippy::unwrap_used,
12    clippy::expect_used,
13    clippy::indexing_slicing,
14    clippy::panic,
15    clippy::unreachable
16)]
17
18// A continuation of one module split across four files, so it needs the names
19// `particles/mod.rs` has in scope.
20use super::*;
21
22/// Which strange-attractor map the compute step iterates. Selected data-driven
23/// via the optional `[particles]` config table (ADR-0007 `configure` hook); the
24/// default is De Jong. Extend as follow-up plans add maps; unknown names are
25/// rejected at load.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum AttractorFamily {
28    /// De Jong — a 2D discrete map, bounded in ~[-2, 2].
29    DeJong,
30    /// Clifford — a 2D discrete map, bounded in ~[-2, 2].
31    Clifford,
32    /// Thomas — a 3D cyclically-symmetric continuous flow.
33    Thomas,
34    /// Lorenz — the 3D convection flow (the butterfly), projected to 2D.
35    Lorenz,
36    /// An iterated function system (ADR-0075) — **not** a strange attractor: four
37    /// affine maps, one drawn at random per particle per step. The figure it
38    /// converges onto is the carried [`IfsFigure`]; see [`ifs`] for why the
39    /// parameterization is the interesting half.
40    Ifs(IfsFigure),
41}
42
43impl AttractorFamily {
44    /// The four **map** families, in roster order. The IFS arm is not listed
45    /// here because it is `IfsFigure::ALL` — one roster, reached through the
46    /// type that owns it, so the schema export renders both without a copy of
47    /// either.
48    pub const MAPS: [AttractorFamily; 4] = [
49        AttractorFamily::DeJong,
50        AttractorFamily::Clifford,
51        AttractorFamily::Thomas,
52        AttractorFamily::Lorenz,
53    ];
54
55    /// Parse a `[particles] family` name, or `None` if unknown.
56    ///
57    /// The IFS figures sit in the **same** namespace as the map families rather
58    /// than behind a `family = "ifs"` + `figure = "fern"` pair: a preset picks
59    /// one figure, the way it picks one map today, and `morph_to` names the other
60    /// end out of the identical vocabulary.
61    pub fn from_name(name: &str) -> Option<Self> {
62        Some(match name {
63            "de_jong" => AttractorFamily::DeJong,
64            "clifford" => AttractorFamily::Clifford,
65            "thomas" => AttractorFamily::Thomas,
66            "lorenz" => AttractorFamily::Lorenz,
67            _ => AttractorFamily::Ifs(IfsFigure::from_name(name)?),
68        })
69    }
70
71    /// The `[particles] family` name this parses from —
72    /// [`from_name`](Self::from_name)'s inverse.
73    pub fn as_str(self) -> &'static str {
74        match self {
75            AttractorFamily::DeJong => "de_jong",
76            AttractorFamily::Clifford => "clifford",
77            AttractorFamily::Thomas => "thomas",
78            AttractorFamily::Lorenz => "lorenz",
79            AttractorFamily::Ifs(figure) => figure.name(),
80        }
81    }
82
83    /// The IFS figure this family draws, or `None` for the four map families.
84    ///
85    /// The `if let` every IFS-only code path funnels through, so "is this an
86    /// IFS" is asked in one spelling.
87    pub(super) fn figure(self) -> Option<IfsFigure> {
88        match self {
89            AttractorFamily::Ifs(figure) => Some(figure),
90            _ => None,
91        }
92    }
93
94    /// The compute shader's family selector.
95    pub(super) fn shader_id(self) -> u32 {
96        match self {
97            AttractorFamily::DeJong => 0,
98            AttractorFamily::Clifford => 1,
99            AttractorFamily::Thomas => 2,
100            AttractorFamily::Lorenz => 3,
101            // Every figure is the same shader arm — the figure is data in the
102            // uniform's affine table, not a branch.
103            AttractorFamily::Ifs(_) => 4,
104        }
105    }
106
107    /// Default coefficients for the family — the meaning is family-specific
108    /// (discrete a,b,c,d; Lorenz sigma,rho,beta; Thomas dissipation in `a`). A
109    /// preset's coefficient params modulate around these; unbound falls back here.
110    pub(super) fn default_coeffs(self) -> [f32; 4] {
111        match self {
112            AttractorFamily::DeJong => [1.641, 1.902, 0.316, 1.525],
113            AttractorFamily::Clifford => [-1.4, 1.6, 1.0, 0.7],
114            AttractorFamily::Thomas => [0.19, 0.0, 0.0, 0.0],
115            AttractorFamily::Lorenz => [10.0, 28.0, 2.6667, 0.0],
116            // An IFS's shape lives in its affine table, not in four scalars, so
117            // `a`..`d` are inert here — the family's own levers are Phase 5's.
118            AttractorFamily::Ifs(_) => [0.0, 0.0, 0.0, 0.0],
119        }
120    }
121
122    /// Which plane a 3D family is viewed in (ADR-0068).
123    ///
124    /// **Named outright per family, deliberately.** It is not derived from
125    /// [`canonical_framing`](Self::canonical_framing)'s `dim`, even though `dim == 3.0` selects
126    /// exactly the same two families today: `dim` and "wants a non-default basis"
127    /// agree on this roster of four and are not the same property, so keying one
128    /// off the other is ADR-0037's trap in another costume. A 2D family with a
129    /// preferred orientation, or a 3D family happy with x–y, would break the
130    /// coincidence silently. The match is exhaustive, so a fifth family has to
131    /// answer the question.
132    ///
133    /// Only the 3D branch of the draw shader reads it; the 2D families' value is
134    /// the default and is never consulted.
135    pub(super) fn basis(self) -> Basis {
136        match self {
137            AttractorFamily::DeJong
138            | AttractorFamily::Clifford
139            | AttractorFamily::Thomas
140            // The IFS family is `dim = 2` and takes the default. A 3-D IFS is a
141            // real thing and a separate decision (ADR-0075).
142            | AttractorFamily::Ifs(_) => Basis::XY,
143            // The butterfly lives in x–z. Seen x–y it is the two lobes edge-on —
144            // a hard X, which is the "dense core inside a diffuse cloud" this
145            // preset shipped as (ADR-0068).
146            AttractorFamily::Lorenz => Basis::XZ,
147        }
148    }
149
150    /// Whether this family's successive positions lie on **one trajectory**
151    /// (ADR-0069), so a segment drawn between them is a piece of that trajectory
152    /// rather than an invented chord.
153    ///
154    /// **Named per family, like [`basis`](Self::basis), and for the same reason.**
155    /// It agrees with `canonical_framing().projection.1 == 3.0` on today's roster of
156    /// four, and that
157    /// agreement is a **coincidence** — "is an ODE flow" and "is three
158    /// dimensional" are different properties. A 2-D flow would be continuous at
159    /// `dim == 2.0`, and a 3-D discrete map would be a 3-D family that must not
160    /// take the branch. Keying off `dim` is ADR-0037's trap in the costume
161    /// ADR-0068 Alternative C already declined once.
162    ///
163    /// The distinction is not cosmetic: a discrete map *replaces* its state each
164    /// iteration, so successive points are scattered across the whole figure and
165    /// a segment between them is a bright chord over the picture — meaningless
166    /// geometry, drawn brightly.
167    pub(super) fn is_continuous(self) -> bool {
168        match self {
169            // An IFS is the extreme case of the discrete argument below: a
170            // particle applies a *randomly chosen* map each step, so successive
171            // points jump right across the figure and a segment between them is
172            // a bright chord over the whole fern.
173            AttractorFamily::DeJong | AttractorFamily::Clifford | AttractorFamily::Ifs(_) => false,
174            AttractorFamily::Thomas | AttractorFamily::Lorenz => true,
175        }
176    }
177
178    /// The framing of roster entry 0 — the coefficients in
179    /// [`default_coeffs`](Self::default_coeffs) — as literal constants.
180    ///
181    /// **These are the numbers this scene shipped with**, and they are here as
182    /// literals rather than derived from anything: entry 0 *is* today's framing
183    /// by construction, which is what makes "an unbound `tuple` is byte-identical
184    /// to the build before the roster existed" structural rather than a claim
185    /// about two tables agreeing (ADR-0093). Every other roster entry is measured
186    /// — see [`measured_framing`].
187    ///
188    /// **`projection` is (world scale, dim 2/3, world centre to subtract).** The
189    /// scale fits the attractor's native extent into the frame; the centre is
190    /// what the projection pivots and frames on, and it is three components
191    /// rather than a z-centre (Plan 0062) — it was scalar while every family that
192    /// needed one was a 3D flow centred on the origin in `x` and `y`, and the
193    /// fern spans `y ∈ [0, 10]`. The four map families carry exactly the values
194    /// they carried before, `[0,0,0]` and `[0,0,25]`, and subtracting a zero is
195    /// exact, so no capture moves.
196    ///
197    /// **`seed_box` is the seeded initial-scatter box**, `(half-spread, centre)`
198    /// per axis, sized to the attractor's native extent so particles start spread
199    /// **across** it — a box too small for a chaotic flow leaves every particle
200    /// on nearly the same trajectory, so the cloud clumps instead of filling the
201    /// shape. The discrete 2D maps converge from any small box, so theirs is the
202    /// historical ~[-1.5, 1.5] (kept identical so their seeded look is unchanged;
203    /// `z` is unused there). It feeds the initial fill and a family change only
204    /// (ADR-0066) — a `reseed` does **not** re-fill it, see
205    /// [`Framing::jitter_extent`], because re-filling replaces the cloud with a
206    /// uniform axis-aligned rectangle, which reads as a wipe rather than a kick.
207    pub(super) fn canonical_framing(self) -> Framing {
208        match self {
209            AttractorFamily::DeJong | AttractorFamily::Clifford => Framing {
210                projection: (0.42, 2.0, [0.0, 0.0, 0.0]),
211                seed_box: ([1.5, 1.5, 1.5], [0.0, 0.0, 0.0]),
212            },
213            AttractorFamily::Thomas => Framing {
214                projection: (0.14, 3.0, [0.0, 0.0, 0.0]),
215                seed_box: ([4.5, 4.5, 4.5], [0.0, 0.0, 0.0]),
216            },
217            AttractorFamily::Lorenz => Framing {
218                projection: (0.022, 3.0, [0.0, 0.0, 25.0]),
219                seed_box: ([20.0, 26.0, 24.0], [0.0, 0.0, 25.0]),
220            },
221            AttractorFamily::Ifs(figure) => {
222                let (scale, centre) = figure.frame();
223                Framing {
224                    projection: (scale, 2.0, centre),
225                    // The figure's own bounding box, so the fill lands *over* the
226                    // attractor and contracts onto it — see [`IfsFigure::seed_box`].
227                    seed_box: figure.seed_box(),
228                }
229            }
230        }
231    }
232
233    /// The curated tuples **past entry 0** (ADR-0093), in roster order.
234    ///
235    /// Coefficients only: their framing is measured rather than written down, so
236    /// a curator adds a figure by adding the four numbers that define it and
237    /// nothing else. Entry 0 is deliberately absent from this table — it is
238    /// [`default_coeffs`](Self::default_coeffs) with
239    /// [`canonical_framing`](Self::canonical_framing), which is what keeps an
240    /// unbound `tuple` byte-identical to the build before this table existed.
241    ///
242    /// **Curated, and the curation kept everything** (Plan 0079 Phase 3,
243    /// 2026-08-13). This table was drafted as a candidate menu for the contact
244    /// sheets; the user judged all 50 entries *in motion in the app* — a sheet
245    /// freezes one instant of a rotating figure and several of these read
246    /// differently once they move — and kept every one. A four-per-family
247    /// shortlist was drafted and rejected, so the length is a verdict rather
248    /// than a default.
249    ///
250    /// The consequence for anyone editing this table: **an entry's index is a
251    /// preset-visible name.** The shipped `attractor_*gallery` presets step
252    /// through these by index, and a preset may pin one (`attractor_torusknot`
253    /// pins Lorenz entry 1), so inserting or reordering renames figures out from
254    /// under them. Append; do not insert.
255    ///
256    /// The map families' tuples are the gallery sets backlog 0055 cites; Thomas
257    /// is a sweep of its single dissipation coefficient across the chaotic band
258    /// and out the far side into its periodic windows; Lorenz walks `rho`
259    /// through the regimes above and below the canonical butterfly, plus three
260    /// tuples that move `sigma`/`beta` instead. Entry 1 on Lorenz is the
261    /// rho ≈ 100 torus knot Phase 1 shipped as the walking skeleton — the regime
262    /// Plan 0075 cohort 5 measured as physically unreachable, because the figure
263    /// is centred on `z ≈ 102` against the canonical framing's `25` and spans
264    /// twice its extent.
265    ///
266    /// **The IFS is empty and stays empty.** Its shape lives in an affine table
267    /// rather than in four scalars, and its figure-to-figure travel is ADR-0075's
268    /// `morph`, which already carries its own measured framing.
269    pub(super) fn extra_tuples(self) -> &'static [[f32; 4]] {
270        match self {
271            AttractorFamily::DeJong => &[
272                [-2.0, -2.0, -1.2, 2.0],
273                [-2.7, -0.09, -0.86, -2.2],
274                [1.4, -2.3, 2.4, -2.1],
275                [2.01, -2.53, 1.61, -0.33],
276                [1.5, -1.8, 1.6, 0.9],
277                [-0.827, -1.637, 1.659, -0.943],
278                [0.97, -1.899, 1.381, -1.506],
279                [-1.24, -1.25, -1.81, -1.9],
280                [-0.709, 1.638, 0.452, 1.74],
281                [-1.9, 1.7, 1.7, -1.4],
282                [1.7, 1.7, 0.6, 1.2],
283                [2.1, -1.9, 1.4, 1.1],
284            ],
285            AttractorFamily::Clifford => &[
286                [-1.7, 1.3, -0.1, -1.21],
287                [1.5, -1.8, 1.6, 0.9],
288                [-1.8, -2.0, -0.5, -0.9],
289                [1.7, 1.7, 0.6, 1.2],
290                [-1.7, 1.8, -1.9, -0.4],
291                [1.6, -0.6, -1.2, 1.6],
292                [1.1, -1.0, 1.0, 1.5],
293                [-1.9, 1.4, 1.9, 0.4],
294                [-1.3, -1.3, -1.8, -1.9],
295                [1.9, -1.9, -1.4, 1.2],
296                [-1.2, -1.9, 1.5, -0.8],
297                [-1.4, -1.5, 1.1, 1.4],
298            ],
299            // Thomas reads `a` alone, so its roster is a one-dimensional sweep:
300            // 0.05 is the space-filling end of the chaotic band, 0.208 is where
301            // the chaos gives way, and past it the flow closes into successively
302            // tighter periodic loops.
303            AttractorFamily::Thomas => &[
304                [0.03, 0.0, 0.0, 0.0],
305                [0.05, 0.0, 0.0, 0.0],
306                [0.07, 0.0, 0.0, 0.0],
307                [0.09, 0.0, 0.0, 0.0],
308                [0.11, 0.0, 0.0, 0.0],
309                [0.13, 0.0, 0.0, 0.0],
310                [0.15, 0.0, 0.0, 0.0],
311                [0.17, 0.0, 0.0, 0.0],
312                [0.20, 0.0, 0.0, 0.0],
313                [0.205, 0.0, 0.0, 0.0],
314                [0.208, 0.0, 0.0, 0.0],
315                [0.22, 0.0, 0.0, 0.0],
316            ],
317            AttractorFamily::Lorenz => &[
318                [10.0, 100.0, 2.6667, 0.0],
319                [10.0, 92.0, 2.6667, 0.0],
320                [10.0, 126.52, 2.6667, 0.0],
321                [10.0, 35.0, 2.6667, 0.0],
322                [10.0, 60.0, 2.6667, 0.0],
323                [10.0, 70.0, 2.6667, 0.0],
324                [10.0, 24.4, 2.6667, 0.0],
325                [16.0, 45.92, 4.0, 0.0],
326                [10.0, 28.0, 1.0, 0.0],
327                [14.0, 28.0, 2.6667, 0.0],
328                [10.0, 28.0, 4.0, 0.0],
329            ],
330            AttractorFamily::Ifs(_) => &[],
331        }
332    }
333}
334
335/// One roster entry's framing (ADR-0093): where the figure is and how big, as
336/// the two constants the render path needs.
337///
338/// **The unit that travels with a tuple.** Two per-family constants instead
339/// are exactly what makes a distant tuple unreachable: the coefficients are
340/// bindable and a per-family framing is not. Both derived quantities below
341/// hang off it, so `reseed` and the depth cues follow a tuple without a second
342/// table to keep in step — the Plan 0062 coupling, preserved by construction
343/// rather than by discipline.
344#[derive(Debug, Clone, Copy, PartialEq)]
345pub(super) struct Framing {
346    /// (world scale, dim 2/3, world centre) — see
347    /// [`AttractorFamily::projection`].
348    pub(super) projection: (f32, f32, [f32; 3]),
349    /// (half-spread, centre) per axis — see [`AttractorFamily::seed_box`].
350    pub(super) seed_box: ([f32; 3], [f32; 3]),
351}
352
353impl Framing {
354    /// Half-extent of the per-axis kick a `reseed` applies to each particle
355    /// **where it already is** (ADR-0066), in the family's own world units.
356    ///
357    /// Extent-relative by construction: it is [`JITTER_FRACTION`] of this
358    /// entry's own [`seed_box`](Self::seed_box), which is itself sized to the
359    /// figure's native extent. So one constant serves a map bounded in
360    /// `[-2, 2]`, a flow spanning `±26`, and a roster entry twice that — with no
361    /// per-entry number to keep in step. **This is the Plan 0062 coupling**, and
362    /// it is why the roster carries framing rather than coefficients alone: a
363    /// tuple whose framing did not travel with it would leave `reseed` kicking
364    /// by the canonical figure's fraction, which on a larger figure is a kick
365    /// too small to read and on a smaller one is a kick that throws the cloud
366    /// off the attractor.
367    ///
368    /// **The magnitude is a look constant with no principled value.** It is large
369    /// enough that the disturbance reads and small enough that the points stay on
370    /// the figure — a chaotic flow separates jittered neighbours within a few
371    /// iterations anyway, which is what makes a small kick sufficient. Plan 0057
372    /// Phase 6 is where it is judged in motion, at both tiers; ADR-0066 records
373    /// that if the disturbance reads too subtle, *this* is the lever and returning
374    /// to the box is not.
375    pub(super) fn jitter_extent(&self) -> [f32; 3] {
376        // Destructured rather than indexed: this file denies `indexing_slicing`.
377        let ([sx, sy, sz], _) = self.seed_box;
378        [
379            sx * JITTER_FRACTION,
380            sy * JITTER_FRACTION,
381            sz * JITTER_FRACTION,
382        ]
383    }
384
385    /// Reciprocal of this entry's half-extent along the **view depth axis**, in
386    /// the family's own world units — and **exactly `0.0` for a 2D family**
387    /// (ADR-0076).
388    ///
389    /// That zero is the whole mechanism by which the flat families opt out: it
390    /// makes `d_n` identically zero for every one of their particles, so the
391    /// perspective magnification is `1`, the haze multiplier is `1` and the hue
392    /// offset is `0`, with **no shader branch, no division and no way to reach a
393    /// `NaN`**. De Jong, Clifford and every IFS figure have no third coordinate
394    /// to project, and ADR-0076 Alternative B records why inventing one for them
395    /// is worse than leaving them alone.
396    ///
397    /// **Derived from [`seed_box`](Self::seed_box), not hand-written** — the
398    /// discipline [`jitter_extent`](Self::jitter_extent) already uses, so there
399    /// is no second table of magnitudes to keep in step. The depth is the
400    /// rotation's third output, and the rotation acts in the plane spanned by
401    /// `x` and the basis's horizontal axis ([`Basis::masks`]'s first selector),
402    /// so the depth swings through *those two* half-extents and the larger is
403    /// what normalizes it. That is **26** for the canonical Lorenz (basis XZ, so
404    /// the plane is `x`–`y`, half-extents 20 and 26) and **4.5** for Thomas
405    /// (basis XY, plane `x`–`z`).
406    ///
407    /// **The family is a parameter and not a field**, because flatness is a
408    /// property of the family rather than of the framing: the match below is
409    /// exhaustive with no wildcard arm, so a fifth family has to answer the
410    /// question rather than inherit an answer — and deriving it from
411    /// `projection.1 == 3.0` would be ADR-0037's trap in the costume
412    /// [`AttractorFamily::basis`] already declined once.
413    pub(super) fn inv_depth_extent(&self, family: AttractorFamily) -> f32 {
414        // Destructured rather than indexed: this file denies `indexing_slicing`.
415        let ([sx, sy, sz], _) = self.seed_box;
416        let half = match family {
417            // Every IFS figure is `dim = 2` — it has no third coordinate to
418            // project, which is exactly the case this doc comment anticipated.
419            AttractorFamily::DeJong | AttractorFamily::Clifford | AttractorFamily::Ifs(_) => {
420                return 0.0;
421            }
422            AttractorFamily::Thomas | AttractorFamily::Lorenz => {
423                // Read off `basis()` rather than restated per family, so the two
424                // cannot disagree about which plane the spin turns in.
425                let partner = match family.basis() {
426                    Basis::XY => sz,
427                    Basis::XZ => sy,
428                };
429                sx.max(partner)
430            }
431        };
432        // A degenerate box would otherwise send an infinity to the shader. It
433        // cannot happen with the canonical boxes; a measured entry makes it a
434        // live possibility rather than a theoretical one, and it costs one
435        // compare either way.
436        if half > 0.0 { 1.0 / half } else { 0.0 }
437    }
438}
439
440/// A roster entry with its framing resolved (ADR-0093) — what the render path
441/// actually reads once `tuple` has selected an entry.
442#[derive(Debug, Clone, Copy, PartialEq)]
443pub(super) struct ResolvedTuple {
444    /// The entry's coefficients, family-interpreted exactly as
445    /// [`AttractorFamily::default_coeffs`]'s are. They become the fallback the
446    /// `a`..`d` params modulate around, which is why selecting an entry changes
447    /// the figure at all.
448    pub(super) coeffs: [f32; 4],
449    pub(super) framing: Framing,
450}
451
452/// A roster entry: the resolved tuple, plus the on-attractor fill a **measured**
453/// entry carries.
454pub(super) struct RosterEntry {
455    pub(super) tuple: ResolvedTuple,
456    /// Points **on** this entry's own attractor, banked by the measurement while
457    /// it framed the figure — see [`MEASURE_BANK`].
458    ///
459    /// **Empty on the canonical entry**, which keeps the box fill it shipped
460    /// with. That is not an omission: entry 0's seeded scatter is what sixteen
461    /// golden baselines were blessed against, and a fill from anywhere else
462    /// would move every one of them.
463    pub(super) fill: Vec<[f32; 3]>,
464}
465
466/// A family's roster, framing and all — **built once at preset load**, off the
467/// hot path (ADR-0093).
468///
469/// Entry 0 is the canonical tuple with its pinned constants; every other entry
470/// is [`measured_framing`]. Resolved here rather than per frame for
471/// [`FitLut::build`](super::ifs::FitLut::build)'s reason: the framing is a pure
472/// function of the family and the tuple, so a frame that pays for it is paying
473/// repeatedly for an answer that cannot have changed — and a `tuple` cut would
474/// spend a measurement *inside the frame loop*, which is a visible hitch on the
475/// exact frame the figure is already changing.
476///
477/// **A measurement that fails falls back to the canonical framing rather than
478/// dropping the entry**, because an index is a preset-visible name: dropping
479/// entry 2 would silently renumber every entry after it. A diverged tuple is
480/// then visibly wrong on its contact sheet, which is where it gets rejected.
481pub(super) fn resolve_roster(family: AttractorFamily) -> Vec<RosterEntry> {
482    let canonical = ResolvedTuple {
483        coeffs: family.default_coeffs(),
484        framing: family.canonical_framing(),
485    };
486    let extras = family.extra_tuples();
487    if extras.is_empty() {
488        // Nothing to measure, so nothing is measured — which is what keeps the
489        // four one-entry families (and every IFS figure) paying literally zero
490        // for the roster at load.
491        return vec![RosterEntry {
492            tuple: canonical,
493            fill: Vec::new(),
494        }];
495    }
496    // The reference extent, measured **once per family** rather than once per
497    // entry: every entry is scaled against the canonical figure's own extent, and
498    // that number does not depend on which entry is being framed.
499    let reference = family_reference(family);
500    std::iter::once(RosterEntry {
501        tuple: canonical,
502        fill: Vec::new(),
503    })
504    .chain(extras.iter().map(|&coeffs| {
505        let measured = measure_figure(family, coeffs)
506            .zip(reference)
507            .and_then(|(m, reference)| {
508                measured_framing(family, &m.extent, reference).map(|framing| (framing, m.fill))
509            });
510        match measured {
511            Some((framing, fill)) => RosterEntry {
512                tuple: ResolvedTuple { coeffs, framing },
513                fill,
514            },
515            None => RosterEntry {
516                tuple: ResolvedTuple {
517                    coeffs,
518                    framing: canonical.framing,
519                },
520                fill: Vec::new(),
521            },
522        }
523    }))
524    .collect()
525}
526
527/// Framing samples taken across a tuple walk (ADR-0093).
528///
529/// [`FIT_STEPS`](super::ifs::FIT_STEPS)' reason, on this family's arithmetic: the
530/// walk's framing is **measured at each sample rather than interpolated between
531/// the endpoints'**, because the figure halfway between two tuples is a figure
532/// in its own right and its extent is not the average of theirs. Nine is enough
533/// that the sampled scale moves smoothly at a walk slow enough to read; the cost
534/// is nine measurements at preset load, which is the same order the roster
535/// itself already pays.
536const WALK_STEPS: usize = 9;
537
538/// A measured path between two roster entries — the mechanism ADR-0093 gates on
539/// evidence.
540///
541/// **It walks a named pair and nothing else.** There is deliberately no way to
542/// reach an arbitrary pair of coefficients through this type: it is constructed
543/// from two roster indices, and the only thing a frame can move is *where along
544/// that pair* it sits. That is the whole difference between this and the free
545/// interpolation `tuple`'s quantization exists to forbid — a curator measured
546/// this pair and decided the walk holds; nobody measured the others.
547pub(super) struct TupleWalk {
548    from: [f32; 4],
549    to: [f32; 4],
550    /// The framing at each of [`WALK_STEPS`] evenly-spaced positions.
551    frames: [Framing; WALK_STEPS],
552}
553
554impl TupleWalk {
555    /// Measure a path between two resolved entries, or `None` if any point
556    /// along it cannot be framed — which is itself a finding: a pair whose
557    /// middle diverges has no walk, whatever its endpoints look like.
558    pub(super) fn build(
559        family: AttractorFamily,
560        from: ResolvedTuple,
561        to: ResolvedTuple,
562        reference: f32,
563    ) -> Option<Self> {
564        let mut frames = [from.framing; WALK_STEPS];
565        for (i, slot) in frames.iter_mut().enumerate() {
566            let t = i as f32 / (WALK_STEPS - 1) as f32;
567            let coeffs = lerp4(from.coeffs, to.coeffs, t);
568            // The endpoints keep the framing the roster already measured for
569            // them, so a walk parked at either end renders exactly the entry it
570            // names rather than a re-measurement of it.
571            *slot = if i == 0 {
572                from.framing
573            } else if i == WALK_STEPS - 1 {
574                to.framing
575            } else {
576                let figure = measure_figure(family, coeffs)?;
577                measured_framing(family, &figure.extent, reference)?
578            };
579        }
580        Some(Self {
581            from: from.coeffs,
582            to: to.coeffs,
583            frames,
584        })
585    }
586
587    /// The coefficients at `t`, clamped into the path.
588    ///
589    /// **This is the one interpolation of coefficients the scene performs**, and
590    /// it is why the type exists rather than the arithmetic being inlined
591    /// somewhere a stray value could reach it.
592    pub(super) fn coeffs_at(&self, t: f32) -> [f32; 4] {
593        lerp4(self.from, self.to, walk_position(t))
594    }
595
596    /// The framing at `t`, interpolated between the two nearest measured
597    /// samples — [`FitLut::sample`](super::ifs::FitLut::sample)'s shape.
598    pub(super) fn framing_at(&self, t: f32) -> Framing {
599        let last = WALK_STEPS - 1;
600        let pos = walk_position(t) * last as f32;
601        let i = (pos.floor() as usize).min(last - 1);
602        let frac = pos - i as f32;
603        let (Some(a), Some(b)) = (self.frames.get(i), self.frames.get(i + 1)) else {
604            return self.frames.first().copied().unwrap_or(Framing {
605                projection: (1.0, 2.0, [0.0; 3]),
606                seed_box: ([1.0; 3], [0.0; 3]),
607            });
608        };
609        let (sa, dim, ca) = a.projection;
610        let (sb, _, cb) = b.projection;
611        let (ha, boxca) = a.seed_box;
612        let (hb, boxcb) = b.seed_box;
613        Framing {
614            projection: (sa + (sb - sa) * frac, dim, lerp3(ca, cb, frac)),
615            seed_box: (lerp3(ha, hb, frac), lerp3(boxca, boxcb, frac)),
616        }
617    }
618}
619
620/// A walk position: clamped into `[0, 1]`, with a non-finite binding parked at
621/// the near end rather than propagated.
622///
623/// Clamped rather than wrapped, and that is ADR-0075's reason on this family's
624/// arithmetic: past either end the coefficients leave the measured pair, and an
625/// unmeasured tuple is exactly what the walk exists to avoid reaching.
626fn walk_position(t: f32) -> f32 {
627    if t.is_finite() {
628        t.clamp(0.0, 1.0)
629    } else {
630        0.0
631    }
632}
633
634fn lerp3(a: [f32; 3], b: [f32; 3], t: f32) -> [f32; 3] {
635    let ([ax, ay, az], [bx, by, bz]) = (a, b);
636    [ax + (bx - ax) * t, ay + (by - ay) * t, az + (bz - az) * t]
637}
638
639fn lerp4(a: [f32; 4], b: [f32; 4], t: f32) -> [f32; 4] {
640    let ([ax, ay, az, aw], [bx, by, bz, bw]) = (a, b);
641    [
642        ax + (bx - ax) * t,
643        ay + (by - ay) * t,
644        az + (bz - az) * t,
645        aw + (bw - aw) * t,
646    ]
647}
648
649/// The reference reach a family's measured framings are scaled against — the
650/// canonical figure's own [`framed_half`]. `None` if the canonical tuple cannot
651/// be measured, which cannot happen for the four shipped families.
652pub(super) fn family_reference(family: AttractorFamily) -> Option<f32> {
653    measure_figure(family, family.default_coeffs()).map(|m| framed_half(family, m.extent.half))
654}
655
656/// `tuple`'s CPU-side quantization: a bound value to a roster index.
657///
658/// **Quantized here and not in the shader, and that is not an optimization**
659/// (ADR-0093). These are chaotic maps: a fractional index would interpolate
660/// coefficients *between two different figures*, which is not a halfway figure
661/// but a third, unmeasured one — with neither endpoint's framing. `kaleido_order`
662/// and `kaleido_edge` round for the same class of reason, and the reason bites
663/// harder here: a smoothing curve makes it **necessary rather than defensive**,
664/// since an eased param is continuous even when the thing it selects is not, so
665/// a binding easing from `0` toward `3` sweeps *through* 1.4 whatever its
666/// endpoints are.
667///
668/// Nearest-integer rather than truncation, so an eased sweep lands on the entry
669/// it is closest to; clamped into the roster, so an over-driven binding holds the
670/// last figure rather than selecting nothing; and a non-finite binding falls back
671/// to the canonical entry, since `f32::clamp` propagates `NaN` and a `NaN as
672/// usize` is zero by saturation rather than by decision.
673pub(super) fn roster_index(value: f32, len: usize) -> usize {
674    if !value.is_finite() {
675        return 0;
676    }
677    let last = len.saturating_sub(1);
678    value.round().clamp(0.0, last as f32) as usize
679}
680
681/// Euler sub-steps per fixed step for the continuous families.
682///
683/// **Mirrored from [`STEP_SHADER`](super::STEP_SHADER), which is the source** —
684/// `the_ode_substeps_agree_between_rust_and_wgsl` holds the WGSL literal to this
685/// constant. The CPU needs the same number because [`measure_extent`] frames a
686/// tuple by iterating the very map the GPU will iterate, and an integrator that
687/// took different steps would measure a different figure.
688pub(super) const ODE_SUBSTEPS: u32 = 4;
689
690/// Trajectories the measurement runs at once.
691///
692/// **A handful rather than a cloud**, because a chaotic attractor is sampled by
693/// one trajectory's *time*, not by how many trajectories are launched — the
694/// steps below are what buys coverage. More than one only so a figure with
695/// disjoint basins cannot be measured from inside one of them.
696const MEASURE_TRAJECTORIES: u32 = 4;
697/// Steps discarded before measuring, so the seed box's own extent is not what
698/// gets measured.
699///
700/// **Sized to the slowest transient on the roster, not to the fastest.** The
701/// discrete maps converge within tens of steps; the Lorenz torus knot at
702/// rho ≈ 100 reaches its periodic orbit through several seconds of transient
703/// chaos, and measured at 600 steps its bounding box comes out ~40 % too large
704/// — a figure framed off that measurement renders correspondingly small. At
705/// 1200 the measurement is stable to three digits against a ten-times-longer
706/// warm-up.
707const MEASURE_WARMUP: u32 = 1200;
708/// Steps the bounding box accumulates over, after the warm-up.
709const MEASURE_STEPS: u32 = 3000;
710/// A coordinate past this is a divergence rather than a figure.
711///
712/// **Euler is conditionally stable and the roster can reach past its
713/// condition**: the Lorenz flow at rho ≈ 160 blows up at this scene's sub-step,
714/// so an uncurated tuple really does produce infinities. The guard is what turns
715/// that into a fallback rather than an `inf` scale reaching the GPU.
716const MEASURE_DIVERGENCE: f32 = 1.0e6;
717/// The measurement's own RNG seed — its own, so the starting points do not
718/// correlate with the scene's seeded scatter.
719const MEASURE_SEED: u64 = 0x4C4D_5641_5455_5031; // "LMVATUP1"
720/// How many on-attractor points a measurement banks for the initial fill
721/// ([`Measurement::fill`]).
722///
723/// **Duplication across the particle buffer is fine and is not what this number
724/// is protecting.** At the `Rich` tier 150 000 particles share these, so each
725/// bank point starts ~37 particles — and on a chaotic figure those separate
726/// within a few steps, while on a periodic one they stay a curve, which is what
727/// the figure is. What the count buys is *coverage*: too few points and the fill
728/// is a handful of arcs rather than the whole attractor for the first second. At
729/// 12 bytes each this is 48 KB per measured entry, held for the life of the
730/// preset.
731const MEASURE_BANK: u32 = 4096;
732
733/// A measured bounding box, as the projection and the seed box both want it.
734pub(super) struct Extent {
735    pub(super) half: [f32; 3],
736    pub(super) centre: [f32; 3],
737}
738
739/// Frame a tuple from its measured [`Extent`] (ADR-0093) — the readback-free
740/// form of auto-centering, run once at load instead of once a frame.
741///
742/// `reference` is the family's canonical figure's own [`framed_half`]; `None`
743/// comes back when the measurement is degenerate, which the caller turns into
744/// the canonical framing.
745///
746/// **The scale is a ratio against the canonical tuple rather than a target fill
747/// fraction**, and that is the whole trick: each family's shipped scale already
748/// encodes a judgement about how much of the frame its figure should occupy —
749/// 0.42 against De Jong's extent of ~1.9 fills far more of the frame than 0.022
750/// against Lorenz's ~26, because a spinning 3D figure needs slack a flat map does
751/// not. Scaling by the ratio of the two extents means a roster entry occupies
752/// **the same footprint as its family's canonical figure**, whatever its native
753/// size — so a curator judges figures, and no fill constant has to be invented
754/// or defended.
755pub(super) fn measured_framing(
756    family: AttractorFamily,
757    extent: &Extent,
758    reference: f32,
759) -> Option<Framing> {
760    let (canonical_scale, dim, _) = family.canonical_framing().projection;
761    let measured = framed_half(family, extent.half);
762    if !(measured > 0.0 && reference > 0.0) {
763        return None;
764    }
765    let scale = canonical_scale * reference / measured;
766    if !scale.is_finite() || scale <= 0.0 {
767        return None;
768    }
769    Some(Framing {
770        projection: (scale, dim, extent.centre),
771        // The measured box IS the figure's extent, so the initial fill lands
772        // across the attractor rather than in a corner of it — and
773        // `jitter_extent` inherits the right magnitude for free.
774        seed_box: (extent.half, extent.centre),
775    })
776}
777
778/// What one measurement pass produces: the figure's extent, and a bank of points
779/// **on** it.
780pub(super) struct Measurement {
781    pub(super) extent: Extent,
782    /// Positions the measured trajectories actually visited, evenly sampled
783    /// across the window — see [`MEASURE_BANK`].
784    pub(super) fill: Vec<[f32; 3]>,
785}
786
787/// Iterate a tuple: where its figure is, how big, and where it lives.
788///
789/// **The bank is not a by-product, it is half the point** (ADR-0087's argument,
790/// applied to a measured tuple). A uniform fill of a figure's bounding box puts
791/// most of its particles *off* the attractor, and getting back on is a transient
792/// the viewer watches: at rho ≈ 100 the cloud wanders out to **2.2 times** the
793/// figure's own extent for its first several seconds — measured, and visible as
794/// a capture clipped on all four edges. The IFS solved exactly this by seeding at
795/// its maps' fixed points, which are on the attractor by construction. A measured
796/// tuple has no closed-form point set, but the measurement **visits** the
797/// attractor thousands of times while it frames it, so banking what it saw costs
798/// one push per sampled step and starts the figure on itself: seeded from the
799/// bank, the same tuple never exceeds its own extent at all.
800pub(super) fn measure_figure(family: AttractorFamily, coeffs: [f32; 4]) -> Option<Measurement> {
801    measure_extent(
802        family,
803        coeffs,
804        // Started from the canonical seed box: it is the one box known to be in
805        // the right neighbourhood before anything has been measured, and a
806        // chaotic map forgets where it started within the warm-up anyway.
807        family.canonical_framing().seed_box,
808        MEASURE_WARMUP,
809        MEASURE_STEPS,
810    )
811}
812
813/// The half-extent the frame is sized against: the largest the figure gets on
814/// screen at any rotation.
815///
816/// Read off [`Basis::masks`] rather than restated, so it cannot disagree with
817/// the shader about which axes are drawn. The spin turns `x` against the basis's
818/// partner axis, so the horizontal sweep reaches the larger of those two — the
819/// same reduction [`Framing::inv_depth_extent`] normalizes depth by, for the same
820/// reason. **A 2D family needs no special case**: its partner axis is `z`, whose
821/// extent is exactly zero, so the `max` falls through to `x`.
822pub(super) fn framed_half(family: AttractorFamily, half: [f32; 3]) -> f32 {
823    let ([hx, hy, hz], [vx, vy, vz]) = family.basis().masks();
824    let [x, y, z] = half;
825    let partner = x * hx + y * hy + z * hz;
826    let vertical = x * vx + y * vy + z * vz;
827    x.max(partner).max(vertical)
828}
829
830/// The tuple's bounding box and point bank over `steps`, from a few trajectories
831/// started in `from` and run `warmup` steps first.
832fn measure_extent(
833    family: AttractorFamily,
834    coeffs: [f32; 4],
835    from: ([f32; 3], [f32; 3]),
836    warmup: u32,
837    steps: u32,
838) -> Option<Measurement> {
839    let ([sx, sy, sz], [cx, cy, cz]) = from;
840    let mut rng = SeededRng::new(MEASURE_SEED);
841    let mut points: Vec<[f32; 3]> = (0..MEASURE_TRAJECTORIES)
842        .map(|_| {
843            [
844                cx + rng.range(-sx, sx),
845                cy + rng.range(-sy, sy),
846                cz + rng.range(-sz, sz),
847            ]
848        })
849        .collect();
850    // Every `stride`-th visited point is banked, so the fill samples the whole
851    // measured window evenly rather than the last few hundred steps of it —
852    // which on a slow flow would be a short arc of the figure rather than the
853    // figure.
854    let visited = steps.max(1) * MEASURE_TRAJECTORIES.max(1);
855    let stride = (visited / MEASURE_BANK.max(1)).max(1) as usize;
856    let mut fill: Vec<[f32; 3]> = Vec::with_capacity(MEASURE_BANK as usize + 1);
857    let mut seen = 0usize;
858    let mut lo = [f32::INFINITY; 3];
859    let mut hi = [f32::NEG_INFINITY; 3];
860    for step in 0..(warmup + steps) {
861        for p in points.iter_mut() {
862            *p = step_once(family, coeffs, *p);
863            let [x, y, z] = *p;
864            let reach = x.abs().max(y.abs()).max(z.abs());
865            if !reach.is_finite() || reach > MEASURE_DIVERGENCE {
866                return None;
867            }
868            if step < warmup {
869                continue;
870            }
871            let ([lx, ly, lz], [hx, hy, hz]) = (lo, hi);
872            lo = [lx.min(x), ly.min(y), lz.min(z)];
873            hi = [hx.max(x), hy.max(y), hz.max(z)];
874            if seen.is_multiple_of(stride) {
875                fill.push(*p);
876            }
877            seen += 1;
878        }
879    }
880    let ([lx, ly, lz], [hx, hy, hz]) = (lo, hi);
881    if !(lx.is_finite() && hx.is_finite()) || fill.is_empty() {
882        return None;
883    }
884    Some(Measurement {
885        extent: Extent {
886            half: [(hx - lx) * 0.5, (hy - ly) * 0.5, (hz - lz) * 0.5],
887            centre: [(hx + lx) * 0.5, (hy + ly) * 0.5, (hz + lz) * 0.5],
888        },
889        fill,
890    })
891}
892
893/// One fixed step of a family's map, on the CPU.
894///
895/// **The CPU mirror of [`STEP_SHADER`](super::STEP_SHADER)'s four map arms** —
896/// the WGSL is the source and this is the mirror, the discipline
897/// [`projection_mirror`](super::projection_mirror) and [`hash_unit`](super::hash_unit)
898/// already follow. `the_cpu_step_mirrors_the_shader` runs both and compares, so
899/// this is held to the shader by a differential rather than by reading.
900///
901/// It exists because a framing measured off *different* arithmetic would frame a
902/// figure the GPU does not draw. The IFS is deliberately absent: its step draws a
903/// random map per particle and its framing is ADR-0075's measured fit, so there
904/// is nothing here for it to be measured by.
905pub(super) fn step_once(family: AttractorFamily, coeffs: [f32; 4], p: [f32; 3]) -> [f32; 3] {
906    let [a, b, c, d] = coeffs;
907    let [x, y, z] = p;
908    match family {
909        AttractorFamily::DeJong => [
910            (a * y).sin() - (b * x).cos(),
911            (c * x).sin() - (d * y).cos(),
912            0.0,
913        ],
914        AttractorFamily::Clifford => [
915            (a * y).sin() + c * (a * x).cos(),
916            (b * x).sin() + d * (b * y).cos(),
917            0.0,
918        ],
919        AttractorFamily::Thomas => {
920            // The shader's "lively speed-up" factor of 3 is part of the map as
921            // far as a measurement is concerned: it is what the figure is
922            // iterated at, so leaving it out would measure a different flow.
923            let h = FIXED_STEP * 3.0 / ODE_SUBSTEPS as f32;
924            let (mut x, mut y, mut z) = (x, y, z);
925            for _ in 0..ODE_SUBSTEPS {
926                let (dx, dy, dz) = (y.sin() - a * x, z.sin() - a * y, x.sin() - a * z);
927                x += dx * h;
928                y += dy * h;
929                z += dz * h;
930            }
931            [x, y, z]
932        }
933        AttractorFamily::Lorenz => {
934            let h = FIXED_STEP / ODE_SUBSTEPS as f32;
935            let (mut x, mut y, mut z) = (x, y, z);
936            for _ in 0..ODE_SUBSTEPS {
937                let (dx, dy, dz) = (a * (y - x), x * (b - z) - y, x * y - c * z);
938                x += dx * h;
939                y += dy * h;
940                z += dz * h;
941            }
942            [x, y, z]
943        }
944        // Nothing to iterate: an IFS has no coefficient tuple to frame (see
945        // `extra_tuples`), so the fixed point of this function is the honest
946        // answer rather than a placeholder.
947        AttractorFamily::Ifs(_) => p,
948    }
949}
950
951/// The plane a 3D attractor family is projected into (ADR-0068), as chosen by
952/// `AttractorFamily::basis`.
953///
954/// The spin always rotates `x` against the *other* horizontal axis and leaves the
955/// vertical alone, so a basis is fully described by naming that pair.
956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957pub enum Basis {
958    /// `x` horizontal, `y` vertical; the spin rotates `x` against `z`. The shared
959    /// convention every 3D family used before ADR-0068, and still every family's
960    /// answer but Lorenz's.
961    XY,
962    /// `x` horizontal, `z` vertical; the spin rotates `x` against `y`. Lorenz's
963    /// butterfly lies in this plane.
964    XZ,
965}
966
967impl Basis {
968    /// The two axis selectors the draw shader dots the centred position against:
969    /// `(the axis the spin rotates x against, the vertical axis)`.
970    ///
971    /// Masks rather than indices because WGSL will not dynamically index a
972    /// `vec3` outside addressable storage, and a `dot` against a one-hot vector
973    /// is branch-free — so the basis stays one pipeline and one draw call.
974    pub(super) fn masks(self) -> ([f32; 3], [f32; 3]) {
975        match self {
976            Basis::XY => ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
977            Basis::XZ => ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
978        }
979    }
980}
981
982/// Base display rotation (rad/s), so the cloud visibly turns even when the point
983/// set saturates its footprint — the animation liveness the differential tests
984/// require, independent of audio.
985///
986/// It is `2π / 0.18` = **one revolution per 34.9 seconds**, and until ADR-0076
987/// that was the *only* rate any attractor could turn at: no preset could reach
988/// the rotation of a 3D figure at all. The slowness is part of why the 3D
989/// families read as flat — a viewer never accumulates enough motion evidence to
990/// resolve which way the thing is turning. `spin` is a **multiplier** on this,
991/// so `1` is unchanged, `0` holds the figure still and negative reverses it.
992pub(super) const SPIN_RATE: f32 = 0.18;
993
994/// `spin`'s default: exactly today's rate.
995pub(super) const DEFAULT_SPIN: f32 = 1.0;
996
997/// The rotation angle, in radians, for an accumulated spin-time.
998///
999/// The spin itself is accumulated by [`Phase`](crate::render::scenes::Phase),
1000/// which every bindable rate in this engine advances through; **the multiply by
1001/// [`SPIN_RATE`] is deferred to here rather than folded into that accumulation**,
1002/// for the arithmetic reason the type's own header records: at the default
1003/// `spin = 1` the accumulator is `Σ dt` term for term, so `spin = 1` reproduces
1004/// the pre-ADR-0076 `time * SPIN_RATE` *exactly* and no golden baseline moves.
1005pub(super) fn spin_phase(spin_time: f32) -> f32 {
1006    spin_time * SPIN_RATE
1007}