Skip to main content

hpr/
flight.rs

1//! A flight: a rocket launched from a rail in an environment, flown to the ground.
2
3use std::sync::Arc;
4
5use hpr_aero::{DragModel, DragTable};
6use hpr_analysis::montecarlo::{DragOverride, FlightInputs};
7use hpr_sim::metrics::{FlightMetrics, FlightSummary, Landing};
8use hpr_sim::{
9    EnvelopeFlag, FlightResult, FlightSettings, IssueWarning, Observer, Rail, Separation,
10    Simulation,
11};
12use serde::{Deserialize, Serialize};
13
14use crate::environment::Environment;
15use crate::error::{Error, finite};
16use crate::rocket::Rocket;
17
18/// How a flight is launched: which rocket, where, and from what rail. Made by
19/// [`Flight::builder`]; [`FlightBuilder::fly`] flies it.
20#[derive(Debug, Clone)]
21pub struct FlightBuilder<'a> {
22    rocket: &'a Rocket,
23    environment: &'a Environment,
24    rail: Rail,
25    /// The rail's angles, degrees, where set: they take the place of the rail's own.
26    inclination_deg: Option<f64>,
27    heading_deg: Option<f64>,
28    settings: FlightSettings,
29    /// A drag model flown in place of HPR Sim's drag buildup, where set.
30    drag_model: Option<Arc<dyn DragModel>>,
31    /// A drag table flown in place of HPR Sim's drag buildup, where set; never with a model.
32    drag_table: Option<DragTable>,
33    /// The stack coming apart in flight, in the order it does: none where unset.
34    separations: Vec<Separation>,
35}
36
37impl FlightBuilder<'_> {
38    /// The rail's angle above the horizon, degrees: 90, the default, is vertical, and 85 leans
39    /// 5° off it. (OpenRocket's launch rod angle is measured from the vertical instead: its 5° is
40    /// 85 here.)
41    #[must_use]
42    pub fn inclination_deg(mut self, inclination_deg: f64) -> Self {
43        self.inclination_deg = Some(inclination_deg);
44        self
45    }
46
47    /// The direction the rail leans toward, clockwise from true north, degrees: 0, the
48    /// default, is north and 90 is east. A wind's direction is where it blows from, so a rail
49    /// leaning into a west wind has both at 270. On a vertical rail the heading still turns the
50    /// rocket about its axis, which way its fins face. That matters to a set of one or two fins,
51    /// whose lift depends on which way the air meets them; three or more equal fins lift nearly
52    /// the same whichever way they face.
53    #[must_use]
54    pub fn heading_deg(mut self, heading_deg: f64) -> Self {
55        self.heading_deg = Some(heading_deg);
56        self
57    }
58
59    /// The whole rail, in place of the one [`Flight::builder`] made: its length, its angles in
60    /// radians, the rocket's roll on it and its friction ([`Rail`]).
61    /// [`FlightBuilder::inclination_deg`] and [`FlightBuilder::heading_deg`], called before or
62    /// after, still set its angles.
63    #[must_use]
64    pub fn rail(mut self, rail: Rail) -> Self {
65        self.rail = rail;
66        self
67    }
68
69    /// The integrator and its limits, in place of the defaults ([`FlightSettings`]).
70    #[must_use]
71    pub fn settings(mut self, settings: FlightSettings) -> Self {
72        self.settings = settings;
73        self
74    }
75
76    /// Flies with `separation`: at its trigger the stack comes apart at a stage boundary, and
77    /// each part flies on to its own landing ([`Simulation::with_separation`], which has the
78    /// rules). Every part needs a recovery device on the rocket, each on its own part
79    /// ([`hpr_sim::Device::on_body`]); for a `.ork` file, [`crate::ork::separated_recovery`]
80    /// makes them. Each separated part's landing is in [`FlightSummary::body_landings`], and
81    /// its own opening shock in [`FlightSummary::body_max_descent_acceleration_m_s2`].
82    #[must_use]
83    pub fn separation(mut self, separation: Separation) -> Self {
84        self.separations = vec![separation];
85        self
86    }
87
88    /// Flies with `separations`, in the order they fire, each at a stage boundary further forward
89    /// than the one before: a stack that drops its stages one at a time under power
90    /// ([`Simulation::with_separations`], which has the rules). As [`FlightBuilder::separation`],
91    /// every part needs a device of its own; for a `.ork` file, [`crate::ork::separations`] and
92    /// [`crate::ork::separated_recovery`] make them. In place of any set before.
93    #[must_use]
94    pub fn separations(mut self, separations: Vec<Separation>) -> Self {
95        self.separations = separations;
96        self
97    }
98
99    /// Flies `model`'s drag in place of HPR Sim's drag buildup: a model of your own, from a wind
100    /// tunnel, another tool or your flights, or HPR Sim's own adjusted
101    /// ([`hpr_aero::custom`], [`Simulation::with_drag_model`]). The model gives the zero-lift
102    /// drag coefficient on the rocket's reference area, by default a circle of its largest body
103    /// diameter; unlike a drag table's, a model's number isn't rescaled, so a curve measured on
104    /// another area is converted before it is returned. The normal force, center of pressure,
105    /// roll and damping stay HPR Sim's, so the stability margin a [`Rocket`] reports doesn't change.
106    /// The last model or table set is the one flown ([`FlightBuilder::drag_table`]), and every
107    /// flight of this builder shares it.
108    ///
109    /// ```
110    /// # use hpr::rocket::{Fins, Mass, MotorTube, Nose, Tube, material};
111    /// # use hpr::{Environment, FinPlanform, Flight, Motor, NoseShape, Position, Rocket};
112    /// use hpr::hpr_aero::{AeroError, DragModel, DragQuery};
113    ///
114    /// /// hpr's own drag, 20% higher.
115    /// #[derive(Debug)]
116    /// struct Rougher;
117    ///
118    /// impl DragModel for Rougher {
119    ///     fn zero_lift_drag(&self, query: &DragQuery<'_>) -> Result<f64, AeroError> {
120    ///         Ok(1.2 * query.buildup()?.zero_lift_coefficient)
121    ///     }
122    /// }
123    ///
124    /// # let mut rocket = Rocket::new("Small", 0.0563)?;
125    /// # rocket
126    /// #     .add_nose(Nose::hollow(NoseShape::Ogive { radius_ratio: 1.0 }, 0.22, 0.0015, material("abs")?))?
127    /// #     .add_tube(Tube::new(0.9, 0.00115, material("kraft_phenolic")?))?
128    /// #     .add_fins(Fins::new(
129    /// #         3,
130    /// #         FinPlanform::Trapezoidal { root_chord_m: 0.1, tip_chord_m: 0.04, span_m: 0.045, sweep_m: 0.05 },
131    /// #         0.003175,
132    /// #         material("birch_plywood")?,
133    /// #     ))?
134    /// #     .add_motor_tube(MotorTube::new(0.2, 0.029, 0.001, material("kraft_phenolic")?))?
135    /// #     .add_mass(Mass::new(0.2, Position::Top { aft_offset_m: 0.07 }))?
136    /// #     .set_motor(Motor::from_catalog("H54")?)?;
137    /// let environment = Environment::new(32.99, -106.97, 1400.0)?;
138    /// let launch = Flight::builder(&rocket, &environment, 1.8);
139    /// let own = launch.fly()?.apogee_m().ok_or("no apogee")?;
140    /// let rougher = launch.drag_model(Rougher).fly()?.apogee_m().ok_or("no apogee")?;
141    /// assert!(rougher < own);
142    /// # Ok::<(), Box<dyn std::error::Error>>(())
143    /// ```
144    #[must_use]
145    pub fn drag_model(self, model: impl DragModel + 'static) -> Self {
146        self.shared_drag_model(Arc::new(model))
147    }
148
149    /// As [`FlightBuilder::drag_model`], with a model already shared: one model, a large table
150    /// say, flown by many builders without a copy for each.
151    #[must_use]
152    pub fn shared_drag_model(mut self, model: Arc<dyn DragModel>) -> Self {
153        self.drag_model = Some(model);
154        self.drag_table = None;
155        self
156    }
157
158    /// Flies `table`'s drag in place of HPR Sim's drag buildup: another tool's zero-lift drag
159    /// coefficient `C_D0` against Mach number, as RocketPy's `power_off_drag` and
160    /// `power_on_drag` curves are ([`DragTable`], [`Simulation::with_drag_table`]). Its power-on
161    /// curve, where it has one, is flown while a motor thrusts, and its power-off curve at every
162    /// other time. A table read by [`DragTable::from_csv`] interpolates linearly between its Mach
163    /// numbers and holds its end values past them; one built from [`hpr_core::interp::Table1D`]s
164    /// interpolates and extrapolates as they say. A table on a reference diameter of its own
165    /// ([`DragTable::with_reference_diameter_m`]) is rescaled to the rocket's reference area by
166    /// the ratio of the two areas, `C_D0 · (d_table / d_rocket)²`. The normal force, center of
167    /// pressure, roll and damping stay HPR Sim's. The last model or table set is the one flown
168    /// ([`FlightBuilder::drag_model`]). A flight that meets a negative coefficient in the table,
169    /// drag that would push the rocket along, stops with an error that says so.
170    ///
171    /// ```
172    /// # use hpr::rocket::{Fins, Mass, MotorTube, Nose, Tube, material};
173    /// # use hpr::{Environment, FinPlanform, Flight, Motor, NoseShape, Position, Rocket};
174    /// use hpr::hpr_aero::DragTable;
175    ///
176    /// # let mut rocket = Rocket::new("Small", 0.0563)?;
177    /// # rocket
178    /// #     .add_nose(Nose::hollow(NoseShape::Ogive { radius_ratio: 1.0 }, 0.22, 0.0015, material("abs")?))?
179    /// #     .add_tube(Tube::new(0.9, 0.00115, material("kraft_phenolic")?))?
180    /// #     .add_fins(Fins::new(
181    /// #         3,
182    /// #         FinPlanform::Trapezoidal { root_chord_m: 0.1, tip_chord_m: 0.04, span_m: 0.045, sweep_m: 0.05 },
183    /// #         0.003175,
184    /// #         material("birch_plywood")?,
185    /// #     ))?
186    /// #     .add_motor_tube(MotorTube::new(0.2, 0.029, 0.001, material("kraft_phenolic")?))?
187    /// #     .add_mass(Mass::new(0.2, Position::Top { aft_offset_m: 0.07 }))?
188    /// #     .set_motor(Motor::from_catalog("H54")?)?;
189    /// let environment = Environment::new(32.99, -106.97, 1400.0)?;
190    /// let launch = Flight::builder(&rocket, &environment, 1.8);
191    /// // C_D0 of 0.45 up to Mach 0.8, 0.6 by Mach 1.2; 0.05 less while the motor burns.
192    /// let table = DragTable::from_csv(
193    ///     "mach,cd\n0,0.45\n0.8,0.45\n1.2,0.6\n",
194    ///     Some("mach,cd\n0,0.40\n0.8,0.40\n1.2,0.55\n"),
195    /// )?;
196    /// let tabled = launch.clone().drag_table(table).fly()?.apogee_m().ok_or("no apogee")?;
197    /// let own = launch.fly()?.apogee_m().ok_or("no apogee")?;
198    /// assert_ne!(tabled, own);
199    /// # Ok::<(), Box<dyn std::error::Error>>(())
200    /// ```
201    #[must_use]
202    pub fn drag_table(mut self, table: DragTable) -> Self {
203        self.drag_table = Some(table);
204        self.drag_model = None;
205        self
206    }
207
208    /// The [`Simulation`] [`FlightBuilder::fly`] runs, for what the facade doesn't offer: user
209    /// events, staging, mass shifts and the rest of [`hpr_sim`].
210    ///
211    /// # Errors
212    ///
213    /// - [`Error::NoMotor`] for a rocket with no motor.
214    /// - [`Error::Domain`] for an inclination outside `(0°, 90°]` or a heading that isn't
215    ///   finite.
216    /// - [`Error::Sim`] for what [`Simulation::new`], [`Simulation::with_recovery`] and
217    ///   [`Simulation::with_separations`] refuse: a rail that isn't positive in length, a design
218    ///   with errors in it ([`hpr_design::checks`]), a recovery device the flight can't fly, a
219    ///   separation with a part that carries no device.
220    pub fn simulation(&self) -> Result<Simulation, Error> {
221        Ok(self.inputs()?.simulation()?)
222    }
223
224    /// Everything the flight is flown from, as [`hpr_analysis::montecarlo::FlightInputs`]: what a
225    /// Monte Carlo run disperses ([`hpr_analysis::montecarlo`]).
226    ///
227    /// # Errors
228    ///
229    /// - [`Error::NoMotor`] for a rocket with no motor.
230    /// - [`Error::Domain`] for an inclination outside `(0°, 90°]` or a heading that isn't
231    ///   finite.
232    /// - [`Error::Sim`] for a rail that isn't positive in length or whose friction is negative.
233    pub fn inputs(&self) -> Result<FlightInputs, Error> {
234        let configuration_id = self.rocket.configuration_id().ok_or(Error::NoMotor)?;
235        let mut rail = self.rail;
236        if let Some(inclination_deg) = self.inclination_deg {
237            if !(inclination_deg > 0.0 && inclination_deg <= 90.0) {
238                return Err(Error::Domain {
239                    what: "rail inclination, degrees above the horizon",
240                    value: inclination_deg,
241                    allowed: "above 0 and at most 90",
242                });
243            }
244            rail.elevation_rad = inclination_deg.to_radians();
245        }
246        if let Some(heading_deg) = self.heading_deg {
247            rail.azimuth_rad = finite("rail heading, degrees", heading_deg)?.to_radians();
248        }
249        rail.validate()?;
250        let mut inputs = FlightInputs::new(
251            self.rocket.design().clone(),
252            configuration_id,
253            self.environment.sim().clone(),
254            rail,
255        );
256        inputs.settings = self.settings;
257        inputs.recovery = self.rocket.recovery().to_vec();
258        // A builder holds one or neither: each setter clears the other.
259        if let Some(model) = &self.drag_model {
260            inputs.drag = Some(DragOverride::Model(Arc::clone(model)));
261        }
262        if let Some(table) = &self.drag_table {
263            inputs.drag = Some(DragOverride::Table(table.clone()));
264        }
265        inputs.separations.clone_from(&self.separations);
266        Ok(inputs)
267    }
268
269    /// Flies the rocket from the rail to the ground.
270    ///
271    /// # Errors
272    ///
273    /// As [`FlightBuilder::simulation`], and [`Error::Sim`] for a flight that fails on the way,
274    /// such as a model asked about a flow it doesn't cover.
275    pub fn fly(&self) -> Result<Flight, Error> {
276        self.fly_with(&mut ())
277    }
278
279    /// Flies the rocket, showing `observer` every step of the flight as it goes: a
280    /// [`hpr_sim::Recorder`] keeps a trajectory, and an [`Observer`] of your own can watch for
281    /// anything.
282    ///
283    /// # Errors
284    ///
285    /// As [`FlightBuilder::fly`], and whatever `observer` returns.
286    pub fn fly_with(&self, observer: &mut dyn Observer) -> Result<Flight, Error> {
287        let simulation = self.simulation()?;
288        let mut metrics = FlightMetrics::new();
289        let result = simulation.run(&mut (&mut metrics, observer))?;
290        let summary = metrics.summary(&result, self.environment.sim())?;
291        // The drag issues are hpr's buildup's: a flight on a drag of its own meets none.
292        let own_drag = self.drag_model.is_some() || self.drag_table.is_some();
293        let mut issue_warnings = if own_drag {
294            Vec::new()
295        } else {
296            let layout = &simulation.assembly().layout;
297            let mut warnings = hpr_sim::issues::layout_issue_warnings(layout, summary.max_mach);
298            warnings.extend(hpr_sim::issues::friction_issue_warnings(summary.max_mach));
299            warnings
300        };
301        // A separated part's descent never takes the rocket's drag, so its issues stay with a
302        // drag of the flight's own.
303        issue_warnings.extend(hpr_sim::issues::separated_part_issue_warnings(
304            &result,
305            summary.max_mach,
306        ));
307        // The stability issues are hpr's normal force's (ADR-181): a drag of the flight's own
308        // keeps them. Asking why the supersonic run stopped may build its table, so only a flight
309        // the switches can matter to asks.
310        let aero = simulation.aero();
311        if aero.normal_force_table().is_none() {
312            let supersonic = summary.max_mach.is_some_and(|mach| {
313                mach.value.is_nan() || mach.value > hpr_sim::issues::SUPERSONIC_SWITCH_MACH
314            });
315            let fallback = if supersonic {
316                aero.supersonic_fallback()
317            } else {
318                None
319            };
320            let layout = &simulation.assembly().layout;
321            issue_warnings.extend(hpr_sim::issues::layout_stability_issue_warnings(
322                layout,
323                summary.max_mach,
324            ));
325            issue_warnings.extend(hpr_sim::issues::stability_issue_warnings(
326                fallback.as_ref(),
327                summary.min_static_margin_cal,
328                summary.max_mach,
329            ));
330        }
331        // The issues whose signs depend on the case (ADR-201) are the rocket's mass, its pods,
332        // its damping stations and the wind's, never the drag's or the normal-force table's: a
333        // flight on its own keeps them. The stations' issue builds the supersonic table only for
334        // a flight past the earliest join. The mass's and the stations' are each vehicle's the
335        // flight flew as a rigid body: the stack, then each sustainer, on its own top speed.
336        let vehicles = simulation.flown_vehicles(&result)?;
337        let masses: Vec<_> = vehicles
338            .iter()
339            .flat_map(hpr_sim::FlownVehicle::mass_samples)
340            .collect();
341        issue_warnings.extend(hpr_sim::issues::center_of_gravity_issue_warnings(
342            &masses,
343            summary.max_mach,
344        ));
345        // A sustainer's layout is a cut of the stack's, so the stack's pods are every pod.
346        issue_warnings.extend(hpr_sim::issues::pod_issue_warnings(
347            &simulation.assembly().layout,
348            summary.max_mach,
349        ));
350        // A vehicle the watcher has no entry for takes the flight's top speed, which is at
351        // least its own: the cautious side.
352        let by_vehicle = metrics.max_mach_by_vehicle();
353        let stations: Vec<_> = vehicles
354            .iter()
355            .enumerate()
356            .map(|(index, vehicle)| {
357                let top = by_vehicle.get(index).copied().unwrap_or(summary.max_mach);
358                (vehicle.aero.as_ref(), top)
359            })
360            .collect();
361        issue_warnings.extend(hpr_sim::issues::body_station_issue_warnings(
362            &stations,
363            summary.max_mach,
364        ));
365        // A wind is read by height above mean sea level: the site's ellipsoidal height less the
366        // geoid's undulation, plus a height above the site.
367        let environment = self.environment.sim();
368        let ground_msl_m = environment.site().height_m - environment.geoid_undulation_m;
369        let top_msl_m = ground_msl_m + hpr_sim::issues::highest_height_m(&result);
370        issue_warnings.extend(hpr_sim::issues::wind_issue_warnings(
371            &environment.wind.direction_turns(),
372            [ground_msl_m, top_msl_m],
373            summary.max_mach,
374        ));
375        Ok(Flight {
376            result,
377            summary,
378            issue_warnings,
379        })
380    }
381}
382
383/// A flown flight: what happened, and its metrics.
384///
385/// Heights are the rocket's center of gravity's, above the launch site: the rocket stands on
386/// the rail at the start, so the first height is not zero. Speeds are relative to the ground.
387/// [`Flight::summary`] has every metric; the methods below are the ones most asked for. A flight
388/// serializes and reads back as a record; one read back isn't flown again or checked.
389#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
390pub struct Flight {
391    result: FlightResult,
392    summary: FlightSummary,
393    /// The known issues it meets, in its drag, its stability margin and its path; none on a
394    /// record saved before they were kept.
395    #[serde(default)]
396    issue_warnings: Vec<IssueWarning>,
397}
398
399impl Flight {
400    /// A flight of `rocket` in `environment` from a vertical, frictionless rail `rail_length_m`
401    /// long, measured from the rocket's aft end at the start to the rail's top. Set the rest on
402    /// the builder; [`FlightBuilder::fly`] flies it.
403    #[must_use]
404    pub fn builder<'a>(
405        rocket: &'a Rocket,
406        environment: &'a Environment,
407        rail_length_m: f64,
408    ) -> FlightBuilder<'a> {
409        FlightBuilder {
410            rocket,
411            environment,
412            rail: Rail::vertical(rail_length_m),
413            inclination_deg: None,
414            heading_deg: None,
415            settings: FlightSettings::default(),
416            drag_model: None,
417            drag_table: None,
418            separations: Vec::new(),
419        }
420    }
421
422    /// Every metric of the flight: apogee, peaks, stability margins, landings.
423    #[must_use]
424    pub fn summary(&self) -> &FlightSummary {
425        &self.summary
426    }
427
428    /// The flight itself: its events, its end, and every body's.
429    #[must_use]
430    pub fn result(&self) -> &FlightResult {
431        &self.result
432    }
433
434    /// The apogee's height above the launch site, m; `None` if the flight ended before it, or an
435    /// ejection parted the rocket on its climb (`FlightSummary::apogee` gives the rule).
436    #[must_use]
437    pub fn apogee_m(&self) -> Option<f64> {
438        self.summary
439            .apogee
440            .map(|apogee| apogee.height_above_ground_m)
441    }
442
443    /// When the apogee came, s after launch.
444    #[must_use]
445    pub fn apogee_time_s(&self) -> Option<f64> {
446        self.summary.apogee.map(|apogee| apogee.time_s)
447    }
448
449    /// The top speed, m/s.
450    #[must_use]
451    pub fn max_speed_m_s(&self) -> Option<f64> {
452        self.summary.max_speed_m_s.map(|peak| peak.value)
453    }
454
455    /// The top Mach number.
456    #[must_use]
457    pub fn max_mach(&self) -> Option<f64> {
458        self.summary.max_mach.map(|peak| peak.value)
459    }
460
461    /// The speed as the rocket left the rail, m/s.
462    #[must_use]
463    pub fn rail_exit_speed_m_s(&self) -> Option<f64> {
464        self.summary.rail_exit_speed_m_s.map(|peak| peak.value)
465    }
466
467    /// Where and how fast the rocket landed; `None` if it never reached the ground.
468    #[must_use]
469    pub fn landing(&self) -> Option<&Landing> {
470        self.summary.landing.as_ref()
471    }
472
473    /// Where the flight's numbers deserve less trust: unstable under power (a static margin below
474    /// zero while a motor burns, so its apogee is not a prediction), and where it goes past what
475    /// HPR Sim's numbers have been checked for: faster than the fastest validated flight, at a high
476    /// angle of attack, outside the core band or beyond the envelope ([`hpr_sim::envelope`]).
477    /// Empty for a flight that raises none.
478    #[must_use]
479    pub fn envelope_flags(&self) -> Vec<EnvelopeFlag> {
480        self.summary.envelope_flags()
481    }
482
483    /// The known errors in HPR Sim's drag, a separated part's drag, the stability margin and the
484    /// flight's path this flight meets, each by its issue number, with the parts whose shape meets
485    /// its condition and which way its numbers lean ([`hpr_sim::issues`]). A flight on a drag
486    /// model or table of its own ([`FlightBuilder::drag_model`], [`FlightBuilder::drag_table`]),
487    /// whose drag isn't HPR Sim's, meets none of HPR Sim's drag issues but keeps the separated parts'
488    /// (#179, #354), the stability ones unless its model has a normal-force table of its own, and
489    /// those whose signs depend on the case, which no table changes (#8, #106, #213, #219). Empty
490    /// for a flight that meets none, and for a record saved before the warnings were kept.
491    #[must_use]
492    pub fn issue_warnings(&self) -> &[IssueWarning] {
493        &self.issue_warnings
494    }
495}