Skip to main content

ifc_material/usage/
resolution.rs

1//! Deterministic material-select and occurrence/type resolution.
2//!
3//! Every hop reads against the model's release: `IfcRelDefinesByType` slots
4//! and the legal `IfcTypeObject` subtypes come from its bundled table, and a
5//! select member the release does not declare is refused.
6
7use ifc_model::{Entity, EntityId};
8
9use crate::release::{is_type_object, Release};
10use crate::usage::index::{Lookup, DEFINES_BY_TYPE};
11use crate::view::required_ref;
12use crate::{
13    Material, MaterialAssignment, MaterialConstituent, MaterialConstituentSet, MaterialError,
14    MaterialLayer, MaterialLayerSet, MaterialLayerSetUsage, MaterialLayerWithOffsets, MaterialList,
15    MaterialProfile, MaterialProfileSet, MaterialProfileSetUsage, MaterialProfileSetUsageTapering,
16    MaterialProfileWithOffsets, MaterialResult, MaterialView,
17};
18
19/// A resolved branch of the abstract `IfcMaterialDefinition` select.
20///
21/// IFC2X3 has no `IfcMaterialDefinition` supertype; its `IfcMaterialSelect`
22/// members `IfcMaterial`, `IfcMaterialLayer` and `IfcMaterialLayerSet`
23/// resolve to the same branches here. The constituent and profile branches
24/// only occur for IFC4 and IFC4X3 models.
25#[derive(Debug, Clone, Copy)]
26pub enum MaterialDefinition<'m> {
27    /// Resolves to an `IfcMaterial`.
28    Material(Material<'m>),
29    /// Resolves to an `IfcMaterialConstituent`.
30    Constituent(MaterialConstituent<'m>),
31    /// Resolves to an `IfcMaterialConstituentSet`.
32    ConstituentSet(MaterialConstituentSet<'m>),
33    /// Resolves to an `IfcMaterialLayer`.
34    Layer(MaterialLayer<'m>),
35    /// Resolves to an `IfcMaterialLayerWithOffsets`.
36    LayerWithOffsets(MaterialLayerWithOffsets<'m>),
37    /// Resolves to an `IfcMaterialLayerSet`.
38    LayerSet(MaterialLayerSet<'m>),
39    /// Resolves to an `IfcMaterialProfile`.
40    Profile(MaterialProfile<'m>),
41    /// Resolves to an `IfcMaterialProfileWithOffsets`.
42    ProfileWithOffsets(MaterialProfileWithOffsets<'m>),
43    /// Resolves to an `IfcMaterialProfileSet`.
44    ProfileSet(MaterialProfileSet<'m>),
45}
46
47/// A resolved branch of the abstract `IfcMaterialUsageDefinition` select.
48///
49/// IFC2X3 has no `IfcMaterialUsageDefinition` supertype; its
50/// `IfcMaterialLayerSetUsage` resolves to [`Self::LayerSet`].
51#[derive(Debug, Clone, Copy)]
52pub enum MaterialUsageDefinition<'m> {
53    /// Resolves to an `IfcMaterialLayerSetUsage`.
54    LayerSet(MaterialLayerSetUsage<'m>),
55    /// Resolves to an `IfcMaterialProfileSetUsage`.
56    ProfileSet(MaterialProfileSetUsage<'m>),
57    /// Resolves to an `IfcMaterialProfileSetUsageTapering`.
58    ProfileSetTapering(MaterialProfileSetUsageTapering<'m>),
59}
60
61/// A resolved branch of the abstract `IfcMaterialSelect`.
62#[derive(Debug, Clone, Copy)]
63pub enum ResolvedMaterialSelect<'m> {
64    /// Resolves to an `IfcMaterialDefinition` subtype.
65    Definition(MaterialDefinition<'m>),
66    /// Resolves to an `IfcMaterialList`.
67    List(MaterialList<'m>),
68    /// Resolves to an `IfcMaterialUsageDefinition` subtype.
69    Usage(MaterialUsageDefinition<'m>),
70}
71
72/// Whether a resolved material assignment came from the object directly or
73/// was inherited from its `IfcTypeObject`.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum AssignmentSource {
76    /// The `IfcRelAssociatesMaterial` directly relates the queried object.
77    Occurrence,
78    /// The `IfcRelAssociatesMaterial` relates the object's `IfcTypeObject`,
79    /// identified by this entity id, and was inherited from it.
80    Type(EntityId),
81}
82
83/// A fully resolved material for one object, with provenance.
84#[derive(Debug, Clone, Copy)]
85#[non_exhaustive]
86pub struct ResolvedAssignment<'m> {
87    /// The `IfcRelAssociatesMaterial` that produced this resolution.
88    pub assignment: MaterialAssignment<'m>,
89    /// The resolved `IfcMaterialSelect` branch.
90    pub material: ResolvedMaterialSelect<'m>,
91    /// Whether the assignment applied directly or via the object's type.
92    pub source: AssignmentSource,
93}
94
95/// Every concrete `IfcMaterialSelect` member of any bundled release that
96/// [`classify`] dispatches. `release_layout` tests pin, per release, that
97/// the release's own select closure is exactly the instantiable subset.
98pub(crate) const SELECT_MEMBERS: &[&str] = &[
99    "IFCMATERIAL",
100    "IFCMATERIALCONSTITUENT",
101    "IFCMATERIALCONSTITUENTSET",
102    "IFCMATERIALLAYER",
103    "IFCMATERIALLAYERWITHOFFSETS",
104    "IFCMATERIALLAYERSET",
105    "IFCMATERIALPROFILE",
106    "IFCMATERIALPROFILEWITHOFFSETS",
107    "IFCMATERIALPROFILESET",
108    "IFCMATERIALLIST",
109    "IFCMATERIALLAYERSETUSAGE",
110    "IFCMATERIALPROFILESETUSAGE",
111    "IFCMATERIALPROFILESETUSAGETAPERING",
112];
113
114/// Dispatch a record to its select branch by type name alone, bound to
115/// `release`. `None` for a type that is no select member of any release.
116fn classify<'m>(
117    id: EntityId,
118    entity: &'m Entity,
119    release: Release<'m>,
120) -> Option<(&'static str, ResolvedMaterialSelect<'m>)> {
121    use MaterialDefinition as D;
122    use MaterialUsageDefinition as U;
123    use ResolvedMaterialSelect as S;
124    let name = SELECT_MEMBERS
125        .iter()
126        .copied()
127        .find(|name| entity.is_type(name))?;
128    let resolved = match name {
129        "IFCMATERIAL" => S::Definition(D::Material(Material::from_known(id, entity, release))),
130        "IFCMATERIALCONSTITUENT" => S::Definition(D::Constituent(MaterialConstituent::from_known(
131            id, entity, release,
132        ))),
133        "IFCMATERIALCONSTITUENTSET" => S::Definition(D::ConstituentSet(
134            MaterialConstituentSet::from_known(id, entity, release),
135        )),
136        "IFCMATERIALLAYER" => {
137            S::Definition(D::Layer(MaterialLayer::from_known(id, entity, release)))
138        }
139        "IFCMATERIALLAYERWITHOFFSETS" => S::Definition(D::LayerWithOffsets(
140            MaterialLayerWithOffsets::from_known(id, entity, release),
141        )),
142        "IFCMATERIALLAYERSET" => S::Definition(D::LayerSet(MaterialLayerSet::from_known(
143            id, entity, release,
144        ))),
145        "IFCMATERIALPROFILE" => {
146            S::Definition(D::Profile(MaterialProfile::from_known(id, entity, release)))
147        }
148        "IFCMATERIALPROFILEWITHOFFSETS" => S::Definition(D::ProfileWithOffsets(
149            MaterialProfileWithOffsets::from_known(id, entity, release),
150        )),
151        "IFCMATERIALPROFILESET" => S::Definition(D::ProfileSet(MaterialProfileSet::from_known(
152            id, entity, release,
153        ))),
154        "IFCMATERIALLIST" => S::List(MaterialList::from_known(id, entity, release)),
155        "IFCMATERIALLAYERSETUSAGE" => S::Usage(U::LayerSet(MaterialLayerSetUsage::from_known(
156            id, entity, release,
157        ))),
158        "IFCMATERIALPROFILESETUSAGE" => S::Usage(U::ProfileSet(
159            MaterialProfileSetUsage::from_known(id, entity, release),
160        )),
161        _ => S::Usage(U::ProfileSetTapering(
162            MaterialProfileSetUsageTapering::from_known(id, entity, release),
163        )),
164    };
165    Some((name, resolved))
166}
167
168impl<'m> MaterialView<'m> {
169    /// Every concrete subtype of the abstract `IfcMaterialDefinition`.
170    ///
171    /// Yields by type name; a record the model's release does not declare
172    /// (an IFC2X3 constituent set, say) is still yielded, and its accessors
173    /// fail with [`MaterialError::EntityNotInSchema`].
174    pub fn material_definitions(self) -> impl Iterator<Item = MaterialDefinition<'m>> + 'm {
175        let release = self.release();
176        self.model()
177            .iter()
178            .filter_map(move |(id, entity)| match classify(id, entity, release)?.1 {
179                ResolvedMaterialSelect::Definition(definition) => Some(definition),
180                _ => None,
181            })
182    }
183
184    /// Every concrete subtype of the abstract `IfcMaterialUsageDefinition`.
185    ///
186    /// Yields by type name, as [`Self::material_definitions`] does.
187    pub fn material_usage_definitions(
188        self,
189    ) -> impl Iterator<Item = MaterialUsageDefinition<'m>> + 'm {
190        let release = self.release();
191        self.model()
192            .iter()
193            .filter_map(move |(id, entity)| match classify(id, entity, release)?.1 {
194                ResolvedMaterialSelect::Usage(usage) => Some(usage),
195                _ => None,
196            })
197    }
198
199    /// Resolves `id` as an `IfcMaterialSelect` branch of the model's release
200    /// by dispatching on its concrete IFC entity type.
201    ///
202    /// # Errors
203    ///
204    /// [`MaterialError::WrongEntityType`] if `id` names an entity that is no
205    /// `MaterialResource` select member;
206    /// [`MaterialError::EntityNotInSchema`] if it is a member of another
207    /// release only, such as an `IfcMaterialConstituentSet` or
208    /// `IfcMaterialProfileSet` in an IFC2X3 model; and the release-binding
209    /// errors when the header binds no release.
210    pub fn resolve_material_select(
211        self,
212        id: EntityId,
213    ) -> MaterialResult<ResolvedMaterialSelect<'m>> {
214        let entity = self.entity(id, id)?;
215        let wrong = || MaterialError::WrongEntityType {
216            expected: "IfcMaterialSelect",
217            actual: entity.type_name.to_string(),
218        };
219        let (name, resolved) = classify(id, entity, self.release()).ok_or_else(wrong)?;
220        let (_, schema) = self.release().require_entity(name, Some(id))?;
221        if !schema.accepts_type("IfcMaterialSelect", name) {
222            return Err(wrong());
223        }
224        Ok(resolved)
225    }
226
227    /// Resolves the single material that applies to `object`, preferring a
228    /// direct `IfcRelAssociatesMaterial` on the object itself and falling
229    /// back to the material assigned to its `IfcTypeObject` via
230    /// `IfcRelDefinesByType`. Returns `Ok(None)` if neither exists. Fails
231    /// with [`crate::MaterialError::AmbiguousAssignment`] or
232    /// [`crate::MaterialError::AmbiguousType`] for more than one distinct
233    /// material, or more than one `IfcRelDefinesByType`, and with
234    /// `crate::MaterialError::UnknownEntity` if `object` is not in the
235    /// model.
236    ///
237    /// Several `IfcRelAssociatesMaterial` on one object, or on its type,
238    /// resolve when they name one `RelatingMaterial` (compared by entity id,
239    /// never by content); `assignment` is then the lowest-id relationship.
240    /// `AmbiguousAssignment::count` is the number of distinct materials.
241    ///
242    /// Every record is read against the model's release, so an IFC2X3 model
243    /// resolves with IFC2X3 slots and type objects.
244    ///
245    /// The type fallback is exactly one `IfcRelDefinesByType` hop, and two
246    /// such relations are ambiguous even when they name the same type: no
247    /// release allows it (IFC2X3 `IfcObject` WR1; IFC4 and IFC4X3
248    /// `IsTypedBy SET [0:1]`), so the file states the typing twice and this
249    /// lookup does not guess which statement was meant. (`ifc-resource`
250    /// deliberately accepts a repeated relation naming the same type.)
251    /// `HasAssociations` is
252    /// `SET [0:?]` in every release, which is why several material
253    /// relationships are accepted. For many objects use
254    /// [`crate::MaterialIndex`].
255    pub fn assigned_material(
256        self,
257        object: EntityId,
258    ) -> MaterialResult<Option<ResolvedAssignment<'m>>> {
259        self.assigned_material_in(self.lookup(), object)
260    }
261
262    pub(crate) fn assigned_material_in(
263        self,
264        lookup: Lookup<'_>,
265        object: EntityId,
266    ) -> MaterialResult<Option<ResolvedAssignment<'m>>> {
267        self.model()
268            .get(object)
269            .ok_or(MaterialError::UnknownEntity { id: object })?;
270
271        let direct = self.assignments_in(lookup, object)?;
272        if let Some(assignment) = self.single_material(object, &direct)? {
273            return self
274                .resolve_assignment(assignment, AssignmentSource::Occurrence)
275                .map(Some);
276        }
277
278        let Some((relation_id, type_id)) = self.type_relation(lookup, object)? else {
279            return Ok(None);
280        };
281        let type_entity = self.entity(relation_id, type_id)?;
282        if !is_type_object(self.release(), &type_entity.type_name)? {
283            return Err(MaterialError::ReferenceType {
284                source_id: relation_id,
285                target: type_id,
286                expected: "IFCTYPEOBJECT subtype",
287                actual: type_entity.type_name.to_string(),
288            });
289        }
290
291        let assigned = self.assignments_in(lookup, type_id)?;
292        self.single_material(type_id, &assigned)?
293            .map(|assignment| self.resolve_assignment(assignment, AssignmentSource::Type(type_id)))
294            .transpose()
295    }
296
297    /// The lowest-id of `holder`'s relationships when they all name one
298    /// `RelatingMaterial` (by entity id; content is never compared), `None`
299    /// when there are none. Every relationship's `RelatingMaterial` is read,
300    /// so a missing or non-reference one refuses with its own error.
301    fn single_material(
302        self,
303        holder: EntityId,
304        assignments: &[MaterialAssignment<'m>],
305    ) -> MaterialResult<Option<MaterialAssignment<'m>>> {
306        let Some(first) = assignments.first().copied() else {
307            return Ok(None);
308        };
309        let mut materials = Vec::new();
310        for assignment in assignments {
311            let material = assignment.relating_material_id()?;
312            if !materials.contains(&material) {
313                materials.push(material);
314            }
315        }
316        if materials.len() > 1 {
317            return Err(MaterialError::AmbiguousAssignment {
318                object: holder,
319                count: materials.len(),
320            });
321        }
322        Ok(Some(first))
323    }
324
325    /// The single `IfcRelDefinesByType` typing `object`, as
326    /// `(relation, type)`.
327    fn type_relation(
328        self,
329        lookup: Lookup<'_>,
330        object: EntityId,
331    ) -> MaterialResult<Option<(EntityId, EntityId)>> {
332        let release = self.release();
333        let mut type_relations = Vec::new();
334        for (relation_id, relation) in
335            self.naming(lookup.referrers, DEFINES_BY_TYPE, "RelatedObjects", object)?
336        {
337            if self.names(lookup, DEFINES_BY_TYPE, relation_id, relation, object)? {
338                let type_slot = release.slot(DEFINES_BY_TYPE, relation_id, "RelatingType")?;
339                let type_id = required_ref(
340                    DEFINES_BY_TYPE,
341                    relation_id,
342                    relation,
343                    type_slot,
344                    "RelatingType",
345                )?;
346                type_relations.push((relation_id, type_id));
347            }
348        }
349        if type_relations.len() > 1 {
350            return Err(MaterialError::AmbiguousType {
351                object,
352                count: type_relations.len(),
353            });
354        }
355        Ok(type_relations.first().copied())
356    }
357
358    fn resolve_assignment(
359        self,
360        assignment: MaterialAssignment<'m>,
361        source: AssignmentSource,
362    ) -> MaterialResult<ResolvedAssignment<'m>> {
363        let material_id = assignment.relating_material_id()?;
364        Ok(ResolvedAssignment {
365            assignment,
366            material: self.resolve_material_select(material_id)?,
367            source,
368        })
369    }
370}