Skip to main content

ifc_geometry/authoring/
grid.rs

1//! `IfcGrid`, the one `IfcRoot` this module authors.
2//!
3//! A grid is an `IfcProduct`, so it carries `IfcRoot.OwnerHistory`, which
4//! IFC2X3 requires and IFC4 made optional, and its attribute count differs
5//! by release (IFC2X3 declares no `PredefinedType`):
6//!
7//! ```text
8//! IFC2X3_TC1   OwnerHistory : IfcOwnerHistory;           10 attributes
9//! IFC4         OwnerHistory : OPTIONAL IfcOwnerHistory;  11 attributes
10//! IFC4X3_ADD2  OwnerHistory : OPTIONAL IfcOwnerHistory;  11 attributes
11//! ```
12//!
13//! [`grid`] takes no model and writes the IFC4 layout.
14//! [`grid_with_owner_history`] binds the model's declared release through
15//! `release.rs`, as the `_in` sweep writers do (#200), and lays the record
16//! out by attribute name from its table (#202).
17
18use ifc_model::guid::Guid;
19use ifc_model::{Edit, Entity, EntityId, Model, Transaction, Value};
20use ifc_schema::TypeKind;
21
22use crate::error::GeometryError;
23
24use super::release::bind;
25use super::{invalid, refs};
26
27const ENTITY: &str = "IFCGRID";
28
29/// Stage an `IfcGrid`: the U/V/W axis system a plan is dimensioned
30/// against.
31///
32/// `UAxes` and `VAxes` are `LIST [1:?] OF UNIQUE`, so a grid needs at
33/// least one axis in each direction and may not list the same axis
34/// twice. A repeated axis is not a harmless duplicate: it makes the
35/// grid ambiguous about which intersection a gridline names.
36///
37/// # Release
38///
39/// Takes no model, so it writes the IFC4 layout (11 attributes) with
40/// `OwnerHistory` `$`. That is valid IFC4 and IFC4X3 and never valid
41/// IFC2X3, which requires `OwnerHistory` and declares 10 attributes. Use
42/// [`grid_with_owner_history`] to write the model's declared release.
43///
44/// # Errors
45///
46/// Refuses a malformed GlobalId, an empty U or V list, and a repeated
47/// axis within any one list.
48pub fn grid(
49    tx: &mut Transaction,
50    global_id: &str,
51    placement: Option<EntityId>,
52    axes: (&[EntityId], &[EntityId], &[EntityId]),
53    predefined_type: Option<&str>,
54) -> Result<EntityId, GeometryError> {
55    check(global_id, axes)?;
56    let (u_axes, v_axes, w_axes) = axes;
57    let mut attrs = vec![Value::Null; 11];
58    attrs[0] = Value::Text(global_id.into());
59    attrs[5] = placement.map_or(Value::Null, Value::Ref);
60    attrs[7] = refs(u_axes);
61    attrs[8] = refs(v_axes);
62    if !w_axes.is_empty() {
63        attrs[9] = refs(w_axes);
64    }
65    attrs[10] = predefined_type.map_or(Value::Null, |t| Value::Enum(t.into()));
66    Ok(tx.create(Entity::new(ENTITY, attrs)))
67}
68
69/// [`grid`] in the model's declared release, with a caller-supplied
70/// `IfcOwnerHistory`, which IFC2X3 requires on every `IfcRoot`.
71///
72/// The record is laid out by attribute name from the bound release's
73/// table, so an IFC2X3 grid has its 10 attributes, not IFC4's 11.
74/// `owner_history` must be in the model or staged earlier on `tx`, and
75/// must be an `IfcOwnerHistory`; one is never invented here (build it with
76/// `ifc-author`). In IFC4 and IFC4X3 the reference fills the optional
77/// slot, and the record is otherwise the one [`grid`] writes.
78///
79/// # Errors
80///
81/// Those of [`grid`], and: [`GeometryError::AuthoringSchemaUnbound`] for a
82/// model that binds no single known release;
83/// [`GeometryError::InvalidAuthoredValue`] for a `predefined_type` in
84/// IFC2X3, which declares none, or outside the release's
85/// `IfcGridTypeEnum`, and on `OwnerHistory` for an `owner_history` that
86/// does not resolve or is another entity. Nothing is staged on an error.
87pub fn grid_with_owner_history(
88    tx: &mut Transaction,
89    model: &Model,
90    global_id: &str,
91    placement: Option<EntityId>,
92    axes: (&[EntityId], &[EntityId], &[EntityId]),
93    predefined_type: Option<&str>,
94    owner_history: EntityId,
95) -> Result<EntityId, GeometryError> {
96    let release = bind(model, ENTITY)?;
97    check(global_id, axes)?;
98    let (schema, version) = (release.schema(), release.version());
99    let declared = schema.attributes(ENTITY);
100    if let Some(token) = predefined_type {
101        let predefined = declared
102            .iter()
103            .find(|attribute| attribute.name.eq_ignore_ascii_case("PredefinedType"))
104            .ok_or_else(|| {
105                invalid(
106                    ENTITY,
107                    "PredefinedType",
108                    format!("{version:?} declares no such attribute"),
109                )
110            })?;
111        let members = match schema.type_def(&predefined.type_name).map(|t| &t.kind) {
112            Some(TypeKind::Enumeration(members)) => members.as_slice(),
113            _ => &[],
114        };
115        if !members.iter().any(|member| member == token) {
116            return Err(invalid(
117                ENTITY,
118                "PredefinedType",
119                format!("{token} is not a {} token", predefined.type_name),
120            ));
121        }
122    }
123    require_owner_history(tx, model, owner_history)?;
124
125    let (u_axes, v_axes, w_axes) = axes;
126    let w_axes = if w_axes.is_empty() {
127        Value::Null
128    } else {
129        refs(w_axes)
130    };
131    let values = [
132        ("GlobalId", Value::Text(global_id.into())),
133        ("OwnerHistory", Value::Ref(owner_history)),
134        ("ObjectPlacement", placement.map_or(Value::Null, Value::Ref)),
135        ("UAxes", refs(u_axes)),
136        ("VAxes", refs(v_axes)),
137        ("WAxes", w_axes),
138        (
139            "PredefinedType",
140            predefined_type.map_or(Value::Null, |t| Value::Enum(t.into())),
141        ),
142    ];
143    let mut attrs = vec![Value::Null; declared.len()];
144    for (attribute, value) in values {
145        match declared
146            .iter()
147            .position(|found| found.name.eq_ignore_ascii_case(attribute))
148        {
149            Some(slot) => attrs[slot] = value,
150            None if value == Value::Null => {}
151            None => {
152                return Err(invalid(
153                    ENTITY,
154                    attribute,
155                    format!("{version:?} declares no such attribute"),
156                ))
157            }
158        }
159    }
160    release.require(ENTITY, &attrs)?;
161    Ok(tx.create(Entity::new(ENTITY, attrs)))
162}
163
164/// The GlobalId and the axis lists, whatever the release.
165fn check(
166    global_id: &str,
167    (u_axes, v_axes, w_axes): (&[EntityId], &[EntityId], &[EntityId]),
168) -> Result<(), GeometryError> {
169    if Guid::parse(global_id).is_none() {
170        return Err(invalid(ENTITY, "GlobalId", global_id));
171    }
172    for (values, attribute) in [(u_axes, "UAxes"), (v_axes, "VAxes")] {
173        if values.is_empty() {
174            return Err(invalid(
175                ENTITY,
176                attribute,
177                "expected at least one axis, per LIST [1:?]",
178            ));
179        }
180    }
181    for (values, attribute) in [(u_axes, "UAxes"), (v_axes, "VAxes"), (w_axes, "WAxes")] {
182        let mut seen = std::collections::HashSet::new();
183        if let Some(repeat) = values.iter().find(|axis| !seen.insert(**axis)) {
184            return Err(invalid(
185                ENTITY,
186                attribute,
187                format!("axis {repeat:?} appears twice in a UNIQUE list"),
188            ));
189        }
190    }
191    Ok(())
192}
193
194/// Fail unless `id` is an `IfcOwnerHistory` in the model or staged on `tx`.
195fn require_owner_history(
196    tx: &Transaction,
197    model: &Model,
198    id: EntityId,
199) -> Result<(), GeometryError> {
200    let mut found = model.get(id).map(|entity| entity.type_name.to_string());
201    for edit in tx.edits() {
202        match edit {
203            Edit::Create { id: target, entity } if *target == id => {
204                found = Some(entity.type_name.to_string());
205            }
206            Edit::Retype {
207                id: target,
208                type_name,
209            } if *target == id => found = Some(type_name.to_string()),
210            Edit::Remove { id: target } if *target == id => found = None,
211            _ => {}
212        }
213    }
214    match found {
215        Some(found) if found.eq_ignore_ascii_case("IFCOWNERHISTORY") => Ok(()),
216        Some(found) => Err(invalid(
217            ENTITY,
218            "OwnerHistory",
219            format!("#{} is a {found}, not an IfcOwnerHistory", id.0),
220        )),
221        None => Err(invalid(
222            ENTITY,
223            "OwnerHistory",
224            format!("#{} does not resolve", id.0),
225        )),
226    }
227}