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