ifc-style 0.4.0

Presentation: styles, colours, textures, layers, annotation.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! Transaction-staged authoring for presentation and annotation entities.

use std::sync::Arc;

use ifc_model::{Edit, Entity, EntityId, Model, Transaction, Value};
use ifc_schema::Schema;

use crate::annotation::{AnnotationType, BoxAlignment, TextPath};
use crate::error::{StyleError, StyleResult};

mod external;
mod fill;
mod light;
mod presentation;
mod surface;
mod texture;

pub use surface::{
    create_colour_rgb, create_presentation_layer_with_style, create_styled_item,
    create_surface_style, create_surface_style_rendering, create_surface_style_shading,
    ColourRgbDraft, PresentationLayerDraft, StyledItemDraft, SurfaceStyleDraft,
    SurfaceStyleRenderingDraft, SurfaceStyleShadingDraft,
};

pub use external::{
    create_blob_texture, create_externally_defined_style, create_indexed_polygonal_texture_map,
    create_indexed_triangle_texture_map, create_light_distribution_data,
    create_light_intensity_distribution, create_surface_style_with_textures, create_text_style,
    create_text_style_text_model, create_texture_coordinate_indices,
    create_texture_coordinate_indices_with_voids, BlobTextureDraft, ExternalStyleKind, SizeValue,
    TextModelDraft,
};
pub use fill::{create_fill_area_style_hatching, create_fill_area_style_tiles, HatchLineDistance};
pub use light::{
    create_light_source_ambient, create_light_source_directional, create_light_source_goniometric,
    create_light_source_positional, create_light_source_spot, create_surface_style_lighting,
    create_surface_style_refraction, Attenuation, GoniometricLight, LightSourceDraft, PointLight,
    SpotCone,
};
pub use presentation::{
    create_colour_rgb_list, create_curve_style, create_curve_style_font,
    create_curve_style_font_and_scaling, create_curve_style_font_pattern,
    create_draughting_predefined_colour, create_draughting_predefined_curve_font,
    create_fill_area_style, create_indexed_colour_map, create_pixel_texture,
    create_presentation_layer_assignment, create_text_style_font_model,
    create_text_style_for_defined_font, create_texture_vertex, create_texture_vertex_list,
    CurveStyleDraft, CurveWidth, FillStyleKind, PixelTextureDraft, PREDEFINED_COLOUR_NAMES,
    PREDEFINED_CURVE_FONT_NAMES,
};
pub use texture::{
    create_image_texture, create_texture_coordinate_generator, create_texture_map,
    ImageTextureDraft,
};

/// Draft input for [`create_annotation`]: the writable attributes of a new
/// `IfcAnnotation`.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct AnnotationDraft<'a> {
    /// The `GlobalId` (IFC GUID); must parse as a valid base64-like GUID.
    pub global_id: &'a str,
    /// The `OwnerHistory` reference, when supplied.
    pub owner_history: Option<EntityId>,
    /// The `Name` attribute, when supplied.
    pub name: Option<&'a str>,
    /// The `Description` attribute, when supplied.
    pub description: Option<&'a str>,
    /// The `ObjectType` attribute. Required (non-empty) when `predefined_type`
    /// is `AnnotationType::UserDefined`.
    pub object_type: Option<&'a str>,
    /// The `ObjectPlacement` reference, when supplied.
    pub object_placement: Option<EntityId>,
    /// The `Representation` reference, when supplied.
    pub representation: Option<EntityId>,
    /// The IFC4X3 `PredefinedType`, when supplied.
    pub predefined_type: Option<AnnotationType>,
}

impl<'a> AnnotationDraft<'a> {
    /// Starts a draft from its required `global_id`; every other field is
    /// unset.
    #[must_use]
    pub fn new(global_id: &'a str) -> Self {
        Self {
            global_id,
            owner_history: None,
            name: None,
            description: None,
            object_type: None,
            object_placement: None,
            representation: None,
            predefined_type: None,
        }
    }

    /// Sets `owner_history`.
    ///
    /// The `OwnerHistory` reference, when supplied.
    #[must_use]
    pub fn owner_history(mut self, value: EntityId) -> Self {
        self.owner_history = Some(value);
        self
    }

