Skip to main content

openbim_ifc_binding_core/
spatial.rs

1//! The spatial tree and containment (feature `spatial`, #123).
2//!
3//! The facade's `SpatialTree` reads the aggregation, containment and
4//! spatial-reference relationships once; this snapshot carries every
5//! container with its parent, sub-containers and the elements placed in
6//! it, so a host builds its project/site/building/storey/space outline
7//! from one call. Containers are classified against the release the header
8//! declares (IFC2X3, IFC4, IFC4X3); `release` is `None` for a bundled
9//! release the tree is not verified for (IFC4X1, IFC4X2), whose containers
10//! are those any verified release declares. A header naming no bundled
11//! release is refused with `unsupported-schema`.
12
13use crate::record::{Field, Record, ToRecord};
14use crate::{BindingError, IfcModel};
15
16/// The containment tree of a model.
17#[derive(Debug, Clone, PartialEq)]
18pub struct SpatialTree {
19    /// The release containers were classified against (`IFC4_ADD2_TC1`), or `None`
20    /// when the header's release is not one the tree is verified for.
21    pub release: Option<String>,
22    /// Containers no relationship places under a parent; a conformant file
23    /// has one, the `IfcProject`.
24    pub roots: Vec<u64>,
25    /// Every spatial container, by entity id.
26    pub nodes: Vec<SpatialNode>,
27    /// Containers other than the most general root that no aggregation
28    /// places under a parent: a detached branch.
29    pub orphans: Vec<u64>,
30    /// `(relationship, target)` pairs naming an entity the file lacks.
31    pub dangling: Vec<(u64, u64)>,
32    /// Statements the tree could not honour, in the order they were met.
33    pub anomalies: Vec<SpatialAnomaly>,
34}
35
36/// One spatial container.
37#[derive(Debug, Clone, PartialEq)]
38pub struct SpatialNode {
39    /// The container's entity id.
40    pub id: u64,
41    /// Its `GlobalId`.
42    pub global_id: Option<String>,
43    /// Its `Name`.
44    pub name: Option<String>,
45    /// Its entity type, upper-case.
46    pub type_name: String,
47    /// `project`, `site`, `building`, `storey`, `space` or `other` (a
48    /// spatial zone, an IFC4X3 facility or facility part, ...).
49    pub kind: String,
50    /// The container it is aggregated into.
51    pub parent: Option<u64>,
52    /// Sub-containers, in file order.
53    pub children: Vec<u64>,
54    /// Elements contained directly, in file order.
55    pub elements: Vec<u64>,
56    /// Elements referenced (`IfcRelReferencedInSpatialStructure`), not
57    /// contained.
58    pub referenced: Vec<u64>,
59}
60
61/// A second parent or a non-container structure the tree rejected.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct SpatialAnomaly {
64    /// `contained-twice`, `aggregated-twice`, `contained-in-non-container`
65    /// or `referenced-in-non-container`.
66    pub kind: String,
67    /// The relationship whose statement was dropped.
68    pub relation: u64,
69    /// The element, child or structure the statement is about.
70    pub subject: u64,
71    /// For a second parent: the parent kept.
72    pub kept: Option<u64>,
73}
74
75impl IfcModel {
76    /// The spatial containment tree.
77    ///
78    /// Refused with `unsupported-schema` when the header names no bundled
79    /// release, and with `feature-disabled` without the `spatial` feature.
80    pub fn spatial_tree(&self) -> Result<SpatialTree, BindingError> {
81        #[cfg(feature = "spatial")]
82        {
83            read(self)
84        }
85        #[cfg(not(feature = "spatial"))]
86        {
87            Err(BindingError::FeatureDisabled("spatial"))
88        }
89    }
90}
91
92#[cfg(feature = "spatial")]
93fn read(model: &IfcModel) -> Result<SpatialTree, BindingError> {
94    use ifc::spatial::SpatialAnomaly as Anomaly;
95    use ifc::SpatialKind;
96
97    model.declared_schema()?;
98    let tree = ifc::SpatialTree::build(&model.inner);
99    let ids = |ids: &[ifc::EntityId]| ids.iter().map(|id| id.0).collect::<Vec<_>>();
100    let mut nodes = Vec::new();
101    for node in tree.containers() {
102        let identity = model.identity(node.id.0)?;
103        let kind = match node.kind {
104            SpatialKind::Project => "project",
105            SpatialKind::Site => "site",
106            SpatialKind::Building => "building",
107            SpatialKind::Storey => "storey",
108            SpatialKind::Space => "space",
109            _ => "other",
110        };
111        nodes.push(SpatialNode {
112            id: node.id.0,
113            global_id: identity.global_id,
114            name: identity.name,
115            type_name: model.type_of(node.id.0)?.to_owned(),
116            kind: kind.to_owned(),
117            parent: node.parent.map(|id| id.0),
118            children: ids(&node.children),
119            elements: ids(&node.elements),
120            referenced: ids(tree.referenced_elements(node.id)),
121        });
122    }
123    let anomalies = tree
124        .anomalies()
125        .iter()
126        .map(|anomaly| {
127            let (kind, relation, subject, kept) = match *anomaly {
128                Anomaly::ContainedTwice {
129                    element,
130                    kept,
131                    relation,
132                    ..
133                } => ("contained-twice", relation, element, Some(kept)),
134                Anomaly::AggregatedTwice {
135                    child,
136                    kept,
137                    relation,
138                    ..
139                } => ("aggregated-twice", relation, child, Some(kept)),
140                Anomaly::ContainedInNonContainer {
141                    relation,
142                    structure,
143                } => ("contained-in-non-container", relation, structure, None),
144                Anomaly::ReferencedInNonContainer {
145                    relation,
146                    structure,
147                } => ("referenced-in-non-container", relation, structure, None),
148                // An anomaly added after this binding: still reported.
149                _ => ("other", ifc::EntityId(0), ifc::EntityId(0), None),
150            };
151            SpatialAnomaly {
152                kind: kind.to_owned(),
153                relation: relation.0,
154                subject: subject.0,
155                kept: kept.map(|id| id.0),
156            }
157        })
158        .collect();
159    Ok(SpatialTree {
160        release: tree
161            .release()
162            .map(|release| release.release_id().to_owned()),
163        roots: ids(tree.roots()),
164        nodes,
165        orphans: ids(tree.orphans()),
166        dangling: tree
167            .dangling()
168            .iter()
169            .map(|(relation, target)| (relation.0, target.0))
170            .collect(),
171        anomalies,
172    })
173}
174
175impl ToRecord for SpatialTree {
176    fn to_record(&self) -> Record {
177        Record::new(
178            "SpatialTree",
179            vec![
180                ("release", Field::text(self.release.clone())),
181                ("roots", Field::ids(self.roots.iter().copied())),
182                ("nodes", Field::records(&self.nodes)),
183                ("orphans", Field::ids(self.orphans.iter().copied())),
184                (
185                    "dangling",
186                    Field::List(
187                        self.dangling
188                            .iter()
189                            .map(|&(relation, target)| {
190                                Field::Record(Record::new(
191                                    "SpatialDanglingReference",
192                                    vec![
193                                        ("relation", Field::Id(relation)),
194                                        ("target", Field::Id(target)),
195                                    ],
196                                ))
197                            })
198                            .collect(),
199                    ),
200                ),
201                ("anomalies", Field::records(&self.anomalies)),
202            ],
203        )
204    }
205}
206
207impl ToRecord for SpatialNode {
208    fn to_record(&self) -> Record {
209        Record::new(
210            "SpatialNode",
211            vec![
212                ("id", Field::Id(self.id)),
213                ("global_id", Field::text(self.global_id.clone())),
214                ("name", Field::text(self.name.clone())),
215                ("type_name", Field::Text(self.type_name.clone())),
216                ("kind", Field::Text(self.kind.clone())),
217                ("parent", Field::id(self.parent)),
218                ("children", Field::ids(self.children.iter().copied())),
219                ("elements", Field::ids(self.elements.iter().copied())),
220                ("referenced", Field::ids(self.referenced.iter().copied())),
221            ],
222        )
223    }
224}
225
226impl ToRecord for SpatialAnomaly {
227    fn to_record(&self) -> Record {
228        Record::new(
229            "SpatialAnomaly",
230            vec![
231                ("kind", Field::Text(self.kind.clone())),
232                ("relation", Field::Id(self.relation)),
233                ("subject", Field::Id(self.subject)),
234                ("kept", Field::id(self.kept)),
235            ],
236        )
237    }
238}