Skip to main content

ifc_systems/authoring/
owned.rs

1//! Release-bound variants of the systems writers, with a caller-supplied
2//! `IfcOwnerHistory` (#202).
3//!
4//! Each binds the model's declared release, runs the plain writer's draft
5//! checks, lays the record out by attribute name from the release's table
6//! and sets `OwnerHistory`, which IFC2X3 requires. The attribute names are
7//! the ones the readers' slot constants stand for; the unit test below pins
8//! each name to its constant in all three bundled releases.
9
10use ifc_model::{EntityId, Model, Transaction, Value};
11
12use super::release::bind;
13use super::{check_ports, check_related, guid, refs, SystemAuthoringResult};
14
15fn text(value: Option<&str>) -> Value {
16    value.map_or(Value::Null, |t| Value::Text(t.into()))
17}
18
19/// [`create_system`](super::create_system) in `model`'s declared release,
20/// with a caller-supplied `IfcOwnerHistory`, which IFC2X3 requires.
21///
22/// The release is bound from `FILE_SCHEMA` (none binds IFC4). The owner
23/// history is never invented: build it with `ifc-author`.
24///
25/// # Errors
26///
27/// Those of [`create_system`](super::create_system), and:
28/// [`MultipleSchemas`](super::SystemAuthoringError::MultipleSchemas) or
29/// [`UnsupportedSchema`](super::SystemAuthoringError::UnsupportedSchema) if
30/// the model binds no single known release;
31/// [`MissingReference`](super::SystemAuthoringError::MissingReference) if
32/// `owner_history` is neither in the model nor staged;
33/// [`WrongReferenceType`](super::SystemAuthoringError::WrongReferenceType)
34/// if it is not an `IfcOwnerHistory`. Nothing is staged on an error.
35pub fn create_system_with_owner_history(
36    tx: &mut Transaction,
37    model: &Model,
38    global_id: &str,
39    name: Option<&str>,
40    owner_history: EntityId,
41) -> SystemAuthoringResult<EntityId> {
42    const ENTITY: &str = "IFCSYSTEM";
43    let release = bind(model)?;
44    guid(ENTITY, global_id)?;
45    let values = vec![
46        ("GlobalId", Value::Text(global_id.into())),
47        ("Name", text(name)),
48    ];
49    release.stage(tx, model, ENTITY, values, owner_history)
50}
51
52/// [`create_port`](super::create_port) in `model`'s declared release, with
53/// a caller-supplied `IfcOwnerHistory`.
54///
55/// IFC2X3 declares eight attributes for `IfcDistributionPort`, IFC4 and
56/// IFC4X3 ten; `FlowDirection` is the eighth in all three.
57///
58/// # Errors
59///
60/// Those of [`create_port`](super::create_port), the release and
61/// owner-history refusals of [`create_system_with_owner_history`], and
62/// [`AuthoringValueType`](super::SystemAuthoringError::AuthoringValueType)
63/// for a token the release's `IfcFlowDirectionEnum` does not declare.
64pub fn create_port_with_owner_history(
65    tx: &mut Transaction,
66    model: &Model,
67    global_id: &str,
68    name: Option<&str>,
69    flow_direction: Option<&str>,
70    owner_history: EntityId,
71) -> SystemAuthoringResult<EntityId> {
72    const ENTITY: &str = "IFCDISTRIBUTIONPORT";
73    let release = bind(model)?;
74    guid(ENTITY, global_id)?;
75    let values = vec![
76        ("GlobalId", Value::Text(global_id.into())),
77        ("Name", text(name)),
78        (
79            "FlowDirection",
80            flow_direction.map_or(Value::Null, |t| Value::Enum(t.into())),
81        ),
82    ];
83    release.stage(tx, model, ENTITY, values, owner_history)
84}
85
86/// [`assign_to_group`](super::assign_to_group) in `model`'s declared
87/// release, with a caller-supplied `IfcOwnerHistory`.
88///
89/// # Errors
90///
91/// Those of [`assign_to_group`](super::assign_to_group), and the release
92/// and owner-history refusals of [`create_system_with_owner_history`].
93pub fn assign_to_group_with_owner_history(
94    tx: &mut Transaction,
95    model: &Model,
96    global_id: &str,
97    group: EntityId,
98    members: &[EntityId],
99    owner_history: EntityId,
100) -> SystemAuthoringResult<EntityId> {
101    const ENTITY: &str = "IFCRELASSIGNSTOGROUP";
102    let release = bind(model)?;
103    check_related(ENTITY, "RelatedObjects", global_id, group, members, "group")?;
104    let values = vec![
105        ("GlobalId", Value::Text(global_id.into())),
106        ("RelatedObjects", refs(members)),
107        ("RelatingGroup", Value::Ref(group)),
108    ];
109    release.stage(tx, model, ENTITY, values, owner_history)
110}
111
112/// [`nest_ports`](super::nest_ports) in `model`'s declared release, with a
113/// caller-supplied `IfcOwnerHistory`.
114///
115/// # Errors
116///
117/// Those of [`nest_ports`](super::nest_ports), and the release and
118/// owner-history refusals of [`create_system_with_owner_history`].
119pub fn nest_ports_with_owner_history(
120    tx: &mut Transaction,
121    model: &Model,
122    global_id: &str,
123    parent: EntityId,
124    children: &[EntityId],
125    owner_history: EntityId,
126) -> SystemAuthoringResult<EntityId> {
127    const ENTITY: &str = "IFCRELNESTS";
128    let release = bind(model)?;
129    check_related(
130        ENTITY,
131        "RelatedObjects",
132        global_id,
133        parent,
134        children,
135        "parent",
136    )?;
137    let values = vec![
138        ("GlobalId", Value::Text(global_id.into())),
139        ("RelatingObject", Value::Ref(parent)),
140        ("RelatedObjects", refs(children)),
141    ];
142    release.stage(tx, model, ENTITY, values, owner_history)
143}
144
145/// [`connect_port_to_element`](super::connect_port_to_element) in
146/// `model`'s declared release, with a caller-supplied `IfcOwnerHistory`.
147///
148/// # Errors
149///
150/// Those of [`connect_port_to_element`](super::connect_port_to_element),
151/// and the release and owner-history refusals of
152/// [`create_system_with_owner_history`].
153pub fn connect_port_to_element_with_owner_history(
154    tx: &mut Transaction,
155    model: &Model,
156    global_id: &str,
157    port: EntityId,
158    element: EntityId,
159    owner_history: EntityId,
160) -> SystemAuthoringResult<EntityId> {
161    const ENTITY: &str = "IFCRELCONNECTSPORTTOELEMENT";
162    let release = bind(model)?;
163    guid(ENTITY, global_id)?;
164    let values = vec![
165        ("GlobalId", Value::Text(global_id.into())),
166        ("RelatingPort", Value::Ref(port)),
167        ("RelatedElement", Value::Ref(element)),
168    ];
169    release.stage(tx, model, ENTITY, values, owner_history)
170}
171
172/// [`connect_ports`](super::connect_ports) in `model`'s declared release,
173/// with a caller-supplied `IfcOwnerHistory`.
174///
175/// # Errors
176///
177/// Those of [`connect_ports`](super::connect_ports), and the release and
178/// owner-history refusals of [`create_system_with_owner_history`].
179pub fn connect_ports_with_owner_history(
180    tx: &mut Transaction,
181    model: &Model,
182    global_id: &str,
183    relating: EntityId,
184    related: EntityId,
185    realizing: Option<EntityId>,
186    owner_history: EntityId,
187) -> SystemAuthoringResult<EntityId> {
188    const ENTITY: &str = "IFCRELCONNECTSPORTS";
189    let release = bind(model)?;
190    check_ports(global_id, relating, related)?;
191    let values = vec![
192        ("GlobalId", Value::Text(global_id.into())),
193        ("RelatingPort", Value::Ref(relating)),
194        ("RelatedPort", Value::Ref(related)),
195        (
196            "RealizingElement",
197            realizing.map_or(Value::Null, Value::Ref),
198        ),
199    ];
200    release.stage(tx, model, ENTITY, values, owner_history)
201}
202
203/// [`contain_in_spatial_structure`](super::contain_in_spatial_structure) in
204/// `model`'s declared release, with a caller-supplied `IfcOwnerHistory`.
205///
206/// Deprecated (#492): `ifc_spatial::contain_with_owner_history` is the
207/// canonical writer.
208///
209/// # Errors
210///
211/// Those of
212/// [`contain_in_spatial_structure`](super::contain_in_spatial_structure),
213/// and the release and owner-history refusals of
214/// [`create_system_with_owner_history`].
215#[deprecated(
216    since = "0.5.0",
217    note = "use ifc_spatial::contain_with_owner_history, the canonical IfcRelContainedInSpatialStructure writer (#492)"
218)]
219pub fn contain_in_spatial_structure_with_owner_history(
220    tx: &mut Transaction,
221    model: &Model,
222    global_id: &str,
223    structure: EntityId,
224    elements: &[EntityId],
225    owner_history: EntityId,
226) -> SystemAuthoringResult<EntityId> {
227    place(
228        tx,
229        model,
230        "IFCRELCONTAINEDINSPATIALSTRUCTURE",
231        global_id,
232        structure,
233        elements,
234        owner_history,
235    )
236}
237
238/// [`reference_in_spatial_structure`](super::reference_in_spatial_structure)
239/// in `model`'s declared release, with a caller-supplied `IfcOwnerHistory`.
240///
241/// # Errors
242///
243/// Those of
244/// [`reference_in_spatial_structure`](super::reference_in_spatial_structure),
245/// and the release and owner-history refusals of
246/// [`create_system_with_owner_history`].
247pub fn reference_in_spatial_structure_with_owner_history(
248    tx: &mut Transaction,
249    model: &Model,
250    global_id: &str,
251    structure: EntityId,
252    elements: &[EntityId],
253    owner_history: EntityId,
254) -> SystemAuthoringResult<EntityId> {
255    place(
256        tx,
257        model,
258        "IFCRELREFERENCEDINSPATIALSTRUCTURE",
259        global_id,
260        structure,
261        elements,
262        owner_history,
263    )
264}
265
266fn place(
267    tx: &mut Transaction,
268    model: &Model,
269    entity: &'static str,
270    global_id: &str,
271    structure: EntityId,
272    elements: &[EntityId],
273    owner_history: EntityId,
274) -> SystemAuthoringResult<EntityId> {
275    let release = bind(model)?;
276    check_related(
277        entity,
278        "RelatedElements",
279        global_id,
280        structure,
281        elements,
282        "structure",
283    )?;
284    let values = vec![
285        ("GlobalId", Value::Text(global_id.into())),
286        ("RelatedElements", refs(elements)),
287        ("RelatingStructure", Value::Ref(structure)),
288    ];
289    release.stage(tx, model, entity, values, owner_history)
290}
291
292/// [`create_group`](super::create_group) in `model`'s declared release,
293/// with a caller-supplied `IfcOwnerHistory`.
294///
295/// # Errors
296///
297/// Those of [`create_group`](super::create_group), and the release and
298/// owner-history refusals of [`create_system_with_owner_history`].
299pub fn create_group_with_owner_history(
300    tx: &mut Transaction,
301    model: &Model,
302    global_id: &str,
303    name: Option<&str>,
304    description: Option<&str>,
305    owner_history: EntityId,
306) -> SystemAuthoringResult<EntityId> {
307    const ENTITY: &str = "IFCGROUP";
308    let release = bind(model)?;
309    guid(ENTITY, global_id)?;
310    let values = vec![
311        ("GlobalId", Value::Text(global_id.into())),
312        ("Name", text(name)),
313        ("Description", text(description)),
314    ];
315    release.stage(tx, model, ENTITY, values, owner_history)
316}
317
318#[cfg(test)]
319mod tests {
320    use ifc_schema::{for_version, SchemaVersion};
321
322    use crate::authoring::distribution::{distribution_slot, spatial_zone_slot, zone_slot};
323    use crate::connectivity::relation::slot as connects_slot;
324    use crate::port::definition::slot as port_slot;
325    use crate::system::group::slot as group_slot;
326    use crate::system::services::slot as services_slot;
327    use crate::zone::spatial_group::slot as placement_slot;
328
329    /// Every attribute name the variants write is the one the reader's (and
330    /// the plain writer's) slot constant stands for, in all three releases
331    /// that declare the entity.
332    #[test]
333    fn names_agree_with_the_slot_constants() {
334        let pinned: &[(&str, &str, usize)] = &[
335            (
336                "IFCRELASSIGNSTOGROUP",
337                "RelatedObjects",
338                group_slot::ASSIGNS_RELATED,
339            ),
340            (
341                "IFCRELASSIGNSTOGROUP",
342                "RelatingGroup",
343                group_slot::ASSIGNS_GROUP,
344            ),
345            ("IFCRELNESTS", "RelatingObject", port_slot::NESTS_PARENT),
346            ("IFCRELNESTS", "RelatedObjects", port_slot::NESTS_CHILDREN),
347            (
348                "IFCRELCONNECTSPORTTOELEMENT",
349                "RelatingPort",
350                port_slot::PORT_TO_ELEMENT_PORT,
351            ),
352            (
353                "IFCRELCONNECTSPORTTOELEMENT",
354                "RelatedElement",
355                port_slot::PORT_TO_ELEMENT_ELEMENT,
356            ),
357            (
358                "IFCDISTRIBUTIONPORT",
359                "FlowDirection",
360                port_slot::FLOW_DIRECTION,
361            ),
362            (
363                "IFCRELCONNECTSPORTS",
364                "RelatingPort",
365                connects_slot::RELATING,
366            ),
367            ("IFCRELCONNECTSPORTS", "RelatedPort", connects_slot::RELATED),
368            (
369                "IFCRELCONNECTSPORTS",
370                "RealizingElement",
371                connects_slot::REALIZING,
372            ),
373            (
374                "IFCRELCONTAINEDINSPATIALSTRUCTURE",
375                "RelatedElements",
376                placement_slot::RELATED_ELEMENTS,
377            ),
378            (
379                "IFCRELCONTAINEDINSPATIALSTRUCTURE",
380                "RelatingStructure",
381                placement_slot::RELATING_STRUCTURE,
382            ),
383            (
384                "IFCRELREFERENCEDINSPATIALSTRUCTURE",
385                "RelatedElements",
386                placement_slot::RELATED_ELEMENTS,
387            ),
388            (
389                "IFCRELREFERENCEDINSPATIALSTRUCTURE",
390                "RelatingStructure",
391                placement_slot::RELATING_STRUCTURE,
392            ),
393            (
394                "IFCRELSERVICESBUILDINGS",
395                "RelatingSystem",
396                services_slot::RELATING_SYSTEM,
397            ),
398            (
399                "IFCRELSERVICESBUILDINGS",
400                "RelatedBuildings",
401                services_slot::RELATED_BUILDINGS,
402            ),
403            ("IFCFLOWSEGMENT", "Name", distribution_slot::NAME),
404            (
405                "IFCFLOWSEGMENT",
406                "Description",
407                distribution_slot::DESCRIPTION,
408            ),
409            (
410                "IFCFLOWSEGMENT",
411                "ObjectPlacement",
412                distribution_slot::OBJECT_PLACEMENT,
413            ),
414            (
415                "IFCFLOWSEGMENT",
416                "Representation",
417                distribution_slot::REPRESENTATION,
418            ),
419            ("IFCFLOWSEGMENT", "Tag", distribution_slot::TAG),
420            ("IFCZONE", "Name", zone_slot::NAME),
421            ("IFCZONE", "LongName", zone_slot::LONG_NAME),
422            ("IFCSPATIALZONE", "LongName", spatial_zone_slot::LONG_NAME),
423            (
424                "IFCSPATIALZONE",
425                "PredefinedType",
426                spatial_zone_slot::PREDEFINED_TYPE,
427            ),
428        ];
429        let mut checked = 0;
430        for version in [
431            SchemaVersion::Ifc2x3,
432            SchemaVersion::Ifc4,
433            SchemaVersion::Ifc4x3,
434        ] {
435            let schema = for_version(version).unwrap();
436            for (entity, name, slot) in pinned {
437                let names = schema.attribute_names(entity);
438                if schema.entity(entity).is_none() {
439                    continue;
440                }
441                if let Some(found) = names.iter().position(|n| n == name) {
442                    assert_eq!(found, *slot, "{version:?} {entity}.{name}");
443                    checked += 1;
444                } else {
445                    // Only IFC2X3 may lack one: IfcZone.LongName.
446                    assert_eq!(
447                        (version, *entity, *name),
448                        (SchemaVersion::Ifc2x3, "IFCZONE", "LongName")
449                    );
450                }
451            }
452        }
453        assert!(checked >= 60, "the pin table matched {checked} names");
454    }
455}