Skip to main content

hpr_aero/
model.rs

1//! A rocket's normal force and center of pressure: every component's terms, built once from a
2//! [`Layout`] and summed at each flow condition.
3//!
4//! The coefficient at an angle of attack `α` is `C_N = C_Nα(α) α`, with the slope defined as
5//! `C_N/α` (Niskanen 2009 eq. 3.8) and the center of pressure as the moment sum
6//! `X = Σ C_Nα,i X_i / Σ C_Nα,i` (Barrowman 1966 p. 38; Niskanen eq. 3.29). The terms:
7//!
8//! - bodies of revolution, `(2/A_ref)ΔA · sin α/α` at `X_B` ([`crate::body`]), plus body lift
9//!   `η C_dn (A_plan/A_ref) sin² α / α` at the planform centroid, Jorgensen's crossflow term
10//!   ([`crate::crossflow`]);
11//! - a step in radius where one body component meets the next, `(2/A_ref)ΔA · sin α/α` at the
12//!   joint, reported with the aft component. This extrapolates Barrowman 1966 eq. 10 over the whole
13//!   body to a transition of zero length; Barrowman 1967 p. 18 assumes no discontinuities;
14//! - fin sets, `(C_Nα)₁ Σ sin² Λ_k · f_N · K_T(B)` at the fin's center of pressure, both at the
15//!   flow's Mach number ([`crate::fins::FinAero`]), and for one or two fins the side force
16//!   `(C_Nα)₁ Σ sin Λ cos Λ · K_T(B)` across the flow's plane ([`crate::fins::side_sum`]);
17//! - tube fin sets, `N` ring wings' slope at the ring's center of pressure below Mach 0.8
18//!   ([`crate::tube_fins`]), with no roll dependence or side force.
19//!
20//! Below the speed of sound the bodies' potential-flow terms don't change with Mach:
21//! slender-body theory's slope and center of pressure hold at any Mach number (Barrowman 1967
22//! p. 18). Body lift changes with the crossflow Mach number `M sin α` at any speed. Faster than
23//! sound, a pointed nose and the cylinders straight behind it take their potential-flow slope and
24//! moment from the second-order shock-expansion method ([`crate::shock_expansion`], NACA TN
25//! 3527), and a boattail behind them Washington and Pettis's measured increment
26//! ([`crate::supersonic_boattail`]), joined to slender-body theory linearly in Mach
27//! ([`SupersonicBody`]; the decision records on flying them, [ADR-034][adr-034] and
28//! [ADR-037][adr-037]).
29//! Other bodies keep slender-body theory's terms. [`BodyModel`] chooses the body-lift and boattail
30//! rules; the default is HPR Sim's current one.
31//!
32//! Launch lugs and rail buttons add drag only, and internal parts sit inside the body. Any part
33//! kind this model doesn't know is refused. Stations are meters aft of the nose tip.
34//!
35//! [adr-034]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-034-the-bodys-supersonic-normal-force-in-flight-tabulated-shock-expansion-shares-joined-linearly-from-mach-12-2026-09-19
36//! [adr-037]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-037-body-lift-by-jorgensens-crossflow-at-every-speed-and-a-boattails-measured-share-faster-than-sound-2026-09-19
37
38use std::collections::VecDeque;
39use std::f64::consts::PI;
40use std::sync::atomic::{AtomicBool, Ordering};
41use std::sync::{Arc, Mutex, OnceLock};
42
43use hpr_design::{Layout, NoseShape, Part, PlacedComponent};
44use serde::{Deserialize, Serialize};
45
46use crate::afterbody::SEPARATION_ONSET_RAD;
47use crate::body::{BodyGeometry, sinc};
48use crate::crossflow::BodyLift;
49use crate::custom::{DragModel, DragQuery, SharedDragModel};
50use crate::drag::{
51    BUILDUP_MACH_LIMIT, ComponentDrag, ComponentDragTerms, Drag, DragConditions, MOTOR_POD_SETS,
52    axial_drag_alpha_factor, body_friction_form_factor, couple_afterbody,
53};
54use crate::error::{AeroError, check_dimension, check_mach};
55use crate::fins::{
56    FinAero, FinLoading, FinRollTerms, fin_count_factor, interference_factor,
57    roll_damping_interference, roll_forcing_interference, roll_sum, side_sum,
58};
59use crate::shock_expansion::{
60    BodySegment, DEFAULT_ELEMENTS_PER_CURVE, SegmentSlope, ShockExpansionBody,
61    flare_corner_limit_rad,
62};
63use crate::supersonic_boattail::{wp_center_fraction, wp_slope};
64use crate::table::{DragTable, NormalForceLookup, NormalForceTable, TableReference};
65use crate::tube_fins::{TubeFinSetAero, check_tube_fin_mach};
66
67/// The largest fin cant the roll model takes, 15°: past it a fin stalls, where its lift stops
68/// growing with the angle, a judgment ([`AeroModel::roll`]).
69pub const MAX_CANT_RAD: f64 = 15.0 * std::f64::consts::PI / 180.0;
70
71/// The top of the normal force's range: Mach 5, where the hypersonic region begins (Niskanen 2009
72/// Table 3.1, p. 19). [`AeroModel::normal_force`] refuses it and anything faster.
73pub const NORMAL_FORCE_MACH_LIMIT: f64 = 5.0;
74
75/// The lowest Mach number at which the body's supersonic join can start ([`SupersonicBody`]):
76/// below it every body keeps slender-body theory's terms. A judgment: the first body that TN
77/// 3527's method covers and TN D-4014 measured is at Mach 1.5, the join's end from here.
78pub const SUPERSONIC_JOIN_START_MACH: f64 = 1.2;
79
80/// Steps of the shock-expansion table per unit Mach: one row every 0.05.
81const SUPERSONIC_STEPS_PER_MACH: f64 = 20.0;
82
83/// The table's first row, Mach 1.2 ([`SUPERSONIC_JOIN_START_MACH`]).
84const SUPERSONIC_FIRST_STEP: usize = 24;
85
86/// The table's last row, Mach 5 ([`NORMAL_FORCE_MACH_LIMIT`]).
87const SUPERSONIC_LAST_STEP: usize = 100;
88
89/// Rows across the join.
90const SUPERSONIC_JOIN_STEPS: usize = 6;
91
92/// The most halvings of the 0.05 step in which the method starts to hold. Bisection stops sooner,
93/// after about 48, when no `f64` lies between its ends: the join's start is then as exact as the
94/// number allows, so it moves with the body's shape, not in 0.05 steps
95/// ([issue #87](https://github.com/nrdptel/fusionspace-eridanus/issues/87)). It has to be that exact: the
96/// shares climb from zero like `√(M − M_start)` there, so a start off by `δ` puts `√δ`-sized
97/// shares in the table's first row.
98const SUPERSONIC_JOIN_BISECTIONS: usize = 64;
99
100/// The smallest share of shelter worth a table: below this a lip counts as out of its boattail's
101/// wake, since weighing the method in at under a millionth changes no number anyone can read and
102/// building the table costs half a second ([`SupersonicBody::shape_weight`]).
103const SUPERSONIC_SHELTER_FLOOR: f64 = 1e-6;
104
105/// The width of the body's supersonic join in Mach, 0.3: over it the shock-expansion shares
106/// replace slender-body theory's linearly ([`SupersonicBody`]).
107pub const SUPERSONIC_JOIN_WIDTH_MACH: f64 =
108    SUPERSONIC_JOIN_STEPS as f64 / SUPERSONIC_STEPS_PER_MACH;
109
110/// Why the shock-expansion method doesn't fly a body faster than sound, so that slender-body
111/// theory flies it whole: the first switch along the body that stopped the run
112/// ([`AeroModel::supersonic_fallback`], [ADR-181][adr-181]). Each of the three named switches
113/// overstates the normal force's lever arm (center of pressure aft) and has its issue.
114///
115/// [adr-181]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0181-the-stability-issue-warnings.md
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case", tag = "switch")]
118#[non_exhaustive]
119pub enum SupersonicFallback {
120    /// [Issue #87](https://github.com/nrdptel/fusionspace-eridanus/issues/87): a step in area at the
121    /// component's fore end larger than a millionth of that area.
122    RadiusStep {
123        /// The component's id.
124        component: String,
125    },
126    /// [Issue #120](https://github.com/nrdptel/fusionspace-eridanus/issues/120): a lip in a boattail's wake
127    /// longer than the boattail's drop in diameter.
128    LongLip {
129        /// The component's id.
130        component: String,
131    },
132    /// [Issue #121](https://github.com/nrdptel/fusionspace-eridanus/issues/121): a pointed tip cone steeper
133    /// than the cone tables' 30° ([`crate::blunt_tip::CONE_TABLE_CAP_RAD`]).
134    SteepTip,
135    /// Any other rule: a shape the run doesn't take, or the method failing past its tables.
136    Other,
137}
138
139/// The second-order shock-expansion method's share of each body component it covers, tabulated in
140/// Mach, and where it joins slender-body theory (the decision record on flying it,
141/// [ADR-034][adr-034]).
142///
143/// The method ([`crate::shock_expansion`]) covers a pointed nose, the cylinders straight behind
144/// it, and boattails and cylinders behind those, up to the first other body (a flare), step in
145/// radius or gap. It flies only if no body after them has a potential-flow slope of its own (a
146/// flare, a step). A boattail doesn't take slender-body theory's share: the method's nose and
147/// cylinder beside slender-body theory's boattail would put the body's center of pressure further
148/// off than slender-body theory alone (milestone
149/// [M1.8e4](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e4)). By default
150/// ([`SupersonicBoattail::WashingtonPettis`]) it takes the share the method gives a cylinder of
151/// its length and fore radius in its place, plus Washington and Pettis's measured increment at
152/// their center of pressure ([`crate::supersonic_boattail`]); [`SupersonicBoattail::Footnote8`]
153/// keeps the method's own, TN 3527 footnote 8. Cylinders behind a boattail take the method's
154/// shares either way. A boattail's share, and a cylinder's behind it, may cross zero, so those
155/// parts keep slender-body theory's station ([`AeroModel::component_station_m`]).
156///
157/// The method is too slow to run at each step of a flight, so [`AeroModel::supersonic_body`] tabulates each covered segment's slope and moment
158/// every 0.05 in Mach, from Mach 5 down to the lowest Mach from which the method holds, and a
159/// flight interpolates linearly between rows. Where the method stops holding above
160/// [`SUPERSONIC_JOIN_START_MACH`], bisection finds that Mach to the last bit of an `f64` and the
161/// table gains a row there, so the join's start moves with the body's shape rather than in 0.05 steps.
162/// The join starts at that Mach, or at
163/// [`SUPERSONIC_JOIN_START_MACH`] if higher: at Mach `M`, a covered component's potential-flow
164/// slope and moment, and a nose's or cylinder's station, are slender-body theory's plus
165/// `w (shock-expansion − slender-body)`, `w = `[`SupersonicBody::weight`]`(M)`: the join's own
166/// `(M − M_join)/`[`SUPERSONIC_JOIN_WIDTH_MACH`] clamped to `[0, 1]`, times
167/// [`SupersonicBody::shape_weight`], which is 1 unless a lip rides along only partly inside its
168/// boattail's wake. Everything is linear in Mach and in that share of shape, so nothing jumps.
169///
170/// [adr-034]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-034-the-bodys-supersonic-normal-force-in-flight-tabulated-shock-expansion-shares-joined-linearly-from-mach-12-2026-09-19
171#[derive(Debug, Clone, PartialEq, Serialize)]
172#[non_exhaustive]
173pub struct SupersonicBody {
174    /// How many body components the method covers: the first entries of [`AeroModel::bodies`].
175    /// The last of them may be lips in a covered boattail's wake, which the method doesn't march:
176    /// the method gives them nothing at any Mach number, so what such a lip carries is
177    /// `(1 − `[`SupersonicBody::weight`]`(M))` of slender-body theory's share, none of it above
178    /// the join where the wake covers it wholly ([`crate::drag::WakeTerm`]; the decision record on
179    /// the lip, [ADR-039][adr-039]).
180    ///
181    /// [adr-039]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-039-a-lip-in-a-boattails-wake-carries-nothing-faster-than-sound-2026-09-19
182    pub covered: usize,
183    /// The Mach number where the join starts; the shares count in full from
184    /// [`SUPERSONIC_JOIN_WIDTH_MACH`] above it.
185    pub join_start_mach: f64,
186    /// The table's first even row is at Mach `first_step / 20`.
187    first_step: usize,
188    /// Each even row's shares, one per covered component: slope per radian and its moment about
189    /// the nose tip, m per radian. Every share with a station is positive.
190    rows: Vec<Vec<SegmentSlope>>,
191    /// Whether each covered component's share has a station of its own: a nose's and a
192    /// cylinder's do, a boattail's and those behind it don't (they may cross zero).
193    stationed: Vec<bool>,
194    /// The shares at `join_start_mach`, where the method starts to hold, when that lies between
195    /// even rows: the table's first row.
196    lead: Option<Vec<SegmentSlope>>,
197    /// How much of the method the body's shape takes, in `(0, 1]`, which multiplies the join's
198    /// weight: below 1 where a lip rides along only partly inside its boattail's wake
199    /// ([`crate::drag::WakeTerm`], [issue #87: the body's normal force jumps with small changes of
200    /// shape](https://github.com/nrdptel/fusionspace-eridanus/issues/87), [ADR-041: a lip's shelter weighed,
201    /// not switched][adr-041]). Slender-body theory takes the rest, so a
202    /// lip drawn a hair taller moves the body between the models continuously instead of
203    /// switching it.
204    ///
205    /// [adr-041]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-041-a-lips-shelter-is-weighed-as-the-drag-buildup-weighs-it-not-switched-at-a-threshold-2026-09-20
206    pub shape_weight: f64,
207}
208
209/// How a boattail that the shock-expansion method covers takes its share of the normal force
210/// faster than sound ([`SupersonicBody`]).
211#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(rename_all = "snake_case")]
213#[non_exhaustive]
214pub enum SupersonicBoattail {
215    /// The share the method gives a cylinder of the boattail's length and fore radius in its
216    /// place, plus Washington and Pettis's measured increment at their center of pressure
217    /// ([`crate::supersonic_boattail`]): HPR Sim's rule since [M1.8e6](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e6) (the decision
218    /// record, [ADR-037](https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-037-body-lift-by-jorgensens-crossflow-at-every-speed-and-a-boattails-measured-share-faster-than-sound-2026-09-19)).
219    #[default]
220    WashingtonPettis,
221    /// The method's own share, TN 3527 footnote 8's tangent cone: HPR Sim's rule from the milestone
222    /// that first flew a boattail by the method ([M1.8e4](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e4)) until
223    /// [M1.8e6](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e6).
224    Footnote8,
225}
226
227/// How a flare (a transition that widens the body) takes its share of the normal force faster
228/// than sound ([`SupersonicBody`]).
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "snake_case")]
231#[non_exhaustive]
232pub enum SupersonicFlare {
233    /// The shock-expansion method's own share, marched through the flare's corner where the shock
234    /// there is attached: HPR Sim's rule since [M1.8e17](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e17) (the decision record,
235    /// [ADR-047](https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-047-a-flare-flies-the-method-where-its-corners-shock-is-attached-and-is-read-drawn-out-where-it-is-not-2026-09-20)).
236    /// Only a **conical** flare, flush with the part ahead of it and not behind a boattail, joins
237    /// the run, which then ends at it. A widening part behind a boattail is a lip in its wake and
238    /// keeps [`SupersonicBody::shape_weight`]'s rule instead; any other widening shape ends the
239    /// run without joining it, as every flare did before that milestone.
240    #[default]
241    Marched,
242    /// None: a flare ends the method's run, so the whole body takes slender-body theory's share
243    /// at every Mach number. HPR Sim's rule until [M1.8e17](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e17).
244    SlenderBody,
245}
246
247/// The choices in the bodies' normal-force model ([`AeroModel::with_body_model`]). The default is
248/// HPR Sim's current model, [`BodyModel::CURRENT`]; [`BodyModel::BEFORE_M1_8E6`] reproduces earlier
249/// results. Change one choice with [`BodyModel::with_body_lift`],
250/// [`BodyModel::with_supersonic_boattail`] or [`BodyModel::with_supersonic_flare`]. In JSON, for
251/// example `{"body_lift": {"kind": "galejs", "k": 1.1}, "supersonic_boattail": "footnote8"}`; a
252/// missing field takes the current choice.
253#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
254#[serde(default, deny_unknown_fields)]
255#[non_exhaustive]
256pub struct BodyModel {
257    /// How body lift is sized.
258    pub body_lift: BodyLift,
259    /// How a boattail takes its share faster than sound.
260    pub supersonic_boattail: SupersonicBoattail,
261    /// How a flare takes its share faster than sound.
262    pub supersonic_flare: SupersonicFlare,
263}
264
265impl BodyModel {
266    /// HPR Sim's current body model: Jorgensen's body lift, Washington and Pettis's boattail and a
267    /// marched flare.
268    pub const CURRENT: Self = Self {
269        body_lift: BodyLift::JORGENSEN,
270        supersonic_boattail: SupersonicBoattail::WashingtonPettis,
271        supersonic_flare: SupersonicFlare::Marched,
272    };
273
274    /// HPR Sim's body model before [M1.8e6](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e6) sized body lift and the boattail: Galejs's
275    /// `K` = 1.1, TN 3527 footnote 8's boattail, and a flare that ends the method's run rather
276    /// than flying it ([`SupersonicFlare::SlenderBody`], as before [M1.8e17](https://hpr.fusionspace.co/decisions-and-roadmap.html#m1-8e17)).
277    pub const BEFORE_M1_8E6: Self = Self {
278        body_lift: BodyLift::GALEJS,
279        supersonic_boattail: SupersonicBoattail::Footnote8,
280        supersonic_flare: SupersonicFlare::SlenderBody,
281    };
282
283    /// This model with body lift sized by `body_lift`.
284    #[must_use]
285    pub const fn with_body_lift(mut self, body_lift: BodyLift) -> Self {
286        self.body_lift = body_lift;
287        self
288    }
289
290    /// This model with a supersonic boattail's share by `supersonic_boattail`.
291    #[must_use]
292    pub const fn with_supersonic_boattail(
293        mut self,
294        supersonic_boattail: SupersonicBoattail,
295    ) -> Self {
296        self.supersonic_boattail = supersonic_boattail;
297        self
298    }
299
300    /// This model with a supersonic flare's share by `supersonic_flare`.
301    #[must_use]
302    pub const fn with_supersonic_flare(mut self, supersonic_flare: SupersonicFlare) -> Self {
303        self.supersonic_flare = supersonic_flare;
304        self
305    }
306}
307
308/// A boattail in the shock-expansion run, for Washington and Pettis's increment: the method's
309/// body with a cylinder of the boattail's length and fore radius in its place (its last segment),
310/// and the boattail's radii and length, m.
311#[derive(Debug, Clone, PartialEq)]
312struct RunBoattail {
313    in_its_place: Vec<BodySegment>,
314    fore_radius_m: f64,
315    aft_radius_m: f64,
316    length_m: f64,
317}
318
319/// A flare in the shock-expansion run (always its last segment) and the run ahead of it, whose
320/// march delivers the flow its corner turns ([`ShockExpansionBody::aft_flow`]). Its radii and
321/// length are the real flare's; where the corner's shock would be detached the method reads one
322/// of the same radii drawn out to the steepest attached turn ([`flare_corner_limit_rad`]).
323#[derive(Debug, Clone, PartialEq)]
324struct RunFlare {
325    /// Which segment of the run the flare is: always its last.
326    index: usize,
327    ahead: Vec<BodySegment>,
328    fore_radius_m: f64,
329    aft_radius_m: f64,
330    length_m: f64,
331    clipped: bool,
332}
333
334/// The segments the shock-expansion method covers, the station of the nose's tip, and each
335/// segment's fore and aft stations, m aft of the nose tip: `None` for a boattail and anything
336/// behind it, whose shares can be negative or cross zero (TN 3527 footnote 8, or Washington and
337/// Pettis's increment) and so needn't have a station on their segments.
338#[derive(Debug, Clone, PartialEq)]
339struct SupersonicRun {
340    segments: Vec<BodySegment>,
341    vertex_m: f64,
342    bounds_m: Vec<Option<(f64, f64)>>,
343    /// Each segment's fore station, m aft of the nose tip.
344    fore_m: Vec<f64>,
345    /// Each segment that is a boattail, when its share is Washington and Pettis's.
346    boattails: Vec<Option<RunBoattail>>,
347    /// The flare that ends the run, where one does ([`SupersonicFlare::Marched`]).
348    flare: Option<RunFlare>,
349    /// How many bodies behind the marched segments are lips wholly in a covered boattail's wake
350    /// ([`crate::drag::WakeTerm`]): they widen the body, carry nothing faster than sound, and so
351    /// the run covers them with a share of zero.
352    sheltered_lips: usize,
353    /// How much of the run's shape the method takes, in `(0, 1]`: the smallest share of the wake
354    /// covering a sheltered lip: its rise, the tube between it and the boattail, and anything
355    /// else in the way (issue #87). One where no lip rides along, or where the wake covers it
356    /// wholly.
357    shape_weight: f64,
358    // `segments`, `bounds_m`, `fore_m` and `boattails` hold one entry per segment: `from_design`
359    // pushes all four in the same branch, and `shares` indexes them together; `shares` then adds
360    // one zero for each sheltered lip.
361}
362
363impl SupersonicRun {
364    /// The method's shares at `mach`, moments about the nose tip, or `None` where it fails or a
365    /// nose's or cylinder's share isn't positive with its station on its own segment (a share
366    /// that crosses zero has no station, and one that is positive but small could put a part's
367    /// damping station far off the rocket). A boattail's share, and those behind it, may take
368    /// either sign: their damping stations stay slender-body theory's
369    /// ([`AeroModel::component_station_m`]). A boattail with `in_its_place`, the method's body
370    /// with a cylinder in its place, takes that cylinder's share plus Washington and Pettis's
371    /// increment ([`SupersonicBoattail::WashingtonPettis`]).
372    fn shares(
373        &self,
374        body: &ShockExpansionBody,
375        in_its_place: &[Option<ShockExpansionBody>],
376        ahead: Option<&ShockExpansionBody>,
377        mach: f64,
378        reference_area_m2: f64,
379    ) -> Option<Vec<SegmentSlope>> {
380        let vertex_m = self.vertex_m;
381        // A flare steeper than its corner's shock can stay attached to is read as one of the same
382        // radii drawn out to that turn (ADR-047 in `docs/DECISIONS.md`). The march is
383        // downstream-only, so the flow reaching the corner comes from the run ahead of the flare,
384        // and the drawn-out body differs from the real one in its last segment alone.
385        let held = match (&self.flare, ahead) {
386            // `SupersonicBody::new` builds one whenever the run has a flare; a run that has one
387            // without it would read the real flare however steep, so refuse the row instead.
388            (Some(_), None) => return None,
389            (Some(flare), Some(ahead)) => {
390                let aft = ahead.aft_flow(mach).ok()?;
391                let rise_m = flare.aft_radius_m - flare.fore_radius_m;
392                let angle_rad = (rise_m / flare.length_m).atan();
393                // The corner's turn is bounded by the shock staying attached; the flare's own
394                // surface angle by the cone tables, which an element's tangent cone is looked up
395                // by. They are bounds on different things, so each caps its own quantity.
396                let turn_limit_rad = flare_corner_limit_rad(aft.surface_mach).ok()?;
397                let angle_limit_rad =
398                    (turn_limit_rad + aft.angle_rad).min(crate::blunt_tip::CONE_TABLE_CAP_RAD);
399                if angle_rad > angle_limit_rad {
400                    // A surface ahead already steeper than the limit turns the flow past it
401                    // however the flare is drawn, and a flare drawn to nothing has no length:
402                    // the method has no reading there. Unreachable while only a flare not behind
403                    // a boattail joins the run, since the angle ahead is then zero or positive.
404                    if angle_limit_rad <= 0.0 || !angle_limit_rad.is_finite() {
405                        return None;
406                    }
407                    let length_m = rise_m / angle_limit_rad.tan();
408                    let mut segments = flare.ahead.clone();
409                    segments.push(BodySegment::Profile {
410                        profile: hpr_design::Profile::transition(
411                            NoseShape::Conical {},
412                            length_m,
413                            flare.fore_radius_m,
414                            flare.aft_radius_m,
415                            flare.clipped,
416                        )
417                        .ok()?,
418                    });
419                    Some((
420                        ShockExpansionBody::new(&segments, DEFAULT_ELEMENTS_PER_CURVE).ok()?,
421                        length_m,
422                    ))
423                } else {
424                    None
425                }
426            }
427            _ => None,
428        };
429        let mut shares = match &held {
430            Some((drawn, _)) => drawn.segment_slopes(mach, reference_area_m2).ok()?,
431            None => body.segment_slopes(mach, reference_area_m2).ok()?,
432        };
433        // The length only enters the march: the center of pressure stays on the real flare, at
434        // the same fraction along it as the drawn-out one reads. At the limit the two lengths are
435        // equal, so this is continuous in the flare's angle and in the Mach number.
436        if let (Some(flare), Some((_, drawn_length_m))) = (&self.flare, &held) {
437            let index = flare.index;
438            let share = *shares.get(index)?;
439            if share.slope_per_rad > 0.0 {
440                let fore_m = self.fore_m[index] - vertex_m;
441                let along = (share.moment_slope_m / share.slope_per_rad - fore_m) / drawn_length_m;
442                shares[index].moment_slope_m =
443                    share.slope_per_rad * (fore_m + along * flare.length_m);
444            }
445        }
446        // A lip in a boattail's wake carries nothing faster than sound (ADR-039).
447        shares.extend(std::iter::repeat_n(
448            SegmentSlope::default(),
449            self.sheltered_lips,
450        ));
451        for (index, (boattail, cylinder_body)) in
452            self.boattails.iter().zip(in_its_place).enumerate()
453        {
454            let (Some(boattail), Some(cylinder_body)) = (boattail, cylinder_body) else {
455                continue;
456            };
457            // The cylinder in its place is that body's last segment; its moment is about the
458            // vertex, as the method's shares are.
459            let cylinder = *cylinder_body
460                .segment_slopes(mach, reference_area_m2)
461                .ok()?
462                .last()?;
463            let fore_radius_m = boattail.fore_radius_m;
464            // Issue #90's cap. Washington and Pettis measured boattails of 4° to 9.5°, whose
465            // flow follows the surface; past about 16° it separates (Cubbage, the angle the drag
466            // buildup uses, `crate::afterbody::SEPARATION_ONSET_RAD`) and nothing measures what
467            // the body then carries. So the correlation is read no steeper than 16°: a boattail
468            // past it takes the increment of one of the same radii drawn out to that angle. The
469            // length only enters the correlation; the center of pressure stays on the real
470            // boattail. Continuous in shape (at 16° the two lengths are equal), and it holds the
471            // lift the boattail takes off rather than letting it go to zero, which would move the
472            // center of pressure aft and make a steep boattail look more stable than measured.
473            let drop_m = fore_radius_m - boattail.aft_radius_m;
474            let read = |length_m| wp_slope(mach, fore_radius_m, boattail.aft_radius_m, length_m);
475            let at_true_angle = read(boattail.length_m).ok()?;
476            let held = read(boattail.length_m.max(drop_m / SEPARATION_ONSET_RAD.tan())).ok()?;
477            // How far the holding may go. Reading a longer boattail walks Fig. 5's argument
478            // toward zero, where the curve comes from the report's lowest supersonic runs
479            // (`crate::supersonic_boattail`) and passes Munk's slender-body line, which
480            // RD-TM-68-5 plots for comparison at subsonic speeds (p. 3). hpr does not invent a
481            // length and then read that branch: the *extra* the holding removes stops at
482            // potential flow's `2 (A_aft − A_fore)/A_fore`. A boattail's read at its own length
483            // is never clipped, whatever it says: that is the correlation as published, and a
484            // genuinely long boattail reads the same branch unbounded. At 16° the two reads are
485            // equal, so this is continuous in shape.
486            let ratio = boattail.aft_radius_m / fore_radius_m;
487            let measured = held.max(at_true_angle.min(2.0 * (ratio * ratio - 1.0)));
488            let increment = measured * PI * fore_radius_m * fore_radius_m / reference_area_m2;
489            let center_m =
490                self.fore_m[index] + wp_center_fraction(mach) * boattail.length_m - vertex_m;
491            shares[index] = SegmentSlope {
492                slope_per_rad: cylinder.slope_per_rad + increment,
493                moment_slope_m: cylinder.moment_slope_m + increment * center_m,
494            };
495        }
496        let on_segment = shares.iter().zip(&self.bounds_m).all(|(s, bounds)| {
497            let Some((fore, aft)) = *bounds else {
498                return s.slope_per_rad.is_finite() && s.moment_slope_m.is_finite();
499            };
500            let station = (s.moment_slope_m + s.slope_per_rad * vertex_m) / s.slope_per_rad;
501            let slack = 1e-9 * (aft - vertex_m);
502            s.slope_per_rad > 0.0 && station >= fore - slack && station <= aft + slack
503        });
504        on_segment.then(|| {
505            shares
506                .into_iter()
507                .map(|s| SegmentSlope {
508                    slope_per_rad: s.slope_per_rad,
509                    moment_slope_m: s.moment_slope_m + s.slope_per_rad * vertex_m,
510                })
511                .collect()
512        })
513    }
514}
515
516/// The table, built once and shared by a model's clones. It follows from the covered segments, so
517/// two models compare equal whether or not either has built it.
518#[derive(Debug, Clone, Default)]
519struct SupersonicTable(Arc<OnceLock<Option<SupersonicBody>>>);
520
521/// The most tables a process that keeps them ([`keep_supersonic_tables`]) holds, the first kept
522/// dropped first: the motor catalog's check flies 24 probe shapes in one process (issue #1427),
523/// and each table holds about 80 rows of a share per covered segment, some kilobytes.
524const KEPT_TABLES: usize = 64;
525
526/// Whether this process keeps the supersonic tables it builds: off until
527/// [`keep_supersonic_tables`] turns it on.
528static KEEPING_TABLES: AtomicBool = AtomicBool::new(false);
529
530/// The tables this process has kept, while [`KEEPING_TABLES`] is on.
531static KEPT: Mutex<KeptTables> = Mutex::new(KeptTables::new(KEPT_TABLES));
532
533/// Has every model this process builds from now on take its supersonic table
534/// ([`AeroModel::supersonic_body`]) as a copy of one the process already built from an equal run
535/// on the same reference area, where there is one, keeping up to 64 tables, the first kept dropped
536/// first. The run and the reference area are the only inputs the table is built from: the run is
537/// compared as [`AeroModel::share_supersonic_table`] compares it, and the area by its bits, so a
538/// flight flies the same either way. Building a table takes up to about 125 runs of the shock-expansion method,
539/// a fifth of a second or more.
540///
541/// For a process that flies a few shapes many times through a path that builds a model each time,
542/// such as the command line run in-process: the motor catalog's check flies 924 motors in 24
543/// probe shapes (issue #1427; its timings are in `docs/perf.md`). Off by default, so that every model builds its own table unless it shares
544/// one by [`AeroModel::share_supersonic_table`]: a check that a shared table's flight matches one
545/// flown alone needs the one alone built afresh. It stays on for the rest of the process.
546pub fn keep_supersonic_tables() {
547    KEEPING_TABLES.store(true, Ordering::Relaxed);
548}
549
550/// Supersonic tables, each with the run and the reference area it was built from, at most `most`
551/// of them, the first kept dropped first.
552#[derive(Debug)]
553struct KeptTables {
554    tables: VecDeque<(SupersonicRun, f64, Option<SupersonicBody>)>,
555    most: usize,
556}
557
558impl KeptTables {
559    /// None kept yet.
560    const fn new(most: usize) -> Self {
561        Self {
562            tables: VecDeque::new(),
563            most,
564        }
565    }
566
567    /// The table kept for an equal `run` on the same `reference_area_m2` (its bits), if one is.
568    fn find(&self, run: &SupersonicRun, reference_area_m2: f64) -> Option<&Option<SupersonicBody>> {
569        self.tables
570            .iter()
571            .find(|(kept_run, kept_area, _)| {
572                kept_area.to_bits() == reference_area_m2.to_bits() && kept_run == run
573            })
574            .map(|(.., table)| table)
575    }
576
577    /// Keeps `table` for `run` on `reference_area_m2`, unless one is kept for them already,
578    /// dropping the first kept when `most` are.
579    fn keep(
580        &mut self,
581        run: &SupersonicRun,
582        reference_area_m2: f64,
583        table: &Option<SupersonicBody>,
584    ) {
585        if self.most == 0 || self.find(run, reference_area_m2).is_some() {
586            return;
587        }
588        if self.tables.len() >= self.most {
589            self.tables.pop_front();
590        }
591        self.tables
592            .push_back((run.clone(), reference_area_m2, table.clone()));
593    }
594}
595
596/// [`SupersonicBody::new`]'s table for `run` on `reference_area_m2`; while this process keeps its
597/// tables ([`keep_supersonic_tables`]), a copy of one it kept for an equal run on the same
598/// reference area, where there is one. A lock another thread poisoned is passed over: the table
599/// is then built here, and not kept.
600fn built_table(run: &SupersonicRun, reference_area_m2: f64) -> Option<SupersonicBody> {
601    if !KEEPING_TABLES.load(Ordering::Relaxed) {
602        return SupersonicBody::new(run, reference_area_m2);
603    }
604    if let Ok(kept) = KEPT.lock()
605        && let Some(table) = kept.find(run, reference_area_m2)
606    {
607        return table.clone();
608    }
609    // Built outside the lock: two threads may both build one table, and each gets the same.
610    let table = SupersonicBody::new(run, reference_area_m2);
611    if let Ok(mut kept) = KEPT.lock() {
612        kept.keep(run, reference_area_m2, &table);
613    }
614    table
615}
616
617impl PartialEq for SupersonicTable {
618    fn eq(&self, _: &Self) -> bool {
619        true
620    }
621}
622
623impl SupersonicBody {
624    /// Tabulates the method's shares of `run`'s segments, whose vertex is at `run.vertex_m` aft
625    /// of the nose tip, or `None` where the method can't take the body or doesn't hold across a
626    /// whole join below Mach 5.
627    fn new(run: &SupersonicRun, reference_area_m2: f64) -> Option<Self> {
628        let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).ok()?;
629        let ahead = match &run.flare {
630            Some(flare) => {
631                Some(ShockExpansionBody::new(&flare.ahead, DEFAULT_ELEMENTS_PER_CURVE).ok()?)
632            }
633            None => None,
634        };
635        let mut in_its_place = Vec::with_capacity(run.boattails.len());
636        for boattail in &run.boattails {
637            in_its_place.push(match boattail {
638                Some(b) => Some(
639                    ShockExpansionBody::new(&b.in_its_place, DEFAULT_ELEMENTS_PER_CURVE).ok()?,
640                ),
641                None => None,
642            });
643        }
644        let at = |step: f64| {
645            run.shares(
646                &body,
647                &in_its_place,
648                ahead.as_ref(),
649                step / SUPERSONIC_STEPS_PER_MACH,
650                reference_area_m2,
651            )
652        };
653        let mut rows = Vec::new();
654        let mut first_step = SUPERSONIC_LAST_STEP + 1;
655        // From Mach 5 down, until the method first fails or a share isn't on its segment.
656        for step in (SUPERSONIC_FIRST_STEP..=SUPERSONIC_LAST_STEP).rev() {
657            let Some(row) = at(step as f64) else {
658                break;
659            };
660            rows.push(row);
661            first_step = step;
662        }
663        rows.reverse();
664        // The join needs its whole width inside the table.
665        if first_step + SUPERSONIC_JOIN_STEPS > SUPERSONIC_LAST_STEP {
666            return None;
667        }
668        // Where the method stops holding between two rows, bisect for that Mach: `high` holds,
669        // `low` doesn't. The join's start then moves continuously with the body's shape, except
670        // where the table itself appears or vanishes: the guard above near Mach 4.7, and the
671        // model switches of issue #87.
672        let mut lead = None;
673        let mut join_start_mach = first_step as f64 / SUPERSONIC_STEPS_PER_MACH;
674        if first_step > SUPERSONIC_FIRST_STEP {
675            let (mut low, mut high) = (first_step as f64 - 1.0, first_step as f64);
676            let mut held = None;
677            for _ in 0..SUPERSONIC_JOIN_BISECTIONS {
678                let mid = 0.5 * (low + high);
679                if mid <= low || mid >= high {
680                    break;
681                }
682                match at(mid) {
683                    Some(row) => {
684                        high = mid;
685                        held = Some(row);
686                    }
687                    None => low = mid,
688                }
689            }
690            if let Some(row) = held {
691                join_start_mach = high / SUPERSONIC_STEPS_PER_MACH;
692                lead = Some(row);
693            }
694        }
695        Some(Self {
696            covered: run.segments.len() + run.sheltered_lips,
697            join_start_mach,
698            first_step,
699            rows,
700            lead,
701            shape_weight: run.shape_weight,
702            stationed: run
703                .bounds_m
704                .iter()
705                .map(Option::is_some)
706                // A sheltered lip keeps slender-body theory's station, as a boattail does.
707                .chain(std::iter::repeat_n(false, run.sheltered_lips))
708                .collect(),
709        })
710    }
711
712    /// How much of the method the body takes at `mach`, in `[0, 1]`: the join's own weight, 0 at
713    /// [`Self::join_start_mach`] and below and 1 from [`SUPERSONIC_JOIN_WIDTH_MACH`] above it,
714    /// times [`Self::shape_weight`]. Slender-body theory takes the rest, so this is the single
715    /// definition of how the two models blend.
716    #[must_use]
717    pub fn weight(&self, mach: f64) -> f64 {
718        self.shape_weight
719            * ((mach - self.join_start_mach) / SUPERSONIC_JOIN_WIDTH_MACH).clamp(0.0, 1.0)
720    }
721
722    /// Whether covered component `index` takes a station of its own from the method past the
723    /// join's start ([`AeroModel::component_station_m`]): a nose's and a cylinder's ahead of any
724    /// boattail do, joined from slender-body theory's station to the method's center of pressure
725    /// as the weight rises. A boattail's, a cylinder's behind it and a sheltered lip's keep
726    /// slender-body theory's station at every Mach number, since their shares may cross zero.
727    /// `false` past [`Self::covered`].
728    #[must_use]
729    pub fn has_station(&self, index: usize) -> bool {
730        self.stationed.get(index).copied().unwrap_or(false)
731    }
732
733    /// Covered component `index`'s share at `mach`, interpolated linearly between rows (clamped
734    /// to the table's ends): slope per radian and moment about the nose tip, m per radian. A
735    /// boattail's share, and a cylinder's behind it, may be negative or cross zero, so their
736    /// moment over slope need not lie on the part.
737    pub fn share(&self, index: usize, mach: f64) -> Option<(f64, f64)> {
738        let x = mach * SUPERSONIC_STEPS_PER_MACH - self.first_step as f64;
739        let (a, b, t) = match &self.lead {
740            // Between the lead row and the first even row.
741            Some(lead) if x < 0.0 => {
742                let lead_x =
743                    self.join_start_mach * SUPERSONIC_STEPS_PER_MACH - self.first_step as f64;
744                let t = ((x - lead_x) / -lead_x).clamp(0.0, 1.0);
745                (lead.get(index)?, self.rows[0].get(index)?, t)
746            }
747            _ => {
748                // `new` keeps at least `SUPERSONIC_JOIN_STEPS + 1` even rows.
749                let i = (x.floor().max(0.0) as usize).min(self.rows.len() - 2);
750                let t = (x - i as f64).clamp(0.0, 1.0);
751                (self.rows[i].get(index)?, self.rows[i + 1].get(index)?, t)
752            }
753        };
754        Some((
755            a.slope_per_rad + t * (b.slope_per_rad - a.slope_per_rad),
756            a.moment_slope_m + t * (b.moment_slope_m - a.moment_slope_m),
757        ))
758    }
759}
760
761/// The whole rocket's rolling moment coefficients at one Mach number ([`AeroModel::roll`]).
762#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
763#[non_exhaustive]
764pub struct Roll {
765    /// `C_l0`: the rolling moment about `+z_B` at no roll rate, from the fins' cant.
766    pub forcing: f64,
767    /// `C_lp = ∂C_l/∂(p d/2V)`, negative: the damping.
768    pub damping: f64,
769}
770
771/// The air-relative flow at one instant.
772#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
773#[serde(deny_unknown_fields)]
774#[non_exhaustive]
775pub struct Flow {
776    /// Mach number: in `[0, 5)` for the normal force and the drag buildup.
777    pub mach: f64,
778    /// Total angle of attack between the body axis `+z_B` and the air-relative velocity, rad, in
779    /// `[0, π]`. The models are small-angle models (see `docs/physics/aero.md`).
780    pub alpha_rad: f64,
781    /// Roll angle of the lateral airflow, rad from `x_B` toward `y_B`: the direction in which the
782    /// air crosses the body. Only fin sets of one or two fins depend on it.
783    pub roll_rad: f64,
784}
785
786impl Flow {
787    /// A flow at `mach`, angle of attack `alpha_rad` and lateral-flow roll `roll_rad`. Checked
788    /// when used ([`Flow::validate`]).
789    pub fn new(mach: f64, alpha_rad: f64, roll_rad: f64) -> Self {
790        Self {
791            mach,
792            alpha_rad,
793            roll_rad,
794        }
795    }
796
797    /// Straight into the wind at `mach`.
798    pub fn axial(mach: f64) -> Self {
799        Self::new(mach, 0.0, 0.0)
800    }
801
802    /// Checks the Mach number against the normal force's range, and the angles.
803    ///
804    /// # Errors
805    ///
806    /// [`AeroError::Mach`] outside `[0, 5)` ([`NORMAL_FORCE_MACH_LIMIT`]), and
807    /// [`AeroError::Domain`] for an angle of attack outside `[0, π]` or a non-finite roll.
808    pub fn validate(&self) -> Result<(), AeroError> {
809        check_mach(self.mach, NORMAL_FORCE_MACH_LIMIT, "the normal force")?;
810        self.validate_angles()
811    }
812
813    /// As [`Flow::validate`], for the drag buildup's range `[0, 5)`, which names the buildup when
814    /// it refuses.
815    fn validate_for_buildup(&self) -> Result<(), AeroError> {
816        check_mach(self.mach, BUILDUP_MACH_LIMIT, "the drag buildup")?;
817        self.validate_angles()
818    }
819
820    /// Checks the angles only.
821    fn validate_angles(&self) -> Result<(), AeroError> {
822        if !(0.0..=PI).contains(&self.alpha_rad) {
823            return Err(AeroError::Domain {
824                what: "angle of attack",
825                value: self.alpha_rad,
826            });
827        }
828        if !self.roll_rad.is_finite() {
829            return Err(AeroError::Domain {
830                what: "flow roll angle",
831                value: self.roll_rad,
832            });
833        }
834        Ok(())
835    }
836}
837
838/// The normal force of a whole rocket, or of one component, at a flow condition.
839#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
840#[non_exhaustive]
841pub struct NormalForce {
842    /// Normal-force coefficient `C_N` on the reference area, in the plane of the flow.
843    pub coefficient: f64,
844    /// `C_N/α` per radian; at `α = 0`, the slope `∂C_N/∂α`.
845    pub slope_per_rad: f64,
846    /// `Σ C_N,i X_i`, m: the normal force's moment about the nose tip per unit dynamic pressure and
847    /// reference area, defined even when the net force is zero.
848    pub moment_m: f64,
849    /// `Σ (C_N,i/α) X_i`, m per radian: [`Self::moment_m`] per radian of angle of attack, and at
850    /// `α = 0` its slope `Σ C_Nα,i X_i`. It is defined when the slopes cancel, where the center of
851    /// pressure is not: the loads are then a pure couple.
852    pub moment_slope_m: f64,
853    /// Center of pressure, m aft of the nose tip; `None` when the slope is zero, or so small
854    /// against its terms (below 1e-12 of `Σ |C_Nα,i|`) that the ratio would be noise.
855    pub cp_station_m: Option<f64>,
856    /// Side-force coefficient across the plane of the flow, along `z_B` × the lateral-flow
857    /// direction. Only fin sets of one or two fins produce it ([`crate::fins::side_sum`]).
858    pub side_coefficient: f64,
859    /// `Σ C_Y,i X_i`, m: the side force's moment about the nose tip per unit dynamic pressure and
860    /// reference area.
861    pub side_moment_m: f64,
862    /// The override table's lookup, on the table's reference area, when the whole rocket's normal
863    /// force came from one ([`AeroModel::with_normal_force_table`]): whether the Mach number was
864    /// outside a column's range, or the angle past the last column's.
865    #[serde(default, skip_serializing_if = "Option::is_none")]
866    pub table: Option<NormalForceLookup>,
867}
868
869/// One component's contributions per radian: slope, moment slope about the nose tip, side slope
870/// and side moment slope, and `Σ |terms|` of the slope to judge cancellation.
871#[derive(Clone, Copy, Default)]
872struct Term {
873    slope: f64,
874    moment: f64,
875    side: f64,
876    side_moment: f64,
877    scale: f64,
878}
879
880impl Term {
881    /// This term `k` times over: `k` copies of a component.
882    fn times(self, k: f64) -> Term {
883        Term {
884            slope: k * self.slope,
885            moment: k * self.moment,
886            side: k * self.side,
887            side_moment: k * self.side_moment,
888            scale: k * self.scale,
889        }
890    }
891
892    fn add(self, other: Term) -> Term {
893        Term {
894            slope: self.slope + other.slope,
895            moment: self.moment + other.moment,
896            side: self.side + other.side,
897            side_moment: self.side_moment + other.side_moment,
898            scale: self.scale + other.scale,
899        }
900    }
901}
902
903impl NormalForce {
904    fn new(term: Term, alpha_rad: f64) -> Self {
905        let cancelled = term.slope.abs() <= 1e-12 * term.scale;
906        Self {
907            coefficient: term.slope * alpha_rad,
908            slope_per_rad: term.slope,
909            moment_m: term.moment * alpha_rad,
910            moment_slope_m: term.moment,
911            cp_station_m: (term.slope != 0.0 && !cancelled).then(|| term.moment / term.slope),
912            side_coefficient: term.side * alpha_rad,
913            side_moment_m: term.side_moment * alpha_rad,
914            table: None,
915        }
916    }
917}
918
919/// One component's share of the normal force.
920#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
921#[non_exhaustive]
922pub struct ComponentNormalForce {
923    /// The component's id.
924    pub id: String,
925    /// Its normal force.
926    pub normal_force: NormalForce,
927}
928
929/// A body component's precomputed terms.
930///
931/// Serialize-only, like [`AeroModel`]: the terms are computed by [`AeroModel::new`], not read.
932#[derive(Debug, Clone, PartialEq, Serialize)]
933#[non_exhaustive]
934pub struct BodyAero {
935    /// The component's id.
936    pub id: String,
937    /// Station of its fore end, m.
938    pub fore_station_m: f64,
939    /// Its geometry.
940    pub geometry: BodyGeometry,
941    /// The step in cross-section area from the previous body component's aft end to this one's
942    /// fore end, m² (zero for the first body component).
943    pub step_area_m2: f64,
944    /// Slender-body theory's potential-flow slope at `α → 0`, per radian, with the step. Faster
945    /// than sound a body the shock-expansion method covers takes its share instead
946    /// ([`SupersonicBody`]).
947    pub slope_per_rad: f64,
948    /// Slender-body theory's potential-flow moment slope about the nose tip, m per radian, with
949    /// the step.
950    pub moment_slope_m: f64,
951    /// Its planform over the reference area, `A_plan / A_ref`: body lift is
952    /// `C_N = factor · planform_ratio · sin² α`, the factor from the model's [`BodyLift`].
953    pub planform_ratio: f64,
954    /// Station of the body lift, m.
955    pub lift_station_m: f64,
956}
957
958/// A fin set's precomputed terms.
959///
960/// Serialize-only, like [`AeroModel`].
961#[derive(Debug, Clone, PartialEq, Serialize)]
962#[non_exhaustive]
963pub struct FinSetAero {
964    /// The component's id.
965    pub id: String,
966    /// Number of fins.
967    pub count: u32,
968    /// Roll angle of the first fin, rad.
969    pub base_angle_rad: f64,
970    /// One fin's normal force through the speed regimes, and its geometry.
971    pub fin: FinAero,
972    /// Fin–fin factor `f_N`.
973    pub count_factor: f64,
974    /// Fin–body interference `K_T(B)`.
975    pub interference: f64,
976    /// Station of the fins' root leading edge, m aft of the nose tip.
977    pub fore_station_m: f64,
978    /// Cant, rad: positive turns fin 0's leading edge toward `−y_B` (`hpr_design::FinSet`).
979    pub cant_rad: f64,
980    /// Radius of the body tube at the fins, m.
981    pub body_radius_m: f64,
982    /// The body's interference with the roll forcing, `k_T(B)` ([`roll_forcing_interference`]).
983    pub roll_forcing_interference: f64,
984    /// The body's interference with the roll damping, `k_R(B)` ([`roll_damping_interference`]).
985    pub roll_damping_interference: f64,
986    /// One fin's roll terms on this body ([`FinAero::roll_terms`]).
987    pub roll: FinRollTerms,
988    /// For a fin set in a pod set, its copies: one per pod. `None` for the airframe's.
989    pub pods: Option<PodFins>,
990}
991
992/// A pod's fin set flown once per pod ([`FinSetAero::pods`]).
993///
994/// Serialize-only, like [`AeroModel`].
995#[derive(Debug, Clone, PartialEq, Serialize)]
996#[non_exhaustive]
997pub struct PodFins {
998    /// Each copy's turn about the rocket's axis, rad, from `x_B` toward `y_B`: a pod turns what it
999    /// holds with it ([`hpr_design::Placement`]), so copy `k`'s fin `j` stands at
1000    /// `θ_j + roll_k`.
1001    pub roll_rad: Vec<f64>,
1002    /// Every fin of every copy, `N` of them, is `ρ_i` from the rocket's axis at its root, along
1003    /// its span: `ρ = o · ê + r_t`, with `o` the copy's offset, `ê` the fin's direction and `r_t`
1004    /// the pod's tube radius. A fin's roll damping is quadratic in `ρ`
1005    /// ([`FinAero::roll_terms`], `∫(ρ + y)² …`), so the sum over the fins is `N/2` times the
1006    /// damping at `μ + σ` plus that at `μ − σ`, with `μ` and `σ` the mean and the standard
1007    /// deviation of the `ρ_i`: these two terms, exactly. Their `body_radius_m` is that offset,
1008    /// which may be negative, and only their damping means anything: a pod's fins are never
1009    /// canted. [`FinSetAero::roll`] is not used for a pod's fins. The whole sum takes the pod
1010    /// tube's roll-damping interference `k_R(B)`, exact for fins on a pod of no radius, where it
1011    /// is 1 (`docs/physics/aero.md`, *Pods*).
1012    pub axis_roll: [FinRollTerms; 2],
1013    /// `N`, the fins over all the copies.
1014    pub fins: u32,
1015}
1016
1017/// A pod set's precomputed terms: one pod's body components, flown once per pod.
1018///
1019/// Each copy's force acts on the rocket's axis at its station. For two pods or more, which stand
1020/// evenly around the axis, the copies' offsets add to zero, so the sum of their forces there has
1021/// the same moment as each at its own pod; the roll damping their offsets give is added in
1022/// [`AeroModel::roll`]. A single pod's drag and normal force off the axis make a moment the model
1023/// leaves out (`docs/physics/aero.md`, *Pods*).
1024///
1025/// Serialize-only, like [`AeroModel`].
1026#[derive(Debug, Clone, PartialEq, Serialize)]
1027#[non_exhaustive]
1028pub struct PodSetAero {
1029    /// The pod set's id.
1030    pub id: String,
1031    /// How many pods fly.
1032    pub copies: u32,
1033    /// `Σ |o_k|²` over the pods, m²: each one's squared distance from the rocket's axis.
1034    pub offset_squares_m2: f64,
1035    /// One pod's length over its largest diameter, which sets its body lift's `η`; 0 for a pod
1036    /// with no body of any size.
1037    pub fineness: f64,
1038    /// Fig. 4's `η` at that fineness.
1039    crossflow_eta_low: f64,
1040    /// One pod's body components, fore to aft, each one copy's terms, at stations along the
1041    /// rocket's axis. The pod's first body has no step in its normal force, as the airframe's
1042    /// first has none; its drag counts its bare front face.
1043    pub bodies: Vec<BodyAero>,
1044}
1045
1046impl FinSetAero {
1047    /// The set's center of pressure at `mach`, m aft of the nose tip.
1048    ///
1049    /// # Errors
1050    ///
1051    /// As [`FinAero::loading`].
1052    pub fn cp_station_m(&self, mach: f64) -> Result<f64, AeroError> {
1053        Ok(self.fore_station_m + self.fin.loading(mach)?.cp_m)
1054    }
1055}
1056
1057/// A rocket's aerodynamic model: normal force, center of pressure and drag.
1058///
1059/// Serialize-only, for inspection: a model is built from a [`Layout`] by [`AeroModel::new`], which
1060/// checks what it builds.
1061#[derive(Debug, Clone, PartialEq, Serialize)]
1062pub struct AeroModel {
1063    reference_area_m2: f64,
1064    reference_diameter_m: f64,
1065    length_m: f64,
1066    /// The largest radius of the bodies, m: RASAero II's reference.
1067    max_body_radius_m: f64,
1068    /// The body's length over its largest diameter, for body lift's `η` ([`crate::crossflow`]).
1069    fineness: f64,
1070    /// Fig. 4's `η` at that fineness, computed once.
1071    crossflow_eta_low: f64,
1072    /// The body-lift and boattail rules.
1073    body_model: BodyModel,
1074    bodies: Vec<BodyAero>,
1075    /// The pod sets that hold a body component.
1076    pods: Vec<PodSetAero>,
1077    /// The nose, the cylinders and boattails behind it, for the shock-expansion method.
1078    #[serde(skip)]
1079    supersonic_run: Option<SupersonicRun>,
1080    /// Why there is no run, when there is none ([`Self::supersonic_fallback`]).
1081    #[serde(skip)]
1082    supersonic_stop: Option<SupersonicFallback>,
1083    /// Their tabulated shares, built the first time a flow faster than
1084    /// [`SUPERSONIC_JOIN_START_MACH`] needs them: building takes up to about 125 runs of the
1085    /// method.
1086    #[serde(skip)]
1087    supersonic: SupersonicTable,
1088    fin_sets: Vec<FinSetAero>,
1089    tube_fin_sets: Vec<TubeFinSetAero>,
1090    drag_terms: Vec<ComponentDragTerms>,
1091    drag_table: Option<DragTable>,
1092    /// A program's own drag model ([`crate::custom`]), in place of the buildup and any table:
1093    /// serialized as its `Debug` text, and left out when there is none.
1094    #[serde(skip_serializing_if = "Option::is_none")]
1095    drag_model: Option<SharedDragModel>,
1096    normal_force_table: Option<NormalForceTable>,
1097    /// Whether the aft base keeps its whole drag while a motor burns
1098    /// ([`AeroModel::with_full_base_drag_under_power`]).
1099    full_base_drag_under_power: bool,
1100    /// The factor on every zero-lift drag coefficient this model gives
1101    /// ([`AeroModel::with_drag_scale`]); left out when it is 1.
1102    #[serde(skip_serializing_if = "is_one")]
1103    drag_scale: f64,
1104}
1105
1106/// Whether a drag scale is 1, the factor that changes nothing (by reference, as serde's
1107/// `skip_serializing_if` asks).
1108fn is_one(scale: &f64) -> bool {
1109    *scale == 1.0
1110}
1111
1112/// `drag` with its zero-lift coefficient and its five parts multiplied by `scale`
1113/// ([`AeroModel::with_drag_scale`]).
1114fn scaled(mut drag: Drag, scale: f64) -> Drag {
1115    if scale != 1.0 {
1116        for part in [
1117            &mut drag.zero_lift_coefficient,
1118            &mut drag.friction,
1119            &mut drag.pressure,
1120            &mut drag.base,
1121            &mut drag.parasitic,
1122            &mut drag.stated,
1123        ] {
1124            *part *= scale;
1125        }
1126    }
1127    drag
1128}
1129
1130/// Puts the drag coefficients the layout's components and stages state in place of their own
1131/// drag ([`hpr_design::DragOverride`], ADR-167): each overridden component's terms take its
1132/// coefficient times its instances, a part its parent's or stage's override covers takes zero,
1133/// a step down behind an overridden body component goes with it, and a stage's coefficient is a
1134/// term of its own. `body_terms` are the airframe's body components' terms, fore to aft.
1135///
1136/// # Errors
1137///
1138/// [`AeroError::Domain`] for a stated coefficient that is negative or not finite, on any
1139/// component or stage, and [`AeroError::Unsupported`] for one OpenRocket hasn't been measured
1140/// on: on a pod set or in a pod, covering one, on a tube fin set, on a parallel stage, or covering
1141/// a stage one hangs on.
1142fn apply_drag_overrides(
1143    layout: &Layout,
1144    drag_terms: &mut Vec<ComponentDragTerms>,
1145    body_terms: &[(usize, BodyGeometry)],
1146) -> Result<(), AeroError> {
1147    let check = |id: &str, coefficient: f64| {
1148        if coefficient.is_finite() && coefficient >= 0.0 {
1149            Ok(coefficient)
1150        } else {
1151            Err(AeroError::InComponent {
1152                id: id.to_owned(),
1153                source: Box::new(AeroError::Domain {
1154                    what: "stated drag coefficient",
1155                    value: coefficient,
1156                }),
1157            })
1158        }
1159    };
1160    let unsupported = |id: &str, what: &str| AeroError::InComponent {
1161        id: id.to_owned(),
1162        source: Box::new(AeroError::Unsupported(what.to_owned())),
1163    };
1164    for (k, stage) in layout.stages.iter().enumerate() {
1165        if let Some(stated) = stage.drag_override {
1166            check(&stage.id, stated.coefficient)?;
1167            // A parallel stage is laid out as a pod set, and how OpenRocket flies an override on
1168            // one, or one covering a stage that holds one, hasn't been measured (ADR-171).
1169            if stage.hung_on.is_some() {
1170                return Err(unsupported(
1171                    &stage.id,
1172                    "a drag override on a parallel stage",
1173                ));
1174            }
1175            if stated.include_children && layout.stages.iter().any(|s| s.hung_on == Some(k)) {
1176                return Err(unsupported(
1177                    &stage.id,
1178                    "a drag override covering a stage a parallel stage hangs on",
1179                ));
1180            }
1181        }
1182    }
1183    // Whether each component is covered by a parent's override or its stage's, whatever it
1184    // states itself. The walk up takes at most one step per component, as
1185    // `Layout::pod_set_of`'s does, so a layout whose parents loop ends it.
1186    let mut covered = Vec::with_capacity(layout.components.len());
1187    for (index, component) in layout.components.iter().enumerate() {
1188        if let Some(stated) = component.drag_override {
1189            check(&component.id, stated.coefficient)?;
1190        }
1191        let mut covers = layout
1192            .stages
1193            .get(component.stage)
1194            .and_then(|s| s.drag_override)
1195            .is_some_and(|o| o.include_children);
1196        let mut parent = component.parent;
1197        for _ in 0..layout.components.len() {
1198            let Some(up) = parent.and_then(|at| layout.components.get(at)) else {
1199                break;
1200            };
1201            covers |= up.drag_override.is_some_and(|o| o.include_children);
1202            parent = up.parent;
1203        }
1204        let in_pod =
1205            layout.pod_set_of(index).is_some() || matches!(component.part, Part::PodSet(_));
1206        if in_pod && component.drag_override.is_some() {
1207            return Err(unsupported(
1208                &component.id,
1209                "a drag override on a pod set or in a pod",
1210            ));
1211        }
1212        if in_pod && covers {
1213            return Err(unsupported(
1214                &component.id,
1215                "a drag override covering a pod set",
1216            ));
1217        }
1218        if component.drag_override.is_some() && matches!(component.part, Part::TubeFinSet(_)) {
1219            return Err(unsupported(
1220                &component.id,
1221                "a drag override on a tube fin set",
1222            ));
1223        }
1224        covered.push(covers);
1225    }
1226    for terms in drag_terms.iter_mut() {
1227        let Some((index, component)) = layout.find(&terms.id) else {
1228            continue;
1229        };
1230        terms.stated = if covered[index] {
1231            Some(0.0)
1232        } else if let Some(stated) = component.drag_override {
1233            let instances = match &component.part {
1234                Part::FinSet(set) => set.count,
1235                Part::LaunchLug(lug) => lug.count,
1236                Part::RailButton(button) => button.count,
1237                _ => 1,
1238            };
1239            Some(stated.coefficient * f64::from(instances))
1240        } else {
1241            None
1242        };
1243    }
1244    // A step down is the aft face of the part ahead of it: it goes with that part's drag.
1245    for pair in body_terms.windows(2) {
1246        let (ahead, behind) = (pair[0].0, pair[1].0);
1247        if drag_terms[ahead].stated.is_some() {
1248            let terms = &mut drag_terms[behind];
1249            terms.boattail_area_ratio -= terms.fore_step_down_area_ratio;
1250            terms.fore_step_down_area_ratio = 0.0;
1251        }
1252    }
1253    for stage in &layout.stages {
1254        if let Some(stated) = stage.drag_override {
1255            drag_terms.push(ComponentDragTerms::stage(&stage.id, stated.coefficient));
1256        }
1257    }
1258    Ok(())
1259}
1260
1261/// `drag` with its axial coefficient at an angle of attack whose factor is `factor`
1262/// ([`axial_drag_alpha_factor`]): `C_A = C_D0 f(α)`.
1263///
1264/// # Errors
1265///
1266/// [`AeroError::Domain`] if either coefficient isn't finite.
1267fn with_axial(mut drag: Drag, factor: f64) -> Result<Drag, AeroError> {
1268    drag.axial_coefficient = drag.zero_lift_coefficient * factor;
1269    if !(drag.zero_lift_coefficient.is_finite() && drag.axial_coefficient.is_finite()) {
1270        return Err(AeroError::Domain {
1271            what: "drag coefficient",
1272            value: drag.zero_lift_coefficient,
1273        });
1274    }
1275    Ok(drag)
1276}
1277
1278impl AeroModel {
1279    /// Builds the terms of every component of `layout`, with HPR Sim's current body model
1280    /// ([`BodyModel::default`]).
1281    ///
1282    /// # Errors
1283    ///
1284    /// As [`Self::with_body_model`].
1285    pub fn new(layout: &Layout) -> Result<Self, AeroError> {
1286        Self::with_body_model(layout, BodyModel::default())
1287    }
1288
1289    /// Builds the terms of every component of `layout`, its bodies' lift and supersonic boattails
1290    /// by `body_model`.
1291    ///
1292    /// # Errors
1293    ///
1294    /// - [`AeroError::Domain`] for a non-positive reference diameter, rocket length or body radius.
1295    /// - [`AeroError::InComponent`] naming the component, around:
1296    ///   - [`AeroError::Unsupported`] for tube fins the ring-wing model doesn't take (fewer than
1297    ///     three, solid, shorter than a third of their diameter, overlapping, or on a pod),
1298    ///     canted fins on a pod, a pod's tube of no length with a radius (a flat disc), or a part
1299    ///     kind or fin cross-section this model doesn't know (a nose shape the drag buildup has
1300    ///     no data for builds, and the buildup refuses it when asked: [`AeroModel::drag`]);
1301    ///   - [`AeroError::Domain`] for a fin set of more than eight fins, a non-finite station, a
1302    ///     pod's body with no fineness, or a drag input out of range (a negative fin thickness, a
1303    ///     launch lug's wall thicker than its radius, a rail button's base and flange taller than
1304    ///     the button, a negative roughness);
1305    ///   - [`AeroError::Layout`] for a fin set or tube fin set without the radius of its body
1306    ///     tube, or a pod's body component listed before its pod set;
1307    ///   - design errors from a profile, a planform, a volume integral or a pod set's placements.
1308    /// - [`AeroError::Unsupported`] for motor mounts in more than [`MOTOR_POD_SETS`] pod sets,
1309    ///   whose thrusting areas [`DragConditions`] can't tell apart.
1310    /// - [`AeroError::Domain`] for a body-lift `K` that isn't finite and non-negative.
1311    pub fn with_body_model(layout: &Layout, body_model: BodyModel) -> Result<Self, AeroError> {
1312        body_model.body_lift.validate()?;
1313        check_dimension("reference diameter", layout.reference_diameter_m, false)?;
1314        let reference_area_m2 = layout.reference_area_m2();
1315        let length_m = layout.length_m;
1316        check_dimension("rocket length", length_m, false)?;
1317        let mut max_radius: f64 = 0.0;
1318        for component in layout.body() {
1319            if let Some(radius) = component.part.max_radius_m()? {
1320                max_radius = max_radius.max(radius);
1321            }
1322        }
1323        check_dimension("maximum body radius", max_radius, false)?;
1324        let fineness = length_m / (2.0 * max_radius);
1325        let form_factor = body_friction_form_factor(fineness)?;
1326        let mut bodies = Vec::new();
1327        let mut fin_sets = Vec::new();
1328        let mut tube_fin_sets = Vec::new();
1329        let mut drag_terms = Vec::new();
1330        let mut previous_aft_area: Option<f64> = None;
1331        let mut body_terms_at = Vec::new();
1332        let mut last_body_terms: Option<usize> = None;
1333        // The nose, the cylinders and boattails behind it, for the shock-expansion method: the
1334        // run stops at the first other body (a flare), step in radius or gap.
1335        let mut supersonic_segments = Vec::new();
1336        let mut supersonic_bounds = Vec::new();
1337        let mut supersonic_fore = Vec::new();
1338        let mut supersonic_boattails = Vec::new();
1339        let mut flare: Option<RunFlare> = None;
1340        let mut proposed_flare: Option<&hpr_design::Transition> = None;
1341        let mut supersonic_open = true;
1342        let mut behind_boattail = false;
1343        let (mut vertex_m, mut supersonic_end_m) = (0.0, 0.0);
1344        // The pod sets being built, and where each pod set of the layout is among them.
1345        let mut pods: Vec<PodBuild> = Vec::new();
1346        let mut pod_at: Vec<Option<usize>> = vec![None; layout.components.len()];
1347        // The pod sets that hold motor mounts: each one's bases take its thrusting motors' area
1348        // ([`DragConditions::thrusting_pod_motor_areas_m2`]).
1349        let motor_pod_sets = motor_pod_sets(layout)?;
1350        for (index, component) in layout.components.iter().enumerate() {
1351            let in_component = |e: AeroError| AeroError::InComponent {
1352                id: component.id.clone(),
1353                source: Box::new(e),
1354            };
1355            if !component.fore_station_m.is_finite() {
1356                return Err(in_component(AeroError::Domain {
1357                    what: "component station",
1358                    value: component.fore_station_m,
1359                }));
1360            }
1361            // A pod's parts: its body components build the pod's own terms, never the airframe's.
1362            let pod = layout.pod_set_of(index).map(|set| pod_at[set]);
1363            let first_new_drag_term = drag_terms.len();
1364            if let Some(at) = pod
1365                && matches!(
1366                    component.part,
1367                    Part::NoseCone(_) | Part::Transition(_) | Part::BodyTube(_)
1368                )
1369            {
1370                // A pod set comes before what it holds, depth first.
1371                let build = at.and_then(|at| pods.get_mut(at)).ok_or_else(|| {
1372                    in_component(AeroError::Layout(
1373                        "a pod's body component before its pod set".to_owned(),
1374                    ))
1375                })?;
1376                build
1377                    .add_body(component, &mut drag_terms, length_m, reference_area_m2)
1378                    .map_err(in_component)?;
1379                continue;
1380            }
1381            let body = match &component.part {
1382                Part::NoseCone(nose) => Some(
1383                    nose.profile()
1384                        .map_err(AeroError::from)
1385                        .and_then(|p| BodyGeometry::from_profile(&p)),
1386                ),
1387                Part::Transition(transition) => Some(
1388                    transition
1389                        .profile()
1390                        .map_err(AeroError::from)
1391                        .and_then(|p| BodyGeometry::from_profile(&p)),
1392                ),
1393                Part::BodyTube(tube) => {
1394                    Some(BodyGeometry::cylinder(tube.length_m, tube.outer_radius_m))
1395                }
1396                Part::FinSet(set) => {
1397                    let mut terms = (|| {
1398                        let fin = FinAero::new(&set.planform, reference_area_m2)?;
1399                        let body_radius = component.body_radius_m.ok_or_else(|| {
1400                            AeroError::Layout(
1401                                "a fin set needs the radius of the body tube it is on".to_owned(),
1402                            )
1403                        })?;
1404                        // Past 15° a fin stalls, where the linear roll model means nothing, and a
1405                        // single canted fin pushes sideways, which the model doesn't carry.
1406                        if !set.cant_rad.is_finite() || set.cant_rad.abs() > MAX_CANT_RAD {
1407                            return Err(AeroError::Domain {
1408                                what: "fin cant",
1409                                value: set.cant_rad,
1410                            });
1411                        }
1412                        if set.count < 2 && set.cant_rad != 0.0 {
1413                            return Err(AeroError::Unsupported(
1414                                "cant on a single fin, whose side force isn't modeled".to_owned(),
1415                            ));
1416                        }
1417                        let span = fin.geometry().span_m;
1418                        let taper = fin.outline().tip_chord_m() / set.planform.root_chord_m();
1419                        let roll = fin.roll_terms(body_radius, layout.reference_diameter_m)?;
1420                        Ok(FinSetAero {
1421                            id: component.id.clone(),
1422                            count: set.count,
1423                            base_angle_rad: set.base_angle_rad,
1424                            count_factor: fin_count_factor(set.count)?,
1425                            interference: interference_factor(span, body_radius)?,
1426                            fore_station_m: component.fore_station_m,
1427                            cant_rad: set.cant_rad,
1428                            body_radius_m: body_radius,
1429                            roll_forcing_interference: roll_forcing_interference(
1430                                span,
1431                                body_radius,
1432                            )?,
1433                            roll_damping_interference: roll_damping_interference(
1434                                span,
1435                                body_radius,
1436                                taper,
1437                            )?,
1438                            roll,
1439                            fin,
1440                            pods: None,
1441                        })
1442                    })()
1443                    .map_err(in_component)?;
1444                    if pod.is_some() {
1445                        terms.pods = Some(
1446                            pod_fins(set, component, &terms, layout.reference_diameter_m)
1447                                .map_err(in_component)?,
1448                        );
1449                    }
1450                    drag_terms.push(
1451                        ComponentDragTerms::fins(
1452                            component,
1453                            set,
1454                            terms.fin.geometry(),
1455                            length_m,
1456                            reference_area_m2,
1457                        )
1458                        .map_err(in_component)?,
1459                    );
1460                    fin_sets.push(terms);
1461                    None
1462                }
1463                Part::TubeFinSet(set) => {
1464                    if pod.is_some() {
1465                        return Err(in_component(AeroError::Unsupported(
1466                            "tube fins on a pod".to_owned(),
1467                        )));
1468                    }
1469                    let terms = TubeFinSetAero::new(component, set, reference_area_m2)
1470                        .map_err(in_component)?;
1471                    drag_terms.push(
1472                        ComponentDragTerms::tube_fins(component, set, length_m, reference_area_m2)
1473                            .map_err(in_component)?,
1474                    );
1475                    tube_fin_sets.push(terms);
1476                    None
1477                }
1478                // A pod set that holds nothing adds no force.
1479                Part::PodSet(_) if !layout.components.iter().any(|c| c.parent == Some(index)) => {
1480                    None
1481                }
1482                Part::PodSet(_) => {
1483                    pod_at[index] = Some(pods.len());
1484                    let mut build =
1485                        PodBuild::new(layout, index, component).map_err(in_component)?;
1486                    build.motor_pod_set = motor_pod_sets.iter().position(|&set| set == index);
1487                    pods.push(build);
1488                    None
1489                }
1490                // Drag only.
1491                Part::LaunchLug(lug) => {
1492                    drag_terms.push(
1493                        ComponentDragTerms::launch_lugs(
1494                            component,
1495                            lug,
1496                            length_m,
1497                            reference_area_m2,
1498                        )
1499                        .map_err(in_component)?,
1500                    );
1501                    None
1502                }
1503                Part::RailButton(button) => {
1504                    drag_terms.push(
1505                        ComponentDragTerms::rail_buttons(
1506                            component,
1507                            button,
1508                            length_m,
1509                            reference_area_m2,
1510                        )
1511                        .map_err(in_component)?,
1512                    );
1513                    None
1514                }
1515                // Inside the body.
1516                Part::InnerTube(_)
1517                | Part::CenteringRing(_)
1518                | Part::MassComponent(_)
1519                | Part::Parachute(_)
1520                | Part::Streamer(_)
1521                | Part::ShockCord(_) => None,
1522                other => {
1523                    return Err(in_component(AeroError::Unsupported(format!(
1524                        "a {} part",
1525                        other.kind_name()
1526                    ))));
1527                }
1528            };
1529            // A pod's fins, lugs and buttons drag once per pod.
1530            if pod.is_some() {
1531                let copies = copy_count(component).map_err(in_component)?;
1532                for terms in &mut drag_terms[first_new_drag_term..] {
1533                    terms.copies = copies;
1534                    terms.in_pod = true;
1535                }
1536            }
1537            if let Some(geometry) = body {
1538                let geometry = geometry.map_err(in_component)?;
1539                let step = previous_aft_area.map_or(0.0, |aft| geometry.fore_area_m2 - aft);
1540                last_body_terms = Some(drag_terms.len());
1541                drag_terms.push(
1542                    ComponentDragTerms::body(
1543                        component,
1544                        &geometry,
1545                        match &component.part {
1546                            Part::NoseCone(nose) => Some(nose.shape),
1547                            Part::Transition(transition) => Some(transition.shape),
1548                            _ => None,
1549                        },
1550                        previous_aft_area,
1551                        form_factor,
1552                        length_m,
1553                        reference_area_m2,
1554                    )
1555                    .map_err(in_component)?,
1556                );
1557                body_terms_at.push((drag_terms.len() - 1, geometry));
1558                let segment = match &component.part {
1559                    Part::NoseCone(nose) if bodies.is_empty() => nose
1560                        .profile()
1561                        .ok()
1562                        .map(|profile| BodySegment::Profile { profile }),
1563                    Part::BodyTube(tube)
1564                        if !bodies.is_empty()
1565                            && step.abs() <= 1e-6 * geometry.fore_area_m2
1566                            && (component.fore_station_m - supersonic_end_m).abs()
1567                                <= 1e-9 * length_m =>
1568                    {
1569                        Some(BodySegment::Cylinder {
1570                            length_m: tube.length_m,
1571                            radius_m: tube.outer_radius_m,
1572                        })
1573                    }
1574                    // A boattail: footnote 8's tangent cone for its elements.
1575                    Part::Transition(transition)
1576                        if !bodies.is_empty()
1577                            && transition.aft_radius_m < transition.fore_radius_m
1578                            && step.abs() <= 1e-6 * geometry.fore_area_m2
1579                            && (component.fore_station_m - supersonic_end_m).abs()
1580                                <= 1e-9 * length_m =>
1581                    {
1582                        transition
1583                            .profile()
1584                            .ok()
1585                            .map(|profile| BodySegment::Profile { profile })
1586                    }
1587                    // A conical flare: the march turns the flow at its corner, and the run ends
1588                    // there (ADR-047). Any other widening shape ends the run without joining it,
1589                    // as every flare did before M1.8e17: the corner's turn is then the profile's
1590                    // own slope at its fore end, which the attachment test is not written for.
1591                    // A widening part behind a boattail is not a flare in the free stream but a
1592                    // lip in the boattail's wake, whose flow the march does not compute: it keeps
1593                    // its own rule (ADR-039, `sheltered_lips` below).
1594                    Part::Transition(transition)
1595                        if !bodies.is_empty()
1596                            && !behind_boattail
1597                            && transition.aft_radius_m > transition.fore_radius_m
1598                            && matches!(transition.shape, NoseShape::Conical {})
1599                            && body_model.supersonic_flare == SupersonicFlare::Marched
1600                            && step.abs() <= 1e-6 * geometry.fore_area_m2
1601                            && (component.fore_station_m - supersonic_end_m).abs()
1602                                <= 1e-9 * length_m =>
1603                    {
1604                        proposed_flare = Some(transition);
1605                        transition
1606                            .profile()
1607                            .ok()
1608                            .map(|profile| BodySegment::Profile { profile })
1609                    }
1610                    _ => None,
1611                };
1612                match segment {
1613                    Some(segment) if supersonic_open => {
1614                        if supersonic_segments.is_empty() {
1615                            vertex_m = component.fore_station_m;
1616                        }
1617                        // Only a segment the run actually takes is the run's flare, and its index
1618                        // is the one `shares` reads its share and station back at.
1619                        if let Some(transition) = proposed_flare.take() {
1620                            flare = Some(RunFlare {
1621                                index: supersonic_segments.len(),
1622                                ahead: supersonic_segments.clone(),
1623                                fore_radius_m: transition.fore_radius_m,
1624                                aft_radius_m: transition.aft_radius_m,
1625                                length_m: transition.length_m,
1626                                clipped: transition.clipped,
1627                            });
1628                        }
1629                        // Washington and Pettis's boattail: the run so far with a cylinder of its
1630                        // length and fore radius in its place.
1631                        supersonic_boattails.push(match (&component.part, body_model) {
1632                            (
1633                                Part::Transition(transition),
1634                                BodyModel {
1635                                    supersonic_boattail: SupersonicBoattail::WashingtonPettis,
1636                                    ..
1637                                },
1638                            ) if transition.aft_radius_m < transition.fore_radius_m => {
1639                                let mut in_its_place = supersonic_segments.clone();
1640                                in_its_place.push(BodySegment::Cylinder {
1641                                    length_m: transition.length_m,
1642                                    radius_m: transition.fore_radius_m,
1643                                });
1644                                Some(RunBoattail {
1645                                    in_its_place,
1646                                    fore_radius_m: transition.fore_radius_m,
1647                                    aft_radius_m: transition.aft_radius_m,
1648                                    length_m: transition.length_m,
1649                                })
1650                            }
1651                            _ => None,
1652                        });
1653                        supersonic_segments.push(segment);
1654                        let fore_m = component.fore_station_m;
1655                        supersonic_fore.push(fore_m);
1656                        supersonic_end_m = fore_m + geometry.length_m;
1657                        // From a boattail aft, the shares may cross zero: the tail behind it
1658                        // carries the decay of the boattail's expansion. A flare's share does
1659                        // not: it is positive with a station on the flare, and the run ends
1660                        // there, so nothing behind it is marched.
1661                        behind_boattail |= matches!(&component.part, Part::Transition(t)
1662                            if t.aft_radius_m < t.fore_radius_m);
1663                        supersonic_bounds
1664                            .push((!behind_boattail).then_some((fore_m, supersonic_end_m)));
1665                        // The run ends at the flare it just took.
1666                        supersonic_open &= flare.is_none();
1667                    }
1668                    _ => supersonic_open = false,
1669                }
1670                previous_aft_area = Some(geometry.aft_area_m2);
1671                bodies.push(body_terms(component, geometry, step, reference_area_m2));
1672            }
1673        }
1674        // The aft base belongs to the last body component.
1675        if let (Some(index), Some(last)) = (last_body_terms, bodies.last()) {
1676            drag_terms[index].base_area_m2 = last.geometry.aft_area_m2;
1677        }
1678        // Boattails, a lip in a boattail's wake, and the base behind them.
1679        couple_afterbody(&mut drag_terms, &body_terms_at, reference_area_m2)?;
1680        // Each pod's the same, among its own body components.
1681        let mut pod_sets = Vec::new();
1682        for build in pods {
1683            if let Some((index, geometry)) = build.terms_at.last() {
1684                drag_terms[*index].base_area_m2 = geometry.aft_area_m2;
1685            }
1686            couple_afterbody(&mut drag_terms, &build.terms_at, reference_area_m2)?;
1687            if !build.aero.bodies.is_empty() {
1688                pod_sets.push(build.aero);
1689            }
1690        }
1691        // Drag coefficients stated in place of the parts' own (ADR-167).
1692        apply_drag_overrides(layout, &mut drag_terms, &body_terms_at)?;
1693        // The method flies only a body it covers to the end, or whose later bodies carry no
1694        // potential-flow slope: its shares beside slender-body theory's for a flare or step would
1695        // mix the models the way a boattail did before M1.8e4 (physics review, ADR-034).
1696        let marched = supersonic_segments.len();
1697        // A lip wholly in a covered boattail's wake carries nothing faster than sound (ADR-039),
1698        // so the run may cover it; the drag buildup's wake already measures the shelter
1699        // ([`crate::drag::WakeTerm`]), and takes the lip's own drag away at the same threshold.
1700        let mut shelter_weight = 1.0_f64;
1701        // Whether the lip rule last refused a lip for its length (issue #120): the take stops
1702        // there, so it speaks for the first body the run doesn't cover.
1703        let mut lip_too_long = false;
1704        let sheltered_lips = (marched..bodies.len())
1705            .take_while(|&index| {
1706                let (term, geometry) = body_terms_at[index];
1707                // A lip widens the body: a narrowing part behind the run is a boattail the method
1708                // hasn't covered, whatever its drag takes from the wake, and it keeps its
1709                // slender-body share.
1710                if bodies[index].slope_per_rad <= 0.0 {
1711                    return false;
1712                }
1713                // It must be short enough to stay in the wake, whose scale is the boattail's own
1714                // drop in diameter; a longer flare grows out of it.
1715                let Some(wake) = drag_terms[term].in_wake_of else {
1716                    return false;
1717                };
1718                let boattail = &wake.boattail;
1719                if geometry.length_m > boattail.fore_diameter_m - boattail.aft_diameter_m {
1720                    lip_too_long = true;
1721                    return false;
1722                }
1723                // Whatever it widens by, a step at its fore end or its own shoulder, must be
1724                // wholly in the wake. The geometry says which it has: a drag term can be missing
1725                // for reasons of its own (a shape the buildup has no curve for).
1726                let steps = body_terms_at[index.saturating_sub(1)]
1727                    .1
1728                    .aft_area_m2
1729                    .lt(&geometry.fore_area_m2);
1730                let shoulders = geometry.aft_area_m2 > geometry.fore_area_m2;
1731                // How much of it the wake covers: the drag buildup's whole fraction, which fades
1732                // with the lip's rise (a quarter of the boattail's drop in diameter to a half),
1733                // with any tube between it and the boattail, and with anything else in the way
1734                // (`crate::drag::WakeTerm`). The normal force now reads the same
1735                // number rather than a threshold on it: the method's share is weighed by it
1736                // ([`SupersonicBody::weight`]), so a lip drawn a hair taller no longer switches
1737                // the whole body between the two models (issue #87, ADR-041 in DECISIONS.md).
1738                let mut covered = 1.0_f64;
1739                if steps {
1740                    covered = covered.min(wake.step_fraction);
1741                }
1742                if shoulders {
1743                    covered = covered.min(wake.shoulder_fraction);
1744                }
1745                // Not `<=`, so a share that somehow came out NaN falls out of the wake rather
1746                // than reading as full shelter through `f64::min`.
1747                if !covered.is_finite() || covered <= SUPERSONIC_SHELTER_FLOOR {
1748                    return false;
1749                }
1750                shelter_weight = shelter_weight.min(covered);
1751                true
1752            })
1753            .count();
1754        let covered = marched + sheltered_lips;
1755        let rest_carries_nothing = bodies[covered..]
1756            .iter()
1757            .all(|body| body.slope_per_rad.abs() <= 1e-9);
1758        // Why the run doesn't fly the body (ADR-181), from the body `rest_carries_nothing` fails
1759        // on: the first one past the run that carries a slope (a NaN counting), not merely the
1760        // first past it, which may be a flush tube behind a flare.
1761        let carrying = (covered..bodies.len()).find(|&index| {
1762            let nothing = bodies[index].slope_per_rad.abs() <= 1e-9;
1763            !nothing
1764        });
1765        let supersonic_stop = if marched > 0 && rest_carries_nothing {
1766            None
1767        } else {
1768            Some(match carrying.map(|index| (index, &bodies[index])) {
1769                Some((index, body)) if lip_too_long && index == covered => {
1770                    SupersonicFallback::LongLip {
1771                        component: body.id.clone(),
1772                    }
1773                }
1774                // Written as the run's own test, negated, so a NaN step counts as a step.
1775                Some((_, body))
1776                    if marched > 0
1777                        && (body.step_area_m2.abs() > 1e-6 * body.geometry.fore_area_m2
1778                            || body.step_area_m2.is_nan()) =>
1779                {
1780                    SupersonicFallback::RadiusStep {
1781                        component: body.id.clone(),
1782                    }
1783                }
1784                _ => SupersonicFallback::Other,
1785            })
1786        };
1787        let supersonic_run = (marched > 0 && rest_carries_nothing).then_some(SupersonicRun {
1788            segments: supersonic_segments,
1789            vertex_m,
1790            bounds_m: supersonic_bounds,
1791            fore_m: supersonic_fore,
1792            boattails: supersonic_boattails,
1793            flare,
1794            sheltered_lips,
1795            shape_weight: shelter_weight,
1796        });
1797        Ok(Self {
1798            reference_area_m2,
1799            reference_diameter_m: layout.reference_diameter_m,
1800            length_m,
1801            max_body_radius_m: max_radius,
1802            fineness,
1803            crossflow_eta_low: crate::crossflow::crossflow_eta_low(fineness),
1804            body_model,
1805            bodies,
1806            pods: pod_sets,
1807            supersonic_run,
1808            supersonic_stop,
1809            supersonic: SupersonicTable::default(),
1810            fin_sets,
1811            tube_fin_sets,
1812            drag_terms,
1813            drag_table: None,
1814            drag_model: None,
1815            normal_force_table: None,
1816            full_base_drag_under_power: false,
1817            drag_scale: 1.0,
1818        })
1819    }
1820
1821    /// This model with `table` replacing the drag buildup's zero-lift drag
1822    /// ([`crate::table`]), and any drag model ([`AeroModel::with_drag_model`]).
1823    #[must_use]
1824    pub fn with_drag_table(mut self, table: DragTable) -> Self {
1825        self.drag_table = Some(table);
1826        self.drag_model = None;
1827        self
1828    }
1829
1830    /// The drag override table, if any.
1831    pub fn drag_table(&self) -> Option<&DragTable> {
1832        self.drag_table.as_ref()
1833    }
1834
1835    /// This model with `model` replacing the drag buildup's zero-lift drag, and any drag table
1836    /// ([`crate::custom`]). The normal force, center of pressure and roll stay this model's.
1837    #[must_use]
1838    pub fn with_drag_model(self, model: impl DragModel + 'static) -> Self {
1839        self.with_shared_drag_model(Arc::new(model))
1840    }
1841
1842    /// As [`AeroModel::with_drag_model`], with a model already shared: models that hold the same
1843    /// one are equal.
1844    #[must_use]
1845    pub fn with_shared_drag_model(mut self, model: Arc<dyn DragModel>) -> Self {
1846        self.drag_model = Some(SharedDragModel(model));
1847        self.drag_table = None;
1848        self
1849    }
1850
1851    /// The drag model in place of the buildup, if any.
1852    pub fn drag_model(&self) -> Option<&Arc<dyn DragModel>> {
1853        self.drag_model.as_ref().map(|shared| &shared.0)
1854    }
1855
1856    /// This model with the aft base's drag kept whole while a motor burns: the thrusting motors'
1857    /// cross-section is not taken off the base ([`DragConditions::thrusting_motor_area_m2`] and
1858    /// the pods' are read as zero), and a burning motor still selects a table's power-on curve.
1859    ///
1860    /// HPR Sim's own buildup takes it off, as Niskanen describes (2009, pp. 50–51: "if the base is
1861    /// the same size as the motor itself, no base drag"). OpenRocket 24.12 does not: on every one
1862    /// of its example designs' flights of one branch, powered pods among them, its base-drag
1863    /// column is the whole base's coefficient while a motor burns, as after, where the motors
1864    /// cover up to 94% of the reference area (`validation/fixtures/ork/openrocket-base-drag.json`,
1865    /// [ADR-097][adr-097]). This is how a comparison with OpenRocket sizes that difference; it is
1866    /// not a better model. On the Hermes A-3A's measured flight below Mach 0.8 (Jackson 1955,
1867    /// NACA RM SL55F15), whose motor case is wider than its base, HPR Sim's rule leaves no base
1868    /// drag under power and reads low, the whole base reads high, and the jet more than doubled
1869    /// the base drag (`validation/fixtures/aero/base-drag-under-power.json`).
1870    ///
1871    /// [adr-097]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-097-a-cause-in-the-drag-sized-by-hpr-flying-openrockets-drag-2026-09-28
1872    #[must_use]
1873    pub fn with_full_base_drag_under_power(mut self) -> Self {
1874        self.full_base_drag_under_power = true;
1875        self
1876    }
1877
1878    /// Whether the aft base keeps its whole drag while a motor burns
1879    /// ([`AeroModel::with_full_base_drag_under_power`]).
1880    pub fn full_base_drag_under_power(&self) -> bool {
1881        self.full_base_drag_under_power
1882    }
1883
1884    /// Multiplies every zero-lift drag coefficient [`AeroModel::drag`] gives by `scale`: the
1885    /// buildup's (each of its five parts too), an override table's or a drag model's. A Monte
1886    /// Carlo run disperses drag this way, as RocketPy's `power_off_drag_factor` and
1887    /// `power_on_drag_factor` do (`rocketpy/stochastic/stochastic_rocket.py:745-746`); the angle of
1888    /// attack's factor, the normal force and the moments are not scaled. A table's
1889    /// [`Drag::table`] lookup stays the table's own value, and [`AeroModel::buildup_drag`], what a
1890    /// drag model is given to adjust, stays unscaled.
1891    ///
1892    /// # Errors
1893    ///
1894    /// [`AeroError::Domain`] for a scale that is negative or not finite.
1895    pub fn with_drag_scale(mut self, scale: f64) -> Result<Self, AeroError> {
1896        if !(scale.is_finite() && scale >= 0.0) {
1897            return Err(AeroError::Domain {
1898                what: "drag scale",
1899                value: scale,
1900            });
1901        }
1902        self.drag_scale = scale;
1903        Ok(self)
1904    }
1905
1906    /// The factor on every zero-lift drag coefficient ([`AeroModel::with_drag_scale`]); 1 unless
1907    /// set.
1908    pub fn drag_scale(&self) -> f64 {
1909        self.drag_scale
1910    }
1911
1912    /// Whether the supersonic table ([`AeroModel::supersonic_body`]) has been built, by this
1913    /// model or by one sharing it ([`AeroModel::share_supersonic_table`]). A flight builds it the
1914    /// first time its flow passes Mach 1.2.
1915    pub fn supersonic_table_built(&self) -> bool {
1916        self.supersonic.0.get().is_some()
1917    }
1918
1919    /// Takes `other`'s supersonic table ([`AeroModel::supersonic_body`]) in place of this model's
1920    /// own, when the two would build the same table: when they cover the same segments on the
1921    /// same reference area, the only inputs the table is built from. Then whichever model first
1922    /// needs the table builds it once for both, and for every clone of either, and the flights
1923    /// they fly are unchanged, bit for bit. Building the table takes up to about 125 runs of the
1924    /// shock-expansion method, a fifth of a second or more, so many flights of one airframe
1925    /// share it this way: a Monte Carlo run, whose samples change masses, motors, drag scale and
1926    /// weather but not the shape.
1927    ///
1928    /// Returns `true` if the table is now shared. It returns `false`, and changes nothing, for
1929    /// another shape or reference area, or for a model with no table to build: one whose body
1930    /// the shock-expansion method doesn't cover from the nose (a blunt nose, for one), which
1931    /// keeps slender-body theory past Mach 1.2.
1932    pub fn share_supersonic_table(&mut self, other: &AeroModel) -> bool {
1933        let shared = self.supersonic_run.is_some()
1934            && self.supersonic_run == other.supersonic_run
1935            && self.reference_area_m2 == other.reference_area_m2;
1936        if shared {
1937            self.supersonic = other.supersonic.clone();
1938        }
1939        shared
1940    }
1941
1942    /// `conditions` as this model reads them: with no motor area under power when the base keeps
1943    /// its whole drag.
1944    fn read(&self, conditions: &DragConditions) -> DragConditions {
1945        if self.full_base_drag_under_power {
1946            DragConditions {
1947                thrusting_motor_area_m2: 0.0,
1948                thrusting_pod_motor_areas_m2: [0.0; MOTOR_POD_SETS],
1949                ..*conditions
1950            }
1951        } else {
1952            *conditions
1953        }
1954    }
1955
1956    /// This model with `table` replacing the whole rocket's normal force and center of pressure
1957    /// ([`AeroModel::normal_force`]). Each component's own terms stay HPR Sim's
1958    /// ([`AeroModel::components`], [`AeroModel::component_normal_force`]): a flight engine takes
1959    /// its pitch and yaw damping from them, which a table doesn't give.
1960    ///
1961    /// # Errors
1962    ///
1963    /// [`AeroError::Domain`] for a center of pressure in the table outside the rocket, from its
1964    /// nose tip to its aft end: the sign of a length in the wrong unit or from another datum. Only
1965    /// the Mach numbers a flight can use are checked, up to [`NORMAL_FORCE_MACH_LIMIT`] and the
1966    /// first past it; a hypersonic row may move where it likes.
1967    pub fn with_normal_force_table(mut self, table: NormalForceTable) -> Result<Self, AeroError> {
1968        for column in table.columns() {
1969            let knots = column.cp_station_m.xs();
1970            let used = knots.partition_point(|&mach| mach <= NORMAL_FORCE_MACH_LIMIT) + 1;
1971            for &cp in column.cp_station_m.ys().iter().take(used) {
1972                if !(0.0..=self.length_m).contains(&cp) {
1973                    return Err(AeroError::Domain {
1974                        what: "normal-force table center of pressure, m aft of the nose tip",
1975                        value: cp,
1976                    });
1977                }
1978            }
1979        }
1980        self.normal_force_table = Some(table);
1981        Ok(self)
1982    }
1983
1984    /// The normal-force override table, if any.
1985    pub fn normal_force_table(&self) -> Option<&NormalForceTable> {
1986        self.normal_force_table.as_ref()
1987    }
1988
1989    /// The components' precomputed drag terms, in layout order.
1990    pub fn drag_terms(&self) -> &[ComponentDragTerms] {
1991        &self.drag_terms
1992    }
1993
1994    /// Rocket length for the Reynolds number: nose tip to the aft end of the last body component,
1995    /// m.
1996    pub fn length_m(&self) -> f64 {
1997        self.length_m
1998    }
1999
2000    /// The whole rocket's drag at `flow` and `conditions`: the zero-lift drag of the buildup, or of
2001    /// the override table or drag model when there is one, and the axial coefficient at the
2002    /// flow's angle of attack.
2003    ///
2004    /// # Errors
2005    ///
2006    /// - [`AeroError::Mach`] outside `[0, 5)` for the buildup
2007    ///   ([`crate::drag::BUILDUP_MACH_LIMIT`]), and from Mach 0.8 around a tube fin set's
2008    ///   ([`crate::tube_fins::TUBE_FIN_MACH_LIMIT`]); with an override table or a drag model any
2009    ///   finite Mach number from 0 is accepted ([`AeroError::Domain`] otherwise).
2010    /// - [`AeroError::DragModel`] around whatever a drag model returns, and [`AeroError::Domain`]
2011    ///   for a coefficient from it that is negative or not finite.
2012    /// - Without a table, [`AeroError::InComponent`] around [`AeroError::Unsupported`] for a nose or
2013    ///   shoulder shape the buildup has no drag data for
2014    ///   ([`crate::drag::ComponentDragTerms::unsupported`]).
2015    /// - [`AeroError::Domain`] for an angle of attack outside `[0, π]` or a non-finite roll.
2016    /// - As [`DragConditions::validate`].
2017    /// - [`AeroError::Table`] from the table lookup, and [`AeroError::Domain`] for a table's
2018    ///   coefficient that is negative at the flow's Mach number, or a drag that isn't finite.
2019    pub fn drag(&self, flow: &Flow, conditions: &DragConditions) -> Result<Drag, AeroError> {
2020        conditions.validate()?;
2021        let conditions = &self.read(conditions);
2022        let factor = axial_drag_alpha_factor(flow.alpha_rad)?;
2023        let drag = if let Some(custom) = &self.drag_model {
2024            flow.validate_angles()?;
2025            if !(flow.mach.is_finite() && flow.mach >= 0.0) {
2026                return Err(AeroError::Domain {
2027                    what: "Mach number for a drag model",
2028                    value: flow.mach,
2029                });
2030            }
2031            let coefficient = custom
2032                .0
2033                .zero_lift_drag(&DragQuery::new(flow, conditions, self))
2034                .map_err(|source| AeroError::DragModel {
2035                    source: Box::new(source),
2036                })?;
2037            if !(coefficient.is_finite() && coefficient >= 0.0) {
2038                return Err(AeroError::Domain {
2039                    what: "zero-lift drag coefficient from a drag model",
2040                    value: coefficient,
2041                });
2042            }
2043            Drag {
2044                zero_lift_coefficient: coefficient,
2045                ..Drag::default()
2046            }
2047        } else if let Some(table) = &self.drag_table {
2048            flow.validate_angles()?;
2049            let lookup = table.lookup(flow.mach, conditions.thrusting)?;
2050            // A table's rows are finite, but one can hold a negative row, or give a negative
2051            // value past its rows or between them (linear extrapolation, a cubic): drag that
2052            // would push the rocket along (#257).
2053            if lookup.value < 0.0 {
2054                return Err(AeroError::Domain {
2055                    what: "zero-lift drag coefficient from a drag table",
2056                    value: lookup.value,
2057                });
2058            }
2059            let scale = match table.reference_diameter_m {
2060                Some(d) => {
2061                    check_dimension("drag table reference diameter", d, false)?;
2062                    0.25 * PI * d * d / self.reference_area_m2
2063                }
2064                None => 1.0,
2065            };
2066            Drag {
2067                zero_lift_coefficient: lookup.value * scale,
2068                table: Some(lookup),
2069                ..Drag::default()
2070            }
2071        } else {
2072            self.buildup_sum(flow, conditions)?
2073        };
2074        with_axial(scaled(drag, self.drag_scale), factor)
2075    }
2076
2077    /// The drag buildup's drag at `flow` and `conditions`, whatever override the model has: the
2078    /// sum of every component's zero-lift terms, and the axial coefficient at the flow's angle of
2079    /// attack. Without an override it is [`AeroModel::drag`]; with one, what the override
2080    /// replaces, which a drag model can adjust ([`crate::custom::DragQuery::buildup`]).
2081    ///
2082    /// # Errors
2083    ///
2084    /// As [`AeroModel::drag`] without an override.
2085    pub fn buildup_drag(
2086        &self,
2087        flow: &Flow,
2088        conditions: &DragConditions,
2089    ) -> Result<Drag, AeroError> {
2090        conditions.validate()?;
2091        let conditions = &self.read(conditions);
2092        let factor = axial_drag_alpha_factor(flow.alpha_rad)?;
2093        with_axial(self.buildup_sum(flow, conditions)?, factor)
2094    }
2095
2096    /// The buildup's zero-lift terms and their sum at `flow`, on conditions already read
2097    /// ([`AeroModel::read`]); the axial coefficient is left for the caller.
2098    fn buildup_sum(&self, flow: &Flow, conditions: &DragConditions) -> Result<Drag, AeroError> {
2099        flow.validate_for_buildup()?;
2100        // Refused here as in the normal force, not wrapped in the tubes' component.
2101        self.check_tube_fins(flow.mach)?;
2102        let reynolds = conditions.reynolds_per_m * self.length_m;
2103        let mut sum = Drag::default();
2104        for terms in &self.drag_terms {
2105            let d = terms.evaluate(reynolds, flow.mach, conditions, self.reference_area_m2)?;
2106            sum.friction += d.friction;
2107            sum.pressure += d.pressure;
2108            sum.base += d.base;
2109            sum.parasitic += d.parasitic;
2110            sum.stated += d.stated;
2111        }
2112        sum.zero_lift_coefficient =
2113            sum.friction + sum.pressure + sum.base + sum.parasitic + sum.stated;
2114        Ok(sum)
2115    }
2116
2117    /// Each component's share of the drag buildup at `flow` and `conditions`, in layout order: its
2118    /// zero-lift coefficient and parts, and its axial coefficient at the flow's angle of attack.
2119    ///
2120    /// These are always the buildup's terms. With an override table or a drag model,
2121    /// [`AeroModel::drag`] returns its value instead of their sum, so they don't add up to it.
2122    ///
2123    /// # Errors
2124    ///
2125    /// As [`AeroModel::drag`] without a table, and [`DragConditions::validate`].
2126    pub fn buildup_components(
2127        &self,
2128        flow: &Flow,
2129        conditions: &DragConditions,
2130    ) -> Result<Vec<ComponentDrag>, AeroError> {
2131        flow.validate_for_buildup()?;
2132        self.check_tube_fins(flow.mach)?;
2133        conditions.validate()?;
2134        let conditions = &self.read(conditions);
2135        let factor = axial_drag_alpha_factor(flow.alpha_rad)?;
2136        let reynolds = conditions.reynolds_per_m * self.length_m;
2137        self.drag_terms
2138            .iter()
2139            .map(|terms| {
2140                let mut drag =
2141                    terms.evaluate(reynolds, flow.mach, conditions, self.reference_area_m2)?;
2142                drag.axial_coefficient *= factor;
2143                Ok(ComponentDrag {
2144                    id: terms.id.clone(),
2145                    drag,
2146                })
2147            })
2148            .collect()
2149    }
2150
2151    /// Reference area, m².
2152    pub fn reference_area_m2(&self) -> f64 {
2153        self.reference_area_m2
2154    }
2155
2156    /// Reference diameter, m: the length the rolling moment is taken on.
2157    pub fn reference_diameter_m(&self) -> f64 {
2158        self.reference_diameter_m
2159    }
2160
2161    /// The whole rocket's rolling moment at `mach` about `+z_B`, on the reference area and
2162    /// diameter: `C_l = C_l0 + C_lp (p d/2V)`, with `p` the roll rate about `+z_B` and `V` the
2163    /// airspeed. Each fin set adds `C_l0 = −N C_lδ k_T(B) δ` and `N C_lp k_R(B)` ([`FinAero::roll`],
2164    /// [`roll_forcing_interference`], [`roll_damping_interference`]); a positive cant `δ` turns
2165    /// each fin's leading edge toward `−y_B` at fin 0, so its lift rolls the rocket toward `−z_B`.
2166    /// Fin–fin interference is not applied to roll, as in Niskanen 2009 eq. 3.66. The airframe's
2167    /// bodies of revolution add nothing. A pod's body parts damp the roll by
2168    /// `C_lp = −2 C_Nα ρ²/d²` per pod, `ρ` its distance from the axis, and a pod's fins damp it by
2169    /// the strips' distance from the rocket's axis ([`PodFins`]); a pod adds no forcing.
2170    ///
2171    /// # Errors
2172    ///
2173    /// [`AeroError::Mach`] outside `[0, 5)`, as [`AeroModel::normal_force`], and [`AeroError::Mach`] at Mach 0.8 and above on a rocket with tube fins
2174    /// ([`crate::tube_fins::TUBE_FIN_MACH_LIMIT`]).
2175    pub fn roll(&self, mach: f64) -> Result<Roll, AeroError> {
2176        check_mach(mach, NORMAL_FORCE_MACH_LIMIT, "the roll moment")?;
2177        let mut roll = Roll::default();
2178        for set in &self.fin_sets {
2179            if let Some(pods) = &set.pods {
2180                // Taken about the rocket's axis; a pod's fins are never canted.
2181                let [a, b] = &pods.axis_roll;
2182                let damping =
2183                    0.5 * (set.fin.roll_with(a, mach).damping + set.fin.roll_with(b, mach).damping);
2184                roll.damping += f64::from(pods.fins) * damping * set.roll_damping_interference;
2185                continue;
2186            }
2187            let fin = set.fin.roll_with(&set.roll, mach);
2188            let n = f64::from(set.count);
2189            roll.forcing -= n * fin.forcing_per_rad * set.roll_forcing_interference * set.cant_rad;
2190            roll.damping += n * fin.damping * set.roll_damping_interference;
2191        }
2192        // A pod's body crosses the air at `p ρ` under the roll rate `p`, `ρ` its distance from
2193        // the axis: its normal force `q A C_Nα p ρ/V` about the axis gives
2194        // `C_lp = −2 C_Nα ρ²/d²` per copy.
2195        let d = self.reference_diameter_m;
2196        for pod in &self.pods {
2197            for body in &pod.bodies {
2198                roll.damping -= 2.0 * body.slope_per_rad * pod.offset_squares_m2 / (d * d);
2199            }
2200        }
2201        // Each tube likewise, about its own axis's distance ([`TubeFinSetAero::roll_damping`]).
2202        for set in &self.tube_fin_sets {
2203            roll.damping += set.roll_damping(mach, d)?;
2204        }
2205        Ok(roll)
2206    }
2207
2208    /// The steady roll rate about `+z_B`, rad/s, at `mach` and airspeed `speed_m_s` in axial flow:
2209    /// where the fins' forcing and damping balance, `p = −(C_l0/C_lp)(2V/d)`. Zero with no fins.
2210    ///
2211    /// # Errors
2212    ///
2213    /// As [`AeroModel::roll`], and [`AeroError::Domain`] for a negative or non-finite airspeed.
2214    pub fn steady_roll_rate_rad_s(&self, mach: f64, speed_m_s: f64) -> Result<f64, AeroError> {
2215        check_dimension("airspeed", speed_m_s, true)?;
2216        let roll = self.roll(mach)?;
2217        Ok(if roll.damping < 0.0 {
2218            -roll.forcing / roll.damping * 2.0 * speed_m_s / self.reference_diameter_m
2219        } else {
2220            0.0
2221        })
2222    }
2223
2224    /// The airframe's body components' terms; a pod's are in [`Self::pod_sets`].
2225    pub fn bodies(&self) -> &[BodyAero] {
2226        &self.bodies
2227    }
2228
2229    /// The shock-expansion method's shares of the nose, the cylinders and boattails behind it,
2230    /// and where they join slender-body theory; `None` where the method can't take the body (a nose
2231    /// steeper than a blunt tip's handover all the way to its base, a tangent cone past TN 3527's
2232    /// Fig. 2, a later body with a slope of its own such as a flare) or doesn't hold across a
2233    /// whole join below Mach 5.
2234    ///
2235    /// The first call builds the table, which takes up to about 125 runs of the method, or, in a
2236    /// process that keeps its tables ([`keep_supersonic_tables`]), copies one it built from an
2237    /// equal run on the same reference area; a flow no faster than [`SUPERSONIC_JOIN_START_MACH`]
2238    /// never needs it.
2239    pub fn supersonic_body(&self) -> Option<&SupersonicBody> {
2240        let run = self.supersonic_run.as_ref()?;
2241        self.supersonic
2242            .0
2243            .get_or_init(|| built_table(run, self.reference_area_m2))
2244            .as_ref()
2245    }
2246
2247    /// Why the shock-expansion method doesn't fly this body faster than sound, or `None` when it
2248    /// does ([`Self::supersonic_body`] is `Some`). Like that, the first call may build the table.
2249    /// A body with no run at all, such as one read back from JSON, gives `Other`.
2250    pub fn supersonic_fallback(&self) -> Option<SupersonicFallback> {
2251        if self.supersonic_run.is_none() {
2252            return Some(
2253                self.supersonic_stop
2254                    .clone()
2255                    .unwrap_or(SupersonicFallback::Other),
2256            );
2257        }
2258        if self.supersonic_body().is_some() {
2259            return None;
2260        }
2261        // A pointed tip past the cone tables fails the method at every Mach number (#121).
2262        let steep_tip = self.supersonic_run.as_ref().is_some_and(|run| {
2263            ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).is_ok_and(|body| {
2264                !body.has_blunt_tip()
2265                    && crate::shock_expansion::past_cone_tables(body.vertex_angle_rad())
2266            })
2267        });
2268        if steep_tip {
2269            return Some(SupersonicFallback::SteepTip);
2270        }
2271        // A step the run's coverage gate (a millionth of the area) lets through can still be
2272        // more than the march merges (a billionth of the radius, `shock_expansion::lay_out`):
2273        // the table then fails, and the step is why (#87).
2274        let marched = self
2275            .supersonic_run
2276            .as_ref()
2277            .map_or(0, |run| run.segments.len());
2278        let stepped = self
2279            .bodies
2280            .iter()
2281            .take(marched)
2282            .find(|body| body.step_area_m2 != 0.0);
2283        Some(match stepped {
2284            Some(body) => SupersonicFallback::RadiusStep {
2285                component: body.id.clone(),
2286            },
2287            None => SupersonicFallback::Other,
2288        })
2289    }
2290
2291    /// [`Self::supersonic_body`] where `mach` is past the earliest join, and `None` below it
2292    /// without building the table.
2293    fn supersonic_at(&self, mach: f64) -> Option<&SupersonicBody> {
2294        (mach > SUPERSONIC_JOIN_START_MACH)
2295            .then(|| self.supersonic_body())
2296            .flatten()
2297    }
2298
2299    /// Body `index`'s potential-flow slope (per radian) and moment slope about the nose tip (m per
2300    /// radian) at a checked `mach`: slender-body theory's, joined to the shock-expansion share
2301    /// where the method covers it ([`SupersonicBody`]).
2302    fn body_potential(&self, index: usize, body: &BodyAero, mach: f64) -> (f64, f64) {
2303        let (slope, moment) = (body.slope_per_rad, body.moment_slope_m);
2304        match self.supersonic_at(mach) {
2305            Some(s) if index < s.covered && mach > s.join_start_mach => {
2306                let w = s.weight(mach);
2307                let Some((se_slope, se_moment)) = s.share(index, mach) else {
2308                    return (slope, moment);
2309                };
2310                (
2311                    slope + w * (se_slope - slope),
2312                    moment + w * (se_moment - moment),
2313                )
2314            }
2315            _ => (slope, moment),
2316        }
2317    }
2318
2319    /// The body-lift factor at `flow`, on `(A_plan/A_ref) sin² α`: Jorgensen's `η C_dn` at the
2320    /// body's fineness and the crossflow Mach number `M sin α`, or Galejs's `K`
2321    /// ([`BodyModel::body_lift`]).
2322    pub fn body_lift_factor(&self, flow: &Flow) -> f64 {
2323        self.lift_factor_at(flow.mach, flow.alpha_rad.sin())
2324    }
2325
2326    /// [`Self::body_lift_factor`] at `mach` and `sin α`.
2327    fn lift_factor_at(&self, mach: f64, sin_alpha: f64) -> f64 {
2328        self.lift_factor_of(self.fineness, self.crossflow_eta_low, mach, sin_alpha)
2329    }
2330
2331    /// The body-lift factor of a body of `fineness`, whose Fig. 4 `η` is `eta_low`, at `mach`
2332    /// and `sin α`: the airframe's, or a pod's.
2333    fn lift_factor_of(&self, fineness: f64, eta_low: f64, mach: f64, sin_alpha: f64) -> f64 {
2334        let crossflow_mach = mach * sin_alpha.abs();
2335        match self.body_model.body_lift {
2336            BodyLift::Jorgensen {} => {
2337                crate::crossflow::crossflow_factor_from_eta_low(eta_low, crossflow_mach)
2338            }
2339            other => other.factor(fineness, crossflow_mach),
2340        }
2341    }
2342
2343    /// The per-radian potential-flow and body-lift factors at `flow` ([`alpha_factors`]), the
2344    /// second with the model's body-lift factor, skipped where it multiplies nothing.
2345    fn body_factors(&self, flow: &Flow) -> (f64, f64) {
2346        let (potential, lift, sin_alpha) = alpha_factors(flow.alpha_rad);
2347        if lift == 0.0 {
2348            (potential, 0.0)
2349        } else {
2350            (potential, lift * self.lift_factor_at(flow.mach, sin_alpha))
2351        }
2352    }
2353
2354    /// [`Self::body_factors`] for `pod`'s bodies: the body-lift factor at the pod's fineness.
2355    fn pod_factors(&self, pod: &PodSetAero, flow: &Flow) -> (f64, f64) {
2356        let (potential, lift, sin_alpha) = alpha_factors(flow.alpha_rad);
2357        if lift == 0.0 {
2358            (potential, 0.0)
2359        } else {
2360            let factor =
2361                self.lift_factor_of(pod.fineness, pod.crossflow_eta_low, flow.mach, sin_alpha);
2362            (potential, lift * factor)
2363        }
2364    }
2365
2366    /// The pod body at `index` among every pod's bodies, in the order of [`Self::components`],
2367    /// and its pod set.
2368    fn pod_body(&self, index: usize) -> Option<(&PodSetAero, &BodyAero)> {
2369        let mut index = index;
2370        for pod in &self.pods {
2371            match pod.bodies.get(index) {
2372                Some(body) => return Some((pod, body)),
2373                None => index -= pod.bodies.len(),
2374            }
2375        }
2376        None
2377    }
2378
2379    /// Every pod's bodies, one copy's terms each, with their pod sets.
2380    fn pod_bodies(&self) -> impl Iterator<Item = (&PodSetAero, &BodyAero)> {
2381        self.pods
2382            .iter()
2383            .flat_map(|pod| pod.bodies.iter().map(move |body| (pod, body)))
2384    }
2385
2386    /// The body model: its body-lift and supersonic-boattail rules.
2387    pub fn body_model(&self) -> BodyModel {
2388        self.body_model
2389    }
2390
2391    /// The body's length over its largest diameter, which sets body lift's `η`.
2392    pub fn fineness(&self) -> f64 {
2393        self.fineness
2394    }
2395
2396    /// The fin sets' terms.
2397    pub fn fin_sets(&self) -> &[FinSetAero] {
2398        &self.fin_sets
2399    }
2400
2401    /// Whether the normal force depends on the direction the air crosses the rocket: a fin set
2402    /// of one or two fins, whose share of its force in a plane varies with the plane
2403    /// ([`crate::roll_sum`]), and no normal-force table, which gives one force in every plane.
2404    pub fn rolls(&self) -> bool {
2405        self.normal_force_table.is_none() && self.fin_sets.iter().any(|set| set.count < 3)
2406    }
2407
2408    /// The tube fin sets' terms.
2409    pub fn tube_fin_sets(&self) -> &[TubeFinSetAero] {
2410        &self.tube_fin_sets
2411    }
2412
2413    /// Checks `mach` against the tube-fin model's range when the rocket has tube fins.
2414    fn check_tube_fins(&self, mach: f64) -> Result<(), AeroError> {
2415        if self.tube_fin_sets.is_empty() {
2416            Ok(())
2417        } else {
2418            check_tube_fin_mach(mach)
2419        }
2420    }
2421
2422    /// The pod sets' terms: those whose pods hold a body component with a size.
2423    pub fn pod_sets(&self) -> &[PodSetAero] {
2424        &self.pods
2425    }
2426
2427    /// Each component's id and contributions at a validated `flow`, and a Mach number the tube
2428    /// fins take ([`Self::check_tube_fins`]): the airframe's bodies first, then the pods' bodies,
2429    /// then fin sets, then tube fin sets, in layout order.
2430    fn terms<'a>(&'a self, flow: &Flow) -> impl Iterator<Item = (&'a str, Term)> + 'a {
2431        let (potential, lift) = self.body_factors(flow);
2432        let (mach, roll) = (flow.mach, flow.roll_rad);
2433        let bodies = self.bodies.iter().enumerate().map(move |(index, body)| {
2434            let (slope, moment) = self.body_potential(index, body, mach);
2435            (
2436                body.id.as_str(),
2437                body_term(body, slope, moment, potential, lift),
2438            )
2439        });
2440        let flow = *flow;
2441        let pods = self
2442            .pod_bodies()
2443            .map(move |(pod, body)| (body.id.as_str(), self.pod_body_term(pod, body, &flow)));
2444        let fins = self
2445            .fin_sets
2446            .iter()
2447            .map(move |set| (set.id.as_str(), fin_term(set, mach, roll)));
2448        let tubes = self
2449            .tube_fin_sets
2450            .iter()
2451            .map(move |set| (set.id.as_str(), tube_fin_term(set, mach)));
2452        bodies.chain(pods).chain(fins).chain(tubes)
2453    }
2454
2455    /// A pod body's contribution at `flow`, over every pod: slender-body theory's slope at every
2456    /// Mach number (the shock-expansion method covers the airframe alone) and the pod's body lift.
2457    fn pod_body_term(&self, pod: &PodSetAero, body: &BodyAero, flow: &Flow) -> Term {
2458        let (potential, lift) = self.pod_factors(pod, flow);
2459        body_term(
2460            body,
2461            body.slope_per_rad,
2462            body.moment_slope_m,
2463            potential,
2464            lift,
2465        )
2466        .times(f64::from(pod.copies))
2467    }
2468
2469    /// The number of components with a normal-force term: the airframe's bodies, the pods'
2470    /// bodies, the fin sets, then the tube fin sets, in the order of [`Self::components`].
2471    pub fn component_count(&self) -> usize {
2472        self.tube_fin_set_start() + self.tube_fin_sets.len()
2473    }
2474
2475    /// The index of the first tube fin set among the components ([`Self::components`]): the
2476    /// bodies and the fin sets come before.
2477    pub fn tube_fin_set_start(&self) -> usize {
2478        self.fin_set_start() + self.fin_sets.len()
2479    }
2480
2481    /// The index of the first fin set among the components ([`Self::components`]): the bodies,
2482    /// the airframe's and the pods', come before. Every component from here is a lifting surface:
2483    /// the fin sets, then the tube fin sets ([`Self::tube_fin_set_start`]).
2484    pub fn fin_set_start(&self) -> usize {
2485        self.bodies.len() + self.pods.iter().map(|pod| pod.bodies.len()).sum::<usize>()
2486    }
2487
2488    /// Component `index`'s normal force at `flow`, in the order of [`Self::components`], without
2489    /// allocating. A flight engine evaluates each component at its own local flow, which includes
2490    /// the airspeed the body's rotation adds at the component.
2491    ///
2492    /// # Errors
2493    ///
2494    /// As [`Flow::validate`], [`AeroError::Mach`] at Mach 0.8 and above for a tube fin set, and
2495    /// [`AeroError::Domain`] for an index past [`Self::component_count`].
2496    pub fn component_normal_force(
2497        &self,
2498        index: usize,
2499        flow: &Flow,
2500    ) -> Result<NormalForce, AeroError> {
2501        flow.validate()?;
2502        let term = if let Some(body) = self.bodies.get(index) {
2503            let (potential, lift) = self.body_factors(flow);
2504            let (slope, moment) = self.body_potential(index, body, flow.mach);
2505            body_term(body, slope, moment, potential, lift)
2506        } else if let Some((pod, body)) = self.pod_body(index - self.bodies.len()) {
2507            self.pod_body_term(pod, body, flow)
2508        } else if let Some(set) = self.fin_sets.get(index - self.fin_set_start()) {
2509            fin_term(set, flow.mach, flow.roll_rad)
2510        } else if let Some(set) = self.tube_fin_sets.get(index - self.tube_fin_set_start()) {
2511            check_tube_fin_mach(flow.mach)?;
2512            tube_fin_term(set, flow.mach)
2513        } else {
2514            return Err(AeroError::Domain {
2515                what: "component index",
2516                value: index as f64,
2517            });
2518        };
2519        Ok(NormalForce::new(term, flow.alpha_rad))
2520    }
2521
2522    /// The station, m aft of the nose tip, where a flight engine takes component `index`'s local
2523    /// airspeed at `mach`.
2524    ///
2525    /// It is the component's small-angle center of pressure wherever one model carries it: a fin
2526    /// set's own, and a body's `moment_slope / slope`, or its body-lift station where it has no
2527    /// potential-flow slope (a cylinder). Where two models share it, it is not: faster than sound
2528    /// a nose's or cylinder's station is joined linearly from slender-body theory's to the
2529    /// method's as the weight rises ([`SupersonicBody`]), while the force blends slopes and
2530    /// moments, so the two agree only at the ends of the join. On a lip riding half in its
2531    /// boattail's wake, which never reaches an end, the tests' tube sits 0.114 m (about two
2532    /// calibers) behind its own center of pressure
2533    /// ([issue #106](https://github.com/nrdptel/fusionspace-eridanus/issues/106), which measures it and holds
2534    /// what a fix has to settle). A covered boattail, and a cylinder behind it, keep
2535    /// slender-body theory's station: their shares may cross zero, where a station would run off
2536    /// to infinity.
2537    ///
2538    /// # Errors
2539    ///
2540    /// [`AeroError::Mach`] outside `[0, 5)`, or `[0, 0.8)` for a tube fin set
2541    /// ([`crate::tube_fins::TUBE_FIN_MACH_LIMIT`]), and [`AeroError::Domain`] for an index past
2542    /// [`Self::component_count`].
2543    pub fn component_station_m(&self, index: usize, mach: f64) -> Result<f64, AeroError> {
2544        check_mach(mach, NORMAL_FORCE_MACH_LIMIT, "the normal force")?;
2545        if let Some(body) = self.bodies.get(index) {
2546            let station = slender_station_m(body, self.reference_area_m2);
2547            // A boattail's share, and those behind it, may cross zero, so their stations stay
2548            // slender-body theory's, on their own segments, while slopes and moments take the
2549            // method's.
2550            Ok(match self.supersonic_at(mach) {
2551                Some(s) if index < s.covered && s.stationed[index] && mach > s.join_start_mach => {
2552                    match s.share(index, mach) {
2553                        // Every tabulated share with a station is positive, so the interpolated
2554                        // one is.
2555                        Some((slope, moment)) => {
2556                            station + s.weight(mach) * (moment / slope - station)
2557                        }
2558                        None => station,
2559                    }
2560                }
2561                _ => station,
2562            })
2563        } else if let Some((_, body)) = self.pod_body(index - self.bodies.len()) {
2564            Ok(slender_station_m(body, self.reference_area_m2))
2565        } else if let Some(set) = self.fin_sets.get(index - self.fin_set_start()) {
2566            Ok(set.fore_station_m + set.fin.loading_at(mach).cp_m)
2567        } else {
2568            let set = self
2569                .tube_fin_sets
2570                .get(index - self.tube_fin_set_start())
2571                .ok_or(AeroError::Domain {
2572                    what: "component index",
2573                    value: index as f64,
2574                })?;
2575            check_tube_fin_mach(mach)?;
2576            Ok(set.loading_at(mach).1)
2577        }
2578    }
2579
2580    /// The pitch-damping coefficient `C_mq` about a point `reference_station_m` aft of the nose
2581    /// tip, at `mach`, per radian of `q d/(2V)`: the damping a flight engine gets when it
2582    /// evaluates each component in its own local flow, as `hpr_sim` does. It is a read-out of
2583    /// that damping, not a term to add to it.
2584    ///
2585    /// A pitch rate `q` about the reference point adds `q (s_i − x_r)/V` to the angle of attack
2586    /// at component `i`'s station `s_i` ([`Self::component_station_m`]). The component's normal
2587    /// force grows by its slope `C_Nα,i` times that angle and acts at its own center of pressure
2588    /// `c_i`, so the moment about the reference point is, per `q d/(2V)`,
2589    ///
2590    /// `C_mq = −(2/d²) Σ_i C_Nα,i (s_i − x_r)(c_i − x_r)`,
2591    ///
2592    /// with `C_Nα,i c_i` the component's moment slope about the nose tip, taken at zero angle of
2593    /// attack; `d` is the reference diameter. Where the station and the center of pressure
2594    /// coincide each term is the component's slope times the square of its arm, the fins'
2595    /// `−2 C_Nα,fins ℓ²/d²` of the guide's pods section. It has no `C_mα̇` part (no lag of the
2596    /// downwash or of the body's flow), so it stands for the sum `C_mq + C_mα̇` that a free
2597    /// flight measures, as the engine's damping does. Components with no slope at zero angle of
2598    /// attack (a cylinder below Mach 1) add nothing. `hpr_sim`'s tests hold the engine's moment
2599    /// at a small pitch rate to this coefficient. A normal-force override table is ignored, as
2600    /// the engine's damping ignores it.
2601    ///
2602    /// # Errors
2603    ///
2604    /// As [`Self::component_station_m`] and [`Self::component_normal_force`], and
2605    /// [`AeroError::Domain`] for a non-finite reference station.
2606    pub fn pitch_damping(&self, mach: f64, reference_station_m: f64) -> Result<f64, AeroError> {
2607        self.pitch_damping_of(mach, reference_station_m, 0..self.component_count())
2608    }
2609
2610    /// The part of [`Self::pitch_damping`] that the components `components` (indices as
2611    /// [`Self::component_normal_force`] takes them) give: the same sum over those components
2612    /// alone, so the parts over a split of `0..component_count()` add up to the whole. The fins'
2613    /// part, fin sets' and tube fins', is `fin_set_start()..component_count()`.
2614    ///
2615    /// Like the flight engine's damping, it is the components' and ignores a normal-force
2616    /// override table ([`AeroModel::with_normal_force_table`]).
2617    ///
2618    /// # Errors
2619    ///
2620    /// As [`Self::pitch_damping`], and as [`Self::component_normal_force`] for an index past the
2621    /// last component.
2622    pub fn pitch_damping_of(
2623        &self,
2624        mach: f64,
2625        reference_station_m: f64,
2626        components: std::ops::Range<usize>,
2627    ) -> Result<f64, AeroError> {
2628        if !reference_station_m.is_finite() {
2629            return Err(AeroError::Domain {
2630                what: "pitch damping reference station",
2631                value: reference_station_m,
2632            });
2633        }
2634        let flow = Flow::axial(mach);
2635        let x_r = reference_station_m;
2636        let mut sum = 0.0;
2637        for index in components {
2638            let force = self.component_normal_force(index, &flow)?;
2639            let station = self.component_station_m(index, mach)?;
2640            sum += (station - x_r) * (force.moment_slope_m - force.slope_per_rad * x_r);
2641        }
2642        let d = self.reference_diameter_m();
2643        Ok(-2.0 * sum / (d * d))
2644    }
2645
2646    /// The whole rocket's normal force at `flow`: the sum of its components, or the override
2647    /// table's when there is one ([`AeroModel::with_normal_force_table`]).
2648    ///
2649    /// A table's normal force acts in the plane of the flow at the table's center of pressure,
2650    /// with no side force; its coefficients are rescaled to the rocket's reference area from the
2651    /// table's ([`crate::table::TableReference`]).
2652    ///
2653    /// # Errors
2654    ///
2655    /// As [`Flow::validate`], and without a table [`AeroError::Mach`] at Mach 0.8 and above on a rocket with tube fins
2656    /// ([`crate::tube_fins::TUBE_FIN_MACH_LIMIT`]). With a table, any finite
2657    /// Mach number from 0 is accepted ([`AeroError::Domain`] otherwise), and table errors are
2658    /// returned.
2659    pub fn normal_force(&self, flow: &Flow) -> Result<NormalForce, AeroError> {
2660        if let Some(table) = &self.normal_force_table {
2661            flow.validate_angles()?;
2662            let lookup = table.lookup_within(flow.mach, flow.alpha_rad, (0.0, self.length_m))?;
2663            let area_m2 = match table.reference() {
2664                TableReference::Diameter { diameter_m } => 0.25 * PI * diameter_m * diameter_m,
2665                TableReference::LargestBody => PI * self.max_body_radius_m * self.max_body_radius_m,
2666                // `TableReference` is non-exhaustive only for other crates.
2667                TableReference::Rocket => self.reference_area_m2,
2668            };
2669            let scale = area_m2 / self.reference_area_m2;
2670            let coefficient = lookup.coefficient * scale;
2671            let slope = lookup.slope_per_rad * scale;
2672            return Ok(NormalForce {
2673                coefficient,
2674                slope_per_rad: slope,
2675                moment_m: coefficient * lookup.cp_station_m,
2676                moment_slope_m: slope * lookup.cp_station_m,
2677                cp_station_m: (slope != 0.0).then_some(lookup.cp_station_m),
2678                side_coefficient: 0.0,
2679                side_moment_m: 0.0,
2680                table: Some(lookup),
2681            });
2682        }
2683        flow.validate()?;
2684        self.check_tube_fins(flow.mach)?;
2685        let total = self
2686            .terms(flow)
2687            .fold(Term::default(), |sum, (_, term)| sum.add(term));
2688        Ok(NormalForce::new(total, flow.alpha_rad))
2689    }
2690
2691    /// Each component's normal force at `flow`: the airframe's bodies, then the pods' bodies (each
2692    /// over all its pods), then fin sets, then tube fin sets, each in layout order. A
2693    /// step in radius is part of the component aft of it.
2694    ///
2695    /// These are always HPR Sim's own terms. With a normal-force table, [`AeroModel::normal_force`]
2696    /// returns the table's value instead of their sum.
2697    ///
2698    /// # Errors
2699    ///
2700    /// As [`Flow::validate`], and [`AeroError::Mach`] at Mach 0.8 and above on a rocket with tube fins
2701    /// ([`crate::tube_fins::TUBE_FIN_MACH_LIMIT`]).
2702    pub fn components(&self, flow: &Flow) -> Result<Vec<ComponentNormalForce>, AeroError> {
2703        flow.validate()?;
2704        self.check_tube_fins(flow.mach)?;
2705        Ok(self
2706            .terms(flow)
2707            .map(|(id, term)| ComponentNormalForce {
2708                id: id.to_owned(),
2709                normal_force: NormalForce::new(term, flow.alpha_rad),
2710            })
2711            .collect())
2712    }
2713}
2714
2715/// A body's small-angle center of pressure in slender-body theory, m aft of the nose tip: its
2716/// `moment_slope / slope`, or its body-lift station where it has no potential-flow slope (a
2717/// cylinder). As `NormalForce`'s CP, a slope that cancels to rounding (a step in radius offsetting
2718/// a taper) has no potential-flow station.
2719fn slender_station_m(body: &BodyAero, reference_area_m2: f64) -> f64 {
2720    let step_slope = 2.0 * body.step_area_m2 / reference_area_m2;
2721    let scale = (body.slope_per_rad - step_slope).abs() + step_slope.abs();
2722    if body.slope_per_rad.abs() <= 1e-12 * scale {
2723        body.lift_station_m
2724    } else {
2725        body.moment_slope_m / body.slope_per_rad
2726    }
2727}
2728
2729/// A fin set's contribution at a checked `mach` and flow roll `roll`, per radian of `α`: over
2730/// every pod for a pod's fins, each pod's turned by its roll.
2731fn fin_term(set: &FinSetAero, mach: f64, roll: f64) -> Term {
2732    let FinLoading {
2733        slope_per_rad,
2734        cp_m,
2735    } = set.fin.loading_at(mach);
2736    let per_set = slope_per_rad * set.count_factor * set.interference;
2737    let station = set.fore_station_m + cp_m;
2738    let (roll_share, side_share) = match &set.pods {
2739        None => (
2740            roll_sum(set.count, set.base_angle_rad, roll),
2741            side_sum(set.count, set.base_angle_rad, roll),
2742        ),
2743        Some(pods) => pods.roll_rad.iter().fold((0.0, 0.0), |(r, s), turn| {
2744            let base = set.base_angle_rad + turn;
2745            (
2746                r + roll_sum(set.count, base, roll),
2747                s + side_sum(set.count, base, roll),
2748            )
2749        }),
2750    };
2751    let slope = per_set * roll_share;
2752    let side = per_set * side_share;
2753    Term {
2754        slope,
2755        moment: slope * station,
2756        side,
2757        side_moment: side * station,
2758        scale: slope.abs(),
2759    }
2760}
2761
2762/// A tube fin set's contribution at a checked `mach`, per radian of `α`: a ring wing lifts the
2763/// same whichever way the flow crosses it, so the set has no roll dependence and no side force.
2764fn tube_fin_term(set: &TubeFinSetAero, mach: f64) -> Term {
2765    let (slope, station) = set.loading_at(mach);
2766    Term {
2767        slope,
2768        moment: slope * station,
2769        side: 0.0,
2770        side_moment: 0.0,
2771        scale: slope.abs(),
2772    }
2773}
2774
2775/// A body's contribution from its potential-flow `slope` and `moment` slope at the flow's Mach
2776/// number ([`AeroModel::body_potential`]), at the potential-flow factor of [`alpha_factors`] and
2777/// its body-lift factor times the model's ([`AeroModel::body_lift_factor`]).
2778fn body_term(body: &BodyAero, slope: f64, moment: f64, potential: f64, lift: f64) -> Term {
2779    let (attached, lift) = (slope * potential, body.planform_ratio * lift);
2780    Term {
2781        slope: attached + lift,
2782        moment: moment * potential + lift * body.lift_station_m,
2783        scale: attached.abs() + lift.abs(),
2784        ..Term::default()
2785    }
2786}
2787
2788/// The per-radian factors of the potential-flow term (`sin α/α`) and of body lift
2789/// (`sin² α/α = sin α · sin α/α`), and `sin α`.
2790fn alpha_factors(alpha_rad: f64) -> (f64, f64, f64) {
2791    let (s, sin) = (sinc(alpha_rad), alpha_rad.sin());
2792    (s, sin * s, sin)
2793}
2794
2795/// The pod sets of `layout` that hold motor mounts ([`Layout::motor_pod_sets`]).
2796///
2797/// # Errors
2798///
2799/// [`AeroError::Unsupported`] for motor mounts in more than [`MOTOR_POD_SETS`] pod sets, whose
2800/// bases' thrusting motor areas the drag conditions don't tell apart
2801/// ([`DragConditions::thrusting_pod_motor_areas_m2`]).
2802fn motor_pod_sets(layout: &Layout) -> Result<Vec<usize>, AeroError> {
2803    let sets = layout.motor_pod_sets();
2804    if sets.len() > MOTOR_POD_SETS {
2805        return Err(AeroError::Unsupported(format!(
2806            "motor mounts in {} pod sets; the drag tells apart the thrusting motors' areas of at \
2807             most {MOTOR_POD_SETS}",
2808            sets.len()
2809        )));
2810    }
2811    Ok(sets)
2812}
2813
2814/// How many copies of `component` fly: one per pod for a part in a pod set.
2815fn copy_count(component: &PlacedComponent) -> Result<u32, AeroError> {
2816    u32::try_from(component.copies.len()).map_err(|_| AeroError::Domain {
2817        what: "copies of a component",
2818        value: component.copies.len() as f64,
2819    })
2820}
2821
2822/// A pod set's terms while [`AeroModel::with_body_model`] builds them.
2823struct PodBuild {
2824    aero: PodSetAero,
2825    /// The friction form factor at the pod's fineness; `None` for a pod with no body of any size.
2826    form_factor: Option<f64>,
2827    /// Where the pod set is among those holding motor mounts ([`Layout::motor_pod_sets`]), if it
2828    /// is one: its pods' bases then take that set's thrusting motors' area.
2829    motor_pod_set: Option<usize>,
2830    previous_aft_area: Option<f64>,
2831    /// Each body component's index in the drag terms, and its geometry, fore to aft.
2832    terms_at: Vec<(usize, BodyGeometry)>,
2833}
2834
2835impl PodBuild {
2836    /// The pod set at `index` of `layout`, before its body components.
2837    fn new(layout: &Layout, index: usize, component: &PlacedComponent) -> Result<Self, AeroError> {
2838        let copies = component.contents_copies()?;
2839        let offset_squares_m2 = copies
2840            .iter()
2841            .map(|c| c.offset_m[0] * c.offset_m[0] + c.offset_m[1] * c.offset_m[1])
2842            .sum();
2843        let mut max_radius: f64 = 0.0;
2844        for child in layout.components.iter().filter(|c| c.parent == Some(index)) {
2845            if let Some(radius) = child.part.max_radius_m()? {
2846                max_radius = max_radius.max(radius);
2847            }
2848        }
2849        // A pod set's length is its pod's.
2850        let fineness = if max_radius > 0.0 && component.length_m > 0.0 {
2851            component.length_m / (2.0 * max_radius)
2852        } else {
2853            0.0
2854        };
2855        let form_factor = if fineness > 0.0 {
2856            Some(body_friction_form_factor(fineness)?)
2857        } else {
2858            None
2859        };
2860        Ok(Self {
2861            aero: PodSetAero {
2862                id: component.id.clone(),
2863                copies: u32::try_from(copies.len()).map_err(|_| AeroError::Domain {
2864                    what: "pods in a pod set",
2865                    value: copies.len() as f64,
2866                })?,
2867                offset_squares_m2,
2868                fineness,
2869                crossflow_eta_low: if fineness > 0.0 {
2870                    crate::crossflow::crossflow_eta_low(fineness)
2871                } else {
2872                    0.0
2873                },
2874                bodies: Vec::new(),
2875            },
2876            form_factor,
2877            motor_pod_set: None,
2878            previous_aft_area: None,
2879            terms_at: Vec::new(),
2880        })
2881    }
2882
2883    /// Adds one of the pod's body components, fore to aft: its normal-force terms, and its drag
2884    /// terms to `drag_terms`, both one copy's. A tube of no length and no radius, the phantom body
2885    /// a pod of fins hangs them from (ADR-091), adds nothing.
2886    fn add_body(
2887        &mut self,
2888        component: &PlacedComponent,
2889        drag_terms: &mut Vec<ComponentDragTerms>,
2890        length_m: f64,
2891        reference_area_m2: f64,
2892    ) -> Result<(), AeroError> {
2893        let (geometry, shape) = match &component.part {
2894            Part::NoseCone(nose) => (
2895                BodyGeometry::from_profile(&nose.profile()?)?,
2896                Some(nose.shape),
2897            ),
2898            Part::Transition(transition) => (
2899                BodyGeometry::from_profile(&transition.profile()?)?,
2900                Some(transition.shape),
2901            ),
2902            Part::BodyTube(tube) if tube.length_m == 0.0 => {
2903                if tube.outer_radius_m == 0.0 {
2904                    return Ok(());
2905                }
2906                return Err(AeroError::Unsupported(
2907                    "a pod's tube of no length with a radius: a flat disc, which the drag buildup \
2908                     has no term for"
2909                        .to_owned(),
2910                ));
2911            }
2912            Part::BodyTube(tube) => (
2913                BodyGeometry::cylinder(tube.length_m, tube.outer_radius_m)?,
2914                None,
2915            ),
2916            _ => return Ok(()),
2917        };
2918        // A body with a length and an area makes the pod's fineness positive.
2919        let form_factor = self.form_factor.ok_or(AeroError::Domain {
2920            what: "pod fineness",
2921            value: self.aero.fineness,
2922        })?;
2923        let step = self
2924            .previous_aft_area
2925            .map_or(0.0, |aft| geometry.fore_area_m2 - aft);
2926        let mut terms = ComponentDragTerms::body(
2927            component,
2928            &geometry,
2929            shape,
2930            self.previous_aft_area,
2931            form_factor,
2932            length_m,
2933            reference_area_m2,
2934        )?;
2935        terms.copies = self.aero.copies;
2936        terms.in_pod = true;
2937        terms.motor_pod_set = self.motor_pod_set;
2938        drag_terms.push(terms);
2939        self.terms_at.push((drag_terms.len() - 1, geometry));
2940        self.previous_aft_area = Some(geometry.aft_area_m2);
2941        self.aero
2942            .bodies
2943            .push(body_terms(component, geometry, step, reference_area_m2));
2944        Ok(())
2945    }
2946}
2947
2948/// A pod's fin set's copies, one per pod, and its roll damping about the rocket's axis
2949/// ([`PodFins`]).
2950///
2951/// # Errors
2952///
2953/// [`AeroError::Unsupported`] for canted fins: their roll forcing about the rocket's axis, with
2954/// the root off it, is not modeled. [`AeroError::Domain`] from [`FinAero::roll_terms_about`].
2955fn pod_fins(
2956    set: &hpr_design::FinSet,
2957    component: &PlacedComponent,
2958    terms: &FinSetAero,
2959    reference_diameter_m: f64,
2960) -> Result<PodFins, AeroError> {
2961    use std::f64::consts::TAU;
2962    if set.cant_rad != 0.0 {
2963        return Err(AeroError::Unsupported(
2964            "cant on a pod's fins, whose roll forcing about the rocket's axis isn't modeled"
2965                .to_owned(),
2966        ));
2967    }
2968    let mut offsets = Vec::new();
2969    for copy in &component.copies {
2970        for j in 0..set.count {
2971            let angle =
2972                set.base_angle_rad + TAU * f64::from(j) / f64::from(set.count) + copy.roll_rad;
2973            let (sin, cos) = angle.sin_cos();
2974            offsets.push(copy.offset_m[0] * cos + copy.offset_m[1] * sin + terms.body_radius_m);
2975        }
2976    }
2977    let fins = u32::try_from(offsets.len()).map_err(|_| AeroError::Domain {
2978        what: "fins over a pod set's pods",
2979        value: offsets.len() as f64,
2980    })?;
2981    let (mean, deviation) = if offsets.is_empty() {
2982        (0.0, 0.0)
2983    } else {
2984        let n = f64::from(fins);
2985        let mean = offsets.iter().sum::<f64>() / n;
2986        let variance = offsets.iter().map(|o| (o - mean) * (o - mean)).sum::<f64>() / n;
2987        (mean, variance.sqrt())
2988    };
2989    Ok(PodFins {
2990        roll_rad: component.copies.iter().map(|c| c.roll_rad).collect(),
2991        axis_roll: [
2992            terms
2993                .fin
2994                .roll_terms_about(mean + deviation, reference_diameter_m)?,
2995            terms
2996                .fin
2997                .roll_terms_about(mean - deviation, reference_diameter_m)?,
2998        ],
2999        fins,
3000    })
3001}
3002
3003fn body_terms(
3004    component: &PlacedComponent,
3005    geometry: BodyGeometry,
3006    step_area_m2: f64,
3007    a_ref: f64,
3008) -> BodyAero {
3009    let station = component.fore_station_m;
3010    let step_slope = 2.0 * step_area_m2 / a_ref;
3011    let slope = geometry.normal_force_slope(a_ref);
3012    BodyAero {
3013        id: component.id.clone(),
3014        fore_station_m: station,
3015        geometry,
3016        step_area_m2,
3017        slope_per_rad: slope + step_slope,
3018        moment_slope_m: (slope + step_slope) * station + geometry.moment_slope_m(a_ref),
3019        planform_ratio: geometry.planform_area_m2 / a_ref,
3020        lift_station_m: station + geometry.planform_centroid_m,
3021    }
3022}
3023
3024#[cfg(test)]
3025mod tests {
3026    use std::f64::consts::{FRAC_PI_2, FRAC_PI_4};
3027
3028    use hpr_design::{
3029        FinPlanform, LaunchLug, NoseShape, Part, PodSet, Position, RailButton, ReferenceDiameter,
3030        TubeFinSet,
3031    };
3032    use proptest::prelude::*;
3033
3034    use super::*;
3035    use crate::BODY_LIFT_K;
3036    use crate::drag::base_drag_coefficient;
3037    use crate::testing::{body_part, component, fin_set, finned_rocket, material, nose, one_stage};
3038
3039    fn close(got: f64, want: f64, rel: f64, what: &str) {
3040        let err = if want == 0.0 {
3041            got.abs()
3042        } else {
3043            ((got - want) / want).abs()
3044        };
3045        assert!(
3046            err <= rel,
3047            "{what}: got {got}, want {want}, rel err {err:e}"
3048        );
3049    }
3050
3051    fn model(rocket: &hpr_design::Rocket) -> AeroModel {
3052        AeroModel::new(&rocket.layout().unwrap()).unwrap()
3053    }
3054
3055    /// `finned_rocket(4)` with `count` pods on its body tube, 0.1 m aft of the tube's top and
3056    /// 0.04 m from the axis: each a conical nose 0.05 m long on a tube 0.2 m long, 10 mm in radius.
3057    fn podded_rocket(count: u32) -> hpr_design::Rocket {
3058        let mut rocket = finned_rocket(4);
3059        let mut pods = component(
3060            "pods",
3061            Part::PodSet(PodSet {
3062                count,
3063                radial_offset_m: 0.04,
3064                angle_rad: 0.3,
3065            }),
3066            Some(Position::Top { aft_offset_m: 0.1 }),
3067        );
3068        pods.children = vec![
3069            component("pod-nose", nose(NoseShape::Conical {}, 0.05, 0.01), None),
3070            component("pod-tube", body_part(0.2, 0.01, 0.01), None),
3071        ];
3072        rocket.stages[0].components[1].children.push(pods);
3073        rocket
3074    }
3075
3076    /// A small trapezoidal fin for pods.
3077    fn pod_fin_planform() -> FinPlanform {
3078        FinPlanform::Trapezoidal {
3079            root_chord_m: 0.06,
3080            tip_chord_m: 0.03,
3081            span_m: 0.04,
3082            sweep_m: 0.02,
3083        }
3084    }
3085
3086    /// `finned_rocket(4)` with two pods of no length 0.05 m from the axis at roll 0 and π, each
3087    /// holding `fins` fins of [`pod_fin_planform`] on its phantom body (ADR-091), the first at
3088    /// `base_angle_rad` in the pod.
3089    fn winglet_rocket(fins: u32, base_angle_rad: f64) -> hpr_design::Rocket {
3090        let mut rocket = finned_rocket(4);
3091        let mut pods = component(
3092            "pods",
3093            Part::PodSet(PodSet {
3094                count: 2,
3095                radial_offset_m: 0.05,
3096                angle_rad: 0.0,
3097            }),
3098            Some(Position::Top { aft_offset_m: 0.3 }),
3099        );
3100        let mut phantom = component("phantom", body_part(0.0, 0.0, 0.0), None);
3101        let mut set = component(
3102            "winglets",
3103            fin_set(fins, pod_fin_planform()),
3104            Some(Position::Top { aft_offset_m: 0.0 }),
3105        );
3106        if let Part::FinSet(fin_set) = &mut set.part {
3107            fin_set.base_angle_rad = base_angle_rad;
3108        }
3109        phantom.children = vec![set];
3110        pods.children = vec![phantom];
3111        rocket.stages[0].components[1].children.push(pods);
3112        rocket
3113    }
3114
3115    /// A pod's body components are Barrowman's, once per pod (ADR-092): a cone's slope
3116    /// `2 A_base/A_ref` at `2L/3` from its tip, a tube of one radius none, slender-body theory's at
3117    /// every Mach number, added to the airframe's unchanged. Worked by hand: two pods of
3118    /// 10 mm radius on a 27 mm reference radius add `2 · 2 (10/27)²` = 0.548697 per radian.
3119    #[test]
3120    fn a_pod_adds_its_bodies_slopes_once_per_pod() {
3121        let bare = model(&finned_rocket(4));
3122        let area_ratio = (0.01_f64 / 0.027).powi(2);
3123        for count in [1, 2, 3] {
3124            let m = model(&podded_rocket(count));
3125            assert_eq!(m.pod_sets().len(), 1);
3126            let pod = &m.pod_sets()[0];
3127            assert_eq!(pod.copies, count);
3128            close(pod.fineness, 0.25 / 0.02, 1e-15, "pod fineness");
3129            close(
3130                pod.offset_squares_m2,
3131                f64::from(count) * 0.04 * 0.04,
3132                1e-14,
3133                "offsets",
3134            );
3135            let n = f64::from(count);
3136            for mach in [0.3, 0.95, 2.0, 3.5] {
3137                let what = format!("{count} pods, Mach {mach}");
3138                let parts = m.components(&Flow::axial(mach)).unwrap();
3139                let find = |id: &str| {
3140                    parts
3141                        .iter()
3142                        .find(|c| c.id == id)
3143                        .map(|c| c.normal_force)
3144                        .unwrap()
3145                };
3146                let cone = find("pod-nose");
3147                close(cone.slope_per_rad, n * 2.0 * area_ratio, 1e-12, &what);
3148                // The pod set is 0.1 m aft of the body tube's top, 0.25 m from the tip.
3149                close(
3150                    cone.cp_station_m.unwrap(),
3151                    0.35 + 2.0 / 3.0 * 0.05,
3152                    1e-12,
3153                    &what,
3154                );
3155                close(find("pod-tube").slope_per_rad, 0.0, 1e-15, &what);
3156                let with = m.normal_force(&Flow::axial(mach)).unwrap();
3157                let without = bare.normal_force(&Flow::axial(mach)).unwrap();
3158                close(
3159                    with.slope_per_rad - without.slope_per_rad,
3160                    n * 2.0 * area_ratio,
3161                    1e-11,
3162                    &what,
3163                );
3164                close(
3165                    with.moment_slope_m - without.moment_slope_m,
3166                    n * 2.0 * area_ratio * (0.35 + 2.0 / 3.0 * 0.05),
3167                    1e-11,
3168                    &what,
3169                );
3170                // The flight engine's stations and indices see them between the bodies and fins.
3171                let index = parts.iter().position(|c| c.id == "pod-nose").unwrap();
3172                assert_eq!(index, bare.bodies().len());
3173                assert_eq!(m.fin_set_start(), bare.bodies().len() + 2);
3174                close(
3175                    m.component_station_m(index, mach).unwrap(),
3176                    0.35 + 2.0 / 3.0 * 0.05,
3177                    1e-12,
3178                    &what,
3179                );
3180                let one = m.component_normal_force(index, &Flow::axial(mach)).unwrap();
3181                assert_eq!(one, cone);
3182            }
3183        }
3184    }
3185
3186    /// A pod's body lift is its own: Jorgensen's `η C_dn` at the pod's fineness, on its
3187    /// planform, once per pod.
3188    #[test]
3189    fn a_pod_s_body_lift_takes_its_own_fineness() {
3190        let m = model(&podded_rocket(3));
3191        let pod = &m.pod_sets()[0];
3192        let (mach, alpha) = (0.5, 0.2_f64);
3193        let parts = m.components(&flow(mach, alpha, 0.0)).unwrap();
3194        let tube = parts.iter().find(|c| c.id == "pod-tube").unwrap();
3195        let factor = m.lift_factor_of(
3196            12.5,
3197            crate::crossflow::crossflow_eta_low(12.5),
3198            mach,
3199            alpha.sin(),
3200        );
3201        assert!(
3202            (factor - m.lift_factor_of(m.fineness(), m.crossflow_eta_low, mach, alpha.sin())).abs()
3203                > 1e-3,
3204            "the pod's fineness must matter"
3205        );
3206        let planform = 2.0 * 0.01 * 0.2 / m.reference_area_m2();
3207        close(
3208            tube.normal_force.coefficient,
3209            3.0 * factor * planform * alpha.sin().powi(2),
3210            1e-12,
3211            "pod tube's body lift",
3212        );
3213        close(pod.fineness, 12.5, 1e-15, "fineness");
3214    }
3215
3216    /// A pod drags once per pod: friction on its surface at its own fineness's form factor, and
3217    /// its whole base, which a thrusting motor never relieves (the motors' area is the
3218    /// airframe's).
3219    #[test]
3220    fn a_pod_drags_once_per_pod() {
3221        let (mach, reynolds_per_m) = (0.4, 5e6);
3222        for count in [1_u32, 2, 3] {
3223            let m = model(&podded_rocket(count));
3224            let n = f64::from(count);
3225            let a_ref = m.reference_area_m2();
3226            for conditions in [
3227                DragConditions::coasting(reynolds_per_m),
3228                DragConditions::thrusting(reynolds_per_m, 2e-4),
3229            ] {
3230                let parts = m
3231                    .buildup_components(&Flow::axial(mach), &conditions)
3232                    .unwrap();
3233                let find = |id: &str| parts.iter().find(|c| c.id == id).unwrap().drag;
3234                let (body, tube) = (find("body"), find("pod-tube"));
3235                // The same finish and Reynolds number: the friction coefficients cancel.
3236                let ratio = n * body_friction_form_factor(12.5).unwrap()
3237                    / body_friction_form_factor(m.fineness()).unwrap()
3238                    * (0.01 * 0.2)
3239                    / (0.027 * 0.7);
3240                close(tube.friction, ratio * body.friction, 1e-12, "pod friction");
3241                close(
3242                    tube.base,
3243                    n * base_drag_coefficient(mach).unwrap() * PI * 0.01 * 0.01 / a_ref,
3244                    1e-12,
3245                    "pod base",
3246                );
3247                // The nose's own pressure drag, and no base.
3248                let cone = find("pod-nose");
3249                assert_eq!(cone.base, 0.0);
3250                assert!(cone.pressure > 0.0);
3251                let one = model(&podded_rocket(1));
3252                let single = one
3253                    .buildup_components(&Flow::axial(mach), &conditions)
3254                    .unwrap();
3255                let single_cone = single.iter().find(|c| c.id == "pod-nose").unwrap().drag;
3256                close(cone.pressure, n * single_cone.pressure, 1e-14, "pod nose");
3257                let total = m.drag(&Flow::axial(mach), &conditions).unwrap();
3258                let sum: f64 = parts.iter().map(|c| c.drag.zero_lift_coefficient).sum();
3259                close(total.zero_lift_coefficient, sum, 1e-14, "total");
3260            }
3261        }
3262    }
3263
3264    /// A pod that holds a motor mount takes its share of the thrusting pod motors' area off its own
3265    /// base; the airframe's base takes only the airframe's motors, and a pod set without mounts
3266    /// keeps its whole base. With mounts in two pod sets, each set's pods take their own set's
3267    /// area (ADR-168).
3268    #[test]
3269    fn a_pod_s_base_takes_its_own_motors_area() {
3270        let (mach, reynolds_per_m) = (0.4, 5e6);
3271        let mut rocket = podded_rocket(2);
3272        let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
3273        pods.children[1].motor_mount = Some(hpr_design::MotorMount::default());
3274        let m = model(&rocket);
3275        let a_ref = m.reference_area_m2();
3276        let base = |conditions: &DragConditions, id: &str| {
3277            m.buildup_components(&Flow::axial(mach), conditions)
3278                .unwrap()
3279                .into_iter()
3280                .find(|c| c.id == id)
3281                .unwrap()
3282                .drag
3283                .base
3284        };
3285        let pod_area = PI * 0.01 * 0.01;
3286        let c_b = base_drag_coefficient(mach).unwrap();
3287        let coasting = DragConditions::coasting(reynolds_per_m);
3288        close(
3289            base(&coasting, "pod-tube"),
3290            2.0 * c_b * pod_area / a_ref,
3291            1e-14,
3292            "coasting",
3293        );
3294        // Two pod motors of 16 mm burning: each pod's base loses one motor's area.
3295        let motor = PI * 0.008 * 0.008;
3296        let thrusting = DragConditions::thrusting(reynolds_per_m, 0.0).with_pod_motors([
3297            2.0 * motor,
3298            0.0,
3299            0.0,
3300            0.0,
3301        ]);
3302        close(
3303            base(&thrusting, "pod-tube"),
3304            2.0 * c_b * (pod_area - motor) / a_ref,
3305            1e-14,
3306            "pod motors",
3307        );
3308        assert_eq!(base(&thrusting, "tail"), base(&coasting, "tail"));
3309        // The airframe's motor leaves the pods' bases whole.
3310        let core = DragConditions::thrusting(reynolds_per_m, 1e-4);
3311        assert_eq!(base(&core, "pod-tube"), base(&coasting, "pod-tube"));
3312        assert!(base(&core, "tail") < base(&coasting, "tail"));
3313        // A second pod set with a mount: each set's pods take their own set's area alone.
3314        let mut second = component(
3315            "more-pods",
3316            Part::PodSet(PodSet {
3317                count: 2,
3318                radial_offset_m: 0.04,
3319                angle_rad: 1.8,
3320            }),
3321            Some(Position::Top { aft_offset_m: 0.4 }),
3322        );
3323        let mut tube = component("more-pod-tube", body_part(0.1, 0.01, 0.01), None);
3324        tube.motor_mount = Some(hpr_design::MotorMount::default());
3325        second.children = vec![tube];
3326        rocket.stages[0].components[1].children.push(second);
3327        let two = model(&rocket);
3328        let base = |conditions: &DragConditions, id: &str| {
3329            two.buildup_components(&Flow::axial(mach), conditions)
3330                .unwrap()
3331                .into_iter()
3332                .find(|c| c.id == id)
3333                .unwrap()
3334                .drag
3335                .base
3336        };
3337        let motor = PI * 0.004 * 0.004;
3338        let first = DragConditions::thrusting(reynolds_per_m, 0.0).with_pod_motors([
3339            2.0 * motor,
3340            0.0,
3341            0.0,
3342            0.0,
3343        ]);
3344        let second = DragConditions::thrusting(reynolds_per_m, 0.0).with_pod_motors([
3345            0.0,
3346            2.0 * motor,
3347            0.0,
3348            0.0,
3349        ]);
3350        for (conditions, relieved, whole) in [
3351            (&first, "pod-tube", "more-pod-tube"),
3352            (&second, "more-pod-tube", "pod-tube"),
3353        ] {
3354            close(
3355                base(conditions, relieved),
3356                2.0 * c_b * (pod_area - motor) / a_ref,
3357                1e-14,
3358                relieved,
3359            );
3360            assert_eq!(base(conditions, whole), base(&coasting, whole), "{whole}");
3361        }
3362    }
3363
3364    /// With the base's drag kept whole under power (OpenRocket's rule, ADR-097), neither the
3365    /// airframe's nor a pod's base loses its burning motor's area, in the whole rocket's drag or
3366    /// by component; without it both do. Coasting is the same either way.
3367    #[test]
3368    fn a_whole_base_under_power_keeps_the_motors_area() {
3369        let mach = 0.4;
3370        let mut rocket = podded_rocket(2);
3371        let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
3372        pods.children[1].motor_mount = Some(hpr_design::MotorMount::default());
3373        let relieved = model(&rocket);
3374        assert!(!relieved.full_base_drag_under_power());
3375        let whole = relieved.clone().with_full_base_drag_under_power();
3376        assert!(whole.full_base_drag_under_power());
3377        let flow = Flow::axial(mach);
3378        let coasting = DragConditions::coasting(5e6);
3379        let thrusting = DragConditions::thrusting(5e6, 1e-4).with_pod_motors([2e-4, 0.0, 0.0, 0.0]);
3380        let base =
3381            |m: &AeroModel, conditions: &DragConditions| m.drag(&flow, conditions).unwrap().base;
3382        assert_eq!(base(&whole, &thrusting), base(&whole, &coasting));
3383        assert_eq!(base(&whole, &coasting), base(&relieved, &coasting));
3384        assert!(base(&relieved, &thrusting) < base(&relieved, &coasting));
3385        for id in ["tail", "pod-tube"] {
3386            let part = |m: &AeroModel, conditions: &DragConditions| {
3387                m.buildup_components(&flow, conditions)
3388                    .unwrap()
3389                    .into_iter()
3390                    .find(|c| c.id == id)
3391                    .unwrap()
3392                    .drag
3393                    .base
3394            };
3395            assert_eq!(part(&whole, &thrusting), part(&whole, &coasting), "{id}");
3396            assert!(
3397                part(&relieved, &thrusting) < part(&relieved, &coasting),
3398                "{id}"
3399            );
3400        }
3401        // Bad conditions are still refused before they are read.
3402        let bad = DragConditions::thrusting(5e6, -1e-4);
3403        assert!(whole.drag(&flow, &bad).is_err());
3404        assert!(whole.buildup_components(&flow, &bad).is_err());
3405    }
3406
3407    /// A pod's fins turn with it: two pods at π/4 and 5π/4, each holding one fin pointing out,
3408    /// take no angle in a flow rolled to π/4, along their span, and the full angle in one rolled
3409    /// to −π/4, across it. Fins that didn't turn would stand at 0 and π and take half in each.
3410    #[test]
3411    fn a_pod_s_fins_turn_with_their_pod() {
3412        let bare = model(&finned_rocket(4));
3413        let mut rocket = winglet_rocket(1, 0.0);
3414        if let Part::PodSet(pods) = &mut rocket.stages[0].components[1]
3415            .children
3416            .last_mut()
3417            .unwrap()
3418            .part
3419        {
3420            pods.angle_rad = FRAC_PI_4;
3421        }
3422        let m = model(&rocket);
3423        let mach = 0.3;
3424        let slope = FinAero::new(&pod_fin_planform(), m.reference_area_m2())
3425            .unwrap()
3426            .loading(mach)
3427            .unwrap()
3428            .slope_per_rad;
3429        for (roll, share) in [(FRAC_PI_4, 0.0), (-FRAC_PI_4, 2.0)] {
3430            let with = m.normal_force(&flow(mach, 0.0, roll)).unwrap();
3431            let without = bare.normal_force(&flow(mach, 0.0, roll)).unwrap();
3432            close(
3433                with.slope_per_rad - without.slope_per_rad,
3434                share * slope,
3435                1e-12,
3436                &format!("roll {roll}"),
3437            );
3438        }
3439    }
3440
3441    /// Each component, by index, is the one [`AeroModel::components`] lists at that place, with
3442    /// the station a flight takes: the airframe's bodies, two pod sets' bodies in turn, then the
3443    /// fin sets, a pod's among them.
3444    #[test]
3445    fn every_component_index_maps_to_its_own_terms_with_pods() {
3446        let mut rocket = podded_rocket(3);
3447        let winglets = winglet_rocket(2, 0.3);
3448        let mut pods = winglets.stages[0].components[1]
3449            .children
3450            .last()
3451            .unwrap()
3452            .clone();
3453        pods.id = "winglet-pods".to_owned();
3454        rocket.stages[0].components[1].children.push(pods);
3455        let mut second = component(
3456            "aft-pods",
3457            Part::PodSet(PodSet {
3458                count: 2,
3459                radial_offset_m: 0.05,
3460                angle_rad: 1.0,
3461            }),
3462            Some(Position::Top { aft_offset_m: 0.45 }),
3463        );
3464        second.children = vec![
3465            component(
3466                "aft-pod-nose",
3467                nose(NoseShape::Conical {}, 0.04, 0.012),
3468                None,
3469            ),
3470            component("aft-pod-tube", body_part(0.1, 0.012, 0.012), None),
3471            component("aft-pod-tail", body_part(0.03, 0.012, 0.008), None),
3472        ];
3473        rocket.stages[0].components[1].children.push(second);
3474        let m = model(&rocket);
3475        assert_eq!(m.pod_sets().len(), 2);
3476        assert_eq!(m.fin_set_start(), m.bodies().len() + 5);
3477        assert_eq!(m.component_count(), m.fin_set_start() + 2);
3478        for mach in [0.3, 2.0] {
3479            let f = flow(mach, 0.1, 0.4);
3480            let parts = m.components(&f).unwrap();
3481            assert_eq!(parts.len(), m.component_count());
3482            for (index, part) in parts.iter().enumerate() {
3483                let one = m.component_normal_force(index, &f).unwrap();
3484                assert_eq!(one, part.normal_force, "{} at {index}", part.id);
3485                let station = m.component_station_m(index, mach).unwrap();
3486                if let Some(cp) = m.components(&flow(mach, 0.0, 0.4)).unwrap()[index]
3487                    .normal_force
3488                    .cp_station_m
3489                    && index >= m.bodies().len()
3490                {
3491                    close(station, cp, 1e-12, &part.id);
3492                }
3493            }
3494            let ids: Vec<&str> = parts.iter().map(|p| p.id.as_str()).collect();
3495            let at = |id: &str| ids.iter().position(|i| *i == id).unwrap();
3496            assert!(at("pod-tube") < at("aft-pod-nose") && at("aft-pod-tail") < at("winglets"));
3497            assert!(m.component_normal_force(m.component_count(), &f).is_err());
3498        }
3499    }
3500
3501    /// The aero page's worked example (`docs/physics/aero.md`, *Pods*): three pods on the tests'
3502    /// rocket at Mach 0.3 and 5e6 per meter, to the digits the page prints.
3503    #[test]
3504    fn the_aero_page_s_pod_example() {
3505        let (bare, pods) = (model(&finned_rocket(4)), model(&podded_rocket(3)));
3506        let at = |m: &AeroModel| {
3507            let n = m.normal_force(&Flow::axial(0.3)).unwrap();
3508            let c = DragConditions::coasting(5e6);
3509            let d = m.drag(&Flow::axial(0.3), &c).unwrap();
3510            (
3511                n.slope_per_rad,
3512                n.cp_station_m.unwrap(),
3513                d.zero_lift_coefficient,
3514                m.roll(0.3).unwrap().damping,
3515            )
3516        };
3517        let round = |x: f64, digits: i32| (x * 10_f64.powi(digits)).round() / 10_f64.powi(digits);
3518        let (slope, cp, drag, damping) = at(&bare);
3519        assert_eq!(
3520            [
3521                round(slope, 3),
3522                round(cp, 4),
3523                round(drag, 4),
3524                round(damping, 3)
3525            ],
3526            [12.374, 1.0662, 0.5051, -35.215]
3527        );
3528        let (slope, cp, drag, damping) = at(&pods);
3529        assert_eq!(
3530            [
3531                round(slope, 3),
3532                round(cp, 4),
3533                round(drag, 4),
3534                round(damping, 3)
3535            ],
3536            [13.197, 1.0237, 0.6386, -36.118]
3537        );
3538        let parts = pods
3539            .buildup_components(&Flow::axial(0.3), &DragConditions::coasting(5e6))
3540            .unwrap();
3541        let find = |id: &str| parts.iter().find(|c| c.id == id).unwrap().drag;
3542        let (cone, tube) = (find("pod-nose"), find("pod-tube"));
3543        assert_eq!(
3544            [
3545                round(cone.friction, 4),
3546                round(cone.pressure, 4),
3547                round(tube.friction, 4),
3548                round(tube.base, 4)
3549            ],
3550            [0.0074, 0.0127, 0.0592, 0.0542]
3551        );
3552        let single = model(&podded_rocket(1))
3553            .buildup_components(&Flow::axial(0.3), &DragConditions::coasting(5e6))
3554            .unwrap();
3555        let one_pod: f64 = single
3556            .iter()
3557            .filter(|c| c.id.starts_with("pod"))
3558            .map(|c| c.drag.zero_lift_coefficient)
3559            .sum();
3560        assert_eq!(round(one_pod, 4), 0.0445);
3561        let one_slope = model(&podded_rocket(1))
3562            .normal_force(&Flow::axial(0.3))
3563            .unwrap()
3564            .slope_per_rad;
3565        assert_eq!(round(one_slope, 2), 12.65);
3566    }
3567
3568    /// A pod's body under the roll rate `p` crosses the air at `p ρ`: its normal force about the
3569    /// axis damps the roll by `C_lp = −2 C_Nα ρ²/d²` per pod. Worked by hand for three pods of
3570    /// cone slope `2 (10/27)²` = 0.2743 at 40 mm on a 54 mm reference diameter:
3571    /// `−2 · 0.2743 · 3 · 0.04²/0.054²` = −0.903 in all.
3572    #[test]
3573    fn a_pod_s_bodies_damp_the_roll() {
3574        let bare = model(&finned_rocket(4));
3575        let m = model(&podded_rocket(3));
3576        let slope = 2.0 * (0.01_f64 / 0.027).powi(2);
3577        let want = -2.0 * slope * 3.0 * 0.04 * 0.04 / (0.054 * 0.054);
3578        close(want, -0.9032_f64, 1e-4, "worked number");
3579        for mach in [0.3, 1.5] {
3580            let got = m.roll(mach).unwrap().damping - bare.roll(mach).unwrap().damping;
3581            close(got, want, 1e-12, "pod roll damping");
3582            assert_eq!(
3583                m.roll(mach).unwrap().forcing,
3584                bare.roll(mach).unwrap().forcing
3585            );
3586        }
3587    }
3588
3589    /// A pod's fins: each pod's turned with its pod, fin–fin interference among one pod's fins,
3590    /// no body interference on a phantom body, and roll damping by the strips' distance from the
3591    /// rocket's axis.
3592    #[test]
3593    fn a_pod_s_fins_are_the_pod_s_turned_with_it() {
3594        let bare = model(&finned_rocket(4));
3595        let a_ref = bare.reference_area_m2();
3596        let d = 0.054;
3597        let fin = FinAero::new(&pod_fin_planform(), a_ref).unwrap();
3598        // One fin per pod, pointing out from the axis on both pods: across a flow rolled to π/2
3599        // both take the full angle; along it, neither.
3600        let m = model(&winglet_rocket(1, 0.0));
3601        assert!(m.pod_sets().is_empty(), "a phantom body has no body terms");
3602        for mach in [0.3, 1.8] {
3603            let slope = fin.loading(mach).unwrap().slope_per_rad;
3604            let across = m.normal_force(&flow(mach, 0.0, FRAC_PI_2)).unwrap();
3605            let bare_across = bare.normal_force(&flow(mach, 0.0, FRAC_PI_2)).unwrap();
3606            close(
3607                across.slope_per_rad - bare_across.slope_per_rad,
3608                2.0 * slope,
3609                1e-12,
3610                "across",
3611            );
3612            let along = m.normal_force(&flow(mach, 0.0, 0.0)).unwrap();
3613            let bare_along = bare.normal_force(&flow(mach, 0.0, 0.0)).unwrap();
3614            close(
3615                along.slope_per_rad - bare_along.slope_per_rad,
3616                0.0,
3617                1e-12,
3618                "along",
3619            );
3620            // Both roots 0.05 m out along their spans: twice a fin on a 0.05 m body, with no
3621            // body interference.
3622            let damping = m.roll(mach).unwrap().damping - bare.roll(mach).unwrap().damping;
3623            close(
3624                damping,
3625                2.0 * fin.roll(mach, 0.05, d).unwrap().damping,
3626                1e-12,
3627                "damping",
3628            );
3629        }
3630        // Two fins per pod, one out and one in: roots at +0.05 and −0.05 m along their spans.
3631        // Barrowman's strips (eq. 3-48) at Mach 0.5, summed by hand over the four fins.
3632        let m = model(&winglet_rocket(2, 0.0));
3633        let mach = 0.5;
3634        let (c_r, c_t, s) = (0.06, 0.03, 0.04);
3635        let area = 0.5 * s * (c_r + c_t);
3636        let per_area = fin.loading(mach).unwrap().slope_per_rad * a_ref / area;
3637        let strips = 20_000;
3638        let mut second = 0.0;
3639        for i in 0..strips {
3640            let y = s * (f64::from(i) + 0.5) / f64::from(strips);
3641            let chord = c_r + (c_t - c_r) * y / s;
3642            for root in [0.05, -0.05] {
3643                second += 2.0 * (root + y) * (root + y) * chord * s / f64::from(strips);
3644            }
3645        }
3646        let want = -2.0 * per_area * second / (a_ref * d * d);
3647        let got = m.roll(mach).unwrap().damping - bare.roll(mach).unwrap().damping;
3648        close(got, want, 1e-7, "strips");
3649        let set = m.fin_sets().iter().find(|s| s.id == "winglets").unwrap();
3650        let pods = set.pods.as_ref().unwrap();
3651        assert_eq!(pods.fins, 4);
3652        assert_eq!(pods.roll_rad.len(), 2);
3653    }
3654
3655    fn flow(mach: f64, alpha_rad: f64, roll_rad: f64) -> Flow {
3656        Flow::new(mach, alpha_rad, roll_rad)
3657    }
3658
3659    /// A cone on a cylinder, broadside and at small angles: the potential term scales with
3660    /// `sin α`, body lift with `sin² α` at the planform centroids (a cone's `½ L D` at `2L/3`, a
3661    /// cylinder's `L D` at its middle; Galejs Table 1) times the model's factor at the flow's
3662    /// crossflow Mach number, and the slope at `α → 0` is the sum of the Barrowman slopes.
3663    #[test]
3664    fn angle_of_attack_terms() {
3665        let (l_n, l_t, r) = (0.2, 0.8, 0.03);
3666        let rocket = one_stage(
3667            vec![
3668                component("nose", nose(NoseShape::Conical {}, l_n, r), None),
3669                component("tube", body_part(l_t, r, r), None),
3670            ],
3671            ReferenceDiameter::Maximum {},
3672        );
3673        let m = model(&rocket);
3674        let a_ref = PI * r * r;
3675        // Jorgensen's η C_dn at fineness 1.0/0.06 and the crossflow Mach number M sin α.
3676        let k = |alpha: f64| crate::crossflow::crossflow_factor(1.0 / 0.06, 0.3 * alpha.sin());
3677        close(m.fineness(), 1.0 / 0.06, 1e-15, "fineness");
3678        let lift_nose = k(FRAC_PI_2) * r * l_n / a_ref;
3679        let lift_tube = k(FRAC_PI_2) * 2.0 * r * l_t / a_ref;
3680
3681        let broadside = m.normal_force(&flow(0.3, FRAC_PI_2, 0.0)).unwrap();
3682        let want = 2.0 + lift_nose + lift_tube;
3683        close(broadside.coefficient, want, 1e-10, "C_N at 90°");
3684        let moment =
3685            2.0 * (2.0 * l_n / 3.0) + lift_nose * (2.0 * l_n / 3.0) + lift_tube * (l_n + 0.5 * l_t);
3686        close(
3687            broadside.cp_station_m.unwrap(),
3688            moment / want,
3689            1e-10,
3690            "CP at 90°",
3691        );
3692
3693        let zero = m.normal_force(&Flow::axial(0.3)).unwrap();
3694        assert_eq!(zero.coefficient, 0.0);
3695        close(zero.slope_per_rad, 2.0, 1e-15, "slope at 0");
3696        // C_N(α)/α tends to the slope, with body lift adding (η C_dn A_plan/A_ref) α.
3697        for alpha in [1e-6, 1e-3, 0.05] {
3698            let f = m.normal_force(&flow(0.3, alpha, 0.0)).unwrap();
3699            let lift = (lift_nose + lift_tube) * k(alpha) / k(FRAC_PI_2);
3700            let want = 2.0 * alpha.sin() + lift * alpha.sin().powi(2);
3701            close(f.coefficient, want, 1e-12, "C_N");
3702            close(f.slope_per_rad, want / alpha, 1e-12, "C_N/α");
3703        }
3704        // Body lift pulls the CP aft as α grows.
3705        let cp = |alpha| {
3706            m.normal_force(&flow(0.3, alpha, 0.0))
3707                .unwrap()
3708                .cp_station_m
3709                .unwrap()
3710        };
3711        assert!(cp(0.02) > cp(0.0) && cp(0.2) > cp(0.02));
3712        // The components add up.
3713        let parts = m.components(&flow(0.3, 0.2, 0.0)).unwrap();
3714        let total = m.normal_force(&flow(0.3, 0.2, 0.0)).unwrap();
3715        let sum: f64 = parts.iter().map(|c| c.normal_force.coefficient).sum();
3716        close(sum, total.coefficient, 1e-14, "component sum");
3717    }
3718
3719    /// Galejs's constant, hpr's body lift before M1.8e6, is `K` = 1.1 at any flow; Jorgensen's
3720    /// is below it at low crossflow Mach number and above it near `M sin α` = 1.
3721    #[test]
3722    fn body_lift_models() {
3723        let rocket = one_stage(
3724            vec![
3725                component("nose", nose(NoseShape::Conical {}, 0.2, 0.03), None),
3726                component("tube", body_part(0.8, 0.03, 0.03), None),
3727            ],
3728            ReferenceDiameter::Maximum {},
3729        );
3730        let layout = rocket.layout().unwrap();
3731        let old = AeroModel::with_body_model(&layout, BodyModel::BEFORE_M1_8E6).unwrap();
3732        let new = AeroModel::new(&layout).unwrap();
3733        assert_eq!(new.body_model(), BodyModel::default());
3734        for (mach, alpha) in [(0.3, 0.1), (2.0, 0.5), (4.0, 1.2)] {
3735            assert_eq!(old.body_lift_factor(&flow(mach, alpha, 0.0)), BODY_LIFT_K);
3736        }
3737        let slow = new.body_lift_factor(&flow(0.3, 0.1, 0.0));
3738        assert!(slow > 0.85 && slow < 0.9, "{slow}");
3739        let near_one = new.body_lift_factor(&flow(2.0, 0.5, 0.0));
3740        assert!(near_one > 1.4, "{near_one}");
3741        let k = BodyModel::BEFORE_M1_8E6.with_body_lift(BodyLift::Galejs { k: -0.5 });
3742        assert!(AeroModel::with_body_model(&layout, k).is_err());
3743        // The precomputed Fig. 4 `η` gives the library function's factor.
3744        for (mach, alpha) in [(0.3, 0.1), (2.0, 0.5), (4.0, 1.2)] {
3745            let f = flow(mach, alpha, 0.0);
3746            assert_eq!(
3747                new.body_lift_factor(&f),
3748                crate::crossflow::crossflow_factor(new.fineness(), mach * alpha.sin())
3749            );
3750        }
3751    }
3752
3753    /// The body model's JSON form is a file format: it round-trips, a missing field takes the
3754    /// current choice, and an unknown one is refused.
3755    #[test]
3756    fn body_model_in_json() {
3757        assert_eq!(BodyModel::default(), BodyModel::CURRENT);
3758        let old = serde_json::to_string(&BodyModel::BEFORE_M1_8E6).unwrap();
3759        assert_eq!(
3760            old,
3761            r#"{"body_lift":{"kind":"galejs","k":1.1},"supersonic_boattail":"footnote8","supersonic_flare":"slender_body"}"#
3762        );
3763        // A document stored before M1.8e17 has no `supersonic_flare`, so it now reads as a
3764        // marched flare rather than the rule it was stored under. Deliberate (a missing field
3765        // takes the current choice), and stated here so it cannot change silently.
3766        let before_m1_8e17 =
3767            r#"{"body_lift":{"kind":"galejs","k":1.1},"supersonic_boattail":"footnote8"}"#;
3768        assert_eq!(
3769            serde_json::from_str::<BodyModel>(before_m1_8e17)
3770                .unwrap()
3771                .supersonic_flare,
3772            SupersonicFlare::Marched
3773        );
3774        assert_eq!(
3775            serde_json::from_str::<BodyModel>(&old).unwrap(),
3776            BodyModel::BEFORE_M1_8E6
3777        );
3778        assert_eq!(
3779            serde_json::from_str::<BodyModel>(r#"{"supersonic_boattail":"washington_pettis"}"#)
3780                .unwrap(),
3781            BodyModel::CURRENT
3782        );
3783        assert_eq!(
3784            serde_json::from_str::<BodyModel>("{}").unwrap(),
3785            BodyModel::CURRENT
3786        );
3787        for bad in [
3788            r#"{"boattail":"footnote8"}"#,
3789            r#"{"supersonic_boattail":"slender_body"}"#,
3790        ] {
3791            assert!(serde_json::from_str::<BodyModel>(bad).is_err(), "{bad}");
3792        }
3793    }
3794
3795    /// Through subsonic flow, Mach changes the fins' slope by Prandtl–Glauert and nothing else;
3796    /// the bodies and every CP stay put.
3797    #[test]
3798    fn mach_changes_only_the_fins() {
3799        let m = model(&finned_rocket(4));
3800        let at = |mach| m.components(&Flow::axial(mach)).unwrap();
3801        let (slow, fast) = (at(0.0), at(0.8));
3802        for (a, b) in slow.iter().zip(&fast) {
3803            assert_eq!(
3804                a.normal_force.cp_station_m, b.normal_force.cp_station_m,
3805                "{}",
3806                a.id
3807            );
3808            if a.id == "fins" {
3809                let set = &m.fin_sets()[0];
3810                let ratio = set
3811                    .fin
3812                    .geometry()
3813                    .single_fin_slope(m.reference_area_m2(), 0.8)
3814                    .unwrap()
3815                    / set
3816                        .fin
3817                        .geometry()
3818                        .single_fin_slope(m.reference_area_m2(), 0.0)
3819                        .unwrap();
3820                assert!(ratio > 1.05, "{ratio}");
3821                close(
3822                    b.normal_force.slope_per_rad / a.normal_force.slope_per_rad,
3823                    ratio,
3824                    1e-14,
3825                    "fin ratio",
3826                );
3827            } else {
3828                assert_eq!(
3829                    a.normal_force.slope_per_rad, b.normal_force.slope_per_rad,
3830                    "{}",
3831                    a.id
3832                );
3833            }
3834        }
3835    }
3836
3837    /// Four fins don't care about roll; two fins lift only when the flow crosses them.
3838    #[test]
3839    fn two_fin_sets_depend_on_roll() {
3840        let four = model(&finned_rocket(4));
3841        let slope =
3842            |m: &AeroModel, roll| m.normal_force(&flow(0.2, 0.0, roll)).unwrap().slope_per_rad;
3843        close(slope(&four, 0.0), slope(&four, 0.4), 1e-15, "four fins");
3844
3845        let two = model(&finned_rocket(2));
3846        let bodies: f64 = two.bodies().iter().map(|b| b.slope_per_rad).sum();
3847        let set = &two.fin_sets()[0];
3848        let one_fin = set
3849            .fin
3850            .geometry()
3851            .single_fin_slope(two.reference_area_m2(), 0.2)
3852            .unwrap()
3853            * set.interference;
3854        // Flow along the fins' plane: no fin force. Across it: both fins at sin² = 1.
3855        close(slope(&two, 0.0), bodies, 1e-13, "along the fins");
3856        close(
3857            slope(&two, FRAC_PI_2),
3858            bodies + 2.0 * one_fin,
3859            1e-13,
3860            "across the fins",
3861        );
3862        // A two-fin set across the flow matches four fins' N/2 = 2.
3863        close(
3864            slope(&two, FRAC_PI_2),
3865            slope(&four, 0.0),
3866            1e-13,
3867            "two across = four",
3868        );
3869    }
3870
3871    /// `finned_rocket(4)` with `count` tube fins at the foot of its tail, 22 mm in radius:
3872    /// `length_m` long, of outer radius `outer_radius_m` and wall `thickness_m`.
3873    fn tube_finned_rocket(
3874        count: u32,
3875        length_m: f64,
3876        outer_radius_m: f64,
3877        thickness_m: f64,
3878    ) -> hpr_design::Rocket {
3879        let mut rocket = crate::testing::finned_rocket(4);
3880        rocket.stages[0].components[3].children.push(component(
3881            "tube-fins",
3882            Part::TubeFinSet(TubeFinSet {
3883                count,
3884                length_m,
3885                outer_radius_m,
3886                thickness_m,
3887                base_angle_rad: 0.3,
3888                material: material(),
3889            }),
3890            Some(Position::Bottom { aft_offset_m: 0.0 }),
3891        ));
3892        rocket
3893    }
3894
3895    #[test]
3896    fn tube_fins_add_their_rings_slopes_at_fletcher_s_center() {
3897        let plain = model(&crate::testing::finned_rocket(4));
3898        let (count, length, outer, wall) = (6_u32, 0.1, 0.022, 0.0005);
3899        let m = model(&tube_finned_rocket(count, length, outer, wall));
3900        let a_ref = m.reference_area_m2();
3901        let d = 2.0 * outer - wall;
3902        // The tubes' leading edges: the tail's foot, 1.3 m aft of the tip, less their length.
3903        let fore = 1.3 - length;
3904        assert_eq!(m.component_count(), plain.component_count() + 1);
3905        assert_eq!(m.tube_fin_set_start(), plain.component_count());
3906        for (mach, roll) in [(0.0_f64, 0.0), (0.3, 0.4), (0.7, 1.1)] {
3907            let beta = (1.0 - mach * mach).sqrt();
3908            let lambda = length / d;
3909            // Weissinger's slope at `λ/β`, over `β`, and Fletcher's center at `β d/L`, by hand.
3910            let slope = f64::from(count)
3911                * (PI * PI
3912                    / (1.0
3913                        + 0.5 * PI * lambda / beta
3914                        + lambda / beta * (1.2 * lambda / beta).atan()))
3915                / beta
3916                * d
3917                * length
3918                / a_ref;
3919            // On the line from the leading edge at A = 0 to Fletcher's 0.143 at A = 2/3.
3920            let a = beta * d / length;
3921            assert!(a < 2.0 / 3.0);
3922            let center = 0.143 * a / (2.0 / 3.0);
3923            let station = fore + center * length;
3924            let flow = Flow::new(mach, 0.05, roll);
3925            let (with, without) = (
3926                m.normal_force(&flow).unwrap(),
3927                plain.normal_force(&flow).unwrap(),
3928            );
3929            close(
3930                with.slope_per_rad - without.slope_per_rad,
3931                slope,
3932                1e-12,
3933                "slope",
3934            );
3935            close(
3936                with.moment_slope_m - without.moment_slope_m,
3937                slope * station,
3938                1e-12,
3939                "moment",
3940            );
3941            // A ring lifts the same whichever way the flow crosses it.
3942            close(
3943                with.side_coefficient,
3944                without.side_coefficient,
3945                1e-12,
3946                "side",
3947            );
3948            let index = m.tube_fin_set_start();
3949            let own = m.component_normal_force(index, &flow).unwrap();
3950            close(own.slope_per_rad, slope, 1e-12, "component slope");
3951            close(
3952                m.component_station_m(index, mach).unwrap(),
3953                station,
3954                1e-12,
3955                "station",
3956            );
3957            let listed = m.components(&flow).unwrap();
3958            assert_eq!(listed[index].id, "tube-fins");
3959            close(
3960                listed[index].normal_force.slope_per_rad,
3961                slope,
3962                1e-12,
3963                "listed",
3964            );
3965            // Each tube damps the roll about its axis's distance, 22 mm + 22 mm.
3966            let rho = 0.022 + outer;
3967            let damping = -2.0 * slope * rho * rho / (0.054 * 0.054);
3968            close(
3969                m.roll(mach).unwrap().damping - plain.roll(mach).unwrap().damping,
3970                damping,
3971                1e-12,
3972                "roll damping",
3973            );
3974            assert_eq!(m.roll(mach).unwrap().forcing, 0.0);
3975        }
3976    }
3977
3978    #[test]
3979    fn short_tube_fins_take_fletcher_s_measured_center() {
3980        // 20 mm long at a 43.5 mm mean diameter: A = 2.175 at Mach 0, between Fletcher's 1.5 and
3981        // 3, and β A = 1.740 at Mach 0.6. The slope on `d L`, by hand from Weissinger's formula at
3982        // λ = 0.4598 and, stretched by Göthert's rule, at λ/β = 0.5747 over β = 0.8: 5.0510 and
3983        // 5.4837 per radian.
3984        let (length, outer, wall) = (0.02, 0.022, 0.0005);
3985        let m = model(&tube_finned_rocket(6, length, outer, wall));
3986        let d = 2.0 * outer - wall;
3987        let index = m.tube_fin_set_start();
3988        for (mach, a, by_hand) in [(0.0, d / length, 5.0510), (0.6, 0.8 * d / length, 5.4837)] {
3989            let fraction = 0.253 + (0.355 - 0.253) * (a - 1.5) / 1.5;
3990            let station = 1.3 - length + fraction * length;
3991            close(
3992                m.component_station_m(index, mach).unwrap(),
3993                station,
3994                1e-12,
3995                "station",
3996            );
3997            let slope = m
3998                .component_normal_force(index, &Flow::new(mach, 0.05, 0.0))
3999                .unwrap()
4000                .slope_per_rad;
4001            let per_ring = slope / 6.0 * m.reference_area_m2() / (d * length);
4002            close(per_ring, by_hand, 1e-4, "slope on d L");
4003        }
4004    }
4005
4006    /// The guide's worked example (`docs/physics/aero.md`, *Tube fins*): OpenRocket's *Tube fin
4007    /// rocket*'s six tubes, 76.2 mm long, 12.3952 mm in radius with a 0.3302 mm wall, on a body of
4008    /// the same radius.
4009    #[test]
4010    fn the_guide_s_tube_fin_example() {
4011        let r = 0.012_395_2;
4012        let mut tail = component("tail", body_part(0.4572, r, r), None);
4013        tail.children = vec![component(
4014            "tube-fins",
4015            Part::TubeFinSet(TubeFinSet {
4016                count: 6,
4017                length_m: 0.0762,
4018                outer_radius_m: r,
4019                thickness_m: 0.000_330_2,
4020                base_angle_rad: 0.0,
4021                material: material(),
4022            }),
4023            Some(Position::Bottom { aft_offset_m: 0.0 }),
4024        )];
4025        let rocket = one_stage(
4026            vec![
4027                component(
4028                    "nose",
4029                    nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.119_888, r),
4030                    None,
4031                ),
4032                tail,
4033            ],
4034            hpr_design::ReferenceDiameter::Maximum {},
4035        );
4036        let m = model(&rocket);
4037        close(m.reference_area_m2(), 4.827e-4, 1e-4, "reference area");
4038        let set = &m.tube_fin_sets()[0];
4039        close(set.mean_diameter_m, 0.024_460_2, 1e-12, "d");
4040        close(set.length_m / set.mean_diameter_m, 3.115, 1e-3, "λ");
4041        let (slope, station) = set.loading(0.0).unwrap();
4042        close(slope, 22.93, 1e-3, "slope at Mach 0");
4043        close(
4044            set.loading(0.35).unwrap().0,
4045            22.96,
4046            1e-3,
4047            "slope at Mach 0.35",
4048        );
4049        close(
4050            (station - set.fore_station_m) / set.length_m,
4051            0.0689,
4052            1e-3,
4053            "center",
4054        );
4055        let terms = m.drag_terms.iter().find(|t| t.id == "tube-fins").unwrap();
4056        close(terms.friction_area_ratio, 145.6, 1e-3, "friction area");
4057        close(
4058            terms.fins.as_ref().unwrap().frontal_area_ratio,
4059            0.3154,
4060            1e-3,
4061            "wall area",
4062        );
4063    }
4064
4065    #[test]
4066    fn tube_fins_drag_inside_and_out_and_on_their_walls() {
4067        let (count, length, outer, wall) = (6_u32, 0.1, 0.022, 0.0005);
4068        let m = model(&tube_finned_rocket(count, length, outer, wall));
4069        let a_ref = m.reference_area_m2();
4070        let n = f64::from(count);
4071        let inner = outer - wall;
4072        let (mach, reynolds_per_m) = (0.5, 4e6);
4073        let conditions = DragConditions::coasting(reynolds_per_m);
4074        let parts = m
4075            .buildup_components(&Flow::axial(mach), &conditions)
4076            .unwrap();
4077        let tubes = parts.iter().find(|c| c.id == "tube-fins").unwrap().drag;
4078        // `C_fc` at the rocket's Reynolds number and the tubes' finish on its length.
4079        let terms = m.drag_terms.iter().find(|t| t.id == "tube-fins").unwrap();
4080        let cf = crate::drag::skin_friction_coefficient(
4081            reynolds_per_m * m.length_m,
4082            terms.relative_roughness,
4083            mach,
4084        )
4085        .unwrap();
4086        let wetted = n * 2.0 * PI * length * (outer + inner);
4087        close(tubes.friction, cf * wetted / a_ref, 1e-12, "friction");
4088        // Stagnation on the leading edge and base drag behind the trailing edge, on the walls.
4089        let annulus = n * PI * (outer * outer - inner * inner);
4090        let square = crate::drag::stagnation_drag_coefficient(mach).unwrap()
4091            + base_drag_coefficient(mach).unwrap();
4092        close(tubes.pressure, square * annulus / a_ref, 1e-12, "pressure");
4093        assert_eq!((tubes.base, tubes.parasitic), (0.0, 0.0));
4094    }
4095
4096    #[test]
4097    fn tube_fins_refuse_mach_0_8() {
4098        let m = model(&tube_finned_rocket(6, 0.1, 0.022, 0.0005));
4099        // Every call refuses in the same shape, so a flight stops with the same error whichever
4100        // call reaches the limit first.
4101        let refused = |e: AeroError| {
4102            matches!(e, AeroError::Mach { mach, limit, model }
4103                if mach == 0.8 && limit == 0.8 && model == "the tube-fin model")
4104        };
4105        let flow = Flow::new(0.8, 0.05, 0.0);
4106        let index = m.tube_fin_set_start();
4107        assert!(refused(m.normal_force(&flow).unwrap_err()));
4108        assert!(refused(m.components(&flow).unwrap_err()));
4109        assert!(refused(m.component_normal_force(index, &flow).unwrap_err()));
4110        assert!(refused(m.component_station_m(index, 0.8).unwrap_err()));
4111        assert!(refused(m.roll(0.8).unwrap_err()));
4112        let coasting = DragConditions::coasting(4e6);
4113        assert!(refused(m.drag(&Flow::axial(0.8), &coasting).unwrap_err()));
4114        assert!(refused(
4115            m.buildup_components(&Flow::axial(0.8), &coasting)
4116                .unwrap_err()
4117        ));
4118        // The tubes' own drag terms refuse too, called on their own, naming the component.
4119        let terms = m.drag_terms().iter().find(|t| t.id == "tube-fins").unwrap();
4120        let own = terms.evaluate(4e6, 0.8, &coasting, m.reference_area_m2());
4121        assert!(matches!(own, Err(AeroError::InComponent { id, source })
4122            if id == "tube-fins" && matches!(*source, AeroError::Mach { limit, .. } if limit == 0.8)));
4123        // The other components still answer faster than that.
4124        assert!(m.component_normal_force(0, &flow).is_ok());
4125        // Just below, every one answers.
4126        let below = Flow::new(0.8 - 1e-9, 0.05, 0.0);
4127        assert!(m.normal_force(&below).is_ok());
4128        assert!(m.drag(&below, &coasting).is_ok());
4129    }
4130
4131    /// Refusals: tube fins the ring-wing model doesn't take, pods, nine fins, Mach 5, angles
4132    /// outside `[0, π]`. Lugs add no normal force.
4133    #[test]
4134    fn unsupported_inputs_are_refused() {
4135        // Two tube fins, around which the body's flow doesn't cancel, and solid ones.
4136        // Six on the 22 mm tail close the ring at 22 mm, so 23 mm overlap; 5 mm long at 22 mm is
4137        // past Fletcher's A = 3.
4138        for (count, length_m, outer_radius_m, thickness_m, why) in [
4139            (2, 0.1, 0.01, 0.001, "2 tube fins"),
4140            (6, 0.1, 0.01, 0.01, "solid tube fins"),
4141            (6, 0.1, 0.023, 0.001, "tube fins that overlap"),
4142            (6, 0.005, 0.022, 0.001, "tube fins shorter than a third"),
4143        ] {
4144            let rocket = tube_finned_rocket(count, length_m, outer_radius_m, thickness_m);
4145            let err = AeroModel::new(&rocket.layout().unwrap()).unwrap_err();
4146            assert!(
4147                matches!(&err, AeroError::InComponent { id, source } if id == "tube-fins"
4148                    && matches!(&**source, AeroError::Unsupported(what) if what.starts_with(why))),
4149                "{err}"
4150            );
4151        }
4152
4153        // Pods: canted fins on a pod, whose roll forcing about the rocket's axis isn't modeled,
4154        // and a pod's tube of no length with a radius, a flat disc.
4155        let mut rocket = podded_rocket(2);
4156        let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
4157        pods.children[1].children.push(component(
4158            "pod-fins",
4159            fin_set(3, pod_fin_planform()),
4160            Some(Position::Bottom { aft_offset_m: 0.0 }),
4161        ));
4162        if let Part::FinSet(set) = &mut pods.children[1].children[0].part {
4163            set.cant_rad = 0.01;
4164        }
4165        let err = AeroModel::new(&rocket.layout().unwrap()).unwrap_err();
4166        assert!(
4167            matches!(&err, AeroError::InComponent { id, source } if id == "pod-fins"
4168                && matches!(&**source, AeroError::Unsupported(what) if what.starts_with("cant on a pod"))),
4169            "{err}"
4170        );
4171        let mut rocket = podded_rocket(2);
4172        let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
4173        pods.children
4174            .push(component("pod-disc", body_part(0.0, 0.01, 0.01), None));
4175        let err = AeroModel::new(&rocket.layout().unwrap()).unwrap_err();
4176        assert!(
4177            matches!(&err, AeroError::InComponent { id, source } if id == "pod-disc"
4178                && matches!(&**source, AeroError::Unsupported(what) if what.contains("flat disc"))),
4179            "{err}"
4180        );
4181        // A pod set that holds nothing adds nothing, and flies.
4182        let bare = AeroModel::new(&crate::testing::finned_rocket(4).layout().unwrap()).unwrap();
4183        let mut rocket = podded_rocket(2);
4184        let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
4185        pods.children.clear();
4186        let empty = AeroModel::new(&rocket.layout().unwrap()).unwrap();
4187        assert_eq!(format!("{empty:?}"), format!("{bare:?}"));
4188
4189        let err = AeroModel::new(&finned_rocket(9).layout().unwrap()).unwrap_err();
4190        assert!(
4191            matches!(&err, AeroError::InComponent { id, .. } if id == "fins"),
4192            "{err}"
4193        );
4194
4195        let m = model(&finned_rocket(4));
4196        for bad in [
4197            flow(NORMAL_FORCE_MACH_LIMIT, 0.0, 0.0),
4198            flow(-0.01, 0.0, 0.0),
4199            flow(f64::NAN, 0.0, 0.0),
4200        ] {
4201            assert!(matches!(
4202                m.normal_force(&bad),
4203                Err(AeroError::Mach { limit, .. }) if limit == NORMAL_FORCE_MACH_LIMIT
4204            ));
4205        }
4206        // Both fly on past Mach 1 and stop at 5, each naming itself (since M1.8b1).
4207        assert!(m.normal_force(&flow(1.0, 0.1, 0.0)).is_ok());
4208        let coasting = DragConditions::coasting(1e7);
4209        assert!(m.drag(&flow(1.0, 0.0, 0.0), &coasting).is_ok());
4210        assert!(matches!(
4211            m.drag(&flow(5.0, 0.0, 0.0), &coasting),
4212            Err(AeroError::Mach { limit, model, .. })
4213                if limit == BUILDUP_MACH_LIMIT && model == "the drag buildup"
4214        ));
4215        assert!(
4216            m.buildup_components(&flow(5.0, 0.0, 0.0), &coasting)
4217                .is_err()
4218        );
4219        for bad in [
4220            flow(0.3, -1e-9, 0.0),
4221            flow(0.3, PI + 1e-9, 0.0),
4222            flow(0.3, f64::NAN, 0.0),
4223            flow(0.3, 0.1, f64::INFINITY),
4224        ] {
4225            assert!(matches!(
4226                m.normal_force(&bad),
4227                Err(AeroError::Domain { .. })
4228            ));
4229            assert!(m.components(&bad).is_err());
4230        }
4231
4232        let mut lugged = finned_rocket(4);
4233        lugged.stages[0].components[1].children.push(component(
4234            "lug",
4235            Part::LaunchLug(LaunchLug {
4236                length_m: 0.05,
4237                outer_radius_m: 0.004,
4238                thickness_m: 0.0005,
4239                angle_rad: 0.0,
4240                count: 1,
4241                spacing_m: 0.0,
4242                material: material(),
4243            }),
4244            Some(Position::Middle { aft_offset_m: 0.0 }),
4245        ));
4246        let with = model(&lugged).normal_force(&flow(0.3, 0.1, 0.0)).unwrap();
4247        assert_eq!(with, m.normal_force(&flow(0.3, 0.1, 0.0)).unwrap());
4248    }
4249
4250    /// A bare tube has no normal force, and so no CP, at `α = 0`; body lift gives it one at its
4251    /// middle at any other angle.
4252    #[test]
4253    fn a_bare_tube_has_no_cp_at_zero_incidence() {
4254        let tube = one_stage(
4255            vec![component("tube", body_part(1.0, 0.05, 0.05), None)],
4256            ReferenceDiameter::Maximum {},
4257        );
4258        let m = model(&tube);
4259        assert_eq!(
4260            m.normal_force(&Flow::axial(0.5)).unwrap().cp_station_m,
4261            None
4262        );
4263        let f = m.normal_force(&flow(0.5, 0.1, 0.0)).unwrap();
4264        close(f.cp_station_m.unwrap(), 0.5, 1e-15, "tube lift CP");
4265    }
4266
4267    proptest! {
4268        /// Barrowman's coefficients are dimensionless: scaling every length by `k` leaves the slope
4269        /// alone and scales the CP by `k`. A custom reference diameter scales the slope by
4270        /// `(d/d′)²` and leaves the CP alone.
4271        #[test]
4272        fn components_sum_to_the_total(
4273            count in 1u32..=8,
4274            mach in 0.0f64..0.99,
4275            alpha in 0.0f64..PI,
4276            roll in -4.0f64..4.0,
4277        ) {
4278            let m = model(&finned_rocket(count));
4279            let f = flow(mach, alpha, roll);
4280            let total = m.normal_force(&f).unwrap();
4281            let parts = m.components(&f).unwrap();
4282            let (c, moment) = parts.iter().fold((0.0, 0.0), |(c, x), p| {
4283                (c + p.normal_force.coefficient, x + p.normal_force.moment_m)
4284            });
4285            let tol = 1e-12 * (1.0 + total.coefficient.abs());
4286            prop_assert!((c - total.coefficient).abs() <= tol);
4287            prop_assert!((moment - total.moment_m).abs() <= 1e-12 * (1.0 + total.moment_m.abs()));
4288            let side: f64 = parts.iter().map(|p| p.normal_force.side_coefficient).sum();
4289            prop_assert!((side - total.side_coefficient).abs() <= 1e-12 * (1.0 + total.side_coefficient.abs()));
4290            let slope: f64 = parts.iter().map(|p| p.normal_force.slope_per_rad).sum();
4291            prop_assert!((slope - total.slope_per_rad).abs() <= 1e-12 * total.slope_per_rad.abs());
4292            // The allocation-free per-component path gives the same terms, and each component's
4293            // small-angle station is its center of pressure as α → 0.
4294            prop_assert_eq!(m.component_count(), parts.len());
4295            let small = flow(mach, 1e-6, roll);
4296            for (index, part) in parts.iter().enumerate() {
4297                prop_assert_eq!(&m.component_normal_force(index, &f).unwrap(), &part.normal_force);
4298                let station = m.component_station_m(index, mach).unwrap();
4299                if let Some(cp) = m.component_normal_force(index, &small).unwrap().cp_station_m {
4300                    prop_assert!((station - cp).abs() <= 1e-6 * (1.0 + cp.abs()));
4301                }
4302            }
4303            prop_assert!(m.component_normal_force(parts.len(), &f).is_err());
4304            prop_assert!(m.component_station_m(parts.len(), mach).is_err());
4305        }
4306
4307        #[test]
4308        fn scaling_leaves_slopes_and_scales_the_cp(
4309            k in 0.1f64..10.0,
4310            nose_fineness in 1.5f64..8.0,
4311            radius in 0.01f64..0.1,
4312            root in 0.02f64..0.3,
4313            tip_ratio in 0.0f64..1.0,
4314            span in 0.01f64..0.3,
4315            sweep in -0.1f64..0.3,
4316            count in 1u32..=8,
4317            alpha in 0.0f64..0.5,
4318            reference in 0.5f64..2.0,
4319        ) {
4320            let build = |s: f64, custom: Option<f64>| {
4321                let (r, l) = (s * radius, s * (root + 0.5));
4322                let mut tube = component("tube", body_part(l, r, r), None);
4323                let planform = FinPlanform::Trapezoidal {
4324                    root_chord_m: s * root,
4325                    tip_chord_m: s * root * tip_ratio,
4326                    span_m: s * span,
4327                    sweep_m: s * sweep,
4328                };
4329                tube.children = vec![component(
4330                    "fins",
4331                    fin_set(count, planform),
4332                    Some(Position::Bottom { aft_offset_m: 0.0 }),
4333                )];
4334                let ogive = NoseShape::Ogive { radius_ratio: 1.0 };
4335                let nose = component("nose", nose(ogive, 2.0 * nose_fineness * r, r), None);
4336                let mut rocket = one_stage(vec![nose, tube], ReferenceDiameter::Maximum {});
4337                if let Some(d) = custom {
4338                    rocket.reference_diameter = ReferenceDiameter::Custom { diameter_m: d };
4339                }
4340                model(&rocket).normal_force(&flow(0.4, alpha, 0.3)).unwrap()
4341            };
4342            let rel = |a: f64, b: f64| (a / b - 1.0).abs();
4343            let base = build(1.0, None);
4344            let base_cp = base.cp_station_m.unwrap();
4345            let scaled = build(k, None);
4346            prop_assert!(rel(scaled.slope_per_rad, base.slope_per_rad) < 1e-9);
4347            prop_assert!(rel(scaled.cp_station_m.unwrap(), k * base_cp) < 1e-9);
4348            let d = 2.0 * radius * reference;
4349            let custom = build(1.0, Some(d));
4350            let factor = (2.0 * radius / d).powi(2);
4351            prop_assert!(rel(custom.slope_per_rad, factor * base.slope_per_rad) < 1e-12);
4352            prop_assert!(rel(custom.cp_station_m.unwrap(), base_cp) < 1e-12);
4353        }
4354    }
4355
4356    /// A step in radius where two body components meet counts as a zero-length transition at the
4357    /// joint, so the body's total slope is Barrowman 1966 eq. 10 over the whole body: `2` for any
4358    /// pointed body however its radii step.
4359    #[test]
4360    fn radius_steps_count_at_the_joint() {
4361        let rocket = one_stage(
4362            vec![
4363                component("nose", nose(NoseShape::Conical {}, 0.2, 0.027), None),
4364                component("tube", body_part(0.5, 0.029, 0.029), None),
4365                component("tail", body_part(0.3, 0.025, 0.025), None),
4366            ],
4367            ReferenceDiameter::Maximum {},
4368        );
4369        let m = model(&rocket);
4370        let a_ref = PI * 0.029 * 0.029;
4371        let total = m.normal_force(&Flow::axial(0.3)).unwrap();
4372        close(
4373            total.slope_per_rad,
4374            2.0 * PI * 0.025 * 0.025 / a_ref,
4375            1e-14,
4376            "eq. 10",
4377        );
4378        let parts = m.components(&Flow::axial(0.3)).unwrap();
4379        let tube = parts[1].normal_force;
4380        close(
4381            tube.slope_per_rad,
4382            2.0 * PI * (0.029f64.powi(2) - 0.027f64.powi(2)) / a_ref,
4383            1e-14,
4384            "step up",
4385        );
4386        close(
4387            tube.cp_station_m.unwrap(),
4388            0.2,
4389            1e-14,
4390            "step up at the joint",
4391        );
4392        let tail = parts[2].normal_force;
4393        assert!(tail.slope_per_rad < 0.0);
4394        close(
4395            tail.cp_station_m.unwrap(),
4396            0.7,
4397            1e-14,
4398            "step down at the joint",
4399        );
4400        assert_eq!(m.bodies()[0].step_area_m2, 0.0);
4401    }
4402
4403    /// A freeform fin set through the model equals the same trapezoid given as a trapezoid.
4404    #[test]
4405    fn freeform_fins_through_the_model() {
4406        let trapezoid = finned_rocket(3);
4407        let mut freeform = trapezoid.clone();
4408        if let Part::FinSet(set) = &mut freeform.stages[0].components[3].children[0].part {
4409            set.planform = FinPlanform::Freeform {
4410                points_m: vec![[0.0, 0.0], [0.07, 0.06], [0.12, 0.06], [0.12, 0.0]],
4411                root_m: Vec::new(),
4412            };
4413        }
4414        let (a, b) = (model(&trapezoid), model(&freeform));
4415        let f = flow(0.7, 0.1, 0.0);
4416        let (fa, fb) = (a.normal_force(&f).unwrap(), b.normal_force(&f).unwrap());
4417        close(fb.coefficient, fa.coefficient, 1e-13, "C_N");
4418        close(
4419            fb.cp_station_m.unwrap(),
4420            fa.cp_station_m.unwrap(),
4421            1e-13,
4422            "CP",
4423        );
4424    }
4425
4426    /// `Flow` and `NormalForce` round-trip through JSON, and a misspelt flow field is refused.
4427    #[test]
4428    fn flow_and_results_round_trip() {
4429        let f = flow(0.3, 0.1, -0.2);
4430        let back: Flow = serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap();
4431        assert_eq!(back, f);
4432        assert!(
4433            serde_json::from_str::<Flow>(
4434                r#"{"mach":0.3,"alpha_rad":0.1,"roll_rad":0,"aoa_deg":5}"#
4435            )
4436            .is_err()
4437        );
4438        let n = model(&finned_rocket(4)).normal_force(&f).unwrap();
4439        let back: NormalForce = serde_json::from_str(&serde_json::to_string(&n).unwrap()).unwrap();
4440        assert_eq!(back, n);
4441    }
4442
4443    /// Layouts that don't hold together: fins without a body radius, a non-finite station.
4444    #[test]
4445    fn inconsistent_layouts_are_refused() {
4446        let layout = finned_rocket(4).layout().unwrap();
4447        let (fins, _) = layout.find("fins").unwrap();
4448        let mut no_radius = layout.clone();
4449        no_radius.components[fins].body_radius_m = None;
4450        let err = AeroModel::new(&no_radius).unwrap_err();
4451        assert!(
4452            matches!(&err, AeroError::InComponent { id, source } if id == "fins"
4453                && matches!(**source, AeroError::Layout(_))),
4454            "{err}"
4455        );
4456        assert_eq!(err, err.clone());
4457        let mut nan = layout;
4458        nan.components[0].fore_station_m = f64::NAN;
4459        assert!(matches!(
4460            AeroModel::new(&nan),
4461            Err(AeroError::InComponent { .. })
4462        ));
4463    }
4464
4465    /// A two-fin set pushes along its fins' common normal: at 45° to the flow its side share
4466    /// equals its in-plane share, with the side moment at the fins' CP. Four fins have none.
4467    #[test]
4468    fn two_fin_sets_push_across_the_flow() {
4469        let two = model(&finned_rocket(2));
4470        let set = &two.fin_sets()[0];
4471        let alpha = 0.05;
4472        let f = two.normal_force(&flow(0.4, alpha, FRAC_PI_4)).unwrap();
4473        let one_fin = set
4474            .fin
4475            .geometry()
4476            .single_fin_slope(two.reference_area_m2(), 0.4)
4477            .unwrap()
4478            * set.interference;
4479        close(f.side_coefficient, one_fin * alpha, 1e-13, "side");
4480        close(
4481            f.side_moment_m,
4482            one_fin * alpha * set.cp_station_m(0.4).unwrap(),
4483            1e-13,
4484            "side moment",
4485        );
4486        let fins = &two.components(&flow(0.4, alpha, FRAC_PI_4)).unwrap()[4];
4487        close(
4488            fins.normal_force.coefficient,
4489            one_fin * alpha,
4490            1e-13,
4491            "in plane",
4492        );
4493        let four = model(&finned_rocket(4))
4494            .normal_force(&flow(0.4, alpha, 0.3))
4495            .unwrap();
4496        assert_eq!((four.side_coefficient, four.side_moment_m), (0.0, 0.0));
4497    }
4498
4499    /// A body whose areas cancel to round-off has no CP rather than a CP at 1e14 m; its moment is
4500    /// still reported.
4501    #[test]
4502    fn a_cancelled_slope_has_no_cp() {
4503        let rocket = one_stage(
4504            vec![
4505                component("nose", nose(NoseShape::Conical {}, 0.2, 0.0254), None),
4506                component("tube", body_part(0.5, 0.0254, 0.0254), None),
4507                component("tail", body_part(0.3, 0.0254, 1e-9), None),
4508            ],
4509            ReferenceDiameter::Maximum {},
4510        );
4511        let m = model(&rocket);
4512        let f = m.normal_force(&Flow::axial(0.3)).unwrap();
4513        assert!(f.slope_per_rad.abs() < 1e-12, "{}", f.slope_per_rad);
4514        assert_eq!(f.cp_station_m, None);
4515        let moving = m.normal_force(&flow(0.3, 0.01, 0.0)).unwrap();
4516        assert!(moving.moment_m.is_finite() && moving.cp_station_m.is_some());
4517    }
4518
4519    /// A normal-force table replaces the whole rocket's normal force and center of pressure, on
4520    /// its own reference area; the components stay hpr's, for the flight's damping.
4521    #[test]
4522    fn a_normal_force_table_replaces_the_sum() {
4523        use crate::table::{NormalForceColumn, NormalForceTable};
4524        use hpr_core::interp::{Extrapolation, Interpolation, Table1D};
4525
4526        let m = model(&finned_rocket(4));
4527        let flat = |value| {
4528            Table1D::new(
4529                vec![0.0, 2.0],
4530                vec![value, value],
4531                Interpolation::Linear,
4532                Extrapolation::Clamp,
4533            )
4534            .unwrap()
4535        };
4536        let table = NormalForceTable::new(vec![NormalForceColumn::new(0.0, flat(10.0), flat(0.9))])
4537            .unwrap();
4538        let with = m.clone().with_normal_force_table(table.clone()).unwrap();
4539        let at = flow(0.5, 0.02, 0.3);
4540        let replaced = with.normal_force(&at).unwrap();
4541        close(replaced.coefficient, 10.0 * 0.02_f64.sin(), 1e-15, "C_N");
4542        close(
4543            replaced.moment_m,
4544            replaced.coefficient * 0.9,
4545            1e-15,
4546            "moment",
4547        );
4548        assert_eq!(replaced.cp_station_m, Some(0.9));
4549        assert_eq!(
4550            (replaced.side_coefficient, replaced.side_moment_m),
4551            (0.0, 0.0)
4552        );
4553        // One column at 0°, so any angle is past it, and the lookup says so.
4554        assert!(replaced.table.is_some_and(|lookup| lookup.beyond_alpha));
4555        assert_eq!(m.normal_force(&at).unwrap().table, None);
4556        assert_eq!(with.components(&at).unwrap(), m.components(&at).unwrap());
4557        assert_eq!(
4558            with.component_normal_force(3, &at).unwrap(),
4559            m.component_normal_force(3, &at).unwrap()
4560        );
4561        assert_ne!(m.normal_force(&at).unwrap(), replaced);
4562        // A table on a 108 mm reference, twice the rocket's 54 mm, gives four times the coefficient.
4563        let wider = m
4564            .clone()
4565            .with_normal_force_table(table.clone().with_reference_diameter_m(0.108).unwrap())
4566            .unwrap();
4567        let scaled = wider.normal_force(&at).unwrap();
4568        close(
4569            scaled.coefficient,
4570            4.0 * replaced.coefficient,
4571            1e-14,
4572            "rescaled",
4573        );
4574        assert_eq!(scaled.cp_station_m, Some(0.9));
4575        // RASAero II's reference, the largest body: 54 mm here, the rocket's own.
4576        let largest = m
4577            .clone()
4578            .with_normal_force_table(
4579                table
4580                    .clone()
4581                    .with_reference(TableReference::LargestBody)
4582                    .unwrap(),
4583            )
4584            .unwrap();
4585        close(
4586            largest.normal_force(&at).unwrap().coefficient,
4587            replaced.coefficient,
4588            1e-14,
4589            "largest body",
4590        );
4591        // On a rocket whose reference is half its largest body, RASAero II's reference, the
4592        // largest body, is four times the area.
4593        let mut half = finned_rocket(4);
4594        half.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.027 };
4595        let half = model(&half)
4596            .with_normal_force_table(
4597                table
4598                    .clone()
4599                    .with_reference(TableReference::LargestBody)
4600                    .unwrap(),
4601            )
4602            .unwrap();
4603        close(
4604            half.normal_force(&at).unwrap().coefficient,
4605            4.0 * replaced.coefficient,
4606            1e-14,
4607            "largest body on a half-size reference",
4608        );
4609        // Past Mach 5 a center of pressure may leave the rocket; below, it may not.
4610        let hypersonic = |cp_at_6: f64| {
4611            let cps = Table1D::new(
4612                vec![0.0, 5.0, 6.0, 25.0],
4613                vec![0.9, 0.9, cp_at_6, -3.0],
4614                Interpolation::Linear,
4615                Extrapolation::Clamp,
4616            )
4617            .unwrap();
4618            NormalForceTable::new(vec![NormalForceColumn::new(0.0, flat(10.0), cps)]).unwrap()
4619        };
4620        assert!(m.clone().with_normal_force_table(hypersonic(0.8)).is_ok());
4621        assert!(m.clone().with_normal_force_table(hypersonic(-0.1)).is_err());
4622        // A center of pressure behind the tail or ahead of the nose is refused.
4623        for cp in [-0.01, 1.4] {
4624            let outside =
4625                NormalForceTable::new(vec![NormalForceColumn::new(0.0, flat(10.0), flat(cp))])
4626                    .unwrap();
4627            assert!(matches!(
4628                m.clone().with_normal_force_table(outside),
4629                Err(AeroError::Domain { .. })
4630            ));
4631        }
4632        // A table takes any Mach number; hpr's own normal force stops at Mach 5.
4633        assert!(with.normal_force(&flow(6.0, 0.02, 0.0)).is_ok());
4634        assert!(matches!(
4635            m.normal_force(&flow(6.0, 0.02, 0.0)),
4636            Err(AeroError::Mach { .. })
4637        ));
4638    }
4639
4640    /// The finned rocket with its boattail and tail at the body's radius: a nose and three
4641    /// cylinders, which the shock-expansion method covers to the end.
4642    fn straight_rocket() -> hpr_design::Rocket {
4643        let mut rocket = crate::testing::finned_rocket(4);
4644        rocket.stages[0].components[2].part = body_part(0.05, 0.027, 0.027);
4645        rocket.stages[0].components[3].part = body_part(0.3, 0.027, 0.027);
4646        rocket
4647    }
4648
4649    /// The straight rocket's body as the method takes it.
4650    fn straight_rocket_body() -> ShockExpansionBody {
4651        let nose =
4652            hpr_design::Profile::nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027).unwrap();
4653        let cylinder = |length_m| BodySegment::Cylinder {
4654            length_m,
4655            radius_m: 0.027,
4656        };
4657        ShockExpansionBody::new(
4658            &[
4659                BodySegment::Profile { profile: nose },
4660                cylinder(0.7),
4661                cylinder(0.05),
4662                cylinder(0.3),
4663            ],
4664            DEFAULT_ELEMENTS_PER_CURVE,
4665        )
4666        .unwrap()
4667    }
4668
4669    /// Each body's slope and moment slope at `α = 0` (body lift vanishes there), and its station.
4670    fn body_values(model: &AeroModel, mach: f64) -> Vec<[f64; 3]> {
4671        (0..model.bodies().len())
4672            .map(|index| {
4673                let force = model
4674                    .component_normal_force(index, &flow(mach, 0.0, 0.0))
4675                    .unwrap();
4676                // At `α = 0` the moment is zero; the slope's moment is the CP times the slope.
4677                let moment = force
4678                    .cp_station_m
4679                    .map_or(0.0, |cp| cp * force.slope_per_rad);
4680                [
4681                    force.slope_per_rad,
4682                    moment,
4683                    model.component_station_m(index, mach).unwrap(),
4684                ]
4685            })
4686            .collect()
4687    }
4688
4689    /// Asserts that no body's slope, moment or station jumps across `mach` at ±1e-9.
4690    fn no_jump(model: &AeroModel, mach: f64) {
4691        let below = body_values(model, mach - 1e-9);
4692        let above = body_values(model, mach + 1e-9);
4693        for (b, a) in below.iter().zip(&above) {
4694            for k in 0..3 {
4695                let scale = b[k].abs().max(a[k].abs()).max(1.0);
4696                assert!(
4697                    (a[k] - b[k]).abs() <= 1e-7 * scale,
4698                    "a jump at Mach {mach}: {b:?} to {a:?}"
4699                );
4700            }
4701        }
4702    }
4703
4704    #[test]
4705    fn the_supersonic_join_has_no_jump() {
4706        let model = model(&straight_rocket());
4707        let join = model.supersonic_body().unwrap();
4708        assert_eq!(join.covered, 4);
4709        assert_eq!(join.join_start_mach, SUPERSONIC_JOIN_START_MACH);
4710        // The join's ends, rows of the table, points between rows, and the table's last row.
4711        let start = join.join_start_mach;
4712        for mach in [
4713            start,
4714            start + SUPERSONIC_JOIN_WIDTH_MACH,
4715            1.35,
4716            2.0,
4717            2.05,
4718            3.0,
4719            4.63,
4720            4.95,
4721            4.999,
4722        ] {
4723            no_jump(&model, mach);
4724        }
4725        // The join moves the body: the cylinder carries lift past it.
4726        let (low, high) = (body_values(&model, 1.0), body_values(&model, 2.0));
4727        assert_eq!(low[1][0], 0.0);
4728        assert!(high[1][0] > 0.1, "{:?}", high[1]);
4729    }
4730
4731    /// M1.8e6's done-when: at an angle of attack, where body lift acts, the whole rocket's
4732    /// normal force and center of pressure don't jump at ±1e-9 in Mach: across the supersonic
4733    /// join, the table's rows, and every Mach number where the crossflow Mach number `M sin α`
4734    /// meets a row of Jorgensen's tables, with either boattail rule.
4735    #[test]
4736    fn crossflow_and_the_boattail_fly_without_a_jump() {
4737        use crate::crossflow::{CROSSFLOW_DRAG_MACHS, ETA_MACHS};
4738        let layout = finned_rocket(4).layout().unwrap();
4739        for boattail in [
4740            SupersonicBoattail::WashingtonPettis,
4741            SupersonicBoattail::Footnote8,
4742        ] {
4743            let model = AeroModel::with_body_model(
4744                &layout,
4745                BodyModel::CURRENT.with_supersonic_boattail(boattail),
4746            )
4747            .unwrap();
4748            let start = model.supersonic_body().unwrap().join_start_mach;
4749            for alpha_deg in [10.0_f64, 30.0] {
4750                let s = alpha_deg.to_radians().sin();
4751                let mut machs = vec![start, start + SUPERSONIC_JOIN_WIDTH_MACH, 2.0, 2.05, 4.999];
4752                machs.extend(
4753                    CROSSFLOW_DRAG_MACHS
4754                        .iter()
4755                        .chain(&ETA_MACHS)
4756                        .map(|m| m / s)
4757                        .filter(|&m| m > 1e-3 && m < 4.999),
4758                );
4759                for mach in machs {
4760                    let at = |m: f64| {
4761                        let f = model
4762                            .normal_force(&flow(m, alpha_deg.to_radians(), 0.0))
4763                            .unwrap();
4764                        [f.coefficient, f.cp_station_m.unwrap()]
4765                    };
4766                    let (below, above) = (at(mach - 1e-9), at(mach + 1e-9));
4767                    for k in 0..2 {
4768                        let scale = below[k].abs().max(1.0);
4769                        assert!(
4770                            (above[k] - below[k]).abs() <= 1e-7 * scale,
4771                            "{boattail:?} at {alpha_deg}° and Mach {mach}: {below:?} to {above:?}"
4772                        );
4773                    }
4774                }
4775            }
4776        }
4777    }
4778
4779    /// Vertical tips (power-series noses below `n` = 1, the von Kármán and L-V Haack, an
4780    /// elliptical nose) fly the method behind TN D-4865's Newtonian cap (M1.8e7), with a boattail
4781    /// and without, and nothing jumps at ±1e-9 in Mach: across the join, every row of the table, three
4782    /// points between each pair of rows,
4783    /// and Mach 2.1, near where the cap's handover reaches Fig. 2's 24°.
4784    #[test]
4785    fn vertical_tips_fly_the_method_without_a_jump() {
4786        for shape in [
4787            NoseShape::PowerSeries { exponent: 0.6369 },
4788            NoseShape::PowerSeries { exponent: 0.5 },
4789            NoseShape::VON_KARMAN,
4790            NoseShape::LV_HAACK,
4791            NoseShape::Elliptical {},
4792        ] {
4793            for boattail in [true, false] {
4794                let mut rocket = if boattail {
4795                    finned_rocket(4)
4796                } else {
4797                    straight_rocket()
4798                };
4799                rocket.stages[0].components[0].part = nose(shape, 0.25, 0.027);
4800                let model = model(&rocket);
4801                let table = model
4802                    .supersonic_body()
4803                    .unwrap_or_else(|| panic!("{shape:?}: no table"));
4804                assert_eq!(table.covered, 4, "{shape:?}");
4805                // On a row, the straight body's shares are the method's own.
4806                if !boattail {
4807                    let Part::NoseCone(cone) = &rocket.stages[0].components[0].part else {
4808                        unreachable!("`nose` builds a nose cone")
4809                    };
4810                    let cylinder = |length_m| BodySegment::Cylinder {
4811                        length_m,
4812                        radius_m: 0.027,
4813                    };
4814                    let body = ShockExpansionBody::new(
4815                        &[
4816                            BodySegment::Profile {
4817                                profile: cone.profile().unwrap(),
4818                            },
4819                            cylinder(0.7),
4820                            cylinder(0.05),
4821                            cylinder(0.3),
4822                        ],
4823                        DEFAULT_ELEMENTS_PER_CURVE,
4824                    )
4825                    .unwrap();
4826                    let method = body.segment_slopes(3.0, model.reference_area_m2()).unwrap();
4827                    let (nose_slope, _) = table.share(0, 3.0).unwrap();
4828                    assert!(
4829                        (nose_slope - method[0].slope_per_rad).abs() <= 1e-12,
4830                        "{shape:?}: {nose_slope} against {:?}",
4831                        method[0]
4832                    );
4833                }
4834                let start = table.join_start_mach;
4835                let mut machs = vec![start, start + SUPERSONIC_JOIN_WIDTH_MACH, 2.1, 4.999];
4836                // Every row of the table, and three points between each pair: a jump could hide
4837                // at a row, and between them the model is more than the interpolation (body lift
4838                // takes the flow's own Mach number).
4839                machs.extend(
4840                    (SUPERSONIC_FIRST_STEP..SUPERSONIC_LAST_STEP).flat_map(|step| {
4841                        let row = step as f64 / SUPERSONIC_STEPS_PER_MACH;
4842                        [row, row + 0.013, row + 0.027, row + 0.041]
4843                    }),
4844                );
4845                for alpha_deg in [1.0_f64, 10.0] {
4846                    for &mach in &machs {
4847                        let at = |m: f64| {
4848                            let f = model
4849                                .normal_force(&flow(m, alpha_deg.to_radians(), 0.0))
4850                                .unwrap();
4851                            [f.coefficient, f.cp_station_m.unwrap()]
4852                        };
4853                        let (below, above) = (at(mach - 1e-9), at(mach + 1e-9));
4854                        for k in 0..2 {
4855                            let scale = below[k].abs().max(1.0);
4856                            assert!(
4857                                (above[k] - below[k]).abs() <= 1e-7 * scale,
4858                                "{shape:?} at {alpha_deg}° and Mach {mach}: {below:?} to {above:?}"
4859                            );
4860                        }
4861                    }
4862                }
4863            }
4864        }
4865    }
4866
4867    /// A blunt tip's join starts where its cap first ends on the nose: at the Mach number whose
4868    /// handover angle is the nose's slope at its base, found without the method from
4869    /// [`crate::blunt_tip::handover_angle_rad`]. The method holds on one side of it only, with no
4870    /// flicker from corners too close to place (the handover packs the nose's elements into
4871    /// nanometers there; issue found when CI's Linux and Windows runs bisected a different start).
4872    #[test]
4873    fn a_blunt_tips_join_starts_where_its_cap_first_ends_on_the_nose() {
4874        let mut rocket = crate::testing::committed_design("wind-tunnel-arcas-robin-short.json");
4875        // The nose, the cylinder and the boattail; the lip left off.
4876        rocket.stages[0].components.truncate(3);
4877        let model = model(&rocket);
4878        let table = model.supersonic_body().unwrap();
4879        let Part::NoseCone(cone) = &rocket.stages[0].components[0].part else {
4880            unreachable!("the committed design starts with its nose")
4881        };
4882        let profile = cone.profile().unwrap();
4883        let base_angle = profile.radius_and_slope(profile.length_m()).1.atan();
4884        let (mut low, mut high) = (1.0 + 1e-9, 2.0);
4885        for _ in 0..200 {
4886            let mid = 0.5 * (low + high);
4887            if crate::blunt_tip::handover_angle_rad(mid).unwrap() < base_angle {
4888                low = mid;
4889            } else {
4890                high = mid;
4891            }
4892        }
4893        assert!(
4894            (table.join_start_mach - high).abs() <= 1e-12,
4895            "{} against {high}",
4896            table.join_start_mach
4897        );
4898        let run = model.supersonic_run.as_ref().unwrap();
4899        let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
4900        let in_its_place: Vec<Option<ShockExpansionBody>> = run
4901            .boattails
4902            .iter()
4903            .map(|b| {
4904                b.as_ref().map(|b| {
4905                    ShockExpansionBody::new(&b.in_its_place, DEFAULT_ELEMENTS_PER_CURVE).unwrap()
4906                })
4907            })
4908            .collect();
4909        let holds = |m: f64| {
4910            run.shares(&body, &in_its_place, None, m, model.reference_area_m2())
4911                .is_some()
4912        };
4913        for i in 1..=2000 {
4914            let d = f64::from(i) * 1e-10;
4915            assert!(
4916                !holds(table.join_start_mach - d),
4917                "holds {d} below the start"
4918            );
4919            assert!(
4920                holds(table.join_start_mach + d),
4921                "fails {d} above the start"
4922            );
4923        }
4924    }
4925
4926    #[test]
4927    fn a_long_lip_is_reported_as_the_runs_fallback() {
4928        // A lip drawn longer than its boattail's drop in diameter is the run's fallback (issue
4929        // #120, ADR-181); one a hair shorter keeps the run.
4930        let rocket = crate::testing::committed_design("wind-tunnel-arcas-robin-short.json");
4931        let components = &rocket.stages[0].components;
4932        let drop_m = components
4933            .iter()
4934            .find_map(|c| match &c.part {
4935                Part::Transition(t) if t.aft_radius_m < t.fore_radius_m => {
4936                    Some(2.0 * (t.fore_radius_m - t.aft_radius_m))
4937                }
4938                _ => None,
4939            })
4940            .unwrap();
4941        let lip_index = components.iter().position(|c| c.id == "lip").unwrap();
4942        let with_lip = |length_m: f64| {
4943            let mut rocket = rocket.clone();
4944            let lip = &mut rocket.stages[0].components[lip_index];
4945            match &mut lip.part {
4946                Part::Transition(t) => t.length_m = length_m,
4947                Part::BodyTube(t) => t.length_m = length_m,
4948                other => panic!("the lip is a {}", other.kind_name()),
4949            }
4950            model(&rocket).supersonic_fallback()
4951        };
4952        assert_eq!(with_lip(drop_m * (1.0 - 1e-9)), None);
4953        assert_eq!(
4954            with_lip(drop_m * (1.0 + 1e-9)),
4955            Some(SupersonicFallback::LongLip {
4956                component: "lip".to_owned()
4957            })
4958        );
4959    }
4960
4961    /// A lip in a boattail's wake carries nothing faster than sound (M1.8e8): the committed Arcas
4962    /// Robin designs fly the method to their base, the lip's share is zero above the join and
4963    /// slender-body theory's below it, and nothing jumps at ±1e-9 in Mach. A lip that rises too
4964    /// far out of the wake still keeps the whole body on slender-body theory.
4965    #[test]
4966    fn a_lip_in_a_boattails_wake_carries_nothing() {
4967        for name in [
4968            "wind-tunnel-arcas-robin-short.json",
4969            "wind-tunnel-arcas-robin-long.json",
4970        ] {
4971            let rocket = crate::testing::committed_design(name);
4972            let model = model(&rocket);
4973            let table = model
4974                .supersonic_body()
4975                .unwrap_or_else(|| panic!("{name}: no table"));
4976            // The nose, the tube, the boattail and the lip.
4977            assert_eq!(table.covered, 4, "{name}");
4978            let lip = model.bodies().last().unwrap();
4979            assert!(lip.slope_per_rad > 0.1, "{name}: the lip is a flare");
4980            for mach in [1.3, 2.0, 3.0, 5.0] {
4981                let (slope, moment) = table.share(3, mach).unwrap();
4982                assert_eq!((slope, moment), (0.0, 0.0), "{name} at Mach {mach}");
4983            }
4984            // Below the join the lip keeps slender-body theory's share; above it, nothing.
4985            let start = table.join_start_mach;
4986            // At zero angle body lift vanishes, so this is the potential-flow share alone.
4987            let lip_slope = |mach: f64| {
4988                model
4989                    .components(&Flow::axial(mach))
4990                    .unwrap()
4991                    .into_iter()
4992                    .find(|c| c.id == "lip")
4993                    .unwrap()
4994                    .normal_force
4995                    .slope_per_rad
4996            };
4997            let below = lip_slope(1.0);
4998            assert!(
4999                (below - lip.slope_per_rad).abs() <= 0.01 * lip.slope_per_rad,
5000                "{name}: {below} against slender-body theory's {}",
5001                lip.slope_per_rad
5002            );
5003            let above = lip_slope(start + SUPERSONIC_JOIN_WIDTH_MACH);
5004            assert!(above.abs() <= 1e-12, "{name}: {above} above the join");
5005            for alpha_deg in [1.0_f64, 10.0] {
5006                let mut machs = vec![start, start + SUPERSONIC_JOIN_WIDTH_MACH, 4.999];
5007                machs.extend(
5008                    (SUPERSONIC_FIRST_STEP..SUPERSONIC_LAST_STEP).flat_map(|step| {
5009                        let row = step as f64 / SUPERSONIC_STEPS_PER_MACH;
5010                        [row, row + 0.017, row + 0.033]
5011                    }),
5012                );
5013                for mach in machs {
5014                    let at = |m: f64| {
5015                        let f = model
5016                            .normal_force(&flow(m, alpha_deg.to_radians(), 0.0))
5017                            .unwrap();
5018                        [f.coefficient, f.cp_station_m.unwrap()]
5019                    };
5020                    let (below, above) = (at(mach - 1e-9), at(mach + 1e-9));
5021                    for k in 0..2 {
5022                        let scale = below[k].abs().max(1.0);
5023                        assert!(
5024                            (above[k] - below[k]).abs() <= 1e-7 * scale,
5025                            "{name} at {alpha_deg}° and Mach {mach}: {below:?} to {above:?}"
5026                        );
5027                    }
5028                }
5029            }
5030        }
5031        // The shelter, weighed. The drag buildup's wake takes a lip rising a quarter of the
5032        // boattail's drop in diameter wholly (`crate::drag::WAKE_FULL_RISE`) and one rising half
5033        // of it not at all, grading between; the method reads the same number as its weight, so
5034        // the body moves between the two models continuously as the lip is drawn taller.
5035        let lipped = |rise: f64| {
5036            let mut rocket = crate::testing::finned_rocket(4);
5037            // The nose, the tube and the boattail, which drops from 0.027 m to 0.022 m in radius:
5038            // 0.010 m in diameter. The lip sits straight behind it, since a wake fades over any
5039            // tube between them.
5040            rocket.stages[0].components.truncate(3);
5041            rocket.stages[0].components.push(component(
5042                "lip",
5043                body_part(0.01, 0.022, 0.022 + 0.5 * rise * 0.010),
5044                None,
5045            ));
5046            model(&rocket)
5047        };
5048        assert_eq!(lipped(0.2).supersonic_body().map(|t| t.covered), Some(4));
5049        assert!(lipped(0.6).supersonic_body().is_none());
5050        let at = |rise: f64| {
5051            let model = lipped(rise);
5052            let f = model
5053                .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
5054                .unwrap();
5055            (f.coefficient, f.cp_station_m.unwrap())
5056        };
5057        // Across the old threshold, a quarter of the drop: before M1.8e10 the whole rocket's
5058        // normal force fell by a third here and its center of pressure jumped 1.8 calibers
5059        // forward (issue #87). What is left is the weight ramping off its clamp, proportional to
5060        // the change in shape: a ten-thousandth of the force over a ten-thousandth of the drop.
5061        let (below, above) = (at(0.2499), at(0.2501));
5062        assert!(
5063            (above.0 - below.0).abs() <= 2e-4 * below.0.abs()
5064                && (above.1 - below.1).abs() <= 2e-4 * below.1.abs(),
5065            "{below:?} to {above:?} across the wake's full-shelter rise"
5066        );
5067        // How far apart the two models are at one shape, which is what a lip in the band is
5068        // uncertain by: take the same rocket out of the wake by making the lip a hair longer
5069        // than the boattail's drop, which changes no radius and no angle.
5070        let out_of_wake = {
5071            let mut rocket = crate::testing::finned_rocket(4);
5072            rocket.stages[0].components.truncate(3);
5073            rocket.stages[0].components.push(component(
5074                "lip",
5075                body_part(0.0101, 0.022, 0.022 + 0.5 * 0.25 * 0.010),
5076                None,
5077            ));
5078            let m = model(&rocket);
5079            assert!(
5080                m.supersonic_body().is_none(),
5081                "out of the wake by its length"
5082            );
5083            let f = m.normal_force(&flow(3.0, 4f64.to_radians(), 0.0)).unwrap();
5084            (
5085                f.coefficient,
5086                f.cp_station_m.unwrap() / m.reference_diameter_m(),
5087            )
5088        };
5089        let in_wake = at(0.25);
5090        let diameter_m = model(&crate::testing::finned_rocket(4)).reference_diameter_m();
5091        let gap_force = out_of_wake.0 / in_wake.0 - 1.0;
5092        let gap_calibers = out_of_wake.1 - in_wake.1 / diameter_m;
5093        assert!(
5094            (gap_force + 0.3295).abs() < 5e-4 && (gap_calibers + 1.774).abs() < 5e-3,
5095            "at one shape the two models differ by {gap_force} in force and {gap_calibers} \
5096             calibers in center of pressure"
5097        );
5098        // What the band is worth, end to end: the jump is gone, but the same difference between
5099        // the two models is spread over it, and the guide quotes these numbers.
5100        let (full, nearly_none) = (at(0.25), at(0.4999));
5101        let calibers = (nearly_none.1 - full.1) / diameter_m;
5102        assert!(
5103            (nearly_none.0 / full.0 - 1.0 + 0.291).abs() < 5e-4 && (calibers + 0.932).abs() < 5e-3,
5104            "across the band: {full:?} to {nearly_none:?}, {calibers} calibers"
5105        );
5106        // The weight is the wake's own share, and it carries the body to slender-body theory by
5107        // the far edge: at half the drop the method is gone, and just inside it is nearly gone.
5108        assert!((lipped(0.25).supersonic_body().unwrap().shape_weight - 1.0).abs() < 1e-12);
5109        // The ramp's shape, not just its ends: linear in the rise, as the wake's own fraction
5110        // is. A smoothstep through the same ends would read 0.896 at a rise of 0.3.
5111        for (rise, want) in [(0.3_f64, 0.8_f64), (0.375, 0.5), (0.45, 0.2)] {
5112            let weight = lipped(rise).supersonic_body().unwrap().shape_weight;
5113            assert!(
5114                (weight - want).abs() < 1e-9,
5115                "at a rise of {rise} the wake covers {weight}, not {want}"
5116            );
5117        }
5118        // Just inside the far edge the weight is all but gone; at the edge itself there is no
5119        // run, since a share of shelter under a millionth is not worth a table.
5120        assert!(
5121            lipped(0.49999).supersonic_body().unwrap().shape_weight < 1e-4,
5122            "a hair inside the wake's far edge the method has almost no weight left"
5123        );
5124        assert!(
5125            lipped(0.5).supersonic_body().is_none(),
5126            "at the wake's far edge there is no run"
5127        );
5128        // The rise is not the only way out of the wake: it fades with any tube between the
5129        // boattail and the lip, and the weight follows that too.
5130        let gapped = |gap_m: f64| {
5131            let mut rocket = crate::testing::finned_rocket(4);
5132            rocket.stages[0].components.truncate(3);
5133            rocket.stages[0].components.push(component(
5134                "gap",
5135                body_part(gap_m, 0.022, 0.022),
5136                None,
5137            ));
5138            rocket.stages[0].components.push(component(
5139                "lip",
5140                body_part(0.01, 0.022, 0.022 + 0.5 * 0.17 * 0.010),
5141                None,
5142            ));
5143            let m = model(&rocket);
5144            let weight = m.supersonic_body().map_or(0.0, |t| t.shape_weight);
5145            let f = m.normal_force(&flow(3.0, 4f64.to_radians(), 0.0)).unwrap();
5146            (
5147                weight,
5148                f.coefficient,
5149                f.cp_station_m.unwrap() / m.reference_diameter_m(),
5150            )
5151        };
5152        let (near, far) = (gapped(1e-6), gapped(0.010));
5153        assert!(
5154            near.0 > 0.999 && far.0 == 0.0,
5155            "a tube of the boattail's own drop in diameter carries the lip out of the wake: \
5156             {near:?} to {far:?}"
5157        );
5158        assert!(
5159            (far.2 - near.2 + 1.973).abs() < 0.01 && (far.1 / near.1 - 1.0 + 0.3381).abs() < 5e-4,
5160            "over that tube the force moves {} and the center of pressure {} calibers",
5161            far.1 / near.1 - 1.0,
5162            far.2 - near.2
5163        );
5164        // Where the method is weighed in only partly, a component's station and its own center of
5165        // pressure part company: the station blends stations, the force blends slopes and
5166        // moments, and the two agree only at the ends (issue #106). At half weight the tube's
5167        // station sits 0.114 m (about two calibers) behind its own center of pressure.
5168        let half = lipped(0.375);
5169        let tube = half
5170            .component_normal_force(1, &flow(3.0, 0.0, 0.0))
5171            .unwrap();
5172        let station = half.component_station_m(1, 3.0).unwrap();
5173        assert!(
5174            (station - tube.cp_station_m.unwrap() - 0.1142).abs() < 5e-4,
5175            "the tube's station {station} against its center of pressure {:?}",
5176            tube.cp_station_m
5177        );
5178        assert!(
5179            lipped(0.55).supersonic_body().is_none(),
5180            "past the wake there is no run at all"
5181        );
5182        // And no jump anywhere across the band, at either end or inside it.
5183        for rise in [0.2499_f64, 0.25, 0.3, 0.375, 0.45, 0.4999] {
5184            let (low, high) = (at(rise - 1e-9), at(rise + 1e-9));
5185            assert!(
5186                (high.0 - low.0).abs() <= 1e-7 * low.0.abs().max(1.0)
5187                    && (high.1 - low.1).abs() <= 1e-7 * low.1.abs().max(1.0),
5188                "at a rise of {rise}: {low:?} to {high:?}"
5189            );
5190        }
5191        // The shelter follows the geometry, not the drag buildup's tables: a lip out of the wake
5192        // is refused whatever its shape, including one whose drag curve the buildup has none for
5193        // (a Haack series past C = 1/3; the physics review found this).
5194        for shape in [NoseShape::Conical {}, NoseShape::Haack { parameter: 0.5 }] {
5195            let mut rocket = crate::testing::committed_design("wind-tunnel-arcas-robin-short.json");
5196            let components = &mut rocket.stages[0].components;
5197            let last = components.len() - 1;
5198            let Part::Transition(lip) = &mut components[last].part else {
5199                unreachable!("the committed design ends in its lip")
5200            };
5201            // Raised to 0.60 of the boattail's drop, past the wake's far edge.
5202            lip.aft_radius_m = lip.fore_radius_m + 0.60 * (0.028575 - 0.0166116);
5203            lip.shape = shape;
5204            assert!(
5205                model(&rocket).supersonic_body().is_none(),
5206                "{shape:?} out of the wake"
5207            );
5208        }
5209        // A flare longer than the boattail's drop in diameter grows out of the wake, however
5210        // little it rises.
5211        let mut rocket = finned_rocket(4);
5212        rocket.stages[0].components.truncate(3);
5213        rocket.stages[0].components.push(component(
5214            "long flare",
5215            body_part(1.0, 0.022, 0.0229),
5216            None,
5217        ));
5218        assert!(model(&rocket).supersonic_body().is_none());
5219        // A narrowing part behind the run is a boattail the method hasn't covered, not a lip,
5220        // even where the wake takes its drag: it keeps slender-body theory's share.
5221        let mut rocket = finned_rocket(4);
5222        rocket.stages[0].components.truncate(3);
5223        rocket.stages[0].components.push(component(
5224            "second boattail",
5225            body_part(0.03, 0.0231, 0.021),
5226            None,
5227        ));
5228        let narrowing = model(&rocket);
5229        assert!(narrowing.bodies().last().unwrap().slope_per_rad < 0.0);
5230        assert!(narrowing.supersonic_body().is_none());
5231    }
5232
5233    /// Washington and Pettis's correlation is read no steeper than the angle where the flow
5234    /// separates, 16° (Cubbage, [issue #90](https://github.com/nrdptel/fusionspace-eridanus/issues/90)): a
5235    /// steeper boattail takes the increment of one of the same radii drawn out to 16°. Shallower
5236    /// boattails are untouched, the increment is continuous in the angle, and it never runs away
5237    /// or falls to zero, which would move the center of pressure aft of where anything measured.
5238    #[test]
5239    fn a_separating_boattail_reads_the_correlation_at_its_steepest_measured_angle() {
5240        // Mach 1.5, where the held read and the true reads at 17° and 23° sit on Fig. 5's curve
5241        // (30° and 40° run past its last entry and clamp, but against a held read that does not).
5242        // At Mach 3 every read clamps to the same number and the assertions below would all be
5243        // identities: the test then passes with the hold deleted, inverted or moved.
5244        let mach = 1.5;
5245        let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5246        let Part::NoseCone(ogive) = ogive else {
5247            unreachable!("`nose` builds a nose cone")
5248        };
5249        // The test rocket's boattail redrawn at each angle from the same fore radius, and what the
5250        // method gives a cylinder of the same length in its place.
5251        let kept_pair = |at: f64, half_angle_deg: f64| {
5252            let length_m = (0.027 - 0.022) / half_angle_deg.to_radians().tan();
5253            let mut rocket = finned_rocket(4);
5254            rocket.stages[0].components[2].part = body_part(length_m, 0.027, 0.022);
5255            let model = model(&rocket);
5256            let a_ref = model.reference_area_m2();
5257            let table = model
5258                .supersonic_body()
5259                .unwrap_or_else(|| panic!("a table at {half_angle_deg}°"));
5260            let share = table.share(2, at).expect("the boattail's share").0;
5261            let in_its_place = ShockExpansionBody::new(
5262                &[
5263                    BodySegment::Profile {
5264                        profile: ogive.profile().unwrap(),
5265                    },
5266                    BodySegment::Cylinder {
5267                        length_m: 0.7,
5268                        radius_m: 0.027,
5269                    },
5270                    BodySegment::Cylinder {
5271                        length_m,
5272                        radius_m: 0.027,
5273                    },
5274                ],
5275                DEFAULT_ELEMENTS_PER_CURVE,
5276            )
5277            .unwrap();
5278            let cylinder = in_its_place.segment_slopes(at, a_ref).unwrap()[2].slope_per_rad;
5279            let raw = |l: f64| {
5280                crate::supersonic_boattail::wp_slope(at, 0.027, 0.022, l).unwrap()
5281                    * PI
5282                    * 0.027
5283                    * 0.027
5284                    / a_ref
5285            };
5286            // The increment the rocket flies, over the correlation read at the true angle.
5287            (share - cylinder, raw(length_m))
5288        };
5289        let kept = |half_angle_deg: f64| kept_pair(mach, half_angle_deg);
5290        let kept_at = |at: f64, half_angle_deg: f64| kept_pair(at, half_angle_deg).0;
5291        let at_16 = (0.027 - 0.022) / 16.0_f64.to_radians().tan();
5292        let close = |got: f64, want: f64, what: &str| {
5293            assert!(
5294                (got - want).abs() < 0.02 * want.abs(),
5295                "{what}: {got} against {want}"
5296            );
5297        };
5298        // Shallower than the onset: the correlation as measured, untouched.
5299        for angle in [8.0, 15.0, 16.0] {
5300            let (flown, raw) = kept(angle);
5301            close(flown, raw, "read at the true angle");
5302        }
5303        // Steeper: held at the 16° geometry, the same for every angle past it, never zero, and
5304        // strictly more lift taken off than reading the true angle would give. Past about 45° the
5305        // method no longer covers the body at all and the rocket keeps slender-body theory (a
5306        // switch of its own, issue #87), so the cap is read below that.
5307        // Scaled onto the rocket's reference area, as the flown increment is.
5308        let a_ref = model(&finned_rocket(4)).reference_area_m2();
5309        let at_16_read = crate::supersonic_boattail::wp_slope(mach, 0.027, 0.022, at_16).unwrap()
5310            * PI
5311            * 0.027
5312            * 0.027
5313            / a_ref;
5314        for angle in [17.0, 23.0, 30.0, 40.0] {
5315            let (flown, raw) = kept(angle);
5316            let (held, _) = kept(16.0);
5317            close(flown, held, "held at 16°");
5318            // The cap's own angle, read straight from the correlation at the 16° length.
5319            close(flown, at_16_read, "the correlation at the 16° geometry");
5320            assert!(flown < 0.0, "{angle}°: the boattail still takes lift off");
5321            // The correlation read at the true angle takes off strictly less, which is the
5322            // optimistic side: holding it keeps the center of pressure forward of that.
5323            assert!(flown < raw, "{angle}°: {flown} against {raw} read raw");
5324        }
5325        // What the choice is worth, and which way it runs: the body's center of pressure with the
5326        // increment held at 16°, against the same body with the boattail's increment faded to
5327        // nothing (the other honest limit for separated flow, a cylinder's share alone). Letting
5328        // it fade moves the center of pressure aft, so the rocket reads more stable.
5329        let length_m = (0.027 - 0.022) / 30.0_f64.to_radians().tan();
5330        let mut steep = finned_rocket(4);
5331        steep.stages[0].components[2].part = body_part(length_m, 0.027, 0.022);
5332        steep.stages[0].components.truncate(3);
5333        let steep = model(&steep);
5334        let body_cp_calibers = |at: f64, increment_kept: bool| {
5335            let parts = steep.components(&Flow::axial(at)).unwrap();
5336            let (mut slope, mut moment) = (0.0, 0.0);
5337            for (index, part) in parts.iter().take(steep.bodies().len()).enumerate() {
5338                let mut share = part.normal_force.slope_per_rad;
5339                let station = part.normal_force.cp_station_m.unwrap_or(0.0);
5340                if index == 2 && !increment_kept {
5341                    share -= kept_at(at, 30.0);
5342                }
5343                slope += share;
5344                moment += share * station;
5345            }
5346            moment / slope / steep.reference_diameter_m()
5347        };
5348        // The gap grows as the speed falls, so it is quoted as a range, not one number.
5349        let gaps: Vec<(f64, f64)> = [1.5_f64, 2.0, 3.0, 4.63]
5350            .iter()
5351            .map(|at| {
5352                (
5353                    *at,
5354                    body_cp_calibers(*at, false) - body_cp_calibers(*at, true),
5355                )
5356            })
5357            .collect();
5358        for (at, gap) in &gaps {
5359            assert!(
5360                *gap > 0.6,
5361                "Mach {at}: the fading rule sits {gap} calibers aft"
5362            );
5363        }
5364        // Every value the guide's table quotes, pinned.
5365        for (at, want) in [(1.5, 1.35), (2.0, 0.91), (3.0, 0.75), (4.63, 0.67)] {
5366            let got = gaps
5367                .iter()
5368                .find(|(m, _)| (m - at).abs() < 1e-9)
5369                .expect("a measured gap")
5370                .1;
5371            assert!(
5372                (got - want).abs() < 0.02,
5373                "Mach {at}: the gap is {got} calibers, the guide says {want}"
5374            );
5375        }
5376        // Continuous in the angle, at the cap and either side of it. Below the cap the read
5377        // moves with the angle, so this is not zero: over ±1e-6 of a degree it is a few times
5378        // 1e-8, where a switch at the cap would show as the 7e-3 that separates the held and raw
5379        // reads just past 16°.
5380        for angle in [15.9_f64, 16.0, 16.1] {
5381            let (below, above) = (kept(angle - 1e-6).0, kept(angle + 1e-6).0);
5382            assert!((above - below).abs() < 1e-6, "{angle}°: {below} to {above}");
5383        }
5384        assert!((at_16 - (0.027 - 0.022) / 16.0_f64.to_radians().tan()).abs() < 1e-15);
5385    }
5386
5387    /// Holding the correlation at 16° reads it at a longer boattail, which walks left along
5388    /// Fig. 5 toward the peak near Mach 1 its points come from. That branch passes Munk's
5389    /// slender-body line, so the extra the holding takes off stops at potential flow. The read at
5390    /// the boattail's true angle is never clipped: that is the measurement, wherever it sits.
5391    #[test]
5392    fn holding_the_correlation_stops_at_potential_flow() {
5393        // A 30° boattail to a twentieth of the radius at Mach 1.42: held −2.077, true −0.981
5394        // and potential flow −1.995 per radian on the boattail's own area, so the bound bites.
5395        // The window is narrow (this shape's table starts at Mach 1.3906 and the held read
5396        // stops passing potential flow at 1.4509), so the Mach is checked against the join.
5397        let (fore_radius_m, aft_radius_m, mach) = (0.027_f64, 0.05 * 0.027_f64, 1.42_f64);
5398        let slender = 2.0 * ((aft_radius_m / fore_radius_m).powi(2) - 1.0);
5399        let length_m = (fore_radius_m - aft_radius_m) / 30.0_f64.to_radians().tan();
5400        let mut rocket = finned_rocket(4);
5401        rocket.stages[0].components[2].part = body_part(length_m, fore_radius_m, aft_radius_m);
5402        rocket.stages[0].components[3].part = body_part(0.3, aft_radius_m, aft_radius_m);
5403        let steep = model(&rocket);
5404        let a_ref = steep.reference_area_m2();
5405        let per_boattail_area = PI * fore_radius_m * fore_radius_m / a_ref;
5406        let table = steep.supersonic_body().expect("the method covers it");
5407        // Inside the table: below its start `share` clamps to the lead row, and the numbers
5408        // above would belong to a Mach number the assertions never touch.
5409        assert!(
5410            mach > table.join_start_mach,
5411            "Mach {mach} is below the table's start, {}",
5412            table.join_start_mach
5413        );
5414        let cylinder = ShockExpansionBody::new(
5415            &[
5416                BodySegment::Profile {
5417                    profile: match nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027) {
5418                        Part::NoseCone(ogive) => ogive.profile().unwrap(),
5419                        _ => unreachable!("`nose` builds a nose cone"),
5420                    },
5421                },
5422                BodySegment::Cylinder {
5423                    length_m: 0.7,
5424                    radius_m: fore_radius_m,
5425                },
5426                BodySegment::Cylinder {
5427                    length_m,
5428                    radius_m: fore_radius_m,
5429                },
5430            ],
5431            DEFAULT_ELEMENTS_PER_CURVE,
5432        )
5433        .unwrap()
5434        .segment_slopes(mach, a_ref)
5435        .unwrap()[2]
5436            .slope_per_rad;
5437        let flown = table.share(2, mach).expect("the boattail's share").0 - cylinder;
5438        // It flies potential flow's value exactly, not the held read that would pass it.
5439        assert!(
5440            (flown / per_boattail_area - slender).abs() < 2e-3,
5441            "{} against potential flow's {slender}",
5442            flown / per_boattail_area
5443        );
5444        let held = crate::supersonic_boattail::wp_slope(
5445            mach,
5446            fore_radius_m,
5447            aft_radius_m,
5448            (fore_radius_m - aft_radius_m) / SEPARATION_ONSET_RAD.tan(),
5449        )
5450        .unwrap();
5451        assert!(
5452            held < slender - 0.05,
5453            "the held read {held} must pass the bound's {slender} to pin it"
5454        );
5455        // And a boattail inside the measured angles keeps its own read, even where that read is
5456        // itself past potential flow: the bound belongs to the holding, not to the measurement.
5457        let gentle_m = (fore_radius_m - 0.6 * fore_radius_m) / 4.0_f64.to_radians().tan();
5458        let gentle =
5459            crate::supersonic_boattail::wp_slope(1.5, fore_radius_m, 0.6 * fore_radius_m, gentle_m)
5460                .unwrap();
5461        let gentle_slender = 2.0 * (0.6_f64.powi(2) - 1.0);
5462        assert!(
5463            gentle < gentle_slender,
5464            "the 4° read {gentle} should pass {gentle_slender}"
5465        );
5466        let mut gentle_rocket = finned_rocket(4);
5467        gentle_rocket.stages[0].components[2].part =
5468            body_part(gentle_m, fore_radius_m, 0.6 * fore_radius_m);
5469        gentle_rocket.stages[0].components[3].part =
5470            body_part(0.3, 0.6 * fore_radius_m, 0.6 * fore_radius_m);
5471        let gentle_model = model(&gentle_rocket);
5472        let gentle_table = gentle_model.supersonic_body().expect("a table");
5473        let gentle_cylinder = ShockExpansionBody::new(
5474            &[
5475                BodySegment::Profile {
5476                    profile: match nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027) {
5477                        Part::NoseCone(ogive) => ogive.profile().unwrap(),
5478                        _ => unreachable!("`nose` builds a nose cone"),
5479                    },
5480                },
5481                BodySegment::Cylinder {
5482                    length_m: 0.7,
5483                    radius_m: fore_radius_m,
5484                },
5485                BodySegment::Cylinder {
5486                    length_m: gentle_m,
5487                    radius_m: fore_radius_m,
5488                },
5489            ],
5490            DEFAULT_ELEMENTS_PER_CURVE,
5491        )
5492        .unwrap()
5493        .segment_slopes(1.5, gentle_model.reference_area_m2())
5494        .unwrap()[2]
5495            .slope_per_rad;
5496        let gentle_flown = gentle_table.share(2, 1.5).expect("the share").0 - gentle_cylinder;
5497        let gentle_area = PI * fore_radius_m * fore_radius_m / gentle_model.reference_area_m2();
5498        assert!(
5499            (gentle_flown / gentle_area - gentle).abs() < 2e-3,
5500            "the 4° boattail flies {} and its correlation reads {gentle}",
5501            gentle_flown / gentle_area
5502        );
5503    }
5504
5505    /// How far the potential-flow bound reaches, read back out of the table rather than
5506    /// recomputed. Over the boattails swept below (16° to 53.6°, narrowing to between a
5507    /// thousandth and three tenths of the fore radius), this pins three things: at the table's
5508    /// rows a boattail never takes off more than potential flow, **except** where its own read
5509    /// already passes it, since the bound never clips that; there, the table carries the
5510    /// correlation as published; and the most the bound moves a **printed** coefficient, after
5511    /// the join's weight. Deleting the bound fails this, and so does clipping the floor.
5512    #[test]
5513    fn what_the_potential_flow_bound_reaches() {
5514        let fore_radius_m = 0.027_f64;
5515        let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5516        let Part::NoseCone(ogive) = ogive else {
5517            unreachable!("`nose` builds a nose cone")
5518        };
5519        let mut worst = (0.0_f64, 0.0_f64, 0.0_f64, 0.0_f64);
5520        let mut steepest_tabled = 0.0_f64;
5521        let mut floor_angles: Vec<f64> = Vec::new();
5522        for angle_deg in [16.0_f64, 16.5, 17.0, 17.25, 17.5, 30.0, 53.0, 53.5, 53.6] {
5523            for ratio in [0.001_f64, 0.02, 0.25, 0.3] {
5524                let aft_radius_m = ratio * fore_radius_m;
5525                let drop_m = fore_radius_m - aft_radius_m;
5526                let length_m = drop_m / angle_deg.to_radians().tan();
5527                let held_length_m = drop_m / SEPARATION_ONSET_RAD.tan();
5528                let ceiling = 2.0 * (ratio * ratio - 1.0);
5529                let read = |mach: f64, length: f64| {
5530                    crate::supersonic_boattail::wp_slope(mach, fore_radius_m, aft_radius_m, length)
5531                        .unwrap()
5532                };
5533                // Skip shapes the bound cannot touch at any Mach the table covers: building a
5534                // supersonic table is the expensive part of this sweep.
5535                if read(1.2, held_length_m) >= ceiling {
5536                    continue;
5537                }
5538                let mut rocket = finned_rocket(4);
5539                rocket.stages[0].components[2].part =
5540                    body_part(length_m, fore_radius_m, aft_radius_m);
5541                rocket.stages[0].components[3].part = body_part(0.3, aft_radius_m, aft_radius_m);
5542                let flown = model(&rocket);
5543                let Some(table) = flown.supersonic_body() else {
5544                    continue;
5545                };
5546                steepest_tabled = steepest_tabled.max(angle_deg);
5547                let a_ref = flown.reference_area_m2();
5548                let per_area = PI * fore_radius_m * fore_radius_m / a_ref;
5549                // The method's share for a cylinder of the boattail's length in its place, which
5550                // the flown share is the increment on top of.
5551                let cylinder_body = ShockExpansionBody::new(
5552                    &[
5553                        BodySegment::Profile {
5554                            profile: ogive.profile().unwrap(),
5555                        },
5556                        BodySegment::Cylinder {
5557                            length_m: 0.7,
5558                            radius_m: fore_radius_m,
5559                        },
5560                        BodySegment::Cylinder {
5561                            length_m,
5562                            radius_m: fore_radius_m,
5563                        },
5564                    ],
5565                    DEFAULT_ELEMENTS_PER_CURVE,
5566                )
5567                .unwrap();
5568                // The shares are computed at the table's rows: its lead row at the join, then
5569                // every 0.05 Mach. Between rows the table interpolates, so a printed value can
5570                // sit a little past the ceiling beside a row on the floor branch below; the
5571                // guarantee belongs to the rows.
5572                let mut rows = vec![table.join_start_mach];
5573                let mut step = (table.join_start_mach * SUPERSONIC_STEPS_PER_MACH).ceil();
5574                while step / SUPERSONIC_STEPS_PER_MACH <= 1.55 {
5575                    rows.push(step / SUPERSONIC_STEPS_PER_MACH);
5576                    step += 1.0;
5577                }
5578                for mach in rows {
5579                    let Some((share, _)) = table.share(2, mach) else {
5580                        break;
5581                    };
5582                    let cylinder =
5583                        cylinder_body.segment_slopes(mach, a_ref).unwrap()[2].slope_per_rad;
5584                    let increment = (share - cylinder) / per_area;
5585                    if read(mach, length_m) >= ceiling {
5586                        // The usual case: the boattail's own read is inside potential flow, so
5587                        // the bound is what stops the hold. Read out of the table, the share a
5588                        // rocket flies never passes potential flow.
5589                        assert!(
5590                            increment >= ceiling - 1e-12,
5591                            "{angle_deg}° to {ratio} of the radius at Mach {mach}: the boattail \
5592                             takes {increment} off, past potential flow's {ceiling}"
5593                        );
5594                    } else {
5595                        // The floor: the boattail's own read already passes potential flow, and
5596                        // that read is never clipped, so the hold does nothing here.
5597                        assert!(
5598                            increment <= ceiling,
5599                            "{angle_deg}° to {ratio} at Mach {mach}: {increment} against {ceiling}"
5600                        );
5601                        // The boattail's own read, as published: the bound never clips it, so
5602                        // the table carries the correlation itself here.
5603                        let published = read(mach, length_m);
5604                        assert!(
5605                            (increment - published).abs() < 1e-9,
5606                            "{angle_deg}° to {ratio} at Mach {mach}: {increment} against the \
5607                             correlation's own {published}"
5608                        );
5609                        if !floor_angles.contains(&angle_deg) {
5610                            floor_angles.push(angle_deg);
5611                        }
5612                    }
5613                    // And how much of the holding that costs, against the unbounded read.
5614                    let moved = (increment - read(mach, held_length_m)).abs()
5615                        * per_area
5616                        * table.weight(mach);
5617                    if moved > worst.0 {
5618                        worst = (moved, angle_deg, ratio, mach);
5619                    }
5620                }
5621            }
5622        }
5623        // The floor is a sliver just above the hold's own angle, on the angles swept: the
5624        // condition is that the boattail's own read passes the curve's Munk crossing, so it
5625        // closes as the angle or the Mach number rises.
5626        assert_eq!(
5627            floor_angles,
5628            [16.0, 16.5, 17.0, 17.25],
5629            "the swept angles where a boattail's own read already passes potential flow"
5630        );
5631        // The steepest shape this sweep both tables and can bind: the method refuses steeper
5632        // bodies, at an angle that depends on how far the boattail narrows.
5633        assert!(
5634            (steepest_tabled - 53.5).abs() < 1e-12,
5635            "the steepest boattail swept that the method tables is {steepest_tabled}°"
5636        );
5637        assert!(
5638            (worst.0 - 0.060).abs() < 5e-4,
5639            "the bound moves a printed coefficient by at most {:.4} per rad, at {}° to {} of the \
5640             radius at Mach {:.3}",
5641            worst.0,
5642            worst.1,
5643            worst.2,
5644            worst.3
5645        );
5646    }
5647
5648    /// Footnote 8's size, by hand, on a boattail **and the tube behind it**
5649    /// ([issue #90](https://github.com/nrdptel/fusionspace-eridanus/issues/90)). On each straight element the
5650    /// method's loading is `Λ(x) = (1 − e^(−η)) Λ_c + e^(−η) Λ₂`, `x` axial from its corner, and
5651    /// `C_Nα = (2π/A_ref) ∫ Λ r dx` over it (TN 3527 eqs. 8, 9, 19). Footnote 8 gives a boattail
5652    /// element the free stream's pressure and a tangent cone of 2 per radian (p. 12), checked
5653    /// here against hard-coded values; the tube behind relaxes from the boattail's loading toward
5654    /// `Λ_c = 0`, so its share is set by the decay rate alone.
5655    ///
5656    /// What this pins: the integration, the footnote's two tangent-cone terms, and that the two
5657    /// segments' shares follow from the reported flow. What it does not pin: the decay rate `η`
5658    /// itself, which comes from eq. 9 and is read from the method here.
5659    #[test]
5660    fn footnote_eights_boattail_share_by_hand() {
5661        let a_ref = PI * 0.027 * 0.027;
5662        let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5663        let Part::NoseCone(ogive) = ogive else {
5664            unreachable!("`nose` builds a nose cone")
5665        };
5666        let (length_m, fore_radius_m, aft_radius_m) = (0.05, 0.027, 0.022);
5667        const TUBE_LENGTH_M: f64 = 0.2;
5668        let body = ShockExpansionBody::new(
5669            &[
5670                BodySegment::Profile {
5671                    profile: ogive.profile().unwrap(),
5672                },
5673                BodySegment::Cylinder {
5674                    length_m: 0.7,
5675                    radius_m: 0.027,
5676                },
5677                BodySegment::Profile {
5678                    profile: hpr_design::Profile::transition(
5679                        NoseShape::Conical {},
5680                        length_m,
5681                        fore_radius_m,
5682                        aft_radius_m,
5683                        false,
5684                    )
5685                    .unwrap(),
5686                },
5687                BodySegment::Cylinder {
5688                    length_m: TUBE_LENGTH_M,
5689                    radius_m: aft_radius_m,
5690                },
5691            ],
5692            DEFAULT_ELEMENTS_PER_CURVE,
5693        )
5694        .unwrap();
5695        let mach = 2.0;
5696        let shares = body.segment_slopes(mach, a_ref).unwrap();
5697        // The boattail is one straight element: the corner at its fore end, then a cone of
5698        // half-angle −δ to its aft end.
5699        let flows = body.element_flows(mach).unwrap();
5700        let boattail = flows
5701            .iter()
5702            .rev()
5703            .nth(1)
5704            .copied()
5705            .expect("the boattail's element");
5706        let (load, decay) = (boattail.loading_per_rad, boattail.decay_per_m);
5707        // Eq. 19's `r` at the corner is the boattail's fore radius.
5708        assert!((boattail.corner_radius_m - fore_radius_m).abs() < 1e-12);
5709        // Footnote 8 gives a boattail element the free stream's pressure and a tangent cone of 2
5710        // per radian, so its loading relaxes toward `tan δ · 2`.
5711        let delta = ((aft_radius_m - fore_radius_m) / length_m).atan();
5712        let cone_load = delta.tan() * 2.0;
5713        assert!((boattail.tangent_cone_loading_per_rad - cone_load).abs() < 1e-12);
5714        assert!((boattail.tangent_cone_pressure_ratio - 1.0).abs() < 1e-12);
5715        // C_Nα = (2π/A_ref) ∫ Λ(x) r(x) dx over a segment, by Simpson's rule on 4001 points.
5716        let integrate = |span_m: f64, fore_r: f64, aft_r: f64, load: f64, cone: f64, decay: f64| {
5717            let steps = 4000;
5718            let mut sum = 0.0;
5719            for i in 0..=steps {
5720                let t = f64::from(i) / f64::from(steps);
5721                let x = t * span_m;
5722                let r = fore_r + (aft_r - fore_r) * t;
5723                let e = (-decay * x).exp();
5724                let lambda = (1.0 - e) * cone + e * load;
5725                let weight = if i == 0 || i == steps {
5726                    1.0
5727                } else if i % 2 == 1 {
5728                    4.0
5729                } else {
5730                    2.0
5731                };
5732                sum += weight * lambda * r;
5733            }
5734            2.0 * PI * (sum * span_m / (3.0 * f64::from(steps))) / a_ref
5735        };
5736        let by_hand = integrate(
5737            length_m,
5738            fore_radius_m,
5739            aft_radius_m,
5740            load,
5741            cone_load,
5742            decay,
5743        );
5744        assert!(
5745            (shares[2].slope_per_rad - by_hand).abs() < 1e-6,
5746            "{} against {by_hand}",
5747            shares[2].slope_per_rad
5748        );
5749        // The tube behind it, which issue #90 asks for too: a cylinder's tangent cone carries no
5750        // loading, so the decay alone takes its share from the boattail's exit loading to zero.
5751        let tube = flows.last().expect("the tube's element");
5752        assert!(tube.angle_rad.abs() < 1e-12 && tube.tangent_cone_loading_per_rad.abs() < 1e-12);
5753        let tube_by_hand = integrate(
5754            TUBE_LENGTH_M,
5755            aft_radius_m,
5756            aft_radius_m,
5757            tube.loading_per_rad,
5758            0.0,
5759            tube.decay_per_m,
5760        );
5761        assert!(
5762            (shares[3].slope_per_rad - tube_by_hand).abs() < 1e-6,
5763            "the tube: {} against {tube_by_hand}",
5764            shares[3].slope_per_rad
5765        );
5766        // The tube carries the larger part of the pair, so the decay sets most of the answer.
5767        assert!(
5768            tube_by_hand < by_hand && tube_by_hand < 0.0,
5769            "the tube's {tube_by_hand} against the boattail's {by_hand}"
5770        );
5771        // And its size: footnote 8 takes far less lift off than slender-body theory's
5772        // 2 (A_aft − A_fore)/A_ref.
5773        let slender = 2.0 * (aft_radius_m.powi(2) - fore_radius_m.powi(2)) / (0.027 * 0.027);
5774        assert!(
5775            by_hand < 0.0 && by_hand / slender < 0.2,
5776            "{by_hand} against slender-body theory's {slender}"
5777        );
5778    }
5779
5780    /// Washington and Pettis's boattail: the method's share for a cylinder of the boattail's
5781    /// length and fore radius in its place, plus the measured increment at its center of
5782    /// pressure; footnote 8's is the method's own segment share.
5783    #[test]
5784    fn the_boattail_takes_washington_and_pettis_increment() {
5785        let layout = finned_rocket(4).layout().unwrap();
5786        let current = AeroModel::new(&layout).unwrap();
5787        let before = AeroModel::with_body_model(&layout, BodyModel::BEFORE_M1_8E6).unwrap();
5788        let a_ref = current.reference_area_m2();
5789        let ogive = nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, 0.027);
5790        let Part::NoseCone(ogive) = ogive else {
5791            unreachable!("`nose` builds a nose cone")
5792        };
5793        let segments = |last: BodySegment| {
5794            [
5795                BodySegment::Profile {
5796                    profile: ogive.profile().unwrap(),
5797                },
5798                BodySegment::Cylinder {
5799                    length_m: 0.7,
5800                    radius_m: 0.027,
5801                },
5802                last,
5803            ]
5804        };
5805        let in_its_place = ShockExpansionBody::new(
5806            &segments(BodySegment::Cylinder {
5807                length_m: 0.05,
5808                radius_m: 0.027,
5809            }),
5810            DEFAULT_ELEMENTS_PER_CURVE,
5811        )
5812        .unwrap();
5813        let rocket = finned_rocket(4);
5814        let Part::Transition(tail) = &rocket.stages[0].components[2].part else {
5815            unreachable!("the test rocket's third part is its boattail")
5816        };
5817        let with_boattail = ShockExpansionBody::new(
5818            &segments(BodySegment::Profile {
5819                profile: tail.profile().unwrap(),
5820            }),
5821            DEFAULT_ELEMENTS_PER_CURVE,
5822        )
5823        .unwrap();
5824        for mach in [2.0, 3.0, 4.5] {
5825            let cylinder = in_its_place.segment_slopes(mach, a_ref).unwrap()[2];
5826            let increment = crate::supersonic_boattail::wp_slope(mach, 0.027, 0.022, 0.05).unwrap()
5827                * PI
5828                * 0.027
5829                * 0.027
5830                / a_ref;
5831            let center = 0.25 + 0.7 + wp_center_fraction(mach) * 0.05;
5832            let (slope, moment) = current.supersonic_body().unwrap().share(2, mach).unwrap();
5833            close(
5834                slope,
5835                cylinder.slope_per_rad + increment,
5836                1e-12,
5837                "W&P slope",
5838            );
5839            close(
5840                moment,
5841                cylinder.moment_slope_m + increment * center,
5842                1e-12,
5843                "W&P moment",
5844            );
5845            // The increment is most of it: the nose's lift has decayed along the cylinder.
5846            assert!(increment < 0.0 && cylinder.slope_per_rad.abs() < 0.1 * increment.abs());
5847            let footnote_8 = with_boattail.segment_slopes(mach, a_ref).unwrap()[2];
5848            let (old, _) = before.supersonic_body().unwrap().share(2, mach).unwrap();
5849            close(old, footnote_8.slope_per_rad, 1e-12, "footnote 8");
5850            // The measured increment takes off more lift than footnote 8, less than
5851            // slender-body theory's -2[1 - (0.022/0.027)^2].
5852            let slender = -2.0 * (1.0 - (0.022_f64 / 0.027).powi(2));
5853            assert!(slender < slope && slope < old, "Mach {mach}: {slope} {old}");
5854        }
5855    }
5856
5857    /// Two boattails in one run, the second last: each takes the method's share for a cylinder
5858    /// of its length and fore radius in its place plus its own Washington and Pettis increment,
5859    /// and the tube between them keeps the method's share, marched through the first boattail by
5860    /// footnote 8. The nose and first tube are the method's either way.
5861    #[test]
5862    fn two_boattails_each_take_their_own_increment() {
5863        let (l_n, l_1, l_b1, l_2, l_b2) = (0.25, 0.4, 0.05, 0.3, 0.04);
5864        let (r_0, r_1, r_2) = (0.027, 0.024, 0.02);
5865        let rocket = one_stage(
5866            vec![
5867                component(
5868                    "nose",
5869                    nose(NoseShape::Ogive { radius_ratio: 1.0 }, l_n, r_0),
5870                    None,
5871                ),
5872                component("tube", body_part(l_1, r_0, r_0), None),
5873                component("boattail", body_part(l_b1, r_0, r_1), None),
5874                component("waist", body_part(l_2, r_1, r_1), None),
5875                component("tail", body_part(l_b2, r_1, r_2), None),
5876            ],
5877            ReferenceDiameter::Maximum {},
5878        );
5879        let model = AeroModel::new(&rocket.layout().unwrap()).unwrap();
5880        let before =
5881            AeroModel::with_body_model(&rocket.layout().unwrap(), BodyModel::BEFORE_M1_8E6)
5882                .unwrap();
5883        let table = model.supersonic_body().unwrap();
5884        assert_eq!(table.covered, 5);
5885        let a_ref = model.reference_area_m2();
5886        let profile = |part: &Part| match part {
5887            Part::NoseCone(n) => n.profile().unwrap(),
5888            Part::Transition(t) => t.profile().unwrap(),
5889            _ => unreachable!("the test's profiled parts are a nose and transitions"),
5890        };
5891        let parts: Vec<Part> = rocket.stages[0]
5892            .components
5893            .iter()
5894            .map(|c| c.part.clone())
5895            .collect();
5896        let cylinder = |length_m, radius_m| BodySegment::Cylinder { length_m, radius_m };
5897        let profiled = |i: usize| BodySegment::Profile {
5898            profile: profile(&parts[i]),
5899        };
5900        let body = |segments: &[BodySegment]| {
5901            ShockExpansionBody::new(segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap()
5902        };
5903        let whole = body(&[
5904            profiled(0),
5905            cylinder(l_1, r_0),
5906            profiled(2),
5907            cylinder(l_2, r_1),
5908            profiled(4),
5909        ]);
5910        let first_in_place = body(&[profiled(0), cylinder(l_1, r_0), cylinder(l_b1, r_0)]);
5911        let second_in_place = body(&[
5912            profiled(0),
5913            cylinder(l_1, r_0),
5914            profiled(2),
5915            cylinder(l_2, r_1),
5916            cylinder(l_b2, r_1),
5917        ]);
5918        let increment = |mach: f64, fore: f64, aft: f64, length: f64| {
5919            crate::supersonic_boattail::wp_slope(mach, fore, aft, length).unwrap()
5920                * PI
5921                * fore
5922                * fore
5923                / a_ref
5924        };
5925        for mach in [2.0, 3.5] {
5926            let method = whole.segment_slopes(mach, a_ref).unwrap();
5927            let share = |i| table.share(i, mach).unwrap().0;
5928            for i in [0, 1, 3] {
5929                close(
5930                    share(i),
5931                    method[i].slope_per_rad,
5932                    1e-12,
5933                    "the method's share",
5934                );
5935            }
5936            let first = first_in_place.segment_slopes(mach, a_ref).unwrap()[2].slope_per_rad
5937                + increment(mach, r_0, r_1, l_b1);
5938            let second = second_in_place.segment_slopes(mach, a_ref).unwrap()[4].slope_per_rad
5939                + increment(mach, r_1, r_2, l_b2);
5940            close(share(2), first, 1e-12, "first boattail");
5941            close(share(4), second, 1e-12, "second boattail");
5942            // Footnote 8 is the method's own share for both.
5943            let old = before.supersonic_body().unwrap();
5944            close(
5945                old.share(2, mach).unwrap().0,
5946                method[2].slope_per_rad,
5947                1e-12,
5948                "fn 8",
5949            );
5950            close(
5951                old.share(4, mach).unwrap().0,
5952                method[4].slope_per_rad,
5953                1e-12,
5954                "fn 8",
5955            );
5956            assert!(share(2) < method[2].slope_per_rad && share(4) < method[4].slope_per_rad);
5957        }
5958    }
5959
5960    #[test]
5961    fn a_boattailed_body_flies_the_method_without_a_jump() {
5962        // M1.8e4: the finned rocket's 5.7° boattail and the tail behind it join the covered run;
5963        // since M1.8e6 the boattail takes Washington and Pettis's share, which takes lift off.
5964        let model = model(&finned_rocket(4));
5965        let join = model.supersonic_body().unwrap();
5966        assert_eq!(join.covered, 4);
5967        let start = join.join_start_mach;
5968        for mach in [
5969            start,
5970            start + SUPERSONIC_JOIN_WIDTH_MACH,
5971            1.35,
5972            2.0,
5973            2.05,
5974            3.0,
5975            4.63,
5976            4.95,
5977            4.999,
5978        ] {
5979            no_jump(&model, mach);
5980        }
5981        let (low, high) = (body_values(&model, 1.0), body_values(&model, 2.0));
5982        let (boattail, share) = (&model.bodies()[2], join.share(2, 2.0).unwrap());
5983        assert!(boattail.slope_per_rad < 0.0 && share.0 < 0.0, "{share:?}");
5984        // The join's weight is 1 at Mach 2; the rest is the join's rounding.
5985        assert!(
5986            (high[2][0] - share.0).abs() <= 1e-12 * share.0.abs(),
5987            "{share:?}"
5988        );
5989        // Its station stays slender-body theory's, on its own segment, at every Mach number;
5990        // the tail's, behind it, is its body-lift station, while its share is negative too.
5991        assert_eq!(low[2][2], high[2][2]);
5992        assert!((0.95..=1.0).contains(&high[2][2]), "{:?}", high[2]);
5993        assert!(high[3][0] < 0.0, "{:?}", high[3]);
5994        for mach in [1.2, 1.3, 1.5, 3.0, 4.999] {
5995            let at = body_values(&model, mach);
5996            assert_eq!((at[2][2], at[3][2]), (low[2][2], low[3][2]), "Mach {mach}");
5997        }
5998        assert!((1.0..=1.3).contains(&low[3][2]), "{:?}", low[3]);
5999        // The cylinder behind the nose carries lift past the join, as on a straight body.
6000        assert_eq!(low[1][0], 0.0);
6001        assert!(high[1][0] > 0.1, "{:?}", high[1]);
6002    }
6003
6004    #[test]
6005    fn a_blunter_cone_joins_where_the_method_starts_to_hold() {
6006        // A 20° cone's shock detaches, or its surface flow turns subsonic, above Mach 1.2, so its
6007        // join starts at the table's first row and still doesn't jump.
6008        let mut rocket = straight_rocket();
6009        let length = 0.027 / 20.0_f64.to_radians().tan();
6010        rocket.stages[0].components[0].part = nose(NoseShape::Conical {}, length, 0.027);
6011        let model = model(&rocket);
6012        let join = model.supersonic_body().unwrap();
6013        let start = join.join_start_mach;
6014        assert!(start > SUPERSONIC_JOIN_START_MACH, "{start}");
6015        for mach in [start, start + SUPERSONIC_JOIN_WIDTH_MACH, start + 0.5] {
6016            no_jump(&model, mach);
6017        }
6018        // Below its join the terms are slender-body theory's.
6019        assert_eq!(body_values(&model, start), body_values(&model, 0.5));
6020    }
6021
6022    #[test]
6023    fn the_joins_start_moves_with_the_nose_not_in_steps() {
6024        // Issue #87: the start used to snap to the table's 0.05 grid in Mach, so a steeper cone
6025        // moved it in steps. It now sits where the method starts to hold.
6026        let start_at = |degrees: f64| {
6027            let mut rocket = straight_rocket();
6028            let length = 0.027 / degrees.to_radians().tan();
6029            rocket.stages[0].components[0].part = nose(NoseShape::Conical {}, length, 0.027);
6030            let model = model(&rocket);
6031            let start = model.supersonic_body().unwrap().join_start_mach;
6032            (model, start)
6033        };
6034        let (model, start) = start_at(20.0);
6035        let grid = start * SUPERSONIC_STEPS_PER_MACH;
6036        assert!((grid - grid.round()).abs() > 1e-3, "on the grid: {start}");
6037        // Nothing jumps at the start, at the first even row after it, or across the join.
6038        let first_row = grid.ceil() / SUPERSONIC_STEPS_PER_MACH;
6039        for mach in [start, first_row, start + SUPERSONIC_JOIN_WIDTH_MACH] {
6040            no_jump(&model, mach);
6041        }
6042        assert_eq!(body_values(&model, start), body_values(&model, 0.5));
6043        // The start the aerodynamics page quotes, found by the method, not on the grid (1.35).
6044        assert!((start - 1.341910).abs() < 1e-6, "{start}");
6045        // The lead row is the method's own run there, where the cylinder's share climbs from zero
6046        // like the root of the distance in Mach (0.41 per radian at the first even row), not a
6047        // copy of that row. A start exact to the last bit leaves about 1e-7; 24 halvings of the
6048        // 0.05 step left 2.2e-5 to 2.5e-4, a sawtooth as the nose changed (issue #87).
6049        let join = model.supersonic_body().unwrap();
6050        let (lead, row) = (
6051            join.share(1, start).unwrap(),
6052            join.share(1, first_row).unwrap(),
6053        );
6054        assert!(lead.0 < 1e-5 && row.0 > 0.3, "{lead:?} against {row:?}");
6055        // A millionth of a degree moves the start by 2.7e-8.
6056        let (_, nudged) = start_at(20.0 + 1e-6);
6057        assert!((nudged - start).abs() < 1e-7, "{start} to {nudged}");
6058        // Steeper cones start later, each a little: no two share a grid row's Mach.
6059        let starts: Vec<f64> = [20.0, 20.1, 20.2, 20.3, 20.4, 20.5]
6060            .into_iter()
6061            .map(|degrees| start_at(degrees).1)
6062            .collect();
6063        assert!((starts[5] - 1.355500).abs() < 1e-6, "{starts:?}");
6064        for pair in starts.windows(2) {
6065            assert!(pair[1] > pair[0] && pair[1] - pair[0] < 0.02, "{starts:?}");
6066        }
6067    }
6068
6069    #[test]
6070    fn below_the_join_the_bodies_keep_slender_body_terms() {
6071        let model = model(&straight_rocket());
6072        let slender: Vec<[f64; 3]> = model
6073            .bodies()
6074            .iter()
6075            .enumerate()
6076            .map(|(index, body)| {
6077                [
6078                    body.slope_per_rad,
6079                    body.moment_slope_m,
6080                    model.component_station_m(index, 0.0).unwrap(),
6081                ]
6082            })
6083            .collect();
6084        for mach in [0.0, 0.5, 0.99, 1.1, SUPERSONIC_JOIN_START_MACH] {
6085            let got = body_values(&model, mach);
6086            for (index, (g, want)) in got.iter().zip(&slender).enumerate() {
6087                assert_eq!(g[0], want[0], "body {index} at Mach {mach}");
6088                assert_eq!(g[2], want[2], "body {index} at Mach {mach}");
6089                if want[0] != 0.0 {
6090                    close(g[1], want[1], 1e-14, "moment");
6091                }
6092            }
6093        }
6094    }
6095
6096    #[test]
6097    fn past_the_join_the_covered_bodies_take_the_method() {
6098        let model = model(&straight_rocket());
6099        let area = model.reference_area_m2();
6100        let body = straight_rocket_body();
6101        let join_end = SUPERSONIC_JOIN_START_MACH + SUPERSONIC_JOIN_WIDTH_MACH;
6102        // On the table's rows, the method itself; between them, within interpolation.
6103        for (mach, rel) in [
6104            (1.5, 1e-12),
6105            (2.0, 1e-12),
6106            (3.0, 1e-12),
6107            (4.95, 1e-12),
6108            (2.96, 1e-3),
6109        ] {
6110            assert!(mach >= join_end);
6111            let want = body.slope(mach, area).unwrap();
6112            let values = body_values(&model, mach);
6113            let slope: f64 = values.iter().map(|v| v[0]).sum();
6114            let moment: f64 = values.iter().map(|v| v[1]).sum();
6115            close(slope, want.slope_per_rad, rel, "slope");
6116            close(
6117                moment / slope,
6118                want.center_of_pressure_m,
6119                rel,
6120                "center of pressure",
6121            );
6122            // Each covered body's station is its share's center of pressure, on its segment.
6123            let bounds = [(0.0, 0.25), (0.25, 0.95), (0.95, 1.0), (1.0, 1.3)];
6124            for (v, (fore, aft)) in values.iter().zip(bounds) {
6125                assert!(v[2] > fore && v[2] < aft, "{v:?} not in {fore} to {aft}");
6126            }
6127        }
6128    }
6129
6130    /// A nose, a tube, a conical flare of `flare_deg`, a tail tube and four fins: the shape
6131    /// M1.8e17 flies through the method.
6132    fn flared_rocket(flare_deg: f64) -> hpr_design::Rocket {
6133        let (fore_r, flare_l) = (0.027, 0.3);
6134        let aft_r = fore_r + flare_l * flare_deg.to_radians().tan();
6135        let mut tail = component("tail", body_part(0.2, aft_r, aft_r), None);
6136        tail.children = vec![component(
6137            "fins",
6138            fin_set(
6139                4,
6140                FinPlanform::Trapezoidal {
6141                    root_chord_m: 0.12,
6142                    tip_chord_m: 0.05,
6143                    span_m: 0.06,
6144                    sweep_m: 0.07,
6145                },
6146            ),
6147            Some(Position::Bottom { aft_offset_m: 0.0 }),
6148        )];
6149        one_stage(
6150            vec![
6151                component(
6152                    "nose",
6153                    nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.25, fore_r),
6154                    None,
6155                ),
6156                component("body", body_part(0.7, fore_r, fore_r), None),
6157                component("flare", body_part(flare_l, fore_r, aft_r), None),
6158                tail,
6159            ],
6160            ReferenceDiameter::Maximum {},
6161        )
6162    }
6163
6164    /// The whole rocket's normal-force slope and center of pressure, m aft of the nose tip, at
6165    /// `mach` and a small angle of attack.
6166    fn flared_at(rocket: &hpr_design::Rocket, mach: f64) -> (f64, f64) {
6167        let model = model(rocket);
6168        let force = model.normal_force(&flow(mach, 1e-4, 0.0)).unwrap();
6169        (force.coefficient / 1e-4, force.cp_station_m.unwrap())
6170    }
6171
6172    /// The run's flare, the march of the body ahead of it, and the reference area: what the
6173    /// flare's corner turns at a Mach number.
6174    fn flared_run(rocket: &hpr_design::Rocket) -> ShockExpansionBody {
6175        let model = model(rocket);
6176        let run = model.supersonic_run.as_ref().expect("a run with a flare");
6177        let flare = run.flare.as_ref().expect("the flare in the run");
6178        ShockExpansionBody::new(&flare.ahead, DEFAULT_ELEMENTS_PER_CURVE).unwrap()
6179    }
6180
6181    /// The steepest **surface angle** the flare is read at, degrees, at `mach`: the corner's turn
6182    /// limit on the flow `ahead` delivers to it, taken from that surface's own angle, under the
6183    /// cone tables' 30°.
6184    fn corner_limit_deg(ahead: &ShockExpansionBody, mach: f64) -> f64 {
6185        let aft = ahead.aft_flow(mach).unwrap();
6186        (crate::shock_expansion::flare_corner_limit_rad(aft.surface_mach).unwrap() + aft.angle_rad)
6187            .min(crate::blunt_tip::CONE_TABLE_CAP_RAD)
6188            .to_degrees()
6189    }
6190
6191    /// A flared body flies the shock-expansion method (M1.8e17, ADR-047). Before it, a flare
6192    /// anywhere behind the run took the whole body off the method at every Mach number; now the
6193    /// run marches through the flare's corner and ends there, and the flare's own share is
6194    /// positive with its center of pressure on the flare.
6195    #[test]
6196    fn a_flared_body_flies_the_method() {
6197        let rocket = flared_rocket(10.0);
6198        let model = model(&rocket);
6199        let body = model
6200            .supersonic_body()
6201            .expect("the method covers the flare");
6202        // Nose, tube and flare: the run ends at the flare, and the tail tube behind it carries no
6203        // slender-body slope of its own.
6204        assert_eq!(body.covered, 3);
6205        let old = AeroModel::with_body_model(
6206            &rocket.layout().unwrap(),
6207            BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6208        )
6209        .unwrap();
6210        assert!(old.supersonic_body().is_none());
6211        // The flare's share, and where it acts: on the flare, which runs from 0.95 m to 1.25 m.
6212        for mach in [2.0, 3.0, 4.95] {
6213            let (slope, moment) = body.share(2, mach).unwrap();
6214            assert!(slope > 0.0, "the flare's share at Mach {mach} is {slope}");
6215            let station = moment / slope;
6216            assert!(
6217                (0.95..=1.25).contains(&station),
6218                "the flare's share acts at {station} m at Mach {mach}"
6219            );
6220        }
6221        // What the method says the rocket is worth, against slender-body theory's answer: the
6222        // slope per radian, the center of pressure in calibers of the 0.1598 m reference, and how
6223        // far forward of slender-body theory's the method puts it. The guide quotes these.
6224        let diameter_m = model.reference_diameter_m();
6225        assert!((diameter_m - 0.159_796).abs() < 5e-7, "{diameter_m} m");
6226        for (mach, want_slope, want_calibers, want_old_slope, want_forward) in [
6227            (2.0, 3.537_087_3, 7.365_003, 3.715_259_2, 0.089_048),
6228            (3.0, 2.889_886_8, 7.014_772, 3.081_544_6, 0.168_593),
6229            (4.95, 2.488_028_5, 6.680_843, 2.643_091_4, 0.237_654),
6230        ] {
6231            let (slope, station_m) = flared_at(&rocket, mach);
6232            let old = old.normal_force(&flow(mach, 1e-4, 0.0)).unwrap();
6233            let forward = (old.cp_station_m.unwrap() - station_m) / diameter_m;
6234            assert!(
6235                (slope - want_slope).abs() < 5e-7
6236                    && (station_m / diameter_m - want_calibers).abs() < 5e-6,
6237                "Mach {mach}: {slope} per rad at {} calibers",
6238                station_m / diameter_m
6239            );
6240            assert!(
6241                (old.coefficient / 1e-4 - want_old_slope).abs() < 5e-7
6242                    && (forward - want_forward).abs() < 5e-6,
6243                "Mach {mach} on slender-body theory: {} per rad, the method {forward} calibers \
6244                 forward",
6245                old.coefficient / 1e-4
6246            );
6247        }
6248    }
6249
6250    /// The flare's corner is read no steeper than the turn its shock stays attached through, and
6251    /// a steeper flare reads one of the same radii drawn out to that turn, with its center of
6252    /// pressure on the real flare (M1.8e17, ADR-047).
6253    ///
6254    /// The limit is [`crate::shock_expansion::flare_corner_limit_rad`] at the flow the march
6255    /// delivers to the corner, which is a little faster than the free stream: the nose and the
6256    /// tube ahead of the flare have expanded it.
6257    #[test]
6258    fn a_flare_is_read_no_steeper_than_its_corners_shock_holds() {
6259        let ahead = flared_run(&flared_rocket(18.5));
6260        for (mach, want_surface_mach, want_limit_deg) in [
6261            (1.5, 1.499_968_751_529, 12.111_850_220_062),
6262            (2.0, 1.999_780_928_628, 22.969_761_173_077),
6263            (2.5, 2.498_954_764_087, 29.786_310_648_004),
6264            // From about Mach 2.51 the cone tables' 30° binds, not the shock (ADR-042).
6265            (3.0, 2.996_526_706_276, 30.0),
6266            (4.95, 4.892_298_698_955, 30.0),
6267        ] {
6268            let aft = ahead.aft_flow(mach).unwrap();
6269            assert!(
6270                (aft.surface_mach - want_surface_mach).abs() < 5e-10 && aft.angle_rad == 0.0,
6271                "Mach {mach}: the corner turns Mach {} at {} rad",
6272                aft.surface_mach,
6273                aft.angle_rad
6274            );
6275            let limit = corner_limit_deg(&ahead, mach);
6276            assert!(
6277                (limit - want_limit_deg).abs() < 5e-10,
6278                "Mach {mach}: the corner is read to {limit}°"
6279            );
6280        }
6281        // At Mach 2 a 30° flare is read drawn out to 22.97°: the same radii, a longer flare.
6282        let steep = model(&flared_rocket(30.0));
6283        let run = steep.supersonic_run.as_ref().unwrap();
6284        let flare = run.flare.as_ref().unwrap();
6285        let rise_m = flare.aft_radius_m - flare.fore_radius_m;
6286        let drawn_length_m = rise_m / corner_limit_deg(&ahead, 2.0).to_radians().tan();
6287        assert!(drawn_length_m > flare.length_m);
6288        let mut segments = flare.ahead.clone();
6289        segments.push(BodySegment::Profile {
6290            profile: hpr_design::Profile::transition(
6291                NoseShape::Conical {},
6292                drawn_length_m,
6293                flare.fore_radius_m,
6294                flare.aft_radius_m,
6295                false,
6296            )
6297            .unwrap(),
6298        });
6299        let drawn = ShockExpansionBody::new(&segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6300        let area = steep.reference_area_m2();
6301        let want = *drawn.segment_slopes(2.0, area).unwrap().last().unwrap();
6302        let body = steep.supersonic_body().unwrap();
6303        let (slope, moment) = body.share(2, 2.0).unwrap();
6304        assert!(
6305            (slope - want.slope_per_rad).abs() < 1e-12 * want.slope_per_rad,
6306            "the held share is {slope}, the drawn-out flare's {}",
6307            want.slope_per_rad
6308        );
6309        // The length only enters the march: the center of pressure comes back onto the real
6310        // flare. The drawn-out one's own station lies behind the real flare's aft end, so this is
6311        // a real move and not an identity.
6312        let (fore_m, aft_m) = (run.fore_m[2], run.fore_m[2] + flare.length_m);
6313        let drawn_station_m = want.moment_slope_m / want.slope_per_rad;
6314        let station_m = moment / slope;
6315        assert!(
6316            station_m > fore_m && station_m < aft_m,
6317            "the held share acts at {station_m}, off the flare's {fore_m} to {aft_m}"
6318        );
6319        // The drawn-out flare is 0.409 m long against the real 0.3 m, so its own station sits
6320        // further aft of the corner than anywhere on the real flare it maps to.
6321        assert!(
6322            (drawn_station_m - 1.207_758).abs() < 5e-6 && station_m < drawn_station_m - 0.05,
6323            "the drawn-out share acts at {drawn_station_m}, the mapped one at {station_m}"
6324        );
6325        // Above the limit the reading is held: the drawn body follows the radii and the flow
6326        // ahead, not the angle. The guide quotes what that costs at the extreme: a 75° flare, an
6327        // annular face a detached bow shock would stand in front of, read 18.5% below
6328        // slender-body theory, where the truth is above both.
6329        let at = |deg: f64| {
6330            let rocket = flared_rocket(deg);
6331            let new = model(&rocket).normal_force(&flow(2.0, 1e-4, 0.0)).unwrap();
6332            let old = AeroModel::with_body_model(
6333                &rocket.layout().unwrap(),
6334                BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6335            )
6336            .unwrap()
6337            .normal_force(&flow(2.0, 1e-4, 0.0))
6338            .unwrap();
6339            (new.coefficient / 1e-4, old.coefficient / 1e-4)
6340        };
6341        for (deg, want_method, want_slender) in
6342            [(30.0, 1.946_513, 2.307_693), (75.0, 1.637_856, 2.010_350)]
6343        {
6344            let (method, slender) = at(deg);
6345            assert!(
6346                (method - want_method).abs() < 5e-6 && (slender - want_slender).abs() < 5e-6,
6347                "{deg}°: the method reads {method}, slender-body theory {slender}"
6348            );
6349            assert!(
6350                method < slender,
6351                "{deg}° should read below slender-body theory"
6352            );
6353        }
6354        // At the limit angle itself the drawn-out flare *is* the real flare, so the reading is
6355        // the march's own, station included, with nothing mapped.
6356        let at_limit = model(&flared_rocket(corner_limit_deg(&ahead, 2.0)));
6357        let limit_run = at_limit.supersonic_run.as_ref().unwrap();
6358        let limit_body =
6359            ShockExpansionBody::new(&limit_run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6360        let marched = *limit_body
6361            .segment_slopes(2.0, at_limit.reference_area_m2())
6362            .unwrap()
6363            .last()
6364            .unwrap();
6365        let (limit_slope, limit_moment) =
6366            at_limit.supersonic_body().unwrap().share(2, 2.0).unwrap();
6367        assert!(
6368            (limit_slope - marched.slope_per_rad).abs() < 1e-12 * marched.slope_per_rad
6369                && (limit_moment - marched.moment_slope_m).abs() < 1e-12 * marched.moment_slope_m,
6370            "at the limit the reading is {limit_slope} at {}, the march's {} at {}",
6371            limit_moment / limit_slope,
6372            marched.slope_per_rad,
6373            marched.moment_slope_m / marched.slope_per_rad
6374        );
6375    }
6376
6377    /// **The milestone's own check.** Nothing jumps where the flare's shock detaches: neither in
6378    /// the flare's angle at a fixed Mach number, nor in the Mach number at a fixed angle
6379    /// (M1.8e17, ADR-047).
6380    ///
6381    /// The reading is continuous because it is built that way (at the limit the drawn-out flare
6382    /// *is* the real flare, so the two branches meet), and the test shows it as a probe either
6383    /// side of the boundary: the gap falls with the probe, a thousandfold over three decades, so
6384    /// the slope is continuous across it too and not merely the value.
6385    #[test]
6386    fn nothing_jumps_where_the_flares_shock_detaches() {
6387        // In the flare's angle, at Mach 2, where the boundary is the corner's own limit. Mach 2
6388        // is a row of the table, so the reading there is that row's and not an interpolation.
6389        let ahead = flared_run(&flared_rocket(18.5));
6390        let boundary_deg = corner_limit_deg(&ahead, 2.0);
6391        assert!((boundary_deg - 22.969_761_173_077).abs() < 5e-12);
6392        for (epsilon, want) in [(1e-9, 4.527e-11), (1e-7, 4.527e-9), (1e-5, 4.527e-7)] {
6393            let below = flared_at(&flared_rocket(boundary_deg - epsilon), 2.0);
6394            let above = flared_at(&flared_rocket(boundary_deg + epsilon), 2.0);
6395            let gap = (above.0 / below.0 - 1.0).abs();
6396            assert!(
6397                (gap - want).abs() < 0.01 * want,
6398                "±{epsilon}° across the boundary moves the slope by {gap}, not {want}"
6399            );
6400            assert!(
6401                (above.1 - below.1).abs() < 2e-3 * epsilon,
6402                "the station moves"
6403            );
6404        }
6405        // In the Mach number, at 18.5°: the angle TN D-4865's model 2 carries, whose shock holds
6406        // from Mach 1.7677 on this body.
6407        //
6408        // This half probes the **rows** the table is built from, not a reading interpolated
6409        // between them. The crossing falls between the Mach 1.75 and 1.80 rows, and
6410        // [`SupersonicBody::share`] runs a straight line across a whole row interval, so a
6411        // reading taken there would be linear whatever the two branches did at the crossing, so
6412        // the probe has to ask the row's own function.
6413        let rocket = flared_rocket(18.5);
6414        let model = model(&rocket);
6415        let run = model.supersonic_run.as_ref().expect("a run with a flare");
6416        let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6417        let in_its_place: Vec<Option<ShockExpansionBody>> =
6418            run.segments.iter().map(|_| None).collect();
6419        let area = model.reference_area_m2();
6420        let (mut low, mut high) = (1.2_f64, 5.0_f64);
6421        for _ in 0..80 {
6422            let mid = 0.5 * (low + high);
6423            if corner_limit_deg(&ahead, mid) < 18.5 {
6424                low = mid;
6425            } else {
6426                high = mid;
6427            }
6428        }
6429        assert!(
6430            (high - 1.767_666_917_849).abs() < 5e-12,
6431            "18.5° attaches from Mach {high}"
6432        );
6433        // Either side of the crossing the flare really is read from two different bodies: below
6434        // it the drawn-out one, above it the flare as drawn.
6435        assert!(corner_limit_deg(&ahead, high - 1e-9) < 18.5);
6436        assert!(corner_limit_deg(&ahead, high + 1e-9) > 18.5);
6437        let flare_share = |mach: f64| {
6438            let shares = run
6439                .shares(&body, &in_its_place, Some(&ahead), mach, area)
6440                .expect("the row holds either side of the crossing");
6441            shares[2]
6442        };
6443        for (epsilon, want) in [(1e-9, 3.622e-10), (1e-7, 3.622e-8), (1e-5, 3.622e-6)] {
6444            let (below, above) = (flare_share(high - epsilon), flare_share(high + epsilon));
6445            let gap = (above.slope_per_rad / below.slope_per_rad - 1.0).abs();
6446            assert!(
6447                (gap - want).abs() < 0.01 * want,
6448                "±{epsilon} in Mach across the boundary moves the flare's share by {gap}, not \
6449                 {want}"
6450            );
6451            // Its station moves with it, and stays on the flare.
6452            let station = |s: SegmentSlope| s.moment_slope_m / s.slope_per_rad;
6453            assert!(
6454                (station(above) - station(below)).abs() < 0.1 * epsilon
6455                    && (0.95..=1.25).contains(&station(below)),
6456                "the flare's share acts at {} then {}",
6457                station(below),
6458                station(above)
6459            );
6460        }
6461        // And the whole rocket's reading is continuous there too, interpolation and all.
6462        for epsilon in [1e-9, 1e-7, 1e-5] {
6463            let below = flared_at(&rocket, high - epsilon);
6464            let above = flared_at(&rocket, high + epsilon);
6465            assert!(
6466                (above.0 / below.0 - 1.0).abs() < 2.0 * epsilon,
6467                "±{epsilon} in Mach moves the rocket's slope by {}",
6468                above.0 / below.0 - 1.0
6469            );
6470        }
6471    }
6472
6473    /// A near-flat flare is marched at every row, and what dropping it would still cost.
6474    ///
6475    /// Before M1.8e19 the march refused a run of Mach rows on a flare of about 0.03816° to
6476    /// 0.05882°, because its one element is reduced ([issue
6477    /// #81](https://github.com/nrdptel/fusionspace-eridanus/issues/81)) and hpr read a reduced element aft of
6478    /// the nose as a refusal. The table is built downward from Mach 5 and needs the join's whole
6479    /// width inside it, so the body then fell back to slender-body theory at **every** Mach
6480    /// number. The march now reads those elements by the generalized method, as it always has on
6481    /// the nose, so every row marches and the table is whole.
6482    ///
6483    /// The size of what that switch was worth is still here, because it is the size of the
6484    /// fallback: [`SupersonicFlare::SlenderBody`] is the reading the model used to drop to.
6485    /// Against the method, at 4° on this rocket, it is −8.30% of the normal force and 1.16
6486    /// calibers at Mach 3 and −4.62% and 0.75 calibers at Mach 2, which is what the two edges
6487    /// [issue #117](https://github.com/nrdptel/fusionspace-eridanus/issues/117) reported used to cross.
6488    ///
6489    /// The low-Mach band is a different thing and has not moved: below about Mach 1.56 on this
6490    /// body the corner's isentropic turn runs out before its shock detaches (ADR-045), the table
6491    /// simply starts there, and the join carries the reading across in Mach
6492    /// ([`where_the_corners_turn_runs_out_the_join_carries_the_reading`]).
6493    #[test]
6494    fn a_near_flat_flare_marches_every_row_and_the_fallback_is_still_measured() {
6495        // Every row from Mach 1.2 to Mach 5 marches, at the angles that used to lose whole runs
6496        // of them and at two inside the region Mach 3's own corner reduces.
6497        let ahead = flared_run(&flared_rocket(1.0));
6498        let at_mach_3 =
6499            crate::shock_expansion::flare_reduction_turns_rad(&ahead.aft_flow(3.0).unwrap())
6500                .unwrap();
6501        let reduced_at_mach_3 =
6502            at_mach_3.crossing_rad.to_degrees()..at_mach_3.balance_rad.to_degrees();
6503        assert!(
6504            reduced_at_mach_3.contains(&0.007) && reduced_at_mach_3.contains(&0.008),
6505            "Mach 3 reduces {reduced_at_mach_3:?}, which was meant to hold 0.007° and 0.008°"
6506        );
6507        for deg in [0.001, 0.007, 0.008, 0.01, 0.03, 0.038_17, 0.045, 0.0589] {
6508            let model = model(&flared_rocket(deg));
6509            let run = model.supersonic_run.as_ref().expect("a run with a flare");
6510            let body = ShockExpansionBody::new(&run.segments, DEFAULT_ELEMENTS_PER_CURVE).unwrap();
6511            let area = model.reference_area_m2();
6512            let refused = (SUPERSONIC_FIRST_STEP..=SUPERSONIC_LAST_STEP).find(|step| {
6513                body.slope(*step as f64 / SUPERSONIC_STEPS_PER_MACH, area)
6514                    .is_err()
6515            });
6516            assert_eq!(
6517                refused,
6518                None,
6519                "a {deg}° flare loses Mach {:?}",
6520                refused.map(|step| step as f64 / SUPERSONIC_STEPS_PER_MACH)
6521            );
6522            // And the march reduces the flare's element exactly on the region Mach 3's corner
6523            // gives, which is what makes these rows the region's rows and not an ordinary march.
6524            let flows = body.element_flows(3.0).unwrap();
6525            assert_eq!(
6526                flows[flows.len() - 1].decay_per_m == 0.0,
6527                reduced_at_mach_3.contains(&deg),
6528                "a {deg}° flare at Mach 3, where the region is {reduced_at_mach_3:?}"
6529            );
6530        }
6531        // What the model used to fall back to, and what that is worth against the method: the
6532        // sizes the two edges of the band used to switch by.
6533        let dropped = |deg: f64, mach: f64| {
6534            let rocket = flared_rocket(deg);
6535            let layout = rocket.layout().unwrap();
6536            let read = |model: AeroModel| {
6537                let force = model
6538                    .normal_force(&flow(mach, 4f64.to_radians(), 0.0))
6539                    .unwrap();
6540                (
6541                    force.coefficient,
6542                    force.cp_station_m.unwrap() / model.reference_diameter_m(),
6543                )
6544            };
6545            let method = read(AeroModel::new(&layout).unwrap());
6546            let bare = read(
6547                AeroModel::with_body_model(
6548                    &layout,
6549                    BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6550                )
6551                .unwrap(),
6552            );
6553            (bare.0 / method.0 - 1.0, bare.1 - method.1)
6554        };
6555        let (force, calibers) = dropped(0.058_820_517_4, 3.0);
6556        assert!(
6557            (force + 0.083_0).abs() < 5e-5 && (calibers - 1.157_4).abs() < 5e-5,
6558            "at the band's steep edge the fallback moves the force {force:.4} and the center of \
6559             pressure {calibers:.4} calibers"
6560        );
6561        let (force, calibers) = dropped(9.018_246_55e-4, 2.0);
6562        assert!(
6563            (force + 0.046_2).abs() < 5e-4 && (calibers - 0.752_2).abs() < 5e-4,
6564            "at the join's shallowest step the fallback moves the force {force:.4} and the center \
6565             of pressure {calibers:.4} calibers"
6566        );
6567    }
6568
6569    /// The low-Mach band moves the join, and the join moves the reading continuously: below the
6570    /// Mach number where the march first takes the flare there is no table row, and the weight
6571    /// the method's share carries rises from zero over [`SUPERSONIC_JOIN_WIDTH_MACH`].
6572    #[test]
6573    fn where_the_corners_turn_runs_out_the_join_carries_the_reading() {
6574        let model = model(&flared_rocket(18.5));
6575        let body = model.supersonic_body().unwrap();
6576        assert!(
6577            (body.join_start_mach - 1.555_220_046_128_9).abs() < 5e-13,
6578            "the table starts at Mach {}",
6579            body.join_start_mach
6580        );
6581        // No lip rides along here, so the join is the whole of the method's weight: zero at the
6582        // start and the shape's full share a join's width above it.
6583        assert_eq!(body.shape_weight, 1.0);
6584        assert_eq!(body.weight(body.join_start_mach), 0.0);
6585        assert_eq!(
6586            body.weight(body.join_start_mach + SUPERSONIC_JOIN_WIDTH_MACH),
6587            1.0
6588        );
6589        // At the join's start the method carries nothing, so the reading is slender-body
6590        // theory's, and it stays continuous through it.
6591        let old = AeroModel::with_body_model(
6592            &flared_rocket(18.5).layout().unwrap(),
6593            BodyModel::CURRENT.with_supersonic_flare(SupersonicFlare::SlenderBody),
6594        )
6595        .unwrap();
6596        let at = |model: &AeroModel, mach| {
6597            model
6598                .normal_force(&flow(mach, 1e-4, 0.0))
6599                .unwrap()
6600                .coefficient
6601                / 1e-4
6602        };
6603        assert!((at(&model, body.join_start_mach) - at(&old, body.join_start_mach)).abs() < 1e-12);
6604        for (epsilon, want) in [
6605            (1e-9, 8.547_36e-10),
6606            (1e-7, 8.547_36e-8),
6607            (1e-5, 8.547_38e-6),
6608        ] {
6609            let below = at(&model, body.join_start_mach - epsilon);
6610            let above = at(&model, body.join_start_mach + epsilon);
6611            let gap = (above / below - 1.0).abs();
6612            assert!(
6613                (gap - want).abs() < 1e-5 * want,
6614                "±{epsilon} across the join's start moves the slope by {gap}, not {want}"
6615            );
6616        }
6617    }
6618
6619    /// **What the drawn-out rule does not give: a smooth first derivative.** The reading is
6620    /// continuous in value across the attachment boundary (that is
6621    /// [`nothing_jumps_where_the_flares_shock_detaches`] and the milestone's own check), but a cap
6622    /// makes a kink, and this measures it so the guide does not have to claim otherwise.
6623    ///
6624    /// Below the boundary the flare's angle moves the body the march sees; above it, only the
6625    /// radii do, so the slope of the reading changes. On the tests' flared rocket at Mach 2 the
6626    /// whole rocket's `dC_Nα/dδ` changes by −31.4% there and the flare's own share's by −141.6%,
6627    /// which is a change of sign. The marched branch is not smooth in the flare's angle either:
6628    /// the same probe at 20°, away from any boundary, finds +3.5% and +41.1%.
6629    #[test]
6630    fn the_cap_makes_a_kink_in_the_slope_even_though_the_reading_holds() {
6631        let ahead = flared_run(&flared_rocket(18.5));
6632        let boundary_deg = corner_limit_deg(&ahead, 2.0);
6633        let whole = |deg: f64| flared_at(&flared_rocket(deg), 2.0).0;
6634        let share = |deg: f64| {
6635            model(&flared_rocket(deg))
6636                .supersonic_body()
6637                .unwrap()
6638                .share(2, 2.0)
6639                .unwrap()
6640                .0
6641        };
6642        let kink = |f: &dyn Fn(f64) -> f64, at: f64| {
6643            let epsilon = 1e-6;
6644            let (down, up) = (
6645                (f(at) - f(at - epsilon)) / epsilon,
6646                (f(at + epsilon) - f(at)) / epsilon,
6647            );
6648            up / down - 1.0
6649        };
6650        for (what, f, at_boundary, at_20, at_26) in [
6651            (
6652                "the whole rocket",
6653                &whole as &dyn Fn(f64) -> f64,
6654                -0.313_9,
6655                0.035_0,
6656                0.0,
6657            ),
6658            ("the flare's share", &share, -1.415_6, 0.410_6, 0.0),
6659        ] {
6660            assert!(
6661                (kink(f, boundary_deg) - at_boundary).abs() < 5e-4,
6662                "{what} kinks {} at the boundary",
6663                kink(f, boundary_deg)
6664            );
6665            assert!(
6666                (kink(f, 20.0) - at_20).abs() < 5e-4,
6667                "{what} kinks {} at 20°",
6668                kink(f, 20.0)
6669            );
6670            // Well past the boundary both sides are drawn out, and the slope is smooth again.
6671            assert!(
6672                (kink(f, 26.0) - at_26).abs() < 1e-6,
6673                "{what} kinks {} at 26°",
6674                kink(f, 26.0)
6675            );
6676        }
6677    }
6678
6679    /// A near-flat flare is read through, and what is left of the region is the corner's
6680    /// crossing.
6681    ///
6682    /// The march reduces the flare's one element to the generalized method between the two turns
6683    /// [`crate::shock_expansion::flare_reduction_turns_rad`] solves for, and hpr now reads it
6684    /// there as it always has on the nose ([issue #81](https://github.com/nrdptel/fusionspace-eridanus/issues/81),
6685    /// M1.8e19) instead of refusing the row. So the table starts at
6686    /// [`SUPERSONIC_JOIN_START_MACH`] at every angle across the region, and the two switches
6687    /// [issue #117](https://github.com/nrdptel/fusionspace-eridanus/issues/117) measured are gone:
6688    ///
6689    /// | crossing it | was worth | is worth |
6690    /// |---|---|---|
6691    /// | the band's steep edge, 0.05882052°, at Mach 3 and 4° | −8.30% and 1.1574 calibers | nothing |
6692    /// | the join's shallowest step, 0.00090182°, at Mach 2 and 4° | −4.62% and 0.7522 calibers | nothing |
6693    ///
6694    /// What is left is the crossing itself, and it is small. At the turn where the pressure
6695    /// behind the corner lands on its tangent cone's, `η` has a pole: an angle a hair below it
6696    /// relaxes the loading onto the tangent cone's within the element, and a hair above it holds
6697    /// the corner's. The pressure rides through (the gap it is multiplied by is zero there), but
6698    /// the loading steps, by the gap between the two. That step does not shrink with the probe,
6699    /// so it is a step and not a slope, and it is the same open question as the loading through a
6700    /// crossing inside a segment ([issue #108](https://github.com/nrdptel/fusionspace-eridanus/issues/108),
6701    /// ADR-044). Measured on this rocket at 4°, it is worth well under a tenth of a percent.
6702    #[test]
6703    fn a_near_flat_flare_reads_through_and_leaves_only_the_corners_crossing() {
6704        let join = |deg: f64| {
6705            model(&flared_rocket(deg))
6706                .supersonic_body()
6707                .map(|body| body.join_start_mach)
6708        };
6709        // The table starts at the floor everywhere across the region, including the two edges of
6710        // the band that used to take it away and the three angles whose start was not monotone.
6711        for deg in [
6712            0.0,
6713            2.4e-4,
6714            2.5e-4,
6715            3e-4,
6716            9.018_246_55e-4,
6717            0.001,
6718            0.01,
6719            0.03,
6720            0.038_161_270_2,
6721            0.045,
6722            0.05,
6723            0.058_820_517_4,
6724            0.06,
6725            0.1,
6726            1.0,
6727        ] {
6728            assert_eq!(
6729                join(deg),
6730                Some(SUPERSONIC_JOIN_START_MACH),
6731                "a {deg}° flare starts its table at {:?}",
6732                join(deg)
6733            );
6734        }
6735        // The whole rocket either side of an angle, as `issue_87s_switches_are_this_big` reads
6736        // the switches it lists: the force's fraction and the center of pressure in calibers.
6737        let at = |deg: f64, mach: f64| {
6738            let model = model(&flared_rocket(deg));
6739            let force = model
6740                .normal_force(&flow(mach, 4f64.to_radians(), 0.0))
6741                .unwrap();
6742            (
6743                force.coefficient,
6744                force.cp_station_m.unwrap() / model.reference_diameter_m(),
6745            )
6746        };
6747        let across = |deg: f64, mach: f64, epsilon: f64| {
6748            let (below, above) = (at(deg - epsilon, mach), at(deg + epsilon, mach));
6749            (above.0 / below.0 - 1.0, above.1 - below.1)
6750        };
6751        // The two switches issue #117 measured, where it measured them.
6752        for (deg, mach) in [(0.058_820_517_4, 3.0), (9.018_246_55e-4, 2.0)] {
6753            let (force, calibers) = across(deg, mach, 1e-9);
6754            assert!(
6755                force.abs() < 1e-7 && calibers.abs() < 1e-7,
6756                "crossing {deg}° at Mach {mach} moves the force {force:.3e} and the center of \
6757                 pressure {calibers:.3e} calibers"
6758            );
6759        }
6760        // What is left: the corner's crossing, at the row it belongs to. It is a step, so it
6761        // holds its size as the probe shrinks, and it grows with the Mach number because the
6762        // crossing itself moves to a steeper flare there.
6763        let ahead = flared_run(&flared_rocket(1.0));
6764        let turns = |mach: f64| {
6765            crate::shock_expansion::flare_reduction_turns_rad(&ahead.aft_flow(mach).unwrap())
6766                .unwrap()
6767        };
6768        for (mach, force_want, caliber_want) in [
6769            (2.0_f64, 3.234e-6, -1.589e-6),
6770            (3.0, 1.1369e-4, 1.8258e-4),
6771            (4.0, 5.5377e-4, 1.6709e-3),
6772            (4.95, 1.2874e-3, 5.1095e-3),
6773        ] {
6774            let crossing = turns(mach).crossing_rad.to_degrees();
6775            // A hundredfold in the probe leaves the step where it is, except at Mach 2, where
6776            // 3.2e-6 is already what the reading itself moves over a 1e-7° probe.
6777            let probes: &[f64] = if mach > 2.0 { &[1e-9, 1e-7] } else { &[1e-9] };
6778            for epsilon in probes {
6779                let (force, calibers) = across(crossing, mach, *epsilon);
6780                assert!(
6781                    (force - force_want).abs() < 0.02 * force_want.abs()
6782                        && (calibers - caliber_want).abs() < 0.02 * caliber_want.abs(),
6783                    "Mach {mach}: ±{epsilon}° across the crossing at {crossing}° moves the force \
6784                     {force:.4e} and the center of pressure {calibers:.4e} calibers"
6785                );
6786            }
6787            // The region's other edge, the balance, is where `η` is zero: the exponential form
6788            // and the generalized method are the same reading there, so nothing steps.
6789            let balance = turns(mach).balance_rad.to_degrees();
6790            let (force, calibers) = across(balance, mach, 1e-9);
6791            assert!(
6792                force.abs() < 1e-7 && calibers.abs() < 1e-7,
6793                "Mach {mach}: the balance at {balance}° moves the force {force:.3e} and the \
6794                 center of pressure {calibers:.3e} calibers"
6795            );
6796        }
6797        // And the reading really does move smoothly through the whole region, which is what the
6798        // switch it replaced did not: swept in twenty steps from a cylinder to well past the
6799        // region's steep end, no neighboring pair moves the force by a fifth of a percent, and
6800        // the reading falls all the way, bar the one pair that straddles the crossing.
6801        let machs = [3.0, 4.0];
6802        let step = 0.08 / 16.0;
6803        let swept: Vec<[f64; 2]> = (0..=16)
6804            .map(|index| {
6805                let model = model(&flared_rocket(index as f64 * step));
6806                machs.map(|mach| {
6807                    model
6808                        .normal_force(&flow(mach, 4f64.to_radians(), 0.0))
6809                        .unwrap()
6810                        .coefficient
6811                })
6812            })
6813            .collect();
6814        for (column, mach) in machs.iter().enumerate() {
6815            let crossing = turns(*mach).crossing_rad.to_degrees();
6816            let mut rises = Vec::new();
6817            for index in 1..swept.len() {
6818                let moved = swept[index][column] / swept[index - 1][column] - 1.0;
6819                let deg = index as f64 * step;
6820                assert!(
6821                    moved.abs() < 2e-3,
6822                    "Mach {mach}: from {}° to {deg}° the force moves {moved:.4}",
6823                    deg - step
6824                );
6825                if moved > 0.0 {
6826                    rises.push(deg);
6827                }
6828            }
6829            assert!(
6830                rises.len() <= 1
6831                    && rises
6832                        .first()
6833                        .is_none_or(|deg| (deg - step..*deg).contains(&crossing)),
6834                "Mach {mach}: the force rises over {rises:?}, against a crossing at {crossing}°"
6835            );
6836        }
6837    }
6838
6839    /// The size of each switch issue #87 lists, measured at Mach 3 and 4° on two test bodies: the
6840    /// flare behind a boattail on a finless body (`finned_rocket(4)` with its tail and fins cut
6841    /// off, then a bare flare), so its share is of a body's normal force alone; the other three on
6842    /// the straight rocket, which keeps its four fins. Each is the whole test body's normal force
6843    /// and center of pressure either side of the threshold, as a share and in calibers. The lip's is gone since M1.8e10; these are what remain, and
6844    /// ADR-041 and the guide quote them from here.
6845    #[test]
6846    fn issue_87s_switches_are_this_big() {
6847        let at = |rocket: &hpr_design::Rocket| {
6848            let model = model(rocket);
6849            let force = model
6850                .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
6851                .unwrap();
6852            (
6853                force.coefficient,
6854                force.cp_station_m.unwrap() / model.reference_diameter_m(),
6855                model.supersonic_body().is_some(),
6856            )
6857        };
6858        // A step in radius, past a millionth of the cylinder's area: the run stops at it.
6859        let stepped = |drop_m: f64| {
6860            let mut rocket = straight_rocket();
6861            // The nose and its first tubes stay at 0.027 m; the last tube steps down, which is
6862            // where the run stops once the step passes a millionth of the cylinder's area.
6863            rocket.stages[0].components[3].part = body_part(0.3, 0.027 - drop_m, 0.027 - drop_m);
6864            rocket
6865        };
6866        // A flare behind a boattail, however small: not a flare in the free stream but a lip in
6867        // the boattail's wake, and too long for the wake to cover, so the run stops at it
6868        // (ADR-039). A conical flare not behind a boattail flies the method since M1.8e17.
6869        let flared = |rise_m: f64| {
6870            let mut rocket = crate::testing::finned_rocket(4);
6871            rocket.stages[0].components.truncate(3);
6872            rocket.stages[0].components.push(component(
6873                "flare",
6874                body_part(1.0, 0.022, 0.022 + rise_m),
6875                None,
6876            ));
6877            rocket
6878        };
6879        // A pointed tip at TN 3527 Fig. 2's edge, 24°.
6880        let coned = |half_angle_deg: f64| {
6881            let mut rocket = straight_rocket();
6882            rocket.stages[0].components[0].part = nose(
6883                NoseShape::Conical {},
6884                0.027 / half_angle_deg.to_radians().tan(),
6885                0.027,
6886            );
6887            rocket
6888        };
6889        // A vertical tip whose base slope is steeper than the cap's handover, at 24°.
6890        let blunt = |length_m: f64| {
6891            let mut rocket = straight_rocket();
6892            rocket.stages[0].components[0].part =
6893                nose(NoseShape::PowerSeries { exponent: 0.5 }, length_m, 0.027);
6894            rocket
6895        };
6896        let at_16 = 0.027 / 24.0_f64.to_radians().tan();
6897        // Where the step's threshold sits, bracketed: a billionth of the radius, which is the
6898        // tangent body's own tolerance for two elements parallel but apart
6899        // (`shock_expansion::lay_out`), not the coverage gate's millionth of the area.
6900        assert!(model(&stepped(2.6e-11)).supersonic_body().is_some());
6901        assert!(model(&stepped(2.8e-11)).supersonic_body().is_none());
6902        // (what it is, the covered side, the bare side, what the docs say it is worth); a side
6903        // is (force, calibers, covered), and the expected pair is signed: bare over covered less
6904        // one, and bare's center of pressure less covered's, in calibers.
6905        type Side = (f64, f64, bool);
6906        let switches: [(&str, Side, Side, (f64, f64)); 4] = [
6907            (
6908                "a step in radius",
6909                at(&stepped(1e-12)),
6910                at(&stepped(1e-9)),
6911                (-0.0865, 1.0285),
6912            ),
6913            (
6914                "a flare behind a boattail",
6915                at(&flared(1e-12)),
6916                at(&flared(1e-9)),
6917                (-0.2749, 0.2872),
6918            ),
6919            (
6920                "a pointed tip past the cone tables' 30°",
6921                at(&coned(29.999)),
6922                at(&coned(30.002)),
6923                (-0.0770, 0.8107),
6924            ),
6925            (
6926                "a vertical tip steeper than the handover",
6927                at(&blunt(0.5 * at_16 * 1.0002)),
6928                at(&blunt(0.5 * at_16 * 0.9998)),
6929                (-0.0699, 0.6383),
6930            ),
6931        ];
6932        // Since M1.8e11 the cone tables reach 30°, so a tip at TN 3527 Fig. 2's old 24° edge no
6933        // longer switches anything: both sides fly the method and agree to a part in a million.
6934        let (below, above) = (at(&coned(23.999)), at(&coned(24.002)));
6935        assert!(
6936            below.2 && above.2,
6937            "a 24° tip flies the method on both sides now"
6938        );
6939        assert!(
6940            (above.0 / below.0 - 1.0).abs() < 1e-4 && (above.1 - below.1).abs() < 1e-4,
6941            "across Fig. 2's old edge: {below:?} to {above:?}"
6942        );
6943        for (what, covered, bare, (want_force, want_calibers)) in switches {
6944            assert!(
6945                covered.2 && !bare.2,
6946                "{what}: the method should cover one side only ({covered:?}, {bare:?})"
6947            );
6948            let force = bare.0 / covered.0 - 1.0;
6949            let calibers = bare.1 - covered.1;
6950            assert!(
6951                (force - want_force).abs() < 5e-4 && (calibers - want_calibers).abs() < 5e-4,
6952                "{what}: the force moves {force:.4} and the center of pressure {calibers:.4} \
6953                 calibers, against {want_force} and {want_calibers}"
6954            );
6955        }
6956    }
6957
6958    #[test]
6959    fn a_steep_tip_is_reported_as_the_runs_fallback() {
6960        // A pointed conical tip a hair steeper than the cone tables' 30° is the run's fallback
6961        // (issue #121, ADR-181); one a hair shallower keeps the run.
6962        let with_tip = |half_angle_deg: f64| {
6963            let mut rocket = straight_rocket();
6964            let Part::NoseCone(nose) = &mut rocket.stages[0].components[0].part else {
6965                panic!("the first part is the nose");
6966            };
6967            nose.shape = NoseShape::Conical {};
6968            nose.length_m = nose.base_radius_m / half_angle_deg.to_radians().tan();
6969            model(&rocket).supersonic_fallback()
6970        };
6971        assert_eq!(with_tip(29.99), None);
6972        assert_eq!(with_tip(30.01), Some(SupersonicFallback::SteepTip));
6973    }
6974
6975    #[test]
6976    fn a_step_is_reported_as_the_runs_fallback() {
6977        // The fallback names the first stepped part (issue #87, ADR-181), and only once the step
6978        // is past the run's millionth of the area; a flush body has none.
6979        let stepped = |drop_m: f64| {
6980            let mut rocket = straight_rocket();
6981            for (i, length_m) in [0.0, 0.7, 0.05, 0.3].iter().enumerate().skip(2) {
6982                rocket.stages[0].components[i].part =
6983                    body_part(*length_m, 0.027 - drop_m, 0.027 - drop_m);
6984            }
6985            let id = rocket.stages[0].components[2].id.clone();
6986            (model(&rocket).supersonic_fallback(), id)
6987        };
6988        assert_eq!(stepped(0.0).0, None);
6989        let (fallback, id) = stepped(1e-3);
6990        assert_eq!(
6991            fallback,
6992            Some(SupersonicFallback::RadiusStep { component: id })
6993        );
6994        let (fallback, id) = stepped(-1e-3);
6995        assert_eq!(
6996            fallback,
6997            Some(SupersonicFallback::RadiusStep { component: id })
6998        );
6999        // At the edge, where the march refuses a step (a billionth of the 0.027 m radius, pinned
7000        // by `a_step_takes_the_whole_body_off_the_method`), and between it and the run's looser
7001        // gate (13.5 nm here), where the table is what fails.
7002        assert_eq!(stepped(2.6e-11).0, None);
7003        for drop_m in [2.8e-11, 1e-9, -1e-9, 1e-8] {
7004            let (fallback, id) = stepped(drop_m);
7005            assert_eq!(
7006                fallback,
7007                Some(SupersonicFallback::RadiusStep { component: id }),
7008                "a step of {drop_m} m"
7009            );
7010        }
7011    }
7012
7013    /// What a **step in radius** costs, measured (M1.8e15, ADR-049).
7014    ///
7015    /// A step is a joint where one component's fore radius does not match the previous one's aft
7016    /// radius. The march cannot cross one (its tangent body needs a profile without a jump in it),
7017    /// and the model around it then takes the *whole* body off the method, because mixing the
7018    /// method's shares with slender-body theory's is what ADR-034 rejected.
7019    ///
7020    /// This pins where that switch sits and what it is worth, so that a fix can be measured
7021    /// against it rather than argued about.
7022    /// What a **step in radius** costs, and where the march refuses one (M1.8e15, ADR-049).
7023    ///
7024    /// A step is a joint where one part's radius does not match the next one's. The tangent body
7025    /// the march walks needs a profile without a jump in it, so a step takes the **whole** body
7026    /// back to slender-body theory, at every speed. Nothing measures a stepped body faster than
7027    /// sound, so the size of that switch is published rather than modeled.
7028    #[test]
7029    fn a_step_takes_the_whole_body_off_the_method() {
7030        use hpr_design::ReferenceDiameter;
7031        // The tests' straight rocket: a tangent-ogive nose 0.25 m and three tubes, 0.7, 0.05 and
7032        // 0.3 m, all at 0.027 m. `joint` is which tube the step is at: 1 is the nose's own joint,
7033        // 3 the last. A positive `drop_m` steps the body **down** from that joint aft, a negative
7034        // one steps it **up**. The reference is pinned at 54 mm so that every row is divided by
7035        // the same area: left on `Maximum`, a step up would widen the reference with it and the
7036        // rows would not be comparable.
7037        let at_joint = |joint: usize, drop_m: f64| {
7038            let mut rocket = straight_rocket();
7039            rocket.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.054 };
7040            let lengths = [0.0, 0.7, 0.05, 0.3];
7041            for (i, length_m) in lengths.iter().enumerate().skip(joint) {
7042                rocket.stages[0].components[i].part =
7043                    body_part(*length_m, 0.027 - drop_m, 0.027 - drop_m);
7044            }
7045            rocket
7046        };
7047        let read = |joint: usize, drop_m: f64| {
7048            let rocket = at_joint(joint, drop_m);
7049            let model = model(&rocket);
7050            let force = model
7051                .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
7052                .unwrap();
7053            (
7054                force.coefficient,
7055                force.cp_station_m.unwrap() / model.reference_diameter_m(),
7056                model.supersonic_body().is_some(),
7057            )
7058        };
7059        let (flush, flush_cp, marched) = read(3, 0.0);
7060        assert!(marched, "with no step the method covers the body");
7061        assert!(
7062            (flush - 0.899_591_695).abs() < 5e-7 && (flush_cp - 16.949_177_4).abs() < 5e-5,
7063            "the flush rocket reads {flush} at {flush_cp} calibers"
7064        );
7065
7066        // What it costs. At the threshold the body is flush to a part in 1e9, so the whole
7067        // difference is the method itself: the same −8.65% and 1.03 calibers wherever the step is
7068        // and whichever way it goes. It grows with a step **down**, which takes area off the body;
7069        // it shrinks with a step **up**, because the area a step up adds carries slender-body
7070        // normal force of its own. Either way the center of pressure moves aft.
7071        for (joint, drop_m, want_force, want_calibers) in [
7072            (1, 2.8e-11, -0.086_518_790, 1.028_480_4),
7073            (2, 2.8e-11, -0.086_518_790, 1.028_480_4),
7074            (3, 2.8e-11, -0.086_518_789, 1.028_480_4),
7075            (1, 1e-3, -0.106_197_868, 1.193_751_6),
7076            (3, 1e-3, -0.102_873_512, 0.994_855_8),
7077            (1, 2e-3, -0.125_539_709, 1.359_310_7),
7078            (3, 2e-3, -0.118_890_998, 0.959_745_0),
7079            (1, -2.8e-11, -0.086_518_788, 1.028_480_4),
7080            (3, -2.8e-11, -0.086_518_789, 1.028_480_4),
7081            (1, -1e-3, -0.067_194_034, 0.867_387_3),
7082            (3, -1e-3, -0.070_503_028, 1.064_443_7),
7083            (1, -2e-3, -0.047_519_789, 0.706_432_7),
7084            (3, -2e-3, -0.054_109_172, 1.098_652_0),
7085        ] {
7086            let (force, cp, marched) = read(joint, drop_m);
7087            assert!(
7088                !marched,
7089                "a {drop_m} m step at joint {joint} kept the method"
7090            );
7091            let (force, calibers) = (force / flush - 1.0, cp - flush_cp);
7092            assert!(
7093                (force - want_force).abs() < 5e-6 && (calibers - want_calibers).abs() < 5e-5,
7094                "a {drop_m} m step at joint {joint} moves the force {force:.9} and the center of \
7095                 pressure {calibers:.7} calibers, against {want_force} and {want_calibers}"
7096            );
7097        }
7098
7099        // Where the switch sits at a joint whose slope does not change: the tangent body merges
7100        // two elements within a billionth of the radius of each other and refuses them past that
7101        // (`shock_expansion::lay_out`), so the step the march refuses is 1e-9 × 0.027 m. Bisected
7102        // at the last joint to a part in 1e6; the other joints and the other direction are
7103        // bracketed either side of it, which is what "wherever it sits, whichever way" means.
7104        let (mut low, mut high) = (1e-13, 1e-8);
7105        assert!(
7106            read(3, low).2 && !read(3, high).2,
7107            "the bisection has to start with the march covering one end and refusing the other"
7108        );
7109        while high - low > 1e-6 * high {
7110            let mid = 0.5 * (low + high);
7111            if read(3, mid).2 {
7112                low = mid
7113            } else {
7114                high = mid
7115            }
7116        }
7117        assert!(
7118            (high / 2.7e-11 - 1.0).abs() < 2e-6,
7119            "the march refuses a step of {high} m, not a billionth of the 0.027 m radius"
7120        );
7121        for joint in [1, 2, 3] {
7122            for sign in [1.0, -1.0] {
7123                assert!(
7124                    read(joint, sign * 2.6e-11).2 && !read(joint, sign * 2.8e-11).2,
7125                    "at joint {joint} with sign {sign} the switch is not at 2.7e-11 m"
7126                );
7127            }
7128        }
7129
7130        // The run's own coverage gate is a different, much looser test (a millionth of the fore
7131        // area, 13.5 nm of radius here), and it owns every step anyone could draw. Below it the
7132        // stepped tube still joins the run and `lay_out` is what refuses the body; above it the
7133        // run never forms. Both give the same reading, so this pins which one owns which range.
7134        let run_segments = |drop_m: f64| {
7135            let rocket = at_joint(3, drop_m);
7136            model(&rocket)
7137                .supersonic_run
7138                .as_ref()
7139                .map(|run| run.segments.len())
7140        };
7141        for drop_m in [1e-8, -1e-8] {
7142            assert_eq!(
7143                run_segments(drop_m),
7144                Some(4),
7145                "{drop_m} m is inside the gate"
7146            );
7147        }
7148        for drop_m in [2e-8, -2e-8] {
7149            assert_eq!(run_segments(drop_m), None, "{drop_m} m is outside the gate");
7150        }
7151
7152        // At a joint where the slope **does** change, the binding constraint is not the merge
7153        // tolerance but the corner ordering (`shock_expansion::lay_out`'s `corner_x <= x + 1e-12 *
7154        // length_m`), so a step **up** is refused at 1e-12 × the body's length × the change of
7155        // slope. On the tests' finned rocket (the same body with a 0.027 → 0.022 m boattail, so
7156        // 1.3 m and a slope change of 0.1), that is 1.3e-13 m, 208× finer than the 2.7e-11 m a
7157        // tube-to-tube joint needs, and it costs more: −11.34% and 1.095 calibers. The threshold
7158        // is a pair, not a number, and this is the common shape it bites on.
7159        let boattail = |drop_m: f64| {
7160            let mut rocket = crate::testing::finned_rocket(4);
7161            rocket.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.054 };
7162            rocket.stages[0].components[2].part = body_part(0.05, 0.027 - drop_m, 0.022);
7163            let model = model(&rocket);
7164            let force = model
7165                .normal_force(&flow(3.0, 4f64.to_radians(), 0.0))
7166                .unwrap();
7167            (
7168                force.coefficient,
7169                force.cp_station_m.unwrap() / model.reference_diameter_m(),
7170                model.supersonic_body().is_some(),
7171            )
7172        };
7173        let (boattail_flush, boattail_flush_cp, marched) = boattail(0.0);
7174        assert!(marched, "flush, the method covers the boattailed body too");
7175        let (mut low, mut high) = (1e-18, 1e-8);
7176        assert!(boattail(-low).2 && !boattail(-high).2);
7177        while high - low > 1e-6 * high {
7178            let mid = 0.5 * (low + high);
7179            if boattail(-mid).2 {
7180                low = mid
7181            } else {
7182                high = mid
7183            }
7184        }
7185        assert!(
7186            (high / (1e-12 * 1.3 * 0.1) - 1.0).abs() < 2e-4,
7187            "a step up at the boattail's joint is refused at {high} m, not 1e-12 × 1.3 m × 0.1"
7188        );
7189        assert!(
7190            boattail(2.6e-11).2 && !boattail(2.8e-11).2,
7191            "stepping down at that joint, the merge tolerance still binds"
7192        );
7193        for drop_m in [-1.4e-13, -2.8e-11, 2.8e-11] {
7194            let (force, cp, marched) = boattail(drop_m);
7195            assert!(
7196                !marched,
7197                "a {drop_m} m step at the boattail kept the method"
7198            );
7199            let (force, calibers) = (force / boattail_flush - 1.0, cp - boattail_flush_cp);
7200            assert!(
7201                (force + 0.113_409_121).abs() < 5e-6 && (calibers - 1.095_116_4).abs() < 5e-5,
7202                "a {drop_m} m step at the boattail moves the force {force:.9} and the center of \
7203                 pressure {calibers:.7} calibers"
7204            );
7205        }
7206    }
7207
7208    #[test]
7209    fn a_body_the_method_cannot_finish_keeps_slender_body_terms() {
7210        let at = |m: &AeroModel, mach| body_values(m, mach);
7211        // A flare the method cannot take (a boattail flies it since M1.8e4, a conical flare
7212        // since M1.8e17), a vertical tip steeper than the blunt tip's handover all the way to
7213        // its base (a power-series nose one radius long;
7214        // longer ones fly the method since M1.8e7), a step in radius behind the nose.
7215        let mut rocket = straight_rocket();
7216        // A conical flare flies the method since M1.8e17
7217        // (`a_flared_body_flies_the_method`); any other widening shape still ends the run.
7218        rocket.stages[0].components[2].part = body_part(0.05, 0.027, 0.032);
7219        if let Part::Transition(transition) = &mut rocket.stages[0].components[2].part {
7220            transition.shape = NoseShape::Ogive { radius_ratio: 1.0 };
7221        }
7222        rocket.stages[0].components[3].part = body_part(0.3, 0.032, 0.032);
7223        let flared = model(&rocket);
7224        // A boattail followed by a flare (a lip), and a boattail at a step down: each leaves a
7225        // body with a slope of its own behind the run.
7226        let mut rocket = crate::testing::finned_rocket(4);
7227        rocket.stages[0]
7228            .components
7229            .push(component("lip", body_part(0.01, 0.022, 0.025), None));
7230        let lipped = model(&rocket);
7231        let mut rocket = crate::testing::finned_rocket(4);
7232        rocket.stages[0].components[2].part = body_part(0.05, 0.026, 0.022);
7233        let stepped_boattail = model(&rocket);
7234        let mut rocket = straight_rocket();
7235        rocket.stages[0].components[0].part =
7236            nose(NoseShape::PowerSeries { exponent: 0.5 }, 0.027, 0.027);
7237        let blunt = model(&rocket);
7238        let mut rocket = straight_rocket();
7239        rocket.stages[0].components[1].part = body_part(0.7, 0.03, 0.03);
7240        let stepped = model(&rocket);
7241        for model in [&flared, &lipped, &stepped_boattail, &blunt, &stepped] {
7242            assert!(model.supersonic_body().is_none());
7243            assert_eq!(at(model, 3.0), at(model, 0.5));
7244        }
7245    }
7246
7247    #[test]
7248    fn clones_share_the_table_and_compare_equal() {
7249        let model = model(&straight_rocket());
7250        let clone = model.clone();
7251        assert_eq!(model, clone);
7252        let built = model.supersonic_body().unwrap() as *const SupersonicBody;
7253        assert_eq!(model, clone);
7254        assert!(std::ptr::eq(built, clone.supersonic_body().unwrap()));
7255    }
7256
7257    /// A kept table is found only for an equal run on the same reference area, and is the one
7258    /// building it gives (issue #1427): the test rocket, the same shape on a wider reference area
7259    /// (the same run) and one with a longer nose (another run) are each kept, and each finds its
7260    /// own, compared with [`SupersonicBody::new`]'s in `Debug`'s digits. With `most` kept, keeping
7261    /// one more drops the first kept; keeping one already kept changes nothing; keeping none
7262    /// keeps nothing.
7263    #[test]
7264    fn kept_tables_are_found_by_run_and_area_and_the_first_kept_drops_first() {
7265        let rocket = straight_rocket();
7266        let mut wider = rocket.clone();
7267        wider.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.07 };
7268        let mut longer = rocket.clone();
7269        longer.stages[0].components[0].part =
7270            nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.4, 0.027);
7271        let keys: Vec<(&str, SupersonicRun, f64)> = [
7272            ("the rocket", &rocket),
7273            ("wider", &wider),
7274            ("longer", &longer),
7275        ]
7276        .into_iter()
7277        .map(|(what, design)| {
7278            let aero = model(design);
7279            let run = aero
7280                .supersonic_run
7281                .clone()
7282                .expect("a run the method covers");
7283            (what, run, aero.reference_area_m2)
7284        })
7285        .collect();
7286        assert_eq!(
7287            keys[0].1, keys[1].1,
7288            "the wider rocket's run is the rocket's"
7289        );
7290        assert_ne!(keys[0].2.to_bits(), keys[1].2.to_bits());
7291        assert_ne!(keys[0].1, keys[2].1);
7292        let built: Vec<Option<SupersonicBody>> = keys
7293            .iter()
7294            .map(|(_, run, area)| SupersonicBody::new(run, *area))
7295            .collect();
7296        assert!(built.iter().all(Option::is_some));
7297        let mut kept = KeptTables::new(3);
7298        for ((_, run, area), table) in keys.iter().zip(&built) {
7299            assert!(kept.find(run, *area).is_none());
7300            kept.keep(run, *area, table);
7301        }
7302        for ((what, run, area), table) in keys.iter().zip(&built) {
7303            let found = kept.find(run, *area).expect("kept");
7304            assert_eq!(format!("{found:?}"), format!("{table:?}"), "{what}");
7305            assert_eq!(
7306                format!("{found:?}"),
7307                format!("{:?}", SupersonicBody::new(run, *area)),
7308                "{what}: not what building it again gives"
7309            );
7310        }
7311        // Kept again, even with another table: nothing changes.
7312        kept.keep(&keys[0].1, keys[0].2, &built[2]);
7313        assert_eq!(kept.tables.len(), 3);
7314        assert_eq!(
7315            format!("{:?}", kept.find(&keys[0].1, keys[0].2)),
7316            format!("{:?}", Some(&built[0]))
7317        );
7318        let (_, run, area) = &keys[2];
7319        let mut fewer = KeptTables::new(2);
7320        fewer.keep(&keys[0].1, keys[0].2, &built[0]);
7321        fewer.keep(&keys[1].1, keys[1].2, &built[1]);
7322        fewer.keep(run, *area, &built[2]);
7323        assert_eq!(fewer.tables.len(), 2);
7324        assert!(
7325            fewer.find(&keys[0].1, keys[0].2).is_none(),
7326            "the first kept is dropped"
7327        );
7328        assert!(fewer.find(&keys[1].1, keys[1].2).is_some());
7329        assert!(fewer.find(run, *area).is_some());
7330        let mut none = KeptTables::new(0);
7331        none.keep(run, *area, &built[2]);
7332        assert!(none.tables.is_empty());
7333    }
7334
7335    /// Two models built apart share a table only where the table follows from the same segments
7336    /// and reference area: a drag scale doesn't stop it; another shape, another reference area or
7337    /// a body the method doesn't take does.
7338    #[test]
7339    fn models_built_apart_share_the_table_only_on_the_same_body() {
7340        let rocket = straight_rocket();
7341        let nominal = model(&rocket);
7342        let alone = model(&rocket).with_drag_scale(1.1).unwrap();
7343        let built = nominal.supersonic_body().unwrap() as *const SupersonicBody;
7344        assert!(!std::ptr::eq(built, alone.supersonic_body().unwrap()));
7345        let mut scaled = model(&rocket).with_drag_scale(1.1).unwrap();
7346        assert!(!scaled.supersonic_table_built());
7347        assert!(scaled.share_supersonic_table(&nominal));
7348        assert!(scaled.supersonic_table_built());
7349        assert!(std::ptr::eq(built, scaled.supersonic_body().unwrap()));
7350        // The other way round: the model that shares builds the table for the one it shares.
7351        let first = model(&rocket);
7352        let mut second = model(&rocket);
7353        assert!(second.share_supersonic_table(&first));
7354        assert!(!first.supersonic_table_built());
7355        let built = second.supersonic_body().unwrap() as *const SupersonicBody;
7356        assert!(first.supersonic_table_built());
7357        assert!(std::ptr::eq(built, first.supersonic_body().unwrap()));
7358        // A longer nose covers other segments; a blunt one has no table.
7359        let mut longer = rocket.clone();
7360        longer.stages[0].components[0].part =
7361            nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.4, 0.027);
7362        let mut longer = model(&longer);
7363        assert!(!longer.share_supersonic_table(&nominal));
7364        assert!(!std::ptr::eq(
7365            nominal.supersonic_body().unwrap(),
7366            longer.supersonic_body().unwrap()
7367        ));
7368        // The same shape on another reference area: the table's shares are per that area.
7369        let mut wider = rocket.clone();
7370        wider.reference_diameter = ReferenceDiameter::Custom { diameter_m: 0.07 };
7371        let mut wider = model(&wider);
7372        assert!(!wider.share_supersonic_table(&nominal));
7373        assert!(!wider.supersonic_table_built());
7374        let mut blunt = rocket;
7375        blunt.stages[0].components[0].part =
7376            nose(NoseShape::PowerSeries { exponent: 0.5 }, 0.027, 0.027);
7377        let mut blunt = model(&blunt);
7378        assert!(!blunt.share_supersonic_table(&nominal));
7379        assert!(blunt.supersonic_body().is_none());
7380    }
7381
7382    /// Each part's share of the drag at Mach 0.3 at sea level, by id, and their sum.
7383    fn shares(rocket: &hpr_design::Rocket) -> (Vec<(String, Drag)>, f64) {
7384        let m = model(rocket);
7385        let conditions = DragConditions::coasting(0.3 * 340.294 / 1.4607e-5);
7386        let parts: Vec<(String, Drag)> = m
7387            .buildup_components(&Flow::axial(0.3), &conditions)
7388            .unwrap()
7389            .into_iter()
7390            .map(|part| (part.id, part.drag))
7391            .collect();
7392        let total = m.drag(&Flow::axial(0.3), &conditions).unwrap();
7393        let sum: f64 = parts.iter().map(|(_, d)| d.zero_lift_coefficient).sum();
7394        close(total.zero_lift_coefficient, sum, 1e-12, "the parts add up");
7395        (parts, total.zero_lift_coefficient)
7396    }
7397
7398    fn share(parts: &[(String, Drag)], id: &str) -> Drag {
7399        parts
7400            .iter()
7401            .find(|(i, _)| i == id)
7402            .map(|(_, d)| *d)
7403            .unwrap()
7404    }
7405
7406    fn stated(coefficient: f64, include_children: bool) -> Option<hpr_design::DragOverride> {
7407        Some(hpr_design::DragOverride {
7408            coefficient,
7409            include_children,
7410        })
7411    }
7412
7413    /// A nose, a tube 27 mm in radius and a tube 22 mm in radius behind it, a step down between
7414    /// them, three fins on the aft tube.
7415    fn stepped_rocket() -> hpr_design::Rocket {
7416        let mut rocket = finned_rocket(3);
7417        let components = &mut rocket.stages[0].components;
7418        components.remove(2);
7419        rocket
7420    }
7421
7422    /// ADR-167: a stated coefficient replaces all of a part's own drag, on the reference area, once
7423    /// per fin; a step down goes with the part ahead of it, whose aft face it is; a part covered
7424    /// by its parent's override has none; a stage's is a term of its own.
7425    #[test]
7426    fn a_stated_drag_coefficient_replaces_the_part_s_own() {
7427        let plain = stepped_rocket();
7428        let (before, total) = shares(&plain);
7429        let step = base_drag_coefficient(0.3).unwrap() * (1.0 - (0.022_f64 / 0.027).powi(2));
7430        // The tail's share holds the step down from the body, a flat face's base drag.
7431        assert!(
7432            share(&before, "tail").pressure >= step,
7433            "{:?}",
7434            share(&before, "tail")
7435        );
7436
7437        // Three fins at 0.5: 1.5 in place of the fins' own drag.
7438        let mut fins = plain.clone();
7439        fins.stages[0].components[2].children[0].drag_override = stated(0.5, false);
7440        let (after, with) = shares(&fins);
7441        close(share(&after, "fins").stated, 1.5, 1e-15, "per fin");
7442        close(
7443            with,
7444            total - share(&before, "fins").zero_lift_coefficient + 1.5,
7445            1e-12,
7446            "fins",
7447        );
7448
7449        // The body at 0.2: the step down behind it goes too.
7450        let mut body = plain.clone();
7451        body.stages[0].components[1].drag_override = stated(0.2, false);
7452        let (after, with) = shares(&body);
7453        close(
7454            share(&after, "body").zero_lift_coefficient,
7455            0.2,
7456            1e-15,
7457            "body",
7458        );
7459        close(
7460            share(&before, "tail").zero_lift_coefficient
7461                - share(&after, "tail").zero_lift_coefficient,
7462            step,
7463            1e-12,
7464            "the step goes with the body",
7465        );
7466        close(
7467            with,
7468            total - share(&before, "body").zero_lift_coefficient - step + 0.2,
7469            1e-12,
7470            "body",
7471        );
7472
7473        // The tail at 0.2: the step down ahead of it stays, its base and fins do not change.
7474        let mut tail = plain.clone();
7475        tail.stages[0].components[2].drag_override = stated(0.2, false);
7476        let (after, with_tail) = shares(&tail);
7477        let own = share(&after, "tail");
7478        close(own.stated, 0.2, 1e-15, "tail");
7479        close(own.pressure, step, 1e-12, "the step stays");
7480        assert_eq!((own.friction, own.base, own.parasitic), (0.0, 0.0, 0.0));
7481        assert_eq!(share(&after, "fins"), share(&before, "fins"));
7482        close(
7483            with_tail,
7484            total - share(&before, "tail").zero_lift_coefficient + step + 0.2,
7485            1e-12,
7486            "tail",
7487        );
7488
7489        // Covering its children, the fins go too.
7490        tail.stages[0].components[2].drag_override = stated(0.2, true);
7491        let (after, _) = shares(&tail);
7492        assert_eq!(share(&after, "fins").zero_lift_coefficient, 0.0);
7493
7494        // A lug and two buttons on the body: each counted per instance when stated, and gone
7495        // with the body's drag when it covers its children.
7496        let mut rails = plain.clone();
7497        rails.stages[0].components[1].children = vec![
7498            component(
7499                "lug",
7500                Part::LaunchLug(LaunchLug {
7501                    length_m: 0.05,
7502                    outer_radius_m: 0.004,
7503                    thickness_m: 0.0005,
7504                    angle_rad: 0.0,
7505                    count: 1,
7506                    spacing_m: 0.0,
7507                    material: material(),
7508                }),
7509                Some(Position::Middle { aft_offset_m: 0.0 }),
7510            ),
7511            component(
7512                "buttons",
7513                Part::RailButton(RailButton {
7514                    outer_diameter_m: 0.01,
7515                    inner_diameter_m: 0.006,
7516                    height_m: 0.008,
7517                    base_height_m: 0.002,
7518                    flange_height_m: 0.002,
7519                    screw_height_m: 0.0,
7520                    angle_rad: 0.0,
7521                    count: 2,
7522                    spacing_m: 0.2,
7523                    material: material(),
7524                }),
7525                Some(Position::Middle { aft_offset_m: 0.0 }),
7526            ),
7527        ];
7528        let (before_rails, total_rails) = shares(&rails);
7529        for id in ["lug", "buttons"] {
7530            assert!(share(&before_rails, id).zero_lift_coefficient > 0.0, "{id}");
7531        }
7532        rails.stages[0].components[1].children[1].drag_override = stated(0.5, false);
7533        let (after, _) = shares(&rails);
7534        close(share(&after, "buttons").stated, 1.0, 1e-15, "per button");
7535        rails.stages[0].components[1].children[1].drag_override = None;
7536        rails.stages[0].components[1].drag_override = stated(0.2, true);
7537        let (after, with) = shares(&rails);
7538        for id in ["lug", "buttons"] {
7539            assert_eq!(share(&after, id).zero_lift_coefficient, 0.0, "{id}");
7540        }
7541        close(
7542            with,
7543            total_rails
7544                - share(&before_rails, "body").zero_lift_coefficient
7545                - share(&before_rails, "lug").zero_lift_coefficient
7546                - share(&before_rails, "buttons").zero_lift_coefficient
7547                - step
7548                + 0.2,
7549            1e-12,
7550            "body covering its lug and buttons",
7551        );
7552
7553        // A stage's coefficient adds a term; covering everything, it is the whole drag.
7554        let mut stage = plain.clone();
7555        stage.stages[0].drag_override = stated(0.1, false);
7556        let (after, with) = shares(&stage);
7557        close(share(&after, "stage").stated, 0.1, 1e-15, "stage");
7558        close(with, total + 0.1, 1e-12, "stage added");
7559        stage.stages[0].drag_override = stated(0.1, true);
7560        let (_, with) = shares(&stage);
7561        close(with, 0.1, 1e-15, "stage alone");
7562
7563        // The drag scale scales it with the rest.
7564        let m = model(&stage).with_drag_scale(2.0).unwrap();
7565        let conditions = DragConditions::coasting(0.3 * 340.294 / 1.4607e-5);
7566        let scaled = m.drag(&Flow::axial(0.3), &conditions).unwrap();
7567        close(scaled.zero_lift_coefficient, 0.2, 1e-15, "scaled");
7568    }
7569
7570    /// A stated coefficient that is negative or not a number is refused by name, and so is one on
7571    /// a pod set or in a pod, which OpenRocket hasn't been measured on (ADR-167).
7572    #[test]
7573    fn a_stated_drag_coefficient_out_of_range_or_in_a_pod_is_refused() {
7574        for bad in [-0.1, f64::NAN, f64::INFINITY] {
7575            let mut rocket = stepped_rocket();
7576            rocket.stages[0].components[1].drag_override = stated(bad, false);
7577            match AeroModel::new(&rocket.layout().unwrap()) {
7578                Err(AeroError::InComponent { id, source }) => {
7579                    assert_eq!(id, "body");
7580                    assert!(
7581                        matches!(
7582                            *source,
7583                            AeroError::Domain {
7584                                what: "stated drag coefficient",
7585                                ..
7586                            }
7587                        ),
7588                        "{source:?}"
7589                    );
7590                }
7591                other => panic!("{bad}: {other:?}"),
7592            }
7593        }
7594        let mut rocket = stepped_rocket();
7595        rocket.stages[0].drag_override = stated(-1.0, true);
7596        assert!(matches!(
7597            AeroModel::new(&rocket.layout().unwrap()),
7598            Err(AeroError::InComponent { ref id, .. }) if id == "stage"
7599        ));
7600        // Refused wherever it is, even where it would change nothing: an inner part, a covered
7601        // fin set.
7602        let mut rocket = stepped_rocket();
7603        rocket.stages[0].components[2].drag_override = stated(0.1, true);
7604        rocket.stages[0].components[2].children[0].drag_override = stated(f64::NAN, false);
7605        assert!(matches!(
7606            AeroModel::new(&rocket.layout().unwrap()),
7607            Err(AeroError::InComponent { ref id, .. }) if id == "fins"
7608        ));
7609        let refused = |rocket: &hpr_design::Rocket, why: &str| match AeroModel::new(
7610            &rocket.layout().unwrap(),
7611        ) {
7612            Err(AeroError::InComponent { source, .. }) => {
7613                assert!(
7614                    matches!(*source, AeroError::Unsupported(ref what) if what == why),
7615                    "{source:?}"
7616                );
7617            }
7618            other => panic!("{why}: {other:?}"),
7619        };
7620        for (pod_set, part) in [(true, 0), (false, 1)] {
7621            let mut rocket = podded_rocket(2);
7622            let pods = rocket.stages[0].components[1].children.last_mut().unwrap();
7623            if pod_set {
7624                pods.drag_override = stated(0.1, true);
7625            } else {
7626                pods.children[part].drag_override = stated(0.1, false);
7627            }
7628            refused(&rocket, "a drag override on a pod set or in a pod");
7629        }
7630        // Covering a pod set, from the body it is on or from the stage.
7631        let mut rocket = podded_rocket(2);
7632        rocket.stages[0].components[1].drag_override = stated(0.1, true);
7633        refused(&rocket, "a drag override covering a pod set");
7634        let mut rocket = podded_rocket(2);
7635        rocket.stages[0].drag_override = stated(0.1, true);
7636        refused(&rocket, "a drag override covering a pod set");
7637        // Not covering, the pods keep their own drag.
7638        let mut rocket = podded_rocket(2);
7639        rocket.stages[0].components[1].drag_override = stated(0.1, false);
7640        assert!(AeroModel::new(&rocket.layout().unwrap()).is_ok());
7641        // A tube fin set's, never measured.
7642        let mut rocket = tube_finned_rocket(6, 0.0762, 0.011, 0.0005);
7643        rocket.stages[0].components[3].children[1].drag_override = stated(0.1, false);
7644        refused(&rocket, "a drag override on a tube fin set");
7645    }
7646
7647    /// A layout whose parents loop, which `Rocket::layout` never makes, still builds a model in
7648    /// finite time: the walk up to a covering override stops after one step per component.
7649    #[test]
7650    fn a_looped_layout_does_not_hang_the_override_walk() {
7651        let mut lugged = stepped_rocket();
7652        lugged.stages[0].components[1].children.push(component(
7653            "lug",
7654            Part::LaunchLug(LaunchLug {
7655                length_m: 0.05,
7656                outer_radius_m: 0.004,
7657                thickness_m: 0.0005,
7658                angle_rad: 0.0,
7659                count: 1,
7660                spacing_m: 0.0,
7661                material: material(),
7662            }),
7663            Some(Position::Middle { aft_offset_m: 0.0 }),
7664        ));
7665        let mut layout = lugged.layout().unwrap();
7666        let (lug, _) = layout.find("lug").unwrap();
7667        layout.components[lug].parent = Some(lug);
7668        // Built or refused, it returns.
7669        let _ = AeroModel::new(&layout);
7670    }
7671
7672    /// A part whose drag is stated is never computed: a shape the buildup has no curve for flies.
7673    #[test]
7674    fn a_stated_drag_coefficient_flies_a_shape_the_buildup_refuses() {
7675        let mut rocket = stepped_rocket();
7676        // A bulged secant ogive, which the buildup refuses (ADR-028).
7677        rocket.stages[0].components[0].part =
7678            nose(NoseShape::Ogive { radius_ratio: 0.8 }, 0.25, 0.027);
7679        let conditions = DragConditions::coasting(0.3 * 340.294 / 1.4607e-5);
7680        assert!(matches!(
7681            model(&rocket).drag(&Flow::axial(0.3), &conditions),
7682            Err(AeroError::InComponent { .. })
7683        ));
7684        rocket.stages[0].components[0].drag_override = stated(0.3, false);
7685        let (parts, _) = shares(&rocket);
7686        close(
7687            share(&parts, "nose").zero_lift_coefficient,
7688            0.3,
7689            1e-15,
7690            "nose",
7691        );
7692    }
7693}