    /// Sets `name`.
    ///
    /// The `Name` attribute, when supplied.
    #[must_use]
    pub fn name(mut self, value: &'a str) -> Self {
        self.name = Some(value);
        self
    }

    /// Sets `description`.
    ///
    /// The `Description` attribute, when supplied.
    #[must_use]
    pub fn description(mut self, value: &'a str) -> Self {
        self.description = Some(value);
        self
    }

    /// Sets `object_type`.
    ///
    /// The `ObjectType` attribute. Required (non-empty) when `predefined_type`
    /// is `AnnotationType::UserDefined`.
    #[must_use]
    pub fn object_type(mut self, value: &'a str) -> Self {
        self.object_type = Some(value);
        self
    }

    /// Sets `object_placement`.
    ///
    /// The `ObjectPlacement` reference, when supplied.
    #[must_use]
    pub fn object_placement(mut self, value: EntityId) -> Self {
        self.object_placement = Some(value);
        self
    }

    /// Sets `representation`.
    ///
    /// The `Representation` reference, when supplied.
    #[must_use]
    pub fn representation(mut self, value: EntityId) -> Self {
        self.representation = Some(value);
        self
    }

    /// Sets `predefined_type`.
    ///
    /// The IFC4X3 `PredefinedType`, when supplied.
    #[must_use]
    pub fn predefined_type(mut self, value: AnnotationType) -> Self {
        self.predefined_type = Some(value);
        self
    }
}

/// Draft input for [`create_text_literal`]: the writable attributes of a new
/// `IfcTextLiteral`.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct TextLiteralDraft<'a> {
    /// The `Literal` attribute; must be non-empty.
    pub literal: &'a str,
    /// The `Placement` reference to an `IfcPlacement`.
    pub placement: EntityId,
    /// The `Path` attribute.
    pub path: TextPath,
}

impl<'a> TextLiteralDraft<'a> {
    /// Starts a draft from its required `literal`, `placement`, `path`; every
    /// other field is unset.
    #[must_use]
    pub fn new(literal: &'a str, placement: EntityId, path: TextPath) -> Self {
        Self {
            literal,
            placement,
            path,
        }
    }
}

/// Draft input for [`create_text_literal_with_extent`]: the writable
/// attributes of a new `IfcTextLiteralWithExtent`.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct TextLiteralWithExtentDraft<'a> {
    /// The `Literal` attribute; must be non-empty.
    pub literal: &'a str,
    /// The `Placement` reference to an `IfcPlacement`.
    pub placement: EntityId,
    /// The `Path` attribute.
    pub path: TextPath,
    /// The `Extent` reference to an `IfcPlanarExtent`.
    pub extent: EntityId,
    /// The `BoxAlignment` attribute.
    pub box_alignment: BoxAlignment,
}

impl<'a> TextLiteralWithExtentDraft<'a> {
    /// Starts a draft from its required `literal`, `placement`, `path`,
    /// `extent`, `box_alignment`; every other field is unset.
    #[must_use]
    pub fn new(
        literal: &'a str,
        placement: EntityId,
        path: TextPath,
        extent: EntityId,
        box_alignment: BoxAlignment,
    ) -> Self {
        Self {
            literal,
            placement,
            path,
            extent,
            box_alignment,
        }
    }
}

/// Draft input for [`create_annotation_fill_area`]: the writable attributes
/// of a new `IfcAnnotationFillArea`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AnnotationFillAreaDraft {
    /// The `OuterBoundary` reference to an `IfcCurve`.
    pub outer_boundary: EntityId,
    /// The `InnerBoundaries` references, if any; an empty list is written
    /// as the IFC null value.
    pub inner_boundaries: Vec<EntityId>,
}

impl AnnotationFillAreaDraft {
    /// Starts a draft from its required `outer_boundary`; every other field is
    /// unset.
    #[must_use]
    pub fn new(outer_boundary: EntityId) -> Self {
        Self {
            outer_boundary,
            inner_boundaries: Vec::new(),
        }
    }

