ifc-spatial 0.3.0

IFC spatial containment and objectified relationship traversal: project, site, building, storey, element.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Authoring space boundaries and path connections.
//!
//! A space boundary says which element bounds a space and how.
//! The three levels refine each other: the base form states the
//! boundary, the 1st level adds a parent, the 2nd level adds the
//! boundary on the other side of the same element.
//!
//! `CorrectPhysOrVirt` ties the physical/virtual flag to the type
//! of the bounding element, so the flag cannot be set independently
//! of what it describes. This module reads the type name from the
//! transaction or model.
//!
//! Records are laid out by attribute name from the model's declared
//! release (#202). IFC2X3 TC1 declares only the base
//! `IfcRelSpaceBoundary`, with a required `IfcRoot.OwnerHistory`, and an
//! `IfcInternalOrExternalEnum` without the `EXTERNAL_*` refinements.

use ifc_model::guid::Guid;
use ifc_model::{Edit, Entity, EntityId, Model, Transaction, Value};

use super::release::stage;
use super::{invalid, SpatialAuthoringResult};

/// Which space-boundary level to stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BoundaryLevel {
    /// `IfcRelSpaceBoundary`: the boundary alone.
    Base,
    /// `IfcRelSpaceBoundary1stLevel`: adds `ParentBoundary`.
    First,
    /// `IfcRelSpaceBoundary2ndLevel`: adds `CorrespondingBoundary`.
    Second,
}

impl BoundaryLevel {
    /// The entity type name for this level.
    fn type_name(self) -> &'static str {
        match self {
            Self::Base => "IFCRELSPACEBOUNDARY",
            Self::First => "IFCRELSPACEBOUNDARY1STLEVEL",
            Self::Second => "IFCRELSPACEBOUNDARY2NDLEVEL",
        }
    }
}

/// Authored fields for a space boundary.
///
/// `#[non_exhaustive]`: build it with [`BoundaryDraft::new`] and the
/// setters.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct BoundaryDraft<'a> {
    /// `IfcRoot.Name`.
    pub name: Option<&'a str>,
    /// `IfcRoot.Description`.
    pub description: Option<&'a str>,
    /// `RelatingSpace`, an `IfcSpaceBoundarySelect`.
    pub space: EntityId,
    /// `RelatedBuildingElement`, an `IfcElement`.
    pub element: EntityId,
    /// `ConnectionGeometry`, if the boundary has a shape.
    pub connection_geometry: Option<EntityId>,
    /// `PhysicalOrVirtualBoundary`. Constrained by `CorrectPhysOrVirt`.
    pub physical_or_virtual: &'a str,
    /// `InternalOrExternalBoundary`.
    pub internal_or_external: &'a str,
    /// `ParentBoundary`. First and second levels only.
    pub parent: Option<EntityId>,
    /// `CorrespondingBoundary`. Second level only.
    pub corresponding: Option<EntityId>,
}

impl<'a> BoundaryDraft<'a> {
    /// A boundary of `space` formed by `element`, with the two enumeration
    /// tokens the schema requires (`PhysicalOrVirtualBoundary`,
    /// `InternalOrExternalBoundary`); every optional attribute unset.
    #[must_use]
    pub fn new(
        space: EntityId,
        element: EntityId,
        physical_or_virtual: &'a str,
        internal_or_external: &'a str,
    ) -> Self {
        Self {
            name: None,
            description: None,
            space,
            element,
            connection_geometry: None,
            physical_or_virtual,
            internal_or_external,
            parent: None,
            corresponding: None,
        }
    }

    /// Set `IfcRoot.Name`.
    #[must_use]
    pub fn name(mut self, value: &'a str) -> Self {
        self.name = Some(value);
        self
    }

    /// Set `IfcRoot.Description`.
    #[must_use]
    pub fn description(mut self, value: &'a str) -> Self {
        self.description = Some(value);
        self
    }

