ifc-structural 0.4.0

Structural analysis model: members, connections, actions, reactions, loads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use ifc_model::{EntityId, Model, Transaction, Value};
use ifc_schema::{Schema, TypeKind};

use super::item::{root_fields, validate_root, StructuralRootDraft};
use super::{build_named, optional_ref, validate_optional_ref, validate_ref, validate_ref_select};
use crate::action::CoordinateSystem;
use crate::error::{StructuralError, StructuralResult};

/// Value of `IfcProjectedOrTrueLengthEnum` naming how a linear/planar action's magnitude is measured.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProjectedOrTrue {
    /// `PROJECTED_LENGTH`: magnitude given per unit of the projected length/area.
    ProjectedLength,
    /// `TRUE_LENGTH`: magnitude given per unit of the true (unprojected) length/area.
    TrueLength,
}

impl ProjectedOrTrue {
    fn token(self) -> &'static str {
        match self {
            Self::ProjectedLength => "PROJECTED_LENGTH",
            Self::TrueLength => "TRUE_LENGTH",
        }
    }
}

/// Staged action subtype for [`ActionDraft::kind`].
#[derive(Debug, Clone)]
pub enum ActionDraftKind {
    /// Stages an `IfcStructuralPointAction`.
    Point,
    /// Stages an `IfcStructuralLinearAction`.
    Linear {
        /// `ProjectedOrTrue`; staged only when the target schema declares the attribute.
        projected_or_true: Option<ProjectedOrTrue>,
    },
    /// Stages an `IfcStructuralPlanarAction`.
    Planar {
        /// `ProjectedOrTrue`; staged only when the target schema declares the attribute.
        projected_or_true: Option<ProjectedOrTrue>,
    },
    /// Stages an `IfcStructuralCurveAction`.
    ///
    /// IFC4 replaced the linear/planar pair with curve/surface forms that
    /// additionally carry a mandatory `PredefinedType`.
    Curve {
        /// `ProjectedOrTrue`; staged only when the target schema declares it.
        projected_or_true: Option<ProjectedOrTrue>,
        /// `PredefinedType`, an `IfcStructuralCurveActivityTypeEnum` token.
        predefined_type: &'static str,
    },
    /// Stages an `IfcStructuralSurfaceAction`.
    Surface {
        /// `ProjectedOrTrue`; staged only when the target schema declares it.
        projected_or_true: Option<ProjectedOrTrue>,
        /// `PredefinedType`, an `IfcStructuralSurfaceActivityTypeEnum` token.
        predefined_type: &'static str,
    },
}

/// Staged fields for creating an `IfcStructuralAction` via [`stage_action`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ActionDraft {
    /// `IfcRoot` attributes shared with other staged structural entities.
    pub root: StructuralRootDraft,
    /// `AppliedLoad`; must reference a load type compatible with `kind`.
    pub applied_load: EntityId,
    /// `GlobalOrLocal`.
    pub coordinate_system: CoordinateSystem,
    /// `DestabilizingLoad`; required when the target schema (IFC2X3) declares it mandatory.
    pub destabilizing_load: Option<bool>,
    /// `CausedBy`; only staged when the target schema declares the attribute.
    pub caused_by: Option<EntityId>,
    /// Which `IfcStructuralAction` subtype to create, and its subtype-specific attributes.
    pub kind: ActionDraftKind,
    /// Varying-load attributes; when set, a [`ActionDraftKind::Linear`] or
    /// [`ActionDraftKind::Planar`] kind stages the IFC2X3 varying subtype.
    pub varying: Option<VaryingActionDraft>,
}

