Skip to main content

ifc_systems/zone/
spatial_group.rs

1//! Where an element sits spatially, and where it is merely referenced.
2//!
3//! # Two relationships that are not interchangeable
4//!
5//! ```text
6//! IfcRelContainedInSpatialStructure   4 = RelatedElements  5 = RelatingStructure
7//! IfcRelReferencedInSpatialStructure  4 = RelatedElements  5 = RelatingStructure
8//! ```
9//!
10//! Same slot layout, different cardinality and different meaning:
11//!
12//! - `ContainedInStructure` is `SET [0:1]`: an element has AT MOST ONE
13//!   containing structure. This is its home.
14//! - `ReferencedInStructures` is `SET [0:?]`: an element may be referenced by
15//!   MANY structures. A duct passing through five rooms is referenced by all
16//!   five and contained by none of them.
17//!
18//! Merging the two loses the distinction that makes the second useful. A
19//! caller asking "which storey owns this pump" wants containment; a caller
20//! asking "which rooms does this duct serve" wants references. They are kept
21//! apart.
22
23use std::collections::{BTreeMap, BTreeSet};
24
25use ifc_model::{EntityId, Model, Value};
26
27use crate::error::{SchemaResolutionError, SystemAnomaly};
28
29fn refs(value: Option<&Value>) -> Vec<EntityId> {
30    match value {
31        Some(Value::List(items)) => items
32            .iter()
33            .filter_map(|v| match v {
34                Value::Ref(id) => Some(*id),
35                _ => None,
36            })
37            .collect(),
38        Some(Value::Ref(id)) => vec![*id],
39        _ => Vec::new(),
40    }
41}
42
43pub(crate) mod slot {
44    /// Both spatial relationships put elements at 4 and the structure at 5.
45    pub const RELATED_ELEMENTS: usize = 4;
46    pub const RELATING_STRUCTURE: usize = 5;
47}
48
49/// Where one element sits in the spatial structure.
50#[derive(Debug, Clone, PartialEq, Eq, Default)]
51#[non_exhaustive]
52pub struct SpatialPlacement {
53    /// The single containing structure, if the file states one.
54    ///
55    /// `Option`, not `Vec`, because the schema says `SET [0:1]`. A file
56    /// stating two is malformed and reports `ContainedTwice`.
57    pub contained_in: Option<EntityId>,
58    /// Structures that reference this element, ascending by id.
59    ///
60    /// Unbounded by the schema, so a `Vec` is the honest shape.
61    pub referenced_in: Vec<EntityId>,
62}
63
64impl SpatialPlacement {
65    /// Every structure this element relates to, containment first.
66    ///
67    /// Convenience for callers that genuinely do not care which mechanism
68    /// stated the link -- but they must opt in, rather than the reader
69    /// flattening the distinction for everyone.
70    pub fn all_structures(&self) -> Vec<EntityId> {
71        let mut out: Vec<_> = self.contained_in.into_iter().collect();
72        out.extend(self.referenced_in.iter().copied());
73        out.dedup();
74        out
75    }
76}
77
78/// Read spatial containment and referencing for every element that has either.
79///
80/// Elements with no spatial relationship are absent from the map rather than
81/// present-and-empty: absence is the file's actual statement.
82///
83/// # Errors
84///
85/// [`SchemaResolutionError`] when the model's `FILE_SCHEMA` binds no release
86/// this crate is verified for (see [`crate::schema_of`]); the fixed slots
87/// above are pinned against each verified release's table.
88pub fn spatial_placements(
89    model: &Model,
90) -> Result<(BTreeMap<EntityId, SpatialPlacement>, Vec<SystemAnomaly>), SchemaResolutionError> {
91    crate::release::resolve(model)?;
92    let mut out: BTreeMap<EntityId, SpatialPlacement> = BTreeMap::new();
93    let mut anomalies = Vec::new();
94
95    // Containment: at most one per element, so a second is an anomaly.
96    for &relation in model.ids_of_type("IFCRELCONTAINEDINSPATIALSTRUCTURE") {
97        let Some(entity) = model.get(relation) else {
98            continue;
99        };
100        let structure = match entity.attributes.get(slot::RELATING_STRUCTURE) {
101            Some(Value::Ref(id)) => *id,
102            _ => continue,
103        };
104        for element in refs(entity.attributes.get(slot::RELATED_ELEMENTS)) {
105            let slot_entry = out.entry(element).or_default();
106            match slot_entry.contained_in {
107                Some(existing) if existing != structure => {
108                    // IfcElement.ContainedInStructure is SET [0:1]; two
109                    // different homes cannot both be true. Keep the first by
110                    // id order so the result is deterministic, and say so.
111                    anomalies.push(SystemAnomaly::ContainedTwice {
112                        element,
113                        first: existing,
114                        second: structure,
115                    });
116                }
117                Some(_) => {}
118                None => slot_entry.contained_in = Some(structure),
119            }
120        }
121    }
122
123    // Referencing: many per element is legal and expected.
124    let mut references: BTreeMap<EntityId, BTreeSet<EntityId>> = BTreeMap::new();
125    for &relation in model.ids_of_type("IFCRELREFERENCEDINSPATIALSTRUCTURE") {
126        let Some(entity) = model.get(relation) else {
127            continue;
128        };
129        let structure = match entity.attributes.get(slot::RELATING_STRUCTURE) {
130            Some(Value::Ref(id)) => *id,
131            _ => continue,
132        };
133        for element in refs(entity.attributes.get(slot::RELATED_ELEMENTS)) {
134            references.entry(element).or_default().insert(structure);
135        }
136    }
137    for (element, structures) in references {
138        out.entry(element).or_default().referenced_in = structures.into_iter().collect();
139    }
140
141    Ok((out, anomalies))
142}