Skip to main content

ifc_style/assignment/
colour.rs

1//! The surface colour of a representation item or a material (#449);
2//! see [`StyleIndex`] for the precedence and its citations.
3
4use std::borrow::Cow;
5
6use ifc_model::{EntityId, ReverseIndex};
7
8use crate::error::{StyleError, StyleResult};
9use crate::StyleView;
10
11/// The colour a surface is painted with, and where it came from.
12#[derive(Debug, Clone, PartialEq)]
13#[non_exhaustive]
14pub struct SurfaceColour {
15    /// `SurfaceColour`: red, green and blue, each in `[0, 1]`.
16    pub rgb: [f64; 3],
17    /// `Transparency` in `[0, 1]`, 0 opaque. `None` when the file states
18    /// none, which the standard reads as opaque; IFC2X3 states it on
19    /// `IfcSurfaceStyleRendering` only.
20    pub transparency: Option<f64>,
21    /// The `IfcSurfaceStyle` the colour is read from.
22    pub surface_style: EntityId,
23    /// Where the style was assigned.
24    pub source: ColourSource,
25}
26
27/// How a surface style reached the surface.
28#[derive(Debug, Clone, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum ColourSource {
31    /// An `IfcStyledItem` on the representation item; carries its id.
32    StyledItem(EntityId),
33    /// An `IfcPresentationLayerWithStyle` the item is on; carries its id.
34    PresentationLayer(EntityId),
35    /// The material's `IfcMaterialDefinitionRepresentation`.
36    Material {
37        /// The `IfcMaterial`.
38        material: EntityId,
39        /// The item-less `IfcStyledItem` in its `IfcStyledRepresentation`.
40        styled_item: EntityId,
41    },
42    /// A material set whose materials all state this colour (#603): the
43    /// layer, profile or constituent set (or the usage) the product is made
44    /// of. Which one of them paints the product is not stated, so the colour
45    /// is neither of theirs alone; a single-material set is
46    /// [`ColourSource::Material`]. Set by the `openbim-ifc` facade, which
47    /// joins materials to products; [`StyleIndex`] itself reads one material.
48    MaterialSet {
49        /// The `IfcMaterialLayerSet`, `IfcMaterialProfileSet`,
50        /// `IfcMaterialConstituentSet` or `IfcMaterialList`, or a usage of
51        /// one (`IfcMaterialLayerSetUsage`, `IfcMaterialProfileSetUsage`
52        /// and its `Tapering` subtype) the materials belong to.
53        definition: EntityId,
54        /// The materials of the set that colour the item: every one, or the
55        /// constituents its shape aspects name (ascending id, distinct).
56        materials: Vec<EntityId>,
57    },
58}
59
60/// Every style assignment of a model, indexed once, for colour lookups by
61/// item and by material.
62///
63/// [`StyleView::resolve_item_style`](crate::StyleView::resolve_item_style)
64/// scans the model per item, which is fine for one item and quadratic for
65/// every item of every product; the index finds an item's `IfcStyledItem`s
66/// and layers, and a material's `IfcMaterialDefinitionRepresentation`s,
67/// through the entities that reference them (#608). A malformed record is
68/// refused by the lookups that reach it, not by `new`. Several records on
69/// one item or material are read in ascending id.
70///
71/// # Precedence
72///
73/// A viewer paints a surface with the colour of an `IfcSurfaceStyle`'s
74/// `IfcSurfaceStyleShading` (or its `IfcSurfaceStyleRendering` subtype).
75/// The style reaches a representation item in one of three ways, and
76/// [`StyleIndex`] answers each of them separately:
77///
78/// 1. **The item.** An `IfcStyledItem` whose `Item` is the representation
79///    item ([`StyleIndex::item_colour`], [`ColourSource::StyledItem`]).
80/// 2. **Its presentation layer.** An `IfcPresentationLayerWithStyle` whose
81///    `AssignedItems` include it ([`StyleIndex::item_colour`],
82///    [`ColourSource::PresentationLayer`]).
83/// 3. **Its material.** The `IfcMaterialDefinitionRepresentation` of the
84///    `IfcMaterial` the element is made of: its `IfcStyledRepresentation`s
85///    hold `IfcStyledItem`s with no `Item` whose styles present the
86///    material ([`StyleIndex::material_colour`], [`ColourSource::Material`]).
87///
88/// The precedence is that order. The item over the layer is the
89/// standard's: "If the styled item has style information assigned [...]
90/// then it overrides the style provided by the
91/// IfcPresentationLayerAssignmentWithStyle" (IFC4 ADD2 TC1,
92/// `IfcPresentationLayerWithStyle`, second note), and it is the cascade
93/// [`StyleView::resolve_item_style`](crate::StyleView::resolve_item_style)
94/// already applies. The material comes last because it is the general
95/// case: `IfcStyledItem` "holds presentation style information for
96/// products, either explicitly for an IfcGeometricRepresentationItem being
97/// part of an IfcShapeRepresentation assigned to a product, or by assigning
98/// presentation information to IfcMaterial being assigned as other
99/// representation for a product" (IFC4 ADD2 TC1, `IfcStyledItem`), and
100/// `IfcMaterialDefinitionRepresentation` "defines presentation information
101/// relating to IfcMaterial" used at element occurrences and types (IFC4
102/// ADD2 TC1, `IfcMaterialDefinitionRepresentation`; the entity is new in
103/// IFC2x3 and unchanged in IFC4X3 ADD2). The standard states no order
104/// between a layer style and a material style; this one is IfcOpenShell's
105/// (`mapping.cpp`, `find_style` before the material fallback) and the
106/// one #449 fixes.
107///
108/// The precedence is per colour, not per style: a level that states no
109/// surface colour (a styled item with only a curve style, say) does not
110/// hide the next one. The layer note says a styled item on a layer
111/// "inherits the style information from the layer", omitting "its own
112/// style information" for the styles it does not state.
113///
114/// Which `IfcMaterial` an element is made of (a layer of a set, a
115/// constituent) is the material domain's question, not this crate's: the
116/// caller resolves it and passes the material here. The `openbim-ifc`
117/// facade joins the two (`product_colour`).
118#[derive(Debug, Clone)]
119pub struct StyleIndex<'m, 's> {
120    view: StyleView<'m, 's>,
121    /// The references held by the style records: the model's own reverse
122    /// index when something built it, else one over the records of the
123    /// three kinds below only.
124    referrers: Cow<'m, ReverseIndex>,
125    /// `IfcStyledItem.Item`; `None` when the release lacks the entity.
126    item_slot: Option<usize>,
127    /// `IfcPresentationLayerAssignment.AssignedItems`.
128    layer_slot: Option<usize>,
129    /// `IfcMaterialDefinitionRepresentation.RepresentedMaterial`; `None` in
130    /// a release without the entity.
131    material_slot: Option<usize>,
132    /// `IfcMaterialDefinitionRepresentation` and its subtypes in the release.
133    definition_types: Vec<&'s str>,
134}
135
136/// The supertypes of the records a [`StyleIndex`] reads.
137const STYLED_ITEM: &str = "IfcStyledItem";
138const LAYER: &str = "IfcPresentationLayerAssignment";
139const DEFINITION: &str = "IfcMaterialDefinitionRepresentation";
140
141impl<'m, 's> StyleIndex<'m, 's> {
142    /// Index `view`'s model for style lookups.
143    ///
144    /// Uses the model's reverse index if something built it; otherwise
145    /// reads once the `IfcStyledItem`, `IfcPresentationLayerAssignment` and
146    /// `IfcMaterialDefinitionRepresentation` records and nothing else, and
147    /// keeps no index behind (#608). The cost of a lookup is the records
148    /// that name what it asks about, not the model.
149    ///
150    /// # Errors
151    ///
152    /// None today: the signature keeps the `Result` of the version that
153    /// validated every assignment here. A malformed
154    /// `IfcStyledItem.Item`, `IfcPresentationLayerAssignment.AssignedItems`
155    /// or `IfcMaterialDefinitionRepresentation.RepresentedMaterial` is
156    /// raised by the lookup it reaches, with the error
157    /// [`StyleView::resolve_item_style`](crate::StyleView::resolve_item_style)
158    /// gives.
159    #[allow(clippy::unnecessary_wraps)]
160    pub fn new(view: StyleView<'m, 's>) -> StyleResult<Self> {
161        let schema = view.schema;
162        let slot = |entity: &str, attribute: &str| {
163            schema.entity(entity)?;
164            schema
165                .attributes(entity)
166                .iter()
167                .position(|a| a.name.eq_ignore_ascii_case(attribute))
168        };
169        let referrers = view.model.reverse_index_if_built().map_or_else(
170            || {
171                let records = [STYLED_ITEM, LAYER, DEFINITION]
172                    .into_iter()
173                    .filter(|name| schema.entity(name).is_some())
174                    .flat_map(|name| std::iter::once(name).chain(schema.subtypes(name)))
175                    .flat_map(|name| view.model.ids_of_type(name).iter().copied());
176                Cow::Owned(ReverseIndex::build_from(view.model, records))
177            },
178            Cow::Borrowed,
179        );
180        let definition_types = if schema.entity(DEFINITION).is_some() {
181            std::iter::once(DEFINITION)
182                .chain(schema.subtypes(DEFINITION))
183                .collect()
184        } else {
185            Vec::new()
186        };
187        Ok(Self {
188            view,
189            referrers,
190            definition_types,
191            item_slot: slot(STYLED_ITEM, "Item"),
192            layer_slot: slot(LAYER, "AssignedItems"),
193            material_slot: slot(DEFINITION, "RepresentedMaterial"),
194        })
195    }
196
197    /// The records of `supertype` that hold `target` in `slot`, ascending by
198    /// id: the candidates a lookup then projects.
199    fn named_in(
200        &self,
201        target: EntityId,
202        slot: Option<usize>,
203        supertype: &'static str,
204    ) -> Vec<EntityId> {
205        let Some(slot) = slot else {
206            return Vec::new();
207        };
208        self.referrers
209            .referrers(target)
210            .iter()
211            .filter(|r| r.slot == slot)
212            .filter(|r| {
213                self.view
214                    .model
215                    .get(r.from)
216                    .is_some_and(|e| self.view.schema.is_a(&e.type_name, supertype))
217            })
218            .map(|r| r.from)
219            .collect()
220    }
221
222    /// The `IfcStyledItem`s whose `Item` is `item`, ascending.
223    fn styled_items_of(&self, item: EntityId) -> StyleResult<Vec<EntityId>> {
224        let mut found = Vec::new();
225        for styled in self.named_in(item, self.item_slot, STYLED_ITEM) {
226            if self.view.styled_item(styled)?.item()? == Some(item) {
227                found.push(styled);
228            }
229        }
230        Ok(found)
231    }
232
233    /// The layer assignments listing `item`, ascending.
234    fn layers_of(&self, item: EntityId) -> StyleResult<Vec<EntityId>> {
235        let mut found = Vec::new();
236        for layer in self.named_in(item, self.layer_slot, LAYER) {
237            if self
238                .view
239                .presentation_layer(layer)?
240                .assigned_items()?
241                .contains(&item)
242            {
243                found.push(layer);
244            }
245        }
246        Ok(found)
247    }
248
249    /// The `IfcMaterialDefinitionRepresentation`s of `material`, ascending.
250    pub(super) fn definitions_of(&self, material: EntityId) -> StyleResult<Vec<EntityId>> {
251        let named = self.named_definitions(material);
252        let mut found = Vec::new();
253        for definition in named {
254            let represented = self
255                .view
256                .record(definition, DEFINITION)?
257                .required_ref("RepresentedMaterial", "IfcMaterial")?;
258            if represented == material {
259                found.push(definition);
260            }
261        }
262        Ok(found)
263    }
264
265    /// The definitions holding `material` in `RepresentedMaterial`. A
266    /// material many relationships reference (every wall of a model made of
267    /// it) has far more referrers than the model has definitions: then the
268    /// definitions are scanned instead, with the same answer.
269    fn named_definitions(&self, material: EntityId) -> Vec<EntityId> {
270        let Some(slot) = self.material_slot else {
271            return Vec::new();
272        };
273        let model = self.view.model;
274        let definitions: usize = self
275            .definition_types
276            .iter()
277            .map(|name| model.ids_of_type(name).len())
278            .sum();
279        if definitions >= self.referrers.referrers(material).len() {
280            return self.named_in(material, self.material_slot, DEFINITION);
281        }
282        let mut found: Vec<EntityId> = self
283            .definition_types
284            .iter()
285            .flat_map(|name| model.ids_of_type(name).iter().copied())
286            .filter(|&id| {
287                model
288                    .get(id)
289                    .and_then(|e| e.attributes.get(slot))
290                    .is_some_and(|value| {
291                        let mut hit = false;
292                        value.for_each_ref(&mut |target| hit |= target == material);
293                        hit
294                    })
295            })
296            .collect();
297        found.sort_unstable();
298        found.dedup();
299        found
300    }
301
302    /// The view the index reads through.
303    #[must_use]
304    pub fn view(&self) -> StyleView<'m, 's> {
305        self.view
306    }
307
308    /// The surface colour `item` states itself: its own `IfcStyledItem`
309    /// first, then its presentation layers (see [the precedence](StyleIndex#precedence)).
310    /// `None` when neither states a surface colour.
311    ///
312    /// # Errors
313    ///
314    /// [`StyleError::AmbiguousStyleAssignment`] for two `IfcStyledItem`s on
315    /// `item`, as `resolve_item_style` refuses it;
316    /// [`StyleError::AmbiguousSurfaceColour`] when one styled item, or the
317    /// layers together, state two different surface colours; and the
318    /// projection errors of a malformed style.
319    pub fn item_colour(&self, item: EntityId) -> StyleResult<Option<SurfaceColour>> {
320        let direct = self.styled_items_of(item)?;
321        if !direct.is_empty() {
322            if direct.len() > 1 {
323                return Err(StyleError::AmbiguousStyleAssignment {
324                    item,
325                    count: direct.len(),
326                });
327            }
328            let styled = direct[0];
329            let styles = self
330                .view
331                .flatten_assignments(self.view.styled_item(styled)?.styles()?)?;
332            if let Some(colour) =
333                self.unique_colour(styled, &styles, ColourSource::StyledItem(styled))?
334            {
335                return Ok(Some(colour));
336            }
337        }
338        let mut found = Vec::new();
339        for layer in self.layers_of(item)? {
340            let styles = self
341                .view
342                .flatten_assignments(self.view.presentation_layer(layer)?.layer_styles()?)?;
343            if let Some(colour) =
344                self.unique_colour(layer, &styles, ColourSource::PresentationLayer(layer))?
345            {
346                found.push(colour);
347            }
348        }
349        agree(item, found)
350    }
351
352    /// The surface colour `material`'s `IfcMaterialDefinitionRepresentation`
353    /// states, over every one of its `IfcStyledRepresentation`s (one per
354    /// representation context). `None` when the material has no
355    /// representation or none states a surface colour.
356    ///
357    /// # Errors
358    ///
359    /// [`StyleError::AmbiguousSurfaceColour`] when its styled items state
360    /// two different surface colours (in two contexts, say);
361    /// [`StyleError::ReferenceType`] for a representation that is no
362    /// `IfcStyledRepresentation` or an item that is no `IfcStyledItem`
363    /// (both rules of the standard); and the projection errors of a
364    /// malformed style.
365    pub fn material_colour(&self, material: EntityId) -> StyleResult<Option<SurfaceColour>> {
366        let mut found = Vec::new();
367        for definition in self.definitions_of(material)? {
368            let representations = self
369                .view
370                .record(definition, "IfcMaterialDefinitionRepresentation")?
371                .required_refs("Representations", "IfcStyledRepresentation", 1, None)?;
372            for representation in representations {
373                let items = self
374                    .view
375                    .record(representation, "IfcStyledRepresentation")?
376                    .required_refs("Items", "IfcStyledItem", 1, None)?;
377                for styled in items {
378                    let styles = self
379                        .view
380                        .flatten_assignments(self.view.styled_item(styled)?.styles()?)?;
381                    let source = ColourSource::Material {
382                        material,
383                        styled_item: styled,
384                    };
385                    if let Some(colour) = self.unique_colour(styled, &styles, source)? {
386                        found.push(colour);
387                    }
388                }
389            }
390        }
391        agree(material, found)
392    }
393
394    /// The one surface colour among `styles`, assigned by `owner`.
395    fn unique_colour(
396        &self,
397        owner: EntityId,
398        styles: &[EntityId],
399        source: ColourSource,
400    ) -> StyleResult<Option<SurfaceColour>> {
401        let mut found = Vec::new();
402        for &style in styles {
403            if let Some((rgb, transparency)) = self.surface_colour(style)? {
404                found.push(SurfaceColour {
405                    rgb,
406                    transparency,
407                    surface_style: style,
408                    source: source.clone(),
409                });
410            }
411        }
412        agree(owner, found)
413    }
414
415    /// `style`'s shading colour and transparency, when it is an
416    /// `IfcSurfaceStyle` with an `IfcSurfaceStyleShading` element.
417    fn surface_colour(&self, style: EntityId) -> StyleResult<Option<([f64; 3], Option<f64>)>> {
418        let view = self.view;
419        let entity = view
420            .model
421            .get(style)
422            .ok_or(StyleError::UnknownEntity { id: style })?;
423        if !view.schema.is_a(&entity.type_name, "IfcSurfaceStyle") {
424            return Ok(None);
425        }
426        for element in view.surface_style(style)?.elements()? {
427            let Some(element_entity) = view.model.get(element) else {
428                continue;
429            };
430            if !view
431                .schema
432                .is_a(&element_entity.type_name, "IfcSurfaceStyleShading")
433            {
434                continue;
435            }
436            let shading = view.surface_style_shading(element)?;
437            let rgb = view.colour_rgb(shading.surface_colour()?)?.channels()?;
438            // IFC2X3 states `Transparency` on the rendering subtype only;
439            // IFC4 moved it up to the shading. Read it where the release
440            // declares it.
441            let transparency = if view
442                .schema
443                .is_a(&element_entity.type_name, "IfcSurfaceStyleRendering")
444            {
445                view.surface_style_rendering(element)?.transparency()?
446            } else {
447                shading.transparency()?
448            };
449            return Ok(Some((rgb, transparency)));
450        }
451        Ok(None)
452    }
453}
454
455/// The first of `found` when every colour agrees (same RGB and
456/// transparency), `None` when empty, else ambiguous.
457fn agree(owner: EntityId, found: Vec<SurfaceColour>) -> StyleResult<Option<SurfaceColour>> {
458    let Some(first) = found.first().cloned() else {
459        return Ok(None);
460    };
461    if found
462        .iter()
463        .all(|c| c.rgb == first.rgb && c.transparency == first.transparency)
464    {
465        return Ok(Some(first));
466    }
467    let mut styles: Vec<EntityId> = found.iter().map(|c| c.surface_style).collect();
468    styles.sort_unstable();
469    styles.dedup();
470    Err(StyleError::AmbiguousSurfaceColour { owner, styles })
471}