Skip to main content

brep_render/engine_state/
part_mass.rs

1//! MASS PROPERTIES OF A PART — computed from the part's geometry and the
2//! density the PART carries, never typed in and never stored per occurrence.
3//!
4//! # One source
5//!
6//! Material and density are attributes of the PART definition: the
7//! `partAttributes` record on the part's own document (see `bom.rs`), edited
8//! in the part's Properties dialog or the BOM's part columns. Everything that
9//! shows a mass — the BOM row, the Info window, the BOM export, the MCP
10//! readers — resolves it here, so they cannot disagree:
11//!
12//! * a solid's density is its own metadata `density` when one is set (a
13//!   multi-material part's per-body override), else its PART's `Density`,
14//!   else the density of the part's `Material` when that names a material
15//!   this build knows (`material_density`), else none;
16//! * a part's volume is the volume of the solids ONE placement of it
17//!   produces (every placement is the same rigid copy), from the existing
18//!   measurement cache (`object_info_json`), so nothing re-executes the history
19//!   per frame and a value is simply pending until the runner answers;
20//! * a part's mass is `Σ volume × density`. A part with NO geometry (a
21//!   purchased or library part with nothing to measure) may carry a stored
22//!   `Mass` instead: that is the only time a mass is typed, and it is still a
23//!   part attribute.
24//!
25//! Units: density in g/cm³ (what material tables quote), volume in mm³ (the
26//! kernel's length unit), mass in kg.
27//!
28//! # Old documents
29//!
30//! A document saved before this rule may hold `Mass` / `Material` / `Density`
31//! on its OCCURRENCES (the ACOMP's `bom` record, or the `occurrenceAttributes`
32//! key an older batch path wrote). `migrate_occurrence_part_attributes`
33//! lifts them onto the part as the document opens, and says so once.
34
35use super::*;
36use serde_json::Value;
37
38/// The part attribute keys that describe the PART's mass properties. None of
39/// them may be stored on an occurrence.
40pub const PART_ONLY_KEYS: [&str; 4] = ["Mass", "Material", "Density", "Volume"];
41
42/// Derived — computed from geometry, never stored.
43pub const VOLUME_KEY: &str = "Volume";
44/// Computed for a part with geometry; a stored override only without.
45pub const MASS_KEY: &str = "Mass";
46/// The part's density in g/cm³.
47pub const DENSITY_KEY: &str = "Density";
48/// The part's material name; resolves a density when no `Density` is set.
49pub const MATERIAL_KEY: &str = "Material";
50
51pub const DENSITY_UNIT: &str = "g/cm³";
52pub const MASS_UNIT: &str = "kg";
53pub const VOLUME_UNIT: &str = "mm³";
54
55/// mm³ × g/cm³ → kg: 1 mm³ = 1e-3 cm³, 1 g = 1e-3 kg.
56const MM3_G_CM3_TO_KG: f64 = 1e-6;
57
58/// Built-in densities (g/cm³) for common material names, most specific
59/// first: the first key found as a whole word (or word run) of the
60/// material's name wins, so `Stainless Steel 304` is stainless and
61/// `6061-T6` is aluminium.
62const MATERIAL_DENSITIES: &[(&str, f64)] = &[
63    ("stainless", 7.93),
64    ("cast iron", 7.20),
65    ("tool steel", 7.80),
66    ("steel", 7.85),
67    ("iron", 7.87),
68    ("aluminium", 2.70),
69    ("aluminum", 2.70),
70    ("6061", 2.70),
71    ("6063", 2.69),
72    ("7075", 2.81),
73    ("2024", 2.78),
74    ("brass", 8.50),
75    ("bronze", 8.80),
76    ("copper", 8.96),
77    ("titanium", 4.43),
78    ("magnesium", 1.74),
79    ("zinc", 7.14),
80    ("nickel", 8.90),
81    ("lead", 11.34),
82    ("abs", 1.04),
83    ("pla", 1.24),
84    ("petg", 1.27),
85    ("nylon", 1.14),
86    ("polycarbonate", 1.20),
87    ("acetal", 1.41),
88    ("delrin", 1.41),
89    ("pom", 1.41),
90    ("hdpe", 0.95),
91    ("polypropylene", 0.90),
92    ("pvc", 1.38),
93    ("acrylic", 1.18),
94    ("pmma", 1.18),
95    ("ptfe", 2.20),
96    ("glass", 2.50),
97    ("oak", 0.75),
98    ("pine", 0.50),
99    ("plywood", 0.60),
100    ("wood", 0.60),
101];
102
103/// The built-in density (g/cm³) for a material NAME, or `None` when the name
104/// matches nothing this build knows (then the part needs an explicit
105/// `Density`).
106pub fn material_density(material: &str) -> Option<f64> {
107    let words: Vec<String> = material
108        .to_lowercase()
109        .split(|c: char| !c.is_alphanumeric())
110        .filter(|word| !word.is_empty())
111        .map(str::to_string)
112        .collect();
113    if words.is_empty() {
114        return None;
115    }
116    let padded = format!(" {} ", words.join(" "));
117    MATERIAL_DENSITIES
118        .iter()
119        .find(|(key, _)| padded.contains(&format!(" {key} ")))
120        .map(|&(_, density)| density)
121}
122
123/// A mass in kg as a reader wants it: kilograms from 1 kg up, grams below.
124pub fn format_mass_kg(kg: f64) -> String {
125    if kg.abs() >= 1.0 {
126        format!("{kg:.3} kg")
127    } else {
128        format!("{:.3} g", kg * 1000.0)
129    }
130}
131
132/// A volume in mm³ as a reader wants it: cm³ from 1 cm³ up, mm³ below.
133pub fn format_volume_mm3(mm3: f64) -> String {
134    if mm3.abs() >= 1000.0 {
135        format!("{:.3} cm³", mm3 / 1000.0)
136    } else {
137        format!("{mm3:.3} mm³")
138    }
139}
140
141/// The display text of a DERIVED part field (`Mass`, `Volume`) with its
142/// unit; `None` for any other field or a non-number.
143pub fn format_derived(field: &str, value: &Value) -> Option<String> {
144    let number = value.as_f64()?;
145    match field {
146        MASS_KEY => Some(format_mass_kg(number)),
147        VOLUME_KEY => Some(format_volume_mm3(number)),
148        _ => None,
149    }
150}
151
152/// Where a resolved density came from.
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub enum DensitySource {
155    /// The solid's own metadata `density` (a per-body override).
156    Solid,
157    /// The part's `Density` attribute.
158    Part,
159    /// The built-in density of the part's `Material`.
160    Material,
161}
162
163impl DensitySource {
164    pub fn as_str(self) -> &'static str {
165        match self {
166            DensitySource::Solid => "solid",
167            DensitySource::Part => "part",
168            DensitySource::Material => "material",
169        }
170    }
171}
172
173/// A positive finite number from a JSON number or numeric string.
174fn positive_number(value: &Value) -> Option<f64> {
175    let number = match value {
176        Value::Number(number) => number.as_f64(),
177        Value::String(text) => text.trim().parse::<f64>().ok(),
178        _ => None,
179    }?;
180    (number.is_finite() && number > 0.0).then_some(number)
181}
182
183/// A part's density from its attribute record: its `Density`, else its
184/// `Material`'s built-in density.
185pub fn part_density(attributes: &Value) -> Option<(f64, DensitySource)> {
186    if let Some(density) = attributes.get(DENSITY_KEY).and_then(positive_number) {
187        return Some((density, DensitySource::Part));
188    }
189    attributes
190        .get(MATERIAL_KEY)
191        .and_then(Value::as_str)
192        .and_then(material_density)
193        .map(|density| (density, DensitySource::Material))
194}
195
196/// What a mass reading is.
197#[derive(Clone, Debug, PartialEq)]
198pub enum MassStatus {
199    /// Volume × density over the part's geometry.
200    Computed,
201    /// A part with no geometry: its stored `Mass`.
202    Override,
203    /// A measurement is still in flight.
204    Pending,
205    /// The geometry is measured but some solid has no density.
206    NoDensity,
207    /// No geometry and no stored mass.
208    NoGeometry,
209    /// The kernel could not measure a solid.
210    Failed(String),
211}
212
213impl MassStatus {
214    pub fn as_str(&self) -> &'static str {
215        match self {
216            MassStatus::Computed => "computed",
217            MassStatus::Override => "override",
218            MassStatus::Pending => "pending",
219            MassStatus::NoDensity => "no-density",
220            MassStatus::NoGeometry => "no-geometry",
221            MassStatus::Failed(_) => "failed",
222        }
223    }
224
225    /// The sentence a reader sees when there is no number.
226    pub fn note(&self) -> Option<String> {
227        match self {
228            MassStatus::Computed | MassStatus::Override => None,
229            MassStatus::Pending => Some("measuring".into()),
230            MassStatus::NoDensity => {
231                Some("no density: set the part's Material or Density".into())
232            }
233            MassStatus::NoGeometry => {
234                Some("no geometry: set the part's Mass".into())
235            }
236            MassStatus::Failed(message) => Some(format!("not measurable: {message}")),
237        }
238    }
239}
240
241/// One part's (or one document's) mass properties.
242#[derive(Clone, Debug, PartialEq)]
243pub struct MassReport {
244    /// Σ solid volume (mm³); `None` with no geometry or while pending.
245    pub volume_mm3: Option<f64>,
246    /// Mass (kg); `None` when it cannot be given — `status` says why.
247    pub mass_kg: Option<f64>,
248    /// The density (g/cm³) when every solid resolves the SAME one (`None`
249    /// for a mixed-density part or when none resolves).
250    pub density_g_cm3: Option<f64>,
251    /// Where that density came from.
252    pub density_source: Option<DensitySource>,
253    /// How many solids the reading covers.
254    pub solid_count: usize,
255    pub status: MassStatus,
256}
257
258impl MassReport {
259    /// The reading as JSON, units in the key names:
260    /// `{volumeMm3, massKg, densityGcm3, densitySource, massStatus, massNote}`.
261    pub fn to_json(&self) -> Value {
262        serde_json::json!({
263            "volumeMm3": self.volume_mm3,
264            "massKg": self.mass_kg,
265            "densityGcm3": self.density_g_cm3,
266            "densitySource": self.density_source.map(DensitySource::as_str),
267            "solidCount": self.solid_count,
268            "massStatus": self.status.as_str(),
269            "massNote": self.status.note(),
270        })
271    }
272}
273
274impl EngineState {
275    /// The part attribute record that owns `solid`: the innermost part along
276    /// its component chain (`ACOMP1:ACOMP2:Body` is the part ACOMP2 places
277    /// inside the part ACOMP1 places), or the open document's own record for
278    /// a solid with no chain. `None` when the chain cannot be resolved.
279    pub(crate) fn owning_part_attributes(&self, solid: &str) -> Option<Value> {
280        let namespace = self.component_namespace();
281        let (chain, _local) = namespace.split(solid);
282        let Some((&head, rest)) = chain.split_first() else {
283            return Some(self.document_part_attributes());
284        };
285        let part_name = self
286            .assembly_components
287            .iter()
288            .find(|component| component.id == head)
289            .map(|component| component.part_name.clone())
290            .or_else(|| {
291                let index = self.history.index_of(head)?;
292                self.history
293                    .feature_params(index)?
294                    .get("partName")?
295                    .as_str()
296                    .map(str::to_string)
297            })?;
298        let mut document = self
299            .history
300            .parts_library()
301            .get(&part_name)?
302            .get("document")?;
303        for segment in rest {
304            let inner = document
305                .get("features")?
306                .as_array()?
307                .iter()
308                .find(|feature| feature["inputParams"]["id"].as_str() == Some(segment))?;
309            let inner_part = inner["inputParams"]["partName"].as_str()?;
310            document = document
311                .get("partsLibrary")?
312                .get(inner_part)?
313                .get("document")?;
314        }
315        Some(
316            document
317                .get(PART_ATTRIBUTES)
318                .filter(|value| value.is_object())
319                .cloned()
320                .unwrap_or_else(|| Value::Object(serde_json::Map::new())),
321        )
322    }
323
324    /// The density (g/cm³) a solid's mass is computed with, and where it came
325    /// from: its own metadata `density`, else its part's (see the module).
326    pub fn solid_density(&self, solid: &str) -> Option<(f64, DensitySource)> {
327        if let Some(density) = self
328            .metadata
329            .attribute(solid, "density")
330            .and_then(|text| text.trim().parse::<f64>().ok())
331            .filter(|density| density.is_finite() && *density > 0.0)
332        {
333            return Some((density, DensitySource::Solid));
334        }
335        part_density(&self.owning_part_attributes(solid)?)
336    }
337
338    /// Measurable scene solids (sketch sheets have no volume).
339    fn measurable_solids<'a>(&'a self, filter: impl Fn(&str) -> bool + 'a) -> Vec<String> {
340        self.scene
341            .solids()
342            .iter()
343            .filter(|solid| !solid.is_sketch && filter(&solid.name))
344            .map(|solid| solid.name.clone())
345            .collect()
346    }
347
348    /// The solids ONE placement of `part_name` produces at the top level: its
349    /// first occurrence's (every occurrence is a rigid copy of the same part).
350    fn part_solids(&self, part_name: &str) -> Vec<String> {
351        let Some(first) = self
352            .assembly_components
353            .iter()
354            .find(|component| component.part_name == part_name)
355            .map(|component| component.id.clone())
356        else {
357            return Vec::new();
358        };
359        self.chain_solids(&first)
360    }
361
362    /// The solids under one occurrence CHAIN (`ACOMP9` or `ACOMP9:ACOMP1`).
363    fn chain_solids(&self, chain: &str) -> Vec<String> {
364        let prefix = format!("{chain}:");
365        self.measurable_solids(|name| name.starts_with(&prefix))
366    }
367
368    /// The mass properties of what one occurrence chain places — a NESTED
369    /// BOM line (`ACOMP9:ACOMP1` is the part ACOMP1 places inside the
370    /// sub-assembly ACOMP9 places), each solid with its own part's density.
371    /// Asks for missing measurements.
372    pub fn chain_mass(&mut self, chain: &str) -> MassReport {
373        let solids = self.chain_solids(chain);
374        self.measure_solids(&solids);
375        self.chain_mass_cached(chain)
376    }
377
378    /// [`Self::chain_mass`] from what is already measured.
379    pub fn chain_mass_cached(&self, chain: &str) -> MassReport {
380        let solids = self.chain_solids(chain);
381        // The chain's own part record (a solid name under it resolves to it).
382        let attributes = self
383            .owning_part_attributes(&format!("{chain}:_"))
384            .unwrap_or_else(|| Value::Object(serde_json::Map::new()));
385        self.mass_over(&solids, &attributes)
386    }
387
388    /// Ask for every placed part's measurements; `true` while any is still in
389    /// flight (an export waits on this rather than writing blanks).
390    pub fn bom_mass_pending(&mut self) -> bool {
391        let parts: Vec<String> =
392            self.assembly_components.iter().map(|c| c.part_name.clone()).collect();
393        self.measure_parts(parts.iter().map(String::as_str));
394        parts
395            .iter()
396            .any(|part| self.part_mass_cached(part).status == MassStatus::Pending)
397    }
398
399    /// Whether the part has geometry to measure (then its mass is computed and
400    /// a typed `Mass` is refused).
401    pub fn part_has_geometry(&self, part_name: &str) -> bool {
402        !self.part_solids(part_name).is_empty()
403    }
404
405    /// Whether the open document has geometry to measure.
406    pub fn document_has_geometry(&self) -> bool {
407        !self.measurable_solids(|_| true).is_empty()
408    }
409
410    /// A solid's volume (mm³) off the measurement cache, WITHOUT asking:
411    /// `Ok(None)` while no answer is cached (see [`Self::measure_solids`]).
412    fn solid_volume_cached(&self, solid: &str) -> Result<Option<f64>, String> {
413        let Some(text) = self.info_cache.get(solid) else {
414            return Ok(None);
415        };
416        let info: Value = serde_json::from_str(text).unwrap_or(Value::Null);
417        if info.get("ok").and_then(Value::as_bool) != Some(true) {
418            return Err(info
419                .get("message")
420                .and_then(Value::as_str)
421                .unwrap_or("no measurement")
422                .to_string());
423        }
424        info.get("volume")
425            .and_then(Value::as_f64)
426            .map(Some)
427            .ok_or_else(|| "no volume".to_string())
428    }
429
430    /// Ask the runner to measure every solid not measured yet (one query per
431    /// solid, deduplicated by the measurement lane itself). An Inline runner
432    /// answers here; a threaded one on a later frame.
433    fn measure_solids(&mut self, solids: &[String]) {
434        for solid in solids {
435            if !self.info_cache.contains_key(solid) {
436                let _ = self.object_info_raw_json(solid);
437            }
438        }
439    }
440
441    /// Ask for the measurements the named parts' masses need — what a panel
442    /// calls before it reads [`Self::part_bom_record_cached`] for each row.
443    pub fn measure_parts<'a>(&mut self, parts: impl IntoIterator<Item = &'a str>) {
444        for part in parts {
445            let solids = self.part_solids(part);
446            self.measure_solids(&solids);
447        }
448    }
449
450    /// Mass properties over `solids`, falling back to `attributes`' stored
451    /// `Mass` when there are none.
452    fn mass_over(&self, solids: &[String], attributes: &Value) -> MassReport {
453        if solids.is_empty() {
454            let stored = attributes.get(MASS_KEY).and_then(positive_number);
455            return MassReport {
456                volume_mm3: None,
457                mass_kg: stored,
458                density_g_cm3: None,
459                density_source: None,
460                solid_count: 0,
461                status: if stored.is_some() {
462                    MassStatus::Override
463                } else {
464                    MassStatus::NoGeometry
465                },
466            };
467        }
468        let mut volume = 0.0;
469        let mut mass = 0.0;
470        let mut pending = false;
471        let mut failure: Option<String> = None;
472        let mut missing_density = false;
473        let mut densities: Vec<(f64, DensitySource)> = Vec::new();
474        for solid in solids {
475            match self.solid_volume_cached(solid) {
476                Ok(Some(v)) => {
477                    volume += v;
478                    match self.solid_density(solid) {
479                        Some((density, source)) => {
480                            mass += v * density * MM3_G_CM3_TO_KG;
481                            densities.push((density, source));
482                        }
483                        None => missing_density = true,
484                    }
485                }
486                Ok(None) => pending = true,
487                Err(message) => {
488                    failure.get_or_insert(format!("{solid}: {message}"));
489                }
490            }
491        }
492        let uniform = densities
493            .first()
494            .copied()
495            .filter(|(first, _)| densities.iter().all(|(d, _)| (d - first).abs() <= 1e-12));
496        let status = if let Some(message) = failure {
497            MassStatus::Failed(message)
498        } else if pending {
499            MassStatus::Pending
500        } else if missing_density {
501            MassStatus::NoDensity
502        } else {
503            MassStatus::Computed
504        };
505        MassReport {
506            volume_mm3: matches!(status, MassStatus::Computed | MassStatus::NoDensity)
507                .then_some(volume),
508            mass_kg: (status == MassStatus::Computed).then_some(mass),
509            density_g_cm3: uniform.map(|(density, _)| density),
510            density_source: uniform.map(|(_, source)| source),
511            solid_count: solids.len(),
512            status,
513        }
514    }
515
516    /// A parts-library part's mass properties (see the module), asking for
517    /// any measurement still missing.
518    pub fn part_mass(&mut self, part_name: &str) -> MassReport {
519        let solids = self.part_solids(part_name);
520        self.measure_solids(&solids);
521        self.part_mass_cached(part_name)
522    }
523
524    /// [`Self::part_mass`] from what is already measured (never asks; a
525    /// solid not measured yet reads as pending).
526    pub fn part_mass_cached(&self, part_name: &str) -> MassReport {
527        let solids = self.part_solids(part_name);
528        let attributes = self.part_attributes(part_name);
529        let mut report = self.mass_over(&solids, &attributes);
530        if solids.is_empty() {
531            // No geometry: still say what density the part names.
532            if let Some((density, source)) = part_density(&attributes) {
533                report.density_g_cm3 = Some(density);
534                report.density_source = Some(source);
535            }
536        }
537        report
538    }
539
540    /// The OPEN document's own mass properties: every measurable solid it
541    /// shows (a part's bodies; an assembly's placed components, each with its
542    /// own part's density).
543    pub fn document_mass(&mut self) -> MassReport {
544        let solids = self.measurable_solids(|_| true);
545        self.measure_solids(&solids);
546        self.document_mass_cached()
547    }
548
549    /// [`Self::document_mass`] from what is already measured.
550    pub fn document_mass_cached(&self) -> MassReport {
551        let solids = self.measurable_solids(|_| true);
552        let attributes = self.document_part_attributes();
553        let mut report = self.mass_over(&solids, &attributes);
554        if solids.is_empty() {
555            if let Some((density, source)) = part_density(&attributes) {
556                report.density_g_cm3 = Some(density);
557                report.density_source = Some(source);
558            }
559        }
560        report
561    }
562
563    /// A part's BOM record: its stored attributes with the DERIVED mass
564    /// properties folded in — `Volume` (mm³) and `Mass` (kg) as computed, and
565    /// `Density` as resolved when the part names only a `Material`. A `Mass`
566    /// stored on a part with geometry is not what the BOM shows: the computed
567    /// value replaces it, or the key is absent when there is none yet.
568    pub fn part_bom_record(&mut self, part_name: &str) -> Value {
569        let report = self.part_mass(part_name);
570        fold_mass(self.part_attributes(part_name), &report)
571    }
572
573    /// [`Self::part_bom_record`] from what is already measured, plus the
574    /// reading itself (a panel row shows the note when there is no number).
575    pub fn part_bom_record_cached(&self, part_name: &str) -> (Value, MassReport) {
576        let report = self.part_mass_cached(part_name);
577        (fold_mass(self.part_attributes(part_name), &report), report)
578    }
579
580    /// The open document's own record with its derived mass properties — the
581    /// same fold as [`Self::part_bom_record`].
582    pub fn document_bom_record(&mut self) -> Value {
583        let attributes = self.document_part_attributes();
584        let report = self.document_mass();
585        fold_mass(attributes, &report)
586    }
587
588    /// Refuse a write a part attribute may not take: `Volume` is derived, and
589    /// `Mass` is computed whenever there is geometry to compute it from.
590    pub(crate) fn check_part_attribute_write(
591        &self,
592        key: &str,
593        value: &Value,
594        has_geometry: bool,
595    ) -> Result<(), String> {
596        let clearing =
597            value.is_null() || matches!(value, Value::String(text) if text.is_empty());
598        if key == VOLUME_KEY && !clearing {
599            return Err("Volume is computed from the part's geometry and cannot be set".into());
600        }
601        if key == MASS_KEY && !clearing && has_geometry {
602            return Err(
603                "Mass is computed from the part's geometry and density: set the part's Material or Density instead (a Mass can be typed only for a part with no geometry)"
604                    .into(),
605            );
606        }
607        Ok(())
608    }
609}
610
611/// Fold a mass reading into an attribute record (see
612/// [`EngineState::part_bom_record`]).
613fn fold_mass(mut attributes: Value, report: &MassReport) -> Value {
614    let Some(record) = attributes.as_object_mut() else {
615        return attributes;
616    };
617    record.remove(VOLUME_KEY);
618    if report.status != MassStatus::Override {
619        record.remove(MASS_KEY);
620    }
621    if let Some(volume) = report.volume_mm3 {
622        record.insert(VOLUME_KEY.into(), Value::from(volume));
623    }
624    if let Some(mass) = report.mass_kg {
625        record.insert(MASS_KEY.into(), Value::from(mass));
626    }
627    if !record.contains_key(DENSITY_KEY) {
628        if let (Some(density), Some(DensitySource::Material)) =
629            (report.density_g_cm3, report.density_source)
630        {
631            record.insert(DENSITY_KEY.into(), Value::from(density));
632        }
633    }
634    attributes
635}
636
637/// Lift part-only attributes (`Mass`, `Material`, `Density`) that an older
638/// document stored on its OCCURRENCES onto the PART, in place, before the
639/// document is loaded. Returns the notices to show (one per part whose
640/// occurrences disagreed or whose part already said otherwise, plus one
641/// summary of what moved).
642///
643/// * Both occurrence records are swept: the BOM's `bom` record and the
644///   `occurrenceAttributes` key an older batch path wrote (its other keys are
645///   folded into `bom`, which wins on a clash).
646/// * Equal values move to the part when the part does not already carry the
647///   key; the occurrences lose them either way.
648/// * Disagreeing occurrences: the FIRST occurrence's value goes to the part
649///   (unless the part already carries one), and the disagreement is reported
650///   once for that part.
651/// * Every embedded part document is swept too (a sub-assembly's own
652///   occurrences), and a changed entry is re-stamped as an attribute edit is.
653pub fn migrate_occurrence_part_attributes(document: &mut Value) -> Vec<String> {
654    let mut notices = Vec::new();
655    migrate_level(document, "", &mut notices);
656    notices
657}
658
659fn migrate_level(document: &mut Value, path: &str, notices: &mut Vec<String>) {
660    // (part, key) -> [(occurrence id, value)] in history order.
661    let mut found: Vec<(String, String, Vec<(String, Value)>)> = Vec::new();
662    if let Some(features) = document.get_mut("features").and_then(Value::as_array_mut) {
663        for feature in features {
664            let is_acomp = feature
665                .get("type")
666                .and_then(Value::as_str)
667                .is_some_and(super::components::is_acomp_feature_type);
668            if !is_acomp {
669                continue;
670            }
671            let Some(params) = feature.get_mut("inputParams").and_then(Value::as_object_mut) else {
672                continue;
673            };
674            let id = params.get("id").and_then(Value::as_str).unwrap_or("").to_string();
675            let part = params.get("partName").and_then(Value::as_str).unwrap_or("").to_string();
676            // Fold the legacy key into the real record (the real one wins).
677            if let Some(Value::Object(legacy)) = params.remove("occurrenceAttributes") {
678                let record = params
679                    .entry(super::bom::OCCURRENCE_ATTRIBUTES.to_string())
680                    .or_insert_with(|| Value::Object(serde_json::Map::new()));
681                if !record.is_object() {
682                    *record = Value::Object(serde_json::Map::new());
683                }
684                let record = record.as_object_mut().expect("normalized");
685                for (key, value) in legacy {
686                    record.entry(key).or_insert(value);
687                }
688            }
689            let Some(record) = params
690                .get_mut(super::bom::OCCURRENCE_ATTRIBUTES)
691                .and_then(Value::as_object_mut)
692            else {
693                continue;
694            };
695            for key in ["Mass", "Material", "Density", "Volume"] {
696                let Some(value) = record.remove(key) else { continue };
697                let blank = value.is_null() || matches!(&value, Value::String(t) if t.trim().is_empty());
698                if blank || key == VOLUME_KEY || part.is_empty() {
699                    continue;
700                }
701                match found.iter_mut().find(|(p, k, _)| *p == part && k == key) {
702                    Some((_, _, values)) => values.push((id.clone(), value)),
703                    None => found.push((part.clone(), key.to_string(), vec![(id.clone(), value)])),
704                }
705            }
706            if record.is_empty() {
707                params.remove(super::bom::OCCURRENCE_ATTRIBUTES);
708            }
709        }
710    }
711
712    let mut moved: Vec<String> = Vec::new();
713    let mut touched: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
714    for (part, key, values) in &found {
715        let label = if path.is_empty() { part.clone() } else { format!("{path}/{part}") };
716        let Some(entry) = document
717            .get_mut("partsLibrary")
718            .and_then(|library| library.get_mut(part))
719            .filter(|entry| entry.get("document").is_some_and(Value::is_object))
720        else {
721            notices.push(format!(
722                "BOM: {key} on {} occurrence(s) of '{label}' was dropped: the part is not in the parts library",
723                values.len()
724            ));
725            continue;
726        };
727        let first = &values[0].1;
728        let disagree = values.iter().any(|(_, value)| value != first);
729        let part_document = entry.get_mut("document").expect("filtered");
730        let existing = part_document
731            .get(PART_ATTRIBUTES)
732            .and_then(|record| record.get(key))
733            .cloned();
734        let shown = |value: &Value| match value {
735            Value::String(text) => format!("'{text}'"),
736            other => other.to_string(),
737        };
738        match existing {
739            Some(existing) if &existing != first || disagree => {
740                notices.push(format!(
741                    "BOM: '{label}' occurrences carried {key} {} — the part keeps its own {key} {}",
742                    values.iter().map(|(id, value)| format!("{id}={}", shown(value))).collect::<Vec<_>>().join(", "),
743                    shown(&existing),
744                ));
745            }
746            Some(_) => {}
747            None => {
748                let object = part_document.as_object_mut().expect("filtered");
749                let record = object
750                    .entry(PART_ATTRIBUTES.to_string())
751                    .or_insert_with(|| Value::Object(serde_json::Map::new()));
752                if !record.is_object() {
753                    *record = Value::Object(serde_json::Map::new());
754                }
755                record
756                    .as_object_mut()
757                    .expect("normalized")
758                    .insert(key.clone(), first.clone());
759                touched.insert(part.clone());
760                if disagree {
761                    notices.push(format!(
762                        "BOM: '{label}' occurrences disagreed on {key} ({}) — the part takes {} from {}",
763                        values.iter().map(|(id, value)| format!("{id}={}", shown(value))).collect::<Vec<_>>().join(", "),
764                        shown(first),
765                        values[0].0,
766                    ));
767                } else {
768                    moved.push(format!("{key} {} → part '{label}'", shown(first)));
769                }
770            }
771        }
772    }
773
774    // Recurse into every embedded part document, then re-stamp what changed.
775    if let Some(library) = document.get_mut("partsLibrary").and_then(Value::as_object_mut) {
776        for (name, entry) in library.iter_mut() {
777            let Some(part_document) = entry.get_mut("document").filter(|d| d.is_object()) else {
778                continue;
779            };
780            let before = notices.len();
781            let label = if path.is_empty() { name.clone() } else { format!("{path}/{name}") };
782            let changed_inside = migrate_level_changed(part_document, &label, notices);
783            if changed_inside || notices.len() != before {
784                touched.insert(name.clone());
785            }
786        }
787        for name in &touched {
788            if let Some(entry) = library.get_mut(name) {
789                let text = entry["document"].to_string();
790                entry["sourceSignature"] = Value::String(super::document_signature(&text));
791            }
792        }
793    }
794
795    if !moved.is_empty() {
796        notices.push(format!(
797            "BOM: mass properties moved from occurrences to their parts: {} (save to keep)",
798            moved.join("; ")
799        ));
800    }
801}
802
803/// [`migrate_level`] on a nested document, reporting whether it changed.
804fn migrate_level_changed(document: &mut Value, path: &str, notices: &mut Vec<String>) -> bool {
805    let before = document.clone();
806    migrate_level(document, path, notices);
807    *document != before
808}
809