Skip to main content

brep_render/render/
frame.rs

1use super::*;
2
3impl RenderCore {
4    /// Render one frame into `resolve_view` (a single-sample view of the
5    /// core's format). This is the whole engine core; every presentation shell
6    /// funnels through it.
7    pub fn render_to_view(
8        &mut self,
9        gpu_scene: &mut GpuScene,
10        scene: &RenderScene,
11        params: &FrameParams,
12        resolve_view: &wgpu::TextureView,
13    ) {
14        self.render_to_view_with_context(gpu_scene, scene, params, resolve_view, None);
15    }
16
17    /// Draw optional, non-pickable assembly context after the opaque work part.
18    pub fn render_to_view_with_context(
19        &mut self,
20        gpu_scene: &mut GpuScene,
21        scene: &RenderScene,
22        params: &FrameParams,
23        resolve_view: &wgpu::TextureView,
24        context: Option<(&GpuScene, &RenderScene)>,
25    ) {
26        let width = params.width.max(1);
27        let height = params.height.max(1);
28        self.ensure_targets(width, height);
29        self.write_global_styles(params.settings);
30
31        let globals = Globals {
32            view_proj: params.camera.view_proj,
33            viewport: [width as f32, height as f32, params.dpr.max(1e-3), 0.0],
34            forward: [
35                params.camera.forward[0],
36                params.camera.forward[1],
37                params.camera.forward[2],
38                0.0,
39            ],
40        };
41        self.queue
42            .write_buffer(&self.globals_buf, 0, bytemuck::bytes_of(&globals));
43
44        // World-axis helper (R20): three world-axis segments sized in CSS px.
45        let axis_len = params.settings.axis_length_px as f64 * params.world_per_pixel;
46        let draw_axes = params.settings.axis_length_px > 0.0 && axis_len.is_finite() && axis_len > 0.0;
47        if draw_axes {
48            let l = axis_len as f32;
49            let segments = [
50                EdgeInstance { p0: [0.0; 3], p1: [l, 0.0, 0.0] },
51                EdgeInstance { p0: [0.0; 3], p1: [0.0, l, 0.0] },
52                EdgeInstance { p0: [0.0; 3], p1: [0.0, 0.0, l] },
53            ];
54            match &gpu_scene.axis_buf {
55                Some(buf) => self.queue.write_buffer(buf, 0, bytemuck::cast_slice(&segments)),
56                None => {
57                    gpu_scene.axis_buf = Some(self.device.create_buffer_init(
58                        &wgpu::util::BufferInitDescriptor {
59                            label: Some("world axes"),
60                            contents: bytemuck::cast_slice(&segments),
61                            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
62                        },
63                    ));
64                }
65            }
66        }
67
68        // Refresh emphasis boundary buffers.
69        let has_emphasis = !params.emphasis.is_empty();
70        // A see-through solid (a `transparency` attribute, or a motion study's
71        // clip) draws in the blended pass; one with both kinds of face draws
72        // its opaque faces here and the rest there.
73        let all_translucent = |gpu_solid: &GpuSolid| gpu_solid.base_translucent && !gpu_solid.mixed_translucency;
74        let any_translucent = |gpu_solid: &GpuSolid| gpu_solid.base_translucent || gpu_solid.mixed_translucency;
75        for solid in scene.solids() {
76            if let Some(gpu_solid) = gpu_scene.solids.get_mut(&solid.name) {
77                self.sync_boundary(gpu_solid, solid, params.emphasis);
78            }
79        }
80
81        // A Line art instructions step draws on the step pictures' ground.
82        let bg = match &scene.line_art {
83            Some(_) => crate::thumbnail::line_art::BACKGROUND,
84            None => params.settings.background,
85        };
86        let targets = self.targets.as_ref().expect("targets ensured");
87        let mut encoder = self
88            .device
89            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
90                label: Some("brep-render frame"),
91            });
92        {
93            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
94                label: Some("scene"),
95                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
96                    view: &targets.msaa_view,
97                    depth_slice: None,
98                    resolve_target: Some(resolve_view),
99                    ops: wgpu::Operations {
100                        load: wgpu::LoadOp::Clear(wgpu::Color {
101                            r: bg[0] as f64,
102                            g: bg[1] as f64,
103                            b: bg[2] as f64,
104                            a: 1.0,
105                        }),
106                        store: wgpu::StoreOp::Store,
107                    },
108                })],
109                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
110                    view: &targets.depth_view,
111                    depth_ops: Some(wgpu::Operations {
112                        load: wgpu::LoadOp::Clear(1.0),
113                        store: wgpu::StoreOp::Discard,
114                    }),
115                    stencil_ops: None,
116                }),
117                timestamp_writes: None,
118                occlusion_query_set: None,
119                multiview_mask: None,
120            });
121            pass.set_bind_group(0, &self.globals_bind, &[]);
122            // The solid pipelines' group 2: a solid's pose, set beside each
123            // solid's buffers; identity for anything else they draw.
124            pass.set_bind_group(2, &self.identity_model.bind, &[0]);
125
126            let visible_solids: Vec<(&SolidDisplay, &GpuSolid)> = gpu_scene
127                .order
128                .iter()
129                .filter_map(|name| {
130                    let solid = scene.solid(name)?;
131                    if !solid.visible {
132                        return None;
133                    }
134                    Some((solid, gpu_scene.solids.get(name)?))
135                })
136                .collect();
137
138            // 1a. Wireframe view: draw each solid's tessellated triangle mesh as
139            //     a line list (base color, no fill), so the face triangles read
140            //     as a wireframe. Picking is CPU ray-based (pick.rs), unaffected.
141            //     A HIDDEN face skips its triangles' wire segments too, exactly as
142            //     the shaded pass masks its triangle ranges — otherwise hiding a
143            //     face (or the whole Faces group) would be a no-op in wireframe view.
144            if params.settings.wireframe && params.settings.show_faces {
145                pass.set_pipeline(&self.wire_pipeline);
146                for (solid, gpu_solid) in &visible_solids {
147                    if gpu_solid.wire_index_count == 0 {
148                        continue;
149                    }
150                    bind_pose(&mut pass, gpu_scene.models.as_ref(), &self.identity_model, gpu_solid.model_slot);
151                    pass.set_vertex_buffer(0, gpu_solid.vertex_buf.slice(..));
152                    pass.set_index_buffer(
153                        gpu_solid.wire_index_buf.slice(..),
154                        wgpu::IndexFormat::Uint32,
155                    );
156                    pass.set_bind_group(1, &gpu_solid.base_style.bind, &[]);
157                    // Fast path: no hidden face → one whole-buffer wire draw.
158                    if !solid.visibility.any_face_hidden() {
159                        pass.draw_indexed(0..gpu_solid.wire_index_count, 0, 0..1);
160                        continue;
161                    }
162                    // Otherwise coalesce contiguous VISIBLE faces' wire ranges and
163                    // skip the hidden ones. The wire buffer is a LINE LIST whose
164                    // segments are grouped by face and de-duplicated inside each
165                    // face (see `scene_sync::upload_solid`), so a face's slice is
166                    // whatever that grouping produced — read it off the face's
167                    // `wire_first`/`wire_count` rather than deriving it from the
168                    // triangle range, which no longer predicts it.
169                    let mut run: Option<(u32, u32)> = None; // first, count
170                    let flush = |pass: &mut wgpu::RenderPass, run: &mut Option<(u32, u32)>| {
171                        if let Some((first, count)) = run.take() {
172                            if count > 0 {
173                                pass.draw_indexed(first..first + count, 0, 0..1);
174                            }
175                        }
176                    };
177                    for (index, _face) in solid.faces.iter().enumerate() {
178                        let range = &gpu_solid.faces[index];
179                        if range.wire_count == 0 {
180                            continue;
181                        }
182                        let first = range.wire_first;
183                        let count = range.wire_count;
184                        if !solid.visibility.is_face_visible(index) {
185                            flush(&mut pass, &mut run);
186                            continue;
187                        }
188                        match &mut run {
189                            Some((run_first, run_count)) if *run_first + *run_count == first => {
190                                *run_count += count;
191                            }
192                            _ => {
193                                flush(&mut pass, &mut run);
194                                run = Some((first, count));
195                            }
196                        }
197                    }
198                    flush(&mut pass, &mut run);
199                }
200            }
201
202            // 1. Shaded faces, coalesced into index-range runs per emphasis
203            //    state (base runs merge back into whole-solid draws). Skipped in
204            //    wireframe mode (1a draws the triangle wireframe instead). Picking
205            //    is CPU ray-based (pick.rs) and the overlay pass is separate.
206            if !params.settings.wireframe && params.settings.show_faces {
207                pass.set_pipeline(&self.mesh_pipeline);
208                for (solid, gpu_solid) in &visible_solids {
209                    // A wholly see-through solid has nothing for this pass.
210                    if solid.mesh.indices.is_empty() || all_translucent(gpu_solid) {
211                        continue;
212                    }
213                    bind_pose(&mut pass, gpu_scene.models.as_ref(), &self.identity_model, gpu_solid.model_slot);
214                    pass.set_vertex_buffer(0, gpu_solid.vertex_buf.slice(..));
215                    pass.set_index_buffer(gpu_solid.index_buf.slice(..), wgpu::IndexFormat::Uint32);
216                    // A Line art step: one flat fill per tier, whatever the
217                    // model's colours.
218                    if let Some(look) = &scene.line_art {
219                        let style = if look.placed.contains(&solid.name) { &self.styles.line_art_placed_face } else { &self.styles.line_art_adding_face };
220                        if !has_emphasis {
221                            pass.set_bind_group(1, &style.bind, &[]);
222                            draw_visible_faces(&mut pass, solid, gpu_solid);
223                            continue;
224                        }
225                        // A picked or hovered face still shows, in the
226                        // emphasis colour in place of the flat fill.
227                        for (index, face) in solid.faces.iter().enumerate() {
228                            let range = &gpu_solid.faces[index];
229                            if range.index_count == 0 || !solid.visibility.is_face_visible(index) {
230                                continue;
231                            }
232                            let bind = match params.emphasis.face_state(&solid.name, &face.name) {
233                                EmphasisState::Base => &style.bind,
234                                EmphasisState::Selected => &self.styles.face_selected.bind,
235                                EmphasisState::Hovered => &self.styles.face_hovered.bind,
236                            };
237                            pass.set_bind_group(1, bind, &[]);
238                            pass.draw_indexed(range.first_index..range.first_index + range.index_count, 0, 0..1);
239                        }
240                        continue;
241                    }
242                    // Fast path: no emphasis AND no hidden faces → one whole-mesh
243                    // draw. When any face is hidden we fall to the per-face loop
244                    // below, which coalesces contiguous VISIBLE faces and skips
245                    // the hidden ones' triangle ranges entirely.
246                    // The whole-mesh fast path also needs every face to share
247                    // the solid's colour — a solid with a per-face palette has
248                    // to walk its faces to bind the right style per run.
249                    let any_face_hidden = solid.visibility.any_face_hidden();
250                    let any_face_colored = !gpu_solid.face_styles.is_empty();
251                    if !has_emphasis && !any_face_hidden && !any_face_colored && !any_translucent(gpu_solid) {
252                        pass.set_bind_group(1, &gpu_solid.base_style.bind, &[]);
253                        pass.draw_indexed(0..solid.mesh.indices.len() as u32, 0, 0..1);
254                        continue;
255                    }
256                    // The run key is (emphasis state, face-colour slot). A
257                    // selected or hovered face draws in the emphasis colour
258                    // whatever colour the model gave it, so its slot is
259                    // normalized away — two adjacent selected faces of
260                    // different colours still coalesce into one draw.
261                    let style_for = |state: EmphasisState, slot: Option<u32>| match state {
262                        EmphasisState::Base => match slot.and_then(|s| gpu_solid.face_styles.get(s as usize)) {
263                            Some(style) => &style.bind,
264                            None => &gpu_solid.base_style.bind,
265                        },
266                        EmphasisState::Selected => &self.styles.face_selected.bind,
267                        EmphasisState::Hovered => &self.styles.face_hovered.bind,
268                    };
269                    type FaceRun = (EmphasisState, Option<u32>, u32, u32); // state, slot, first, count
270                    let mut run: Option<FaceRun> = None;
271                    let flush = |pass: &mut wgpu::RenderPass, run: &mut Option<FaceRun>| {
272                        if let Some((state, slot, first, count)) = run.take() {
273                            if count > 0 {
274                                pass.set_bind_group(1, style_for(state, slot), &[]);
275                                pass.draw_indexed(first..first + count, 0, 0..1);
276                            }
277                        }
278                    };
279                    for (index, face) in solid.faces.iter().enumerate() {
280                        let range = &gpu_solid.faces[index];
281                        if range.index_count == 0 {
282                            continue;
283                        }
284                        // Hidden face: skip its triangles and break the run so
285                        // the surviving neighbours don't coalesce across the gap.
286                        if !solid.visibility.is_face_visible(index) {
287                            flush(&mut pass, &mut run);
288                            continue;
289                        }
290                        // A see-through face belongs to the blended pass,
291                        // picked or not: it stays see-through while selected
292                        // (its outline marks it), so a transparency being set
293                        // on the selection shows as it changes.
294                        if range.translucent {
295                            flush(&mut pass, &mut run);
296                            continue;
297                        }
298                        let state = if has_emphasis {
299                            params.emphasis.face_state(&solid.name, &face.name)
300                        } else {
301                            EmphasisState::Base
302                        };
303                        let slot = if state == EmphasisState::Base {
304                            range.style
305                        } else {
306                            None
307                        };
308                        match &mut run {
309                            Some((run_state, run_slot, first, count))
310                                if *run_state == state
311                                    && *run_slot == slot
312                                    && *first + *count == range.first_index =>
313                            {
314                                *count += range.index_count;
315                            }
316                            _ => {
317                                flush(&mut pass, &mut run);
318                                run = Some((state, slot, range.first_index, range.index_count));
319                            }
320                        }
321                    }
322                    flush(&mut pass, &mut run);
323                }
324            }
325
326            // 1b. A Line art step's outlines: each part's mesh pushed out on
327            //    screen and back in depth, in its tier's ink, over the faces
328            //    but behind them: only the ring round each silhouette (over
329            //    the ground or a part further back) passes the depth test.
330            if let (Some(look), false) = (&scene.line_art, params.settings.wireframe) {
331                pass.set_pipeline(&self.hull_pipeline);
332                for (solid, gpu_solid) in &visible_solids {
333                    if solid.mesh.indices.is_empty() || all_translucent(gpu_solid) {
334                        continue;
335                    }
336                    let style = if look.placed.contains(&solid.name) { &self.styles.line_art_placed_outline } else { &self.styles.line_art_adding_outline };
337                    pass.set_bind_group(1, &style.bind, &[]);
338                    bind_pose(&mut pass, gpu_scene.models.as_ref(), &self.identity_model, gpu_solid.model_slot);
339                    pass.set_vertex_buffer(0, gpu_solid.vertex_buf.slice(..));
340                    pass.set_index_buffer(gpu_solid.index_buf.slice(..), wgpu::IndexFormat::Uint32);
341                    draw_visible_faces(&mut pass, solid, gpu_solid);
342                }
343            }
344
345            // 2. Occluded edge portions, dimmed (depth test inverted). Hidden
346            //    edges skip their segments (their occluded portion too).
347            if params.settings.show_edges
348                && params.settings.show_occluded_edges
349                && params.settings.hidden_edge_alpha > 0.0
350                && scene.line_art.is_none()
351            {
352                pass.set_pipeline(&self.edge_hidden_pipeline);
353                pass.set_bind_group(1, &self.styles.edge_hidden.bind, &[]);
354                for (solid, gpu_solid) in &visible_solids {
355                    let Some(edge_buf) = &gpu_solid.edge_buf else { continue };
356                    if gpu_solid.occludable_edge_instances == 0 {
357                        continue;
358                    }
359                    bind_pose(&mut pass, gpu_scene.models.as_ref(), &self.identity_model, gpu_solid.model_slot);
360                    pass.set_vertex_buffer(0, edge_buf.slice(..));
361                    if !gpu_solid.edge_styles.is_empty() {
362                        // Edges with a look of their own dim in their own colour.
363                        draw_edge_runs(&mut pass, solid, gpu_solid, |index, edge| {
364                            if edge.aux || !solid.visibility.is_edge_visible(index) {
365                                return None;
366                            }
367                            Some(match gpu_solid.edges[index].style {
368                                Some(slot) => &gpu_solid.edge_styles[slot as usize].hidden.bind,
369                                None => &self.styles.edge_hidden.bind,
370                            })
371                        });
372                        pass.set_bind_group(1, &self.styles.edge_hidden.bind, &[]);
373                    } else if solid.visibility.any_edge_hidden() {
374                        // Single style already bound: draw only visible edges.
375                        draw_visible_edge_ranges(&mut pass, solid, gpu_solid, EdgeFilter::Real);
376                    } else {
377                        // Aux edges are not drawn occluded (`occludable_edge_instances`).
378                        pass.draw(0..6, 0..gpu_solid.occludable_edge_instances);
379                    }
380                }
381            }
382
383            // 3. Visible edges, per-edge emphasis runs; hidden edges skipped.
384            //    The whole pass is off when the Edges display toggle is.
385            if params.settings.show_edges {
386                let aux_shown = params.world_per_pixel <= AUX_EDGE_MAX_WORLD_PER_PIXEL;
387                pass.set_pipeline(&self.edge_visible_pipeline);
388                for (solid, gpu_solid) in &visible_solids {
389                    let Some(edge_buf) = &gpu_solid.edge_buf else { continue };
390                    if gpu_solid.edge_instances == 0 {
391                        continue;
392                    }
393                    bind_pose(&mut pass, gpu_scene.models.as_ref(), &self.identity_model, gpu_solid.model_slot);
394                    pass.set_vertex_buffer(0, edge_buf.slice(..));
395                    let any_edge_hidden = solid.visibility.any_edge_hidden();
396                    // The real edges are a prefix of the buffer and the AUX
397                    // ones the rest; at rest the two draw in their own styles,
398                    // and the aux ones only while the view is close enough
399                    // for them to be told apart (`AUX_EDGE_MAX_WORLD_PER_PIXEL`).
400                    let split = gpu_solid.occludable_edge_instances;
401                    // A Line art step: the real edges in the tier's ink, a picked
402                    // or hovered one in its emphasis style instead.
403                    if let Some(look) = &scene.line_art {
404                        let style = if look.placed.contains(&solid.name) { &self.styles.line_art_placed_edge } else { &self.styles.line_art_adding_edge };
405                        if !has_emphasis {
406                            pass.set_bind_group(1, &style.bind, &[]);
407                            if any_edge_hidden {
408                                draw_visible_edge_ranges(&mut pass, solid, gpu_solid, EdgeFilter::Real);
409                            } else if split > 0 {
410                                pass.draw(0..6, 0..split);
411                            }
412                            continue;
413                        }
414                        for (index, edge) in solid.edges.iter().enumerate() {
415                            let range = &gpu_solid.edges[index];
416                            if range.instance_count == 0 || edge.aux || !solid.visibility.is_edge_visible(index) {
417                                continue;
418                            }
419                            let bind = match params.emphasis.edge_state(&solid.name, &edge.name) {
420                                EmphasisState::Base => &style.bind,
421                                EmphasisState::Selected => &self.styles.edge_selected.bind,
422                                EmphasisState::Hovered => &self.styles.edge_hovered.bind,
423                            };
424                            pass.set_bind_group(1, bind, &[]);
425                            pass.draw(0..6, range.first_instance..range.first_instance + range.instance_count);
426                        }
427                        continue;
428                    }
429                    if !gpu_solid.edge_styles.is_empty() {
430                        // Some edge has its own colour or opacity: every edge
431                        // picks its bind group, runs of one coalesced.
432                        draw_edge_runs(&mut pass, solid, gpu_solid, |index, edge| {
433                            if !solid.visibility.is_edge_visible(index) || (edge.aux && !aux_shown) {
434                                return None;
435                            }
436                            let state = if has_emphasis {
437                                params.emphasis.edge_state(&solid.name, &edge.name)
438                            } else {
439                                EmphasisState::Base
440                            };
441                            Some(match (gpu_solid.edges[index].style, state) {
442                                (Some(slot), EmphasisState::Base) => &gpu_solid.edge_styles[slot as usize].base.bind,
443                                (Some(slot), EmphasisState::Selected) => &gpu_solid.edge_styles[slot as usize].selected.bind,
444                                (Some(slot), EmphasisState::Hovered) => &gpu_solid.edge_styles[slot as usize].hovered.bind,
445                                (None, EmphasisState::Base) if edge.aux => &self.styles.edge_aux.bind,
446                                (None, EmphasisState::Base) => &self.styles.edge_base.bind,
447                                (None, EmphasisState::Selected) => &self.styles.edge_selected.bind,
448                                (None, EmphasisState::Hovered) => &self.styles.edge_hovered.bind,
449                            })
450                        });
451                        continue;
452                    }
453                    if !has_emphasis {
454                        pass.set_bind_group(1, &self.styles.edge_base.bind, &[]);
455                        if any_edge_hidden {
456                            draw_visible_edge_ranges(&mut pass, solid, gpu_solid, EdgeFilter::Real);
457                            if aux_shown {
458                                pass.set_bind_group(1, &self.styles.edge_aux.bind, &[]);
459                                draw_visible_edge_ranges(&mut pass, solid, gpu_solid, EdgeFilter::Aux);
460                            }
461                        } else {
462                            if split > 0 {
463                                pass.draw(0..6, 0..split);
464                            }
465                            if aux_shown && split < gpu_solid.edge_instances {
466                                pass.set_bind_group(1, &self.styles.edge_aux.bind, &[]);
467                                pass.draw(0..6, split..gpu_solid.edge_instances);
468                            }
469                        }
470                        continue;
471                    }
472                    // An aux edge at rest keeps its own style; hovered or
473                    // selected (its SOLID is), it emphasises like any edge.
474                    let style_for = |(state, aux): (EmphasisState, bool)| match state {
475                        EmphasisState::Base if aux => &self.styles.edge_aux.bind,
476                        EmphasisState::Base => &self.styles.edge_base.bind,
477                        EmphasisState::Selected => &self.styles.edge_selected.bind,
478                        EmphasisState::Hovered => &self.styles.edge_hovered.bind,
479                    };
480                    let mut run: Option<((EmphasisState, bool), u32, u32)> = None;
481                    let flush = |pass: &mut wgpu::RenderPass, run: &mut Option<((EmphasisState, bool), u32, u32)>| {
482                        if let Some((state, first, count)) = run.take() {
483                            if count > 0 {
484                                pass.set_bind_group(1, style_for(state), &[]);
485                                pass.draw(0..6, first..first + count);
486                            }
487                        }
488                    };
489                    for (index, edge) in solid.edges.iter().enumerate() {
490                        let range = &gpu_solid.edges[index];
491                        if range.instance_count == 0 {
492                            continue;
493                        }
494                        // Hidden edge: skip its segments and break the run.
495                        if !solid.visibility.is_edge_visible(index) || (edge.aux && !aux_shown) {
496                            flush(&mut pass, &mut run);
497                            continue;
498                        }
499                        let state = (params.emphasis.edge_state(&solid.name, &edge.name), edge.aux);
500                        match &mut run {
501                            Some((run_state, first, count))
502                                if *run_state == state
503                                    && *first + *count == range.first_instance =>
504                            {
505                                *count += range.instance_count;
506                            }
507                            _ => {
508                                flush(&mut pass, &mut run);
509                                run = Some((state, range.first_instance, range.instance_count));
510                            }
511                        }
512                    }
513                    flush(&mut pass, &mut run);
514                }
515            }
516
517            // 4. Selected/hovered face boundary outlines.
518            if has_emphasis {
519                // Bind the pipeline explicitly rather than inheriting whatever
520                // the passes above left set: pass 3 binds this same pipeline,
521                // but only when `show_edges` is on. With edges hidden the
522                // inherited pipeline was the mesh/wireframe one, whose slot 0
523                // is a Vertex-step `MeshVertex` — so the `draw(0..6, ..)` below
524                // read this Instance-step `EdgeInstance` buffer as vertices and
525                // overran it (a 4-segment boundary is 4 "vertices" at the same
526                // 24-byte stride), which wgpu reports as a fatal validation error.
527                pass.set_pipeline(&self.edge_visible_pipeline);
528                pass.set_bind_group(1, &self.styles.boundary.bind, &[]);
529                for (_, gpu_solid) in &visible_solids {
530                    let Some(boundary) = &gpu_solid.boundary else { continue };
531                    let Some(buf) = &boundary.buf else { continue };
532                    if boundary.count == 0 {
533                        continue;
534                    }
535                    pass.set_bind_group(2, &self.identity_model.bind, &[0]);
536                    pass.set_vertex_buffer(0, buf.slice(..));
537                    pass.draw(0..6, 0..boundary.count);
538                }
539            }
540
541            // 5. Vertex points; hidden vertices skip their point sprite. A
542            //    Line art step is an illustration: no vertex dots.
543            if params.settings.show_vertices && params.settings.vertex_size_px > 0.0 && scene.line_art.is_none() {
544                pass.set_pipeline(&self.point_pipeline);
545                for (solid, gpu_solid) in &visible_solids {
546                    let Some(point_buf) = &gpu_solid.point_buf else { continue };
547                    if gpu_solid.point_count == 0 {
548                        continue;
549                    }
550                    // A fully-hidden points group draws nothing — skip before touching
551                    // the per-vertex loop below. When ALL vertices are hidden that loop
552                    // would still iterate every one of them each frame; the O(N)/frame
553                    // cost is invisible on native but throttles the WebGL backend on
554                    // point-heavy models (the "can't spin after hiding points" case).
555                    if solid.visibility.all_vertices_hidden(solid.vertices.len()) {
556                        continue;
557                    }
558                    bind_pose(&mut pass, gpu_scene.models.as_ref(), &self.identity_model, gpu_solid.model_slot);
559                    pass.set_vertex_buffer(0, point_buf.slice(..));
560                    let any_vertex_hidden = solid.visibility.any_vertex_hidden();
561                    if has_emphasis || any_vertex_hidden {
562                        let tol = 1e-9_f64.max(params.world_per_pixel * 1e-3);
563                        let mut base_run: Option<(u32, u32)> = None;
564                        let mut emphasized: Vec<(EmphasisState, u32)> = Vec::new();
565                        for (index, vertex) in solid.vertices.iter().enumerate() {
566                            // Hidden vertex: skip its point and break the run.
567                            if !solid.visibility.is_vertex_visible(index) {
568                                if let Some((first, count)) = base_run.take() {
569                                    pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
570                                    pass.draw(0..6, first..first + count);
571                                }
572                                continue;
573                            }
574                            let state = if has_emphasis {
575                                params.emphasis.vertex_state(&solid.name, vertex.position, tol)
576                            } else {
577                                EmphasisState::Base
578                            };
579                            if state == EmphasisState::Base {
580                                match &mut base_run {
581                                    Some((first, count)) if *first + *count == index as u32 => {
582                                        *count += 1
583                                    }
584                                    _ => {
585                                        if let Some((first, count)) = base_run.take() {
586                                            pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
587                                            pass.draw(0..6, first..first + count);
588                                        }
589                                        base_run = Some((index as u32, 1));
590                                    }
591                                }
592                            } else {
593                                emphasized.push((state, index as u32));
594                            }
595                        }
596                        if let Some((first, count)) = base_run {
597                            pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
598                            pass.draw(0..6, first..first + count);
599                        }
600                        for (state, index) in emphasized {
601                            let style = match state {
602                                EmphasisState::Selected => &self.styles.point_selected.bind,
603                                _ => &self.styles.point_hovered.bind,
604                            };
605                            pass.set_bind_group(1, style, &[]);
606                            pass.draw(0..6, index..index + 1);
607                        }
608                    } else {
609                        pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
610                        pass.draw(0..6, 0..gpu_solid.point_count);
611                    }
612                }
613            }
614
615            // 6. World axes on top of nothing special (normal depth test).
616            if draw_axes {
617                if let Some(axis_buf) = &gpu_scene.axis_buf {
618                    pass.set_pipeline(&self.edge_visible_pipeline);
619                    pass.set_bind_group(2, &self.identity_model.bind, &[0]);
620                    pass.set_vertex_buffer(0, axis_buf.slice(..));
621                    for (index, style) in [
622                        &self.styles.axis_x,
623                        &self.styles.axis_y,
624                        &self.styles.axis_z,
625                    ]
626                    .iter()
627                    .enumerate()
628                    {
629                        pass.set_bind_group(1, &style.bind, &[]);
630                        let i = index as u32;
631                        pass.draw(0..6, i..i + 1);
632                    }
633                }
634            }
635            // See-through faces (a `transparency` attribute, or a motion
636            // study's clip): after every opaque thing, through the blended
637            // context pipeline (depth test on, depth write off), each in its
638            // own style, whose alpha is the face's opacity. A picked or
639            // hovered one keeps its own look; its outline marks it.
640            if !params.settings.wireframe && params.settings.show_faces {
641                let mut any = false;
642                for (solid, gpu_solid) in visible_solids.iter().filter(|(solid, gpu_solid)| any_translucent(gpu_solid) && !solid.mesh.indices.is_empty()) {
643                    // A Line art step drew a part-opaque solid whole, flat.
644                    if scene.line_art.is_some() && !all_translucent(gpu_solid) {
645                        continue;
646                    }
647                    if !any {
648                        pass.set_pipeline(&self.context_pipeline);
649                        any = true;
650                    }
651                    bind_pose(&mut pass, gpu_scene.models.as_ref(), &self.identity_model, gpu_solid.model_slot);
652                    pass.set_vertex_buffer(0, gpu_solid.vertex_buf.slice(..));
653                    pass.set_index_buffer(gpu_solid.index_buf.slice(..), wgpu::IndexFormat::Uint32);
654                    // One style, nothing to leave out: the whole mesh (or its
655                    // visible faces) in one go.
656                    if all_translucent(gpu_solid) && gpu_solid.face_styles.is_empty() {
657                        pass.set_bind_group(1, &gpu_solid.base_style.bind, &[]);
658                        draw_visible_faces(&mut pass, solid, gpu_solid);
659                        continue;
660                    }
661                    // Otherwise walk the faces, coalescing contiguous ones
662                    // that share a style.
663                    type Run = (Option<u32>, u32, u32); // slot, first, count
664                    let mut run: Option<Run> = None;
665                    let flush = |pass: &mut wgpu::RenderPass, run: &mut Option<Run>| {
666                        if let Some((slot, first, count)) = run.take() {
667                            let style = slot.and_then(|s| gpu_solid.face_styles.get(s as usize)).unwrap_or(&gpu_solid.base_style);
668                            pass.set_bind_group(1, &style.bind, &[]);
669                            pass.draw_indexed(first..first + count, 0, 0..1);
670                        }
671                    };
672                    for (index, range) in gpu_solid.faces.iter().enumerate() {
673                        if range.index_count == 0 {
674                            continue;
675                        }
676                        if !range.translucent || !solid.visibility.is_face_visible(index) {
677                            flush(&mut pass, &mut run);
678                            continue;
679                        }
680                        match &mut run {
681                            Some((slot, first, count)) if *slot == range.style && *first + *count == range.first_index => {
682                                *count += range.index_count;
683                            }
684                            _ => {
685                                flush(&mut pass, &mut run);
686                                run = Some((range.style, range.first_index, range.index_count));
687                            }
688                        }
689                    }
690                    flush(&mut pass, &mut run);
691                }
692            }
693            if let Some((gpu_context, context_scene)) = context {
694                // Blend without depth writes: surroundings must not hide the
695                // editable geometry. Keep the work part's depth buffer intact.
696                self.context_style.write(&self.queue, context_scene.tint.unwrap_or(super::WORK_PART_CONTEXT_RGBA), [0.0; 4]);
697                pass.set_pipeline(&self.context_pipeline);
698                pass.set_bind_group(1, &self.context_style.bind, &[]);
699                for solid in context_scene.solids().iter().filter(|solid| solid.visible) {
700                    let Some(gpu) = gpu_context.solids.get(&solid.name) else { continue };
701                    bind_pose(&mut pass, gpu_context.models.as_ref(), &self.identity_model, gpu.model_slot);
702                    pass.set_vertex_buffer(0, gpu.vertex_buf.slice(..));
703                    pass.set_index_buffer(gpu.index_buf.slice(..), wgpu::IndexFormat::Uint32);
704                    if !solid.visibility.any_face_hidden() {
705                        pass.draw_indexed(0..solid.mesh.indices.len() as u32, 0, 0..1);
706                        continue;
707                    }
708                    for (index, face) in gpu.faces.iter().enumerate() {
709                        if solid.visibility.is_face_visible(index) {
710                            pass.draw_indexed(face.first_index..face.first_index + face.index_count, 0, 0..1);
711                        }
712                    }
713                }
714                // The context face picked or hovered, over its translucent self;
715                // or the context edge a sketch would copy, as a lit edge.
716                for (solid_name, face_name, selected) in &context_scene.highlight {
717                    let Some(solid) = context_scene.solid(solid_name) else { continue };
718                    let Some(gpu) = gpu_context.solids.get(solid_name) else { continue };
719                    let Some(index) = solid.faces.iter().position(|face| &face.name == face_name) else {
720                        let edge = solid.edges.iter().position(|edge| &edge.name == face_name);
721                        let (Some(index), Some(edge_buf)) = (edge, &gpu.edge_buf) else { continue };
722                        let Some(range) = gpu.edges.get(index) else { continue };
723                        pass.set_pipeline(&self.edge_visible_pipeline);
724                        pass.set_bind_group(1, if *selected { &self.styles.edge_selected.bind } else { &self.styles.edge_hovered.bind }, &[]);
725                        bind_pose(&mut pass, gpu_context.models.as_ref(), &self.identity_model, gpu.model_slot);
726                        pass.set_vertex_buffer(0, edge_buf.slice(..));
727                        pass.draw(0..6, range.first_instance..range.first_instance + range.instance_count);
728                        pass.set_pipeline(&self.context_pipeline);
729                        continue;
730                    };
731                    let Some(range) = gpu.faces.get(index) else { continue };
732                    pass.set_bind_group(1, if *selected { &self.context_selected.bind } else { &self.context_hovered.bind }, &[]);
733                    bind_pose(&mut pass, gpu_context.models.as_ref(), &self.identity_model, gpu.model_slot);
734                    pass.set_vertex_buffer(0, gpu.vertex_buf.slice(..));
735                    pass.set_index_buffer(gpu.index_buf.slice(..), wgpu::IndexFormat::Uint32);
736                    pass.draw_indexed(range.first_index..range.first_index + range.index_count, 0, 0..1);
737                }
738            }
739        }
740
741        // --- Overlay-widget passes: the brep-gizmos overlay drawn
742        //     over the solids in a depth-cleared pass so widgets read on top.
743        //     The main overlay uses the scene camera + full viewport; the
744        //     ViewCube uses its own mini-camera + corner viewport.
745        if let Some(overlay) = params.overlay {
746            let make_tris = |ov: &brep_gizmos::Overlay| -> Option<wgpu::Buffer> {
747                let verts = overlay_tri_verts(ov);
748                (!verts.is_empty()).then(|| {
749                    self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
750                        label: Some("overlay tris"),
751                        contents: bytemuck::cast_slice(&verts),
752                        usage: wgpu::BufferUsages::VERTEX,
753                    })
754                })
755            };
756            let make_lines = |ov: &brep_gizmos::Overlay| -> Option<wgpu::Buffer> {
757                let insts = overlay_line_insts(ov);
758                (!insts.is_empty()).then(|| {
759                    self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
760                        label: Some("overlay lines"),
761                        contents: bytemuck::cast_slice(&insts),
762                        usage: wgpu::BufferUsages::VERTEX,
763                    })
764                })
765            };
766
767            let main_tri_count = overlay.main.tris.len() as u32;
768            let main_line_count = (overlay.main.lines.len() / 2) as u32;
769            let main_tri_buf = make_tris(&overlay.main);
770            let main_line_buf = make_lines(&overlay.main);
771            if main_tri_buf.is_some() || main_line_buf.is_some() {
772                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
773                    label: Some("overlay-main"),
774                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
775                        view: &targets.msaa_view,
776                        depth_slice: None,
777                        resolve_target: Some(resolve_view),
778                        ops: wgpu::Operations {
779                            load: wgpu::LoadOp::Load,
780                            store: wgpu::StoreOp::Store,
781                        },
782                    })],
783                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
784                        view: &targets.depth_view,
785                        depth_ops: Some(wgpu::Operations {
786                            load: wgpu::LoadOp::Clear(1.0),
787                            store: wgpu::StoreOp::Discard,
788                        }),
789                        stencil_ops: None,
790                    }),
791                    timestamp_writes: None,
792                    occlusion_query_set: None,
793                    multiview_mask: None,
794                });
795                pass.set_bind_group(0, &self.globals_bind, &[]);
796                pass.set_bind_group(1, &self.styles.overlay_line.bind, &[]);
797                if let Some(buf) = &main_tri_buf {
798                    pass.set_vertex_buffer(0, buf.slice(..));
799                    // The datum/construction PLANE tris come FIRST; draw them with
800                    // depth-write OFF so a translucent plane never occludes the
801                    // gizmo/dimension tris that follow. The rest keep depth-write
802                    // so gizmos self-occlude correctly.
803                    let plane_verts = (overlay.plane_tri_verts as u32).min(main_tri_count);
804                    if plane_verts > 0 {
805                        pass.set_pipeline(&self.overlay_tri_nodepth_pipeline);
806                        pass.draw(0..plane_verts, 0..1);
807                    }
808                    if plane_verts < main_tri_count {
809                        pass.set_pipeline(&self.overlay_tri_pipeline);
810                        pass.draw(plane_verts..main_tri_count, 0..1);
811                    }
812                }
813                if let Some(buf) = &main_line_buf {
814                    pass.set_pipeline(&self.overlay_line_pipeline);
815                    pass.set_vertex_buffer(0, buf.slice(..));
816                    pass.draw(0..6, 0..main_line_count);
817                }
818            }
819
820            if let Some(vc) = &overlay.viewcube {
821                let dpr = params.dpr.max(1e-3);
822                let mut x = (vc.rect_css[0] * dpr).max(0.0);
823                let mut y = (vc.rect_css[1] * dpr).max(0.0);
824                let mut w = (vc.rect_css[2] * dpr).max(1.0);
825                let mut h = (vc.rect_css[3] * dpr).max(1.0);
826                // Clamp the corner viewport to the framebuffer.
827                w = w.min(width as f32 - x).max(1.0);
828                h = h.min(height as f32 - y).max(1.0);
829                x = x.min(width as f32 - w).max(0.0);
830                y = y.min(height as f32 - h).max(0.0);
831
832                let vc_globals = Globals {
833                    view_proj: vc.view_proj,
834                    viewport: [w, h, dpr, 0.0],
835                    forward: [vc.forward[0], vc.forward[1], vc.forward[2], 0.0],
836                };
837                self.queue
838                    .write_buffer(&self.vc_globals_buf, 0, bytemuck::bytes_of(&vc_globals));
839
840                let vc_tri_count = vc.overlay.tris.len() as u32;
841                let vc_line_count = (vc.overlay.lines.len() / 2) as u32;
842                let vc_tri_buf = make_tris(&vc.overlay);
843                let vc_line_buf = make_lines(&vc.overlay);
844                if vc_tri_buf.is_some() || vc_line_buf.is_some() {
845                    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
846                        label: Some("overlay-viewcube"),
847                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
848                            view: &targets.msaa_view,
849                            depth_slice: None,
850                            resolve_target: Some(resolve_view),
851                            ops: wgpu::Operations {
852                                load: wgpu::LoadOp::Load,
853                                store: wgpu::StoreOp::Store,
854                            },
855                        })],
856                        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
857                            view: &targets.depth_view,
858                            depth_ops: Some(wgpu::Operations {
859                                load: wgpu::LoadOp::Clear(1.0),
860                                store: wgpu::StoreOp::Discard,
861                            }),
862                            stencil_ops: None,
863                        }),
864                        timestamp_writes: None,
865                        occlusion_query_set: None,
866                        multiview_mask: None,
867                    });
868                    pass.set_viewport(x, y, w, h, 0.0, 1.0);
869                    pass.set_scissor_rect(x as u32, y as u32, w as u32, h as u32);
870                    pass.set_bind_group(0, &self.vc_globals_bind, &[]);
871                    pass.set_bind_group(1, &self.styles.overlay_line.bind, &[]);
872                    if let Some(buf) = &vc_tri_buf {
873                        pass.set_pipeline(&self.overlay_tri_pipeline);
874                        pass.set_vertex_buffer(0, buf.slice(..));
875                        pass.draw(0..vc_tri_count, 0..1);
876                    }
877                    if let Some(buf) = &vc_line_buf {
878                        pass.set_pipeline(&self.overlay_line_pipeline);
879                        pass.set_vertex_buffer(0, buf.slice(..));
880                        pass.draw(0..6, 0..vc_line_count);
881                    }
882                }
883            }
884        }
885
886        self.queue.submit([encoder.finish()]);
887    }
888
889    /// Headless capture (R32/R34): render the scene and return PNG bytes
890    /// (8-bit RGB, no ancillary chunks — deterministic, R33).
891    #[cfg(not(target_arch = "wasm32"))]
892    pub fn render_to_png(
893        &mut self,
894        scene: &RenderScene,
895        camera: &Camera,
896        width: u32,
897        height: u32,
898    ) -> Result<Vec<u8>, String> {
899        let settings = RenderSettings::artifact();
900        let mut gpu_scene = self.upload_scene_with(scene, &settings);
901        self.render_gpu_scene_to_png(&mut gpu_scene, scene, camera, width, height)
902    }
903
904    /// [`Self::render_to_png`] from buffers the caller already holds (synced
905    /// with [`RenderSettings::artifact`]): what the viewport's retained GPU
906    /// scene would draw.
907    #[cfg(not(target_arch = "wasm32"))]
908    pub(crate) fn render_gpu_scene_to_png(
909        &mut self,
910        gpu_scene: &mut GpuScene,
911        scene: &RenderScene,
912        camera: &Camera,
913        width: u32,
914        height: u32,
915    ) -> Result<Vec<u8>, String> {
916        let settings = RenderSettings::artifact();
917        let rgb = self.render_gpu_scene_to_rgb(gpu_scene, scene, camera, width, height, &settings)?;
918        encode_png(&rgb, width, height)
919    }
920
921    /// Draw `scene` through `gpu_scene` (synced or uploaded by the caller) at
922    /// `width`×`height` under `settings` and read the frame back as packed
923    /// RGB, top row first: what a motion study's video export encodes frame
924    /// by frame with the viewport's own render core and the user's settings.
925    #[cfg(not(target_arch = "wasm32"))]
926    pub fn render_gpu_scene_to_rgb(
927        &mut self,
928        gpu_scene: &mut GpuScene,
929        scene: &RenderScene,
930        camera: &Camera,
931        width: u32,
932        height: u32,
933        settings: &RenderSettings,
934    ) -> Result<Vec<u8>, String> {
935        let emphasis = Emphasis::default();
936        let params = FrameParams {
937            camera,
938            width,
939            height,
940            dpr: 1.0,
941            settings,
942            emphasis: &emphasis,
943            world_per_pixel: 0.0,
944            overlay: None,
945        };
946        let resolve = self.device.create_texture(&wgpu::TextureDescriptor {
947            label: Some("resolve"),
948            size: wgpu::Extent3d {
949                width,
950                height,
951                depth_or_array_layers: 1,
952            },
953            mip_level_count: 1,
954            sample_count: 1,
955            dimension: wgpu::TextureDimension::D2,
956            format: self.format,
957            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
958            view_formats: &[],
959        });
960        let resolve_view = resolve.create_view(&Default::default());
961        self.render_to_view(gpu_scene, scene, &params, &resolve_view);
962
963        // Readback: rows padded to 256 bytes per wgpu's copy alignment.
964        let bytes_per_row = (width * 4).div_ceil(256) * 256;
965        let readback = self.device.create_buffer(&wgpu::BufferDescriptor {
966            label: Some("readback"),
967            size: bytes_per_row as u64 * height as u64,
968            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
969            mapped_at_creation: false,
970        });
971        let mut encoder = self
972            .device
973            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
974                label: Some("readback"),
975            });
976        encoder.copy_texture_to_buffer(
977            wgpu::TexelCopyTextureInfo {
978                texture: &resolve,
979                mip_level: 0,
980                origin: wgpu::Origin3d::ZERO,
981                aspect: wgpu::TextureAspect::All,
982            },
983            wgpu::TexelCopyBufferInfo {
984                buffer: &readback,
985                layout: wgpu::TexelCopyBufferLayout {
986                    offset: 0,
987                    bytes_per_row: Some(bytes_per_row),
988                    rows_per_image: None,
989                },
990            },
991            wgpu::Extent3d {
992                width,
993                height,
994                depth_or_array_layers: 1,
995            },
996        );
997        self.queue.submit([encoder.finish()]);
998
999        let slice = readback.slice(..);
1000        let (sender, receiver) = std::sync::mpsc::channel();
1001        slice.map_async(wgpu::MapMode::Read, move |result| {
1002            let _ = sender.send(result);
1003        });
1004        self.device
1005            .poll(wgpu::PollType::wait_indefinitely())
1006            .map_err(|error| format!("wgpu poll: {error:?}"))?;
1007        receiver
1008            .recv()
1009            .map_err(|_| "readback callback dropped".to_string())?
1010            .map_err(|error| format!("readback map failed: {error:?}"))?;
1011
1012        let data = slice.get_mapped_range();
1013        let mut rgb = Vec::with_capacity((width * height * 3) as usize);
1014        for row in 0..height {
1015            let start = (row * bytes_per_row) as usize;
1016            for col in 0..width as usize {
1017                let px = start + col * 4;
1018                rgb.extend_from_slice(&data[px..px + 3]);
1019            }
1020        }
1021        drop(data);
1022        readback.unmap();
1023        Ok(rgb)
1024    }
1025}
1026
1027/// Issue draw calls for a solid's VISIBLE edge instances only, coalescing
1028/// contiguous edge ranges into as few `draw`s as possible. Used by the
1029/// single-style edge passes (occluded/hidden, and the no-emphasis visible pass)
1030/// when the solid has any hidden edge — the caller has already bound the style.
1031/// The coarsest view, in world millimetres per CSS pixel, that still draws AUX
1032/// edges — a board's copper outline. Past it a 0.2 mm track is under two
1033/// pixels, so its outline would cover it instead of edging it and a dense track
1034/// field reads as one slab; and a board seen whole at that scale is exactly
1035/// when the most of its thousands of outline segments are on screen at once.
1036/// Zooming in brings them back.
1037const AUX_EDGE_MAX_WORLD_PER_PIXEL: f64 = 0.1;
1038
1039/// Which of a solid's edges a [`draw_visible_edge_ranges`] call draws.
1040#[derive(Clone, Copy, PartialEq, Eq)]
1041enum EdgeFilter {
1042    /// The solid's own edges, not its display-only (aux) ones.
1043    Real,
1044    /// Only the display-only ones.
1045    Aux,
1046}
1047
1048/// Draw a solid's triangles with whatever style is bound, its hidden faces
1049/// left out (contiguous visible faces drawn as one range).
1050fn draw_visible_faces(pass: &mut wgpu::RenderPass<'_>, solid: &SolidDisplay, gpu_solid: &GpuSolid) {
1051    if !solid.visibility.any_face_hidden() {
1052        pass.draw_indexed(0..solid.mesh.indices.len() as u32, 0, 0..1);
1053        return;
1054    }
1055    let mut run: Option<(u32, u32)> = None; // first_index, count
1056    for index in 0..solid.faces.len() {
1057        let range = &gpu_solid.faces[index];
1058        if range.index_count == 0 {
1059            continue;
1060        }
1061        if !solid.visibility.is_face_visible(index) {
1062            if let Some((first, count)) = run.take() {
1063                pass.draw_indexed(first..first + count, 0, 0..1);
1064            }
1065            continue;
1066        }
1067        match &mut run {
1068            Some((first, count)) if *first + *count == range.first_index => *count += range.index_count,
1069            _ => {
1070                if let Some((first, count)) = run.take() {
1071                    pass.draw_indexed(first..first + count, 0, 0..1);
1072                }
1073                run = Some((range.first_index, range.index_count));
1074            }
1075        }
1076    }
1077    if let Some((first, count)) = run {
1078        pass.draw_indexed(first..first + count, 0, 0..1);
1079    }
1080}
1081
1082/// Draw a solid's edges each in the bind group `bind_for` gives it (`None`:
1083/// not drawn), contiguous edges sharing one coalesced into a single call.
1084fn draw_edge_runs<'a>(
1085    pass: &mut wgpu::RenderPass<'_>,
1086    solid: &SolidDisplay,
1087    gpu_solid: &GpuSolid,
1088    bind_for: impl Fn(usize, &crate::scene::EdgeDisplay) -> Option<&'a wgpu::BindGroup>,
1089) {
1090    let mut run: Option<(&wgpu::BindGroup, u32, u32)> = None; // bind, first_instance, count
1091    for (index, edge) in solid.edges.iter().enumerate() {
1092        let range = &gpu_solid.edges[index];
1093        if range.instance_count == 0 {
1094            continue;
1095        }
1096        let bind = bind_for(index, edge);
1097        match (&mut run, bind) {
1098            (Some((run_bind, first, count)), Some(bind))
1099                if std::ptr::eq(*run_bind, bind) && *first + *count == range.first_instance =>
1100            {
1101                *count += range.instance_count;
1102            }
1103            _ => {
1104                if let Some((run_bind, first, count)) = run.take() {
1105                    pass.set_bind_group(1, run_bind, &[]);
1106                    pass.draw(0..6, first..first + count);
1107                }
1108                run = bind.map(|bind| (bind, range.first_instance, range.instance_count));
1109            }
1110        }
1111    }
1112    if let Some((run_bind, first, count)) = run {
1113        pass.set_bind_group(1, run_bind, &[]);
1114        pass.draw(0..6, first..first + count);
1115    }
1116}
1117
1118fn draw_visible_edge_ranges(
1119    pass: &mut wgpu::RenderPass<'_>,
1120    solid: &SolidDisplay,
1121    gpu_solid: &GpuSolid,
1122    filter: EdgeFilter,
1123) {
1124    let mut run: Option<(u32, u32)> = None; // first_instance, count
1125    for (index, edge) in solid.edges.iter().enumerate() {
1126        let range = &gpu_solid.edges[index];
1127        if range.instance_count == 0 {
1128            continue;
1129        }
1130        if !solid.visibility.is_edge_visible(index) || edge.aux != (filter == EdgeFilter::Aux) {
1131            if let Some((first, count)) = run.take() {
1132                pass.draw(0..6, first..first + count);
1133            }
1134            continue;
1135        }
1136        match &mut run {
1137            Some((first, count)) if *first + *count == range.first_instance => {
1138                *count += range.instance_count;
1139            }
1140            _ => {
1141                if let Some((first, count)) = run.take() {
1142                    pass.draw(0..6, first..first + count);
1143                }
1144                run = Some((range.first_instance, range.instance_count));
1145            }
1146        }
1147    }
1148    if let Some((first, count)) = run {
1149        pass.draw(0..6, first..first + count);
1150    }
1151}
1152
1153/// Convert a gizmo `Overlay`'s triangles into GPU vertices (per-vertex color).
1154fn overlay_tri_verts(ov: &brep_gizmos::Overlay) -> Vec<OverlayTriVertex> {
1155    ov.tris
1156        .iter()
1157        .map(|v| OverlayTriVertex {
1158            position: v.pos,
1159            normal: v.normal,
1160            color: v.color,
1161        })
1162        .collect()
1163}
1164
1165/// Convert a gizmo `Overlay`'s line segments (vertex pairs) into GPU instances
1166/// (per-instance color; both endpoints of a gizmo segment share a color).
1167fn overlay_line_insts(ov: &brep_gizmos::Overlay) -> Vec<OverlayLineInstance> {
1168    ov.lines
1169        .chunks_exact(2)
1170        .map(|pair| OverlayLineInstance {
1171            p0: pair[0].pos,
1172            p1: pair[1].pos,
1173            color: pair[0].color,
1174        })
1175        .collect()
1176}
1177
1178/// Bind a solid's pose: its slot of the scene's pose buffer (identity when
1179/// the scene holds none yet).
1180fn bind_pose(pass: &mut wgpu::RenderPass<'_>, models: Option<&ModelArena>, identity: &IdentityModel, slot: u32) {
1181    match models {
1182        Some(models) => pass.set_bind_group(2, &models.bind, &[ModelArena::offset(slot)]),
1183        None => pass.set_bind_group(2, &identity.bind, &[0]),
1184    }
1185}