Skip to main content

openbim_ifc_binding_core/
systems.rs

1//! Distribution systems and their membership (feature `systems`, #123).
2//!
3//! The facade's `systems` reader finds every `IfcSystem` subtype the
4//! declared release has (an `IfcZone` is one in IFC4, not in IFC2X3), with
5//! its members and the structures it serves. Memberships the file states
6//! but cannot support are reported as anomalies with a stable `kind`, never
7//! dropped silently. Records are read against the release the header
8//! declares, IFC2X3, IFC4 or IFC4X3; any other is refused with
9//! `unsupported-schema`.
10
11use crate::record::{Field, Record, ToRecord};
12use crate::{BindingError, IfcModel};
13
14/// Every system in a model, and what the reader could not place.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Systems {
17    /// The systems, by entity id.
18    pub systems: Vec<System>,
19    /// Memberships the file states but the schema forbids or the file
20    /// cannot resolve.
21    pub anomalies: Vec<SystemAnomaly>,
22}
23
24/// One system.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct System {
27    /// Its entity id.
28    pub id: u64,
29    /// Its `GlobalId`.
30    pub global_id: Option<String>,
31    /// Its entity type, upper-case: `IFCDISTRIBUTIONSYSTEM`, ...
32    pub type_name: String,
33    /// `Name`.
34    pub name: Option<String>,
35    /// `IfcDistributionSystem.LongName` (IFC4, IFC4X3).
36    pub long_name: Option<String>,
37    /// `IfcDistributionSystem.PredefinedType`, e.g. `HEATING`.
38    pub predefined_type: Option<String>,
39    /// Members (`IfcRelAssignsToGroup`), in file order.
40    pub members: Vec<u64>,
41    /// Spatial structures it serves (`IfcRelServicesBuildings`).
42    pub serviced_buildings: Vec<u64>,
43    /// IFC4X3: spatial elements referencing it (`ServicesFacilities`).
44    pub serviced_facilities: Vec<u64>,
45}
46
47/// A membership the reader could not honour.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct SystemAnomaly {
50    /// `dangling`, `zone-member-not-spatial`, `contained-twice`,
51    /// `port-attached-twice`, `not-a-port`, `not-a-system`,
52    /// `services-buildings-twice` or `serviced-not-spatial`.
53    pub kind: String,
54    /// The relationship (or, for the `-twice` kinds, the entity) at fault.
55    pub subject: u64,
56    /// The other entity involved: the missing id, the rejected member,
57    /// structure, element or relationship.
58    pub other: Option<u64>,
59    /// A one-line explanation.
60    pub message: String,
61}
62
63impl IfcModel {
64    /// Every system, with its members and served structures.
65    ///
66    /// Refused with `unsupported-schema` for a release other than IFC2X3,
67    /// IFC4 or IFC4X3, and with `feature-disabled` without the `systems`
68    /// feature.
69    pub fn systems(&self) -> Result<Systems, BindingError> {
70        #[cfg(feature = "systems")]
71        {
72            read(self)
73        }
74        #[cfg(not(feature = "systems"))]
75        {
76            Err(BindingError::FeatureDisabled("systems"))
77        }
78    }
79}
80
81#[cfg(feature = "systems")]
82fn read(model: &IfcModel) -> Result<Systems, BindingError> {
83    use ifc::systems::{SchemaResolutionError, SystemAnomaly as Anomaly};
84
85    let (systems, anomalies) =
86        ifc::systems::systems(&model.inner).map_err(|error| match error {
87            SchemaResolutionError::UnsupportedSchema { schema } => {
88                BindingError::UnsupportedSchema(schema)
89            }
90            SchemaResolutionError::MissingSchema => BindingError::UnsupportedSchema(String::new()),
91            other => BindingError::UnsupportedSchema(other.to_string()),
92        })?;
93    let mut out = Vec::with_capacity(systems.len());
94    for system in systems {
95        let identity = model.identity(system.id.0)?;
96        out.push(System {
97            id: system.id.0,
98            global_id: identity.global_id,
99            type_name: system.type_name,
100            name: system.name,
101            long_name: system.long_name,
102            predefined_type: system.predefined_type,
103            members: system.members.iter().map(|id| id.0).collect(),
104            serviced_buildings: system.serviced_buildings.iter().map(|id| id.0).collect(),
105            serviced_facilities: system.serviced_facilities.iter().map(|id| id.0).collect(),
106        });
107    }
108    let anomalies = anomalies
109        .into_iter()
110        .map(|anomaly| {
111            let message = format!("{anomaly:?}");
112            let (kind, subject, other) = match anomaly {
113                Anomaly::Dangling { relation, missing } => ("dangling", relation, Some(missing)),
114                Anomaly::ZoneMemberNotSpatial {
115                    relation, member, ..
116                } => ("zone-member-not-spatial", relation, Some(member)),
117                Anomaly::ContainedTwice {
118                    element, second, ..
119                } => ("contained-twice", element, Some(second)),
120                Anomaly::PortAttachedTwice { port, rejected, .. } => {
121                    ("port-attached-twice", port, Some(rejected))
122                }
123                Anomaly::NotAPort {
124                    relation, entity, ..
125                } => ("not-a-port", relation, Some(entity)),
126                Anomaly::NotASystem {
127                    relation, group, ..
128                } => ("not-a-system", relation, Some(group)),
129                Anomaly::ServicesBuildingsTwice {
130                    system, rejected, ..
131                } => ("services-buildings-twice", system, Some(rejected)),
132                Anomaly::ServicedNotSpatial {
133                    relation, target, ..
134                } => ("serviced-not-spatial", relation, Some(target)),
135                // An anomaly added after this binding: the message names it.
136                _ => ("other", ifc::EntityId(0), None),
137            };
138            SystemAnomaly {
139                kind: kind.to_owned(),
140                subject: subject.0,
141                other: other.map(|id| id.0),
142                message,
143            }
144        })
145        .collect();
146    Ok(Systems {
147        systems: out,
148        anomalies,
149    })
150}
151
152impl ToRecord for Systems {
153    fn to_record(&self) -> Record {
154        Record::new(
155            "Systems",
156            vec![
157                ("systems", Field::records(&self.systems)),
158                ("anomalies", Field::records(&self.anomalies)),
159            ],
160        )
161    }
162}
163
164impl ToRecord for System {
165    fn to_record(&self) -> Record {
166        Record::new(
167            "System",
168            vec![
169                ("id", Field::Id(self.id)),
170                ("global_id", Field::text(self.global_id.clone())),
171                ("type_name", Field::Text(self.type_name.clone())),
172                ("name", Field::text(self.name.clone())),
173                ("long_name", Field::text(self.long_name.clone())),
174                ("predefined_type", Field::text(self.predefined_type.clone())),
175                ("members", Field::ids(self.members.iter().copied())),
176                (
177                    "serviced_buildings",
178                    Field::ids(self.serviced_buildings.iter().copied()),
179                ),
180                (
181                    "serviced_facilities",
182                    Field::ids(self.serviced_facilities.iter().copied()),
183                ),
184            ],
185        )
186    }
187}
188
189impl ToRecord for SystemAnomaly {
190    fn to_record(&self) -> Record {
191        Record::new(
192            "SystemAnomaly",
193            vec![
194                ("kind", Field::Text(self.kind.clone())),
195                ("subject", Field::Id(self.subject)),
196                ("other", Field::id(self.other)),
197                ("message", Field::Text(self.message.clone())),
198            ],
199        )
200    }
201}