ifc_systems/authoring/distribution.rs
1//! Distribution element occurrences and the two grouping forms.
2//!
3//! # Why one writer per class and not one taking a type name
4//!
5//! `IfcFlowSegment`, `IfcFlowFitting` and their siblings share an
6//! identical eight-slot layout inherited from `IfcDistributionElement`.
7//! A single `create_distribution_element(type_name, ..)` would be less
8//! code, but it would also accept `"IFCWALL"` or a typo, and the caller
9//! would learn about it from a validator rather than the compiler. The
10//! enum below keeps the set closed: every variant is a class the flow
11//! reader in this crate already understands.
12//!
13//! # `IfcZone` and `IfcSpatialZone` are not the same thing
14//!
15//! Both group spaces, but `IfcZone` is an `IfcGroup` -- membership is
16//! an objectified relationship, and it carries no placement. An
17//! `IfcSpatialZone` is an `IfcSpatialElement`: it has its own
18//! placement, representation and a `PredefinedType`, so it can occupy
19//! geometry a zone cannot. Authoring the wrong one produces a file that
20//! parses and then answers spatial queries incorrectly, which is why
21//! they get separate constructors rather than a flag.
22
23use ifc_model::{Entity, EntityId, Model, Transaction, Value};
24
25use super::release::bind;
26use crate::authoring::{invalid, SystemAuthoringResult};
27
28/// `IfcDistributionElement` slots, from IFC4X3 ADD2.
29///
30/// All eight are inherited: `IfcRoot` contributes 0-3, `IfcObject`
31/// contributes `ObjectType` at 4, `IfcProduct` contributes placement
32/// and representation at 5-6, and `IfcElement` contributes `Tag` at 7.
33/// None of the concrete subtypes in [`DistributionElementKind`] add an
34/// attribute of their own, so the width is the same for every one.
35pub(crate) mod distribution_slot {
36 /// `GlobalId`.
37 pub const GLOBAL_ID: usize = 0;
38 /// `Name`.
39 pub const NAME: usize = 2;
40 /// `Description`.
41 pub const DESCRIPTION: usize = 3;
42 /// `ObjectPlacement`.
43 pub const OBJECT_PLACEMENT: usize = 5;
44 /// `Representation`.
45 pub const REPRESENTATION: usize = 6;
46 /// `Tag`.
47 pub const TAG: usize = 7;
48 /// Total attribute count.
49 pub const WIDTH: usize = 8;
50}
51
52/// `IfcZone` slots. `IfcGroup` has no placement, so the list is short.
53pub(crate) mod zone_slot {
54 /// `GlobalId`.
55 pub const GLOBAL_ID: usize = 0;
56 /// `Name`.
57 pub const NAME: usize = 2;
58 /// `Description`.
59 pub const DESCRIPTION: usize = 3;
60 /// `LongName`, declared by `IfcZone` itself.
61 pub const LONG_NAME: usize = 5;
62 /// Total attribute count.
63 pub const WIDTH: usize = 6;
64}
65
66/// `IfcSpatialZone` slots.
67pub(crate) mod spatial_zone_slot {
68 /// `GlobalId`.
69 pub const GLOBAL_ID: usize = 0;
70 /// `Name`.
71 pub const NAME: usize = 2;
72 /// `Description`.
73 pub const DESCRIPTION: usize = 3;
74 /// `ObjectPlacement`.
75 pub const OBJECT_PLACEMENT: usize = 5;
76 /// `Representation`.
77 pub const REPRESENTATION: usize = 6;
78 /// `LongName`, from `IfcSpatialElement`.
79 pub const LONG_NAME: usize = 7;
80 /// `PredefinedType`, declared by `IfcSpatialZone`.
81 pub const PREDEFINED_TYPE: usize = 8;
82 /// Total attribute count.
83 pub const WIDTH: usize = 9;
84}
85
86/// A concrete distribution element class.
87///
88/// The variants are exactly the classes this crate's flow reader
89/// traverses. Holding them in a closed enum means a caller cannot
90/// stage a class the reader will later fail to recognise.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum DistributionElementKind {
93 /// `IfcDistributionElement`: the general form.
94 DistributionElement,
95 /// `IfcEnergyConversionDevice`: boilers, chillers, coils.
96 EnergyConversionDevice,
97 /// `IfcFlowController`: valves, dampers, switches.
98 FlowController,
99 /// `IfcFlowFitting`: junctions, bends, transitions.
100 FlowFitting,
101 /// `IfcFlowMovingDevice`: pumps, fans, compressors.
102 FlowMovingDevice,
103 /// `IfcFlowSegment`: a run of duct, pipe or cable.
104 FlowSegment,
105 /// `IfcFlowStorageDevice`: tanks and batteries.
106 FlowStorageDevice,
107 /// `IfcFlowTerminal`: the point where flow leaves the system.
108 FlowTerminal,
109 /// `IfcFlowTreatmentDevice`: filters, interceptors.
110 FlowTreatmentDevice,
111}
112
113impl DistributionElementKind {
114 /// The IFC entity name this kind stages.
115 pub fn type_name(self) -> &'static str {
116 match self {
117 Self::DistributionElement => "IFCDISTRIBUTIONELEMENT",
118 Self::EnergyConversionDevice => "IFCENERGYCONVERSIONDEVICE",
119 Self::FlowController => "IFCFLOWCONTROLLER",
120 Self::FlowFitting => "IFCFLOWFITTING",
121 Self::FlowMovingDevice => "IFCFLOWMOVINGDEVICE",
122 Self::FlowSegment => "IFCFLOWSEGMENT",
123 Self::FlowStorageDevice => "IFCFLOWSTORAGEDEVICE",
124 Self::FlowTerminal => "IFCFLOWTERMINAL",
125 Self::FlowTreatmentDevice => "IFCFLOWTREATMENTDEVICE",
126 }
127 }
128}
129
130/// Optional descriptive attributes shared by every distribution element.
131///
132/// Grouped into a struct because all six are optional and positional
133/// arguments at that count invite silent transposition -- `name` and
134/// `description` are both `Option<&str>` and swapping them compiles.
135#[derive(Debug, Clone, Copy, Default)]
136pub struct ElementAttributes<'a> {
137 /// `Name`.
138 pub name: Option<&'a str>,
139 /// `Description`.
140 pub description: Option<&'a str>,
141 /// `ObjectPlacement`, usually an `IfcLocalPlacement`.
142 pub placement: Option<EntityId>,
143 /// `Representation`, an `IfcProductDefinitionShape`.
144 pub representation: Option<EntityId>,
145 /// `Tag`, the authoring tool's own identifier.
146 pub tag: Option<&'a str>,
147}
148
149fn text(value: Option<&str>) -> Value {
150 value.map_or(Value::Null, |v| Value::Text(v.into()))
151}
152
153fn reference(value: Option<EntityId>) -> Value {
154 value.map_or(Value::Null, Value::Ref)
155}
156
157/// Stage a distribution element occurrence.
158///
159/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
160/// [`create_distribution_element_with_owner_history`] for IFC2X3.
161///
162/// # Errors
163///
164/// Refuses a malformed GlobalId.
165pub fn create_distribution_element(
166 tx: &mut Transaction,
167 kind: DistributionElementKind,
168 global_id: &str,
169 attributes: ElementAttributes<'_>,
170) -> SystemAuthoringResult<EntityId> {
171 let type_name = kind.type_name();
172 super::guid(type_name, global_id)?;
173
174 let mut attrs = vec![Value::Null; distribution_slot::WIDTH];
175 attrs[distribution_slot::GLOBAL_ID] = Value::Text(global_id.into());
176 attrs[distribution_slot::NAME] = text(attributes.name);
177 attrs[distribution_slot::DESCRIPTION] = text(attributes.description);
178 attrs[distribution_slot::OBJECT_PLACEMENT] = reference(attributes.placement);
179 attrs[distribution_slot::REPRESENTATION] = reference(attributes.representation);
180 attrs[distribution_slot::TAG] = text(attributes.tag);
181 Ok(tx.create(Entity::new(type_name, attrs)))
182}
183
184/// Stage an `IfcZone`: spaces grouped for a shared purpose.
185///
186/// A zone holds no members directly. Membership is an
187/// `IfcRelAssignsToGroup` pointing at this entity, which is why this
188/// takes no member list -- staging one here would imply the zone
189/// owns its contents, and it does not.
190///
191/// Writes the IFC4/IFC4X3 six-attribute layout with `OwnerHistory` `$`,
192/// so the record is IFC4/IFC4X3 only; use
193/// [`create_zone_with_owner_history`] for IFC2X3, which declares five
194/// (no `LongName`).
195///
196/// # Errors
197///
198/// Refuses a malformed GlobalId.
199pub fn create_zone(
200 tx: &mut Transaction,
201 global_id: &str,
202 name: Option<&str>,
203 description: Option<&str>,
204 long_name: Option<&str>,
205) -> SystemAuthoringResult<EntityId> {
206 super::guid("IFCZONE", global_id)?;
207
208 let mut attrs = vec![Value::Null; zone_slot::WIDTH];
209 attrs[zone_slot::GLOBAL_ID] = Value::Text(global_id.into());
210 attrs[zone_slot::NAME] = text(name);
211 attrs[zone_slot::DESCRIPTION] = text(description);
212 attrs[zone_slot::LONG_NAME] = text(long_name);
213 Ok(tx.create(Entity::new("IFCZONE", attrs)))
214}
215
216/// Stage an `IfcSpatialZone`: a zone that occupies space.
217///
218/// # The USERDEFINED rule
219///
220/// `IfcSpatialZoneTypeEnum` includes `USERDEFINED`, which means
221/// "the predefined list does not cover this". The schema pairs that
222/// with `ObjectType` on `IfcObject`: choosing USERDEFINED without
223/// naming the user-defined kind leaves the zone's purpose
224/// unrecoverable, so it is refused here rather than written out as
225/// a file nobody can interpret.
226///
227/// Writes `OwnerHistory` `$`, so the record is IFC4/IFC4X3 only; use
228/// [`create_spatial_zone_with_owner_history`] for a release-bound record.
229/// IFC2X3 declares no `IfcSpatialZone`.
230///
231/// # Errors
232///
233/// Refuses a malformed GlobalId, and USERDEFINED without an
234/// `object_type` label.
235pub fn create_spatial_zone(
236 tx: &mut Transaction,
237 global_id: &str,
238 attributes: ElementAttributes<'_>,
239 long_name: Option<&str>,
240 predefined_type: Option<&str>,
241 object_type: Option<&str>,
242) -> SystemAuthoringResult<EntityId> {
243 check_spatial_zone(global_id, predefined_type, object_type)?;
244
245 let mut attrs = vec![Value::Null; spatial_zone_slot::WIDTH];
246 attrs[spatial_zone_slot::GLOBAL_ID] = Value::Text(global_id.into());
247 attrs[spatial_zone_slot::NAME] = text(attributes.name);
248 attrs[spatial_zone_slot::DESCRIPTION] = text(attributes.description);
249 attrs[4] = text(object_type);
250 attrs[spatial_zone_slot::OBJECT_PLACEMENT] = reference(attributes.placement);
251 attrs[spatial_zone_slot::REPRESENTATION] = reference(attributes.representation);
252 attrs[spatial_zone_slot::LONG_NAME] = text(long_name);
253 attrs[spatial_zone_slot::PREDEFINED_TYPE] =
254 predefined_type.map_or(Value::Null, |t| Value::Enum(t.into()));
255 Ok(tx.create(Entity::new("IFCSPATIALZONE", attrs)))
256}
257
258/// The plain spatial-zone checks, shared with the release-bound variant.
259fn check_spatial_zone(
260 global_id: &str,
261 predefined_type: Option<&str>,
262 object_type: Option<&str>,
263) -> SystemAuthoringResult<()> {
264 super::guid("IFCSPATIALZONE", global_id)?;
265 if predefined_type == Some("USERDEFINED") && object_type.is_none() {
266 return Err(invalid(
267 "IFCSPATIALZONE",
268 "PredefinedType",
269 "USERDEFINED requires an ObjectType naming the kind",
270 ));
271 }
272 Ok(())
273}
274
275/// [`create_distribution_element`] in `model`'s declared release, with a
276/// caller-supplied `IfcOwnerHistory`, which IFC2X3 requires (#202).
277///
278/// Every [`DistributionElementKind`] declares the same eight attributes in
279/// IFC2X3, IFC4 and IFC4X3; only `OwnerHistory` changes, from required to
280/// optional. The owner history is never invented.
281///
282/// # Errors
283///
284/// Those of [`create_distribution_element`], and the release and
285/// owner-history refusals of
286/// [`create_system_with_owner_history`](super::create_system_with_owner_history).
287/// Nothing is staged on an error.
288pub fn create_distribution_element_with_owner_history(
289 tx: &mut Transaction,
290 model: &Model,
291 kind: DistributionElementKind,
292 global_id: &str,
293 attributes: ElementAttributes<'_>,
294 owner_history: EntityId,
295) -> SystemAuthoringResult<EntityId> {
296 let release = bind(model)?;
297 let type_name = kind.type_name();
298 super::guid(type_name, global_id)?;
299 let values = vec![
300 ("GlobalId", Value::Text(global_id.into())),
301 ("Name", text(attributes.name)),
302 ("Description", text(attributes.description)),
303 ("ObjectPlacement", reference(attributes.placement)),
304 ("Representation", reference(attributes.representation)),
305 ("Tag", text(attributes.tag)),
306 ];
307 release.stage(tx, model, type_name, values, owner_history)
308}
309
310/// [`create_zone`] in `model`'s declared release, with a caller-supplied
311/// `IfcOwnerHistory`, which IFC2X3 requires (#202).
312///
313/// IFC2X3 `IfcZone` declares no `LongName`, so a `long_name` there is
314/// refused rather than dropped.
315///
316/// # Errors
317///
318/// Those of [`create_zone`], the release and owner-history refusals of
319/// [`create_system_with_owner_history`](super::create_system_with_owner_history),
320/// and [`AuthoringNotInSchema`](super::SystemAuthoringError::AuthoringNotInSchema)
321/// for an IFC2X3 `long_name`. Nothing is staged on an error.
322pub fn create_zone_with_owner_history(
323 tx: &mut Transaction,
324 model: &Model,
325 global_id: &str,
326 name: Option<&str>,
327 description: Option<&str>,
328 long_name: Option<&str>,
329 owner_history: EntityId,
330) -> SystemAuthoringResult<EntityId> {
331 let release = bind(model)?;
332 super::guid("IFCZONE", global_id)?;
333 let values = vec![
334 ("GlobalId", Value::Text(global_id.into())),
335 ("Name", text(name)),
336 ("Description", text(description)),
337 ("LongName", text(long_name)),
338 ];
339 release.stage(tx, model, "IFCZONE", values, owner_history)
340}
341
342/// [`create_spatial_zone`] in `model`'s declared release, with a
343/// caller-supplied `IfcOwnerHistory` (#202).
344///
345/// `PredefinedType` is checked against the release's own
346/// `IfcSpatialZoneTypeEnum`: IFC4X3 adds `INTERFERENCE` and `RESERVATION`,
347/// which IFC4 refuses.
348///
349/// # Errors
350///
351/// Those of [`create_spatial_zone`], the release and owner-history
352/// refusals of
353/// [`create_system_with_owner_history`](super::create_system_with_owner_history),
354/// [`EntityNotInSchema`](super::SystemAuthoringError::EntityNotInSchema) in
355/// IFC2X3, and
356/// [`AuthoringValueType`](super::SystemAuthoringError::AuthoringValueType)
357/// for a token the release does not declare. Nothing is staged on an error.
358#[allow(clippy::too_many_arguments)]
359pub fn create_spatial_zone_with_owner_history(
360 tx: &mut Transaction,
361 model: &Model,
362 global_id: &str,
363 attributes: ElementAttributes<'_>,
364 long_name: Option<&str>,
365 predefined_type: Option<&str>,
366 object_type: Option<&str>,
367 owner_history: EntityId,
368) -> SystemAuthoringResult<EntityId> {
369 const ENTITY: &str = "IFCSPATIALZONE";
370 let release = bind(model)?;
371 release.require_entity(ENTITY)?;
372 check_spatial_zone(global_id, predefined_type, object_type)?;
373 let values = vec![
374 ("GlobalId", Value::Text(global_id.into())),
375 ("Name", text(attributes.name)),
376 ("Description", text(attributes.description)),
377 ("ObjectType", text(object_type)),
378 ("ObjectPlacement", reference(attributes.placement)),
379 ("Representation", reference(attributes.representation)),
380 ("LongName", text(long_name)),
381 (
382 "PredefinedType",
383 predefined_type.map_or(Value::Null, |t| Value::Enum(t.into())),
384 ),
385 ];
386 release.stage(tx, model, ENTITY, values, owner_history)
387}