/// IFC2X3 varying-action attributes for [`ActionDraft::varying`].
///
/// With [`ActionDraftKind::Linear`] it stages an
/// `IfcStructuralLinearActionVarying` (`SubsequentAppliedLoads : LIST [1:?]`);
/// with [`ActionDraftKind::Planar`] an `IfcStructuralPlanarActionVarying`
/// (`LIST [2:?]`). IFC4 and IFC4X3 declare neither entity.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VaryingActionDraft {
    /// `VaryingAppliedLoadLocation`, an `IfcShapeAspect` reference.
    pub varying_applied_load_location: EntityId,
    /// `SubsequentAppliedLoads`, `IfcStructuralLoad` references in list
    /// order after the action's `AppliedLoad`. Repeats are allowed (LIST).
    pub subsequent_applied_loads: Vec<EntityId>,
}

impl VaryingActionDraft {
    /// Starts a draft from its two required attributes.
    #[must_use]
    pub fn new(
        varying_applied_load_location: EntityId,
        subsequent_applied_loads: Vec<EntityId>,
    ) -> Self {
        Self {
            varying_applied_load_location,
            subsequent_applied_loads,
        }
    }
}

impl ActionDraft {
    /// Starts a draft from its required fields; every other field is unset.
    #[must_use]
    pub fn new(
        root: StructuralRootDraft,
        applied_load: EntityId,
        coordinate_system: CoordinateSystem,
        kind: ActionDraftKind,
    ) -> Self {
        Self {
            root,
            applied_load,
            coordinate_system,
            destabilizing_load: None,
            caused_by: None,
            kind,
            varying: None,
        }
    }

    /// Sets `destabilizing_load`: `DestabilizingLoad`; required when the target
    /// schema (IFC2X3) declares it mandatory.
    #[must_use]
    pub fn destabilizing_load(mut self, value: bool) -> Self {
        self.destabilizing_load = Some(value);
        self
    }

    /// Sets `caused_by`: `CausedBy`; only staged when the target schema
    /// declares the attribute.
    #[must_use]
    pub fn caused_by(mut self, value: EntityId) -> Self {
        self.caused_by = Some(value);
        self
    }

    /// Sets `varying`: stage the IFC2X3 varying subtype of a linear or
    /// planar action with these attributes.
    #[must_use]
    pub fn varying(mut self, value: VaryingActionDraft) -> Self {
        self.varying = Some(value);
        self
    }
}

