Skip to main content

hpr_validate/
openrocket.rs

1//! hpr held to OpenRocket's own answers ([M2.2][m2-2]): the tests, and one rule of OpenRocket's
2//! that `cargo xtask ork` needs to explain a gap, [`openrocket_fin_set_roll_kg_m2`].
3//!
4//! `validation/fixtures/ork/openrocket-conventions.json` is OpenRocket 24.12 reading small probe
5//! designs, each asking one question a `.ork` leaves to its reader. What does a shoulder written
6//! with no wall weigh? What is a part that names no material made of? Where is a center of gravity
7//! override measured from? Which override wins when a part and the parts inside it both have one?
8//! The record is written by `validation/oracles/openrocket/conventions.py`, which runs OpenRocket
9//! and never reads it ([ADR-061][adr-061]). These tests read the same documents with `hpr_io::ork`
10//! and hold hpr's structure to OpenRocket's. Where hpr keeps a rule of its own, a *departure*, the
11//! test pins how far apart the two are, so a change on either side shows.
12//!
13//! [m2-2]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-2
14//! [adr-061]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-061-what-a-ork-leaves-unsaid-read-as-openrocket-reads-it-overrides-measured-two-departures-kept-2026-09-21
15
16use hpr_design::fins::FinSet;
17
18/// The roll inertia OpenRocket 24.12 gives a fin set about its own center of mass, kg·m², **inferred
19/// from its output, not taken from its source** (which is GPL and not read). For two or more fins,
20/// whose center is on the rocket's axis, it is the set's mass `m` spread evenly along a thin rod
21/// from the body at `R` out to `R + hₑ`,
22///
23/// ```text
24/// I = m (R² + R hₑ + hₑ²/3),   hₑ² = A h / c_r,
25/// ```
26///
27/// where `A` is one fin's planform area, `h` its span and `c_r` its root chord: a rectangle's own
28/// span, shorter for a fin that narrows outward. For one fin it is the same rod about its own
29/// middle, `m hₑ²/12`. `validation/oracles/openrocket/conventions.py` measured it on rectangles of
30/// two chords, two spans and two body radii, a trapezoid, a triangle, an ellipse (OpenRocket's
31/// 30-sided polygon), one fin, and fins with a rounded or airfoil section, a tab or fillets: every
32/// one to 1e-12 on the probe's structure but the ellipse (by its polygon) and a cant (2.66e-5). A
33/// tab's mass takes the planform's value, and the section and thickness play no part. hpr's own is
34/// the exact integral of `r²` over the fin ([`FinSet::mass_properties`]); the two agree on a
35/// rectangle without a tab, but for the thickness ([ADR-062][adr-062]).
36///
37/// `mass_kg` is the set's, all fins together. `None` for a planform `hpr-design` refuses, a count
38/// of zero, or a radius or mass that is negative or not finite.
39///
40/// [adr-062]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-062-fins-and-rail-buttons-against-openrocket-roll-inertia-explained-2026-09-21
41#[must_use]
42pub fn openrocket_fin_set_roll_kg_m2(
43    fins: &FinSet,
44    body_radius_m: f64,
45    mass_kg: f64,
46) -> Option<f64> {
47    let area_m2 = fins.planform.geometry().ok()?.area_m2;
48    rod_roll_kg_m2(
49        fins.count,
50        area_m2,
51        fins.planform.span_m(),
52        fins.planform.root_chord_m(),
53        body_radius_m,
54        mass_kg,
55    )
56}
57
58/// [`openrocket_fin_set_roll_kg_m2`] from the numbers it uses, so that a test can give it
59/// OpenRocket's polygon for an ellipse.
60fn rod_roll_kg_m2(
61    count: u32,
62    area_m2: f64,
63    span_m: f64,
64    root_m: f64,
65    body_radius_m: f64,
66    mass_kg: f64,
67) -> Option<f64> {
68    let usable = |x: f64| x.is_finite() && x >= 0.0;
69    if count == 0
70        || !(usable(area_m2) && usable(span_m) && usable(body_radius_m) && usable(mass_kg))
71        || !(root_m.is_finite() && root_m > 0.0)
72    {
73        return None;
74    }
75    let reach2 = area_m2 * span_m / root_m;
76    if count == 1 {
77        return Some(mass_kg * reach2 / 12.0);
78    }
79    let r = body_radius_m;
80    Some(mass_kg * (r * r + r * reach2.sqrt() + reach2 / 3.0))
81}
82
83#[cfg(test)]
84mod tests {
85    use hpr_design::tree::{Layout, Part};
86    use hpr_io::ork::{self, StoredReferenceExclusion, StoredSimulation};
87    use serde_json::Value;
88
89    fn record() -> Value {
90        let text = include_str!("../../../validation/fixtures/ork/openrocket-conventions.json");
91        serde_json::from_str(text).expect("the committed record is JSON")
92    }
93
94    fn probe<'a>(record: &'a Value, question: &str) -> &'a Value {
95        let probe = &record["probes"][question];
96        assert!(probe.is_object(), "no probe asks {question:?}");
97        probe
98    }
99
100    /// hpr's layout of a probe, and the warnings it raised reading it.
101    fn hpr(probe: &Value) -> (Layout, Vec<String>) {
102        let document = probe["document"].as_str().expect("the probe's document");
103        let read = ork::read(document.as_bytes()).expect("a probe reads");
104        let spine = ork::rocket(&read.value.document);
105        let layout = spine.value.layout().expect("a probe lays out");
106        let warnings = spine.warnings.iter().map(|w| w.message.clone()).collect();
107        (layout, warnings)
108    }
109
110    /// Mass (kg), the center of mass's station aft of the tip (m), and the roll and pitch inertias
111    /// about it (kg·m²): hpr's and OpenRocket's. Pitch is the mean of the two inertias across the
112    /// axis, and OpenRocket's `ixx` is roll: both as `cargo xtask ork` measured on its probe tube
113    /// (ADR-060).
114    fn both(probe: &Value) -> ([f64; 4], [f64; 4], Vec<String>) {
115        let (layout, warnings) = hpr(probe);
116        let s = &layout.structure;
117        let i = s.inertia_kg_m2;
118        let ours = [
119            s.mass_kg,
120            // hpr's `+z` points at the nose from the tip, so a station aft of it is `-z`.
121            -s.cg_m.z,
122            i.z_axis.z,
123            (i.x_axis.x + i.y_axis.y) / 2.0,
124        ];
125        let or = &probe["structure"];
126        let number = |key: &str| or[key].as_f64().expect("a number");
127        let theirs = [
128            number("mass_kg"),
129            number("cm_x_m"),
130            number("ixx"),
131            (number("iyy") + number("izz")) / 2.0,
132        ];
133        (ours, theirs, warnings)
134    }
135
136    fn relative(ours: f64, theirs: f64) -> f64 {
137        (ours - theirs) / theirs
138    }
139
140    fn stored(status: &str, results_xml: Option<&str>) -> StoredSimulation {
141        let xml = format!(
142            r#"<openrocket version="1.10"><rocket><name>R</name></rocket><simulations>
143              <simulation status="{status}"><name>stored</name><simulator>RK4Simulator</simulator><calculator>BarrowmanCalculator</calculator>{results}</simulation>
144            </simulations></openrocket>"#,
145            results = results_xml.unwrap_or_default(),
146        );
147        ork::design(
148            &ork::read(xml.as_bytes())
149                .expect("stored fixture reads")
150                .value,
151        )
152        .value
153        .simulations
154        .into_iter()
155        .next()
156        .expect("stored simulation")
157    }
158
159    fn plausible_results_xml() -> &'static str {
160        r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"/>"#
161    }
162
163    fn stored_with_provenance(
164        simulator: Option<&str>,
165        calculator: Option<&str>,
166    ) -> StoredSimulation {
167        let simulator = simulator.map_or_else(String::new, |value| {
168            format!("<simulator>{value}</simulator>")
169        });
170        let calculator = calculator.map_or_else(String::new, |value| {
171            format!("<calculator>{value}</calculator>")
172        });
173        let xml = format!(
174            r#"<openrocket version="1.10"><rocket><name>R</name></rocket><simulations>
175              <simulation status="uptodate"><name>stored</name>{simulator}{calculator}{results}</simulation>
176            </simulations></openrocket>"#,
177            results = plausible_results_xml(),
178        );
179        ork::design(
180            &ork::read(xml.as_bytes())
181                .expect("stored fixture reads")
182                .value,
183        )
184        .value
185        .simulations
186        .into_iter()
187        .next()
188        .expect("stored simulation")
189    }
190
191    fn stored_with_results(results_xml: &str) -> StoredSimulation {
192        stored("uptodate", Some(results_xml))
193    }
194
195    fn results_with_branches(apogee: &str, branches: &str) -> String {
196        format!(
197            r#"<flightdata maxaltitude="{apogee}" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20">{branches}</flightdata>"#
198        )
199    }
200
201    /// Stored results remain readable, but stale, missing and physically contradictory values are
202    /// not allowed to become validation references or inflate a reference census.
203    #[test]
204    fn stale_and_implausible_stored_results_are_excluded_from_gates_and_census() {
205        let cases = [
206            (stored("uptodate", Some(plausible_results_xml())), None),
207            (
208                stored(
209                    "uptodate",
210                    Some(
211                        r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,1</datapoint><datapoint>2,1</datapoint></databranch></flightdata>"#,
212                    ),
213                ),
214                Some(StoredReferenceExclusion::InconsistentResults),
215            ),
216            (
217                stored(
218                    "uptodate",
219                    Some(
220                        r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,100</datapoint><datapoint>2,100.05</datapoint></databranch></flightdata>"#,
221                    ),
222                ),
223                None,
224            ),
225            (
226                stored(
227                    "uptodate",
228                    Some(
229                        r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,100</datapoint><datapoint>2,100.2</datapoint></databranch></flightdata>"#,
230                    ),
231                ),
232                Some(StoredReferenceExclusion::InconsistentResults),
233            ),
234            (
235                stored("outdated", Some(plausible_results_xml())),
236                Some(StoredReferenceExclusion::Outdated),
237            ),
238            (
239                stored("notsimulated", Some(plausible_results_xml())),
240                Some(StoredReferenceExclusion::NotSimulated),
241            ),
242            (
243                stored("uptodate", None),
244                Some(StoredReferenceExclusion::MissingResults),
245            ),
246            (
247                stored(
248                    "uptodate",
249                    Some(
250                        r#"<flightdata maxaltitude="-1" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"/>"#,
251                    ),
252                ),
253                Some(StoredReferenceExclusion::ImpossibleSummary),
254            ),
255            (
256                stored(
257                    "uptodate",
258                    Some(
259                        r#"<flightdata maxaltitude="NaN" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"/>"#,
260                    ),
261                ),
262                Some(StoredReferenceExclusion::MissingSummary),
263            ),
264            (
265                stored(
266                    "uptodate",
267                    Some(
268                        r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>2,10</datapoint><datapoint>1,20</datapoint></databranch></flightdata>"#,
269                    ),
270                ),
271                Some(StoredReferenceExclusion::InconsistentResults),
272            ),
273            (
274                stored(
275                    "uptodate",
276                    Some(
277                        r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,-1</datapoint><datapoint>2,20</datapoint></databranch></flightdata>"#,
278                    ),
279                ),
280                Some(StoredReferenceExclusion::ImpossibleSummary),
281            ),
282        ];
283        let classified = cases
284            .iter()
285            .filter(|(simulation, exclusion)| simulation.reference_exclusion() == *exclusion)
286            .count();
287        assert_eq!(classified, cases.len());
288        assert_eq!(
289            cases
290                .iter()
291                .filter(|(_, exclusion)| exclusion.is_none())
292                .count(),
293            2
294        );
295        assert_eq!(
296            StoredReferenceExclusion::Outdated.reason(),
297            "status-outdated"
298        );
299        assert_eq!(
300            StoredReferenceExclusion::MissingResults.reason(),
301            "missing-results"
302        );
303        assert_eq!(
304            stored_with_provenance(None, Some("BarrowmanCalculator")).reference_exclusion(),
305            Some(StoredReferenceExclusion::MissingSimulator)
306        );
307        assert_eq!(
308            stored_with_provenance(Some("OtherSimulator"), Some("BarrowmanCalculator"))
309                .reference_exclusion(),
310            Some(StoredReferenceExclusion::UnsupportedSimulator)
311        );
312        assert_eq!(
313            stored_with_provenance(Some("RK4Simulator"), None).reference_exclusion(),
314            Some(StoredReferenceExclusion::MissingCalculator)
315        );
316        assert_eq!(
317            stored_with_provenance(Some("RK4Simulator"), Some("OtherCalculator"))
318                .reference_exclusion(),
319            Some(StoredReferenceExclusion::UnsupportedCalculator)
320        );
321    }
322
323    /// The apogee summary maps to OpenRocket's primary branch, not whichever branch happens to
324    /// have the numerically closest maximum. Secondary stages may also record apogee events.
325    #[test]
326    fn stored_apogee_uses_the_first_apogee_branch() {
327        let branches = r#"
328          <databranch name="Sustainer" types="Time,Altitude">
329            <event time="5" type="apogee"/><datapoint>0,0</datapoint><datapoint>5,100</datapoint>
330          </databranch>
331          <databranch name="Booster" types="Time,Altitude">
332            <event time="4" type="apogee"/><datapoint>0,0</datapoint><datapoint>4,99.9</datapoint>
333          </databranch>"#;
334        let simulation = stored_with_results(&results_with_branches("100", branches));
335        assert_eq!(simulation.reference_exclusion(), None);
336    }
337
338    /// A single altitude-bearing branch identifies the summary without an apogee event, but two
339    /// such branches do not give enough information to identify which series owns it.
340    #[test]
341    fn stored_apogee_branch_requires_unambiguous_branch_evidence() {
342        let single = r#"<databranch name="Sustainer" types="Time,Altitude">
343          <datapoint>0,0</datapoint><datapoint>5,100</datapoint>
344        </databranch>"#;
345        assert_eq!(
346            stored_with_results(&results_with_branches("100", single)).reference_exclusion(),
347            None
348        );
349        let multiple = format!(
350            r#"{single}<databranch name="Booster" types="Time,Altitude"><datapoint>0,0</datapoint><datapoint>5,99</datapoint></databranch>"#
351        );
352        assert_eq!(
353            stored_with_results(&results_with_branches("100", &multiple)).reference_exclusion(),
354            Some(StoredReferenceExclusion::UninspectableSeries)
355        );
356    }
357
358    /// A stored maximum matches at the exact allowance boundary; just beyond it does not. The
359    /// relative allowance takes over at 1 m, where it equals the fixed 1 mm allowance.
360    #[test]
361    fn stored_apogee_comparison_uses_the_two_sided_allowance() {
362        let check = |apogee: &str, series: &str| {
363            let branch = format!(
364                r#"<databranch name="Sustainer" types="Time,Altitude"><datapoint>0,0</datapoint><datapoint>5,{series}</datapoint></databranch>"#
365            );
366            stored_with_results(&results_with_branches(apogee, &branch)).reference_exclusion()
367        };
368        assert_eq!(check("100", "100.1"), None);
369        assert_eq!(
370            check("100", "100.1000001"),
371            Some(StoredReferenceExclusion::InconsistentResults)
372        );
373        assert_eq!(check("1", "1.001"), None);
374        assert_eq!(
375            check("1", "1.0010001"),
376            Some(StoredReferenceExclusion::InconsistentResults)
377        );
378        assert_eq!(
379            check("0.5", "0.501"),
380            Some(StoredReferenceExclusion::InconsistentResults)
381        );
382        assert_eq!(check("0.5", "0.5009999"), None);
383        assert_eq!(check("100", "99.9"), None);
384        assert_eq!(
385            check("100", "99.8999999"),
386            Some(StoredReferenceExclusion::InconsistentResults)
387        );
388    }
389
390    #[test]
391    fn stored_times_agree_with_flight_and_apogee_summaries() {
392        let branch = |last_time: &str, apogee_time: &str| {
393            format!(
394                r#"<databranch name="Sustainer" types="Time,Altitude"><event time="{apogee_time}" type="apogee"/><datapoint>0,0</datapoint><datapoint>{last_time},100</datapoint></databranch>"#
395            )
396        };
397        let run = |last_time: &str, apogee_time: &str| {
398            stored_with_results(&results_with_branches(
399                "100",
400                &branch(last_time, apogee_time),
401            ))
402            .reference_exclusion()
403        };
404        assert_eq!(run("20.0009", "5"), None);
405        assert_eq!(run("20", "5.0009"), None);
406        assert_eq!(
407            run("20.0011", "5"),
408            Some(StoredReferenceExclusion::InconsistentResults)
409        );
410        assert_eq!(
411            run("20", "5.0011"),
412            Some(StoredReferenceExclusion::InconsistentResults)
413        );
414    }
415
416    #[test]
417    fn non_finite_event_times_exclude_stored_results() {
418        let mut simulation = stored_with_results(&results_with_branches(
419            "100",
420            r#"<databranch name="Sustainer" types="Time,Altitude"><event time="5" type="launch"/><datapoint>0,0</datapoint><datapoint>5,100</datapoint></databranch>"#,
421        ));
422        simulation.results.as_mut().unwrap().branches[0].events[0].time_s = f64::NAN;
423        assert_eq!(
424            simulation.reference_exclusion(),
425            Some(StoredReferenceExclusion::ImpossibleSummary)
426        );
427    }
428
429    #[test]
430    fn fatal_events_and_events_outside_the_flight_exclude_stored_results() {
431        let with_event = |time: &str, kind: &str| {
432            let branch = format!(
433                r#"<databranch name="Sustainer" types="Time,Altitude"><event time="{time}" type="{kind}"/><datapoint>0,0</datapoint><datapoint>5,100</datapoint></databranch>"#
434            );
435            stored_with_results(&results_with_branches("100", &branch)).reference_exclusion()
436        };
437        assert_eq!(
438            with_event("6", "SIM_ABORT"),
439            Some(StoredReferenceExclusion::FatalEvent)
440        );
441        assert_eq!(
442            with_event("6", "Simulation-Abort"),
443            Some(StoredReferenceExclusion::FatalEvent)
444        );
445        assert_eq!(
446            with_event("-0.1", "launch"),
447            Some(StoredReferenceExclusion::ImpossibleSummary)
448        );
449        assert_eq!(
450            with_event("21", "simulationend"),
451            Some(StoredReferenceExclusion::InconsistentResults)
452        );
453    }
454
455    /// The override probes, each with how far hpr's center of mass is from OpenRocket's, in meters
456    /// (hpr's station less OpenRocket's). A zero is agreement; the last two are the departure
457    /// ADR-061 keeps for a mass override that covers the parts inside and states no center.
458    const PRECEDENCE: [(&str, f64); 12] = [
459        (
460            "a centre of gravity override on a nose with a shoulder",
461            0.0,
462        ),
463        (
464            "a centre of gravity override on a transition with a fore shoulder",
465            0.0,
466        ),
467        ("a mass override on a nose with a shoulder", 0.0),
468        ("a mass override on a tube, not the part inside", 0.0),
469        ("a mass override on the part inside only", 0.0),
470        (
471            "a centre of gravity override on a tube, not the part inside",
472            0.0,
473        ),
474        (
475            "a centre of gravity override on a tube and the part inside",
476            0.0,
477        ),
478        ("a mass override on the stage", 0.0),
479        ("both overrides on the stage", 0.0),
480        ("a stage override over a part's own", 0.0),
481        ("a mass override on a tube and the part inside", -0.003686),
482        (
483            "a mass override on a tube and the part inside, which has its own",
484            -0.019690,
485        ),
486    ];
487
488    /// Both overrides on one part, with flags that disagree, and the center's distance as above.
489    const DISAGREEING: [(&str, f64); 2] = [
490        (
491            "both overrides on a tube, the centre covering the part inside and the mass not",
492            0.004672,
493        ),
494        (
495            "both overrides on a tube, the mass covering the part inside and the centre not",
496            0.0,
497        ),
498    ];
499
500    /// Loft lesson L51: Loft's rule for which center-of-gravity override wins came from
501    /// OpenRocket's source and was unsettled by up to 133 mm. Here it is measured.
502    ///
503    /// On every override probe hpr's mass is OpenRocket's, so the winning mass override is the
504    /// same one: a parent's override that covers its children wins over a child's own, and a
505    /// stage's over everything in it. A center of gravity override is measured from the part's
506    /// front, not its shoulder's, and moves the shoulder with the part. A center of gravity override
507    /// alone that covers the parts inside sets the assembly's center in both programs (how each
508    /// places the parts inside differs, which shows only in the inertia: see
509    /// `inertia_under_an_override_departs_as_written`).
510    ///
511    /// Two cases are hpr's own rule, written in ADR-061 and pinned here in meters:
512    ///
513    /// - a mass override that covers the parts inside and states no center: OpenRocket puts the
514    ///   center at the overriding part's own, leaving out the parts inside; hpr keeps the
515    ///   assembly's, as its parts lay it out;
516    /// - both overrides, with flags that disagree: hpr states one scope and takes the mass's, and
517    ///   says so.
518    #[test]
519    fn override_precedence_matches_oracle() {
520        let record = record();
521        for (question, apart_m) in PRECEDENCE {
522            let (ours, theirs, warnings) = both(probe(&record, question));
523            assert!(
524                relative(ours[0], theirs[0]).abs() < 1e-5,
525                "{question}: mass {ours:?} {theirs:?}"
526            );
527            assert!(
528                (ours[1] - theirs[1] - apart_m).abs() < 1e-6,
529                "{question}: center {} m apart, not {apart_m}",
530                ours[1] - theirs[1]
531            );
532            assert!(warnings.is_empty(), "{question}: {warnings:?}");
533        }
534        // Flags that disagree cannot be said in `hpr-design`; the mass flag decides, out loud.
535        // Where the mass covers the parts inside, the center lands on OpenRocket's anyway.
536        for (question, apart_m) in DISAGREEING {
537            let (ours, theirs, warnings) = both(probe(&record, question));
538            assert!(relative(ours[0], theirs[0]).abs() < 1e-9, "{question}");
539            assert!(
540                (ours[1] - theirs[1] - apart_m).abs() < 1e-6,
541                "{question}: center {} m apart, not {apart_m}",
542                ours[1] - theirs[1]
543            );
544            assert_eq!(warnings.len(), 1, "{question}: {warnings:?}");
545            assert!(
546                warnings[0].contains("the mass flag was taken"),
547                "{warnings:?}"
548            );
549        }
550    }
551
552    /// Stages whose mass override doesn't cover their parts, or whose center of gravity override
553    /// doesn't, with no override that covers them: by a flag of `false`, by none written, and by
554    /// the single older flag; on one stage and on a rocket of two; over a part with an override of
555    /// its own; a mass of nothing; a center ahead of the tip; and both overrides with only one
556    /// flag written, `false`. One is the rocket of two stages with no override at all: what the
557    /// two tools weigh before any of this applies.
558    const STAGE_ADDS: [&str; 19] = [
559        "a mass override on the stage, not its parts",
560        "a centre of gravity override on the stage, not its parts",
561        "both overrides on the stage, not its parts",
562        "a mass override on the stage with no flag",
563        "both overrides on the stage with no flag",
564        "a center of gravity override on the stage with no flag",
565        "a mass override on the stage, not its parts, over a part's own",
566        "both overrides on the stage, not its parts, over a part's own",
567        "a mass override of nothing on the stage, not its parts",
568        "both overrides on the stage, not its parts, the center ahead of the tip",
569        "both overrides on the stage, only the mass flag written, false",
570        "both overrides on the stage, only the center flag written, false",
571        "the old flag, false, on a stage's mass override, schema 1.4",
572        "the old flag, false, on both of a stage's overrides, schema 1.4",
573        "two stages with no override",
574        "a lower stage's mass override, not its parts",
575        "a lower stage's overrides, not its parts",
576        "an upper stage's mass override, not its parts, above another stage",
577        "two stages' overrides, not their parts",
578    ];
579
580    /// Stages with an override that covers their parts, held to OpenRocket 24.12's mass, center
581    /// and both inertias: a center of gravity override alone, a mass override alone, both, a mass
582    /// override alone over a part's own, a center beside a mass override that doesn't cover the
583    /// parts, a mass override beside a center of gravity override that doesn't, and the two
584    /// pairings with only one flag written, `true`.
585    const STAGE_WHOLE: [&str; 8] = [
586        "a center of gravity override on the stage",
587        "a mass override on the stage",
588        "both overrides on the stage",
589        "a stage override over a part's own",
590        "a mass override on the stage, not its parts, and a center that covers them",
591        "both overrides on the stage, only the center flag written, true",
592        "both overrides on the stage, only the mass flag written, true",
593        "a mass override that covers the stage's parts and a center that doesn't",
594    ];
595
596    /// The same overrides on the lower of two stages, with how far hpr's roll and pitch inertias
597    /// are from OpenRocket's (relative): the rocket's inertias, which OpenRocket sums in a way no
598    /// stage that keeps its parts in place gives (ADR-340, and
599    /// `openrockets_lower_stage_sum_is_below_its_parts_in_place`).
600    const STAGE_WHOLE_BELOW: [(&str, [f64; 2]); 2] = [
601        (
602            "a lower stage's mass override, not its parts, and a center that covers them",
603            [0.0, 0.0495],
604        ),
605        (
606            "a lower stage's mass override that covers its parts and a center that doesn't",
607            [0.0, 0.0333],
608        ),
609    ];
610
611    /// Where a stage's override covers its parts, HPR Sim leaves the parts where the design puts
612    /// them ([`hpr_design::StageOverrideRule::PartsInPlace`], ADR-340), as OpenRocket 24.12
613    /// does: the stage's inertia is its parts' about the stage's center, and the mass an override
614    /// adds sits at that center. Its mass, center and inertias are OpenRocket's, and nothing is
615    /// warned of:
616    ///
617    /// - A mass override that doesn't cover the parts, beside a center of gravity override that
618    ///   does: the mass is added to the parts, at the override's center.
619    /// - A mass override that covers the parts, beside a center of gravity override that doesn't:
620    ///   OpenRocket weighs it exactly as it does both covering them (the first assertion below),
621    ///   and so does HPR Sim.
622    ///
623    /// On the lower of two stages the mass and the center are OpenRocket's, and the inertias are
624    /// pinned ([`STAGE_WHOLE_BELOW`]).
625    #[test]
626    fn a_stage_override_covering_its_parts_beside_one_that_does_not() {
627        let record = record();
628        let structure = |question: &str| both(probe(&record, question)).1;
629        assert_eq!(
630            structure("a mass override that covers the stage's parts and a center that doesn't"),
631            structure("both overrides on the stage")
632        );
633        // A flag that isn't written reads as `false` beside one that is: OpenRocket weighs each
634        // of these four exactly as it does a pairing with both flags written, the missing one
635        // `false` (a mass that covers the parts weighs the same whatever the center's flag says,
636        // the assertion above).
637        for (one_flag, both_flags) in [
638            (
639                "both overrides on the stage, only the mass flag written, true",
640                "both overrides on the stage",
641            ),
642            (
643                "both overrides on the stage, only the center flag written, true",
644                "a mass override on the stage, not its parts, and a center that covers them",
645            ),
646            (
647                "both overrides on the stage, only the mass flag written, false",
648                "both overrides on the stage, not its parts",
649            ),
650            (
651                "both overrides on the stage, only the center flag written, false",
652                "both overrides on the stage, not its parts",
653            ),
654        ] {
655            assert_eq!(structure(one_flag), structure(both_flags), "{one_flag}");
656        }
657        // The probes can tell the two rules apart: on each, the stage's parts moved whole, or
658        // their inertia scaled with a mass that covers them, is more than 10% from OpenRocket's
659        // inertia across the axis.
660        for question in STAGE_WHOLE {
661            let (layout, warnings) = hpr(probe(&record, question));
662            assert!(warnings.is_empty(), "{question}: {warnings:?}");
663            let (ours, theirs, _) = both(probe(&record, question));
664            assert!(
665                relative(ours[0], theirs[0]).abs() < 5e-7,
666                "{question}: mass {ours:?} {theirs:?}"
667            );
668            assert!(
669                (ours[1] - theirs[1]).abs() < 2e-7,
670                "{question}: center {ours:?} {theirs:?}"
671            );
672            for k in [2, 3] {
673                assert!(
674                    relative(ours[k], theirs[k]).abs() < 3e-6,
675                    "{question}: inertia {k} {ours:?} {theirs:?}"
676                );
677            }
678            let rescaled = rescaled_pitch(&record, question, &layout);
679            assert!(
680                relative(rescaled, theirs[3]).abs() > 0.10,
681                "{question}: {rescaled} against {}",
682                theirs[3]
683            );
684        }
685        for (question, pinned) in STAGE_WHOLE_BELOW {
686            let (ours, theirs, warnings) = both(probe(&record, question));
687            assert!(warnings.is_empty(), "{question}: {warnings:?}");
688            assert!(
689                relative(ours[0], theirs[0]).abs() < 5e-7,
690                "{question}: mass {ours:?} {theirs:?}"
691            );
692            assert!(
693                (ours[1] - theirs[1]).abs() < 2e-7,
694                "{question}: center {ours:?} {theirs:?}"
695            );
696            let found = [2, 3].map(|k| (relative(ours[k], theirs[k]) * 1e4).round() / 1e4);
697            assert_eq!(found, pinned, "{question}");
698            assert!(
699                relative(ours[2], theirs[2]).abs() < 3e-6,
700                "{question}: roll {ours:?} {theirs:?}"
701            );
702        }
703    }
704
705    /// The pitch inertia `layout` would have under the rule `hpr-design` gives a stage by default
706    /// ([`hpr_design::StageOverrideRule::Rescaled`]): the same design read from `question`'s
707    /// document, its one stage's rule switched.
708    fn rescaled_pitch(record: &Value, question: &str, layout: &Layout) -> f64 {
709        let document = probe(record, question)["document"]
710            .as_str()
711            .expect("the probe's document");
712        let read = ork::read(document.as_bytes()).expect("a probe reads");
713        let mut design = ork::rocket(&read.value.document).value;
714        let mut switched = 0;
715        for stage in &mut design.stages {
716            if !stage.override_rule.is_rescaled() {
717                stage.override_rule = hpr_design::StageOverrideRule::Rescaled;
718                switched += 1;
719            }
720        }
721        assert_eq!(switched, 1, "{question}");
722        let rescaled = design.layout().expect("a probe lays out").structure;
723        assert_eq!(rescaled.mass_kg, layout.structure.mass_kg, "{question}");
724        let i = rescaled.inertia_kg_m2;
725        (i.x_axis.x + i.y_axis.y) / 2.0
726    }
727
728    /// Why the lower-stage probes keep a difference. OpenRocket 24.12's inertia across the axis
729    /// on each is, to 1e-12, the sum about the rocket's center `X` of every part at its own place
730    /// and the stage's override mass `m_o` (2 kg) as a point at the stage's stated center `c`:
731    /// `I = Σ (I_i + m_i (x_i − X)²) + m_o (c − X)²`. No stage that keeps its parts where the
732    /// design puts them gives that:
733    ///
734    /// - Read as the lower stage's own inertia about its stated center `c`, the sum is less than
735    ///   the stage's tube alone has about `c`. A stage that keeps the tube in place has at least
736    ///   that, whatever the rest of its mass does; HPR Sim's rule gives exactly that.
737    /// - Under a center that covers the parts beside an added mass, it is less even than the
738    ///   tube has about the tube's own center: no body that holds the tube has it.
739    /// - Under a mass that covers the parts, `m_o` is the whole stage's mass, so the lower tube is
740    ///   counted twice: the sum carries more mass than the rocket weighs.
741    ///
742    /// On one stage `X = c` and the sum is the parts' inertia about `c`, which is HPR Sim's rule.
743    #[test]
744    fn openrockets_lower_stage_sum_is_below_its_parts_in_place() {
745        let record = record();
746        let structure = |question: &str| {
747            let or = &probe(&record, question)["structure"];
748            ["mass_kg", "cm_x_m", "iyy"].map(|key| or[key].as_f64().expect("a number"))
749        };
750        // The upper stage alone, from the one-stage probe whose 2 kg sits at its parts' center,
751        // and the lower stage's tube, from the two stages with no override.
752        let [added_kg, upper_m, upper_i] = structure("a mass override on the stage, not its parts");
753        let upper_kg = added_kg - 2.0;
754        let [both_kg, both_m, both_i] = structure("two stages with no override");
755        let tube_kg = both_kg - upper_kg;
756        let tube_m = (both_kg * both_m - upper_kg * upper_m) / tube_kg;
757        let tube_i = both_i
758            - upper_i
759            - upper_kg * (upper_m - both_m).powi(2)
760            - tube_kg * (tube_m - both_m).powi(2);
761        assert!((tube_m - 1.05).abs() < 1e-9, "{tube_m}");
762        // The lower stage starts 0.8 m aft of the tip, and its center override is 0.4 m.
763        let center_m = 1.2;
764        for (question, _) in STAGE_WHOLE_BELOW {
765            let [kg, at_m, inertia] = structure(question);
766            let sum = upper_i
767                + upper_kg * (upper_m - at_m).powi(2)
768                + tube_i
769                + tube_kg * (tube_m - at_m).powi(2)
770                + 2.0 * (center_m - at_m).powi(2);
771            assert!(
772                relative(sum, inertia).abs() < 1e-12,
773                "{question}: {sum} {inertia}"
774            );
775            // The rocket's center is the stated one's: the stage weighs `kg − upper_kg` at 1.2 m.
776            let stage_kg = kg - upper_kg;
777            assert!(
778                ((kg * at_m - upper_kg * upper_m) / stage_kg - center_m).abs() < 1e-9,
779                "{question}"
780            );
781            // The lower stage's own inertia about its stated center, read from OpenRocket's.
782            let rigid = inertia
783                - upper_i
784                - upper_kg * (upper_m - at_m).powi(2)
785                - stage_kg * (center_m - at_m).powi(2);
786            // What its tube alone has about that center, in place: the least a stage that keeps
787            // it there can have, and HPR Sim's figure (0.0137 kg·m², against 0.0038 and 0.0070).
788            let in_place = tube_i + tube_kg * (tube_m - center_m).powi(2);
789            assert!(
790                rigid < 0.6 * in_place,
791                "{question}: {rigid} against {in_place}"
792            );
793            if (stage_kg - 2.0).abs() < 1e-12 {
794                // The mass covers the parts: the sum holds the tube and 2 kg in a 2 kg stage.
795                assert!(tube_kg + 2.0 > stage_kg + 0.3, "{question}: {tube_kg}");
796            } else {
797                assert!(
798                    (stage_kg - tube_kg - 2.0).abs() < 1e-12,
799                    "{question}: {stage_kg}"
800                );
801                assert!(rigid < 0.6 * tube_i, "{question}: {rigid} against {tube_i}");
802            }
803        }
804    }
805
806    /// OpenRocket 24.12 adds a stage's mass override that doesn't cover the stage's parts to what
807    /// the parts weigh, whether its flag is `false` or not written: as a point at the center of
808    /// that stage's own parts, or, beside a center of gravity override that doesn't cover the
809    /// parts either, at that override's station from the stage's forward end. A center of gravity
810    /// override alone that doesn't cover the parts changes nothing. HPR Sim reads each the same
811    /// way ([`hpr_design::AddedMass`], ADR-335), so the mass, the center and both inertias are
812    /// OpenRocket's, and nothing is warned of: the design flies.
813    #[test]
814    fn a_stage_override_not_covering_its_parts_adds_to_them() {
815        let record = record();
816        for question in STAGE_ADDS {
817            let (ours, theirs, warnings) = both(probe(&record, question));
818            assert!(warnings.is_empty(), "{question}: {warnings:?}");
819            assert!(
820                relative(ours[0], theirs[0]).abs() < 5e-7,
821                "{question}: mass {ours:?} {theirs:?}"
822            );
823            assert!(
824                (ours[1] - theirs[1]).abs() < 2e-7,
825                "{question}: center {ours:?} {theirs:?}"
826            );
827            for k in [2, 3] {
828                assert!(
829                    relative(ours[k], theirs[k]).abs() < 3e-6,
830                    "{question}: inertia {ours:?} {theirs:?}"
831                );
832            }
833        }
834        // What OpenRocket adds is the override's 2 kg, and the 1 kg of the lower stage's beside it.
835        let structure = |question: &str| both(probe(&record, question)).1;
836        let parts = structure("a center of gravity override on the stage with no flag");
837        let added = structure("a mass override on the stage, not its parts");
838        assert!((added[0] - parts[0] - 2.0).abs() < 1e-12, "{added:?}");
839        // With no center stated the mass sits at the parts' center, and moves nothing.
840        assert_eq!(added[1..], parts[1..]);
841        let two = structure("two stages with no override");
842        let both_add = structure("two stages' overrides, not their parts");
843        assert!((both_add[0] - two[0] - 3.0).abs() < 1e-12, "{both_add:?}");
844    }
845
846    /// A stage of a nose and a tube with no wall, which weigh nothing, under a 2 kg mass override
847    /// that doesn't cover them.
848    const STAGE_ADDS_TO_NOTHING: &str =
849        "a mass override on a stage of parts that weigh nothing, not its parts";
850
851    /// Parts that weigh nothing have no center of mass for an added mass to sit at. OpenRocket
852    /// 24.12 weighs the stage at the override's 2 kg and reports its center at a station of zero,
853    /// the tip. One probe doesn't say whether that is the stage's forward end or a number left
854    /// unset, so HPR Sim doesn't take it as a rule: the layout refuses the design, naming why.
855    #[test]
856    fn a_stages_added_mass_on_parts_that_weigh_nothing_is_refused() {
857        let record = record();
858        let probe = probe(&record, STAGE_ADDS_TO_NOTHING);
859        let theirs = &probe["structure"];
860        assert_eq!(theirs["mass_kg"], 2.0);
861        assert_eq!(theirs["cm_x_m"], 0.0);
862        let document = probe["document"].as_str().expect("the probe's document");
863        let read = ork::read(document.as_bytes()).expect("a probe reads");
864        let spine = ork::rocket(&read.value.document);
865        assert!(spine.warnings.is_empty(), "{:?}", spine.warnings);
866        let refused = spine.value.layout().expect_err("no center to sit at");
867        let hpr_design::DesignError::InComponent { id, source } = &refused else {
868            panic!("{refused:?}");
869        };
870        assert_eq!(id, &spine.value.stages[0].id);
871        assert!(
872            matches!(
873                **source,
874                hpr_design::DesignError::Domain { what, value }
875                    if what == "added mass with no station, on parts that weigh nothing (kg)"
876                        && value == 2.0
877            ),
878            "{refused:?}"
879        );
880    }
881
882    /// `openrocket-added-mass-placement.json`, held to the scripts that wrote it.
883    fn placement_record() -> Value {
884        let text =
885            include_str!("../../../validation/fixtures/ork/openrocket-added-mass-placement.json");
886        let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
887        assert_eq!(record["openrocket"], "24.12");
888        for (name, bytes) in [
889            (
890                "added_mass_placement.py",
891                include_bytes!("../../../validation/oracles/openrocket/added_mass_placement.py")
892                    .as_slice(),
893            ),
894            (
895                "pod_probes.py",
896                include_bytes!("../../../validation/oracles/openrocket/pod_probes.py").as_slice(),
897            ),
898            (
899                "conventions.py",
900                include_bytes!("../../../validation/oracles/openrocket/conventions.py").as_slice(),
901            ),
902            (
903                "events.py",
904                include_bytes!("../../../validation/oracles/openrocket/events.py").as_slice(),
905            ),
906            (
907                "automatic_radius.py",
908                include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
909                    .as_slice(),
910            ),
911        ] {
912            assert_eq!(
913                record["inputs_sha256"][name],
914                crate::real_flight::sha256_hex(bytes).as_str(),
915                "{name} changed since the record was written: rerun it"
916            );
917        }
918        record
919    }
920
921    /// One body as a placement probe weighs it: mass (kg), the center's station aft of the tip
922    /// and its distance off the axis (m), and the inertias about the axis and across it (kg·m²).
923    type Body = [f64; 5];
924
925    /// One of OpenRocket's bodies in a placement probe's record.
926    fn their_body(or: &Value) -> Body {
927        let number = |key: &str| or[key].as_f64().expect("a number");
928        [
929            number("mass_kg"),
930            number("cm_x_m"),
931            number("cm_y_m").hypot(number("cm_z_m")),
932            number("ixx"),
933            (number("iyy") + number("izz")) / 2.0,
934        ]
935    }
936
937    /// One of hpr's bodies. OpenRocket gives one inertia across the axis, the one about its y
938    /// axis, as both `iyy` and `izz`. A probe's one booster hangs off the axis along that
939    /// axis, so how far off it is adds nothing to OpenRocket's figure. hpr's inertia about the
940    /// body axis the booster lies along has no such term either: it is the smaller of the two
941    /// across the axis. A probe's body centered on the axis is the same all the way round it
942    /// (three boosters, three fins), so its two are equal, which this holds: taking the
943    /// smaller hides nothing there.
944    fn our_body(mass: &hpr_design::MassProperties) -> Body {
945        let i = mass.inertia_kg_m2;
946        if mass.cg_m.x.hypot(mass.cg_m.y) < 1e-12 {
947            assert!(
948                (i.x_axis.x - i.y_axis.y).abs() <= 1e-10 * i.x_axis.x.abs(),
949                "a body on the axis, unequal across it: {i:?}"
950            );
951        }
952        [
953            mass.mass_kg,
954            -mass.cg_m.z,
955            mass.cg_m.x.hypot(mass.cg_m.y),
956            i.z_axis.z,
957            i.x_axis.x.min(i.y_axis.y),
958        ]
959    }
960
961    /// A placement probe as each tool weighs it: the rocket, then each stage alone.
962    struct Placement {
963        rocket: Body,
964        alone: [Body; 2],
965    }
966
967    /// hpr's design of a placement probe, read with no warning.
968    fn placement_design(record: &Value, question: &str) -> hpr_design::Rocket {
969        let document = probe(record, question)["document"]
970            .as_str()
971            .expect("the probe's document");
972        let read = ork::read(document.as_bytes()).expect("a probe reads");
973        let spine = ork::rocket(&read.value.document);
974        assert!(
975            spine.warnings.is_empty(),
976            "{question}: {:?}",
977            spine.warnings
978        );
979        spine.value
980    }
981
982    fn our_placement(layout: &Layout) -> Placement {
983        assert_eq!(layout.stages.len(), 2);
984        Placement {
985            rocket: our_body(&layout.structure),
986            alone: [0, 1].map(|k| our_body(&layout.stages[k].mass)),
987        }
988    }
989
990    /// hpr's and OpenRocket's weighing of a placement probe hpr lays out.
991    fn placements(record: &Value, question: &str) -> (Placement, Placement) {
992        let layout = placement_design(record, question)
993            .layout()
994            .unwrap_or_else(|e| panic!("{question}: {e}"));
995        (our_placement(&layout), their_placement(record, question))
996    }
997
998    fn their_placement(record: &Value, question: &str) -> Placement {
999        let probe = probe(record, question);
1000        Placement {
1001            rocket: their_body(&probe["structure"]),
1002            alone: [0, 1].map(|k| their_body(&probe["alone"][k])),
1003        }
1004    }
1005
1006    /// The mass within 5 parts in 10 million, and the center within 0.2 µm along the axis and
1007    /// off it: the bounds the stage probes above hold.
1008    fn same_mass_and_center(ours: &Body, theirs: &Body, what: &str) {
1009        assert!(
1010            relative(ours[0], theirs[0]).abs() < 5e-7,
1011            "{what}: mass {ours:?} {theirs:?}"
1012        );
1013        for k in [1, 2] {
1014            assert!(
1015                (ours[k] - theirs[k]).abs() < 2e-7,
1016                "{what}: center {ours:?} {theirs:?}"
1017            );
1018        }
1019    }
1020
1021    /// Both inertias within 3 parts in a million.
1022    fn same_inertias(ours: &Body, theirs: &Body, what: &str) {
1023        for k in [3, 4] {
1024            assert!(
1025                relative(ours[k], theirs[k]).abs() < 3e-6,
1026                "{what}: inertia {ours:?} {theirs:?}"
1027            );
1028        }
1029    }
1030
1031    /// What an override adds to both inertias, against the same probe with none, within 5
1032    /// parts in 10 million of what it adds in OpenRocket, or within 1e-9 kg·m² where it adds
1033    /// less than 0.002 kg·m². The probes' airframe has fins, whose inertia hpr and OpenRocket
1034    /// don't weigh alike (`hpr_s_own_fin_roll_departs_as_pinned`), so the airframe's inertias
1035    /// are held by what is added to them.
1036    ///
1037    /// The probes with pods and with a motor aboard hold 1e-9 kg·m² flat, each in its own
1038    /// test, on overrides that add 0.00071 kg·m² and less
1039    /// (`a_stages_added_mass_sits_among_its_pods_and_level_with_their_center`,
1040    /// `a_motor_aboard_does_not_move_a_stages_added_mass`). A 2 kg mass on boosters adds more
1041    /// than 0.018 kg·m², and the flat bound doesn't hold there
1042    /// (`a_parallel_stages_override_not_covering_its_parts_adds_to_them` pins by how much). What
1043    /// a point adds is its mass times a distance squared, and the two tools' masses agree
1044    /// within 5 parts in 10 million (`same_mass_and_center`), so that share of what is added is
1045    /// the bound, with the flat one as its floor (ADR-341 decision 3).
1046    fn adds_the_same_inertias(ours: [&Body; 2], theirs: [&Body; 2], what: &str) {
1047        for k in [3, 4] {
1048            let (ours_adds, theirs_adds) = (ours[0][k] - ours[1][k], theirs[0][k] - theirs[1][k]);
1049            assert!(
1050                (ours_adds - theirs_adds).abs() < (5e-7 * theirs_adds.abs()).max(1e-9),
1051                "{what}: inertia {k} gains {ours_adds:e}, OpenRocket's {theirs_adds:e}"
1052            );
1053        }
1054    }
1055
1056    /// The two parallel stages `added_mass_placement.py` asks about: how it names each, and how
1057    /// far off the axis the boosters' center is.
1058    const BOOSTERS: [(&str, f64); 2] = [("three boosters", 0.0), ("one booster", 0.052)];
1059
1060    /// A parallel stage's overrides that don't cover its parts and sit beside none that does.
1061    const ADDS_TO_THE_BOOSTERS: [&str; 2] = [
1062        "a mass override on the parallel stage, not its parts",
1063        "both overrides on the parallel stage, not its parts",
1064    ];
1065    /// The same two with no flag written, asked with three boosters.
1066    const ADDS_WITH_NO_FLAG: [(&str, &str); 2] = [
1067        (
1068            "three boosters and a mass override on the parallel stage with no flag",
1069            "three boosters and a mass override on the parallel stage, not its parts",
1070        ),
1071        (
1072            "three boosters and both overrides on the parallel stage with no flag",
1073            "three boosters and both overrides on the parallel stage, not its parts",
1074        ),
1075    ];
1076    /// A parallel stage's added mass beside a center that covers its parts. The numbers are
1077    /// what the whole rocket's inertia gains in HPR Sim less what it gains in OpenRocket, as a
1078    /// share of OpenRocket's inertia: across the axis with three boosters and with one, then
1079    /// about the axis with one (with three, the two gain the same).
1080    const ADDS_BESIDE_A_COVERING_CENTER: (&str, [f64; 2], f64) = (
1081        "a mass override on the parallel stage, not its parts, and a center that covers them",
1082        [-0.006_289, -0.002_172],
1083        0.0,
1084    );
1085    /// A parallel stage's overrides with no added mass, where one covers its parts, and the
1086    /// same shares under each.
1087    const COVERS_THE_BOOSTERS: [(&str, [f64; 2], f64); 4] = [
1088        (
1089            "a mass override on the parallel stage",
1090            [-0.002_091, -0.000_703],
1091            -0.001_025,
1092        ),
1093        (
1094            "both overrides on the parallel stage",
1095            [-0.007_879, -0.002_676],
1096            -0.001_025,
1097        ),
1098        (
1099            "a mass override that covers the parallel stage's parts and a center that doesn't",
1100            [-0.007_879, -0.002_676],
1101            -0.001_025,
1102        ),
1103        (
1104            "a center of gravity override on the parallel stage",
1105            [-0.046_730, -0.018_921],
1106            0.0,
1107        ),
1108    ];
1109    const A_CENTER_ALONE_NOT_COVERING: &str =
1110        "a center of gravity override on the parallel stage, not its parts";
1111
1112    /// A parallel stage's mass override that doesn't cover its parts adds to them, as an axial
1113    /// stage's does (ADR-341, M2.3d10). On OpenRocket 24.12's probes the 2 kg is added once to
1114    /// the set of boosters, not to each. With no center stated it sits at the boosters' center
1115    /// and leaves the parallel stage's center and inertias the boosters' own. With a center
1116    /// override that doesn't cover the parts either, it sits at that station, measured from the
1117    /// parallel stage's forward end, as far off the axis as the boosters' center is: one
1118    /// booster's center is 52 mm off, and stays there. The stage the boosters hang on is as it
1119    /// was. A flag not written reads as `false`.
1120    ///
1121    /// HPR Sim reads each with no warning. The parallel stage alone has OpenRocket's mass,
1122    /// center and both inertias; the stage it hangs on, and the whole rocket, have OpenRocket's
1123    /// mass and center, and the override adds what it adds in OpenRocket to both of the
1124    /// rocket's inertias.
1125    #[test]
1126    fn a_parallel_stages_override_not_covering_its_parts_adds_to_them() {
1127        let record = placement_record();
1128        for (boosters, off_axis_m) in BOOSTERS {
1129            let none = format!("{boosters} and no override");
1130            let (bare_ours, bare_theirs) = placements(&record, &none);
1131            assert!((bare_theirs.alone[1][2] - off_axis_m).abs() < 1e-12);
1132            same_mass_and_center(&bare_ours.rocket, &bare_theirs.rocket, &none);
1133            same_mass_and_center(&bare_ours.alone[0], &bare_theirs.alone[0], &none);
1134            same_mass_and_center(&bare_ours.alone[1], &bare_theirs.alone[1], &none);
1135            same_inertias(&bare_ours.alone[1], &bare_theirs.alone[1], &none);
1136
1137            for (k, question) in ADDS_TO_THE_BOOSTERS.into_iter().enumerate() {
1138                let question = format!("{boosters} and {question}");
1139                let (ours, theirs) = placements(&record, &question);
1140
1141                // What OpenRocket does: 2 kg more, once; the boosters' center kept with no
1142                // station, and moved toward the station with one, along the axis only.
1143                let [stage, bare] = [theirs.alone[1], bare_theirs.alone[1]];
1144                assert!((stage[0] - bare[0] - 2.0).abs() < 1e-12, "{question}");
1145                assert!((stage[2] - bare[2]).abs() < 1e-12, "{question}");
1146                if k == 0 {
1147                    assert!((stage[1] - bare[1]).abs() < 1e-12, "{question}");
1148                    assert_eq!([stage[3], stage[4]], [bare[3], bare[4]], "{question}");
1149                } else {
1150                    // The parallel stage's forward end is 0.45 m aft of the tip (a nose of
1151                    // 0.2 m and 0.25 m down the tube), so its 0.1 m station is 0.55 m aft.
1152                    let want = (bare[0] * bare[1] + 2.0 * 0.55) / (bare[0] + 2.0);
1153                    assert!((stage[1] - want).abs() < 1e-12, "{question}: {stage:?}");
1154                    assert!(bare[1] - stage[1] > 0.06, "{question}: {stage:?}");
1155                }
1156                assert_eq!(theirs.alone[0], bare_theirs.alone[0], "{question}");
1157
1158                // HPR Sim's is the same.
1159                same_mass_and_center(&ours.alone[1], &theirs.alone[1], &question);
1160                same_inertias(&ours.alone[1], &theirs.alone[1], &question);
1161                assert_eq!(ours.alone[0], bare_ours.alone[0], "{question}");
1162                same_mass_and_center(&ours.rocket, &theirs.rocket, &question);
1163                // The bound below can tell: the override adds 9e-3 kg·m² and more across the
1164                // axis.
1165                assert!(
1166                    theirs.rocket[4] - bare_theirs.rocket[4] > 9e-3,
1167                    "{question}"
1168                );
1169                adds_the_same_inertias(
1170                    [&ours.rocket, &bare_ours.rocket],
1171                    [&theirs.rocket, &bare_theirs.rocket],
1172                    &question,
1173                );
1174                // The flat 1e-9 kg·m² of the probes with pods doesn't hold on the mass alone,
1175                // which adds 0.018 kg·m² and more: the two differ by 1.4e-9 and 1.5e-9 there,
1176                // under 8 parts in 100 million of what is added.
1177                if k == 0 {
1178                    let adds = |body: &Placement, bare: &Placement| body.rocket[4] - bare.rocket[4];
1179                    let (ours_adds, theirs_adds) =
1180                        (adds(&ours, &bare_ours), adds(&theirs, &bare_theirs));
1181                    let apart = (ours_adds - theirs_adds).abs();
1182                    assert!(theirs_adds > 0.018, "{question}: {theirs_adds}");
1183                    assert!(apart > 1.3e-9 && apart < 1.6e-9, "{question}: {apart:e}");
1184                    assert!(apart < 8e-8 * theirs_adds, "{question}: {apart:e}");
1185                }
1186            }
1187        }
1188        for (unflagged, flagged) in ADDS_WITH_NO_FLAG {
1189            let (ours, theirs) = placements(&record, unflagged);
1190            let (flagged_ours, flagged_theirs) = placements(&record, flagged);
1191            assert_eq!(theirs.rocket, flagged_theirs.rocket, "{unflagged}");
1192            assert_eq!(theirs.alone, flagged_theirs.alone, "{unflagged}");
1193            assert_eq!(ours.rocket, flagged_ours.rocket, "{unflagged}");
1194            assert_eq!(ours.alone, flagged_ours.alone, "{unflagged}");
1195        }
1196    }
1197
1198    /// The parallel stage of a placement probe laid out under `hpr-design`'s default rule,
1199    /// which rescales and moves a stage as one body: its inertia across the axis.
1200    fn rescaled_boosters(record: &Value, question: &str) -> f64 {
1201        let mut design = placement_design(record, question);
1202        assert_eq!(
1203            design.stages[1].override_rule,
1204            hpr_design::StageOverrideRule::PartsInPlace,
1205            "{question}"
1206        );
1207        design.stages[1].override_rule = hpr_design::StageOverrideRule::Rescaled;
1208        let layout = design
1209            .layout()
1210            .expect("the probe lays out under either rule");
1211        our_body(&layout.stages[1].mass)[4]
1212    }
1213
1214    /// A parallel stage's override that covers its parts leaves them in place, as an axial
1215    /// stage's does (ADR-340, extended to a parallel stage by ADR-341). On OpenRocket 24.12's
1216    /// probes the parallel stage alone weighs what a covering mass says, balances where a
1217    /// covering center says, and has its boosters' inertia about that center: under a mass
1218    /// alone the boosters' own, under a center their own and their mass times the square of
1219    /// how far the center moved. An added mass beside a covering center sits at that center
1220    /// and adds none. A center alone that doesn't cover the parts changes nothing.
1221    ///
1222    /// HPR Sim reads each with no warning and gives the parallel stage the parts-in-place rule.
1223    /// The parallel stage alone has OpenRocket's mass, center and both inertias, where the
1224    /// default rule's inertia across the axis is more than a third off. The whole rocket has
1225    /// OpenRocket's mass and center.
1226    ///
1227    /// The rocket's inertia across the axis is not OpenRocket's on these probes, and each
1228    /// shortfall is pinned: from 0.070% to 4.673% of OpenRocket's. OpenRocket sums each booster
1229    /// about the rocket's center from where the design puts it, with its own mass, and adds a
1230    /// point at the stage's stated center: the whole stated mass under a mass that covers the
1231    /// boosters, and what the stage weighs more than they do otherwise. It takes the rocket's
1232    /// center from the stage as overridden. A stage weighed as one body can't give that sum
1233    /// and OpenRocket's inertia for the stage alone
1234    /// (`openrockets_sum_with_a_parallel_stages_covering_center_is_no_bodys`). About the axis
1235    /// the rocket gains what OpenRocket's does, but for one booster under a mass that covers
1236    /// it: OpenRocket's sum there counts the booster's own mass beside the stated one, and HPR
1237    /// Sim's is 0.103% short, pinned.
1238    #[test]
1239    fn a_parallel_stages_override_covering_its_parts_leaves_them_in_place() {
1240        let record = placement_record();
1241        for (n, (boosters, _)) in BOOSTERS.into_iter().enumerate() {
1242            let none = format!("{boosters} and no override");
1243            let (bare_ours, bare_theirs) = placements(&record, &none);
1244
1245            let alone = format!("{boosters} and {A_CENTER_ALONE_NOT_COVERING}");
1246            let (ours, theirs) = placements(&record, &alone);
1247            assert_eq!(theirs.rocket, bare_theirs.rocket, "{alone}");
1248            assert_eq!(theirs.alone, bare_theirs.alone, "{alone}");
1249            assert_eq!(ours.rocket, bare_ours.rocket, "{alone}");
1250            assert_eq!(ours.alone, bare_ours.alone, "{alone}");
1251
1252            let covering =
1253                std::iter::once(ADDS_BESIDE_A_COVERING_CENTER).chain(COVERS_THE_BOOSTERS);
1254            for (question, across, about_with_one) in covering {
1255                let question = format!("{boosters} and {question}");
1256                let (ours, theirs) = placements(&record, &question);
1257
1258                // What OpenRocket does to the parallel stage alone.
1259                let [stage, bare] = [theirs.alone[1], bare_theirs.alone[1]];
1260                assert_eq!(stage[3], bare[3], "{question}");
1261                let moved = stage[1] - bare[1];
1262                let in_place = bare[4] + bare[0] * moved * moved;
1263                assert!(
1264                    relative(stage[4], in_place).abs() < 1e-12,
1265                    "{question}: {stage:?} against {in_place}"
1266                );
1267                assert_eq!(theirs.alone[0], bare_theirs.alone[0], "{question}");
1268
1269                // HPR Sim's parallel stage is the same, and its default rule's is not.
1270                same_mass_and_center(&ours.alone[1], &theirs.alone[1], &question);
1271                same_inertias(&ours.alone[1], &theirs.alone[1], &question);
1272                let rescaled = rescaled_boosters(&record, &question);
1273                assert!(
1274                    relative(rescaled, stage[4]).abs() > 0.37,
1275                    "{question}: {rescaled} against {stage:?}"
1276                );
1277                assert_eq!(ours.alone[0], bare_ours.alone[0], "{question}");
1278
1279                // The whole rocket: mass, center, and what the override adds about the axis.
1280                same_mass_and_center(&ours.rocket, &theirs.rocket, &question);
1281                let roll = (ours.rocket[3] - bare_ours.rocket[3])
1282                    - (theirs.rocket[3] - bare_theirs.rocket[3]);
1283                if n == 0 || about_with_one == 0.0 {
1284                    assert!(
1285                        roll.abs() < 1e-9,
1286                        "{question}: roll gains differ by {roll:e}"
1287                    );
1288                } else {
1289                    let short = roll / theirs.rocket[3];
1290                    assert!(
1291                        (short - about_with_one).abs() < 5e-6,
1292                        "{question}: about the axis {short} against {about_with_one}"
1293                    );
1294                }
1295                // Across the axis, pinned: what the override adds short of OpenRocket's, as a
1296                // share of OpenRocket's inertia.
1297                let short = ((ours.rocket[4] - bare_ours.rocket[4])
1298                    - (theirs.rocket[4] - bare_theirs.rocket[4]))
1299                    / theirs.rocket[4];
1300                assert!(
1301                    (short - across[n]).abs() < 5e-6,
1302                    "{question}: across the axis {short} against {}",
1303                    across[n]
1304                );
1305            }
1306        }
1307    }
1308
1309    /// Why no stage weighed as one body gives OpenRocket 24.12's inertia across the axis beside
1310    /// a parallel stage whose center override covers its parts. From OpenRocket's own records,
1311    /// with three boosters: its figure for the rocket is the stage the boosters hang on about
1312    /// the rocket's center, the boosters about that center from where the design puts them,
1313    /// 0.62 m aft of the tip, and the 2 kg added mass as a point at the stated center, 0.55 m
1314    /// aft. The rocket's center, though, is taken with the boosters' mass at 0.55 m. A body's
1315    /// inertia about a point goes with where its mass is, so the stage as OpenRocket weighs it
1316    /// alone, taken as one body, can't give that sum. The sum
1317    /// is more than that body's by `2 m (x − c)(c − X)`, with the boosters' mass `m`, their
1318    /// center `x`, the stated center `c` and the rocket's center `X`: the shortfall the test
1319    /// above pins. Closing it means composing the inertia at the rocket's level, as M2.3d14
1320    /// plans (ADR-341).
1321    ///
1322    /// The second half holds the same sum on all ten probes whose override covers the boosters.
1323    /// Under a mass that covers them, OpenRocket's point is the whole stated mass, beside the
1324    /// boosters' own: their mass is counted twice, which is why those rows fall short even
1325    /// where the center doesn't move.
1326    #[test]
1327    fn openrockets_sum_with_a_parallel_stages_covering_center_is_no_bodys() {
1328        let record = placement_record();
1329        let bare = their_placement(&record, "three boosters and no override");
1330        let question = format!("three boosters and {}", ADDS_BESIDE_A_COVERING_CENTER.0);
1331        let theirs = their_placement(&record, &question);
1332        let [core, boosters] = bare.alone;
1333        let (at, center) = (theirs.rocket[1], 0.55);
1334        assert!((theirs.alone[1][1] - center).abs() < 1e-12);
1335        let about = |body: &Body| body[4] + body[0] * (body[1] - at).powi(2);
1336        let sum = about(&core) + about(&boosters) + 2.0 * (center - at).powi(2);
1337        assert!(
1338            relative(sum, theirs.rocket[4]).abs() < 1e-12,
1339            "{sum} against {:?}",
1340            theirs.rocket
1341        );
1342        // One body: the parallel stage as OpenRocket weighs it alone, about the same center.
1343        let body = about(&core) + about(&theirs.alone[1]);
1344        let more = 2.0 * boosters[0] * (boosters[1] - center) * (center - at);
1345        assert!((sum - body - more).abs() < 1e-12, "{sum} {body} {more}");
1346        assert!(
1347            (more / theirs.rocket[4] + ADDS_BESIDE_A_COVERING_CENTER.1[0]).abs() < 5e-6,
1348            "{more} of {:?}",
1349            theirs.rocket
1350        );
1351
1352        // About the axis, with one booster under a mass that covers it, the same sum holds: the
1353        // stage the booster hangs on, the booster where the design puts it with its own mass,
1354        // and the stated mass as a point at the stage's center, each as far from the rocket's
1355        // center as it is off the axis. One body leaves the booster's own mass out.
1356        for (question, _, about_with_one) in COVERS_THE_BOOSTERS {
1357            if about_with_one == 0.0 {
1358                continue;
1359            }
1360            let bare = their_placement(&record, "one booster and no override");
1361            let theirs = their_placement(&record, &format!("one booster and {question}"));
1362            let ([core, pod], stage, off) = (bare.alone, theirs.alone[1], theirs.rocket[2]);
1363            let about = |body: &Body| body[3] + body[0] * (body[2] - off).powi(2);
1364            let sum = about(&core) + about(&pod) + stage[0] * (stage[2] - off).powi(2);
1365            assert!(
1366                relative(sum, theirs.rocket[3]).abs() < 1e-11,
1367                "{question}: {sum} against {:?}",
1368                theirs.rocket
1369            );
1370            let body = about(&core) + about(&stage);
1371            assert!(
1372                ((body - sum) / theirs.rocket[3] - about_with_one).abs() < 5e-6,
1373                "{question}: {body} {sum}"
1374            );
1375        }
1376
1377        // The same sum on each probe whose override covers the boosters, with three and with
1378        // one: the stage they hang on and each booster where the design puts it, with its own
1379        // mass, and a point at the parallel stage's center. Where the mass override doesn't
1380        // cover the boosters, the point is what the stage weighs more than they do. Where it
1381        // does, the point is the whole stated mass, so the boosters' own is counted beside it.
1382        let covering = std::iter::once(ADDS_BESIDE_A_COVERING_CENTER).chain(COVERS_THE_BOOSTERS);
1383        for (k, (question, _, _)) in covering.enumerate() {
1384            let covers_the_mass = matches!(k, 1..=3);
1385            assert_eq!(
1386                covers_the_mass,
1387                !question.contains("not its parts") && question.contains("mass")
1388                    || question.starts_with("both"),
1389                "{question}"
1390            );
1391            for (boosters, _) in BOOSTERS {
1392                let bare = their_placement(&record, &format!("{boosters} and no override"));
1393                let theirs = their_placement(&record, &format!("{boosters} and {question}"));
1394                let ([core, pods], stage, at) = (bare.alone, theirs.alone[1], theirs.rocket[1]);
1395                let about = |body: &Body| body[4] + body[0] * (body[1] - at).powi(2);
1396                let point_kg = if covers_the_mass {
1397                    assert_eq!(stage[0], 2.0, "{boosters} and {question}");
1398                    stage[0]
1399                } else {
1400                    stage[0] - pods[0]
1401                };
1402                let sum = about(&core) + about(&pods) + point_kg * (stage[1] - at).powi(2);
1403                assert!(
1404                    relative(sum, theirs.rocket[4]).abs() < 1e-11,
1405                    "{boosters} and {question}: {sum} against {:?}",
1406                    theirs.rocket
1407                );
1408            }
1409        }
1410    }
1411
1412    /// An added mass at a station, on the stage a parallel stage hangs on (ADR-341, M2.3d10).
1413    /// On OpenRocket 24.12's probes with three boosters, 2 kg at 0.4 m on that stage leaves the
1414    /// parallel stage as it was, and the stage alone is its parts and a point 0.4 m aft of the
1415    /// tip. HPR Sim reads each with no warning: both stages alone and the whole rocket have
1416    /// OpenRocket's mass and center, the parallel stage OpenRocket's inertias, and the override
1417    /// adds what it adds in OpenRocket to the inertias of the stage and of the rocket.
1418    ///
1419    /// With one booster, off the axis, HPR Sim refuses the layout. OpenRocket's rocket is then
1420    /// as far off the axis as it was with no override, 2.7 mm, where a 2 kg point on the axis
1421    /// would pull it in to 0.4 mm: with the booster hanging there, OpenRocket's point sits off
1422    /// the axis with the rocket's center, and on the axis once the booster is gone. With 2 kg
1423    /// on the booster as well, the rocket stays 44 mm off the axis, not 24 mm.
1424    #[test]
1425    fn an_added_mass_at_a_station_on_the_stage_boosters_hang_on() {
1426        let record = placement_record();
1427        let none = "three boosters and no override";
1428        let (bare_ours, bare_theirs) = placements(&record, none);
1429        for (question, on_boosters) in [
1430            (
1431                "both overrides on the stage they hang on, not its parts",
1432                "no override",
1433            ),
1434            (
1435                "both overrides on each stage, not its parts",
1436                ADDS_TO_THE_BOOSTERS[1],
1437            ),
1438        ] {
1439            let question = format!("three boosters and {question}");
1440            let (ours, theirs) = placements(&record, &question);
1441            let (beside_ours, beside_theirs) =
1442                placements(&record, &format!("three boosters and {on_boosters}"));
1443
1444            let [stage, bare] = [theirs.alone[0], bare_theirs.alone[0]];
1445            let want = (bare[0] * bare[1] + 2.0 * 0.4) / (bare[0] + 2.0);
1446            assert!((stage[0] - bare[0] - 2.0).abs() < 1e-12, "{question}");
1447            assert!((stage[1] - want).abs() < 1e-12, "{question}: {stage:?}");
1448            assert_eq!(theirs.alone[1], beside_theirs.alone[1], "{question}");
1449
1450            same_mass_and_center(&ours.alone[0], &theirs.alone[0], &question);
1451            assert!(stage[4] - bare[4] > 8e-4, "{question}: {stage:?}");
1452            adds_the_same_inertias(
1453                [&ours.alone[0], &bare_ours.alone[0]],
1454                [&theirs.alone[0], &bare_theirs.alone[0]],
1455                &question,
1456            );
1457            assert_eq!(ours.alone[1], beside_ours.alone[1], "{question}");
1458            same_mass_and_center(&ours.alone[1], &theirs.alone[1], &question);
1459            same_inertias(&ours.alone[1], &theirs.alone[1], &question);
1460            same_mass_and_center(&ours.rocket, &theirs.rocket, &question);
1461            adds_the_same_inertias(
1462                [&ours.rocket, &bare_ours.rocket],
1463                [&theirs.rocket, &bare_theirs.rocket],
1464                &question,
1465            );
1466        }
1467
1468        let bare = their_placement(&record, "one booster and no override");
1469        for question in [
1470            "one booster and both overrides on the stage they hang on, not its parts",
1471            "one booster and both overrides on each stage, not its parts",
1472        ] {
1473            let refused = placement_design(&record, question)
1474                .layout()
1475                .expect_err("one booster off the axis");
1476            assert!(
1477                refused.to_string().contains("one pod off the axis"),
1478                "{question}: {refused}"
1479            );
1480        }
1481        let theirs = their_placement(
1482            &record,
1483            "one booster and both overrides on the stage they hang on, not its parts",
1484        );
1485        assert!((theirs.rocket[2] - bare.rocket[2]).abs() < 1e-12);
1486        assert!(
1487            (bare.rocket[2] - 0.002_749).abs() < 1e-6,
1488            "{:?}",
1489            bare.rocket
1490        );
1491        let on_the_axis = bare.rocket[0] * bare.rocket[2] / theirs.rocket[0];
1492        assert!((on_the_axis - 0.000_441).abs() < 1e-6, "{on_the_axis}");
1493        assert_eq!(theirs.alone[0][2], 0.0);
1494        // With 2 kg at a station on the booster too, the rocket is as far off the axis as
1495        // with that override alone, 44 mm, where a point on the axis would pull it in to 24 mm.
1496        let each = their_placement(
1497            &record,
1498            "one booster and both overrides on each stage, not its parts",
1499        );
1500        let beside = their_placement(
1501            &record,
1502            &format!("one booster and {}", ADDS_TO_THE_BOOSTERS[1]),
1503        );
1504        assert!((each.rocket[2] - beside.rocket[2]).abs() < 1e-12);
1505        assert!(
1506            (beside.rocket[2] - 0.044_105).abs() < 1e-6,
1507            "{:?}",
1508            beside.rocket
1509        );
1510        let on_the_axis = beside.rocket[0] * beside.rocket[2] / each.rocket[0];
1511        assert!((on_the_axis - 0.023_974).abs() < 1e-6, "{on_the_axis}");
1512        assert_eq!(each.alone[0][2], 0.0);
1513    }
1514
1515    /// The overrides `added_mass_placement.py` puts on the stage the boosters hang on that HPR
1516    /// Sim still refuses, each with the words of the refusal.
1517    const STILL_REFUSED_ON_THE_CORE: [(&str, &str); 6] = [
1518        (
1519            "a mass override on the stage they hang on, not its parts",
1520            "carries an added mass with no station",
1521        ),
1522        (
1523            "a mass override on each stage, not its parts",
1524            "carries an added mass with no station",
1525        ),
1526        (
1527            "a mass override on the stage they hang on, not its parts, and a center that covers them",
1528            "carries an added mass with no station",
1529        ),
1530        (
1531            "a mass override on the stage they hang on",
1532            "under a mass override that covers",
1533        ),
1534        (
1535            "both overrides on the stage they hang on",
1536            "under a mass override that covers",
1537        ),
1538        (
1539            "a center of gravity override on the stage they hang on",
1540            "under a mass override that covers",
1541        ),
1542    ];
1543
1544    /// What OpenRocket 24.12 does where HPR Sim still refuses the layout (ADR-341): the stage a
1545    /// parallel stage hangs on is weighed with the boosters while they hang there, and without
1546    /// them once they are gone.
1547    ///
1548    /// - A 2 kg mass that doesn't cover the parts, with no center stated, leaves the rocket's
1549    ///   center where it was with no override: the point sits at the center of the stage and
1550    ///   its boosters together. The stage alone keeps its own parts' center, 39 mm forward of
1551    ///   that with three boosters and 14 mm with one. So the point moves when the boosters
1552    ///   drop. With 2 kg on the parallel stage too, it sits at the center of all the rest.
1553    /// - A center that covers the parts is the rocket's center with the boosters, and the
1554    ///   stage's without them. A mass that covers the parts is the rocket's mass with the
1555    ///   boosters, and the stage's without them: the rocket weighs 2 kg either way, and the
1556    ///   boosters alone their own 61 g or 20 g.
1557    ///
1558    /// HPR Sim weighs each stage as one body that keeps its mass and its center when another
1559    /// drops, so it refuses these, by the words named. M2.3d11 is the work.
1560    #[test]
1561    fn the_stage_boosters_hang_on_is_weighed_with_them_in_openrocket() {
1562        let record = placement_record();
1563        for (boosters, gap_m) in [("three boosters", 0.039), ("one booster", 0.014)] {
1564            for (question, says) in STILL_REFUSED_ON_THE_CORE {
1565                let question = format!("{boosters} and {question}");
1566                let refused = placement_design(&record, &question)
1567                    .layout()
1568                    .expect_err("refused");
1569                assert!(refused.to_string().contains(says), "{question}: {refused}");
1570            }
1571            let asked =
1572                |question: &str| their_placement(&record, &format!("{boosters} and {question}"));
1573            let bare = asked("no override");
1574            let [added, each, beside, whole, both, center] =
1575                STILL_REFUSED_ON_THE_CORE.map(|(question, _)| asked(question));
1576            // An added mass with no station: at the center of everything that hangs together.
1577            assert!((added.rocket[0] - bare.rocket[0] - 2.0).abs() < 1e-12);
1578            for k in [1, 2] {
1579                assert!(
1580                    (added.rocket[k] - bare.rocket[k]).abs() < 1e-12,
1581                    "{boosters}"
1582                );
1583                assert!(
1584                    (added.alone[0][k] - bare.alone[0][k]).abs() < 1e-12,
1585                    "{boosters}"
1586                );
1587            }
1588            let moves = added.rocket[1] - added.alone[0][1];
1589            assert!((moves - gap_m).abs() < 5e-4, "{boosters}: {moves}");
1590            assert_eq!(added.alone[1], bare.alone[1]);
1591            let rest = asked(ADDS_TO_THE_BOOSTERS[0]);
1592            assert!((each.rocket[0] - rest.rocket[0] - 2.0).abs() < 1e-12);
1593            for k in [1, 2] {
1594                assert!(
1595                    (each.rocket[k] - rest.rocket[k]).abs() < 1e-12,
1596                    "{boosters}"
1597                );
1598            }
1599            // A center that covers the parts: the rocket's with the boosters, the stage's
1600            // without. Off the axis the rocket stays where it was.
1601            for covered in [&beside, &both, &center] {
1602                assert!((covered.rocket[1] - 0.4).abs() < 1e-12, "{boosters}");
1603                assert!((covered.alone[0][1] - 0.4).abs() < 1e-12, "{boosters}");
1604                assert!(
1605                    (covered.rocket[2] - bare.rocket[2]).abs() < 1e-12,
1606                    "{boosters}"
1607                );
1608                assert_eq!(covered.alone[1], bare.alone[1]);
1609            }
1610            assert!((beside.rocket[0] - bare.rocket[0] - 2.0).abs() < 1e-12);
1611            assert!((center.rocket[0] - bare.rocket[0]).abs() < 1e-12);
1612            // A mass that covers the parts: the rocket's with the boosters, the stage's without.
1613            for covered in [&whole, &both] {
1614                assert_eq!(covered.rocket[0], 2.0, "{boosters}");
1615                assert_eq!(covered.alone[0][0], 2.0, "{boosters}");
1616                assert_eq!(covered.alone[1], bare.alone[1]);
1617            }
1618        }
1619    }
1620
1621    /// `added_mass_placement.py`'s stages that weigh nothing, each with an added mass and no
1622    /// station: the question, and the stage that carries the mass.
1623    const NO_PLACE_TO_SIT: [(&str, usize); 8] = [
1624        (
1625            "a lower stage that weighs nothing, a mass override on it, not its parts",
1626            1,
1627        ),
1628        (
1629            "a lower stage that weighs nothing, a mass override on it, not its parts, and a center that covers them",
1630            1,
1631        ),
1632        (
1633            "an upper stage that weighs nothing, a mass override on it, not its parts",
1634            0,
1635        ),
1636        (
1637            "an upper stage that weighs nothing, a mass override on it, not its parts, and a center that covers them",
1638            0,
1639        ),
1640        (
1641            "two stages that weigh nothing, a mass override on the lower, not its parts",
1642            1,
1643        ),
1644        (
1645            "two stages that weigh nothing, a mass override on the upper, not its parts",
1646            0,
1647        ),
1648        (
1649            "two stages that weigh nothing, a mass override on each, not its parts",
1650            0,
1651        ),
1652        (
1653            "three boosters that weigh nothing and a mass override on the parallel stage, not its parts",
1654            1,
1655        ),
1656    ];
1657
1658    /// Where OpenRocket 24.12 puts an added mass with no station on parts that weigh nothing
1659    /// (ADR-341), on six of the eight probes: at the rocket's tip, on the axis, whichever
1660    /// stage carries it. A lower stage that starts 0.8 m aft of the tip and boosters that start
1661    /// 0.45 m aft, 52 mm off the axis, each weigh their 2 kg at the tip, alone as with the other
1662    /// stage: the rocket's center is its stages' alone, summed. On the other two a center that
1663    /// covers the parts is beside the mass, and the 2 kg is at that center: 0.4 m aft of the
1664    /// stage's forward end.
1665    ///
1666    /// HPR Sim refuses each: a mass at the tip of the rocket is the placement that reads the
1667    /// stability margin highest. M2.3d12 is the work. With a station of its own the mass has a
1668    /// place, and on the one probe of it, a lower stage that weighs nothing, HPR Sim's stage is
1669    /// OpenRocket's.
1670    #[test]
1671    fn an_added_mass_on_parts_that_weigh_nothing_sits_at_the_tip_in_openrocket() {
1672        let record = placement_record();
1673        for (question, stage) in NO_PLACE_TO_SIT {
1674            let design = placement_design(&record, question);
1675            let refused = design.layout().expect_err("no center to sit at");
1676            let hpr_design::DesignError::InComponent { id, source } = &refused else {
1677                panic!("{question}: {refused:?}");
1678            };
1679            assert_eq!(id, &design.stages[stage].id, "{question}");
1680            assert!(
1681                matches!(
1682                    **source,
1683                    hpr_design::DesignError::Domain { what, value }
1684                        if what == "added mass with no station, on parts that weigh nothing (kg)"
1685                            && value == 2.0
1686                ),
1687                "{question}: {refused:?}"
1688            );
1689            let theirs = their_placement(&record, question).alone[stage];
1690            let covered = question.ends_with("a center that covers them");
1691            let station = match (covered, stage) {
1692                (false, _) => 0.0,
1693                (true, 0) => 0.4,
1694                (true, _) => 1.2,
1695            };
1696            assert!(
1697                (theirs[1] - station).abs() < 1e-12,
1698                "{question}: {theirs:?}"
1699            );
1700            // With the other stage, the mass sits where it sits alone.
1701            let whole = their_placement(&record, question);
1702            let moment = |body: &Body| body[0] * body[1];
1703            let summed: f64 = whole.alone.iter().map(moment).sum();
1704            assert!(
1705                (moment(&whole.rocket) - summed).abs() < 1e-12,
1706                "{question}: {whole_rocket:?}",
1707                whole_rocket = whole.rocket
1708            );
1709            let weighed: f64 = whole.alone.iter().map(|body| body[0]).sum();
1710            assert!((whole.rocket[0] - weighed).abs() < 1e-12, "{question}");
1711            assert_eq!(
1712                [theirs[0], theirs[2], theirs[3], theirs[4]],
1713                [2.0, 0.0, 0.0, 0.0],
1714                "{question}"
1715            );
1716        }
1717        // The weightless stages do start aft of the tip: the lower stage's 2 kg at a station
1718        // 0.4 m aft of its forward end is 1.2 m aft of the tip, in both tools.
1719        let none = "a lower stage that weighs nothing, with no override";
1720        let (ours, theirs) = placements(&record, none);
1721        assert_eq!(theirs.alone[1], [0.0; 5]);
1722        assert_eq!(ours.alone[1][0], 0.0);
1723        same_mass_and_center(&ours.rocket, &theirs.rocket, none);
1724        same_inertias(&ours.rocket, &theirs.rocket, none);
1725        let stationed = "a lower stage that weighs nothing, both overrides on it, not its parts";
1726        let (ours, theirs) = placements(&record, stationed);
1727        for alone in [theirs.alone[1], ours.alone[1]] {
1728            assert!((alone[1] - 1.2).abs() < 1e-12, "{alone:?}");
1729            assert_eq!(
1730                [alone[0], alone[2], alone[3], alone[4]],
1731                [2.0, 0.0, 0.0, 0.0]
1732            );
1733        }
1734        same_mass_and_center(&ours.rocket, &theirs.rocket, stationed);
1735        same_inertias(&ours.rocket, &theirs.rocket, stationed);
1736    }
1737
1738    /// `added_mass_placement.py`'s probes with the airframe's motor aboard, beside the first:
1739    /// three boosters and no override.
1740    const BOOSTERS_WITH_A_MOTOR: [&str; 3] = [
1741        "three boosters, a motor in the airframe and no override",
1742        "three boosters, a motor in the airframe and a mass override on the parallel stage, not its parts",
1743        "three boosters, a motor in the airframe and both overrides on the parallel stage, not its parts",
1744    ];
1745
1746    /// A motor aboard doesn't move a parallel stage's added mass, as it doesn't move an axial
1747    /// stage's (`a_motor_aboard_does_not_move_a_stages_added_mass`). The motor is what launch,
1748    /// or burnout, adds to OpenRocket 24.12's structure with no override, and under each
1749    /// override its launch and burnout are that same motor added to the overridden structure.
1750    /// HPR Sim's structure of each probe has OpenRocket's mass and center, the parallel stage
1751    /// alone both of OpenRocket's inertias, and the override adds what it adds in OpenRocket
1752    /// to the rocket's inertias. OpenRocket's launch and burnout are held by mass and center
1753    /// only. These are the designs the command line's test flies.
1754    #[test]
1755    fn a_motor_aboard_does_not_move_a_parallel_stages_added_mass() {
1756        let record = placement_record();
1757        let weighed = |question: &str, when: &str| {
1758            let body = &probe(&record, question)[when];
1759            ["mass_kg", "cm_x_m"].map(|key| body[key].as_f64().expect("a number"))
1760        };
1761        let none = BOOSTERS_WITH_A_MOTOR[0];
1762        let [bare_kg, bare_m] = weighed(none, "structure");
1763        for when in ["launch", "burnout"] {
1764            let [with_kg, with_m] = weighed(none, when);
1765            let motor_kg = with_kg - bare_kg;
1766            let motor_m = (with_kg * with_m - bare_kg * bare_m) / motor_kg;
1767            assert!(motor_kg > 0.05 && motor_m > bare_m, "{motor_kg} {motor_m}");
1768            for question in &BOOSTERS_WITH_A_MOTOR[1..] {
1769                let [structure_kg, structure_m] = weighed(question, "structure");
1770                let [got_kg, got_m] = weighed(question, when);
1771                assert!(
1772                    (got_kg - (structure_kg + motor_kg)).abs() < 1e-12,
1773                    "{question} at {when}: {got_kg}"
1774                );
1775                let want_m =
1776                    (structure_kg * structure_m + motor_kg * motor_m) / (structure_kg + motor_kg);
1777                assert!(
1778                    (got_m - want_m).abs() < 1e-12,
1779                    "{question} at {when}: {got_m} against {want_m}"
1780                );
1781            }
1782            // The test can tell: the motor moves the rocket's center 6 cm and more, so a mass
1783            // that followed a center with the motor counted would move too.
1784            assert!(with_m - bare_m > 0.06, "{when}: {with_m} {bare_m}");
1785        }
1786        let (bare_ours, bare_theirs) = placements(&record, none);
1787        for question in BOOSTERS_WITH_A_MOTOR {
1788            let (ours, theirs) = placements(&record, question);
1789            same_mass_and_center(&ours.rocket, &theirs.rocket, question);
1790            same_mass_and_center(&ours.alone[1], &theirs.alone[1], question);
1791            same_inertias(&ours.alone[1], &theirs.alone[1], question);
1792            adds_the_same_inertias(
1793                [&ours.rocket, &bare_ours.rocket],
1794                [&theirs.rocket, &bare_theirs.rocket],
1795                question,
1796            );
1797        }
1798    }
1799
1800    /// Every probe `added_mass_placement.py` recorded is read by one of the tests above.
1801    #[test]
1802    fn every_placement_probe_is_checked() {
1803        let record = placement_record();
1804        let mut read: Vec<String> = Vec::new();
1805        for (boosters, _) in BOOSTERS {
1806            read.push(format!("{boosters} and no override"));
1807            let on_the_boosters = ADDS_TO_THE_BOOSTERS
1808                .into_iter()
1809                .chain([ADDS_BESIDE_A_COVERING_CENTER.0, A_CENTER_ALONE_NOT_COVERING])
1810                .chain(COVERS_THE_BOOSTERS.map(|(question, ..)| question));
1811            let on_the_core = [
1812                "both overrides on the stage they hang on, not its parts",
1813                "both overrides on each stage, not its parts",
1814            ]
1815            .into_iter()
1816            .chain(STILL_REFUSED_ON_THE_CORE.map(|(question, _)| question));
1817            read.extend(
1818                on_the_boosters
1819                    .chain(on_the_core)
1820                    .map(|question| format!("{boosters} and {question}")),
1821            );
1822        }
1823        read.extend(ADDS_WITH_NO_FLAG.map(|(unflagged, _)| unflagged.to_owned()));
1824        read.extend(NO_PLACE_TO_SIT.map(|(question, _)| question.to_owned()));
1825        read.extend(
1826            [
1827                "a lower stage that weighs nothing, with no override",
1828                "a lower stage that weighs nothing, both overrides on it, not its parts",
1829            ]
1830            .map(str::to_owned),
1831        );
1832        read.extend(BOOSTERS_WITH_A_MOTOR.map(str::to_owned));
1833        read.sort_unstable();
1834        let mut recorded: Vec<&str> = record["probes"]
1835            .as_object()
1836            .expect("the record's probes")
1837            .keys()
1838            .map(String::as_str)
1839            .collect();
1840        recorded.sort_unstable();
1841        assert_eq!(read, recorded);
1842        // HPR Sim lays out 27 of the 49 and refuses 22: 12 with an override on the stage the
1843        // boosters hang on, 2 with a mass at a station there beside one booster, and 8 with
1844        // no place for the mass to sit.
1845        let laid_out = recorded
1846            .iter()
1847            .filter(|question| placement_design(&record, question).layout().is_ok())
1848            .count();
1849        assert_eq!((recorded.len(), laid_out), (49, 27));
1850        // 25 of the 27 carry boosters; the other two are a lower stage that weighs nothing.
1851        let with_boosters = recorded
1852            .iter()
1853            .map(|question| placement_design(&record, question))
1854            .filter(|design| design.stages.iter().any(|stage| stage.parallel.is_some()))
1855            .filter(|design| design.layout().is_ok())
1856            .count();
1857        assert_eq!(with_boosters, 25);
1858        assert_eq!(
1859            2 * STILL_REFUSED_ON_THE_CORE.len() + 2 + NO_PLACE_TO_SIT.len(),
1860            22
1861        );
1862    }
1863
1864    /// `openrocket-stage-added-mass.json`, held to the scripts that wrote it.
1865    fn added_mass_record() -> Value {
1866        let text =
1867            include_str!("../../../validation/fixtures/ork/openrocket-stage-added-mass.json");
1868        let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
1869        assert_eq!(record["openrocket"], "24.12");
1870        for (name, bytes) in [
1871            (
1872                "stage_added_mass.py",
1873                include_bytes!("../../../validation/oracles/openrocket/stage_added_mass.py")
1874                    .as_slice(),
1875            ),
1876            (
1877                "pod_probes.py",
1878                include_bytes!("../../../validation/oracles/openrocket/pod_probes.py").as_slice(),
1879            ),
1880            (
1881                "conventions.py",
1882                include_bytes!("../../../validation/oracles/openrocket/conventions.py").as_slice(),
1883            ),
1884            (
1885                "events.py",
1886                include_bytes!("../../../validation/oracles/openrocket/events.py").as_slice(),
1887            ),
1888            (
1889                "automatic_radius.py",
1890                include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
1891                    .as_slice(),
1892            ),
1893        ] {
1894            assert_eq!(
1895                record["inputs_sha256"][name],
1896                crate::real_flight::sha256_hex(bytes).as_str(),
1897                "{name} changed since the record was written: rerun it"
1898            );
1899        }
1900        record
1901    }
1902
1903    /// `stage_added_mass.py`'s probes on the airframe with pods: the airframe with no override,
1904    /// then that airframe under each override.
1905    const ADDED_WITH_PODS: [(&str, &[&str]); 2] = [
1906        (
1907            "three pods and no override",
1908            &["three pods and a mass override on the stage, not its parts"],
1909        ),
1910        (
1911            "one pod and no override",
1912            &[
1913                "one pod and a mass override on the stage, not its parts",
1914                "one pod and both overrides on the stage, not its parts",
1915                "one pod and a mass override on the stage, not its parts, and a center that covers them",
1916            ],
1917        ),
1918    ];
1919
1920    /// A stage's pods are among the parts its added mass sits among, and a station moves the
1921    /// added mass along the axis only (ADR-335). Three pods move the parts' center aft, and
1922    /// OpenRocket 24.12's added mass with no station leaves the center there: it sits at the
1923    /// center with the pods counted. One pod pulls the parts' center off the axis, and under every
1924    /// override OpenRocket's center stays that far off it: an added mass at a station sits as far
1925    /// off the axis as the parts' center, not on it, as a center override moves a stage along
1926    /// the axis only. HPR Sim's structure of each probe has OpenRocket's mass, its center along
1927    /// the axis and its distance off it, and the inertia the override adds, under a center that
1928    /// covers the parts too (ADR-340).
1929    #[test]
1930    fn a_stages_added_mass_sits_among_its_pods_and_level_with_their_center() {
1931        let record = added_mass_record();
1932        let theirs = |question: &str, key: &str| {
1933            probe(&record, question)["structure"][key]
1934                .as_f64()
1935                .expect("a number")
1936        };
1937        let off_axis_m =
1938            |question: &str| theirs(question, "cm_y_m").hypot(theirs(question, "cm_z_m"));
1939        // Three pods: the parts' center is centimeters aft of the airframe's with none, and the
1940        // added mass doesn't move it.
1941        let [three, three_added] = [
1942            "three pods and no override",
1943            "three pods and a mass override on the stage, not its parts",
1944        ];
1945        assert!(theirs(three, "cm_x_m") - theirs("no override", "cm_x_m") > 0.03);
1946        assert!((theirs(three_added, "cm_x_m") - theirs(three, "cm_x_m")).abs() < 1e-12);
1947        assert!((theirs(three_added, "mass_kg") - theirs(three, "mass_kg") - 2.0).abs() < 1e-12);
1948        // One pod: the parts' center is millimeters off the axis, and stays there under each
1949        // override. On the axis, a 2 kg point would pull it most of the way back.
1950        let (one, one_added) = ADDED_WITH_PODS[1];
1951        assert!(off_axis_m(one) > 0.0025, "{}", off_axis_m(one));
1952        for question in one_added {
1953            assert!(
1954                (off_axis_m(question) - off_axis_m(one)).abs() < 1e-12,
1955                "{question}: {}",
1956                off_axis_m(question)
1957            );
1958        }
1959
1960        // Every probe in the record is read, here or with the motor above.
1961        let mut read: Vec<&str> = std::iter::once("no override")
1962            .chain(ADDED_WITH_A_MOTOR)
1963            .collect();
1964        for (bare, added) in ADDED_WITH_PODS {
1965            read.push(bare);
1966            read.extend(added);
1967        }
1968        read.sort_unstable();
1969        let mut recorded: Vec<&str> = record["probes"]
1970            .as_object()
1971            .expect("the record's probes")
1972            .keys()
1973            .map(String::as_str)
1974            .collect();
1975        recorded.sort_unstable();
1976        assert_eq!(read, recorded);
1977
1978        // The station's probe gains an inertia across the axis that the bound below can tell
1979        // from none: 2.9e-4 kg·m², against a bound of 1e-9.
1980        let gained = (theirs(one_added[1], "iyy") + theirs(one_added[1], "izz")) / 2.0
1981            - (theirs(one, "iyy") + theirs(one, "izz")) / 2.0;
1982        assert!(gained > 2.9e-4, "{gained:e}");
1983        for (bare, added) in ADDED_WITH_PODS {
1984            let (bare_ours, bare_theirs, _) = both(probe(&record, bare));
1985            for question in std::iter::once(bare).chain(added.iter().copied()) {
1986                let (layout, warnings) = hpr(probe(&record, question));
1987                let (ours, theirs_, _) = both(probe(&record, question));
1988                assert!(warnings.is_empty(), "{question}: {warnings:?}");
1989                assert!(
1990                    relative(ours[0], theirs_[0]).abs() < 5e-7,
1991                    "{question}: mass {ours:?} {theirs_:?}"
1992                );
1993                assert!(
1994                    (ours[1] - theirs_[1]).abs() < 2e-7,
1995                    "{question}: center {ours:?} {theirs_:?}"
1996                );
1997                let center = layout.structure.cg_m;
1998                assert!(
1999                    (center.x.hypot(center.y) - off_axis_m(question)).abs() < 2e-7,
2000                    "{question}: {center:?} against {}",
2001                    off_axis_m(question)
2002                );
2003                // What the override adds to the inertia, against the same airframe with none.
2004                // Under a center that covers the parts, OpenRocket adds the parts' inertia about
2005                // the overridden center, 1.2% of its inertia across the axis there, which the
2006                // bound below can tell from none (ADR-340).
2007                if question.ends_with("a center that covers them") {
2008                    let adds = theirs_[3] - bare_theirs[3];
2009                    assert!((adds - 3.490e-4).abs() < 1e-7, "{question}: {adds:e}");
2010                }
2011                for k in [2, 3] {
2012                    let (ours_adds, theirs_adds) =
2013                        (ours[k] - bare_ours[k], theirs_[k] - bare_theirs[k]);
2014                    assert!(
2015                        (ours_adds - theirs_adds).abs() < 1e-9,
2016                        "{question}: inertia {k} gains {ours_adds:e}, OpenRocket's {theirs_adds:e}"
2017                    );
2018                }
2019            }
2020        }
2021    }
2022
2023    /// The overrides `stage_added_mass.py` gives its airframe's stage, beside `no override`.
2024    const ADDED_WITH_A_MOTOR: [&str; 3] = [
2025        "a mass override on the stage, not its parts",
2026        "both overrides on the stage, not its parts",
2027        "a mass override on the stage, not its parts, and a center that covers them",
2028    ];
2029
2030    /// A motor aboard doesn't move the mass OpenRocket 24.12 adds for a stage's override. With no
2031    /// center stated that mass sits at the center of the stage's parts, and the probes above
2032    /// carry no motor, so they can't tell the parts' center from the parts' and the motor's
2033    /// together. This record can: the motor is what launch, or burnout, adds to the structure
2034    /// with no override, and under each override OpenRocket's launch and burnout are that same
2035    /// motor added to the overridden structure. HPR Sim's layout holds no motor, so its added mass
2036    /// sits among the structure's parts ([`hpr_design::AddedMass`], ADR-335), and its structure's
2037    /// mass, center and the inertia the override adds on each probe are OpenRocket's.
2038    #[test]
2039    fn a_motor_aboard_does_not_move_a_stages_added_mass() {
2040        let record = added_mass_record();
2041        let weighed = |question: &str, when: &str| {
2042            let body = &probe(&record, question)[when];
2043            ["mass_kg", "cm_x_m"].map(|key| body[key].as_f64().expect("a number"))
2044        };
2045        let [bare_kg, bare_m] = weighed("no override", "structure");
2046        for when in ["launch", "burnout"] {
2047            let [with_kg, with_m] = weighed("no override", when);
2048            let motor_kg = with_kg - bare_kg;
2049            let motor_m = (with_kg * with_m - bare_kg * bare_m) / motor_kg;
2050            assert!(motor_kg > 0.05 && motor_m > bare_m, "{motor_kg} {motor_m}");
2051            for question in ADDED_WITH_A_MOTOR {
2052                let [structure_kg, structure_m] = weighed(question, "structure");
2053                let [got_kg, got_m] = weighed(question, when);
2054                assert!(
2055                    (got_kg - (structure_kg + motor_kg)).abs() < 1e-12,
2056                    "{question} at {when}: {got_kg}"
2057                );
2058                let want_m =
2059                    (structure_kg * structure_m + motor_kg * motor_m) / (structure_kg + motor_kg);
2060                assert!(
2061                    (got_m - want_m).abs() < 1e-12,
2062                    "{question} at {when}: {got_m} against {want_m}"
2063                );
2064            }
2065            // The test can tell: had the 2 kg sat at the center of the parts and the motor
2066            // together, the center would be the unoverridden rocket's, centimeters aft of this.
2067            let [_, got_m] = weighed(ADDED_WITH_A_MOTOR[0], when);
2068            assert!(with_m - got_m > 0.05, "{when}: {with_m} {got_m}");
2069        }
2070        // hpr's structure of each probe is OpenRocket's: the 2 kg added, where OpenRocket has it.
2071        let (bare_ours, bare_theirs, _) = both(probe(&record, "no override"));
2072        for question in std::iter::once("no override").chain(ADDED_WITH_A_MOTOR) {
2073            let (ours, theirs, warnings) = both(probe(&record, question));
2074            assert!(warnings.is_empty(), "{question}: {warnings:?}");
2075            assert!(
2076                relative(ours[0], theirs[0]).abs() < 5e-7,
2077                "{question}: mass {ours:?} {theirs:?}"
2078            );
2079            assert!(
2080                (ours[1] - theirs[1]).abs() < 2e-7,
2081                "{question}: center {ours:?} {theirs:?}"
2082            );
2083            // And so is the inertia the override adds to this airframe's. Under a center that
2084            // covers the parts, OpenRocket adds the parts' inertia about the overridden center,
2085            // 2.4% of its inertia across the axis there, which the bound below can tell from none
2086            // (ADR-340).
2087            if question == ADDED_WITH_A_MOTOR[2] {
2088                let adds = theirs[3] - bare_theirs[3];
2089                assert!((adds - 7.006e-4).abs() < 1e-7, "{question}: {adds:e}");
2090            }
2091            for k in [2, 3] {
2092                let (ours_adds, theirs_adds) = (ours[k] - bare_ours[k], theirs[k] - bare_theirs[k]);
2093                assert!(
2094                    (ours_adds - theirs_adds).abs() < 1e-9,
2095                    "{question}: inertia {k} gains {ours_adds:e}, OpenRocket's {theirs_adds:e}"
2096                );
2097            }
2098        }
2099        let gained = both(probe(&record, ADDED_WITH_A_MOTOR[1])).1[3] - bare_theirs[3];
2100        assert!(gained > 5.9e-4, "{gained:e}");
2101        let [added_kg, _] = weighed(ADDED_WITH_A_MOTOR[0], "structure");
2102        assert!((added_kg - bare_kg - 2.0).abs() < 1e-12, "{added_kg}");
2103    }
2104
2105    /// With a motor aboard, OpenRocket 24.12's inertia across the axis at launch and at burnout is
2106    /// the same sum as on the lower of two stages
2107    /// (`openrockets_lower_stage_sum_is_below_its_parts_in_place`):
2108    /// each part at its own place, the stage's 2 kg as a point at the stage's center, and the
2109    /// motor, about the rocket's center, to 1e-12 on each of the three probes. Under a center that
2110    /// covers the parts beside an added mass, HPR Sim's rule (ADR-340), the parts' inertia about
2111    /// the stage's stated center with the rest of its mass there, gives 1.6% less at launch and
2112    /// 1.1% less at burnout. Both readings take the motor's term from OpenRocket's own records.
2113    #[test]
2114    fn openrockets_inertia_with_a_motor_aboard_is_the_same_sum() {
2115        let record = added_mass_record();
2116        let body = |question: &str, when: &str| {
2117            let body = &probe(&record, question)[when];
2118            ["mass_kg", "cm_x_m", "iyy"].map(|key| body[key].as_f64().expect("a number"))
2119        };
2120        let [parts_kg, parts_m, parts_i] = body("no override", "structure");
2121        // The 2 kg sits at the parts' center, at the center override's 0.4 m station from the
2122        // tip where the stage starts, and at the same station beside a center that covers them.
2123        let at_m = [parts_m, 0.4, 0.4];
2124        for when in ["launch", "burnout"] {
2125            let [with_kg, with_m, with_i] = body("no override", when);
2126            let motor_kg = with_kg - parts_kg;
2127            let motor_m = (with_kg * with_m - parts_kg * parts_m) / motor_kg;
2128            let motor_i = with_i
2129                - parts_i
2130                - parts_kg * (parts_m - with_m).powi(2)
2131                - motor_kg * (motor_m - with_m).powi(2);
2132            for (question, point_m) in ADDED_WITH_A_MOTOR.into_iter().zip(at_m) {
2133                let [_, x_m, inertia] = body(question, when);
2134                let sum = parts_i
2135                    + parts_kg * (parts_m - x_m).powi(2)
2136                    + 2.0 * (point_m - x_m).powi(2)
2137                    + motor_i
2138                    + motor_kg * (motor_m - x_m).powi(2);
2139                assert!(
2140                    relative(sum, inertia).abs() < 1e-12,
2141                    "{question} at {when}: {sum} {inertia}"
2142                );
2143            }
2144            // A rigid stage at its stated center, the motor added to it.
2145            let question = ADDED_WITH_A_MOTOR[2];
2146            let [stage_kg, stage_m, stage_i] = body(question, "structure");
2147            let [_, x_m, inertia] = body(question, when);
2148            let rigid = stage_i
2149                + stage_kg * (stage_m - x_m).powi(2)
2150                + motor_i
2151                + motor_kg * (motor_m - x_m).powi(2);
2152            let apart = (relative(rigid, inertia) * 1e3).round() / 1e3;
2153            assert_eq!(
2154                apart,
2155                if when == "launch" { -0.016 } else { -0.011 },
2156                "{when}"
2157            );
2158        }
2159    }
2160
2161    /// The single subcomponent-override flag written before schema 1.9, and how far hpr's center
2162    /// of mass is from OpenRocket's, in meters, on each probe of it.
2163    const OLD_FLAG: [(&str, f64); 11] = [
2164        (
2165            "the old flag on both of a stage's overrides, schema 1.4",
2166            0.0,
2167        ),
2168        (
2169            "the old flag on a tube's mass override, schema 1.4",
2170            -0.003686,
2171        ),
2172        (
2173            "the old flag on a tube's mass override, schema 1.8",
2174            -0.003686,
2175        ),
2176        (
2177            "the old flag, false, on a tube's mass override, schema 1.8",
2178            0.0,
2179        ),
2180        (
2181            "the old flag on a tube's mass override, schema 1.10",
2182            -0.003686,
2183        ),
2184        ("the old flag after a mass flag that says false", -0.003686),
2185        ("the old flag before a mass flag that says false", 0.0),
2186        ("the old flag before a drag flag that says false", -0.003686),
2187        ("the old flag after a drag flag that says false", -0.003686),
2188        (
2189            "the old flag, false, after a centre flag that says true",
2190            0.0,
2191        ),
2192        (
2193            "the old flag, false, before a centre flag that says true",
2194            0.0,
2195        ),
2196    ];
2197
2198    /// The element at or under `element` whose `<id>` is `id`.
2199    fn with_id<'a>(element: &'a ork::Element, id: &str) -> Option<&'a ork::Element> {
2200        if element
2201            .child("id")
2202            .is_some_and(|own| own.text().trim() == id)
2203        {
2204            return Some(element);
2205        }
2206        element.elements().find_map(|child| with_id(child, id))
2207    }
2208
2209    /// OpenRocket 24.12 reads the single flag the three per-quantity ones replaced before schema
2210    /// 1.9 as setting all three, in schema 1.4, 1.8 and 1.10 alike, and where a part writes both
2211    /// forms the later one wins, quantity by quantity. hpr reads it so (M2.2e6): part by part, the
2212    /// three flags are OpenRocket's, nothing is warned of, the mass is OpenRocket's, and the center
2213    /// is OpenRocket's but where a mass override covering the parts inside states no center, which
2214    /// is ADR-061's departure, the same 3.686 mm as the per-quantity flag's probe above.
2215    #[test]
2216    fn the_old_subcomponent_flag_reads_as_openrocket_reads_it() {
2217        let record = record();
2218        for (question, apart_m) in OLD_FLAG {
2219            let probe = probe(&record, question);
2220            let (ours, theirs, warnings) = both(probe);
2221            assert!(
2222                relative(ours[0], theirs[0]).abs() < 1e-9,
2223                "{question}: mass {ours:?} {theirs:?}"
2224            );
2225            assert!(
2226                (ours[1] - theirs[1] - apart_m).abs() < 1e-6,
2227                "{question}: center {} m apart, not {apart_m}",
2228                ours[1] - theirs[1]
2229            );
2230            assert!(warnings.is_empty(), "{question}: {warnings:?}");
2231
2232            let document = probe["document"].as_str().expect("the probe's document");
2233            let parsed = ork::read(document.as_bytes()).expect("a probe reads");
2234            let flags = probe["override_flags"].as_object().expect("the flags");
2235            assert!(flags.len() >= 3, "{question}: {flags:?}");
2236            for (id, recorded) in flags {
2237                let element = with_id(&parsed.value.document.root, id).expect("the part");
2238                let mut part_warnings = Vec::new();
2239                let overrides = ork::Values::new(element, "probe", &mut part_warnings).overrides();
2240                let flags_ours = [
2241                    overrides.subcomponents_mass,
2242                    overrides.subcomponents_cg,
2243                    overrides.subcomponents_cd,
2244                ]
2245                .map(Option::unwrap_or_default);
2246                let flags_theirs =
2247                    ["mass", "cg", "cd"].map(|k| recorded[k].as_bool().expect("a flag"));
2248                assert_eq!(flags_ours, flags_theirs, "{question}: {id}");
2249                assert!(part_warnings.is_empty(), "{question}: {part_warnings:?}");
2250            }
2251        }
2252    }
2253
2254    /// The probes whose inertias are compared, with hpr's roll and pitch relative to OpenRocket's.
2255    const INERTIA: [(&str, [f64; 2]); 8] = [
2256        ("a mass override on a nose with a shoulder", [0.0, 0.0]),
2257        ("a mass override on a tube, not the part inside", [0.0, 0.0]),
2258        ("a mass override on the part inside only", [0.0, 0.0]),
2259        (
2260            "a mass override on a tube and the part inside",
2261            [-0.0693, -0.0667],
2262        ),
2263        (
2264            "a mass override on a tube and the part inside, which has its own",
2265            [-0.3713, -0.3724],
2266        ),
2267        (
2268            "a centre of gravity override on a tube and the part inside",
2269            [0.0, -0.0265],
2270        ),
2271        (
2272            "both overrides on a tube, the centre covering the part inside and the mass not",
2273            [0.0, -0.0010],
2274        ),
2275        (
2276            "both overrides on a tube, the mass covering the part inside and the centre not",
2277            [-0.0693, -0.0818],
2278        ),
2279    ];
2280
2281    /// Inertia under a part's override is hpr's own rule, a departure written in ADR-061 (a
2282    /// stage's follows OpenRocket since ADR-340: [`STAGE_WHOLE`]). hpr scales a mass override's
2283    /// inertia with its mass, over everything the override covers, so the extra mass sits where
2284    /// the parts' does; OpenRocket scales only the overriding part's own inertia, keeps the
2285    /// inertias of the parts inside, and leaves the covered parts' masses out. For a center of gravity override that covers the
2286    /// parts inside, hpr moves the assembly whole; OpenRocket moves the part alone and adds the
2287    /// parts inside where they were. On a lone part both scale, and agree. The relative
2288    /// differences, hpr's to OpenRocket's, are pinned here as roll and pitch.
2289    #[test]
2290    fn inertia_under_an_override_departs_as_written() {
2291        let record = record();
2292        for (question, pinned) in INERTIA {
2293            let (ours, theirs, _) = both(probe(&record, question));
2294            let found = [2, 3].map(|k| (relative(ours[k], theirs[k]) * 1e4).round() / 1e4);
2295            assert_eq!(found, pinned, "{question}");
2296        }
2297    }
2298
2299    /// The probes whose readings hpr takes from OpenRocket, where no rule of hpr's own is in play.
2300    const READINGS: [&str; 18] = [
2301        "a nose with no shoulder",
2302        "a nose with a walled shoulder",
2303        "a nose whose shoulder has no wall",
2304        "a nose whose shoulder has no wall, capped",
2305        "a filled nose whose shoulder has no wall",
2306        "a filled nose with a walled shoulder",
2307        "a transition whose shoulders have no wall",
2308        "a nose of no wall",
2309        "a transition of no wall",
2310        "a tube of no wall",
2311        "a tube holding an inner tube, a coupler and a lug of no wall",
2312        "a mass override on a nose of no wall",
2313        "a nose, a shoulder and a tube that write no thickness at all",
2314        "a narrower nose and tube that write no thickness at all",
2315        "a transition that writes no thickness at all",
2316        "a nose and a tube that name no material, with one part of each kind inside",
2317        "a transition, and more kinds inside a tube, that name no material",
2318        // Not a reading hpr takes: pinned below.
2319        "a tube holding an inner tube, a coupler and a lug that write no thickness",
2320    ];
2321
2322    /// The gaps a reading probe shows, each pinned rather than hidden: a part's class, and how far
2323    /// hpr's is from OpenRocket's, as its mass relative to OpenRocket's and its station in meters.
2324    ///
2325    /// - An elliptical fin set: hpr's planform is the exact ellipse, `π c h / 4`; OpenRocket's
2326    ///   weighs 0.18% less, which matches a 30-sided polygon inscribed at equal angles,
2327    ///   `(π/30) / sin(π/30) − 1`, to 13 digits: an inference from its output, not its source
2328    ///   (M2.2b2, with the fins).
2329    const PART_GAPS: [(&str, f64, f64); 1] = [("EllipticalFinSet", 0.001830, 0.0)];
2330
2331    /// hpr reads OpenRocket's words for walls, shoulders and materials as OpenRocket 24.12 does
2332    /// (ADR-061): a wall or a shoulder of no thickness weighs nothing, capped or not, on a filled
2333    /// nose or a hollow one, and so does an inner tube, coupler or lug of no wall; a nose,
2334    /// transition or tube that writes no thickness has a 2 mm wall, and a shoulder that writes none
2335    /// has no wall; a part that names no material is made of OpenRocket's cardboard, ripstop nylon,
2336    /// elastic cord or (a rail button) Delrin; and a mass override on a part that weighs nothing is
2337    /// a point mass at the middle of its length, unless the part is packed (ADR-063, below). So the
2338    /// mass and the center of mass agree, part by part as well as whole, and nothing is warned of;
2339    /// where no fin, rail button or recovery part is in the probe, the inertias agree as well.
2340    ///
2341    /// The worst mass is a transition's, 2.9e-6 from OpenRocket's (hpr measures its wall normal to
2342    /// the surface); the worst center, 1.5e-7 m. The bounds are a few times those. The two gaps in
2343    /// [`PART_GAPS`] are pinned, and so is the one reading hpr does not take: an inner tube or lug
2344    /// that writes no thickness, which OpenRocket gives a wall of its own (0.5 mm on the 20 mm
2345    /// inner tube, 1 mm on the 5 mm lug, none on the coupler) and hpr reads as none, with a warning.
2346    #[test]
2347    fn walls_shoulders_and_unnamed_materials_read_as_openrocket_does() {
2348        let record = record();
2349        for question in READINGS {
2350            let probe = probe(&record, question);
2351            let unwritten = question.ends_with("that write no thickness");
2352            let (ours, theirs, warnings) = both(probe);
2353            if unwritten {
2354                assert_eq!(warnings.len(), 3, "{question}: {warnings:?}");
2355            } else {
2356                assert!(warnings.is_empty(), "{question}: {warnings:?}");
2357            }
2358            if theirs[0] == 0.0 {
2359                // A structure that weighs nothing has no center to compare.
2360                assert_eq!(ours[0], 0.0, "{question}");
2361                assert!(ours[1].is_finite(), "{question}");
2362                continue;
2363            }
2364            let (layout, _) = hpr(probe);
2365            // The whole is the parts: whatever the parts' gaps add up to, and nothing more.
2366            let mut gap_kg = 0.0;
2367            let mut gap_moment = 0.0;
2368            let mut plain = true;
2369            for part in probe["parts"].as_array().expect("parts") {
2370                let class = part["class"].as_str().expect("a class");
2371                if matches!(class, "Rocket" | "AxialStage") {
2372                    continue; // they weigh nothing of their own, and hpr lays out no part for them
2373                }
2374                let id = part["id"].as_str().expect("an id");
2375                let (_, placed) = layout
2376                    .find(id)
2377                    .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
2378                let mass = part["mass_kg"].as_f64().expect("a mass");
2379                let station = part["cm_x_m"].as_f64().expect("a station");
2380                plain &= !matches!(
2381                    class,
2382                    "TrapezoidFinSet"
2383                        | "EllipticalFinSet"
2384                        | "FreeformFinSet"
2385                        | "RailButton"
2386                        | "Parachute"
2387                        | "Streamer"
2388                        | "ShockCord"
2389                );
2390                let (mass_gap, station_gap) =
2391                    if unwritten && matches!(class, "InnerTube" | "LaunchLug") {
2392                        // OpenRocket's own wall, which hpr does not give: all of the part's mass.
2393                        (-1.0, 0.0)
2394                    } else {
2395                        PART_GAPS
2396                            .iter()
2397                            .find(|(kind, _, _)| *kind == class)
2398                            .map_or((0.0, 0.0), |(_, m, z)| (*m, *z))
2399                    };
2400                if mass == 0.0 {
2401                    assert_eq!(placed.own.mass_kg, 0.0, "{question}: {id}");
2402                    continue;
2403                }
2404                let found = relative(placed.own.mass_kg, mass);
2405                assert!(
2406                    (found - mass_gap).abs() < 1e-5,
2407                    "{question}: {id} is {found} from OpenRocket's mass, not {mass_gap}"
2408                );
2409                if placed.own.mass_kg > 0.0 {
2410                    let apart_m = -placed.own.cg_m.z - station;
2411                    assert!(
2412                        (apart_m - station_gap).abs() < 1e-6,
2413                        "{question}: {id} is {apart_m} m from OpenRocket's station"
2414                    );
2415                }
2416                gap_kg += placed.own.mass_kg - mass;
2417                gap_moment += placed.own.mass_kg * (-placed.own.cg_m.z) - mass * station;
2418            }
2419            assert!(
2420                (ours[0] - theirs[0] - gap_kg).abs() < 1e-5 * theirs[0],
2421                "{question}: mass {ours:?} {theirs:?}"
2422            );
2423            let expected_m = (theirs[0] * theirs[1] + gap_moment) / (theirs[0] + gap_kg);
2424            assert!(
2425                (ours[1] - expected_m).abs() < 1e-6,
2426                "{question}: center {ours:?} {theirs:?}"
2427            );
2428            if plain && !unwritten {
2429                for k in [2, 3] {
2430                    let (a, b) = (ours[k], theirs[k]);
2431                    assert!(
2432                        (a - b).abs() <= 1e-5 * b.abs().max(1e-12),
2433                        "{question}: inertia {ours:?} {theirs:?}"
2434                    );
2435                }
2436            }
2437        }
2438    }
2439
2440    /// The probes of one tube and one part (M2.2b2, [ADR-062][adr-062]), each with how far hpr's
2441    /// structure is from OpenRocket's: the mass (relative), the center of mass (meters, hpr's less
2442    /// OpenRocket's), the roll inertia (relative) with OpenRocket's fin rule on OpenRocket's own fin
2443    /// mass in place of hpr's ([`super::openrocket_fin_set_roll_kg_m2`]), and the pitch inertia
2444    /// (relative). Each is pinned to three figures, and a zero to 1e-12. The tube alone is
2445    /// OpenRocket's, so each row is its one part's:
2446    ///
2447    /// - A bulkhead, centering ring, inner tube, mass component, parachute (under an override too),
2448    ///   shock cord and streamer: OpenRocket's in all four.
2449    /// - A fin set: its roll is OpenRocket's rule exactly, whatever its outline, section, tab or
2450    ///   fillets, but for an ellipse (OpenRocket's is a 30-sided polygon) and a cant (−2.66e-5).
2451    ///   Its mass is OpenRocket's but for a rounded or airfoil section
2452    ///   ([`a_fin_section_is_weighed_as_pinned`]), an ellipse, and a cant (−4.19e-5, not traced).
2453    ///   Its pitch inertia is apart by up to 0.11% where the masses agree (0.406% on a single fin,
2454    ///   below): OpenRocket's pitch rule for fins is not measured here.
2455    /// - Fillets (M2.2e7, [ADR-096][adr-096]): OpenRocket's in mass and center to 1e-15 (held
2456    ///   here to 1e-12), in their own material or cardboard's when none is named, on any outline,
2457    ///   count or tube; before, hpr left them out (−0.808% and −2.79% of the probe's mass at 5 and
2458    ///   10 mm). The pitch inertia is apart by −0.0077% to −0.638%, largest with the 30 mm fillets,
2459    ///   and +0.425% on a single fin: hpr's is the exact prism, and OpenRocket's pitch rule for fins
2460    ///   is not measured.
2461    /// - A rail button, one or a row, from any end: OpenRocket's in mass and center (#151), its
2462    ///   inertias apart by 7.16e-6 and 9.23e-5 (one), 1.43e-5 and 4.99e-4 (two).
2463    /// - A launch lug: its pitch inertia is apart by 3.13e-4.
2464    /// - A packed part that writes no packed size, or only half of one: OpenRocket packs it 25 mm
2465    ///   long and 12.5 mm in radius, whatever the tube, and so does hpr now (ADR-063; before, hpr
2466    ///   read zero and was 0.611 mm off in the center, −0.167% in roll).
2467    /// - A packed part that weighs nothing, under a mass override: OpenRocket spreads the override
2468    ///   over its packing, `m r²/2` in roll, and so does hpr now (ADR-063; before, a point mass,
2469    ///   −0.805%).
2470    /// - A single fin: the rule about the fin's own center, `m hₑ²/12`, agrees; its pitch is
2471    ///   apart by 0.406%.
2472    /// - A 3-ring clustered inner tube: hpr reads all three tubes (M1.9b), so the mass and center
2473    ///   agree; the roll inertia is +5.11% and the pitch +0.273%, the tubes' parallel-axis terms
2474    ///   `3 m d²` and half of it, which OpenRocket leaves out (ADR-075). Before M1.9b hpr read one
2475    ///   tube: −12.85% mass, +5.95 mm center, −2.43% roll and −3.68% pitch.
2476    ///
2477    /// [adr-062]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-062-fins-and-rail-buttons-against-openrocket-roll-inertia-explained-2026-09-21
2478    /// [adr-064]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-064-clusters-fillets-and-unread-parts-remain-visible-departures-2026-09-22
2479    /// [adr-096]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-096-fin-fillets-and-an-automatic-radius-inside-a-nose-cone-read-as-openrocket-reads-them-2026-09-28
2480    const ALONE: [(&str, [f64; 4]); 50] = [
2481        ("a tube and a bulkhead", [0.0, 0.0, 0.0, 0.0]),
2482        (
2483            "a tube and a canted fin set",
2484            [-4.19e-5, -4.54e-6, -2.66e-5, 7.58e-5],
2485        ),
2486        ("a tube and a centering ring", [0.0, 0.0, 0.0, 0.0]),
2487        (
2488            "a tube and a fin set of airfoil section",
2489            [-0.0165, 0.000935, 0.0, -0.00488],
2490        ),
2491        (
2492            "a tube and a fin set of rounded section",
2493            [0.00014, -1.24e-5, 0.0, 7.37e-5],
2494        ),
2495        (
2496            "a tube and a fin set of square section",
2497            [0.0, 0.0, 0.0, 4.57e-5],
2498        ),
2499        ("a tube and a fin set with a tab", [0.0, 0.0, 0.0, -0.00109]),
2500        (
2501            "a tube and a fin set with fillets",
2502            [0.0, 0.0, 0.0, -0.00035],
2503        ),
2504        (
2505            "a tube and a fin set with wider fillets",
2506            [0.0, 0.0, 0.0, -0.00129],
2507        ),
2508        (
2509            "a tube and a fin set with fillets of 30 mm",
2510            [0.0, 0.0, 0.0, -0.00638],
2511        ),
2512        (
2513            "a tube and a fin set with fillets of their own material",
2514            [0.0, 0.0, 0.0, -0.000749],
2515        ),
2516        (
2517            "a tube and a fin set with fillets that name no material",
2518            [0.0, 0.0, 0.0, -0.000223],
2519        ),
2520        (
2521            "a tube and a single fin with fillets",
2522            [0.0, 0.0, 7.78e-6, 0.00425],
2523        ),
2524        (
2525            "a tube and four fins of rounded section with fillets",
2526            [0.000179, -1.52e-5, 0.0, -0.000428],
2527        ),
2528        (
2529            "a tube and a freeform fin set with fillets",
2530            [0.0, 0.0, 0.0, -7.74e-5],
2531        ),
2532        (
2533            "a wider tube and a fin set with fillets",
2534            [0.0, 0.0, 0.0, -0.00123],
2535        ),
2536        ("a tube and a freeform fin set", [0.0, 0.0, 0.0, 4.57e-5]),
2537        ("a tube and a launch lug", [0.0, 0.0, 0.0, 0.000313]),
2538        ("a tube and a mass component", [0.0, 0.0, 0.0, 0.0]),
2539        ("a tube and a parachute", [0.0, 0.0, 0.0, 0.0]),
2540        (
2541            "a tube and a parachute that writes no packed size",
2542            [0.0, 0.0, 0.0, 0.0],
2543        ),
2544        (
2545            "a tube and a parachute that writes only a packed length",
2546            [0.0, 0.0, 0.0, 0.0],
2547        ),
2548        (
2549            "a tube and a parachute that writes only a packed radius",
2550            [0.0, 0.0, 0.0, 0.0],
2551        ),
2552        (
2553            "a tube and a streamer that writes no packed size",
2554            [0.0, 0.0, 0.0, 0.0],
2555        ),
2556        (
2557            "a tube and a shock cord that writes no packed size",
2558            [0.0, 0.0, 0.0, 0.0],
2559        ),
2560        (
2561            "a tube and a mass component that writes no packed size",
2562            [0.0, 0.0, 0.0, 0.0],
2563        ),
2564        (
2565            "a tube and a mass component of no mass, under a mass override",
2566            [0.0, 0.0, 0.0, 0.0],
2567        ),
2568        (
2569            "a tube and a shock cord of no length, under a mass override",
2570            [0.0, 0.0, 0.0, 0.0],
2571        ),
2572        (
2573            "a wider tube and a parachute that writes no packed size",
2574            [0.0, 0.0, 0.0, 0.0],
2575        ),
2576        (
2577            "a narrow tube and a parachute that writes no packed size",
2578            [0.0, 0.0, 0.0, 0.0],
2579        ),
2580        (
2581            "a tube and a parachute with a mass override",
2582            [0.0, 0.0, 0.0, 0.0],
2583        ),
2584        ("a tube and a rail button", [0.0, 0.0, 7.16e-6, 9.23e-5]),
2585        (
2586            "a tube and a rail button from the bottom",
2587            [0.0, 0.0, 7.16e-6, 9.23e-5],
2588        ),
2589        (
2590            "a tube and a rail button from the middle",
2591            [0.0, 0.0, 7.16e-6, 9.24e-5],
2592        ),
2593        (
2594            "a tube and a row of two rail buttons from the bottom",
2595            [0.0, 0.0, 1.43e-5, 0.000497],
2596        ),
2597        (
2598            "a tube and a row of two rail buttons from the middle",
2599            [0.0, 0.0, 1.43e-5, 0.000499],
2600        ),
2601        (
2602            "a tube and a row of two rail buttons from the top",
2603            [0.0, 0.0, 1.43e-5, 0.000499],
2604        ),
2605        ("a tube and a shock cord", [0.0, 0.0, 0.0, 0.0]),
2606        ("a tube and a streamer", [0.0, 0.0, 0.0, 0.0]),
2607        (
2608            "a tube and a thicker fin set of airfoil section",
2609            [-0.0305, 0.00155, 0.0, -0.00842],
2610        ),
2611        (
2612            "a tube and an elliptical fin set",
2613            [0.000188, -1.69e-5, 0.000122, -0.000328],
2614        ),
2615        ("a tube and an inner tube", [0.0, 0.0, 0.0, 0.0]),
2616        (
2617            "a tube and a clustered inner tube",
2618            [0.0, 0.0, 0.0511, 0.00273],
2619        ),
2620        ("a tube and rectangular fins", [0.0, 0.0, 0.0, 2.3e-6]),
2621        (
2622            "a tube and rectangular fins of twice the chord",
2623            [0.0, 0.0, 0.0, 4.49e-6],
2624        ),
2625        (
2626            "a tube and rectangular fins of twice the span",
2627            [0.0, 0.0, 0.0, 4.2e-6],
2628        ),
2629        ("a tube and a single fin", [0.0, 0.0, 0.0, 0.00406]),
2630        (
2631            "a tube and a parachute of no canopy, under a mass override",
2632            [0.0, 0.0, 0.0, 0.0],
2633        ),
2634        ("a tube and triangular fins", [0.0, 0.0, 0.0, 0.00028]),
2635        ("a wider tube and rectangular fins", [0.0, 0.0, 0.0, 1e-6]),
2636    ];
2637
2638    #[test]
2639    fn each_part_alone_is_openrocket_s_or_pinned() {
2640        let record = record();
2641        for (question, pinned) in ALONE {
2642            let probe = probe(&record, question);
2643            let (ours, theirs, warnings) = both(probe);
2644            assert!(warnings.is_empty(), "{question}: {warnings:?}");
2645            let (layout, _) = hpr(probe);
2646            let mut roll = ours[2];
2647            for part in probe["parts"].as_array().expect("parts") {
2648                let Some((_, placed)) = part["id"].as_str().and_then(|id| layout.find(id)) else {
2649                    continue;
2650                };
2651                if let Part::FinSet(fins) = &placed.part {
2652                    let mass_kg = part["mass_kg"].as_f64().expect("a mass");
2653                    let radius_m = placed.body_radius_m.expect("fins sit on a tube");
2654                    let rule = super::openrocket_fin_set_roll_kg_m2(fins, radius_m, mass_kg)
2655                        .expect("three fins");
2656                    roll += rule - placed.own.inertia_kg_m2.z_axis.z;
2657                }
2658            }
2659            let found = [
2660                relative(ours[0], theirs[0]),
2661                ours[1] - theirs[1],
2662                relative(roll, theirs[2]),
2663                relative(ours[3], theirs[3]),
2664            ];
2665            for (k, (found, pinned)) in found.iter().zip(pinned).enumerate() {
2666                let bound = if pinned == 0.0 {
2667                    1e-12
2668                } else {
2669                    5e-3 * pinned.abs()
2670                };
2671                assert!(
2672                    (found - pinned).abs() <= bound,
2673                    "{question}: quantity {k} is {found:e}, not {pinned:e}"
2674                );
2675            }
2676        }
2677    }
2678
2679    /// hpr's own fin roll inertia against OpenRocket's, set by set: the departure
2680    /// [ADR-062][adr-062] keeps. OpenRocket's set is its structure's roll inertia less everything
2681    /// else, which is hpr's (every other part of these probes is OpenRocket's to 1e-15). Pinned to
2682    /// three figures: the guide's table quotes them.
2683    ///
2684    /// [adr-062]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-062-fins-and-rail-buttons-against-openrocket-roll-inertia-explained-2026-09-21
2685    #[test]
2686    fn hpr_s_own_fin_roll_departs_as_pinned() {
2687        let record = record();
2688        let departures = [
2689            ("a tube and rectangular fins", 0.000_129),
2690            ("a tube and a fin set of square section", 0.0241),
2691            ("a tube and triangular fins", -0.0214),
2692            ("a tube and a fin set with a tab", -0.0512),
2693        ];
2694        for (question, pinned) in departures {
2695            let probe = probe(&record, question);
2696            let (ours, theirs, _) = both(probe);
2697            let (layout, _) = hpr(probe);
2698            let fins = layout
2699                .components
2700                .iter()
2701                .find(|placed| matches!(placed.part, Part::FinSet(_)))
2702                .expect("a fin set");
2703            let hpr_fins = fins.own.inertia_kg_m2.z_axis.z;
2704            let their_fins = theirs[2] - (ours[2] - hpr_fins);
2705            let found = relative(hpr_fins, their_fins);
2706            assert!(
2707                (found - pinned).abs() <= 5e-3 * pinned.abs(),
2708                "{question}: {found:e}, not {pinned:e}"
2709            );
2710        }
2711    }
2712
2713    /// OpenRocket weighs a fin set as its outline times its thickness times a factor for its
2714    /// section, whatever the thickness: 1 for square, 0.99 for rounded and 0.85 for airfoil (read from
2715    /// its output, at 3 mm and 6 mm for the airfoil). hpr integrates the section: a rounded edge is a
2716    /// semicircle, and an airfoil is NACA's four-digit section, `0.6851 t c` (Abbott and von
2717    /// Doenhoff). hpr keeps its own ([ADR-062][adr-062]); the ratios are pinned.
2718    ///
2719    /// [adr-062]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-062-fins-and-rail-buttons-against-openrocket-roll-inertia-explained-2026-09-21
2720    #[test]
2721    fn a_fin_section_is_weighed_as_pinned() {
2722        let record = record();
2723        let fins = |question: &str| -> (f64, f64) {
2724            let probe = probe(&record, question);
2725            let (layout, _) = hpr(probe);
2726            let theirs = probe["parts"]
2727                .as_array()
2728                .expect("parts")
2729                .iter()
2730                .find(|part| part["class"] == "TrapezoidFinSet")
2731                .expect("a fin set");
2732            let id = theirs["id"].as_str().expect("an id");
2733            let (_, ours) = layout.find(id).expect("hpr's fin set");
2734            (
2735                ours.own.mass_kg,
2736                theirs["mass_kg"].as_f64().expect("a mass"),
2737            )
2738        };
2739        let square = fins("a tube and a fin set of square section");
2740        assert!((square.0 - square.1).abs() < 1e-15, "{square:?}");
2741        let sections = [
2742            (
2743                "a tube and a fin set of rounded section",
2744                1.0,
2745                0.99,
2746                0.991_416,
2747            ),
2748            (
2749                "a tube and a fin set of airfoil section",
2750                1.0,
2751                0.85,
2752                0.685_083,
2753            ),
2754            (
2755                "a tube and a thicker fin set of airfoil section",
2756                2.0,
2757                0.85,
2758                0.685_083,
2759            ),
2760        ];
2761        for (question, thickness, openrocket, ours) in sections {
2762            let (hpr, theirs) = fins(question);
2763            let slab = thickness * square.1;
2764            assert!(
2765                (theirs / slab - openrocket).abs() < 1e-12,
2766                "{question}: {}",
2767                theirs / slab
2768            );
2769            assert!(
2770                (hpr / slab - ours).abs() < 1e-6,
2771                "{question}: {}",
2772                hpr / slab
2773            );
2774        }
2775    }
2776
2777    /// Loft's `demo-boattail.ork`, whose roll inertia is 2.64% from OpenRocket's, 0.093% with
2778    /// OpenRocket's fin rule in place of hpr's (`cargo xtask ork`). Its fins are elliptical, and
2779    /// OpenRocket's ellipse is a 30-sided polygon, of `sin(π/30) / (π/30)` the area and so the
2780    /// mass: with that in the rule too, the two are 1.5e-6 apart. The design and OpenRocket's
2781    /// record of it are both committed (ADR-060).
2782    #[test]
2783    fn the_loft_boattail_s_roll_is_the_rule_on_openrocket_s_ellipse() {
2784        let text = include_str!("../../../validation/fixtures/ork/openrocket-mass-loft-demo.json");
2785        let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
2786        let file = "validation/fixtures/ork/loft-demo/demo-boattail.ork";
2787        let design = record["designs"]
2788            .as_array()
2789            .expect("designs")
2790            .iter()
2791            .find(|design| design["file"] == file)
2792            .expect("the boattail's record");
2793        let theirs = design["structure"]["ixx"].as_f64().expect("a roll inertia");
2794        let bytes = include_bytes!("../../../validation/fixtures/ork/loft-demo/demo-boattail.ork");
2795        let read = ork::read(bytes.as_slice()).expect("the design reads");
2796        let layout = ork::design(&read.value)
2797            .value
2798            .rocket
2799            .layout()
2800            .expect("it lays out");
2801        let polygon = (std::f64::consts::PI / 30.0).sin() / (std::f64::consts::PI / 30.0);
2802        let mut ours = layout.structure.inertia_kg_m2.z_axis.z;
2803        let mut fins = 0;
2804        for placed in &layout.components {
2805            let Part::FinSet(set) = &placed.part else {
2806                continue;
2807            };
2808            assert!(matches!(
2809                set.planform,
2810                hpr_design::fins::FinPlanform::Elliptical { .. }
2811            ));
2812            // The rule on the polygon: its mass, and its area in `hₑ² = A h / c_r`.
2813            let rule = super::rod_roll_kg_m2(
2814                set.count,
2815                set.planform.geometry().expect("an outline").area_m2 * polygon,
2816                set.planform.span_m(),
2817                set.planform.root_chord_m(),
2818                placed.body_radius_m.expect("fins sit on a tube"),
2819                placed.own.mass_kg * polygon,
2820            )
2821            .expect("three fins");
2822            ours += rule - placed.own.inertia_kg_m2.z_axis.z;
2823            fins += 1;
2824        }
2825        assert_eq!(fins, 1);
2826        let apart = relative(ours, theirs);
2827        assert!(apart.abs() < 2e-6, "{apart:e}");
2828    }
2829
2830    fn pods() -> Value {
2831        let text = include_str!("../../../validation/fixtures/ork/openrocket-pods.json");
2832        serde_json::from_str(text).expect("the committed record is JSON")
2833    }
2834
2835    /// Every part inside every pod OpenRocket 24.12 was asked about sits where OpenRocket puts it:
2836    /// each copy across the axis to 1e-15 m, with OpenRocket's `(y, z)` read as hpr's `(x, y)`,
2837    /// and along it to 1e-15 m. That holds the reader's distance from the axis for each
2838    /// `radiusoffset` method (`relative`, `surface`, `free`), a pod whose widest part is in its
2839    /// middle, one, two and three pods, a negative angle, every angle method, and a pod set placed
2840    /// from its tube's bottom (M1.13b). A pod of no length holds its fins and its lug on a tube of
2841    /// its own radius, most often none, turned with the pod: each fin's root and the lug's axis are
2842    /// where OpenRocket puts them, matched as sets, since OpenRocket lists a fin set's fins across
2843    /// its pods in an order of its own. On a tube 10 mm in radius, two pods at 30° with three fins
2844    /// each at 20° show every fin turned with its pod (M1.13b2).
2845    #[test]
2846    fn every_pod_is_where_openrocket_puts_it() {
2847        let record = pods();
2848        let probes = record["probes"].as_object().expect("probes");
2849        assert_eq!(probes.len(), 18);
2850        for (question, probe) in probes {
2851            let (layout, warnings) = hpr(probe);
2852            if question.ends_with("its mass overridden to 0.1 kg") {
2853                assert_eq!(warnings.len(), 1, "{question}: {warnings:?}");
2854                assert!(warnings[0].contains("at the rocket's tip"), "{warnings:?}");
2855            } else {
2856                assert!(warnings.is_empty(), "{question}: {warnings:?}");
2857            }
2858            let mut inside = 0;
2859            for (id, theirs) in probe["components"].as_object().expect("components") {
2860                let Some((_, placed)) = layout.find(id) else {
2861                    continue;
2862                };
2863                if !in_a_pod(&layout, id) {
2864                    continue;
2865                }
2866                inside += 1;
2867                let theirs: Vec<[f64; 3]> = theirs["locations_m"]
2868                    .as_array()
2869                    .expect("locations")
2870                    .iter()
2871                    .map(|l| {
2872                        let at = |k: usize| l[k].as_f64().expect("a number");
2873                        [at(1), at(2), at(0)]
2874                    })
2875                    .collect();
2876                let ours = where_hpr_puts(placed);
2877                assert_eq!(ours.len(), theirs.len(), "{question}: {id}");
2878                let near = |a: &[f64; 3], b: &[f64; 3]| {
2879                    (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-15 && (a[2] - b[2]).abs() <= 1e-15
2880                };
2881                if matches!(placed.part, Part::FinSet(_)) {
2882                    let mut left = ours.clone();
2883                    for place in &theirs {
2884                        let k = left.iter().position(|o| near(o, place));
2885                        let k = k.unwrap_or_else(|| panic!("{question}: {id} {place:?} {ours:?}"));
2886                        left.swap_remove(k);
2887                    }
2888                } else {
2889                    for (o, t) in ours.iter().zip(&theirs) {
2890                        assert!(near(o, t), "{question}: {id} {o:?} vs {t:?}");
2891                    }
2892                }
2893            }
2894            let least = if question.starts_with("an empty") {
2895                0
2896            } else {
2897                2
2898            };
2899            assert!(inside >= least, "{question}: {inside} parts in the pod");
2900        }
2901    }
2902
2903    /// Whether the part `id` hangs, at any depth, from a pod set.
2904    fn in_a_pod(layout: &Layout, id: &str) -> bool {
2905        let mut at = layout.find(id).expect("the part").1.parent;
2906        while let Some(index) = at {
2907            let parent = &layout.components[index];
2908            if matches!(parent.part, Part::PodSet(_)) {
2909                return true;
2910            }
2911            at = parent.parent;
2912        }
2913        false
2914    }
2915
2916    /// Where hpr puts a part in a pod, as OpenRocket's component locations name it: `[x, y]`
2917    /// across the axis and the station along it, for every copy. A body component is its fore
2918    /// end on its pod's axis; a fin is its root's leading edge, on its tube's surface at its own
2919    /// angle; a lug is its axis's fore end, its own radius out from its tube's surface. What a pod
2920    /// holds turns with its pod.
2921    fn where_hpr_puts(placed: &hpr_design::tree::PlacedComponent) -> Vec<[f64; 3]> {
2922        let fore = placed.fore_station_m;
2923        let out = |offset: [f64; 2], radius: f64, angle: f64| {
2924            [
2925                offset[0] + radius * angle.cos(),
2926                offset[1] + radius * angle.sin(),
2927                fore,
2928            ]
2929        };
2930        let body = placed.body_radius_m.unwrap_or_default();
2931        let mut places = Vec::new();
2932        for copy in &placed.copies {
2933            match &placed.part {
2934                Part::FinSet(set) => {
2935                    let step = std::f64::consts::TAU / f64::from(set.count);
2936                    for k in 0..set.count {
2937                        let angle = copy.roll_rad + set.base_angle_rad + step * f64::from(k);
2938                        places.push(out(copy.offset_m, body, angle));
2939                    }
2940                }
2941                Part::LaunchLug(lug) => {
2942                    let angle = copy.roll_rad + lug.angle_rad;
2943                    places.push(out(copy.offset_m, body + lug.outer_radius_m, angle));
2944                }
2945                _ => places.push(out(copy.offset_m, 0.0, 0.0)),
2946            }
2947        }
2948        places
2949    }
2950
2951    /// A design with pods weighs what OpenRocket 24.12 says, on every probe.
2952    ///
2953    /// - **Part by part.** Every part OpenRocket weighs in a pod, and the pod set itself, is found
2954    ///   in hpr with OpenRocket's mass, all its copies together, and its center along the axis: a
2955    ///   tube, a fin set or a lug within 2e-15, relative (9.5e-16 at worst), so each pod is
2956    ///   weighed where it sits (ADR-089), a pod of no length and an empty pod set weigh nothing,
2957    ///   and a pod's fins and lug weigh what OpenRocket's do. A pod's nose cone is 8.3e-8 from
2958    ///   OpenRocket's in mass and 4.0e-9 in its center, held within 1e-7 and 5e-9. OpenRocket
2959    ///   weighs a nose cone differently from hpr: the probes' own nose, on the airframe, is
2960    ///   5.10e-7 apart in mass and −4.64e-7 in its center, pinned here to 0.5%, and the
2961    ///   airframe's tube agrees to 2e-15.
2962    /// - **The whole.** The empty pod set's probe is the bare airframe: 1.17e-7 from OpenRocket's
2963    ///   in mass and −1.125e-7 in the center, relative, pinned. No probe's mass
2964    ///   or center is further from OpenRocket's than that, so no pod here adds a gap of its own.
2965    ///   The mass is within 1.2e-7 on every probe; the center within 1.1e-7 where the pods have
2966    ///   a length (M1.13b1's), and within 1.13e-7 where they have none and weigh little.
2967    /// - **Roll**, within 2e-9, with each fin set in a pod given OpenRocket's own roll inertia
2968    ///   about its pod's axis ([`super::openrocket_fin_set_roll_kg_m2`], ADR-062) in place of hpr's.
2969    /// - **Pitch.** OpenRocket gives one pitch inertia, the same number as `iyy` and `izz`. Where
2970    ///   the pods hold no fins it is hpr's inertia about `x_B` (OpenRocket's `y`) within 6.1e-7,
2971    ///   and so the mean across the axis only where the pods leave the two equal (three pods):
2972    ///   with one or two of M1.13b1's pods, OpenRocket's `izz` is not the inertia about its `z`
2973    ///   axis, and hpr's is, 0.3% to 1.1% apart. Where they hold fins, the gap about `x_B` is
2974    ///   pinned to 0.5% of itself, as on the airframe: OpenRocket's pitch rule for fins is not
2975    ///   measured.
2976    /// - **An override on an empty pod set.** OpenRocket adds its mass at the rocket's tip, on the
2977    ///   axis: its structure is the bare airframe's but 0.1 kg heavier, with the same first
2978    ///   moment and roll inertia. hpr's reader drops the override, with a warning, so hpr's is the
2979    ///   bare airframe exactly.
2980    #[test]
2981    fn pods_weigh_as_openrocket_s() {
2982        // Mass and center, relative: every tube, fin set and lug in a pod; a pod's nose cone.
2983        const PART: (f64, f64) = (2e-15, 2e-15);
2984        const NOSE: (f64, f64) = (1e-7, 5e-9);
2985        // hpr's pitch about `x_B` less OpenRocket's, relative, where the pods hold fins.
2986        const FIN_PITCH: [(&str, f64); 4] = [
2987            (
2988                "one pod of no length 0.01 in radius, relative 0.02, two fins at 90",
2989                3.35e-5,
2990            ),
2991            (
2992                "one pod of no length, relative 0.03, bottom 0.0, two fins at 90",
2993                9.35e-6,
2994            ),
2995            (
2996                "two pods of no length 0.01 in radius, relative 0.02, at 30, three fins at 20",
2997                2.58e-7,
2998            ),
2999            (
3000                "two pods of no length, relative 0.02, at 45, three fins",
3001                -9.05e-7,
3002            ),
3003        ];
3004        let pinned = |got: f64, want: f64| (got - want).abs() <= 0.005 * want.abs();
3005        let record = pods();
3006        let probes = record["probes"].as_object().expect("probes");
3007        let empty = &probes["an empty pod set, relative 0.004"];
3008        let (ours, theirs, _) = both(empty);
3009        let bare = [relative(ours[0], theirs[0]), relative(ours[1], theirs[1])];
3010        assert!(pinned(bare[0], 1.17e-7), "{bare:?}");
3011        assert!(pinned(bare[1], -1.125e-7), "{bare:?}");
3012        let (layout, _) = hpr(empty);
3013        let nose = &empty["parts"][0];
3014        assert_eq!(nose["class"], "NoseCone");
3015        let (_, placed) = layout.find(conventions_id(1)).expect("the nose");
3016        let apart = relative(
3017            placed.own.mass_kg,
3018            nose["mass_kg"].as_f64().expect("a mass"),
3019        );
3020        assert!(pinned(apart, 5.10e-7), "{apart:e}");
3021        let apart = relative(
3022            -placed.own.cg_m.z,
3023            nose["cm_x_m"].as_f64().expect("a station"),
3024        );
3025        assert!(pinned(apart, -4.64e-7), "{apart:e}");
3026        // The tube is OpenRocket's, so the nose is all of the bare airframe's gap.
3027        let tube = &empty["parts"][1];
3028        assert_eq!(tube["class"], "BodyTube");
3029        let (_, placed) = layout.find(conventions_id(2)).expect("the tube");
3030        let apart = relative(
3031            placed.own.mass_kg,
3032            tube["mass_kg"].as_f64().expect("a mass"),
3033        );
3034        assert!(apart.abs() < PART.0, "{apart:e}");
3035
3036        for (question, probe) in probes {
3037            let (ours, theirs, _) = both(probe);
3038            let (layout, _) = hpr(probe);
3039            if question.ends_with("its mass overridden to 0.1 kg") {
3040                let (bare_ours, bare_theirs, _) = both(empty);
3041                assert_eq!(ours, bare_ours, "{question}");
3042                let mass = theirs[0] - bare_theirs[0];
3043                assert!((mass - 0.1).abs() < 1e-15, "{question}: {mass:e}");
3044                let moment = theirs[0] * theirs[1] - bare_theirs[0] * bare_theirs[1];
3045                assert!(moment.abs() < 1e-15, "{question}: {moment:e}");
3046                assert_eq!(theirs[2], bare_theirs[2], "{question}");
3047                continue;
3048            }
3049            let airframe = [conventions_id(1), conventions_id(2)];
3050            let mut weighed = 0;
3051            let mut in_pods = 0;
3052            for part in probe["parts"].as_array().expect("parts") {
3053                let id = part["id"].as_str().expect("an id");
3054                let class = part["class"].as_str().expect("a class");
3055                if matches!(class, "Rocket" | "AxialStage") || airframe.contains(&id) {
3056                    continue;
3057                }
3058                in_pods += 1;
3059                let (_, placed) = layout
3060                    .find(id)
3061                    .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
3062                assert!(
3063                    in_a_pod(&layout, id) || matches!(placed.part, Part::PodSet(_)),
3064                    "{question}: {id}"
3065                );
3066                weighed += 1;
3067                let mass = part["mass_kg"].as_f64().expect("a mass");
3068                let own = placed.own;
3069                if mass == 0.0 {
3070                    assert_eq!(own.mass_kg, 0.0, "{question}: {id}");
3071                    continue;
3072                }
3073                let (mass_bound, center_bound) = if matches!(placed.part, Part::NoseCone(_)) {
3074                    NOSE
3075                } else {
3076                    PART
3077                };
3078                let apart = relative(own.mass_kg, mass);
3079                assert!(apart.abs() < mass_bound, "{question}: {id} mass {apart:e}");
3080                let station = part["cm_x_m"].as_f64().expect("a station");
3081                let apart = relative(-own.cg_m.z, station);
3082                assert!(
3083                    apart.abs() < center_bound,
3084                    "{question}: {id} center {apart:e}"
3085                );
3086            }
3087            assert_eq!(weighed, in_pods, "{question}");
3088            let holds_nothing = question.starts_with("an empty");
3089            let least = if holds_nothing { 1 } else { 3 };
3090            assert!(in_pods >= least, "{question}: {in_pods}");
3091
3092            let of_length = !(holds_nothing || question.contains("of no length"));
3093            let center_bound = if of_length { 1.1e-7 } else { 1.13e-7 };
3094            for (k, bound) in [(0, 1.2e-7), (1, center_bound)] {
3095                let apart = relative(ours[k], theirs[k]);
3096                assert!(apart.abs() < bound, "{question}: quantity {k}, {apart:e}");
3097                assert!(
3098                    apart.abs() <= bare[k].abs(),
3099                    "{question}: quantity {k}, {apart:e}"
3100                );
3101            }
3102
3103            let mut roll = ours[2];
3104            for placed in &layout.components {
3105                let Part::FinSet(set) = &placed.part else {
3106                    continue;
3107                };
3108                let radius = placed.body_radius_m.expect("fins sit on a tube");
3109                let one = placed
3110                    .part
3111                    .mass_properties(Some(radius))
3112                    .expect("a fin set");
3113                let copies = f64::from(u32::try_from(placed.copies.len()).expect("a few pods"));
3114                let rule = super::openrocket_fin_set_roll_kg_m2(set, radius, one.mass_kg)
3115                    .expect("two or more fins");
3116                roll += copies * (rule - one.inertia_kg_m2.z_axis.z);
3117            }
3118            let apart = relative(roll, theirs[2]);
3119            assert!(apart.abs() < 2e-9, "{question}: roll {apart:e}");
3120
3121            let i = layout.structure.inertia_kg_m2;
3122            let pitch = probe["structure"]["iyy"].as_f64().expect("a number");
3123            assert_eq!(
3124                probe["structure"]["izz"].as_f64(),
3125                Some(pitch),
3126                "{question}"
3127            );
3128            let about_x = relative(i.x_axis.x, pitch);
3129            if let Some((_, want)) = FIN_PITCH.iter().find(|(q, _)| q == question) {
3130                assert!(pinned(about_x, *want), "{question}: {about_x:e}");
3131                continue;
3132            }
3133            assert!(
3134                !layout
3135                    .components
3136                    .iter()
3137                    .any(|c| matches!(c.part, Part::FinSet(_))),
3138                "{question}: fins not pinned"
3139            );
3140            assert!(about_x.abs() < 6.1e-7, "{question}: {about_x:e}");
3141            let about_y = relative(i.y_axis.y, pitch);
3142            if question.starts_with("three") {
3143                assert!(about_y.abs() < 6.1e-7, "{question}: {about_y:e}");
3144            } else if of_length {
3145                assert!((0.002..0.011).contains(&about_y), "{question}: {about_y:e}");
3146            }
3147        }
3148    }
3149
3150    /// The probes' fixed ids, as `conventions.py` writes them.
3151    fn conventions_id(n: u32) -> &'static str {
3152        match n {
3153            1 => "00000000-0000-4000-8000-000000000001",
3154            2 => "00000000-0000-4000-8000-000000000002",
3155            _ => unreachable!("only the probes' nose and tube are asked for"),
3156        }
3157    }
3158
3159    fn clusters() -> Value {
3160        let text = include_str!("../../../validation/fixtures/ork/openrocket-clusters.json");
3161        serde_json::from_str(text).expect("the committed record is JSON")
3162    }
3163
3164    /// Every tube of every cluster OpenRocket 24.12 was asked about sits where OpenRocket puts it,
3165    /// to 1e-15 m: each of its fourteen patterns at scale 1, a scale, a rotation, a radial offset,
3166    /// and all three at once, with OpenRocket's `(y, z)` read as hpr's `(x, y)` (ADR-075). A
3167    /// pattern OpenRocket has no name for is one tube, as OpenRocket reads it, with a warning.
3168    #[test]
3169    fn every_tube_of_a_cluster_is_where_openrocket_puts_it() {
3170        let record = clusters();
3171        let patterns = record["patterns"].as_object().expect("patterns");
3172        assert_eq!(patterns.len(), 14);
3173        for name in patterns.keys() {
3174            assert!(
3175                record["probes"][format!("{name} at scale 1")].is_object(),
3176                "no probe of {name}"
3177            );
3178        }
3179        for (question, probe) in record["probes"].as_object().expect("probes") {
3180            let (layout, warnings) = hpr(probe);
3181            let unnamed = question == "a pattern OpenRocket has no name for";
3182            assert_eq!(
3183                warnings.len(),
3184                usize::from(unnamed),
3185                "{question}: {warnings:?}"
3186            );
3187            if unnamed {
3188                assert!(
3189                    warnings[0].contains("is not one of OpenRocket's cluster patterns"),
3190                    "{warnings:?}"
3191                );
3192            }
3193            for (id, tube) in probe["tubes"].as_object().expect("tubes") {
3194                let (_, placed) = layout.find(id).expect("the tube");
3195                let Part::InnerTube(inner) = &placed.part else {
3196                    panic!("{question}: {id} is not an inner tube");
3197                };
3198                let [x, y] = placed.part.axis_offset_m();
3199                let ours: Vec<[f64; 2]> = inner
3200                    .tubes_m()
3201                    .expect("finite")
3202                    .iter()
3203                    .map(|[u, v]| [x + u, y + v])
3204                    .collect();
3205                let theirs: Vec<[f64; 2]> = tube["instance_offsets_m"]
3206                    .as_array()
3207                    .expect("offsets")
3208                    .iter()
3209                    .map(|c| [c[1].as_f64().expect("y"), c[2].as_f64().expect("z")])
3210                    .collect();
3211                assert_eq!(ours.len(), theirs.len(), "{question}");
3212                assert_eq!(
3213                    tube["count"].as_u64(),
3214                    Some(ours.len() as u64),
3215                    "{question}"
3216                );
3217                for (ours, theirs) in ours.iter().zip(&theirs) {
3218                    let apart = (ours[0] - theirs[0]).hypot(ours[1] - theirs[1]);
3219                    assert!(apart <= 1e-15, "{question}: {ours:?} vs {theirs:?}");
3220                }
3221            }
3222        }
3223    }
3224
3225    /// A cluster weighs what OpenRocket 24.12 says, but for the spread of its own tubes about the
3226    /// cluster's axis. The mass and center agree to 1e-12 on every probe: every tube counted, an
3227    /// engine block inside counted once in each tube, a mass override on the cluster its whole
3228    /// mass, and an automatic ring's bore the tube's own radius, as if the cluster were one tube on
3229    /// the axis. OpenRocket weighs a cluster's tubes stacked on its axis (a 3-ring at scale 1 and at
3230    /// 1.5 have the same inertias), while hpr places each where it is: so on every cluster on the
3231    /// body's axis, hpr's roll inertia is OpenRocket's plus `Σ m |c|²` over the tubes, `c` each
3232    /// tube's offset and `m` its mass, and the pitch inertia (the mean across the axis) plus half
3233    /// of it, to 1e-12, worked here by hand (ADR-075). Off the axis the roll rule still holds for a
3234    /// cluster, but three departures are left, pinned as measured, less the spread: a lone tube
3235    /// 10 mm off the axis, whose offset OpenRocket leaves out of both inertias, and the pitch of
3236    /// two clusters off the axis, 0.015% and 0.021%, which hpr has not traced.
3237    #[test]
3238    fn a_cluster_weighs_as_openrocket_s_but_for_its_tubes_spread() {
3239        const OFF_AXIS: [(&str, [f64; 2]); 3] = [
3240            (
3241                "an unclustered tube 10 mm off the axis at 30",
3242                [0.00303, 0.000164],
3243            ),
3244            ("a 2-row 10 mm off the axis at 30", [0.0, 0.00015]),
3245            (
3246                "a 3-ring 10 mm off the axis at 30, turned 20",
3247                [0.0, 0.000206],
3248            ),
3249        ];
3250        let record = clusters();
3251        for (question, probe) in record["probes"].as_object().expect("probes") {
3252            let (ours, theirs, _) = both(probe);
3253            assert!(
3254                relative(ours[0], theirs[0]).abs() <= 1e-12,
3255                "{question}: mass"
3256            );
3257            assert!((ours[1] - theirs[1]).abs() <= 1e-12, "{question}: center");
3258            let (layout, _) = hpr(probe);
3259            let mut spread = 0.0;
3260            for id in probe["tubes"].as_object().expect("tubes").keys() {
3261                let (_, placed) = layout.find(id).expect("the tube");
3262                let Part::InnerTube(inner) = &placed.part else {
3263                    panic!("{question}: {id} is not an inner tube");
3264                };
3265                let tubes = inner.tubes_m().expect("finite");
3266                let each_kg = placed.own.mass_kg / tubes.len() as f64;
3267                spread += tubes
3268                    .iter()
3269                    .map(|[u, v]| each_kg * (u * u + v * v))
3270                    .sum::<f64>();
3271            }
3272            // Roll and pitch less the spread, against OpenRocket's.
3273            let found = [
3274                relative(ours[2] - spread, theirs[2]),
3275                relative(ours[3] - spread / 2.0, theirs[3]),
3276            ];
3277            let pinned = OFF_AXIS
3278                .iter()
3279                .find(|(q, _)| q == question)
3280                .map_or([0.0, 0.0], |(_, pinned)| *pinned);
3281            for (k, (found, pinned)) in found.iter().zip(pinned).enumerate() {
3282                let bound = if pinned == 0.0 {
3283                    1e-12
3284                } else {
3285                    5e-3 * pinned.abs()
3286                };
3287                assert!(
3288                    (found - pinned).abs() <= bound,
3289                    "{question}: inertia {k} less the spread is {found:e}, not {pinned:e}"
3290                );
3291            }
3292        }
3293    }
3294
3295    /// The cluster record was written by the script it names, from OpenRocket 24.12, and every
3296    /// probe in it is one the tests above read, which read them all.
3297    #[test]
3298    fn the_cluster_record_is_openrocket_s() {
3299        let record = clusters();
3300        assert_eq!(record["openrocket"], "24.12");
3301        assert_eq!(
3302            record["source"],
3303            "validation/oracles/openrocket/clusters.py"
3304        );
3305        assert!(record["probes"].as_object().expect("probes").len() >= 22);
3306    }
3307
3308    /// The probes of an automatic outer radius inside a nose cone or transition, and of an inner
3309    /// tube written `auto` (M2.2e7).
3310    const BORES: [&str; 13] = [
3311        "a nose holding a coupler of automatic radius at its bottom",
3312        "an ogive nose holding a coupler of automatic radius at its bottom",
3313        "a nose holding a coupler of automatic radius past its base",
3314        "a nose with a shoulder, holding a coupler of automatic radius past its base",
3315        "a nose holding a long coupler of automatic radius from its middle",
3316        "a nose holding an engine block of automatic radius",
3317        "a nose holding a centering ring and a bulkhead of automatic radius",
3318        "a nose holding a coupler of automatic radius and a wall thicker than its bore",
3319        "a nose holding a coupler of automatic radius with a mass inside",
3320        "a transition holding a coupler of automatic radius",
3321        "a tube holding a coupler of automatic radius and a wall thicker than its bore",
3322        "a tube holding an inner tube of automatic radius",
3323        "a nose holding an inner tube of automatic radius",
3324    ];
3325
3326    /// The one bore probe hpr refuses: a coupler at the tip, where the cone's wall meets the axis.
3327    const BORE_REFUSED: &str = "a nose holding a coupler of automatic radius at its tip";
3328
3329    /// M2.2e7 ([ADR-096][adr-096]): inside a hollow nose cone or transition, an automatic outer
3330    /// radius is the parent's outer radius at the part's narrower end less its wall, the shoulder
3331    /// left out; a wall thicker than that is the tube solid, in a body tube too; and an
3332    /// `innertube` written `auto` keeps 9.5 mm, with no warning, as OpenRocket reads it. So every
3333    /// coupler, engine block, inner tube, ring and bulkhead weighs OpenRocket's mass to 1e-14 at
3334    /// OpenRocket's station to 1e-15.
3335    ///
3336    /// The nose cones and the transition carry the gaps their walls already had: 5.1e-7 of the
3337    /// cone's mass, 3.93e-5 of the ogive's and 2.85e-6 of the transition's, and centers within
3338    /// 2.5e-6 m (hpr measures a wall normal to the surface). One mass component is pinned apart: packed with an
3339    /// automatic radius inside the coupler, OpenRocket shortens it to 8.49 mm, keeping the volume
3340    /// of its 12.5 mm by 50 mm default, and hpr keeps its written 50 mm, 20.75 mm further aft of
3341    /// its center ([#186][i186]). A coupler at the tip, where the wall meets the axis, has no
3342    /// radius: OpenRocket weighs it as nothing, and hpr refuses the design.
3343    ///
3344    /// [adr-096]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-096-fin-fillets-and-an-automatic-radius-inside-a-nose-cone-read-as-openrocket-reads-them-2026-09-28
3345    /// [i186]: https://github.com/nrdptel/fusionspace-eridanus/issues/186
3346    #[test]
3347    fn an_automatic_radius_inside_a_nose_reads_as_openrocket_does() {
3348        let record = record();
3349        for question in BORES {
3350            let probe = probe(&record, question);
3351            let (layout, warnings) = hpr(probe);
3352            assert!(warnings.is_empty(), "{question}: {warnings:?}");
3353            for part in probe["parts"].as_array().expect("parts") {
3354                let class = part["class"].as_str().expect("a class");
3355                if matches!(class, "Rocket" | "AxialStage") {
3356                    continue;
3357                }
3358                let id = part["id"].as_str().expect("an id");
3359                let (_, placed) = layout
3360                    .find(id)
3361                    .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
3362                let mass = part["mass_kg"].as_f64().expect("a mass");
3363                let station = part["cm_x_m"].as_f64().expect("a station");
3364                let (mass_bound, station_gap, station_bound) = match class {
3365                    "NoseCone" | "Transition" => (5e-5, 0.0, 5e-6),
3366                    "MassComponent" => (1e-15, 0.020755, 1e-6),
3367                    _ => (1e-14, 0.0, 1e-15),
3368                };
3369                let found = relative(placed.own.mass_kg, mass);
3370                assert!(
3371                    found.abs() <= mass_bound,
3372                    "{question}: {class} {id} is {found:e} from OpenRocket's mass"
3373                );
3374                let apart_m = -placed.own.cg_m.z - station;
3375                assert!(
3376                    (apart_m - station_gap).abs() <= station_bound,
3377                    "{question}: {class} {id} is {apart_m:e} m from OpenRocket's station"
3378                );
3379            }
3380        }
3381
3382        let probe = probe(&record, BORE_REFUSED);
3383        let coupler = probe["parts"]
3384            .as_array()
3385            .expect("parts")
3386            .iter()
3387            .find(|part| part["class"] == "TubeCoupler")
3388            .expect("the coupler");
3389        assert_eq!(coupler["mass_kg"].as_f64(), Some(0.0));
3390        let document = probe["document"].as_str().expect("the probe's document");
3391        let read = ork::read(document.as_bytes()).expect("a probe reads");
3392        let error = ork::rocket(&read.value.document)
3393            .value
3394            .layout()
3395            .expect_err("a tube of no radius");
3396        assert!(
3397            matches!(
3398                &error,
3399                hpr_design::DesignError::InComponent { source, .. }
3400                    if matches!(
3401                        **source,
3402                        hpr_design::DesignError::Domain { what: "outer radius", value }
3403                            if value == 0.0
3404                    )
3405            ),
3406            "{error:?}"
3407        );
3408    }
3409
3410    /// M2.2e8's probes: tube fin sets on a 50 mm or a 20 mm tube, most written `auto` (ADR-098).
3411    const TUBE_FINS: [&str; 19] = [
3412        "a tube and 1 tube fins of automatic radius",
3413        "a tube and 2 tube fins of automatic radius",
3414        "a tube and 3 tube fins of automatic radius",
3415        "a tube and 4 tube fins of automatic radius",
3416        "a tube and 5 tube fins of automatic radius",
3417        "a tube and 6 tube fins of automatic radius",
3418        "a tube and 8 tube fins of automatic radius",
3419        "a tube and 9 tube fins of automatic radius",
3420        "a tube and 12 tube fins of automatic radius",
3421        "a tube and 20 tube fins of automatic radius",
3422        "a tube and 6 tube fins of a stated radius",
3423        "a tube and 6 tube fins of automatic radius and a wall thicker than it",
3424        "a tube and 6 tube fins of a stated radius, offset from the body",
3425        "a tube of automatic radius and 4 tube fins of automatic radius",
3426        "a tube and 12 tube fins of a stated radius",
3427        "a tube and 100 tube fins of automatic radius",
3428        "a 20 mm tube and 1 tube fins of automatic radius",
3429        "a 20 mm tube and 2 tube fins of automatic radius",
3430        "a 20 mm tube and 5 tube fins of automatic radius",
3431    ];
3432
3433    /// A tube fin set written `auto` has the radius OpenRocket 24.12 works out, the ring closed
3434    /// around the body for three tubes or more and the body's radius for one or two; a wall thicker
3435    /// than it is cut to it; more than 8 tubes are 8; and the tubes weigh what OpenRocket's do,
3436    /// centered where its are (ADR-098). A written radial offset moves nothing in OpenRocket, and
3437    /// hpr does not read one. Two inertias depart, and hpr keeps its hollow tubes at `R_b + r`:
3438    /// OpenRocket's roll exceeds what any mass inside the ring can have, `(R_b + 2r)²` a unit of
3439    /// mass, and its pitch is `N` times one tube's own, with no term for the ring's spread.
3440    #[test]
3441    fn a_tube_fin_sets_automatic_radius_reads_as_openrocket_does() {
3442        let record = record();
3443        for question in TUBE_FINS {
3444            let probe = probe(&record, question);
3445            let (layout, warnings) = hpr(probe);
3446            // More than 8 tubes are read as 8 out loud; an offset from the body is read as none,
3447            // out loud, which is also what OpenRocket's numbers show.
3448            let capped = ["9", "12", "20", "100"]
3449                .iter()
3450                .any(|n| question.contains(&format!(" and {n} tube fins")));
3451            let offset = question.contains("offset");
3452            assert_eq!(
3453                warnings.len(),
3454                usize::from(capped || offset),
3455                "{question}: {warnings:?}"
3456            );
3457            let said = if offset {
3458                "read sitting on it"
3459            } else {
3460                "reads at most 8"
3461            };
3462            assert!(
3463                warnings.iter().all(|w| w.contains(said)),
3464                "{question}: {warnings:?}"
3465            );
3466            for part in probe["parts"].as_array().expect("parts") {
3467                let class = part["class"].as_str().expect("a class");
3468                if matches!(class, "Rocket" | "AxialStage") {
3469                    continue;
3470                }
3471                let id = part["id"].as_str().expect("an id");
3472                let (_, placed) = layout
3473                    .find(id)
3474                    .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
3475                // A nose cone's shell is the bore probes' bound (the nose is only on one probe).
3476                let (mass_bound, station_bound) = match class {
3477                    "NoseCone" => (5e-5, 5e-6),
3478                    _ => (1e-14, 1e-15),
3479                };
3480                let mass = part["mass_kg"].as_f64().expect("a mass");
3481                let found = relative(placed.own.mass_kg, mass);
3482                assert!(
3483                    found.abs() <= mass_bound,
3484                    "{question}: {class} is {found:e} from OpenRocket's mass"
3485                );
3486                let apart_m = -placed.own.cg_m.z - part["cm_x_m"].as_f64().expect("a station");
3487                assert!(
3488                    apart_m.abs() <= station_bound,
3489                    "{question}: {class} is {apart_m:e} m from OpenRocket's"
3490                );
3491            }
3492            let (id, theirs) = probe["tube_fins"]
3493                .as_object()
3494                .and_then(|sets| sets.iter().next())
3495                .expect("one tube fin set");
3496            let (_, placed) = layout.find(id).expect("the tube fin set");
3497            let Part::TubeFinSet(ours) = &placed.part else {
3498                panic!("{question}: {:?}", placed.part);
3499            };
3500            let number = |key: &str| theirs[key].as_f64().expect(key);
3501            assert_eq!(
3502                theirs["automatic"].as_bool(),
3503                Some(!question.contains("stated"))
3504            );
3505            assert_eq!(
3506                Some(u64::from(ours.count)),
3507                theirs["count"].as_u64(),
3508                "{question}"
3509            );
3510            let r = number("outer_radius_m");
3511            assert!(
3512                relative(ours.outer_radius_m, r).abs() <= 1e-15,
3513                "{question}: radius {} against OpenRocket's {r}",
3514                ours.outer_radius_m
3515            );
3516            assert!(
3517                relative(ours.thickness_m, number("thickness_m")).abs() <= 1e-15,
3518                "{question}: wall {} against {}",
3519                ours.thickness_m,
3520                number("thickness_m")
3521            );
3522            let body_radius_m = number("body_radius_m");
3523            assert_eq!(placed.body_radius_m, Some(body_radius_m), "{question}");
3524            // Per unit mass, about the set's center: one tube's own inertias, across and about its
3525            // axis, and how far its axis is from the body's.
3526            let (r_i, length_m) = (number("inner_radius_m"), 0.1);
3527            let across = (r * r + r_i * r_i) / 4.0 + length_m * length_m / 12.0;
3528            let about = (r * r + r_i * r_i) / 2.0;
3529            let d2 = (body_radius_m + r).powi(2);
3530            let unit = |i: f64| i / placed.own.mass_kg;
3531            let inertia = &placed.own.inertia_kg_m2;
3532            // OpenRocket's pitch is each tube's own inertia across it, times the count, with no term
3533            // for the tubes' distance from the axis: a second departure (ADR-098).
3534            let their_pitch = number("longitudinal_unit_inertia_m2");
3535            let n = f64::from(ours.count);
3536            assert!(
3537                relative(their_pitch, n * across).abs() <= 1e-14,
3538                "{question}: {their_pitch}"
3539            );
3540            if ours.count == 1 {
3541                // One tube: its center `R_b + r` off the axis, and its own roll, in both codes.
3542                let [_, y, z] =
3543                    [0, 1, 2].map(|k| theirs["component_cg_xyz_m"][k].as_f64().expect("a center"));
3544                let off = y.hypot(z);
3545                assert!(
3546                    (off - (body_radius_m + r)).abs() <= 1e-15,
3547                    "{question}: {off}"
3548                );
3549                let ours_off = placed.own.cg_m.x.hypot(placed.own.cg_m.y);
3550                assert!(
3551                    (ours_off - off).abs() <= 1e-15,
3552                    "{question}: hpr's center {ours_off}"
3553                );
3554                let roll = number("rotational_unit_inertia_m2");
3555                assert!(relative(roll, about).abs() <= 1e-15, "{question}: {roll}");
3556                assert!(
3557                    relative(unit(inertia.z_axis.z), roll).abs() <= 1e-14,
3558                    "{question}"
3559                );
3560                // And its own pitch, about its own center: the one count where the two agree.
3561                assert!(
3562                    relative(unit(inertia.x_axis.x), across).abs() <= 1e-13,
3563                    "{question}"
3564                );
3565                assert!(relative(their_pitch, across).abs() <= 1e-14, "{question}");
3566            } else {
3567                // A ring: hpr's tubes at `R_b + r`, which OpenRocket's roll exceeds past any mass
3568                // inside `R_b + 2r`.
3569                assert!(
3570                    relative(unit(inertia.z_axis.z), about + d2).abs() <= 1e-13,
3571                    "{question}"
3572                );
3573                let bound = (body_radius_m + 2.0 * r).powi(2);
3574                let roll = number("rotational_unit_inertia_m2");
3575                assert!(
3576                    roll > bound,
3577                    "{question}: OpenRocket's {roll} within {bound}"
3578                );
3579                if ours.count >= 3 {
3580                    let pitch = unit(inertia.x_axis.x);
3581                    assert!(
3582                        relative(pitch, across + d2 / 2.0).abs() <= 1e-13,
3583                        "{question}: {pitch}"
3584                    );
3585                    assert!(
3586                        relative(unit(inertia.y_axis.y), pitch).abs() <= 1e-13,
3587                        "{question}"
3588                    );
3589                    assert!(
3590                        their_pitch > pitch * 1.2,
3591                        "{question}: {their_pitch} against hpr's {pitch}"
3592                    );
3593                }
3594            }
3595        }
3596    }
3597
3598    /// The record was written by the script it names, from OpenRocket 24.12 with no default
3599    /// materials saved in its preferences, and every probe it holds is one a test here reads: a
3600    /// probe added to the script and not to a test would be a question nobody checks the answer
3601    /// to.
3602    #[test]
3603    fn every_probe_is_checked() {
3604        let record = record();
3605        assert_eq!(record["openrocket"], "24.12");
3606        assert_eq!(
3607            record["source"],
3608            "validation/oracles/openrocket/conventions.py"
3609        );
3610        assert_eq!(record["saved_default_materials"], serde_json::json!({}));
3611        let mut read: Vec<&str> = READINGS.to_vec();
3612        read.extend(PRECEDENCE.iter().map(|(question, _)| *question));
3613        read.extend(DISAGREEING.iter().map(|(question, _)| *question));
3614        read.extend(INERTIA.iter().map(|(question, _)| *question));
3615        read.extend(ALONE.iter().map(|(question, _)| *question));
3616        read.extend(OLD_FLAG.iter().map(|(question, _)| *question));
3617        read.extend(STAGE_ADDS);
3618        read.push(STAGE_ADDS_TO_NOTHING);
3619        read.extend(STAGE_WHOLE);
3620        read.extend(STAGE_WHOLE_BELOW.iter().map(|(question, _)| *question));
3621        read.extend(BORES);
3622        read.push(BORE_REFUSED);
3623        read.extend(TUBE_FINS);
3624        let probes: Vec<&str> = record["probes"]
3625            .as_object()
3626            .expect("probes")
3627            .keys()
3628            .map(String::as_str)
3629            .collect();
3630        for question in &probes {
3631            assert!(
3632                read.contains(question),
3633                "no test reads the probe {question:?}"
3634            );
3635        }
3636        for question in &read {
3637            assert!(probes.contains(question), "no probe asks {question:?}");
3638        }
3639    }
3640
3641    /// Where hpr puts a tube fin set, against OpenRocket 24.12 (Loft lesson L19, ADR-102).
3642    struct TubeFinsSeen {
3643        probe: String,
3644        mach: f64,
3645        /// OpenRocket's set slope over hpr's.
3646        slope_ratio: f64,
3647        /// OpenRocket's set slope over `N π d²/A_ref`, the long-ring limit of `N` isolated rings.
3648        over_long_ring_limit: f64,
3649        /// hpr's rocket center of pressure less OpenRocket's, calibers.
3650        gap_cal: f64,
3651        /// How far hpr's center moves, calibers, with the tubes at OpenRocket's center alone, and
3652        /// with OpenRocket's slope alone.
3653        center_only_cal: f64,
3654        slope_only_cal: f64,
3655    }
3656
3657    /// `openrocket-tube-fin-aero.json`, held to the scripts that wrote it.
3658    fn tube_fin_record() -> Value {
3659        let text = include_str!("../../../validation/fixtures/ork/openrocket-tube-fin-aero.json");
3660        let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
3661        for (name, bytes) in [
3662            (
3663                "tube_fin_aero.py",
3664                include_bytes!("../../../validation/oracles/openrocket/tube_fin_aero.py")
3665                    .as_slice(),
3666            ),
3667            (
3668                "automatic_radius.py",
3669                include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
3670                    .as_slice(),
3671            ),
3672        ] {
3673            assert_eq!(
3674                record["inputs_sha256"][name],
3675                crate::real_flight::sha256_hex(bytes).as_str(),
3676                "{name} changed since the record was written: rerun it"
3677            );
3678        }
3679        record
3680    }
3681
3682    /// Every probe of `record` at each Mach number below the tube-fin model's limit, with the
3683    /// checks that hold whatever the two codes' models: the same geometry, the same nose and body,
3684    /// and OpenRocket's rule as its record shows it.
3685    fn tube_fins_seen(record: &Value) -> Vec<TubeFinsSeen> {
3686        let number = |value: &Value| value.as_f64().expect("a number");
3687        let mut seen = Vec::new();
3688        let probes = record["probes"].as_object().expect("probes");
3689        assert_eq!(probes.len(), 14);
3690        for (name, probe) in probes {
3691            let document = probe["document"].as_str().expect("the probe's document");
3692            let read = ork::read(document.as_bytes()).expect("a probe reads");
3693            let layout = ork::rocket(&read.value.document)
3694                .value
3695                .layout()
3696                .expect("a probe lays out");
3697            let model = hpr_aero::AeroModel::new(&layout).expect("hpr models the probe");
3698            let [set] = model.tube_fin_sets() else {
3699                panic!("{name}: not one tube fin set in hpr");
3700            };
3701            let mut slopes = Vec::new();
3702            for asked in probe["machs"].as_array().expect("machs") {
3703                let mach = number(&asked["mach"]);
3704                let cal = number(&asked["reference_length_m"]);
3705                let components = asked["components"].as_object().expect("components");
3706                let of = |class: &str| {
3707                    let mut found = components.values().filter(|c| c["class"] == class);
3708                    let one = found.next().expect("the component");
3709                    assert!(found.next().is_none(), "{name}: two of {class}");
3710                    one
3711                };
3712                let rocket = of("Rocket");
3713                let tubes = &components[&set.id];
3714                assert_eq!(tubes["class"], "TubeFinSet", "{name}");
3715                // The same rocket: reference area, the tubes' count, radii, leading edge and
3716                // length.
3717                let (outer, inner) = (
3718                    number(&tubes["outer_radius_m"]),
3719                    number(&tubes["inner_radius_m"]),
3720                );
3721                assert!(
3722                    (set.mean_diameter_m - (outer + inner)).abs() <= 1e-12,
3723                    "{name}"
3724                );
3725                let axis = number(&tubes["body_radius_m"]) + outer;
3726                assert!((set.axis_radius_m - axis).abs() <= 1e-12, "{name}");
3727                assert!(
3728                    (model.reference_area_m2() / number(&asked["reference_area_m2"]) - 1.0).abs()
3729                        <= 1e-12,
3730                    "{name}"
3731                );
3732                assert_eq!(
3733                    tubes["count"].as_u64(),
3734                    Some(u64::from(set.count)),
3735                    "{name}"
3736                );
3737                let fore_m = number(&tubes["leading_edge_x_m"]);
3738                let length_m = number(&tubes["length_m"]);
3739                assert!((set.fore_station_m - fore_m).abs() <= 1e-12, "{name}");
3740                assert!((set.length_m - length_m).abs() <= 1e-12, "{name}");
3741                // OpenRocket's rule, as its record shows it: one slope at every Mach number, and
3742                // the center a quarter of the length aft of the leading edge up to Mach 0.5, at
3743                // the leading edge from Mach 0.6.
3744                let (theirs, their_x) = (number(&tubes["cna_per_rad"]), number(&tubes["cp_x_m"]));
3745                slopes.push(theirs);
3746                let quarter = if mach <= 0.5 { 0.25 } else { 0.0 };
3747                assert!(
3748                    ((their_x - fore_m) / length_m - quarter).abs() <= 1e-9,
3749                    "{name} at Mach {mach}"
3750                );
3751                if mach >= hpr_aero::tube_fins::TUBE_FIN_MACH_LIMIT {
3752                    continue;
3753                }
3754                let (ours, our_x) = set.loading(mach).expect("below the limit");
3755                let whole = model
3756                    .normal_force(&hpr_aero::Flow::new(mach, 0.0, 0.0))
3757                    .expect("hpr's normal force");
3758                let our_cp = whole.cp_station_m.expect("a center of pressure");
3759                let (their_whole, their_cp) =
3760                    (number(&rocket["cna_per_rad"]), number(&rocket["cp_x_m"]));
3761                // The rest of the rocket, the nose and the body, is nearly the same in both
3762                // codes: OpenRocket gives the body tube a slope of 0.003 at its middle, hpr none,
3763                // which puts their center 0.015 calibers aft of hpr's nose's.
3764                let rest = whole.slope_per_rad - ours;
3765                let rest_moment = whole.moment_slope_m - ours * our_x;
3766                let (their_rest, their_rest_moment) = (
3767                    their_whole - theirs,
3768                    their_whole * their_cp - theirs * their_x,
3769                );
3770                assert!(
3771                    (rest - their_rest).abs() <= 0.005,
3772                    "{name}: {rest} {their_rest}"
3773                );
3774                assert!(
3775                    (rest_moment / rest - their_rest_moment / their_rest).abs() <= 0.02 * cal,
3776                    "{name}"
3777                );
3778                let center = |slope: f64, x: f64| (rest_moment + slope * x) / (rest + slope);
3779                // So the gap is the tubes': hpr with OpenRocket's slope and center for them is
3780                // OpenRocket's rocket.
3781                assert!(
3782                    (center(theirs, their_x) - their_cp).abs() <= 0.01 * cal,
3783                    "{name} at Mach {mach}: {}",
3784                    (center(theirs, their_x) - their_cp) / cal
3785                );
3786                let pi_d2 = std::f64::consts::PI * set.mean_diameter_m * set.mean_diameter_m;
3787                seen.push(TubeFinsSeen {
3788                    probe: name.clone(),
3789                    mach,
3790                    slope_ratio: theirs / ours,
3791                    over_long_ring_limit: theirs
3792                        / (f64::from(set.count) * pi_d2 / model.reference_area_m2()),
3793                    gap_cal: (our_cp - their_cp) / cal,
3794                    center_only_cal: (center(ours, their_x) - our_cp) / cal,
3795                    slope_only_cal: (center(theirs, our_x) - our_cp) / cal,
3796                });
3797            }
3798            assert!(
3799                slopes.iter().all(|s| (s / slopes[0] - 1.0).abs() <= 1e-12),
3800                "{name}: {slopes:?}"
3801            );
3802        }
3803        seen
3804    }
3805
3806    /// hpr's rocket center of pressure less OpenRocket's on each probe, calibers, at Mach 0.05,
3807    /// 0.3, 0.5, 0.6 and 0.75, as measured when ADR-102 was written.
3808    const TUBE_FIN_GAPS_CAL: [(&str, [f64; 5]); 14] = [
3809        (
3810            "3 tubes of 6 mm radius",
3811            [-2.7269, -2.7278, -2.7294, -2.2099, -2.2126],
3812        ),
3813        (
3814            "4 tubes of 6 mm radius",
3815            [-2.5611, -2.5624, -2.5648, -2.0028, -2.0068],
3816        ),
3817        (
3818            "5 tubes of 6 mm radius",
3819            [-2.3960, -2.3976, -2.4007, -1.8097, -1.8147],
3820        ),
3821        (
3822            "6 tubes of 6 mm radius",
3823            [-2.2474, -2.2493, -2.2529, -1.6410, -1.6468],
3824        ),
3825        (
3826            "8 tubes of 6 mm radius",
3827            [-2.0048, -2.0070, -2.0115, -1.3712, -1.3784],
3828        ),
3829        (
3830            "six touching tubes",
3831            [-1.0427, -1.0501, -1.0647, -0.3634, -0.3867],
3832        ),
3833        (
3834            "six touching tubes 0.025 m long",
3835            [-0.4262, -0.4237, -0.4197, -0.1844, -0.1834],
3836        ),
3837        (
3838            "six touching tubes 0.05 m long",
3839            [-0.7755, -0.7816, -0.7937, -0.3301, -0.3502],
3840        ),
3841        (
3842            "six touching tubes 0.15 m long",
3843            [-1.7202, -1.7285, -1.7448, -0.3262, -0.3518],
3844        ),
3845        (
3846            "six touching tubes 0.3 m long",
3847            [-2.9728, -2.9815, -2.9984, -0.1432, -0.1699],
3848        ),
3849        (
3850            "six touching tubes with a 0.001 m wall",
3851            [-1.0252, -1.0323, -1.0463, -0.3486, -0.3710],
3852        ),
3853        (
3854            "six touching tubes with a 0.003 m wall",
3855            [-0.8964, -0.9026, -0.9150, -0.2324, -0.2521],
3856        ),
3857        (
3858            "six tubes of 0.004 m radius",
3859            [-2.8034, -2.8039, -2.8048, -2.3076, -2.3091],
3860        ),
3861        (
3862            "six tubes of 0.008 m radius",
3863            [-1.7089, -1.7124, -1.7194, -1.0576, -1.0688],
3864        ),
3865    ];
3866
3867    /// Loft lesson L19: Loft put a tube fin set's center of pressure about 0.9 calibers forward of
3868    /// OpenRocket's. hpr's is further forward still, and the lesson's bar, a quarter caliber, is
3869    /// not met: this test measures the gap on OpenRocket 24.12's 14 probes, at five Mach numbers,
3870    /// and on its *Tube fin rocket*, and pins every one, so a change to either code shows
3871    /// (ADR-102).
3872    ///
3873    /// The whole gap is the tubes': the probes' geometry, nose and body agree, and with
3874    /// OpenRocket's slope and center for the tubes hpr's rocket is OpenRocket's. Both of
3875    /// OpenRocket's differ from hpr's cited ring wing (ADR-099). Its slope is 1.26 to 1.86 times
3876    /// hpr's, and 1.20 to 1.86 times the long-ring limit of as many isolated thin rings,
3877    /// `N π d²/A_ref`; its center is a quarter of the tube's length aft of the leading edge up to
3878    /// Mach 0.5, and the leading edge from Mach 0.6, a jump its maintainers call a bug and fixed
3879    /// after 24.12 (openrocket#3235).
3880    #[test]
3881    fn tube_fin_cp_against_the_oracle_measured_and_pinned() {
3882        let record = tube_fin_record();
3883        let seen = tube_fins_seen(&record);
3884        let close = |found: f64, pinned: f64, what: &str| {
3885            assert!(
3886                (found - pinned).abs() <= 5e-4,
3887                "{what}: {found} against {pinned}"
3888            );
3889        };
3890        // Every gap, probe by probe and Mach number by Mach number.
3891        assert_eq!(seen.len(), TUBE_FIN_GAPS_CAL.len() * 5);
3892        for (probe, gaps) in TUBE_FIN_GAPS_CAL {
3893            let found: Vec<&TubeFinsSeen> = seen.iter().filter(|s| s.probe == probe).collect();
3894            assert_eq!(found.len(), gaps.len(), "{probe}");
3895            for (s, gap) in found.iter().zip(gaps) {
3896                close(s.gap_cal, gap, &format!("{probe} at Mach {}", s.mach));
3897            }
3898        }
3899        let range = |values: Vec<f64>| {
3900            let least = values.iter().copied().fold(f64::INFINITY, f64::min);
3901            (
3902                least,
3903                values.iter().copied().fold(f64::NEG_INFINITY, f64::max),
3904            )
3905        };
3906        // OpenRocket's slope against hpr's, and against the long-ring limit of isolated rings.
3907        let (least, most) = range(seen.iter().map(|s| s.slope_ratio).collect());
3908        close(least, 1.2631, "the least slope ratio");
3909        close(most, 1.8638, "the largest slope ratio");
3910        let (least, most) = range(seen.iter().map(|s| s.over_long_ring_limit).collect());
3911        close(least, 1.2038, "the least share of the long-ring limit");
3912        close(most, 1.8556, "the largest share of the long-ring limit");
3913        // OpenRocket's slope per tube does not change with the count: it models no interference
3914        // that does (ADR-102).
3915        let per_tube: Vec<f64> = [3, 4, 5, 6, 8]
3916            .iter()
3917            .map(|count| {
3918                let asked = &record["probes"][format!("{count} tubes of 6 mm radius")]["machs"][0];
3919                let tubes = asked["components"]
3920                    .as_object()
3921                    .and_then(|all| all.values().find(|c| c["class"] == "TubeFinSet"))
3922                    .expect("the tubes");
3923                tubes["cna_per_rad"].as_f64().expect("a slope") / f64::from(*count)
3924            })
3925            .collect();
3926        assert!(
3927            per_tube
3928                .iter()
3929                .all(|s| (s / per_tube[0] - 1.0).abs() <= 1e-15),
3930            "{per_tube:?}"
3931        );
3932        // On the probe built like the *Tube fin rocket*, at Mach 0.05, what OpenRocket's center
3933        // alone and its slope alone would move hpr's by.
3934        let touching = seen
3935            .iter()
3936            .find(|s| s.probe == "six touching tubes")
3937            .expect("the probe");
3938        close(
3939            touching.center_only_cal,
3940            0.4952,
3941            "OpenRocket's center alone",
3942        );
3943        close(touching.slope_only_cal, 0.5319, "OpenRocket's slope alone");
3944        // Up to Mach 0.5, where OpenRocket takes the quarter length, no probe is within L19's
3945        // bar; from Mach 0.6, where it takes the leading edge, five of the 28 are. That jump is a
3946        // bug in 24.12, fixed after it (openrocket#3235).
3947        let within: Vec<(&str, f64)> = seen
3948            .iter()
3949            .filter(|s| s.gap_cal.abs() <= 0.25)
3950            .map(|s| (s.probe.as_str(), s.mach))
3951            .collect();
3952        assert_eq!(
3953            within,
3954            [
3955                ("six touching tubes 0.025 m long", 0.6),
3956                ("six touching tubes 0.025 m long", 0.75),
3957                ("six touching tubes 0.3 m long", 0.6),
3958                ("six touching tubes 0.3 m long", 0.75),
3959                ("six touching tubes with a 0.003 m wall", 0.6),
3960            ]
3961        );
3962        // OpenRocket's own *Tube fin rocket*: the probe record's example and the flight record's
3963        // are the same OpenRocket answer, and hpr's center, in the flight record, is 1.07
3964        // calibers forward of it at rod clearance.
3965        let flights: Value = serde_json::from_str(include_str!(
3966            "../../../validation/reports/openrocket-flights.json"
3967        ))
3968        .expect("the flight record");
3969        let flight = flights["flights"]
3970            .as_array()
3971            .and_then(|all| all.iter().find(|f| f["design"] == "Tube fin rocket"))
3972            .expect("the Tube fin rocket's flight");
3973        let at = &flight["at_rod_clearance"];
3974        let number = |value: &Value| value.as_f64().expect("a number");
3975        let example = &record["example"]["machs"][0];
3976        assert_eq!(number(&example["mach"]), 0.05);
3977        let rocket = example["components"]
3978            .as_object()
3979            .and_then(|all| all.values().find(|c| c["class"] == "Rocket"))
3980            .expect("the example's rocket");
3981        let theirs = number(&at["openrocket"]["cp_from_nose_m"]);
3982        // The flight record's is OpenRocket's flight data at rod clearance; it is 1.4e-5 m from
3983        // its calculator's answer asked directly.
3984        assert!((number(&rocket["cp_x_m"]) - theirs).abs() <= 1e-4);
3985        assert!(
3986            number(&at["mach"]) < 0.5,
3987            "OpenRocket's quarter-length center"
3988        );
3989        let gap = (number(&at["hpr"]["cp_from_nose_m"]) - theirs)
3990            / number(&at["openrocket"]["reference_length_m"]);
3991        close(gap, -1.0747, "the Tube fin rocket at rod clearance");
3992    }
3993
3994    /// `openrocket-drag-override.json`, held to the scripts that wrote it.
3995    fn drag_override_record() -> Value {
3996        let text = include_str!("../../../validation/fixtures/ork/openrocket-drag-override.json");
3997        let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
3998        for (name, bytes) in [
3999            (
4000                "drag_override.py",
4001                include_bytes!("../../../validation/oracles/openrocket/drag_override.py")
4002                    .as_slice(),
4003            ),
4004            (
4005                "automatic_radius.py",
4006                include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
4007                    .as_slice(),
4008            ),
4009        ] {
4010            assert_eq!(
4011                record["inputs_sha256"][name],
4012                crate::real_flight::sha256_hex(bytes).as_str(),
4013                "{name} changed since the record was written: rerun it"
4014            );
4015        }
4016        record
4017    }
4018
4019    /// hpr's zero-lift drag coefficient for a probe document at `mach`, at sea level.
4020    fn probe_drag(document: &str, mach: f64) -> f64 {
4021        // `V/ν` at sea level in the US Standard Atmosphere (a = 340.294 m/s, ν = 1.4607e-5 m²/s).
4022        let reynolds_per_m = mach * 340.294 / 1.4607e-5;
4023        let read = ork::read(document.as_bytes()).expect("a probe reads");
4024        let layout = ork::rocket(&read.value.document)
4025            .value
4026            .layout()
4027            .expect("a probe lays out");
4028        hpr_aero::AeroModel::new(&layout)
4029            .expect("hpr models the probe")
4030            .drag(
4031                &hpr_aero::Flow::axial(mach),
4032                &hpr_aero::DragConditions::coasting(reynolds_per_m),
4033            )
4034            .expect("hpr's drag")
4035            .zero_lift_coefficient
4036    }
4037
4038    /// M4.5h (#165, ADR-167): a part's stated drag coefficient changes hpr's drag as it changes
4039    /// OpenRocket 24.12's, on every probe of `drag_override.py`: the change from the same airframe
4040    /// with nothing stated, hpr's against OpenRocket's.
4041    ///
4042    /// The stated coefficient is the same in both codes, so what is left is the difference between
4043    /// the two codes' own drag of the parts it replaces, and OpenRocket's raising the friction of
4044    /// the parts left when an aft part is stated (ADR-167). Below Mach 0.6, where hpr's buildup and
4045    /// OpenRocket's agree closely on bodies and fins, that is at most 0.0059 here (the probes stating
4046    /// the flare), and no more at any Mach number for all but the nose's and the boattail's;
4047    /// a step's base drag charged to the wrong part would move it by 0.043 or more (the `step`
4048    /// airframe's, the smallest), and a fin set's coefficient counted once by 1.0. The nose's and
4049    /// the boattail's probes are held only up to Mach 0.6: faster, the two codes' own drag of
4050    /// those parts differs by up to 0.21 and 0.061, the buildups' difference, not the setting's.
4051    ///
4052    /// hpr's lugs and buttons drag more than OpenRocket's (0.036 and 0.032 more for the two of
4053    /// each here), so the probes that state them are held to 0.075; one instance counted wrong
4054    /// would move them by 0.5. The tube covering its children is held as a body is, once the lugs'
4055    /// and buttons' own gaps, from those probes, are taken off: a lug or a button left uncovered
4056    /// would move it by 0.03 or more. The stage covering its children is the whole drag in both
4057    /// codes: exactly 0.5. A stage's coefficient alone, and one on a part inside the body, change
4058    /// both codes' drag exactly as much at every Mach number, and the fins' agree within 1e-4.
4059    ///
4060    /// Since M1.14i3 (ADR-362) hpr's base behind a boattail keeps `d_B/d₁` of the flat-base
4061    /// drag below Mach 0.8 (NASA TR R-100, p. 11), where OpenRocket keeps all of it, so stating
4062    /// the boattail, which carries the base, moves hpr's drag by that much more. The difference
4063    /// is written out by hand from the probe's 8° cone, 25 mm to 18 mm in radius, and taken off
4064    /// before the probe is held as before.
4065    #[test]
4066    fn a_stated_drag_coefficient_moves_the_drag_as_openrocket_s() {
4067        // The flat-base drag, (0.12 + 0.13 M²) on the base's area over the body's (Niskanen
4068        // 2009, eq. 3.94), less the share of it hpr keeps behind the boattail, d_B/d₁.
4069        let (fore, aft) = (0.025_f64, 0.018_f64);
4070        let relief =
4071            |mach: f64| (0.12 + 0.13 * mach * mach) * (aft / fore).powi(2) * (1.0 - aft / fore);
4072        let record = drag_override_record();
4073        let variants = record["variants"].as_object().expect("variants");
4074        assert_eq!(variants.len(), 25);
4075        // Each probe's Mach numbers, with hpr's drag and the change in hpr's and OpenRocket's.
4076        let mut changes = std::collections::BTreeMap::new();
4077        for (name, variant) in variants {
4078            let airframe = &variants[variant["airframe"].as_str().expect("an airframe")];
4079            let document = variant["document"].as_str().expect("a document");
4080            let plain = airframe["document"].as_str().expect("a document");
4081            let mut rows = Vec::new();
4082            for (asked, plain_asked) in variant["machs"]
4083                .as_array()
4084                .expect("machs")
4085                .iter()
4086                .zip(airframe["machs"].as_array().expect("machs"))
4087            {
4088                let mach = asked["mach"].as_f64().expect("a Mach number");
4089                let cd = asked["rocket"]["cd"].as_f64().expect("a coefficient");
4090                let theirs = cd - plain_asked["rocket"]["cd"].as_f64().expect("a coefficient");
4091                let ours_cd = probe_drag(document, mach);
4092                rows.push((mach, ours_cd, cd, ours_cd - probe_drag(plain, mach), theirs));
4093            }
4094            changes.insert(name.as_str(), rows);
4095        }
4096        let gap_of = |name: &str, at: usize| {
4097            let (_, _, _, ours, theirs) = changes[name][at];
4098            ours - theirs
4099        };
4100        let mut largest_body_gap: f64 = 0.0;
4101        for (name, rows) in &changes {
4102            let exact = ["the stage at 0.5", "the inner tube", "the ring", "the mass"]
4103                .iter()
4104                .any(|part| name.ends_with(&format!("{part} at 0.5")) || name.ends_with(part));
4105            let lugs_or_buttons = name.contains("the lugs") || name.contains("the buttons");
4106            let subsonic_only = name.contains("the nose") || name.contains("the boattail at");
4107            for (at, &(mach, ours_cd, theirs_cd, ours, theirs)) in rows.iter().enumerate() {
4108                let mut gap = ours - theirs;
4109                let what =
4110                    format!("{name} at Mach {mach}: hpr {ours:+.5}, OpenRocket {theirs:+.5}");
4111                if *name == "flare, the stage at 0.5 with its children" {
4112                    assert!((ours_cd - 0.5).abs() <= 1e-12, "{what}: hpr {ours_cd}");
4113                    assert!(
4114                        (theirs_cd - 0.5).abs() <= 1e-12,
4115                        "{what}: OpenRocket {theirs_cd}"
4116                    );
4117                    continue;
4118                }
4119                if *name == "flare, the tube at 0.5 with its children" {
4120                    gap -= gap_of("flare, the lugs at 0.5", at)
4121                        + gap_of("flare, the buttons at 0.5", at);
4122                }
4123                if *name == "boattail, the boattail at 0.2" && mach <= 0.8 {
4124                    gap -= relief(mach);
4125                }
4126                if exact {
4127                    assert!(gap.abs() <= 1e-9, "{what}");
4128                } else if name.contains("the fins") {
4129                    assert!(gap.abs() <= 1e-4, "{what}");
4130                } else if lugs_or_buttons {
4131                    assert!(gap.abs() <= 0.075, "{what}");
4132                } else if mach <= 0.6 || !subsonic_only {
4133                    assert!(gap.abs() <= 0.0065, "{what}");
4134                    largest_body_gap = largest_body_gap.max(gap.abs());
4135                }
4136            }
4137        }
4138        assert!(
4139            (largest_body_gap - 0.0059).abs() < 1e-4,
4140            "{largest_body_gap}"
4141        );
4142    }
4143
4144    /// `openrocket-nose-pressure-drag.json`, held to the scripts that wrote it.
4145    fn nose_pressure_drag_record() -> Value {
4146        let text =
4147            include_str!("../../../validation/fixtures/ork/openrocket-nose-pressure-drag.json");
4148        let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
4149        for (name, bytes) in [
4150            (
4151                "nose_pressure_drag.py",
4152                include_bytes!("../../../validation/oracles/openrocket/nose_pressure_drag.py")
4153                    .as_slice(),
4154            ),
4155            (
4156                "automatic_radius.py",
4157                include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
4158                    .as_slice(),
4159            ),
4160        ] {
4161            assert_eq!(
4162                record["inputs_sha256"][name],
4163                crate::real_flight::sha256_hex(bytes).as_str(),
4164                "{name} changed since the record was written: rerun it"
4165            );
4166        }
4167        record
4168    }
4169
4170    /// hpr's pressure drag of the part `id` of a probe document at `mach`, at sea level and zero
4171    /// angle of attack, put on `area_m2` instead of the rocket's reference area.
4172    fn probe_part_pressure_drag(document: &str, id: &str, mach: f64, area_m2: f64) -> f64 {
4173        // `V/ν` at sea level in the US Standard Atmosphere (a = 340.294 m/s, ν = 1.4607e-5 m²/s).
4174        let reynolds_per_m = mach * 340.294 / 1.4607e-5;
4175        let read = ork::read(document.as_bytes()).expect("a probe reads");
4176        let layout = ork::rocket(&read.value.document)
4177            .value
4178            .layout()
4179            .expect("a probe lays out");
4180        let model = hpr_aero::AeroModel::new(&layout).expect("hpr models the probe");
4181        let parts = model
4182            .buildup_components(
4183                &hpr_aero::Flow::axial(mach),
4184                &hpr_aero::DragConditions::coasting(reynolds_per_m),
4185            )
4186            .expect("hpr's drag by part");
4187        let mut found = parts.iter().filter(|part| part.id == id);
4188        let part = found.next().expect("the part is in the buildup");
4189        assert!(found.next().is_none(), "one part of that id");
4190        part.drag.pressure * model.reference_area_m2() / area_m2
4191    }
4192
4193    /// The nose `id` of a probe document as hpr reads it, and the largest aft radius of the
4194    /// document's transitions, m (0 with none).
4195    fn probe_nose(document: &str, id: &str) -> (hpr_design::NoseCone, f64) {
4196        let read = ork::read(document.as_bytes()).expect("a probe reads");
4197        let layout = ork::rocket(&read.value.document)
4198            .value
4199            .layout()
4200            .expect("a probe lays out");
4201        let nose = layout
4202            .components
4203            .iter()
4204            .find_map(|placed| match &placed.part {
4205                Part::NoseCone(nose) if placed.id == id => Some(nose.clone()),
4206                _ => None,
4207            })
4208            .expect("the nose");
4209        let widest_m = layout
4210            .components
4211            .iter()
4212            .filter_map(|placed| match &placed.part {
4213                Part::Transition(transition) => Some(transition.aft_radius_m),
4214                _ => None,
4215            })
4216            .fold(0.0, f64::max);
4217        (nose, widest_m)
4218    }
4219
4220    /// M2.3c10 (ADR-273, ADR-349): a fineness-3 tangent ogive's pressure drag at Mach 1.3, 1.5
4221    /// and 2, on the nose's base area, in hpr and in OpenRocket 24.12, beside the equivalent
4222    /// cone's.
4223    ///
4224    /// The equivalent cone has the nose's length and base diameter: its half-angle `ε` has
4225    /// `sin ε = 1/√(1 + 4f²)` for fineness `f`, and Niskanen's eq. B.4 gives it
4226    /// `2.1 sin² ε + 0.5 sin ε/√(M² − 1)` from Mach 1.3 up (2009, appendix B). Eq. B.8 multiplies
4227    /// that by `0.72 (κ − ½)² + 0.82` for an ogive, which is exactly 1 for a tangent ogive
4228    /// (`κ = 1`), so the documented method gives a tangent ogive its equivalent cone's drag.
4229    ///
4230    /// - hpr's tangent ogive is the equivalent cone's at each Mach number: 0.15571, 0.13028 and
4231    ///   0.10421.
4232    /// - OpenRocket 24.12's cone, the control, is the same closed form, within 1e-12 at Mach 1.5
4233    ///   and 2 and 4.8e-6 below it at Mach 1.3: its per-component pressure column is the nose's
4234    ///   pressure drag alone.
4235    /// - The same cone on a body that widens behind it, where the reference area is 2.56 times
4236    ///   the nose's base, gives 1/2.56 of that: the column is on the rocket's reference area.
4237    /// - OpenRocket 24.12's tangent ogive is 0.00098, 0.00073 and 0.00047: under 1% of the
4238    ///   equivalent cone's at each. That is the defect OpenRocket's issue #3391
4239    ///   (<https://github.com/openrocket/openrocket/issues/3391>) reports; a fix was merged
4240    ///   after 24.12 (pull request #3431).
4241    ///
4242    /// Neither number is a measurement: whether the equivalent cone's value matches a measured
4243    /// tangent ogive is open (#222, #616).
4244    #[test]
4245    fn a_tangent_ogive_s_pressure_drag_past_mach_1_beside_openrocket_24_12_s() {
4246        let record = nose_pressure_drag_record();
4247        assert_eq!(record["openrocket"], "24.12");
4248        assert_eq!(
4249            record["cites"],
4250            "https://github.com/openrocket/openrocket/issues/3391"
4251        );
4252        let number = |value: &Value| value.as_f64().expect("a number");
4253        let nose = record["nose_id"].as_str().expect("the nose's id");
4254        let base_area_m2 = number(&record["nose_base_area_m2"]);
4255        let fineness =
4256            number(&record["nose_length_m"]) / (2.0 * (base_area_m2 / std::f64::consts::PI).sqrt());
4257        assert!((fineness - 3.0).abs() < 1e-12, "fineness {fineness}");
4258        let sin_half_angle = 1.0 / (1.0 + 4.0 * fineness * fineness).sqrt();
4259        let equivalent_cone = |mach: f64| {
4260            2.1 * sin_half_angle * sin_half_angle
4261                + 0.5 * sin_half_angle / (mach * mach - 1.0).sqrt()
4262        };
4263        let designs = record["designs"].as_object().expect("designs");
4264        assert_eq!(
4265            designs.keys().map(String::as_str).collect::<Vec<_>>(),
4266            ["cone", "cone, wider body", "tangent ogive"]
4267        );
4268        // Each row: the Mach number, the equivalent cone's coefficient, hpr's tangent ogive and
4269        // OpenRocket 24.12's, all on the nose's base area; then OpenRocket's cone less the
4270        // closed form, and how closely that is held. At Mach 1.5 and 2 OpenRocket's cone is the
4271        // closed form within 1e-12; at Mach 1.3 it is 4.8e-6 below it (0.003%).
4272        let pinned = [
4273            (1.3, 0.155_71, 0.155_71, 0.000_98, -4.8e-6, 1e-7),
4274            (1.5, 0.130_28, 0.130_28, 0.000_73, 0.0, 1e-12),
4275            (2.0, 0.104_21, 0.104_21, 0.000_47, 0.0, 1e-12),
4276        ];
4277        // Each design's document and rows, with its reference area over the nose's base area:
4278        // 1 where the nose's tube is the widest, 2.56 where the body widens to 80 mm.
4279        let rows = |design: &str, area_ratio: f64| {
4280            let design = &designs[design];
4281            let document = design["document"].as_str().expect("a document").to_owned();
4282            let machs = design["machs"].as_array().expect("machs").clone();
4283            assert_eq!(machs.len(), pinned.len(), "one row a Mach number");
4284            for (row, pin) in machs.iter().zip(&pinned) {
4285                assert!((number(&row["mach"]) - pin.0).abs() < 1e-12);
4286                let ratio = number(&row["reference_area_m2"]) / base_area_m2;
4287                assert!((ratio - area_ratio).abs() < 1e-12, "area ratio {ratio}");
4288            }
4289            (document, machs)
4290        };
4291        let (ogive, ogive_rows) = rows("tangent ogive", 1.0);
4292        let (cone, cone_rows) = rows("cone", 1.0);
4293        let (wide, wide_rows) = rows("cone, wider body", 2.56);
4294        // Each document holds the nose its name says, as hpr reads it. hpr gives a tangent ogive
4295        // and a cone the same pressure drag here, so without this the documents could be
4296        // swapped and every number below would still hold.
4297        for (document, shape, widest_m) in [
4298            (
4299                &ogive,
4300                hpr_design::NoseShape::Ogive { radius_ratio: 1.0 },
4301                0.0,
4302            ),
4303            (&cone, hpr_design::NoseShape::Conical {}, 0.0),
4304            (&wide, hpr_design::NoseShape::Conical {}, 0.04),
4305        ] {
4306            let (read, read_widest_m) = probe_nose(document, nose);
4307            assert_eq!(read.shape, shape);
4308            assert!((read.length_m - number(&record["nose_length_m"])).abs() < 1e-12);
4309            let read_base_m2 = std::f64::consts::PI * read.base_radius_m * read.base_radius_m;
4310            assert!((read_base_m2 - base_area_m2).abs() < 1e-12);
4311            assert!(
4312                (read_widest_m - widest_m).abs() < 1e-12,
4313                "the body widens to {read_widest_m} m"
4314            );
4315        }
4316        // OpenRocket's coefficient of the nose as it returns it, and put on the nose's base area.
4317        let column = |row: &Value| number(&row["components"][nose]["pressure"]);
4318        let theirs = |row: &Value| column(row) * number(&row["reference_area_m2"]) / base_area_m2;
4319        for (at, (mach, cone_pin, ours_pin, theirs_pin, cone_gap_pin, cone_gap_within)) in
4320            pinned.into_iter().enumerate()
4321        {
4322            let closed_form = equivalent_cone(mach);
4323            assert!(
4324                (closed_form - cone_pin).abs() < 5e-6,
4325                "{mach}: {closed_form}"
4326            );
4327
4328            // hpr: the tangent ogive is its equivalent cone, and so is the cone, on either body.
4329            let ours = probe_part_pressure_drag(&ogive, nose, mach, base_area_m2);
4330            assert!((ours - ours_pin).abs() < 5e-6, "hpr at Mach {mach}: {ours}");
4331            assert!(
4332                (ours - closed_form).abs() < 1e-12,
4333                "hpr at Mach {mach}: {ours}"
4334            );
4335            for document in [&cone, &wide] {
4336                let ours_cone = probe_part_pressure_drag(document, nose, mach, base_area_m2);
4337                assert!(
4338                    (ours_cone - closed_form).abs() < 1e-12,
4339                    "hpr's cone at Mach {mach}: {ours_cone}"
4340                );
4341            }
4342
4343            // OpenRocket 24.12: the cone is the closed form, so the column read is the nose's
4344            // pressure drag.
4345            let cone_gap = theirs(&cone_rows[at]) - closed_form;
4346            assert!(
4347                (cone_gap - cone_gap_pin).abs() < cone_gap_within,
4348                "OpenRocket's cone at Mach {mach}: {cone_gap:e} from the closed form"
4349            );
4350            // On the wider body the column is 1/2.56 of the cone's on its own tube, and the
4351            // closed form again once put on the nose's base: it is on the reference area.
4352            let wide_column = column(&wide_rows[at]);
4353            assert!(
4354                (wide_column * 2.56 - column(&cone_rows[at])).abs() < 1e-12,
4355                "OpenRocket's cone on the wider body at Mach {mach}: {wide_column}"
4356            );
4357            let wide_gap = theirs(&wide_rows[at]) - closed_form;
4358            assert!(
4359                (wide_gap - cone_gap_pin).abs() < cone_gap_within,
4360                "OpenRocket's cone on the wider body at Mach {mach}: {wide_gap:e}"
4361            );
4362
4363            // The tangent ogive is under 1% of the equivalent cone's.
4364            let their_ogive = theirs(&ogive_rows[at]);
4365            assert!(
4366                (their_ogive - theirs_pin).abs() < 5e-6,
4367                "OpenRocket's tangent ogive at Mach {mach}: {their_ogive}"
4368            );
4369            assert!(
4370                their_ogive > 0.0 && their_ogive < 0.01 * closed_form,
4371                "OpenRocket's tangent ogive at Mach {mach}: {their_ogive} of {closed_form}"
4372            );
4373        }
4374    }
4375
4376    /// `openrocket-nose-pressure-drag-transonic.json`, held to the scripts that wrote it.
4377    fn nose_pressure_drag_transonic_record() -> Value {
4378        let text = include_str!(
4379            "../../../validation/fixtures/ork/openrocket-nose-pressure-drag-transonic.json"
4380        );
4381        let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
4382        for (name, bytes) in [
4383            (
4384                "nose_pressure_drag_transonic.py",
4385                include_bytes!(
4386                    "../../../validation/oracles/openrocket/nose_pressure_drag_transonic.py"
4387                )
4388                .as_slice(),
4389            ),
4390            (
4391                "nose_pressure_drag.py",
4392                include_bytes!("../../../validation/oracles/openrocket/nose_pressure_drag.py")
4393                    .as_slice(),
4394            ),
4395            (
4396                "automatic_radius.py",
4397                include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
4398                    .as_slice(),
4399            ),
4400        ] {
4401            assert_eq!(
4402                record["inputs_sha256"][name],
4403                crate::real_flight::sha256_hex(bytes).as_str(),
4404                "{name} changed since the record was written: rerun it"
4405            );
4406        }
4407        record
4408    }
4409
4410    /// #1500: the same fineness-3 tangent ogive and its conical control from Mach 1 to 1.3,
4411    /// every 0.01, in hpr and in OpenRocket 24.12, on the nose's base area (the rocket's
4412    /// reference area on these two designs).
4413    ///
4414    /// Niskanen's method gives a cone `sin ε` at Mach 1 and eq. B.4 from Mach 1.3, joined by the
4415    /// cubic that meets both ends' values and slopes (2009, appendix B, eq. B.3 to B.6); a
4416    /// tangent ogive takes its equivalent cone's value (eq. B.8).
4417    ///
4418    /// - hpr's tangent ogive is its cone at every row, bit for bit: 0.16440 at Mach 1, 0.23428 at
4419    ///   Mach 1.1, the highest of the 31 rows, and 0.15571 at Mach 1.3.
4420    /// - OpenRocket 24.12's cone, the control, is hpr's within 5e-6 at every even hundredth, so
4421    ///   the column read is again the nose's pressure drag. Each odd hundredth of OpenRocket's,
4422    ///   for both noses, is the mean of its two neighbors within 1e-15, as if OpenRocket read its
4423    ///   curve every 0.02 and drew straight lines between. That leaves its cone within 0.00094
4424    ///   (0.53%) of hpr's, the most at Mach 1.01.
4425    /// - OpenRocket 24.12's tangent ogive is below hpr's at every row, by 0.155 to 0.163: 1.0%
4426    ///   of it at Mach 1, rising to 32.2% at Mach 1.1 (the hump OpenRocket's issue #3391
4427    ///   reports), and 0.6% at Mach 1.3.
4428    ///
4429    /// Neither number is a measurement (#222, #616).
4430    #[test]
4431    fn a_tangent_ogive_s_pressure_drag_from_mach_1_to_1_3_beside_openrocket_24_12_s() {
4432        let record = nose_pressure_drag_transonic_record();
4433        let first = nose_pressure_drag_record();
4434        assert_eq!(record["openrocket"], "24.12");
4435        for key in [
4436            "nose_id",
4437            "nose_length_m",
4438            "nose_base_area_m2",
4439            "cites",
4440            "jar_sha256",
4441            "java",
4442        ] {
4443            assert_eq!(record[key], first[key], "{key}");
4444        }
4445        let number = |value: &Value| value.as_f64().expect("a number");
4446        let nose = record["nose_id"].as_str().expect("the nose's id");
4447        let base_area_m2 = number(&record["nose_base_area_m2"]);
4448        let designs = record["designs"].as_object().expect("designs");
4449        assert_eq!(
4450            designs.keys().map(String::as_str).collect::<Vec<_>>(),
4451            ["cone", "tangent ogive"]
4452        );
4453        // The documents are the first probe's, whose test reads each with hpr and checks that it
4454        // holds the nose its name says.
4455        for name in ["cone", "tangent ogive"] {
4456            assert_eq!(
4457                designs[name]["document"],
4458                first["designs"][name]["document"]
4459            );
4460        }
4461        let rows = |name: &str| designs[name]["machs"].as_array().expect("machs").clone();
4462        let (ogive_rows, cone_rows) = (rows("tangent ogive"), rows("cone"));
4463        assert_eq!((ogive_rows.len(), cone_rows.len()), (31, 31));
4464        let column = |row: &Value| number(&row["components"][nose]["pressure"]);
4465        for (step, (ogive_row, cone_row)) in ogive_rows.iter().zip(&cone_rows).enumerate() {
4466            for row in [ogive_row, cone_row] {
4467                let mach = 1.0 + 0.01 * step as f64;
4468                assert!((number(&row["mach"]) - mach).abs() < 1e-12);
4469                assert!((number(&row["reference_area_m2"]) - base_area_m2).abs() < 1e-15);
4470            }
4471        }
4472        // The nose's column at Mach 1.3 is the first probe's.
4473        let first_at_1_3 = |name: &str| first["designs"][name]["machs"][0].clone();
4474        assert_eq!(number(&first_at_1_3("cone")["mach"]), 1.3);
4475        assert_eq!(
4476            column(&ogive_rows[30]),
4477            column(&first_at_1_3("tangent ogive"))
4478        );
4479        assert_eq!(column(&cone_rows[30]), column(&first_at_1_3("cone")));
4480
4481        let document = |name: &str| designs[name]["document"].as_str().expect("a document");
4482        let (ogive, cone) = (document("tangent ogive"), document("cone"));
4483        // At Mach 1 the method gives the cone sin ε = 1/√37.
4484        let at_1 = probe_part_pressure_drag(cone, nose, 1.0, base_area_m2);
4485        assert!((at_1 - 37_f64.sqrt().recip()).abs() < 1e-12, "{at_1}");
4486        let (mut least_gap, mut most_gap) = (f64::INFINITY, f64::NEG_INFINITY);
4487        let mut least_share = (f64::INFINITY, 0.0);
4488        let mut most_share = (f64::NEG_INFINITY, 0.0);
4489        let (mut odd_gap, mut odd_share, mut odd_at) = (0.0_f64, 0.0_f64, 0.0);
4490        let mut highest = (f64::NEG_INFINITY, 0.0);
4491        for (step, (ogive_row, cone_row)) in ogive_rows.iter().zip(&cone_rows).enumerate() {
4492            let mach = number(&ogive_row["mach"]);
4493            let ours = probe_part_pressure_drag(ogive, nose, mach, base_area_m2);
4494            let ours_cone = probe_part_pressure_drag(cone, nose, mach, base_area_m2);
4495            assert_eq!(ours, ours_cone, "hpr's ogive is its cone at Mach {mach}");
4496            if ours > highest.0 {
4497                highest = (ours, mach);
4498            }
4499            // OpenRocket's cone: hpr's at the even hundredths. At the odd ones each of its
4500            // columns is the mean of its two neighbors.
4501            let cone_gap = column(cone_row) - ours_cone;
4502            if step % 2 == 0 {
4503                assert!(cone_gap.abs() < 5e-6, "Mach {mach}: {cone_gap:e}");
4504            } else {
4505                for rows in [&ogive_rows, &cone_rows] {
4506                    let mean = 0.5 * (column(&rows[step - 1]) + column(&rows[step + 1]));
4507                    let off = column(&rows[step]) - mean;
4508                    assert!(off.abs() < 1e-15, "Mach {mach}: {off:e} from the mean");
4509                }
4510                if cone_gap.abs() > odd_gap {
4511                    (odd_gap, odd_at) = (cone_gap.abs(), mach);
4512                }
4513                odd_share = odd_share.max(cone_gap.abs() / ours_cone);
4514            }
4515            // OpenRocket's tangent ogive: below hpr's at every row.
4516            let gap = ours - column(ogive_row);
4517            assert!(gap > 0.0, "Mach {mach}");
4518            least_gap = least_gap.min(gap);
4519            most_gap = most_gap.max(gap);
4520            let share = column(ogive_row) / ours;
4521            if share < least_share.0 {
4522                least_share = (share, mach);
4523            }
4524            if share > most_share.0 {
4525                most_share = (share, mach);
4526            }
4527        }
4528        assert!((odd_gap - 0.000_94).abs() < 5e-6, "{odd_gap}");
4529        assert!((odd_at - 1.01_f64).abs() < 1e-12, "{odd_at}");
4530        assert!((highest.1 - 1.1_f64).abs() < 1e-12, "{highest:?}");
4531        assert!((odd_share - 0.0053).abs() < 5e-5, "{odd_share}");
4532        let share_at_1 = column(&ogive_rows[0]) / at_1;
4533        assert!((share_at_1 - 0.0099).abs() < 5e-5, "{share_at_1}");
4534        assert!((least_gap - 0.1547).abs() < 1e-4, "{least_gap}");
4535        assert!((most_gap - 0.1628).abs() < 1e-4, "{most_gap}");
4536        assert!((least_share.0 - 0.0063).abs() < 1e-4, "{least_share:?}");
4537        assert!((least_share.1 - 1.3_f64).abs() < 1e-12, "{least_share:?}");
4538        assert!((most_share.0 - 0.3223).abs() < 1e-4, "{most_share:?}");
4539        assert!((most_share.1 - 1.1_f64).abs() < 1e-12, "{most_share:?}");
4540
4541        // The rows the aerodynamics page shows: Mach, hpr's tangent ogive (and cone), then
4542        // OpenRocket 24.12's tangent ogive and its cone, all on the nose's base area.
4543        let shown = [
4544            (1.0, 0.164_40, 0.001_62, 0.164_40),
4545            (1.05, 0.218_16, 0.058_58, 0.217_41),
4546            (1.1, 0.234_28, 0.075_51, 0.234_27),
4547            (1.15, 0.224_41, 0.063_54, 0.224_12),
4548            (1.2, 0.200_24, 0.038_24, 0.200_24),
4549            (1.25, 0.173_45, 0.012_94, 0.173_63),
4550            (1.3, 0.155_71, 0.000_98, 0.155_71),
4551        ];
4552        for (mach, ours_pin, ogive_pin, cone_pin) in shown {
4553            let at = ((mach - 1.0) / 0.01_f64).round() as usize;
4554            assert!((number(&ogive_rows[at]["mach"]) - mach).abs() < 1e-12);
4555            let ours = probe_part_pressure_drag(ogive, nose, mach, base_area_m2);
4556            assert!((ours - ours_pin).abs() < 5e-6, "hpr at Mach {mach}: {ours}");
4557            let theirs = column(&ogive_rows[at]);
4558            assert!(
4559                (theirs - ogive_pin).abs() < 5e-6,
4560                "OpenRocket at Mach {mach}: {theirs}"
4561            );
4562            let theirs_cone = column(&cone_rows[at]);
4563            assert!(
4564                (theirs_cone - cone_pin).abs() < 5e-6,
4565                "OpenRocket's cone at Mach {mach}: {theirs_cone}"
4566            );
4567        }
4568    }
4569}