Skip to main content

hpr_io/orc/
mod.rs

1//! OpenRocket's `.orc` parts catalogs: nose cones, tubes, rings, transitions, parachutes and
2//! streamers as their makers sell them, by maker and part number.
3//!
4//! A `.orc` file is XML: an `<OpenRocketComponent>` root holding a `<Version>`, a `<Materials>`
5//! list (each a name, a density, the density's units and its kind: `BULK`, `SURFACE` or `LINE`)
6//! and a `<Components>` list of parts. A part names its maker, part number and description, its
7//! dimensions each with its own `Unit` attribute, and its material by name and kind; the material
8//! must be defined in the same file. The format has no published schema; its field list and units
9//! are the ones the `openrocket-database` project documents (`docs/TechnicalInfo.md` at the pinned
10//! commit), and what each field means is what OpenRocket 24.12's preset loader makes of it,
11//! measured by running that loader on the same files as an oracle
12//! (`validation/oracles/openrocket/orc_presets.py`).
13//!
14//! [`read`] reads one file into a [`Catalog`]. [`bundled`] is the catalog OpenRocket 24.12
15//! ships: the 16 files of `openrocket-database` (Apache-2.0) at the commit
16//! `validation/refs.lock.toml` pins, compiled into this crate unchanged, 3,449 parts.
17//! [`Catalog::find`] looks a part up by maker and part number.
18//!
19//! **What is read, and how far it agrees with OpenRocket.** Every value is converted to SI as the
20//! file states it: lengths in meters, masses in kilograms, densities in kg/m³, kg/m² or kg/m. On
21//! the bundled files, every part OpenRocket reads is read here, in the same order, and every
22//! value equals OpenRocket's bit for bit (17,911 of 18,306 numbers), with four exceptions that the
23//! test `crates/hpr-io/tests/orc_openrocket.rs` counts:
24//!
25//! - **Ounces.** OpenRocket's ounce is 0.0283495231 kg; the avoirdupois ounce is exactly
26//!   0.028349523125 kg (NIST Handbook 44, Appendix C), and that is the one used here. The
27//!   difference is 9e-10 of the value, on the 185 masses stated in ounces. OpenRocket rounds a
28//!   few other imperial factors the same way (`lb/ft³`, `oz/in²`, `oz/ft²`, `lb/ft²`, `oz/ft`);
29//!   no bundled file uses them.
30//! - **Makers' names.** OpenRocket shows two makers under names of its own: "LOC Precision" as
31//!   "LOC/Precision" and "Public Missiles" as "Public Missiles, Ltd." The name here is the file's.
32//! - **A stated mass.** When a solid part states its mass, OpenRocket replaces its material's
33//!   density with the one that gives the part that mass. Here the material keeps the file's
34//!   density and the part keeps its mass ([`Part::mass_kg`]), which a design built from the part
35//!   by hand can set as its mass. This is 207 parts; with the masses taken out of the files,
36//!   OpenRocket's density is the one read here on every one of them. A parachute's or streamer's
37//!   stated mass leaves its fabric's density alone, here and in OpenRocket.
38//! - **Undefined materials.** A material the file names but doesn't define has no density here
39//!   ([`MaterialRef::density`] is `None`); OpenRocket gives it zero. This is 3 parts.
40//!
41//! **What the file leaves unsaid.** No `.orc` field gives a nose or transition shape's parameter
42//! (an ogive's radius, a Haack series' `C`), a shoulder's wall, or a parachute's drag coefficient;
43//! OpenRocket uses its own defaults for these when a part is put in a design. A part's material
44//! is only as good as the file's density, and the database's own README warns to weigh real parts.
45//!
46//! **Warnings.** A part or material that can't be read is left out with a [`Warning`] saying why,
47//! rather than failing the file; so are fields ignored or repeated, and values read as written but
48//! implausible (an inside diameter not less than the outside, a solid lighter than air, a fabric
49//! under 1 g/m²). The bundled files give 55.
50
51mod bundled;
52#[cfg(test)]
53mod tests;
54
55pub use bundled::{BUNDLED_FILES, bundled};
56
57use serde::{Deserialize, Serialize};
58
59use crate::ork::{NOTHING_DEPENDS, nothing_depends};
60
61/// The most characters of a file's text a warning or an error quotes.
62const QUOTE_LIMIT: usize = 64;
63
64/// A `.orc` file that can't be read at all.
65#[derive(Debug, Clone, PartialEq, thiserror::Error)]
66#[non_exhaustive]
67pub enum OrcError {
68    /// The elements nest deeper than [`MAX_DEPTH`]. Checked before the XML is parsed, as the
69    /// parser descends the tree and a file nested deep enough would exhaust the stack.
70    #[error("the elements nest {depth} deep, past the {limit} this reads")]
71    TooDeep {
72        /// [`MAX_DEPTH`].
73        limit: usize,
74        /// The nesting found, or more.
75        depth: usize,
76    },
77    /// The text is not well-formed XML.
78    #[error("not well-formed XML: {reason}")]
79    Xml {
80        /// The XML parser's message.
81        reason: String,
82    },
83    /// The root element is not `<OpenRocketComponent>`.
84    #[error("the root element is <{root}>, not <OpenRocketComponent>: not a parts catalog")]
85    NotACatalog {
86        /// The root element's name, shortened.
87        root: String,
88    },
89}
90
91/// The deepest nesting read. A `.orc` nests four deep (the root, the parts list, a part, its
92/// field); the parser below has been seen to exhaust a 2 MiB stack at 130 levels (the `.ork`
93/// reader's measurement, [`crate::ork::MAX_DEPTH`]).
94pub const MAX_DEPTH: usize = 16;
95
96/// The most warnings one file gives; past it, one last warning says how many more there were.
97pub const MAX_WARNINGS: usize = 1000;
98
99/// What a [`Warning`] is about.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102#[non_exhaustive]
103pub enum WarningKind {
104    /// A part was left out: a size missing, unreadable or below zero, a unit or shape the reader
105    /// doesn't take, a material of the wrong kind, a value holding an element, or an element that
106    /// isn't a kind of part.
107    PartLeftOut,
108    /// A material was left out: an unknown unit or kind, no density, a density below zero or too
109    /// large for an `f64`, or a name or kind holding an element.
110    MaterialLeftOut,
111    /// A part names a material its file doesn't define; it has no density.
112    MaterialUndefined,
113    /// A file defines two materials of the same name and kind with different densities; parts
114    /// take the first.
115    MaterialRepeated,
116    /// Fields a part's kind doesn't have, elements beside the catalog's lists, or a `<Version>`
117    /// holding an element, were ignored.
118    Ignored,
119    /// A field or a list was stated more than once; the last was read.
120    Repeated,
121    /// A value read as written that can't be right: a wall of no thickness or less, a solid
122    /// lighter than air, or a fabric lighter than any made.
123    Implausible,
124    /// [`MAX_WARNINGS`] were given; the rest are counted, not listed.
125    TooMany,
126}
127
128/// Something read differently from what the file says, or left out. Reading goes on.
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130#[non_exhaustive]
131pub struct Warning {
132    /// Where: the part's maker and number, `Materials: ` and a material's name, or the file.
133    pub at: String,
134    /// What kind of warning.
135    pub kind: WarningKind,
136    /// What happened, in a sentence.
137    pub message: String,
138}
139
140/// A catalog file read, with what was left out of it.
141#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
142#[non_exhaustive]
143pub struct CatalogFile {
144    /// The parts read, in the file's order.
145    pub catalog: Catalog,
146    /// The file's `<Version>`, as written; `None` if it has none.
147    pub version: Option<String>,
148    /// The materials the file defines, in its order.
149    pub materials: Vec<CatalogMaterial>,
150    /// Parts left out and values read differently, one entry each, at most [`MAX_WARNINGS`] and
151    /// one more.
152    pub warnings: Vec<Warning>,
153}
154
155/// Parts, from one catalog file or several.
156#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
157pub struct Catalog {
158    /// Every part, in file order.
159    pub parts: Vec<Part>,
160}
161
162/// One part as its catalog lists it.
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
164#[non_exhaustive]
165pub struct Part {
166    /// The catalog file it came from, such as `estes_classic.orc`.
167    pub file: String,
168    /// The maker, as the file writes it.
169    pub manufacturer: String,
170    /// The maker's part number, as the file writes it.
171    pub part_number: String,
172    /// The file's description; empty if it has none. A part that states two keeps the last, as
173    /// OpenRocket does.
174    pub description: String,
175    /// The part's mass as the file states it, kg; `None` for most parts, whose mass follows from
176    /// their size and material.
177    pub mass_kg: Option<f64>,
178    /// What kind of part, with its dimensions.
179    pub kind: PartKind,
180}
181
182/// A part's kind and dimensions.
183///
184/// The five tube-like kinds share [`Tube`]'s fields, as the format gives them: an inner and
185/// outer diameter and a length (a centering ring's length is its thickness).
186#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
187#[serde(tag = "kind", rename_all = "snake_case")]
188#[non_exhaustive]
189pub enum PartKind {
190    /// An airframe tube (`<BodyTube>`).
191    BodyTube(Tube),
192    /// A coupler that joins two tubes (`<TubeCoupler>`); an inner diameter of zero makes it a
193    /// solid nose block.
194    TubeCoupler(Tube),
195    /// A ring that stops the motor moving forward (`<EngineBlock>`).
196    EngineBlock(Tube),
197    /// A ring that holds an inner tube in an outer one (`<CenteringRing>`).
198    CenteringRing(Tube),
199    /// A launch lug (`<LaunchLug>`).
200    LaunchLug(Tube),
201    /// A solid disc (`<BulkHead>`).
202    Bulkhead(Bulkhead),
203    /// A nose cone (`<NoseCone>`).
204    NoseCone(NoseCone),
205    /// A transition between two diameters (`<Transition>`).
206    Transition(Transition),
207    /// A parachute (`<Parachute>`).
208    Parachute(Parachute),
209    /// A streamer (`<Streamer>`).
210    Streamer(Streamer),
211}
212
213/// A tube-like part: a body tube, coupler, engine block, centering ring or launch lug.
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215#[non_exhaustive]
216pub struct Tube {
217    /// Inner diameter, m.
218    pub inner_diameter_m: f64,
219    /// Outer diameter, m.
220    pub outer_diameter_m: f64,
221    /// Length, m.
222    pub length_m: f64,
223    /// Material (bulk).
224    pub material: MaterialRef,
225}
226
227impl Tube {
228    /// The wall's thickness, m: `(outer diameter − inner diameter)/2`, as OpenRocket works it out.
229    #[must_use]
230    pub fn thickness_m(&self) -> f64 {
231        (self.outer_diameter_m - self.inner_diameter_m) / 2.0
232    }
233}
234
235/// A bulkhead: a solid disc.
236#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
237#[non_exhaustive]
238pub struct Bulkhead {
239    /// Outer diameter, m.
240    pub outer_diameter_m: f64,
241    /// Length (thickness), m.
242    pub length_m: f64,
243    /// `<Filled>` as written; `None` if absent. A bulkhead is solid either way.
244    pub filled: Option<bool>,
245    /// Material (bulk).
246    pub material: MaterialRef,
247}
248
249/// A nose cone.
250#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
251#[non_exhaustive]
252pub struct NoseCone {
253    /// Profile shape. The file gives no shape parameter.
254    pub shape: Shape,
255    /// Length from tip to base, not counting the shoulder, m.
256    pub length_m: f64,
257    /// Base diameter, m.
258    pub outer_diameter_m: f64,
259    /// Shoulder diameter, m; zero for no shoulder.
260    pub shoulder_diameter_m: f64,
261    /// Shoulder length, m; zero for no shoulder.
262    pub shoulder_length_m: f64,
263    /// `<Filled>` as written; `None` if absent.
264    pub filled: Option<bool>,
265    /// Wall thickness, m; `None` if absent.
266    pub thickness_m: Option<f64>,
267    /// Material (bulk).
268    pub material: MaterialRef,
269}
270
271/// A transition.
272#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
273#[non_exhaustive]
274pub struct Transition {
275    /// Profile shape. The file gives no shape parameter.
276    pub shape: Shape,
277    /// Length, not counting shoulders, m.
278    pub length_m: f64,
279    /// Forward outer diameter, m.
280    pub fore_outer_diameter_m: f64,
281    /// Forward shoulder diameter, m; zero for none.
282    pub fore_shoulder_diameter_m: f64,
283    /// Forward shoulder length, m; zero for none.
284    pub fore_shoulder_length_m: f64,
285    /// Aft outer diameter, m.
286    pub aft_outer_diameter_m: f64,
287    /// Aft shoulder diameter, m; zero for none.
288    pub aft_shoulder_diameter_m: f64,
289    /// Aft shoulder length, m; zero for none.
290    pub aft_shoulder_length_m: f64,
291    /// `<Filled>` as written; `None` if absent.
292    pub filled: Option<bool>,
293    /// Wall thickness, m; `None` if absent.
294    pub thickness_m: Option<f64>,
295    /// Material (bulk).
296    pub material: MaterialRef,
297}
298
299/// A parachute.
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301#[non_exhaustive]
302pub struct Parachute {
303    /// Canopy diameter, m.
304    pub diameter_m: f64,
305    /// The canopy's number of sides.
306    pub sides: u32,
307    /// Number of shroud lines.
308    pub line_count: u32,
309    /// Length of each shroud line, m.
310    pub line_length_m: f64,
311    /// Canopy fabric (surface).
312    pub material: MaterialRef,
313    /// Shroud-line cord (line); `None` if the file names none.
314    pub line_material: Option<MaterialRef>,
315}
316
317/// A streamer.
318#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
319#[non_exhaustive]
320pub struct Streamer {
321    /// Length, m.
322    pub length_m: f64,
323    /// Width, m.
324    pub width_m: f64,
325    /// Thickness, m. The database notes OpenRocket may make no use of it.
326    pub thickness_m: f64,
327    /// Material (surface).
328    pub material: MaterialRef,
329}
330
331/// A nose cone's or transition's profile, as the file names it.
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
333#[serde(rename_all = "snake_case")]
334#[non_exhaustive]
335pub enum Shape {
336    /// `CONICAL`.
337    Conical,
338    /// `OGIVE`.
339    Ogive,
340    /// `ELLIPSOID`.
341    Ellipsoid,
342    /// `PARABOLIC`: a parabolic series.
343    Parabolic,
344    /// `HAACK`: a Haack series.
345    Haack,
346    /// `POWER`: a power series.
347    Power,
348}
349
350impl Shape {
351    /// The shape named by `word`, as the format spells it.
352    fn parse(word: &str) -> Option<Self> {
353        Some(match word {
354            "CONICAL" => Self::Conical,
355            "OGIVE" => Self::Ogive,
356            "ELLIPSOID" => Self::Ellipsoid,
357            "PARABOLIC" => Self::Parabolic,
358            "HAACK" => Self::Haack,
359            "POWER" => Self::Power,
360            _ => return None,
361        })
362    }
363}
364
365/// The kind of density a material has.
366#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
367#[serde(rename_all = "snake_case")]
368#[non_exhaustive]
369pub enum MaterialKind {
370    /// Mass per volume, kg/m³: anything solid.
371    Bulk,
372    /// Mass per area, kg/m²: canopy and streamer fabric.
373    Surface,
374    /// Mass per length, kg/m: shroud lines.
375    Line,
376}
377
378impl MaterialKind {
379    /// The kind named by `word`, as the format spells it.
380    fn parse(word: &str) -> Option<Self> {
381        Some(match word {
382            "BULK" => Self::Bulk,
383            "SURFACE" => Self::Surface,
384            "LINE" => Self::Line,
385            _ => return None,
386        })
387    }
388}
389
390/// A material a catalog file defines.
391#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
392#[non_exhaustive]
393pub struct CatalogMaterial {
394    /// Its name.
395    pub name: String,
396    /// Its kind.
397    pub kind: MaterialKind,
398    /// Its density in SI units of its kind: kg/m³, kg/m² or kg/m.
399    pub density: f64,
400}
401
402/// The material a part names, with the density its file defines for it.
403#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
404#[non_exhaustive]
405pub struct MaterialRef {
406    /// The name the part gives.
407    pub name: String,
408    /// The kind the part gives.
409    pub kind: MaterialKind,
410    /// The density in SI units of its kind, from the first material of that name and kind the
411    /// file defines; `None` if it defines none.
412    pub density: Option<f64>,
413}
414
415impl MaterialRef {
416    /// The material as `hpr_design` holds it, or `None` if the file doesn't define it.
417    #[must_use]
418    pub fn material(&self) -> Option<hpr_design::Material> {
419        let density = self.density?;
420        Some(match self.kind {
421            MaterialKind::Bulk => hpr_design::Material::bulk(self.name.clone(), density),
422            MaterialKind::Surface => hpr_design::Material::surface(self.name.clone(), density),
423            MaterialKind::Line => hpr_design::Material::line(self.name.clone(), density),
424        })
425    }
426}
427
428impl Catalog {
429    /// Every part whose maker is `manufacturer` and whose part number is `part_number`, in
430    /// catalog order. Both are compared with surrounding spaces trimmed, the maker in any case
431    /// and the part number exactly. The maker is the file's name for it, not OpenRocket's display
432    /// name ("LOC Precision", not "LOC/Precision"). Most numbers name one part; in the bundled
433    /// catalog, 21 numbers name two parts of the same kind, and 3 of those pairs are identical.
434    #[must_use]
435    pub fn find(&self, manufacturer: &str, part_number: &str) -> Vec<&Part> {
436        let manufacturer = manufacturer.trim().to_lowercase();
437        let part_number = part_number.trim();
438        self.parts
439            .iter()
440            .filter(|part| {
441                part.manufacturer.trim().to_lowercase() == manufacturer
442                    && part.part_number.trim() == part_number
443            })
444            .collect()
445    }
446
447    /// Every part whose part number or description holds `text`, in any case, from the maker
448    /// `manufacturer` (in any case) or from any maker if `None`, in catalog order; empty
449    /// `text` matches every part. Part numbers are often several numbers in one, such as Estes'
450    /// `BT-20, 30316`, which `find` matches only whole; a search for `30316` finds it.
451    #[must_use]
452    pub fn search(&self, manufacturer: Option<&str>, text: &str) -> Vec<&Part> {
453        let text = text.trim().to_lowercase();
454        let manufacturer = manufacturer.map(|maker| maker.trim().to_lowercase());
455        self.parts
456            .iter()
457            .filter(|part| {
458                manufacturer
459                    .as_ref()
460                    .is_none_or(|maker| part.manufacturer.trim().to_lowercase() == *maker)
461                    && (part.part_number.to_lowercase().contains(&text)
462                        || part.description.to_lowercase().contains(&text))
463            })
464            .collect()
465    }
466
467    /// The makers, each once, in the order they first appear.
468    #[must_use]
469    pub fn manufacturers(&self) -> Vec<&str> {
470        let mut seen = std::collections::BTreeSet::new();
471        self.parts
472            .iter()
473            .map(|part| part.manufacturer.as_str())
474            .filter(|name| seen.insert(*name))
475            .collect()
476    }
477
478    /// Adds another catalog's parts after this one's.
479    pub fn extend(&mut self, other: Catalog) {
480        self.parts.extend(other.parts);
481    }
482}
483
484/// Reads one `.orc` file's text; `file` names it in each [`Part::file`].
485///
486/// Only text nested past [`MAX_DEPTH`], text that isn't XML, or a root that isn't
487/// `<OpenRocketComponent>` is refused. A part this can't read (a missing or unreadable size, a
488/// unit or shape it doesn't take, a material of the wrong kind, an element that isn't a kind of
489/// part) is left out with a warning, where OpenRocket 24.12 refuses the whole file for most of
490/// these. Fields a part's kind doesn't have are ignored with a warning, as is anything beside the
491/// three lists; a list stated twice keeps the last, as OpenRocket does, with a warning.
492///
493/// # Errors
494///
495/// [`OrcError::TooDeep`], [`OrcError::Xml`] and [`OrcError::NotACatalog`].
496pub fn read(text: &str, file: &str) -> Result<CatalogFile, OrcError> {
497    let depth = crate::ork::document::deepest_nesting(text);
498    if depth > MAX_DEPTH {
499        return Err(OrcError::TooDeep {
500            limit: MAX_DEPTH,
501            depth,
502        });
503    }
504    let document = roxmltree::Document::parse(text).map_err(|error| OrcError::Xml {
505        reason: error.to_string(),
506    })?;
507    let root = document.root_element();
508    if root.tag_name().name() != "OpenRocketComponent" {
509        return Err(OrcError::NotACatalog {
510            root: quote(root.tag_name().name()),
511        });
512    }
513    let mut warnings = Warnings::default();
514    let mut ignored: Vec<String> = Vec::new();
515    // Each list by name, the last of a repeated one kept: OpenRocket 24.12 reads only the last
516    // `<Materials>` and the last `<Components>` (the oracle's `second materials` and `second
517    // components` probes).
518    let mut lists: [(&str, Option<roxmltree::Node<'_, '_>>, usize); 3] = [
519        ("Version", None, 0),
520        ("Materials", None, 0),
521        ("Components", None, 0),
522    ];
523    for element in root.children().filter(roxmltree::Node::is_element) {
524        let name = element.tag_name().name();
525        match lists.iter_mut().find(|(list, _, _)| *list == name) {
526            Some((_, last, count)) => {
527                *last = Some(element);
528                *count += 1;
529            }
530            None => ignored.push(format!("<{}>", quote(name))),
531        }
532    }
533    for (name, _, count) in &lists {
534        if *count > 1 {
535            // The oracle's probes show it for the two lists, not for `<Version>`.
536            let reads = if *name == "Version" {
537                ""
538            } else {
539                ", as OpenRocket reads it"
540            };
541            warnings.push(
542                file,
543                WarningKind::Repeated,
544                format!("<{name}> is stated {count} times; the last was read{reads}"),
545            );
546        }
547    }
548    let [(_, version, _), (_, materials, _), (_, components, _)] = lists;
549    if !ignored.is_empty() {
550        warnings.push(
551            file,
552            WarningKind::Ignored,
553            format!(
554                "{} beside the catalog's lists {} left out, and {}",
555                listed(&ignored),
556                if ignored.len() == 1 { "was" } else { "were" },
557                nothing_depends(ignored.len())
558            ),
559        );
560    }
561    let version = version.and_then(|node| match value_text(node, "Version") {
562        Ok(text) => Some(text),
563        Err(why) => {
564            warnings.push(
565                file,
566                WarningKind::Ignored,
567                format!("{why}; it was left out, and {NOTHING_DEPENDS}"),
568            );
569            None
570        }
571    });
572    let (materials, index) = materials
573        .map(|list| read_materials(list, &mut warnings))
574        .unwrap_or_default();
575    let mut parts = Vec::new();
576    if let Some(list) = components {
577        for element in list.children().filter(roxmltree::Node::is_element) {
578            if let Some(part) = read_part(element, file, &materials, &index, &mut warnings) {
579                parts.push(part);
580            }
581        }
582    }
583    Ok(CatalogFile {
584        catalog: Catalog { parts },
585        version,
586        materials,
587        warnings: warnings.finish(file),
588    })
589}
590
591/// A file's warnings, up to [`MAX_WARNINGS`], and a count of the rest.
592#[derive(Default)]
593struct Warnings {
594    list: Vec<Warning>,
595    more: usize,
596}
597
598impl Warnings {
599    fn push(&mut self, at: &str, kind: WarningKind, message: String) {
600        if self.list.len() < MAX_WARNINGS {
601            self.list.push(Warning {
602                at: at.to_owned(),
603                kind,
604                message,
605            });
606        } else {
607            self.more += 1;
608        }
609    }
610
611    fn finish(mut self, file: &str) -> Vec<Warning> {
612        if self.more > 0 {
613            self.list.push(Warning {
614                at: file.to_owned(),
615                kind: WarningKind::TooMany,
616                message: format!("{} more warnings were not listed", self.more),
617            });
618        }
619        self.list
620    }
621}
622
623/// Up to the first five of `items`, joined, and how many more.
624fn listed(items: &[String]) -> String {
625    let shown = items.iter().take(5).cloned().collect::<Vec<_>>().join(", ");
626    match items.len() {
627        0..=5 => shown,
628        n => format!("{shown} and {} more", n - 5),
629    }
630}
631
632/// The first child element named `name`.
633fn child<'a, 'input>(
634    node: roxmltree::Node<'a, 'input>,
635    name: &str,
636) -> Option<roxmltree::Node<'a, 'input>> {
637    node.children()
638        .find(|child| child.is_element() && child.tag_name().name() == name)
639}
640
641/// An element's text, every text node joined, as written.
642fn text_of(node: roxmltree::Node<'_, '_>) -> String {
643    node.children()
644        .filter(roxmltree::Node::is_text)
645        .filter_map(|text| text.text())
646        .collect()
647}
648
649/// A value's text, or why it has none: an element inside a value is not part of the format.
650fn value_text(node: roxmltree::Node<'_, '_>, name: &str) -> Result<String, String> {
651    if node.children().any(|child| child.is_element()) {
652        Err(format!("<{name}> holds an element, not a value"))
653    } else {
654        Ok(text_of(node))
655    }
656}
657
658/// `text` cut to [`QUOTE_LIMIT`] characters, marked when cut.
659fn quote(text: &str) -> String {
660    match text.char_indices().nth(QUOTE_LIMIT) {
661        Some((end, _)) => format!("{}…", &text[..end]),
662        None => text.to_owned(),
663    }
664}
665
666/// A number as the format writes one: a finite decimal, spaces around it allowed.
667fn number(text: &str) -> Option<f64> {
668    text.trim()
669        .parse::<f64>()
670        .ok()
671        .filter(|value| value.is_finite())
672        // `-0` is zero.
673        .map(|value| value + 0.0)
674}
675
676/// The SI factor of a length unit. These are the length units OpenRocket 24.12 reads in a
677/// `.orc` (`docs/TechnicalInfo.md`'s list less `in/64`, which OpenRocket reads as inches); each
678/// factor is its exact definition (NIST Handbook 44, Appendix C: 1 in = 0.0254 m,
679/// 1 ft = 0.3048 m).
680fn length_factor(unit: &str) -> Option<f64> {
681    Some(match unit {
682        "m" => 1.0,
683        "cm" => 0.01,
684        "mm" => 0.001,
685        "in" => INCH_M,
686        "ft" => FOOT_M,
687        _ => return None,
688    })
689}
690
691/// The avoirdupois pound, kg (NIST Handbook 44, Appendix C).
692const POUND_KG: f64 = 0.453_592_37;
693/// The avoirdupois ounce, a sixteenth of a pound, kg.
694const OUNCE_KG: f64 = POUND_KG / 16.0;
695/// The inch, m.
696const INCH_M: f64 = 0.0254;
697/// The foot, m.
698const FOOT_M: f64 = 0.3048;
699
700/// The SI factor of a mass unit (exact definitions, as [`length_factor`]).
701fn mass_factor(unit: &str) -> Option<f64> {
702    Some(match unit {
703        "kg" => 1.0,
704        "g" => 0.001,
705        "oz" => OUNCE_KG,
706        "lb" => POUND_KG,
707        _ => return None,
708    })
709}
710
711/// The SI factor of a density unit of `kind`: the units `docs/TechnicalInfo.md` lists for each
712/// kind that OpenRocket 24.12 reads (it refuses a file with `oz/in`), from the exact definitions.
713fn density_factor(kind: MaterialKind, unit: &str) -> Option<f64> {
714    Some(match (kind, unit) {
715        (MaterialKind::Bulk, "kg/m3") => 1.0,
716        (MaterialKind::Bulk, "g/cm3" | "kg/dm3") => 1000.0,
717        (MaterialKind::Bulk, "lb/ft3") => POUND_KG / (FOOT_M * FOOT_M * FOOT_M),
718        (MaterialKind::Surface, "kg/m2") => 1.0,
719        (MaterialKind::Surface, "g/m2") => 0.001,
720        (MaterialKind::Surface, "g/cm2") => 10.0,
721        (MaterialKind::Surface, "oz/in2") => OUNCE_KG / (INCH_M * INCH_M),
722        (MaterialKind::Surface, "oz/ft2") => OUNCE_KG / (FOOT_M * FOOT_M),
723        (MaterialKind::Surface, "lb/ft2") => POUND_KG / (FOOT_M * FOOT_M),
724        (MaterialKind::Line, "kg/m") => 1.0,
725        (MaterialKind::Line, "g/m") => 0.001,
726        (MaterialKind::Line, "g/cm") => 0.1,
727        (MaterialKind::Line, "oz/ft") => OUNCE_KG / FOOT_M,
728        _ => return None,
729    })
730}
731
732/// The lightest fabric this reads without a warning, kg/m²: 1 g/m². The lightest correctly
733/// labeled in the bundled files is 0.3 mil polyethylene film at 7.05 g/m²; a canopy under 1 g/m²
734/// is a unit written wrong, as the six `g/m2` ripstop nylons of the bundled files are (0.067 g/m²
735/// for a fabric of about 67 g/m²).
736const LIGHTEST_FABRIC_KG_M2: f64 = 0.001;
737
738/// The lightest solid this reads without a warning, kg/m³: 1 kg/m³, below air at sea level
739/// (1.225 kg/m³). Two bundled files give a paper `0.0011` kg/m³, where paper is roughly 1,000
740/// kg/m³: the value or its unit is wrong.
741const LIGHTEST_SOLID_KG_M3: f64 = 1.0;
742
743impl MaterialKind {
744    /// The kind's name, for messages.
745    fn name(self) -> &'static str {
746        match self {
747            Self::Bulk => "bulk",
748            Self::Surface => "surface",
749            Self::Line => "line",
750        }
751    }
752}
753
754/// The `<Materials>` list. A material that can't be read is left out with a warning, so parts
755/// naming it read with no density.
756fn read_materials(
757    list: roxmltree::Node<'_, '_>,
758    warnings: &mut Warnings,
759) -> (Vec<CatalogMaterial>, MaterialIndex) {
760    let mut materials: Vec<CatalogMaterial> = Vec::new();
761    let mut index = MaterialIndex::new();
762    for element in list.children().filter(roxmltree::Node::is_element) {
763        let name = child(element, "Name").map(text_of).unwrap_or_default();
764        let at = format!("Materials: {}", quote(&name));
765        let left_out = |warnings: &mut Warnings, why: String| {
766            warnings.push(
767                &at,
768                WarningKind::MaterialLeftOut,
769                format!("{why}; it was left out, so a part naming it has no density"),
770            );
771        };
772        if element.tag_name().name() != "Material" {
773            let why = format!("<{}> is not a material", quote(element.tag_name().name()));
774            left_out(warnings, why);
775            continue;
776        }
777        if let Some(why) = ["Name", "Type"]
778            .into_iter()
779            .filter_map(|field| child(element, field).map(|node| (field, node)))
780            .find_map(|(field, node)| value_text(node, field).err())
781        {
782            left_out(warnings, why);
783            continue;
784        }
785        let Some(kind) = child(element, "Type")
786            .map(text_of)
787            .and_then(|word| MaterialKind::parse(word.trim()))
788        else {
789            left_out(
790                warnings,
791                "its <Type> is not BULK, SURFACE or LINE".to_owned(),
792            );
793            continue;
794        };
795        let Some((written, value)) = child(element, "Density")
796            .and_then(|node| value_text(node, "Density").ok())
797            .and_then(|text| number(&text).map(|value| (text, value)))
798        else {
799            left_out(
800                warnings,
801                "its <Density> is missing or not a number".to_owned(),
802            );
803            continue;
804        };
805        // A density with no units is read in SI, as OpenRocket 24.12 reads it (the oracle's
806        // `no units` probe).
807        let unit = element.attribute("UnitsOfMeasure").unwrap_or(match kind {
808            MaterialKind::Bulk => "kg/m3",
809            MaterialKind::Surface => "kg/m2",
810            MaterialKind::Line => "kg/m",
811        });
812        let Some(factor) = density_factor(kind, unit) else {
813            let why = format!(
814                "`{}` is not a unit of {} density this reads",
815                quote(unit),
816                kind.name()
817            );
818            left_out(warnings, why);
819            continue;
820        };
821        let density = value * factor;
822        if !density.is_finite() || density < 0.0 {
823            let why = format!(
824                "its density, {} {}, is not one a material has",
825                quote(written.trim()),
826                quote(unit)
827            );
828            left_out(warnings, why);
829            continue;
830        }
831        if let Some(first) = index
832            .get(&(kind, name.clone()))
833            .and_then(|&first| materials.get(first))
834            && first.density != density
835        {
836            warnings.push(
837                &at,
838                WarningKind::MaterialRepeated,
839                format!(
840                    "it is defined again with another density, {density} against {}; parts \
841                     take the first",
842                    first.density
843                ),
844            );
845        }
846        if kind == MaterialKind::Surface && density < LIGHTEST_FABRIC_KG_M2 {
847            warnings.push(
848                &at,
849                WarningKind::Implausible,
850                format!(
851                    "{value} {} is {density} kg/m², lighter than any fabric: the unit is likely \
852                     wrong; it was read as written, as OpenRocket reads it",
853                    quote(unit)
854                ),
855            );
856        }
857        if kind == MaterialKind::Bulk && density < LIGHTEST_SOLID_KG_M3 {
858            warnings.push(
859                &at,
860                WarningKind::Implausible,
861                format!(
862                    "{value} {} is {density} kg/m³, lighter than air: the value or its unit is \
863                     likely wrong; it was read as written, as OpenRocket reads it",
864                    quote(unit)
865                ),
866            );
867        }
868        index.entry((kind, name.clone())).or_insert(materials.len());
869        materials.push(CatalogMaterial {
870            name,
871            kind,
872            density,
873        });
874    }
875    (materials, index)
876}
877
878/// Where each material is in a file's list, by kind and name: the first of a name and kind.
879type MaterialIndex = std::collections::BTreeMap<(MaterialKind, String), usize>;
880
881/// Why a part was left out.
882struct Skip(String);
883
884/// The fields every kind of part has.
885const COMMON_FIELDS: &[&str] = &[
886    "Manufacturer",
887    "PartNumber",
888    "Description",
889    "Material",
890    "Mass",
891];
892
893/// One part, or `None` (with a warning) if it can't be read.
894fn read_part(
895    element: roxmltree::Node<'_, '_>,
896    file: &str,
897    materials: &[CatalogMaterial],
898    index: &MaterialIndex,
899    warnings: &mut Warnings,
900) -> Option<Part> {
901    let tag = element.tag_name().name();
902    // Each field by name, the last of a repeated one kept, as OpenRocket keeps it.
903    let mut fields: std::collections::BTreeMap<&str, (roxmltree::Node<'_, '_>, usize)> =
904        std::collections::BTreeMap::new();
905    for node in element.children().filter(roxmltree::Node::is_element) {
906        let entry = fields.entry(node.tag_name().name()).or_insert((node, 0));
907        *entry = (node, entry.1 + 1);
908    }
909    let text = |name: &str| fields.get(name).map(|(node, _)| text_of(*node));
910    let manufacturer = text("Manufacturer").unwrap_or_default();
911    let part_number = text("PartNumber").unwrap_or_default();
912    let at = format!("{} {}", quote(&manufacturer), quote(&part_number));
913    let Some(known) = known_fields(tag) else {
914        warnings.push(
915            &at,
916            WarningKind::PartLeftOut,
917            format!(
918                "<{}> is not a kind of part this reads; it was left out of the catalog",
919                quote(tag)
920            ),
921        );
922        return None;
923    };
924    let unknown: Vec<String> = fields
925        .keys()
926        .filter(|name| !known.contains(name) && !COMMON_FIELDS.contains(name))
927        .map(|name| format!("<{}>", quote(name)))
928        .collect();
929    if !unknown.is_empty() {
930        warnings.push(
931            &at,
932            WarningKind::Ignored,
933            format!(
934                "{} {} not a field of a <{tag}> OpenRocket reads; {} left out, and {}",
935                listed(&unknown),
936                if unknown.len() == 1 { "is" } else { "are" },
937                if unknown.len() == 1 {
938                    "it was"
939                } else {
940                    "they were"
941                },
942                nothing_depends(unknown.len())
943            ),
944        );
945    }
946    for (name, (_, count)) in &fields {
947        if *count > 1 && (known.contains(name) || COMMON_FIELDS.contains(name)) {
948            warnings.push(
949                &at,
950                WarningKind::Repeated,
951                format!(
952                    "<{name}> is stated {count} times; the last was read, as OpenRocket reads it"
953                ),
954            );
955        }
956    }
957    let get = |name: &str| fields.get(name).map(|(node, _)| *node);
958    match part(tag, &get, materials, index) {
959        Ok((kind, mass_kg)) => {
960            for material in kind.materials() {
961                if material.density.is_none() {
962                    warnings.push(
963                        &at,
964                        WarningKind::MaterialUndefined,
965                        format!(
966                            "its material `{}` is not defined in this file, so it has no density",
967                            quote(&material.name)
968                        ),
969                    );
970                }
971            }
972            if let Some(tube) = kind.tube()
973                && tube.inner_diameter_m >= tube.outer_diameter_m
974            {
975                warnings.push(
976                    &at,
977                    WarningKind::Implausible,
978                    format!(
979                        "its inside diameter, {} m, is not less than its outside diameter, {} \
980                         m, so its wall is {} m. It is read as written, as OpenRocket reads it",
981                        tube.inner_diameter_m,
982                        tube.outer_diameter_m,
983                        tube.thickness_m()
984                    ),
985                );
986            }
987            Some(Part {
988                file: file.to_owned(),
989                manufacturer,
990                part_number,
991                description: text("Description").unwrap_or_default(),
992                mass_kg,
993                kind,
994            })
995        }
996        Err(Skip(reason)) => {
997            warnings.push(
998                &at,
999                WarningKind::PartLeftOut,
1000                format!("{reason}; the part was left out of the catalog"),
1001            );
1002            None
1003        }
1004    }
1005}
1006
1007/// The fields OpenRocket 24.12 reads for a kind of part, besides [`COMMON_FIELDS`]; `None` for an
1008/// element that isn't a kind of part.
1009fn known_fields(tag: &str) -> Option<&'static [&'static str]> {
1010    Some(match tag {
1011        "BodyTube" | "TubeCoupler" | "EngineBlock" | "CenteringRing" | "LaunchLug" => {
1012            &["InsideDiameter", "OutsideDiameter", "Length"]
1013        }
1014        "BulkHead" => &["OutsideDiameter", "Length", "Filled"],
1015        "NoseCone" => &[
1016            "Shape",
1017            "OutsideDiameter",
1018            "ShoulderDiameter",
1019            "ShoulderLength",
1020            "Length",
1021            "Filled",
1022            "Thickness",
1023        ],
1024        "Transition" => &[
1025            "Shape",
1026            "ForeOutsideDiameter",
1027            "ForeShoulderDiameter",
1028            "ForeShoulderLength",
1029            "AftOutsideDiameter",
1030            "AftShoulderDiameter",
1031            "AftShoulderLength",
1032            "Length",
1033            "Filled",
1034            "Thickness",
1035        ],
1036        "Parachute" => &[
1037            "Diameter",
1038            "Sides",
1039            "LineCount",
1040            "LineLength",
1041            "LineMaterial",
1042        ],
1043        "Streamer" => &["Width", "Length", "Thickness"],
1044        _ => return None,
1045    })
1046}
1047
1048impl PartKind {
1049    /// The tube-like part's sizes, for the five tube-like kinds.
1050    #[must_use]
1051    pub fn tube(&self) -> Option<&Tube> {
1052        match self {
1053            Self::BodyTube(tube)
1054            | Self::TubeCoupler(tube)
1055            | Self::EngineBlock(tube)
1056            | Self::CenteringRing(tube)
1057            | Self::LaunchLug(tube) => Some(tube),
1058            _ => None,
1059        }
1060    }
1061
1062    /// The materials the part names: one, or a parachute's canopy and its lines.
1063    #[must_use]
1064    pub fn materials(&self) -> Vec<&MaterialRef> {
1065        match self {
1066            Self::BodyTube(tube)
1067            | Self::TubeCoupler(tube)
1068            | Self::EngineBlock(tube)
1069            | Self::CenteringRing(tube)
1070            | Self::LaunchLug(tube) => vec![&tube.material],
1071            Self::Bulkhead(bulkhead) => vec![&bulkhead.material],
1072            Self::NoseCone(nose) => vec![&nose.material],
1073            Self::Transition(transition) => vec![&transition.material],
1074            Self::Parachute(parachute) => {
1075                let mut list = vec![&parachute.material];
1076                list.extend(parachute.line_material.as_ref());
1077                list
1078            }
1079            Self::Streamer(streamer) => vec![&streamer.material],
1080        }
1081    }
1082}
1083
1084/// A part's kind and stated mass; `get` finds a field by name.
1085fn part<'a, 'input: 'a>(
1086    tag: &str,
1087    get: &dyn Fn(&str) -> Option<roxmltree::Node<'a, 'input>>,
1088    materials: &[CatalogMaterial],
1089    index: &MaterialIndex,
1090) -> Result<(PartKind, Option<f64>), Skip> {
1091    if get("Manufacturer").is_none() {
1092        return Err(Skip("it names no <Manufacturer>".to_owned()));
1093    }
1094    if get("PartNumber").is_none() {
1095        return Err(Skip("it has no <PartNumber>".to_owned()));
1096    }
1097    // OpenRocket reads only the text after the last element inside a value (the oracle's
1098    // `element in number` probe: `BT<b>-</b>20` is `20`); such a value is not read here.
1099    for name in ["Manufacturer", "PartNumber", "Description"] {
1100        if let Some(node) = get(name) {
1101            value_text(node, name).map_err(Skip)?;
1102        }
1103    }
1104    let mass_kg = get("Mass")
1105        .map(|node| measure(node, "Mass", mass_factor))
1106        .transpose()?;
1107    let length = |name: &str| -> Result<f64, Skip> {
1108        let node = get(name).ok_or_else(|| Skip(format!("it has no <{name}>")))?;
1109        measure(node, name, length_factor)
1110    };
1111    let optional_length = |name: &str| -> Result<Option<f64>, Skip> {
1112        get(name)
1113            .map(|node| measure(node, name, length_factor))
1114            .transpose()
1115    };
1116    let material = |name: &str, want: MaterialKind| -> Result<MaterialRef, Skip> {
1117        let node = get(name).ok_or_else(|| Skip(format!("it names no <{name}>")))?;
1118        material_ref(node, name, want, materials, index)
1119    };
1120    let word = |name: &str| -> Result<Option<String>, Skip> {
1121        get(name)
1122            .map(|node| value_text(node, name).map_err(Skip))
1123            .transpose()
1124    };
1125    let filled = || -> Result<Option<bool>, Skip> {
1126        word("Filled")?
1127            .map(|text| match text.trim() {
1128                "true" | "1" => Ok(true),
1129                "false" | "0" => Ok(false),
1130                other => Err(Skip(format!(
1131                    "<Filled> is `{}`, not true or false",
1132                    quote(other)
1133                ))),
1134            })
1135            .transpose()
1136    };
1137    let shape = || -> Result<Shape, Skip> {
1138        let text = word("Shape")?.ok_or_else(|| Skip("it has no <Shape>".to_owned()))?;
1139        Shape::parse(text.trim()).ok_or_else(|| {
1140            Skip(format!(
1141                "<Shape> is `{}`, not one of CONICAL, OGIVE, ELLIPSOID, PARABOLIC, HAACK or POWER",
1142                quote(&text)
1143            ))
1144        })
1145    };
1146    let count = |name: &str| -> Result<u32, Skip> {
1147        let text = word(name)?.ok_or_else(|| Skip(format!("it has no <{name}>")))?;
1148        text.trim().parse::<u32>().map_err(|_| {
1149            Skip(format!(
1150                "<{name}> is `{}`, not a whole number",
1151                quote(&text)
1152            ))
1153        })
1154    };
1155    let tube = || -> Result<Tube, Skip> {
1156        Ok(Tube {
1157            inner_diameter_m: length("InsideDiameter")?,
1158            outer_diameter_m: length("OutsideDiameter")?,
1159            length_m: length("Length")?,
1160            material: material("Material", MaterialKind::Bulk)?,
1161        })
1162    };
1163    let kind = match tag {
1164        "BodyTube" => PartKind::BodyTube(tube()?),
1165        "TubeCoupler" => PartKind::TubeCoupler(tube()?),
1166        "EngineBlock" => PartKind::EngineBlock(tube()?),
1167        "CenteringRing" => PartKind::CenteringRing(tube()?),
1168        "LaunchLug" => PartKind::LaunchLug(tube()?),
1169        "BulkHead" => PartKind::Bulkhead(Bulkhead {
1170            outer_diameter_m: length("OutsideDiameter")?,
1171            length_m: length("Length")?,
1172            filled: filled()?,
1173            material: material("Material", MaterialKind::Bulk)?,
1174        }),
1175        "NoseCone" => PartKind::NoseCone(NoseCone {
1176            shape: shape()?,
1177            length_m: length("Length")?,
1178            outer_diameter_m: length("OutsideDiameter")?,
1179            shoulder_diameter_m: length("ShoulderDiameter")?,
1180            shoulder_length_m: length("ShoulderLength")?,
1181            filled: filled()?,
1182            thickness_m: optional_length("Thickness")?,
1183            material: material("Material", MaterialKind::Bulk)?,
1184        }),
1185        "Transition" => PartKind::Transition(Transition {
1186            shape: shape()?,
1187            length_m: length("Length")?,
1188            fore_outer_diameter_m: length("ForeOutsideDiameter")?,
1189            fore_shoulder_diameter_m: length("ForeShoulderDiameter")?,
1190            fore_shoulder_length_m: length("ForeShoulderLength")?,
1191            aft_outer_diameter_m: length("AftOutsideDiameter")?,
1192            aft_shoulder_diameter_m: length("AftShoulderDiameter")?,
1193            aft_shoulder_length_m: length("AftShoulderLength")?,
1194            filled: filled()?,
1195            thickness_m: optional_length("Thickness")?,
1196            material: material("Material", MaterialKind::Bulk)?,
1197        }),
1198        "Parachute" => PartKind::Parachute(Parachute {
1199            diameter_m: length("Diameter")?,
1200            sides: count("Sides")?,
1201            line_count: count("LineCount")?,
1202            line_length_m: length("LineLength")?,
1203            material: material("Material", MaterialKind::Surface)?,
1204            line_material: get("LineMaterial")
1205                .map(|node| {
1206                    material_ref(node, "LineMaterial", MaterialKind::Line, materials, index)
1207                })
1208                .transpose()?,
1209        }),
1210        "Streamer" => PartKind::Streamer(Streamer {
1211            length_m: length("Length")?,
1212            width_m: length("Width")?,
1213            thickness_m: length("Thickness")?,
1214            material: material("Material", MaterialKind::Surface)?,
1215        }),
1216        // `known_fields` let through only the kinds above.
1217        _ => return Err(Skip(format!("<{}> is not a kind of part", quote(tag)))),
1218    };
1219    Ok((kind, mass_kg))
1220}
1221
1222/// A size in SI: its number times its `Unit`'s factor. A size with no unit is in SI, as
1223/// OpenRocket 24.12 reads it (the oracle's `no units` probe).
1224fn measure(
1225    node: roxmltree::Node<'_, '_>,
1226    name: &str,
1227    factor: fn(&str) -> Option<f64>,
1228) -> Result<f64, Skip> {
1229    let text = value_text(node, name).map_err(Skip)?;
1230    let value = number(&text)
1231        .ok_or_else(|| Skip(format!("<{name}> is `{}`, not a number", quote(&text))))?;
1232    if value < 0.0 {
1233        return Err(Skip(format!("<{name}> is {value}, less than zero")));
1234    }
1235    let scale = match node.attribute("Unit") {
1236        None => 1.0,
1237        Some(unit) => factor(unit).ok_or_else(|| {
1238            Skip(format!(
1239                "<{name}>'s unit `{}` is not one this reads",
1240                quote(unit)
1241            ))
1242        })?,
1243    };
1244    Ok(value * scale)
1245}
1246
1247/// The material a part names: its name and kind from the part, its density from the first
1248/// material of that name and kind in the file. A part that names a material as another kind than
1249/// it needs is left out (OpenRocket reads it with a density of zero; no bundled part does it).
1250fn material_ref(
1251    node: roxmltree::Node<'_, '_>,
1252    name: &str,
1253    want: MaterialKind,
1254    materials: &[CatalogMaterial],
1255    index: &MaterialIndex,
1256) -> Result<MaterialRef, Skip> {
1257    let kind = node
1258        .attribute("Type")
1259        .and_then(MaterialKind::parse)
1260        .ok_or_else(|| Skip(format!("<{name}>'s Type is not BULK, SURFACE or LINE")))?;
1261    if kind != want {
1262        return Err(Skip(format!(
1263            "<{name}> names a material of the wrong kind for the part"
1264        )));
1265    }
1266    let material_name = value_text(node, name).map_err(Skip)?;
1267    let density = index
1268        .get(&(kind, material_name.clone()))
1269        .and_then(|&first| materials.get(first))
1270        .map(|material| material.density);
1271    Ok(MaterialRef {
1272        name: material_name,
1273        kind,
1274        density,
1275    })
1276}