/// Stage an `IfcStructuralAction` create edit on `tx`.
///
/// Fails with [`StructuralError::WrongReferenceType`] if `draft.applied_load`
/// is not one of the load types `kind` permits, [`StructuralError::SemanticViolation`]
/// if `ProjectedOrTrue` is `PROJECTED_LENGTH` while `coordinate_system` is not
/// `Global`, and [`StructuralError::MissingRequired`] if `destabilizing_load`
/// is unset while the target schema requires it.
///
/// With [`ActionDraft::varying`] set, a linear kind stages
/// `IfcStructuralLinearActionVarying` and a planar kind
/// `IfcStructuralPlanarActionVarying`. That fails with
/// [`StructuralError::EntityNotInSchema`] outside IFC2X3, with
/// [`StructuralError::InvalidDraftValue`] for any other kind or a
/// `SubsequentAppliedLoads` list below its minimum (1 linear, 2 planar),
/// and with the reference errors when the location is not an
/// `IfcShapeAspect` or a subsequent load not an `IfcStructuralLoad`.
/// Every refusal stages nothing. Returns the id staged for the new entity.
pub fn stage_action(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: ActionDraft,
) -> StructuralResult<EntityId> {
    let varying = validate_varying(tx, model, schema, &draft)?;
    validate_root(tx, model, schema, &draft.root)?;
    let (entity_type, projected_or_true, load_members): (&str, Option<ProjectedOrTrue>, &[&str]) =
        match draft.kind {
            ActionDraftKind::Point => (
                "IfcStructuralPointAction",
                None,
                &[
                    "IfcStructuralLoadSingleForce",
                    "IfcStructuralLoadSingleDisplacement",
                ],
            ),
            ActionDraftKind::Linear { projected_or_true } => (
                "IfcStructuralLinearAction",
                projected_or_true,
                &[
                    "IfcStructuralLoadLinearForce",
                    "IfcStructuralLoadTemperature",
                ],
            ),
            ActionDraftKind::Planar { projected_or_true } => (
                "IfcStructuralPlanarAction",
                projected_or_true,
                &[
                    "IfcStructuralLoadPlanarForce",
                    "IfcStructuralLoadTemperature",
                ],
            ),
            ActionDraftKind::Curve {
                projected_or_true, ..
            } => (
                "IfcStructuralCurveAction",
                projected_or_true,
                &[
                    "IfcStructuralLoadLinearForce",
                    "IfcStructuralLoadTemperature",
                ],
            ),
            ActionDraftKind::Surface {
                projected_or_true, ..
            } => (
                "IfcStructuralSurfaceAction",
                projected_or_true,
                &[
                    "IfcStructuralLoadPlanarForce",
                    "IfcStructuralLoadTemperature",
                ],
            ),
        };
    let entity_type = varying.as_ref().map_or(entity_type, |(name, _)| *name);
    validate_ref_select(
        tx,
        model,
        schema,
        draft.applied_load,
        "compatible structural load",
        load_members,
    )?;
    validate_optional_ref(tx, model, schema, draft.caused_by, "IfcStructuralReaction")?;
    if projected_or_true == Some(ProjectedOrTrue::ProjectedLength)
        && draft.coordinate_system != CoordinateSystem::Global
    {
        return Err(StructuralError::SemanticViolation {
            entity: None,
            rule: "PROJECTED_LENGTH structural action requires GLOBAL_COORDS",
        });
    }
    let attributes = schema.attributes(entity_type);

    let destabilizing_required = attributes
        .iter()
        .find(|a| a.name.eq_ignore_ascii_case("DestabilizingLoad"))
        .is_some_and(|attribute| !attribute.optional);
    if destabilizing_required && draft.destabilizing_load.is_none() {
        return Err(StructuralError::MissingRequired {
            entity_type: entity_type.into(),
            attribute: "DestabilizingLoad".into(),
        });
    }
    let has_object_type = draft.root.object_type.is_some();
    let mut fields = root_fields(draft.root);
    fields.push(("AppliedLoad", Value::Ref(draft.applied_load)));
    fields.push((
        "GlobalOrLocal",
        Value::Enum(match draft.coordinate_system {
            CoordinateSystem::Global => "GLOBAL_COORDS".into(),
            CoordinateSystem::Local => "LOCAL_COORDS".into(),
        }),
    ));
    if attributes
        .iter()
        .any(|a| a.name.eq_ignore_ascii_case("DestabilizingLoad"))
    {
        fields.push((
            "DestabilizingLoad",
            draft.destabilizing_load.map_or(Value::Null, Value::Bool),
        ));
    }
    if attributes
        .iter()
        .any(|a| a.name.eq_ignore_ascii_case("CausedBy"))
    {
        fields.push(("CausedBy", optional_ref(draft.caused_by)));
    }
    if attributes
        .iter()
        .any(|a| a.name.eq_ignore_ascii_case("ProjectedOrTrue"))
    {
        fields.push((
            "ProjectedOrTrue",
            projected_or_true.map_or(Value::Null, |value| Value::Enum(value.token().into())),
        ));
    }
    if attributes
        .iter()
        .any(|a| a.name.eq_ignore_ascii_case("PredefinedType"))
    {
        // IFC4 makes PredefinedType mandatory on the curve and surface
        // forms. USERDEFINED without an ObjectType names nothing, which
        // is the same trap the element types carry.
        let token = match draft.kind {
            ActionDraftKind::Curve {
                predefined_type, ..
            }
            | ActionDraftKind::Surface {
                predefined_type, ..
            } => predefined_type,
            _ => "NOTDEFINED",
        };
        if token.eq_ignore_ascii_case("USERDEFINED") && !has_object_type {
            return Err(StructuralError::SemanticViolation {
                entity: None,
                rule: "USERDEFINED PredefinedType requires an ObjectType",
            });
        }
        // SuitablePredefinedType: the curve form alone excludes
        // EQUIDISTANT. The token exists in the enum because the
        // activity-type enum is shared with curve *reactions*, where
        // equidistant results are meaningful; an applied action
        // cannot be equidistant.
        if matches!(draft.kind, ActionDraftKind::Curve { .. })
            && token.eq_ignore_ascii_case("EQUIDISTANT")
        {
            return Err(StructuralError::SemanticViolation {
                entity: None,
                rule: "IfcStructuralCurveAction.SuitablePredefinedType",
            });
        }
        // The token must be one the target schema declares for this
        // attribute: a surface token on a curve action resolves to a
        // slot that accepts it structurally and means nothing.
        validate_activity_token(schema, entity_type, token)?;
        fields.push(("PredefinedType", Value::Enum(token.into())));
    }
    if let Some((_, varying)) = varying {
        fields.push((
            "VaryingAppliedLoadLocation",
            Value::Ref(varying.varying_applied_load_location),
        ));
        fields.push((
            "SubsequentAppliedLoads",
            Value::List(
                varying
                    .subsequent_applied_loads
                    .into_iter()
                    .map(Value::Ref)
                    .collect(),
            ),
        ));
    }
    Ok(tx.create(build_named(schema, entity_type, fields)?))
}

