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    /// The colour recorded for `name`.
68    pub fn get(&self, name: &str) -> Option<[u8; 3]> {
69        self.by_name.get(name).copied()
70    }
71
72    /// Record one entity's colour. An empty name is ignored (no phantom entry).
73    pub fn set(&mut self, name: &str, rgb: [u8; 3]) {
74        if name.is_empty() {
75            return;
76        }
77        self.by_name.insert(name.to_string(), rgb);
78    }
79
80    /// Nothing to style — the whole writer short-circuits on it.
81    pub fn is_empty(&self) -> bool {
82        self.by_name.is_empty()
83    }
84
85    /// How many names carry a colour.
86    pub fn len(&self) -> usize {
87        self.by_name.len()
88    }
89
90    /// The colour for `name` under the first of `prefixes` that has one.
91    ///
92    /// `prefixes` is the occurrence namespaces a product's geometry is known by
93    /// in the document (`""` for the root, `"ACOMP3:"`, `"ACOMP5:ACOMP1:"` …).
94    /// A part placed several times has ONE written geometry, so it carries
95    /// one colour of its own per entity: the first prefix in the caller's
96    /// order wins, the same "a shared part resolves to the one face" rule the
97    /// PMI writer documents for annotations. (An instance placed by the root in
98    /// another colour gets it as that occurrence's own, `assembly.rs` step 6b.)
99    pub(crate) fn resolve(&self, prefixes: &[String], name: &str) -> Option<[u8; 3]> {
100        prefixes.iter().find_map(|prefix| {
101            if prefix.is_empty() {
102                self.by_name.get(name).copied()
103            } else {
104                self.by_name.get(&format!("{prefix}{name}")).copied()
105            }
106        })
107    }
108}
109
110/// `COLOUR_RGB('',r,g,b)` — the ONE producer, shared with the PMI writer.
111/// Components are 0..=1 sRGB, which is what every consumer of an exchange
112/// colour treats them as (`io/appearance.rs` "Units").
113pub(crate) fn write_colour_rgb(
114    writer: &mut StepWriter,
115    rgb: [f64; 3],
116) -> Result<usize, String> {
117    Ok(writer.add(format!(
118        "COLOUR_RGB('',{},{},{})",
119        real(rgb[0])?,
120        real(rgb[1])?,
121        real(rgb[2])?
122    )))
123}
124
125/// `PRESENTATION_STYLE_ASSIGNMENT((…))` over `elements`, already rendered as a
126/// Part 21 list body (`#12` references, or an inline `NULL_STYLE(.NULL.)`).
127pub(crate) fn write_style_assignment(writer: &mut StepWriter, elements: &str) -> usize {
128    writer.add(format!("PRESENTATION_STYLE_ASSIGNMENT(({elements}))"))
129}
130
131/// `STYLED_ITEM(name,(#style),#item)` — one style assignment on one item.
132pub(crate) fn write_styled_item(
133    writer: &mut StepWriter,
134    name: &str,
135    style: usize,
136    item: usize,
137) -> usize {
138    writer.add(format!("STYLED_ITEM('{name}',(#{style}),#{item})"))
139}
140
141/// The styled items one product's geometry contributes: its coloured bodies
142/// first (in body order), then its coloured faces (in face order).
143///
144/// Bodies before faces is deliberate — it is the precedence a reader that keeps
145/// only one style per shell sees, and it matches the importer's own reading
146/// (a body colour is the body's, a face colour overrides it for that face).
147pub(crate) fn styled_items(
148    geometry: &ProductGeometry,
149    colors: &StepColors,
150    prefixes: &[String],
151) -> Vec<(usize, [u8; 3])> {
152    styled_items_split(geometry, colors, prefixes, prefixes)
153}
154
155/// [`styled_items`] with the solids resolved through `solid_prefixes` and the
156/// faces through `face_prefixes`.
157pub(crate) fn styled_items_split(
158    geometry: &ProductGeometry,
159    colors: &StepColors,
160    solid_prefixes: &[String],
161    face_prefixes: &[String],
162) -> Vec<(usize, [u8; 3])> {
163    let mut items = Vec::new();
164    for (name, id) in &geometry.solids {
165        if let Some(rgb) = colors.resolve(solid_prefixes, name) {
166            items.push((*id, rgb));
167        }
168    }
169    for (name, id) in &geometry.faces {
170        if let Some(rgb) = colors.resolve(face_prefixes, name) {
171            items.push((*id, rgb));
172        }
173    }
174    items
175}
176
177/// Write the file's geometry styles: one style chain per DISTINCT colour, one
178/// `STYLED_ITEM` per entity, and one
179/// `MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION` gathering them.
180///
181/// Returns how many styled items were written — `0` for an empty `items`, in
182/// which case NOTHING is emitted (not an empty presentation representation,
183/// which several readers reject and which would change every uncoloured file).
184pub(crate) fn write_geometry_styles(
185    writer: &mut StepWriter,
186    geometry_context: usize,
187    items: &[(usize, [u8; 3])],
188) -> Result<usize, String> {
189    Ok(write_geometry_styles_keyed(writer, geometry_context, items)?.len())
190}
191
192/// [`write_geometry_styles`], returning each item's `STYLED_ITEM` id (item →
193/// styled item), so an occurrence's override can name the style it overrides.
194pub(crate) fn write_geometry_styles_keyed(
195    writer: &mut StepWriter,
196    geometry_context: usize,
197    items: &[(usize, [u8; 3])],
198) -> Result<BTreeMap<usize, usize>, String> {
199    if items.is_empty() {
200        return Ok(BTreeMap::new());
201    }
202    // One chain per distinct colour, minted on first use so entity order
203    // follows `items` order. Keyed on the 8-bit triple, which IS the colour's
204    // persisted identity.
205    let mut assignments: BTreeMap<[u8; 3], usize> = BTreeMap::new();
206    let mut styled = Vec::with_capacity(items.len());
207    let mut keyed = BTreeMap::new();
208    for (item, rgb) in items {
209        let assignment = match assignments.get(rgb) {
210            Some(id) => *id,
211            None => {
212                let id = write_surface_style(writer, *rgb)?;
213                assignments.insert(*rgb, id);
214                id
215            }
216        };
217        let id = write_styled_item(writer, "color", assignment, *item);
218        styled.push(id);
219        keyed.entry(*item).or_insert(id);
220    }
221    writer.add(format!(
222        "MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',{},#{geometry_context})",
223        id_list(&styled)
224    ));
225    Ok(keyed)
226}
227
228/// Write each occurrence's own colour: for every `(item, relationship, rgb)`,
229/// a `CONTEXT_DEPENDENT_OVER_RIDING_STYLED_ITEM` on the part's `item` in the
230/// context of the occurrence's `REPRESENTATION_RELATIONSHIP` (the one its
231/// `CONTEXT_DEPENDENT_SHAPE_REPRESENTATION` places the part through), over the
232/// item's own style in `base`. An item with no style of its own gets one that
233/// says so (`NULL_STYLE`), so the override has a style to name and the part's
234/// other instances stay uncoloured. Gathered in a presentation representation
235/// of their own; returns how many styled items were written.
236pub(crate) fn write_occurrence_styles(
237    writer: &mut StepWriter,
238    geometry_context: usize,
239    base: &BTreeMap<usize, usize>,
240    items: &[(usize, usize, [u8; 3])],
241) -> Result<usize, String> {
242    if items.is_empty() {
243        return Ok(0);
244    }
245    let mut assignments: BTreeMap<[u8; 3], usize> = BTreeMap::new();
246    let mut unstyled: BTreeMap<usize, usize> = BTreeMap::new();
247    let mut null_style = None;
248    let mut styled = Vec::with_capacity(items.len());
249    for (item, relationship, rgb) in items {
250        let over_ridden = match base.get(item).or_else(|| unstyled.get(item)) {
251            Some(id) => *id,
252            None => {
253                let null = *null_style.get_or_insert_with(|| write_style_assignment(writer, "NULL_STYLE(.NULL.)"));
254                let id = write_styled_item(writer, "", null, *item);
255                unstyled.insert(*item, id);
256                styled.push(id);
257                id
258            }
259        };
260        let assignment = match assignments.get(rgb) {
261            Some(id) => *id,
262            None => {
263                let id = write_surface_style(writer, *rgb)?;
264                assignments.insert(*rgb, id);
265                id
266            }
267        };
268        styled.push(writer.add(format!(
269            "CONTEXT_DEPENDENT_OVER_RIDING_STYLED_ITEM('color',(#{assignment}),#{item},#{over_ridden},(#{relationship}))"
270        )));
271    }
272    writer.add(format!(
273        "MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',{},#{geometry_context})",
274        id_list(&styled)
275    ));
276    Ok(styled.len())
277}
278
279/// One colour's whole chain, `COLOUR_RGB` up to the
280/// `PRESENTATION_STYLE_ASSIGNMENT` a `STYLED_ITEM` names.
281fn write_surface_style(writer: &mut StepWriter, rgb: [u8; 3]) -> Result<usize, String> {
282    let colour = write_colour_rgb(
283        writer,
284        [
285            rgb[0] as f64 / 255.0,
286            rgb[1] as f64 / 255.0,
287            rgb[2] as f64 / 255.0,
288        ],
289    )?;
290    let fill_colour = writer.add(format!("FILL_AREA_STYLE_COLOUR('',#{colour})"));
291    let fill_area = writer.add(format!("FILL_AREA_STYLE('',(#{fill_colour}))"));
292    let fill_style = writer.add(format!("SURFACE_STYLE_FILL_AREA(#{fill_area})"));
293    let side_style = writer.add(format!("SURFACE_SIDE_STYLE('',(#{fill_style}))"));
294    let usage = writer.add(format!("SURFACE_STYLE_USAGE(.BOTH.,#{side_style})"));
295    Ok(write_style_assignment(writer, &format!("#{usage}")))
296}
297