    /// Sets `inner_boundaries`.
    ///
    /// The `InnerBoundaries` references, if any; an empty list is written
    /// as the IFC null value.
    #[must_use]
    pub fn inner_boundaries(mut self, value: Vec<EntityId>) -> Self {
        self.inner_boundaries = value;
        self
    }
}

/// Stage a new `IfcAnnotation` in `tx`. Fails if `GlobalId` does not parse as
/// a GUID, if `PredefinedType` is `USERDEFINED` with an empty `ObjectType`,
/// or if any referenced entity does not resolve to its expected IFC type.
pub fn create_annotation(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: AnnotationDraft<'_>,
) -> StyleResult<EntityId> {
    if ifc_model::guid::Guid::parse(draft.global_id).is_none() {
        return Err(invalid_authoring(
            "IfcAnnotation",
            "GlobalId",
            draft.global_id,
        ));
    }
    if draft.predefined_type == Some(AnnotationType::UserDefined)
        && draft
            .object_type
            .is_none_or(|value| value.trim().is_empty())
    {
        return Err(invalid_authoring(
            "IfcAnnotation",
            "ObjectType",
            "USERDEFINED requires a non-empty ObjectType",
        ));
    }
    validate_optional_ref(tx, model, schema, draft.owner_history, "IfcOwnerHistory")?;
    validate_optional_ref(
        tx,
        model,
        schema,
        draft.object_placement,
        "IfcObjectPlacement",
    )?;
    validate_optional_ref(
        tx,
        model,
        schema,
        draft.representation,
        "IfcProductRepresentation",
    )?;

    let mut values = vec![("GlobalId", text(draft.global_id))];
    optional_reference(&mut values, "OwnerHistory", draft.owner_history);
    optional_text(&mut values, "Name", draft.name);
    optional_text(&mut values, "Description", draft.description);
    optional_text(&mut values, "ObjectType", draft.object_type);
    optional_reference(&mut values, "ObjectPlacement", draft.object_placement);
    optional_reference(&mut values, "Representation", draft.representation);
    if let Some(value) = draft.predefined_type {
        values.push(("PredefinedType", enumeration(value.as_ifc())));
    }
    Ok(tx.create(build_named(schema, "IfcAnnotation", values)?))
}

/// Stage a new `IfcTextLiteral` in `tx`. Fails if `literal` is empty or
/// `placement` does not resolve to an `IfcPlacement`.
pub fn create_text_literal(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: TextLiteralDraft<'_>,
) -> StyleResult<EntityId> {
    if draft.literal.is_empty() {
        return Err(invalid_authoring("IfcTextLiteral", "Literal", "empty"));
    }
    validate_ref(tx, model, schema, draft.placement, "IfcPlacement")?;
    Ok(tx.create(build_named(
        schema,
        "IfcTextLiteral",
        vec![
            ("Literal", text(draft.literal)),
            ("Placement", Value::Ref(draft.placement)),
            ("Path", enumeration(draft.path.as_ifc())),
        ],
    )?))
}

/// Stage a new `IfcTextLiteralWithExtent` in `tx`. Fails if `literal` is
/// empty, or if `placement`/`extent` do not resolve to their expected types.
pub fn create_text_literal_with_extent(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: TextLiteralWithExtentDraft<'_>,
) -> StyleResult<EntityId> {
    if draft.literal.is_empty() {
        return Err(invalid_authoring(
            "IfcTextLiteralWithExtent",
            "Literal",
            "empty",
        ));
    }

    validate_ref(tx, model, schema, draft.placement, "IfcPlacement")?;
    validate_ref(tx, model, schema, draft.extent, "IfcPlanarExtent")?;
    Ok(tx.create(build_named(
        schema,
        "IfcTextLiteralWithExtent",
        vec![
            ("Literal", text(draft.literal)),
            ("Placement", Value::Ref(draft.placement)),
            ("Path", enumeration(draft.path.as_ifc())),
            ("Extent", Value::Ref(draft.extent)),
            ("BoxAlignment", text(draft.box_alignment.as_ifc())),
        ],
    )?))
}

