Skip to main content

ifc_systems/authoring/
mod.rs

1//! Transactional authoring of systems, ports and their connections.
2//!
3//! # Slot layouts come from the readers
4//!
5//! Each relationship here has its own idea of which end is which:
6//! IfcRelAssignsToGroup names members at slot 4 and the group at 6,
7//! IfcRelNests parent at 4 and children at 5, IfcRelConnectsPortToElement
8//! port at 4 and element at 5. The reading side already encodes all of
9//! that; authoring resolves the same constants so one cannot be
10//! corrected without the other.
11//!
12//! # Releases and `OwnerHistory` (#202)
13//!
14//! `IfcRoot.OwnerHistory` is required in IFC2X3 TC1 and `OPTIONAL` from
15//! IFC4 on:
16//!
17//! ```text
18//! IFC2X3_TC1   OwnerHistory : IfcOwnerHistory;
19//! IFC4         OwnerHistory : OPTIONAL IfcOwnerHistory;
20//! IFC4X3_ADD2  OwnerHistory : OPTIONAL IfcOwnerHistory;
21//! ```
22//!
23//! The writers without a model (`create_system`, `connect_ports`, ...)
24//! cannot see the release. They write the IFC4/IFC4X3 layout with
25//! `OwnerHistory` `$`, so their records are IFC4/IFC4X3 only. Each has a
26//! `*_with_owner_history` variant that takes the model, binds its declared
27//! release (`release.rs`), lays the record out by attribute name from that
28//! release's table, and takes a caller-supplied `IfcOwnerHistory`, which
29//! must exist (in the model or staged on the transaction) and be an
30//! `IfcOwnerHistory`; one is never invented here. This follows
31//! `ifc-material` (#77), `ifc-properties` (#191) and `ifc-classification`
32//! (#194). In IFC4 and IFC4X3 a variant writes the plain writer's record
33//! with the reference in the optional slot.
34
35use ifc_model::guid::Guid;
36use ifc_model::{Entity, EntityId, Transaction, Value};
37
38use crate::connectivity::relation::slot as connects_slot;
39use crate::port::definition::slot as port_slot;
40use crate::system::group::slot as group_slot;
41use crate::zone::spatial_group::slot as placement_slot;
42
43mod distribution;
44mod error;
45mod owned;
46mod release;
47mod services;
48mod system_kind;
49
50pub use distribution::{
51    create_distribution_element, create_distribution_element_with_owner_history,
52    create_spatial_zone, create_spatial_zone_with_owner_history, create_zone,
53    create_zone_with_owner_history, DistributionElementKind, ElementAttributes,
54};
55pub use error::{SystemAuthoringError, SystemAuthoringResult};
56pub use owned::{
57    assign_to_group_with_owner_history, connect_port_to_element_with_owner_history,
58    connect_ports_with_owner_history, create_group_with_owner_history,
59    create_port_with_owner_history, create_system_with_owner_history,
60    nest_ports_with_owner_history, reference_in_spatial_structure_with_owner_history,
61};
62// Deprecated duplicates of ifc-spatial's writers (#492), still exported.
63#[allow(deprecated)]
64pub use owned::contain_in_spatial_structure_with_owner_history;
65#[allow(deprecated)]
66pub use services::{serve_buildings, serve_buildings_with_owner_history};
67pub use system_kind::{
68    create_classified_system, create_classified_system_with_owner_history, ClassifiedSystemDraft,
69    SystemKind,
70};
71
72use error::invalid;
73
74fn guid(entity: &'static str, global_id: &str) -> SystemAuthoringResult<()> {
75    if Guid::parse(global_id).is_none() {
76        return Err(invalid(entity, "GlobalId", global_id));
77    }
78    Ok(())
79}
80
81/// Refuse an empty related set, and the relating end listed in it.
82fn check_related(
83    entity: &'static str,
84    attribute: &'static str,
85    global_id: &str,
86    relating: EntityId,
87    related: &[EntityId],
88    relating_word: &str,
89) -> SystemAuthoringResult<()> {
90    guid(entity, global_id)?;
91    if related.is_empty() {
92        return Err(invalid(entity, attribute, "empty"));
93    }
94    if related.contains(&relating) {
95        return Err(invalid(
96            entity,
97            attribute,
98            format!("contains the {relating_word}"),
99        ));
100    }
101    Ok(())
102}
103
104/// Refuse a port connected to itself.
105fn check_ports(
106    global_id: &str,
107    relating: EntityId,
108    related: EntityId,
109) -> SystemAuthoringResult<()> {
110    guid("IFCRELCONNECTSPORTS", global_id)?;
111    if relating == related {
112        return Err(invalid(
113            "IFCRELCONNECTSPORTS",
114            "RelatedPort",
115            "same as RelatingPort",
116        ));
117    }
118    Ok(())
119}
120
121fn refs(ids: &[EntityId]) -> Value {
122    Value::List(ids.iter().copied().map(Value::Ref).collect())
123}
124
125/// Stage an `IfcSystem`.
126///
127/// Writes the IFC4/IFC4X3 layout with `OwnerHistory` `$`, so the record
128/// is IFC4/IFC4X3 only; use [`create_system_with_owner_history`] for a
129/// release-bound record, which IFC2X3 needs.
130///
131/// # Errors
132///
133/// Refuses a malformed GlobalId.
134pub fn create_system(
135    tx: &mut Transaction,
136    global_id: &str,
137    name: Option<&str>,
138) -> SystemAuthoringResult<EntityId> {
139    guid("IFCSYSTEM", global_id)?;
140    let mut attributes = vec![Value::Null; 5];
141    attributes[0] = Value::Text(global_id.into());
142    attributes[2] = name.map_or(Value::Null, |t| Value::Text(t.into()));
143    Ok(tx.create(Entity::new("IFCSYSTEM", attributes)))
144}
145
146/// Stage an `IfcDistributionPort`.
147///
148/// `flow_direction` is an `IfcFlowDirectionEnum` token: SOURCE, SINK
149/// or SOURCEANDSINK. It is what the flow reader follows, so a port
150/// without one is invisible to downstream/upstream queries.
151///
152/// Writes the IFC4/IFC4X3 ten-attribute layout with `OwnerHistory` `$`,
153/// so the record is IFC4/IFC4X3 only; use
154/// [`create_port_with_owner_history`] for IFC2X3, which declares eight.
155///
156/// # Errors
157///
158/// Refuses a malformed GlobalId.
159pub fn create_port(
160    tx: &mut Transaction,
161    global_id: &str,
162    name: Option<&str>,
163    flow_direction: Option<&str>,
164) -> SystemAuthoringResult<EntityId> {
165    guid("IFCDISTRIBUTIONPORT", global_id)?;
166    let mut attributes = vec![Value::Null; 10];
167    attributes[0] = Value::Text(global_id.into());
168    attributes[2] = name.map_or(Value::Null, |t| Value::Text(t.into()));
169    attributes[7] = flow_direction.map_or(Value::Null, |t| Value::Enum(t.into()));
170    Ok(tx.create(Entity::new("IFCDISTRIBUTIONPORT", attributes)))
171}
172
173/// Stage an `IfcRelAssignsToGroup`: elements joined into a system.
174///
175/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
176/// [`assign_to_group_with_owner_history`] for IFC2X3.
177///
178/// # Errors
179///
180/// Refuses a malformed GlobalId, an empty member list, and the group
181/// listed among its own members.
182pub fn assign_to_group(
183    tx: &mut Transaction,
184    global_id: &str,
185    group: EntityId,
186    members: &[EntityId],
187) -> SystemAuthoringResult<EntityId> {
188    check_related(
189        "IFCRELASSIGNSTOGROUP",
190        "RelatedObjects",
191        global_id,
192        group,
193        members,
194        "group",
195    )?;
196    let width = group_slot::ASSIGNS_GROUP.max(group_slot::ASSIGNS_RELATED) + 1;
197    let mut attributes = vec![Value::Null; width];
198    attributes[0] = Value::Text(global_id.into());
199    attributes[group_slot::ASSIGNS_RELATED] = refs(members);
200    attributes[group_slot::ASSIGNS_GROUP] = Value::Ref(group);
201    Ok(tx.create(Entity::new("IFCRELASSIGNSTOGROUP", attributes)))
202}
203
204/// Stage an `IfcRelNests`: ports nested under the element owning them.
205///
206/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
207/// [`nest_ports_with_owner_history`] for IFC2X3.
208///
209/// # Errors
210///
211/// Refuses a malformed GlobalId, an empty child list, and a parent
212/// nested under itself.
213pub fn nest_ports(
214    tx: &mut Transaction,
215    global_id: &str,
216    parent: EntityId,
217    children: &[EntityId],
218) -> SystemAuthoringResult<EntityId> {
219    check_related(
220        "IFCRELNESTS",
221        "RelatedObjects",
222        global_id,
223        parent,
224        children,
225        "parent",
226    )?;
227    let width = port_slot::NESTS_PARENT.max(port_slot::NESTS_CHILDREN) + 1;
228    let mut attributes = vec![Value::Null; width];
229    attributes[0] = Value::Text(global_id.into());
230    attributes[port_slot::NESTS_PARENT] = Value::Ref(parent);
231    attributes[port_slot::NESTS_CHILDREN] = refs(children);
232    Ok(tx.create(Entity::new("IFCRELNESTS", attributes)))
233}
234
235/// Stage an `IfcRelConnectsPortToElement`.
236///
237/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
238/// [`connect_port_to_element_with_owner_history`] for IFC2X3.
239///
240/// # Errors
241///
242/// Refuses a malformed GlobalId.
243pub fn connect_port_to_element(
244    tx: &mut Transaction,
245    global_id: &str,
246    port: EntityId,
247    element: EntityId,
248) -> SystemAuthoringResult<EntityId> {
249    guid("IFCRELCONNECTSPORTTOELEMENT", global_id)?;
250    let width = port_slot::PORT_TO_ELEMENT_PORT.max(port_slot::PORT_TO_ELEMENT_ELEMENT) + 1;
251    let mut attributes = vec![Value::Null; width];
252    attributes[0] = Value::Text(global_id.into());
253    attributes[port_slot::PORT_TO_ELEMENT_PORT] = Value::Ref(port);
254    attributes[port_slot::PORT_TO_ELEMENT_ELEMENT] = Value::Ref(element);
255    Ok(tx.create(Entity::new("IFCRELCONNECTSPORTTOELEMENT", attributes)))
256}
257
258/// Stage an `IfcRelConnectsPorts`: the link the flow graph walks.
259///
260/// `realizing` names the element that physically realises the
261/// connection, such as the fitting between two segments.
262///
263/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
264/// [`connect_ports_with_owner_history`] for IFC2X3.
265///
266/// # Errors
267///
268/// Refuses a malformed GlobalId and a port connected to itself, which
269/// is a self-loop the reachability walk would report as a component.
270pub fn connect_ports(
271    tx: &mut Transaction,
272    global_id: &str,
273    relating: EntityId,
274    related: EntityId,
275    realizing: Option<EntityId>,
276) -> SystemAuthoringResult<EntityId> {
277    check_ports(global_id, relating, related)?;
278    let width = connects_slot::REALIZING + 1;
279    let mut attributes = vec![Value::Null; width];
280    attributes[0] = Value::Text(global_id.into());
281    attributes[connects_slot::RELATING] = Value::Ref(relating);
282    attributes[connects_slot::RELATED] = Value::Ref(related);
283    attributes[connects_slot::REALIZING] = realizing.map_or(Value::Null, Value::Ref);
284    Ok(tx.create(Entity::new("IFCRELCONNECTSPORTS", attributes)))
285}
286
287/// Stage an `IfcRelContainedInSpatialStructure`.
288///
289/// Deprecated (#492): `ifc_spatial::contain` is the canonical writer of
290/// this relationship, with the same rules and layout. This one stays, with
291/// its own error type, for compatibility.
292///
293/// Containment is exclusive: an element belongs to exactly one
294/// structure. Use [`reference_in_spatial_structure`] for the
295/// non-exclusive case, such as a duct crossing several storeys.
296///
297/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
298/// [`contain_in_spatial_structure_with_owner_history`] for IFC2X3.
299///
300/// # Errors
301///
302/// Refuses a malformed GlobalId, an empty element list, and the
303/// structure listed among its own contents.
304#[deprecated(
305    since = "0.5.0",
306    note = "use ifc_spatial::contain, the canonical IfcRelContainedInSpatialStructure writer (#492)"
307)]
308pub fn contain_in_spatial_structure(
309    tx: &mut Transaction,
310    global_id: &str,
311    structure: EntityId,
312    elements: &[EntityId],
313) -> SystemAuthoringResult<EntityId> {
314    place(
315        tx,
316        "IFCRELCONTAINEDINSPATIALSTRUCTURE",
317        global_id,
318        structure,
319        elements,
320    )
321}
322
323/// Stage an `IfcRelReferencedInSpatialStructure`.
324///
325/// The non-exclusive counterpart of containment.
326///
327/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
328/// [`reference_in_spatial_structure_with_owner_history`] for IFC2X3.
329///
330/// # Errors
331///
332/// Refuses a malformed GlobalId, an empty element list, and the
333/// structure listed among its own references.
334pub fn reference_in_spatial_structure(
335    tx: &mut Transaction,
336    global_id: &str,
337    structure: EntityId,
338    elements: &[EntityId],
339) -> SystemAuthoringResult<EntityId> {
340    place(
341        tx,
342        "IFCRELREFERENCEDINSPATIALSTRUCTURE",
343        global_id,
344        structure,
345        elements,
346    )
347}
348
349/// Both placement relationships share a layout: elements at 4,
350/// structure at 5 -- the inverse of IfcRelAggregates.
351fn place(
352    tx: &mut Transaction,
353    entity: &'static str,
354    global_id: &str,
355    structure: EntityId,
356    elements: &[EntityId],
357) -> SystemAuthoringResult<EntityId> {
358    check_related(
359        entity,
360        "RelatedElements",
361        global_id,
362        structure,
363        elements,
364        "structure",
365    )?;
366    let width = placement_slot::RELATING_STRUCTURE.max(placement_slot::RELATED_ELEMENTS) + 1;
367    let mut attributes = vec![Value::Null; width];
368    attributes[0] = Value::Text(global_id.into());
369    attributes[placement_slot::RELATED_ELEMENTS] = refs(elements);
370    attributes[placement_slot::RELATING_STRUCTURE] = Value::Ref(structure);
371    Ok(tx.create(Entity::new(entity, attributes)))
372}
373
374/// Stage an `IfcGroup`: an arbitrary named collection.
375///
376/// A group is the supertype a system specialises. Where an
377/// `IfcSystem` claims its members function together, a plain group
378/// claims only that someone gathered them, so this writer is what to
379/// reach for when no stronger statement is true.
380///
381/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
382/// [`create_group_with_owner_history`] for IFC2X3.
383///
384/// # Errors
385///
386/// Refuses a malformed GlobalId.
387pub fn create_group(
388    tx: &mut Transaction,
389    global_id: &str,
390    name: Option<&str>,
391    description: Option<&str>,
392) -> SystemAuthoringResult<EntityId> {
393    guid("IFCGROUP", global_id)?;
394    let mut attributes = vec![Value::Null; 5];
395    attributes[0] = Value::Text(global_id.into());
396    attributes[2] = name.map_or(Value::Null, |t| Value::Text(t.into()));
397    attributes[3] = description.map_or(Value::Null, |t| Value::Text(t.into()));
398    Ok(tx.create(Entity::new("IFCGROUP", attributes)))
399}