Skip to main content

ifc_properties/pset/
scalar.rs

1//! Single, bounded, list and enumerated property values.
2//!
3//! # Slots, verified against the IFC4 EXPRESS schema
4//!
5//! Every `IfcProperty` starts with `Name` (0) and `Description` (1); the
6//! subtype attributes follow. The families disagree about what comes next,
7//! and reading slot 2 as "the value" is wrong for four of the six:
8//!
9//! ```text
10//! IfcPropertySingleValue      2 = NominalValue      3 = Unit
11//! IfcPropertyEnumeratedValue  2 = EnumerationValues 3 = EnumerationReference
12//! IfcPropertyBoundedValue     2 = UpperBoundValue   3 = LowerBoundValue
13//!                             4 = Unit              5 = SetPointValue
14//! IfcPropertyListValue        2 = ListValues        3 = Unit
15//! IfcPropertyTableValue       2 = DefiningValues    3 = DefinedValues
16//!                             4 = Expression        5 = DefiningUnit
17//!                             6 = DefinedUnit       7 = CurveInterpolation
18//! IfcPropertyReferenceValue   2 = UsageName         3 = PropertyReference
19//! ```
20//!
21//! Note `IfcPropertyBoundedValue`: UPPER bound is slot 2, LOWER is slot 3.
22//! Reading them in the intuitive order silently inverts every range in the
23//! file, and the result still looks like a plausible range.
24
25use std::sync::Arc;
26
27use ifc_model::{EntityId, Model};
28
29use crate::error::PropertyAnomaly;
30use crate::nesting::Nesting;
31use crate::pset::complex::complex_members;
32use crate::value::MeasureValue;
33
34/// Attribute slots shared by every `IfcProperty`.
35const NAME: usize = 0;
36const DESCRIPTION: usize = 1;
37
38/// What a property actually states.
39///
40/// One variant per concrete `IfcProperty` subtype in IFC4. A file stating a
41/// subtype this crate does not model yields [`PropertyValue::Unsupported`]
42/// carrying the type name, so an unknown property is reported rather than
43/// silently dropped from its set.
44#[derive(Debug, Clone, PartialEq)]
45pub enum PropertyValue {
46    /// `IfcPropertySingleValue`: one measure, optionally with a unit.
47    Single {
48        /// The nominal value. `None` when the file omits it, which is legal.
49        value: Option<MeasureValue>,
50        /// `IfcNamedUnit`/`IfcDerivedUnit` override for this property.
51        unit: Option<EntityId>,
52    },
53    /// `IfcPropertyEnumeratedValue`: chosen constants plus their enumeration.
54    Enumerated {
55        /// The selected values.
56        values: Vec<MeasureValue>,
57        /// The `IfcPropertyEnumeration` they were selected from.
58        enumeration: Option<EntityId>,
59    },
60    /// `IfcPropertyBoundedValue`: a range, optionally with a set point.
61    Bounded {
62        /// Slot 2. Named explicitly because the schema order is upper-first.
63        upper: Option<MeasureValue>,
64        /// Slot 3.
65        lower: Option<MeasureValue>,
66        /// Slot 5.
67        set_point: Option<MeasureValue>,
68        /// Slot 4.
69        unit: Option<EntityId>,
70    },
71    /// `IfcPropertyListValue`: an ordered list of measures.
72    List {
73        /// The values, in file order. Order is meaningful in a LIST.
74        values: Vec<MeasureValue>,
75        /// Unit shared by every entry.
76        unit: Option<EntityId>,
77    },
78    /// `IfcPropertyTableValue`: a defining/defined value mapping.
79    Table {
80        /// The x column.
81        defining: Vec<MeasureValue>,
82        /// The y column.
83        defined: Vec<MeasureValue>,
84        /// How to interpolate between rows, when stated.
85        interpolation: Option<Arc<str>>,
86    },
87    /// `IfcPropertyReferenceValue`: a pointer to another entity.
88    Reference {
89        /// What the reference is for.
90        usage: Option<Arc<str>>,
91        /// The referenced entity.
92        reference: Option<EntityId>,
93    },
94    /// `IfcComplexProperty`: nested properties under a usage name.
95    Complex {
96        /// The grouping name.
97        usage: Option<Arc<str>>,
98        /// Contained properties, in file order.
99        properties: Vec<Property>,
100    },
101    /// A concrete `IfcProperty` subtype this crate does not model.
102    Unsupported {
103        /// The declared type, upper-cased.
104        type_name: Arc<str>,
105    },
106}
107
108/// One property: its name, description and value.
109#[derive(Debug, Clone, PartialEq)]
110#[non_exhaustive]
111pub struct Property {
112    /// The `IfcProperty` entity.
113    pub id: EntityId,
114    /// `Name`. Required by the schema; `None` means the file broke that.
115    pub name: Option<Arc<str>>,
116    /// `Description`, when stated.
117    pub description: Option<Arc<str>>,
118    /// The value, by family.
119    pub value: PropertyValue,
120}
121
122/// Read one property by id.
123///
124/// Returns `None` when `id` is not in the file. `IfcComplexProperty` may
125/// nest, and a malformed file can make one reach itself; such a member, one
126/// nested deeper than the reader follows, and one naming an absent entity are
127/// left out of the resolved [`PropertyValue::Complex`]. This function does
128/// not say which members were cut: use [`property_checked`], which returns
129/// the same value together with the [`PropertyAnomaly`] for each.
130pub fn property(model: &Model, id: EntityId) -> Option<Property> {
131    property_checked(model, id).map(|(property, _)| property)
132}
133
134/// Read one property by id, reporting every nested member left unread.
135///
136/// Nested complex properties are followed along a tracked path with a depth
137/// bound and a member budget. A member that re-enters the path
138/// ([`PropertyAnomaly::ComplexCycle`]), a complex property nested too deep
139/// ([`PropertyAnomaly::ComplexTooDeep`]), members past the budget
140/// ([`PropertyAnomaly::ComplexBudgetExceeded`]) and member ids absent from
141/// the file ([`PropertyAnomaly::MissingMember`]) are reported, never
142/// silently dropped.
143pub fn property_checked(model: &Model, id: EntityId) -> Option<(Property, Vec<PropertyAnomaly>)> {
144    let mut anomalies = Vec::new();
145    let property = read_property(model, id, &mut Nesting::new(&mut anomalies))?;
146    Some((property, anomalies))
147}
148
149pub(crate) fn read_property(
150    model: &Model,
151    id: EntityId,
152    nesting: &mut Nesting<'_>,
153) -> Option<Property> {
154    let entity = model.get(id)?;
155    let ty = entity.type_name.to_ascii_uppercase();
156    let name = entity.attributes.get(NAME).and_then(text);
157    let description = entity.attributes.get(DESCRIPTION).and_then(text);
158
159    let value = match ty.as_str() {
160        "IFCPROPERTYSINGLEVALUE" => PropertyValue::Single {
161            value: entity.attributes.get(2).and_then(MeasureValue::read),
162            unit: entity.attributes.get(3).and_then(entity_ref),
163        },
164        "IFCPROPERTYENUMERATEDVALUE" => PropertyValue::Enumerated {
165            values: entity
166                .attributes
167                .get(2)
168                .and_then(MeasureValue::read_list)
169                .unwrap_or_default(),
170            enumeration: entity.attributes.get(3).and_then(entity_ref),
171        },
172        // Upper is slot 2, lower is slot 3. See the module note.
173        "IFCPROPERTYBOUNDEDVALUE" => PropertyValue::Bounded {
174            upper: entity.attributes.get(2).and_then(MeasureValue::read),
175            lower: entity.attributes.get(3).and_then(MeasureValue::read),
176            unit: entity.attributes.get(4).and_then(entity_ref),
177            set_point: entity.attributes.get(5).and_then(MeasureValue::read),
178        },
179        "IFCPROPERTYLISTVALUE" => PropertyValue::List {
180            values: entity
181                .attributes
182                .get(2)
183                .and_then(MeasureValue::read_list)
184                .unwrap_or_default(),
185            unit: entity.attributes.get(3).and_then(entity_ref),
186        },
187        "IFCPROPERTYTABLEVALUE" => PropertyValue::Table {
188            defining: entity
189                .attributes
190                .get(2)
191                .and_then(MeasureValue::read_list)
192                .unwrap_or_default(),
193            defined: entity
194                .attributes
195                .get(3)
196                .and_then(MeasureValue::read_list)
197                .unwrap_or_default(),
198            interpolation: entity.attributes.get(7).and_then(enum_text),
199        },
200        "IFCPROPERTYREFERENCEVALUE" => PropertyValue::Reference {
201            usage: entity.attributes.get(2).and_then(text),
202            reference: entity.attributes.get(3).and_then(entity_ref),
203        },
204        "IFCCOMPLEXPROPERTY" => PropertyValue::Complex {
205            usage: entity.attributes.get(2).and_then(text),
206            properties: complex_members(model, id, entity.attributes.get(3), nesting),
207        },
208        _ => PropertyValue::Unsupported {
209            type_name: ty.as_str().into(),
210        },
211    };
212
213    Some(Property {
214        id,
215        name,
216        description,
217        value,
218    })
219}
220
221/// Read an enumeration constant such as `.LINEAR.`
222///
223/// Distinct from `text`: an IFC enum is written unquoted, so a reader
224/// expecting `Value::Text` finds nothing and silently reports "unstated".
225fn enum_text(value: &ifc_model::Value) -> Option<Arc<str>> {
226    match value.unwrap_typed() {
227        ifc_model::Value::Enum(t) | ifc_model::Value::Text(t) => Some(t.clone()),
228        _ => None,
229    }
230}
231
232fn text(value: &ifc_model::Value) -> Option<Arc<str>> {
233    match value.unwrap_typed() {
234        ifc_model::Value::Text(t) => Some(t.clone()),
235        _ => None,
236    }
237}
238
239fn entity_ref(value: &ifc_model::Value) -> Option<EntityId> {
240    match value.unwrap_typed() {
241        ifc_model::Value::Ref(id) => Some(*id),
242        _ => None,
243    }
244}