/// Stage a new `IfcAnnotationFillArea` in `tx`. Fails if `outer_boundary` or
/// any of `inner_boundaries` does not resolve to an `IfcCurve`.
pub fn create_annotation_fill_area(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: AnnotationFillAreaDraft,
) -> StyleResult<EntityId> {
    validate_ref(tx, model, schema, draft.outer_boundary, "IfcCurve")?;
    for inner in &draft.inner_boundaries {
        validate_ref(tx, model, schema, *inner, "IfcCurve")?;
    }
    let inner = if draft.inner_boundaries.is_empty() {
        Value::Null
    } else {
        Value::List(draft.inner_boundaries.into_iter().map(Value::Ref).collect())
    };
    Ok(tx.create(build_named(
        schema,
        "IfcAnnotationFillArea",
        vec![
            ("OuterBoundary", Value::Ref(draft.outer_boundary)),
            ("InnerBoundaries", inner),
        ],
    )?))
}

/// Pick whichever spelling of an attribute the target schema declares.
///
/// A handful of attributes were renamed between IFC4 and IFC4X3 without
/// moving slot or changing type: `IfcFillAreaStyle.ModelorDraughting`
/// became `ModelOrDraughting`, and
/// `IfcCurveStyleFontAndScaling.CurveFont` became `CurveStyleFont`.
/// Writing a hardcoded spelling makes the writer refuse its own output
/// under the other schema, so the candidates are resolved against the
/// schema in use. Falls back to the first candidate so an unknown entity
/// still produces the usual `build_named` error rather than a silent miss.
/// Stage an `IfcPlanarExtent`, or its `IfcPlanarBox` subtype.
///
/// The extent is a rectangular presentation area: two sizes and, for
/// the box form, the placement that positions it. Sizes are
/// `IfcLengthMeasure`, which admits negatives in the type system;
/// a negative or non-finite extent describes no area, so it is
/// refused here rather than written for a reader to puzzle over.
///
/// Passing a placement selects `IfcPlanarBox`; omitting it stages the
/// plain extent. The two share slots 0 and 1, so the subtype only ever
/// adds.
///
/// # Errors
///
/// Refuses a non-finite or non-positive `SizeInX`/`SizeInY`, and a
/// `placement` that is not an `IfcAxis2Placement2D`/`3D`.
pub fn create_planar_extent(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    size_in_x: f64,
    size_in_y: f64,
    placement: Option<EntityId>,
) -> StyleResult<EntityId> {
    let entity = if placement.is_some() {
        "IfcPlanarBox"
    } else {
        "IfcPlanarExtent"
    };
    for (attribute, value) in [("SizeInX", size_in_x), ("SizeInY", size_in_y)] {
        if !value.is_finite() || value <= 0.0 {
            return Err(invalid_authoring(entity, attribute, format!("{value}")));
        }
    }
    let mut values = vec![
        ("SizeInX", Value::Real(size_in_x)),
        ("SizeInY", Value::Real(size_in_y)),
    ];
    if let Some(placement) = placement {
        // `IfcAxis2Placement` is a SELECT over the 2D and 3D forms, not
        // a supertype, so `validate_ref`'s `is_a` check rejects both
        // members. Each concrete form is checked instead.
        let placement_type = schema_placement_type(tx, model, placement)?;
        if !matches!(
            placement_type.as_str(),
            "IFCAXIS2PLACEMENT2D" | "IFCAXIS2PLACEMENT3D"
        ) {
            return Err(StyleError::ReferenceType {
                target: placement,
                expected: "IfcAxis2Placement",
                actual: placement_type,
            });
        }
        values.push(("Placement", Value::Ref(placement)));
    }
    Ok(tx.create(build_named(schema, entity, values)?))
}

/// Resolve the type name of a staged or committed entity.
///
/// A `Transaction` cannot be read back, so a reference to an
/// entity created earlier in the same transaction is only visible
/// in its edit list.
fn schema_placement_type(tx: &Transaction, model: &Model, target: EntityId) -> StyleResult<String> {
    tx.edits()
        .iter()
        .rev()
        .find_map(|edit| match edit {
            Edit::Create { id, entity } if *id == target => Some(entity.type_name.to_string()),
            _ => None,
        })
        .or_else(|| model.get(target).map(|e| e.type_name.to_string()))
        .ok_or(StyleError::DanglingReference {
            source_id: EntityId(0),
            target,
        })
}

