hpr_io/ork/value.rs
1//! Reading the values a `.ork` writes inside its elements.
2//!
3//! Every later step walks the document tree and asks it for numbers, counts, flags and
4//! dimensions. Three things make that less simple than it sounds, and all three are mistakes Loft
5//! made:
6//!
7//! - **A dimension may be automatic.** `<outerradius>auto 0.0125</outerradius>` means "OpenRocket
8//! works this out from the neighbors, and 0.0125 m is what it last worked out". Keeping only
9//! the number turns an automatic dimension into a hand-typed one the next time the design is
10//! saved ([Loft lesson L58][lessons]). [`Dimension`] keeps both.
11//! - **A tag may have two names.** OpenRocket renamed several, and writes both for older readers.
12//! The reader takes the first name it finds, newest first ([Loft lesson L62][lessons]).
13//! - **A stated zero is a value.** `<overridecd>0.0</overridecd>` means no drag at all, not "no
14//! override". Loft read it as missing and charged the part full drag
15//! ([Loft lesson L63][lessons]).
16//!
17//! [lessons]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/loft-lessons.md
18
19use serde::{Deserialize, Serialize};
20
21use super::document::Element;
22use super::warning::{AS_IF_NOT_GIVEN, Warning, WarningKind};
23
24/// The two names OpenRocket writes a component's distance along its parent under.
25///
26/// `position` carries a `type` attribute and `axialoffset` a `method`, with the same vocabulary
27/// (`top`, `middle`, `bottom`, `after`, `absolute`), and **Observed:** on all 642 elements of the
28/// reference corpus that carry both, the two agree on the text *and* on that attribute.
29pub const AXIAL_OFFSET: [&str; 2] = ["axialoffset", "position"];
30
31/// The two names for how many of an instanced component there are (fins, rail buttons, pods).
32///
33/// **Observed:** 109 elements carry both, agreeing every time. Neither carries an attribute, so a
34/// count is the one value here that a rename cannot change the meaning of.
35pub const INSTANCE_COUNT: [&str; 2] = ["instancecount", "fincount"];
36
37/// The flags that say whether a component's overrides cover the components inside it: the single
38/// one files before schema 1.9 write, then one per quantity. Which of them wins is their order in
39/// the file ([`Values::overrides`]).
40pub(crate) const OVERRIDE_FLAGS: [&str; 4] = [
41 "overridesubcomponents",
42 "overridesubcomponentsmass",
43 "overridesubcomponentscg",
44 "overridesubcomponentscd",
45];
46
47// `angleoffset`/`radialdirection` and `radiusoffset`/`radialposition` are deliberately **not**
48// here. They look like the two pairs above, and they are not: the newer name of each carries a
49// `method` attribute (the frame the number is measured in) that the older name never carries.
50// `cargo xtask ork` measures it: of the 26 elements with both `angleoffset` and `radialdirection`
51// the texts agree every time and the frames differ every time, and `radiusoffset` (106 elements)
52// and `radialposition` (542) are never written together at all. Reading one as the other would
53// silently move a component, so settling what the older name's frame is belongs to the milestone
54// that places components (M3.1b2), with a source, not to a constant here. See the `.ork` page:
55// <https://hpr.fusionspace.co/format/ork.html>.
56
57/// A number a `.ork` writes, which OpenRocket may be working out for itself.
58#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
59#[serde(rename_all = "snake_case", tag = "kind")]
60#[non_exhaustive]
61#[serde(deny_unknown_fields)]
62pub enum Dimension {
63 /// A number the designer typed.
64 Stated {
65 /// The number, in whatever unit the tag is written in.
66 value: f64,
67 },
68 /// A number OpenRocket works out from the neighboring components.
69 Automatic {
70 /// What it last worked out, when the file says (`auto 0.0125`). A bare `auto` gives
71 /// `None`. Either way this is a cached answer, not an input: a reader that resolves the
72 /// dimension itself should prefer its own.
73 cached: Option<f64>,
74 },
75}
76
77impl Dimension {
78 /// The number, whether it was typed or cached. `None` for a bare `auto`.
79 pub fn value(self) -> Option<f64> {
80 match self {
81 Self::Stated { value } => Some(value),
82 Self::Automatic { cached } => cached,
83 }
84 }
85
86 /// Whether OpenRocket works this dimension out for itself.
87 pub fn is_automatic(self) -> bool {
88 matches!(self, Self::Automatic { .. })
89 }
90
91 /// Reads a dimension from an element's text, or `None` when the text is neither a finite
92 /// number nor `auto`.
93 ///
94 /// Only a tag that *holds* a dimension should be read this way. `<ignitionevent>automatic
95 /// </ignitionevent>` is a word, not a number, and gives `None` rather than an automatic
96 /// dimension.
97 pub fn parse(text: &str) -> Option<Self> {
98 let text = text.trim();
99 if let Some(rest) = text.strip_prefix("auto") {
100 if rest.is_empty() {
101 return Some(Self::Automatic { cached: None });
102 }
103 // `auto` is a word: `auto 0.025` is a cached dimension, `auto-1` and `automatic` are
104 // not this tag's business.
105 let cached = rest.strip_prefix(char::is_whitespace)?.trim();
106 return finite(cached).map(|cached| Self::Automatic {
107 cached: Some(cached),
108 });
109 }
110 finite(text).map(|value| Self::Stated { value })
111 }
112}
113
114/// Reads a `.ork` element's child values, collecting a warning for anything it cannot.
115///
116/// Borrowed rather than owned so that walking a tree costs nothing: make one per element.
117#[derive(Debug)]
118pub struct Values<'a> {
119 element: &'a Element,
120 at: &'a str,
121 warnings: &'a mut Vec<Warning>,
122}
123
124impl<'a> Values<'a> {
125 /// Reads the children of `element`, reporting anything odd as happening at `at`.
126 pub fn new(element: &'a Element, at: &'a str, warnings: &'a mut Vec<Warning>) -> Self {
127 Self {
128 element,
129 at,
130 warnings,
131 }
132 }
133
134 /// The first child called one of `names`, newest name first.
135 ///
136 /// When more than one is present they are checked against each other, on the text **and** on
137 /// the `method`/`type` attribute that says what the text is measured from: in the reference
138 /// corpus OpenRocket agrees with itself on both, every time. A disagreement is therefore worth
139 /// a warning, and the first name still wins. The name that lost says something the design
140 /// does not hold, so it is kept as written, in `x-openrocket`.
141 pub fn element(&mut self, names: &[&str]) -> Option<&'a Element> {
142 let mut found: Option<&'a Element> = None;
143 for name in names {
144 super::reads::note(self.element, name);
145 let Some(child) = self.element.child(name) else {
146 continue;
147 };
148 let Some(first) = found else {
149 found = Some(child);
150 continue;
151 };
152 let (winner, loser) = (first.name.clone(), child.name.clone());
153 let disagree =
154 first.text().trim() != child.text().trim() || frame(first) != frame(child);
155 if disagree {
156 super::reads::forget(self.element, &loser);
157 }
158 if first.text().trim() != child.text().trim() {
159 self.warn(
160 WarningKind::Dropped,
161 format!(
162 "`{winner}` says `{}` and `{loser}` says `{}`; they are two names for one \
163 value, so `{winner}` was taken",
164 first.text().trim(),
165 child.text().trim()
166 ),
167 );
168 } else if frame(first) != frame(child) {
169 self.warn(
170 WarningKind::Dropped,
171 format!(
172 "`{winner}` and `{loser}` both say `{}` but measure it from {} and {}; \
173 `{winner}` was taken",
174 first.text().trim(),
175 named(frame(first)),
176 named(frame(child))
177 ),
178 );
179 }
180 }
181 found
182 }
183
184 /// The text of the first child called one of `names`, trimmed. An empty tag gives `""`.
185 pub fn word(&mut self, names: &[&str]) -> Option<String> {
186 self.element(names)
187 .map(|child| child.text().trim().to_owned())
188 }
189
190 /// A number. A tag whose text is not a finite number is ignored, with a warning.
191 pub fn number(&mut self, names: &[&str]) -> Option<f64> {
192 let child = self.element(names)?;
193 let text = child.text();
194 match finite(text.trim()) {
195 Some(value) => Some(value),
196 None => {
197 let name = child.name.clone();
198 self.warn(
199 WarningKind::Dropped,
200 format!(
201 "`{name}` says `{}`, which is not a number; it was left out, \
202 {AS_IF_NOT_GIVEN}",
203 text.trim()
204 ),
205 );
206 self.forget(names);
207 None
208 }
209 }
210 }
211
212 /// A count. A negative or fractional one is ignored, with a warning.
213 pub fn count(&mut self, names: &[&str]) -> Option<u32> {
214 let value = self.number(names)?;
215 let rounded = value.round();
216 if rounded < 0.0 || rounded > f64::from(u32::MAX) || (value - rounded).abs() > 1e-9 {
217 self.warn(
218 WarningKind::Dropped,
219 format!(
220 "a count of `{value}` is not a whole number of things; it was left out, \
221 {AS_IF_NOT_GIVEN}"
222 ),
223 );
224 self.forget(names);
225 return None;
226 }
227 // The bounds above are what make this cast exact.
228 #[expect(
229 clippy::cast_possible_truncation,
230 clippy::cast_sign_loss,
231 reason = "checked to be a whole number within u32 on the line above"
232 )]
233 Some(rounded as u32)
234 }
235
236 /// A `true`/`false` flag. Anything else is ignored, with a warning.
237 pub fn flag(&mut self, names: &[&str]) -> Option<bool> {
238 let child = self.element(names)?;
239 match child.text().trim() {
240 "true" => Some(true),
241 "false" => Some(false),
242 other => {
243 let name = child.name.clone();
244 let other = other.to_owned();
245 self.warn(
246 WarningKind::Dropped,
247 format!(
248 "`{name}` says `{other}`, which is neither true nor false; it was left \
249 out, {AS_IF_NOT_GIVEN}"
250 ),
251 );
252 self.forget(names);
253 None
254 }
255 }
256 }
257
258 /// A dimension, which may be `auto` with or without the number OpenRocket last worked out.
259 pub fn dimension(&mut self, names: &[&str]) -> Option<Dimension> {
260 let child = self.element(names)?;
261 let text = child.text();
262 match Dimension::parse(&text) {
263 Some(dimension) => Some(dimension),
264 None => {
265 let name = child.name.clone();
266 self.warn(
267 WarningKind::Dropped,
268 format!(
269 "`{name}` says `{}`, which is neither a number nor `auto`; it was left \
270 out, {AS_IF_NOT_GIVEN}",
271 text.trim()
272 ),
273 );
274 self.forget(names);
275 None
276 }
277 }
278 }
279
280 /// Records a warning about the element being read, for a caller that decided something this
281 /// reader could not.
282 pub fn warn_at(&mut self, kind: WarningKind, message: impl Into<String>) {
283 self.warn(kind, message.into());
284 }
285
286 /// Records that what the children called any of `names` say was dropped or simplified, not
287 /// read into the design, so that each is kept as written ([`super::reads::forget`]) and an
288 /// export writes it back.
289 pub(crate) fn forget(&mut self, names: &[&str]) {
290 for name in names {
291 super::reads::forget(self.element, name);
292 }
293 }
294
295 /// The mass, center of gravity and drag a component's own figures are replaced by, and
296 /// whether each covers the components inside this one.
297 ///
298 /// Until schema 1.9 a file said that last once, with `overridesubcomponents`, for all three
299 /// quantities. OpenRocket 24.12 reads that flag, in schema 1.4, 1.8 and 1.10 files alike, as
300 /// setting all three, and where a component writes it beside a per-quantity flag, the tag
301 /// written later wins, quantity by quantity: measured on probe designs
302 /// ([M2.2e6][m2-2e6], [ADR-095][adr-095]), whose answers `hpr_validate::openrocket` holds HPR Sim
303 /// to. This reads it the same way. A flag tag written twice on one component is read at its
304 /// first copy only, and warned of, since which copy OpenRocket takes is not measured. What the
305 /// design does not hold (a flag read at one copy of two, or the single older flag beside a
306 /// drag override, which the design says per quantity) is kept as written, the flags all
307 /// together, so that an export writes back what the file said, in its order.
308 ///
309 /// [m2-2e6]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m2-2e6
310 /// [adr-095]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-095-the-single-pre-19-override-flag-read-as-openrocket-reads-it-2026-09-27
311 pub fn overrides(&mut self) -> Overrides {
312 let mass_kg = self.number(&["overridemass"]);
313 let cg_m = self.number(&["overridecg"]);
314 let cd = self.number(&["overridecd"]);
315 let all = self.placed_flag("overridesubcomponents");
316 let [mass, cg, drag] = [
317 "overridesubcomponentsmass",
318 "overridesubcomponentscg",
319 "overridesubcomponentscd",
320 ]
321 .map(|name| match (self.placed_flag(name), all) {
322 (Some((own, own_at)), Some((all, all_at))) => {
323 Some(if all_at > own_at { all } else { own })
324 }
325 (Some((own, _)), None) => Some(own),
326 (None, Some((all, _))) => Some(all),
327 (None, None) => None,
328 });
329 // What the design does not hold is kept as written. The flags are kept together when any
330 // one is, since which of them wins is their order in the file, and a kept tag goes back
331 // after the ones an export writes.
332 let dropped_flag = OVERRIDE_FLAGS.iter().any(|name| {
333 let mut copies = self.element.children_named(name);
334 let first = copies.next();
335 copies.next().is_some()
336 || first.is_some_and(|flag| !matches!(flag.text().trim(), "true" | "false"))
337 });
338 // The single older flag covers drag too: beside a drag override, it is kept as written.
339 let drag_stated = ["overridecd", "overridesubcomponentscd"]
340 .iter()
341 .any(|name| self.element.child(name).is_some());
342 if dropped_flag || (drag_stated && all.is_some()) {
343 self.forget(&OVERRIDE_FLAGS);
344 }
345 Overrides {
346 mass_kg,
347 cg_m,
348 cd,
349 subcomponents_mass: mass,
350 subcomponents_cg: cg,
351 subcomponents_cd: drag,
352 }
353 }
354
355 /// The flag called `name`, and where it stands among the element's children in document
356 /// order. A tag written more than once is read at its first copy, with a warning.
357 fn placed_flag(&mut self, name: &str) -> Option<(bool, usize)> {
358 let copies = self.element.children_named(name).count();
359 if copies > 1 {
360 self.warn(
361 WarningKind::Dropped,
362 format!("`{name}` is written {copies} times; only the first is read"),
363 );
364 }
365 let value = self.flag(&[name])?;
366 let place = self
367 .element
368 .elements()
369 .position(|child| child.name == name)?;
370 Some((value, place))
371 }
372
373 fn warn(&mut self, kind: WarningKind, message: impl Into<String>) {
374 self.warnings.push(Warning::new(self.at, kind, message));
375 }
376}
377
378/// What a component says its own mass, center of gravity and drag coefficient are, instead of
379/// what its geometry and material would give.
380///
381/// The three values and the three flags are independent, which is [Loft lesson L63: Loft read
382/// neither `overridecd` nor `overridesubcomponentscg`, so a part set to a drag coefficient of zero
383/// was still charged full drag][lessons]. A stated `0.0` here is an override to zero, not a
384/// missing one.
385///
386/// [lessons]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/loft-lessons.md
387#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
388#[non_exhaustive]
389pub struct Overrides {
390 /// The mass the component is declared to have, in kilograms.
391 pub mass_kg: Option<f64>,
392 /// Where its center of gravity is declared to be, in meters from its fore end.
393 pub cg_m: Option<f64>,
394 /// The drag coefficient it is declared to have.
395 pub cd: Option<f64>,
396 /// Whether the mass override covers the components inside this one too.
397 pub subcomponents_mass: Option<bool>,
398 /// Whether the center-of-gravity override covers them.
399 pub subcomponents_cg: Option<bool>,
400 /// Whether the drag override covers them.
401 pub subcomponents_cd: Option<bool>,
402}
403
404/// What a placement tag says its number is measured from: `method` on the newer name of a pair,
405/// `type` on the older.
406fn frame(element: &Element) -> Option<&str> {
407 element
408 .attribute("method")
409 .or_else(|| element.attribute("type"))
410}
411
412fn named(frame: Option<&str>) -> String {
413 frame.map_or_else(|| "nowhere stated".to_owned(), |frame| format!("`{frame}`"))
414}
415
416/// Rust also parses `inf` and `NaN`, which no design file means.
417fn finite(text: &str) -> Option<f64> {
418 text.parse::<f64>().ok().filter(|value| value.is_finite())
419}