ifc_lite_processing/data_model/
quantity.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Physical-quantity decoding and the one `QuantityKind` vocabulary (C6-8,
6//! EXPORT-DATA-17). Moved from `rust/export/src/model_props.rs`.
7//!
8//! `IfcPhysicalComplexQuantity` is skipped by every consumer, on purpose.
9
10use super::rows::{QuantitySet, QuantityValue};
11use ifc_lite_core::{slot, DecodedEntity, EntityDecoder, IfcType};
12
13/// The seven simple quantity classes.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum QuantityKind {
17    Length,
18    Area,
19    Volume,
20    Count,
21    Weight,
22    Time,
23    Number,
24}
25
26impl QuantityKind {
27    pub const ALL: [QuantityKind; 7] = [
28        Self::Length, Self::Area, Self::Volume, Self::Count, Self::Weight, Self::Time, Self::Number,
29    ];
30
31    /// The class of a quantity entity, `None` for any other type.
32    pub fn of(ty: &IfcType) -> Option<Self> {
33        Some(match ty {
34            IfcType::IfcQuantityLength => Self::Length,
35            IfcType::IfcQuantityArea => Self::Area,
36            IfcType::IfcQuantityVolume => Self::Volume,
37            IfcType::IfcQuantityCount => Self::Count,
38            IfcType::IfcQuantityNumber => Self::Number,
39            IfcType::IfcQuantityWeight => Self::Weight,
40            IfcType::IfcQuantityTime => Self::Time,
41            _ => return None,
42        })
43    }
44
45    /// The class from a STEP keyword, ASCII-case-insensitive.
46    pub fn from_keyword(keyword: &str) -> Option<Self> {
47        Self::ALL.into_iter().find(|k| k.keyword().eq_ignore_ascii_case(keyword))
48    }
49
50    /// The flat exports' kind string (`QuantityValue::kind`): `Length`, ...
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::Length => "Length",
54            Self::Area => "Area",
55            Self::Volume => "Volume",
56            Self::Count => "Count",
57            Self::Weight => "Weight",
58            Self::Time => "Time",
59            Self::Number => "Number",
60        }
61    }
62
63    /// The inverse of [`as_str`](Self::as_str).
64    pub fn parse(kind: &str) -> Option<Self> {
65        Self::ALL.into_iter().find(|k| k.as_str() == kind)
66    }
67
68    /// The server's lower-case `quantity_type` column: `length`, ...
69    pub fn lower(self) -> &'static str {
70        match self {
71            Self::Length => "length",
72            Self::Area => "area",
73            Self::Volume => "volume",
74            Self::Count => "count",
75            Self::Weight => "weight",
76            Self::Time => "time",
77            Self::Number => "number",
78        }
79    }
80
81    /// The upper-case STEP keyword, `IFCQUANTITYLENGTH`.
82    pub fn keyword(self) -> &'static str {
83        match self {
84            Self::Length => "IFCQUANTITYLENGTH",
85            Self::Area => "IFCQUANTITYAREA",
86            Self::Volume => "IFCQUANTITYVOLUME",
87            Self::Count => "IFCQUANTITYCOUNT",
88            Self::Weight => "IFCQUANTITYWEIGHT",
89            Self::Time => "IFCQUANTITYTIME",
90            Self::Number => "IFCQUANTITYNUMBER",
91        }
92    }
93
94    /// The EXPRESS entity name, `IfcQuantityLength`.
95    pub fn ifc_entity(self) -> &'static str {
96        match self {
97            Self::Length => "IfcQuantityLength",
98            Self::Area => "IfcQuantityArea",
99            Self::Volume => "IfcQuantityVolume",
100            Self::Count => "IfcQuantityCount",
101            Self::Weight => "IfcQuantityWeight",
102            Self::Time => "IfcQuantityTime",
103            Self::Number => "IfcQuantityNumber",
104        }
105    }
106}
107
108/// The kinds a consumer reads: `Number` only in the opt-in analysis view
109/// (flat exports drop it until C6-14).
110/// Where every simple quantity (`IfcQuantityLength`, `Area`, `Volume`, `Count`,
111/// `Number`, `Weight`, `Time`) keeps its value. The seven classes share no
112/// supertype that declares it, so the position is named once here and the
113/// assertions below fail the build if any class disagrees.
114const QUANTITY_VALUE: usize = slot::IfcQuantityLength::LENGTH_VALUE.index();
115const _: () = {
116    assert!(slot::IfcQuantityArea::AREA_VALUE.index() == QUANTITY_VALUE);
117    assert!(slot::IfcQuantityVolume::VOLUME_VALUE.index() == QUANTITY_VALUE);
118    assert!(slot::IfcQuantityCount::COUNT_VALUE.index() == QUANTITY_VALUE);
119    assert!(slot::IfcQuantityNumber::NUMBER_VALUE.index() == QUANTITY_VALUE);
120    assert!(slot::IfcQuantityWeight::WEIGHT_VALUE.index() == QUANTITY_VALUE);
121    assert!(slot::IfcQuantityTime::TIME_VALUE.index() == QUANTITY_VALUE);
122};
123
124fn quantity_kind(ty: &IfcType, mode: QuantityDecodeMode) -> Option<QuantityKind> {
125    QuantityKind::of(ty).filter(|k| *k != QuantityKind::Number || matches!(mode, QuantityDecodeMode::AuthoredAnalysis))
126}
127
128/// Decode one `IfcElementQuantity` definition into our model.
129pub fn decode_quantity_set(decoder: &mut EntityDecoder, def: &DecodedEntity) -> Option<QuantitySet> {
130    let decoded = decode_quantity_records(decoder, def, None, QuantityDecodeMode::FlatExport)?;
131    let quantities = decoded.records.into_iter().map(|record| record.value).collect();
132    Some(QuantitySet { name: decoded.name, quantities })
133}
134
135/// The quantity kinds each consumer has historically read.
136#[derive(Clone, Copy)]
137pub enum QuantityDecodeMode {
138    /// Preserve the existing flat-export set of kinds.
139    FlatExport,
140    /// Include IFC4X3 Number in the opt-in view.
141    AuthoredAnalysis,
142}
143
144pub struct QuantityRecord {
145    pub id: u32,
146    pub unit_id: Option<u32>,
147    pub invalid_unit_ref: bool,
148    pub value: QuantityValue,
149}
150
151pub struct QuantityRecordDecode {
152    pub name: String,
153    pub records: Vec<QuantityRecord>,
154    pub rejected_members: usize,
155    pub first_rejected_id: Option<u32>,
156}
157
158/// Parse physical quantities once while preserving the provenance needed by the
159/// opt-in view. Flat exports discard that metadata and retain their old scope.
160pub fn decode_quantity_records(
161    decoder: &mut EntityDecoder, def: &DecodedEntity, max_members: Option<usize>,
162    mode: QuantityDecodeMode,
163) -> Option<QuantityRecordDecode> {
164    let name = def.string_at(slot::IfcElementQuantity::NAME).unwrap_or("").to_string();
165    let quantities_attr = def.attr(slot::IfcElementQuantity::QUANTITIES)?;
166    if max_members.is_some_and(|max| quantities_attr.as_list().is_none_or(|items| items.len() > max)) {
167        return None;
168    }
169    let quants = decoder.resolve_ref_list(quantities_attr).ok()?;
170    let mut records = Vec::new();
171    let mut rejected_members = 0;
172    let mut first_rejected_id = None;
173    for q in &quants {
174        // The slots are read only for a class that has them: a leaf that is not
175        // a quantity (an `IfcPropertySingleValue`) is a rejected member.
176        let parsed = quantity_kind(&q.ifc_type, mode).and_then(|kind| {
177            let qname = q.string_at(slot::IfcPhysicalQuantity::NAME).filter(|name| !name.is_empty())?;
178            // as_float already accepts STEP integers, including authored Count.
179            Some((kind, qname, q.real_at(QUANTITY_VALUE)?))
180        });
181        let Some((kind, qname, value)) = parsed else {
182            rejected_members += 1;
183            first_rejected_id.get_or_insert(q.id);
184            continue;
185        };
186        records.push(QuantityRecord {
187            id: q.id,
188            unit_id: q.ref_at(slot::IfcPhysicalSimpleQuantity::UNIT),
189            invalid_unit_ref: q.attr(slot::IfcPhysicalSimpleQuantity::UNIT).is_some_and(|unit| !unit.is_null() && unit.as_entity_ref().is_none()),
190            value: QuantityValue { name: qname.to_string(), value, kind: kind.as_str() },
191        });
192    }
193    Some(QuantityRecordDecode { name, records, rejected_members, first_rejected_id })
194}
195
196
197#[cfg(test)]
198#[path = "quantity_tests.rs"]
199mod tests;