pub(crate) fn schema_attribute(
    schema: &Schema,
    entity: &str,
    candidates: [&'static str; 2],
) -> &'static str {
    candidates
        .into_iter()
        .find(|candidate| {
            schema
                .attributes(entity)
                .iter()
                .any(|attribute| attribute.name.eq_ignore_ascii_case(candidate))
        })
        .unwrap_or(candidates[0])
}

pub(crate) fn build_named(
    schema: &Schema,
    entity: &'static str,
    values: Vec<(&'static str, Value)>,
) -> StyleResult<Entity> {
    let declared = schema.attributes(entity);
    if declared.is_empty() && schema.entity(entity).is_none() {
        return Err(StyleError::UnsupportedEntity {
            schema: schema.name().to_owned(),
            entity,
        });
    }
    let mut slots = vec![Value::Null; declared.len()];
    let mut filled = vec![false; declared.len()];
    for (name, value) in values {
        let Some(index) = declared
            .iter()
            .position(|attribute| attribute.name.eq_ignore_ascii_case(name))
        else {
            return Err(StyleError::UnsupportedAttribute {
                schema: schema.name().to_owned(),
                entity,
                attribute: name,
            });
        };
        slots[index] = value;
        filled[index] = true;
    }
    for (index, attribute) in declared.iter().enumerate() {
        if !filled[index] && !attribute.optional {
            return Err(StyleError::AuthoringInvalid {
                entity,
                attribute: "required attribute",
                value: attribute.name.clone(),
            });
        }
    }
    Ok(Entity::new(entity.to_ascii_uppercase(), slots))
}

pub(crate) fn validate_ref(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    target: EntityId,
    expected: &'static str,
) -> StyleResult<()> {
    let type_name = tx
        .edits()
        .iter()
        .rev()
        .find_map(|edit| match edit {
            Edit::Create { id, entity } if *id == target => Some(entity.type_name.as_ref()),
            _ => None,
        })
        .or_else(|| model.get(target).map(|entity| entity.type_name.as_ref()))
        .ok_or(StyleError::DanglingReference {
            source_id: EntityId(0),
            target,
        })?;
    if !schema.is_a(type_name, expected) {
        return Err(StyleError::ReferenceType {
            target,
            expected,
            actual: type_name.to_owned(),
        });
    }
    Ok(())
}

pub(crate) fn validate_optional_ref(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    target: Option<EntityId>,
    expected: &'static str,
) -> StyleResult<()> {
    if let Some(target) = target {
        validate_ref(tx, model, schema, target, expected)?;
    }
    Ok(())
}

fn text(value: &str) -> Value {
    Value::Text(Arc::from(value))
}

pub(crate) fn enumeration(value: &str) -> Value {
    Value::Enum(Arc::from(value.to_ascii_uppercase()))
}

fn optional_text(values: &mut Vec<(&'static str, Value)>, name: &'static str, value: Option<&str>) {
    if let Some(value) = value {
        values.push((name, text(value)));
    }
}

fn optional_reference(
    values: &mut Vec<(&'static str, Value)>,
    name: &'static str,
    value: Option<EntityId>,
) {
    if let Some(value) = value {
        values.push((name, Value::Ref(value)));
    }
}

pub(crate) fn invalid_authoring(
    entity: &'static str,
    attribute: &'static str,
    value: impl ToString,
) -> StyleError {
    StyleError::AuthoringInvalid {
        entity,
        attribute,
        value: value.to_string(),
    }
}

pub(crate) fn validate_ratio(
    entity: &'static str,
    attribute: &'static str,
    value: f64,
) -> StyleResult<()> {
    if value.is_finite() && (0.0..=1.0).contains(&value) {
        Ok(())
    } else {
        Err(invalid_authoring(entity, attribute, value))
    }
}