Skip to main content

brep_kernel/io/step/
styles.rs

1//! Geometry COLOUR on export — the ISO 10303-46 presentation entities that give
2//! an exported body or face the colour the document persisted for it.
3//!
4//! This is the WRITE half of `io/step_import/styles.rs`, and it writes exactly
5//! the chain that module reads:
6//!
7//! ```text
8//! MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',(styled …),ctx)
9//!   └ STYLED_ITEM('color',(#style),#item)            item = solid or face
10//!       └ PRESENTATION_STYLE_ASSIGNMENT((#usage))
11//!           └ SURFACE_STYLE_USAGE(.BOTH.,#side)
12//!               └ SURFACE_SIDE_STYLE('',(#fill))
13//!                   └ SURFACE_STYLE_FILL_AREA(#area)
14//!                       └ FILL_AREA_STYLE('',(#colour))
15//!                           └ FILL_AREA_STYLE_COLOUR('',#rgb)
16//!                               └ COLOUR_RGB('',r,g,b)
17//! ```
18//!
19//! `SURFACE_STYLE_FILL_AREA` (the SHADED colour) is written rather than
20//! `SURFACE_STYLE_RENDERING`: it is the form OpenCASCADE's XCAF reader takes
21//! first, the form the corpus fixtures overwhelmingly carry, and the only one
22//! the importer's fill-area lane needs. `.BOTH.` because the kernel shades one
23//! face with one colour and has no side-specific notion to express.
24//!
25//! **The style ENTITIES are shared with the PMI writer** — `write_colour_rgb`,
26//! [`write_style_assignment`] and [`write_styled_item`] here are the single
27//! producers, and `step/pmi.rs` writes its null style, its annotation colour and
28//! its mapped-shape styled item through them. Colour and annotation
29//! presentation stay independent otherwise: a file may carry either, both or
30//! neither, and nothing here reads the PMI block.
31//!
32//! # Where the colour comes from
33//!
34//! [`StepColors`] is the caller's map from SCENE NAME to an 8-bit sRGB triple —
35//! a body name (`Extrude1`, `ACOMP3:Extrude1`) or a face name
36//! (`Extrude1_PX`). The caller owns the policy: the app fills it from the
37//! document's persisted `color` metadata attribute, which is the same attribute
38//! a STEP import stamps and the Info window edits, and adds a name-derived
39//! colour only for a body the viewport is itself colouring by name hash. This
40//! module never invents a colour: a name with no entry gets no style, and an
41//! export with an empty map is byte-for-byte the export that ran before colours
42//! existed.
43//!
44//! The triple is 8-bit because `#RRGGBB` IS the persisted form
45//! (`io/appearance.rs`), so the round trip is exact: `n/255` prints through
46//! [`real`] and reads back through `round(c * 255) = n`.
47
48use std::collections::BTreeMap;
49
50use super::{id_list, real, ProductGeometry, StepWriter};
51
52/// Display colours to write as presentation styles, keyed by SCENE NAME.
53///
54/// Deterministic iteration (a `BTreeMap`) so a file's styled items come out in
55/// the same order every run; lookups are by exact name, with the occurrence
56/// prefixes a structured export resolves through supplied per product.
57#[derive(Clone, Debug, Default)]
58pub struct StepColors {
59    by_name: BTreeMap<String, [u8; 3]>,
60}
61
62impl StepColors {
63    pub fn new() -> Self {
64        Self::default()
65    }
66
67    /// Record one entity's colour. An empty name is ignored (no phantom entry).
68    pub fn set(&mut self, name: &str, rgb: [u8; 3]) {
69        if name.is_empty() {
70            return;
71        }
72        self.by_name.insert(name.to_string(), rgb);
73    }
74
75    /// Nothing to style — the whole writer short-circuits on it.
76    pub fn is_empty(&self) -> bool {
77        self.by_name.is_empty()
78    }
79
80    /// How many names carry a colour.
81    pub fn len(&self) -> usize {
82        self.by_name.len()
83    }
84
85    /// The colour for `name` under the first of `prefixes` that has one.
86    ///
87    /// `prefixes` is the occurrence namespaces a product's geometry is known by
88    /// in the document (`""` for the root, `"ACOMP3:"`, `"ACOMP5:ACOMP1:"` …).
89    /// A part placed several times has ONE written geometry, so it carries
90    /// one colour of its own per entity: the first prefix in the caller's
91    /// order wins, the same "a shared part resolves to the one face" rule the
92    /// PMI writer documents for annotations. (An instance placed by the root in
93    /// another colour gets it as that occurrence's own, `assembly.rs` step 6b.)
94    pub(crate) fn resolve(&self, prefixes: &[String], name: &str) -> Option<[u8; 3]> {
95        prefixes.iter().find_map(|prefix| {
96            if prefix.is_empty() {
97                self.by_name.get(name).copied()
98            } else {
99                self.by_name.get(&format!("{prefix}{name}")).copied()
100            }
101        })
102    }
103}
104
105/// `COLOUR_RGB('',r,g,b)` — the ONE producer, shared with the PMI writer.
106/// Components are 0..=1 sRGB, which is what every consumer of an exchange
107/// colour treats them as (`io/appearance.rs` "Units").
108pub(crate) fn write_colour_rgb(
109    writer: &mut StepWriter,
110    rgb: [f64; 3],
111) -> Result<usize, String> {
112    Ok(writer.add(format!(
113        "COLOUR_RGB('',{},{},{})",
114        real(rgb[0])?,
115        real(rgb[1])?,
116        real(rgb[2])?
117    )))
118}
119
120/// `PRESENTATION_STYLE_ASSIGNMENT((…))` over `elements`, already rendered as a
121/// Part 21 list body (`#12` references, or an inline `NULL_STYLE(.NULL.)`).
122pub(crate) fn write_style_assignment(writer: &mut StepWriter, elements: &str) -> usize {
123    writer.add(format!("PRESENTATION_STYLE_ASSIGNMENT(({elements}))"))
124}
125
126/// `STYLED_ITEM(name,(#style),#item)` — one style assignment on one item.
127pub(crate) fn write_styled_item(
128    writer: &mut StepWriter,
129    name: &str,
130    style: usize,
131    item: usize,
132) -> usize {
133    writer.add(format!("STYLED_ITEM('{name}',(#{style}),#{item})"))
134}
135
136/// The styled items one product's geometry contributes: its coloured bodies
137/// first (in body order), then its coloured faces (in face order).
138///
139/// Bodies before faces is deliberate — it is the precedence a reader that keeps
140/// only one style per shell sees, and it matches the importer's own reading
141/// (a body colour is the body's, a face colour overrides it for that face).
142pub(crate) fn styled_items(
143    geometry: &ProductGeometry,
144    colors: &StepColors,
145    prefixes: &[String],
146) -> Vec<(usize, [u8; 3])> {
147    styled_items_split(geometry, colors, prefixes, prefixes)
148}
149
150/// [`styled_items`] with the solids resolved through `solid_prefixes` and the
151/// faces through `face_prefixes`.
152pub(crate) fn styled_items_split(
153    geometry: &ProductGeometry,
154    colors: &StepColors,
155    solid_prefixes: &[String],
156    face_prefixes: &[String],
157) -> Vec<(usize, [u8; 3])> {
158    let mut items = Vec::new();
159    for (name, id) in &geometry.solids {
160        if let Some(rgb) = colors.resolve(solid_prefixes, name) {
161            items.push((*id, rgb));
162        }
163    }
164    for (name, id) in &geometry.faces {
165        if let Some(rgb) = colors.resolve(face_prefixes, name) {
166            items.push((*id, rgb));
167        }
168    }
169    items
170}
171
172/// Write the file's geometry styles: one style chain per DISTINCT colour, one
173/// `STYLED_ITEM` per entity, and one
174/// `MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION` gathering them.
175///
176/// Returns how many styled items were written — `0` for an empty `items`, in
177/// which case NOTHING is emitted (not an empty presentation representation,
178/// which several readers reject and which would change every uncoloured file).
179pub(crate) fn write_geometry_styles(
180    writer: &mut StepWriter,
181    geometry_context: usize,
182    items: &[(usize, [u8; 3])],
183) -> Result<usize, String> {
184    Ok(write_geometry_styles_keyed(writer, geometry_context, items)?.len())
185}
186
187/// [`write_geometry_styles`], returning each item's `STYLED_ITEM` id (item →
188/// styled item), so an occurrence's override can name the style it overrides.
189pub(crate) fn write_geometry_styles_keyed(
190    writer: &mut StepWriter,
191    geometry_context: usize,
192    items: &[(usize, [u8; 3])],
193) -> Result<BTreeMap<usize, usize>, String> {
194    if items.is_empty() {
195        return Ok(BTreeMap::new());
196    }
197    // One chain per distinct colour, minted on first use so entity order
198    // follows `items` order. Keyed on the 8-bit triple, which IS the colour's
199    // persisted identity.
200    let mut assignments: BTreeMap<[u8; 3], usize> = BTreeMap::new();
201    let mut styled = Vec::with_capacity(items.len());
202    let mut keyed = BTreeMap::new();
203    for (item, rgb) in items {
204        let assignment = match assignments.get(rgb) {
205            Some(id) => *id,
206            None => {
207                let id = write_surface_style(writer, *rgb)?;
208                assignments.insert(*rgb, id);
209                id
210            }
211        };
212        let id = write_styled_item(writer, "color", assignment, *item);
213        styled.push(id);
214        keyed.entry(*item).or_insert(id);
215    }
216    writer.add(format!(
217        "MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',{},#{geometry_context})",
218        id_list(&styled)
219    ));
220    Ok(keyed)
221}
222
223/// Write each occurrence's own colour: for every `(item, relationship, rgb)`,
224/// a `CONTEXT_DEPENDENT_OVER_RIDING_STYLED_ITEM` on the part's `item` in the
225/// context of the occurrence's `REPRESENTATION_RELATIONSHIP` (the one its
226/// `CONTEXT_DEPENDENT_SHAPE_REPRESENTATION` places the part through), over the
227/// item's own style in `base`. An item with no style of its own gets one that
228/// says so (`NULL_STYLE`), so the override has a style to name and the part's
229/// other instances stay uncoloured. Gathered in a presentation representation
230/// of their own; returns how many styled items were written.
231pub(crate) fn write_occurrence_styles(
232    writer: &mut StepWriter,
233    geometry_context: usize,
234    base: &BTreeMap<usize, usize>,
235    items: &[(usize, usize, [u8; 3])],
236) -> Result<usize, String> {
237    if items.is_empty() {
238        return Ok(0);
239    }
240    let mut assignments: BTreeMap<[u8; 3], usize> = BTreeMap::new();
241    let mut unstyled: BTreeMap<usize, usize> = BTreeMap::new();
242    let mut null_style = None;
243    let mut styled = Vec::with_capacity(items.len());
244    for (item, relationship, rgb) in items {
245        let over_ridden = match base.get(item).or_else(|| unstyled.get(item)) {
246            Some(id) => *id,
247            None => {
248                let null = *null_style.get_or_insert_with(|| write_style_assignment(writer, "NULL_STYLE(.NULL.)"));
249                let id = write_styled_item(writer, "", null, *item);
250                unstyled.insert(*item, id);
251                styled.push(id);
252                id
253            }
254        };
255        let assignment = match assignments.get(rgb) {
256            Some(id) => *id,
257            None => {
258                let id = write_surface_style(writer, *rgb)?;
259                assignments.insert(*rgb, id);
260                id
261            }
262        };
263        styled.push(writer.add(format!(
264            "CONTEXT_DEPENDENT_OVER_RIDING_STYLED_ITEM('color',(#{assignment}),#{item},#{over_ridden},(#{relationship}))"
265        )));
266    }
267    writer.add(format!(
268        "MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',{},#{geometry_context})",
269        id_list(&styled)
270    ));
271    Ok(styled.len())
272}
273
274/// One colour's whole chain, `COLOUR_RGB` up to the
275/// `PRESENTATION_STYLE_ASSIGNMENT` a `STYLED_ITEM` names.
276fn write_surface_style(writer: &mut StepWriter, rgb: [u8; 3]) -> Result<usize, String> {
277    let colour = write_colour_rgb(
278        writer,
279        [
280            rgb[0] as f64 / 255.0,
281            rgb[1] as f64 / 255.0,
282            rgb[2] as f64 / 255.0,
283        ],
284    )?;
285    let fill_colour = writer.add(format!("FILL_AREA_STYLE_COLOUR('',#{colour})"));
286    let fill_area = writer.add(format!("FILL_AREA_STYLE('',(#{fill_colour}))"));
287    let fill_style = writer.add(format!("SURFACE_STYLE_FILL_AREA(#{fill_area})"));
288    let side_style = writer.add(format!("SURFACE_SIDE_STYLE('',(#{fill_style}))"));
289    let usage = writer.add(format!("SURFACE_STYLE_USAGE(.BOTH.,#{side_style})"));
290    Ok(write_style_assignment(writer, &format!("#{usage}")))
291}
292