Skip to main content

ifc_properties/pset/
reinforcement.rs

1//! Reinforcement, section, and profile property families.
2//!
3//! These five carry no WHERE rules. What constrains them is structural:
4//! required slots with no unset fallback, aggregate lower bounds of
5//! `[1:?]`, closed enumerations, and the measure type each numeric slot
6//! declares -- including `IfcCountMeasure`, which is an EXPRESS INTEGER.
7//!
8//! Only `IfcReinforcementDefinitionProperties` is an
9//! `IfcPropertySetDefinition` with the four `IfcRoot` slots. The other
10//! four are `IfcPropertyAbstraction` subtypes and start at their own
11//! first attribute.
12
13use ifc_model::{Entity, EntityId, Model, Transaction, Value};
14
15use crate::PropertyResult;
16
17use super::authoring::optional_text;
18use super::owned::{stage_ifc4, stage_owned, Rooted};
19use super::predefined::{invalid, measure, require_guid, Measure};
20const BAR_SURFACE: &[&str] = &["PLAIN", "TEXTURED"];
21
22/// Attributes of an `IfcReinforcementBarProperties`.
23///
24/// `total_cross_section_area` and `steel_grade` are required by the
25/// schema, so they are plain fields rather than options.
26#[derive(Debug, Clone, Copy)]
27#[non_exhaustive]
28pub struct ReinforcementBarDraft<'a> {
29    /// `TotalCrossSectionArea`, an area measure. Required.
30    pub total_cross_section_area: f64,
31    /// `SteelGrade`. Required.
32    pub steel_grade: &'a str,
33    /// `BarSurface`: `PLAIN` or `TEXTURED`.
34    pub bar_surface: Option<&'a str>,
35    /// `EffectiveDepth`, a length. May be negative.
36    pub effective_depth: Option<f64>,
37    /// `NominalBarDiameter`, a positive length.
38    pub nominal_bar_diameter: Option<f64>,
39    /// `BarCount`, an integer count.
40    pub bar_count: Option<i64>,
41}
42
43impl<'a> ReinforcementBarDraft<'a> {
44    /// Starts a draft from its required `total_cross_section_area`,
45    /// `steel_grade`; every other field is unset.
46    #[must_use]
47    pub fn new(total_cross_section_area: f64, steel_grade: &'a str) -> Self {
48        Self {
49            total_cross_section_area,
50            steel_grade,
51            bar_surface: None,
52            effective_depth: None,
53            nominal_bar_diameter: None,
54            bar_count: None,
55        }
56    }
57
58    /// Sets `bar_surface`.
59    ///
60    /// `BarSurface`: `PLAIN` or `TEXTURED`.
61    #[must_use]
62    pub fn bar_surface(mut self, value: &'a str) -> Self {
63        self.bar_surface = Some(value);
64        self
65    }
66
67    /// Sets `effective_depth`.
68    ///
69    /// `EffectiveDepth`, a length. May be negative.
70    #[must_use]
71    pub fn effective_depth(mut self, value: f64) -> Self {
72        self.effective_depth = Some(value);
73        self
74    }
75
76    /// Sets `nominal_bar_diameter`.
77    ///
78    /// `NominalBarDiameter`, a positive length.
79    #[must_use]
80    pub fn nominal_bar_diameter(mut self, value: f64) -> Self {
81        self.nominal_bar_diameter = Some(value);
82        self
83    }
84
85    /// Sets `bar_count`.
86    ///
87    /// `BarCount`, an integer count.
88    #[must_use]
89    pub fn bar_count(mut self, value: i64) -> Self {
90        self.bar_count = Some(value);
91        self
92    }
93}
94
95/// Stage an `IfcReinforcementBarProperties`.
96///
97/// # Errors
98///
99/// Refuses a blank steel grade, a non-finite or negative cross-section
100/// area, a bar surface outside the enumeration, and a measure that
101/// violates its schema measure type.
102pub fn add_reinforcement_bar_properties(
103    tx: &mut Transaction,
104    draft: ReinforcementBarDraft<'_>,
105) -> PropertyResult<EntityId> {
106    const ENTITY: &str = "IFCREINFORCEMENTBARPROPERTIES";
107
108    if draft.steel_grade.trim().is_empty() {
109        return Err(invalid(ENTITY, "SteelGrade", "blank"));
110    }
111    // An area is a magnitude: negative has no reading, and the slot is
112    // required, so there is no "unset" to fall back to.
113    if !draft.total_cross_section_area.is_finite() || draft.total_cross_section_area < 0.0 {
114        return Err(invalid(
115            ENTITY,
116            "TotalCrossSectionArea",
117            format!("{}", draft.total_cross_section_area),
118        ));
119    }
120    if let Some(surface) = draft.bar_surface {
121        if !BAR_SURFACE.contains(&surface) {
122            return Err(invalid(ENTITY, "BarSurface", surface));
123        }
124    }
125
126    let mut attributes = vec![Value::Null; 6];
127    attributes[0] = Value::Real(draft.total_cross_section_area);
128    attributes[1] = Value::Text(draft.steel_grade.into());
129    attributes[2] = draft
130        .bar_surface
131        .map_or(Value::Null, |s| Value::Enum(s.into()));
132    attributes[3] = measure(
133        ENTITY,
134        "EffectiveDepth",
135        draft.effective_depth,
136        Measure::Length,
137    )?;
138    attributes[4] = measure(
139        ENTITY,
140        "NominalBarDiameter",
141        draft.nominal_bar_diameter,
142        Measure::Positive,
143    )?;
144    // IfcCountMeasure is declared INTEGER in EXPRESS. Writing it as a
145    // real produces a record of the right arity that states the wrong
146    // type, which the structural validator does not catch.
147    attributes[5] = draft.bar_count.map_or(Value::Null, Value::Integer);
148
149    Ok(tx.create(Entity::new(ENTITY, attributes)))
150}
151
152const SECTION_TYPE: &[&str] = &["TAPERED", "UNIFORM"];
153
154/// Stage an `IfcSectionProperties`.
155///
156/// `section_type` is `TAPERED` or `UNIFORM`. A uniform section may still
157/// carry an end profile; the schema does not tie the two, and refusing
158/// the combination here would reject files it permits.
159///
160/// # Errors
161///
162/// Refuses a section type outside the enumeration.
163pub fn add_section_properties(
164    tx: &mut Transaction,
165    section_type: &str,
166    start_profile: EntityId,
167    end_profile: Option<EntityId>,
168) -> PropertyResult<EntityId> {
169    const ENTITY: &str = "IFCSECTIONPROPERTIES";
170
171    if !SECTION_TYPE.contains(&section_type) {
172        return Err(invalid(ENTITY, "SectionType", section_type));
173    }
174
175    let mut attributes = vec![Value::Null; 3];
176    attributes[0] = Value::Enum(section_type.into());
177    attributes[1] = Value::Ref(start_profile);
178    attributes[2] = end_profile.map_or(Value::Null, Value::Ref);
179
180    Ok(tx.create(Entity::new(ENTITY, attributes)))
181}
182
183const BAR_ROLE: &[&str] = &[
184    "ANCHORING",
185    "EDGE",
186    "LIGATURE",
187    "MAIN",
188    "PUNCHING",
189    "RING",
190    "SHEAR",
191    "STUD",
192    "USERDEFINED",
193    "NOTDEFINED",
194];
195
196/// Attributes of an `IfcSectionReinforcementProperties`.
197#[derive(Debug, Clone, Copy)]
198#[non_exhaustive]
199pub struct SectionReinforcementDraft<'a> {
200    /// `LongitudinalStartPosition`, a length. Required.
201    pub longitudinal_start_position: f64,
202    /// `LongitudinalEndPosition`, a length. Required.
203    pub longitudinal_end_position: f64,
204    /// `TransversePosition`, a length.
205    pub transverse_position: Option<f64>,
206    /// `ReinforcementRole`, from `IfcReinforcingBarRoleEnum`. Required.
207    pub reinforcement_role: &'a str,
208    /// `SectionDefinition`: an `IfcSectionProperties`. Required.
209    pub section_definition: EntityId,
210    /// `CrossSectionReinforcementDefinitions`: at least one
211    /// `IfcReinforcementBarProperties`.
212    pub cross_section_reinforcement_definitions: &'a [EntityId],
213}
214
215impl<'a> SectionReinforcementDraft<'a> {
216    /// Starts a draft from its required `longitudinal_start_position`,
217    /// `longitudinal_end_position`, `reinforcement_role`, `section_definition`,
218    /// `cross_section_reinforcement_definitions`; every other field is unset.
219    #[must_use]
220    pub fn new(
221        longitudinal_start_position: f64,
222        longitudinal_end_position: f64,
223        reinforcement_role: &'a str,
224        section_definition: EntityId,
225        cross_section_reinforcement_definitions: &'a [EntityId],
226    ) -> Self {
227        Self {
228            longitudinal_start_position,
229            longitudinal_end_position,
230            transverse_position: None,
231            reinforcement_role,
232            section_definition,
233            cross_section_reinforcement_definitions,
234        }
235    }
236
237    /// Sets `transverse_position`.
238    ///
239    /// `TransversePosition`, a length.
240    #[must_use]
241    pub fn transverse_position(mut self, value: f64) -> Self {
242        self.transverse_position = Some(value);
243        self
244    }
245}
246
247/// Stage an `IfcSectionReinforcementProperties`.
248///
249/// Both longitudinal positions are `IfcLengthMeasure`, which admits
250/// negatives, and the schema states no ordering between them: a section
251/// measured from a datum may legitimately start at a negative station.
252/// Only non-finite values are refused.
253///
254/// # Errors
255///
256/// Refuses a role outside the enumeration, a non-finite position, and an
257/// empty reinforcement-definition set, whose schema bound is `[1:?]`.
258pub fn add_section_reinforcement_properties(
259    tx: &mut Transaction,
260    draft: SectionReinforcementDraft<'_>,
261) -> PropertyResult<EntityId> {
262    const ENTITY: &str = "IFCSECTIONREINFORCEMENTPROPERTIES";
263
264    if !BAR_ROLE.contains(&draft.reinforcement_role) {
265        return Err(invalid(
266            ENTITY,
267            "ReinforcementRole",
268            draft.reinforcement_role,
269        ));
270    }
271    if draft.cross_section_reinforcement_definitions.is_empty() {
272        return Err(invalid(
273            ENTITY,
274            "CrossSectionReinforcementDefinitions",
275            "empty",
276        ));
277    }
278
279    let mut attributes = vec![Value::Null; 6];
280    attributes[0] = measure(
281        ENTITY,
282        "LongitudinalStartPosition",
283        Some(draft.longitudinal_start_position),
284        Measure::Length,
285    )?;
286    attributes[1] = measure(
287        ENTITY,
288        "LongitudinalEndPosition",
289        Some(draft.longitudinal_end_position),
290        Measure::Length,
291    )?;
292    attributes[2] = measure(
293        ENTITY,
294        "TransversePosition",
295        draft.transverse_position,
296        Measure::Length,
297    )?;
298    attributes[3] = Value::Enum(draft.reinforcement_role.into());
299    attributes[4] = Value::Ref(draft.section_definition);
300    attributes[5] = Value::List(
301        draft
302            .cross_section_reinforcement_definitions
303            .iter()
304            .copied()
305            .map(Value::Ref)
306            .collect(),
307    );
308
309    Ok(tx.create(Entity::new(ENTITY, attributes)))
310}
311
312/// Stage an `IfcReinforcementDefinitionProperties`.
313///
314/// This is the only member of the family that is an
315/// `IfcPropertySetDefinition`, so it carries the four `IfcRoot` slots and
316/// a GlobalId. The others are `IfcPropertyAbstraction` subtypes with no
317/// identity of their own.
318///
319/// Takes no model, so it writes the IFC4 layout with `OwnerHistory` `$`:
320/// valid IFC4 and IFC4X3, never valid IFC2X3. Use
321/// [`add_reinforcement_definition_properties_with_owner_history`] to
322/// write the model's declared release.
323///
324/// # Errors
325///
326/// Refuses a malformed GlobalId and an empty section-definition list,
327/// whose schema bound is `[1:?]`.
328pub fn add_reinforcement_definition_properties(
329    tx: &mut Transaction,
330    global_id: &str,
331    name: Option<&str>,
332    description: Option<&str>,
333    definition_type: Option<&str>,
334    reinforcement_section_definitions: &[EntityId],
335) -> PropertyResult<EntityId> {
336    let rooted = reinforcement_definition(
337        global_id,
338        (name, description),
339        definition_type,
340        reinforcement_section_definitions,
341    )?;
342    stage_ifc4(tx, rooted)
343}
344
345/// [`add_reinforcement_definition_properties`] in the model's declared
346/// release, with a caller-supplied `IfcOwnerHistory`, which IFC2X3
347/// requires (#202).
348///
349/// # Errors
350///
351/// Those of [`add_reinforcement_definition_properties`], and the release
352/// and owner-history refusals of
353/// [`add_door_lining_properties_with_owner_history`](crate::add_door_lining_properties_with_owner_history).
354/// Nothing is staged on an error.
355#[allow(clippy::too_many_arguments)]
356pub fn add_reinforcement_definition_properties_with_owner_history(
357    tx: &mut Transaction,
358    model: &Model,
359    global_id: &str,
360    name: Option<&str>,
361    description: Option<&str>,
362    definition_type: Option<&str>,
363    reinforcement_section_definitions: &[EntityId],
364    owner_history: EntityId,
365) -> PropertyResult<EntityId> {
366    let rooted = reinforcement_definition(
367        global_id,
368        (name, description),
369        definition_type,
370        reinforcement_section_definitions,
371    )?;
372    stage_owned(tx, model, rooted, owner_history)
373}
374
375fn reinforcement_definition<'a>(
376    global_id: &'a str,
377    (name, description): (Option<&'a str>, Option<&'a str>),
378    definition_type: Option<&str>,
379    reinforcement_section_definitions: &[EntityId],
380) -> PropertyResult<Rooted<'a>> {
381    const ENTITY: &str = "IFCREINFORCEMENTDEFINITIONPROPERTIES";
382
383    if reinforcement_section_definitions.is_empty() {
384        return Err(invalid(ENTITY, "ReinforcementSectionDefinitions", "empty"));
385    }
386    require_guid(ENTITY, global_id)?;
387    let sections = reinforcement_section_definitions.iter().copied();
388    let values = vec![
389        ("DefinitionType", optional_text(definition_type)),
390        (
391            "ReinforcementSectionDefinitions",
392            Value::List(sections.map(Value::Ref).collect()),
393        ),
394    ];
395    Ok(Rooted {
396        entity: ENTITY,
397        global_id,
398        name,
399        description,
400        values,
401    })
402}
403
404/// Stage an `IfcProfileProperties`.
405///
406/// `properties` are `IfcProperty` instances, not measures: this is the
407/// extended-property form, where the profile's characteristics are
408/// expressed as named properties rather than fixed typed slots.
409///
410/// # Errors
411///
412/// Refuses an empty property set, whose schema bound is `[1:?]`.
413pub fn add_profile_properties(
414    tx: &mut Transaction,
415    name: Option<&str>,
416    description: Option<&str>,
417    properties: &[EntityId],
418    profile_definition: EntityId,
419) -> PropertyResult<EntityId> {
420    const ENTITY: &str = "IFCPROFILEPROPERTIES";
421
422    if properties.is_empty() {
423        return Err(invalid(ENTITY, "Properties", "empty"));
424    }
425
426    let mut attributes = vec![Value::Null; 4];
427    attributes[0] = optional_text(name);
428    attributes[1] = optional_text(description);
429    attributes[2] = Value::List(properties.iter().copied().map(Value::Ref).collect());
430    attributes[3] = Value::Ref(profile_definition);
431
432    Ok(tx.create(Entity::new(ENTITY, attributes)))
433}