Skip to main content

hpr_sim/
recovery.rs

1//! Recovery devices: what opens, when it opens, and the drag area it presents.
2//!
3//! A [`Device`] is a drag area ([`DeviceDrag`]) with a [`Trigger`], a lag from the trigger to line
4//! stretch, and an [`Inflation`] law. A flight carries a list of them ([`crate::Simulation`]); the
5//! first one to open starts the descent phase ([`crate::Phase::Descent`]), where the rocket flies
6//! as a point mass under the sum of the open devices' drag areas (`docs/physics/recovery.md`).
7//!
8//! Streamers and tumbling bodies are drag areas too, from their own sources
9//! ([`StreamerModel`], [`DeviceDrag::tumbling`]).
10//!
11//! Canopy data comes from T. W. Knacke, *Parachute Recovery Systems Design Manual*, NWC TP 6575
12//! (1991): drag coefficients on the nominal area `S₀` from Tables 5-1 and 5-2, canopy fill
13//! constants from Table 5-6, the drag-area growth exponents of Pflanz's method (Figure 5-51) and
14//! the infinite-mass opening-force coefficients `C_x` from the same tables. Every number is cited
15//! at its accessor, with the printed page.
16
17use hpr_core::DVec3;
18use serde::{Deserialize, Serialize};
19
20use crate::error::SimError;
21
22/// The smallest aspect ratio `l/w` a streamer may have. A strip wider than it is long is not a
23/// streamer, and both correlations run away there: Carruthers and Filippone's `C_D → ∞` as
24/// `AR → 0`, and appendix C notes its own form "obtains maximum drag for a fixed surface area at
25/// the limit `l → 0`, `w → ∞`" (printed page 117).
26pub const MIN_STREAMER_ASPECT_RATIO: f64 = 1.0;
27
28/// The largest `C_D0` a canopy may be given. Knacke's printed values run from 0.30 to 0.96 on the
29/// nominal area; anything above this is a drag area mistaken for a coefficient.
30const MAX_CANOPY_DRAG_COEFFICIENT: f64 = 2.0;
31
32/// A canopy type with printed data in Knacke's tables.
33///
34/// Solid textile canopies come from Table 5-1 (printed page 5-3), slotted ones from Table 5-2
35/// (5-4).
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38#[non_exhaustive]
39pub enum CanopyType {
40    /// Flat circular (solid textile).
41    FlatCircular,
42    /// Conical (solid textile).
43    Conical,
44    /// Biconical (solid textile).
45    Biconical,
46    /// Triconical or polyconical (solid textile).
47    Triconical,
48    /// Extended skirt, 10% flat (solid textile).
49    ExtendedSkirt10Flat,
50    /// Extended skirt, 14.3% full (solid textile).
51    ExtendedSkirt14Full,
52    /// Hemispherical (solid textile).
53    Hemispherical,
54    /// Annular (solid textile).
55    Annular,
56    /// Cross, or cruciform (solid textile).
57    Cross,
58    /// Flat (FIST) ribbon (slotted).
59    FlatRibbon,
60    /// Conical ribbon (slotted).
61    ConicalRibbon,
62    /// Ringslot (slotted).
63    Ringslot,
64    /// Ringsail (slotted).
65    Ringsail,
66}
67
68impl CanopyType {
69    /// Knacke's printed range of `C_D0`, the drag coefficient on the nominal area `S₀`
70    /// (Tables 5-1 and 5-2, printed pages 5-3 and 5-4).
71    #[must_use]
72    pub const fn drag_coefficient_range(self) -> (f64, f64) {
73        match self {
74            Self::FlatCircular => (0.75, 0.80),
75            Self::Conical => (0.75, 0.90),
76            Self::Biconical => (0.75, 0.92),
77            Self::Triconical => (0.80, 0.96),
78            Self::ExtendedSkirt10Flat => (0.78, 0.87),
79            Self::ExtendedSkirt14Full => (0.75, 0.90),
80            Self::Hemispherical => (0.62, 0.77),
81            Self::Annular => (0.85, 0.95),
82            Self::Cross => (0.60, 0.85),
83            Self::FlatRibbon => (0.45, 0.50),
84            Self::ConicalRibbon => (0.50, 0.55),
85            Self::Ringslot => (0.56, 0.65),
86            Self::Ringsail => (0.75, 0.85),
87        }
88    }
89
90    /// The middle of [`Self::drag_coefficient_range`], which is what HPR Sim uses when the user gives
91    /// no `C_D0`. Knacke prints a range for every type and no single value; the middle is HPR Sim's
92    /// choice, not his (the decision record on recovery, [ADR-012][adr-012]).
93    ///
94    /// [adr-012]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-012-recovery-drag-areas-triggers-inflation-and-the-descent-phase-2026-09-17
95    #[must_use]
96    pub const fn drag_coefficient(self) -> f64 {
97        let (low, high) = self.drag_coefficient_range();
98        0.5 * (low + high)
99    }
100
101    /// The canopy fill constant `n` of `t_f = n D₀/v` (Table 5-6, printed page 5-44, unreefed
102    /// column), where Knacke prints one. `None` where the table has no unreefed value for the
103    /// type, which for five of these is because it has no row there at all.
104    ///
105    /// Knacke's rows cover types, not every variant: the ribbon row serves both ribbon entries.
106    /// (The ringsail row prints 7 unreefed; its 7 to 8 is the reefed column.)
107    #[must_use]
108    pub const fn fill_constant(self) -> Option<f64> {
109        match self {
110            Self::FlatCircular => Some(8.0),
111            Self::ExtendedSkirt10Flat => Some(10.0),
112            Self::ExtendedSkirt14Full => Some(12.0),
113            Self::Cross => Some(11.7),
114            Self::FlatRibbon | Self::ConicalRibbon => Some(14.0),
115            Self::Ringslot => Some(14.0),
116            Self::Ringsail => Some(7.0),
117            Self::Conical
118            | Self::Biconical
119            | Self::Triconical
120            | Self::Hemispherical
121            | Self::Annular => None,
122        }
123    }
124
125    /// The drag-area growth exponent `j` of `(C_D S)(t) = (C_D S)₀ (t/t_f)^j`, for the types
126    /// Pflanz's method names (Figure 5-51, printed page 5-59): `j = 2` for solid cloth (flat
127    /// circular, conical, extended skirt, triconical) and `j = 1` for ribbon and ringslot.
128    /// `None` for the types he doesn't name, which need a measured exponent.
129    #[must_use]
130    pub const fn growth_exponent(self) -> Option<f64> {
131        match self {
132            Self::FlatCircular
133            | Self::Conical
134            | Self::Triconical
135            | Self::ExtendedSkirt10Flat
136            | Self::ExtendedSkirt14Full => Some(2.0),
137            Self::FlatRibbon | Self::ConicalRibbon | Self::Ringslot => Some(1.0),
138            Self::Biconical
139            | Self::Hemispherical
140            | Self::Annular
141            | Self::Cross
142            | Self::Ringsail => None,
143        }
144    }
145
146    /// The infinite-mass opening-force coefficient `C_x = F_x/F_c` (Tables 5-1 and 5-2; the cross
147    /// canopy's printed 1.1 to 1.2 is taken at its middle). HPR Sim reports it; it is not used in the
148    /// equations, which integrate the opening force instead.
149    #[must_use]
150    pub const fn opening_force_coefficient(self) -> f64 {
151        match self {
152            Self::FlatCircular => 1.7,
153            Self::Conical | Self::Biconical | Self::Triconical => 1.8,
154            Self::ExtendedSkirt10Flat | Self::ExtendedSkirt14Full | Self::Annular => 1.4,
155            Self::Hemispherical => 1.6,
156            Self::Cross => 1.15,
157            Self::FlatRibbon | Self::ConicalRibbon | Self::Ringslot => 1.05,
158            Self::Ringsail => 1.10,
159        }
160    }
161
162    /// Where the numbers come from, for reports.
163    #[must_use]
164    pub const fn source(self) -> &'static str {
165        "Knacke, Parachute Recovery Systems Design Manual, NWC TP 6575 (1991). Table 5-1 (solid \
166         textile canopies), Table 5-2 (slotted), Table 5-6 (fill constants) and Figure 5-51 \
167         (drag-area growth)"
168    }
169}
170
171/// How a streamer's drag area is estimated. A streamer of length `l` and width `w` has a
172/// planform (one-side) area `S = l w` and an aspect ratio `AR = l/w`.
173///
174/// The two models disagree by a factor of about four in drag area, so
175/// `docs/physics/recovery.md` sets out what each is fitted to and how each compares with the only
176/// free-drop data in hand (the decision record on streamer and tumble drag, [ADR-013][adr-013]).
177///
178/// [adr-013]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-013-streamer-and-tumble-drag-2026-09-17
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
180#[serde(rename_all = "snake_case")]
181#[non_exhaustive]
182pub enum StreamerModel {
183    /// A. C. Carruthers and A. Filippone, "Aerodynamic Drag of Streamers and Flags", *Journal of
184    /// Aircraft* 42(4), 2005, pp. 976-982, on the planform area, from wind-tunnel tests of cotton
185    /// streamers at `AR` 3.3 to 30 and 6 to 18.9 m/s. It fits one power curve per planform area:
186    ///
187    /// - `C_D = 0.561 AR^−0.480` at `S = 0.025 m²` (eq. 2; Figure 2's trend line reads
188    ///   `0.561 AR^−0.4795`),
189    /// - `C_D = 0.6514 AR^−0.6075` at `S = 0.05 m²` (the trend line on Figure 3, which the text
190    ///   does not repeat as an equation),
191    /// - `C_D = 0.405 AR^−0.494` at `S = 0.075 m²` (eq. 1; Figure 4 reads `0.4046 AR^−0.494`).
192    ///
193    /// HPR Sim interpolates between **neighboring** curves linearly in `ln S` and holds the end
194    /// curve outside the fitted range. That interpolation is HPR Sim's, not the paper's. All three
195    /// are needed because `C_D` is far from linear in `ln S`: at `AR = 3.3` the middle curve sits
196    /// 0.3% *below* the smallest area's rather than 63% of the way to the largest's, so blending
197    /// only the extremes reads 18% low there.
198    ///
199    /// The correlations are for streamers clamped at the luff; the paper measures more drag when
200    /// the luff is free, which is what a descending streamer has.
201    ///
202    /// This is the default: on the one free-drop measurement in hand that a flat correlation
203    /// should fit (Kidwell's unpleated streamer) it is 9% fast where [`Self::OpenRocket`] is 88%
204    /// fast. Both are fast on his pleated streamers, which neither models
205    /// (`docs/physics/recovery.md`).
206    #[default]
207    Filippone,
208    /// The OpenRocket technical documentation v13.05, Appendix C (printed pages 113-118):
209    /// `C_Dm = 0.034 ((ρ_m + 25 g/m²)/(105 g/m²)) ((l + 1 m)/l)` on the planform area, fitted to
210    /// wind-tunnel tests of model-rocket streamers (`w` 0.01 to 0.09 m, `l` 0.2 to 1.0 m, surface
211    /// density 10 to 80 g/m², 6 to 12 m/s), with a stated 12 to 27% error on an independent set.
212    ///
213    /// Use it to compare with OpenRocket. Against Kidwell's free drops it is low in drag area by
214    /// 4.2 times on his flat crêpe streamer and 7.8 times on his pleated Micafilm one, which is
215    /// 88% and 154% fast in descent rate (`docs/physics/recovery.md`).
216    OpenRocket,
217}
218
219impl StreamerModel {
220    /// Carruthers and Filippone's three fitted curves, as `(planform area m², coefficient,
221    /// exponent)` with `C_D = coefficient · AR^exponent`, in order of area.
222    const FILIPPONE_CURVES: [(f64, f64, f64); 3] = [
223        (0.025, 0.561, -0.480),
224        (0.05, 0.6514, -0.6075),
225        (0.075, 0.405, -0.494),
226    ];
227
228    /// The aspect ratios `AR = l/w` the correlations were fitted over. Outside it they only
229    /// extrapolate, and as `AR → 0` the power law runs away (`C_D → ∞`), which is why a flight
230    /// refuses a strip wider than it is long ([`MIN_STREAMER_ASPECT_RATIO`]).
231    pub const FILIPPONE_ASPECT_RATIO_RANGE: (f64, f64) = (3.3, 30.0);
232
233    /// The drag area `C_D S` of a streamer, m².
234    ///
235    /// `surface_density_kg_m2` is the fabric's, which only [`Self::OpenRocket`] uses. Outside the
236    /// ranges each correlation was fitted over this extrapolates; a flight refuses the shapes
237    /// that make it meaningless ([`crate::Simulation::with_recovery`]).
238    #[must_use]
239    pub fn drag_area_m2(self, length_m: f64, width_m: f64, surface_density_kg_m2: f64) -> f64 {
240        let planform_m2 = length_m * width_m;
241        match self {
242            Self::Filippone => {
243                let aspect_ratio = length_m / width_m;
244                let curve = |(_, coefficient, exponent): (f64, f64, f64)| {
245                    coefficient * aspect_ratio.powf(exponent)
246                };
247                let curves = Self::FILIPPONE_CURVES;
248                // Between two neighboring curves, linearly in `ln S`; outside, the end curve.
249                let coefficient = if planform_m2 <= curves[0].0 {
250                    curve(curves[0])
251                } else if planform_m2 >= curves[2].0 {
252                    curve(curves[2])
253                } else {
254                    let upper = usize::from(planform_m2 > curves[1].0) + 1;
255                    let (low_m2, high_m2) = (curves[upper - 1].0, curves[upper].0);
256                    let fraction = (planform_m2 / low_m2).ln() / (high_m2 / low_m2).ln();
257                    let (low, high) = (curve(curves[upper - 1]), curve(curves[upper]));
258                    low + fraction * (high - low)
259                };
260                coefficient * planform_m2
261            }
262            Self::OpenRocket => {
263                0.034
264                    * ((surface_density_kg_m2 + 0.025) / 0.105)
265                    * ((length_m + 1.0) / length_m)
266                    * planform_m2
267            }
268        }
269    }
270}
271
272/// What gives a device its drag area `C_D S`.
273#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
274#[serde(rename_all = "snake_case", deny_unknown_fields)]
275#[non_exhaustive]
276pub enum DeviceDrag {
277    /// A drag area given directly, m² (RocketPy's `cd_s`).
278    DragArea {
279        /// `C_D S`, m².
280        cd_s_m2: f64,
281    },
282    /// A streamer: a strip of fabric `length_m` by `width_m`, whose drag area comes from
283    /// `model` ([`StreamerModel`]).
284    Streamer {
285        /// Its length `l`, m.
286        length_m: f64,
287        /// Its width `w`, m.
288        width_m: f64,
289        /// The fabric's surface density, kg/m² ([`StreamerModel::OpenRocket`] uses it).
290        surface_density_kg_m2: f64,
291        /// Which correlation gives its drag area.
292        #[serde(default)]
293        model: StreamerModel,
294    },
295    /// A body descending broadside, tumbling, with no device open: the drag area of its body tubes
296    /// and fins. Build it with [`DeviceDrag::tumbling`], which computes it from the airframe.
297    Tumble {
298        /// The drag area `C_D S`, m².
299        drag_area_m2: f64,
300        /// The body's side profile area, m² (for reports; it and the fin area have to add up to
301        /// the drag area through the model's two coefficients, so a file that leaves one out is
302        /// refused by serde rather than silently defaulting to an inconsistent device).
303        body_profile_m2: f64,
304        /// The effective fin area, m² (for reports).
305        fin_area_m2: f64,
306    },
307    /// A canopy of nominal diameter `D₀` with `C_D0` on the nominal area `S₀ = π D₀²/4`
308    /// (Knacke's convention, printed page 5-2).
309    Canopy {
310        /// The nominal diameter `D₀`, m.
311        nominal_diameter_m: f64,
312        /// `C_D0` on `S₀`.
313        drag_coefficient: f64,
314        /// The canopy type, where it is one of Knacke's.
315        #[serde(default, skip_serializing_if = "Option::is_none")]
316        kind: Option<CanopyType>,
317    },
318}
319
320/// The drag coefficient of a tumbling body tube, on its side profile area (the OpenRocket
321/// technical documentation v13.05, §3.5, printed page 54: fitted to 22 m drop tests of five
322/// models, and half the 1.12 of a circular cylinder in crossflow, as expected of a cylinder
323/// falling at a random angle).
324pub const TUMBLE_BODY_DRAG_COEFFICIENT: f64 = 0.56;
325
326/// The drag coefficient of a tumbling fin set, on its effective fin area (the same source; it
327/// sits between a flat plate's 1.17 and an open hemispherical cup's 1.42, and the documentation
328/// says it is the less reliable of the two).
329pub const TUMBLE_FIN_DRAG_COEFFICIENT: f64 = 1.42;
330
331/// The effective fin area of a tumbling set is one fin's area times this factor, by fin count
332/// (the same source, Table 3.4, printed page 55, for 1 to 8 fins). It is a fit, not a model: it
333/// is not `n` times one fin, and it is not monotonic.
334pub const TUMBLE_FIN_EFFICIENCY: [f64; 8] = [0.50, 1.00, 1.50, 1.41, 1.81, 1.73, 1.90, 1.85];
335
336/// A body component's side profile area `∫ d dx`, m²: a tube's diameter times its length, and a
337/// nose cone's or transition's own profile integrated ([`hpr_design::revolve`]'s planform area).
338/// Other parts add no body profile (fins are counted apart).
339fn side_profile_m2(component: &hpr_design::PlacedComponent) -> Result<f64, SimError> {
340    let profile = match &component.part {
341        hpr_design::Part::BodyTube(tube) => {
342            return Ok(2.0 * tube.outer_radius_m * component.length_m);
343        }
344        hpr_design::Part::NoseCone(nose) => nose.profile()?,
345        hpr_design::Part::Transition(transition) => transition.profile()?,
346        _ => return Ok(0.0),
347    };
348    Ok(hpr_design::revolve(&profile, hpr_design::Wall::Filled {})?.planform_area_m2)
349}
350
351impl DeviceDrag {
352    /// The drag area of `assembly` tumbling: `C_D,f A_f + C_D,bt A_bt` (the OpenRocket technical
353    /// documentation v13.05, §3.5, eq. 3.98 and 3.99, printed pages 53 to 55).
354    ///
355    /// - `A_bt` is the body's side profile area, the integral of its outer diameter along the
356    ///   axis, `∫ d dx`, taken over each body component's own profile (a curved nose's or
357    ///   transition's by quadrature, [`hpr_design::revolve`]). Shoulders are inside the airframe
358    ///   and add nothing.
359    /// - `A_f` is, for each fin set, one fin's planform area times the efficiency factor for its
360    ///   fin count ([`TUMBLE_FIN_EFFICIENCY`]). Launch lugs and rail buttons add nothing, and an
361    ///   airframe with **tube fins** is refused: they are a large part of its broadside area and
362    ///   the model has no factor for them.
363    /// - A **pod**'s body components and fins count as the airframe's do, once per pod: the
364    ///   documentation's model has no term for them, and none for one part shading another.
365    ///
366    /// It sums **every** stage, so it is the whole stack tumbling. For a spent booster on its
367    /// own, which is what the documentation's model was written for, use
368    /// [`Self::tumbling_stages`] with that body's stages.
369    ///
370    /// The constants were fitted to 22 m drop tests of five models 44 to 103 mm across and 6.8 to
371    /// 160 g, descending at 5.0 to 6.6 m/s, and predict those terminal velocities within 3 to 14%.
372    /// Bodies much larger or faster than that are outside the fit: above a Reynolds number of
373    /// about 3e5 a cylinder's crossflow drag falls by roughly half (`docs/physics/recovery.md`).
374    ///
375    /// # Errors
376    ///
377    /// [`SimError::Design`] if a fin planform's area or a nose cone's or transition's profile can't
378    /// be computed, and [`SimError::Domain`] if the airframe presents no area at all, carries tube
379    /// fins, or has a fin set of more than the eight fins Table 3.4 covers.
380    pub fn tumbling(assembly: &hpr_design::Assembly) -> Result<Self, SimError> {
381        Self::tumbling_stages(
382            assembly,
383            (0, assembly.layout.stages.len().saturating_sub(1)),
384        )
385    }
386
387    /// The drag area of the stages `first..=last` of `assembly` tumbling on their own, which is
388    /// what a separated body does ([`Separation`]). [`Self::tumbling`] is this over every stage.
389    /// It covers whole stages only: for an ejected piece that is part of a stage
390    /// ([`crate::Ejection`]) use [`crate::Simulation::tumbling_piece`], which sums the piece's
391    /// own components.
392    ///
393    /// # Errors
394    ///
395    /// As [`Self::tumbling`].
396    pub fn tumbling_stages(
397        assembly: &hpr_design::Assembly,
398        (first, last): (usize, usize),
399    ) -> Result<Self, SimError> {
400        let stages = assembly.layout.stages.len();
401        if first > last || last >= stages {
402            return Err(SimError::Domain {
403                what: "stage range of a tumbling body (first must not pass last, and last must \
404                       be a stage of the design); the last given",
405                value: last as f64,
406            });
407        }
408        Self::tumbling_where(assembly, |_, component| {
409            (first..=last).contains(&component.stage)
410        })
411    }
412
413    /// The drag area of the components of `assembly` for which `member` (given each one's index
414    /// in the layout) is true, tumbling: the sum [`Self::tumbling`] describes, over them alone.
415    pub(crate) fn tumbling_where(
416        assembly: &hpr_design::Assembly,
417        member: impl Fn(usize, &hpr_design::PlacedComponent) -> bool,
418    ) -> Result<Self, SimError> {
419        let mut body_profile_m2 = 0.0;
420        let mut fin_area_m2 = 0.0;
421        for (index, component) in assembly.layout.components.iter().enumerate() {
422            if !member(index, component) {
423                continue;
424            }
425            // A part in a pod counts once per pod: each pod's body components and fins are
426            // broadside to the air as the airframe's are.
427            let copies = component.copies.len() as f64;
428            body_profile_m2 += copies * side_profile_m2(component)?;
429            if matches!(component.part, hpr_design::Part::TubeFinSet(_)) {
430                // Tube fins are a large part of such a rocket's broadside area and the model has
431                // no factor for them, so hpr refuses rather than crediting a bare tube's drag.
432                return Err(SimError::Domain {
433                    what: "tumbling an airframe with tube fins (the model covers body tubes and \
434                           fin sets only)",
435                    value: 0.0,
436                });
437            }
438            if let hpr_design::Part::FinSet(fins) = &component.part {
439                let count = fins.count as usize;
440                let efficiency =
441                    TUMBLE_FIN_EFFICIENCY
442                        .get(count.wrapping_sub(1))
443                        .ok_or(SimError::Domain {
444                            what: "number of fins in a tumbling set (the fitted efficiency factors \
445                               cover 1 to 8)",
446                            value: fins.count.into(),
447                        })?;
448                fin_area_m2 += copies * fins.planform.geometry()?.area_m2 * efficiency;
449            }
450        }
451        let drag_area_m2 = TUMBLE_FIN_DRAG_COEFFICIENT * fin_area_m2
452            + TUMBLE_BODY_DRAG_COEFFICIENT * body_profile_m2;
453        if !(drag_area_m2.is_finite() && drag_area_m2 > 0.0) {
454            return Err(SimError::Domain {
455                what: "drag area of the tumbling airframe, m²",
456                value: drag_area_m2,
457            });
458        }
459        Ok(Self::Tumble {
460            drag_area_m2,
461            body_profile_m2,
462            fin_area_m2,
463        })
464    }
465
466    /// A streamer `length_m` by `width_m` of a fabric of `surface_density_kg_m2`, by the default
467    /// model ([`StreamerModel::Filippone`]).
468    #[must_use]
469    pub const fn streamer(length_m: f64, width_m: f64, surface_density_kg_m2: f64) -> Self {
470        Self::Streamer {
471            length_m,
472            width_m,
473            surface_density_kg_m2,
474            model: StreamerModel::Filippone,
475        }
476    }
477
478    /// A canopy of `nominal_diameter_m` with its type's default `C_D0`
479    /// ([`CanopyType::drag_coefficient`]).
480    #[must_use]
481    pub const fn canopy(kind: CanopyType, nominal_diameter_m: f64) -> Self {
482        Self::Canopy {
483            nominal_diameter_m,
484            drag_coefficient: kind.drag_coefficient(),
485            kind: Some(kind),
486        }
487    }
488
489    /// The fully open drag area `C_D S`, m².
490    #[must_use]
491    pub fn drag_area_m2(&self) -> f64 {
492        match *self {
493            Self::DragArea { cd_s_m2 } => cd_s_m2,
494            Self::Streamer {
495                length_m,
496                width_m,
497                surface_density_kg_m2,
498                model,
499            } => model.drag_area_m2(length_m, width_m, surface_density_kg_m2),
500            Self::Tumble { drag_area_m2, .. } => drag_area_m2,
501            Self::Canopy {
502                nominal_diameter_m,
503                drag_coefficient,
504                ..
505            } => {
506                drag_coefficient * std::f64::consts::PI * nominal_diameter_m * nominal_diameter_m
507                    / 4.0
508            }
509        }
510    }
511
512    /// The nominal diameter `D₀`, m, where the device has one.
513    #[must_use]
514    pub const fn nominal_diameter_m(&self) -> Option<f64> {
515        match *self {
516            Self::DragArea { .. } | Self::Streamer { .. } | Self::Tumble { .. } => None,
517            Self::Canopy {
518                nominal_diameter_m, ..
519            } => Some(nominal_diameter_m),
520        }
521    }
522
523    /// The canopy type, where the device has one.
524    #[must_use]
525    pub const fn canopy_type(&self) -> Option<CanopyType> {
526        match *self {
527            Self::DragArea { .. } | Self::Streamer { .. } | Self::Tumble { .. } => None,
528            Self::Canopy { kind, .. } => kind,
529        }
530    }
531}
532
533/// When a device's charge fires.
534#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
535#[serde(rename_all = "snake_case")]
536#[non_exhaustive]
537pub enum Trigger {
538    /// At apogee.
539    Apogee,
540    /// The first time from apogee that the center of mass is at or below this height above the
541    /// launch site, m: an altimeter's main setting. A rocket whose apogee is already below it
542    /// fires at apogee.
543    Altitude {
544        /// The height above the launch site, m.
545        height_above_ground_m: f64,
546    },
547    /// At a time after launch, s. Charges are checked in free flight and during the descent, so a
548    /// time that passes on the pad or the rail fires at rail exit.
549    Time {
550        /// The time after launch, s.
551        time_s: f64,
552    },
553    /// A motor's ejection delay after that motor's burnout. The motor is its index in
554    /// [`hpr_design::Assembly::motors`], and it must have a [`hpr_motor::Delay::Seconds`] delay.
555    /// As [`Self::Time`], a delay that expires before the rail exit fires there. A motor that
556    /// never lights never fires it, so on a cluster with a motor out
557    /// ([`hpr_design::MountedMotor::failed_tubes`]) name a tube that lights.
558    MotorDelay {
559        /// The motor's index.
560        motor: usize,
561    },
562    /// A delay after a motor's burnout, whatever its ejection delay: a stage separation timed
563    /// from the booster's burnout. The motor is its index in [`hpr_design::Assembly::motors`].
564    /// As [`Self::MotorDelay`], it fires no earlier than the rail exit, and never if the motor
565    /// never lights.
566    Burnout {
567        /// The motor's index.
568        motor: usize,
569        /// The delay after its burnout, s.
570        delay_s: f64,
571    },
572}
573
574impl Trigger {
575    /// When it fires on a flight of `assembly`, if that is known before the flight: a
576    /// [`Self::Time`], or a delay after the burnout of a motor `assembly` lights at a known time
577    /// (one lit by a separation has none yet). `None` for [`Self::Apogee`] and
578    /// [`Self::Altitude`], which the flight watches for. A time that passes on the pad or the
579    /// rail fires at the rail exit in flight, which this does not know.
580    ///
581    /// # Errors
582    ///
583    /// [`SimError::Domain`] as the flight refuses the trigger: a time before launch, a motor that
584    /// isn't there, a [`Self::MotorDelay`] on a motor with no ejection delay in seconds, or a
585    /// delay that is negative or not finite.
586    pub fn known_time_s(self, assembly: &hpr_design::Assembly) -> Result<Option<f64>, SimError> {
587        trigger_time_s(self, &assembly.motors, &assembly.ignition_times_s(|_| None))
588    }
589}
590
591/// How a device's drag area grows once it is deployed.
592///
593/// Knacke's measurements (Figure 5-40, printed page 5-47) overshoot the steady drag area by 10 to
594/// 80% near the end of filling. These laws don't: they rise to the steady value and stay there.
595#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
596#[serde(rename_all = "snake_case")]
597#[non_exhaustive]
598pub enum Inflation {
599    /// The full drag area from the moment the device deploys.
600    Instant,
601    /// `(C_D S)(t) = (C_D S)₀ (t/t_f)^j` over a filling time `t_f` fixed in advance.
602    FillingTime {
603        /// The filling time `t_f`, s.
604        time_s: f64,
605        /// The growth exponent `j` (Pflanz: 1 for ribbon and ringslot, 2 for solid cloth).
606        exponent: f64,
607    },
608    /// The same growth law with Knacke's filling time `t_f = n D₀/v` (printed page 5-43), where
609    /// `v` is the airspeed at deployment and `n` the canopy fill constant. Needs a device with a
610    /// nominal diameter.
611    ///
612    /// Knacke states this linear form "gives satisfactory results in the medium-velocity range of
613    /// about 150 to 500 ft/s" (45.7 to 152.4 m/s, printed page 5-44). A hobby main opening at 20
614    /// to 30 m/s is below that range, and his alternative there
615    /// (`t_f = n D₀/v^0.85`, `n = 4.0` for solid flat circular canopies) is dimensional, so it
616    /// cannot be used in SI as printed. [`Inflation::FILL_CONSTANT_RANGE_M_S`] holds the range,
617    /// and `docs/physics/recovery.md` says what using it outside costs.
618    FillConstant {
619        /// The fill constant `n` (Table 5-6).
620        constant: f64,
621        /// The growth exponent `j`.
622        exponent: f64,
623    },
624}
625
626impl Inflation {
627    /// The airspeeds at line stretch where Knacke's linear filling time `t_f = n D₀/v` is stated
628    /// to hold, m/s (150 to 500 ft/s, printed page 5-44).
629    pub const FILL_CONSTANT_RANGE_M_S: (f64, f64) = (45.72, 152.4);
630
631    /// Knacke's filling time and growth exponent for `kind`, where his tables print both.
632    #[must_use]
633    pub const fn knacke(kind: CanopyType) -> Option<Self> {
634        match (kind.fill_constant(), kind.growth_exponent()) {
635            (Some(constant), Some(exponent)) => Some(Self::FillConstant { constant, exponent }),
636            _ => None,
637        }
638    }
639
640    /// The filling time, s, for a device of nominal diameter `diameter_m` deployed at airspeed
641    /// `airspeed_m_s`. Zero means the drag area appears at once.
642    fn filling_time_s(&self, diameter_m: Option<f64>, airspeed_m_s: f64) -> f64 {
643        match *self {
644            Self::Instant => 0.0,
645            Self::FillingTime { time_s, .. } => time_s,
646            Self::FillConstant { constant, .. } => match diameter_m {
647                // A deployment at rest has no filling time: there is no flow to fill the canopy,
648                // and `n D₀/v` diverges. The canopy opens as the rocket picks up speed instead.
649                Some(diameter_m) if airspeed_m_s > 0.0 => constant * diameter_m / airspeed_m_s,
650                _ => 0.0,
651            },
652        }
653    }
654
655    /// The growth exponent `j`.
656    const fn exponent(&self) -> f64 {
657        match *self {
658            Self::Instant => 1.0,
659            Self::FillingTime { exponent, .. } | Self::FillConstant { exponent, .. } => exponent,
660        }
661    }
662}
663
664/// A recovery device: a drag area, when it opens, and how it fills.
665///
666/// Build one with [`Device::new`] and the builders: the struct is `#[non_exhaustive]` so that
667/// streamers ([M1.7b][m1-7b]) and separation ([M1.7c][m1-7c]) can add fields without breaking
668/// callers.
669///
670/// [m1-7b]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-7b
671/// [m1-7c]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-7c
672#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
673#[serde(deny_unknown_fields)]
674#[non_exhaustive]
675pub struct Device {
676    /// A name for reports.
677    pub name: String,
678    /// What gives it its drag area.
679    pub drag: DeviceDrag,
680    /// When its charge fires.
681    pub trigger: Trigger,
682    /// Seconds from the trigger to line stretch, when the canopy starts to fill (RocketPy's
683    /// `lag`).
684    #[serde(default)]
685    pub lag_s: f64,
686    /// How its drag area grows from line stretch.
687    #[serde(default = "instant")]
688    pub inflation: Inflation,
689    /// The device whose opening releases this one, by its index in the flight's list: a drogue cut
690    /// away once the main is fully open. A device released before its own charge fires never
691    /// deploys.
692    #[serde(default, skip_serializing_if = "Option::is_none")]
693    pub released_by: Option<usize>,
694    /// Which body it is attached to, after a separation ([`Separation`]) or an ejection
695    /// ([`crate::Ejection`]): body 0 keeps the nose, body 1 is the separation's aft stages, and each
696    /// ejection's piece the next number, in the order given, so with no separation the first
697    /// ejection makes body 1. Without either there is only body 0.
698    #[serde(default)]
699    pub body: usize,
700}
701
702fn instant() -> Inflation {
703    Inflation::Instant
704}
705
706impl Device {
707    /// A device with no lag, opening at once and never released.
708    #[must_use]
709    pub fn new(name: impl Into<String>, drag: DeviceDrag, trigger: Trigger) -> Self {
710        Self {
711            name: name.into(),
712            drag,
713            trigger,
714            lag_s: 0.0,
715            inflation: Inflation::Instant,
716            released_by: None,
717            body: 0,
718        }
719    }
720
721    /// The same device with `lag_s` seconds from the trigger to line stretch.
722    #[must_use]
723    pub fn with_lag_s(mut self, lag_s: f64) -> Self {
724        self.lag_s = lag_s;
725        self
726    }
727
728    /// The same device with an inflation law.
729    #[must_use]
730    pub fn with_inflation(mut self, inflation: Inflation) -> Self {
731        self.inflation = inflation;
732        self
733    }
734
735    /// The same device, released when device `index` is fully open.
736    #[must_use]
737    pub fn with_release_by(mut self, index: usize) -> Self {
738        self.released_by = Some(index);
739        self
740    }
741
742    /// The same device, carried by body `index` after a separation ([`Separation`]) or an
743    /// ejection ([`crate::Ejection`]); [`Self::body`] has the numbering. It acts only once that
744    /// body flies on its own.
745    #[must_use]
746    pub fn on_body(mut self, index: usize) -> Self {
747        self.body = index;
748        self
749    }
750
751    /// Checks the device's numbers.
752    fn validate(&self, count: usize, index: usize) -> Result<(), SimError> {
753        match self.drag {
754            DeviceDrag::Streamer {
755                length_m,
756                width_m,
757                surface_density_kg_m2,
758                model,
759            } => {
760                for (what, value) in [
761                    ("streamer length, m", length_m),
762                    ("streamer width, m", width_m),
763                ] {
764                    if !(value.is_finite() && value > 0.0) {
765                        return Err(SimError::Domain { what, value });
766                    }
767                }
768                if !(surface_density_kg_m2.is_finite() && surface_density_kg_m2 >= 0.0) {
769                    return Err(SimError::Domain {
770                        what: "streamer fabric surface density, kg/m²",
771                        value: surface_density_kg_m2,
772                    });
773                }
774                // A strip wider than it is long is not a streamer, and both correlations run
775                // away there. Above the fitted range they only extrapolate, which is allowed.
776                let _ = model;
777                if length_m / width_m < MIN_STREAMER_ASPECT_RATIO {
778                    return Err(SimError::Domain {
779                        what: "streamer aspect ratio, length over width (Carruthers and \
780                               Filippone fit 3.3 to 30, and both correlations are meaningless \
781                               below 1)",
782                        value: length_m / width_m,
783                    });
784                }
785            }
786            DeviceDrag::Tumble {
787                drag_area_m2,
788                body_profile_m2,
789                fin_area_m2,
790            } => {
791                for (what, value) in [
792                    ("tumbling body side profile area, m²", body_profile_m2),
793                    ("tumbling effective fin area, m²", fin_area_m2),
794                ] {
795                    if !(value.is_finite() && value >= 0.0) {
796                        return Err(SimError::Domain { what, value });
797                    }
798                }
799                let parts = TUMBLE_FIN_DRAG_COEFFICIENT * fin_area_m2
800                    + TUMBLE_BODY_DRAG_COEFFICIENT * body_profile_m2;
801                if (drag_area_m2 - parts).abs() > 1e-9 * drag_area_m2.abs().max(1.0) {
802                    return Err(SimError::Domain {
803                        what: "tumbling drag area against its body and fin areas (build one with \
804                               DeviceDrag::tumbling)",
805                        value: drag_area_m2,
806                    });
807                }
808            }
809            DeviceDrag::DragArea { .. } | DeviceDrag::Canopy { .. } => {}
810        }
811        if let DeviceDrag::Canopy {
812            drag_coefficient, ..
813        } = self.drag
814            // Knacke's tables run from 0.30 (hemisflo ribbon) to 0.96 (triconical) on the nominal
815            // area. The bound is loose enough for a coefficient measured on another reference
816            // area, and tight enough to catch a drag area passed as a coefficient.
817            && !(drag_coefficient.is_finite()
818                && drag_coefficient > 0.0
819                && drag_coefficient <= MAX_CANOPY_DRAG_COEFFICIENT)
820        {
821            return Err(SimError::Domain {
822                what: "canopy drag coefficient on the nominal area (0 to 2]",
823                value: drag_coefficient,
824            });
825        }
826        let area = self.drag.drag_area_m2();
827        if !(area.is_finite() && area > 0.0) {
828            return Err(SimError::Domain {
829                what: "recovery device drag area, m²",
830                value: area,
831            });
832        }
833        if let Some(diameter) = self.drag.nominal_diameter_m()
834            && !(diameter.is_finite() && diameter > 0.0)
835        {
836            return Err(SimError::Domain {
837                what: "canopy nominal diameter, m",
838                value: diameter,
839            });
840        }
841        if !(self.lag_s.is_finite() && self.lag_s >= 0.0) {
842            return Err(SimError::Domain {
843                what: "recovery device lag, s",
844                value: self.lag_s,
845            });
846        }
847        match self.inflation {
848            Inflation::Instant => {}
849            Inflation::FillingTime { time_s, exponent } => {
850                if !(time_s.is_finite() && time_s >= 0.0) {
851                    return Err(SimError::Domain {
852                        what: "canopy filling time, s",
853                        value: time_s,
854                    });
855                }
856                check_exponent(exponent)?;
857            }
858            Inflation::FillConstant { constant, exponent } => {
859                if !(constant.is_finite() && constant > 0.0) {
860                    return Err(SimError::Domain {
861                        what: "canopy fill constant",
862                        value: constant,
863                    });
864                }
865                if self.drag.nominal_diameter_m().is_none() {
866                    return Err(SimError::Domain {
867                        what: "canopy fill constant without a nominal diameter (give a canopy, \
868                               or a filling time)",
869                        value: constant,
870                    });
871                }
872                check_exponent(exponent)?;
873            }
874        }
875        match self.trigger {
876            Trigger::Apogee | Trigger::MotorDelay { .. } | Trigger::Burnout { .. } => {}
877            Trigger::Altitude {
878                height_above_ground_m,
879            } => {
880                if !(height_above_ground_m.is_finite() && height_above_ground_m > 0.0) {
881                    return Err(SimError::Domain {
882                        what: "deployment height above the launch site, m",
883                        value: height_above_ground_m,
884                    });
885                }
886            }
887            Trigger::Time { time_s } => {
888                if !(time_s.is_finite() && time_s >= 0.0) {
889                    return Err(SimError::Domain {
890                        what: "deployment time after launch, s",
891                        value: time_s,
892                    });
893                }
894            }
895        }
896        if let Some(other) = self.released_by
897            && (other >= count || other == index)
898        {
899            return Err(SimError::Domain {
900                what: "index of the device that releases this one",
901                value: other as f64,
902            });
903        }
904        Ok(())
905    }
906}
907
908fn check_exponent(exponent: f64) -> Result<(), SimError> {
909    if exponent.is_finite() && exponent > 0.0 {
910        Ok(())
911    } else {
912        Err(SimError::Domain {
913            what: "canopy drag-area growth exponent",
914            value: exponent,
915        })
916    }
917}
918
919/// A separation: the stack comes apart at a stage boundary and every body descends under its own
920/// devices (`docs/physics/recovery.md`, and the decision record on separation, [ADR-014][adr-014]).
921///
922/// Bodies are contiguous runs of stages. Stages `0..=after_stage` keep the nose and are body 0;
923/// the stages aft of the split are body 1. Each body flies as a point mass from the separation,
924/// with the mass properties of its own stages and motors, so every body must carry at least one
925/// device: the descent phase has no airframe drag (the decision record on recovery,
926/// [ADR-012][adr-012]), and a body with nothing open would fall as if in a vacuum.
927///
928/// A separation is an ideal one: no impulse, so each body leaves with the velocity its own center
929/// of mass already had. The aft body's motors must have burned out by then, because a body's
930/// mass is taken as constant through its descent, unless the separation may drop one burning
931/// ([`Separation::drops_burning`]). When the nose's body still has a motor to burn,
932/// it is a sustainer: it flies on as a rigid body on its own stages' aerodynamics, and only the aft
933/// body descends as a point mass (the decision record on staging, [ADR-074][adr-074]).
934///
935/// [adr-012]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-012-recovery-drag-areas-triggers-inflation-and-the-descent-phase-2026-09-17
936/// [adr-014]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-014-separation-bodies-their-masses-and-their-descents-2026-09-17
937/// [adr-074]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-074-ignition-times-and-powered-staging-the-sustainer-flies-on-as-a-rigid-body-2026-09-25
938#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
939#[serde(deny_unknown_fields)]
940pub struct Separation {
941    /// When the stack comes apart.
942    pub trigger: Trigger,
943    /// The last stage that stays with the nose. Stages after it form the aft body.
944    pub after_stage: usize,
945    /// Whether, when it is powered ([`Self::powered_at`]), it may drop a motor that still burns,
946    /// as OpenRocket's first burnout of a stage drops the stage's other motors (the decision
947    /// record on a stage's first burnout, [ADR-172](https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0172-a-stage-s-first-burnout.md)). The dropped body's descent is a point
948    /// mass with no thrust, so it leaves out the impulse that motor had left
949    /// ([`BodyFlight::impulse_left_n_s`]). Off by default: then the aft body's motors must have
950    /// burned out by the separation. A motor still to light is refused either way, and so is any
951    /// in an unpowered separation's aft body.
952    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
953    pub drops_burning: bool,
954}
955
956impl Separation {
957    /// A separation at the boundary after `after_stage`, on `trigger`.
958    #[must_use]
959    pub const fn new(trigger: Trigger, after_stage: usize) -> Self {
960        Self {
961            trigger,
962            after_stage,
963            drops_burning: false,
964        }
965    }
966
967    /// The same separation, let drop a motor that still burns when it is powered
968    /// ([`Self::drops_burning`]).
969    #[must_use]
970    pub const fn dropping_burning(mut self) -> Self {
971        self.drops_burning = true;
972        self
973    }
974
975    /// The stages of body `index`: body 0 keeps the nose, body 1 is the rest. `None` when there
976    /// is no such body, including when the boundary is at or past the last stage.
977    #[must_use]
978    pub const fn stages_of(&self, index: usize, stage_count: usize) -> Option<(usize, usize)> {
979        let Some(aft) = self.after_stage.checked_add(1) else {
980            return None;
981        };
982        if aft >= stage_count {
983            return None;
984        }
985        match index {
986            0 => Some((0, self.after_stage)),
987            1 => Some((aft, stage_count - 1)),
988            _ => None,
989        }
990    }
991
992    /// Whether it is powered when it fires at `time_s`, as the flight decides for the first
993    /// separation it flies: a motor of the nose's body (stages `0..=after_stage`) burns then, or
994    /// lights later at a known time, counting one this separation lights. A powered separation's
995    /// nose body flies on as a rigid body on its own stages' aerodynamics (the decision record on
996    /// staging, [ADR-074][adr-074]); an unpowered one's descends as a point mass with only its
997    /// devices' drag, as every body does (the decision record on separation, [ADR-014][adr-014]).
998    ///
999    /// [adr-014]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-014-separation-bodies-their-masses-and-their-descents-2026-09-17
1000    /// [adr-074]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-074-ignition-times-and-powered-staging-the-sustainer-flies-on-as-a-rigid-body-2026-09-25
1001    #[must_use]
1002    pub fn powered_at(&self, assembly: &hpr_design::Assembly, time_s: f64) -> bool {
1003        let lit = assembly.ignition_times_s(|stage| (stage == self.after_stage).then_some(time_s));
1004        assembly.motors.iter().zip(&lit).any(|(placed, ignition)| {
1005            placed.stage <= self.after_stage
1006                && ignition.is_some_and(|ignition| {
1007                    ignition + placed.mounted.motor.burnout_time_s() > time_s
1008                })
1009        })
1010    }
1011
1012    /// How many bodies it makes: two.
1013    pub const BODIES: usize = 2;
1014
1015    /// The body stage `stage` rides once every one of `separations` (in the order they fire, as
1016    /// [`crate::Simulation::with_separations`] takes them) has fired: body `k + 1` for the first
1017    /// separation `k` it is aft of, the part that separation drops; body 0, the nose's, for a
1018    /// stage aft of none.
1019    #[must_use]
1020    pub fn body_of(separations: &[Self], stage: usize) -> usize {
1021        separations
1022            .iter()
1023            .position(|separation| stage > separation.after_stage)
1024            .map_or(0, |k| k + 1)
1025    }
1026
1027    /// The stages of body `body` once every one of `separations` has fired, in a design of
1028    /// `stage_count` stages: body 0 keeps the nose, and body `k + 1` is the stages separation `k`
1029    /// drops, from its boundary back to the one behind it (or the tail). `None` when there is no
1030    /// such body, including when a boundary is at or past the last stage, or the boundaries don't
1031    /// move forward in the order given.
1032    #[must_use]
1033    pub fn stages_of_body(
1034        separations: &[Self],
1035        body: usize,
1036        stage_count: usize,
1037    ) -> Option<(usize, usize)> {
1038        let mut last = stage_count.checked_sub(1)?;
1039        for separation in separations {
1040            if separation.after_stage >= last {
1041                return None;
1042            }
1043            last = separation.after_stage;
1044        }
1045        match body {
1046            0 => Some((0, last)),
1047            _ => {
1048                let separation = separations.get(body - 1)?;
1049                let end = match body - 1 {
1050                    0 => stage_count - 1,
1051                    k => separations[k - 1].after_stage,
1052                };
1053                Some((separation.after_stage + 1, end))
1054            }
1055        }
1056    }
1057}
1058
1059/// The mass properties of the stages `first..=last` of `assembly`, with their motors, at flight
1060/// time `t_s`, each motor lit at its `ignition_s`. Summing over every stage gives
1061/// [`hpr_design::Assembly::mass_properties_lit`]. The flights sum pieces instead
1062/// (`crate::pieces`); the tests keep this as a reference that sums stages.
1063#[cfg(test)]
1064pub(crate) fn body_mass_properties(
1065    assembly: &hpr_design::Assembly,
1066    (first, last): (usize, usize),
1067    t_s: f64,
1068    ignition_s: &[Option<f64>],
1069) -> hpr_design::MassProperties {
1070    let mut parts = vec![];
1071    for (index, stage) in assembly.layout.stages.iter().enumerate() {
1072        if (first..=last).contains(&index) {
1073            parts.push(stage.mass);
1074        }
1075    }
1076    let motors: Vec<_> = assembly
1077        .motors
1078        .iter()
1079        .zip(ignition_s)
1080        .filter(|(motor, _)| (first..=last).contains(&motor.stage))
1081        .map(|(motor, ignition)| motor.mass_properties_lit(t_s, *ignition))
1082        .collect();
1083    parts.extend(motors);
1084    hpr_design::MassProperties::combine(parts.iter())
1085}
1086
1087/// The time a trigger fires, when it is one that is known before the flight: a time after
1088/// launch, or a delay after a motor's burnout, with the motors lit at `ignition_s`. A trigger on
1089/// a motor with no known ignition time has none either, and doesn't fire.
1090///
1091/// # Errors
1092///
1093/// [`SimError::Domain`] for a time before launch, a motor that isn't there, a motor with no
1094/// ejection delay in seconds, or a delay that is negative or not finite.
1095pub(crate) fn trigger_time_s(
1096    trigger: Trigger,
1097    motors: &[hpr_design::PlacedMotor],
1098    ignition_s: &[Option<f64>],
1099) -> Result<Option<f64>, SimError> {
1100    let burnout_s = |motor: usize| {
1101        ignition_s
1102            .get(motor)
1103            .copied()
1104            .flatten()
1105            .zip(motors.get(motor))
1106            .map(|(ignition_s, placed)| ignition_s + placed.mounted.motor.burnout_time_s())
1107    };
1108    match trigger {
1109        Trigger::Time { time_s } => {
1110            if !(time_s.is_finite() && time_s >= 0.0) {
1111                return Err(SimError::Domain {
1112                    what: "deployment time after launch, s",
1113                    value: time_s,
1114                });
1115            }
1116            Ok(Some(time_s))
1117        }
1118        Trigger::MotorDelay { motor } => {
1119            let placed = motors.get(motor).ok_or(SimError::Domain {
1120                what: "index of the motor whose delay fires a device",
1121                value: motor as f64,
1122            })?;
1123            let delay_s = match placed.mounted.delay {
1124                Some(hpr_motor::Delay::Seconds(delay_s)) => delay_s,
1125                _ => {
1126                    return Err(SimError::Domain {
1127                        what: "the motor firing a device has no ejection delay in seconds (it is \
1128                               plugged, or its delay is unset)",
1129                        value: motor as f64,
1130                    });
1131                }
1132            };
1133            if !(delay_s.is_finite() && delay_s >= 0.0) {
1134                return Err(SimError::Domain {
1135                    what: "motor ejection delay, s",
1136                    value: delay_s,
1137                });
1138            }
1139            Ok(burnout_s(motor).map(|t| t + delay_s))
1140        }
1141        Trigger::Burnout { motor, delay_s } => {
1142            if motor >= motors.len() {
1143                return Err(SimError::Domain {
1144                    what: "index of the motor whose burnout a trigger counts from",
1145                    value: motor as f64,
1146                });
1147            }
1148            if !(delay_s.is_finite() && delay_s >= 0.0) {
1149                return Err(SimError::Domain {
1150                    what: "delay after a motor's burnout, s",
1151                    value: delay_s,
1152                });
1153            }
1154            Ok(burnout_s(motor).map(|t| t + delay_s))
1155        }
1156        Trigger::Apogee | Trigger::Altitude { .. } => Ok(None),
1157    }
1158}
1159
1160/// Checks a flight's devices, and finds the trigger times that are known before it flies.
1161///
1162/// The result has one entry per device: `Some(t)` for a [`Trigger::Time`], and for a
1163/// [`Trigger::MotorDelay`] or [`Trigger::Burnout`] on a motor lit at a known time (of
1164/// `ignition_s`); `None` for the triggers the flight has to watch for, and for one on a motor that
1165/// hasn't a known ignition.
1166pub(crate) fn plan(
1167    devices: &[Device],
1168    motors: &[hpr_design::PlacedMotor],
1169    ignition_s: &[Option<f64>],
1170) -> Result<Vec<Option<f64>>, SimError> {
1171    // A device is cut away by a line on its own body; a release across a separation has nothing
1172    // to act through.
1173    for (index, device) in devices.iter().enumerate() {
1174        if let Some(other) = device.released_by
1175            && devices.get(other).is_some_and(|by| by.body != device.body)
1176        {
1177            return Err(SimError::Domain {
1178                what: "release across a separation (a device can only be released by one on its \
1179                       own body); index of the released device",
1180                value: index as f64,
1181            });
1182        }
1183    }
1184    // A cycle of releases (A released by B, B released by A) can leave every device released and
1185    // the rocket falling under nothing at all, which the descent phase would fly as a vacuum drop
1186    // (found in review). Each chain has to end.
1187    for start in 0..devices.len() {
1188        let mut at = start;
1189        for _ in 0..devices.len() {
1190            match devices[at].released_by {
1191                Some(next) if next < devices.len() => at = next,
1192                _ => break,
1193            }
1194            if at == start {
1195                return Err(SimError::Domain {
1196                    what: "recovery device releases run in a cycle, so every one of them could \
1197                           be released at once; index of a device in the cycle",
1198                    value: start as f64,
1199                });
1200            }
1201        }
1202    }
1203    let mut times = Vec::with_capacity(devices.len());
1204    for (index, device) in devices.iter().enumerate() {
1205        device.validate(devices.len(), index)?;
1206        let time = trigger_time_s(device.trigger, motors, ignition_s)?;
1207        times.push(time);
1208    }
1209    Ok(times)
1210}
1211
1212/// One device's progress through a flight.
1213#[derive(Debug, Clone, Copy, Default, PartialEq)]
1214pub(crate) struct DeviceRun {
1215    /// When its charge fired, s after launch.
1216    pub(crate) triggered_s: Option<f64>,
1217    /// When it will deploy (line stretch), s: the trigger plus the lag.
1218    pub(crate) deploy_s: Option<f64>,
1219    /// When it deployed (line stretch), s.
1220    pub(crate) deployed_s: Option<f64>,
1221    /// Its filling time, s, fixed at deployment.
1222    pub(crate) filling_time_s: f64,
1223    /// When it is released, s: the time the device that releases it is fully open.
1224    pub(crate) released_s: Option<f64>,
1225    /// Whether that release has been recorded.
1226    pub(crate) release_recorded: bool,
1227    /// Whether it was cut away before its own charge fired, so it never deploys.
1228    pub(crate) abandoned: bool,
1229}
1230
1231/// Every device's progress through one flight. The [`crate::Simulation`] is not mutated by a run
1232/// (Loft lesson L24), so this lives with the flight.
1233///
1234/// Every method here indexes `devices` by a device's position in the flight's list, which is the
1235/// invariant [`Run::new`] establishes: a run is built with one entry per device and is only ever
1236/// passed the same slice. Indexing therefore cannot be out of range, and a caller that broke that
1237/// (a future per-body run, M1.7b) would panic here rather than silently pull the wrong canopy.
1238#[derive(Debug, Clone, Default)]
1239pub(crate) struct Run {
1240    pub(crate) devices: Vec<DeviceRun>,
1241}
1242
1243impl Run {
1244    pub(crate) fn new(count: usize) -> Self {
1245        Self {
1246            devices: vec![DeviceRun::default(); count],
1247        }
1248    }
1249
1250    /// Fires device `index`'s charge at `t`, and returns when it will deploy.
1251    pub(crate) fn trigger(&mut self, devices: &[Device], index: usize, t: f64) -> f64 {
1252        let deploy_s = t + devices[index].lag_s;
1253        self.devices[index].triggered_s = Some(t);
1254        self.devices[index].deploy_s = Some(deploy_s);
1255        deploy_s
1256    }
1257
1258    /// Deploys device `index` at `t` with airspeed `airspeed_m_s`, schedules the release of
1259    /// whatever it releases for the moment its own canopy is full, and returns that time.
1260    pub(crate) fn deploy(
1261        &mut self,
1262        devices: &[Device],
1263        index: usize,
1264        t: f64,
1265        airspeed_m_s: f64,
1266    ) -> f64 {
1267        let device = &devices[index];
1268        let filling_time_s = device
1269            .inflation
1270            .filling_time_s(device.drag.nominal_diameter_m(), airspeed_m_s);
1271        self.devices[index].deployed_s = Some(t);
1272        self.devices[index].filling_time_s = filling_time_s;
1273        let full_s = t + filling_time_s;
1274        for (other, run) in devices.iter().zip(&mut self.devices) {
1275            if other.released_by == Some(index) && run.released_s.is_none() {
1276                run.released_s = Some(full_s);
1277            }
1278        }
1279        full_s
1280    }
1281
1282    /// Every time device `index` already has that a descent must not step past: its deployment,
1283    /// the end of its filling and its release.
1284    pub(crate) fn times_of(&self, index: usize) -> Vec<f64> {
1285        let run = self.devices[index];
1286        let mut times = Vec::new();
1287        times.extend(run.deploy_s);
1288        if let Some(deployed_s) = run.deployed_s {
1289            times.push(deployed_s + run.filling_time_s);
1290        }
1291        times.extend(run.released_s);
1292        times.retain(|time| time.is_finite());
1293        times
1294    }
1295
1296    /// When device `index` is released, s.
1297    pub(crate) fn released_s(&self, index: usize) -> Option<f64> {
1298        self.devices[index].released_s
1299    }
1300
1301    /// Whether a device among those for which `member` is true was open just before `t`: deployed
1302    /// before `t` and not released before it. That is something a body hangs from as it falls,
1303    /// any device but a tumble. So what happens at `t` itself, a deployment or a release, doesn't
1304    /// count yet, and the answer doesn't depend on how fast a device opening at `t` fills.
1305    pub(crate) fn hung_before(
1306        &self,
1307        devices: &[Device],
1308        member: impl Fn(usize) -> bool,
1309        t: f64,
1310    ) -> bool {
1311        devices.iter().enumerate().any(|(index, device)| {
1312            member(index)
1313                && !matches!(device.drag, DeviceDrag::Tumble { .. })
1314                && self.devices[index]
1315                    .deployed_s
1316                    .is_some_and(|deployed_s| deployed_s < t)
1317                && !self.devices[index]
1318                    .released_s
1319                    .is_some_and(|released_s| released_s < t)
1320        })
1321    }
1322
1323    /// Whether device `index`'s release has come and has not been recorded.
1324    pub(crate) fn release_due(&self, index: usize, t: f64) -> bool {
1325        let run = self.devices[index];
1326        !run.release_recorded && run.released_s.is_some_and(|released| t >= released)
1327    }
1328
1329    /// Marks device `index`'s release as recorded.
1330    pub(crate) fn release(&mut self, index: usize) {
1331        self.devices[index].release_recorded = true;
1332    }
1333
1334    /// Gives up on device `index`, which was cut away before its charge fired.
1335    pub(crate) fn abandon(&mut self, index: usize) {
1336        self.devices[index].abandoned = true;
1337    }
1338
1339    /// Whether device `index` has been triggered but has not deployed or been abandoned.
1340    pub(crate) fn waiting(&self, index: usize) -> bool {
1341        let run = self.devices[index];
1342        run.triggered_s.is_some() && run.deployed_s.is_none() && !run.abandoned
1343    }
1344
1345    /// When device `index` deploys, s: infinite until its charge fires.
1346    pub(crate) fn deploy_s(&self, index: usize) -> f64 {
1347        self.devices[index].deploy_s.unwrap_or(f64::INFINITY)
1348    }
1349
1350    /// Whether device `index` is still waiting for its trigger.
1351    pub(crate) fn pending(&self, index: usize) -> bool {
1352        self.devices[index].triggered_s.is_none()
1353    }
1354
1355    /// The total drag area of body `body`'s open devices at `t`, m².
1356    pub(crate) fn body_drag_area_m2(&self, devices: &[Device], body: usize, t: f64) -> f64 {
1357        devices
1358            .iter()
1359            .enumerate()
1360            .filter(|(_, device)| device.body == body)
1361            .map(|(index, _)| self.one_drag_area_m2(devices, index, t))
1362            .sum()
1363    }
1364
1365    /// The total drag area of the open devices at `t`, m².
1366    ///
1367    /// A device deployed at `t_d` with filling time `t_f` and growth exponent `j` contributes
1368    /// `(C_D S)₀ min(1, (t − t_d)/t_f)^j`, and nothing once it is released.
1369    pub(crate) fn drag_area_m2(&self, devices: &[Device], t: f64) -> f64 {
1370        (0..devices.len())
1371            .map(|index| self.one_drag_area_m2(devices, index, t))
1372            .sum()
1373    }
1374
1375    /// The drag area of device `index` at `t`, m²: nothing before it deploys or after it is
1376    /// released, and its inflation law in between.
1377    fn one_drag_area_m2(&self, devices: &[Device], index: usize, t: f64) -> f64 {
1378        let (device, run) = (&devices[index], self.devices[index]);
1379        let Some(deployed_s) = run.deployed_s else {
1380            return 0.0;
1381        };
1382        if run.released_s.is_some_and(|released| t >= released) {
1383            return 0.0;
1384        }
1385        let full = device.drag.drag_area_m2();
1386        let elapsed = t - deployed_s;
1387        if elapsed < 0.0 {
1388            return 0.0;
1389        }
1390        if run.filling_time_s <= 0.0 {
1391            return full;
1392        }
1393        let fraction = (elapsed / run.filling_time_s).min(1.0);
1394        // `j` is 1 (ribbon and ringslot) or 2 (solid cloth) for every canopy Knacke's method
1395        // names, so the common cases avoid `powf`.
1396        let growth = match device.inflation.exponent() {
1397            1.0 => fraction,
1398            2.0 => fraction * fraction,
1399            exponent => fraction.powf(exponent),
1400        };
1401        full * growth
1402    }
1403}
1404
1405/// One separated body at an instant of its descent.
1406#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1407pub struct BodySample {
1408    /// Time since launch, s.
1409    pub time_s: f64,
1410    /// Its center of mass in the launch frame, m.
1411    pub cg_enu_m: DVec3,
1412    /// That point's velocity relative to the launch frame, m/s.
1413    pub cg_velocity_enu_m_s: DVec3,
1414    /// Its center of mass's ellipsoidal height above the launch site, m.
1415    pub height_above_ground_m: f64,
1416    /// The rate of that height, m/s.
1417    pub vertical_speed_m_s: f64,
1418    /// Its airspeed, m/s.
1419    pub airspeed_m_s: f64,
1420    /// The drag area `C_D S` of its open devices, m².
1421    pub recovery_drag_area_m2: f64,
1422    /// Its mass, kg.
1423    pub mass_kg: f64,
1424}
1425
1426/// An event during a separated body's descent, with the body at that instant.
1427#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1428pub struct BodyEvent {
1429    /// What happened: a device's [`crate::EventKind::Trigger`], [`crate::EventKind::Deployment`],
1430    /// [`crate::EventKind::Release`], the body's [`crate::EventKind::Apogee`] or
1431    /// [`crate::EventKind::GroundHit`], or a piece leaving it at a
1432    /// [`crate::EventKind::Separation`] or [`crate::EventKind::Ejection`], whose sample has the
1433    /// body's mass from before the piece left.
1434    pub kind: crate::EventKind,
1435    /// The body at that instant.
1436    pub sample: BodySample,
1437    /// For a piece leaving it, the body just after: its mass without the piece, and its velocity
1438    /// once the ejections' impulses have pushed it ([`crate::Ejection::with_impulse`]). Partings
1439    /// at one instant share it: it is the body after all of them. `None` for every other event.
1440    #[serde(default, skip_serializing_if = "Option::is_none")]
1441    pub after: Option<BodySample>,
1442}
1443
1444/// One separated body's descent, from the moment it flies on its own to its landing.
1445#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1446pub struct BodyFlight {
1447    /// Which body: 0 keeps the nose. A body is numbered by its lead piece ([`crate::Ejection`]).
1448    pub body: usize,
1449    /// The first and last stage it has a component in when it lands.
1450    pub stages: (usize, usize),
1451    /// The pieces it lands with: its own, and any joined to it whose split never fired. Piece 0
1452    /// is the nose's, the separation makes piece 1, and each ejection the next.
1453    #[serde(default)]
1454    pub pieces: Vec<usize>,
1455    /// Its mass when it lands, kg. It is constant between splits, and steps down when a piece
1456    /// leaves it on the way down (an [`crate::EventKind::Ejection`] among its events).
1457    pub mass_kg: f64,
1458    /// Where it started flying on its own: at the airframe's first parting, its own center of mass
1459    /// and that point's velocity; at a later one, on the way down, the point and velocity of the
1460    /// body it left. Either way plus the pushes of the pushed ejections on its sides
1461    /// ([`crate::Ejection::with_impulse`]).
1462    pub start_sample: BodySample,
1463    /// Why its descent ended.
1464    pub termination: crate::Termination,
1465    /// Its events, in order.
1466    pub events: Vec<BodyEvent>,
1467    /// Where it ended.
1468    pub final_sample: BodySample,
1469    /// The integrator's work on it.
1470    pub stats: crate::Stats,
1471    /// The impulse its motors still had to give when it started flying on its own, N·s, which
1472    /// its descent leaves out: a point mass has no thrust. It is 0 but for a body a powered
1473    /// separation dropped with a motor still burning, as OpenRocket's first burnout of a stage
1474    /// drops its other motors ([ADR-172](https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0172-a-stage-s-first-burnout.md)). That thrust could have changed its speed by
1475    /// about this over its mass, a little more as the propellant left burns away.
1476    #[serde(default)]
1477    pub impulse_left_n_s: f64,
1478}
1479
1480impl BodyFlight {
1481    /// The first event of `kind`.
1482    #[must_use]
1483    pub fn event(&self, kind: crate::EventKind) -> Option<&BodyEvent> {
1484        self.events.iter().find(|event| event.kind == kind)
1485    }
1486}
1487
1488/// The equilibrium descent speed `v_e = √(2 m g/(ρ C_D S))`, m/s (Knacke, printed page 5-128).
1489///
1490/// It is the speed at which the drag area's drag balances the weight, so it is also the speed a
1491/// long descent settles at.
1492///
1493/// The formula is evaluated as written, with no domain checks: a zero drag area or density gives
1494/// infinity, and a negative mass, density, drag area or gravity gives NaN. Flights validate their
1495/// devices instead ([`crate::Simulation::with_recovery`]).
1496#[must_use]
1497pub fn terminal_speed_m_s(
1498    mass_kg: f64,
1499    drag_area_m2: f64,
1500    density_kg_m3: f64,
1501    gravity_m_s2: f64,
1502) -> f64 {
1503    (2.0 * mass_kg * gravity_m_s2 / (density_kg_m3 * drag_area_m2)).sqrt()
1504}
1505
1506#[cfg(test)]
1507mod tests {
1508    use std::f64::consts::PI;
1509
1510    use hpr_atmos::ConstantWind;
1511    use hpr_core::DVec3;
1512
1513    use super::*;
1514    use crate::environment::Environment;
1515    use crate::flight::{EventKind, FlightResult, FlightSettings, Simulation, Termination};
1516    use crate::rail::Rail;
1517    use crate::recorder::{Channel, Recorder};
1518    use crate::state::State;
1519    use crate::testing::{
1520        QuadraticDragFall, UniformAir, analytic_environment, analytic_wind_environment,
1521        closed_form_quadratic_drag, design, rotating_analytic_environment,
1522    };
1523
1524    const G: f64 = 9.806_65;
1525    /// Valetudo's motor burns out at 3.26 s; the descents start well after that.
1526    const START_S: f64 = 10.0;
1527
1528    /// Valetudo with `devices`, an hour's cap and a rail it never uses.
1529    fn flight(environment: Environment, devices: Vec<Device>, max_time_s: f64) -> Simulation {
1530        Simulation::new(
1531            &design("rocketpy-valetudo"),
1532            "example",
1533            environment,
1534            Rail::vertical(3.0),
1535            FlightSettings {
1536                max_time_s,
1537                ..FlightSettings::default()
1538            },
1539        )
1540        .unwrap()
1541        .with_recovery(devices)
1542        .unwrap()
1543    }
1544
1545    /// The same rocket with an ejection delay of `delay_s` on every motor of every configuration.
1546    fn with_delay(mut rocket: hpr_design::Rocket, delay_s: f64) -> hpr_design::Rocket {
1547        for configuration in &mut rocket.configurations {
1548            for motor in &mut configuration.motors {
1549                motor.delay = Some(hpr_motor::Delay::Seconds(delay_s));
1550            }
1551        }
1552        rocket
1553    }
1554
1555    /// A device open from the moment the descent starts.
1556    fn open_at_start(drag: DeviceDrag) -> Device {
1557        Device::new("test", drag, Trigger::Time { time_s: START_S })
1558    }
1559
1560    /// The state at rest (`velocity_enu_m_s`) with the center of mass `height_m` above the site,
1561    /// nose up.
1562    fn dropped(sim: &Simulation, height_m: f64, velocity_enu_m_s: DVec3) -> State {
1563        let attitude = Rail::vertical(3.0).attitude();
1564        let cg_m = sim.assembly().mass_properties(START_S).cg_m;
1565        State {
1566            position_enu_m: DVec3::new(0.0, 0.0, height_m) - attitude.mul_vec3(cg_m),
1567            velocity_enu_m_s,
1568            attitude,
1569            body_rate_rad_s: DVec3::ZERO,
1570        }
1571    }
1572
1573    /// The column `name` of every row.
1574    fn column(recorder: &Recorder, name: &str) -> Vec<f64> {
1575        let index = recorder
1576            .columns()
1577            .iter()
1578            .position(|c| c == name)
1579            .unwrap_or_else(|| panic!("no column {name}"));
1580        recorder.rows().iter().map(|row| row[index]).collect()
1581    }
1582
1583    /// The largest canopy drag force of a flight, N, over the event samples and the recorded
1584    /// steps: `q (C_D S)`.
1585    fn peak_load_n(result: &FlightResult, recorder: &Recorder) -> f64 {
1586        let from_events = result
1587            .events
1588            .iter()
1589            .map(|event| event.sample.dynamic_pressure_pa * event.sample.recovery_drag_area_m2);
1590        let pressure = column(recorder, "dynamic_pressure_pa");
1591        let area = column(recorder, "recovery_drag_area_m2");
1592        let from_rows = pressure.iter().zip(&area).map(|(q, s)| q * s);
1593        from_events.chain(from_rows).fold(0.0, f64::max)
1594    }
1595
1596    #[test]
1597    fn default_canopy_cd_carries_its_citation() {
1598        // Loft lesson L29. Loft's parachute C_D 0.8 was copied out of OpenRocket's GPL source.
1599        // hpr's default is the middle of Knacke's printed range for the type, on the nominal area
1600        // S₀ = π D₀²/4, and says where it comes from. RocketPy's 1.4 is not a C_D0 at all: it is a
1601        // hemispherical canopy's coefficient on the projected area, and Knacke's hemispherical
1602        // range on S₀ is 0.62 to 0.77.
1603        let flat = CanopyType::FlatCircular;
1604        assert_eq!(flat.drag_coefficient_range(), (0.75, 0.80));
1605        assert_eq!(flat.drag_coefficient(), 0.775);
1606        let (low, high) = flat.drag_coefficient_range();
1607        assert!(low <= flat.drag_coefficient() && flat.drag_coefficient() <= high);
1608        let source = flat.source();
1609        for cited in ["Knacke", "NWC TP 6575", "Table 5-1"] {
1610            assert!(source.contains(cited), "{source} does not cite {cited}");
1611        }
1612        assert_eq!(
1613            CanopyType::Hemispherical.drag_coefficient_range(),
1614            (0.62, 0.77)
1615        );
1616        assert!(CanopyType::Hemispherical.drag_coefficient() < 1.4);
1617        // The drag area is C_D0 on the nominal area, not on the projected area.
1618        let canopy = DeviceDrag::canopy(flat, 2.0);
1619        assert!((canopy.drag_area_m2() - 0.775 * PI).abs() < 1e-15);
1620        assert_eq!(canopy.nominal_diameter_m(), Some(2.0));
1621        assert_eq!(canopy.canopy_type(), Some(flat));
1622        // Knacke's tables as transcribed, entry by entry: the `C_D0` range (Tables 5-1 and 5-2),
1623        // the unreefed fill constant (Table 5-6, `None` where the table prints "insufficient
1624        // data"), the drag-area growth exponent (Pflanz, Figure 5-51, `None` for the types he
1625        // does not name) and the infinite-mass opening-force coefficient `C_x`. A typo in any of
1626        // these changes a user's descent rate, so they are pinned literally.
1627        let table = [
1628            (
1629                CanopyType::FlatCircular,
1630                0.75,
1631                0.80,
1632                Some(8.0),
1633                Some(2.0),
1634                1.7,
1635            ),
1636            (CanopyType::Conical, 0.75, 0.90, None, Some(2.0), 1.8),
1637            (CanopyType::Biconical, 0.75, 0.92, None, None, 1.8),
1638            (CanopyType::Triconical, 0.80, 0.96, None, Some(2.0), 1.8),
1639            (
1640                CanopyType::ExtendedSkirt10Flat,
1641                0.78,
1642                0.87,
1643                Some(10.0),
1644                Some(2.0),
1645                1.4,
1646            ),
1647            (
1648                CanopyType::ExtendedSkirt14Full,
1649                0.75,
1650                0.90,
1651                Some(12.0),
1652                Some(2.0),
1653                1.4,
1654            ),
1655            (CanopyType::Hemispherical, 0.62, 0.77, None, None, 1.6),
1656            (CanopyType::Annular, 0.85, 0.95, None, None, 1.4),
1657            (CanopyType::Cross, 0.60, 0.85, Some(11.7), None, 1.15),
1658            (
1659                CanopyType::FlatRibbon,
1660                0.45,
1661                0.50,
1662                Some(14.0),
1663                Some(1.0),
1664                1.05,
1665            ),
1666            (
1667                CanopyType::ConicalRibbon,
1668                0.50,
1669                0.55,
1670                Some(14.0),
1671                Some(1.0),
1672                1.05,
1673            ),
1674            (
1675                CanopyType::Ringslot,
1676                0.56,
1677                0.65,
1678                Some(14.0),
1679                Some(1.0),
1680                1.05,
1681            ),
1682            (CanopyType::Ringsail, 0.75, 0.85, Some(7.0), None, 1.10),
1683        ];
1684        for (kind, low, high, fill_constant, growth_exponent, opening) in table {
1685            assert_eq!(kind.drag_coefficient_range(), (low, high), "{kind:?}");
1686            assert_eq!(kind.drag_coefficient(), 0.5 * (low + high), "{kind:?}");
1687            assert_eq!(kind.fill_constant(), fill_constant, "{kind:?}");
1688            assert_eq!(kind.growth_exponent(), growth_exponent, "{kind:?}");
1689            assert_eq!(kind.opening_force_coefficient(), opening, "{kind:?}");
1690            assert!(
1691                source.contains("Knacke") && kind.source() == source,
1692                "{kind:?}"
1693            );
1694        }
1695
1696        assert_eq!(Inflation::knacke(CanopyType::Hemispherical), None);
1697        assert_eq!(
1698            Inflation::knacke(CanopyType::FlatCircular),
1699            Some(Inflation::FillConstant {
1700                constant: 8.0,
1701                exponent: 2.0
1702            })
1703        );
1704    }
1705
1706    #[test]
1707    fn descent_rate_equals_terminal_velocity() {
1708        // Loft lesson L92. Loft's own case, recomputed from Knacke's equilibrium descent speed
1709        // v_e = √(2 W/(ρ C_D0 S₀)) (printed page 5-128): 1.1 kg under a 1 m flat canopy of C_D 0.8
1710        // at ρ = 1.225 comes to 5.294 m/s. Loft allowed ±30% against it; hpr's formula has to
1711        // print it.
1712        let cd_s = 0.8 * PI * 1.0 * 1.0 / 4.0;
1713        let loft = terminal_speed_m_s(1.1, cd_s, 1.225, G);
1714        assert!((loft - 5.294).abs() < 5e-4, "{loft}");
1715
1716        // A flight under the same law: dropped from rest with the canopy already open, in uniform
1717        // air under constant gravity, the descent is the closed-form fall under quadratic drag,
1718        // v = −v_t tanh(g t/v_t), and it lands at the speed v_t that the formula gives.
1719        let air = UniformAir::sea_level();
1720        let rho = air.0.density_kg_m3;
1721        let device = open_at_start(DeviceDrag::canopy(CanopyType::FlatCircular, 1.5));
1722        let drag_area_m2 = device.drag.drag_area_m2();
1723        let sim = flight(analytic_environment(air, G), vec![device], 3600.0);
1724        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
1725        let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, rho, G);
1726        let height_m = 2_000.0;
1727        let closed = closed_form_quadratic_drag(
1728            &QuadraticDragFall {
1729                gravity_mps2: G,
1730                k_per_m: rho * drag_area_m2 / (2.0 * mass_kg),
1731            },
1732            0.0,
1733        );
1734        assert!((closed.apogee_s).abs() < 1e-15);
1735
1736        let mut recorder = Recorder::new(
1737            vec![
1738                Channel::Time,
1739                Channel::VerticalSpeed,
1740                Channel::HeightAboveGround,
1741            ],
1742            Some(5.0),
1743        )
1744        .unwrap();
1745        let result = sim
1746            .run_free(START_S, dropped(&sim, height_m, DVec3::ZERO), &mut recorder)
1747            .unwrap();
1748        assert_eq!(result.termination, Termination::GroundHit);
1749        assert_eq!(result.final_sample.phase, crate::Phase::Descent);
1750
1751        // The whole descent follows the closed form, and the impact speed is the terminal speed
1752        // (reached to 1e-9 of it after 2 km).
1753        let times = column(&recorder, "time_s");
1754        let speeds = column(&recorder, "vertical_speed_m_s");
1755        let mut worst: f64 = 0.0;
1756        for (t, v) in times.iter().zip(&speeds) {
1757            let expected = closed.state(t - START_S)[1];
1758            worst = worst.max((v - expected).abs() / terminal_m_s);
1759        }
1760        // Measured: 2.1e-8 of v_t, the integrator's own error at rtol = atol = 1e-8.
1761        assert!(worst < 1e-7, "{worst} of v_t");
1762        let landing = result.event(EventKind::GroundHit).unwrap().sample;
1763        assert!(
1764            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-7,
1765            "{} vs {terminal_m_s}",
1766            landing.vertical_speed_m_s
1767        );
1768        // And it lands when the closed form says, to 1e-5 s of a 200 s descent.
1769        let expected_s = START_S + closed.time_at_descending_height_s(-height_m);
1770        assert!(
1771            (landing.time_s - expected_s).abs() < 1e-5,
1772            "{} vs {expected_s}",
1773            landing.time_s
1774        );
1775    }
1776
1777    #[test]
1778    fn drift_equals_the_wind_times_the_descent_time() {
1779        // Dropped into a steady wind with the same horizontal velocity as the air, the rocket has
1780        // no crossflow: the horizontal equation holds v = w for the whole descent, so the drift is
1781        // exactly the wind times the time of flight, and the vertical fall is unchanged.
1782        let air = UniformAir::sea_level();
1783        let device = open_at_start(DeviceDrag::canopy(CanopyType::FlatCircular, 1.5));
1784        let drag_area_m2 = device.drag.drag_area_m2();
1785        let sim = flight(
1786            analytic_wind_environment(air, G, ConstantWind::new(6.5, 0.7).unwrap()),
1787            vec![device],
1788            3600.0,
1789        );
1790        let wind_enu = sim.environment().wind.wind(0.0).unwrap().velocity_enu_m_s;
1791        assert!(wind_enu.z == 0.0 && wind_enu.length() > 6.4, "{wind_enu}");
1792        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
1793        let closed = closed_form_quadratic_drag(
1794            &QuadraticDragFall {
1795                gravity_mps2: G,
1796                k_per_m: air.0.density_kg_m3 * drag_area_m2 / (2.0 * mass_kg),
1797            },
1798            0.0,
1799        );
1800        let height_m = 1_000.0;
1801        let start = dropped(&sim, height_m, wind_enu);
1802        let result = sim.run_free(START_S, start, &mut ()).unwrap();
1803        assert_eq!(result.termination, Termination::GroundHit);
1804        let landing = result.event(EventKind::GroundHit).unwrap().sample;
1805
1806        let flown_s = landing.time_s - START_S;
1807        let drift =
1808            landing.cg_enu_m - start.point_enu_m(sim.assembly().mass_properties(START_S).cg_m);
1809        let expected = wind_enu * flown_s;
1810        assert!(
1811            (drift.x - expected.x).abs() < 1e-8 * expected.x.abs()
1812                && (drift.y - expected.y).abs() < 1e-8 * expected.y.abs(),
1813            "{drift} vs {expected}"
1814        );
1815        // The wind doesn't change the fall: the descent takes what the closed form says, to 1e-4
1816        // of it (the drift of 1.5 km costs 0.13 m of ellipsoidal height, which the closed form
1817        // over a flat Earth doesn't have).
1818        let expected_s = closed.time_at_descending_height_s(-height_m);
1819        assert!(
1820            (flown_s - expected_s).abs() < 1e-4 * expected_s,
1821            "{flown_s} vs {expected_s}"
1822        );
1823        assert!(drift.length() > 600.0, "{drift}");
1824    }
1825
1826    #[test]
1827    fn coriolis_drifts_a_descent_east_by_the_analytic_amount() {
1828        // Every other analytic descent here runs with Earth's rotation off. With it on, a body
1829        // falling at `v_t` feels `−2Ω × v = 2Ω v_t cos φ` to the east, which the canopy's drag
1830        // balances at `v_east = 2Ω cos φ · m/(½ρ C_D S) = 2Ω cos φ · v_t²/g`. The drift is that
1831        // times the time of flight, once the fall has settled.
1832        let air = UniformAir::sea_level();
1833        let device = open_at_start(DeviceDrag::canopy(CanopyType::FlatCircular, 1.5));
1834        let drag_area_m2 = device.drag.drag_area_m2();
1835        let sim = flight(rotating_analytic_environment(air, G), vec![device], 3600.0);
1836        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
1837        let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, air.0.density_kg_m3, G);
1838        let latitude_rad = sim.environment().site().latitude_rad;
1839        let rate_rad_s = 7.292_115e-5;
1840        let east_m_s = 2.0 * rate_rad_s * latitude_rad.cos() * terminal_m_s * terminal_m_s / G;
1841        assert!(east_m_s > 1e-3, "{east_m_s} m/s is too small to measure");
1842
1843        let height_m = 3_000.0;
1844        let start = dropped(&sim, height_m, DVec3::ZERO);
1845        let result = sim.run_free(START_S, start, &mut ()).unwrap();
1846        assert_eq!(result.termination, Termination::GroundHit);
1847        let landing = result.event(EventKind::GroundHit).unwrap().sample;
1848        let flown_s = landing.time_s - START_S;
1849        let drift =
1850            landing.cg_enu_m - start.point_enu_m(sim.assembly().mass_properties(START_S).cg_m);
1851        let expected_m = east_m_s * flown_s;
1852        // The drift builds up over the first few seconds, while the fall settles, so the
1853        // prediction is the steady one. Measured: 0.3666 m east against the steady prediction's
1854        // 0.3685 m over 306.0 s, and 29 µm north.
1855        assert!(
1856            (drift.x - expected_m).abs() < 0.05 * expected_m,
1857            "{} m east against {expected_m} m in {flown_s} s",
1858            drift.x
1859        );
1860        assert!(
1861            drift.y.abs() < 0.02 * expected_m,
1862            "{} m north, which should be second order",
1863            drift.y
1864        );
1865        // The fall itself is the same as without rotation, to the size of the drift's effect.
1866        let without = terminal_speed_m_s(mass_kg, drag_area_m2, air.0.density_kg_m3, G);
1867        assert!(
1868            (-landing.vertical_speed_m_s / without - 1.0).abs() < 1e-5,
1869            "{} vs {without}",
1870            landing.vertical_speed_m_s
1871        );
1872    }
1873
1874    #[test]
1875    fn inflation_time_limits_peak_opening_load() {
1876        // Loft lesson L27. Loft's canopies opened instantly, so its peak load was the whole
1877        // steady drag at deployment speed. Knacke's filling time t_f = n D₀/v (printed page 5-43)
1878        // with the drag area growing as (t/t_f)^j (Pflanz, Figure 5-51) spreads the opening out:
1879        // the canopy builds its area while the rocket is already slowing down.
1880        //
1881        // hpr does not model Knacke's measured overshoot (C_x = 1.7 for a flat circular canopy at
1882        // infinite mass). For a deployment well above the canopy's terminal speed, as here, the
1883        // instant opening gives hpr's highest load; near terminal speed a filling time can give a
1884        // higher one, because the rocket speeds up while the canopy fills.
1885        let air = UniformAir::sea_level();
1886        let rho = air.0.density_kg_m3;
1887        let diameter_m = 1.5;
1888        let fall = DVec3::new(0.0, 0.0, -60.0);
1889        let mut loads = Vec::new();
1890        let mut mass_kg = 0.0;
1891        for inflation in [
1892            Inflation::Instant,
1893            Inflation::knacke(CanopyType::FlatCircular).unwrap(),
1894        ] {
1895            let device = open_at_start(DeviceDrag::canopy(CanopyType::FlatCircular, diameter_m))
1896                .with_inflation(inflation);
1897            let drag_area_m2 = device.drag.drag_area_m2();
1898            let sim = flight(analytic_environment(air, G), vec![device], 3600.0);
1899            let mut recorder = Recorder::new(
1900                vec![
1901                    Channel::Time,
1902                    Channel::DynamicPressure,
1903                    Channel::RecoveryDragArea,
1904                    Channel::VerticalSpeed,
1905                ],
1906                None,
1907            )
1908            .unwrap();
1909            let result = sim
1910                .run_free(START_S, dropped(&sim, 2_000.0, fall), &mut recorder)
1911                .unwrap();
1912            assert_eq!(result.termination, Termination::GroundHit);
1913            mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
1914            let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, rho, G);
1915            let landing = result.event(EventKind::GroundHit).unwrap().sample;
1916            assert!(
1917                (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
1918                "{}",
1919                landing.vertical_speed_m_s
1920            );
1921            loads.push((peak_load_n(&result, &recorder), drag_area_m2));
1922        }
1923        let (instant_n, drag_area_m2) = loads[0];
1924        let (filled_n, _) = loads[1];
1925        // The instant opening's peak is the steady drag at the deployment speed, at deployment.
1926        let steady_n = 0.5 * rho * drag_area_m2 * fall.z * fall.z;
1927        assert!(
1928            (instant_n - steady_n).abs() < 1e-6 * steady_n,
1929            "{instant_n} vs {steady_n}"
1930        );
1931        // Filling in t_f = n D₀/v = 8 · 1.5/60 = 0.2 s cuts the peak to 1,615 N, 0.53 of the
1932        // instant opening. That is pinned against the closed form rather than a fraction, because
1933        // a fraction cannot tell the growth exponents apart (`j = 1` would peak near 0.42).
1934        //
1935        // Ignoring gravity, `m dv/dt = −½ρ(C_D S)(t/t_f)² v²` separates to
1936        // `1/v = 1/v₀ + k t³/(3 t_f²)` with `k = ρ(C_D S)/2m`, so at the end of filling
1937        // `v = v₀/(1 + k v₀ t_f/3)` and the peak load is `½ρ(C_D S) v²` there (the load rises
1938        // while the canopy grows and falls once it is full). Gravity adds at most `g t_f` to that
1939        // speed, which is where the upper bound comes from.
1940        let k_per_m = rho * drag_area_m2 / (2.0 * mass_kg);
1941        let filling_s = CanopyType::FlatCircular.fill_constant().unwrap() * diameter_m / -fall.z;
1942        let end_m_s = -fall.z / (1.0 + k_per_m * -fall.z * filling_s / 3.0);
1943        let closed_n = 0.5 * rho * drag_area_m2 * end_m_s * end_m_s;
1944        let with_gravity_n = closed_n * (1.0 + G * filling_s / end_m_s).powi(2);
1945        assert!(
1946            (closed_n..=with_gravity_n).contains(&filled_n),
1947            "{filled_n} N is outside {closed_n} to {with_gravity_n} N (t_f {filling_s} s)"
1948        );
1949        assert!(filled_n < 0.6 * instant_n, "{filled_n} against {instant_n}");
1950    }
1951
1952    #[test]
1953    fn a_whole_flight_deploys_a_drogue_at_apogee_and_a_main_that_releases_it() {
1954        // A flight from the pad: the drogue's charge fires at apogee and opens 1 s later, the main
1955        // fires at 300 m above the site and opens 1.5 s later, and the main's opening releases the
1956        // drogue. The events have to come in that order, the drag area has to follow, and each
1957        // stage of the descent has to settle at its own terminal speed.
1958        let devices = vec![
1959            Device::new(
1960                "drogue",
1961                DeviceDrag::DragArea { cd_s_m2: 0.45 },
1962                Trigger::Apogee,
1963            )
1964            .with_lag_s(1.0)
1965            .with_release_by(1),
1966            Device::new(
1967                "main",
1968                DeviceDrag::canopy(CanopyType::FlatCircular, 2.5),
1969                Trigger::Altitude {
1970                    height_above_ground_m: 300.0,
1971                },
1972            )
1973            .with_lag_s(1.5),
1974        ];
1975        let drogue_m2 = devices[0].drag.drag_area_m2();
1976        let main_m2 = devices[1].drag.drag_area_m2();
1977        let sim = flight(
1978            analytic_wind_environment(
1979                UniformAir::sea_level(),
1980                G,
1981                ConstantWind::new(4.0, 0.0).unwrap(),
1982            ),
1983            devices,
1984            3600.0,
1985        );
1986        let mut recorder = Recorder::new(
1987            vec![
1988                Channel::Time,
1989                Channel::HeightAboveGround,
1990                Channel::VerticalSpeed,
1991                Channel::RecoveryDragArea,
1992            ],
1993            Some(0.25),
1994        )
1995        .unwrap();
1996        let result = sim.run(&mut recorder).unwrap();
1997        assert_eq!(result.termination, Termination::GroundHit);
1998
1999        let kinds: Vec<EventKind> = result.events.iter().map(|event| event.kind).collect();
2000        assert_eq!(
2001            kinds,
2002            vec![
2003                EventKind::Liftoff,
2004                EventKind::RailExit,
2005                EventKind::Burnout,
2006                EventKind::Apogee,
2007                EventKind::Trigger(0),
2008                EventKind::Deployment(0),
2009                EventKind::Trigger(1),
2010                EventKind::Deployment(1),
2011                EventKind::Release(0),
2012                EventKind::GroundHit,
2013            ]
2014        );
2015        let at = |kind| result.event(kind).unwrap().sample;
2016        // Each charge opens its device after its lag, and the descent starts at the first opening.
2017        assert!(
2018            (at(EventKind::Deployment(0)).time_s - at(EventKind::Trigger(0)).time_s - 1.0).abs()
2019                < 1e-12
2020        );
2021        assert!(
2022            (at(EventKind::Deployment(1)).time_s - at(EventKind::Trigger(1)).time_s - 1.5).abs()
2023                < 1e-12
2024        );
2025        assert_eq!(at(EventKind::Apogee).phase, crate::Phase::Free);
2026        assert_eq!(at(EventKind::Deployment(0)).phase, crate::Phase::Descent);
2027        // The main fires as the center of mass passes 300 m, descending under the drogue.
2028        let trigger = at(EventKind::Trigger(1));
2029        assert!(
2030            (trigger.height_above_ground_m - 300.0).abs() < 1e-6,
2031            "{trigger:?}"
2032        );
2033        assert!(trigger.vertical_speed_m_s < 0.0);
2034        // The drag area: the drogue alone, then the main alone once it releases the drogue.
2035        assert!((at(EventKind::Deployment(0)).recovery_drag_area_m2 - drogue_m2).abs() < 1e-12);
2036        assert!((at(EventKind::Trigger(1)).recovery_drag_area_m2 - drogue_m2).abs() < 1e-12);
2037        assert!((at(EventKind::Deployment(1)).recovery_drag_area_m2 - main_m2).abs() < 1e-12);
2038        assert!((at(EventKind::GroundHit).recovery_drag_area_m2 - main_m2).abs() < 1e-12);
2039
2040        // Both stages settle at their own terminal speeds, so the descent rate falls when the
2041        // main opens. The drogue's stage is the speed just before the main's charge fires.
2042        let mass_kg = sim
2043            .assembly()
2044            .mass_properties(at(EventKind::Apogee).time_s)
2045            .mass_kg;
2046        let rho = UniformAir::sea_level().0.density_kg_m3;
2047        let under_drogue = terminal_speed_m_s(mass_kg, drogue_m2, rho, G);
2048        let under_main = terminal_speed_m_s(mass_kg, main_m2, rho, G);
2049        assert!(
2050            (-trigger.vertical_speed_m_s / under_drogue - 1.0).abs() < 0.02,
2051            "{} vs {under_drogue}",
2052            trigger.vertical_speed_m_s
2053        );
2054        let landing = at(EventKind::GroundHit);
2055        assert!(
2056            (-landing.vertical_speed_m_s / under_main - 1.0).abs() < 0.02,
2057            "{} vs {under_main}",
2058            landing.vertical_speed_m_s
2059        );
2060        assert!(
2061            under_main < 0.5 * under_drogue,
2062            "{under_main} {under_drogue}"
2063        );
2064        // The recorder's drag-area channel never exceeds one device's area: they never add up.
2065        let area = column(&recorder, "recovery_drag_area_m2");
2066        assert!(area.iter().all(|a| *a <= main_m2 + 1e-12));
2067        assert!(area.iter().any(|a| (*a - drogue_m2).abs() < 1e-12));
2068    }
2069
2070    #[test]
2071    fn a_motor_delay_fires_a_device_and_a_canopy_fills_by_knackes_law() {
2072        // The ejection charge of Valetudo's motor (a 2 s delay after its 3.26 s burn) fires the
2073        // canopy, which then fills over t_f = n D₀/v from the airspeed at line stretch, its drag
2074        // area growing as (t/t_f)^j.
2075        let kind = CanopyType::FlatCircular;
2076        let diameter_m = 1.2;
2077        // Valetudo's example gives its motor no ejection charge, so the test picks one.
2078        let sim = Simulation::new(
2079            &with_delay(design("rocketpy-valetudo"), 2.0),
2080            "example",
2081            analytic_environment(UniformAir::sea_level(), G),
2082            Rail::vertical(3.0),
2083            FlightSettings::default(),
2084        )
2085        .unwrap()
2086        .with_recovery(vec![
2087            Device::new(
2088                "ejection",
2089                DeviceDrag::canopy(kind, diameter_m),
2090                Trigger::MotorDelay { motor: 0 },
2091            )
2092            .with_inflation(Inflation::knacke(kind).unwrap()),
2093        ])
2094        .unwrap();
2095        let delay_s = match sim.assembly().motors[0].mounted.delay {
2096            Some(hpr_motor::Delay::Seconds(delay_s)) => delay_s,
2097            other => panic!("Valetudo's motor has no delay in seconds: {other:?}"),
2098        };
2099        let burnout_s = sim.assembly().motors[0].mounted.motor.burnout_time_s();
2100        let mut recorder =
2101            Recorder::new(vec![Channel::Time, Channel::RecoveryDragArea], None).unwrap();
2102        let result = sim.run(&mut recorder).unwrap();
2103        assert_eq!(result.termination, Termination::GroundHit);
2104        let trigger = result.event(EventKind::Trigger(0)).unwrap().sample;
2105        let deployment = result.event(EventKind::Deployment(0)).unwrap().sample;
2106        assert!(
2107            (trigger.time_s - (burnout_s + delay_s)).abs() < 1e-12,
2108            "{} vs {}",
2109            trigger.time_s,
2110            burnout_s + delay_s
2111        );
2112        assert_eq!(deployment.time_s, trigger.time_s, "no lag was given");
2113        assert_eq!(deployment.recovery_drag_area_m2, 0.0, "it starts empty");
2114
2115        // Knacke's filling time from the airspeed at line stretch, and the growth law between.
2116        let filling_s = kind.fill_constant().unwrap() * diameter_m / deployment.airspeed_m_s;
2117        assert!(filling_s > 0.05 && filling_s < 0.5, "{filling_s} s");
2118        let full_m2 = sim.recovery()[0].drag.drag_area_m2();
2119        let times = column(&recorder, "time_s");
2120        let areas = column(&recorder, "recovery_drag_area_m2");
2121        let mut checked = 0;
2122        for (t, area) in times.iter().zip(&areas) {
2123            let elapsed = t - deployment.time_s;
2124            if elapsed <= 0.0 {
2125                assert_eq!(*area, 0.0, "area before line stretch at {t}");
2126                continue;
2127            }
2128            let fraction = (elapsed / filling_s).min(1.0);
2129            let expected = full_m2 * fraction.powf(kind.growth_exponent().unwrap());
2130            assert!(
2131                (area - expected).abs() < 1e-9 * full_m2,
2132                "{area} vs {expected} at {t}"
2133            );
2134            if elapsed < filling_s {
2135                checked += 1;
2136            }
2137        }
2138        assert!(checked >= 3, "only {checked} rows inside the filling time");
2139    }
2140
2141    /// The comparison against RocketPy's own parachute phase
2142    /// (`validation/oracles/rocketpy/recovery.py`, M1.7a): the same declared state, devices, wind
2143    /// and site, and the descent that follows.
2144    #[test]
2145    fn descent_matches_rocketpy_examples() {
2146        let fixture = include_str!("../../../validation/fixtures/recovery/rocketpy-descent.json");
2147        let document: serde_json::Value = serde_json::from_str(fixture).unwrap();
2148        assert_eq!(document["oracle"], "rocketpy 1.13.0");
2149        let cases = document["cases"].as_array().unwrap();
2150        assert!(cases.len() >= 3, "{} cases", cases.len());
2151        let number = |value: &serde_json::Value| value.as_f64().unwrap();
2152        // The milestone's tolerance and ADR-319's tighter one, as fractions of RocketPy's value.
2153        const MILESTONE: f64 = 0.03;
2154        const TIGHT: f64 = 0.003;
2155        let mut rows = Vec::new();
2156
2157        for case in cases {
2158            let name = case["name"].as_str().unwrap();
2159            let environment = case["environment"].clone();
2160
2161            // The site: RocketPy's elevation above sea level, taken as the ellipsoidal height with
2162            // no geoid undulation (hpr has no geoid model, and the oracle's atmosphere and wind
2163            // are functions of that same height).
2164            let site = hpr_core::geodesy::Geodetic::from_degrees(
2165                number(&environment["latitude_deg"]),
2166                number(&environment["longitude_deg"]),
2167                number(&environment["elevation_m"]),
2168            )
2169            .unwrap();
2170            let wind = wind_of(&environment);
2171            // Gravity: RocketPy applies it to the vertical axis alone (`Flight.u_dot_parachute`,
2172            // `flight.py:2777`, where only `az` carries a gravity term), so this flies hpr's
2173            // model of the same shape. hpr's default is the full normal-gravity vector, which
2174            // differs from that in two ways: it turns with the vertical downrange (`g d/R`,
2175            // 2.1e-3 m/s² at Calisto's 1.4 km of drift, and the larger effect wherever a rocket
2176            // drifts), and above the ellipsoid it leans a few parts in 10^6 toward the equator
2177            // (3e-5 m/s²). The lean is what issue #27 chased: over Valetudo's 800 m of still-air
2178            // descent it is 5.2e-4 m of drift, 26 times what the Coriolis term produces there.
2179            let earth = hpr_core::earth::Earth::new(
2180                hpr_core::gravity::NormalGravity::wgs84(),
2181                site,
2182                hpr_core::earth::GravityModel::VerticalTaylor,
2183                hpr_core::earth::EarthRotation::Coriolis,
2184            )
2185            .unwrap();
2186            let sim = Simulation::new(
2187                &design(&format!("rocketpy-{name}")),
2188                "example",
2189                Environment {
2190                    wind,
2191                    ..Environment::new(
2192                        earth,
2193                        hpr_atmos::AtmosphereModel::default(),
2194                        hpr_atmos::ConstantWind::calm(),
2195                    )
2196                },
2197                // The rail is never used: these flights start in the air. It only has to be
2198                // long enough for the design's guides.
2199                Rail::vertical(6.0),
2200                FlightSettings {
2201                    max_time_s: 6000.0,
2202                    ..FlightSettings::default()
2203                },
2204            )
2205            .unwrap();
2206
2207            // First the environments: a descent compared against an oracle whose air, gravity or
2208            // wind differs is not comparing recovery.
2209            for sample in environment["samples"].as_array().unwrap() {
2210                let height_msl_m = number(&sample["height_msl_m"]);
2211                let air = sim.environment().atmosphere.air(height_msl_m).unwrap().air;
2212                let density = air.density_kg_m3;
2213                let oracle = number(&sample["density_kg_m3"]);
2214                // RocketPy reads its standard atmosphere off a 100-point linear pressure table
2215                // over 0 to 80 km, so it differs from the exact 1976 atmosphere. Measured worst
2216                // over all the samples: 3.7e-4 relative (NDRT at 206 m), which is 1.9e-4 in a
2217                // descent rate, below every difference this test goes on to report.
2218                assert!(
2219                    (density - oracle).abs() < 5e-4 * oracle,
2220                    "{name}: density {density} vs {oracle} at {height_msl_m} m"
2221                );
2222                // Gravity: RocketPy's "Somigliana" model is the same WGS 84 normal gravity hpr
2223                // uses, so these have to agree, not merely be close. They have to agree as a
2224                // *vector*, because agreeing in magnitude is exactly what let a model difference
2225                // hide here for a milestone. Under the model this test flies, gravity is vertical,
2226                // as RocketPy's is; under hpr's default it would not be, and the next assertion
2227                // measures what that would have added.
2228                let up = DVec3::new(0.0, 0.0, height_msl_m - number(&environment["elevation_m"]));
2229                let gravity = sim.environment().earth.gravity_enu_mps2(up).unwrap();
2230                let oracle_gravity = number(&sample["gravity_m_s2"]);
2231                // 1e-8, not the 1e-6 this used to allow: the worst residual over the 23 samples
2232                // is 4.7e-9 relative, and 1e-6 of g is 9.8e-6 m/s², which is larger than the
2233                // deflection issue #27 turned on. A bound has to be tighter than the effects it
2234                // is meant to see.
2235                assert!(
2236                    (gravity.length() - oracle_gravity).abs() < 1e-8 * oracle_gravity,
2237                    "{name}: gravity {gravity:?} vs {oracle_gravity} at {height_msl_m} m"
2238                );
2239                assert_eq!(
2240                    (gravity.x, gravity.y),
2241                    (0.0, 0.0),
2242                    "{name}: gravity leans off the vertical where RocketPy's cannot"
2243                );
2244                // What hpr's own model would have added, so the difference is a number in this
2245                // file rather than a surprise in a validation report. To first order the
2246                // meridional component of normal gravity above the ellipsoid is
2247                //
2248                //     γ_φ ≈ −C h sin 2φ,   C = 8.15e-9 s⁻²
2249                //
2250                // which is proportional to height above the ellipsoid, points toward the equator
2251                // in both hemispheres, and is zero on it (`docs/physics/gravity.md`). Over these
2252                // five cases it runs from +6.9e-6 m/s² at Valetudo's topmost sample (1,168 m, 23°S,
2253                // so northward) to −3.3e-5 m/s² at Calisto's 4,400 m (33°N, so southward).
2254                // Checking the form rather than a bound is the point: "less than 5e-5" would pass
2255                // an implementation whose size was wrong by half.
2256                let latitude_rad = number(&environment["latitude_deg"]).to_radians();
2257                let expected = -8.15e-9 * height_msl_m * (2.0 * latitude_rad).sin();
2258                let ellipsoidal = hpr_core::earth::Earth::new(
2259                    hpr_core::gravity::NormalGravity::wgs84(),
2260                    site,
2261                    hpr_core::earth::GravityModel::Ellipsoidal,
2262                    hpr_core::earth::EarthRotation::Coriolis,
2263                )
2264                .unwrap()
2265                .gravity_enu_mps2(up)
2266                .unwrap();
2267                assert!(
2268                    ellipsoidal.x.abs() < 1e-12,
2269                    "{name}: normal gravity has no east component, but this one is {}",
2270                    ellipsoidal.x
2271                );
2272                assert!(
2273                    (ellipsoidal.y - expected).abs() <= 0.02 * expected.abs().max(1e-9),
2274                    "{name}: hpr's own gravity leans {} m/s² at {height_msl_m} m, where the \
2275                     first-order normal-gravity term is {expected} m/s² (issue #27)",
2276                    ellipsoidal.y
2277                );
2278                let wind = sim
2279                    .environment()
2280                    .wind
2281                    .wind(height_msl_m)
2282                    .unwrap()
2283                    .velocity_enu_m_s;
2284                for (component, key) in [(wind.x, "wind_east_m_s"), (wind.y, "wind_north_m_s")] {
2285                    let oracle = number(&sample[key]);
2286                    assert!(
2287                        (component - oracle).abs() < 1e-9,
2288                        "{name}: {key} {component} vs {oracle} at {height_msl_m} m"
2289                    );
2290                }
2291                assert_eq!(wind.z, 0.0);
2292            }
2293
2294            // The devices: the oracle's drag areas and triggers, with the first open from the
2295            // start and each one released by the next, which is how RocketPy's single `cd_s`
2296            // behaves when a main replaces a drogue.
2297            let start = case["start"].clone();
2298            let start_s = number(&start["time_s"]);
2299            let oracle_devices = case["devices"].as_array().unwrap();
2300            let mut devices = Vec::new();
2301            for (index, device) in oracle_devices.iter().enumerate() {
2302                let drag = DeviceDrag::DragArea {
2303                    cd_s_m2: number(&device["cd_s_m2"]),
2304                };
2305                let trigger = if index == 0 {
2306                    assert_eq!(device["trigger"]["kind"], "apogee");
2307                    assert_eq!(
2308                        number(&device["lag_s"]),
2309                        0.0,
2310                        "{name}: the first lag is zero"
2311                    );
2312                    Trigger::Time { time_s: start_s }
2313                } else {
2314                    assert_eq!(device["trigger"]["kind"], "descending_below_height_agl");
2315                    Trigger::Altitude {
2316                        height_above_ground_m: number(&device["trigger"]["height_m"]),
2317                    }
2318                };
2319                let mut next = Device::new(device["name"].as_str().unwrap(), drag, trigger)
2320                    .with_lag_s(number(&device["lag_s"]));
2321                if index + 1 < oracle_devices.len() {
2322                    next = next.with_release_by(index + 1);
2323                }
2324                devices.push(next);
2325            }
2326            let sim = sim.with_recovery(devices).unwrap();
2327
2328            // The mass: RocketPy's parachute phase uses the rocket's dry mass, and hpr the
2329            // assembly's mass once the propellant is gone. The design is generated from the same
2330            // example, so they have to agree.
2331            let mass_kg = sim.assembly().mass_properties(start_s).mass_kg;
2332            let dry_mass_kg = number(&case["dry_mass_kg"]);
2333            assert!(
2334                (mass_kg - dry_mass_kg).abs() < 1e-9 * dry_mass_kg,
2335                "{name}: mass {mass_kg} vs the oracle's dry mass {dry_mass_kg}"
2336            );
2337
2338            // The declared start, with the center of mass where the oracle put it.
2339            let position = start["position_msl_m"].as_array().unwrap();
2340            let velocity = start["velocity_m_s"].as_array().unwrap();
2341            let cg_enu_m = DVec3::new(
2342                number(&position[0]),
2343                number(&position[1]),
2344                number(&position[2]) - number(&environment["elevation_m"]),
2345            );
2346            let attitude = Rail::vertical(6.0).attitude();
2347            let state = State {
2348                position_enu_m: cg_enu_m
2349                    - attitude.mul_vec3(sim.assembly().mass_properties(start_s).cg_m),
2350                velocity_enu_m_s: DVec3::new(
2351                    number(&velocity[0]),
2352                    number(&velocity[1]),
2353                    number(&velocity[2]),
2354                ),
2355                attitude,
2356                body_rate_rad_s: DVec3::ZERO,
2357            };
2358            let result = sim.run_free(start_s, state, &mut ()).unwrap();
2359            assert_eq!(result.termination, Termination::GroundHit, "{name}");
2360            let landing = result.event(EventKind::GroundHit).unwrap().sample;
2361
2362            // The first device opens where both models agree, to within RocketPy's own trigger
2363            // sampling: it checks its triggers on a grid of `1/sampling_rate` anchored at t = 0,
2364            // and only over the span after its first accepted step, so its deployment comes a
2365            // little after hpr's, which locates the crossing exactly. Measured: 2.5 ms for the
2366            // four 105 Hz cases and 13 ms for Prometheus's 100 Hz one, against descents of 46 to
2367            // 257 s, so under 0.01% of the descent either way.
2368            let first = &case["events"].as_array().unwrap()[0];
2369            let late_s = number(&first["deploy_s"]) - start_s;
2370            let descent_s = number(&case["metrics"]["descent_time_s"]);
2371            assert!(
2372                (0.0..=0.02).contains(&late_s) && late_s < 1e-4 * descent_s,
2373                "{name}: the oracle deployed {late_s} s after the start, of a {descent_s} s descent"
2374            );
2375
2376            // Every later device fired at its own setting, and the oracle's grid put its own
2377            // trigger a little below it: that difference is reported, not assumed away.
2378            for (index, device) in oracle_devices.iter().enumerate().skip(1) {
2379                let trigger = result
2380                    .event(EventKind::Trigger(index))
2381                    .unwrap_or_else(|| panic!("{name}: device {index} never fired"))
2382                    .sample;
2383                let height_m = number(&device["trigger"]["height_m"]);
2384                assert!(
2385                    (trigger.height_above_ground_m - height_m).abs() < 1e-3,
2386                    "{name}: device {index} fired at {} m, not its setting {height_m}",
2387                    trigger.height_above_ground_m
2388                );
2389                let oracle_event = &case["events"].as_array().unwrap()[index];
2390                // The oracle's own reported height at its trigger, which comes from RocketPy's
2391                // reporting spline over its stored samples, not from the dense output its
2392                // trigger was evaluated on. It can only have fired at or below the setting, by
2393                // at most one sample of fall (`v_z/sampling_rate`).
2394                rows.push((
2395                    format!(
2396                        "{name}: device {index} trigger height, hpr against the oracle's report"
2397                    ),
2398                    trigger.height_above_ground_m,
2399                    number(&oracle_event["height_above_ground_at_trigger_m"]),
2400                    MILESTONE,
2401                ));
2402                // The descent rate under the device before it, where the oracle reports its own.
2403                let oracle_speed = -number(&oracle_event["vertical_speed_at_trigger_m_s"]);
2404                let speed = -trigger.vertical_speed_m_s;
2405                rows.push((
2406                    format!("{name}: descent rate under device {}", index - 1),
2407                    speed,
2408                    oracle_speed,
2409                    MILESTONE,
2410                ));
2411            }
2412
2413            // An independent anchor on both simulators: by the time it lands, the rocket is
2414            // descending at Knacke's equilibrium speed under the last device to open, computed
2415            // here from hpr's own air and gravity at the site.
2416            let last = oracle_devices.last().unwrap();
2417            let air = sim
2418                .environment()
2419                .atmosphere
2420                .air(number(&environment["elevation_m"]))
2421                .unwrap()
2422                .air;
2423            let gravity_m_s2 = sim
2424                .environment()
2425                .earth
2426                .gravity_enu_mps2(DVec3::ZERO)
2427                .unwrap()
2428                .length();
2429            let equilibrium_m_s = terminal_speed_m_s(
2430                mass_kg,
2431                number(&last["cd_s_m2"]),
2432                air.density_kg_m3,
2433                gravity_m_s2,
2434            );
2435            for (who, speed) in [
2436                ("hpr", -landing.vertical_speed_m_s),
2437                ("rocketpy", number(&case["metrics"]["impact_speed_m_s"])),
2438            ] {
2439                assert!(
2440                    (speed - equilibrium_m_s).abs() < 0.01 * equilibrium_m_s,
2441                    "{name}: {who} lands at {speed} m/s, not the equilibrium {equilibrium_m_s}"
2442                );
2443            }
2444
2445            let metrics = case["metrics"].clone();
2446            // ADR-319: 0.3% where RocketPy's added mass, the one model difference, is small: 3.5
2447            // times the largest difference so held and 880 times RocketPy's own solver movement.
2448            // NDRT 2020 keeps the milestone's 3%: its descent time differs by 0.705%, from that
2449            // added mass. So does Valetudo's drift, the Earth's rotation alone in still air.
2450            let held = if name == "ndrt-2020-nose-to-tail" {
2451                MILESTONE
2452            } else {
2453                TIGHT
2454            };
2455            let drift_held = if name == "valetudo" { MILESTONE } else { held };
2456            let descent_time_s = landing.time_s - start_s;
2457            let drift = landing.cg_enu_m - cg_enu_m;
2458            rows.push((
2459                format!("{name}: descent time"),
2460                descent_time_s,
2461                number(&metrics["descent_time_s"]),
2462                held,
2463            ));
2464            rows.push((
2465                format!("{name}: impact descent rate"),
2466                -landing.vertical_speed_m_s,
2467                number(&metrics["impact_speed_m_s"]),
2468                held,
2469            ));
2470            rows.push((
2471                format!("{name}: drift"),
2472                drift.truncate().length(),
2473                number(&metrics["drift_m"]),
2474                drift_held,
2475            ));
2476            if number(&metrics["drift_m"]) > 10.0 {
2477                rows.push((
2478                    format!("{name}: drift east"),
2479                    drift.x,
2480                    number(&metrics["drift_east_m"]),
2481                    held,
2482                ));
2483                rows.push((
2484                    format!("{name}: drift north"),
2485                    drift.y,
2486                    number(&metrics["drift_north_m"]),
2487                    held,
2488                ));
2489            }
2490        }
2491
2492        // Each row within its bound of RocketPy's: the milestone's 3%, or ADR-319's 0.3%.
2493        let mut failed = Vec::new();
2494        let mut report = String::new();
2495        for (what, hpr, oracle, bound) in &rows {
2496            let error = (hpr - oracle) / oracle;
2497            // A NaN error fails too.
2498            if error.is_nan() || error.abs() >= *bound {
2499                failed.push(what.clone());
2500            }
2501            report.push_str(&format!(
2502                "{what}: hpr {hpr:.4}, rocketpy {oracle:.4}, {:+.3}% (bound {}%)\n",
2503                100.0 * error,
2504                100.0 * bound
2505            ));
2506        }
2507        eprintln!("{report}");
2508        assert!(
2509            failed.is_empty(),
2510            "outside their bounds: {failed:?}:\n{report}"
2511        );
2512    }
2513
2514    /// The oracle's wind: a constant, or a profile in height above sea level. RocketPy
2515    /// interpolates its east and north components linearly, which is
2516    /// [`hpr_atmos::WindInterpolation::Components`].
2517    fn wind_of(environment: &serde_json::Value) -> std::sync::Arc<dyn hpr_atmos::Wind> {
2518        /// A level from east and north components, m/s: the speed and the direction the wind
2519        /// blows from, clockwise from north (`hpr_atmos::velocity_from_speed_direction`).
2520        fn level(height_msl_m: f64, east: f64, north: f64) -> hpr_atmos::WindLevel {
2521            hpr_atmos::WindLevel {
2522                height_msl_m,
2523                speed_m_s: east.hypot(north),
2524                direction_from_rad: (-east).atan2(-north).rem_euclid(std::f64::consts::TAU),
2525            }
2526        }
2527        let components = |key: &str| -> Option<Vec<(f64, f64)>> {
2528            environment[key].as_array().map(|rows| {
2529                rows.iter()
2530                    .map(|row| {
2531                        let row = row.as_array().unwrap();
2532                        (row[0].as_f64().unwrap(), row[1].as_f64().unwrap())
2533                    })
2534                    .collect()
2535            })
2536        };
2537        let levels = match (components("wind_u"), components("wind_v")) {
2538            (Some(east), Some(north)) => {
2539                assert_eq!(east.len(), north.len());
2540                east.iter()
2541                    .zip(&north)
2542                    .map(|((height_msl_m, east), (other, north))| {
2543                        assert_eq!(height_msl_m, other, "the profiles differ in height");
2544                        level(*height_msl_m, *east, *north)
2545                    })
2546                    .collect()
2547            }
2548            (None, None) => vec![level(
2549                0.0,
2550                environment["wind_u"].as_f64().unwrap(),
2551                environment["wind_v"].as_f64().unwrap(),
2552            )],
2553            _ => panic!("one wind component is a profile and the other is not"),
2554        };
2555        std::sync::Arc::new(
2556            hpr_atmos::LayeredWind::new(levels, hpr_atmos::WindInterpolation::Components).unwrap(),
2557        )
2558    }
2559
2560    #[test]
2561    fn a_deployment_keeps_the_center_of_mass_moving_as_it_was() {
2562        // Dropping the body rates at deployment must not move the center of mass's momentum:
2563        // the state carries the nose tip's velocity, so it has to be shifted by `ω × r_cg`
2564        // (found in review). With `r_cg` along the axis and `ω` across it the error is across the
2565        // axis too, so for this nose-up drop it is about 0.9 m/s of drift rate; it becomes a
2566        // descent-rate error once the rocket has pitched over.
2567        let air = UniformAir::sea_level();
2568        let device = open_at_start(DeviceDrag::DragArea { cd_s_m2: 1.5 });
2569        let sim = flight(analytic_environment(air, G), vec![device], 3600.0);
2570        let rate_rad_s = DVec3::new(0.0, 0.7, 0.0);
2571        let mut state = dropped(&sim, 1_500.0, DVec3::new(2.0, 0.0, -12.0));
2572        state.body_rate_rad_s = rate_rad_s;
2573        let cg_m = sim.assembly().mass_properties(START_S).cg_m;
2574        // The center of mass's velocity before the canopy opens: the nose tip's plus `ω × r_cg`
2575        // (the propellant is gone, so the center of mass doesn't move inside the body).
2576        let before =
2577            state.velocity_enu_m_s + state.unit_attitude().mul_vec3(rate_rad_s.cross(cg_m));
2578        assert!(
2579            (before - state.velocity_enu_m_s).length() > 0.5,
2580            "the test needs a lever arm: {before}"
2581        );
2582        let result = sim.run_free(START_S, state, &mut ()).unwrap();
2583        let deployment = result.event(EventKind::Deployment(0)).unwrap().sample;
2584        assert_eq!(deployment.time_s, START_S);
2585        assert!(
2586            (deployment.cg_velocity_enu_m_s - before).length() < 1e-12,
2587            "{} vs {before}",
2588            deployment.cg_velocity_enu_m_s
2589        );
2590        assert_eq!(deployment.state.body_rate_rad_s, DVec3::ZERO);
2591        // The descent then settles at the terminal speed, as before.
2592        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
2593        let terminal_m_s = terminal_speed_m_s(mass_kg, 1.5, air.0.density_kg_m3, G);
2594        let landing = result.event(EventKind::GroundHit).unwrap().sample;
2595        assert!(
2596            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
2597            "{} vs {terminal_m_s}",
2598            landing.vertical_speed_m_s
2599        );
2600    }
2601
2602    #[test]
2603    fn a_deployment_during_a_burn_keeps_the_center_of_mass_moving_as_it_was() {
2604        // The same handover while propellant still burns, so the center of mass is moving inside
2605        // the body as well (`v_cg = v_O + q(ω × r_cg + ṙ_cg)`). The two `ṙ_cg` terms cancel, so
2606        // the net shift is `q(ω × r_cg)` whatever the motor is doing; this pins that, and that
2607        // the canopy opening under thrust (an off-nominal case the descent phase keeps the thrust
2608        // for) does not move the center of mass. Valetudo burns until 3.26 s, and the crosswind
2609        // gives it a body rate to shift by.
2610        let sim = flight(
2611            analytic_wind_environment(
2612                UniformAir::sea_level(),
2613                G,
2614                ConstantWind::new(8.0, 1.5).unwrap(),
2615            ),
2616            vec![Device::new(
2617                "early",
2618                DeviceDrag::DragArea { cd_s_m2: 0.2 },
2619                Trigger::Time { time_s: 2.0 },
2620            )],
2621            3600.0,
2622        );
2623        let result = sim.run(&mut ()).unwrap();
2624        let trigger = result.event(EventKind::Trigger(0)).unwrap().sample;
2625        let deployment = result.event(EventKind::Deployment(0)).unwrap().sample;
2626        assert_eq!(trigger.time_s, 2.0);
2627        assert_eq!(deployment.time_s, 2.0);
2628        assert!(
2629            trigger.thrust_n > 0.0,
2630            "the motor has to be burning: {trigger:?}"
2631        );
2632        assert!(
2633            trigger.state.body_rate_rad_s.length() > 1e-3,
2634            "the flight needs a body rate to shift by: {}",
2635            trigger.state.body_rate_rad_s
2636        );
2637        // The center of mass keeps its velocity, and the nose tip's moved by exactly `ω × r_cg`.
2638        assert!(
2639            (deployment.cg_velocity_enu_m_s - trigger.cg_velocity_enu_m_s).length() < 1e-12,
2640            "{} vs {}",
2641            deployment.cg_velocity_enu_m_s,
2642            trigger.cg_velocity_enu_m_s
2643        );
2644        let cg_m = sim.assembly().mass_properties(2.0).cg_m;
2645        let shift = trigger
2646            .state
2647            .unit_attitude()
2648            .mul_vec3(trigger.state.body_rate_rad_s.cross(cg_m));
2649        assert!(shift.length() > 1e-3, "{shift}");
2650        assert!(
2651            (deployment.state.velocity_enu_m_s - trigger.state.velocity_enu_m_s - shift).length()
2652                < 1e-12,
2653            "{} vs {} + {shift}",
2654            deployment.state.velocity_enu_m_s,
2655            trigger.state.velocity_enu_m_s
2656        );
2657        assert_eq!(deployment.phase, crate::Phase::Descent);
2658        assert_eq!(result.termination, Termination::GroundHit);
2659    }
2660
2661    #[test]
2662    fn devices_that_open_together_add_their_drag_areas() {
2663        // Two devices triggered at the same instant both open in the same pass, and the descent
2664        // runs under the sum of their drag areas.
2665        let air = UniformAir::sea_level();
2666        let devices = vec![
2667            open_at_start(DeviceDrag::DragArea { cd_s_m2: 1.0 }),
2668            open_at_start(DeviceDrag::DragArea { cd_s_m2: 2.0 }),
2669        ];
2670        let sim = flight(analytic_environment(air, G), devices, 3600.0);
2671        let result = sim
2672            .run_free(START_S, dropped(&sim, 1_000.0, DVec3::ZERO), &mut ())
2673            .unwrap();
2674        assert_eq!(result.termination, Termination::GroundHit);
2675        for index in 0..2 {
2676            let deployment = result.event(EventKind::Deployment(index)).unwrap().sample;
2677            assert_eq!(deployment.time_s, START_S, "device {index}");
2678        }
2679        let landing = result.event(EventKind::GroundHit).unwrap().sample;
2680        assert!((landing.recovery_drag_area_m2 - 3.0).abs() < 1e-12);
2681        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
2682        let terminal_m_s = terminal_speed_m_s(mass_kg, 3.0, air.0.density_kg_m3, G);
2683        assert!(
2684            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
2685            "{} vs {terminal_m_s}",
2686            landing.vertical_speed_m_s
2687        );
2688    }
2689
2690    #[test]
2691    fn a_device_released_before_it_opens_never_pulls() {
2692        // The main opens first and releases the drogue; when the drogue's own charge fires later
2693        // there is nothing left to open, so it is recorded as triggered and never deploys.
2694        let air = UniformAir::sea_level();
2695        let devices = vec![
2696            Device::new(
2697                "drogue",
2698                DeviceDrag::DragArea { cd_s_m2: 4.0 },
2699                Trigger::Time {
2700                    time_s: START_S + 5.0,
2701                },
2702            )
2703            .with_release_by(1),
2704            open_at_start(DeviceDrag::DragArea { cd_s_m2: 1.0 }),
2705        ];
2706        let sim = flight(analytic_environment(air, G), devices, 3600.0);
2707        let result = sim
2708            .run_free(START_S, dropped(&sim, 1_000.0, DVec3::ZERO), &mut ())
2709            .unwrap();
2710        assert_eq!(result.termination, Termination::GroundHit);
2711        let release = result.event(EventKind::Release(0)).unwrap().sample;
2712        assert_eq!(
2713            release.time_s, START_S,
2714            "the main opens at once, so it releases at once"
2715        );
2716        let trigger = result.event(EventKind::Trigger(0)).unwrap().sample;
2717        assert_eq!(trigger.time_s, START_S + 5.0);
2718        assert!(
2719            result.event(EventKind::Deployment(0)).is_none(),
2720            "a released device must not deploy: {:?}",
2721            result.events.iter().map(|e| e.kind).collect::<Vec<_>>()
2722        );
2723        let landing = result.event(EventKind::GroundHit).unwrap().sample;
2724        assert!((landing.recovery_drag_area_m2 - 1.0).abs() < 1e-12);
2725        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
2726        let terminal_m_s = terminal_speed_m_s(mass_kg, 1.0, air.0.density_kg_m3, G);
2727        assert!(
2728            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
2729            "{} vs {terminal_m_s}",
2730            landing.vertical_speed_m_s
2731        );
2732    }
2733
2734    #[test]
2735    fn a_release_waits_for_the_main_to_fill_so_the_drag_area_never_dips() {
2736        // A drogue cut away at the main's line stretch would leave the rocket under an empty
2737        // canopy: the drag area would collapse and the descent would speed up. The release waits
2738        // until the main is full, so the drag area only ever grows here (ADR-012).
2739        let air = UniformAir::sea_level();
2740        let drogue_m2 = 0.45;
2741        let main_m2 = 6.0;
2742        let filling_s = 2.0;
2743        let devices = vec![
2744            open_at_start(DeviceDrag::DragArea { cd_s_m2: drogue_m2 }).with_release_by(1),
2745            Device::new(
2746                "main",
2747                DeviceDrag::DragArea { cd_s_m2: main_m2 },
2748                Trigger::Time {
2749                    time_s: START_S + 20.0,
2750                },
2751            )
2752            .with_inflation(Inflation::FillingTime {
2753                time_s: filling_s,
2754                exponent: 2.0,
2755            }),
2756        ];
2757        let sim = flight(analytic_environment(air, G), devices, 3600.0);
2758        let mut recorder = Recorder::new(
2759            vec![
2760                Channel::Time,
2761                Channel::RecoveryDragArea,
2762                Channel::VerticalSpeed,
2763            ],
2764            None,
2765        )
2766        .unwrap();
2767        let result = sim
2768            .run_free(START_S, dropped(&sim, 2_000.0, DVec3::ZERO), &mut recorder)
2769            .unwrap();
2770        assert_eq!(result.termination, Termination::GroundHit);
2771        let main = result.event(EventKind::Deployment(1)).unwrap().sample;
2772        let release = result.event(EventKind::Release(0)).unwrap().sample;
2773        assert_eq!(main.time_s, START_S + 20.0);
2774        assert!(
2775            (release.time_s - (main.time_s + filling_s)).abs() < 1e-9,
2776            "released at {} m, not at the end of filling {}",
2777            release.time_s,
2778            main.time_s + filling_s
2779        );
2780        // The drag area never falls below the drogue's, and the descent never speeds up after the
2781        // main's charge fires.
2782        let areas = column(&recorder, "recovery_drag_area_m2");
2783        let times = column(&recorder, "time_s");
2784        let speeds = column(&recorder, "vertical_speed_m_s");
2785        let mut worst_area = f64::INFINITY;
2786        let mut fastest = 0.0_f64;
2787        for ((t, area), speed) in times.iter().zip(&areas).zip(&speeds) {
2788            if *t < main.time_s {
2789                continue;
2790            }
2791            worst_area = worst_area.min(*area);
2792            fastest = fastest.max(-speed);
2793        }
2794        assert!(
2795            worst_area >= drogue_m2 - 1e-12,
2796            "the drag area dipped to {worst_area} m², below the drogue's {drogue_m2}"
2797        );
2798        assert!(
2799            fastest <= -main.vertical_speed_m_s + 1e-9,
2800            "the descent sped up after the main fired: {fastest} against {}",
2801            -main.vertical_speed_m_s
2802        );
2803        // And by the end the main alone carries it.
2804        let landing = result.event(EventKind::GroundHit).unwrap().sample;
2805        assert!((landing.recovery_drag_area_m2 - main_m2).abs() < 1e-12);
2806    }
2807
2808    #[test]
2809    fn a_recovered_flight_repeats_bit_identically() {
2810        // Determinism, and Loft lesson L24: the devices' progress belongs to the flight, not to
2811        // the simulation, so flying the same simulation twice gives bit-identical rows and events.
2812        let sim = flight(
2813            analytic_wind_environment(
2814                UniformAir::sea_level(),
2815                G,
2816                ConstantWind::new(3.0, 1.2).unwrap(),
2817            ),
2818            vec![
2819                Device::new(
2820                    "drogue",
2821                    DeviceDrag::canopy(CanopyType::FlatCircular, 0.5),
2822                    Trigger::Apogee,
2823                )
2824                .with_lag_s(0.75)
2825                .with_inflation(Inflation::knacke(CanopyType::FlatCircular).unwrap())
2826                .with_release_by(1),
2827                Device::new(
2828                    "main",
2829                    DeviceDrag::canopy(CanopyType::FlatCircular, 2.0),
2830                    Trigger::Altitude {
2831                        height_above_ground_m: 200.0,
2832                    },
2833                )
2834                .with_lag_s(1.25)
2835                .with_inflation(Inflation::knacke(CanopyType::FlatCircular).unwrap()),
2836            ],
2837            3600.0,
2838        );
2839        let fly = || {
2840            let mut recorder = Recorder::new(Channel::ALL.to_vec(), Some(0.1)).unwrap();
2841            let result = sim.run(&mut recorder).unwrap();
2842            (recorder.rows().to_vec(), result)
2843        };
2844        let (first_rows, first) = fly();
2845        let (second_rows, second) = fly();
2846        assert_eq!(first.termination, Termination::GroundHit);
2847        assert!(first_rows.len() > 100, "{} rows", first_rows.len());
2848        assert_eq!(first_rows, second_rows, "the rows differ between runs");
2849        assert_eq!(
2850            first.events, second.events,
2851            "the events differ between runs"
2852        );
2853        assert_eq!(first.final_sample, second.final_sample);
2854        assert_eq!(first.stats, second.stats);
2855        // And the events are the full sequence, once each.
2856        let kinds: Vec<EventKind> = first.events.iter().map(|event| event.kind).collect();
2857        assert_eq!(
2858            kinds,
2859            vec![
2860                EventKind::Liftoff,
2861                EventKind::RailExit,
2862                EventKind::Burnout,
2863                EventKind::Apogee,
2864                EventKind::Trigger(0),
2865                EventKind::Deployment(0),
2866                EventKind::Trigger(1),
2867                EventKind::Deployment(1),
2868                EventKind::Release(0),
2869                EventKind::GroundHit,
2870            ]
2871        );
2872    }
2873
2874    #[test]
2875    fn an_apogee_charge_fires_on_a_flight_that_starts_descending() {
2876        // The apogee trigger is RocketPy's `y[5] < 0`, not only hpr's apogee event: a flight
2877        // restarted past its apogee (`run_free`, which M1.9's staging and flight-data replay use)
2878        // still deploys. Found in review: with an event-only trigger this flight fell ballistically
2879        // to the ground with no deployment and no error.
2880        let air = UniformAir::sea_level();
2881        let device = Device::new(
2882            "main",
2883            DeviceDrag::DragArea { cd_s_m2: 2.0 },
2884            Trigger::Apogee,
2885        );
2886        let drag_area_m2 = device.drag.drag_area_m2();
2887        let sim = flight(analytic_environment(air, G), vec![device], 3600.0);
2888        let result = sim
2889            .run_free(
2890                START_S,
2891                dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, -5.0)),
2892                &mut (),
2893            )
2894            .unwrap();
2895        assert_eq!(result.termination, Termination::GroundHit);
2896        let deployment = result.event(EventKind::Deployment(0)).unwrap().sample;
2897        assert_eq!(deployment.time_s, START_S, "it is already descending");
2898        assert_eq!(
2899            result.event(EventKind::Apogee),
2900            None,
2901            "there is no apogee to find"
2902        );
2903        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
2904        let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, air.0.density_kg_m3, G);
2905        let landing = result.event(EventKind::GroundHit).unwrap().sample;
2906        assert!(
2907            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
2908            "{} vs {terminal_m_s}",
2909            landing.vertical_speed_m_s
2910        );
2911        // A climbing flight does not fire it early: the charge waits for the apogee.
2912        let climbing = sim
2913            .run_free(
2914                START_S,
2915                dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 30.0)),
2916                &mut (),
2917            )
2918            .unwrap();
2919        let apogee = climbing.event(EventKind::Apogee).unwrap().sample;
2920        let fired = climbing.event(EventKind::Trigger(0)).unwrap().sample;
2921        assert_eq!(fired.time_s, apogee.time_s);
2922        assert!(apogee.time_s > START_S + 1.0, "{}", apogee.time_s);
2923    }
2924
2925    #[test]
2926    fn user_events_keep_their_numbers_and_fire_during_the_descent() {
2927        // The event list is rebuilt per interval (`flight::Watch`), and the height triggers come
2928        // and go, so the user events sit after them. This pins that their indices don't move and
2929        // that they still fire once the descent has started.
2930        let air = UniformAir::sea_level();
2931        let devices = vec![
2932            open_at_start(DeviceDrag::DragArea { cd_s_m2: 0.5 }).with_release_by(1),
2933            Device::new(
2934                "main",
2935                DeviceDrag::DragArea { cd_s_m2: 4.0 },
2936                Trigger::Altitude {
2937                    height_above_ground_m: 400.0,
2938                },
2939            ),
2940        ];
2941        let sim = flight(analytic_environment(air, G), devices, 3600.0)
2942            .with_event(crate::flight::UserEvent {
2943                name: "through 700 m".to_owned(),
2944                direction: crate::events::Direction::Falling,
2945                function: Box::new(|sample| sample.height_above_ground_m - 700.0),
2946            })
2947            .with_event(crate::flight::UserEvent {
2948                name: "through 100 m".to_owned(),
2949                direction: crate::events::Direction::Falling,
2950                function: Box::new(|sample| sample.height_above_ground_m - 100.0),
2951            });
2952        let result = sim
2953            .run_free(START_S, dropped(&sim, 1_000.0, DVec3::ZERO), &mut ())
2954            .unwrap();
2955        assert_eq!(result.termination, Termination::GroundHit);
2956        for (user, height_m) in [(0usize, 700.0), (1, 100.0)] {
2957            let event = result
2958                .event(EventKind::User(user))
2959                .unwrap_or_else(|| panic!("user event {user} never fired"))
2960                .sample;
2961            assert!(
2962                (event.height_above_ground_m - height_m).abs() < 1e-6,
2963                "user event {user} fired at {} m",
2964                event.height_above_ground_m
2965            );
2966            assert_eq!(event.phase, crate::Phase::Descent);
2967        }
2968        // The user events fire between the main's trigger and the ground, in height order.
2969        let kinds: Vec<EventKind> = result.events.iter().map(|event| event.kind).collect();
2970        let position = |kind| kinds.iter().position(|other| *other == kind).unwrap();
2971        assert!(position(EventKind::User(0)) < position(EventKind::Trigger(1)));
2972        assert!(position(EventKind::Trigger(1)) < position(EventKind::User(1)));
2973        assert!(position(EventKind::User(1)) < position(EventKind::GroundHit));
2974    }
2975
2976    #[test]
2977    fn the_public_recovery_types_round_trip_through_json() {
2978        let devices = vec![
2979            Device::new(
2980                "drogue",
2981                DeviceDrag::DragArea { cd_s_m2: 0.45 },
2982                Trigger::Apogee,
2983            )
2984            .with_lag_s(1.5)
2985            .with_release_by(1),
2986            Device::new(
2987                "main",
2988                DeviceDrag::canopy(CanopyType::Ringsail, 3.0),
2989                Trigger::Altitude {
2990                    height_above_ground_m: 250.0,
2991                },
2992            )
2993            .with_inflation(Inflation::FillingTime {
2994                time_s: 1.5,
2995                exponent: 2.0,
2996            }),
2997            Device::new(
2998                "timer",
2999                DeviceDrag::canopy(CanopyType::FlatCircular, 1.0),
3000                Trigger::Time { time_s: 12.0 },
3001            )
3002            .with_inflation(Inflation::knacke(CanopyType::FlatCircular).unwrap()),
3003            Device::new(
3004                "ejection",
3005                DeviceDrag::DragArea { cd_s_m2: 1.0 },
3006                Trigger::MotorDelay { motor: 0 },
3007            ),
3008            Device::new(
3009                "streamer",
3010                DeviceDrag::streamer(1.2, 0.12, 0.032),
3011                Trigger::Apogee,
3012            ),
3013            Device::new(
3014                "appendix C streamer",
3015                DeviceDrag::Streamer {
3016                    length_m: 1.0,
3017                    width_m: 0.1,
3018                    surface_density_kg_m2: 0.04,
3019                    model: StreamerModel::OpenRocket,
3020                },
3021                Trigger::Apogee,
3022            ),
3023            Device::new(
3024                "tumble",
3025                DeviceDrag::tumbling(&design("rocketpy-valetudo").assemble("example").unwrap())
3026                    .unwrap(),
3027                Trigger::Apogee,
3028            ),
3029        ];
3030        let text = serde_json::to_string(&devices).unwrap();
3031        let back: Vec<Device> = serde_json::from_str(&text).unwrap();
3032        assert_eq!(devices, back);
3033        // The defaults are optional in a file, and unknown fields are refused.
3034        let terse: Device = serde_json::from_str(
3035            r#"{"name":"d","drag":{"drag_area":{"cd_s_m2":1.5}},"trigger":"apogee"}"#,
3036        )
3037        .unwrap();
3038        assert_eq!(terse.lag_s, 0.0);
3039        assert_eq!(terse.inflation, Inflation::Instant);
3040        assert_eq!(terse.released_by, None);
3041        assert!(
3042            serde_json::from_str::<Device>(
3043                r#"{"name":"d","drag":{"drag_area":{"cd_s_m2":1.5}},"trigger":"apogee","lg":1}"#
3044            )
3045            .is_err()
3046        );
3047        // A typo inside the drag is refused too: `model` defaults, and the two streamer models
3048        // differ by a factor of four in drag area, so a silent default would be a wrong number.
3049        let typo = r#"{"name":"s","drag":{"streamer":{"length_m":1.0,"width_m":0.1,
3050            "surface_density_kg_m2":0.04,"modle":"open_rocket"}},"trigger":"apogee"}"#;
3051        assert!(serde_json::from_str::<Device>(typo).is_err(), "{typo}");
3052        // And the model itself round-trips by name.
3053        let named: DeviceDrag = serde_json::from_str(
3054            r#"{"streamer":{"length_m":1.0,"width_m":0.1,"surface_density_kg_m2":0.04,
3055                "model":"open_rocket"}}"#,
3056        )
3057        .unwrap();
3058        assert_eq!(named.canopy_type(), None);
3059        assert!(
3060            (named.drag_area_m2() - StreamerModel::OpenRocket.drag_area_m2(1.0, 0.1, 0.04)).abs()
3061                < 1e-15
3062        );
3063    }
3064
3065    #[test]
3066    fn streamer_models_reproduce_their_printed_equations() {
3067        // Carruthers and Filippone's three printed curves, on the planform area, at the areas
3068        // they were fitted at: `0.405 AR^−0.494` at 0.075 m² (eq. 1), `0.561 AR^−0.480` at
3069        // 0.025 m² (eq. 2) and `0.6514 AR^−0.6075` at 0.05 m² (the trend line on Figure 3).
3070        let cases: [(f64, f64, f64); 6] = [
3071            (10.0, 0.075, 0.405 * 10.0_f64.powf(-0.494)),
3072            (30.0, 0.075, 0.405 * 30.0_f64.powf(-0.494)),
3073            (10.0, 0.025, 0.561 * 10.0_f64.powf(-0.480)),
3074            (3.3, 0.025, 0.561 * 3.3_f64.powf(-0.480)),
3075            // The trend line on Figure 3, which the text does not repeat as an equation.
3076            (3.3, 0.05, 0.6514 * 3.3_f64.powf(-0.6075)),
3077            (30.0, 0.05, 0.6514 * 30.0_f64.powf(-0.6075)),
3078        ];
3079        for (aspect_ratio, planform_m2, expected) in cases {
3080            // A planform area `S` at aspect ratio `l/w` means `l = √(S·AR)`, `w = √(S/AR)`.
3081            let length_m = (planform_m2 * aspect_ratio).sqrt();
3082            let width_m = (planform_m2 / aspect_ratio).sqrt();
3083            let drag_area_m2 = StreamerModel::Filippone.drag_area_m2(length_m, width_m, 0.05);
3084            let coefficient = drag_area_m2 / planform_m2;
3085            assert!(
3086                (coefficient - expected).abs() < 1e-12,
3087                "AR {aspect_ratio} at {planform_m2} m²: {coefficient} vs {expected}"
3088            );
3089        }
3090        // Between the two areas it interpolates, and outside them it holds the end curve. A
3091        // planform of 0.05 m² at `AR = 10` is `l = √0.5 m` by `w = l/10`.
3092        let middle_m = (0.5_f64).sqrt();
3093        let between = StreamerModel::Filippone.drag_area_m2(middle_m, middle_m / 10.0, 0.05) / 0.05;
3094        let small = 0.561 * 10.0_f64.powf(-0.480);
3095        let large = 0.405 * 10.0_f64.powf(-0.494);
3096        assert!(large < between && between < small, "{between}");
3097        let huge = StreamerModel::Filippone.drag_area_m2(3.0, 0.3, 0.05) / 0.9;
3098        assert!((huge - large).abs() < 1e-12, "{huge} vs {large}");
3099
3100        // The OpenRocket technical documentation's appendix C: its own reference material is
3101        // 80 g/m² polyethylene, where the material factor is exactly 1 and `C_Dm` is
3102        // `0.034 (l + 1)/l`.
3103        let reference = StreamerModel::OpenRocket.drag_area_m2(0.4, 0.04, 0.080) / (0.4 * 0.04);
3104        assert!(
3105            (reference - 0.034 * (0.4 + 1.0) / 0.4).abs() < 1e-12,
3106            "{reference}"
3107        );
3108        // And its material correction is linear in surface density about −25 g/m².
3109        let light = StreamerModel::OpenRocket.drag_area_m2(0.4, 0.04, 0.010);
3110        let heavy = StreamerModel::OpenRocket.drag_area_m2(0.4, 0.04, 0.080);
3111        assert!(
3112            (light / heavy - (0.010 + 0.025) / (0.080 + 0.025)).abs() < 1e-12,
3113            "{light} {heavy}"
3114        );
3115    }
3116
3117    /// The average speed of a drop from rest through `height_m` under a drag area, m/s: the
3118    /// closed-form fall `h = (v_t²/g) ln cosh(g t/v_t)` solved for the time. A drop test measures
3119    /// this, not the terminal speed it is approaching.
3120    fn drop_average_m_s(
3121        mass_kg: f64,
3122        drag_area_m2: f64,
3123        density_kg_m3: f64,
3124        height_m: f64,
3125    ) -> (f64, f64) {
3126        let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, density_kg_m3, G);
3127        let time_s =
3128            (terminal_m_s / G) * (G * height_m / (terminal_m_s * terminal_m_s)).exp().acosh();
3129        (height_m / time_s, terminal_m_s)
3130    }
3131
3132    #[test]
3133    fn streamer_models_against_kidwells_drop_tests() {
3134        // The only free-drop streamer data in hand: C. Kidwell, "Streamer Duration Optimization",
3135        // NAR R&D, NARAM-43 (2001). Sixteen 4 in × 40 in streamers, each with a weight of about
3136        // 5 g at one corner, dropped 20.1 m from a stadium deck.
3137        //
3138        // Two details of his method decide how to compare (both found in review):
3139        //
3140        // - his descent rates are **distance over time**, so they are averages over the drop, not
3141        //   terminal speeds. A 20.1 m drop averages 0.97 of terminal at 2.8 m/s and 0.89 at
3142        //   5.9 m/s, so the correction matters most for the model that predicts the fastest fall.
3143        //   The prediction here is therefore the same average, from the closed-form fall.
3144        // - he **normalized** each rate "by dividing by the actual mass of the attached weight
3145        //   and multiplying by 5 g", so the rates belong to a notional 5.000 g weight, not to
3146        //   Table 1's actual one.
3147        let length_m = 40.0 * 0.0254;
3148        let width_m = 4.0 * 0.0254;
3149        let planform_m2 = length_m * width_m;
3150        let rho = 1.225;
3151        let drop_m = 20.1;
3152        let cases = [
3153            // (material, streamer mass from Table 1, normalized descent rate, pleated)
3154            ("crepe paper", 3.3206e-3, 2.80, false),
3155            ("Micafilm", 4.3412e-3, 2.04, true),
3156        ];
3157        let mut report = String::new();
3158        for (material, streamer_kg, measured_m_s, pleated) in cases {
3159            let surface_density_kg_m2 = streamer_kg / planform_m2;
3160            let mass_kg = streamer_kg + 5.0e-3;
3161            let predict = |model: StreamerModel| {
3162                let drag_area_m2 = model.drag_area_m2(length_m, width_m, surface_density_kg_m2);
3163                let (average_m_s, terminal_m_s) =
3164                    drop_average_m_s(mass_kg, drag_area_m2, rho, drop_m);
3165                (average_m_s, terminal_m_s, drag_area_m2)
3166            };
3167            let (filippone, _, filippone_m2) = predict(StreamerModel::Filippone);
3168            let (open_rocket, _, open_rocket_m2) = predict(StreamerModel::OpenRocket);
3169            // What the drop itself says the drag area was.
3170            let measured_m2 = {
3171                // Invert the closed-form average: search the drag area whose average matches.
3172                let mut low = 1e-4;
3173                let mut high = 1.0;
3174                for _ in 0..200 {
3175                    let middle = 0.5 * (low + high);
3176                    if drop_average_m_s(mass_kg, middle, rho, drop_m).0 > measured_m_s {
3177                        low = middle;
3178                    } else {
3179                        high = middle;
3180                    }
3181                }
3182                0.5 * (low + high)
3183            };
3184            report.push_str(&format!(
3185                "{material}: measured {measured_m_s:.2} m/s (C_D S {measured_m2:.5} m², C_D \
3186                 {:.3}), Filippone {filippone:.2} ({:+.0}%, C_D S {filippone_m2:.5}), OpenRocket \
3187                 {open_rocket:.2} ({:+.0}%, C_D S {open_rocket_m2:.5})\n",
3188                measured_m2 / planform_m2,
3189                100.0 * (filippone / measured_m_s - 1.0),
3190                100.0 * (open_rocket / measured_m_s - 1.0),
3191            ));
3192            // Both models predict a faster descent than the drop: neither knows about pleats, and
3193            // the correlations are for a streamer clamped at its leading edge, which the paper
3194            // measures as less draggy than a free one.
3195            assert!(filippone > measured_m_s, "{material}: {filippone}");
3196            assert!(open_rocket > filippone, "{material}: {open_rocket}");
3197            if pleated {
3198                // Pleats more than double the drag: measured C_D 0.338 against 0.155 flat.
3199                assert!(
3200                    (filippone / measured_m_s - 1.0) < 0.75,
3201                    "{material}: {filippone} against {measured_m_s}"
3202                );
3203            } else {
3204                // Flat streamer, flat correlation: within 10%, where appendix C is 88% fast.
3205                assert!(
3206                    (filippone / measured_m_s - 1.0) < 0.10,
3207                    "{material}: {filippone} against {measured_m_s}"
3208                );
3209                assert!(
3210                    (open_rocket / measured_m_s - 1.0) > 0.5,
3211                    "{material}: appendix C should be the slow one: {open_rocket}"
3212                );
3213            }
3214        }
3215        eprintln!("{report}");
3216    }
3217
3218    #[test]
3219    fn a_streamer_descends_at_its_cited_terminal_velocity() {
3220        // A streamer's drag area is its model's, and a descent under it settles at Knacke's
3221        // equilibrium speed for that area, the same as a canopy's.
3222        let air = UniformAir::sea_level();
3223        let drag = DeviceDrag::streamer(1.5, 0.15, 0.040);
3224        let drag_area_m2 = drag.drag_area_m2();
3225        // 1.5 m by 0.15 m is a planform of 0.225 m², above the largest area Carruthers and
3226        // Filippone fitted, so their 0.075 m² curve holds: `C_D = 0.405 · 10^−0.494 = 0.12984`
3227        // and `C_D S = 0.029216 m²`.
3228        let expected_m2 = 0.405 * 10.0_f64.powf(-0.494) * 0.225;
3229        assert!(
3230            (drag_area_m2 - expected_m2).abs() < 1e-12,
3231            "{drag_area_m2} vs {expected_m2}"
3232        );
3233        let sim = flight(
3234            analytic_environment(air, G),
3235            vec![open_at_start(drag)],
3236            3600.0,
3237        );
3238        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
3239        let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, air.0.density_kg_m3, G);
3240        // A streamer is a feeble decelerator: Valetudo falls at 67 m/s under this one, so the
3241        // drop has to be long enough to settle (the time constant is `v_t/g`, near 7 s).
3242        assert!(terminal_m_s > 20.0, "{terminal_m_s}");
3243        let result = sim
3244            .run_free(START_S, dropped(&sim, 6_000.0, DVec3::ZERO), &mut ())
3245            .unwrap();
3246        assert_eq!(result.termination, Termination::GroundHit);
3247        let landing = result.event(EventKind::GroundHit).unwrap().sample;
3248        assert!(
3249            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
3250            "{} vs {terminal_m_s}",
3251            landing.vertical_speed_m_s
3252        );
3253    }
3254
3255    #[test]
3256    fn the_tumble_model_against_its_own_drop_tests() {
3257        // The tumbling constants were fitted to the five models of the OpenRocket technical
3258        // documentation's Table 3.3 (printed page 54), dropped 22 m at ρ = 1.31 kg/m³ with the
3259        // terminal velocity read off the video to ±0.3 m/s. Replaying them through hpr's reading
3260        // of the model (`1.42 · eff(n) · A_1fin + 0.56 · d · l`, with one fin's area the
3261        // trapezoid `(C_r + C_t) s/2`) is the only independent check of it available, and it
3262        // does **not** reproduce the documentation's claim of 3 to 14%.
3263        let rho = 1.31;
3264        // (model, fins, root chord, tip chord, span, diameter, body length, mass, measured v0)
3265        let models = [
3266            (
3267                "#1", 3usize, 0.070, 0.040, 0.060, 0.044, 0.108, 18.0e-3, 5.6,
3268            ),
3269            ("#2", 4, 0.070, 0.040, 0.060, 0.044, 0.108, 22.0e-3, 6.3),
3270            ("#3", 3, 0.200, 0.140, 0.130, 0.103, 0.290, 160.0e-3, 6.6),
3271            ("#4", 0, 0.0, 0.0, 0.0, 0.044, 0.100, 6.8e-3, 5.4),
3272            ("#5", 4, 0.085, 0.085, 0.050, 0.0, 0.0, 11.5e-3, 5.0),
3273        ];
3274        let mut report = String::new();
3275        let mut worst: f64 = 0.0;
3276        let mut errors = Vec::new();
3277        for (name, fins, root_m, tip_m, span_m, diameter_m, body_m, mass_kg, measured_m_s) in models
3278        {
3279            let fin_area_m2 = if fins == 0 {
3280                0.0
3281            } else {
3282                let one_m2 = 0.5 * (root_m + tip_m) * span_m;
3283                one_m2 * TUMBLE_FIN_EFFICIENCY[fins - 1]
3284            };
3285            let body_profile_m2 = diameter_m * body_m;
3286            let drag_area_m2 = TUMBLE_FIN_DRAG_COEFFICIENT * fin_area_m2
3287                + TUMBLE_BODY_DRAG_COEFFICIENT * body_profile_m2;
3288            let predicted_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, rho, G);
3289            let error = predicted_m_s / measured_m_s - 1.0;
3290            worst = worst.max(error.abs());
3291            errors.push(error);
3292            report.push_str(&format!(
3293                "{name}: measured {measured_m_s:.1} m/s, hpr {predicted_m_s:.2} ({:+.1}%)\n",
3294                100.0 * error
3295            ));
3296        }
3297        eprintln!("{report}");
3298        // The spread is −10 to +19%, not the 3 to 14% the documentation claims for its own fit,
3299        // and the finless model is the outlier: it wants a body coefficient near 0.79 where the
3300        // model says 0.56. Either hpr's reading of the two areas is not the one behind the
3301        // constants (the text pins neither convention) or the claim is not reproducible;
3302        // `docs/physics/recovery.md` prints this table rather than repeating the 3 to 14%.
3303        //
3304        // Every model's error is pinned, not just the worst: a wrong efficiency factor would
3305        // move one of the others while the extreme stayed put.
3306        assert_eq!(
3307            errors
3308                .iter()
3309                .map(|error| format!("{:+.1}", 100.0 * error))
3310                .collect::<Vec<_>>(),
3311            ["-5.8", "-5.4", "-7.2", "+19.0", "-10.0"],
3312            "{report}"
3313        );
3314        assert!(worst < 0.20, "{worst} spread:\n{report}");
3315    }
3316
3317    #[test]
3318    fn tumbling_refuses_an_airframe_the_model_cannot_represent() {
3319        // Tube fins are a large part of a tumbling rocket's broadside area and §3.5 has no factor
3320        // for them, so `tumbling` refuses rather than crediting a bare tube's drag.
3321        let mut rocket = design("rocketpy-valetudo");
3322        let (index, fins) = rocket.stages[0].components[1]
3323            .children
3324            .iter()
3325            .enumerate()
3326            .find_map(|(index, child)| match &child.part {
3327                hpr_design::Part::FinSet(fins) => Some((index, fins.clone())),
3328                _ => None,
3329            })
3330            .expect("Valetudo has a fin set");
3331        rocket.stages[0].components[1].children[index].part =
3332            hpr_design::Part::TubeFinSet(hpr_design::TubeFinSet {
3333                count: 3,
3334                length_m: 0.15,
3335                outer_radius_m: 0.02,
3336                thickness_m: 0.001,
3337                base_angle_rad: 0.0,
3338                material: fins.material.clone(),
3339            });
3340        let assembly = rocket.assemble("example").unwrap();
3341        let error = DeviceDrag::tumbling(&assembly).expect_err("tube fins");
3342        assert!(matches!(error, SimError::Domain { .. }), "{error:?}");
3343        // The unchanged design is fine, so the refusal is about the tube fins and nothing else.
3344        assert!(
3345            DeviceDrag::tumbling(&design("rocketpy-valetudo").assemble("example").unwrap()).is_ok()
3346        );
3347
3348        // Pods: each pod's tube and fins count as the airframe's do, once per pod.
3349        let mut rocket = design("rocketpy-valetudo");
3350        let airframe = &mut rocket.stages[0].components[1];
3351        let fin_set = airframe
3352            .children
3353            .iter()
3354            .find(|c| matches!(c.part, hpr_design::Part::FinSet(_)))
3355            .expect("Valetudo has a fin set")
3356            .clone();
3357        let mut pod_tube = airframe.clone();
3358        pod_tube.id = "pod-tube".to_owned();
3359        pod_tube.auto.clear();
3360        pod_tube.motor_mount = None;
3361        pod_tube.children.clear();
3362        let hpr_design::Part::BodyTube(tube) = &pod_tube.part else {
3363            panic!("Valetudo's airframe is a body tube");
3364        };
3365        let tube_profile_m2 = 2.0 * tube.outer_radius_m * tube.length_m;
3366        let hpr_design::Part::FinSet(fins) = &fin_set.part else {
3367            unreachable!("found as a fin set");
3368        };
3369        // Three fins: Table 3.4's factor 1.50.
3370        let fin_m2 = 1.5 * fins.planform.geometry().unwrap().area_m2;
3371        let mut pod_fins = fin_set.clone();
3372        pod_fins.id = "pod-fins".to_owned();
3373        pod_tube.children.push(pod_fins);
3374        let mut pods = pod_tube.clone();
3375        pods.id = "pods".to_owned();
3376        pods.part = hpr_design::Part::PodSet(hpr_design::PodSet {
3377            count: 2,
3378            radial_offset_m: 0.2,
3379            angle_rad: 0.0,
3380        });
3381        pods.position = Some(hpr_design::Position::Top { aft_offset_m: 0.0 });
3382        pods.children = vec![pod_tube];
3383        pods.overrides = hpr_design::Overrides::default();
3384        airframe.children.push(pods);
3385        let tumble = |rocket: &hpr_design::Rocket| match DeviceDrag::tumbling(
3386            &rocket.assemble("example").unwrap(),
3387        )
3388        .unwrap()
3389        {
3390            DeviceDrag::Tumble {
3391                body_profile_m2,
3392                fin_area_m2,
3393                ..
3394            } => (body_profile_m2, fin_area_m2),
3395            other => panic!("tumbling should build a Tumble: {other:?}"),
3396        };
3397        let (bare_body, bare_fins) = tumble(&design("rocketpy-valetudo"));
3398        let (body, fins) = tumble(&rocket);
3399        assert!(
3400            (body - bare_body - 2.0 * tube_profile_m2).abs() <= 1e-15,
3401            "{body}"
3402        );
3403        assert!((fins - bare_fins - 2.0 * fin_m2).abs() <= 1e-15, "{fins}");
3404        // A pod set that holds nothing adds no drag area.
3405        let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
3406        pods.children.clear();
3407        assert_eq!(
3408            DeviceDrag::tumbling(&rocket.assemble("example").unwrap()).unwrap(),
3409            DeviceDrag::tumbling(&design("rocketpy-valetudo").assemble("example").unwrap())
3410                .unwrap()
3411        );
3412    }
3413
3414    #[test]
3415    fn a_tumbling_body_descends_at_its_cited_terminal_velocity() {
3416        // The OpenRocket technical documentation's tumbling model, §3.5: the drag area is
3417        // `1.42 A_f + 0.56 A_bt`, with `A_bt` the body's side profile and `A_f` one fin's area
3418        // times the efficiency factor for the fin count. Computed here from Valetudo's own
3419        // geometry, and checked by a flight.
3420        let air = UniformAir::sea_level();
3421        let rocket = design("rocketpy-valetudo");
3422        let assembly = rocket.assemble("example").unwrap();
3423        let drag = DeviceDrag::tumbling(&assembly).unwrap();
3424        let DeviceDrag::Tumble {
3425            drag_area_m2,
3426            body_profile_m2,
3427            fin_area_m2,
3428        } = drag
3429        else {
3430            panic!("tumbling should build a Tumble: {drag:?}");
3431        };
3432        // Valetudo: a 0.274 m tangent ogive nose of 40.45 mm base radius and 1.884 m of 80.9 mm
3433        // tube. The ogive's arc has radius `ρ = (R² + L²)/(2R)`, so its side area in closed form
3434        // is `L√(ρ² − L²) + ρ² asin(L/ρ) + 2(R − ρ)L` = 0.014842 m², a third more than the
3435        // triangle through its ends; the side profile is that plus 0.0809·1.884 = 0.1673 m².
3436        // Three fins of 0.058 m root, 0.018 m tip and 0.077 m span, so one fin is 2.93e-3 m² and
3437        // the three-fin factor is 1.50.
3438        let expected_fin_m2 = 1.5
3439            * match &assembly
3440                .layout
3441                .components
3442                .iter()
3443                .find(|c| matches!(c.part, hpr_design::Part::FinSet(_)))
3444                .unwrap()
3445                .part
3446            {
3447                hpr_design::Part::FinSet(fins) => fins.planform.geometry().unwrap().area_m2,
3448                _ => unreachable!(),
3449            };
3450        assert!(
3451            (fin_area_m2 - expected_fin_m2).abs() < 1e-12,
3452            "{fin_area_m2}"
3453        );
3454        assert!(
3455            (drag_area_m2 - (1.42 * fin_area_m2 + 0.56 * body_profile_m2)).abs() < 1e-15,
3456            "{drag_area_m2}"
3457        );
3458        let (nose_m, base_m) = (0.274_f64, 0.040_45_f64);
3459        let arc_m = (base_m * base_m + nose_m * nose_m) / (2.0 * base_m);
3460        let ogive_m2 = nose_m * (arc_m * arc_m - nose_m * nose_m).sqrt()
3461            + arc_m * arc_m * (nose_m / arc_m).asin()
3462            + 2.0 * (base_m - arc_m) * nose_m;
3463        assert!((ogive_m2 - 0.014_842).abs() < 5e-7, "{ogive_m2}");
3464        assert!(
3465            (body_profile_m2 - (ogive_m2 + 0.080_9 * 1.884)).abs() < 1e-12,
3466            "{body_profile_m2}"
3467        );
3468
3469        let sim = flight(
3470            analytic_environment(air, G),
3471            vec![open_at_start(drag)],
3472            3600.0,
3473        );
3474        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
3475        let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, air.0.density_kg_m3, G);
3476        // Tumbling is slower than a ballistic dive but far faster than a canopy: 36.38 m/s for
3477        // this 8.3 kg rocket, well outside the 6.8 to 160 g the constants were fitted on. Its
3478        // nose's end diameters alone gave 36.77 m/s, before the side area was integrated.
3479        assert!((terminal_m_s - 36.38).abs() < 0.005, "{terminal_m_s}");
3480        let result = sim
3481            .run_free(START_S, dropped(&sim, 4_000.0, DVec3::ZERO), &mut ())
3482            .unwrap();
3483        assert_eq!(result.termination, Termination::GroundHit);
3484        let landing = result.event(EventKind::GroundHit).unwrap().sample;
3485        assert!(
3486            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
3487            "{} vs {terminal_m_s}",
3488            landing.vertical_speed_m_s
3489        );
3490    }
3491
3492    /// The two-stage test design, whose booster and sustainer each carry a motor.
3493    fn two_stage() -> hpr_design::Rocket {
3494        design("synthetic-two-stage-75mm-54mm")
3495    }
3496
3497    /// That design flown with `devices` and a separation, from a vertical rail.
3498    fn staged_flight(
3499        environment: Environment,
3500        devices: Vec<Device>,
3501        separation: Separation,
3502    ) -> Simulation {
3503        Simulation::new(
3504            &two_stage(),
3505            "j760-i175",
3506            environment,
3507            Rail::vertical(6.0),
3508            FlightSettings {
3509                max_time_s: 3600.0,
3510                ..FlightSettings::default()
3511            },
3512        )
3513        .unwrap()
3514        .with_recovery(devices)
3515        .unwrap()
3516        .with_separation(separation)
3517        .unwrap()
3518    }
3519
3520    #[test]
3521    fn a_separation_lands_every_body_and_the_masses_add_up() {
3522        // The stack comes apart at apogee: the sustainer descends under a canopy, the booster
3523        // tumbles. Both have to reach the ground, each at its own terminal speed, and their
3524        // masses have to add up to the whole rocket's.
3525        let air = UniformAir::sea_level();
3526        let assembly = two_stage().assemble("j760-i175").unwrap();
3527        // The booster tumbles on its own stage's geometry, not the whole stack's.
3528        let tumble = DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap();
3529        let devices = vec![
3530            Device::new(
3531                "sustainer main",
3532                DeviceDrag::canopy(CanopyType::FlatCircular, 1.8),
3533                Trigger::Altitude {
3534                    height_above_ground_m: 1_500.0,
3535                },
3536            ),
3537            Device::new(
3538                "booster tumble",
3539                tumble,
3540                Trigger::Altitude {
3541                    height_above_ground_m: 1_500.0,
3542                },
3543            )
3544            .on_body(1),
3545        ];
3546        let sim = staged_flight(
3547            analytic_environment(air, G),
3548            devices,
3549            Separation::new(Trigger::Apogee, 0),
3550        );
3551        // From just past apogee: the ascent is not what this test is about.
3552        let start = dropped(&sim, 2_000.0, DVec3::new(0.0, 0.0, -0.5));
3553        let result = sim.run_free(START_S, start, &mut ()).unwrap();
3554        assert_eq!(result.termination, Termination::Separated);
3555        assert!(result.event(EventKind::Separation).is_some());
3556        assert_eq!(result.bodies.len(), 2, "{:?}", result.bodies.len());
3557
3558        // The bodies' masses add up to the rocket's at the separation, and each is a real share.
3559        let separation = result.event(EventKind::Separation).unwrap().sample;
3560        let whole_kg = sim.assembly().mass_properties(separation.time_s).mass_kg;
3561        let sum_kg: f64 = result.bodies.iter().map(|body| body.mass_kg).sum();
3562        assert!(
3563            (sum_kg - whole_kg).abs() < 1e-12 * whole_kg,
3564            "{sum_kg} vs {whole_kg}"
3565        );
3566        assert_eq!(result.bodies[0].stages, (0, 0));
3567        assert_eq!(result.bodies[1].stages, (1, 1));
3568        for body in &result.bodies {
3569            // Each body is its own stage's structure plus the motor mounted in it, so a swapped
3570            // split or a motor on the wrong stage fails here and not only in the sum.
3571            let layout = &sim.assembly().layout;
3572            let expected_kg = layout.stages[body.stages.0].mass.mass_kg
3573                + sim
3574                    .assembly()
3575                    .motors
3576                    .iter()
3577                    .filter(|motor| motor.stage == body.stages.0)
3578                    .map(|motor| motor.mass_properties(separation.time_s).mass_kg)
3579                    .sum::<f64>();
3580            assert!(
3581                (body.mass_kg - expected_kg).abs() < 1e-12 * expected_kg,
3582                "body {}: {} vs {expected_kg}",
3583                body.body,
3584                body.mass_kg
3585            );
3586        }
3587        // Measured: a 0.550 kg sustainer and a 1.125 kg booster of a 1.675 kg stack.
3588        assert!(
3589            (result.bodies[0].mass_kg - 0.550_344).abs() < 1e-5,
3590            "{}",
3591            result.bodies[0].mass_kg
3592        );
3593        assert!(
3594            (result.bodies[1].mass_kg - 1.124_834).abs() < 1e-5,
3595            "{}",
3596            result.bodies[1].mass_kg
3597        );
3598
3599        // Every body lands, under its own device, at its own terminal speed.
3600        let rho = air.0.density_kg_m3;
3601        for body in &result.bodies {
3602            assert_eq!(
3603                body.termination,
3604                Termination::GroundHit,
3605                "body {}",
3606                body.body
3607            );
3608            let landing = body.event(EventKind::GroundHit).unwrap().sample;
3609            assert!(landing.height_above_ground_m.abs() < 1e-6, "{landing:?}");
3610            assert!(landing.time_s > separation.time_s, "{landing:?}");
3611            let device = body.body;
3612            let drag_area_m2 = sim.recovery()[device].drag.drag_area_m2();
3613            let terminal_m_s = terminal_speed_m_s(body.mass_kg, drag_area_m2, rho, G);
3614            assert!(
3615                (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-3,
3616                "body {}: {} vs {terminal_m_s}",
3617                body.body,
3618                landing.vertical_speed_m_s
3619            );
3620            assert!(
3621                (landing.recovery_drag_area_m2 - drag_area_m2).abs() < 1e-12,
3622                "body {}: {landing:?}",
3623                body.body
3624            );
3625            assert!(body.event(EventKind::Deployment(device)).is_some());
3626        }
3627        // The tumbling booster comes down much faster than the sustainer under its canopy, and
3628        // both descent times are pinned, not just the speeds. Measured: the sustainer lands at
3629        // 729.00 s at 2.114 m/s under its 1.8 m canopy, the booster at 107.51 s at 16.745 m/s.
3630        let landing_of = |body: usize| {
3631            result.bodies[body]
3632                .event(EventKind::GroundHit)
3633                .unwrap()
3634                .sample
3635        };
3636        let under_canopy = -landing_of(0).vertical_speed_m_s;
3637        let tumbling = -landing_of(1).vertical_speed_m_s;
3638        assert!(
3639            tumbling / under_canopy > 7.5,
3640            "{tumbling} vs {under_canopy}"
3641        );
3642        assert!(
3643            (landing_of(0).time_s - 729.00).abs() < 0.5,
3644            "{}",
3645            landing_of(0).time_s
3646        );
3647        assert!(
3648            (landing_of(1).time_s - 107.51).abs() < 0.2,
3649            "{}",
3650            landing_of(1).time_s
3651        );
3652        assert!(result.bodies_landed(), "{:?}", result.bodies.len());
3653        assert_eq!(result.landings().len(), 2);
3654    }
3655
3656    /// A west wind of `east_m_s` below `below_msl_m` above sea level, and calm above.
3657    #[derive(Debug)]
3658    struct WindBelow {
3659        below_msl_m: f64,
3660        east_m_s: f64,
3661    }
3662
3663    impl hpr_atmos::Wind for WindBelow {
3664        fn wind(&self, height_msl_m: f64) -> Result<hpr_atmos::WindSample, hpr_atmos::AtmosError> {
3665            let east_m_s = if height_msl_m < self.below_msl_m {
3666                self.east_m_s
3667            } else {
3668                0.0
3669            };
3670            Ok(hpr_atmos::WindSample {
3671                velocity_enu_m_s: DVec3::new(east_m_s, 0.0, 0.0),
3672                extrapolated: None,
3673            })
3674        }
3675    }
3676
3677    #[test]
3678    fn a_separated_body_refuses_a_wind_that_is_not_finite() {
3679        // Issue #237: the bodies flown apart after a separation read the wind through their own
3680        // point-mass rates and samples, not the rigid-body step. A wind that isn't finite below
3681        // 1,000 m over the site (2,400 m above sea level) is refused there, by name, with the
3682        // height, as the bodies come down through it under their devices.
3683        let assembly = two_stage().assemble("j760-i175").unwrap();
3684        let tumble = DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap();
3685        let devices = || {
3686            vec![
3687                Device::new(
3688                    "sustainer main",
3689                    DeviceDrag::canopy(CanopyType::FlatCircular, 1.8),
3690                    Trigger::Altitude {
3691                        height_above_ground_m: 1_500.0,
3692                    },
3693                ),
3694                Device::new(
3695                    "booster tumble",
3696                    tumble,
3697                    Trigger::Altitude {
3698                        height_above_ground_m: 1_500.0,
3699                    },
3700                )
3701                .on_body(1),
3702            ]
3703        };
3704        let below_msl_m = crate::testing::site().height_m + 1_000.0;
3705        let fly = |east_m_s: f64| {
3706            let environment =
3707                analytic_environment(UniformAir::sea_level(), G).with_wind(WindBelow {
3708                    below_msl_m,
3709                    east_m_s,
3710                });
3711            let sim = staged_flight(environment, devices(), Separation::new(Trigger::Apogee, 0));
3712            let start = dropped(&sim, 2_000.0, DVec3::new(0.0, 0.0, -0.5));
3713            sim.run_free(START_S, start, &mut ())
3714        };
3715        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
3716            match fly(bad) {
3717                Err(SimError::Domain { what, value }) => {
3718                    assert_eq!(what, crate::environment::WIND_NOT_FINITE, "{bad}");
3719                    // Within a step below the wind's edge.
3720                    assert!(
3721                        value < below_msl_m && value > below_msl_m - 50.0,
3722                        "{bad}: {value}"
3723                    );
3724                }
3725                other => panic!("{bad}: not the wind's refusal: {other:?}"),
3726            }
3727        }
3728        // The same wind, finite, lands both bodies.
3729        let result = fly(5.0).unwrap();
3730        assert_eq!(result.termination, Termination::Separated);
3731        assert!(result.bodies_landed(), "{:?}", result.bodies.len());
3732    }
3733
3734    /// Sea-level air, with field `field` (density, pressure, temperature, speed of sound,
3735    /// viscosity, in that order) set to `value` below `below_msl_m` above sea level.
3736    #[derive(Debug)]
3737    struct AirBelow {
3738        below_msl_m: f64,
3739        field: usize,
3740        value: f64,
3741    }
3742
3743    impl hpr_atmos::Atmosphere for AirBelow {
3744        fn air(&self, height_msl_m: f64) -> Result<hpr_atmos::AirSample, hpr_atmos::AtmosError> {
3745            let mut air = UniformAir::sea_level().0;
3746            if height_msl_m < self.below_msl_m {
3747                *[
3748                    &mut air.density_kg_m3,
3749                    &mut air.pressure_pa,
3750                    &mut air.temperature_k,
3751                    &mut air.speed_of_sound_m_s,
3752                    &mut air.dynamic_viscosity_pa_s,
3753                ]
3754                .into_iter()
3755                .nth(self.field)
3756                .unwrap() = self.value;
3757            }
3758            Ok(hpr_atmos::AirSample {
3759                air,
3760                extrapolated: None,
3761            })
3762        }
3763    }
3764
3765    #[test]
3766    fn a_separated_body_refuses_air_it_cannot_use() {
3767        // Issue #301: the bodies flown apart after a separation read the air through their own
3768        // point-mass rates, not the rigid-body step. Before, a density that was NaN, negative or
3769        // minus infinity turned their drag off, and both landed at about 140 m/s with a
3770        // successful result. Air the flight can't use below 1,000 m over the site (2,400 m above
3771        // sea level) is now refused there, naming the field, with the height, as the bodies come
3772        // down through it under their devices. A zero density or pressure, a vacuum's, is taken.
3773        use crate::environment::{
3774            AIR_DENSITY_REFUSED, AIR_PRESSURE_REFUSED, AIR_SPEED_OF_SOUND_REFUSED,
3775            AIR_TEMPERATURE_REFUSED, AIR_VISCOSITY_REFUSED,
3776        };
3777        let assembly = two_stage().assemble("j760-i175").unwrap();
3778        let tumble = DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap();
3779        let devices = || {
3780            vec![
3781                Device::new(
3782                    "sustainer main",
3783                    DeviceDrag::canopy(CanopyType::FlatCircular, 1.8),
3784                    Trigger::Altitude {
3785                        height_above_ground_m: 1_500.0,
3786                    },
3787                ),
3788                Device::new(
3789                    "booster tumble",
3790                    tumble,
3791                    Trigger::Altitude {
3792                        height_above_ground_m: 1_500.0,
3793                    },
3794                )
3795                .on_body(1),
3796            ]
3797        };
3798        let below_msl_m = crate::testing::site().height_m + 1_000.0;
3799        let fly = |field: usize, value: f64| {
3800            let mut environment = analytic_environment(UniformAir::sea_level(), G);
3801            environment.atmosphere = std::sync::Arc::new(AirBelow {
3802                below_msl_m,
3803                field,
3804                value,
3805            });
3806            let sim = staged_flight(environment, devices(), Separation::new(Trigger::Apogee, 0));
3807            let start = dropped(&sim, 2_000.0, DVec3::new(0.0, 0.0, -0.5));
3808            sim.run_free(START_S, start, &mut ())
3809        };
3810        // Each field, its refusal, and whether a zero is taken.
3811        let fields = [
3812            (AIR_DENSITY_REFUSED, true),
3813            (AIR_PRESSURE_REFUSED, true),
3814            (AIR_TEMPERATURE_REFUSED, false),
3815            (AIR_SPEED_OF_SOUND_REFUSED, false),
3816            (AIR_VISCOSITY_REFUSED, false),
3817        ];
3818        for (field, (refusal, takes_zero)) in fields.into_iter().enumerate() {
3819            let zero = if takes_zero { vec![] } else { vec![0.0] };
3820            for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0]
3821                .into_iter()
3822                .chain(zero)
3823            {
3824                match fly(field, bad) {
3825                    Err(SimError::Domain { what, value }) => {
3826                        assert_eq!(what, refusal, "{field} {bad}");
3827                        // Within a step below the air's edge.
3828                        assert!(
3829                            value < below_msl_m && value > below_msl_m - 50.0,
3830                            "{field} {bad}: {value}"
3831                        );
3832                    }
3833                    other => panic!("{field} {bad}: not the air's refusal: {other:?}"),
3834                }
3835            }
3836            if takes_zero {
3837                let result = fly(field, 0.0).unwrap();
3838                assert_eq!(result.termination, Termination::Separated, "{field}");
3839                assert!(result.bodies_landed(), "{field}");
3840            }
3841        }
3842        // Good air lands both bodies.
3843        let result = fly(0, UniformAir::sea_level().0.density_kg_m3).unwrap();
3844        assert_eq!(result.termination, Termination::Separated);
3845        assert!(result.bodies_landed(), "{:?}", result.bodies.len());
3846    }
3847
3848    #[test]
3849    fn a_separation_conserves_momentum_and_gives_each_body_its_own_start() {
3850        // An ideal separation adds no impulse: each body leaves with the velocity its own center
3851        // of mass already had, so the bodies' momenta add to the stack's.
3852        let air = UniformAir::sea_level();
3853        let assembly = two_stage().assemble("j760-i175").unwrap();
3854        let devices = vec![
3855            Device::new(
3856                "sustainer",
3857                DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
3858                Trigger::Altitude {
3859                    height_above_ground_m: 1_500.0,
3860                },
3861            ),
3862            Device::new(
3863                "booster",
3864                DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
3865                Trigger::Altitude {
3866                    height_above_ground_m: 1_500.0,
3867                },
3868            )
3869            .on_body(1),
3870        ];
3871        let sim = staged_flight(
3872            analytic_wind_environment(air, G, ConstantWind::new(5.0, 0.9).unwrap()),
3873            devices,
3874            Separation::new(Trigger::Apogee, 0),
3875        );
3876        // Separating with a body rate, so that `ω × r` is part of each body's start.
3877        let mut start = dropped(&sim, 2_000.0, DVec3::new(3.0, 0.0, -2.0));
3878        start.body_rate_rad_s = DVec3::new(0.0, 0.6, 0.0);
3879        let result = sim.run_free(START_S, start, &mut ()).unwrap();
3880        let separation = result.event(EventKind::Separation).unwrap().sample;
3881        let whole_kg = sim.assembly().mass_properties(separation.time_s).mass_kg;
3882        let momentum: DVec3 = result
3883            .bodies
3884            .iter()
3885            .map(|body| body.start_sample.cg_velocity_enu_m_s * body.mass_kg)
3886            .sum();
3887        let expected = separation.cg_velocity_enu_m_s * whole_kg;
3888        assert!(
3889            (momentum - expected).length() < 1e-9 * expected.length(),
3890            "{momentum} vs {expected}"
3891        );
3892        // And each body starts where **its own** center of mass was, not the stack's: the two
3893        // are 0.817 m apart on this design.
3894        let state = result.final_sample.state;
3895        for body in &result.bodies {
3896            let lit = vec![Some(0.0); sim.assembly().motors.len()];
3897            let cg_m =
3898                body_mass_properties(sim.assembly(), body.stages, separation.time_s, &lit).cg_m;
3899            let expected = state.point_enu_m(cg_m);
3900            assert!(
3901                (body.start_sample.cg_enu_m - expected).length() < 1e-12,
3902                "body {}: {} vs {expected}",
3903                body.body,
3904                body.start_sample.cg_enu_m
3905            );
3906        }
3907        let gap = (result.bodies[0].start_sample.cg_enu_m - result.bodies[1].start_sample.cg_enu_m)
3908            .length();
3909        assert!((gap - 0.817).abs() < 0.01, "{gap}");
3910    }
3911
3912    #[test]
3913    fn a_body_separated_while_climbing_finds_its_own_apogee() {
3914        // Found in review: a body's system watched only the ground and its own deployment
3915        // heights, so a body that separated while still climbing never saw a descending moment,
3916        // its apogee charge never fired, and it hit the ground in a vacuum at 165 m/s reported as
3917        // an ordinary landing. Both bodies now find their own apogee.
3918        let air = UniformAir::sea_level();
3919        let assembly = two_stage().assemble("j760-i175").unwrap();
3920        let devices = vec![
3921            Device::new(
3922                "sustainer",
3923                DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
3924                Trigger::Apogee,
3925            ),
3926            Device::new(
3927                "booster",
3928                DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
3929                Trigger::Apogee,
3930            )
3931            .on_body(1),
3932        ];
3933        let burnout_s = assembly
3934            .motors
3935            .iter()
3936            .map(|motor| motor.mounted.motor.burnout_time_s())
3937            .fold(0.0, f64::max);
3938        let sim = staged_flight(
3939            analytic_environment(air, G),
3940            devices,
3941            Separation::new(
3942                Trigger::Time {
3943                    time_s: burnout_s + 1.0,
3944                },
3945                0,
3946            ),
3947        );
3948        // Still climbing hard when the stack comes apart.
3949        let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
3950        let result = sim.run_free(burnout_s + 1.0, start, &mut ()).unwrap();
3951        assert_eq!(result.termination, Termination::Separated);
3952        assert!(result.bodies_landed(), "{:?}", result.bodies.len());
3953        let rho = air.0.density_kg_m3;
3954        for body in &result.bodies {
3955            assert!(
3956                body.start_sample.vertical_speed_m_s > 50.0,
3957                "body {} should still be climbing: {:?}",
3958                body.body,
3959                body.start_sample.vertical_speed_m_s
3960            );
3961            // Each body records its own apogee, then fires its charge and opens.
3962            let apogee = body
3963                .event(EventKind::Apogee)
3964                .unwrap_or_else(|| panic!("body {} found no apogee", body.body))
3965                .sample;
3966            assert!(apogee.vertical_speed_m_s.abs() < 1e-6, "{apogee:?}");
3967            assert!(
3968                apogee.height_above_ground_m > 1_400.0,
3969                "body {}: {:?}",
3970                body.body,
3971                apogee.height_above_ground_m
3972            );
3973            assert!(body.event(EventKind::Deployment(body.body)).is_some());
3974            // And it lands at its own terminal speed, not ballistically.
3975            let drag_area_m2 = sim.recovery()[body.body].drag.drag_area_m2();
3976            let terminal_m_s = terminal_speed_m_s(body.mass_kg, drag_area_m2, rho, G);
3977            let landing = body.event(EventKind::GroundHit).unwrap().sample;
3978            assert!(
3979                (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 0.01,
3980                "body {}: {} vs {terminal_m_s}",
3981                body.body,
3982                landing.vertical_speed_m_s
3983            );
3984        }
3985    }
3986
3987    #[test]
3988    fn the_part_that_keeps_the_nose_has_its_own_opening_shock() {
3989        // #1519: a stack that comes apart with nothing left to burn leaves the part that keeps
3990        // the nose, body 0, to fly on as a point mass. Its opening shock is the drag of its own
3991        // device over its mass, `q C_D S / m` at the opening for a device that opens at once
3992        // (Knacke, NWC TP 6575, p. 5-50, with C_x X_1 = 1), as the stack's is (#1258). Before,
3993        // the summary had none: the stack opened nothing before the split.
3994        let air = UniformAir::sea_level();
3995        let assembly = two_stage().assemble("j760-i175").unwrap();
3996        let burnout_s = assembly
3997            .motors
3998            .iter()
3999            .map(|motor| motor.mounted.motor.burnout_time_s())
4000            .fold(0.0, f64::max);
4001        let split_s = burnout_s + 1.0;
4002        let flight = |devices: Vec<Device>| {
4003            let sim = staged_flight(
4004                analytic_environment(air, G),
4005                devices,
4006                Separation::new(Trigger::Time { time_s: split_s }, 0),
4007            );
4008            let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4009            let mut metrics = crate::metrics::FlightMetrics::new();
4010            let result = sim.run_free(split_s, start, &mut metrics).unwrap();
4011            let summary = metrics.summary(&result, sim.environment()).unwrap();
4012            (result, summary)
4013        };
4014        // Each body's own apogee, from a flight whose devices open there.
4015        let (scouted, _) = flight(vec![
4016            Device::new(
4017                "nose part",
4018                DeviceDrag::DragArea { cd_s_m2: 0.3 },
4019                Trigger::Apogee,
4020            ),
4021            Device::new(
4022                "aft part",
4023                DeviceDrag::DragArea { cd_s_m2: 1.0 },
4024                Trigger::Apogee,
4025            )
4026            .on_body(1),
4027        ]);
4028        let apogee_s = |body: usize| {
4029            let flown = scouted.bodies.iter().find(|b| b.body == body).unwrap();
4030            flown.event(EventKind::Apogee).unwrap().sample.time_s
4031        };
4032        // Each opens falling fast: the nose part 5 s past its apogee, the aft part 8 s past its
4033        // own under a larger device, so its shock is the larger and must not be taken.
4034        let cd_s_m2 = [0.3, 1.0];
4035        let (result, summary) = flight(vec![
4036            Device::new(
4037                "nose part",
4038                DeviceDrag::DragArea {
4039                    cd_s_m2: cd_s_m2[0],
4040                },
4041                Trigger::Time {
4042                    time_s: apogee_s(0) + 5.0,
4043                },
4044            ),
4045            Device::new(
4046                "aft part",
4047                DeviceDrag::DragArea {
4048                    cd_s_m2: cd_s_m2[1],
4049                },
4050                Trigger::Time {
4051                    time_s: apogee_s(1) + 8.0,
4052                },
4053            )
4054            .on_body(1),
4055        ]);
4056        assert_eq!(result.termination, Termination::Separated);
4057        assert!(result.bodies_landed());
4058        // The stack itself opened nothing: what the summary has is body 0's.
4059        assert!(
4060            !result
4061                .events
4062                .iter()
4063                .any(|event| matches!(event.kind, EventKind::Deployment(_)))
4064        );
4065        let rho = air.0.density_kg_m3;
4066        let opening = |body: usize| {
4067            let flown = result.bodies.iter().find(|b| b.body == body).unwrap();
4068            let deployed = flown.event(EventKind::Deployment(body)).unwrap().sample;
4069            assert!(deployed.vertical_speed_m_s < -40.0, "{deployed:?}");
4070            let q_pa = 0.5 * rho * deployed.airspeed_m_s.powi(2);
4071            (q_pa * cd_s_m2[body] / deployed.mass_kg, deployed)
4072        };
4073        let (nose_per_kg, deployed) = opening(0);
4074        let (aft_per_kg, _) = opening(1);
4075        assert!(
4076            aft_per_kg > 1.5 * nose_per_kg,
4077            "{aft_per_kg} vs {nose_per_kg}"
4078        );
4079        let shock = summary.max_descent_acceleration_m_s2.unwrap();
4080        assert!(
4081            (shock.value / nose_per_kg - 1.0).abs() < 1e-9,
4082            "{} vs {nose_per_kg}",
4083            shock.value
4084        );
4085        assert_eq!(shock.time_s, deployed.time_s);
4086        assert_eq!(shock.height_above_ground_m, deployed.height_above_ground_m);
4087        // #1532: each body has its own figure too. Body 0's is the flight's here; the part
4088        // dropped aft has `q C_D S / m` over its own mass, where and when its own device opened.
4089        let own = &summary.body_max_descent_acceleration_m_s2;
4090        assert_eq!(own.iter().map(|peak| peak.body).collect::<Vec<_>>(), [0, 1]);
4091        assert_eq!(
4092            (own[0].value, own[0].time_s, own[0].height_above_ground_m),
4093            (shock.value, shock.time_s, shock.height_above_ground_m)
4094        );
4095        let (_, aft_deployed) = opening(1);
4096        assert!(
4097            (own[1].value / aft_per_kg - 1.0).abs() < 1e-9,
4098            "{} vs {aft_per_kg}",
4099            own[1].value
4100        );
4101        assert_eq!(own[1].time_s, aft_deployed.time_s);
4102        assert_eq!(
4103            own[1].height_above_ground_m,
4104            aft_deployed.height_above_ground_m
4105        );
4106    }
4107
4108    #[test]
4109    fn a_split_with_an_ejection_keeps_the_lead_pieces_shock_out() {
4110        // #1519: with an ejection at the split, body 0 is the ejection's lead piece, here the
4111        // nose cone alone under its own device, not the part that keeps the nose; its opening
4112        // shock is left out of the summary as its apogee is (ADR-165), though it opens at once
4113        // at 100 m/s.
4114        let air = UniformAir::sea_level();
4115        let assembly = two_stage().assemble("j760-i175").unwrap();
4116        let burnout_s = assembly
4117            .motors
4118            .iter()
4119            .map(|motor| motor.mounted.motor.burnout_time_s())
4120            .fold(0.0, f64::max);
4121        let split_s = burnout_s + 1.0;
4122        let at = Trigger::Time { time_s: split_s };
4123        let devices = vec![
4124            Device::new("nose cone", DeviceDrag::DragArea { cd_s_m2: 0.3 }, at),
4125            Device::new(
4126                "sustainer",
4127                DeviceDrag::DragArea { cd_s_m2: 1.0 },
4128                Trigger::Apogee,
4129            )
4130            .on_body(1),
4131            Device::new(
4132                "booster",
4133                DeviceDrag::DragArea { cd_s_m2: 1.0 },
4134                Trigger::Apogee,
4135            )
4136            .on_body(2),
4137        ];
4138        let sim = staged_flight(
4139            analytic_environment(air, G),
4140            devices,
4141            Separation::new(at, 0),
4142        )
4143        .with_ejections(vec![crate::Ejection::aft_of(at, "nose")])
4144        .unwrap();
4145        let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4146        let mut metrics = crate::metrics::FlightMetrics::new();
4147        let result = sim.run_free(split_s, start, &mut metrics).unwrap();
4148        assert_eq!(result.termination, Termination::Separated);
4149        assert!(result.event(EventKind::Separation).is_some());
4150        let opened = result.event(EventKind::Deployment(0)).unwrap().sample;
4151        assert_eq!(
4152            opened.time_s,
4153            result.event(EventKind::Ejection(0)).unwrap().sample.time_s
4154        );
4155        assert!(opened.airspeed_m_s > 50.0, "{opened:?}");
4156        let summary = metrics.summary(&result, sim.environment()).unwrap();
4157        assert_eq!(summary.max_descent_acceleration_m_s2, None);
4158    }
4159
4160    #[test]
4161    fn the_nose_parts_shock_stops_counting_where_an_ejection_parts_it() {
4162        // #1519, found in review: after the split, the part that keeps the nose opens a drogue,
4163        // then pushes off its nose cone under the cone's own canopy. From the ejection on, body 0
4164        // is the nose cone alone, whose far larger shock is left out: the flight's is the
4165        // drogue's, `q C_D S / m` at its opening on the whole part.
4166        let air = UniformAir::sea_level();
4167        let assembly = two_stage().assemble("j760-i175").unwrap();
4168        let burnout_s = assembly
4169            .motors
4170            .iter()
4171            .map(|motor| motor.mounted.motor.burnout_time_s())
4172            .fold(0.0, f64::max);
4173        let split_s = burnout_s + 1.0;
4174        let charge = Trigger::Time {
4175            time_s: split_s + 15.0,
4176        };
4177        let drogue_m2 = 0.05;
4178        let devices = vec![
4179            Device::new(
4180                "drogue",
4181                DeviceDrag::DragArea { cd_s_m2: drogue_m2 },
4182                Trigger::Time {
4183                    time_s: split_s + 12.0,
4184                },
4185            ),
4186            Device::new("nose cone", DeviceDrag::DragArea { cd_s_m2: 0.3 }, charge),
4187            Device::new(
4188                "booster",
4189                DeviceDrag::DragArea { cd_s_m2: 1.0 },
4190                Trigger::Apogee,
4191            )
4192            .on_body(1),
4193            Device::new("airframe", DeviceDrag::DragArea { cd_s_m2: 1.0 }, charge).on_body(2),
4194        ];
4195        let sim = staged_flight(
4196            analytic_environment(air, G),
4197            devices,
4198            Separation::new(Trigger::Time { time_s: split_s }, 0),
4199        )
4200        .with_ejections(vec![crate::Ejection::aft_of(charge, "nose")])
4201        .unwrap();
4202        let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4203        let mut metrics = crate::metrics::FlightMetrics::new();
4204        let result = sim.run_free(split_s, start, &mut metrics).unwrap();
4205        assert_eq!(result.termination, Termination::Separated);
4206        // The stack only split; the ejection is body 0's own, after the drogue opened.
4207        assert!(
4208            !result
4209                .events
4210                .iter()
4211                .any(|event| matches!(event.kind, EventKind::Ejection(_)))
4212        );
4213        let nose = result.bodies.iter().find(|body| body.body == 0).unwrap();
4214        let drogue = nose.event(EventKind::Deployment(0)).unwrap().sample;
4215        let ejected = nose.event(EventKind::Ejection(0)).unwrap().sample;
4216        let cone = nose.event(EventKind::Deployment(1)).unwrap().sample;
4217        assert!(drogue.time_s < ejected.time_s);
4218        assert!(drogue.vertical_speed_m_s < 0.0, "{drogue:?}");
4219        let rho = air.0.density_kg_m3;
4220        let per_kg = |sample: &BodySample, cd_s_m2: f64| {
4221            0.5 * rho * sample.airspeed_m_s.powi(2) * cd_s_m2 / sample.mass_kg
4222        };
4223        let drogue_per_kg = per_kg(&drogue, drogue_m2);
4224        // The nose cone alone, much lighter, under its canopy (the samples at the charge are
4225        // the whole part's, taken as it fires): what must not be taken.
4226        let cone_kg = nose.final_sample.mass_kg;
4227        assert!(cone_kg < 0.5 * drogue.mass_kg, "{cone_kg} {drogue:?}");
4228        let cone_per_kg = per_kg(&cone, 0.3) * cone.mass_kg / cone_kg;
4229        assert!(
4230            cone_per_kg > 5.0 * drogue_per_kg,
4231            "{cone_per_kg} {drogue_per_kg}"
4232        );
4233        let summary = metrics.summary(&result, sim.environment()).unwrap();
4234        let shock = summary.max_descent_acceleration_m_s2.unwrap();
4235        assert!(
4236            (shock.value / drogue_per_kg - 1.0).abs() < 1e-9,
4237            "{} vs {drogue_per_kg}",
4238            shock.value
4239        );
4240        assert_eq!(shock.time_s, drogue.time_s);
4241        // #1532: each body's own figure. Body 0 keeps its number through the charge, so its own
4242        // is the larger of the drogue's on the whole part and, after it, the cone's: the drogue
4243        // and the cone's canopy together on the cone alone, over the cone's mass, not the
4244        // heavier part's from before.
4245        let own = &summary.body_max_descent_acceleration_m_s2;
4246        assert_eq!(
4247            own.iter().map(|peak| peak.body).collect::<Vec<_>>(),
4248            [0, 1, 2]
4249        );
4250        let cone_own_per_kg = per_kg(&cone, drogue_m2 + 0.3) * cone.mass_kg / cone_kg;
4251        assert!(
4252            (own[0].value / cone_own_per_kg - 1.0).abs() < 1e-9,
4253            "{} vs {cone_own_per_kg}",
4254            own[0].value
4255        );
4256        assert_eq!(own[0].time_s, ejected.time_s);
4257        // The airframe behind the parted joint, body 2, opens its canopy as it starts flying on
4258        // its own: `q C_D S / m` there, over its own mass.
4259        let airframe = result.bodies.iter().find(|body| body.body == 2).unwrap();
4260        let start = airframe.start_sample;
4261        assert_eq!(start.time_s, ejected.time_s);
4262        assert!(start.mass_kg < drogue.mass_kg - cone_kg + 1e-9, "{start:?}");
4263        let airframe_per_kg = per_kg(&start, 1.0);
4264        assert!(airframe_per_kg > 5.0 * G, "{airframe_per_kg}");
4265        assert!(
4266            (own[2].value / airframe_per_kg - 1.0).abs() < 1e-9,
4267            "{} vs {airframe_per_kg}",
4268            own[2].value
4269        );
4270        assert_eq!(own[2].time_s, start.time_s);
4271        assert_eq!(own[2].height_above_ground_m, start.height_above_ground_m);
4272        // The booster opens at its own apogee, at rest in the air, and only speeds up to its
4273        // steady fall: its figure is that fall's, one g.
4274        assert!((own[1].value / G - 1.0).abs() < 0.01, "{}", own[1].value);
4275    }
4276
4277    #[test]
4278    fn an_ejection_in_the_part_dropped_aft_leaves_the_flights_shock_alone() {
4279        // #1532, asked in #1530's review: after the split the part dropped aft, body 1, parts at
4280        // a charge of its own: the interstage ahead of the joint keeps the number, and the
4281        // booster's airframe behind it is body 2. Each opens a canopy at once, falling fast.
4282        // Neither is the part that keeps the nose, so the flight's opening shock is what it is
4283        // without the charge, body 0's own; each piece has its own figure, `q C_D S / m` over
4284        // its own mass.
4285        let air = UniformAir::sea_level();
4286        let assembly = two_stage().assemble("j760-i175").unwrap();
4287        let burnout_s = assembly
4288            .motors
4289            .iter()
4290            .map(|motor| motor.mounted.motor.burnout_time_s())
4291            .fold(0.0, f64::max);
4292        let split_s = burnout_s + 1.0;
4293        let charge = Trigger::Time {
4294            time_s: split_s + 15.0,
4295        };
4296        let (nose_m2, interstage_m2, airframe_m2) = (0.3, 0.5, 1.0);
4297        let flight = |parted: bool| {
4298            let mut devices = vec![
4299                Device::new(
4300                    "nose part",
4301                    DeviceDrag::DragArea { cd_s_m2: nose_m2 },
4302                    charge,
4303                ),
4304                Device::new(
4305                    "interstage",
4306                    DeviceDrag::DragArea {
4307                        cd_s_m2: interstage_m2,
4308                    },
4309                    charge,
4310                )
4311                .on_body(1),
4312            ];
4313            let mut ejections = Vec::new();
4314            if parted {
4315                devices.push(
4316                    Device::new(
4317                        "booster airframe",
4318                        DeviceDrag::DragArea {
4319                            cd_s_m2: airframe_m2,
4320                        },
4321                        charge,
4322                    )
4323                    .on_body(2),
4324                );
4325                ejections.push(crate::Ejection::aft_of(charge, "interstage"));
4326            }
4327            let sim = staged_flight(
4328                analytic_environment(air, G),
4329                devices,
4330                Separation::new(Trigger::Time { time_s: split_s }, 0),
4331            )
4332            .with_ejections(ejections)
4333            .unwrap();
4334            let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4335            let mut metrics = crate::metrics::FlightMetrics::new();
4336            let result = sim.run_free(split_s, start, &mut metrics).unwrap();
4337            assert_eq!(result.termination, Termination::Separated);
4338            assert!(result.bodies_landed());
4339            let summary = metrics.summary(&result, sim.environment()).unwrap();
4340            (result, summary)
4341        };
4342        let (whole, whole_summary) = flight(false);
4343        let (result, summary) = flight(true);
4344        assert_eq!(whole.bodies.len(), 2);
4345        assert_eq!(result.bodies.len(), 3);
4346        let body = |body: usize| result.bodies.iter().find(|b| b.body == body).unwrap();
4347        // The charge is the aft part's own, not the stack's and not body 0's.
4348        let ejection = |event: &EventKind| matches!(event, EventKind::Ejection(_));
4349        assert!(!result.events.iter().any(|event| ejection(&event.kind)));
4350        assert!(!body(0).events.iter().any(|event| ejection(&event.kind)));
4351        let ejected = body(1)
4352            .events
4353            .iter()
4354            .find(|event| ejection(&event.kind))
4355            .unwrap();
4356        let rho = air.0.density_kg_m3;
4357        let per_kg = |sample: &BodySample, cd_s_m2: f64, mass_kg: f64| {
4358            0.5 * rho * sample.airspeed_m_s.powi(2) * cd_s_m2 / mass_kg
4359        };
4360        // The flight's: body 0's, the same to the bit with the charge and without.
4361        let opened = body(0).event(EventKind::Deployment(0)).unwrap().sample;
4362        assert!(opened.vertical_speed_m_s < -40.0, "{opened:?}");
4363        let nose_per_kg = per_kg(&opened, nose_m2, opened.mass_kg);
4364        let shock = summary.max_descent_acceleration_m_s2.unwrap();
4365        assert!(
4366            (shock.value / nose_per_kg - 1.0).abs() < 1e-9,
4367            "{} vs {nose_per_kg}",
4368            shock.value
4369        );
4370        assert_eq!(
4371            summary.max_descent_acceleration_m_s2,
4372            whole_summary.max_descent_acceleration_m_s2
4373        );
4374        // Each piece's own: the interstage alone, far lighter than the part it left (the sample
4375        // at the charge is the whole part's, taken as it fires), and the airframe behind it.
4376        let own = &summary.body_max_descent_acceleration_m_s2;
4377        assert_eq!(
4378            own.iter().map(|peak| peak.body).collect::<Vec<_>>(),
4379            [0, 1, 2]
4380        );
4381        assert_eq!(own[0].value, shock.value);
4382        let interstage_kg = body(1).final_sample.mass_kg;
4383        let airframe = body(2).start_sample;
4384        assert!(
4385            (interstage_kg + airframe.mass_kg - ejected.sample.mass_kg).abs() < 1e-9,
4386            "{interstage_kg} + {} vs {}",
4387            airframe.mass_kg,
4388            ejected.sample.mass_kg
4389        );
4390        let interstage_per_kg = per_kg(&ejected.sample, interstage_m2, interstage_kg);
4391        let airframe_per_kg = per_kg(&airframe, airframe_m2, airframe.mass_kg);
4392        for (peak, per_kg) in [(own[1], interstage_per_kg), (own[2], airframe_per_kg)] {
4393            // Either would have raised the flight's figure had it counted.
4394            assert!(per_kg > 1.5 * shock.value, "{per_kg} vs {}", shock.value);
4395            assert!(
4396                (peak.value / per_kg - 1.0).abs() < 1e-9,
4397                "body {}: {} vs {per_kg}",
4398                peak.body,
4399                peak.value
4400            );
4401            assert_eq!(peak.time_s, ejected.sample.time_s);
4402        }
4403        // Without the charge the whole aft part hangs from the interstage's canopy: one figure,
4404        // over the whole part's mass.
4405        let whole_own = &whole_summary.body_max_descent_acceleration_m_s2;
4406        assert_eq!(
4407            whole_own.iter().map(|peak| peak.body).collect::<Vec<_>>(),
4408            [0, 1]
4409        );
4410        let whole_per_kg = per_kg(&ejected.sample, interstage_m2, ejected.sample.mass_kg);
4411        assert!(
4412            (whole_own[1].value / whole_per_kg - 1.0).abs() < 1e-9,
4413            "{} vs {whole_per_kg}",
4414            whole_own[1].value
4415        );
4416    }
4417
4418    #[test]
4419    fn a_nose_cone_ejected_on_the_climb_after_a_split_leaves_the_summary_no_apogee() {
4420        // #1531: after the split, the part that keeps the nose pushes off its nose cone. From
4421        // that charge on, body 0 is the nose cone alone, so an apogee body 0 reaches after it is
4422        // the cone's, under its own canopy, not the rocket's: the summary has none, as it has
4423        // none when an ejection parts the stack itself on the climb (ADR-165). An apogee the
4424        // part reaches whole, at the charge or before it, stays the flight's.
4425        let air = UniformAir::sea_level();
4426        let assembly = two_stage().assemble("j760-i175").unwrap();
4427        let burnout_s = assembly
4428            .motors
4429            .iter()
4430            .map(|motor| motor.mounted.motor.burnout_time_s())
4431            .fold(0.0, f64::max);
4432        let split_s = burnout_s + 1.0;
4433        let flight = |charge: Option<Trigger>| {
4434            let fires = charge.unwrap_or(Trigger::Apogee);
4435            let devices = vec![
4436                Device::new("nose cone", DeviceDrag::DragArea { cd_s_m2: 0.3 }, fires),
4437                Device::new(
4438                    "booster",
4439                    DeviceDrag::DragArea { cd_s_m2: 1.0 },
4440                    Trigger::Apogee,
4441                )
4442                .on_body(1),
4443                Device::new("airframe", DeviceDrag::DragArea { cd_s_m2: 1.0 }, fires).on_body(2),
4444            ];
4445            let sim = staged_flight(
4446                analytic_environment(air, G),
4447                // With no charge the part comes down whole: its third device has no body.
4448                devices
4449                    .into_iter()
4450                    .take(if charge.is_some() { 3 } else { 2 })
4451                    .collect(),
4452                Separation::new(Trigger::Time { time_s: split_s }, 0),
4453            );
4454            let sim = match charge {
4455                Some(charge) => sim
4456                    .with_ejections(vec![crate::Ejection::aft_of(charge, "nose")])
4457                    .unwrap(),
4458                None => sim,
4459            };
4460            let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4461            let mut metrics = crate::metrics::FlightMetrics::new();
4462            let result = sim.run_free(split_s, start, &mut metrics).unwrap();
4463            assert_eq!(result.termination, Termination::Separated);
4464            // The stack only split, on its way up: an ejection is body 0's own.
4465            assert!(result.event(EventKind::Apogee).is_none());
4466            assert!(
4467                !result
4468                    .events
4469                    .iter()
4470                    .any(|event| matches!(event.kind, EventKind::Ejection(_)))
4471            );
4472            let summary = metrics.summary(&result, sim.environment()).unwrap();
4473            let nose = result.bodies.iter().find(|body| body.body == 0).unwrap();
4474            let apogee = nose.event(EventKind::Apogee).unwrap().sample;
4475            let ejected = nose.event(EventKind::Ejection(0)).map(|event| event.sample);
4476            (summary, apogee, ejected)
4477        };
4478        // The part that keeps the nose, whole to its apogee: the flight's apogee.
4479        let (whole_summary, whole, none) = flight(None);
4480        assert!(none.is_none());
4481        let whole_apogee = whole_summary.apogee.unwrap();
4482        assert_eq!(whole_apogee.time_s, whole.time_s);
4483        assert_eq!(
4484            whole_apogee.height_above_ground_m,
4485            whole.height_above_ground_m
4486        );
4487
4488        // The charge fires 5 s after the split, the part still climbing fast. The nose cone,
4489        // light under its canopy, stops well short of where the whole part would have coasted.
4490        let (summary, cone, ejected) = flight(Some(Trigger::Time {
4491            time_s: split_s + 5.0,
4492        }));
4493        let ejected = ejected.unwrap();
4494        assert!(ejected.vertical_speed_m_s > 30.0, "{ejected:?}");
4495        assert!(cone.time_s > ejected.time_s, "{cone:?} {ejected:?}");
4496        assert!(
4497            cone.height_above_ground_m < whole.height_above_ground_m - 50.0,
4498            "{} vs {}",
4499            cone.height_above_ground_m,
4500            whole.height_above_ground_m
4501        );
4502        assert_eq!(summary.apogee, None);
4503
4504        // A charge at the part's own apogee, or 3 s after it, parts it once it has peaked: the
4505        // apogee is the whole part's, the same as with no charge.
4506        for charge in [
4507            Trigger::Apogee,
4508            Trigger::Time {
4509                time_s: whole.time_s + 3.0,
4510            },
4511        ] {
4512            let (summary, apogee, ejected) = flight(Some(charge));
4513            let ejected = ejected.unwrap();
4514            assert!(ejected.time_s >= apogee.time_s, "{charge:?}");
4515            assert_eq!(apogee.time_s, whole.time_s, "{charge:?}");
4516            assert_eq!(summary.apogee, whole_summary.apogee, "{charge:?}");
4517        }
4518    }
4519
4520    #[test]
4521    fn the_nose_parts_kept_peaks_are_a_running_maximum_with_the_same_shock() {
4522        // #1533: the watcher keeps a step's peak for the part that keeps the nose only when it
4523        // beats the last one kept, not one for every step under a device. The summary's shock,
4524        // its time and its height are the same as from every step's peak, on three flights
4525        // built like the separation tests': a device opening at once, a drogue then a nose cone
4526        // pushed off (the count cut at the charge), and a canopy filling in a crosswind.
4527        /// Every step's peak for body 0 under a device, with the step's start, none dropped.
4528        #[derive(Default)]
4529        struct Every(Vec<(f64, crate::metrics::Peak)>);
4530        impl crate::recorder::Observer for Every {
4531            fn body_step(
4532                &mut self,
4533                body: usize,
4534                step: &dyn crate::recorder::BodyStep,
4535            ) -> Result<(), crate::SimError> {
4536                if body == 0 {
4537                    let peak = crate::metrics::body_step_peak(step)?;
4538                    if peak.value > 0.0 || peak.value.is_nan() {
4539                        self.0.push((step.start_s(), peak));
4540                    }
4541                }
4542                Ok(())
4543            }
4544        }
4545        let air = UniformAir::sea_level();
4546        let assembly = two_stage().assemble("j760-i175").unwrap();
4547        let burnout_s = assembly
4548            .motors
4549            .iter()
4550            .map(|motor| motor.mounted.motor.burnout_time_s())
4551            .fold(0.0, f64::max);
4552        let split_s = burnout_s + 1.0;
4553        let split = || Separation::new(Trigger::Time { time_s: split_s }, 0);
4554        let aft = || {
4555            Device::new(
4556                "aft part",
4557                DeviceDrag::DragArea { cd_s_m2: 1.0 },
4558                Trigger::Apogee,
4559            )
4560            .on_body(1)
4561        };
4562        let charge = Trigger::Time {
4563            time_s: split_s + 15.0,
4564        };
4565        let late = Trigger::Time {
4566            time_s: split_s + 16.0,
4567        };
4568        let flights = [
4569            // Opens at once, falling: the first step under it is the largest.
4570            staged_flight(
4571                analytic_environment(air, G),
4572                vec![
4573                    Device::new("nose part", DeviceDrag::DragArea { cd_s_m2: 0.3 }, late),
4574                    aft(),
4575                ],
4576                split(),
4577            ),
4578            // A drogue, then the nose cone pushed off under its own canopy: larger peaks after
4579            // the charge, which the summary cuts.
4580            staged_flight(
4581                analytic_environment(air, G),
4582                vec![
4583                    Device::new(
4584                        "drogue",
4585                        DeviceDrag::DragArea { cd_s_m2: 0.05 },
4586                        Trigger::Time {
4587                            time_s: split_s + 12.0,
4588                        },
4589                    ),
4590                    Device::new("nose cone", DeviceDrag::DragArea { cd_s_m2: 0.3 }, charge),
4591                    aft(),
4592                    Device::new("airframe", DeviceDrag::DragArea { cd_s_m2: 1.0 }, charge)
4593                        .on_body(2),
4594                ],
4595                split(),
4596            )
4597            .with_ejections(vec![crate::Ejection::aft_of(charge, "nose")])
4598            .unwrap(),
4599            // A canopy filling over a second: the load rises through several steps.
4600            staged_flight(
4601                analytic_wind_environment(air, G, ConstantWind::new(8.0, 1.5).unwrap()),
4602                vec![
4603                    Device::new("nose part", DeviceDrag::DragArea { cd_s_m2: 0.3 }, late)
4604                        .with_inflation(Inflation::FillingTime {
4605                            time_s: 1.0,
4606                            exponent: 2.0,
4607                        }),
4608                    aft(),
4609                ],
4610                split(),
4611            ),
4612        ];
4613        let mut cut = 0;
4614        for (i, sim) in flights.iter().enumerate() {
4615            let start = dropped(sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4616            let mut metrics = crate::metrics::FlightMetrics::new();
4617            let mut every = Every::default();
4618            let result = sim
4619                .run_free(split_s, start, &mut (&mut metrics, &mut every))
4620                .unwrap();
4621            assert_eq!(result.termination, Termination::Separated, "flight {i}");
4622            // The stack opened nothing and parted at no ejection: the shock is body 0's alone.
4623            assert!(!result.events.iter().any(|event| matches!(
4624                event.kind,
4625                EventKind::Deployment(_) | EventKind::Ejection(_)
4626            )));
4627            let nose = result.bodies.iter().find(|body| body.body == 0).unwrap();
4628            let parted_s = nose
4629                .events
4630                .iter()
4631                .find(|event| matches!(event.kind, EventKind::Ejection(_)))
4632                .map_or(f64::INFINITY, |event| event.sample.time_s);
4633            // The summary's rule over every step's peak: the largest that starts before the
4634            // charge, the first of equals.
4635            let mut by_every: Option<crate::metrics::Peak> = None;
4636            for (start_s, peak) in &every.0 {
4637                if *start_s < parted_s && by_every.is_none_or(|best| peak.value > best.value) {
4638                    by_every = Some(*peak);
4639                }
4640            }
4641            cut += every.0.iter().filter(|(s, _)| *s >= parted_s).count();
4642            let summary = metrics.summary(&result, sim.environment()).unwrap();
4643            let by_every = by_every.unwrap();
4644            assert!(by_every.value > 0.0, "flight {i}");
4645            assert_eq!(
4646                summary.max_descent_acceleration_m_s2,
4647                Some(by_every),
4648                "flight {i}"
4649            );
4650            // Over a hundred steps fly under the device; the kept ones are those where the load
4651            // still rose: one for a device that opens at once, one a step while a canopy fills.
4652            let (kept, all) = (metrics.nose_peaks_kept(), every.0.len());
4653            assert!(all > 100, "flight {i}: {all} steps under a device");
4654            assert!(20 * kept <= all, "flight {i}: {kept} kept of {all}");
4655            if i == 0 {
4656                assert_eq!(kept, 1, "of {all}");
4657            }
4658        }
4659        // The second flight's count is cut: peaks after its charge are among every step's.
4660        assert!(cut > 100, "{cut}");
4661    }
4662
4663    #[test]
4664    fn the_nose_parts_shock_tops_inside_a_step_under_a_filling_canopy() {
4665        // #1519: under a canopy that fills over a time, the nose part's load tops between a
4666        // step's ends, where the growing drag area meets the falling speed. The summary finds the
4667        // top by a search inside the step, as the stack's is found; the step's start, middle and
4668        // end alone read it low, the flattering side. A crosswind keeps the airspeed apart from
4669        // the speed over the ground: the load follows the airspeed.
4670        /// Body 0's load over its mass, by hand from each sample's drag area, airspeed and mass.
4671        struct Scan {
4672            rho: f64,
4673            /// Where the canopy fills, s: the steps scanned finely.
4674            filling_s: (f64, f64),
4675            /// The largest over the steps' starts, middles and ends.
4676            coarse: f64,
4677            /// The largest over those and 2,000 intervals of each step that meets the filling.
4678            fine: f64,
4679            /// The most the step's specific force differs from the hand value, relative (the
4680            /// force itself where nothing is open).
4681            worst_gap: f64,
4682            /// The most the airspeed differs from the speed over the ground under a device,
4683            /// relative.
4684            wind_share: f64,
4685        }
4686        impl crate::recorder::Observer for Scan {
4687            fn body_step(
4688                &mut self,
4689                body: usize,
4690                step: &dyn crate::recorder::BodyStep,
4691            ) -> Result<(), crate::SimError> {
4692                if body != 0 {
4693                    return Ok(());
4694                }
4695                let (a, b) = (step.start_s(), step.end_s());
4696                let fills = a < self.filling_s.1 && b > self.filling_s.0;
4697                let points: u32 = if fills { 2_000 } else { 2 };
4698                for i in 0..=points {
4699                    let t_s = a + (b - a) * f64::from(i) / f64::from(points);
4700                    let sample = step.sample(t_s)?;
4701                    let by_hand =
4702                        0.5 * self.rho * sample.recovery_drag_area_m2 * sample.airspeed_m_s.powi(2)
4703                            / sample.mass_kg;
4704                    let force = step.specific_force_enu_m_s2(t_s)?.length();
4705                    // With nothing open the hand value is zero, and so must the force be.
4706                    let gap = if by_hand > 0.0 {
4707                        (force / by_hand - 1.0).abs()
4708                    } else {
4709                        force
4710                    };
4711                    self.worst_gap = self.worst_gap.max(gap);
4712                    if by_hand > 0.0 {
4713                        let ground_m_s = sample.cg_velocity_enu_m_s.length();
4714                        self.wind_share = self
4715                            .wind_share
4716                            .max((ground_m_s / sample.airspeed_m_s - 1.0).abs());
4717                    }
4718                    self.fine = self.fine.max(by_hand);
4719                    if i % (points / 2) == 0 {
4720                        self.coarse = self.coarse.max(by_hand);
4721                    }
4722                }
4723                Ok(())
4724            }
4725        }
4726        let air = UniformAir::sea_level();
4727        let assembly = two_stage().assemble("j760-i175").unwrap();
4728        let burnout_s = assembly
4729            .motors
4730            .iter()
4731            .map(|motor| motor.mounted.motor.burnout_time_s())
4732            .fold(0.0, f64::max);
4733        let split_s = burnout_s + 1.0;
4734        let fill_s = 1.0;
4735        let flight = |trigger: Trigger, filling_s: (f64, f64)| {
4736            let sim = staged_flight(
4737                analytic_wind_environment(air, G, ConstantWind::new(8.0, 1.5).unwrap()),
4738                vec![
4739                    Device::new("nose part", DeviceDrag::DragArea { cd_s_m2: 0.3 }, trigger)
4740                        .with_inflation(Inflation::FillingTime {
4741                            time_s: fill_s,
4742                            exponent: 2.0,
4743                        }),
4744                    Device::new(
4745                        "aft part",
4746                        DeviceDrag::DragArea { cd_s_m2: 1.0 },
4747                        Trigger::Apogee,
4748                    )
4749                    .on_body(1),
4750                ],
4751                Separation::new(Trigger::Time { time_s: split_s }, 0),
4752            );
4753            let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4754            let mut metrics = crate::metrics::FlightMetrics::new();
4755            let mut scan = Scan {
4756                rho: air.0.density_kg_m3,
4757                filling_s,
4758                coarse: 0.0,
4759                fine: 0.0,
4760                worst_gap: 0.0,
4761                wind_share: 0.0,
4762            };
4763            let result = sim
4764                .run_free(split_s, start, &mut (&mut metrics, &mut scan))
4765                .unwrap();
4766            let summary = metrics.summary(&result, sim.environment()).unwrap();
4767            (result, summary, scan)
4768        };
4769        // The nose part's own apogee, from a flight whose device opens there.
4770        let (scouted, _, _) = flight(Trigger::Apogee, (0.0, 0.0));
4771        let nose = scouted.bodies.iter().find(|b| b.body == 0).unwrap();
4772        let open_s = nose.event(EventKind::Apogee).unwrap().sample.time_s + 5.0;
4773        let (result, summary, scan) =
4774            flight(Trigger::Time { time_s: open_s }, (open_s, open_s + fill_s));
4775        assert_eq!(result.termination, Termination::Separated);
4776        assert!(result.bodies_landed());
4777        let nose = result.bodies.iter().find(|b| b.body == 0).unwrap();
4778        let deployed = nose.event(EventKind::Deployment(0)).unwrap().sample;
4779        assert_eq!(deployed.time_s, open_s);
4780        assert!(deployed.vertical_speed_m_s < -40.0, "{deployed:?}");
4781        // The step's specific force is the hand value everywhere, and the wind is in it: under
4782        // the canopy the airspeed and the speed over the ground differ by more than a tenth.
4783        assert!(scan.worst_gap < 1e-12, "{}", scan.worst_gap);
4784        assert!(scan.wind_share > 0.1, "{}", scan.wind_share);
4785        // The top is inside a step: the steps' starts, middles and ends alone read it low.
4786        assert!(
4787            scan.fine > scan.coarse * (1.0 + 1e-5),
4788            "{} vs {}",
4789            scan.fine,
4790            scan.coarse
4791        );
4792        // The summary's shock is that top: no lower than the fine scan, and no higher than a
4793        // scan's spacing can miss.
4794        let shock = summary.max_descent_acceleration_m_s2.unwrap();
4795        assert!(
4796            shock.value >= scan.fine * (1.0 - 1e-9) && shock.value <= scan.fine * (1.0 + 1e-6),
4797            "{} vs {}",
4798            shock.value,
4799            scan.fine
4800        );
4801        assert!(
4802            shock.time_s > open_s && shock.time_s < open_s + fill_s,
4803            "{} in {open_s} + {fill_s}",
4804            shock.time_s
4805        );
4806        // #1532: body 0's own figure is that top too, not the steps' ends alone, which would
4807        // read it low.
4808        let own = &summary.body_max_descent_acceleration_m_s2;
4809        assert_eq!(own[0].body, 0);
4810        assert_eq!(
4811            (own[0].value, own[0].time_s, own[0].height_above_ground_m),
4812            (shock.value, shock.time_s, shock.height_above_ground_m)
4813        );
4814    }
4815
4816    #[test]
4817    fn a_timed_separation_fires_at_its_own_time() {
4818        // Found in review: the separation's trigger was neither a stop time nor a located event,
4819        // so a timed or height separation fired at whatever boundary happened to come next,
4820        // measured hundreds of seconds late, or never. Its time is a stop time now, and its
4821        // height is an event.
4822        let air = UniformAir::sea_level();
4823        let assembly = two_stage().assemble("j760-i175").unwrap();
4824        let devices = || {
4825            vec![
4826                Device::new(
4827                    "sustainer",
4828                    DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
4829                    Trigger::Altitude {
4830                        height_above_ground_m: 300.0,
4831                    },
4832                ),
4833                Device::new(
4834                    "booster",
4835                    DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
4836                    Trigger::Apogee,
4837                )
4838                .on_body(1),
4839            ]
4840        };
4841        let burnout_s = assembly
4842            .motors
4843            .iter()
4844            .map(|motor| motor.mounted.motor.burnout_time_s())
4845            .fold(0.0, f64::max);
4846        // A time, well after the burnout and nowhere near a thrust knot or a device's trigger.
4847        let at_s = burnout_s + 7.5;
4848        let sim = staged_flight(
4849            analytic_environment(air, G),
4850            devices(),
4851            Separation::new(Trigger::Time { time_s: at_s }, 0),
4852        );
4853        let result = sim
4854            .run_free(
4855                burnout_s + 0.5,
4856                dropped(&sim, 2_000.0, DVec3::new(0.0, 0.0, -1.0)),
4857                &mut (),
4858            )
4859            .unwrap();
4860        let separation = result.event(EventKind::Separation).unwrap().sample;
4861        assert!(
4862            (separation.time_s - at_s).abs() < 1e-9,
4863            "{} vs {at_s}",
4864            separation.time_s
4865        );
4866
4867        // And a height separation fires at its height, located rather than polled.
4868        let sim = staged_flight(
4869            analytic_environment(air, G),
4870            devices(),
4871            Separation::new(
4872                Trigger::Altitude {
4873                    height_above_ground_m: 1_000.0,
4874                },
4875                0,
4876            ),
4877        );
4878        let result = sim
4879            .run_free(
4880                burnout_s + 0.5,
4881                dropped(&sim, 2_000.0, DVec3::new(0.0, 0.0, -1.0)),
4882                &mut (),
4883            )
4884            .unwrap();
4885        let separation = result.event(EventKind::Separation).unwrap().sample;
4886        assert!(
4887            (separation.height_above_ground_m - 1_000.0).abs() < 1e-6,
4888            "{:?}",
4889            separation.height_above_ground_m
4890        );
4891        assert!(result.bodies_landed(), "{:?}", result.bodies.len());
4892    }
4893
4894    #[test]
4895    fn a_body_separated_while_climbing_with_its_device_lagging_is_refused() {
4896        // Found in review of M4.6a: a part parted on the way up, its device fired by the split
4897        // but waiting out its lag, climbed through the lag with no drag at all (a Monte Carlo
4898        // run's drawn lag did it). It is refused by name; the same flight whose device opened
4899        // before the split flies.
4900        let air = UniformAir::sea_level();
4901        let assembly = two_stage().assemble("j760-i175").unwrap();
4902        let burnout_s = assembly
4903            .motors
4904            .iter()
4905            .map(|motor| motor.mounted.motor.burnout_time_s())
4906            .fold(0.0, f64::max);
4907        let fly = |lag_s: f64| {
4908            let sim = staged_flight(
4909                analytic_environment(air, G),
4910                vec![
4911                    Device::new(
4912                        "sustainer",
4913                        DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
4914                        Trigger::Time {
4915                            time_s: burnout_s + 1.2,
4916                        },
4917                    )
4918                    .with_lag_s(lag_s),
4919                    Device::new(
4920                        "booster",
4921                        DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
4922                        Trigger::Apogee,
4923                    )
4924                    .on_body(1),
4925                ],
4926                Separation::new(
4927                    Trigger::Time {
4928                        time_s: burnout_s + 1.5,
4929                    },
4930                    0,
4931                ),
4932            );
4933            let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 100.0));
4934            sim.run_free(burnout_s + 1.0, start, &mut ())
4935        };
4936        // Fired at 1.2 s after the burnout, open at 1.3 s: open at the split, so it flies.
4937        let result = fly(0.1).unwrap();
4938        assert_eq!(result.termination, Termination::Separated);
4939        assert!(result.bodies_landed(), "{:?}", result.bodies.len());
4940        // Open at 2.2 s, 0.7 s after the split: refused, at the split's time.
4941        let error = fly(1.0).expect_err("a part climbing with nothing open");
4942        assert!(
4943            matches!(
4944                error,
4945                SimError::Domain { what, value }
4946                    if what.starts_with("time of a split with nothing left to burn, before \
4947                                         apogee")
4948                        && (value - (burnout_s + 1.5)).abs() < 1e-9
4949            ),
4950            "{error:?}"
4951        );
4952    }
4953
4954    #[test]
4955    fn a_separated_part_warns_of_179_and_of_354_while_it_has_nothing_open() {
4956        // M10.1d5 (ADR-200): the stack parts on the way down. The booster tumbles from the split,
4957        // so the flight meets #179 whatever the sustainer does; the sustainer's canopy fired
4958        // 0.3 s before the split meets #354 only when its lag leaves it closed at the split.
4959        use crate::issues::{KnownIssue, separated_part_issue_warnings};
4960        use crate::metrics::Peak;
4961        let air = UniformAir::sea_level();
4962        let assembly = two_stage().assemble("j760-i175").unwrap();
4963        let burnout_s = assembly
4964            .motors
4965            .iter()
4966            .map(|motor| motor.mounted.motor.burnout_time_s())
4967            .fold(0.0, f64::max);
4968        let split_s = burnout_s + 1.5;
4969        let fly = |lag_s: f64| {
4970            let sim = staged_flight(
4971                analytic_environment(air, G),
4972                vec![
4973                    Device::new(
4974                        "sustainer",
4975                        DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
4976                        Trigger::Time {
4977                            time_s: burnout_s + 1.2,
4978                        },
4979                    )
4980                    .with_lag_s(lag_s),
4981                    // Fired at the split itself, with no lag: open from the booster's start.
4982                    Device::new(
4983                        "booster",
4984                        DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
4985                        Trigger::Time { time_s: split_s },
4986                    )
4987                    .on_body(1),
4988                ],
4989                Separation::new(Trigger::Time { time_s: split_s }, 0),
4990            );
4991            let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, -5.0));
4992            sim.run_free(burnout_s + 1.0, start, &mut ()).unwrap()
4993        };
4994        let peak = Peak {
4995            value: 0.2,
4996            time_s: 0.0,
4997            height_above_ground_m: 0.0,
4998        };
4999        let warned = |result: &FlightResult| -> Vec<KnownIssue> {
5000            separated_part_issue_warnings(result, Some(peak))
5001                .into_iter()
5002                .map(|warning| warning.issue)
5003                .collect()
5004        };
5005        // Open 0.1 s before the split: every body starts with drag, so only the booster's #179.
5006        let open = fly(0.2);
5007        assert_eq!(open.termination, Termination::Separated);
5008        assert!(open.bodies_landed(), "{:?}", open.bodies.len());
5009        let [sustainer, booster] = &open.bodies[..] else {
5010            panic!("{} bodies", open.bodies.len())
5011        };
5012        assert_eq!((sustainer.stages, booster.stages), ((0, 0), (1, 1)));
5013        assert!(sustainer.start_sample.recovery_drag_area_m2 > 0.0);
5014        // The booster's start is the instant before its tumble opens, at that same instant.
5015        assert_eq!(booster.start_sample.recovery_drag_area_m2, 0.0);
5016        let tumbled = booster.event(EventKind::Deployment(1)).unwrap().sample;
5017        assert_eq!(tumbled.time_s, booster.start_sample.time_s);
5018        assert!(tumbled.recovery_drag_area_m2 > 0.0);
5019        assert_eq!(warned(&open), [KnownIssue::BoosterAirframeDrag]);
5020        // Open 0.7 s after it: the sustainer falls with nothing open until then, so #354 too.
5021        let lagging = fly(1.0);
5022        assert!(lagging.bodies_landed(), "{:?}", lagging.bodies.len());
5023        let sustainer = &lagging.bodies[0];
5024        assert_eq!(sustainer.start_sample.recovery_drag_area_m2, 0.0);
5025        let opened_s = sustainer
5026            .event(EventKind::Deployment(0))
5027            .unwrap()
5028            .sample
5029            .time_s;
5030        assert!((opened_s - (split_s + 0.7)).abs() < 1e-9, "{opened_s}");
5031        assert_eq!(
5032            warned(&lagging),
5033            [
5034                KnownIssue::BoosterAirframeDrag,
5035                KnownIssue::DragFreeSeparatedPart
5036            ]
5037        );
5038        // A device that opens just after the start counts as closed at the start; a NaN drag area
5039        // counts as none, so a broken one can't hide #354; a flight with no top Mach number warns
5040        // of nothing; a flight that never parts meets neither.
5041        let mut late = open.clone();
5042        let deployment = &mut late.bodies[1].events[1];
5043        assert_eq!(deployment.kind, EventKind::Deployment(1));
5044        deployment.sample.time_s = deployment.sample.time_s.next_up();
5045        assert_eq!(warned(&late).len(), 2);
5046        let mut broken = open.clone();
5047        broken.bodies[0].start_sample.recovery_drag_area_m2 = f64::NAN;
5048        assert_eq!(warned(&broken).len(), 2);
5049        let mut timeless = open.clone();
5050        timeless.bodies[1].events[1].sample.time_s = f64::NAN;
5051        assert_eq!(warned(&timeless).len(), 2);
5052        // Both are drag issues, by these names in a record.
5053        for (issue, name) in [
5054            (KnownIssue::BoosterAirframeDrag, "\"booster_airframe_drag\""),
5055            (
5056                KnownIssue::DragFreeSeparatedPart,
5057                "\"drag_free_separated_part\"",
5058            ),
5059        ] {
5060            assert!(!issue.is_stability() && !issue.has_mach_condition());
5061            assert_eq!(serde_json::to_string(&issue).unwrap(), name);
5062        }
5063        assert!(separated_part_issue_warnings(&lagging, None).is_empty());
5064        // Bodies all in the nose's stage, as an ejection's are, meet no #179.
5065        let mut forward = open.clone();
5066        forward.bodies.truncate(1);
5067        assert!(warned(&forward).is_empty());
5068        let mut whole = open;
5069        whole.bodies.clear();
5070        assert!(warned(&whole).is_empty());
5071    }
5072
5073    #[test]
5074    fn a_body_whose_device_never_opens_is_refused() {
5075        // Found in review: a device that is attached but never fires (an altimeter set above the
5076        // body's own apogee) dropped the body with no drag at all, at 170 m/s, reported as an
5077        // ordinary landing. A body that reaches the ground with nothing open is an error.
5078        let air = UniformAir::sea_level();
5079        let assembly = two_stage().assemble("j760-i175").unwrap();
5080        let sim = staged_flight(
5081            analytic_environment(air, G),
5082            vec![
5083                Device::new(
5084                    "sustainer",
5085                    DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
5086                    Trigger::Apogee,
5087                ),
5088                Device::new(
5089                    "booster",
5090                    DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
5091                    // Long after the body lands, so it never fires. (A height above the body
5092                    // fires at once on a body already descending below it, which is the
5093                    // altimeter's rule; this test once used one and passed only because the
5094                    // sustainer's canopy, opened on the stack at the separation, was not
5095                    // counted as open. See ADR-074.)
5096                    Trigger::Time { time_s: 100_000.0 },
5097                )
5098                .on_body(1),
5099            ],
5100            Separation::new(Trigger::Apogee, 0),
5101        );
5102        let error = sim
5103            .run_free(
5104                10.0,
5105                dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, -1.0)),
5106                &mut (),
5107            )
5108            .expect_err("a body with nothing open");
5109        // The booster, body 1, is the one refused.
5110        assert!(
5111            matches!(error, SimError::Domain { value, .. } if value == 1.0),
5112            "{error:?}"
5113        );
5114    }
5115
5116    #[test]
5117    fn a_body_that_runs_out_of_time_says_so() {
5118        // A flight that separates says only that the stack came apart: each body's own
5119        // termination says whether it reached the ground.
5120        let air = UniformAir::sea_level();
5121        let assembly = two_stage().assemble("j760-i175").unwrap();
5122        let sim = Simulation::new(
5123            &two_stage(),
5124            "j760-i175",
5125            analytic_environment(air, G),
5126            Rail::vertical(6.0),
5127            FlightSettings {
5128                max_time_s: 60.0,
5129                ..FlightSettings::default()
5130            },
5131        )
5132        .unwrap()
5133        .with_recovery(vec![
5134            Device::new(
5135                "sustainer",
5136                DeviceDrag::canopy(CanopyType::FlatCircular, 1.8),
5137                Trigger::Apogee,
5138            ),
5139            Device::new(
5140                "booster",
5141                DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
5142                Trigger::Apogee,
5143            )
5144            .on_body(1),
5145        ])
5146        .unwrap()
5147        .with_separation(Separation::new(Trigger::Apogee, 0))
5148        .unwrap();
5149        let result = sim
5150            .run_free(10.0, dropped(&sim, 2_000.0, DVec3::ZERO), &mut ())
5151            .unwrap();
5152        assert_eq!(result.termination, Termination::Separated);
5153        assert!(!result.bodies_landed(), "{:?}", result.bodies.len());
5154        assert!(
5155            result
5156                .bodies
5157                .iter()
5158                .any(|body| body.termination == Termination::TimeCap),
5159            "{:?}",
5160            result
5161                .bodies
5162                .iter()
5163                .map(|b| b.termination)
5164                .collect::<Vec<_>>()
5165        );
5166        assert!(result.landings().len() < result.bodies.len());
5167    }
5168
5169    #[test]
5170    fn separations_outside_their_domain_are_refused() {
5171        let environment = || analytic_environment(UniformAir::sea_level(), G);
5172        let canopy = DeviceDrag::canopy(CanopyType::FlatCircular, 1.5);
5173        // The devices are checked when they are given, the separation when it is; a caller sees
5174        // whichever refuses first.
5175        let build = |devices: Vec<Device>, separation: Separation| {
5176            Simulation::new(
5177                &two_stage(),
5178                "j760-i175",
5179                environment(),
5180                Rail::vertical(6.0),
5181                FlightSettings::default(),
5182            )
5183            .unwrap()
5184            .with_recovery(devices)
5185            .and_then(|sim| sim.with_separation(separation))
5186            .map(|_| ())
5187        };
5188        let both = || {
5189            vec![
5190                Device::new("sustainer", canopy, Trigger::Apogee),
5191                Device::new("booster", canopy, Trigger::Apogee).on_body(1),
5192            ]
5193        };
5194        // No stage aft of the split.
5195        let error = build(both(), Separation::new(Trigger::Apogee, 1)).expect_err("no aft stage");
5196        assert!(matches!(error, SimError::Domain { .. }), "{error:?}");
5197        // A body with no device would fall in a vacuum.
5198        let error = build(
5199            vec![Device::new("sustainer", canopy, Trigger::Apogee)],
5200            Separation::new(Trigger::Apogee, 0),
5201        )
5202        .expect_err("the booster has nothing");
5203        assert!(matches!(error, SimError::Domain { .. }), "{error:?}");
5204        // A device on a body the separation doesn't make. An ejection given afterwards could
5205        // make it, so it is refused when the flight starts rather than by the builders.
5206        let error = Simulation::new(
5207            &two_stage(),
5208            "j760-i175",
5209            environment(),
5210            Rail::vertical(6.0),
5211            FlightSettings::default(),
5212        )
5213        .unwrap()
5214        .with_recovery(vec![
5215            Device::new("sustainer", canopy, Trigger::Apogee),
5216            Device::new("booster", canopy, Trigger::Apogee).on_body(1),
5217            Device::new("ghost", canopy, Trigger::Apogee).on_body(2),
5218        ])
5219        .and_then(|sim| sim.with_separation(Separation::new(Trigger::Apogee, 0)))
5220        .and_then(|sim| sim.run(&mut ()))
5221        .expect_err("a third body");
5222        assert!(
5223            matches!(error, SimError::Domain { what, value }
5224                if what == "body a device is attached to (the separation and ejections don't \
5225                            make it)" && value == 2.0),
5226            "{error:?}"
5227        );
5228        // A release across the separation has no line to act through.
5229        let error = build(
5230            vec![
5231                Device::new("sustainer", canopy, Trigger::Apogee).with_release_by(1),
5232                Device::new("booster", canopy, Trigger::Apogee).on_body(1),
5233            ],
5234            Separation::new(Trigger::Apogee, 0),
5235        )
5236        .expect_err("a release across bodies");
5237        assert!(matches!(error, SimError::Domain { .. }), "{error:?}");
5238        // And the ordinary case is accepted.
5239        assert!(build(both(), Separation::new(Trigger::Apogee, 0)).is_ok());
5240    }
5241
5242    #[test]
5243    fn a_separation_before_burnout_is_refused() {
5244        // A body's mass is held constant through its descent, so a separation under thrust would
5245        // fly the wrong mass. A time that is known to precede the burnout is refused when the
5246        // separation is given; an apogee or height trigger can only be checked in flight, and is.
5247        let air = UniformAir::sea_level();
5248        let assembly = two_stage().assemble("j760-i175").unwrap();
5249        let canopy = DeviceDrag::canopy(CanopyType::FlatCircular, 1.5);
5250        let devices = || {
5251            vec![
5252                Device::new("sustainer", canopy, Trigger::Apogee),
5253                Device::new(
5254                    "booster",
5255                    DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap(),
5256                    Trigger::Apogee,
5257                )
5258                .on_body(1),
5259            ]
5260        };
5261        let burnout_s = assembly
5262            .motors
5263            .iter()
5264            .map(|motor| motor.mounted.motor.burnout_time_s())
5265            .fold(0.0, f64::max);
5266        assert!(burnout_s > 1.0, "{burnout_s}");
5267        let build = |separation| {
5268            Simulation::new(
5269                &two_stage(),
5270                "j760-i175",
5271                analytic_environment(air, G),
5272                Rail::vertical(6.0),
5273                FlightSettings::default(),
5274            )
5275            .unwrap()
5276            .with_recovery(devices())
5277            .unwrap()
5278            .with_separation(separation)
5279        };
5280        // Known in advance: refused at once, even though a flight might start after it.
5281        let error = build(Separation::new(
5282            Trigger::Time {
5283                time_s: 0.5 * burnout_s,
5284            },
5285            0,
5286        ))
5287        .expect_err("a timed separation under thrust");
5288        assert!(matches!(error, SimError::Domain { .. }), "{error:?}");
5289
5290        // Only knowable in flight: a height a climbing rocket passes before its burnout.
5291        let sim = build(Separation::new(
5292            Trigger::Altitude {
5293                height_above_ground_m: 500.0,
5294            },
5295            0,
5296        ))
5297        .unwrap();
5298        let error = sim
5299            .run_free(
5300                0.5 * burnout_s,
5301                dropped(&sim, 400.0, DVec3::new(0.0, 0.0, -1.0)),
5302                &mut (),
5303            )
5304            .expect_err("a height separation under thrust");
5305        assert!(matches!(error, SimError::Domain { .. }), "{error:?}");
5306    }
5307
5308    #[test]
5309    fn devices_outside_their_domain_are_refused() {
5310        let environment = || analytic_environment(UniformAir::sea_level(), G);
5311        let rocket = design("rocketpy-valetudo");
5312        let build = |devices: Vec<Device>| {
5313            Simulation::new(
5314                &rocket,
5315                "example",
5316                environment(),
5317                Rail::vertical(3.0),
5318                FlightSettings::default(),
5319            )
5320            .unwrap()
5321            .with_recovery(devices)
5322            .map(|_| ())
5323        };
5324        let canopy = DeviceDrag::canopy(CanopyType::FlatCircular, 1.0);
5325        let apogee = Trigger::Apogee;
5326        for devices in [
5327            vec![Device::new(
5328                "zero",
5329                DeviceDrag::DragArea { cd_s_m2: 0.0 },
5330                apogee,
5331            )],
5332            vec![Device::new(
5333                "nan",
5334                DeviceDrag::DragArea { cd_s_m2: f64::NAN },
5335                apogee,
5336            )],
5337            vec![Device::new("negative lag", canopy, apogee).with_lag_s(-1.0)],
5338            vec![Device::new(
5339                "ground",
5340                canopy,
5341                Trigger::Altitude {
5342                    height_above_ground_m: 0.0,
5343                },
5344            )],
5345            vec![Device::new(
5346                "before ignition",
5347                canopy,
5348                Trigger::Time { time_s: -1.0 },
5349            )],
5350            vec![Device::new(
5351                "no such motor",
5352                canopy,
5353                Trigger::MotorDelay { motor: 7 },
5354            )],
5355            vec![Device::new("itself", canopy, apogee).with_release_by(0)],
5356            vec![Device::new("no such device", canopy, apogee).with_release_by(3)],
5357            vec![
5358                Device::new("no diameter", DeviceDrag::DragArea { cd_s_m2: 1.0 }, apogee)
5359                    .with_inflation(Inflation::FillConstant {
5360                        constant: 8.0,
5361                        exponent: 2.0,
5362                    }),
5363            ],
5364            vec![Device::new("bad exponent", canopy, apogee).with_inflation(
5365                Inflation::FillingTime {
5366                    time_s: 1.0,
5367                    exponent: 0.0,
5368                },
5369            )],
5370        ] {
5371            let name = devices[0].name.clone();
5372            let error = build(devices).expect_err(&name);
5373            assert!(
5374                matches!(error, SimError::Domain { .. }),
5375                "{name}: {error:?}"
5376            );
5377        }
5378        // A cycle of releases is refused: it could leave nothing open.
5379        let cycle = build(vec![
5380            Device::new("a", canopy, apogee).with_release_by(1),
5381            Device::new("b", canopy, apogee).with_release_by(0),
5382        ])
5383        .expect_err("a release cycle");
5384        assert!(matches!(cycle, SimError::Domain { .. }), "{cycle:?}");
5385        // A chain that ends is fine.
5386        assert!(
5387            build(vec![
5388                Device::new("a", canopy, apogee).with_release_by(1),
5389                Device::new("b", canopy, apogee).with_release_by(2),
5390                Device::new("c", canopy, apogee),
5391            ])
5392            .is_ok()
5393        );
5394        // Valetudo's motor has no ejection charge in its example, so it can't fire a device.
5395        let error = build(vec![Device::new(
5396            "no charge",
5397            canopy,
5398            Trigger::MotorDelay { motor: 0 },
5399        )])
5400        .expect_err("a motor with no delay");
5401        assert!(matches!(error, SimError::Domain { .. }), "{error:?}");
5402        // With a delay set, it can.
5403        assert!(
5404            Simulation::new(
5405                &with_delay(rocket.clone(), 3.0),
5406                "example",
5407                environment(),
5408                Rail::vertical(3.0),
5409                FlightSettings::default(),
5410            )
5411            .unwrap()
5412            .with_recovery(vec![Device::new(
5413                "charge",
5414                canopy,
5415                Trigger::MotorDelay { motor: 0 }
5416            )])
5417            .is_ok()
5418        );
5419        // And a device that is fine passes.
5420        assert!(build(vec![Device::new("fine", canopy, apogee).with_lag_s(1.5)]).is_ok());
5421    }
5422
5423    #[test]
5424    fn oversized_canopy_and_ten_km_descent_land_without_step_collapse() {
5425        // Loft lesson L28. Loft's explicit RK4 needed a 2e-4 s step floor under a stiff canopy,
5426        // and its 1200 s cap left slow descents from height unlanded: a 10 km descent at 3 m/s
5427        // takes an hour. Here an oversized canopy opens at 100 m/s at 10 km, and the adaptive
5428        // integrator flies the whole descent in a few hundred steps.
5429        let air = UniformAir::sea_level();
5430        let device = open_at_start(DeviceDrag::canopy(CanopyType::FlatCircular, 5.0));
5431        let drag_area_m2 = device.drag.drag_area_m2();
5432        let sim = flight(analytic_environment(air, G), vec![device], 3600.0);
5433        let mass_kg = sim.assembly().mass_properties(START_S).mass_kg;
5434        let terminal_m_s = terminal_speed_m_s(mass_kg, drag_area_m2, air.0.density_kg_m3, G);
5435        // Measured: 2.95 m/s under a 5 m canopy, so the descent takes about 3,400 s.
5436        assert!(terminal_m_s < 3.5, "{terminal_m_s}");
5437        let result = sim
5438            .run_free(
5439                START_S,
5440                dropped(&sim, 10_000.0, DVec3::new(0.0, 0.0, -100.0)),
5441                &mut (),
5442            )
5443            .unwrap();
5444        assert_eq!(result.termination, Termination::GroundHit);
5445        let landing = result.event(EventKind::GroundHit).unwrap().sample;
5446        assert!(
5447            (-landing.vertical_speed_m_s / terminal_m_s - 1.0).abs() < 1e-6,
5448            "{}",
5449            landing.vertical_speed_m_s
5450        );
5451        // The descent takes about 10 km / v_t, and the flight has to reach the ground inside the
5452        // default one-hour cap.
5453        let flown_s = landing.time_s - START_S;
5454        assert!(
5455            (flown_s - 10_000.0 / terminal_m_s).abs() < 60.0,
5456            "{flown_s} s"
5457        );
5458        assert!(flown_s < 3_600.0, "{flown_s} s");
5459        // No step collapse: the mean step stays near half a second, where Loft's explicit RK4
5460        // needed a 2e-4 s floor. Measured: 6,914 accepted steps and 2 rejected over 3,392 s, a
5461        // mean step of 0.49 s, against the 1.7e7 steps Loft's floor would have taken. The step is
5462        // limited by the tolerances (unit weights on a 10 km height), not by stiffness.
5463        let mean_step_s = flown_s / result.stats.accepted_steps as f64;
5464        assert!(
5465            mean_step_s > 0.1,
5466            "{mean_step_s} s mean step: {:?}",
5467            result.stats
5468        );
5469        assert!(result.stats.accepted_steps < 20_000, "{:?}", result.stats);
5470        assert!(result.stats.rejected_steps < 100, "{:?}", result.stats);
5471    }
5472
5473    #[test]
5474    fn several_separations_number_their_bodies_from_the_tail() {
5475        // Three stages, the booster (2) dropped first, then the middle (1): body 1 is the
5476        // booster, body 2 the middle, body 0 the nose's.
5477        let at = |after_stage| Separation::new(Trigger::Apogee, after_stage);
5478        let two = [at(1), at(0)];
5479        assert_eq!(
5480            (0..3)
5481                .map(|stage| Separation::body_of(&two, stage))
5482                .collect::<Vec<_>>(),
5483            [0, 2, 1]
5484        );
5485        assert_eq!(Separation::stages_of_body(&two, 0, 3), Some((0, 0)));
5486        assert_eq!(Separation::stages_of_body(&two, 1, 3), Some((2, 2)));
5487        assert_eq!(Separation::stages_of_body(&two, 2, 3), Some((1, 1)));
5488        assert_eq!(Separation::stages_of_body(&two, 3, 3), None);
5489        // One separation agrees with `stages_of`, and none leaves every stage on body 0.
5490        for (after_stage, stages) in [(0, 3), (1, 3), (0, 2)] {
5491            for body in 0..3 {
5492                assert_eq!(
5493                    Separation::stages_of_body(&[at(after_stage)], body, stages),
5494                    at(after_stage).stages_of(body, stages)
5495                );
5496            }
5497        }
5498        assert_eq!(Separation::stages_of_body(&[], 0, 3), Some((0, 2)));
5499        assert_eq!(Separation::body_of(&[], 2), 0);
5500        // Boundaries that don't move forward, or one at the last stage, make no bodies.
5501        assert_eq!(Separation::stages_of_body(&[at(0), at(1)], 0, 3), None);
5502        assert_eq!(Separation::stages_of_body(&[at(2)], 1, 3), None);
5503        // Five stages dropped two at a time and then one.
5504        let uneven = [at(2), at(0)];
5505        assert_eq!(Separation::stages_of_body(&uneven, 1, 5), Some((3, 4)));
5506        assert_eq!(Separation::stages_of_body(&uneven, 2, 5), Some((1, 2)));
5507        assert_eq!(
5508            (0..5)
5509                .map(|stage| Separation::body_of(&uneven, stage))
5510                .collect::<Vec<_>>(),
5511            [0, 2, 2, 1, 1]
5512        );
5513    }
5514}