Skip to main content

brep_render/render/
scene_sync.rs

1use super::*;
2
3/// An AUX edge's width at rest, in CSS px ([`GlobalStyles::edge_aux`]).
4const AUX_EDGE_WIDTH_PX: f32 = 1.0;
5
6impl RenderCore {
7    /// The base face color of one solid under the active settings, in LINEAR
8    /// space (converted with f64 precision so artifact bytes stay stable); a
9    /// display with an `opacity` carries it as the alpha (the blended pass
10    /// reads it, the opaque pass skips such a solid).
11    fn face_base_color(solid: &SolidDisplay, settings: &RenderSettings) -> Rgba {
12        let mut color = Self::face_base_color_opaque(solid, settings);
13        if solid.opacity.is_some() || solid.model_opacity.is_some() {
14            color[3] = solid.base_opacity();
15        }
16        color
17    }
18
19    fn face_base_color_opaque(solid: &SolidDisplay, settings: &RenderSettings) -> Rgba {
20        if let Some(rgb) = solid.color_override {
21            return Self::opaque_linear(rgb);
22        }
23        match settings.face_color_mode {
24            FaceColorMode::HashedBySolid => {
25                let srgb = solid_color_srgb(&solid.name);
26                [
27                    srgb_to_linear(srgb[0]) as f32,
28                    srgb_to_linear(srgb[1]) as f32,
29                    srgb_to_linear(srgb[2]) as f32,
30                    1.0,
31                ]
32            }
33            FaceColorMode::Uniform => {
34                let c = settings.face_color;
35                [
36                    srgb_to_linear(c[0] as f64) as f32,
37                    srgb_to_linear(c[1] as f64) as f32,
38                    srgb_to_linear(c[2] as f64) as f32,
39                    c[3],
40                ]
41            }
42        }
43    }
44
45    /// One sRGB model colour as an opaque LINEAR `Rgba` — the conversion the
46    /// solid's base style and the per-face palette must share.
47    fn opaque_linear(rgb: [f32; 3]) -> Rgba {
48        [
49            srgb_to_linear(rgb[0] as f64) as f32,
50            srgb_to_linear(rgb[1] as f64) as f32,
51            srgb_to_linear(rgb[2] as f64) as f32,
52            1.0,
53        ]
54    }
55
56    /// The shading params every face style carries (flat-vs-smooth in `.x`).
57    fn style_params(settings: &RenderSettings) -> [f32; 4] {
58        [if settings.flat_shading { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]
59    }
60
61    /// The distinct PER-FACE styles of a solid, as `(colour, opacity)` keys in
62    /// first-use order, and each face's index into them.
63    ///
64    /// A face needs a style of its own when it carries its own colour, or
65    /// draws at an opacity other than its solid's (a `transparency` attribute
66    /// on the face). `None` for the colour means the solid's base colour.
67    /// The palette upload and [`Self::restyle`] both read this, so the two
68    /// cannot disagree about which slot is which.
69    fn face_style_keys(solid: &SolidDisplay) -> (Vec<(Option<[f32; 3]>, f32)>, Vec<Option<u32>>) {
70        let base = solid.base_opacity();
71        let mut keys: Vec<(Option<[f32; 3]>, f32)> = Vec::new();
72        let mut per_face: Vec<Option<u32>> = Vec::with_capacity(solid.faces.len());
73        for face in &solid.faces {
74            let opacity = solid.face_opacity(face);
75            let color = face.analysis_color.or(face.color_override);
76            if color.is_none() && opacity == base {
77                per_face.push(None);
78                continue;
79            }
80            let key = (color, opacity);
81            let slot = match keys.iter().position(|k| *k == key) {
82                Some(slot) => slot,
83                None => {
84                    keys.push(key);
85                    keys.len() - 1
86                }
87            };
88            per_face.push(Some(slot as u32));
89        }
90        (keys, per_face)
91    }
92
93    /// The LINEAR colour one [`Self::face_style_keys`] entry draws in; its
94    /// alpha is the face's opacity (read by the blended pass only).
95    fn face_style_color(solid: &SolidDisplay, settings: &RenderSettings, key: (Option<[f32; 3]>, f32)) -> Rgba {
96        let mut color = match key.0 {
97            Some(rgb) => Self::opaque_linear(rgb),
98            None => Self::face_base_color_opaque(solid, settings),
99        };
100        color[3] = key.1;
101        color
102    }
103
104    /// Build this solid's PER-FACE style palette, de-duplicated by colour and
105    /// opacity, and the per-face index into it.
106    ///
107    /// Faces sharing a style share one uniform buffer, so an imported body
108    /// painted in three colours costs three buffers however many faces it has —
109    /// and the draw loop can still coalesce a contiguous run of same-styled
110    /// faces into one call. A solid with no per-face styles returns an EMPTY
111    /// palette, which is what re-arms the whole-mesh fast path.
112    fn face_style_palette(
113        &self,
114        solid: &SolidDisplay,
115        settings: &RenderSettings,
116    ) -> (Vec<StyleBuf>, Vec<Option<u32>>) {
117        let (keys, per_face) = Self::face_style_keys(solid);
118        let params = Self::style_params(settings);
119        let styles = keys
120            .into_iter()
121            .map(|key| {
122                let style = StyleBuf::new(&self.device, &self.style_layout, solid.name.as_str());
123                style.write(&self.queue, Self::face_style_color(solid, settings, key), params);
124                style
125            })
126            .collect();
127        (styles, per_face)
128    }
129
130    /// The vertex buffer's contents: positions and normals.
131    fn mesh_vertices(solid: &SolidDisplay) -> Vec<MeshVertex> {
132        solid
133            .mesh
134            .positions
135            .iter()
136            .zip(&solid.mesh.normals)
137            .map(|(&position, &normal)| MeshVertex { position, normal })
138            .collect()
139    }
140
141    /// The edge buffer's contents (one instance per polyline segment) and each
142    /// edge's instance range.
143    fn edge_segments(solid: &SolidDisplay) -> (Vec<EdgeInstance>, Vec<EdgeRange>) {
144        let mut segments: Vec<EdgeInstance> = Vec::new();
145        let mut edges = Vec::with_capacity(solid.edges.len());
146        for edge in &solid.edges {
147            let first_instance = segments.len() as u32;
148            for pair in edge.polyline.windows(2) {
149                segments.push(EdgeInstance {
150                    p0: pair[0],
151                    p1: pair[1],
152                });
153            }
154            edges.push(EdgeRange {
155                first_instance,
156                instance_count: segments.len() as u32 - first_instance,
157                style: None,
158            });
159        }
160        (segments, edges)
161    }
162
163    /// The distinct (colour, opacity) looks among a solid's edges, and each
164    /// edge's index into them (`None`: the theme's edge style).
165    fn edge_style_keys(solid: &SolidDisplay) -> (Vec<(Option<[f32; 3]>, f32)>, Vec<Option<u32>>) {
166        let mut keys: Vec<(Option<[f32; 3]>, f32)> = Vec::new();
167        let mut per_edge: Vec<Option<u32>> = Vec::with_capacity(solid.edges.len());
168        for edge in &solid.edges {
169            if !edge.is_styled() {
170                per_edge.push(None);
171                continue;
172            }
173            let key = (edge.color_override, edge.opacity.unwrap_or(1.0).clamp(0.0, 1.0));
174            let slot = match keys.iter().position(|k| *k == key) {
175                Some(slot) => slot,
176                None => {
177                    keys.push(key);
178                    keys.len() - 1
179                }
180            };
181            per_edge.push(Some(slot as u32));
182        }
183        (keys, per_edge)
184    }
185
186    /// Write one per-edge look's four state buffers for these settings.
187    fn write_edge_style(&self, style: &EdgeStyle, settings: &RenderSettings, key: (Option<[f32; 3]>, f32)) {
188        let q = &self.queue;
189        let params = [settings.edge_width_px, EDGE_NUDGE, 0.0, 0.0];
190        let (color, opacity) = key;
191        // Edge colours are written out as they are (`fs_edge`), so the
192        // metadata's sRGB value is used directly, like the theme's.
193        let mut base = match color {
194            Some([r, g, b]) => [r, g, b, 1.0],
195            None => settings.edge_color,
196        };
197        let mut hidden = base;
198        base[3] *= opacity;
199        hidden[3] = settings.hidden_edge_alpha * opacity;
200        style.base.write(q, base, params);
201        style.hidden.write(q, hidden, params);
202        // Picked or hovered: the emphasis colour, at the edge's own opacity so
203        // a transparency drag shows while the edge is selected, but never so
204        // clear that the pick cannot be seen.
205        let emphasis = |mut rgba: Rgba| {
206            rgba[3] *= opacity.max(EMPHASIS_EDGE_MIN_OPACITY);
207            rgba
208        };
209        style.selected.write(q, emphasis(settings.edge_selected_color), params);
210        style.hovered.write(q, emphasis(settings.hover_color), params);
211    }
212
213    /// Build this solid's per-edge style palette and the per-edge index into it.
214    fn edge_style_palette(&self, solid: &SolidDisplay, settings: &RenderSettings) -> (Vec<EdgeStyle>, Vec<Option<u32>>) {
215        let (keys, per_edge) = Self::edge_style_keys(solid);
216        let styles = keys
217            .into_iter()
218            .map(|key| {
219                let buf = || StyleBuf::new(&self.device, &self.style_layout, solid.name.as_str());
220                let style = EdgeStyle { base: buf(), selected: buf(), hovered: buf(), hidden: buf() };
221                self.write_edge_style(&style, settings, key);
222                style
223            })
224            .collect();
225        (styles, per_edge)
226    }
227
228    /// The point buffer's contents: one instance per vertex.
229    fn point_instances(solid: &SolidDisplay) -> Vec<PointInstance> {
230        solid
231            .vertices
232            .iter()
233            .map(|v| PointInstance {
234                center: [
235                    v.position[0] as f32,
236                    v.position[1] as f32,
237                    v.position[2] as f32,
238                ],
239            })
240            .collect()
241    }
242
243    /// Re-pose a solid whose buffers hold the same SHAPE (a rigid move): rewrite
244    /// its vertex, edge and point buffers in place. `false` (nothing written)
245    /// when any count differs, so the caller rebuilds instead.
246    fn repose_solid(&self, existing: &GpuSolid, solid: &SolidDisplay) -> bool {
247        let vertices = Self::mesh_vertices(solid);
248        let (segments, edges) = Self::edge_segments(solid);
249        let points = Self::point_instances(solid);
250        let same = vertices.len() as u32 == existing.vertex_count
251            && segments.len() as u32 == existing.edge_instances
252            && edges.len() == existing.edges.len()
253            && points.len() as u32 == existing.point_count
254            && solid.faces.len() == existing.faces.len()
255            && existing.edge_buf.is_some() == !segments.is_empty()
256            && existing.point_buf.is_some() == !points.is_empty();
257        if !same {
258            return false;
259        }
260        self.queue.write_buffer(&existing.vertex_buf, 0, bytemuck::cast_slice(&vertices));
261        if let Some(buf) = &existing.edge_buf {
262            self.queue.write_buffer(buf, 0, bytemuck::cast_slice(&segments));
263        }
264        if let Some(buf) = &existing.point_buf {
265            self.queue.write_buffer(buf, 0, bytemuck::cast_slice(&points));
266        }
267        true
268    }
269
270    fn upload_solid(&self, solid: &SolidDisplay, settings: &RenderSettings) -> GpuSolid {
271        let vertices = Self::mesh_vertices(solid);
272        let vertex_buf = self
273            .device
274            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
275                label: Some(solid.name.as_str()),
276                contents: bytemuck::cast_slice(&vertices),
277                // COPY_DST: a rigid re-pose rewrites it in place.
278                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
279            });
280        let index_buf = self
281            .device
282            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
283                label: Some(solid.name.as_str()),
284                contents: bytemuck::cast_slice(&solid.mesh.indices),
285                usage: wgpu::BufferUsages::INDEX,
286            });
287        // Wireframe line-list, built PER FACE and de-duplicated inside each face.
288        //
289        // The obvious expansion — every triangle (a,b,c) → (a,b),(b,c),(c,a) —
290        // emits each of a face's INTERIOR edges twice, once from each of the two
291        // triangles that share it. That is two-thirds of the segments on a typical
292        // tessellation: twice the index data to upload and hold, and twice the
293        // vertex work per frame to draw two collinear lines on top of each other.
294        // The wire pipeline does not blend (`color_target(None)` in `pipelines.rs`),
295        // so the second draw of a segment lands on the same pixels in the same
296        // colour at the same depth — it was never visible.
297        //
298        // De-duplicating WITHIN a face, rather than across the whole mesh, is what
299        // keeps each face's segments CONTIGUOUS, which is what lets the hidden-face
300        // path below address them by range the way the shaded path addresses
301        // triangle ranges. The seam between two faces stays doubled (once per
302        // owning face) — a small fraction, and the price of a face still being able
303        // to hide its own wireframe.
304        let tri_total = solid.mesh.indices.len() / 3;
305        let mut wire_indices: Vec<u32> = Vec::with_capacity(solid.mesh.indices.len());
306        let mut wire_ranges: Vec<(u32, u32)> = Vec::with_capacity(solid.faces.len());
307        let mut covered = vec![false; tri_total];
308        let mut seen: HashSet<(u32, u32), BuildEdgeHasher> = HashSet::default();
309        let emit_triangle = |wire: &mut Vec<u32>,
310                                 seen: &mut HashSet<(u32, u32), BuildEdgeHasher>,
311                                 tri: usize| {
312            let idx = [
313                solid.mesh.indices[tri * 3],
314                solid.mesh.indices[tri * 3 + 1],
315                solid.mesh.indices[tri * 3 + 2],
316            ];
317            for k in 0..3 {
318                let (a, b) = (idx[k], idx[(k + 1) % 3]);
319                let key = if a < b { (a, b) } else { (b, a) };
320                if seen.insert(key) {
321                    wire.push(a);
322                    wire.push(b);
323                }
324            }
325        };
326        for face in &solid.faces {
327            let first = wire_indices.len() as u32;
328            seen.clear();
329            let start = (face.tri_start as usize).min(tri_total);
330            let end = (start + face.tri_count as usize).min(tri_total);
331            for tri in start..end {
332                covered[tri] = true;
333                emit_triangle(&mut wire_indices, &mut seen, tri);
334            }
335            wire_ranges.push((first, wire_indices.len() as u32 - first));
336        }
337        // Any triangle no face claims still belongs in the whole-mesh draw — the
338        // fast path draws the buffer end to end. It is addressed by no face range,
339        // exactly as before: the per-face path could never reach it either.
340        seen.clear();
341        for tri in 0..tri_total {
342            if !covered[tri] {
343                emit_triangle(&mut wire_indices, &mut seen, tri);
344            }
345        }
346        let wire_index_count = wire_indices.len() as u32;
347        let wire_index_buf = self
348            .device
349            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
350                label: Some(solid.name.as_str()),
351                contents: bytemuck::cast_slice(&wire_indices),
352                usage: wgpu::BufferUsages::INDEX,
353            });
354        let (face_styles, face_style_index) = self.face_style_palette(solid, settings);
355        let faces: Vec<FaceRange> = solid
356            .faces
357            .iter()
358            .zip(&face_style_index)
359            .zip(&wire_ranges)
360            .map(|((face, style), &(wire_first, wire_count))| FaceRange {
361                first_index: face.tri_start * 3,
362                index_count: face.tri_count * 3,
363                wire_first,
364                wire_count,
365                style: *style,
366                translucent: solid.face_opacity(face) < 1.0,
367            })
368            .collect();
369        let base_translucent = solid.base_opacity() < 1.0;
370        let mixed_translucency = faces.iter().any(|face| face.translucent != base_translucent);
371
372        let (segments, mut edges) = Self::edge_segments(solid);
373        let (edge_styles, edge_style_index) = self.edge_style_palette(solid, settings);
374        for (range, style) in edges.iter_mut().zip(edge_style_index) {
375            range.style = style;
376        }
377        let occludable_edge_instances = solid
378            .edges
379            .iter()
380            .zip(&edges)
381            .find(|(edge, _)| edge.aux)
382            .map_or(segments.len() as u32, |(_, range): (_, &EdgeRange)| range.first_instance);
383        let edge_buf = (!segments.is_empty()).then(|| {
384            self.device
385                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
386                    label: Some(solid.name.as_str()),
387                    contents: bytemuck::cast_slice(&segments),
388                    usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
389                })
390        });
391
392        let points = Self::point_instances(solid);
393        let point_buf = (!points.is_empty()).then(|| {
394            self.device
395                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
396                    label: Some(solid.name.as_str()),
397                    contents: bytemuck::cast_slice(&points),
398                    usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
399                })
400        });
401
402        let base_style = StyleBuf::new(&self.device, &self.style_layout, solid.name.as_str());
403        base_style.write(
404            &self.queue,
405            Self::face_base_color(solid, settings),
406            Self::style_params(settings),
407        );
408
409        GpuSolid {
410            revision: solid.revision,
411            shape: Self::shape_of(solid),
412            vertex_count: vertices.len() as u32,
413            face_styles,
414            base_translucent,
415            mixed_translucency,
416            vertex_buf,
417            index_buf,
418            wire_index_buf,
419            wire_index_count,
420            faces,
421            edge_buf,
422            edges,
423            edge_styles,
424            edge_instances: segments.len() as u32,
425            occludable_edge_instances,
426            point_buf,
427            point_count: points.len() as u32,
428            base_style,
429            boundary: None,
430            // Its pose slot is given by the sync. Uploaded as it is shown,
431            // so drawn through no pose; its buffers hold its shape's own
432            // geometry only when it is not a pose itself.
433            model_slot: 0,
434            holds_shape: solid.shape_revision == 0,
435        }
436    }
437
438    /// Bring the GPU scene in line with the display scene: new/changed solids
439    /// upload, unchanged solids keep their buffers (R10), removed solids drop
440    /// theirs. `settings_generation` invalidates per-solid style buffers only.
441    pub fn sync_scene(
442        &self,
443        gpu: &mut GpuScene,
444        scene: &RenderScene,
445        settings: &RenderSettings,
446        settings_generation: u64,
447    ) {
448        gpu.order.clear();
449        let models = gpu.models.get_or_insert_with(|| ModelArena::new(&self.device, &self.model_layout, scene.solids().len() as u32));
450        let mut seen: Vec<&str> = Vec::with_capacity(scene.solids().len());
451        for solid in scene.solids() {
452            gpu.order.push(solid.name.clone());
453            seen.push(solid.name.as_str());
454            let refresh_style = gpu.settings_generation != settings_generation;
455            match gpu.solids.get_mut(&solid.name) {
456                Some(existing) if existing.revision == solid.revision => {
457                    if refresh_style {
458                        self.restyle(existing, solid, settings);
459                    }
460                }
461                // The shape whose geometry the buffers hold, shown through a
462                // pose (an exploded view's step) or as it is: one matrix
463                // write, nothing of the mesh rewritten.
464                Some(existing)
465                    if existing.holds_shape
466                        && existing.shape == Self::shape_of(solid)
467                        && (solid.pose.is_some() || solid.shape_revision == 0) =>
468                {
469                    models.set(existing.model_slot, solid.pose.as_ref());
470                    existing.revision = solid.revision;
471                    gpu.pose_writes += 1;
472                    if refresh_style {
473                        self.restyle(existing, solid, settings);
474                    }
475                }
476                // The same shape moved rigidly (a live drag frame, its
477                // restore): rewrite positions in place, rebuild nothing.
478                Some(existing) if existing.shape == Self::shape_of(solid) && self.repose_solid(existing, solid) => {
479                    // The buffers now hold this pose itself, drawn as it is.
480                    models.set(existing.model_slot, None);
481                    existing.holds_shape = false;
482                    existing.revision = solid.revision;
483                    gpu.reposes += 1;
484                    if refresh_style {
485                        self.restyle(existing, solid, settings);
486                    }
487                }
488                _ => {
489                    let mut uploaded = self.upload_solid(solid, settings);
490                    match gpu.solids.get(&solid.name) {
491                        Some(replaced) => uploaded.model_slot = replaced.model_slot,
492                        None => uploaded.model_slot = models.alloc(),
493                    }
494                    models.set(uploaded.model_slot, None);
495                    gpu.solids.insert(solid.name.clone(), uploaded);
496                    gpu.uploads += 1;
497                }
498            }
499        }
500        let seen: std::collections::HashSet<&str> = seen.into_iter().collect();
501        gpu.solids.retain(|name, solid| {
502            let keep = seen.contains(name.as_str());
503            if !keep {
504                models.release(solid.model_slot);
505            }
506            keep
507        });
508        models.flush(&self.device, &self.queue, &self.model_layout);
509        gpu.settings_generation = settings_generation;
510    }
511
512    /// The shape a display's buffers would hold: its `shape_revision` when it
513    /// is a rigid move of another revision, else its own revision.
514    fn shape_of(solid: &SolidDisplay) -> u64 {
515        if solid.shape_revision != 0 {
516            solid.shape_revision
517        } else {
518            solid.revision
519        }
520    }
521
522    /// Rewrite a held solid's base and per-face styles for new settings.
523    fn restyle(&self, existing: &GpuSolid, solid: &SolidDisplay, settings: &RenderSettings) {
524        let params = Self::style_params(settings);
525        existing.base_style.write(&self.queue, Self::face_base_color(solid, settings), params);
526        // The per-face palette carries the same shading params, so it restyles
527        // with the base or flat shading would stop applying to individually
528        // coloured faces.
529        let (keys, _) = Self::face_style_keys(solid);
530        for (style, key) in existing.face_styles.iter().zip(keys) {
531            style.write(&self.queue, Self::face_style_color(solid, settings, key), params);
532        }
533        // The per-edge palette carries the edge width and the theme's edge
534        // and emphasis colours.
535        let (keys, _) = Self::edge_style_keys(solid);
536        for (style, key) in existing.edge_styles.iter().zip(keys) {
537            self.write_edge_style(style, settings, key);
538        }
539    }
540
541    /// Upload a scene from scratch (artifact/one-shot path).
542    pub fn upload_scene(&self, scene: &RenderScene) -> GpuScene {
543        self.upload_scene_with(scene, &RenderSettings::artifact())
544    }
545
546    pub fn upload_scene_with(&self, scene: &RenderScene, settings: &RenderSettings) -> GpuScene {
547        let mut gpu = GpuScene::default();
548        self.sync_scene(&mut gpu, scene, settings, 0);
549        gpu
550    }
551
552    pub(super) fn ensure_targets(&mut self, width: u32, height: u32) {
553        if let Some(targets) = &self.targets {
554            if targets.width == width && targets.height == height {
555                return;
556            }
557        }
558        let size = wgpu::Extent3d {
559            width,
560            height,
561            depth_or_array_layers: 1,
562        };
563        let msaa = self.device.create_texture(&wgpu::TextureDescriptor {
564            label: Some("msaa color"),
565            size,
566            mip_level_count: 1,
567            sample_count: SAMPLES,
568            dimension: wgpu::TextureDimension::D2,
569            format: self.format,
570            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
571            view_formats: &[],
572        });
573        let depth = self.device.create_texture(&wgpu::TextureDescriptor {
574            label: Some("depth"),
575            size,
576            mip_level_count: 1,
577            sample_count: SAMPLES,
578            dimension: wgpu::TextureDimension::D2,
579            format: DEPTH_FORMAT,
580            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
581            view_formats: &[],
582        });
583        self.targets = Some(CachedTargets {
584            width,
585            height,
586            msaa_view: msaa.create_view(&Default::default()),
587            depth_view: depth.create_view(&Default::default()),
588        });
589    }
590
591    pub(super) fn write_global_styles(&self, settings: &RenderSettings) {
592        let flat = if settings.flat_shading { 1.0 } else { 0.0 };
593        let face = |c: Rgba| -> Rgba {
594            [
595                srgb_to_linear(c[0] as f64) as f32,
596                srgb_to_linear(c[1] as f64) as f32,
597                srgb_to_linear(c[2] as f64) as f32,
598                c[3],
599            ]
600        };
601        let s = &self.styles;
602        let q = &self.queue;
603        s.face_selected
604            .write(q, face(settings.face_selected_color), [flat, 0.0, 0.0, 0.0]);
605        s.face_hovered
606            .write(q, face(settings.hover_color), [flat, 0.0, 0.0, 0.0]);
607        // A context face picked or hovered: its selection colour, kept see-through.
608        let translucent = |rgba: [f32; 4], alpha: f32| [rgba[0], rgba[1], rgba[2], alpha];
609        self.context_selected.write(q, translucent(settings.face_selected_color, 0.6), [0.0; 4]);
610        self.context_hovered.write(q, translucent(settings.hover_color, 0.45), [0.0; 4]);
611        let edge_params = [settings.edge_width_px, EDGE_NUDGE, 0.0, 0.0];
612        s.edge_base.write(q, settings.edge_color, edge_params);
613        s.edge_selected.write(q, settings.edge_selected_color, edge_params);
614        s.edge_hovered.write(q, settings.hover_color, edge_params);
615        let mut hidden = settings.edge_color;
616        hidden[3] = settings.hidden_edge_alpha;
617        s.edge_hidden.write(q, hidden, edge_params);
618        // An AUX edge at rest is the theme's edge at hairline WIDTH: a board's
619        // copper outline is thousands of edges a fraction of a millimetre
620        // apart, and at the full width the outlines of a track field crowd
621        // the gaps between its tracks. (Too coarse a view does not draw them
622        // at all — `frame::AUX_EDGE_MAX_WORLD_PER_PIXEL`.)
623        s.edge_aux.write(q, settings.edge_color, [AUX_EDGE_WIDTH_PX, EDGE_NUDGE, 0.0, 0.0]);
624        // Selected-face boundary: selected-edge color, slightly wider, extra
625        // nudge so it reads as an outline on top of the fill.
626        s.boundary.write(
627            q,
628            settings.edge_selected_color,
629            [settings.edge_width_px + 1.0, EDGE_NUDGE * 1.5, 0.0, 0.0],
630        );
631        let point_params = [settings.vertex_size_px, 0.0, 0.0, 0.0];
632        s.point_base.write(q, settings.vertex_color, point_params);
633        s.point_selected
634            .write(q, settings.vertex_selected_color, [settings.vertex_size_px + 1.0, 0.0, 0.0, 0.0]);
635        s.point_hovered
636            .write(q, settings.hover_color, [settings.vertex_size_px + 1.0, 0.0, 0.0, 0.0]);
637        let axis_params = [2.0, EDGE_NUDGE, 0.0, 0.0];
638        s.axis_x.write(q, [0.91, 0.30, 0.32, 1.0], axis_params);
639        s.axis_y.write(q, [0.27, 0.80, 0.42, 1.0], axis_params);
640        s.axis_z.write(q, [0.23, 0.51, 0.96, 1.0], axis_params);
641        // Overlay-widget line width (color is per-instance from the gizmo).
642        s.overlay_line.write(q, [1.0, 1.0, 1.0, 1.0], [2.5, 0.0, 0.0, 0.0]);
643        // Line art: the step pictures' colours (thumbnail::line_art), faces
644        // unlit (params.y), edges and outlines in sRGB.
645        use crate::thumbnail::line_art as la;
646        let srgb = |c: [f32; 3]| [c[0], c[1], c[2], 1.0];
647        s.line_art_placed_face.write(q, face(srgb(la::PLACED_FILL)), [0.0, 1.0, 0.0, 0.0]);
648        s.line_art_adding_face.write(q, face(srgb(la::ADDING_FILL)), [0.0, 1.0, 0.0, 0.0]);
649        s.line_art_placed_edge.write(q, srgb(la::PLACED_EDGE), [1.0, EDGE_NUDGE, 0.0, 0.0]);
650        s.line_art_adding_edge.write(q, srgb(la::INK), [1.2, EDGE_NUDGE, 0.0, 0.0]);
651        s.line_art_placed_outline.write(q, srgb(la::PLACED_OUTLINE), [LINE_ART_PLACED_OUTLINE_PX, LINE_ART_OUTLINE_DEPTH, 0.0, 0.0]);
652        s.line_art_adding_outline.write(q, srgb(la::INK), [LINE_ART_ADDING_OUTLINE_PX, LINE_ART_OUTLINE_DEPTH, 0.0, 0.0]);
653    }
654
655    /// Rebuild the selected/hovered-face boundary outline buffer for one solid
656    /// when the emphasis or the solid changed. The boundary of a face's
657    /// triangle range = mesh edges used an odd number of times inside it.
658    pub(super) fn sync_boundary(&self, gpu_solid: &mut GpuSolid, solid: &SolidDisplay, emphasis: &Emphasis) {
659        if let Some(boundary) = &gpu_solid.boundary {
660            if boundary.emphasis_generation == emphasis.generation
661                && boundary.revision == solid.revision
662            {
663                return;
664            }
665        }
666        let mut segments: Vec<EdgeInstance> = Vec::new();
667        for face in &solid.faces {
668            if face.tri_count == 0 {
669                continue;
670            }
671            let state = emphasis.face_state(&solid.name, &face.name);
672            if state == EmphasisState::Base {
673                continue;
674            }
675            let mut edge_use: HashMap<(u32, u32), u32> = HashMap::new();
676            let start = face.tri_start as usize;
677            let end = (start + face.tri_count as usize).min(solid.mesh.indices.len() / 3);
678            for tri in start..end {
679                let idx = [
680                    solid.mesh.indices[tri * 3],
681                    solid.mesh.indices[tri * 3 + 1],
682                    solid.mesh.indices[tri * 3 + 2],
683                ];
684                for k in 0..3 {
685                    let a = idx[k];
686                    let b = idx[(k + 1) % 3];
687                    let key = if a < b { (a, b) } else { (b, a) };
688                    *edge_use.entry(key).or_insert(0) += 1;
689                }
690            }
691            let mut boundary: Vec<(u32, u32)> = edge_use
692                .into_iter()
693                .filter_map(|(key, count)| (count == 1).then_some(key))
694                .collect();
695            boundary.sort_unstable();
696            for (a, b) in boundary {
697                segments.push(EdgeInstance {
698                    p0: solid.mesh.positions[a as usize],
699                    p1: solid.mesh.positions[b as usize],
700                });
701            }
702        }
703        let buf = (!segments.is_empty()).then(|| {
704            self.device
705                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
706                    label: Some("emphasis boundary"),
707                    contents: bytemuck::cast_slice(&segments),
708                    usage: wgpu::BufferUsages::VERTEX,
709                })
710        });
711        gpu_solid.boundary = Some(BoundaryBuf {
712            emphasis_generation: emphasis.generation,
713            revision: solid.revision,
714            buf,
715            count: segments.len() as u32,
716        });
717    }
718}