Skip to main content

hpr_design/
config.rs

1//! Motor mounts, configurations and the assembled rocket: the structure with its motors placed,
2//! and its mass properties through the burn.
3//!
4//! **Placement.** A motor's axis runs forward from its nozzle exit ([`hpr_motor::mass`]). In a
5//! mount whose axial extent ends at station `s_aft`, the nozzle exit sits at station
6//! `s_aft + overhang`, on the mount's axis (an inner tube's radial offset and angle, or the body
7//! axis). A motor element at `z_m` along the motor axis is then at body
8//! `(x_mount, y_mount, −(s_aft + overhang) + z_m)` ([`MassProperties::from_motor_element`]).
9//!
10//! **Composition.** The rocket at time `t` is the structure ([`Layout::structure`]) combined with
11//! each motor's loaded, burning or spent mass properties ([`SolidMotor::state`]) at its own time
12//! since ignition. [`Assembly::mass_properties`] lights every motor at `t = 0`;
13//! [`Assembly::mass_properties_lit`] takes each motor's ignition time ([`Ignition`], resolved by
14//! [`Assembly::ignition_times_s`]), and a motor not yet lit is loaded. This is RocketPy's
15//! composition (`Rocket.total_mass`, `center_of_mass`, and the inertias of
16//! `rocketpy/rocket/rocket.py`), checked against RocketPy 1.13.0 in the tests.
17//!
18//! See `docs/physics/design.md`.
19
20use std::collections::BTreeSet;
21use std::sync::Arc;
22
23use hpr_core::DVec3;
24use hpr_motor::{Delay, MassElement, SolidMotor};
25use serde::{Deserialize, Serialize};
26
27use crate::error::DesignError;
28use crate::mass::MassProperties;
29use crate::shapes::check_dimension;
30use crate::tree::{Layout, Rocket, StageMasses};
31
32/// Makes a body tube or inner tube a motor mount.
33#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
34#[serde(deny_unknown_fields)]
35pub struct MotorMount {
36    /// How far the nozzle exit sits aft of the mount's aft end, m (negative when recessed).
37    #[serde(default)]
38    pub overhang_m: f64,
39}
40
41/// A set of motors to fly with: at most one per mount. A mount that is a cluster
42/// ([`InnerTube::cluster_m`](crate::InnerTube::cluster_m)) takes its motor in every tube.
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
44#[serde(deny_unknown_fields)]
45pub struct Configuration {
46    /// Unique id among the configurations.
47    pub id: String,
48    /// Name.
49    #[serde(default)]
50    pub name: String,
51    /// The motors.
52    pub motors: Vec<MountedMotor>,
53}
54
55/// When a motor lights, on the flight's clock: `t = 0` is launch, when the motors that light at
56/// launch ignite. A delay is counted from its event (the decision record on staging,
57/// [ADR-074][adr-074]).
58///
59/// [adr-074]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-074-ignition-times-and-powered-staging-the-sustainer-flies-on-as-a-rigid-body-2026-09-25
60#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
61#[serde(rename_all = "snake_case", deny_unknown_fields)]
62#[non_exhaustive]
63pub enum Ignition {
64    /// At launch, `t = 0`.
65    #[default]
66    Launch,
67    /// At a time after launch: an air start on a timer.
68    Time {
69        /// The time after launch, s.
70        time_s: f64,
71    },
72    /// A delay after another mount's motor burns out: a sustainer lit by the booster's burnout,
73    /// or by its ejection charge with the charge's delay.
74    Burnout {
75        /// The id of the mount whose motor's burnout lights this one.
76        mount: String,
77        /// The delay after that burnout, s.
78        delay_s: f64,
79    },
80    /// A delay after the stage aft of this motor's stage separates from it (the flight gives the
81    /// separation). A motor whose stage is never freed never lights; one in the last stage, with
82    /// nothing aft of it to separate, is refused.
83    Separation {
84        /// The delay after the separation, s.
85        delay_s: f64,
86    },
87    /// Never: the motor stays loaded and gives no thrust all flight, as if every tube of its mount
88    /// were listed in [`MountedMotor::failed_tubes`]. A `.ork` design can set a motor so, or light
89    /// it at an event that never comes, and OpenRocket then flies it unlit.
90    Never,
91}
92
93impl Ignition {
94    /// Whether this is [`Ignition::Launch`].
95    #[must_use]
96    pub fn is_launch(&self) -> bool {
97        *self == Self::Launch
98    }
99}
100
101/// A motor in a mount.
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
103#[serde(deny_unknown_fields)]
104pub struct MountedMotor {
105    /// The id of the mount component.
106    pub mount: String,
107    /// Designation, for display.
108    #[serde(default)]
109    pub designation: String,
110    /// Case outer diameter, m.
111    pub diameter_m: f64,
112    /// Case length, m.
113    pub length_m: f64,
114    /// The motor.
115    pub motor: SolidMotor,
116    /// The ejection delay chosen, if any.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub delay: Option<Delay>,
119    /// When it lights.
120    #[serde(default, skip_serializing_if = "Ignition::is_launch")]
121    pub ignition: Ignition,
122    /// The tubes whose motor fails to light, by index into the mount's tubes (a cluster's in the
123    /// order of [`InnerTube::cluster_m`](crate::InnerTube::cluster_m), `0` for a single tube; a
124    /// cluster inside another cluster counts the outer copies first, each with all its tubes; a
125    /// mount in a pod counts the pods, in the order of [`PodSet::pods`](crate::PodSet::pods)): a
126    /// motor out. Each is carried loaded and gives no thrust. An ignition on the mount's burnout
127    /// takes its first motor that lights, but a recovery device or separation triggered by one
128    /// motor's index waits on that motor alone: point it at a tube that lights, or it never fires.
129    /// Empty (the default) when every motor lights.
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub failed_tubes: Vec<usize>,
132}
133
134/// A motor placed in the rocket: one per tube of its mount, so a cluster's mount gives several,
135/// one after another in the order of its tubes.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct PlacedMotor {
138    /// The mount's id.
139    pub mount: String,
140    /// Index of the mount's stage.
141    pub stage: usize,
142    /// The nozzle exit's position in body axes, m.
143    pub nozzle_m: DVec3,
144    /// The motor as configured.
145    pub mounted: MountedMotor,
146    /// Which of the mount's tubes it is in (`0` for a single tube).
147    #[serde(default)]
148    pub tube: usize,
149    /// Whether it never lights: its tube fails ([`MountedMotor::failed_tubes`]), or the motor is
150    /// set never to light ([`Ignition::Never`]).
151    #[serde(default)]
152    pub fails: bool,
153}
154
155impl PlacedMotor {
156    /// Station of the nozzle exit, m aft of the nose tip.
157    pub fn nozzle_station_m(&self) -> f64 {
158        -self.nozzle_m.z
159    }
160
161    /// Station of the motor case's forward end, m.
162    pub fn fore_station_m(&self) -> f64 {
163        self.nozzle_station_m() - self.mounted.length_m
164    }
165
166    /// A motor-axis mass element in body axes.
167    pub fn place(&self, element: &MassElement) -> MassProperties {
168        MassProperties::from_motor_element(element, self.nozzle_m.z).translated(DVec3::new(
169            self.nozzle_m.x,
170            self.nozzle_m.y,
171            0.0,
172        ))
173    }
174
175    /// The whole motor at `t_s` seconds after ignition, in body axes.
176    pub fn mass_properties(&self, t_s: f64) -> MassProperties {
177        self.place(&self.mounted.motor.state(t_s).total)
178    }
179
180    /// The whole motor at flight time `t_s` when it lit at `ignition_s` (`None`: it never lights),
181    /// in body axes: loaded before it lights.
182    pub fn mass_properties_lit(&self, t_s: f64, ignition_s: Option<f64>) -> MassProperties {
183        let since_s = ignition_s.map_or(0.0, |ignition_s| (t_s - ignition_s).max(0.0));
184        self.mass_properties(since_s)
185    }
186
187    /// The motor's dry mass (case, closures, nozzle) in body axes.
188    pub fn dry_mass_properties(&self) -> MassProperties {
189        self.place(&self.mounted.motor.dry())
190    }
191}
192
193/// A rocket with one configuration's motors in place.
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195pub struct Assembly {
196    /// The configuration's id.
197    pub configuration: String,
198    /// The resolved structure.
199    pub layout: Layout,
200    /// The motors.
201    pub motors: Vec<PlacedMotor>,
202}
203
204impl Assembly {
205    /// The rocket `t_s` seconds after ignition: the structure and every motor, but for a motor
206    /// that fails ([`PlacedMotor::fails`]), which stays loaded. Every other motor is taken as lit,
207    /// even one waiting on a mount whose every motor fails; [`Self::mass_properties_lit`] with
208    /// [`Self::ignition_times_s`] gives the flight's.
209    pub fn mass_properties(&self, t_s: f64) -> MassProperties {
210        self.motors
211            .iter()
212            .fold(self.layout.structure, |sum, motor| {
213                let ignition = (!motor.fails).then_some(0.0);
214                MassProperties::combine([&sum, &motor.mass_properties_lit(t_s, ignition)])
215            })
216    }
217
218    /// The rocket at flight time `t_s`, each motor lit at its `ignition_s`, one per motor in
219    /// order ([`Self::ignition_times_s`]): `None` for one that never lights, which stays loaded.
220    /// A motor past the end of `ignition_s` is taken as lit at launch, as
221    /// [`Self::mass_properties`] lights them all.
222    pub fn mass_properties_lit(&self, t_s: f64, ignition_s: &[Option<f64>]) -> MassProperties {
223        self.mass_properties_lit_on(self.layout.structure, t_s, ignition_s)
224    }
225
226    /// As [`Self::mass_properties_lit`], with `structure` in place of the layout's: the
227    /// structure with a part taken out, say ([`MassProperties::without_part`]).
228    pub fn mass_properties_lit_on(
229        &self,
230        structure: MassProperties,
231        t_s: f64,
232        ignition_s: &[Option<f64>],
233    ) -> MassProperties {
234        self.motors
235            .iter()
236            .enumerate()
237            .fold(structure, |sum, (index, motor)| {
238                let ignition = ignition_s.get(index).copied().unwrap_or(Some(0.0));
239                MassProperties::combine([&sum, &motor.mass_properties_lit(t_s, ignition)])
240            })
241    }
242
243    /// Each motor's ignition time on the flight's clock, in order: `None` for one that never
244    /// lights. `separated_s(stage)` gives the time at which the stage aft of `stage` came away, if
245    /// it has; [`Ignition::Separation`] counts from it.
246    ///
247    /// A motor lit by another mount's burnout lights when one of that mount's motors that lights
248    /// has a known ignition; a chain that never reaches a known time (a cycle is refused by
249    /// [`Layout::place_motors`], so only a separation that never comes, or a mount whose every
250    /// motor fails) leaves it unlit. A motor that fails ([`PlacedMotor::fails`]) never lights.
251    #[must_use]
252    pub fn ignition_times_s(&self, separated_s: impl Fn(usize) -> Option<f64>) -> Vec<Option<f64>> {
253        ignition_times_s(&self.motors, separated_s, true)
254    }
255
256    /// The rocket with every motor spent: the structure and the motors' dry masses, but for a
257    /// motor that fails ([`PlacedMotor::fails`]), which is carried loaded.
258    pub fn dry_mass_properties(&self) -> MassProperties {
259        self.motors
260            .iter()
261            .fold(self.layout.structure, |sum, motor| {
262                let motor = if motor.fails {
263                    motor.mass_properties_lit(0.0, None)
264                } else {
265                    motor.dry_mass_properties()
266                };
267                MassProperties::combine([&sum, &motor])
268            })
269    }
270}
271
272/// As [`Assembly::ignition_times_s`], over `motors`; with `failures` false, as if every motor
273/// lit.
274fn ignition_times_s(
275    motors: &[PlacedMotor],
276    separated_s: impl Fn(usize) -> Option<f64>,
277    failures: bool,
278) -> Vec<Option<f64>> {
279    let fails = |motor: &PlacedMotor| failures && motor.fails;
280    let mut times: Vec<Option<f64>> = motors
281        .iter()
282        .map(|motor| match &motor.mounted.ignition {
283            _ if fails(motor) => None,
284            Ignition::Launch => Some(0.0),
285            Ignition::Time { time_s } => Some(*time_s),
286            Ignition::Separation { delay_s } => separated_s(motor.stage).map(|t| t + delay_s),
287            Ignition::Burnout { .. } => None,
288            // Taken as lit only for the check of a cycle of burnouts, where every motor is.
289            Ignition::Never => (!failures).then_some(0.0),
290        })
291        .collect();
292    // Each pass resolves at least one more link of every chain that can resolve, so as many
293    // passes as there are motors settle them all.
294    for _ in 0..motors.len() {
295        let mut changed = false;
296        for (index, motor) in motors.iter().enumerate() {
297            let Ignition::Burnout { mount, delay_s } = &motor.mounted.ignition else {
298                continue;
299            };
300            if times[index].is_some() || fails(motor) {
301                continue;
302            }
303            // Every motor of a mount lights together, so the first that lights gives the burnout.
304            let lit = motors
305                .iter()
306                .zip(&times)
307                .filter(|(other, _)| other.mount == *mount)
308                .find_map(|(other, time)| time.map(|t| t + other.mounted.motor.burnout_time_s()));
309            if let Some(burnout_s) = lit {
310                times[index] = Some(burnout_s + delay_s);
311                changed = true;
312            }
313        }
314        if !changed {
315            break;
316        }
317    }
318    times
319}
320
321impl Layout {
322    /// Places `configuration`'s motors in their mounts in this layout.
323    ///
324    /// # Errors
325    ///
326    /// - [`DesignError::UnknownId`] for a mount that doesn't exist.
327    /// - [`DesignError::Tree`] for a mount that isn't a motor mount, or two motors in one mount.
328    /// - [`DesignError::InComponent`] (with the mount's id) wrapping [`DesignError::Domain`] for a
329    ///   non-positive or non-finite motor diameter or length, or a non-finite overhang, or an
330    ///   ignition time or delay that is negative or not finite.
331    /// - [`DesignError::Tree`] for an ignition by the burnout of a mount with no motor in this
332    ///   configuration, or by a chain of burnouts that comes back to the motor itself.
333    /// - [`DesignError::InComponent`] (with the mount's id) wrapping [`DesignError::Domain`] for a
334    ///   failed tube the mount doesn't have, or one named twice, or a cluster offset that is not
335    ///   finite.
336    pub fn place_motors(
337        &self,
338        configuration: &Configuration,
339    ) -> Result<Vec<PlacedMotor>, DesignError> {
340        let mut mounts = BTreeSet::new();
341        let mut motors = Vec::with_capacity(configuration.motors.len());
342        for mounted in &configuration.motors {
343            let (_, mount) = self
344                .find(&mounted.mount)
345                .ok_or_else(|| DesignError::UnknownId {
346                    what: "motor mount",
347                    id: mounted.mount.clone(),
348                })?;
349            let in_mount = |error| DesignError::InComponent {
350                id: mount.id.clone(),
351                source: Box::new(error),
352            };
353            check_dimension("motor diameter (m)", mounted.diameter_m, false).map_err(in_mount)?;
354            check_dimension("motor length (m)", mounted.length_m, false).map_err(in_mount)?;
355            let Some(spec) = mount.motor_mount else {
356                return Err(DesignError::Tree {
357                    id: mount.id.clone(),
358                    message: format!(
359                        "configuration {} puts a motor here, but it is not a motor mount",
360                        configuration.id
361                    ),
362                });
363            };
364            if !mounts.insert(mount.id.as_str()) {
365                return Err(DesignError::Tree {
366                    id: mount.id.clone(),
367                    message: format!(
368                        "configuration {} puts two motors in this mount",
369                        configuration.id
370                    ),
371                });
372            }
373            if !spec.overhang_m.is_finite() {
374                return Err(in_mount(DesignError::Domain {
375                    what: "motor overhang (m)",
376                    value: spec.overhang_m,
377                }));
378            }
379            match &mounted.ignition {
380                Ignition::Launch => {}
381                Ignition::Time { time_s: value } => {
382                    check_ignition("ignition time after launch (s)", *value).map_err(in_mount)?;
383                }
384                Ignition::Burnout { delay_s: value, .. } => {
385                    check_ignition("ignition delay (s)", *value).map_err(in_mount)?;
386                }
387                Ignition::Separation { delay_s: value } => {
388                    check_ignition("ignition delay (s)", *value).map_err(in_mount)?;
389                    if mount.stage + 1 >= self.stages.len() {
390                        return Err(DesignError::Tree {
391                            id: mount.id.clone(),
392                            message: format!(
393                                "configuration {} lights this motor at its stage's separation, \
394                                 but no stage is aft of it to separate",
395                                configuration.id
396                            ),
397                        });
398                    }
399                }
400                Ignition::Never => {}
401            }
402            let tubes = mount.contents_copies().map_err(in_mount)?;
403            for (k, &tube) in mounted.failed_tubes.iter().enumerate() {
404                if tube >= tubes.len() || mounted.failed_tubes[..k].contains(&tube) {
405                    return Err(in_mount(DesignError::Domain {
406                        what: "failed tube (index into the mount's tubes, each named once)",
407                        value: tube as f64,
408                    }));
409                }
410            }
411            let axis = mount.part.axis_offset_m();
412            let z = -(mount.aft_station_m() + spec.overhang_m);
413            for (tube, place) in tubes.into_iter().enumerate() {
414                let [x, y] = place.point(axis);
415                motors.push(PlacedMotor {
416                    mount: mount.id.clone(),
417                    stage: mount.stage,
418                    nozzle_m: DVec3::new(x, y, z),
419                    mounted: mounted.clone(),
420                    tube,
421                    fails: mounted.ignition == Ignition::Never
422                        || mounted.failed_tubes.contains(&tube),
423                });
424            }
425        }
426        for motor in &motors {
427            if let Ignition::Burnout { mount, .. } = &motor.mounted.ignition
428                && !motors.iter().any(|other| other.mount == *mount)
429            {
430                return Err(DesignError::Tree {
431                    id: motor.mount.clone(),
432                    message: format!(
433                        "configuration {} lights this motor at the burnout of mount {mount}, \
434                         which holds no motor in it",
435                        configuration.id
436                    ),
437                });
438            }
439        }
440        // With every separation at once and every motor lit, only a cycle of burnouts is left
441        // unlit.
442        let lit = ignition_times_s(&motors, |_| Some(0.0), false);
443        if let Some(index) = lit.iter().position(Option::is_none) {
444            return Err(DesignError::Tree {
445                id: motors[index].mount.clone(),
446                message: format!(
447                    "configuration {} lights this motor by a chain of burnouts that comes back \
448                     to it",
449                    configuration.id
450                ),
451            });
452        }
453        Ok(motors)
454    }
455}
456
457/// An ignition time or delay: finite and not negative.
458fn check_ignition(what: &'static str, value: f64) -> Result<(), DesignError> {
459    if value.is_finite() && value >= 0.0 {
460        Ok(())
461    } else {
462        Err(DesignError::Domain { what, value })
463    }
464}
465
466impl Rocket {
467    /// The configuration with id `id`.
468    pub fn configuration(&self, id: &str) -> Option<&Configuration> {
469        self.configurations.iter().find(|c| c.id == id)
470    }
471
472    /// Checks that configuration ids are unique and non-empty.
473    ///
474    /// # Errors
475    ///
476    /// [`DesignError::DuplicateId`] for the first empty or repeated id.
477    pub fn check_configuration_ids(&self) -> Result<(), DesignError> {
478        let mut ids = BTreeSet::new();
479        for configuration in &self.configurations {
480            if configuration.id.is_empty() || !ids.insert(configuration.id.as_str()) {
481                return Err(DesignError::DuplicateId(configuration.id.clone()));
482            }
483        }
484        Ok(())
485    }
486
487    /// Resolves the tree and places the motors of configuration `configuration_id`.
488    ///
489    /// # Errors
490    ///
491    /// - As [`Rocket::layout`] and [`Layout::place_motors`].
492    /// - [`DesignError::DuplicateId`] for an empty or repeated configuration id.
493    /// - [`DesignError::UnknownId`] for a configuration that doesn't exist.
494    pub fn assemble(&self, configuration_id: &str) -> Result<Assembly, DesignError> {
495        self.check_configuration_ids()?;
496        let configuration = self.configuration_or_error(configuration_id)?;
497        let layout = self.layout()?;
498        let motors = layout.place_motors(configuration)?;
499        Ok(Assembly {
500            configuration: configuration.id.clone(),
501            layout,
502            motors,
503        })
504    }
505
506    /// Lays the design out once ([`Rocket::layout`]), to check it ([`LaidOut::check`]) and
507    /// assemble it ([`LaidOut::into_assembly`]) without laying it out again: the layout is most
508    /// of the cost of either, and a Monte Carlo run builds a flight thousands of times.
509    ///
510    /// # Errors
511    ///
512    /// As [`Rocket::check_configuration_ids`] and [`Rocket::layout`].
513    pub fn lay_out(&self) -> Result<LaidOut, DesignError> {
514        self.clone().into_laid_out()
515    }
516
517    /// As [`Rocket::lay_out`], keeping this copy of the design.
518    fn into_laid_out(self) -> Result<LaidOut, DesignError> {
519        self.check_configuration_ids()?;
520        let (components, masses) = self.placed_components()?;
521        Ok(LaidOut {
522            layout: self.staged_layout(components, &masses)?,
523            rocket: self,
524            masses: Arc::new(masses),
525        })
526    }
527
528    /// Configuration `configuration_id`, or [`DesignError::UnknownId`].
529    fn configuration_or_error(
530        &self,
531        configuration_id: &str,
532    ) -> Result<&Configuration, DesignError> {
533        self.configuration(configuration_id)
534            .ok_or_else(|| DesignError::UnknownId {
535                what: "configuration",
536                id: configuration_id.to_owned(),
537            })
538    }
539}
540
541/// A copy of a design and its layout, laid out once by [`Rocket::lay_out`], to check it and
542/// assemble it ([`LaidOut::into_assembly`]) without laying it out again. Its fields are private,
543/// so the layout is always the design's own.
544#[derive(Debug, Clone)]
545pub struct LaidOut {
546    rocket: Rocket,
547    layout: Layout,
548    /// What the layout's stages are made from, for [`LaidOut::relay`]; shared by the designs
549    /// relaid from it.
550    masses: Arc<StageMasses>,
551}
552
553impl LaidOut {
554    /// The design.
555    pub fn rocket(&self) -> &Rocket {
556        &self.rocket
557    }
558
559    /// The layout ([`Rocket::layout`]).
560    pub fn layout(&self) -> &Layout {
561        &self.layout
562    }
563
564    /// As [`Rocket::assemble`], on this layout, which it takes rather than copies, with the design
565    /// given back.
566    ///
567    /// # Errors
568    ///
569    /// - As [`Layout::place_motors`].
570    /// - [`DesignError::UnknownId`] for a configuration that doesn't exist.
571    pub fn into_assembly(self, configuration_id: &str) -> Result<(Rocket, Assembly), DesignError> {
572        let configuration = self.rocket.configuration_or_error(configuration_id)?;
573        let motors = self.layout.place_motors(configuration)?;
574        let assembly = Assembly {
575            configuration: configuration.id.clone(),
576            layout: self.layout,
577            motors,
578        };
579        Ok((self.rocket, assembly))
580    }
581
582    /// `rocket` laid out, as [`Rocket::lay_out`] lays it out. Where `rocket` differs from this
583    /// design only in its stages' overrides (mass, center of mass, inertia) and its
584    /// configurations (motors), this layout's parts are kept and only the stages are done again,
585    /// which gives the same layout bit for bit when the rest of the two designs is bitwise
586    /// equal, as a copy's is (two values equal under `==` can still differ in a zero's sign):
587    /// placing the parts is most of a layout's cost, and a Monte Carlo sample changes nothing
588    /// else. Any other difference lays `rocket` out from the start.
589    ///
590    /// # Errors
591    ///
592    /// As [`Rocket::lay_out`].
593    pub fn relay(&self, rocket: Rocket) -> Result<LaidOut, DesignError> {
594        if !self.same_but_overrides_and_motors(&rocket) {
595            return rocket.into_laid_out();
596        }
597        rocket.check_configuration_ids()?;
598        let layout = rocket.staged_layout(self.layout.components.clone(), &self.masses)?;
599        Ok(LaidOut {
600            rocket,
601            layout,
602            masses: Arc::clone(&self.masses),
603        })
604    }
605
606    /// Whether `rocket` is this design but for its stages' overrides and its configurations.
607    /// Every other field is compared, so a field added to either type has to be added here.
608    fn same_but_overrides_and_motors(&self, rocket: &Rocket) -> bool {
609        let Rocket {
610            name,
611            stages,
612            reference_diameter,
613            configurations: _,
614        } = rocket;
615        *name == self.rocket.name
616            && *reference_diameter == self.rocket.reference_diameter
617            && stages.len() == self.rocket.stages.len()
618            && stages.iter().zip(&self.rocket.stages).all(|(stage, ours)| {
619                let crate::Stage {
620                    id,
621                    name,
622                    components,
623                    overrides: _,
624                    override_rule: _,
625                    added_mass,
626                    drag_override: _,
627                    parallel,
628                } = stage;
629                *id == ours.id
630                    && *name == ours.name
631                    && *components == ours.components
632                    // Compared, not skipped as the overrides are: `layout` refuses some added
633                    // masses beside a parallel stage, which doing only the stages again would
634                    // not see.
635                    && *added_mass == ours.added_mass
636                    && *parallel == ours.parallel
637            })
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    use hpr_core::DMat3;
644
645    use super::*;
646    use crate::testing::{motor, three_fin_rocket};
647
648    /// Laying a design out once checks and assembles it as [`crate::checks::check`] and
649    /// [`Rocket::assemble`] do, and refuses an unknown configuration the same way.
650    #[test]
651    fn a_design_laid_out_once_checks_and_assembles_as_twice() {
652        let design = three_fin_rocket();
653        let laid_out = design.lay_out().unwrap();
654        assert_eq!(laid_out.layout(), &design.layout().unwrap());
655        assert_eq!(
656            laid_out.check().unwrap(),
657            crate::checks::check(&design).unwrap()
658        );
659        let id = design.configurations[0].id.clone();
660        assert_eq!(
661            laid_out.clone().into_assembly(&id).unwrap(),
662            (design.clone(), design.assemble(&id).unwrap())
663        );
664        assert!(matches!(
665            laid_out.into_assembly("no such configuration"),
666            Err(DesignError::UnknownId { what: "configuration", ref id })
667                if id == "no such configuration"
668        ));
669    }
670
671    /// A design relaid from another's layout is the design laid out alone, bit for bit: with
672    /// other stage overrides and motors, the parts are kept; with another part, it starts over.
673    #[test]
674    fn a_relaid_design_is_laid_out_as_alone() {
675        let nominal = three_fin_rocket();
676        let laid_out = nominal.lay_out().unwrap();
677        let id = nominal.configurations[0].id.clone();
678        let same = |relaid: &LaidOut, design: &Rocket| {
679            let alone = design.lay_out().unwrap();
680            assert_eq!(relaid.rocket(), design);
681            assert_eq!(relaid.layout(), alone.layout());
682            assert_eq!(relaid.check().unwrap(), alone.check().unwrap());
683            assert_eq!(
684                relaid.clone().into_assembly(&id).unwrap(),
685                alone.into_assembly(&id).unwrap()
686            );
687        };
688        let mut overridden = nominal.clone();
689        let stage = &mut overridden.stages[0].overrides;
690        stage.mass_kg = Some(1.234_567);
691        stage.cg_aft_m = Some(0.456_789);
692        stage.cg_xy_m = Some([0.001, -0.002]);
693        let mounted = &mut overridden.configurations[0].motors[0];
694        mounted.motor = motor(&mounted.mount, mounted.diameter_m, 0.25).motor;
695        assert!(laid_out.same_but_overrides_and_motors(&overridden));
696        let relaid = laid_out.relay(overridden.clone()).unwrap();
697        same(&relaid, &overridden);
698        assert_ne!(relaid.layout(), laid_out.layout());
699        // Relaid again, back to the nominal design.
700        same(&relaid.relay(nominal.clone()).unwrap(), &nominal);
701        // Another part: laid out from the start.
702        let mut longer = nominal.clone();
703        let crate::Part::BodyTube(tube) = &mut longer.stages[0].components[1].part else {
704            panic!("the test rocket's second component is its airframe");
705        };
706        tube.length_m += 0.1;
707        assert!(!laid_out.same_but_overrides_and_motors(&longer));
708        let relaid = laid_out.relay(longer.clone()).unwrap();
709        same(&relaid, &longer);
710        // Another stage id, or a stage more: laid out from the start too.
711        let mut renamed = nominal.clone();
712        renamed.stages[0].id = "renamed".to_owned();
713        assert!(!laid_out.same_but_overrides_and_motors(&renamed));
714        same(&laid_out.relay(renamed.clone()).unwrap(), &renamed);
715        let mut staged = nominal.clone();
716        let mut booster = staged.stages[0].clone();
717        booster.id = "booster".to_owned();
718        for (index, component) in booster.components.iter_mut().enumerate() {
719            component.id = format!("booster-{index}");
720            component.children.clear();
721        }
722        booster
723            .components
724            .retain(|c| matches!(c.part, crate::Part::BodyTube(_)));
725        staged.stages.push(booster);
726        assert!(!laid_out.same_but_overrides_and_motors(&staged));
727        let relaid = laid_out.relay(staged.clone()).unwrap();
728        same(&relaid, &staged);
729        assert_eq!(relaid.layout().stages.len(), 2);
730        // Two stages, the second's mass and center overridden: its parts are kept.
731        let mut heavier = staged.clone();
732        heavier.stages[1].overrides.mass_kg = Some(0.75);
733        heavier.stages[1].overrides.cg_aft_m = Some(0.3);
734        assert!(relaid.same_but_overrides_and_motors(&heavier));
735        let twice = relaid.relay(heavier.clone()).unwrap();
736        same(&twice, &heavier);
737        assert_ne!(twice.layout().stages[1], relaid.layout().stages[1]);
738        assert_eq!(twice.layout().stages[0], relaid.layout().stages[0]);
739        assert_ne!(relaid.layout().length_m, laid_out.layout().length_m);
740        // An added mass is not an override: the design is laid out from the start, which checks
741        // what only a whole layout checks (an added mass with no station beside a parallel
742        // stage).
743        let mut added = staged.clone();
744        added.stages[1].added_mass = Some(crate::AddedMass {
745            mass_kg: 0.2,
746            cg_aft_m: None,
747        });
748        assert!(!relaid.same_but_overrides_and_motors(&added));
749        same(&relaid.relay(added.clone()).unwrap(), &added);
750        // A bad override is refused as laying it out alone refuses it.
751        let mut bad = nominal;
752        bad.stages[0].overrides.mass_kg = Some(-1.0);
753        assert_eq!(
754            laid_out.relay(bad.clone()).unwrap_err().to_string(),
755            bad.lay_out().unwrap_err().to_string()
756        );
757    }
758
759    /// The sample rocket's mount spans stations 0.7 to 1.0 with 0.01 m of overhang, so the nozzle
760    /// exit is at 1.01. Its envelope motor (1 kg loaded, 0.5 kg of propellant, 0.2 m long) puts
761    /// dry mass and propellant both 0.1 m forward of the nozzle, at body z = −0.91.
762    #[test]
763    fn motor_sits_at_mount_aft_end_plus_overhang() {
764        let design = three_fin_rocket();
765        let assembly = design.assemble("main").unwrap();
766        let [placed] = &assembly.motors[..] else {
767            panic!("one motor")
768        };
769        assert!((placed.nozzle_station_m() - 1.01).abs() < 1e-15);
770        assert!((placed.fore_station_m() - 0.81).abs() < 1e-15);
771        assert_eq!(placed.stage, 0);
772        assert_eq!((placed.nozzle_m.x, placed.nozzle_m.y), (0.0, 0.0));
773
774        let structure = assembly.layout.structure;
775        let (m_s, z_s) = (structure.mass_kg, structure.cg_m.z);
776        for (t, motor_kg) in [(0.0, 1.0), (0.5, 0.75), (2.0, 0.5)] {
777            let whole = assembly.mass_properties(t);
778            let want_mass = m_s + motor_kg;
779            assert!((whole.mass_kg - want_mass).abs() < 1e-12, "{t}");
780            let want_z = (m_s * z_s + motor_kg * -0.91) / want_mass;
781            assert!((whole.cg_m.z - want_z).abs() < 1e-12, "{t}");
782            // Parallel axis about the rocket's center, from the motor's own moments at `t`. The
783            // launch lug puts the center slightly off the axis, where the motor is not.
784            let state = placed.mounted.motor.state(t).total;
785            let (dx, dy, dz) = (-whole.cg_m.x, -whole.cg_m.y, -0.91 - whole.cg_m.z);
786            let about = structure.inertia_about(whole.cg_m);
787            let transverse =
788                about.x_axis.x + state.transverse_inertia_kg_m2 + motor_kg * (dy * dy + dz * dz);
789            assert!(
790                (whole.inertia_kg_m2.x_axis.x - transverse).abs() < 1e-12 * transverse,
791                "{t}"
792            );
793            let axial = about.z_axis.z + state.axial_inertia_kg_m2 + motor_kg * (dx * dx + dy * dy);
794            assert!(
795                (whole.inertia_kg_m2.z_axis.z - axial).abs() < 1e-12 * axial,
796                "{t}"
797            );
798            assert!(whole.cg_m.x.abs() > 1e-6, "the lug is off the axis");
799        }
800        let dry = assembly.dry_mass_properties();
801        assert!((dry.mass_kg - (m_s + 0.5)).abs() < 1e-12);
802        assert_eq!(dry, assembly.mass_properties(1.0));
803    }
804
805    /// A motor in an inner tube 0.01 m off the axis at 90° sits at `y = 0.01`, and the rocket
806    /// picks up the product of inertia `I_yz = −Σ m y z` that offset makes.
807    #[test]
808    fn motor_in_an_offset_mount_is_off_axis() {
809        let mut design = three_fin_rocket();
810        let mount = &mut design.stages[0].components[1].children[0];
811        if let crate::Part::InnerTube(tube) = &mut mount.part {
812            tube.outer_radius_m = 0.0105;
813            tube.radial_offset_m = 0.01;
814            tube.angle_rad = std::f64::consts::FRAC_PI_2;
815        }
816        // Drop the on-axis centering rings.
817        design.stages[0].components[1].children.drain(1..3);
818        design.configurations[0].motors = vec![motor("mmt", 0.018, 0.1)];
819        let assembly = design.assemble("main").unwrap();
820        let placed = &assembly.motors[0];
821        assert!(placed.nozzle_m.x.abs() < 1e-18);
822        assert!((placed.nozzle_m.y - 0.01).abs() < 1e-18);
823        let m = placed.mass_properties(0.0);
824        assert!((m.cg_m.y - 0.01).abs() < 1e-18);
825        let about_origin = m.inertia_about(DVec3::ZERO);
826        let own = MassProperties {
827            cg_m: DVec3::ZERO,
828            ..m
829        };
830        let offset = about_origin - own.inertia_kg_m2;
831        let want_yz = -m.mass_kg * m.cg_m.y * m.cg_m.z;
832        assert!((offset.z_axis.y - want_yz).abs() < 1e-15, "{offset:?}");
833        // cos 90° is 6e-17, not zero.
834        assert!(offset.y_axis.x.abs() < 1e-18);
835        assert!(assembly.mass_properties(0.0).inertia_kg_m2.z_axis.y.abs() > 1e-6);
836        assert_ne!(m.inertia_kg_m2, DMat3::ZERO);
837    }
838
839    /// The sample rocket with its mount a cluster of `tubes` 18 mm tubes (their axes where
840    /// `tubes` says), holding a 0.1 m envelope motor, and no centering rings.
841    fn clustered(tubes: Vec<[f64; 2]>) -> Rocket {
842        let mut design = three_fin_rocket();
843        let mount = &mut design.stages[0].components[1].children[0];
844        if let crate::Part::InnerTube(tube) = &mut mount.part {
845            tube.outer_radius_m = 0.0095;
846            tube.cluster_m = tubes;
847        }
848        design.stages[0].components[1].children.drain(1..3);
849        design.configurations[0].motors = vec![motor("mmt", 0.018, 0.1)];
850        design
851    }
852
853    /// Three tubes on a ring of radius `d = 0.02` m, at 90°, 210° and 330°.
854    fn ring_of_three() -> Vec<[f64; 2]> {
855        [90.0_f64, 210.0, 330.0]
856            .iter()
857            .map(|a| [0.02 * a.to_radians().cos(), 0.02 * a.to_radians().sin()])
858            .collect()
859    }
860
861    /// A motor in a 3-ring cluster is three motors, one in each tube, their nozzles where the tubes
862    /// are and at the one station. The rocket weighs the structure and all three at every time,
863    /// and about the body's axis its roll inertia is the structure's plus, for each motor, its own
864    /// axial inertia and `m d²`, worked by hand.
865    #[test]
866    fn a_cluster_mount_takes_its_motor_in_every_tube() {
867        let assembly = clustered(ring_of_three()).assemble("main").unwrap();
868        assert_eq!(assembly.motors.len(), 3);
869        for (k, (placed, [x, y])) in assembly.motors.iter().zip(ring_of_three()).enumerate() {
870            assert_eq!((placed.tube, placed.fails), (k, false));
871            assert_eq!(placed.mount, "mmt");
872            assert_eq!((placed.nozzle_m.x, placed.nozzle_m.y), (x, y));
873            assert!((placed.nozzle_station_m() - 1.01).abs() < 1e-15);
874        }
875        let structure = assembly.layout.structure;
876        for (t, motor_kg) in [(0.0, 1.0), (0.5, 0.75), (2.0, 0.5)] {
877            let whole = assembly.mass_properties(t);
878            assert!((whole.mass_kg - (structure.mass_kg + 3.0 * motor_kg)).abs() < 1e-12);
879            let axis = DVec3::new(0.0, 0.0, whole.cg_m.z);
880            let own = assembly.motors[0].mounted.motor.state(t).total;
881            let want = structure.inertia_about(axis).z_axis.z
882                + 3.0 * (own.axial_inertia_kg_m2 + motor_kg * 0.02 * 0.02);
883            let got = whole.inertia_about(axis).z_axis.z;
884            assert!((got - want).abs() < 1e-12 * want, "{t}: {got} vs {want}");
885        }
886    }
887
888    /// A motor out: the tube named in `failed_tubes` keeps its motor loaded and never lights it,
889    /// the others burn. A tube the mount doesn't have, or one named twice, is refused.
890    #[test]
891    fn a_failed_tube_never_lights() {
892        let mut design = clustered(ring_of_three());
893        design.configurations[0].motors[0].failed_tubes = vec![0];
894        let assembly = design.assemble("main").unwrap();
895        let fails: Vec<bool> = assembly.motors.iter().map(|m| m.fails).collect();
896        assert_eq!(fails, [true, false, false]);
897        let lit = assembly.ignition_times_s(|_| None);
898        assert_eq!(lit, [None, Some(0.0), Some(0.0)]);
899        let spent = assembly.mass_properties_lit(2.0, &lit);
900        let structure = assembly.layout.structure.mass_kg;
901        assert!((spent.mass_kg - (structure + 1.0 + 0.5 + 0.5)).abs() < 1e-12);
902        // The loaded motor pulls the center toward its tube, at 90°: +y.
903        let all_burning = assembly.mass_properties_lit(2.0, &[Some(0.0); 3]);
904        assert!(spent.cg_m.y > all_burning.cg_m.y + 1e-4);
905        assert_eq!(assembly.mass_properties(2.0), spent);
906
907        for (failed, value) in [(vec![3], 3.0), (vec![1, 1], 1.0)] {
908            let mut design = clustered(ring_of_three());
909            design.configurations[0].motors[0].failed_tubes = failed;
910            let Err(DesignError::InComponent { id, source }) = design.assemble("main") else {
911                panic!("refused");
912            };
913            assert_eq!(id, "mmt");
914            assert!(
915                matches!(*source, DesignError::Domain { what, value: v }
916                    if what.starts_with("failed tube") && v == value),
917                "{source:?}"
918            );
919        }
920        // One tube is tube 0.
921        let mut design = three_fin_rocket();
922        design.configurations[0].motors[0].failed_tubes = vec![0];
923        let assembly = design.assemble("main").unwrap();
924        assert_eq!(assembly.ignition_times_s(|_| None), [None]);
925        // A motor that never lights is carried loaded, spent or burning as the rest may be.
926        let loaded = MassProperties::combine([
927            &assembly.layout.structure,
928            &assembly.motors[0].mass_properties(0.0),
929        ]);
930        assert_eq!(assembly.dry_mass_properties(), loaded);
931        assert_eq!(assembly.mass_properties(10.0), loaded);
932    }
933
934    #[test]
935    fn bad_configurations_are_refused() {
936        let design = three_fin_rocket();
937        assert!(matches!(
938            design.assemble("missing"),
939            Err(DesignError::UnknownId {
940                what: "configuration",
941                ..
942            })
943        ));
944
945        let mut d = design.clone();
946        d.configurations[0].motors[0].mount = "nowhere".to_owned();
947        assert!(matches!(
948            d.assemble("main"),
949            Err(DesignError::UnknownId {
950                what: "motor mount",
951                ..
952            })
953        ));
954
955        let mut d = design.clone();
956        d.configurations[0].motors[0].mount = "airframe".to_owned();
957        assert!(
958            matches!(d.assemble("main"), Err(DesignError::Tree { ref id, .. }) if id == "airframe")
959        );
960
961        let mut d = design.clone();
962        let second = d.configurations[0].motors[0].clone();
963        d.configurations[0].motors.push(second);
964        assert!(matches!(d.assemble("main"), Err(DesignError::Tree { ref id, .. }) if id == "mmt"));
965
966        let mut d = design.clone();
967        let copy = d.configurations[0].clone();
968        d.configurations.push(copy);
969        assert_eq!(
970            d.assemble("main"),
971            Err(DesignError::DuplicateId("main".to_owned()))
972        );
973
974        let mut d = design.clone();
975        d.configurations[0].motors[0].diameter_m = 0.0;
976        assert!(matches!(
977            d.assemble("main"),
978            Err(DesignError::InComponent { ref id, ref source })
979                if id == "mmt" && matches!(**source, DesignError::Domain { .. })
980        ));
981
982        let mut d = design.clone();
983        d.stages[0].components[1].children[0].motor_mount = Some(MotorMount {
984            overhang_m: f64::NAN,
985        });
986        assert!(matches!(
987            d.assemble("main"),
988            Err(DesignError::InComponent { .. })
989        ));
990
991        // A layout places any configuration handed to it, not only the rocket's own.
992        let layout = design.layout().unwrap();
993        let mut candidate = design.configurations[0].clone();
994        candidate.id = "candidate".to_owned();
995        assert_eq!(layout.place_motors(&candidate).unwrap().len(), 1);
996        candidate.motors[0].mount = "chute".to_owned();
997        assert!(matches!(
998            layout.place_motors(&candidate),
999            Err(DesignError::Tree { ref id, .. }) if id == "chute"
1000        ));
1001    }
1002    /// The RocketPy example designs in `validation/designs/`, by oracle case name.
1003    const ROCKETPY_DESIGNS: [(&str, &str); 13] = [
1004        (
1005            "astra",
1006            include_str!("../../../validation/designs/rocketpy-astra.json"),
1007        ),
1008        (
1009            "andromeda",
1010            include_str!("../../../validation/designs/rocketpy-andromeda.json"),
1011        ),
1012        (
1013            "erebus-11",
1014            include_str!("../../../validation/designs/rocketpy-erebus-11.json"),
1015        ),
1016        (
1017            "calisto-getting-started-motor-at-minus-1.255",
1018            include_str!(
1019                "../../../validation/designs/rocketpy-calisto-getting-started-motor-at-minus-1.255.json"
1020            ),
1021        ),
1022        (
1023            "calisto-tests-motor-at-minus-1.373",
1024            include_str!(
1025                "../../../validation/designs/rocketpy-calisto-tests-motor-at-minus-1.373.json"
1026            ),
1027        ),
1028        (
1029            "bella-lui",
1030            include_str!("../../../validation/designs/rocketpy-bella-lui.json"),
1031        ),
1032        (
1033            "ndrt-2020-nose-to-tail",
1034            include_str!("../../../validation/designs/rocketpy-ndrt-2020-nose-to-tail.json"),
1035        ),
1036        (
1037            "valetudo",
1038            include_str!("../../../validation/designs/rocketpy-valetudo.json"),
1039        ),
1040        (
1041            "juno-iii",
1042            include_str!("../../../validation/designs/rocketpy-juno-iii.json"),
1043        ),
1044        (
1045            "cavour",
1046            include_str!("../../../validation/designs/rocketpy-cavour.json"),
1047        ),
1048        (
1049            "genesis",
1050            include_str!("../../../validation/designs/rocketpy-genesis.json"),
1051        ),
1052        (
1053            "lince",
1054            include_str!("../../../validation/designs/rocketpy-lince.json"),
1055        ),
1056        (
1057            "prometheus-2022-generic-motor",
1058            include_str!("../../../validation/designs/rocketpy-prometheus-2022-generic-motor.json"),
1059        ),
1060    ];
1061
1062    #[derive(Debug, serde::Deserialize)]
1063    struct Oracle {
1064        oracle: String,
1065        cases: Vec<OracleCase>,
1066    }
1067
1068    #[derive(Debug, serde::Deserialize)]
1069    struct OracleCase {
1070        name: String,
1071        rocket: OracleRocket,
1072        motor: serde_json::Value,
1073        geometry: serde_json::Value,
1074        scalars: OracleScalars,
1075        series: OracleSeries,
1076        knot_series: Option<OracleSeries>,
1077    }
1078
1079    #[derive(Debug, serde::Deserialize)]
1080    struct OracleRocket {
1081        mass: f64,
1082        inertia: Vec<f64>,
1083        center_of_mass_without_motor: f64,
1084        coordinate_system_orientation: String,
1085        motor_position: f64,
1086    }
1087
1088    #[derive(Debug, serde::Deserialize)]
1089    #[allow(non_snake_case, reason = "RocketPy's attribute names")]
1090    struct OracleScalars {
1091        dry_mass_kg: f64,
1092        center_of_dry_mass_position_m: f64,
1093        dry_I_11_kg_m2: f64,
1094        dry_I_33_kg_m2: f64,
1095        nozzle_position_m: f64,
1096        propellant_initial_mass_kg: f64,
1097    }
1098
1099    #[derive(Debug, serde::Deserialize)]
1100    #[allow(non_snake_case, reason = "RocketPy's attribute names")]
1101    struct OracleSeries {
1102        time_s: Vec<f64>,
1103        propellant_mass: Vec<f64>,
1104        total_mass: Vec<f64>,
1105        center_of_mass: Vec<f64>,
1106        I_11: Vec<f64>,
1107        I_33: Vec<f64>,
1108        I_11_about_cg: Vec<f64>,
1109    }
1110
1111    /// The largest error seen for each quantity, with where.
1112    #[derive(Default)]
1113    struct Worst(Vec<(&'static str, f64, String)>);
1114
1115    impl Worst {
1116        fn see(&mut self, what: &'static str, error: f64, at: impl Fn() -> String) {
1117            assert!(error.is_finite(), "{what}: {}", at());
1118            match self.0.iter_mut().find(|w| w.0 == what) {
1119                Some(w) if error > w.1 => (w.1, w.2) = (error, at()),
1120                Some(_) => {}
1121                None => self.0.push((what, error, at())),
1122            }
1123        }
1124    }
1125
1126    fn relative(got: f64, want: f64) -> f64 {
1127        ((got - want) / want).abs()
1128    }
1129
1130    fn number(v: &serde_json::Value, key: &str) -> f64 {
1131        v[key]
1132            .as_f64()
1133            .unwrap_or_else(|| panic!("fixture motor `{key}`"))
1134    }
1135
1136    /// M1.4b's done-when: mass, center of mass and inertia match RocketPy's example rockets. The
1137    /// fixture comes from `validation/oracles/rocketpy/rocket_mass.py` (RocketPy 1.13.0), which
1138    /// builds each example rocket from its own inputs, with the bundled public-domain curve nearest
1139    /// in impulse in place of the example's thrust file (whose terms are unclear; ADR-007). Its
1140    /// docstring lists the examples left out and why.
1141    ///
1142    /// The designs in `validation/designs/` are generated by `cargo xtask designs`. This test
1143    /// derives the mass inputs again from the fixture, independently of that generator: the stage
1144    /// override, the nozzle station through RocketPy's placement rule
1145    /// (`rocket.py:1113-1125`: `z = p + s·z_m`, `s` the product of the two orientation signs), and
1146    /// the motor's grains or column, dry mass and curve. Then it compares, at 103 times through the
1147    /// burn and after it and at up to 60 of RocketPy's LSODA knots: total mass, the center of mass
1148    /// (as a station, relative to the rocket's length), `I_11` about the center of dry mass
1149    /// (RocketPy's reference point), `I_11` about the center of mass, `I_33`, and the propellant
1150    /// mass, plus the dry scalars.
1151    #[test]
1152    fn matches_rocketpy_example_rockets() {
1153        let oracle: Oracle = serde_json::from_str(include_str!(
1154            "../../../validation/fixtures/design/rocketpy-rocket-mass.json"
1155        ))
1156        .unwrap();
1157        assert_eq!(oracle.oracle, "rocketpy 1.13.0");
1158        assert_eq!(oracle.cases.len(), ROCKETPY_DESIGNS.len());
1159        let catalog = hpr_motor::Catalog::bundled().unwrap();
1160        let mut worst = Worst::default();
1161        for case in &oracle.cases {
1162            let (_, text) = ROCKETPY_DESIGNS
1163                .iter()
1164                .find(|(name, _)| *name == case.name)
1165                .unwrap_or_else(|| panic!("no design for {}", case.name));
1166            let design: Rocket = serde_json::from_str(text).unwrap();
1167            let assembly = design.assemble("example").unwrap();
1168            let name = case.name.as_str();
1169
1170            // Stations aft of the nose tip, from RocketPy coordinates.
1171            let tip = case.geometry["nose"]["position"].as_f64().unwrap();
1172            let rocket_sign = match case.rocket.coordinate_system_orientation.as_str() {
1173                "tail_to_nose" => 1.0,
1174                "nose_to_tail" => -1.0,
1175                other => panic!("{other}"),
1176            };
1177            let station = |z: f64| rocket_sign * (tip - z);
1178
1179            // The stage override is the example's rocket without its motor.
1180            let overrides = design.stages[0].overrides;
1181            assert_eq!(overrides.mass_kg, Some(case.rocket.mass), "{name}");
1182            assert_eq!(overrides.cg_xy_m, Some([0.0, 0.0]), "{name}: on the axis");
1183            let cg_aft = overrides.cg_aft_m.unwrap();
1184            assert!(
1185                (cg_aft - station(case.rocket.center_of_mass_without_motor)).abs() < 1e-12,
1186                "{name}"
1187            );
1188            let [i11, i22, i33] = case.rocket.inertia[..] else {
1189                panic!("{name}: inertia")
1190            };
1191            assert_eq!(i11, i22);
1192            assert_eq!(
1193                overrides.inertia,
1194                Some(crate::InertiaOverride::axisymmetric(i33, i11)),
1195                "{name}"
1196            );
1197
1198            // The motor: RocketPy's inputs on hpr's axis, forward of the nozzle exit.
1199            let m = &case.motor;
1200            let motor_sign = match m["coordinate_system_orientation"].as_str().unwrap() {
1201                "nozzle_to_combustion_chamber" => 1.0,
1202                "combustion_chamber_to_nozzle" => -1.0,
1203                other => panic!("{other}"),
1204            };
1205            let nozzle = number(m, "nozzle_position");
1206            let to_motor_axis = |z: f64| motor_sign * (z - nozzle);
1207            let [placed] = &assembly.motors[..] else {
1208                panic!("{name}: one motor")
1209            };
1210            let rocketpy_nozzle = case.rocket.motor_position + rocket_sign * motor_sign * nozzle;
1211            assert!(
1212                (rocketpy_nozzle - case.scalars.nozzle_position_m).abs() < 1e-12,
1213                "{name}"
1214            );
1215            assert!(
1216                (placed.nozzle_station_m() - station(rocketpy_nozzle)).abs() < 1e-12,
1217                "{name}: nozzle at {} vs {}",
1218                placed.nozzle_station_m(),
1219                station(rocketpy_nozzle)
1220            );
1221            let motor = &placed.mounted.motor;
1222            let file = m["thrust_file"].as_str().unwrap();
1223            let (entry, curve) = catalog
1224                .motors
1225                .iter()
1226                .find_map(|e| e.curves.iter().find(|c| c.file == file).map(|c| (e, c)))
1227                .unwrap();
1228            assert_eq!(curve.sha256, m["thrust_file_sha256"].as_str().unwrap());
1229            let bundled = entry
1230                .thrust_curve(
1231                    curve,
1232                    hpr_motor::catalog::bundled_curve_text(&curve.file).unwrap(),
1233                )
1234                .unwrap();
1235            assert_eq!(motor.curve(), &bundled, "{name}: the bundled curve");
1236            let dry = motor.dry();
1237            // hpr's motor needs a positive dry mass: the generator gives Cavour's massless dry
1238            // parts 1e-15 kg.
1239            let example_dry = number(m, "dry_mass");
1240            let expected_dry = if example_dry == 0.0 {
1241                1e-15
1242            } else {
1243                example_dry
1244            };
1245            assert_eq!(dry.mass_kg, expected_dry, "{name}");
1246            let dry_inertia: Vec<f64> = m["dry_inertia"]
1247                .as_array()
1248                .unwrap()
1249                .iter()
1250                .map(|v| v.as_f64().unwrap())
1251                .collect();
1252            assert_eq!(dry.transverse_inertia_kg_m2, dry_inertia[0], "{name}");
1253            assert_eq!(dry.axial_inertia_kg_m2, dry_inertia[2], "{name}");
1254            match (m["motor_kind"].as_str().unwrap(), motor.propellant()) {
1255                ("solid", hpr_motor::Propellant::Grains(g)) => {
1256                    assert_eq!(
1257                        *g,
1258                        hpr_motor::BatesGrains {
1259                            count: u32::try_from(m["grain_number"].as_u64().unwrap()).unwrap(),
1260                            density_kg_m3: number(m, "grain_density"),
1261                            outer_radius_m: number(m, "grain_outer_radius"),
1262                            initial_inner_radius_m: number(m, "grain_initial_inner_radius"),
1263                            initial_height_m: number(m, "grain_initial_height"),
1264                            separation_m: number(m, "grain_separation"),
1265                            center_m: to_motor_axis(number(m, "grains_center_of_mass_position")),
1266                            inhibited_ends: m["only_radial_burn"].as_bool().unwrap(),
1267                        },
1268                        "{name}"
1269                    );
1270                    assert!(
1271                        (dry.cg_m - to_motor_axis(number(m, "center_of_dry_mass_position"))).abs()
1272                            < 1e-15,
1273                        "{name}"
1274                    );
1275                }
1276                ("generic", hpr_motor::Propellant::Column(c)) => {
1277                    // RocketPy puts an unset dry center at the chamber (motor.py:1518-1523).
1278                    assert!(m["center_of_dry_mass_position"].is_null());
1279                    let chamber = to_motor_axis(number(m, "chamber_position"));
1280                    assert_eq!(
1281                        *c,
1282                        hpr_motor::PropellantColumn {
1283                            mass_kg: number(m, "propellant_initial_mass"),
1284                            center_m: chamber,
1285                            outer_radius_m: number(m, "chamber_radius"),
1286                            inner_radius_m: 0.0,
1287                            length_m: number(m, "chamber_height"),
1288                        },
1289                        "{name}"
1290                    );
1291                    assert_eq!(dry.cg_m, chamber, "{name}");
1292                }
1293                (kind, other) => panic!("{name}: {kind} vs {other:?}"),
1294            }
1295            let m_p0 = motor.propellant_initial_mass_kg();
1296            worst.see(
1297                "initial propellant mass",
1298                relative(m_p0, case.scalars.propellant_initial_mass_kg),
1299                || name.to_owned(),
1300            );
1301
1302            // The dry rocket.
1303            let length = assembly.layout.length_m;
1304            let dry_rocket = assembly.dry_mass_properties();
1305            worst.see(
1306                "dry mass",
1307                relative(dry_rocket.mass_kg, case.scalars.dry_mass_kg),
1308                || name.to_owned(),
1309            );
1310            worst.see(
1311                "dry center (of length)",
1312                (-dry_rocket.cg_m.z - station(case.scalars.center_of_dry_mass_position_m)).abs()
1313                    / length,
1314                || name.to_owned(),
1315            );
1316            worst.see(
1317                "dry I_11",
1318                relative(
1319                    dry_rocket.inertia_kg_m2.x_axis.x,
1320                    case.scalars.dry_I_11_kg_m2,
1321                ),
1322                || name.to_owned(),
1323            );
1324            worst.see(
1325                "dry I_33",
1326                relative(
1327                    dry_rocket.inertia_kg_m2.z_axis.z,
1328                    case.scalars.dry_I_33_kg_m2,
1329                ),
1330                || name.to_owned(),
1331            );
1332
1333            // Through the burn, on the even grid and at RocketPy's own knots.
1334            let grids = [
1335                ("", Some(&case.series)),
1336                (" at knots", case.knot_series.as_ref()),
1337            ];
1338            for (grid, s) in grids.into_iter().filter_map(|(g, s)| Some((g, s?))) {
1339                let label = |what: &'static str| -> &'static str {
1340                    match (what, grid.is_empty()) {
1341                        (_, true) => what,
1342                        ("total mass", false) => "total mass at knots",
1343                        ("center of mass (of length)", false) => "center of mass at knots",
1344                        ("I_11 about the dry center", false) => {
1345                            "I_11 about the dry center at knots"
1346                        }
1347                        ("I_22 about the dry center", false) => {
1348                            "I_22 about the dry center at knots"
1349                        }
1350                        ("I_11 about the center of mass", false) => {
1351                            "I_11 about the center of mass at knots"
1352                        }
1353                        ("I_33", false) => "I_33 at knots",
1354                        ("products of inertia (of I_11)", false) => "products of inertia at knots",
1355                        ("propellant mass, grains (of initial)", false) => {
1356                            "propellant mass, grains, at knots"
1357                        }
1358                        (other, false) => panic!("no knot label for {other}"),
1359                    }
1360                };
1361                for (i, &t) in s.time_s.iter().enumerate() {
1362                    let at = || format!("{name} at t = {t} s");
1363                    let whole = assembly.mass_properties(t);
1364                    worst.see(
1365                        label("total mass"),
1366                        relative(whole.mass_kg, s.total_mass[i]),
1367                        at,
1368                    );
1369                    worst.see(
1370                        label("center of mass (of length)"),
1371                        (-whole.cg_m.z - station(s.center_of_mass[i])).abs() / length,
1372                        at,
1373                    );
1374                    let about_dry = whole.inertia_about(dry_rocket.cg_m);
1375                    worst.see(
1376                        label("I_11 about the dry center"),
1377                        relative(about_dry.x_axis.x, s.I_11[i]),
1378                        at,
1379                    );
1380                    worst.see(
1381                        label("I_22 about the dry center"),
1382                        relative(about_dry.y_axis.y, s.I_11[i]),
1383                        at,
1384                    );
1385                    worst.see(
1386                        label("I_11 about the center of mass"),
1387                        relative(whole.inertia_kg_m2.x_axis.x, s.I_11_about_cg[i]),
1388                        at,
1389                    );
1390                    worst.see(
1391                        label("I_33"),
1392                        relative(whole.inertia_kg_m2.z_axis.z, s.I_33[i]),
1393                        at,
1394                    );
1395                    let products = [
1396                        whole.inertia_kg_m2.y_axis.x,
1397                        whole.inertia_kg_m2.z_axis.x,
1398                        whole.inertia_kg_m2.z_axis.y,
1399                    ];
1400                    worst.see(
1401                        label("products of inertia (of I_11)"),
1402                        products.iter().fold(0.0f64, |a, v| a.max(v.abs())) / s.I_11[i],
1403                        at,
1404                    );
1405                    let what = match motor.propellant() {
1406                        hpr_motor::Propellant::Column(_) => "propellant mass, column (of initial)",
1407                        _ => "propellant mass, grains (of initial)",
1408                    };
1409                    worst.see(
1410                        label(what),
1411                        (motor.propellant_mass_kg(t) - s.propellant_mass[i]).abs() / m_p0,
1412                        at,
1413                    );
1414                }
1415            }
1416        }
1417        // Measured worst (RocketPy 1.13.0), rounded up, and each tolerance's margin over the
1418        // worst before rounding:
1419        //
1420        // - Exact quantities: dry mass, center and inertias, initial propellant mass and the
1421        //   column's propellant mass agree to 3.5e-16 (tolerance 1e-12). Products of inertia are
1422        //   exactly zero (1e-15).
1423        // - At RocketPy's LSODA knots, where its grain geometry holds computed values: total mass
1424        //   3.4e-10, center 1.4e-10 of the length, `I_11` 8.0e-10, `I_33` 1.8e-10, grain propellant
1425        //   mass 2.5e-9 of its initial value. That is the solver's own accuracy (rtol 1e-11); the
1426        //   tolerance is 1e-8, a margin of 4 to 73.
1427        // - On the even grid, between knots: total mass 1.4e-5 (Lince), center 4.0e-6 (Erebus 11),
1428        //   `I_11` 2.6e-5, `I_33` 1.5e-5, grain propellant mass 6.4e-5 (Erebus 11). `SolidMotor`
1429        //   interpolates its grain volumes linearly between LSODA knots
1430        //   (`solid_motor.py:375-383`, `:603-630`) and
1431        //   `GenericMotor` samples its inertias at the thrust knots, while hpr's are exact for a
1432        //   piecewise-linear curve. Tolerances: 5e-5 (margin 3.8), 2e-5 (5.0), 1e-4 (3.8 and 7) and
1433        //   2.5e-4 (3.9).
1434        let tolerance = |what: &str| match what {
1435            "initial propellant mass"
1436            | "dry mass"
1437            | "dry center (of length)"
1438            | "dry I_11"
1439            | "dry I_33"
1440            | "propellant mass, column (of initial)" => 1e-12,
1441            "products of inertia (of I_11)" | "products of inertia at knots" => 1e-15,
1442            "total mass at knots"
1443            | "center of mass at knots"
1444            | "I_11 about the dry center at knots"
1445            | "I_22 about the dry center at knots"
1446            | "I_11 about the center of mass at knots"
1447            | "I_33 at knots"
1448            | "propellant mass, grains, at knots" => 1e-8,
1449            "total mass" => 5e-5,
1450            "center of mass (of length)" => 2e-5,
1451            "I_11 about the dry center"
1452            | "I_22 about the dry center"
1453            | "I_11 about the center of mass"
1454            | "I_33" => 1e-4,
1455            "propellant mass, grains (of initial)" => 2.5e-4,
1456            other => panic!("no tolerance for {other}"),
1457        };
1458        for (what, error, at) in &worst.0 {
1459            println!("{what}: {error:.3e} ({at})");
1460        }
1461        assert_eq!(worst.0.len(), 22, "every quantity was compared");
1462        for (what, error, at) in &worst.0 {
1463            assert!(*error <= tolerance(what), "{what}: {error:e} at {at}");
1464        }
1465    }
1466
1467    /// The synthetic two-stage design with its sustainer lit by `ignition`: a J760 in the
1468    /// booster (motor 0), an I175 in the sustainer (motor 1).
1469    fn two_stage(ignition: Ignition) -> Rocket {
1470        let mut rocket: Rocket = serde_json::from_str(include_str!(
1471            "../../../validation/designs/synthetic-two-stage-75mm-54mm.json"
1472        ))
1473        .unwrap();
1474        rocket.configurations[0].motors[1].ignition = ignition;
1475        rocket
1476    }
1477
1478    /// A sustainer lit by a clustered booster's burnout lights at the burnout of the booster's
1479    /// first motor that lights, so one motor out doesn't hold it back; with every booster motor
1480    /// out it never lights, and that is not the cycle of burnouts assembly refuses.
1481    #[test]
1482    fn a_burnout_of_a_cluster_is_its_first_motor_that_lights() {
1483        let mut rocket = two_stage(Ignition::Burnout {
1484            mount: "booster-motor-mount".to_owned(),
1485            delay_s: 1.0,
1486        });
1487        let booster = rocket.stages[1].components[1]
1488            .children
1489            .iter_mut()
1490            .find(|c| c.id == "booster-motor-mount")
1491            .expect("the booster's mount");
1492        if let crate::Part::InnerTube(tube) = &mut booster.part {
1493            tube.cluster_m = vec![[-0.01, 0.0], [0.01, 0.0]];
1494        }
1495        let booster_burnout_s =
1496            |assembly: &Assembly| assembly.motors[0].mounted.motor.burnout_time_s();
1497        rocket.configurations[0].motors[0].failed_tubes = vec![0];
1498        let assembly = rocket.assemble("j760-i175").unwrap();
1499        let burnout_s = booster_burnout_s(&assembly);
1500        assert_eq!(
1501            assembly.ignition_times_s(|_| None),
1502            [None, Some(0.0), Some(burnout_s + 1.0)]
1503        );
1504        rocket.configurations[0].motors[0].failed_tubes = vec![1, 0];
1505        let assembly = rocket.assemble("j760-i175").unwrap();
1506        assert_eq!(assembly.ignition_times_s(|_| None), [None, None, None]);
1507    }
1508
1509    /// A motor set never to light is carried loaded to the end, as a motor out is, and a motor
1510    /// lit by its burnout never lights either; that is not the cycle of burnouts assembly refuses.
1511    #[test]
1512    fn a_motor_set_never_to_light_stays_loaded() {
1513        let assembly = two_stage(Ignition::Never).assemble("j760-i175").unwrap();
1514        assert_eq!(
1515            assembly.motors.iter().map(|m| m.fails).collect::<Vec<_>>(),
1516            [false, true]
1517        );
1518        assert_eq!(assembly.ignition_times_s(|_| Some(0.0)), [Some(0.0), None]);
1519        let loaded = assembly.motors[1].mass_properties(0.0);
1520        let structure = assembly.layout.structure;
1521        let booster = |t: f64| assembly.motors[0].mass_properties(t);
1522        let lit = assembly.ignition_times_s(|_| None);
1523        for t in [0.0, 3.0, 100.0] {
1524            // Summed motor by motor, in order, as the assembly sums them.
1525            let expected = MassProperties::combine([
1526                &MassProperties::combine([&structure, &booster(t)]),
1527                &loaded,
1528            ]);
1529            assert_eq!(assembly.mass_properties_lit(t, &lit), expected);
1530            assert_eq!(assembly.mass_properties(t), expected);
1531        }
1532        let dry = MassProperties::combine([&structure, &assembly.motors[0].dry_mass_properties()]);
1533        assert_eq!(
1534            assembly.dry_mass_properties(),
1535            MassProperties::combine([&dry, &loaded])
1536        );
1537        let mut rocket = two_stage(Ignition::Burnout {
1538            mount: "booster-motor-mount".to_owned(),
1539            delay_s: 0.0,
1540        });
1541        rocket.configurations[0].motors[0].ignition = Ignition::Never;
1542        let assembly = rocket.assemble("j760-i175").unwrap();
1543        assert_eq!(assembly.ignition_times_s(|_| Some(0.0)), [None, None]);
1544        let json = serde_json::to_string(&two_stage(Ignition::Never)).unwrap();
1545        assert!(json.contains(r#""ignition":"never""#), "{json}");
1546        assert_eq!(
1547            serde_json::from_str::<Rocket>(&json).unwrap(),
1548            two_stage(Ignition::Never)
1549        );
1550    }
1551
1552    #[test]
1553    fn ignition_times_follow_their_events() {
1554        let j760 = |assembly: &Assembly| assembly.motors[0].mounted.motor.burnout_time_s();
1555        // At launch, and at a time.
1556        let assembly = two_stage(Ignition::Launch).assemble("j760-i175").unwrap();
1557        assert_eq!(assembly.ignition_times_s(|_| None), [Some(0.0), Some(0.0)]);
1558        let assembly = two_stage(Ignition::Time { time_s: 3.5 })
1559            .assemble("j760-i175")
1560            .unwrap();
1561        assert_eq!(assembly.ignition_times_s(|_| None), [Some(0.0), Some(3.5)]);
1562        // At the booster's burnout plus a delay.
1563        let assembly = two_stage(Ignition::Burnout {
1564            mount: "booster-motor-mount".to_owned(),
1565            delay_s: 1.25,
1566        })
1567        .assemble("j760-i175")
1568        .unwrap();
1569        let burnout_s = j760(&assembly);
1570        assert!(burnout_s > 1.0, "{burnout_s}");
1571        assert_eq!(
1572            assembly.ignition_times_s(|_| None),
1573            [Some(0.0), Some(burnout_s + 1.25)]
1574        );
1575        // At the separation of the stage aft of the sustainer's (stage 0), and never without it.
1576        let assembly = two_stage(Ignition::Separation { delay_s: 0.5 })
1577            .assemble("j760-i175")
1578            .unwrap();
1579        assert_eq!(assembly.ignition_times_s(|_| None), [Some(0.0), None]);
1580        assert_eq!(
1581            assembly.ignition_times_s(|stage| (stage == 0).then_some(4.0)),
1582            [Some(0.0), Some(4.5)]
1583        );
1584        assert_eq!(
1585            assembly.ignition_times_s(|stage| (stage == 1).then_some(4.0)),
1586            [Some(0.0), None]
1587        );
1588        // A motor not yet lit is loaded; lit, it burns on its own clock.
1589        let lit = [Some(0.0), Some(4.5)];
1590        let loaded = assembly.motors[1].mass_properties(0.0).mass_kg;
1591        let spent = assembly.motors[1].dry_mass_properties().mass_kg;
1592        let at = |t: f64| assembly.mass_properties_lit(t, &lit).mass_kg;
1593        let structure = assembly.layout.structure.mass_kg;
1594        let booster = |t: f64| assembly.motors[0].mass_properties(t).mass_kg;
1595        assert_eq!(at(4.0), structure + booster(4.0) + loaded);
1596        let sustainer = assembly.motors[1].mass_properties(1.0).mass_kg;
1597        assert!(sustainer < loaded && sustainer > spent);
1598        assert!((at(5.5) - (structure + booster(5.5) + sustainer)).abs() < 1e-12);
1599        assert!((at(100.0) - assembly.dry_mass_properties().mass_kg).abs() < 1e-12);
1600    }
1601
1602    #[test]
1603    fn bad_ignitions_are_refused() {
1604        let refused = |ignition: Ignition| two_stage(ignition).assemble("j760-i175").is_err();
1605        assert!(refused(Ignition::Time { time_s: -1.0 }));
1606        assert!(refused(Ignition::Time { time_s: f64::NAN }));
1607        assert!(refused(Ignition::Separation {
1608            delay_s: f64::INFINITY
1609        }));
1610        // The booster is the last stage: nothing is aft of it to separate.
1611        let mut rocket = two_stage(Ignition::Launch);
1612        rocket.configurations[0].motors[0].ignition = Ignition::Separation { delay_s: 0.0 };
1613        let error = rocket.assemble("j760-i175").unwrap_err();
1614        assert!(matches!(error, DesignError::Tree { .. }), "{error:?}");
1615        assert!(refused(Ignition::Burnout {
1616            mount: "booster-motor-mount".to_owned(),
1617            delay_s: -0.1,
1618        }));
1619        // A mount with no motor, or no such mount.
1620        assert!(refused(Ignition::Burnout {
1621            mount: "nose".to_owned(),
1622            delay_s: 0.0,
1623        }));
1624        // Its own burnout, and a cycle through the other motor.
1625        assert!(refused(Ignition::Burnout {
1626            mount: "sustainer-motor-mount".to_owned(),
1627            delay_s: 0.0,
1628        }));
1629        let mut rocket = two_stage(Ignition::Burnout {
1630            mount: "booster-motor-mount".to_owned(),
1631            delay_s: 0.0,
1632        });
1633        rocket.configurations[0].motors[0].ignition = Ignition::Burnout {
1634            mount: "sustainer-motor-mount".to_owned(),
1635            delay_s: 0.0,
1636        };
1637        let error = rocket.assemble("j760-i175").unwrap_err();
1638        assert!(matches!(error, DesignError::Tree { .. }), "{error:?}");
1639        // A launch is written as nothing at all, so older designs read the same.
1640        let json = serde_json::to_string(&two_stage(Ignition::Launch)).unwrap();
1641        assert!(!json.contains("ignition"));
1642        let timed = serde_json::to_string(&two_stage(Ignition::Time { time_s: 2.0 })).unwrap();
1643        assert!(
1644            timed.contains(r#""ignition":{"time":{"time_s":2.0}}"#),
1645            "{timed}"
1646        );
1647    }
1648}