/// Resolve and check [`ActionDraft::varying`] before anything is staged.
///
/// Returns the varying entity type with its attributes, or `None` when the
/// draft is not varying.
fn validate_varying(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    draft: &ActionDraft,
) -> StructuralResult<Option<(&'static str, VaryingActionDraft)>> {
    let Some(varying) = &draft.varying else {
        return Ok(None);
    };
    let (entity_type, minimum, expected) = match draft.kind {
        ActionDraftKind::Linear { .. } => (
            "IfcStructuralLinearActionVarying",
            1,
            "LIST [1:?] of IfcStructuralLoad references",
        ),
        ActionDraftKind::Planar { .. } => (
            "IfcStructuralPlanarActionVarying",
            2,
            "LIST [2:?] of IfcStructuralLoad references",
        ),
        _ => {
            return Err(StructuralError::InvalidDraftValue {
                entity_type: "IfcStructuralAction",
                attribute: "SubsequentAppliedLoads",
                expected: "a Linear or Planar action kind (only those have varying subtypes)",
            })
        }
    };
    if schema.entity(entity_type).is_none() {
        return Err(StructuralError::EntityNotInSchema {
            entity: entity_type,
            schema: schema.name().to_owned(),
        });
    }
    if varying.subsequent_applied_loads.len() < minimum {
        return Err(StructuralError::InvalidDraftValue {
            entity_type,
            attribute: "SubsequentAppliedLoads",
            expected,
        });
    }
    validate_ref(
        tx,
        model,
        schema,
        varying.varying_applied_load_location,
        "IfcShapeAspect",
    )?;
    for load in &varying.subsequent_applied_loads {
        validate_ref(tx, model, schema, *load, "IfcStructuralLoad")?;
    }
    Ok(Some((entity_type, varying.clone())))
}

/// Refuse a `PredefinedType` token the schema does not declare
/// for `entity_type`.
///
/// The curve and surface forms carry different activity enums
/// with overlapping tokens (`CONST`, `DISCRETE`), so a wrong-form
/// token is not always visibly wrong.
pub(super) fn validate_activity_token(
    schema: &Schema,
    entity_type: &'static str,
    token: &str,
) -> StructuralResult<()> {
    let declared = schema
        .attributes(entity_type)
        .iter()
        .find(|a| a.name.eq_ignore_ascii_case("PredefinedType"))
        .and_then(|a| schema.type_def(&a.type_name))
        .is_some_and(|def| {
            matches!(&def.kind, TypeKind::Enumeration(values)
                if values.iter().any(|v| v.eq_ignore_ascii_case(token)))
        });
    if declared {
        return Ok(());
    }
    Err(StructuralError::InvalidDraftValue {
        entity_type,
        attribute: "PredefinedType",
        expected: "a token this action's activity enum declares",
    })
}