Skip to main content

brep_render/
render.rs

1//! The wgpu render core — windowing-agnostic (the dual-target seam).
2//!
3//! [`RenderCore::render_to_view`] draws a [`RenderScene`] into ANY
4//! `wgpu::TextureView` (MSAA 4x): shaded faces with per-face selection/hover
5//! emphasis (R17), screen-constant-width edges with occluded portions dimmed
6//! rather than dropped (R17), selected-face boundary outlines, vertex point
7//! sprites, and the world-axis helper (R20). Presentation shells stay thin:
8//! - headless: [`RenderCore::render_to_png`] (render-to-texture → readback →
9//!   PNG bytes) — the artifact binary and R34 screenshot capture;
10//! - desktop: the winit shell hands the surface texture's view here;
11//! - web: the wasm canvas shell does the same.
12//!
13//! GPU buffers are retained per solid and reused while the solid's scene
14//! revision is unchanged (R10 — reused solids keep their buffers across
15//! history reruns). Determinism (R33): same scene + camera + size + styles ⇒
16//! the same command stream on the same device ⇒ identical PNG bytes.
17
18use crate::camera::Camera;
19use crate::color::{solid_color_srgb, srgb_to_linear};
20use crate::scene::{RenderScene, SolidDisplay};
21use crate::style::{Emphasis, EmphasisState, FaceColorMode, RenderSettings, Rgba};
22use std::collections::{HashMap, HashSet};
23use wgpu::util::DeviceExt;
24
25/// MSAA sample count (R7-equivalent quality).
26pub const SAMPLES: u32 = 4;
27/// Offscreen color format. Non-sRGB: the shaders encode explicitly, so the
28/// clear color's bytes land in the PNG exactly.
29pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
30const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
31
32/// Boundary-edge depth bias: NDC in orthographic, scaled by the remaining
33/// depth range in perspective (see vs_edge). Faces also carry rasterizer bias.
34const EDGE_NUDGE: f32 = 2e-4;
35/// A Line art step's outline widths outside the silhouette, CSS px.
36const LINE_ART_PLACED_OUTLINE_PX: f32 = 1.5;
37const LINE_ART_ADDING_OUTLINE_PX: f32 = 2.5;
38/// How far back (of the fitted depth range) an outline is pushed beyond what
39/// its faces' slopes call for (`vs_hull`).
40const LINE_ART_OUTLINE_DEPTH: f32 = 2e-3;
41
42#[repr(C)]
43#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
44struct Globals {
45    view_proj: [[f32; 4]; 4],
46    viewport: [f32; 4],
47    forward: [f32; 4],
48}
49
50/// A solid's pose on the GPU: the model matrix its buffers are drawn
51/// through, and the inverse transpose of its linear part for the normals.
52#[repr(C)]
53#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
54struct ModelParams {
55    model: [f32; 16],
56    normal: [f32; 16],
57}
58
59const IDENTITY4: [f32; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
60
61impl ModelParams {
62    fn of(pose: Option<&[f32; 16]>) -> Self {
63        let Some(m) = pose else { return Self { model: IDENTITY4, normal: IDENTITY4 } };
64        // The normals' matrix: the inverse transpose of the 3×3 linear part
65        // (equal to it for a rotation; it keeps them normal under a scale).
66        let a = |row: usize, col: usize| m[col * 4 + row] as f64;
67        let cof = |r0: usize, r1: usize, c0: usize, c1: usize| a(r0, c0) * a(r1, c1) - a(r0, c1) * a(r1, c0);
68        let det = a(0, 0) * cof(1, 2, 1, 2) - a(0, 1) * cof(1, 2, 0, 2) + a(0, 2) * cof(1, 2, 0, 1);
69        let mut normal = IDENTITY4;
70        if det.abs() > 1e-30 {
71            // (A⁻¹)ᵀ = cofactor(A) / det.
72            let c = [
73                [cof(1, 2, 1, 2), -cof(1, 2, 0, 2), cof(1, 2, 0, 1)],
74                [-cof(0, 2, 1, 2), cof(0, 2, 0, 2), -cof(0, 2, 0, 1)],
75                [cof(0, 1, 1, 2), -cof(0, 1, 0, 2), cof(0, 1, 0, 1)],
76            ];
77            for row in 0..3 {
78                for col in 0..3 {
79                    normal[col * 4 + row] = (c[row][col] / det) as f32;
80                }
81            }
82        }
83        Self { model: *m, normal }
84    }
85}
86
87/// Every solid pose of one GPU scene in ONE uniform buffer, a [`MODEL_STRIDE`]
88/// slot each, bound at the solid's offset (group 2, dynamic offset). A frame
89/// that moves 500 solids writes the changed range once: a write per solid was
90/// most of the frame (~0.25-0.8 ms a write under a software adapter).
91struct ModelArena {
92    buf: wgpu::Buffer,
93    bind: wgpu::BindGroup,
94    capacity: u32,
95    data: Vec<u8>,
96    free: Vec<u32>,
97    next: u32,
98    /// The byte range written since the last flush.
99    dirty: Option<(usize, usize)>,
100    /// The buffer is new (grown): the whole of it is written.
101    fresh: bool,
102}
103
104/// One pose slot: the uniform offset alignment every adapter honours.
105const MODEL_STRIDE: u64 = 256;
106
107fn model_binding(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, buf: &wgpu::Buffer, label: &str) -> wgpu::BindGroup {
108    device.create_bind_group(&wgpu::BindGroupDescriptor {
109        label: Some(label),
110        layout,
111        entries: &[wgpu::BindGroupEntry {
112            binding: 0,
113            resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
114                buffer: buf,
115                offset: 0,
116                size: std::num::NonZeroU64::new(std::mem::size_of::<ModelParams>() as u64),
117            }),
118        }],
119    })
120}
121
122fn model_buffer(device: &wgpu::Device, slots: u32, label: &str) -> wgpu::Buffer {
123    device.create_buffer(&wgpu::BufferDescriptor {
124        label: Some(label),
125        size: slots as u64 * MODEL_STRIDE,
126        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
127        mapped_at_creation: false,
128    })
129}
130
131impl ModelArena {
132    fn new(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, capacity: u32) -> Self {
133        let capacity = capacity.max(16);
134        let buf = model_buffer(device, capacity, "solid poses");
135        let bind = model_binding(device, layout, &buf, "solid poses");
136        Self { buf, bind, capacity, data: vec![0; capacity as usize * MODEL_STRIDE as usize], free: Vec::new(), next: 0, dirty: None, fresh: true }
137    }
138
139    fn alloc(&mut self) -> u32 {
140        self.free.pop().unwrap_or_else(|| {
141            self.next += 1;
142            self.next - 1
143        })
144    }
145
146    fn release(&mut self, slot: u32) {
147        self.free.push(slot);
148    }
149
150    fn set(&mut self, slot: u32, pose: Option<&[f32; 16]>) {
151        let need = (slot as usize + 1) * MODEL_STRIDE as usize;
152        if self.data.len() < need {
153            self.data.resize(need.next_power_of_two(), 0);
154        }
155        let at = slot as usize * MODEL_STRIDE as usize;
156        let params = ModelParams::of(pose);
157        let bytes = bytemuck::bytes_of(&params);
158        self.data[at..at + bytes.len()].copy_from_slice(bytes);
159        let (lo, hi) = self.dirty.unwrap_or((at, at + bytes.len()));
160        self.dirty = Some((lo.min(at), hi.max(at + bytes.len())));
161    }
162
163    fn offset(slot: u32) -> u32 {
164        (slot as u64 * MODEL_STRIDE) as u32
165    }
166
167    /// Put what changed on the GPU: one write (or a new, larger buffer).
168    fn flush(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, layout: &wgpu::BindGroupLayout) {
169        let slots = (self.data.len() / MODEL_STRIDE as usize) as u32;
170        if slots > self.capacity {
171            self.capacity = slots;
172            self.buf = model_buffer(device, slots, "solid poses");
173            self.bind = model_binding(device, layout, &self.buf, "solid poses");
174            self.fresh = true;
175        }
176        if std::mem::take(&mut self.fresh) {
177            queue.write_buffer(&self.buf, 0, &self.data[..self.capacity as usize * MODEL_STRIDE as usize]);
178        } else if let Some((lo, hi)) = self.dirty {
179            let hi = hi.next_multiple_of(4);
180            queue.write_buffer(&self.buf, lo as u64, &self.data[lo..hi]);
181        }
182        self.dirty = None;
183    }
184}
185
186/// A single identity pose for what the solid pipelines draw that is not a
187/// solid's own buffers (bound at offset 0).
188struct IdentityModel {
189    _buf: wgpu::Buffer,
190    bind: wgpu::BindGroup,
191}
192
193impl IdentityModel {
194    fn new(device: &wgpu::Device, queue: &wgpu::Queue, layout: &wgpu::BindGroupLayout) -> Self {
195        let buf = model_buffer(device, 1, "identity pose");
196        queue.write_buffer(&buf, 0, bytemuck::bytes_of(&ModelParams::of(None)));
197        let bind = model_binding(device, layout, &buf, "identity pose");
198        Self { _buf: buf, bind }
199    }
200}
201
202#[repr(C)]
203#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
204struct StyleParams {
205    color: [f32; 4],
206    params: [f32; 4],
207}
208
209#[repr(C)]
210#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
211struct MeshVertex {
212    position: [f32; 3],
213    normal: [f32; 3],
214}
215
216#[repr(C)]
217#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
218struct EdgeInstance {
219    p0: [f32; 3],
220    p1: [f32; 3],
221}
222
223#[repr(C)]
224#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
225struct PointInstance {
226    center: [f32; 3],
227}
228
229/// One overlay-widget line segment (per-instance colored, screen-constant width).
230#[repr(C)]
231#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
232struct OverlayLineInstance {
233    p0: [f32; 3],
234    p1: [f32; 3],
235    color: [f32; 4],
236}
237
238/// One overlay-widget triangle vertex (per-vertex colored, shaded).
239#[repr(C)]
240#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
241struct OverlayTriVertex {
242    position: [f32; 3],
243    normal: [f32; 3],
244    color: [f32; 4],
245}
246
247/// One uniform style buffer + its bind group (a material variant).
248struct StyleBuf {
249    buf: wgpu::Buffer,
250    bind: wgpu::BindGroup,
251}
252
253impl StyleBuf {
254    fn new(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, label: &str) -> Self {
255        let buf = device.create_buffer(&wgpu::BufferDescriptor {
256            label: Some(label),
257            size: std::mem::size_of::<StyleParams>() as u64,
258            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
259            mapped_at_creation: false,
260        });
261        let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
262            label: Some(label),
263            layout,
264            entries: &[wgpu::BindGroupEntry {
265                binding: 0,
266                resource: buf.as_entire_binding(),
267            }],
268        });
269        Self { buf, bind }
270    }
271
272    fn write(&self, queue: &wgpu::Queue, color: Rgba, params: [f32; 4]) {
273        queue.write_buffer(&self.buf, 0, bytemuck::bytes_of(&StyleParams { color, params }));
274    }
275}
276
277/// The global material variants (updated from [`RenderSettings`] each frame).
278struct GlobalStyles {
279    face_selected: StyleBuf,
280    face_hovered: StyleBuf,
281    edge_base: StyleBuf,
282    edge_selected: StyleBuf,
283    edge_hovered: StyleBuf,
284    edge_hidden: StyleBuf,
285    /// A display-only (AUX) edge at rest — a board's copper outline.
286    edge_aux: StyleBuf,
287    boundary: StyleBuf,
288    point_base: StyleBuf,
289    point_selected: StyleBuf,
290    point_hovered: StyleBuf,
291    axis_x: StyleBuf,
292    axis_y: StyleBuf,
293    axis_z: StyleBuf,
294    /// Overlay-widget line width (CSS px in `params.x`); color is per-instance.
295    overlay_line: StyleBuf,
296    /// A Line art instructions step ([`crate::scene::RenderScene::line_art`]):
297    /// the unlit fills, the visible edges and the outlines of the parts
298    /// earlier steps placed and of the parts the step adds.
299    line_art_placed_face: StyleBuf,
300    line_art_adding_face: StyleBuf,
301    line_art_placed_edge: StyleBuf,
302    line_art_adding_edge: StyleBuf,
303    line_art_placed_outline: StyleBuf,
304    line_art_adding_outline: StyleBuf,
305}
306
307struct FaceRange {
308    first_index: u32,
309    index_count: u32,
310    /// This face's slice of the WIREFRAME index buffer. Not derivable from
311    /// `first_index`: the wire buffer holds one segment per DISTINCT mesh edge
312    /// of the face, so its length depends on how the face's triangles share
313    /// edges, not on how many there are.
314    wire_first: u32,
315    wire_count: u32,
316    /// Index into [`GpuSolid::face_styles`] when this face carries its OWN
317    /// colour (a `color` metadata attribute on the face name); `None` = shade
318    /// with the solid's `base_style`.
319    style: Option<u32>,
320    /// This face draws see-through (its own or its solid's `transparency`, or
321    /// a motion study's clip): the opaque pass leaves it to the blended one.
322    translucent: bool,
323}
324
325/// The hasher behind the wireframe's per-face edge de-duplication.
326///
327/// The keys are pairs of mesh vertex INDICES — dense, small, and entirely under
328/// our control, so there is no adversary for SipHash to defend against, and its
329/// per-key cost is the whole cost of the de-duplication (three probes per
330/// triangle, at every solid upload). This is the multiply-xor mix `rustc-hash`
331/// uses, written out rather than depended on: `rustc-hash` only rides into this
332/// build through wgpu's internals, and a published crate should not take a
333/// direct dependency for fifteen lines.
334#[derive(Default)]
335struct EdgeHasher(u64);
336
337impl std::hash::Hasher for EdgeHasher {
338    fn write(&mut self, bytes: &[u8]) {
339        for &byte in bytes {
340            self.write_u32(u32::from(byte));
341        }
342    }
343
344    fn write_u32(&mut self, value: u32) {
345        // 2^64 / golden ratio: the odd multiplier spreads low-index bits into
346        // the high ones, which is where `finish` folds them back down from.
347        self.0 = (self.0 ^ u64::from(value)).wrapping_mul(0x9E37_79B9_7F4A_7C15);
348    }
349
350    fn finish(&self) -> u64 {
351        self.0 ^ (self.0 >> 32)
352    }
353}
354
355type BuildEdgeHasher = std::hash::BuildHasherDefault<EdgeHasher>;
356
357/// The least opacity a picked or hovered edge is drawn at, however clear its
358/// own `transparency` makes it, so the pick can still be seen.
359const EMPHASIS_EDGE_MIN_OPACITY: f32 = 0.35;
360
361struct EdgeRange {
362    first_instance: u32,
363    instance_count: u32,
364    /// Index into [`GpuSolid::edge_styles`] when this edge carries its OWN
365    /// colour or opacity (its metadata's); `None` draws it in the theme's.
366    style: Option<u32>,
367}
368
369/// One distinct per-edge look of a solid (a colour and an opacity), in the
370/// four states an edge is drawn in.
371struct EdgeStyle {
372    base: StyleBuf,
373    /// The selection colour at the edge's own opacity (floored, so a clear
374    /// edge can still be seen while it is picked).
375    selected: StyleBuf,
376    hovered: StyleBuf,
377    /// The occluded-pass look: the edge's colour dimmed like any hidden edge.
378    hidden: StyleBuf,
379}
380
381struct GpuSolid {
382    revision: u64,
383    /// The shape revision these buffers were built from (`shape_revision`, or
384    /// the revision itself for an unposed display): a display of the same
385    /// shape is re-posed by rewriting `vertex_buf`, `edge_buf` and `point_buf`.
386    shape: u64,
387    vertex_count: u32,
388    vertex_buf: wgpu::Buffer,
389    index_buf: wgpu::Buffer,
390    /// Line-list indices for the wireframe view (each triangle → its 3 edges).
391    wire_index_buf: wgpu::Buffer,
392    wire_index_count: u32,
393    faces: Vec<FaceRange>,
394    edge_buf: Option<wgpu::Buffer>,
395    edges: Vec<EdgeRange>,
396    /// The per-edge style palette (empty when no edge has a look of its own,
397    /// which keeps the whole-buffer edge draws).
398    edge_styles: Vec<EdgeStyle>,
399    edge_instances: u32,
400    /// The instances drawn by the OCCLUDED-edge pass: every edge's up to the
401    /// first AUX one. A display-only outline (a board's copper) is not dimmed
402    /// through what hides it — the bottom copper would ghost through the board
403    /// — and aux edges trail the real ones, so it is a prefix.
404    occludable_edge_instances: u32,
405    point_buf: Option<wgpu::Buffer>,
406    point_count: u32,
407    /// Per-solid base face style (uniform or hashed color; metadata override).
408    base_style: StyleBuf,
409    /// De-duplicated palette of PER-FACE styles — one entry per distinct face
410    /// colour on this solid, referenced by [`FaceRange::style`]. Empty for the
411    /// overwhelmingly common solid whose faces are all one colour, which is what
412    /// keeps the whole-mesh fast path in `frame.rs` alive.
413    face_styles: Vec<StyleBuf>,
414    /// The solid's own faces draw see-through (triangles no face claims too).
415    base_translucent: bool,
416    /// Some face differs from [`Self::base_translucent`]: an opaque face on a
417    /// see-through solid, or the reverse. Such a solid draws in both passes.
418    mixed_translucency: bool,
419    /// Selected/hovered face boundary outline segments (cache keyed by the
420    /// emphasis generation).
421    boundary: Option<BoundaryBuf>,
422    /// This solid's slot in its scene's [`ModelArena`] (the pose its buffers
423    /// are drawn through; identity unless posed).
424    model_slot: u32,
425    /// The buffers hold the geometry of `shape` itself, as uploaded: a pose
426    /// of that shape is then a matrix write. False once a re-pose rewrote
427    /// them (a drag), until the next upload.
428    holds_shape: bool,
429}
430
431struct BoundaryBuf {
432    emphasis_generation: u64,
433    revision: u64,
434    buf: Option<wgpu::Buffer>,
435    count: u32,
436}
437
438/// The Work part context tint: assembly components around the part being
439/// edited are drawn in this colour, alpha-blended without depth writes and
440/// without pick handles.
441pub const WORK_PART_CONTEXT_RGBA: [f32; 4] = [0.45, 0.55, 0.65, 0.22];
442
443/// A scene uploaded to GPU buffers, retained across frames; sync with
444/// [`RenderCore::sync_scene`].
445#[derive(Default)]
446pub struct GpuScene {
447    solids: HashMap<String, GpuSolid>,
448    /// Draw order (scene insertion order at last sync).
449    order: Vec<String>,
450    settings_generation: u64,
451    axis_buf: Option<wgpu::Buffer>,
452    /// Count of solid (re)uploads (R10 observability: a reused solid must NOT
453    /// bump this across a sync).
454    uploads: u64,
455    /// Count of in-place re-poses (positions rewritten, nothing rebuilt).
456    reposes: u64,
457    /// Count of poses drawn through a matrix (a 128-byte write, no vertex).
458    pose_writes: u64,
459    /// Every solid's pose, one buffer (made on the first sync).
460    models: Option<ModelArena>,
461}
462
463impl GpuScene {
464    /// Total solid buffer uploads since creation (test/telemetry hook for the
465    /// reused-buffer fast path).
466    pub fn upload_count(&self) -> u64 {
467        self.uploads
468    }
469
470    /// Total in-place re-poses since creation (a rigidly moved solid whose
471    /// buffers were rewritten rather than rebuilt).
472    pub fn repose_count(&self) -> u64 {
473        self.reposes
474    }
475
476    /// Total poses taken by a matrix write alone (the buffers kept the
477    /// shape's geometry and nothing of it was rewritten).
478    pub fn pose_write_count(&self) -> u64 {
479        self.pose_writes
480    }
481}
482
483struct CachedTargets {
484    width: u32,
485    height: u32,
486    msaa_view: wgpu::TextureView,
487    depth_view: wgpu::TextureView,
488}
489
490/// Everything a frame needs beyond the scene buffers.
491pub struct FrameParams<'a> {
492    pub camera: &'a Camera,
493    /// Physical pixel size of the target.
494    pub width: u32,
495    pub height: u32,
496    /// Device pixel ratio (CSS px → physical px) for line/point widths.
497    pub dpr: f32,
498    pub settings: &'a RenderSettings,
499    pub emphasis: &'a Emphasis,
500    /// World units per CSS pixel (for the screen-sized axis helper).
501    pub world_per_pixel: f64,
502    /// In-scene overlay widgets: transform gizmo, ViewCube, datum /
503    /// dimension / curve visuals. `None` on the artifact/headless path.
504    pub overlay: Option<&'a crate::widgets::WidgetOverlay>,
505}
506
507/// Create a headless device: adapter picked by `BREP_RENDER_ADAPTER`
508/// (case-insensitive substring of the adapter name, e.g. "llvmpipe") or wgpu's
509/// high-performance default. Native only — the browser shell gets its device
510/// from the canvas context.
511#[cfg(not(target_arch = "wasm32"))]
512pub fn create_headless_device() -> Result<(wgpu::Device, wgpu::Queue, String), String> {
513    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
514    let want = std::env::var("BREP_RENDER_ADAPTER").ok();
515    let adapter = if let Some(want) = &want {
516        let want_lower = want.to_lowercase();
517        pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all()))
518            .into_iter()
519            .find(|adapter| adapter.get_info().name.to_lowercase().contains(&want_lower))
520            .ok_or_else(|| format!("no adapter matching BREP_RENDER_ADAPTER={want}"))?
521    } else {
522        pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
523            power_preference: wgpu::PowerPreference::HighPerformance,
524            compatible_surface: None,
525            force_fallback_adapter: false,
526        }))
527        .map_err(|error| format!("no wgpu adapter available: {error}"))?
528    };
529    let info = adapter.get_info();
530    let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
531        label: Some("brep-render"),
532        ..Default::default()
533    }))
534    .map_err(|error| format!("wgpu device request failed: {error}"))?;
535    Ok((device, queue, format!("{} ({:?})", info.name, info.backend)))
536}
537
538/// The window-agnostic renderer: pipelines + layouts for one color format.
539pub struct RenderCore {
540    pub device: wgpu::Device,
541    pub queue: wgpu::Queue,
542    format: wgpu::TextureFormat,
543    globals_buf: wgpu::Buffer,
544    globals_bind: wgpu::BindGroup,
545    style_layout: wgpu::BindGroupLayout,
546    /// Group 2 of the solid pipelines: a solid's pose in its scene's
547    /// [`ModelArena`], at a dynamic offset.
548    model_layout: wgpu::BindGroupLayout,
549    /// Bound for whatever the solid pipelines draw that is not a solid's own
550    /// buffers (face boundaries, the world axes).
551    identity_model: IdentityModel,
552    mesh_pipeline: wgpu::RenderPipeline,
553    /// The Line art outline pass (`vs_hull`/`fs_hull`).
554    hull_pipeline: wgpu::RenderPipeline,
555    context_pipeline: wgpu::RenderPipeline,
556    context_style: StyleBuf,
557    /// A selected / hovered context face: the selection colours, still
558    /// translucent (the context pass blends without depth writes).
559    context_selected: StyleBuf,
560    context_hovered: StyleBuf,
561    wire_pipeline: wgpu::RenderPipeline,
562    edge_visible_pipeline: wgpu::RenderPipeline,
563    edge_hidden_pipeline: wgpu::RenderPipeline,
564    point_pipeline: wgpu::RenderPipeline,
565    /// Overlay-widget passes: shaded per-vertex tris + screen-constant
566    /// per-instance lines, drawn over the solids in a depth-cleared pass.
567    overlay_tri_pipeline: wgpu::RenderPipeline,
568    /// Same as `overlay_tri_pipeline` but WITHOUT depth-write — for the datum/
569    /// construction PLANES, which are translucent UI aids that must NOT occlude
570    /// the gizmos/dimensions drawn after them (a plane no longer hides an offset
571    /// arrow behind it). The gizmo tris still use the depth-writing pipeline so
572    /// they self-occlude correctly.
573    overlay_tri_nodepth_pipeline: wgpu::RenderPipeline,
574    overlay_line_pipeline: wgpu::RenderPipeline,
575    /// Second globals buffer for the ViewCube pass (its own mini-camera).
576    vc_globals_buf: wgpu::Buffer,
577    vc_globals_bind: wgpu::BindGroup,
578    styles: GlobalStyles,
579    targets: Option<CachedTargets>,
580}
581
582/// 8-bit RGB PNG encode (no text/time chunks — byte-deterministic).
583#[cfg(not(target_arch = "wasm32"))]
584fn encode_png(rgb: &[u8], width: u32, height: u32) -> Result<Vec<u8>, String> {
585    brep_gizmos::raster::encode_png(rgb, width, height, png::ColorType::Rgb)
586}
587
588mod pipelines;
589mod scene_sync;
590mod frame;