    /// Set `ConnectionGeometry`.
    #[must_use]
    pub fn connection_geometry(mut self, value: EntityId) -> Self {
        self.connection_geometry = Some(value);
        self
    }

    /// Set `ParentBoundary` (first and second levels only).
    #[must_use]
    pub fn parent(mut self, value: EntityId) -> Self {
        self.parent = Some(value);
        self
    }

    /// Set `CorrespondingBoundary` (second level only).
    #[must_use]
    pub fn corresponding(mut self, value: EntityId) -> Self {
        self.corresponding = Some(value);
        self
    }
}

const PHYS_OR_VIRT: &[&str] = &["PHYSICAL", "VIRTUAL", "NOTDEFINED"];
const INT_OR_EXT: &[&str] = &[
    "INTERNAL",
    "EXTERNAL",
    "EXTERNAL_EARTH",
    "EXTERNAL_WATER",
    "EXTERNAL_FIRE",
    "NOTDEFINED",
];

/// Resolve the type name of a staged or committed entity.
fn type_name<'a>(tx: &'a Transaction, model: &'a Model, id: EntityId) -> Option<&'a str> {
    tx.edits()
        .iter()
        .rev()
        .find_map(|edit| match edit {
            Edit::Create { id: staged, entity } if *staged == id => Some(entity.type_name.as_ref()),
            _ => None,
        })
        .or_else(|| model.get(id).map(|entity| entity.type_name.as_ref()))
}

/// Stage an `IfcRelSpaceBoundary` at the requested level, in the model's
/// declared release, with `OwnerHistory` unset.
///
/// The record is laid out by attribute name from the release's table. IFC4
/// and IFC4X3 allow the unset `OwnerHistory`; IFC2X3 requires it, so an
/// IFC2X3 model is refused with
/// [`AuthoringRequired`](super::SpatialAuthoringError::AuthoringRequired):
/// use [`create_space_boundary_with_owner_history`] there.
///
/// # Errors
///
/// Refuses a malformed GlobalId, an unknown enum token, a `parent`
/// or `corresponding` reference on a level that does not declare the
/// slot, and a physical/virtual flag that contradicts the bounding
/// element (`CorrectPhysOrVirt`). Against the release: a header binding no
/// single known release (`MultipleSchemas`, `UnsupportedSchema`), a level
/// it does not declare (`EntityNotInSchema`: IFC2X3 has no 1st or 2nd
/// level), a token it does not declare (`AuthoringValueType`), and the
/// IFC2X3 `OwnerHistory` (`AuthoringRequired`). Nothing is staged on an
/// error.
pub fn create_space_boundary(
    tx: &mut Transaction,
    model: &Model,
    level: BoundaryLevel,
    global_id: &str,
    draft: BoundaryDraft<'_>,
) -> SpatialAuthoringResult<EntityId> {
    let values = boundary_values(tx, model, level, global_id, draft)?;
    stage(tx, model, level.type_name(), values, None)
}

/// [`create_space_boundary`] with a caller-supplied `IfcOwnerHistory`,
/// which IFC2X3 requires.
///
/// # Errors
///
/// Those of [`create_space_boundary`] except the IFC2X3 refusal, and an
/// `owner_history` that is neither in the model nor staged
/// (`MissingReference`) or not an `IfcOwnerHistory`
/// (`WrongReferenceType`). Nothing is staged on an error.
pub fn create_space_boundary_with_owner_history(
    tx: &mut Transaction,
    model: &Model,
    level: BoundaryLevel,
    global_id: &str,
    draft: BoundaryDraft<'_>,
    owner_history: EntityId,
) -> SpatialAuthoringResult<EntityId> {
    let values = boundary_values(tx, model, level, global_id, draft)?;
    stage(tx, model, level.type_name(), values, Some(owner_history))
}

