hpr_io/ork/mod.rs
1//! Reading OpenRocket `.ork` design files.
2//!
3//! **Guide:** [OpenRocket `.ork` design files][guide] says what this reads and what it leaves out.
4//!
5//! [guide]: https://hpr.fusionspace.co/format/ork.html
6//!
7//! A `.ork` is a design: a tree of components, the materials they are made of, the motors flown in
8//! them, and the simulations OpenRocket last ran. This module is the first step of reading one:
9//! getting the design document out of whichever container it arrived in, and into a tree that
10//! keeps everything the file said. [`rocket`] turns that tree into [`hpr_design`] types: the spine,
11//! which is the stages and the body components stacked in them ([`component`]), and the parts on
12//! and inside each of those ([`attached`]).
13//!
14//! Nothing here reads a file: `hpr-io` does no I/O and builds for `wasm32-unknown-unknown`, so the
15//! caller supplies the bytes.
16//!
17//! ```
18//! # fn main() -> Result<(), hpr_io::ork::OrkError> {
19//! let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
20//! <openrocket version="1.10" creator="OpenRocket 24.12">
21//! <rocket><name>Sounder</name></rocket>
22//! </openrocket>"#;
23//!
24//! let read = hpr_io::ork::read(xml)?;
25//! assert_eq!(read.value.container, hpr_io::ork::Container::Xml);
26//! assert_eq!(read.value.document.version.to_string(), "1.10");
27//! let rocket = read.value.document.root.child("rocket").expect("a rocket");
28//! assert_eq!(rocket.child("name").expect("a name").text(), "Sounder");
29//! assert!(read.warnings.is_empty());
30//! # Ok(())
31//! # }
32//! ```
33
34pub mod attached;
35pub mod component;
36pub mod container;
37pub mod document;
38mod error;
39pub mod export;
40pub mod extensions;
41mod left_out;
42pub mod motors;
43mod reads;
44pub mod recovery;
45pub mod simulations;
46pub mod staging;
47pub mod value;
48mod warning;
49
50pub use attached::ATTACHED_TAGS;
51pub use component::{OPENROCKET_DEFAULT_RADIUS_M, rocket};
52pub use container::{Attachment, Container, MAX_UNPACKED_BYTES, Unpacked};
53pub use document::{Document, Element, MAX_DEPTH, MAX_KNOWN_MINOR, Node, SchemaVersion};
54pub use error::OrkError;
55pub use extensions::{Extensions, Kept, KeptAttribute, OpenRocketExtension, element_at};
56pub(crate) use left_out::{NOTHING_DEPENDS, nothing_depends};
57pub use motors::{
58 CaseSize, Curve, Ignition, IgnitionEvent, LeftOut, MotorConfiguration, Motors, NoCurve,
59 NotFlown, OrkMotor, SuppliedCurves, UnreadMotor,
60};
61pub use recovery::{
62 DeployEvent, Deployment, DeviceKind, EventSetting, Recovery, RecoveryDevice, Separation,
63 SeparationEvent, StageSeparation, UnreadDevice,
64};
65pub use simulations::{
66 Atmosphere, LaunchConditions, OPENROCKET_CALCULATOR, OPENROCKET_SIMULATOR, StoredBranch,
67 StoredEvent, StoredReferenceExclusion, StoredResults, StoredSimulation, WindLevel,
68};
69pub use staging::{Staging, StagingTrigger};
70pub use value::{AXIAL_OFFSET, Dimension, INSTANCE_COUNT, Overrides, Values};
71pub use warning::{Imported, Warning, WarningKind};
72
73/// A `.ork` file, read: the container it came in, its design document, and everything else it
74/// carried.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct OrkFile {
77 /// Which of the three containers the bytes were packed in.
78 pub container: Container,
79 /// The archive entry the design came from, when it came from an archive.
80 pub design_entry: Option<String>,
81 /// The design document.
82 pub document: Document,
83 /// The archive's other entries, in archive order: thrust curves, preview images, lookup
84 /// tables. Held as stored, for the milestones that read them and for an export to put back.
85 pub attachments: Vec<Attachment>,
86}
87
88impl OrkFile {
89 /// The attachment called `name`, if the archive had one.
90 pub fn attachment(&self, name: &str) -> Option<&Attachment> {
91 self.attachments
92 .iter()
93 .find(|attachment| attachment.name == name)
94 }
95}
96
97/// A `.ork` design read whole: its rocket, carrying every motor configuration HPR Sim can fly as
98/// written, and everything the file says about its motors.
99#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
100#[non_exhaustive]
101pub struct Design {
102 /// The rocket, as [`rocket`] reads it, with [`Rocket::configurations`] holding the
103 /// configurations in [`Design::motors`] that were not left out, each motor lit as the file
104 /// says. A configuration whose [`MotorConfiguration::staging`] is set must be flown with that
105 /// separation (`hpr::ork::separation`): without it the stack carries its booster to the ground
106 /// with the sustainer lit on it.
107 ///
108 /// [`Rocket::configurations`]: hpr_design::Rocket::configurations
109 pub rocket: hpr_design::Rocket,
110 /// Every motor configuration in the file, flown or not.
111 pub motors: Motors,
112 /// When each parachute and streamer opens and each stage separates.
113 pub recovery: Recovery,
114 /// The simulations OpenRocket last ran on the design, with their conditions and results.
115 pub simulations: Vec<StoredSimulation>,
116 /// What the file holds that HPR Sim does not model, kept whole for an export to put back.
117 #[serde(default)]
118 pub extensions: Extensions,
119}
120
121impl Design {
122 /// A design from its parts, as the HPR design format holds them (`hpr_format::DesignFile`).
123 pub fn new(
124 rocket: hpr_design::Rocket,
125 motors: Motors,
126 recovery: Recovery,
127 simulations: Vec<StoredSimulation>,
128 extensions: Extensions,
129 ) -> Self {
130 Self {
131 rocket,
132 motors,
133 recovery,
134 simulations,
135 extensions,
136 }
137 }
138
139 /// Whether the rocket is reduced: the file describes parts of it (a pod, a parallel stage, a
140 /// part HPR Sim cannot shape) that are kept in [`Design::extensions`] rather than read into it.
141 ///
142 /// The flag is on the `Design`, not on [`Design::rocket`]: check it before using the rocket on
143 /// its own. A part read as something simpler, such as a cluster of tubes read as one, does not
144 /// make a design reduced; its warning keeps every configuration of it from flying
145 /// ([ADR-055][adr-055], the rule for which configurations fly).
146 ///
147 /// [adr-055]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-055-m31c-split-and-the-motors-a-ork-flies-its-own-curve-first-and-only-what-lights-at-launch-2026-09-21
148 pub fn is_reduced(&self) -> bool {
149 !self.extensions.x_openrocket.parts.is_empty()
150 }
151
152 /// Returns why `simulation` cannot be used as a reference for this design.
153 ///
154 /// This combines the stored-result screen with HPR Sim's design-reproduction screen. Use
155 /// [`StoredSimulation::reference_exclusion`] and [`Self::reproduction_exclusion`] separately
156 /// when those two questions need to be reported independently.
157 #[must_use]
158 pub fn reference_exclusion(
159 &self,
160 simulation: &StoredSimulation,
161 ) -> Option<StoredReferenceExclusion> {
162 simulation
163 .reference_exclusion()
164 .or_else(|| self.reproduction_exclusion(simulation))
165 }
166
167 /// Returns why HPR Sim cannot reproduce the design named by a stored launch configuration.
168 ///
169 /// This is deliberately separate from [`StoredSimulation::reference_exclusion`]: a complete
170 /// OpenRocket result can be a useful stored reference even when HPR Sim does not yet have its
171 /// motor curve or full airframe model. A caller that needs a result HPR Sim can fly should apply
172 /// both classifiers.
173 #[must_use]
174 pub fn reproduction_exclusion(
175 &self,
176 simulation: &StoredSimulation,
177 ) -> Option<StoredReferenceExclusion> {
178 if self.is_reduced() {
179 return Some(StoredReferenceExclusion::ReducedDesign);
180 }
181 let Some(conditions) = simulation.conditions.as_ref() else {
182 return Some(StoredReferenceExclusion::MissingConfiguration);
183 };
184 let Some(configuration_id) = conditions.configuration.as_deref() else {
185 return Some(StoredReferenceExclusion::MissingConfiguration);
186 };
187 let Some(configuration) = self
188 .motors
189 .configurations
190 .iter()
191 .find(|configuration| configuration.id == configuration_id)
192 else {
193 return Some(StoredReferenceExclusion::UnknownConfiguration);
194 };
195 if configuration.left_out.is_some()
196 || self.rocket.configuration(configuration_id).is_none()
197 || self.rocket.assemble(configuration_id).is_err()
198 {
199 return Some(StoredReferenceExclusion::UnflyableConfiguration);
200 }
201 None
202 }
203}
204
205/// Reads the design in a `.ork` file: the rocket ([`rocket`]) and its motors ([`motors`]), with
206/// thrust curves from the archive's `thrustcurves/*.rse` entries or the bundled catalog.
207///
208/// ```
209/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
210/// let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
211/// <openrocket version="1.10" creator="OpenRocket 24.12">
212/// <rocket><name>Sounder</name>
213/// <motorconfiguration configid="c1" default="true"><name>F15</name></motorconfiguration>
214/// <subcomponents><stage><name>Sustainer</name><subcomponents>
215/// <nosecone><name>Nose</name><id>nose</id>
216/// <material type="bulk" density="1000.0">Plastic</material>
217/// <length>0.15</length><thickness>0.002</thickness><shape>ogive</shape>
218/// <aftradius>0.0165</aftradius></nosecone>
219/// <bodytube><name>Body</name><id>body</id>
220/// <material type="bulk" density="680.0">Cardboard</material>
221/// <length>0.6</length><thickness>0.001</thickness><radius>0.0165</radius>
222/// <motormount><ignitionevent>automatic</ignitionevent><ignitiondelay>0.0</ignitiondelay>
223/// <overhang>0.005</overhang>
224/// <motor configid="c1"><type>single</type><manufacturer>Estes</manufacturer>
225/// <designation>F15</designation><diameter>0.029</diameter><length>0.114</length>
226/// <delay>4.0</delay></motor>
227/// </motormount></bodytube>
228/// </subcomponents></stage></subcomponents></rocket>
229/// </openrocket>"#;
230///
231/// let read = hpr_io::ork::read(xml)?;
232/// let design = hpr_io::ork::design(&read.value).value;
233///
234/// // The F15 has no curve in this file, so it comes from the bundled catalog...
235/// let motor = &design.motors.configurations[0].motors[0];
236/// assert!(matches!(motor.curve, hpr_io::ork::Curve::Catalog { .. }));
237/// assert_eq!(motor.delay, Some(hpr_motor::Delay::Seconds(4.0)));
238/// let impulse_ns = motor.curve.motor().expect("a curve").curve().total_impulse_ns();
239/// assert!((impulse_ns - 49.61).abs() < 0.01, "{impulse_ns}");
240///
241/// // ...and it ignites at launch, so the configuration is one the rocket flies.
242/// let assembly = design.rocket.assemble("c1")?;
243/// assert_eq!(assembly.motors[0].mount, "body");
244/// # Ok(())
245/// # }
246/// ```
247pub fn design(file: &OrkFile) -> Imported<Design> {
248 design_with(file, &SuppliedCurves::default())
249}
250
251/// Like [`design`], but a motor can also take its thrust curve from `supplied`.
252///
253/// Each motor looks in three places, in order: a curve embedded in the file, then a supplied
254/// curve for the motor's digest, then the bundled catalog. An embedded curve that does not read
255/// or build is passed over, with a warning, for the next place.
256///
257/// ```
258/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
259/// use hpr_io::ork::{CaseSize, Curve, SuppliedCurves};
260/// use hpr_motor::{SolidMotor, ThrustCurve};
261///
262/// let xml = br#"<?xml version='1.0' encoding='utf-8'?>
263/// <openrocket version="1.9" creator="example">
264/// <rocket><subcomponents><stage><name>Sustainer</name><subcomponents>
265/// <bodytube><id>body</id><length>0.4</length><thickness>0.001</thickness>
266/// <radius>0.0125</radius>
267/// <motormount><ignitionevent>automatic</ignitionevent><ignitiondelay>0.0</ignitiondelay>
268/// <overhang>0.0</overhang>
269/// <motor configid="c1"><type>single</type><manufacturer>Example</manufacturer>
270/// <digest>0123abcd</digest><designation>E9</designation>
271/// <diameter>0.024</diameter><length>0.07</length><delay>4.0</delay></motor>
272/// </motormount></bodytube>
273/// </subcomponents></stage></subcomponents></rocket>
274/// </openrocket>"#;
275/// let read = hpr_io::ork::read(xml)?;
276///
277/// // A made-up 19 N·s motor: 10 N for about two seconds, from 10 g of propellant in a 30 g motor.
278/// let thrust = ThrustCurve::new(vec![0.0, 0.1, 1.9, 2.0], vec![0.0, 10.0, 10.0, 0.0])?;
279/// let (diameter_m, length_m, propellant_kg, loaded_kg) = (0.024, 0.07, 0.01, 0.03);
280/// let motor = SolidMotor::from_envelope(thrust, diameter_m, length_m, propellant_kg, loaded_kg)?;
281/// let mut supplied = SuppliedCurves::new("a motor database");
282/// supplied.insert("0123abcd", CaseSize { diameter_m, length_m }, motor)?;
283///
284/// let design = hpr_io::ork::design_with(&read.value, &supplied).value;
285/// let flown = &design.motors.configurations[0].motors[0];
286/// assert!(matches!(flown.curve, Curve::Supplied { .. }));
287/// assert!(design.rocket.assemble("c1").is_ok());
288/// # Ok(())
289/// # }
290/// ```
291pub fn design_with(file: &OrkFile, supplied: &SuppliedCurves) -> Imported<Design> {
292 // Every tag the readers ask for is recorded, so that the extension can keep the rest.
293 let ((mut design, warnings, read), reads) = reads::recording(|| {
294 let (mut design, mut warnings, read) = read_design(file, supplied);
295 // Stored simulations stand apart from the airframe, so their warnings come after the check
296 // in `read_design`; a document can hold them without a design, as Debrief's results-only
297 // file does.
298 design.simulations = simulations::read(&file.document, &mut warnings);
299 (design, warnings, read)
300 });
301 design.extensions = Extensions {
302 x_openrocket: extensions::read(&file.document, &read, &reads),
303 };
304 Imported {
305 value: design,
306 warnings,
307 }
308}
309
310/// Why the rocket in `file` was not read exactly as written, or `None` if it was. A rocket read
311/// otherwise flies in none of its configurations, whatever its motors ([ADR-055][adr-055], the
312/// rule for which configurations fly), so a program that puts a motor of its own into a
313/// configuration [`design`] left out, as `hpr sim --motor` does, asks this first: a
314/// configuration's [`LeftOut`] names only the first reason on [`NotFlown`]'s list, and a missing
315/// curve comes before the airframe.
316///
317/// [adr-055]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-055-m31c-split-and-the-motors-a-ork-flies-its-own-curve-first-and-only-what-lights-at-launch-2026-09-21
318#[must_use]
319pub fn airframe_not_as_written(file: &OrkFile) -> Option<String> {
320 let (rocket, _) = component::walk(&file.document);
321 incomplete(&rocket.warnings)
322}
323
324// Any warning the walk raised about the rocket or a motor mount means it was not read exactly as
325// written: a part left out, a value dropped or simplified, or something assumed. No configuration
326// of such a rocket is flown (ADR-055). A recovery device's or a stage separation's own warnings
327// are about when things happen, which is not flown (ADR-056), and their paths say so.
328//
329// The reason is one warning: the first whole part left out if any was, else the first value left
330// out, else the first. Every warning is listed beside it. It names no count of the others, so a `.ork` hpr writes, which states
331// the values this file left hpr to assume and so raises fewer warnings, gives the same reason
332// (ADR-302).
333fn incomplete(warnings: &[Warning]) -> Option<String> {
334 let skipped: Vec<&Warning> = warnings
335 .iter()
336 .filter(|w| {
337 ![recovery::DEPLOYMENT, recovery::DRAG, recovery::SEPARATION]
338 .iter()
339 .any(|segment| w.at.contains(segment))
340 })
341 .collect();
342 skipped
343 .iter()
344 .find(|w| w.kind == WarningKind::Skipped)
345 .or_else(|| skipped.iter().find(|w| w.kind == WarningKind::Dropped))
346 .or_else(|| skipped.first())
347 .map(|w| w.message.clone())
348}
349
350/// The rocket, its motors and its recovery, the warnings reading them raised, and the paths of
351/// the stages and components read.
352fn read_design(
353 file: &OrkFile,
354 supplied: &SuppliedCurves,
355) -> (Design, Vec<Warning>, std::collections::BTreeSet<String>) {
356 let (rocket, walked) = component::walk(&file.document);
357 let Imported {
358 value: rocket,
359 mut warnings,
360 } = rocket;
361 let incomplete = incomplete(&warnings);
362 let mut design = Design {
363 rocket,
364 motors: Motors::default(),
365 recovery: Recovery::default(),
366 simulations: Vec::new(),
367 extensions: Extensions::default(),
368 };
369 if let Some(element) = file.document.root.child("rocket") {
370 // The separations first: a configuration flies only if its stages come apart as hpr
371 // can fly them.
372 design.recovery =
373 recovery::read(element, &design.rocket, walked.devices, walked.separations);
374 design.motors = motors::read(
375 element,
376 &mut design.rocket,
377 motors::Airframe {
378 incomplete: incomplete.as_deref(),
379 separations: &design.recovery.separations,
380 },
381 &walked.mounts,
382 &file.attachments,
383 supplied,
384 &mut warnings,
385 );
386 }
387 (design, warnings, walked.read)
388}
389
390/// Reads a `.ork` file from its bytes: sniffs the container, unpacks it, and parses the design.
391///
392/// # Errors
393///
394/// Returns [`OrkError`] when the bytes are not a `.ork` at all, when the container is damaged,
395/// when no entry in it can be the design document, or when that document is not well-formed XML
396/// rooted at `<openrocket>` with a readable schema version. Everything a reader can go on from is
397/// a [`Warning`] instead.
398pub fn read(bytes: &[u8]) -> Result<Imported<OrkFile>, OrkError> {
399 let unpacked = container::unpack(bytes)?;
400 let mut warnings = unpacked.warnings;
401 let Unpacked {
402 container,
403 design_entry,
404 design,
405 attachments,
406 } = unpacked.value;
407 let document = Document::parse(&design)?;
408 warnings.extend(document.warnings);
409 let document = document.value;
410 Ok(Imported {
411 value: OrkFile {
412 container,
413 design_entry,
414 document,
415 attachments,
416 },
417 warnings,
418 })
419}
420
421#[cfg(test)]
422mod tests;