/// Validate a boundary draft and name its values.
fn boundary_values(
    tx: &Transaction,
    model: &Model,
    level: BoundaryLevel,
    global_id: &str,
    draft: BoundaryDraft<'_>,
) -> SpatialAuthoringResult<Vec<(&'static str, Value)>> {
    let entity = level.type_name();
    if Guid::parse(global_id).is_none() {
        return Err(invalid(entity, "GlobalId", global_id));
    }
    let physical = draft.physical_or_virtual.to_ascii_uppercase();
    if !PHYS_OR_VIRT.contains(&physical.as_str()) {
        return Err(invalid(
            entity,
            "PhysicalOrVirtualBoundary",
            draft.physical_or_virtual,
        ));
    }
    let internal = draft.internal_or_external.to_ascii_uppercase();
    if !INT_OR_EXT.contains(&internal.as_str()) {
        return Err(invalid(
            entity,
            "InternalOrExternalBoundary",
            draft.internal_or_external,
        ));
    }

    // CorrectPhysOrVirt: the flag and the element must agree. A
    // physical boundary cannot be bounded by a virtual element, and a
    // virtual one only by a virtual element or an opening. NOTDEFINED
    // is unconstrained.
    let bounded_by = type_name(tx, model, draft.element)
        .map(str::to_ascii_uppercase)
        .unwrap_or_default();
    let is_virtual = bounded_by == "IFCVIRTUALELEMENT";
    let is_opening = bounded_by == "IFCOPENINGELEMENT";
    let agrees = match physical.as_str() {
        "PHYSICAL" => !is_virtual,
        "VIRTUAL" => is_virtual || is_opening,
        _ => true,
    };
    if !agrees {
        return Err(invalid(
            entity,
            "PhysicalOrVirtualBoundary",
            format!("{physical} does not agree with {bounded_by}"),
        ));
    }

    // A slot the level does not declare cannot be filled: writing it
    // would land past the end of the record.
    if draft.parent.is_some() && level == BoundaryLevel::Base {
        return Err(invalid(
            entity,
            "ParentBoundary",
            "not declared at this level",
        ));
    }
    if draft.corresponding.is_some() && level != BoundaryLevel::Second {
        return Err(invalid(
            entity,
            "CorrespondingBoundary",
            "not declared at this level",
        ));
    }

    let text = |value: Option<&str>| value.map_or(Value::Null, |t| Value::Text(t.into()));
    let reference = |value: Option<EntityId>| value.map_or(Value::Null, Value::Ref);
    Ok(vec![
        ("GlobalId", Value::Text(global_id.into())),
        ("Name", text(draft.name)),
        ("Description", text(draft.description)),
        ("RelatingSpace", Value::Ref(draft.space)),
        ("RelatedBuildingElement", Value::Ref(draft.element)),
        ("ConnectionGeometry", reference(draft.connection_geometry)),
        ("PhysicalOrVirtualBoundary", Value::Enum(physical.into())),
        ("InternalOrExternalBoundary", Value::Enum(internal.into())),
        ("ParentBoundary", reference(draft.parent)),
        ("CorrespondingBoundary", reference(draft.corresponding)),
    ])
}

const CONNECTION_TYPE: &[&str] = &["ATPATH", "ATSTART", "ATEND", "NOTDEFINED"];
const PATH: &str = "IFCRELCONNECTSPATHELEMENTS";

/// Stage an `IfcRelConnectsPathElements`.
///
/// Priorities rank which element wins where two path elements meet.
/// `NormalizedRelatingPriorities` and its related twin bound every
/// entry to 0..=100; an out-of-range entry is a ranking the schema
/// cannot express, so it is refused rather than clamped.
///
/// IFC4 and IFC4X3 only: it writes their layout and leaves
/// `OwnerHistory` `$`, which IFC2X3 requires. In IFC2X3 use
/// [`connect_path_elements_with_owner_history`], which binds the model's
/// declared release.
///
/// # Errors
///
/// Refuses a malformed GlobalId, an element connected to itself, an
/// unknown connection-type token, and a priority outside 0..=100.
pub fn connect_path_elements(
    tx: &mut Transaction,
    global_id: &str,
    relating: EntityId,
    related: EntityId,
    priorities: (&[i64], &[i64]),
    connection_types: (&str, &str),
) -> SpatialAuthoringResult<EntityId> {
    let (relating_token, related_token) =
        check_path(global_id, relating, related, priorities, connection_types)?;
    let (relating_priorities, related_priorities) = priorities;
    let mut attributes = vec![Value::Null; 11];
    attributes[0] = Value::Text(global_id.into());
    attributes[5] = Value::Ref(relating);
    attributes[6] = Value::Ref(related);
    attributes[7] = integers(relating_priorities);
    attributes[8] = integers(related_priorities);
    attributes[9] = Value::Enum(related_token.into());
    attributes[10] = Value::Enum(relating_token.into());
    Ok(tx.create(Entity::new(PATH, attributes)))
}

/// [`connect_path_elements`] in the model's declared release, with a
/// caller-supplied `IfcOwnerHistory`, which IFC2X3 requires.
///
/// # Errors
///
/// Those of [`connect_path_elements`], and the release and owner-history
/// refusals of [`create_space_boundary`] and
/// [`create_space_boundary_with_owner_history`]. Nothing is staged on an
/// error.
#[allow(clippy::too_many_arguments)]
pub fn connect_path_elements_with_owner_history(
    tx: &mut Transaction,
    model: &Model,
    global_id: &str,
    relating: EntityId,
    related: EntityId,
    priorities: (&[i64], &[i64]),
    connection_types: (&str, &str),
    owner_history: EntityId,
) -> SpatialAuthoringResult<EntityId> {
    let (relating_token, related_token) =
        check_path(global_id, relating, related, priorities, connection_types)?;
    let (relating_priorities, related_priorities) = priorities;
    let values = vec![
        ("GlobalId", Value::Text(global_id.into())),
        ("RelatingElement", Value::Ref(relating)),
        ("RelatedElement", Value::Ref(related)),
        ("RelatingPriorities", integers(relating_priorities)),
        ("RelatedPriorities", integers(related_priorities)),
        ("RelatedConnectionType", Value::Enum(related_token.into())),
        ("RelatingConnectionType", Value::Enum(relating_token.into())),
    ];
    stage(tx, model, PATH, values, Some(owner_history))
}

fn integers(values: &[i64]) -> Value {
    Value::List(values.iter().copied().map(Value::Integer).collect())
}

/// The checks of [`connect_path_elements`]; the upper-cased relating and
/// related connection-type tokens.
fn check_path(
    global_id: &str,
    relating: EntityId,
    related: EntityId,
    priorities: (&[i64], &[i64]),
    connection_types: (&str, &str),
) -> SpatialAuthoringResult<(String, String)> {
    if Guid::parse(global_id).is_none() {
        return Err(invalid(PATH, "GlobalId", global_id));
    }
    if relating == related {
        return Err(invalid(PATH, "RelatedElement", "is the relating element"));
    }
    let (relating_priorities, related_priorities) = priorities;
    for (values, attribute) in [
        (relating_priorities, "RelatingPriorities"),
        (related_priorities, "RelatedPriorities"),
    ] {
        if let Some(out) = values.iter().find(|value| !(0..=100).contains(*value)) {
            return Err(invalid(PATH, attribute, out.to_string()));
        }
    }
    let (relating_type, related_type) = connection_types;
    let relating_token = relating_type.to_ascii_uppercase();
    let related_token = related_type.to_ascii_uppercase();
    for (token, attribute) in [
        (&relating_token, "RelatingConnectionType"),
        (&related_token, "RelatedConnectionType"),
    ] {
        if !CONNECTION_TYPE.contains(&token.as_str()) {
            return Err(invalid(PATH, attribute, token.clone()));
        }
    }
    Ok((relating_token, related_token))
}