diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 7980b295f..d4c0c46ad 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -37,6 +37,15 @@ fn clipped(p: vec3) -> bool { return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w; } @group(0) @binding(0) var u: U; +// The scene's colours, 2048 entries to a row: an R32Uint texture rather than a storage buffer, +// so the viewport draws on WebGL2 (which has no storage buffers) as well. +@group(0) @binding(1) var pal: texture_2d; + +/// The colour at palette entry `i`, as byte/255 (the old Unorm8x4 conversion, bit for bit). +fn palette(i: u32) -> vec4 { + let v = textureLoad(pal, vec2(i32(i & 2047u), i32(i >> 11u)), 0).x; + return vec4(f32(v & 255u), f32((v >> 8u) & 255u), f32((v >> 16u) & 255u), f32((v >> 24u) & 255u)) / 255.0; +} fn to_linear(c: vec3) -> vec3 { return select(c, pow((c + vec3(0.055)) / vec3(1.055), vec3(2.4)), c > vec3(0.04045)); @@ -57,11 +66,11 @@ struct TOut { }; @vertex -fn vs_tri(@location(0) p: vec3, @location(1) n: vec3, @location(2) c: vec4) -> TOut { +fn vs_tri(@location(0) p: vec3, @location(1) n: vec3, @location(2) c: u32) -> TOut { var o: TOut; o.pos = u.vp * vec4(p, 1.0); o.n = n; - o.c = c; + o.c = palette(c); o.wp = p; return o; } @@ -76,14 +85,14 @@ fn vs_tri_inst( @location(3) r0: vec4, @location(4) r1: vec4, @location(5) r2: vec4, - @location(6) c: vec4, + @location(6) c: u32, ) -> TOut { let q = vec4(p, 1.0); let wp = vec3(dot(r0, q), dot(r1, q), dot(r2, q)); var o: TOut; o.pos = u.vp * vec4(wp, 1.0); o.n = vec3(dot(r0.xyz, n), dot(r1.xyz, n), dot(r2.xyz, n)); - o.c = c; + o.c = palette(c); o.wp = wp; return o; } @@ -106,14 +115,14 @@ fn vs_tri_inst_flat( @location(3) r0: vec4, @location(4) r1: vec4, @location(5) r2: vec4, - @location(6) c: vec4, + @location(6) c: u32, ) -> FOut { let q = vec4(p, 1.0); let wp = vec3(dot(r0, q), dot(r1, q), dot(r2, q)); var o: FOut; o.pos = u.vp * vec4(wp, 1.0); o.rp = wp - u.eye.xyz; - o.c = c; + o.c = palette(c); return o; } @@ -546,7 +555,7 @@ fn lifted_z(p: vec3, c: vec4, px: f32, half: vec2) -> f32 { } @vertex -fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3, @location(1) b: vec3, @location(2) c: vec4, @location(3) wbits: u32) -> LOut { +fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3, @location(1) b: vec3, @location(2) c: u32, @location(3) wbits: u32) -> LOut { var pa = a; var pb = b; var ca = u.vp * vec4(a, 1.0); @@ -596,7 +605,8 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3, @location( } var o: LOut; o.pos = vec4(base.xy + off / half * base.w, z, base.w); - o.c = vec4(c.rgb, c.a * (wa / wd)); + let col = palette(c); + o.c = vec4(col.rgb, col.a * (wa / wd)); o.wp = select(pa, pb, t > 0.5); return o; } diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index 25c99daa1..225c9923e 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -76,7 +76,7 @@ impl Capturer { let samples = if samples > 1 && flags(FORMAT).sample_count_supported(samples) && flags(depth).sample_count_supported(samples) { samples } else { 1 }; let scopes = error_scopes(&device); - let renderer = Renderer::new(&device, GpuTarget { format: FORMAT, depth: Some(depth), samples, tess: false }, None); + let renderer = Renderer::new(&device, GpuTarget { format: FORMAT, depth: Some(depth), samples, tess: false, oit: false }, None); let background = background_pipeline(&device, samples, depth); caught(scopes).map_or(Ok(()), |e| Err(GpuError::Pipeline(e)))?; let max_side = device.limits().max_texture_dimension_2d.min(MAX_SIDE); @@ -417,7 +417,7 @@ pub fn scene_geometry(scene: &Scene) -> GpuScene { let faces: HashMap = m.face_colors.iter().copied().collect(); let mesh = &m.mesh; for (ti, t) in mesh.triangles.iter().enumerate() { - let col = c4(mesh.tri_face.get(ti).and_then(|f| faces.get(f)).copied().unwrap_or(m.color)); + let col = sc.color(c4(mesh.tri_face.get(ti).and_then(|f| faces.get(f)).copied().unwrap_or(m.color))); let [Some(a), Some(b), Some(c)] = t.map(|k| mesh.positions.get(k as usize).copied()) else { continue }; let flat = (b - a).cross(c - a).normalized().unwrap_or(Vec3::Z); for (k, p) in t.iter().zip([a, b, c]) { @@ -430,15 +430,17 @@ pub fn scene_geometry(scene: &Scene) -> GpuScene { } } } - let c4 = |c: Rgb, a: f32| [c.0, c.1, c.2, (a.clamp(0.0, 1.0) * 255.0).round() as u8]; + let alpha = |a: f32| (a.clamp(0.0, 1.0) * 255.0).round() as u8; for l in &scene.grid { + let col = sc.color([l.color.0, l.color.1, l.color.2, alpha(l.alpha)]); for w in l.points.windows(2) { - sc.under_line(w[0].to_f32(), w[1].to_f32(), c4(l.color, l.alpha), l.width as f32); + sc.under_line(w[0].to_f32(), w[1].to_f32(), col, l.width as f32); } } for l in &scene.lines { + let col = sc.color([l.color.0, l.color.1, l.color.2, alpha(l.alpha)]); for w in l.points.windows(2) { - sc.line(w[0].to_f32(), w[1].to_f32(), c4(l.color, l.alpha), l.width as f32, l.on_top); + sc.line(w[0].to_f32(), w[1].to_f32(), col, l.width as f32, l.on_top); } } sc @@ -567,9 +569,10 @@ mod tests { }) } - /// The alpha of a triangle `scene_geometry` wrote (the last byte of its first vertex). - fn alpha(bytes: &[u8]) -> Option { - bytes.get(TRI_SIZE - 1).copied() + /// The colour of a triangle `scene_geometry` wrote (its first vertex's palette entry). + fn color(scene: &GpuScene, bytes: &[u8]) -> Option<[u8; 4]> { + let index = bytes.get(TRI_SIZE - 4..TRI_SIZE)?.try_into().ok().map(u32::from_le_bytes)?; + scene.palette.get(crate::view::PaletteIndex(index)) } /// A body the design draws see-through goes into the scene's glass, at its own alpha, and @@ -582,17 +585,19 @@ mod tests { let solid = geometry(1.0); assert_eq!((solid.tris.len(), solid.glass.len()), (3 * TRI_SIZE, 0)); - assert_eq!(alpha(&solid.tris), Some(255), "a solid body is drawn opaque"); + assert_eq!(color(&solid, &solid.tris), Some([200, 30, 30, 255]), "a solid body is drawn opaque"); let glass = geometry(0.3); assert_eq!((glass.tris.len(), glass.glass.len()), (0, 3 * TRI_SIZE), "a see-through body is glass, not a solid triangle"); - assert_eq!(alpha(&glass.glass), Some(77), "0.3 of 255"); + assert_eq!(color(&glass, &glass.glass).map(|c| c[3]), Some(77), "0.3 of 255"); // The threshold and the floor are the viewport's: an appearance a hair under 1 stays // solid, and opacity 0 still leaves a trace rather than vanishing. let almost = geometry(0.9995); assert_eq!((almost.tris.len(), almost.glass.len()), (3 * TRI_SIZE, 0), "an appearance a hair under 1 is still solid"); - assert_eq!(alpha(&geometry(0.0).glass), Some(13), "0.05 of 255"); + assert_eq!(color(&almost, &almost.tris).map(|c| c[3]), Some(255)); + let trace = geometry(0.0); + assert_eq!(color(&trace, &trace.glass).map(|c| c[3]), Some(13), "0.05 of 255"); } /// A face with a colour of its own is drawn in that colour, and takes its body's opacity: @@ -602,7 +607,6 @@ mod tests { let mesh = SceneMesh { mesh: sheet(), color: Rgb(200, 30, 30), face_colors: vec![(0, Rgb(0, 255, 0))], opacity: 0.5 }; let sc = scene_geometry(&Scene { meshes: vec![mesh], ..Default::default() }); assert_eq!(sc.tris.len(), 0); - let first = sc.glass.get(TRI_SIZE - 4..TRI_SIZE); - assert_eq!(first, Some(&[0, 255, 0, 128][..]), "the face's own colour at the body's alpha"); + assert_eq!(color(&sc, &sc.glass), Some([0, 255, 0, 128]), "the face's own colour at the body's alpha"); } } diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 31dc62ae5..28c6b7696 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -23,15 +23,105 @@ mod oit; #[cfg(not(target_arch = "wasm32"))] pub use msaa_check::MsaaCheck; -/// Triangle vertex: position (3 × f32), normal (3 × f32), sRGB colour (4 × u8). +/// Triangle vertex: position (3 × f32), normal (3 × f32), palette index (u32). pub const TRI_SIZE: usize = 28; pub const PBR_SIZE: usize = pbr::VERTEX_SIZE; -/// Line instance: a, b (3 × f32 each), colour (4 × u8), width in pixels (f32). +/// Line instance: a, b (3 × f32 each), palette index (u32), width in pixels (f32). pub const LINE_SIZE: usize = 32; /// Placement of an [`InstancedMesh`]: the rows of its rigid move (3 × 4 f32; a point's x, y and z -/// are each row's dot product with (p, 1)), then its colour (4 × u8). +/// are each row's dot product with (p, 1)), then its palette index (u32). pub const INSTANCE_SIZE: usize = 52; +/// An index into a scene's [`Palette`]. Deliberately not convertible from a colour: every +/// producer must go through a palette, and the compiler should say so. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +#[repr(transparent)] +pub struct PaletteIndex(pub u32); + +/// How many palette entries fit on one texel row: the shader reads `x = i & 2047`, +/// `y = i >> 11`. A power of two keeps the lookup a shift and a mask. +pub const PALETTE_WIDTH: u32 = 2048; +/// Most palette entries a scene may carry (2048 × 512): the palette is an `R32Uint` texture +/// (`downlevel_defaults`/WebGL2 have no storage buffers in the vertex stage). +pub const MAX_PALETTE: usize = 1 << 20; + +/// sRGB RGBA bytes, looked up in the shader by [`PaletteIndex`]. +/// +/// The first [`Palette::stable_len`] entries are stable for a scene: cached block bytes keep +/// referring to them, so appearance edits only change their values. Entries after that are +/// interned per build for ephemeral geometry (grids, highlights, sketch, previews). +#[derive(Clone, Debug, Default)] +pub struct Palette { + entries: Vec<[u8; 4]>, + lookup: std::collections::HashMap<[u8; 4], u32>, + stable_len: usize, +} + +impl Palette { + /// A palette whose entries are all stable (the model scene's body/face slots). + pub fn with_stable(entries: Vec<[u8; 4]>) -> Palette { + Palette { stable_len: entries.len(), entries, lookup: std::collections::HashMap::new() } + } + + /// Where the stable entries end and the per-build interned ones begin. + pub fn stable_len(&self) -> usize { + self.stable_len + } + + pub fn entries(&self) -> &[[u8; 4]] { + &self.entries + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// The colour at `i`, if the palette has it. + pub fn get(&self, i: PaletteIndex) -> Option<[u8; 4]> { + self.entries.get(i.0 as usize).copied() + } + + /// Set an entry's colour; `false` when the index is out of range. Stable entries are updated + /// in place (what appearance and theme edits do); interned entries keep their lookup current. + pub fn set(&mut self, i: PaletteIndex, rgba: [u8; 4]) -> bool { + let at = i.0 as usize; + let ephemeral = at >= self.stable_len; + let Some(slot) = self.entries.get_mut(at) else { return false }; + if ephemeral { + self.lookup.remove(slot); + } + *slot = rgba; + if ephemeral { + self.lookup.insert(rgba, i.0); + } + true + } + + /// A colour's index in the per-build section, appended when it is new. At [`MAX_PALETTE`] + /// the first entry stands in: far past what any real scene interns, and never a panic. + pub fn intern(&mut self, rgba: [u8; 4]) -> PaletteIndex { + if let Some(&i) = self.lookup.get(&rgba) { + return PaletteIndex(i); + } + if self.entries.len() >= MAX_PALETTE { + return PaletteIndex(0); + } + let i = u32::try_from(self.entries.len()).unwrap_or(0); + self.entries.push(rgba); + self.lookup.insert(rgba, i); + PaletteIndex(i) + } + + /// The palette as the shader's `R32Uint` texels (rgba bytes packed little-endian). + pub fn texels(&self) -> Vec { + self.entries.iter().map(|[r, g, b, a]| u32::from_le_bytes([*r, *g, *b, *a])).collect() + } +} + /// The width slot of a lifted line ([`GpuScene::lifted_line`]): the top bit set (a plain line's /// width is a positive `f32`, whose top bit is clear), the width in eighths of a pixel (7 bits, /// up to 15.9 px), and the two faces' normals in octahedral form (6 bits a component). The @@ -64,12 +154,15 @@ fn octahedral6(n: [f32; 3]) -> u32 { /// whole-body highlight colours (`uniform_bytes`). const UNIFORM_SIZE: u64 = 416; -/// A body drawn from its display plan, evaluated on the GPU: the plan, and a colour per face -/// (the plan's face numbering; faces past the end take the last colour). +/// A body drawn from its display plan, evaluated on the GPU: the plan, and a palette index per +/// face (the plan's face numbering; faces past the end take the last index). #[derive(Clone)] pub struct PlannedBody { pub plan: Arc, - pub face_colors: Vec<[u8; 4]>, + pub face_colors: Vec, + /// How the whole body is drawn: opaque with the model, or faded or see-through blended + /// order-independently (only on a renderer that does that: [`GpuTarget::oit`]). + pub class: TriClass, } /// What the viewport's last frame drew, counted as it was drawn (the performance overlay, #2548). @@ -84,6 +177,23 @@ pub struct DrawStats { pub supersampled: bool, } +/// What the last scene change uploaded to the GPU, in bytes: what an edit costs beyond the CPU +/// work of building the scene. Counted per scene ([`Renderer::uploads`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct UploadStats { + /// Triangle vertices, index lists and lines: of the blocks and of the scene's own lists, and + /// the triangles shared by instanced meshes. + pub geometry: u64, + /// Placements of instanced meshes. + pub placements: u64, + /// Palette rows written. + pub palette: u64, + /// Planned bodies' per-vertex palette indices. + pub planned: u64, + /// Vertices of planned bodies evaluated again on the GPU (chunks whose plans changed). + pub evaluated: u64, +} + /// The renderer's last [`DrawStats`], shared with the UI that shows them. pub type DrawStatsHandle = Arc>; @@ -296,12 +406,12 @@ pub struct InstancedMesh { } impl InstancedMesh { - /// Add a placement: `rows` of its rigid move (see [`INSTANCE_SIZE`]) and its colour. - pub fn place(&mut self, rows: [[f32; 4]; 3], color: [u8; 4]) { + /// Add a placement: `rows` of its rigid move (see [`INSTANCE_SIZE`]) and its palette index. + pub fn place(&mut self, rows: [[f32; 4]; 3], color: PaletteIndex) { for v in rows.iter().flatten() { self.instances.extend_from_slice(&v.to_le_bytes()); } - self.instances.extend_from_slice(&color); + self.instances.extend_from_slice(&color.0.to_le_bytes()); } /// Its triangles at every placement, as the GPU draws them, appended to `out` (laid out as @@ -311,14 +421,14 @@ impl InstancedMesh { for inst in self.instances.as_chunks::().0 { let row = |r: usize| [f(inst, 16 * r), f(inst, 16 * r + 4), f(inst, 16 * r + 8), f(inst, 16 * r + 12)]; let rows = [row(0), row(1), row(2)]; - let color = inst.get(48..52).unwrap_or(&[0; 4]); + let index = inst.get(48..52).and_then(|b| b.try_into().ok()).map_or(0, u32::from_le_bytes); for (p, n) in self.tris.corners().flatten() { let moved = rows.map(|r| r[0] * p[0] + r[1] * p[1] + r[2] * p[2] + r[3]); let turned = rows.map(|r| r[0] * n[0] + r[1] * n[1] + r[2] * n[2]); for x in moved.iter().chain(&turned) { out.extend_from_slice(&x.to_le_bytes()); } - out.extend_from_slice(color); + out.extend_from_slice(&index.to_le_bytes()); } } } @@ -333,6 +443,8 @@ impl InstancedMesh { /// highlight scene (hover, selection, the origin widget) changes often and is small. #[derive(Default, Clone)] pub struct GpuScene { + /// The colours every vertex, line and instance index into. + pub palette: Arc, /// Opaque triangles. A zero normal draws the colour flat (unlit). pub tris: Vec, /// Opaque product PBR vertices; linear base color and explicit optical parameters. @@ -379,6 +491,10 @@ pub struct GpuScene { pub hover_blocks: Vec, /// Whole selected bodies, as `hover_blocks`, in the selection colour. pub selected_blocks: Vec, + /// Whole highlighted bodies the model builds in its blocks but does not draw opaque (faded + /// context, see-through): every one of their vertices drawn again, in this scene's palette, + /// whose entries for their faces hold the highlight colour. No triangle is copied. + pub recoloured: Vec, /// Whole hovered bodies the model draws as placements of shared triangles: those meshes with /// the body's highlight colour on each placement. pub hover_instanced: Vec, @@ -392,13 +508,25 @@ pub struct GpuScene { } impl GpuScene { + /// A scene whose palette starts with `palette`'s stable entries (the model scene). + pub fn with_palette(palette: Palette) -> GpuScene { + GpuScene { palette: Arc::new(palette), ..Default::default() } + } + + /// Intern an ephemeral colour (grid, highlight, sketch, preview) into this scene's palette. + pub fn color(&mut self, rgba: [u8; 4]) -> PaletteIndex { + Arc::make_mut(&mut self.palette).intern(rgba) + } + /// The blocks' geometry moved into the scene's own lists, in drawing order (for tests that /// count what the scene holds). pub fn merged(mut self) -> GpuScene { - let mut out = GpuScene { glass: std::mem::take(&mut self.glass), ..Default::default() }; + let palette = self.palette.clone(); + let mut out = GpuScene { glass: std::mem::take(&mut self.glass), palette: palette.clone(), ..Default::default() }; for block in std::mem::take(&mut self.blocks) { - out.tris.extend_from_slice(&block.bytes.tris); - out.trans.extend_from_slice(&block.bytes.trans); + append_runs(&block.bytes.vertices, &block.bytes.opaque, &mut out.tris); + append_runs(&block.bytes.vertices, &block.bytes.glass, &mut out.glass); + append_runs(&block.bytes.vertices, &block.bytes.faded, &mut out.trans); out.lines.extend_from_slice(&block.bytes.lines); out.hidden.extend_from_slice(&block.bytes.hidden); } @@ -413,10 +541,32 @@ impl GpuScene { out.trans.append(&mut self.trans); out.lines.append(&mut self.lines); out.hidden.append(&mut self.hidden); - GpuScene { tris: out.tris, trans: out.trans, glass: out.glass, lines: out.lines, hidden: out.hidden, ..self } + let palette = std::mem::replace(&mut self.palette, palette); + GpuScene { palette, tris: out.tris, trans: out.trans, glass: out.glass, lines: out.lines, hidden: out.hidden, ..self } } } +/// A class's triangles as `TRI_SIZE` vertex records: its runs of the block's vertices, in order. +fn append_runs(vertices: &[u8], runs: &[std::ops::Range], out: &mut Vec) { + for r in runs { + let (a, b) = (r.start as usize * TRI_SIZE, r.end as usize * TRI_SIZE); + if let Some(v) = vertices.get(a..b) { + out.extend_from_slice(v); + } + } +} + +/// The part of `runs` (sorted, not overlapping) inside `within`. +pub fn runs_within(runs: &[std::ops::Range], within: std::ops::Range) -> Vec> { + let first = runs.partition_point(|r| r.end <= within.start); + runs[first..] + .iter() + .take_while(|r| r.start < within.end) + .map(|r| r.start.max(within.start)..r.end.min(within.end)) + .filter(|r| !r.is_empty()) + .collect() +} + /// A run of the model's bodies in the scene: their triangles and edges, and a key that names /// exactly this content (the viewport keeps the bytes while the key comes back). #[derive(Clone)] @@ -425,24 +575,142 @@ pub struct SceneBlock { pub bytes: Arc, } -/// A whole highlighted body the model builds on the CPU: its triangles in a model scene block, -/// as vertices of the block's triangle buffer. +/// A whole highlighted body the model builds on the CPU: its triangles in a model scene block. #[derive(Clone, Debug)] pub struct BlockTris { /// The block's key ([`SceneBlock::key`]). pub block: u64, - /// The body's vertices in it. - pub tris: std::ops::Range, + /// The body's opaque triangles: runs of the block's vertices (a block too large for one + /// vertex buffer draws from copies instead; its highlights are then skipped). + pub tris: Vec>, + /// All of the body's vertices in the block's canonical vertex stream. + pub vertices: std::ops::Range, } -/// A block's geometry, laid out as in [`GpuScene`]. -#[derive(Default)] +/// How a built triangle is drawn: opaque, see-through (glass), or faded context. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum TriClass { + Opaque, + Glass, + Faded, +} + +/// A block's geometry: one canonical triangle vertex stream (`TRI_SIZE` bytes a vertex, three a +/// triangle) and, per draw class, the runs of that stream the class draws. A colour or opacity +/// edit changes no vertex; an opacity class change changes only the runs, which are drawn +/// straight from the vertex buffer (no index buffer to upload). +#[derive(Default, Clone)] pub struct BlockBytes { - pub tris: Vec, - pub trans: Vec, - pub glass: Vec, - pub lines: Vec, - pub hidden: Vec, + pub vertices: Arc>, + pub opaque: Arc>>, + pub glass: Arc>>, + pub faded: Arc>>, + pub lines: Arc>, + pub hidden: Arc>, +} + +impl BlockBytes { + /// The runs of `class`. + pub fn runs(&self, class: TriClass) -> &Arc>> { + match class { + TriClass::Opaque => &self.opaque, + TriClass::Glass => &self.glass, + TriClass::Faded => &self.faded, + } + } +} + +/// Add a triangle starting at vertex `at` to `runs`, extending the last run when it ends there. +pub fn extend_runs(runs: &mut Vec>, at: u32) { + let end = at.saturating_add(3); + match runs.last_mut() { + Some(last) if last.end == at => last.end = end, + _ => runs.push(at..end), + } +} + +/// Builds a [`BlockBytes`], writing each triangle's vertices once and filing it by class. +#[derive(Default)] +pub struct BlockBuilder { + vertices: Vec, + opaque: Vec>, + glass: Vec>, + faded: Vec>, + lines: Vec, + hidden: Vec, +} + +impl BlockBuilder { + /// Room for `triangles` more triangles, so a block of large bodies is written without + /// reallocating (and copying) its vertex stream as it grows. + pub fn reserve_triangles(&mut self, triangles: usize) { + let _ = self.vertices.try_reserve_exact(triangles.saturating_mul(3 * TRI_SIZE)); + } + + /// Add a triangle (three positions and normals, one palette index) under `class`. + pub fn triangle(&mut self, p: [[f32; 3]; 3], n: [[f32; 3]; 3], c: PaletteIndex, class: TriClass) { + let at = u32::try_from(self.vertices.len() / TRI_SIZE).unwrap_or(u32::MAX); + let mut record = [0u8; 3 * TRI_SIZE]; + for ((out, p), n) in record.as_chunks_mut::().0.iter_mut().zip(p).zip(n) { + let words = [p[0].to_bits(), p[1].to_bits(), p[2].to_bits(), n[0].to_bits(), n[1].to_bits(), n[2].to_bits(), c.0]; + for (w, slot) in words.iter().zip(out.as_chunks_mut::<4>().0) { + *slot = w.to_le_bytes(); + } + } + self.vertices.extend_from_slice(&record); + let runs = match class { + TriClass::Opaque => &mut self.opaque, + TriClass::Glass => &mut self.glass, + TriClass::Faded => &mut self.faded, + }; + extend_runs(runs, at); + } + + /// The runs of `class` that fall within `vertices` (a body's share of the block). + pub fn runs_within(&self, class: TriClass, vertices: std::ops::Range) -> Vec> { + let runs = match class { + TriClass::Opaque => &self.opaque, + TriClass::Glass => &self.glass, + TriClass::Faded => &self.faded, + }; + runs_within(runs, vertices) + } + + /// A depth-tested line, or one only shown where the model hides it. + pub fn line(&mut self, a: [f32; 3], b: [f32; 3], c: PaletteIndex, width: f32) { + let out = &mut self.lines; + for v in a.iter().chain(&b) { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&c.0.to_le_bytes()); + out.extend_from_slice(&width.to_le_bytes()); + } + + pub fn hidden_line(&mut self, a: [f32; 3], b: [f32; 3], c: PaletteIndex, width: f32) { + let out = &mut self.hidden; + for v in a.iter().chain(&b) { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&c.0.to_le_bytes()); + out.extend_from_slice(&width.to_le_bytes()); + } + + /// How many vertices the block holds so far. + pub fn vertices_len(&self) -> usize { + self.vertices.len() / TRI_SIZE + } + + /// The block, frozen for the scene and the GPU cache. + pub fn freeze(self) -> Arc { + Arc::new(BlockBytes { + vertices: Arc::new(self.vertices), + opaque: Arc::new(self.opaque), + glass: Arc::new(self.glass), + faded: Arc::new(self.faded), + lines: Arc::new(self.lines), + hidden: Arc::new(self.hidden), + }) + } } impl GpuScene { @@ -453,72 +721,72 @@ impl GpuScene { self.pbr.extend_from_slice(&value.to_le_bytes()); } } - pub fn tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + pub fn tri(&mut self, p: [f32; 3], n: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&n) { self.tris.extend_from_slice(&v.to_le_bytes()); } - self.tris.extend_from_slice(&c); + self.tris.extend_from_slice(&c.0.to_le_bytes()); } /// A vertex of the ground-plane shadow (see [`GpuScene::shadow`]). - pub fn shadow_tri(&mut self, p: [f32; 3], c: [u8; 4]) { + pub fn shadow_tri(&mut self, p: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&[0.0; 3]) { self.shadow.extend_from_slice(&v.to_le_bytes()); } - self.shadow.extend_from_slice(&c); + self.shadow.extend_from_slice(&c.0.to_le_bytes()); } - pub fn trans_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + pub fn trans_tri(&mut self, p: [f32; 3], n: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&n) { self.trans.extend_from_slice(&v.to_le_bytes()); } - self.trans.extend_from_slice(&c); + self.trans.extend_from_slice(&c.0.to_le_bytes()); } /// A line shown only where the model hides it. - pub fn hidden_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { + pub fn hidden_line(&mut self, a: [f32; 3], b: [f32; 3], c: PaletteIndex, width: f32) { for v in a.iter().chain(&b) { self.hidden.extend_from_slice(&v.to_le_bytes()); } - self.hidden.extend_from_slice(&c); + self.hidden.extend_from_slice(&c.0.to_le_bytes()); self.hidden.extend_from_slice(&width.to_le_bytes()); } - pub fn glass_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + pub fn glass_tri(&mut self, p: [f32; 3], n: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&n) { self.glass.extend_from_slice(&v.to_le_bytes()); } - self.glass.extend_from_slice(&c); + self.glass.extend_from_slice(&c.0.to_le_bytes()); } - pub fn ghost_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + pub fn ghost_tri(&mut self, p: [f32; 3], n: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&n) { self.ghost.extend_from_slice(&v.to_le_bytes()); } - self.ghost.extend_from_slice(&c); + self.ghost.extend_from_slice(&c.0.to_le_bytes()); } - pub fn xray_tri(&mut self, p: [f32; 3], n: [f32; 3], c: [u8; 4]) { + pub fn xray_tri(&mut self, p: [f32; 3], n: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&n) { self.xray.extend_from_slice(&v.to_le_bytes()); } - self.xray.extend_from_slice(&c); + self.xray.extend_from_slice(&c.0.to_le_bytes()); } /// A line under everything (see [`GpuScene::under`]). - pub fn under_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { + pub fn under_line(&mut self, a: [f32; 3], b: [f32; 3], c: PaletteIndex, width: f32) { for v in a.iter().chain(&b) { self.under.extend_from_slice(&v.to_le_bytes()); } - self.under.extend_from_slice(&c); + self.under.extend_from_slice(&c.0.to_le_bytes()); self.under.extend_from_slice(&width.to_le_bytes()); } /// A translucent triangle of a plane a section does not cut (see [`GpuScene::guide_trans`]). - pub fn guide_tri(&mut self, p: [f32; 3], c: [u8; 4]) { + pub fn guide_tri(&mut self, p: [f32; 3], c: PaletteIndex) { for v in p.iter().chain(&[0.0; 3]) { self.guide_trans.extend_from_slice(&v.to_le_bytes()); } - self.guide_trans.extend_from_slice(&c); + self.guide_trans.extend_from_slice(&c.0.to_le_bytes()); } /// A depth-tested line a section does not cut (see [`GpuScene::guide_lines`]). - pub fn guide_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32) { + pub fn guide_line(&mut self, a: [f32; 3], b: [f32; 3], c: PaletteIndex, width: f32) { for v in a.iter().chain(&b) { self.guide_lines.extend_from_slice(&v.to_le_bytes()); } - self.guide_lines.extend_from_slice(&c); + self.guide_lines.extend_from_slice(&c.0.to_le_bytes()); self.guide_lines.extend_from_slice(&width.to_le_bytes()); } /// A thick highlight along an edge (a selected or hovered edge with its halo), lit like a @@ -526,19 +794,19 @@ impl GpuScene { /// steeply the faces beside it are seen (`normals`: theirs along the segment; zero when /// unknown), so a face seen at a grazing angle no longer buries part of the band (it showed as /// a thin wedge instead of a line). See [`lifted_width`] for how this travels. - pub fn lifted_line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32, normals: [[f32; 3]; 2]) { + pub fn lifted_line(&mut self, a: [f32; 3], b: [f32; 3], c: PaletteIndex, width: f32, normals: [[f32; 3]; 2]) { for v in a.iter().chain(&b) { self.lines.extend_from_slice(&v.to_le_bytes()); } - self.lines.extend_from_slice(&c); + self.lines.extend_from_slice(&c.0.to_le_bytes()); self.lines.extend_from_slice(&lifted_width(width, normals).to_le_bytes()); } - pub fn line(&mut self, a: [f32; 3], b: [f32; 3], c: [u8; 4], width: f32, on_top: bool) { + pub fn line(&mut self, a: [f32; 3], b: [f32; 3], c: PaletteIndex, width: f32, on_top: bool) { let out = if on_top { &mut self.overlay } else { &mut self.lines }; for v in a.iter().chain(&b) { out.extend_from_slice(&v.to_le_bytes()); } - out.extend_from_slice(&c); + out.extend_from_slice(&c.0.to_le_bytes()); out.extend_from_slice(&width.to_le_bytes()); } } @@ -723,6 +991,7 @@ pub fn analysis_uniform(mode: Option, access: O /// Vertices (or line instances) on the GPU, in as many buffers as the device's buffer size /// limit needs: a large import's triangles can exceed one buffer (#883). +#[derive(Clone)] struct Batch { /// Each buffer and its vertex (instance) count. parts: Vec<(wgpu::Buffer, u32)>, @@ -734,6 +1003,8 @@ struct Batch { struct PlannedDraw { mesh: Arc, colors: wgpu::Buffer, + /// Its bodies' class: a chunk holds bodies of one class. + class: TriClass, /// The address of each plan in the chunk, in `mesh.parts` order: a whole-body highlight /// finds the evaluated triangles of the body it lights. plans: Vec, @@ -915,15 +1186,148 @@ impl LevelDraw { } } -/// A scene block on the GPU, with the bytes it was uploaded from. +/// Most runs a class draws one by one; a class broken into more (faces of their own opacity all +/// over a body) is drawn through an index buffer instead, in one call. +const MAX_RUNS: usize = 64; + +/// One class's triangles on the GPU: runs of the block's vertex buffer (no buffer of their own), +/// an index buffer for a fragmented class, or copies of its triangles when the block is too large +/// for one vertex buffer. +#[derive(Clone)] +enum ClassGpu { + Runs(Arc>>), + Indexed { indices: wgpu::Buffer, count: u32 }, + Unindexed(Batch), +} + +/// A scene block on the GPU, with the bytes it was uploaded from. Each artifact is kept while +/// its `Arc` comes back, so an opacity class change uploads nothing for a class drawn by runs. struct BlockGpu { bytes: Arc, - tris: Option, - trans: Option, + vertices: Option, + opaque: Option, + glass: Option, + faded: Option, lines: Option, hidden: Option, } +fn class_gpu( + device: &wgpu::Device, + fits: bool, + vertices: &[u8], + runs: &Arc>>, + old: Option<(&ClassGpu, &Arc>>)>, + same_vertices: bool, + uploaded: &mut u64, +) -> Option { + if runs.is_empty() { + return None; + } + let same_runs = old.is_some_and(|(_, old_runs)| Arc::ptr_eq(old_runs, runs)); + if !fits { + if let (Some((ClassGpu::Unindexed(batch), _)), true) = (old, same_vertices && same_runs) { + return Some(ClassGpu::Unindexed(batch.clone())); + } + let mut bytes = Vec::new(); + append_runs(vertices, runs, &mut bytes); + *uploaded += bytes.len() as u64; + return upload(device, "sc_block_class", &bytes, TRI_SIZE).map(ClassGpu::Unindexed); + } + if runs.len() <= MAX_RUNS { + return Some(ClassGpu::Runs(runs.clone())); + } + if let (Some((ClassGpu::Indexed { indices, count }, _)), true) = (old, same_runs) { + return Some(ClassGpu::Indexed { indices: indices.clone(), count: *count }); + } + let bytes: Vec = runs.iter().flat_map(|r| r.clone()).flat_map(|i| i.to_le_bytes()).collect(); + *uploaded += bytes.len() as u64; + let count = u32::try_from(bytes.len() / 4).unwrap_or(u32::MAX); + let indices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("sc_block_indices"), + contents: &bytes, + usage: wgpu::BufferUsages::INDEX, + }); + Some(ClassGpu::Indexed { indices, count }) +} + +impl BlockGpu { + fn update(device: &wgpu::Device, old: Option, bytes: Arc, uploaded: &mut u64) -> BlockGpu { + let fits = bytes.vertices.len() as u64 <= device.limits().max_buffer_size; + let same_vertices = old.as_ref().is_some_and(|o| Arc::ptr_eq(&o.bytes.vertices, &bytes.vertices)); + let vertices = if !fits || bytes.vertices.is_empty() { + None + } else if same_vertices { + old.as_ref().and_then(|o| o.vertices.clone()) + } else { + *uploaded += bytes.vertices.len() as u64; + Some(device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("sc_block_vertices"), + contents: &bytes.vertices, + usage: wgpu::BufferUsages::VERTEX, + })) + }; + let mut class = |class: TriClass| { + let old_pair = old.as_ref().and_then(|o| o.class(class).map(|c| (c, o.bytes.runs(class)))); + class_gpu(device, fits, &bytes.vertices, bytes.runs(class), old_pair, same_vertices, uploaded) + }; + let (opaque, glass, faded) = (class(TriClass::Opaque), class(TriClass::Glass), class(TriClass::Faded)); + let keep = |old: Option<&BlockGpu>, pick: fn(&BlockBytes) -> &Arc>, old_lines: fn(&BlockGpu) -> Option<&Batch>| { + old.filter(|o| Arc::ptr_eq(pick(&o.bytes), pick(&bytes))).and_then(old_lines).cloned() + }; + let mut fresh = |data: &[u8], label: &str| { + *uploaded += data.len() as u64; + upload(device, label, data, LINE_SIZE) + }; + let lines = keep(old.as_ref(), |b| &b.lines, |b| b.lines.as_ref()).or_else(|| fresh(&bytes.lines, "sc_block_lines")); + let hidden = keep(old.as_ref(), |b| &b.hidden, |b| b.hidden.as_ref()).or_else(|| fresh(&bytes.hidden, "sc_block_hidden")); + BlockGpu { bytes, vertices, opaque, glass, faded, lines, hidden } + } + + fn class(&self, class: TriClass) -> Option<&ClassGpu> { + match class { + TriClass::Opaque => self.opaque.as_ref(), + TriClass::Glass => self.glass.as_ref(), + TriClass::Faded => self.faded.as_ref(), + } + } + + /// Draw `class`'s triangles with the pipeline already set (`tally`: what is counted). + fn draw(&self, pass: &mut wgpu::RenderPass<'_>, class: TriClass, tally: &Tally) { + match self.class(class) { + Some(ClassGpu::Runs(runs)) => { + let Some(vertices) = &self.vertices else { return }; + pass.set_vertex_buffer(0, vertices.slice(..)); + for r in runs.iter() { + pass.draw(r.clone(), 0..1); + tally.triangles(r.len() as u32, 1); + } + } + Some(ClassGpu::Indexed { indices, count }) => { + let Some(vertices) = &self.vertices else { return }; + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..*count, 0, 0..1); + tally.triangles(*count, 1); + } + Some(ClassGpu::Unindexed(batch)) => { + for (buffer, count) in &batch.parts { + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..*count, 0..1); + tally.triangles(*count, 1); + } + } + None => {} + } + } +} + +/// The group 0 bind of the scene that owns the data being drawn: its palette (and the shared +/// uniform), or the one-entry stand-in for draws that read no colours. +fn scene_bind<'a>(scene: &'a Batches, fallback: &'a wgpu::BindGroup) -> &'a wgpu::BindGroup { + scene.palette.as_ref().map_or(fallback, |p| &p.bind) +} + /// The blocks' buffers, then the scene's own, as one batch (the blocks' buffers are shared, /// not copied). fn joined<'a>(blocks: impl Iterator>, own: Option) -> Option { @@ -933,6 +1337,133 @@ fn joined<'a>(blocks: impl Iterator>, own: Option, + /// Held for the bind group, which views it. + _texture: wgpu::Texture, + bind: wgpu::BindGroup, + rows: u32, + entries: Vec<[u8; 4]>, +} + +fn palette_texture(device: &wgpu::Device, rows: u32) -> wgpu::Texture { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("sc_palette"), + size: wgpu::Extent3d { width: PALETTE_WIDTH, height: rows.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Uint, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }) +} + +/// Rows `first..last` of `entries` as the texture's texels (zero past the end). +fn palette_bytes(entries: &[[u8; 4]], first: u32, last: u32) -> Vec { + let width = PALETTE_WIDTH as usize; + let mut out = Vec::with_capacity((last - first) as usize * width * 4); + for row in first..last { + for col in 0..PALETTE_WIDTH { + let i = row as usize * width + col as usize; + let texel = entries.get(i).map_or(0, |[r, g, b, a]| u32::from_le_bytes([*r, *g, *b, *a])); + out.extend_from_slice(&texel.to_le_bytes()); + } + } + out +} + +fn palette_rows(entries: &[[u8; 4]]) -> u32 { + u32::try_from(entries.len().div_ceil(PALETTE_WIDTH as usize)).unwrap_or(1).max(1) +} + +impl PaletteGpu { + fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + uniform: &wgpu::Buffer, + bgl: &wgpu::BindGroupLayout, + palette: Arc, + written: &mut u64, + ) -> PaletteGpu { + let entries = palette.entries().to_vec(); + let rows = palette_rows(&entries); + let texture = palette_texture(device, rows); + let bytes = palette_bytes(&entries, 0, rows); + *written += bytes.len() as u64; + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(PALETTE_WIDTH * 4), rows_per_image: Some(rows) }, + wgpu::Extent3d { width: PALETTE_WIDTH, height: rows, depth_or_array_layers: 1 }, + ); + let view = texture.create_view(&Default::default()); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("sc_palette"), + layout: bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&view) }, + ], + }); + PaletteGpu { palette, _texture: texture, bind, rows, entries } + } + + /// Bring the texture up to `palette`, writing only the rows whose entries changed (or the + /// whole texture when it must grow). The bind group is rebuilt only then. + fn update( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + uniform: &wgpu::Buffer, + bgl: &wgpu::BindGroupLayout, + palette: Arc, + written: &mut u64, + ) { + if Arc::ptr_eq(&self.palette, &palette) { + return; + } + let entries = palette.entries().to_vec(); + let rows = palette_rows(&entries); + if rows != self.rows { + *self = PaletteGpu::new(device, queue, uniform, bgl, palette, written); + return; + } + let width = PALETTE_WIDTH as usize; + let same = |row: u32| { + let base = row as usize * width; + (0..width).all(|c| self.entries.get(base + c).copied().unwrap_or_default() == entries.get(base + c).copied().unwrap_or_default()) + }; + let mut row = 0u32; + while row < rows { + if same(row) { + row += 1; + continue; + } + let first = row; + while row < rows && !same(row) { + row += 1; + } + let bytes = palette_bytes(&entries, first, row); + *written += bytes.len() as u64; + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &self._texture, + mip_level: 0, + origin: wgpu::Origin3d { x: 0, y: first, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(PALETTE_WIDTH * 4), rows_per_image: Some(row - first) }, + wgpu::Extent3d { width: PALETTE_WIDTH, height: row - first, depth_or_array_layers: 1 }, + ); + } + self.entries = entries; + self.palette = palette; + } +} + /// Planned bodies end a GPU chunk one time in this many (by their plan's address), and a chunk /// holds at most [`MAX_CHUNK_BODIES`]: a scene of a thousand bodies takes a few dozen dispatches /// once, and a changed body re-evaluates a few dozen bodies, not all of them. @@ -941,8 +1472,17 @@ const MAX_CHUNK_BODIES: usize = 128; #[derive(Default)] struct Batches { - /// The scene blocks on the GPU, by key. + /// What the last scene taken uploaded. + uploads: UploadStats, + /// The blocks' see-through triangles the global glass stream was assembled from (block key, + /// vertices and glass runs, by address), when it holds nothing else: an edit that changes + /// neither leaves the sorted stream as it is. + glass_from: Option>, + /// The scene's palette texture and its group 0 bind (uniform + palette). + palette: Option, + /// The scene blocks on the GPU, by key, and their drawing order. blocks: std::collections::HashMap, + block_order: Vec, key: Option, tris: Option, pbr: Option, @@ -968,6 +1508,8 @@ struct Batches { /// Whole highlighted bodies redrawn from the scene's blocks, by block key and vertex range. hover_blocks: Vec, selected_blocks: Vec, + /// Whole faded or see-through bodies redrawn from the model's blocks in this scene's palette. + recoloured: Vec, /// Whole highlighted bodies drawn as placements of the scene's shared triangles. hover_instanced: Vec, selected_instanced: Vec, @@ -982,11 +1524,32 @@ struct Batches { impl Batches { /// Upload a new scene. Planned bodies not yet on the GPU are evaluated there: their /// dispatches go into `encoder`, ahead of this frame's render pass. - fn take(&mut self, device: &wgpu::Device, key: u64, slot: &SceneSlot, tess: Option<(&crate::TessGpu, &mut wgpu::CommandEncoder)>) { + fn take( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + uniform: &wgpu::Buffer, + bgl: &wgpu::BindGroupLayout, + key: u64, + slot: &SceneSlot, + tess: Option<(&crate::TessGpu, &mut wgpu::CommandEncoder)>, + oit_available: bool, + ) { if self.key == Some(key) { return; } if let Some(sc) = slot.lock().ok().and_then(|mut s| s.take()) { + self.uploads = UploadStats::default(); + let palette = sc.palette.clone(); + let mut written = 0; + match self.palette.take() { + Some(mut p) => { + p.update(device, queue, uniform, bgl, palette, &mut written); + self.palette = Some(p); + } + None => self.palette = Some(PaletteGpu::new(device, queue, uniform, bgl, palette, &mut written)), + } + self.uploads.palette = written; self.planned = match tess { Some((tess, encoder)) => self.planned(device, tess, encoder, &sc.planned), None => Vec::new(), @@ -996,43 +1559,65 @@ impl Batches { self.selected_planned = sc.selected_planned; self.hover_blocks = sc.hover_blocks; self.selected_blocks = sc.selected_blocks; + self.recoloured = sc.recoloured; self.hover_instanced = self.instanced(device, &sc.hover_instanced); self.selected_instanced = self.instanced(device, &sc.selected_instanced); let mut kept = std::mem::take(&mut self.blocks); - let mut blocks: Vec<&BlockGpu> = Vec::with_capacity(sc.blocks.len()); + let mut order = Vec::with_capacity(sc.blocks.len()); + let mut geometry = 0; for block in &sc.blocks { - let gpu = match kept.remove(&block.key).filter(|g| Arc::ptr_eq(&g.bytes, &block.bytes)) { - Some(g) => g, - None => BlockGpu { - bytes: block.bytes.clone(), - tris: upload(device, "sc_tris", &block.bytes.tris, TRI_SIZE), - trans: upload(device, "sc_trans", &block.bytes.trans, TRI_SIZE), - lines: upload(device, "sc_lines", &block.bytes.lines, LINE_SIZE), - hidden: upload(device, "sc_hidden", &block.bytes.hidden, LINE_SIZE), - }, - }; - self.blocks.insert(block.key, gpu); + let old = kept.remove(&block.key); + self.blocks.insert(block.key, BlockGpu::update(device, old, block.bytes.clone(), &mut geometry)); + order.push(block.key); } - for block in &sc.blocks { - if let Some(g) = self.blocks.get(&block.key) { - blocks.push(g); + self.block_order = order; + let mut own = |label: &str, data: &[u8], stride: usize| { + geometry += data.len() as u64; + upload(device, label, data, stride) + }; + self.tris = own("sc_tris", &sc.tris, TRI_SIZE); + self.pbr = own("sc_pbr", &sc.pbr, PBR_SIZE); + self.trans = own("sc_trans", &sc.trans, TRI_SIZE); + self.shadow = own("sc_shadow", &sc.shadow, TRI_SIZE); + let own_lines = own("sc_lines", &sc.lines, LINE_SIZE); + let own_hidden = own("sc_hidden", &sc.hidden, LINE_SIZE); + self.overlays = own("sc_overlay", &sc.overlay, LINE_SIZE); + self.ghost = own("sc_ghost", &sc.ghost, TRI_SIZE); + self.xray = own("sc_xray", &sc.xray, TRI_SIZE); + self.under = own("sc_under", &sc.under, LINE_SIZE); + self.guide_trans = own("sc_guide_trans", &sc.guide_trans, TRI_SIZE); + self.guide_lines = own("sc_guide_lines", &sc.guide_lines, LINE_SIZE); + let blocks: Vec<&BlockGpu> = self.block_order.iter().filter_map(|k| self.blocks.get(k)).collect(); + self.lines = joined(blocks.iter().map(|b| &b.lines), own_lines); + self.hidden = joined(blocks.iter().map(|b| &b.hidden), own_hidden); + // Without order-independent transparency one global glass stream is sorted per view, + // so cross-body blend order is kept; the blocks' glass triangles join it here. With + // OIT the blocks draw their own runs and nothing is sorted. A stream made of the same + // blocks' glass as before (a colour or opacity edit, a selection) is kept as sorted. + let from: Vec<(u64, usize, usize)> = if oit_available { + Vec::new() + } else { + sc.blocks + .iter() + .filter(|b| !b.bytes.glass.is_empty()) + .map(|b| (b.key, Arc::as_ptr(&b.bytes.vertices) as usize, Arc::as_ptr(&b.bytes.glass) as usize)) + .collect() + }; + let same_glass = sc.glass.is_empty() && self.glass_from.as_ref() == Some(&from); + if !same_glass { + self.glass_cpu.clear(); + self.glass_cpu.extend_from_slice(&sc.glass); + if !oit_available { + for block in &sc.blocks { + append_runs(&block.bytes.vertices, &block.bytes.glass, &mut self.glass_cpu); + } } + geometry += self.glass_cpu.len() as u64; + self.glass = upload_with(device, "sc_glass", &self.glass_cpu, TRI_SIZE, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST); + self.glass_sorted_for = None; + self.glass_from = sc.glass.is_empty().then_some(from); } - self.tris = joined(blocks.iter().map(|b| &b.tris), upload(device, "sc_tris", &sc.tris, TRI_SIZE)); - self.pbr = upload(device, "sc_pbr", &sc.pbr, PBR_SIZE); - self.trans = joined(blocks.iter().map(|b| &b.trans), upload(device, "sc_trans", &sc.trans, TRI_SIZE)); - self.shadow = upload(device, "sc_shadow", &sc.shadow, TRI_SIZE); - self.glass = upload_with(device, "sc_glass", &sc.glass, TRI_SIZE, wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST); - self.glass_cpu = sc.glass; - self.glass_sorted_for = None; - self.lines = joined(blocks.iter().map(|b| &b.lines), upload(device, "sc_lines", &sc.lines, LINE_SIZE)); - self.hidden = joined(blocks.iter().map(|b| &b.hidden), upload(device, "sc_hidden", &sc.hidden, LINE_SIZE)); - self.overlays = upload(device, "sc_overlay", &sc.overlay, LINE_SIZE); - self.ghost = upload(device, "sc_ghost", &sc.ghost, TRI_SIZE); - self.xray = upload(device, "sc_xray", &sc.xray, TRI_SIZE); - self.under = upload(device, "sc_under", &sc.under, LINE_SIZE); - self.guide_trans = upload(device, "sc_guide_trans", &sc.guide_trans, TRI_SIZE); - self.guide_lines = upload(device, "sc_guide_lines", &sc.guide_lines, LINE_SIZE); + self.uploads.geometry += geometry; self.key = Some(key); } } @@ -1054,7 +1639,10 @@ impl Batches { let gpu = match kept.remove(&key).or_else(|| self.instanced_tris.remove(&key)).filter(|(b, _)| Arc::ptr_eq(b, tris)) { Some(t) => t, None => match SharedGpu::new(device, tris) { - Some(g) => (tris.clone(), Arc::new(g)), + Some(g) => { + self.uploads.geometry += (tris.vertices.len() + tris.indices.len() * 4) as u64; + (tris.clone(), Arc::new(g)) + } None => continue, }, }; @@ -1064,6 +1652,7 @@ impl Batches { contents: &placements, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, }); + self.uploads.placements += placements.len() as u64; let count = if i == 0 { count } else { 0 }; levels.push(LevelDraw { tris: gpu.1.clone(), flat: tris.flat, error, instances, count }); self.instanced_tris.insert(key, gpu); @@ -1152,7 +1741,7 @@ impl Batches { for b in bodies { let n = b.plan.vertex_count(); match chunks.last_mut() { - Some(c) if open && filled + n <= crate::MAX_BATCH => c.push(b), + Some(c) if open && filled + n <= crate::MAX_BATCH && c.first().is_some_and(|f| f.class == b.class) => c.push(b), _ => { chunks.push(vec![b]); filled = 0; @@ -1173,6 +1762,7 @@ impl Batches { let plans: Vec<&solidcraft_geom::tess::TessPlan> = chunk.iter().map(|b| &*b.plan).collect(); match tess.prepare_many(&plans) { Ok(m) => { + self.uploads.evaluated += plans.iter().map(|p| p.vertex_count() as u64).sum::(); tess.record(encoder, &m); let m = Arc::new(m); self.resident.insert(key(chunk), (chunk.iter().map(|b| b.plan.clone()).collect(), m.clone())); @@ -1187,12 +1777,16 @@ impl Batches { }; let mut bytes = Vec::with_capacity(mesh.vertex_face.len() * 4); for (part, b) in mesh.parts.iter().zip(chunk) { - let last = b.face_colors.last().copied().unwrap_or([200, 200, 200, 255]); + let last = b.face_colors.last().copied().unwrap_or(PaletteIndex(0)); let faces = mesh.vertex_face.get(part.vertices.start as usize..part.vertices.end as usize).unwrap_or_default(); - bytes.extend(faces.iter().flat_map(|f| b.face_colors.get(*f as usize).copied().unwrap_or(last))); + for f in faces { + bytes.extend_from_slice(&b.face_colors.get(*f as usize).copied().unwrap_or(last).0.to_le_bytes()); + } } + self.uploads.planned += bytes.len() as u64; if let Some((colors, _)) = upload(device, "sc_planned_colors", &bytes, 4).and_then(|c| c.parts.into_iter().next()) { - out.push(PlannedDraw { mesh, colors, plans: key(chunk) }); + let class = chunk.first().map_or(TriClass::Opaque, |b| b.class); + out.push(PlannedDraw { mesh, colors, class, plans: key(chunk) }); } } out @@ -1272,6 +1866,9 @@ pub struct Renderer { guide_trans: wgpu::RenderPipeline, guide_line: wgpu::RenderPipeline, uniform: wgpu::Buffer, + /// The layout of group 0 (the uniform and a palette), for per-scene bind groups. + uniform_bgl: wgpu::BindGroupLayout, + /// Group 0 with a one-entry palette: draws that do not read colours (images, AO, depth). bind: wgpu::BindGroup, linear_out: bool, model: Batches, @@ -1453,7 +2050,7 @@ fn access_texture(device: &wgpu::Device, queue: Option<&wgpu::Queue>, bgl: &wgpu pub const SHADER: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/shaders/viewport.wgsl")); fn tri_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4]; + const A: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Uint32]; wgpu::VertexBufferLayout { array_stride: TRI_SIZE as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } } @@ -1480,7 +2077,7 @@ fn shared_layout() -> wgpu::VertexBufferLayout<'static> { /// An instanced mesh's placements ([`INSTANCE_SIZE`]), one per instance. fn instance_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![3 => Float32x4, 4 => Float32x4, 5 => Float32x4, 6 => Unorm8x4]; + const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![3 => Float32x4, 4 => Float32x4, 5 => Float32x4, 6 => Uint32]; wgpu::VertexBufferLayout { array_stride: INSTANCE_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } } @@ -1518,12 +2115,12 @@ impl TriSource { /// A planned body's colours, one per vertex. fn color_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![2 => Unorm8x4]; + const A: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![2 => Uint32]; wgpu::VertexBufferLayout { array_stride: 4, step_mode: wgpu::VertexStepMode::Vertex, attributes: &A } } fn line_layout() -> wgpu::VertexBufferLayout<'static> { - const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Unorm8x4, 3 => Uint32]; + const A: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Uint32, 3 => Uint32]; wgpu::VertexBufferLayout { array_stride: LINE_SIZE as u64, step_mode: wgpu::VertexStepMode::Instance, attributes: &A } } @@ -1535,6 +2132,10 @@ pub struct GpuTarget { pub samples: u32, /// The device evaluates display plans (compute shaders): bodies may be drawn from them. pub tess: bool, + /// The renderer blends see-through surfaces order-independently: faded and see-through + /// bodies may be drawn from their plans too (they need no sorting on the CPU). Set by the + /// renderer ([`Renderer::target`]); asking for it does not make it so. + pub oit: bool, } impl GpuTarget { @@ -1602,12 +2203,25 @@ impl Renderer { device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_viewport"), source: wgpu::ShaderSource::Wgsl(source.into()) }); let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("sc_viewport"), - entries: &[wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, - ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, - count: None, - }], + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + // The palette: a texture (not a storage buffer), so WebGL2 can draw it. + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Uint, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + ], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("sc_viewport"), @@ -1620,10 +2234,15 @@ impl Renderer { usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + let dummy_palette = palette_texture(device, 1); + let dummy_view = dummy_palette.create_view(&Default::default()); let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("sc_viewport"), layout: &bgl, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }], + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&dummy_view) }, + ], }); let reversed = t.reversed_depth(); let depth = |compare: wgpu::CompareFunction, write: bool| -> Option { @@ -1939,7 +2558,7 @@ impl Renderer { ao, depth_reset, section_reset: t.depth.filter(|f| f.has_stencil_aspect()).and_then(|_| depth_reset_pipeline(device, t)), - target: t, + target: GpuTarget { oit: oit.is_some(), ..t }, window, max_texture: device.limits().max_texture_dimension_2d, ss_blit, @@ -2000,6 +2619,7 @@ impl Renderer { guide_trans: pipeline("sc_guide_trans", "vs_tri", "fs_tri_all", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), guide_line: pipeline("sc_guide_lines", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha), uniform, + uniform_bgl: bgl, bind, linear_out: t.format.is_srgb(), model: Batches::default(), @@ -2131,7 +2751,11 @@ pub fn sort_back_to_front(bytes: &[u8], back: [f32; 3]) -> Vec { impl Batches { /// Whether it has see-through surfaces (glass or faded, instanced or not). fn see_through(&self) -> bool { - self.glass.is_some() || self.trans.is_some() || self.instanced.iter().any(|d| d.look != InstanceLook::Opaque) + self.glass.is_some() + || self.trans.is_some() + || self.planned.iter().any(|d| d.class != TriClass::Opaque) + || self.instanced.iter().any(|d| d.look != InstanceLook::Opaque) + || self.block_order.iter().any(|k| self.blocks.get(k).is_some_and(|b| b.glass.is_some() || b.faded.is_some())) } /// Re-sort the glass for a new view direction (when it turned more than about 2 degrees). @@ -2263,7 +2887,7 @@ impl Renderer { } res.cached = None; if cb.product { - res.product.take(device, cb.key, &cb.slot, None); + res.product.take(device, queue, &res.uniform, &res.uniform_bgl, cb.key, &cb.slot, None, false); res.product.sort_glass(queue, cb.back); queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out, res.target.reversed_depth())); // The product picture goes through the window's pass too: offscreen when the targets @@ -2272,10 +2896,19 @@ impl Renderer { res.ss_key = res.ss_ready.then_some(key); return; } - res.model.take(device, cb.key, &cb.slot, res.tess.as_ref().map(|t| (t, &mut *encoder))); - res.sketch.take(device, cb.sketch_key, &cb.sketch_slot, None); - res.highlight.take(device, cb.hl_key, &cb.hl_slot, None); - res.preview.take(device, cb.pv_key, &cb.pv_slot, None); + res.model.take( + device, + queue, + &res.uniform, + &res.uniform_bgl, + cb.key, + &cb.slot, + res.tess.as_ref().map(|t| (t, &mut *encoder)), + res.oit.is_some(), + ); + res.sketch.take(device, queue, &res.uniform, &res.uniform_bgl, cb.sketch_key, &cb.sketch_slot, None, res.oit.is_some()); + res.highlight.take(device, queue, &res.uniform, &res.uniform_bgl, cb.hl_key, &cb.hl_slot, None, res.oit.is_some()); + res.preview.take(device, queue, &res.uniform, &res.uniform_bgl, cb.pv_key, &cb.pv_slot, None, res.oit.is_some()); // See-through surfaces are drawn without sorting where the device can (order-independent // transparency, in an offscreen frame); else their triangles are sorted for the view. let see_through = res.oit.is_some() && res.model.see_through(); @@ -2290,7 +2923,8 @@ impl Renderer { res.access_bind = access_texture(device, Some(queue), &res.access_bgl, a.size, &a.depth); res.access_version = a.version; } - res.ao.prepare(device, encoder, &res.bind, cb.ao_radius, cb.size_px, res.target.reversed_depth(), [&res.model, &res.preview]); + let ao_binds = [scene_bind(&res.model, &res.bind), scene_bind(&res.preview, &res.bind)]; + res.ao.prepare(device, encoder, ao_binds, cb.ao_radius, cb.size_px, res.target.reversed_depth(), [&res.model, &res.preview]); // Images: upload new or changed textures, drop removed ones, rebuild the quads. res.textures.retain(|id, _| cb.images.iter().any(|i| i.id == *id)); res.quads.clear(); @@ -2382,6 +3016,11 @@ impl Renderer { self.stats.clone() } + /// What the model scene's last change uploaded ([`UploadStats`]). + pub fn uploads(&self) -> UploadStats { + self.model.uploads + } + fn publish(&self, drawn: DrawStats) { if let Ok(mut s) = self.stats.lock() { *s = drawn; @@ -2426,18 +3065,31 @@ impl Renderer { } else { (&res.model, &res.sketch, &res.highlight, &res.preview) }; + // A block's triangles of one class, drawn from its canonical vertex buffer. + let block_class = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, class: TriClass| { + for key in &m.block_order { + let Some(block) = m.blocks.get(key) else { continue }; + if block.class(class).is_some() { + pass.set_pipeline(p); + block.draw(pass, class, tally); + } + } + }; if phase == Phase::AfterSeeThrough { pass.set_bind_group(1, &res.access_bind, &[]); pass.set_bind_group(2, &res.ao.bind, &[]); Self::draw_over(res, pass, sk, h, pv, m, &tris, &lines); return; } + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); lines(pass, &res.overlay, &m.under); + pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); lines(pass, &res.overlay, &sk.under); pass.set_bind_group(1, &res.access_bind, &[]); pass.set_bind_group(2, &res.ao.bind, &[]); + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline| { - for d in &m.planned { + for d in m.planned.iter().filter(|d| d.class == TriClass::Opaque) { pass.set_pipeline(p); pass.set_vertex_buffer(0, d.mesh.vertices.slice(..)); pass.set_vertex_buffer(1, d.colors.slice(..)); @@ -2467,23 +3119,17 @@ impl Renderer { } } }; - // Whole highlighted bodies the model builds on the CPU: their part of a block's triangle - // buffer (the blocks may run over several buffers). + // Whole highlighted bodies the model builds on the CPU: their runs of a block's vertex + // buffer (a block too large for one vertex buffer has its highlight skipped). let tinted_blocks = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, refs: &[BlockTris]| { for r in refs { let Some(block) = m.blocks.get(&r.block) else { continue }; - let Some(batch) = &block.tris else { continue }; + let Some(vertices) = &block.vertices else { continue }; pass.set_pipeline(p); - let mut base = 0u32; - for (buffer, count) in &batch.parts { - let end = base.saturating_add(*count); - let (lo, hi) = (r.tris.start.max(base), r.tris.end.min(end)); - if lo < hi { - pass.set_vertex_buffer(0, buffer.slice(..)); - pass.draw(lo - base..hi - base, 0..1); - tally.triangles(hi - lo, 1); - } - base = end; + pass.set_vertex_buffer(0, vertices.slice(..)); + for run in &r.tris { + pass.draw(run.clone(), 0..1); + tally.triangles(run.len() as u32, 1); } } }; @@ -2504,11 +3150,16 @@ impl Renderer { res.section_reset.as_ref(), ) { (Some(cut), Some(cut_planned), Some(cut_instanced), Some(cut_flat), Some(reset)) => { + // The model's own triangles, blocks, plans and instances with its palette, then the + // preview's with its own. let all = |pass: &mut wgpu::RenderPass<'static>, pick: fn(&Cut) -> &wgpu::RenderPipeline| { + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); tris(pass, pick(cut), &m.tris); - tris(pass, pick(cut), &pv.tris); + block_class(pass, pick(cut), TriClass::Opaque); planned(pass, pick(cut_planned)); instanced(pass, pick(cut_instanced), pick(cut_flat)); + pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); + tris(pass, pick(cut), &pv.tris); }; pass.set_stencil_reference(1); all(pass, |c| &c.mark); @@ -2519,30 +3170,60 @@ impl Renderer { all(pass, |c| &c.cap); } _ => { + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); tris(pass, &res.tri, &m.tris); - tris(pass, &res.tri, &pv.tris); + block_class(pass, &res.tri, TriClass::Opaque); planned(pass, &res.tri_planned); instanced(pass, &res.tri_instanced, &res.tri_instanced_flat); + pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); + tris(pass, &res.tri, &pv.tris); } } + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); tris(pass, &res.pbr, &m.pbr); // Whole-body tints first, so a face or an edge highlighted over the body (in `h.tris` // and `h.lines`) keeps its own colour, as it did when the body's triangles were built // into the same list before them. + // The model's own data (blocks, plans, instanced meshes) uses the model palette; the + // highlight scene's own geometry uses the highlight palette. tinted(pass, &res.tri_hl_hover, &h.hover_planned); tinted(pass, &res.tri_hl_selected, &h.selected_planned); tinted_blocks(pass, &res.tri_hl_hover_built, &h.hover_blocks); tinted_blocks(pass, &res.tri_hl_selected_built, &h.selected_blocks); + pass.set_bind_group(0, scene_bind(h, &res.bind), &[]); tinted_instanced(pass, &res.tri_hl_instanced, &res.tri_hl_instanced_flat, &h.hover_instanced); tinted_instanced(pass, &res.tri_hl_instanced, &res.tri_hl_instanced_flat, &h.selected_instanced); + // Whole faded or see-through bodies: the model's block vertices, in this palette. + for r in &h.recoloured { + let Some(block) = m.blocks.get(&r.block) else { continue }; + let Some(vertices) = &block.vertices else { continue }; + pass.set_pipeline(&res.tri_hl); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.draw(r.vertices.clone(), 0..1); + tally.triangles(r.vertices.len() as u32, 1); + } + // The highlight's own feedback triangles: its blocks' (kept while it is unchanged), then + // the loose ones. + for key in &h.block_order { + if let Some(block) = h.blocks.get(key).filter(|b| b.class(TriClass::Opaque).is_some()) { + pass.set_pipeline(&res.tri_hl); + block.draw(pass, TriClass::Opaque, tally); + } + } tris(pass, &res.tri_hl, &h.tris); + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); lines(pass, &res.line, &m.lines); + pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); lines(pass, &res.line, &sk.lines); + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); lines(pass, &res.line_hidden, &m.hidden); + pass.set_bind_group(0, scene_bind(h, &res.bind), &[]); lines(pass, &res.line_hidden, &h.hidden); - lines(pass, &res.line, &pv.lines); lines(pass, &res.line, &h.lines); lines(pass, &res.guide_line, &h.guide_lines); + pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); + lines(pass, &res.line, &pv.lines); + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); for (id, q) in res.quads.iter().filter(|_| !cb.product) { if let Some((_, bind)) = res.textures.get(id) { pass.set_pipeline(&res.image); @@ -2554,7 +3235,9 @@ impl Renderer { } } } + pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); tris(pass, &res.ghost, &pv.ghost); + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); tris(pass, &res.trans, &m.shadow); if phase == Phase::BeforeSeeThrough { return; @@ -2571,6 +3254,7 @@ impl Renderer { tris(pass, &res.glass_near, &m.glass); see_through(pass, InstanceLook::Glass, &res.glass_near_instanced); tris(pass, &res.trans, &m.trans); + block_class(pass, &res.trans, TriClass::Faded); see_through(pass, InstanceLook::Faded, &res.trans_instanced); Self::draw_over(res, pass, sk, h, pv, m, &tris, &lines); } @@ -2587,20 +3271,26 @@ impl Renderer { tris: &dyn Fn(&mut wgpu::RenderPass<'static>, &wgpu::RenderPipeline, &Option), lines: &dyn Fn(&mut wgpu::RenderPass<'static>, &wgpu::RenderPipeline, &Option), ) { + pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); tris(pass, &res.trans, &sk.trans); + pass.set_bind_group(0, scene_bind(h, &res.bind), &[]); tris(pass, &res.trans, &h.trans); tris(pass, &res.guide_trans, &h.guide_trans); - tris(pass, &res.xray, &pv.xray); tris(pass, &res.xray, &h.xray); + pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]); + tris(pass, &res.xray, &pv.xray); + pass.set_bind_group(0, scene_bind(m, &res.bind), &[]); lines(pass, &res.overlay, &m.overlays); + pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]); lines(pass, &res.overlay, &sk.overlays); + pass.set_bind_group(0, scene_bind(h, &res.bind), &[]); lines(pass, &res.overlay, &h.overlays); } /// The model's see-through surfaces into the order-independent transparency's targets. fn draw_see_through(&self, pass: &mut wgpu::RenderPass<'static>, p: &oit::Pipelines, tally: &Tally) { let m = &self.model; - pass.set_bind_group(0, &self.bind, &[]); + pass.set_bind_group(0, scene_bind(m, &self.bind), &[]); pass.set_pipeline(&p.built); for batch in [&m.glass, &m.trans].into_iter().flatten() { for (buffer, count) in &batch.parts { @@ -2609,6 +3299,26 @@ impl Renderer { tally.triangles(*count, 1); } } + // The blocks' see-through triangles, straight from their vertex buffers (nothing sorted). + for class in [TriClass::Glass, TriClass::Faded] { + for key in &m.block_order { + if let Some(block) = m.blocks.get(key) { + block.draw(pass, class, tally); + } + } + } + // Faded and see-through bodies drawn from their plans. + let mut planned = m.planned.iter().filter(|d| d.class != TriClass::Opaque).peekable(); + if planned.peek().is_some() { + pass.set_pipeline(&p.planned); + for d in planned { + pass.set_vertex_buffer(0, d.mesh.vertices.slice(..)); + pass.set_vertex_buffer(1, d.colors.slice(..)); + pass.set_index_buffer(d.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..d.mesh.index_count, 0, 0..1); + tally.triangles(d.mesh.index_count, 1); + } + } for d in m.instanced.iter().filter(|d| d.look != InstanceLook::Opaque) { d.draw(pass, &p.instanced, &p.instanced_flat, tally); } @@ -3156,8 +3866,9 @@ mod glass_tests { fn ground_shadow_blends_and_stays_behind_opaque_geometry() { let mut scene = GpuScene::default(); let square = [[-5.0, -5.0, -5.0], [5.0, -5.0, -5.0], [5.0, 5.0, -5.0], [-5.0, -5.0, -5.0], [5.0, 5.0, -5.0], [-5.0, 5.0, -5.0]]; + let shadow_color = scene.color([0, 0, 0, 128]); for p in square { - scene.shadow_tri(p, [0, 0, 0, 128]); + scene.shadow_tri(p, shadow_color); } for samples in [1, 4] { let Some(shadow) = middle_pixel_with_samples(scene.clone(), true, samples) else { @@ -3166,9 +3877,10 @@ mod glass_tests { }; assert!(shadow[..3].iter().all(|c| (125..=129).contains(c)), "{samples}× alpha-blended shadow: {shadow:?}"); let mut occluded = scene.clone(); + let green = occluded.color([0, 255, 0, 255]); for mut p in square { p[2] = 5.0; - occluded.tri(p, [0.0; 3], [0, 255, 0, 255]); + occluded.tri(p, [0.0; 3], green); } assert_eq!(middle_pixel_with_samples(occluded, true, samples), Some([0, 255, 0, 255]), "opaque geometry hides the ground shadow"); } @@ -3190,6 +3902,43 @@ mod glass_tests { assert!(buffer_chunk(TRI_SIZE, 1) >= TRI_SIZE * 6, "a tiny limit still holds one unit"); } + /// Without order-independent transparency, the sorted glass stream is kept while the blocks' + /// see-through triangles stay the same: a colour edit (a new palette) uploads palette rows + /// and no geometry; a class change rebuilds the stream. + #[test] + fn a_colour_edit_keeps_the_sorted_glass_stream() { + let Ok((_, device, queue)) = crate::open_headless() else { return }; + let format = wgpu::TextureFormat::Rgba8Unorm; + let mut r = + Renderer::new(&device, GpuTarget { format, depth: Some(crate::depth_format(&device, true)), samples: 1, tess: false, oit: false }, None); + let mut palette = Palette::with_stable(vec![[200, 0, 0, 128]]); + let mut b = BlockBuilder::default(); + b.triangle([[0.0; 3], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], [[0.0, 0.0, 1.0]; 3], PaletteIndex(0), TriClass::Glass); + let bytes = b.freeze(); + let scene = |palette: &Palette, bytes: &Arc| GpuScene { + palette: Arc::new(palette.clone()), + blocks: vec![SceneBlock { key: 7, bytes: bytes.clone() }], + ..GpuScene::default() + }; + let take = |r: &mut Renderer, key: u64, sc: GpuScene| { + let slot: SceneSlot = Arc::new(Mutex::new(Some(sc))); + r.model.take(&device, &queue, &r.uniform, &r.uniform_bgl, key, &slot, None, false); + r.model.uploads + }; + let first = take(&mut r, 1, scene(&palette, &bytes)); + assert_eq!(first.geometry, (2 * 3 * TRI_SIZE) as u64, "the block's vertices and the sorted stream: {first:?}"); + palette.set(PaletteIndex(0), [0, 0, 200, 128]); + let colour = take(&mut r, 2, scene(&palette, &bytes)); + assert_eq!(colour.geometry, 0, "a colour edit keeps the stream: {colour:?}"); + assert!(colour.palette > 0, "and writes the palette: {colour:?}"); + let mut b = BlockBuilder::default(); + b.triangle([[0.0; 3], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], [[0.0, 0.0, 1.0]; 3], PaletteIndex(0), TriClass::Opaque); + let opaque = take(&mut r, 3, scene(&palette, &b.freeze())); + assert!(opaque.geometry > 0, "new block geometry is uploaded: {opaque:?}"); + let back = take(&mut r, 4, scene(&palette, &bytes)); + assert!(back.geometry >= (3 * TRI_SIZE) as u64, "the stream is rebuilt when the see-through set changes: {back:?}"); + } + /// The middle pixel of `scene` drawn looking down -Z (x, y in -10..10) into a 64 × 64 frame, /// with order-independent transparency (`oit`) or with the see-through triangles sorted. /// `None` without a GPU adapter. @@ -3202,7 +3951,7 @@ mod glass_tests { let (_, device, queue) = crate::open_headless().ok()?; let depth = crate::depth_format(&device, true); let format = wgpu::TextureFormat::Rgba8Unorm; - let mut r = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples, tess: false }, None); + let mut r = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples, tess: false, oit: false }, None); assert!(r.oit.is_some(), "this device does order-independent transparency"); if !oit { r.oit = None; @@ -3411,9 +4160,10 @@ mod glass_tests { /// A frame of opaque triangles at the fixed view. fn test_scene() -> GpuScene { let mut scene = GpuScene::default(); - scene.tri([-5.0, -5.0, 0.0], [0.0, 0.0, 1.0], [255, 0, 0, 255]); - scene.tri([5.0, -5.0, 0.0], [0.0, 0.0, 1.0], [255, 0, 0, 255]); - scene.tri([0.0, 5.0, 0.0], [0.0, 0.0, 1.0], [255, 0, 0, 255]); + let red = scene.color([255, 0, 0, 255]); + scene.tri([-5.0, -5.0, 0.0], [0.0, 0.0, 1.0], red); + scene.tri([5.0, -5.0, 0.0], [0.0, 0.0, 1.0], red); + scene.tri([0.0, 5.0, 0.0], [0.0, 0.0, 1.0], red); scene } @@ -3425,7 +4175,7 @@ mod glass_tests { let Some((_, device, queue)) = crate::open_headless().ok() else { return }; let depth = crate::depth_format(&device, true); let format = wgpu::TextureFormat::Rgba8Unorm; - let mut r = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples: 1, tess: false }, None); + let mut r = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples: 1, tess: false, oit: false }, None); // Supersampled: the picture is drawn into a texture, so it can be cached. let mut frame = test_frame(test_scene(), 2.0); let first = render_frame(&mut r, &device, &queue, &frame, true); @@ -3448,8 +4198,8 @@ mod glass_tests { let Some((_, device, queue)) = crate::open_headless().ok() else { return }; let depth = crate::depth_format(&device, true); let format = wgpu::TextureFormat::Rgba8Unorm; - let scene_target = GpuTarget { format, depth: Some(depth), samples: 1, tess: false }; - let window_target = GpuTarget { format, depth: None, samples: 1, tess: false }; + let scene_target = GpuTarget { format, depth: Some(depth), samples: 1, tess: false, oit: false }; + let window_target = GpuTarget { format, depth: None, samples: 1, tess: false, oit: false }; let mut direct = Renderer::new(&device, scene_target, None); let mut split = Renderer::with_window_target(&device, scene_target, window_target, None); // Each renderer takes the scene out of its slot: a frame of its own for each. @@ -3468,7 +4218,7 @@ mod glass_tests { let Some((_, device, queue)) = crate::open_headless().ok() else { return }; let depth = crate::depth_format(&device, true); let format = wgpu::TextureFormat::Rgba8Unorm; - let mut r = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples: 1, tess: false }, None); + let mut r = Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples: 1, tess: false, oit: false }, None); let middle = |pixels: &[u8]| -> [i32; 4] { let at = (32 * 64 + 32) * 4; std::array::from_fn(|i| pixels.get(at + i).map_or(-1, |v| i32::from(*v))) @@ -3478,8 +4228,9 @@ mod glass_tests { assert!(r.ss_ready, "the see-through modelling frame is drawn offscreen"); assert!(model[0] > model[2] + 60, "the modelling frame shows its red layers: {model:?}"); let mut product = GpuScene::default(); + let blue = product.color([40, 80, 220, 255]); for p in [[-5.0, -5.0], [5.0, -5.0], [5.0, 5.0], [-5.0, -5.0], [5.0, 5.0], [-5.0, 5.0]] { - product.tri([p[0], p[1], 0.0], [0.0, 0.0, 1.0], [40, 80, 220, 255]); + product.tri([p[0], p[1], 0.0], [0.0, 0.0, 1.0], blue); } let mut frame = test_frame(product, 1.0); frame.product = true; @@ -3503,7 +4254,7 @@ mod glass_tests { }; let depth = crate::depth_format(&device, true); for format in [wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureFormat::Bgra8Unorm, wgpu::TextureFormat::Bgra8UnormSrgb] { - let window = GpuTarget { format, depth: None, samples: 1, tess: false }; + let window = GpuTarget { format, depth: None, samples: 1, tess: false, oit: false }; for samples in [1, 4] { if ![format, depth].iter().all(|f| adapter.get_texture_format_features(*f).flags.sample_count_supported(samples)) { continue; @@ -3539,6 +4290,7 @@ mod glass_tests { layers.reverse(); } for (z, c) in layers { + let c = sc.color(c); for p in [[-5.0, -5.0], [5.0, -5.0], [5.0, 5.0], [-5.0, -5.0], [5.0, 5.0], [-5.0, 5.0]] { sc.glass_tri([p[0], p[1], z], [0.0, 0.0, 1.0], c); } @@ -3572,9 +4324,10 @@ mod glass_tests { fn glass_is_drawn_far_to_near() { // Two triangles at z = 5 and z = -5, given near first; looking down from +Z. let mut sc = GpuScene::default(); + let red = sc.color([255, 0, 0, 100]); for z in [5.0f32, -5.0] { for p in [[0.0, 0.0, z], [1.0, 0.0, z], [0.0, 1.0, z]] { - sc.glass_tri(p, [0.0, 0.0, 1.0], [255, 0, 0, 100]); + sc.glass_tri(p, [0.0, 0.0, 1.0], red); } } let sorted = sort_back_to_front(&sc.glass, [0.0, 0.0, 1.0]); diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rs index 7bba01b88..e6e51525c 100644 --- a/crates/gpu/src/view/ao.rs +++ b/crates/gpu/src/view/ao.rs @@ -116,7 +116,7 @@ impl Resources { &mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, - uniform: &wgpu::BindGroup, + binds: [&wgpu::BindGroup; 2], radius: f32, size_px: [f32; 2], reversed: bool, @@ -152,8 +152,8 @@ impl Resources { occlusion_query_set: None, multiview_mask: None, }); - pass.set_bind_group(0, uniform, &[]); - for batch in batches { + for (batch, bind) in batches.into_iter().zip(binds) { + pass.set_bind_group(0, bind, &[]); pass.set_pipeline(&self.pipeline); if let Some(tris) = &batch.tris { for (buffer, count) in &tris.parts { @@ -161,15 +161,21 @@ impl Resources { pass.draw(0..*count, 0..1); } } + // The depth prepass is left out of the performance overlay's counts, as before. + let uncounted = super::Tally::default(); + // The blocks' opaque triangles, for the same depth. + for key in &batch.block_order { + if let Some(block) = batch.blocks.get(key) { + block.draw(&mut pass, super::TriClass::Opaque, &uncounted); + } + } pass.set_pipeline(&self.planned_pipeline); - for draw in &batch.planned { + for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) { pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..)); pass.set_vertex_buffer(1, draw.colors.slice(..)); pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32); pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1); } - // The depth prepass is left out of the performance overlay's counts, as before. - let uncounted = super::Tally::default(); for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) { draw.draw(&mut pass, &self.instanced_pipeline, &self.instanced_flat_pipeline, &uncounted); } diff --git a/crates/gpu/src/view/msaa_check.rs b/crates/gpu/src/view/msaa_check.rs index 7ad61ffe9..591c3581d 100644 --- a/crates/gpu/src/view/msaa_check.rs +++ b/crates/gpu/src/view/msaa_check.rs @@ -80,12 +80,14 @@ impl Renderer { fn probe_pixels(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, blank_samples: u32) -> Result { const SIZE: u32 = 16; let mut model = GpuScene::default(); + let red = model.color([255, 0, 0, 255]); for p in [[-0.9, -0.9, 0.0], [0.9, -0.9, 0.0], [0.0, 0.9, 0.0]] { - model.tri(p, [0.0, 0.0, 1.0], [255, 0, 0, 255]); + model.tri(p, [0.0, 0.0, 1.0], red); } let mut highlight = GpuScene::default(); + let blue = highlight.color([0, 0, 255, 64]); for p in [[-0.8, -0.8, 0.0], [0.8, -0.8, 0.0], [0.8, 0.8, 0.0], [-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], [-0.8, 0.8, 0.0]] { - highlight.xray_tri(p, [0.0, 0.0, 1.0], [0, 0, 255, 64]); + highlight.xray_tri(p, [0.0, 0.0, 1.0], blue); } let slot = |scene| Arc::new(Mutex::new(scene)); let frame = Frame { diff --git a/crates/gpu/src/view/oit.rs b/crates/gpu/src/view/oit.rs index 54245ceec..27bd99a45 100644 --- a/crates/gpu/src/view/oit.rs +++ b/crates/gpu/src/view/oit.rs @@ -8,7 +8,7 @@ //! sorted, on the CPU or the GPU, however many see-through triangles there are. The targets share //! the frame's depth (tested, not written), so the opaque model hides what lies behind it. -use super::{TriSource, depth_compare, instance_layout, shared_layout, tri_layout}; +use super::{TriSource, color_layout, depth_compare, instance_layout, planned_layout, shared_layout, tri_layout}; /// The accumulated colour (premultiplied, weighted) and alpha. const ACCUM: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; @@ -38,6 +38,8 @@ fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { pub(super) struct Pipelines { /// Built triangles ([`tri_layout`]), and instanced meshes smooth and flat. pub built: wgpu::RenderPipeline, + /// Faded and see-through bodies drawn from their plans' evaluated vertices. + pub planned: wgpu::RenderPipeline, pub instanced: wgpu::RenderPipeline, pub instanced_flat: wgpu::RenderPipeline, composite: wgpu::RenderPipeline, @@ -90,6 +92,7 @@ impl Pipelines { }), ]; let built_buffers = [Some(tri_layout())]; + let evaluated = [Some(planned_layout()), Some(color_layout())]; let placed = [Some(shared_layout()), Some(instance_layout())]; let pipeline = |label: &str, source: TriSource| { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { @@ -98,7 +101,11 @@ impl Pipelines { vertex: wgpu::VertexState { module, entry_point: Some(source.entry()), - buffers: if source == TriSource::Built { &built_buffers[..] } else { &placed[..] }, + buffers: match source { + TriSource::Built => &built_buffers[..], + TriSource::Planned => &evaluated[..], + TriSource::Instanced | TriSource::InstancedFlat => &placed[..], + }, compilation_options: Default::default(), }, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, @@ -121,6 +128,7 @@ impl Pipelines { }) }; let built = pipeline("sc_oit", TriSource::Built); + let planned = pipeline("sc_oit_planned", TriSource::Planned); let instanced = pipeline("sc_oit_instanced", TriSource::Instanced); let instanced_flat = pipeline("sc_oit_instanced_flat", TriSource::InstancedFlat); let texture = |binding| wgpu::BindGroupLayoutEntry { @@ -183,7 +191,7 @@ impl Pipelines { log::info!("see-through surfaces are sorted (no order-independent transparency here: {e})"); return None; } - Some(Pipelines { built, instanced, instanced_flat, composite, bgl }) + Some(Pipelines { built, planned, instanced, instanced_flat, composite, bgl }) } /// The targets for a frame of `size` pixels at `samples` per pixel. diff --git a/crates/gpu/tests/depth.rs b/crates/gpu/tests/depth.rs index 04744bf52..024aeca91 100644 --- a/crates/gpu/tests/depth.rs +++ b/crates/gpu/tests/depth.rs @@ -197,7 +197,8 @@ fn an_edge_on_a_face_draws_whole_at_any_angle() { fn a_selected_edge_on_a_grazing_face_draws_whole() { let highlight = |a: Vec3, b: Vec3, n: Vec3| { let mut sc = solidcraft_gpu::view::GpuScene::default(); - sc.lifted_line(a.to_f32(), b.to_f32(), [255, 0, 0, 255], 6.0, [n.to_f32(), n.to_f32()]); + let red = sc.color([255, 0, 0, 255]); + sc.lifted_line(a.to_f32(), b.to_f32(), red, 6.0, [n.to_f32(), n.to_f32()]); sc }; let reference = |a: Vec3, b: Vec3| vec![SceneLine { points: vec![a, b], color: Rgb(255, 0, 0), alpha: 1.0, width: 6.0, on_top: true }]; diff --git a/crates/ui-egui/src/extrude_preview.rs b/crates/ui-egui/src/extrude_preview.rs index 14d1541d4..227daa4bb 100644 --- a/crates/ui-egui/src/extrude_preview.rs +++ b/crates/ui-egui/src/extrude_preview.rs @@ -105,13 +105,15 @@ impl StraightPreview { let cache = self.cached.as_ref()?; let mut scene = GpuScene::default(); let mut bounds = cache.bounds; - let color = if operation == "cut" { - colors.removed + let (color, cut_edge) = if operation == "cut" { + (colors.removed, [colors.removed[0], colors.removed[1], colors.removed[2], 255]) } else if operation == "intersect" { - [colors.added[0], colors.added[1], colors.added[2], colors.removed[3]] + ([colors.added[0], colors.added[1], colors.added[2], colors.removed[3]], colors.edge) } else { - colors.added + (colors.added, colors.edge) }; + let color = scene.color(color); + let cut_edge = scene.color(cut_edge); let triangle = |scene: &mut GpuScene, points: [Vec3; 3], normal: Vec3| { for point in points { if matches!(operation, "cut" | "intersect") { @@ -131,7 +133,7 @@ impl StraightPreview { bounds.add(point); } } - let edge_color = if operation == "cut" { [color[0], color[1], color[2], 255] } else { colors.edge }; + let edge_color = if operation == "cut" { cut_edge } else { scene.color(colors.edge) }; for &[a, b] in &surface.edges { let normal = (b - a).cross(surface.normal).normalized()?; triangle(&mut scene, [a + low, b + low, b + high], normal); diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 4903b7511..2535f3dda 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -8,9 +8,9 @@ use std::sync::{Arc, Mutex}; use egui_wgpu::wgpu; pub use solidcraft_gpu::view::{ - AccessMap, BlockBytes, BlockTris, DrawStats, DrawStatsHandle, Frame, GpuImage, GpuScene, GpuTarget, INSTANCE_SIZE, InstanceLook, InstancedMesh, - LINE_SIZE, LOD_PX, PBR_SIZE, PlannedBody, Renderer, SHARED_SIZE, SceneBlock, SceneSlot, SharedTris, TRI_SIZE, level_for, placement_scale, - supersampled_size, + AccessMap, BlockBuilder, BlockBytes, BlockTris, DrawStats, DrawStatsHandle, Frame, GpuImage, GpuScene, GpuTarget, INSTANCE_SIZE, InstanceLook, + InstancedMesh, LINE_SIZE, LOD_PX, MAX_PALETTE, PBR_SIZE, Palette, PaletteIndex, PlannedBody, Renderer, SHARED_SIZE, SceneBlock, SceneSlot, + SharedTris, TRI_SIZE, TriClass, extend_runs, level_for, placement_scale, runs_within, supersampled_size, }; /// A frame of the viewport as an egui paint callback. @@ -27,6 +27,8 @@ pub fn install(rs: &egui_wgpu::RenderState, scene: GpuTarget, window: GpuTarget, let scene = GpuTarget { tess: tess.is_some(), ..scene }; let window = GpuTarget { tess: tess.is_some(), ..window }; let res = Renderer::with_window_target(&rs.device, scene, window, tess); + // What the renderer can do (order-independent transparency), not only what was asked for. + let scene = res.target(); let stats = res.stats(); rs.renderer.write().callback_resources.insert(res); (scene, stats) @@ -333,7 +335,7 @@ fn offscreen( let format = if srgb { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }; let depth = solidcraft_gpu::depth_format(&device, true); let compute = tess.and_then(|shader| solidcraft_gpu::view::tessellation(&adapter, &device, &queue, shader)); - let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: compute.is_some() }; + let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: compute.is_some(), oit: false }; let mut resources = egui_wgpu::CallbackResources::default(); resources.insert(Renderer::new(&device, target, compute)); let none = || Arc::new(Mutex::new(None)); @@ -428,6 +430,106 @@ fn offscreen( Some(bytes) } +/// A viewport renderer kept on an offscreen device of its own, for timing frames (prepare, paint, +/// and the GPU finishing them) as the window would draw them. Scale measurements only. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) struct OffscreenFrames { + device: wgpu::Device, + queue: wgpu::Queue, + resources: egui_wgpu::CallbackResources, + color: wgpu::TextureView, + depth: wgpu::TextureView, + size: u32, +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +impl OffscreenFrames { + /// `None` without a GPU adapter. With `tess`, planned bodies are evaluated on the GPU. + pub(crate) fn new(size: u32, tess: bool) -> Option { + let (adapter, device, queue) = offscreen_device()?; + let format = wgpu::TextureFormat::Rgba8Unorm; + let depth = solidcraft_gpu::depth_format(&device, true); + let compute = if tess { solidcraft_gpu::view::tessellation(&adapter, &device, &queue, solidcraft_gpu::SHADER) } else { None }; + let target = GpuTarget { format, depth: Some(depth), samples: 1, tess: compute.is_some(), oit: false }; + let mut resources = egui_wgpu::CallbackResources::default(); + resources.insert(Renderer::new(&device, target, compute)); + let texture = |format, usage| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some("offscreen frames"), + size: wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let color = texture(format, wgpu::TextureUsages::RENDER_ATTACHMENT); + let depth = texture(depth, wgpu::TextureUsages::RENDER_ATTACHMENT); + Some(OffscreenFrames { device, queue, resources, color, depth, size }) + } + + /// What the renderer can do, as the viewport is told when the window's renderer is + /// installed (plans evaluated, order-independent transparency). + pub(crate) fn target(&self) -> Option { + self.resources.get::().map(Renderer::target) + } + + /// Whether the device evaluates plans (so scenes should be built with `tess`). + pub(crate) fn tessellates(&self) -> bool { + self.resources.get::().is_some_and(|r| r.target().tess) + } + + /// Draw one frame and wait for the GPU: milliseconds from `prepare` to the work finishing. + pub(crate) fn frame(&mut self, frame: Frame) -> f64 { + let started = std::time::Instant::now(); + let cb = ViewportCallback(frame); + let mut encoder = self.device.create_command_encoder(&Default::default()); + let screen = egui_wgpu::ScreenDescriptor { size_in_pixels: [self.size, self.size], pixels_per_point: 1.0 }; + let extra = egui_wgpu::CallbackTrait::prepare(&cb, &self.device, &self.queue, &screen, &mut encoder, &mut self.resources); + { + let mut pass = encoder + .begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("offscreen frames"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &self.color, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &self.depth, + depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Store }), + stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Store }), + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + .forget_lifetime(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(self.size as f32, self.size as f32)); + let info = egui::PaintCallbackInfo { viewport: rect, clip_rect: rect, pixels_per_point: 1.0, screen_size_px: [self.size, self.size] }; + egui_wgpu::CallbackTrait::paint(&cb, info, &mut pass, &self.resources); + } + self.queue.submit(extra.into_iter().chain([encoder.finish()])); + let _ = self.device.poll(wgpu::PollType::wait_indefinitely()); + started.elapsed().as_secs_f64() * 1000.0 + } + + /// What the model scene's last change uploaded. + pub(crate) fn uploads(&self) -> solidcraft_gpu::view::UploadStats { + self.resources.get::().map(Renderer::uploads).unwrap_or_default() + } + + /// What the last frame drew. + pub(crate) fn stats(&self) -> DrawStats { + self.resources.get::().and_then(|r| r.stats().lock().ok().map(|s| *s)).unwrap_or_default() + } +} + #[cfg(test)] mod tests { /// The offscreen tests start the backends the app would: on Windows without `WGPU_BACKEND` diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b9fad80b3..e4bb6b38b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -211,6 +211,7 @@ mod rule_editor; mod rule_editor_tests; pub mod save_job; pub mod scenario; +pub(crate) mod scene_palette; pub mod select_other; pub mod selection; pub mod shell; @@ -778,6 +779,7 @@ impl SolveApp { depth: egui_wgpu::depth_format_from_bits(depth_bits, stencil_bits), samples: samples.max(1), tess: false, + oit: false, }; self.set_wgpu_targets(rs, target, target); } @@ -792,8 +794,9 @@ impl SolveApp { depth: egui_wgpu::depth_format_from_bits(depth_bits, stencil_bits), samples: samples.max(1), tess: false, + oit: false, }; - let window = crate::gpu::GpuTarget { format: rs.target_format, depth: None, samples: 1, tess: false }; + let window = crate::gpu::GpuTarget { format: rs.target_format, depth: None, samples: 1, tess: false, oit: false }; self.set_wgpu_targets(rs, scene, window); self.viewport.gpu.map_or(samples, |g| g.samples) } diff --git a/crates/ui-egui/src/move_preview.rs b/crates/ui-egui/src/move_preview.rs index afbe61bb7..f66ba782d 100644 --- a/crates/ui-egui/src/move_preview.rs +++ b/crates/ui-egui/src/move_preview.rs @@ -91,6 +91,7 @@ impl MovePreview { let m = rigid(translate, Vec3::ZERO, axis, angle); let copy = params.get("copy").and_then(Value::as_bool) == Some(true); let mut scene = GpuScene::default(); + let removed = scene.color(colors.removed); let mut bounds = Aabb3::EMPTY; for mesh in &cache.meshes { draw(&mut scene, mesh, &m, colors, &mut bounds); @@ -99,7 +100,7 @@ impl MovePreview { for t in &mesh.triangles { for k in t { if let (Some(p), Some(n)) = (mesh.positions.get(*k as usize), mesh.normals.get(*k as usize)) { - scene.ghost_tri(p.to_f32(), n.to_f32(), colors.removed); + scene.ghost_tri(p.to_f32(), n.to_f32(), removed); } } } @@ -120,22 +121,24 @@ impl MovePreview { /// `mesh` moved by `m`, in the colour of geometry the feature adds, with its shaded edges. fn draw(scene: &mut GpuScene, mesh: &Mesh, m: &Mat, colors: Colors, bounds: &mut Aabb3) { + let added = scene.color(colors.added); for t in &mesh.triangles { for k in t { let i = *k as usize; if let (Some(p), Some(n)) = (mesh.positions.get(i), mesh.normals.get(i)) { let p = apply_point(m, *p); bounds.add(p); - scene.tri(p.to_f32(), apply_vector(m, *n).to_f32(), colors.added); + scene.tri(p.to_f32(), apply_vector(m, *n).to_f32(), added); } } } + let edge = scene.color(colors.edge); for (ei, e) in mesh.edges.iter().enumerate() { if !mesh.shaded_edge_visible(ei) { continue; } for w in e.windows(2) { - scene.line(apply_point(m, w[0]).to_f32(), apply_point(m, w[1]).to_f32(), colors.edge, 1.3, false); + scene.line(apply_point(m, w[0]).to_f32(), apply_point(m, w[1]).to_f32(), edge, 1.3, false); } } } diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index 53d980725..e64fb145e 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -520,6 +520,10 @@ fn state_bounds(st: &ModelState) -> Aabb3 { /// (red) and intersect. fn build_tool(before: &ModelState, after: &ModelState, c: Colors, op: &str) -> Built { let mut sc = GpuScene::default(); + let removed = sc.color(c.removed); + let intersect = sc.color([c.added[0], c.added[1], c.added[2], c.removed[3]]); + let added = sc.color(c.added); + let edge = if op == "cut" { sc.color([c.removed[0], c.removed[1], c.removed[2], 255]) } else { sc.color(c.edge) }; for a in after.bodies.iter().filter(|a| before.body(&a.name).is_none()) { let m = a.mesh(); for t in &m.triangles { @@ -527,14 +531,13 @@ fn build_tool(before: &ModelState, after: &ModelState, c: Colors, op: &str) -> B let i = *k as usize; if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { match op { - "cut" => sc.xray_tri(p.to_f32(), n.to_f32(), c.removed), - "intersect" => sc.xray_tri(p.to_f32(), n.to_f32(), [c.added[0], c.added[1], c.added[2], c.removed[3]]), - _ => sc.tri(p.to_f32(), n.to_f32(), c.added), + "cut" => sc.xray_tri(p.to_f32(), n.to_f32(), removed), + "intersect" => sc.xray_tri(p.to_f32(), n.to_f32(), intersect), + _ => sc.tri(p.to_f32(), n.to_f32(), added), } } } } - let edge = if op == "cut" { [c.removed[0], c.removed[1], c.removed[2], 255] } else { c.edge }; for (ei, e) in m.edges.iter().enumerate() { if m.shaded_edge_visible(ei) { for w in e.windows(2) { @@ -586,6 +589,12 @@ fn same(a: &Mesh, b: &Mesh) -> bool { /// version of changed or removed bodies. pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { let mut sc = GpuScene::default(); + let added_color = sc.color(c.added); + let added_plane = sc.color([c.added[0], c.added[1], c.added[2], 64]); + let body_color = sc.color(c.body); + let new_body = sc.color(c.new_body); + let removed = sc.color(c.removed); + let edge = sc.color(c.edge); let mut replaced = Vec::new(); for construct in &after.construct { if before.construct.iter().any(|old| old == construct) { @@ -594,14 +603,13 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { if let solidcraft_engine::doc::construct::ConstructGeom::Plane(plane) = construct.geom { let (o, x, y) = (plane.origin, plane.x * 10.0, plane.y * 10.0); let quad = [o - x - y, o + x - y, o + x + y, o - x + y]; - let color = [c.added[0], c.added[1], c.added[2], 64]; for triangle in [[quad[0], quad[1], quad[2]], [quad[0], quad[2], quad[3]]] { for p in triangle { - sc.xray_tri(p.to_f32(), plane.normal().to_f32(), color); + sc.xray_tri(p.to_f32(), plane.normal().to_f32(), added_plane); } } for (a, b) in Ring::from(quad).edges() { - sc.line(a.to_f32(), b.to_f32(), c.added, 1.3, true); + sc.line(a.to_f32(), b.to_f32(), added_color, 1.3, true); } } } @@ -622,16 +630,16 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { for (t, f) in am.triangles.iter().zip(&am.tri_face) { let new = added.get(*f as usize).copied().unwrap_or(true); let col = match (new, old.is_some()) { - (false, _) => c.body, - (true, true) => c.added, - (true, false) => c.new_body, + (false, _) => body_color, + (true, true) => added_color, + (true, false) => new_body, }; for k in t { let i = *k as usize; if let (Some(p), Some(n)) = (am.positions.get(i), am.normals.get(i)) { sc.tri(p.to_f32(), n.to_f32(), col); if new && cut { - sc.xray_tri(p.to_f32(), n.to_f32(), c.removed); + sc.xray_tri(p.to_f32(), n.to_f32(), removed); } } } @@ -641,7 +649,7 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { continue; } for w in e.windows(2) { - sc.line(w[0].to_f32(), w[1].to_f32(), c.edge, 1.3, false); + sc.line(w[0].to_f32(), w[1].to_f32(), edge, 1.3, false); } } if old.is_some() { @@ -658,7 +666,7 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { for k in t { let i = *k as usize; if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { - sc.ghost_tri(p.to_f32(), n.to_f32(), c.removed); + sc.ghost_tri(p.to_f32(), n.to_f32(), removed); } } } @@ -1127,8 +1135,14 @@ mod tests { assert!((b.max.z - 18.0).abs() < 1e-6 && (b.max.y - 30.0).abs() < 1e-6, "on top, not at right angles: {b:?}"); } - fn count(bytes: &[u8], stride: usize, col: [u8; 4]) -> usize { - bytes.chunks(stride).filter(|v| v.get(24..28) == Some(&col[..])).count() + fn count(scene: &GpuScene, bytes: &[u8], stride: usize, col: [u8; 4]) -> usize { + bytes + .chunks(stride) + .filter(|v| { + let Some(i) = v.get(24..28).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) else { return false }; + scene.palette.get(crate::gpu::PaletteIndex(i)) == Some(col) + }) + .count() } #[test] @@ -1138,10 +1152,11 @@ mod tests { let p = s.preview(&[("solid.hole".to_string(), json!({"position": [20, 15, 20], "diameter": 5, "depth": 10}))]).unwrap(); let b = build(&p.before, &p.after, colors()); // The hole's walls are drawn see-through in the cut colour (seen from any side). - assert!(count(&b.scene.xray, 28, colors().removed) > 0); + assert!(count(&b.scene, &b.scene.xray, 28, colors().removed) > 0); // A feature that only adds material shows no cut. let p = s.preview(&[("solid.box".to_string(), json!({"length": 10, "width": 10, "height": 30, "operation": "join"}))]).unwrap(); - assert_eq!(count(&build(&p.before, &p.after, colors()).scene.xray, 28, colors().removed), 0); + let b = build(&p.before, &p.after, colors()); + assert_eq!(count(&b.scene, &b.scene.xray, 28, colors().removed), 0); } fn plate() -> Session { @@ -1276,8 +1291,8 @@ mod tests { let (rev, undo) = (s.revision, s.undo.len()); let b = compute(&s, &[("solid.fillet".into(), json!({"edges": [[0, 0, 10]], "radius": 3}))], colors()).unwrap(); assert_eq!(b.replaced, vec!["Body1".to_string()]); - let added = count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().added); - let kept = count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().body); + let added = count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().added); + let kept = count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().body); assert!(added > 0 && kept > 0, "added {added} kept {kept}"); assert!(!b.scene.ghost.is_empty()); assert_eq!(s.revision, rev); @@ -1306,10 +1321,10 @@ mod tests { s.execute("sketch.finish", &json!({})).unwrap(); let b = compute(&s, &[("solid.extrude".into(), json!({"distance": "15 mm"}))], colors()).unwrap(); assert!(b.replaced.is_empty()); - assert_eq!(count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().body), 0); + assert_eq!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().body), 0); // #1805: a new body has its own colour, not a join's. - assert!(count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().new_body) > 0); - assert_eq!(count(&b.scene.tris, crate::gpu::TRI_SIZE, colors().added), 0); + assert!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().new_body) > 0); + assert_eq!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, colors().added), 0); assert!(b.scene.ghost.is_empty()); assert!(compute(&s, &[("solid.extrude".into(), json!({"distance": "1 +"}))], colors()).is_err()); assert!(s.model.state().bodies.is_empty()); @@ -1404,7 +1419,8 @@ mod tests { fn reset_hands_the_viewport_an_empty_scene() { let mut pv = PreviewState::default(); let mut sc = GpuScene::default(); - sc.xray_tri([0.0; 3], [0.0, 0.0, 1.0], [255; 4]); + let white = sc.color([255; 4]); + sc.xray_tri([0.0; 3], [0.0, 0.0, 1.0], white); pv.set_scene(sc); pv.active = true; pv.replaced = vec!["Body1".into()]; diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 5ce821678..27c796ef8 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -1511,6 +1511,7 @@ pub fn gpu_scene(scene: &ProductScene) -> Result<(u64, GpuScene), String> { }); let [Some(a), Some(b), Some(c)] = vertices else { return Err("invalid product triangle".into()) }; let rgba = [color[0], color[1], color[2], (opacity * 255.0).round() as u8]; + let index = gpu.color(rgba); for (p, n) in [a, b, c] { if let Some(surface) = surface { if n.iter().all(|v| *v == 0.0) { @@ -1518,9 +1519,9 @@ pub fn gpu_scene(scene: &ProductScene) -> Result<(u64, GpuScene), String> { } gpu.pbr_tri(p, n, surface); } else if opacity < 0.999 { - gpu.glass_tri(p, n, rgba); + gpu.glass_tri(p, n, index); } else { - gpu.tri(p, n, rgba); + gpu.tri(p, n, index); } } } diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index a7fbecc80..965207560 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -645,7 +645,11 @@ fn product_gpu_buffers_preserve_opacity_and_never_contain_overlays() { let (key, gpu) = gpu_scene(&scene).unwrap(); assert!(gpu.tris.is_empty()); assert!(!gpu.glass.is_empty()); - assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| v[24..] == [51, 102, 153, 102])); + let color = |v: &[u8]| { + let i = v.get(crate::gpu::TRI_SIZE - 4..).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; + gpu.palette.get(crate::gpu::PaletteIndex(i)) + }; + assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| color(v) == Some([51, 102, 153, 102]))); assert!(gpu.lines.is_empty() && gpu.overlay.is_empty() && gpu.under.is_empty() && gpu.hidden.is_empty() && gpu.ghost.is_empty()); s.selection = vec![solidcraft_engine::Sel::Body { name: "Glass".into() }]; s.section = Some((solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::X)); diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs index 501171960..ad7598c7d 100644 --- a/crates/ui-egui/src/scale_tests.rs +++ b/crates/ui-egui/src/scale_tests.rs @@ -71,6 +71,303 @@ fn frame_and_cheap_command_cost_by_body_count() { } } +/// Times the model scene build after the edits that used to rebuild and upload everything: +/// selection (a revision bump with no model change), an appearance colour and an opacity class +/// change, a theme switch, and one body's geometry edit. Run with `--ignored --nocapture`. +#[test] +#[ignore = "manual palette measurement"] +fn appearance_and_selection_rebuild_cost() { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + for n in [200usize, 1000, 5000] { + let mut h = grid(n); + h.app.session.world_state().warm_meshes(|| true); + h.frames(2); + let body = h.app.session.world_state().bodies[0].name.clone(); + let cold = ms(|| drop(crate::viewport::build_scene(&h.app))); + let again = ms(|| drop(crate::viewport::build_scene(&h.app))); + let proj = crate::viewport::projection(&h.app, rect); + let key = crate::viewport::display_scene_keys(&h.app, &proj).0; + h.app.run("select.set", json!({"items":[{"type":"body","name":body}]})).unwrap(); + let selection_key_changed = crate::viewport::display_scene_keys(&h.app, &proj).0 != key; + let selection = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("select.clear", json!({})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699"})).unwrap(); + let colour = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699","opacity":0.5})).unwrap(); + let opacity_class = ms(|| drop(crate::viewport::build_scene(&h.app))); + let theme_name = if crate::theme::is_dark() { "light" } else { "dark" }; + let _ = h.call("ui.prefs", json!({"theme": theme_name})); + let theme = ms(|| drop(crate::viewport::build_scene(&h.app))); + let geometry = match h.app.run("solid.move", json!({"bodies":[body.clone()], "translate":[1.0, 0.0, 0.0]})) { + Ok(_) => ms(|| drop(crate::viewport::build_scene(&h.app))), + Err(e) => { + println!("MEASURE n={n} geometry edit refused: {e}"); + f64::NAN + } + }; + println!( + "MEASURE n={n} cold_ms={cold:.1} unchanged_ms={again:.1} selection_ms={selection:.1} selection_rebuilds={selection_key_changed} colour_ms={colour:.1} opacity_class_ms={opacity_class:.1} theme_ms={theme:.1} geometry_ms={geometry:.1}" + ); + } +} + +/// The same edits on a design of few, large meshes: the case where rebuilding a block rebuilt and +/// re-uploaded a large part of the model. Run with `--ignored --nocapture`. +#[test] +#[ignore = "manual palette measurement"] +fn large_body_scene_rebuild_cost() { + for n in [20usize, 100] { + let mut h = Harness::new(); + for k in 0..n { + h.app + .run("solid.torus", json!({"major": 100, "minor": 10, "center": [k as f64 * 220.0, 0.0, 0.0], "body_name": format!("T{k}")})) + .unwrap(); + } + h.app.session.world_state().warm_meshes(|| true); + h.frames(2); + let bodies = h.app.session.world_state().bodies.len(); + let triangles: usize = h.app.session.world_state().bodies.iter().map(|b| b.mesh().triangles.len()).sum(); + let body = h.app.session.world_state().bodies[0].name.clone(); + let cold = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699"})).unwrap(); + let colour = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("appearance.assign", json!({"bodies":[body.clone()],"color":"#336699","opacity":0.5})).unwrap(); + let opacity_class = ms(|| drop(crate::viewport::build_scene(&h.app))); + let theme_name = if crate::theme::is_dark() { "light" } else { "dark" }; + let _ = h.call("ui.prefs", json!({"theme": theme_name})); + let theme = ms(|| drop(crate::viewport::build_scene(&h.app))); + println!( + "LARGE n={n} bodies={bodies} triangles={triangles} cold_ms={cold:.1} colour_ms={colour:.1} opacity_class_ms={opacity_class:.1} theme_ms={theme:.1}" + ); + } +} + +/// An assembly: `unique` detailed parts (a patterned torus, ~8,400 triangles each) and one +/// detailed component placed `placed` times (drawn as instances). Settled, with warm meshes. +fn assembly(unique: usize, placed: usize) -> Harness { + let mut h = Harness::new(); + let per = |n: usize| (n as f64).sqrt().ceil().max(1.0) as usize; + h.app.run("solid.torus", json!({"major": 40, "minor": 6, "center": [0, 0, 0], "body_name": "Part"})).unwrap(); + let (c1, c2) = (per(unique), unique.div_ceil(per(unique))); + h.app + .run( + "solid.pattern.rectangular", + json!({"bodies": ["Part"], "dir1": [1, 0, 0], "count1": c1, "spacing1": 100, "dir2": [0, 1, 0], "count2": c2, "spacing2": 100}), + ) + .unwrap(); + h.app.run("solid.torus", json!({"major": 40, "minor": 6, "center": [0, 0, -200], "body_name": "Wheel"})).unwrap(); + h.app.run("component.from_bodies", json!({"bodies": ["Wheel"]})).unwrap(); + let (p1, p2) = (per(placed), placed.div_ceil(per(placed))); + h.app + .run( + "solid.pattern.rectangular", + json!({"components": ["Wheel"], "dir1": [1, 0, 0], "count1": p1, "spacing1": 100, "dir2": [0, 1, 0], "count2": p2, "spacing2": 100}), + ) + .unwrap(); + h.app.session.world_state().warm_meshes(|| true); + h.frames(3); + h +} + +/// The edits made on an assembly, timed on the model scene build: selection, a part's colour and +/// opacity, a component's colour (every placement), a theme switch, hiding a part, and moving one +/// part. Run with `--ignored --nocapture`. +#[test] +#[ignore = "manual palette measurement"] +fn assembly_scene_rebuild_cost() { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + for (unique, placed) in [(100, 100), (300, 500)] { + let mut h = assembly(unique, placed); + let st = h.app.session.world_state(); + let bodies = st.bodies.len(); + let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum(); + let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap(); + drop(st); + let cold = ms(|| drop(crate::viewport::build_scene(&h.app))); + let unchanged = ms(|| drop(crate::viewport::build_scene(&h.app))); + let proj = crate::viewport::projection(&h.app, rect); + let key = crate::viewport::display_scene_keys(&h.app, &proj).0; + h.app.run("select.set", json!({"items": [{"type": "body", "name": part}]})).unwrap(); + let selection_rebuilds = crate::viewport::display_scene_keys(&h.app, &proj).0 != key; + let selection = if selection_rebuilds { ms(|| drop(crate::viewport::build_scene(&h.app))) } else { 0.0 }; + h.app.run("select.clear", json!({})).unwrap(); + // The command itself (the engine's refresh) and then the scene build. + let colour_command = ms(|| drop(h.app.run("appearance.assign", json!({"bodies": [part.clone()], "color": "#336699"})).unwrap())); + let colour = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("appearance.assign", json!({"bodies": [part.clone()], "color": "#336699", "opacity": 0.5})).unwrap(); + let opacity_class = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("appearance.assign", json!({"components": ["Wheel"], "color": "#cc6633"})).unwrap(); + let component_colour = ms(|| drop(crate::viewport::build_scene(&h.app))); + let theme_name = if crate::theme::is_dark() { "light" } else { "dark" }; + let _ = h.call("ui.prefs", json!({"theme": theme_name})); + let theme = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("browser.visibility", json!({"visible": false, "items": [part.clone()]})).unwrap(); + let hide = ms(|| drop(crate::viewport::build_scene(&h.app))); + h.app.run("browser.visibility", json!({"visible": true, "items": [part.clone()]})).unwrap(); + let _ = crate::viewport::build_scene(&h.app); + let geometry = match h.app.run("solid.move", json!({"bodies": [part.clone()], "translate": [1.0, 0.0, 0.0]})) { + Ok(_) => ms(|| drop(crate::viewport::build_scene(&h.app))), + Err(_) => f64::NAN, + }; + println!( + "ASSEMBLY unique={unique} placed={placed} bodies={bodies} triangles={triangles} cold_ms={cold:.1} unchanged_ms={unchanged:.1} selection_ms={selection:.1} colour_command_ms={colour_command:.1} colour_ms={colour:.1} opacity_class_ms={opacity_class:.1} component_colour_ms={component_colour:.1} theme_ms={theme:.1} hide_ms={hide:.1} geometry_ms={geometry:.1}" + ); + } +} + +/// Hovering the document tree on an assembly: the highlight scene built as the pointer moves +/// from row to row (one part, one placement of the component, the component's every placement, +/// the whole design), then back over rows it has lit before. Run with `--ignored --nocapture`. +#[test] +#[ignore = "manual highlight measurement"] +fn assembly_tree_hover_highlight_cost() { + for (unique, placed) in [(100, 100), (300, 500)] { + let mut h = assembly(unique, placed); + let _ = crate::viewport::build_scene(&h.app); + let st = h.app.session.world_state(); + let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap(); + let wheels: Vec = st.bodies.iter().filter(|b| b.component != 0).map(|b| b.name.clone()).collect(); + let everything: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); + drop(st); + let rows = [("part", vec![part.clone()]), ("placement", wheels[..1].to_vec()), ("component", wheels.clone()), ("design", everything.clone())]; + let mut line = format!("HOVER unique={unique} placed={placed}"); + for (name, bodies) in rows.iter() { + h.app.viewport.hover_bodies = bodies.clone(); + let first = ms(|| drop(crate::viewport::build_highlight(&h.app))); + line.push_str(&format!(" {name}_ms={first:.2}")); + } + // Moving back and forth between two rows, as the pointer runs down the tree. + let mut again = Vec::new(); + for i in 0..20 { + h.app.viewport.hover_bodies = if i % 2 == 0 { vec![part.clone()] } else { wheels.clone() }; + again.push(ms(|| drop(crate::viewport::build_highlight(&h.app)))); + } + again.sort_by(f64::total_cmp); + line.push_str(&format!(" back_and_forth_median_ms={:.2}", again[again.len() / 2])); + h.app.viewport.hover_bodies.clear(); + let none = ms(|| drop(crate::viewport::build_highlight(&h.app))); + line.push_str(&format!(" none_ms={none:.2}")); + println!("{line}"); + } +} + +/// A frame of the viewport for `app`'s camera, drawing the given model and highlight scenes. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn view_frame( + app: &crate::SolveApp, + size: u32, + model: (u64, &crate::gpu::SceneSlot), + highlight: (u64, &crate::gpu::SceneSlot), +) -> crate::gpu::Frame { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(size as f32, size as f32)); + let proj = crate::viewport::projection(app, rect); + let e = proj.cam.eye().to_f32(); + let t = crate::theme::Tokens::get(); + let none = || std::sync::Arc::new(std::sync::Mutex::new(None)); + crate::gpu::Frame { + product: false, + key: model.0, + slot: model.1.clone(), + sketch_key: 0, + sketch_slot: none(), + hl_key: highlight.0, + hl_slot: highlight.1.clone(), + pv_key: 0, + pv_slot: none(), + pv_hide: false, + view_proj: proj.vp.to_f32(), + back: proj.cam.back().to_f32(), + size_px: [size as f32; 2], + clip: [0.0; 4], + cap: [0.0; 4], + images: Vec::new(), + analysis: [0.0; 8], + analysis_colors: crate::gpu::analysis_colors(&t.analysis), + access: None, + outline: false, + eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }], + ao_radius: 0.0, + ssaa: 1.0, + hover_tint: [f32::from(t.hover_face_lift) / 255.0; 3], + selection_tint: [0.4, 0.6, 0.9], + } +} + +/// Time hovering four rows of `h`'s tree (one part, one placement, every placement of the +/// component, the whole design), each hover change building, uploading and drawing the highlight. +#[cfg(not(target_arch = "wasm32"))] +fn hover_rows(h: &mut Harness, frames: &mut crate::gpu::OffscreenFrames, size: u32, model_key: u64, label: &str) -> String { + let st = h.app.session.world_state(); + let part = st.bodies.iter().find(|b| b.component == 0).map(|b| b.name.clone()).unwrap(); + let wheels: Vec = st.bodies.iter().filter(|b| b.component != 0).map(|b| b.name.clone()).collect(); + let everything: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); + drop(st); + let model: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(crate::viewport::build_scene(&h.app)))); + let highlight: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None)); + let cold = frames.frame(view_frame(&h.app, size, (model_key, &model), (model_key, &highlight))); + let mut still = Vec::new(); + for _ in 0..5 { + still.push(frames.frame(view_frame(&h.app, size, (model_key, &model), (model_key, &highlight)))); + } + still.sort_by(f64::total_cmp); + let mut line = format!("{label} cold_ms={cold:.1} still_ms={:.2} triangles={}", still[2], frames.stats().triangles); + let rows = [("part", vec![part]), ("placement", wheels[..1].to_vec()), ("component", wheels.clone()), ("design", everything)]; + let mut key = model_key; + for (name, bodies) in rows.iter() { + let mut times = Vec::new(); + for _ in 0..7 { + // Off the row and back on: each time a new highlight scene, as a sweep does. + for hovered in [Vec::new(), bodies.clone()] { + h.app.viewport.hover_bodies = hovered; + key += 1; + let built = std::time::Instant::now(); + *highlight.lock().unwrap() = Some(crate::viewport::build_highlight(&h.app)); + let build_ms = built.elapsed().as_secs_f64() * 1000.0; + let ms = frames.frame(view_frame(&h.app, size, (model_key, &model), (key, &highlight))); + if !h.app.viewport.hover_bodies.is_empty() { + times.push((build_ms + ms, build_ms)); + } + } + } + times.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (total, build) = times[times.len() / 2]; + line.push_str(&format!(" {name}_ms={total:.2} {name}_build_ms={build:.2}")); + } + h.app.viewport.hover_bodies.clear(); + line +} + +/// Hovering the document tree on an assembly, as the window draws it: each hover change builds +/// the highlight scene, uploads it and draws the frame (GPU work included), on an offscreen +/// renderer with GPU tessellation where the device has it. Then the same with the component +/// active (every other part faded, as when working in context) and with see-through parts. +/// Skipped without a GPU adapter. Run with `--ignored --nocapture`. +#[cfg(not(target_arch = "wasm32"))] +#[test] +#[ignore = "manual highlight measurement"] +fn assembly_tree_hover_frame_cost() { + const SIZE: u32 = 1024; + let Some(mut frames) = crate::gpu::OffscreenFrames::new(SIZE, true) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + for (design, (unique, placed)) in [(100, 100), (300, 500)].into_iter().enumerate() { + // Keys of their own for each scene: the renderer keeps a scene while its key comes back. + let base = 1_000_000 * (3 * design as u64 + 1); + let mut h = assembly(unique, placed); + h.app.viewport.gpu = frames.target(); + h.app.fit_view(); + let label = format!("HOVERFRAME unique={unique} placed={placed} tess={}", frames.tessellates()); + println!("{}", hover_rows(&mut h, &mut frames, SIZE, base, &format!("{label} mode=plain"))); + h.app.run("component.activate", json!({"component": "Wheel"})).unwrap(); + println!("{}", hover_rows(&mut h, &mut frames, SIZE, base + 1_000_000, &format!("{label} mode=component_active"))); + h.app.run("component.activate", json!({"component": 0})).unwrap(); + let parts: Vec = h.app.session.world_state().bodies.iter().filter(|b| b.component == 0).map(|b| b.name.clone()).collect(); + h.app.run("appearance.assign", json!({"bodies": parts, "color": "#88aacc", "opacity": 0.5})).unwrap(); + println!("{}", hover_rows(&mut h, &mut frames, SIZE, base + 2_000_000, &format!("{label} mode=glass_parts"))); + } +} + /// A design from a file (`SOLIDCRAFT_SCALE_DESIGN`), every browser folder open: the time of an /// idle frame and of the cheap commands, as [`frame_and_cheap_command_cost_by_body_count`]. #[test] @@ -128,7 +425,105 @@ fn whole_body_highlight_cost_from_the_models_own_triangles() { let bodies = names.len(); h.app.viewport.hover_bodies = names; let copied = ms(|| drop(crate::viewport::build_highlight(&h.app))); - h.app.viewport.gpu = Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true }); + h.app.viewport.gpu = + Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true, oit: false }); let planned = ms(|| drop(crate::viewport::build_highlight(&h.app))); println!("HIGHLIGHT bodies={bodies} triangles={triangles} cpu_copy_ms={copied:.2} model_triangles_ms={planned:.2}"); } + +/// A STEP file (`SOLIDCRAFT_SCALE_STEP`), opened as the app opens one (a new design and +/// `file.insert_step`): the time of each phase of opening it, of an idle frame with its tree, of +/// the model scene and of appearance edits on it, and of hovering its bodies on an offscreen GPU +/// (skipped without an adapter). Run with `--ignored --nocapture`. +#[cfg(not(target_arch = "wasm32"))] +#[test] +#[ignore = "manual measurement on a STEP file"] +fn step_file_cost() { + let Some(path) = std::env::var_os("SOLIDCRAFT_SCALE_STEP") else { return }; + let mut h = Harness::new(); + let mut line = String::from("STEP"); + let phase = |line: &mut String, name: &str, ms: f64| { + line.push_str(&format!(" {name}_ms={ms:.1}")); + eprintln!("{name}: {ms:.1} ms"); + }; + let import = ms(|| drop(h.app.run("file.insert_step", json!({"path": path.to_string_lossy()})).unwrap())); + phase(&mut line, "import", import); + let world = ms(|| drop(h.app.session.world_state())); + phase(&mut line, "world", world); + let mesh = ms(|| h.app.session.world_state().warm_meshes(|| true)); + phase(&mut line, "mesh", mesh); + let st = h.app.session.world_state(); + let bodies: Vec = st.bodies.iter().map(|b| b.name.clone()).collect(); + let triangles: usize = st.bodies.iter().map(|b| b.mesh().triangles.len()).sum(); + let components = h.app.session.doc.components.len(); + let occurrences = h.app.session.doc.occurrences.len(); + drop(st); + line.push_str(&format!(" bodies={} triangles={triangles} components={components} occurrences={occurrences}", bodies.len())); + let first_frame = ms(|| h.frame()); + phase(&mut line, "first_frame", first_frame); + let mut idle: Vec = (0..5).map(|_| ms(|| h.frame())).collect(); + idle.sort_by(f64::total_cmp); + phase(&mut line, "idle_frame", idle[2]); + let cold = ms(|| drop(crate::viewport::build_scene(&h.app))); + phase(&mut line, "scene_cold", cold); + let unchanged = ms(|| drop(crate::viewport::build_scene(&h.app))); + phase(&mut line, "scene_unchanged", unchanged); + let Some(part) = bodies.first().cloned() else { + println!("{line}"); + return; + }; + let colour_command = ms(|| drop(h.app.run("appearance.assign", json!({"bodies": [&part], "color": "#336699"})).unwrap())); + phase(&mut line, "colour_command", colour_command); + let colour = ms(|| drop(crate::viewport::build_scene(&h.app))); + phase(&mut line, "colour_scene", colour); + let opacity_command = ms(|| drop(h.app.run("appearance.assign", json!({"bodies": [&part], "color": "#336699", "opacity": 0.5})).unwrap())); + phase(&mut line, "opacity_command", opacity_command); + let opacity = ms(|| drop(crate::viewport::build_scene(&h.app))); + phase(&mut line, "opacity_scene", opacity); + let theme_name = if crate::theme::is_dark() { "light" } else { "dark" }; + let _ = h.call("ui.prefs", json!({"theme": theme_name})); + let theme = ms(|| drop(crate::viewport::build_scene(&h.app))); + phase(&mut line, "theme_scene", theme); + let select = ms(|| drop(h.app.run("select.set", json!({"items": [{"type": "body", "name": &part}]})).unwrap())); + phase(&mut line, "select_command", select); + let selected_frame = ms(|| h.frame()); + phase(&mut line, "selected_frame", selected_frame); + let _ = h.app.run("select.clear", json!({})); + const SIZE: u32 = 1024; + if let Some(mut frames) = crate::gpu::OffscreenFrames::new(SIZE, true) { + h.app.viewport.gpu = frames.target(); + h.app.fit_view(); + let model: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(crate::viewport::build_scene(&h.app)))); + let highlight: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None)); + let gpu_cold = frames.frame(view_frame(&h.app, SIZE, (1, &model), (1, &highlight))); + phase(&mut line, "gpu_cold_frame", gpu_cold); + let mut still: Vec = (0..5).map(|_| frames.frame(view_frame(&h.app, SIZE, (1, &model), (1, &highlight)))).collect(); + still.sort_by(f64::total_cmp); + phase(&mut line, "gpu_still_frame", still[2]); + line.push_str(&format!(" gpu_triangles={}", frames.stats().triangles)); + let tenth = bodies.len().div_ceil(10); + let mut key = 1; + for (name, hovered) in [("hover_one", vec![part.clone()]), ("hover_tenth", bodies[..tenth].to_vec()), ("hover_all", bodies.clone())] { + let mut times = Vec::new(); + for _ in 0..5 { + for set in [Vec::new(), hovered.clone()] { + h.app.viewport.hover_bodies = set; + key += 1; + let built = std::time::Instant::now(); + *highlight.lock().unwrap() = Some(crate::viewport::build_highlight(&h.app)); + let build = built.elapsed().as_secs_f64() * 1000.0; + let frame = frames.frame(view_frame(&h.app, SIZE, (1, &model), (key, &highlight))); + if !h.app.viewport.hover_bodies.is_empty() { + times.push((build + frame, build)); + } + } + } + times.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (total, build) = times[times.len() / 2]; + phase(&mut line, name, total); + phase(&mut line, &format!("{name}_build"), build); + } + h.app.viewport.hover_bodies.clear(); + } + println!("{line}"); +} diff --git a/crates/ui-egui/src/scene_palette.rs b/crates/ui-egui/src/scene_palette.rs new file mode 100644 index 000000000..3db6a5e6c --- /dev/null +++ b/crates/ui-egui/src/scene_palette.rs @@ -0,0 +1,188 @@ +//! Stable palette slots for the model scene. +//! +//! Cached block bytes index a scene palette (`solidcraft_gpu::view::Palette`). A body's faces, +//! edges and placement keep their slots while the scene rebuilds, so an appearance or theme edit +//! changes only palette entries — never a block's vertex bytes. Slots are append-only for the +//! session and are reset when a different design replaces the one they belonged to. +//! +//! The model scene needs at most one stable slot per visible body face (plus a few per body), so +//! the arena is capped by [`MAX_PALETTE`]. Past the cap a face falls back to its body's slot: +//! editing such a face once rebuilds that body's block (the build still succeeds). + +use std::collections::HashMap; + +use crate::gpu::{MAX_PALETTE, PaletteIndex}; + +/// The stable slots of one body: its own colour, its face range, its edges and its instances. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct BodySlots { + /// The body's own colour: the fallback for faces past the allocated range. + pub body: PaletteIndex, + /// The first face slot, or [`u32::MAX`] when the arena is full (every face uses `body`). + pub faces: u32, + pub face_capacity: u32, + pub edge: PaletteIndex, + pub hidden_edge: PaletteIndex, + pub instance: PaletteIndex, +} + +impl BodySlots { + /// The slot of face `face`, or the body's slot when the face has none. + pub fn face(&self, face: usize) -> PaletteIndex { + if self.faces == u32::MAX || face >= self.face_capacity as usize { + return self.body; + } + PaletteIndex(self.faces.saturating_add(face as u32)) + } +} + +#[derive(Default)] +pub(crate) struct PaletteArena { + entries: Vec<[u8; 4]>, + bodies: HashMap, + /// Bumped when the arena is reset (a different design); cached blocks must rebuild then. + generation: u64, +} + +impl PaletteArena { + /// The stable entries, copied into the scene's palette. + pub fn entries(&self) -> Vec<[u8; 4]> { + self.entries.clone() + } + + pub fn generation(&self) -> u64 { + self.generation + } + + /// The slots of `name`, allocating them (and `face_count` face slots) the first time. + pub fn body(&mut self, name: &str, face_count: usize) -> BodySlots { + if let Some(slots) = self.bodies.get(name).copied() { + let grown = self.grow_faces(&slots, face_count); + // Written back only when it grew: most rebuilds find every body as it was. + if grown != slots + && let Some(kept) = self.bodies.get_mut(name) + { + *kept = grown; + } + return grown; + } + let body = self.push(); + let edge = self.push(); + let hidden_edge = self.push(); + let instance = self.push(); + let slots = BodySlots { body, faces: u32::MAX, face_capacity: 0, edge, hidden_edge, instance }; + let slots = self.grow_faces(&slots, face_count); + self.bodies.insert(name.to_string(), slots); + slots + } + + /// Extend a body's face range when its face count grew. The range is reused when it is at the + /// end of the arena; otherwise a new range is appended (the old one is left unused rather + /// than moving an index cached blocks may refer to). + fn grow_faces(&mut self, slots: &BodySlots, face_count: usize) -> BodySlots { + let want = u32::try_from(face_count).unwrap_or(u32::MAX); + if slots.faces != u32::MAX && slots.face_capacity >= want { + return *slots; + } + let room = MAX_PALETTE.saturating_sub(self.entries.len()); + let need = usize::try_from(want).unwrap_or(usize::MAX).saturating_sub(slots.face_capacity as usize); + let at_end = slots.faces != u32::MAX && slots.faces as usize + slots.face_capacity as usize == self.entries.len(); + if at_end && need <= room { + self.entries.resize(self.entries.len() + need, [0; 4]); + return BodySlots { face_capacity: want, ..*slots }; + } + if want as usize <= room { + let base = u32::try_from(self.entries.len()).unwrap_or(u32::MAX); + self.entries.resize(self.entries.len() + want as usize, [0; 4]); + return BodySlots { faces: base, face_capacity: want, ..*slots }; + } + // Out of room: every face falls back to the body's own slot. + BodySlots { faces: u32::MAX, face_capacity: 0, ..*slots } + } + + /// Append a zero entry; [`PaletteIndex(0)`] when the arena is full (never a panic). + fn push(&mut self) -> PaletteIndex { + if self.entries.len() >= MAX_PALETTE { + return PaletteIndex(0); + } + let i = u32::try_from(self.entries.len()).unwrap_or(0); + self.entries.push([0; 4]); + PaletteIndex(i) + } + + /// The slots of `name`, if it has any (nothing is allocated). + pub fn slots(&self, name: &str) -> Option { + self.bodies.get(name).copied() + } + + /// The colour at `slot`, if it is allocated. + pub fn get(&self, slot: PaletteIndex) -> Option<[u8; 4]> { + self.entries.get(slot.0 as usize).copied() + } + + /// Set a slot's colour; out-of-range slots are ignored. + pub fn set(&mut self, slot: PaletteIndex, rgba: [u8; 4]) { + if let Some(entry) = self.entries.get_mut(slot.0 as usize) { + *entry = rgba; + } + } + + /// Drop every body when the scene belongs to a different design (no body name survives). + /// A design that removed every body and then adds one keeps its slots (the empty set does + /// not reset the arena). + pub fn sync<'a>(&mut self, names: impl IntoIterator) { + if self.bodies.is_empty() { + return; + } + let mut names = names.into_iter().peekable(); + if names.peek().is_none() { + return; + } + if !names.any(|n| self.bodies.contains_key(n)) { + self.entries.clear(); + self.bodies.clear(); + self.generation = self.generation.wrapping_add(1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slots_survive_rebuilds_and_faces_fall_back_at_the_cap() { + let mut arena = PaletteArena::default(); + let first = arena.body("A", 2); + let again = arena.body("A", 2); + assert_eq!(first, again); + assert_ne!(first.face(0), first.face(1)); + assert_eq!(first.face(2), first.body); + arena.set(first.face(0), [1, 2, 3, 4]); + assert_eq!(arena.entries()[first.face(0).0 as usize], [1, 2, 3, 4]); + // A grown face count reuses the range at the end of the arena. + let grown = arena.body("A", 4); + assert_eq!(grown.faces, first.faces); + assert_ne!(grown.face(3), grown.body); + // A new design with no shared names resets the slots. + let generation = arena.generation(); + arena.sync(["B"]); + assert_eq!(arena.generation(), generation.wrapping_add(1)); + assert!(arena.entries().is_empty()); + // An empty scene does not reset. + let before = arena.generation(); + arena.sync([]); + assert_eq!(arena.generation(), before); + } + + #[test] + fn the_cap_falls_back_to_the_body_slot_without_panicking() { + // The arena cannot allocate past MAX_PALETTE; simulate a full one by filling entries. + let mut arena = PaletteArena { entries: vec![[0; 4]; MAX_PALETTE], ..Default::default() }; + let slots = arena.body("Big", 10); + assert_eq!(slots.faces, u32::MAX); + assert_eq!(slots.face(3), slots.body); + // Every push after the cap is index 0, never an out-of-range write. + assert_eq!(arena.push(), PaletteIndex(0)); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a039fa188..b176cc1dc 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -88,7 +88,12 @@ pub struct ViewportState { mesh_bounds: std::sync::Mutex, /// Each shown body mesh's section index for the cut's normal (the mesh held, so its address /// stays its own): a Section Analysis dragged along its normal cuts through it. - section_index: std::sync::Mutex, std::sync::Arc)>>, + section_index: std::sync::Mutex< + std::collections::HashMap< + (usize, [u64; 3]), + (std::sync::Arc, std::sync::Arc), + >, + >, /// Each body mesh's picking index (made the first time a pick reaches the body), kept while /// the mesh is part of the world state. pub(crate) pick_index: crate::pick_index::PickIndexes, @@ -122,8 +127,13 @@ pub struct ViewportState { /// Browser/timeline body feedback, independent of the camera and reference widget scale. hover_block: std::sync::Mutex>, /// Each shown body the model builds on the CPU: the block of the model scene that holds its - /// triangles, and the body's vertex range in it (for whole-body highlights). - body_tris: std::sync::Mutex)>>, + /// triangles, and the body's index and vertex ranges in it (for whole-body highlights). + body_tris: std::sync::Mutex>, + /// The stable palette slots of the model scene (body faces, edges, placements). + pub(crate) palette: std::sync::Mutex, + /// Each body's resolved look, kept while its geometry and the design's appearance state are + /// the same: a theme or visibility rebuild does not resolve every face again. + appearance: std::sync::Mutex, pub nav: Option, /// The preset's navigation for the left-button drag under way (Alias: Shift+Alt), taken /// when the button went down, so the drag neither selects nor moves sketch geometry. @@ -406,10 +416,12 @@ fn in_view(proj: &Proj, b: &solidcraft_engine::geom::Aabb3) -> bool { fn scene_key(app: &SolveApp) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); - app.session.revision.hash(&mut h); + // Not the session revision: selection and view-only commands bump it without changing the + // model. The document identity catches edits, including appearance-only ones (whose world + // state may be the same Arc). + (std::sync::Arc::as_ptr(&app.session.doc) as usize).hash(&mut h); app.session.colored_components.hash(&mut h); (std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h); - app.ui.show_grid.hash(&mut h); app.ui.visual_style.hash(&mut h); app.ui.ground_shadow.hash(&mut h); solidcraft_engine::doc::display_quality::current().hash(&mut h); @@ -430,12 +442,21 @@ fn scene_key(app: &SolveApp) -> u64 { app.preview.effective_replaced().hash(&mut h); app.preview.rolled_back.hash(&mut h); app.preferences.cosmetic_threads.hash(&mut h); - app.tree.redefine.hash(&mut h); crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); // Two themes may share a light/dark base while drawing different geometry colours. crate::theme_files::color_key(&Tokens::get()).hash(&mut h); app.session.active_sketch.hash(&mut h); + // A reset palette arena (another design) invalidates every cached block's indices. + app.viewport.palette.lock().map_or(0, |a| a.generation()).hash(&mut h); + // Continuity seams are model-scene lines but are not part of the document or world state. + for seam in &app.session.continuity { + seam.body.hash(&mut h); + seam.edge.hash(&mut h); + seam.points.len().hash(&mut h); + format!("{:?}", seam.verdict).hash(&mut h); + seam.points.first().map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]).hash(&mut h); + } h.finish() } @@ -444,6 +465,7 @@ fn sketch_scene_key(app: &SolveApp, proj: &Proj) -> u64 { scene_key(app).hash(&mut h); // The grid this scene draws follows the view when the preference says so (#1470): turning it // on or off redraws even while the camera holds still. + app.ui.show_grid.hash(&mut h); app.preferences.grid_follows_view.hash(&mut h); // Finished sketches are drawn over the bodies when the preference says so. app.preferences.reference_geometry_through_bodies.hash(&mut h); @@ -565,10 +587,7 @@ fn shown_mesh( // Refined: faces drawn from the refined plan on the GPU or built from its mesh here. return mesh; } - let doc = &app.session.doc; - let opaque = - || !body_faded(app, b, active_bodies) && doc.model_body_opacity(b) >= 0.999 && doc.face_colors(b).iter().all(|(_, l)| l.opacity >= 0.999); - (app.viewport.gpu.is_some_and(|g| g.tess) && opaque()) + (app.viewport.gpu.is_some_and(|g| g.tess) && model_plan_class(app, b, active_bodies).is_some()) .then(|| drawn_plan(app, b, true)) .flatten() // A large body's plan mesh is made on a worker: until then its faces are lit on the @@ -682,14 +701,154 @@ fn update_refinement(app: &mut SolveApp, ctx: &egui::Context, proj: &Proj) { } } +/// A body's look as the scene resolves it: the component/body colours, the body opacity and the +/// faces with looks of their own. +#[derive(Clone)] +struct ResolvedAppearance { + component: Option, + body: Option, + opacity: f64, + face_looks: std::collections::HashMap, +} + +/// [`ViewportState::appearance`]: resolved bodies by name, with their geometry key and the +/// appearance state they were resolved from. +#[derive(Default)] +struct AppearanceCache { + /// The document the face index below was built from, and whether components coloured bodies. + doc: Option<(usize, bool)>, + /// A hash of each body's face appearances, so a body's look is keyed without scanning them. + faces: std::collections::HashMap, + /// Each body's appearance key, reused while the document and its geometry are unchanged. + keys: std::collections::HashMap, + bodies: std::collections::HashMap)>, + /// Bodies actually resolved (the test asserts an unrelated edit resolves only its body). + #[cfg(test)] + resolved: u32, +} + +/// A hash per body of the face appearances that name it, in design order (a later assignment +/// wins). Rebuilt when the document changes. +fn face_appearance_hashes(doc: &solidcraft_engine::doc::Document) -> std::collections::HashMap { + use std::hash::Hasher as _; + let mut out: std::collections::HashMap = std::collections::HashMap::new(); + for f in &doc.appearances.faces { + let mut h = std::collections::hash_map::DefaultHasher::new(); + out.get(&f.body).hash(&mut h); + serde_json::to_string(f).ok().hash(&mut h); + out.insert(f.body.clone(), h.finish()); + } + out +} + +fn hash_look(look: Option<&solidcraft_engine::doc::appearance::Look>, h: &mut impl std::hash::Hasher) { + use std::hash::Hash as _; + match look { + Some(l) => { + 1u8.hash(h); + l.name.hash(h); + l.color.hash(h); + l.opacity.to_bits().hash(h); + match &l.pbr { + Some(p) => { + 1u8.hash(h); + p.metallic().to_bits().hash(h); + p.roughness().to_bits().hash(h); + p.dielectric_ior().to_bits().hash(h); + } + None => 0u8.hash(h), + } + } + None => 0u8.hash(h), + } +} + +/// What a body's resolved look depends on: its geometry (imported paint), the body/component +/// looks, its material, its face appearances, and component colouring. +fn body_appearance_key( + doc: &solidcraft_engine::doc::Document, + b: &solidcraft_engine::doc::ModelBody, + faces: &std::collections::HashMap, + colored: bool, +) -> u64 { + use std::hash::{Hash as _, Hasher as _}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + b.geometry_key().unwrap_or(0).hash(&mut h); + let name = b.definition_name(); + hash_look(doc.appearances.bodies.get(name), &mut h); + hash_look(doc.appearances.components.get(&b.component), &mut h); + doc.materials.get(name).hash(&mut h); + faces.get(name).copied().unwrap_or(0).hash(&mut h); + colored.hash(&mut h); + if colored { + doc.component_identification_color(b.component).hash(&mut h); + } + h.finish() +} + +fn resolve_appearance(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody) -> ResolvedAppearance { + let s = &app.session; + ResolvedAppearance { + component: solidcraft_engine::view::component_color(s, b.component).map(|[r, g, b]| Color32::from_rgb(r, g, b)), + body: body_color(&s.doc, b), + opacity: s.doc.model_body_opacity(b), + face_looks: if s.colored_components.is_none() { s.doc.face_colors(b).into_iter().collect() } else { Default::default() }, + } +} + +/// How a body whose faces all share one class may be drawn from its plan: opaque on any GPU +/// path; faded or see-through only where the renderer blends them order-independently (the +/// sorted fallback needs the triangles on the CPU). `None`: faces of different classes, which +/// are built on the CPU. `faces` are the classes [`build_scene`] gives the body's faces. +fn plan_class(app: &SolveApp, faces: &[crate::gpu::TriClass]) -> Option { + let first = faces.first().copied().unwrap_or(crate::gpu::TriClass::Opaque); + if faces.iter().any(|c| *c != first) { + return None; + } + (first == crate::gpu::TriClass::Opaque || app.viewport.gpu.is_some_and(|g| g.oit)).then_some(first) +} + +/// The classes [`build_scene`] gives `b`'s faces: faded outside the active component, else +/// see-through below full opacity (the body's, or a face's own look). +fn face_classes(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option>) -> Vec { + if body_faded(app, b, active_bodies) { + return vec![crate::gpu::TriClass::Faded; b.body.face_count()]; + } + let resolved = resolve_appearance(app, b); + (0..b.body.face_count()) + .map(|f| { + let opacity = resolved.face_looks.get(&f).map_or(resolved.opacity, |l| l.opacity); + if opacity < 0.999 { crate::gpu::TriClass::Glass } else { crate::gpu::TriClass::Opaque } + }) + .collect() +} + +/// Whether the model scene draws `b` from its plan's GPU-evaluated triangles (and with which +/// class), as [`build_scene`] decides: a live preview stands in for none. +fn model_plan_class(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option>) -> Option { + if app.preview.effective_replaced().contains(&b.name) { + return None; + } + plan_class(app, &face_classes(app, b, active_bodies)) +} + /// A model scene block kept by the viewport: its bytes and the meshes they were built from /// (held, so no other mesh can take their addresses while the block is kept). pub(crate) struct CachedBlock { bytes: std::sync::Arc, meshes: Vec>, - /// Each body's triangles in `bytes.tris`, by body name: whole-body highlights draw those - /// vertices again instead of building a copy of them on the CPU. - ranges: Vec<(String, std::ops::Range)>, + /// Each body's share of the block: its vertices, its opaque runs of them (whole-body + /// highlights draw those again), and the face classes the runs were built from. + ranges: Vec, +} + +/// One body's share of a block. +struct BodyRange { + name: String, + /// Its vertices: three per triangle, in mesh order (none when its faces are drawn elsewhere). + vertices: std::ops::Range, + opaque: Vec>, + face_classes: Vec, } /// [`ViewportState::mesh_bounds`]: each box by the shared mesh it was measured on (held, so its @@ -736,7 +895,8 @@ fn taken_shared_tris(mesh: &std::sync::Arc) -> Op Some(warmed.remove(at).1) } -/// One body as the model scene draws it. +/// One body as the model scene draws it. Its geometry lives in a block's canonical vertex +/// buffer; its colours are palette indices, so appearance edits never touch vertex bytes. struct BodyDraw { /// The body's name in the world state, for the highlight's lookup of its triangles. name: String, @@ -744,54 +904,51 @@ struct BodyDraw { mesh: std::sync::Arc, /// The move from `mesh` to where the body stands, for a body drawn as an instance. place: Option, - col: [u8; 4], + /// The palette index of each face's colour, and the body's fallback. + face_colors: Vec, + body_color: crate::gpu::PaletteIndex, + /// The render class of each face (opaque, glass or faded). + face_classes: Vec, faded: bool, - opacity: f64, - face_looks: std::collections::HashMap, /// Its faces are drawn elsewhere, from its plan on the GPU or as an instance of shared /// triangles (only its edges are built here). on_gpu: bool, + /// The body's first face slot: stable while the body exists, so cached block indices are. + slot_base: u32, + edge: crate::gpu::PaletteIndex, + hidden_edge: crate::gpu::PaletteIndex, } impl BodyDraw { - /// Everything [`BodyDraw::build`] reads. - fn key(&self, shaded: bool, edges: bool, hidden_edges: bool, edge_col: [u8; 4], hidden_col: [u8; 4]) -> u64 { + /// Everything [`BodyDraw::build`] reads. Colours, opacity and classes are deliberately left + /// out: changing them must not change the block's vertices. + fn key(&self, shaded: bool, edges: bool, hidden_edges: bool) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); (std::sync::Arc::as_ptr(&self.mesh) as usize).hash(&mut h); self.place.iter().flatten().flatten().for_each(|v| v.to_bits().hash(&mut h)); - (self.col, self.faded, self.opacity.to_bits(), self.on_gpu, shaded, edges, hidden_edges, edge_col, hidden_col).hash(&mut h); - let mut looks: Vec<_> = self.face_looks.iter().map(|(f, l)| (*f, l.color, l.opacity.to_bits())).collect(); - looks.sort_unstable(); - looks.hash(&mut h); + (self.faded, self.on_gpu, shaded, edges, hidden_edges, self.slot_base, self.edge.0, self.hidden_edge.0).hash(&mut h); h.finish() } - fn build(&self, sc: &mut crate::gpu::BlockBytes, shaded: bool, edges: bool, hidden_edges: bool, edge_col: [u8; 4], hidden_col: [u8; 4]) { + fn build(&self, out: &mut crate::gpu::BlockBuilder, shaded: bool, edges: bool, hidden_edges: bool) { let m = &self.mesh; - let mut out = GpuScene::default(); - for (ti, t) in m.triangles.iter().enumerate().filter(|_| shaded && !self.on_gpu) { - let (mut col, a) = match m.tri_face.get(ti).and_then(|f| self.face_looks.get(&(*f as usize))) { - Some(l) => { - let c = Color32::from_rgb(l.color[0], l.color[1], l.color[2]); - (if self.faded { c4(c.gamma_multiply(0.35)) } else { c4(c) }, l.opacity) - } - None => (self.col, self.opacity), - }; - let glass = !self.faded && a < 0.999; - if glass { - col[3] = (a.clamp(0.05, 1.0) * 255.0).round() as u8; + let color = |ti: usize| m.tri_face.get(ti).and_then(|f| self.face_colors.get(*f as usize)).copied().unwrap_or(self.body_color); + let class = |ti: usize| { + if self.faded { + return crate::gpu::TriClass::Faded; } - for k in t { - let i = *k as usize; - if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { - if self.faded { - out.trans_tri(p.to_f32(), n.to_f32(), col); - } else if glass { - out.glass_tri(p.to_f32(), n.to_f32(), col); - } else { - out.tri(p.to_f32(), n.to_f32(), col); - } - } + m.tri_face.get(ti).and_then(|f| self.face_classes.get(*f as usize)).copied().unwrap_or(crate::gpu::TriClass::Opaque) + }; + if shaded && !self.on_gpu { + let corner = |k: u32| { + let i = k as usize; + (m.positions.get(i).copied().unwrap_or(Vec3::ZERO).to_f32(), m.normals.get(i).copied().unwrap_or(Vec3::ZERO).to_f32()) + }; + // Exactly three vertices per triangle, in mesh order: a class change regenerates the + // runs without touching the vertices (see `reindex_block`). + for (ti, t) in m.triangles.iter().enumerate() { + let [a, b, c] = t.map(corner); + out.triangle([a.0, b.0, c.0], [a.1, b.1, c.1], color(ti), class(ti)); } } let at = |p: Vec3| self.place.as_ref().map_or(p, |m| solidcraft_engine::doc::apply_point(m, p)).to_f32(); @@ -801,17 +958,12 @@ impl BodyDraw { } for w in e.windows(2) { let (a, b) = (at(w[0]), at(w[1])); - out.line(a, b, edge_col, 1.3, false); + out.line(a, b, self.edge, 1.3); if hidden_edges { - out.hidden_line(a, b, hidden_col, 1.0); + out.hidden_line(a, b, self.hidden_edge, 1.0); } } } - sc.tris.extend_from_slice(&out.tris); - sc.trans.extend_from_slice(&out.trans); - sc.glass.extend_from_slice(&out.glass); - sc.lines.extend_from_slice(&out.lines); - sc.hidden.extend_from_slice(&out.hidden); } } @@ -823,38 +975,117 @@ fn push_block( made: &mut std::collections::HashMap, key: u64, draws: Vec, - build: impl Fn(&BodyDraw, &mut crate::gpu::BlockBytes), + shaded: bool, + build: impl Fn(&BodyDraw, &mut crate::gpu::BlockBuilder), ) { let same = |c: &CachedBlock| c.meshes.len() == draws.len() && c.meshes.iter().zip(&draws).all(|(m, d)| std::sync::Arc::ptr_eq(m, &d.mesh)); + let classes_same = |c: &CachedBlock| c.ranges.len() == draws.len() && c.ranges.iter().zip(&draws).all(|(r, d)| r.face_classes == d.face_classes); let mut block = match kept.remove(&key).or_else(|| made.remove(&key)).filter(same) { - Some(c) => c, - None => { - let mut bytes = crate::gpu::BlockBytes::default(); - let mut ranges = Vec::with_capacity(draws.len()); - for d in &draws { - let start = u32::try_from(bytes.tris.len() / crate::gpu::TRI_SIZE).unwrap_or(u32::MAX); - build(d, &mut bytes); - let end = u32::try_from(bytes.tris.len() / crate::gpu::TRI_SIZE).unwrap_or(u32::MAX); - ranges.push((d.name.clone(), start..end)); - } - CachedBlock { bytes: std::sync::Arc::new(bytes), meshes: draws.iter().map(|d| d.mesh.clone()).collect(), ranges } - } + Some(c) if classes_same(&c) => c, + Some(c) => reindex_block(c, &draws), + None => build_block(&draws, shaded, &build), }; // The body names are not part of a block's key (its bytes are the same whatever a body is // called): keep the ranges' names those of the bodies drawn from them this time. if block.ranges.len() == draws.len() { for (range, d) in block.ranges.iter_mut().zip(&draws) { - if range.0 != d.name { - range.0.clone_from(&d.name); + if range.name != d.name { + range.name.clone_from(&d.name); } } } - // See-through triangles are sorted with the rest of the glass, every view. - sc.glass.extend_from_slice(&block.bytes.glass); sc.blocks.push(crate::gpu::SceneBlock { key, bytes: block.bytes.clone() }); made.insert(key, block); } +/// Write a body's colour into the stable arena and into the scene palette being built from it. +fn set_palette_color( + arena: &mut crate::scene_palette::PaletteArena, + palette: &mut std::sync::Arc, + slot: crate::gpu::PaletteIndex, + rgba: [u8; 4], +) { + // The scene palette starts as a copy of the arena's entries: an unchanged slot is already + // right, and most rebuilds (visibility, LOD, section) change none. + if arena.get(slot) == Some(rgba) { + return; + } + arena.set(slot, rgba); + std::sync::Arc::make_mut(palette).set(slot, rgba); +} + +fn build_block(draws: &[BodyDraw], shaded: bool, build: &impl Fn(&BodyDraw, &mut crate::gpu::BlockBuilder)) -> CachedBlock { + let mut builder = crate::gpu::BlockBuilder::default(); + if shaded { + builder.reserve_triangles(draws.iter().filter(|d| !d.on_gpu).map(|d| d.mesh.triangles.len()).sum()); + } + let at = |i: usize| u32::try_from(i).unwrap_or(u32::MAX); + let mut spans = Vec::with_capacity(draws.len()); + for d in draws { + let v0 = builder.vertices_len(); + build(d, &mut builder); + spans.push(at(v0)..at(builder.vertices_len())); + } + let ranges = draws + .iter() + .zip(spans) + .map(|(d, vertices)| BodyRange { + name: d.name.clone(), + opaque: builder.runs_within(crate::gpu::TriClass::Opaque, vertices.clone()), + vertices, + face_classes: d.face_classes.clone(), + }) + .collect(); + CachedBlock { bytes: builder.freeze(), meshes: draws.iter().map(|d| d.mesh.clone()).collect(), ranges } +} + +/// Keep a block's vertex, line and hidden artifacts and regenerate only the class runs (an +/// opacity class change). A body's vertices are three per triangle in mesh order, so this reads +/// each triangle's face, not the mesh's geometry. +fn reindex_block(block: CachedBlock, draws: &[BodyDraw]) -> CachedBlock { + use crate::gpu::TriClass; + let mut runs: [Vec>; 3] = Default::default(); + for (range, d) in block.ranges.iter().zip(draws) { + // The triangles this body wrote (none when its faces are drawn from a plan or as an + // instance), never more than its mesh has. + let written = ((range.vertices.end.saturating_sub(range.vertices.start)) / 3) as usize; + for j in 0..written.min(d.mesh.triangles.len()) { + let class = d.mesh.tri_face.get(j).and_then(|f| d.face_classes.get(*f as usize)).copied().unwrap_or(TriClass::Opaque); + let slot = match class { + TriClass::Opaque => 0, + TriClass::Glass => 1, + TriClass::Faded => 2, + }; + let at = range.vertices.start.saturating_add(u32::try_from(j * 3).unwrap_or(u32::MAX)); + if let Some(list) = runs.get_mut(slot) { + crate::gpu::extend_runs(list, at); + } + } + } + let [opaque, glass, faded] = runs; + let ranges = block + .ranges + .iter() + .zip(draws) + .map(|(range, d)| BodyRange { + name: d.name.clone(), + vertices: range.vertices.clone(), + opaque: crate::gpu::runs_within(&opaque, range.vertices.clone()), + face_classes: d.face_classes.clone(), + }) + .collect(); + let old = block.bytes; + let bytes = std::sync::Arc::new(crate::gpu::BlockBytes { + vertices: old.vertices.clone(), + opaque: std::sync::Arc::new(opaque), + glass: std::sync::Arc::new(glass), + faded: std::sync::Arc::new(faded), + lines: old.lines.clone(), + hidden: old.hidden.clone(), + }); + CachedBlock { bytes, meshes: draws.iter().map(|d| d.mesh.clone()).collect(), ranges } +} + /// The model scene's instanced meshes: the shared triangles drawn more than once among the shown /// bodies (or large: [`INSTANCE_ALONE`]), and each body placed from them. struct Instances { @@ -862,6 +1093,8 @@ struct Instances { candidates: std::collections::HashMap, solidcraft_engine::doc::Mat)>, /// The meshes drawn as instances, in the order their first placement came, by address. meshes: Vec<(std::sync::Arc, crate::gpu::InstancedMesh)>, + /// Where a mesh's look already is in `meshes`, so placing a body is a lookup, not a scan. + by_mesh: std::collections::HashMap<(usize, crate::gpu::InstanceLook), usize>, kept: InstancedTris, lods: crate::mesh_lod::MeshLods, } @@ -883,7 +1116,7 @@ impl Instances { .filter(|(_, (m, _))| m.triangles.len() >= INSTANCE_ALONE || uses.get(&(std::sync::Arc::as_ptr(m) as usize)).is_some_and(|n| *n > 1)) .collect(); } - Instances { candidates, meshes: Vec::new(), kept, lods: app.viewport.mesh_lods.clone() } + Instances { candidates, meshes: Vec::new(), by_mesh: std::collections::HashMap::new(), kept, lods: app.viewport.mesh_lods.clone() } } /// Draw `b` as an instance when it is one, in colour `col` (its alpha for a see-through @@ -891,13 +1124,13 @@ impl Instances { fn place( &mut self, b: &solidcraft_engine::doc::ModelBody, - col: [u8; 4], + col: crate::gpu::PaletteIndex, look: crate::gpu::InstanceLook, ) -> Option<(std::sync::Arc, solidcraft_engine::doc::Mat)> { let (mesh, m) = self.candidates.get(&b.name)?.clone(); let rows = [0, 1, 2].map(|r| [m[0][r] as f32, m[1][r] as f32, m[2][r] as f32, m[3][r] as f32]); let key = std::sync::Arc::as_ptr(&mesh) as usize; - let at = match self.meshes.iter().position(|(k, i)| std::sync::Arc::ptr_eq(k, &mesh) && i.look == look) { + let at = match self.by_mesh.get(&(key, look)).copied() { Some(at) => at, None => { // The same triangles (and levels) for each look of a mesh. @@ -914,6 +1147,7 @@ impl Instances { ), }; self.meshes.push((mesh.clone(), crate::gpu::InstancedMesh { key: key as u64, tris, instances: Vec::new(), look, levels })); + self.by_mesh.insert((key, look), self.meshes.len() - 1); self.meshes.len() - 1 } }; @@ -950,7 +1184,6 @@ fn shared_mesh( pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { let tk = Tokens::get(); - let mut sc = GpuScene::default(); let s = &app.session; // Bodies where their occurrences place them. let st = crate::open_meshing::shown_world(app); @@ -964,53 +1197,107 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { // Shaded with hidden edges: edges behind the model show faintly. let hidden_edges = app.ui.visual_style == 3; let hidden_col = c4(tk.text.gamma_multiply(0.35)); + let shown: Vec<&solidcraft_engine::doc::ModelBody> = + st.bodies.iter().filter(|b| app.session.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name)).collect(); + let mut arena = app.viewport.palette.lock().unwrap_or_else(|e| e.into_inner()); + let shown_names: Vec<&str> = shown.iter().map(|b| b.name.as_str()).collect(); + arena.sync(shown_names.iter().copied()); + // Allocate every body's slots before the scene's palette is copied, so the stable prefix + // covers them; the colours themselves are written in the loop below, into both the arena + // and the scene's palette. + let slots: Vec<_> = shown.iter().map(|b| arena.body(&b.name, b.body.face_count())).collect(); + let mut sc = GpuScene::with_palette(crate::gpu::Palette::with_stable(arena.entries())); + // Resolve looks once per body and appearance state: a theme, visibility or LOD rebuild does + // not scan the whole design's face appearances again. + let mut appearance = app.viewport.appearance.lock().unwrap_or_else(|e| e.into_inner()); + let doc = std::sync::Arc::as_ptr(&s.doc) as usize; + let colored = s.colored_components.is_some(); + if appearance.doc != Some((doc, colored)) { + appearance.doc = Some((doc, colored)); + appearance.faces = face_appearance_hashes(&s.doc); + // A design or colouring edit can key any body differently; the resolved looks whose + // key comes back unchanged are still reused. + appearance.keys.clear(); + } // The blocks the last scene built, reused when their bodies come back as they were. let mut kept = app.viewport.blocks.lock().map(|mut b| std::mem::take(&mut *b)).unwrap_or_default(); let mut made: std::collections::HashMap = std::collections::HashMap::new(); let mut run: Vec = Vec::new(); let mut run_key = std::collections::hash_map::DefaultHasher::new(); - let shown: Vec<&solidcraft_engine::doc::ModelBody> = - st.bodies.iter().filter(|b| app.session.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name)).collect(); // Bodies drawn from the same triangles more than once (a part placed by many occurrences) // are drawn as instances of them: one copy of the triangles on the GPU, and none moved on // the CPU. let mut instances = Instances::new(app, &shown, shaded); let mut thread_budget = solidcraft_engine::cosmetic_threads::Budget::default(); - for b in shown { + for (b, slots) in shown.into_iter().zip(slots) { let faded = body_faded(app, b, &active_bodies); + let identity = match appearance.keys.get(&b.name).copied() { + Some(key) => key, + None => { + let key = body_appearance_key(&s.doc, b, &appearance.faces, colored); + appearance.keys.insert(b.name.clone(), key); + key + } + }; + let resolved = match appearance.bodies.get(&b.name) { + Some((key, resolved)) if *key == identity => resolved.clone(), + _ => { + let resolved = std::sync::Arc::new(resolve_appearance(app, b)); + appearance.bodies.insert(b.name.clone(), (identity, resolved.clone())); + #[cfg(test)] + { + appearance.resolved = appearance.resolved.saturating_add(1); + } + resolved + } + }; + set_palette_color(&mut arena, &mut sc.palette, slots.edge, edge_col); + set_palette_color(&mut arena, &mut sc.palette, slots.hidden_edge, hidden_col); if app.preferences.cosmetic_threads && thread_budget.available() && shaded && !faded && thread_budget.has_thread(&b.name, &st.threads) - && s.doc.model_body_opacity(b) >= 0.999 - && s.doc.face_colors(b).iter().all(|(_, l)| l.opacity >= 0.999) + && resolved.opacity >= 0.999 + && resolved.face_looks.values().all(|l| l.opacity >= 0.999) { let mesh = shown_mesh(app, b, &active_bodies); for (a, c) in solidcraft_engine::cosmetic_threads::segments_with_budget(b, &mesh, &st.threads, &mut thread_budget) { - sc.line(a.to_f32(), c.to_f32(), c4(tk.body_edge), 0.85, false); + sc.line(a.to_f32(), c.to_f32(), slots.edge, 0.85, false); } } - let base = solidcraft_engine::view::component_color(s, b.component) - .map(|[r, g, b]| Color32::from_rgb(r, g, b)) - .or_else(|| body_color(&s.doc, b)) - .unwrap_or(tk.body); + let base = resolved.component.or(resolved.body).unwrap_or(tk.body); let col = if faded { c4(base.gamma_multiply(0.35)) } else { c4(base) }; + set_palette_color(&mut arena, &mut sc.palette, slots.body, col); // Appearances: the body's opacity, and faces with looks of their own. - let opacity = s.doc.model_body_opacity(b); - let face_looks: std::collections::HashMap = - if shaded && s.colored_components.is_none() { s.doc.face_colors(b).into_iter().collect() } else { Default::default() }; - let opaque = !faded && opacity >= 0.999 && face_looks.values().all(|l| l.opacity >= 0.999); - let planned = drawn_plan(app, b, opaque); + let opacity = resolved.opacity; + let face_looks = &resolved.face_looks; + let faces = b.body.face_count(); + let mut face_colors = Vec::with_capacity(faces); + let mut face_classes = Vec::with_capacity(faces); + for f in 0..faces { + let look = face_looks.get(&f); + let color = look.map_or(base, |l| Color32::from_rgb(l.color[0], l.color[1], l.color[2])); + let opacity = look.map_or(opacity, |l| l.opacity); + let (rgba, class) = if faded { + (c4(color.gamma_multiply(0.35)), crate::gpu::TriClass::Faded) + } else if opacity < 0.999 { + let mut rgba = c4(color); + rgba[3] = (opacity.clamp(0.05, 1.0) * 255.0).round() as u8; + (rgba, crate::gpu::TriClass::Glass) + } else { + (c4(color), crate::gpu::TriClass::Opaque) + }; + let slot = slots.face(f); + set_palette_color(&mut arena, &mut sc.palette, slot, rgba); + face_colors.push(slot); + face_classes.push(class); + } + let class = plan_class(app, &face_classes); + let planned = class.and_then(|class| drawn_plan(app, b, true).map(|plan| (plan, class))); let on_gpu = planned.is_some(); - if let Some(plan) = planned { - let face_colors = (0..b.body.face_count()) - .map(|f| match face_looks.get(&f) { - Some(l) => c4(Color32::from_rgb(l.color[0], l.color[1], l.color[2])), - None => col, - }) - .collect(); - sc.planned.push(crate::gpu::PlannedBody { plan, face_colors }); + if let Some((plan, class)) = planned { + sc.planned.push(crate::gpu::PlannedBody { plan, face_colors: face_colors.clone(), class }); } // Opaque, faded and see-through bodies alike, in one colour (faces of their own colour // are built as before). @@ -1026,13 +1313,38 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { crate::gpu::InstanceLook::Glass => (opacity.clamp(0.05, 1.0) * 255.0).round() as u8, crate::gpu::InstanceLook::Opaque => 255, }; - let instanced = (!on_gpu && face_looks.is_empty()).then(|| instances.place(b, [col[0], col[1], col[2], alpha], look)).flatten(); + set_palette_color(&mut arena, &mut sc.palette, slots.instance, [col[0], col[1], col[2], alpha]); + let instanced = (!on_gpu && face_looks.is_empty()).then(|| instances.place(b, slots.instance, look)).flatten(); let name = b.name.clone(); let body = match instanced { - Some((mesh, place)) => BodyDraw { name, mesh, place: Some(place), col, faded, opacity, face_looks, on_gpu: true }, - None => BodyDraw { name, mesh: drawn_mesh(app, b), place: None, col, faded, opacity, face_looks, on_gpu }, + Some((mesh, place)) => BodyDraw { + name, + mesh, + place: Some(place), + face_colors, + body_color: slots.body, + face_classes, + faded, + on_gpu: true, + slot_base: slots.faces, + edge: slots.edge, + hidden_edge: slots.hidden_edge, + }, + None => BodyDraw { + name, + mesh: drawn_mesh(app, b), + place: None, + face_colors, + body_color: slots.body, + face_classes, + faded, + on_gpu, + slot_base: slots.faces, + edge: slots.edge, + hidden_edge: slots.hidden_edge, + }, }; - let key = body.key(shaded, edges, hidden_edges, edge_col, hidden_col); + let key = body.key(shaded, edges, hidden_edges); key.hash(&mut run_key); run.push(body); // Blocks end where a body's own key says, so a body added or removed changes only its @@ -1040,25 +1352,32 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { if key.is_multiple_of(16) || run.len() >= 64 { let draws = std::mem::take(&mut run); let block_key = std::mem::replace(&mut run_key, std::collections::hash_map::DefaultHasher::new()).finish(); - push_block(&mut sc, &mut kept, &mut made, block_key, draws, |d, out| d.build(out, shaded, edges, hidden_edges, edge_col, hidden_col)); + push_block(&mut sc, &mut kept, &mut made, block_key, draws, shaded, |d, out| d.build(out, shaded, edges, hidden_edges)); } } if !run.is_empty() { - push_block(&mut sc, &mut kept, &mut made, run_key.finish(), run, |d, out| d.build(out, shaded, edges, hidden_edges, edge_col, hidden_col)); + push_block(&mut sc, &mut kept, &mut made, run_key.finish(), run, shaded, |d, out| d.build(out, shaded, edges, hidden_edges)); } // Where each CPU-built body's triangles are in the model's blocks, for whole-body // highlights (see `highlight_block_tris`). let mut body_tris = std::collections::HashMap::new(); for (key, c) in &made { - for (name, tris) in &c.ranges { - if !tris.is_empty() { - body_tris.insert(name.clone(), (*key, tris.clone())); + for range in &c.ranges { + if !range.vertices.is_empty() { + body_tris + .insert(range.name.clone(), crate::gpu::BlockTris { block: *key, tris: range.opaque.clone(), vertices: range.vertices.clone() }); } } } if let Ok(mut m) = app.viewport.body_tris.lock() { *m = body_tris; } + // Every shown body has its entries, so only a larger map holds bodies no longer shown. + if appearance.bodies.len() > shown_names.len() || appearance.keys.len() > shown_names.len() { + let names: std::collections::HashSet<&str> = shown_names.iter().copied().collect(); + appearance.bodies.retain(|name, _| names.contains(name.as_str())); + appearance.keys.retain(|name, _| names.contains(name.as_str())); + } if let Ok(mut b) = app.viewport.blocks.lock() { *b = made; } @@ -1068,19 +1387,21 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { } // Section: the outline of each body where the plane cuts it, in the view's text colour (#4146). if let Some((o, n)) = section_plane(app) { - let col = c4(Tokens::view().text.gamma_multiply(0.9)); + let col = sc.color(c4(Tokens::view().text.gamma_multiply(0.9))); let mut kept = app.viewport.section_index.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default(); - let mut made = Vec::new(); + let mut made = std::collections::HashMap::with_capacity(kept.len()); + let normal = [n.x.to_bits(), n.y.to_bits(), n.z.to_bits()]; for b in st.bodies.iter().filter(|b| app.session.body_visible(&b.name)) { let mesh = b.mesh(); - let index = match kept.iter().position(|(m, i)| std::sync::Arc::ptr_eq(m, &mesh) && i.normal() == n) { - Some(k) => kept.swap_remove(k).1, + let key = (std::sync::Arc::as_ptr(&mesh) as usize, normal); + let index = match kept.remove(&key).filter(|(m, i)| std::sync::Arc::ptr_eq(m, &mesh) && i.normal() == n) { + Some((_, index)) => index, None => std::sync::Arc::new(solidcraft_engine::view::SectionIndex::new(&mesh, n)), }; for (a, c) in index.segments(&mesh, o) { sc.line(a.to_f32(), c.to_f32(), col, 1.8, false); } - made.push((mesh, index)); + made.insert(key, (mesh, index)); } if let Ok(mut k) = app.viewport.section_index.lock() { *k = made; @@ -1089,7 +1410,7 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene { // Continuity analysis: each seam `inspect.continuity` measured, drawn over the model in the // colour of its worst verdict. for seam in &s.continuity { - let col = c4(continuity_color(&tk, seam.verdict)); + let col = sc.color(c4(continuity_color(&tk, seam.verdict))); for w in seam.points.windows(2) { if let (Some(a), Some(b)) = (w.first(), w.get(1)) { sc.line(a.to_f32(), b.to_f32(), col, 2.6, true); @@ -1172,15 +1493,17 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { // before its own edge, which is therefore never seen. let fade = GridFade::new(app.cam.half_height(), slant, ext, far_reach); let n = ((fade.end / minor) as i64).clamp(1, 300); + let (grid, grid_major) = (c4(tk.grid), c4(tk.grid_major)); for i in -n..=n { let t = i as f64 * minor; let maj = (t / major).round() * major == t; - let col = if maj { c4(tk.grid_major) } else { c4(tk.grid) }; + let col = if maj { grid_major } else { grid }; let wd = if maj { 1.0 } else { 0.7 }; // Two lines through the point `c + u * t`: one along v, one along u. for (along, across) in [(v, u), (u, v)] { for (s0, s1, alpha) in fade.pieces(t) { - sc.under_line(w3(c + across * t + along * s0), w3(c + across * t + along * s1), grid_colour(col, alpha), wd); + let col = sc.color(grid_colour(col, alpha)); + sc.under_line(w3(c + across * t + along * s0), w3(c + across * t + along * s1), col, wd); } } } @@ -1191,11 +1514,12 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { // Closed profiles are shaded (lifted off a face they may lie on). let lift = ss.plane.normal() * 0.01; let profiles = if app.session.visibility.hidden_profiles.contains(&sid) || ss.sketch.view.hide_profile { &[][..] } else { &ss.profiles[..] }; + let profile_fill = sc.color(c4(tk.profile_fill)); for (index, _) in profiles.iter().enumerate() { let display = crate::sketch_display::profile_region(app, sid, index, &ss.plane, proj); for tri in display.as_ref().as_ref().map_or_else(Vec::new, |region| crate::sketch_display::fill_triangles(region, &mut fill_budget)) { for q in tri { - sc.trans_tri((ss.plane.to_world(q) + lift).to_f32(), [0.0; 3], c4(tk.profile_fill)); + sc.trans_tri((ss.plane.to_world(q) + lift).to_f32(), [0.0; 3], profile_fill); } } } @@ -1220,12 +1544,12 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { unit, ); let haloed = app.preferences.sketch_halo && !active && col != colors::SKETCH_PROJECTED && col != colors::SKETCH_LOST; - strokes.push((segs, sketch_color(&tk, col), if cons { 1.2 } else { 2.0 }, haloed)); + strokes.push((segs, sc.color(sketch_color(&tk, col)), if cons { 1.2 } else { 2.0 }, haloed)); } // Active sketches retain their existing through-body display. Inactive sketches // can opt into the same behaviour in Preferences. let through = active || app.preferences.reference_geometry_through_bodies; - let halo = c4(tk.sketch_halo); + let halo = sc.color(c4(tk.sketch_halo)); for (segs, _, width, _) in strokes.iter().filter(|stroke| stroke.3) { for (a, b) in segs { sc.line(a.to_f32(), b.to_f32(), halo, width + SKETCH_HALO_WIDTH, through); @@ -1238,9 +1562,10 @@ fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene { } } let guide_unit = grid_step(app.cam.half_height()).0; + let warning = sc.color(c4(tk.warning)); for points in crate::sketch_attachment_ui::display_guide_lines(app, proj) { for (a, b) in dashes(&points, &[guide_unit * 0.25, guide_unit * 0.15]) { - sc.line(a.to_f32(), b.to_f32(), c4(tk.warning), 1.5, true); + sc.line(a.to_f32(), b.to_f32(), warning, 1.5, true); } } sc @@ -1283,7 +1608,7 @@ fn ground_shadow(sc: &mut GpuScene, app: &SolveApp, st: &std::sync::Arc bool) { + let col = sc.color(col); for (t, f) in m.triangles.iter().zip(&m.tri_face) { if !takes(*f) { continue; @@ -2487,13 +2813,15 @@ const SKETCH_HALO_WIDTH: f32 = 2.0; /// pick on the far side still shows). fn edge_lines(sc: &mut GpuScene, e: &[Vec3], core: Color32, halo: Color32, w: f32, normals: &[[[f32; 3]; 2]]) { for (col, width) in [(halo, w + 3.0), (core, w)] { + let col = sc.color(c4(col)); for (i, p) in e.windows(2).enumerate() { let n = normals.get(i).copied().unwrap_or_default(); - sc.lifted_line(p[0].to_f32(), p[1].to_f32(), c4(col), width, n); + sc.lifted_line(p[0].to_f32(), p[1].to_f32(), col, width, n); } } + let hidden = sc.color(c4(core.gamma_multiply(0.45))); for p in e.windows(2) { - sc.hidden_line(p[0].to_f32(), p[1].to_f32(), c4(core.gamma_multiply(0.45)), (w * 0.7).max(1.0)); + sc.hidden_line(p[0].to_f32(), p[1].to_f32(), hidden, (w * 0.7).max(1.0)); } } @@ -2527,11 +2855,12 @@ fn edge_normals(m: &solidcraft_engine::geom::Mesh, e: &[Vec3]) -> Vec<[[f32; 3]; /// The outline of a highlighted face where the model hides it (dimmed). fn hidden_face_outline(sc: &mut GpuScene, m: &solidcraft_engine::geom::Mesh, face: usize, col: Color32) { + let col = sc.color(c4(col.gamma_multiply(0.45))); for (ei, e) in m.edges.iter().enumerate() { let on = m.edge_faces.get(ei).is_some_and(|f| f.iter().any(|x| *x as usize == face)); if on && m.edge_pickable(ei) { for p in e.windows(2) { - sc.hidden_line(p[0].to_f32(), p[1].to_f32(), c4(col.gamma_multiply(0.45)), 1.4); + sc.hidden_line(p[0].to_f32(), p[1].to_f32(), col, 1.4); } } } @@ -2549,7 +2878,8 @@ pub(crate) fn profile_fill(sc: &mut GpuScene, app: &SolveApp, sketch: u64, index // Lift toward the eye so a profile on a face shows over it. let lift = app.cam.back() * (app.cam.half_height() * 0.002); let w = |q: solidcraft_engine::geom::Vec2| (plane.to_world(q) + lift).to_f32(); - let col = c4(fill); + let col = sc.color(c4(fill)); + let edge = sc.color(c4(edge)); // In the translucent pass (after the grid and edges) so it covers them. let proj = display_proj(app); let display = crate::sketch_display::profile_region(app, sketch, index, &plane, &proj); @@ -2561,7 +2891,7 @@ pub(crate) fn profile_fill(sc: &mut GpuScene, app: &SolveApp, sketch: u64, index for lp in std::iter::once(&p.region.outer).chain(&p.region.holes) { for part in crate::sketch_display::boundary_parts(lp, &plane, &proj, app.viewport.pixels_per_point()) { for pair in part.windows(2) { - sc.line((pair[0] + lift).to_f32(), (pair[1] + lift).to_f32(), c4(edge), 2.0, false); + sc.line((pair[0] + lift).to_f32(), (pair[1] + lift).to_f32(), edge, 2.0, false); } } } @@ -2572,7 +2902,7 @@ pub(crate) fn profile_fill(sc: &mut GpuScene, app: &SolveApp, sketch: u64, index /// a body stays visible and pickable; or the Preferences setting to show reference geometry /// through bodies), else it is depth-tested like the rest of the scene. fn quad(sc: &mut GpuScene, q: &[Vec3; 4], fill: Color32, edge: Color32, through: bool) { - let col = c4(fill); + let col = sc.color(c4(fill)); for i in [0, 1, 2, 0, 2, 3] { if let Some(p) = q.get(i) { if through { @@ -2591,6 +2921,7 @@ fn quad(sc: &mut GpuScene, q: &[Vec3; 4], fill: Color32, edge: Color32, through: /// A reference line (plane edge, axis): over the model when `through` (as [`quad`]), else depth-tested and /// left whole by a section. fn reference_line(sc: &mut GpuScene, a: [f32; 3], b: [f32; 3], col: [u8; 4], width: f32, through: bool) { + let col = sc.color(col); if through { sc.line(a, b, col, width, true); } else { @@ -2671,6 +3002,8 @@ struct HoverBlock { key: u64, state: std::sync::Arc, doc: std::sync::Arc, + /// The colours the block's palette indices refer to. + palette: std::sync::Arc, block: crate::gpu::SceneBlock, /// Whole bodies the model draws from their plans: reused like the block when the camera /// moves (they are the model's own evaluated triangles, not a copy of them). @@ -2683,6 +3016,8 @@ struct HoverBlock { /// highlight colour. hover_instanced: Vec, selected_instanced: Vec, + /// Faded or see-through bodies in the model's blocks, drawn again in this palette. + recoloured: Vec, } /// The plan the model draws a whole highlighted body from, when it draws one on the GPU. The @@ -2694,7 +3029,7 @@ fn highlight_plan( b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option>, ) -> Option> { - drawn_plan(app, b, highlight_opaque(app, b, active_bodies)) + drawn_plan(app, b, model_plan_class(app, b, active_bodies).is_some()) } /// Whether the model draws a whole body opaque on the GPU, rather than building it on the CPU: @@ -2722,9 +3057,11 @@ struct HighlightInstances { impl HighlightInstances { /// Add the body at `color`, when the model draws it as an instanced placement of an opaque /// shared mesh; `false` when it does not (the caller builds its feedback on the CPU). - fn add(&mut self, app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, active_bodies: &Option>, color: [u8; 4]) -> bool { - // A body with face appearances of its own is built on the CPU, never as an instance. - if !highlight_opaque(app, b, active_bodies) || !app.session.doc.face_colors(b).is_empty() { + fn add(&mut self, app: &SolveApp, b: &solidcraft_engine::doc::ModelBody, color: crate::gpu::PaletteIndex) -> bool { + // A live preview stands in for the body; a body with face appearances of its own is built + // on the CPU, never as an instance. A faded or see-through placement is lit like an opaque + // one: the highlight colour is the placement's own here, not the model's. + if app.preview.effective_replaced().contains(&b.name) || !app.session.doc.face_colors(b).is_empty() { return false; } let Some((mesh, m)) = shared_mesh(app, b) else { return false }; @@ -2778,15 +3115,75 @@ fn highlight_block_tris(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody) - return None; } let map = app.viewport.body_tris.lock().ok()?; - let (block, tris) = map.get(&b.name)?; - Some(crate::gpu::BlockTris { block: *block, tris: tris.clone() }) + map.get(&b.name).cloned() +} + +/// How a whole body is lit: hovered or selected, and in which colour (where the model's own +/// colour is not kept: placements, and faded or see-through bodies). +#[derive(Clone, Copy)] +struct WholeBody { + selected: bool, + colour: [u8; 4], +} + +/// Light the whole of `b` from what the model already has on the GPU, copying no triangle: its +/// plan or its opaque runs (tinted over the model's own colours), its block's vertices recoloured +/// in the highlight's palette (faded and see-through bodies), or its placements. `false` when +/// none applies (wireframe, a live preview standing in for the body): the caller copies it. +fn light_whole_body( + app: &SolveApp, + b: &solidcraft_engine::doc::ModelBody, + active_bodies: &Option>, + lit: WholeBody, + body_slots: &crate::scene_palette::PaletteArena, + feedback: &mut GpuScene, + instances: &mut HighlightInstances, +) -> bool { + if let Some(plan) = highlight_plan(app, b, active_bodies) { + if lit.selected { + feedback.selected_planned.push(plan) + } else { + feedback.hover_planned.push(plan) + } + return true; + } + let opaque = highlight_opaque(app, b, active_bodies); + if let Some(tris) = highlight_block_tris(app, b) { + if opaque && !tris.tris.is_empty() { + if lit.selected { + feedback.selected_blocks.push(tris) + } else { + feedback.hover_blocks.push(tris) + } + return true; + } + // Faded or see-through: the body's every vertex again, its slots in this palette holding + // the highlight colour (as the copy it replaces was drawn). + if !opaque && let Some(slots) = body_slots.slots(&b.name) { + let palette = std::sync::Arc::make_mut(&mut feedback.palette); + palette.set(slots.body, lit.colour); + for f in 0..b.body.face_count() { + palette.set(slots.face(f), lit.colour); + } + feedback.recoloured.push(tris); + return true; + } + } + let colour = feedback.color(lit.colour); + instances.add(app, b, colour) } /// The highlight scene: origin widget, construction planes, selection and hover. pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { let began = crate::now_ms(); let t = Tokens::get(); - let mut sc = GpuScene::default(); + // The model scene's stable palette slots first: whole faded or see-through bodies are drawn + // again from the model's own vertices in this palette, their slots set to the highlight's + // colour (see `light_whole_body`); this scene's own colours follow. + // The key first: it reads the arena (`scene_key`), which is held below. + let key = highlight_geometry_key(app); + let body_slots = app.viewport.palette.lock().unwrap_or_else(|e| e.into_inner()); + let mut sc = GpuScene::with_palette(crate::gpu::Palette::with_stable(body_slots.entries())); let st = crate::open_meshing::shown_world(app); let s = &app.session; let active_bodies = s.active_occurrence_path.as_ref().and_then(|p| s.occurrence_bodies(p, true).ok()); @@ -2857,7 +3254,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { for (name, p) in construction_points(app) { let on = sel.iter().any(|x| matches!(x, Sel::ConstructionPoint { name: n } if *n == name)) || matches!(hover, Some(Hit::ConstructionPoint { name: n }) if *n == name); - let col = c4(if on { t.sel_edge } else { t.construction_geom }); + let col = sc.color(c4(if on { t.sel_edge } else { t.construction_geom })); let r = size * 0.04; for d in [Vec3::X, Vec3::Y, Vec3::Z] { sc.line((p - d * r).to_f32(), (p + d * r).to_f32(), col, 2.0, true); @@ -2867,41 +3264,43 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { // circle in a point input its centre, as construction geometry. The axis runs through the // solid it belongs to, so it is drawn over the model. let (round_axes, round_centres) = round_pick_feedback(app); + let construction = sc.color(c4(t.construction_geom)); for (a, b) in round_axes { let len = a.dist(b); let dash = size * 0.08; let mut s = 0.0; while s < len { let e = (s + dash).min(len); - sc.line(a.lerp(b, s / len).to_f32(), a.lerp(b, e / len).to_f32(), c4(t.construction_geom), 2.0, true); + sc.line(a.lerp(b, s / len).to_f32(), a.lerp(b, e / len).to_f32(), construction, 2.0, true); s += dash * 1.6; } } for p in round_centres { let r = size * 0.04; for d in [Vec3::X, Vec3::Y, Vec3::Z] { - sc.line((p - d * r).to_f32(), (p + d * r).to_f32(), c4(t.construction_geom), 2.0, true); + sc.line((p - d * r).to_f32(), (p + d * r).to_f32(), construction, 2.0, true); } } // Reference widgets follow zoom; the often much larger world-space feedback does not. let projected = sel.iter().any(|s| matches!(s, Sel::Profile { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. })) || matches!(hover, Some(Hit::Profile { .. })); - let key = highlight_geometry_key(app); if !projected && let Some(cached) = app.viewport.hover_block.lock().ok().and_then(|cache| { cache.as_ref().filter(|c| c.key == key && std::sync::Arc::ptr_eq(&c.state, &st) && std::sync::Arc::ptr_eq(&c.doc, &s.doc)).cloned() }) { + sc.palette = cached.palette; sc.blocks.push(cached.block); sc.hover_planned = cached.hover_planned; sc.selected_planned = cached.selected_planned; sc.hover_blocks = cached.hover_blocks; sc.selected_blocks = cached.selected_blocks; + sc.recoloured = cached.recoloured; sc.hover_instanced = cached.hover_instanced; sc.selected_instanced = cached.selected_instanced; return sc; } - let mut feedback = GpuScene::default(); + let mut feedback = GpuScene { palette: std::sync::Arc::new((*sc.palette).clone()), ..Default::default() }; let mut hover_instances = HighlightInstances::default(); let mut selected_instances = HighlightInstances::default(); // Selected things. @@ -2918,11 +3317,8 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { if let Some(b) = st.body(name) && app.session.body_visible(name) { - if let Some(plan) = highlight_plan(app, b, &active_bodies) { - feedback.selected_planned.push(plan); - } else if let Some(tris) = highlight_block_tris(app, b) { - feedback.selected_blocks.push(tris); - } else if !selected_instances.add(app, b, &active_bodies, c4(t.body_selected)) { + let lit = WholeBody { selected: true, colour: c4(t.body_selected) }; + if !light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut selected_instances) { let m = shown(b); let count = b.body.face_count(); mesh_tris(&mut feedback, &m, c4(t.body_selected), true, |f| (f as usize) < count); @@ -2942,29 +3338,31 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { Sel::Profile { sketch, index } => profile_fill(&mut feedback, app, *sketch, *index, t.sel_profile, t.sel_profile_edge), // A 3D sketch curve, in the sketch it names, or whichever sketch has it. Sel::SketchCurve { id, sketch } if st.sketches.iter().any(|ss| ss.sketch.wire_index(id).is_some()) => { + let sel_edge = feedback.color(c4(t.sel_edge)); for ss in st.sketches.iter().filter(|ss| sketch.is_none_or(|k| ss.feature == k)) { if let Some(w) = ss.sketch.wire_index(id).and_then(|i| ss.sketch.wires.get(i)) { for q in w.pts.windows(2) { - feedback.line(q[0].to_f32(), q[1].to_f32(), c4(t.sel_edge), 3.5, true); + feedback.line(q[0].to_f32(), q[1].to_f32(), sel_edge, 3.5, true); } } } } // A curve picked into a dialog from another sketch than the active one names it. Sel::ExternalSketchCurve { sketch, id } | Sel::SketchCurve { id, sketch: Some(sketch) } => { + let sel_edge = feedback.color(c4(t.sel_edge)); if let Some(ss) = st.sketch(*sketch) && let Some(ci) = ss.sketch.curve_index(id) { for pts in &crate::sketch_display::curve_sample(app, *sketch, ci, &ss.plane, &display_proj(app)).parts { let mode = ss.sketch.curves.get(ci).map_or(0, |c| if c.centerline { 2 } else { u8::from(c.construction) }); for (a, b) in sketch_segments(pts, mode, grid_step(app.cam.half_height()).0) { - feedback.line(a.to_f32(), b.to_f32(), c4(t.sel_edge), 3.5, true); + feedback.line(a.to_f32(), b.to_f32(), sel_edge, 3.5, true); } } } else if let Some(w) = st.sketch(*sketch).and_then(|ss| ss.sketch.wire_index(id).and_then(|i| ss.sketch.wires.get(i))) { // A 3D sketch curve of that sketch. for q in w.pts.windows(2) { - feedback.line(q[0].to_f32(), q[1].to_f32(), c4(t.sel_edge), 3.5, true); + feedback.line(q[0].to_f32(), q[1].to_f32(), sel_edge, 3.5, true); } } } @@ -2972,10 +3370,11 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { if let Some(ss) = app.session.active_sketch.and_then(|sid| st.sketch(sid)) && let Some(ci) = ss.sketch.curve_index(id) { + let sel_edge = feedback.color(c4(t.sel_edge)); for pts in &crate::sketch_display::curve_sample(app, ss.feature, ci, &ss.plane, &display_proj(app)).parts { let mode = ss.sketch.curves.get(ci).map_or(0, |c| if c.centerline { 2 } else { u8::from(c.construction) }); for (a, b) in sketch_segments(pts, mode, grid_step(app.cam.half_height()).0) { - feedback.line(a.to_f32(), b.to_f32(), c4(t.sel_edge), 3.5, true); + feedback.line(a.to_f32(), b.to_f32(), sel_edge, 3.5, true); } } } @@ -3019,12 +3418,9 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { if !selected_body { // A whole body the model draws from a plan is lit by redrawing the plan's own // evaluated triangles, not by building every triangle again (see `highlight_plan`). - if whole && let Some(plan) = highlight_plan(app, b, &active_bodies) { - feedback.hover_planned.push(plan); - } else if whole && let Some(tris) = highlight_block_tris(app, b) { - feedback.hover_blocks.push(tris); - } else if whole && hover_instances.add(app, b, &active_bodies, hover_col) { - // Its placements carry the highlight colour. + let lit = WholeBody { selected: false, colour: hover_col }; + if whole && light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut hover_instances) { + // Drawn again from what the model already has on the GPU. } else { let lit = shown(b); let selected_faces = selected_faces.get(b.name.as_str()); @@ -3050,11 +3446,8 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { let k = t.hover_face_lift; let c = body_color(&s.doc, b).unwrap_or(t.body); let hover_col = [c.r().saturating_add(k), c.g().saturating_add(k), c.b().saturating_add(k), 255]; - if let Some(plan) = highlight_plan(app, b, &active_bodies) { - feedback.hover_planned.push(plan); - } else if let Some(tris) = highlight_block_tris(app, b) { - feedback.hover_blocks.push(tris); - } else if !hover_instances.add(app, b, &active_bodies, hover_col) { + let lit = WholeBody { selected: false, colour: hover_col }; + if !light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut hover_instances) { let m = shown(b); let count = b.body.face_count(); mesh_tris(&mut feedback, &m, hover_col, true, |f| (f as usize) < count); @@ -3104,6 +3497,9 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { } feedback.hover_instanced = hover_instances.finish(); feedback.selected_instanced = selected_instances.finish(); + // The feedback palette extends the scene's own: set it before sharing the geometry, and keep + // the indices valid on the cache hit above. + sc.palette = feedback.palette.clone(); if projected { sc.tris.append(&mut feedback.tris); sc.trans.append(&mut feedback.trans); @@ -3114,26 +3510,34 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { sc.selected_planned.append(&mut feedback.selected_planned); sc.hover_blocks.append(&mut feedback.hover_blocks); sc.selected_blocks.append(&mut feedback.selected_blocks); + sc.recoloured.append(&mut feedback.recoloured); sc.hover_instanced.append(&mut feedback.hover_instanced); sc.selected_instanced.append(&mut feedback.selected_instanced); } else { + // The feedback triangles become a block's canonical vertices, in one opaque list. + let vertices = std::mem::take(&mut feedback.tris); + let count = u32::try_from(vertices.len() / crate::gpu::TRI_SIZE).unwrap_or(0); let block = crate::gpu::SceneBlock { key, bytes: std::sync::Arc::new(crate::gpu::BlockBytes { - tris: feedback.tris, - lines: feedback.lines, - hidden: feedback.hidden, + vertices: std::sync::Arc::new(vertices), + opaque: std::sync::Arc::new(std::iter::once(0..count).filter(|r| !r.is_empty()).collect()), + lines: std::sync::Arc::new(std::mem::take(&mut feedback.lines)), + hidden: std::sync::Arc::new(std::mem::take(&mut feedback.hidden)), ..Default::default() }), }; + let palette = feedback.palette.clone(); let (hover_planned, selected_planned) = (feedback.hover_planned, feedback.selected_planned); let (hover_blocks, selected_blocks) = (feedback.hover_blocks, feedback.selected_blocks); let (hover_instanced, selected_instanced) = (feedback.hover_instanced, feedback.selected_instanced); + let recoloured = feedback.recoloured; if let Ok(mut cache) = app.viewport.hover_block.lock() { *cache = Some(HoverBlock { key, state: st.clone(), doc: s.doc.clone(), + palette, block: block.clone(), hover_planned: hover_planned.clone(), selected_planned: selected_planned.clone(), @@ -3141,6 +3545,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { selected_blocks: selected_blocks.clone(), hover_instanced: hover_instanced.clone(), selected_instanced: selected_instanced.clone(), + recoloured: recoloured.clone(), }); } sc.blocks.push(block); @@ -3150,11 +3555,12 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { sc.selected_blocks = selected_blocks; sc.hover_instanced = hover_instanced; sc.selected_instanced = selected_instanced; + sc.recoloured = recoloured; } if solidcraft_engine::geom::env::var_os("PROFILE_FRAMES").is_some() { let in_blocks = |f: fn(&crate::gpu::SceneBlock) -> usize| sc.blocks.iter().map(f).sum::(); - let tris = sc.tris.len() + in_blocks(|b| b.bytes.tris.len()); + let tris = sc.tris.len() + in_blocks(|b| b.bytes.vertices.len()); let lines = sc.lines.len() + in_blocks(|b| b.bytes.lines.len()); let hidden = sc.hidden.len() + in_blocks(|b| b.bytes.hidden.len()); eprintln!( @@ -5269,7 +5675,11 @@ mod tests { ground_shadow(&mut scene, &app, &app.session.world_state()); assert!(scene.trans.is_empty(), "the ground shadow must not trigger order-independent transparency"); assert_eq!(scene.shadow.len(), 48 * 5 * 3 * crate::gpu::TRI_SIZE, "all shadow rings are retained"); - assert!(scene.shadow.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().any(|v| v.get(27).is_some_and(|a| *a > 0))); + let shadow_alpha = |v: &[u8]| { + let i = u32::from_le_bytes(v.get(24..28)?.try_into().ok()?); + scene.palette.get(crate::gpu::PaletteIndex(i)).map(|c| c[3]) + }; + assert!(scene.shadow.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().any(|v| shadow_alpha(v).is_some_and(|a| a > 0))); Ok(()) } @@ -5411,7 +5821,7 @@ mod tests { .find_map(|(lies, n)| lies.then_some(n)) }; for tess in [false, true] { - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false }); let proj = projection(&app, rect); let e = proj.cam.eye().to_f32(); let eye = [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]; @@ -5477,7 +5887,16 @@ mod tests { let app = SolveApp::new(s, crate::Services::default()); let sc = build_scene(&app); // An overlay line is two points, a colour and a width: 32 bytes. - let colours: Vec<[u8; 4]> = sc.overlay.as_chunks::<32>().0.iter().map(|r| [r[24], r[25], r[26], r[27]]).collect(); + let colours: Vec<[u8; 4]> = sc + .overlay + .as_chunks::<32>() + .0 + .iter() + .filter_map(|r| { + let i = u32::from_le_bytes(r.get(24..28)?.try_into().ok()?); + sc.palette.get(crate::gpu::PaletteIndex(i)) + }) + .collect(); let t = Tokens::get(); let count = |c: Color32| colours.iter().filter(|x| **x == c4(c)).count(); let [smooth, jump, sharp, gap] = t.continuity.map(count); @@ -5498,7 +5917,7 @@ mod tests { const SIZE: u32 = 256; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); let mut render = |tess: bool| { - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false }); let scene = build_scene(&app).merged(); let proj = projection(&app, rect); let e = proj.cam.eye().to_f32(); @@ -5557,7 +5976,7 @@ mod tests { s.run_script(&solidcraft_engine::sample::script()).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); app.fit_view(); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false }); const SIZE: u32 = 256; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); let scene = build_scene(&app).merged(); @@ -5595,7 +6014,7 @@ mod tests { s.run_script(&solidcraft_engine::sample::script()).unwrap(); let mut app = SolveApp::new(s, crate::Services::default()); app.fit_view(); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); const SIZE: u32 = 256; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); let proj = projection(&app, rect); @@ -5658,7 +6077,7 @@ mod tests { app.ui.show_grid = false; app.set_origin_shown(false); app.ui.ground_shadow = false; - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); const SIZE: u32 = 512; const RADIUS: f32 = 45.0; let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); @@ -5701,6 +6120,77 @@ mod tests { assert!(step < 0.005, "no copies of the block's outline: a step of {step:.4} between neighbouring columns"); } + /// Faded and see-through bodies are drawn from their plans where the renderer blends them + /// order-independently, and look as they did built on the CPU: a see-through box beside a + /// part faded outside the active component, drawn both ways. Without order-independent + /// transparency they stay on the CPU (the sorted fallback needs their triangles). Skipped + /// without a GPU adapter. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn faded_and_see_through_bodies_are_drawn_from_their_plans_with_oit() { + let mut s = solidcraft_engine::Session::default(); + let part = s.execute("component.create", &json!({"name": "Part"})).unwrap()["component"].as_u64().unwrap(); + s.execute("solid.box", &json!({"length": 30, "width": 30, "height": 30, "corner": [0, 0, 0], "operation": "new", "body_name": "Glass"})) + .unwrap(); + s.execute("appearance.assign", &json!({"bodies": ["Glass"], "color": "#3366cc", "opacity": 0.5})).unwrap(); + s.execute("solid.box", &json!({"length": 20, "width": 20, "height": 20, "corner": [40, 0, 0], "operation": "new", "body_name": "Inside"})) + .unwrap(); + s.execute("component.activate", &json!({"component": 0})).unwrap(); + s.execute("solid.box", &json!({"length": 20, "width": 20, "height": 20, "corner": [0, 40, 0], "operation": "new", "body_name": "Faded"})) + .unwrap(); + s.execute("component.activate", &json!({"component": part})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.ui.ground_shadow = false; + app.fit_view(); + const SIZE: u32 = 192; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); + let target = + |tess: bool, oit: bool| Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit }); + let classes = |scene: &GpuScene| { + let mut c: Vec<_> = scene.planned.iter().map(|b| format!("{:?}", b.class)).collect(); + c.sort(); + c + }; + app.viewport.gpu = target(true, false); + assert_eq!(classes(&build_scene(&app)), ["Opaque"], "without OIT only the opaque body is drawn from its plan"); + app.viewport.gpu = target(true, true); + let planned = build_scene(&app); + assert_eq!(classes(&planned), ["Faded", "Glass", "Opaque"], "with OIT every body is"); + let built: usize = planned.blocks.iter().map(|b| b.bytes.vertices.len()).sum(); + assert_eq!(built, 0, "and none is built on the CPU"); + // Hovered, a faded body drawn from its plan lights through the plan's triangles. + let faded = app.session.world_state().bodies.iter().find(|b| b.name.starts_with("Faded")).map(|b| b.name.clone()).unwrap(); + app.viewport.hover_bodies = vec![faded]; + assert_eq!(build_highlight(&app).hover_planned.len(), 1, "the faded body's plan is lit"); + app.viewport.hover_bodies.clear(); + app.viewport.gpu = target(false, false); + let cpu = build_scene(&app); + let render = |scene: GpuScene, tess: bool| { + let proj = projection(&app, rect); + let e = proj.cam.eye().to_f32(); + let eye = [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]; + crate::gpu::render_offscreen( + scene, + None, + proj.vp.to_f32(), + proj.cam.back().to_f32(), + eye, + SIZE, + tess.then_some(solidcraft_gpu::SHADER), + [0.0; 8], + crate::gpu::analysis_colors(&Tokens::get().analysis), + ) + }; + let (Some(from_plans), Some(from_cpu)) = (render(planned, true), render(cpu, false)) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let differ = from_plans.chunks(4).zip(from_cpu.chunks(4)).filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 6)).count(); + let shown = from_cpu.chunks(4).filter(|p| p[..3] != from_cpu[..3]).count(); + assert!(shown > 2000, "the bodies are in view ({shown} px)"); + assert!(differ * 100 < shown, "{differ} of {shown} px differ between the plan and CPU pictures"); + } + /// A hovered face lights solidly over a body drawn from its display plan on the GPU: the /// highlight uses the plan's triangles, not the reference mesh's other triangulation of the /// same face, which fought the model at equal depth and shimmered in wedges. Every face of a @@ -5720,7 +6210,7 @@ mod tests { let body = app.session.world_state().bodies[0].clone(); let faces = body.body.face_count(); let mut render = |tess: bool, hover: Option| { - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false }); app.viewport.hover = hover.map(|index| Hit::Face { body: body.name.clone(), index, point: Vec3::ZERO }); let (scene, highlight) = (build_scene(&app), build_highlight(&app).merged()); assert_eq!(!scene.planned.is_empty(), tess, "the box is drawn from its plan exactly on the GPU path"); @@ -5798,6 +6288,53 @@ mod tests { if saved { format!("pictures in {}", dir.display()) } else { format!("the pictures could not be saved in {}", dir.display()) } } + /// The highlight scene as the viewport hands it over keeps its feedback (a hovered face, a + /// body copied on the CPU) in a block of its own, kept while the highlight is unchanged. That + /// block is drawn: the picture is the same as with the feedback merged into the scene's own + /// triangles. Skipped without a GPU adapter. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_highlight_scenes_own_block_is_drawn() { + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0], "operation": "new"})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.fit_view(); + const SIZE: u32 = 128; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); + let body = app.session.world_state().bodies[0].clone(); + let proj = projection(&app, rect); + let e = proj.cam.eye().to_f32(); + let eye = [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]; + let model = build_scene(&app); + let render = |highlight: GpuScene| { + crate::gpu::render_offscreen( + model.clone(), + Some(highlight), + proj.vp.to_f32(), + proj.cam.back().to_f32(), + eye, + SIZE, + None, + [0.0; 8], + crate::gpu::analysis_colors(&Tokens::get().analysis), + ) + }; + let Some(plain) = render(GpuScene::default()) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut lit = 0; + for index in 0..body.body.face_count() { + app.viewport.hover = Some(Hit::Face { body: body.name.clone(), index, point: Vec3::ZERO }); + let highlight = build_highlight(&app); + assert!(highlight.blocks.iter().any(|b| !b.bytes.vertices.is_empty()), "the face's feedback is in the highlight's block"); + let (Some(as_handed), Some(merged)) = (render(highlight.clone()), render(highlight.merged())) else { return }; + assert!(as_handed == merged, "face {index}: the highlight's block is not drawn as its merged triangles are"); + lit += usize::from(as_handed != plain); + } + assert!(lit >= 3, "{lit} faces light up"); + } + /// An origin plane lying on a body's face is tinted evenly over it (#1739: a box built at the /// origin, seen from below in orthographic; the XY plane's square z-fought with the bottom /// face in stripes). Faces are pushed back by their slope (`FACE_BIAS`), the planes are not. @@ -5822,7 +6359,8 @@ mod tests { let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); let mut render = |origin: bool| { app.set_origin_shown(origin); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = + Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); let (scene, highlight) = (build_scene(&app), build_highlight(&app).merged()); let proj = projection(&app, rect); let e = proj.cam.eye().to_f32(); @@ -6010,7 +6548,17 @@ mod tests { h.app.run("inspect.section", json!({"plane": "XZ", "at": 15})).unwrap(); h.call("ui.prefs", json!({"theme": "dark", "viewport_theme": "light"})); h.frames(2); - let colours: Vec<[u8; 4]> = build_scene(&h.app).lines.as_chunks::<32>().0.iter().map(|l| [l[24], l[25], l[26], l[27]]).collect(); + let scene = build_scene(&h.app); + let colours: Vec<[u8; 4]> = scene + .lines + .as_chunks::<32>() + .0 + .iter() + .filter_map(|l| { + let i = u32::from_le_bytes(l.get(24..28)?.try_into().ok()?); + scene.palette.get(crate::gpu::PaletteIndex(i)) + }) + .collect(); let (view, window) = (Tokens::light().text.gamma_multiply(0.9), Tokens::dark().text.gamma_multiply(0.9)); assert!(colours.contains(&c4(view)), "the outlines in the view's text colour"); assert!(!colours.contains(&c4(window)), "none in the window's"); @@ -6174,7 +6722,7 @@ mod tests { let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); app.ui.ground_shadow = false; app.set_origin_shown(false); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); app.run("component.create", json!({"name":"Part"})).unwrap(); app.run(command, serde_json::from_str(params).unwrap()).unwrap(); app.run("occurrence.copy", json!({"component":"Part","translate":[40,0,0]})).unwrap(); @@ -6208,7 +6756,7 @@ mod tests { let corners = shared.indices.len(); let vertices = shared.vertices.len() / crate::gpu::SHARED_SIZE; assert!(vertices * 2 < corners, "{part:?}: {vertices} vertices shared by {corners} corners"); - assert!(scene.blocks.iter().all(|b| b.bytes.tris.is_empty()), "no body's triangles built where it stands"); + assert!(scene.blocks.iter().all(|b| b.bytes.vertices.is_empty()), "no body's triangles built where it stands"); let moved = st.bodies.iter().filter(|b| b.cached_mesh().is_some()).count(); assert!(moved <= 1, "{moved} bodies made a moved mesh to be drawn"); let merged = scene.merged(); @@ -6342,7 +6890,7 @@ mod tests { let (w, h, samples) = (3600u32 / scale, 2190u32 / scale, 4u32); let depth = solidcraft_gpu::depth_format(&device, true); let format = wgpu::TextureFormat::Rgba8Unorm; - app.viewport.gpu = Some(GpuTarget { format, depth: Some(depth), samples, tess: false }); + app.viewport.gpu = Some(GpuTarget { format, depth: Some(depth), samples, tess: false, oit: false }); app.fit_view(); let texture = |format, samples| { device @@ -6419,7 +6967,7 @@ mod tests { return; } for (label, scene) in [("own triangles", scene.clone().merged()), ("instanced", scene), ("instanced, levels of detail", lod)] { - let mut renderer = crate::gpu::Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples, tess: false }, None); + let mut renderer = crate::gpu::Renderer::new(&device, GpuTarget { format, depth: Some(depth), samples, tess: false, oit: false }, None); let slot: SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(scene))); let none = || std::sync::Arc::new(std::sync::Mutex::new(None)); let (mut times, mut prepared) = (Vec::new(), Vec::new()); @@ -6521,7 +7069,7 @@ mod tests { }]; doc.add_feature(FeatureKind::MeshImport { file: "grid.stl".into(), meshes }, Some("Grid")).unwrap(); let mut app = SolveApp::new(solidcraft_engine::Session::new(doc), crate::Services::default()); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); let (mesh, _) = app.session.world_state().bodies[0].mesh_in_place(); assert!(mesh.triangles.len() >= INSTANCE_ALONE); warm_shared_tris(&mesh); @@ -6558,7 +7106,7 @@ mod tests { let mut app = SolveApp::new(solidcraft_engine::Session::new(doc), crate::Services::default()); app.ui.ground_shadow = false; app.set_origin_shown(false); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); app } @@ -6632,7 +7180,11 @@ mod tests { let glass = build_scene(&app); assert_eq!(glass.instanced.len(), 1); assert_eq!((glass.instanced[0].look, glass.instanced[0].count()), (InstanceLook::Glass, 3)); - assert!(glass.instanced[0].instances.as_chunks::<{ crate::gpu::INSTANCE_SIZE }>().0.iter().all(|p| p[51] == 102), "alpha 0.4"); + let alpha = |p: &[u8]| { + let i = u32::from_le_bytes(p.get(48..52)?.try_into().ok()?); + glass.palette.get(crate::gpu::PaletteIndex(i)).map(|c| c[3]) + }; + assert!(glass.instanced[0].instances.as_chunks::<{ crate::gpu::INSTANCE_SIZE }>().0.iter().all(|p| alpha(p) == Some(102)), "alpha 0.4"); assert!(glass.glass.is_empty(), "no triangle sorted one by one"); assert!(!glass.clone().merged().glass.is_empty()); // One placement active (as right after the part is made): the others faded. @@ -6874,7 +7426,8 @@ mod tests { let mut app = SolveApp::new(s, crate::Services::default()); if gpu { // The callback is queued by egui; no device is needed to inspect scene updates. - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = + Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); } app } @@ -7432,7 +7985,8 @@ mod tests { let mut app = SolveApp::new(s, crate::Services::default()); app.set_origin_shown(false); if gpu { - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = + Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); } app.cam.target = Vec3::new(20.0, 15.0, 10.0); hover_frame(&mut app, &ctx, vec![]); @@ -7517,7 +8071,7 @@ mod tests { }; for tess in [true, false] { let mut app = cylinder_app(); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false }); let body = app.session.world_state().bodies[0].clone(); let before = build_scene(&app).merged(); let key = scene_key(&app); @@ -7617,7 +8171,7 @@ mod tests { app.viewport.hover_bodies = vec!["Body1".into()]; let before = build_highlight(&app); let bytes = before.blocks[0].bytes.clone(); - assert!(!bytes.tris.is_empty()); + assert!(!bytes.vertices.is_empty()); app.cam.zoom_at(4.0, None); let after = build_highlight(&app); assert!(std::sync::Arc::ptr_eq(&bytes, &after.blocks[0].bytes), "zoom must not regenerate or upload body feedback"); @@ -7625,10 +8179,10 @@ mod tests { app.session.visibility.hidden_bodies.push("Body1".into()); let hidden = build_highlight(&app); assert!(!std::sync::Arc::ptr_eq(&bytes, &hidden.blocks[0].bytes)); - assert!(hidden.blocks[0].bytes.tris.is_empty(), "hidden bodies must lose their feedback"); + assert!(hidden.blocks[0].bytes.vertices.is_empty(), "hidden bodies must lose their feedback"); app.session.visibility.hidden_bodies.clear(); let shown = build_highlight(&app); - assert_eq!(shown.blocks[0].bytes.tris, bytes.tris); + assert_eq!(shown.blocks[0].bytes.vertices, bytes.vertices); } #[test] @@ -7652,7 +8206,7 @@ mod tests { #[test] fn whole_body_highlights_reuse_the_models_own_triangles() { let mut app = cylinder_app(); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true, oit: false }); let body = app.session.world_state().bodies[0].clone(); let plan = body.display_plan().expect("the test body is drawn from a plan"); app.viewport.hover_bodies = vec![body.name.clone()]; @@ -7660,13 +8214,13 @@ mod tests { assert_eq!(hovered.hover_planned.len(), 1, "the whole hovered body is lit from its plan"); assert!(std::sync::Arc::ptr_eq(&hovered.hover_planned[0], &plan)); assert_eq!(hovered.tris.len(), 0); - assert!(hovered.blocks.iter().all(|b| b.bytes.tris.is_empty()), "no copy of the body's triangles"); + assert!(hovered.blocks.iter().all(|b| b.bytes.vertices.is_empty()), "no copy of the body's triangles"); app.viewport.hover_bodies.clear(); app.session.selection = vec![Sel::Body { name: body.name.clone() }]; let selected = build_highlight(&app); assert_eq!(selected.selected_planned.len(), 1, "a selected whole body is lit from its plan too"); assert_eq!(selected.tris.len(), 0); - assert!(selected.blocks.iter().all(|b| b.bytes.tris.is_empty())); + assert!(selected.blocks.iter().all(|b| b.bytes.vertices.is_empty())); // A body the model builds on the CPU (here: no GPU plans) is lit from its own vertices // in the model scene's blocks. app.session.selection.clear(); @@ -7678,7 +8232,7 @@ mod tests { assert!(built.hover_planned.is_empty()); assert_eq!(built.hover_blocks.len(), 1, "a CPU-built body is lit from the model's block"); assert_eq!(built.tris.len(), 0); - assert!(built.blocks.iter().all(|b| b.bytes.tris.is_empty()), "no copy of the body's triangles"); + assert!(built.blocks.iter().all(|b| b.bytes.vertices.is_empty()), "no copy of the body's triangles"); // Two occurrences of one component are drawn as placements of its shared triangles: the // highlight draws those placements again, in its colour. let mut s = solidcraft_engine::Session::default(); @@ -7696,15 +8250,91 @@ mod tests { assert_eq!(instanced.hover_instanced.len(), 1, "the part's one shared mesh"); assert_eq!(instanced.hover_instanced[0].count(), 2, "both of its placements"); assert_eq!(instanced.tris.len(), 0); - assert!(instanced.blocks.iter().all(|b| b.bytes.tris.is_empty()), "no copy of the placements"); - // A see-through body is not in the block's opaque triangles: its feedback is built here. + assert!(instanced.blocks.iter().all(|b| b.bytes.vertices.is_empty()), "no copy of the placements"); + // A see-through body is not in the block's opaque runs: its own vertices in the block are + // drawn again, recoloured in the highlight's palette, and still no triangle is copied. app.viewport.hover_bodies.clear(); app.run("appearance.assign", json!({"bodies": [body.name.clone()], "color": [200, 200, 200], "opacity": 0.5})).unwrap(); build_scene(&app); app.viewport.hover_bodies = vec![body.name.clone()]; let see_through = build_highlight(&app); assert!(see_through.hover_planned.is_empty(), "a see-through body is not drawn from a plan"); - assert!(!see_through.merged().tris.is_empty(), "its highlight is still lit"); + assert_eq!(see_through.recoloured.len(), 1, "it is lit from the model's own vertices"); + assert!(!see_through.recoloured[0].vertices.is_empty()); + assert!(see_through.blocks.iter().all(|b| b.bytes.vertices.is_empty()), "no copy of its triangles"); + } + + /// A whole faded or see-through body lit from the model's own vertices, recoloured in the + /// highlight's palette, looks exactly as the copy of its triangles it replaces did: hovered, + /// and selected. Skipped without a GPU adapter. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn faded_and_see_through_bodies_light_as_their_copies_did() { + const SIZE: u32 = 128; + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 30, "width": 20, "height": 10, "corner": [0, 0, 0], "body_name": "Plate"})).unwrap(); + s.execute("solid.cylinder", &json!({"base": [45, 10, 0], "diameter": 12, "height": 25, "body_name": "Post"})).unwrap(); + s.execute("component.from_bodies", &json!({"bodies": ["Post"]})).unwrap(); + let mut app = SolveApp::new(s, crate::Services::default()); + app.fit_view(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32)); + let proj = projection(&app, rect); + let e = proj.cam.eye().to_f32(); + let eye = [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]; + let render = |model: GpuScene, highlight: GpuScene| { + crate::gpu::render_offscreen( + model, + Some(highlight), + proj.vp.to_f32(), + proj.cam.back().to_f32(), + eye, + SIZE, + None, + [0.0; 8], + crate::gpu::analysis_colors(&Tokens::get().analysis), + ) + }; + for case in ["see-through", "faded"] { + match case { + "see-through" => drop(app.run("appearance.assign", json!({"bodies": ["Plate"], "color": "#88aacc", "opacity": 0.4})).unwrap()), + _ => { + app.run("appearance.assign", json!({"bodies": ["Plate"]})).unwrap(); + app.run("component.activate", json!({"component": "Post"})).unwrap(); + } + } + for selected in [false, true] { + app.viewport.hover_bodies = if selected { Vec::new() } else { vec!["Plate".into()] }; + app.session.selection = if selected { vec![Sel::Body { name: "Plate".into() }] } else { Vec::new() }; + let model = build_scene(&app); + let highlight = build_highlight(&app); + assert_eq!(highlight.recoloured.len(), 1, "{case}: the plate is lit from the model's vertices"); + let highlight_handed = highlight.clone(); + // The copy it replaces: every triangle, lit, in the colour the copy was drawn in. + let t = Tokens::get(); + let colour = if selected { + c4(t.body_selected) + } else { + let c = body_color(&app.session.doc, &app_body(&app, "Plate")).unwrap_or(t.body); + let k = t.hover_face_lift; + [c.r().saturating_add(k), c.g().saturating_add(k), c.b().saturating_add(k), 255] + }; + // The same highlight (its edges and widgets), the plate copied instead of recoloured. + let mut copy = highlight.clone().merged(); + copy.recoloured.clear(); + let mesh = drawn_mesh(&app, &app_body(&app, "Plate")); + mesh_tris(&mut copy, &mesh, colour, true, |_| true); + let (Some(lit), Some(copied)) = (render(model.clone(), highlight_handed), render(model, copy)) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + assert!(lit == copied, "{case}, selected {selected}: the recoloured body does not look as its copy did"); + } + app.session.selection.clear(); + } + } + + fn app_body(app: &SolveApp, name: &str) -> solidcraft_engine::doc::ModelBody { + app.session.world_state().body(name).cloned().unwrap() } #[test] @@ -9111,7 +9741,7 @@ mod tests { let mut app = SolveApp::new(s, crate::Services::default()); app.fit_view(); app.run("inspect.draft", json!({"pull": [-1, -1, 0]})).unwrap(); - app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); const SIZE: u32 = 256; let proj = projection(&app, Rect::from_min_size(Pos2::ZERO, vec2(SIZE as f32, SIZE as f32))); let e = proj.cam.eye().to_f32(); @@ -9433,7 +10063,8 @@ mod grid_plane_tests { app.cam.yaw = 0.0; app.cam.target = Vec3::ZERO; app.cam.distance = 100.0; - let under = build_sketch_scene(&app, &projection(&app, rect)).under; + let scene = build_sketch_scene(&app, &projection(&app, rect)); + let under = &scene.under; // Each line of the grid: two points, a colour and a width. let segments: Vec<([f32; 3], [f32; 3], u8)> = under .as_chunks::<32>() @@ -9441,7 +10072,9 @@ mod grid_plane_tests { .iter() .map(|l| { let point = |at: usize| [0, 4, 8].map(|i| f32::from_le_bytes(l[at + i..at + i + 4].try_into().unwrap())); - (point(0), point(12), l[27]) + let index = u32::from_le_bytes(l[24..28].try_into().unwrap()); + let alpha = scene.palette.get(crate::gpu::PaletteIndex(index)).map_or(0, |c| c[3]); + (point(0), point(12), alpha) }) .collect(); assert!(!segments.is_empty(), "the grid is drawn"); @@ -9548,8 +10181,14 @@ mod grid_plane_tests { let faded = build_sketch_scene(&app, &proj).merged(); // The same grid at full strength: every piece of it opaque. let mut full = faded.clone(); - for piece in full.under.as_chunks_mut::<32>().0 { - piece[27] = 255; + let palette = std::sync::Arc::make_mut(&mut full.palette); + for piece in full.under.as_chunks::<32>().0 { + let index = u32::from_le_bytes(piece[24..28].try_into().unwrap()); + let slot = crate::gpu::PaletteIndex(index); + if let Some(mut colour) = palette.get(slot) { + colour[3] = 255; + palette.set(slot, colour); + } } let (Some(faded), Some(full)) = (render(faded), render(full)) else { eprintln!("skipping: no GPU adapter"); diff --git a/crates/ui-egui/src/viewport_appearance_tests.rs b/crates/ui-egui/src/viewport_appearance_tests.rs index 50867e41f..ab9d180a7 100644 --- a/crates/ui-egui/src/viewport_appearance_tests.rs +++ b/crates/ui-egui/src/viewport_appearance_tests.rs @@ -34,12 +34,19 @@ fn a_finished_sketch_on_a_face_draws_a_halo_under_its_own_curves_only() { let (lines, remainder) = bytes.as_chunks::<{ crate::gpu::LINE_SIZE }>(); assert!(remainder.is_empty()); let halo = super::c4(tokens.sketch_halo); - let halo_count = lines.iter().filter(|line| line[24..28] == halo).count(); + let halo_count = lines.iter().filter(|line| line_color(&scene, *line) == halo).count(); crate::prefs::set(&mut app, &json!({"sketch_halo": false})).unwrap(); assert_ne!(super::sketch_scene_key(&app, &projection), enabled_key, "changing the preference rebuilds the sketch scene"); let disabled = super::build_sketch_scene(&app, &projection); - let without_halos: Vec = lines.iter().filter(|line| line[24..28] != halo).flat_map(|line| line.iter().copied()).collect(); - assert_eq!(if finished { &disabled.lines } else { &disabled.overlay }, &without_halos, "off draws only the original curves"); + let disabled_bytes = if finished { &disabled.lines } else { &disabled.overlay }; + let (without_halos, _) = disabled_bytes.as_chunks::<{ crate::gpu::LINE_SIZE }>(); + let cores_only: Vec<&[u8]> = lines.iter().filter(|line| line_color(&scene, *line) != halo).map(|line| &line[..]).collect(); + assert_eq!(cores_only.len(), without_halos.len(), "off draws only the original curves"); + for (a, b) in cores_only.iter().zip(without_halos) { + assert_eq!(a[..24], b[..24], "same segment"); + assert_eq!(line_color(&scene, a), line_color(&disabled, b), "same colour"); + assert_eq!(a[28..32], b[28..32], "same width"); + } if !finished { assert_eq!(halo_count, 0, "a sketch being edited has no halo"); continue; @@ -49,13 +56,13 @@ fn a_finished_sketch_on_a_face_draws_a_halo_under_its_own_curves_only() { let projected = super::c4(tokens.sketch_projected); let mut cores = 0; let mut references = 0; - for (index, core) in lines.iter().enumerate().filter(|(_, line)| line[24..28] != halo) { - let rim = lines[..index].iter().find(|line| line[..24] == core[..24] && line[24..28] == halo); - if core[24..28] == projected { + for (index, core) in lines.iter().enumerate().filter(|(_, line)| line_color(&scene, *line) != halo) { + let rim = lines[..index].iter().find(|line| line[..24] == core[..24] && line_color(&scene, *line) == halo); + if line_color(&scene, core) == projected { assert!(rim.is_none(), "the face's projected outline has no halo"); references += 1; } else { - assert_eq!(core[24..28], super::c4(tokens.sketch_fixed)); + assert_eq!(line_color(&scene, core), super::c4(tokens.sketch_fixed)); let rim = rim.unwrap(); assert_eq!(width(rim), width(core) + super::SKETCH_HALO_WIDTH, "halo precedes the narrower core"); cores += 1; @@ -109,17 +116,155 @@ fn placed_step_body_uses_imported_opacity_until_a_design_look_overrides_it() { ); let (vertices, remainder) = scene.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>(); assert!(remainder.is_empty()); - assert!(vertices.iter().all(|v| v[27] == 102)); + assert!(vertices.iter().all(|v| vertex_color(&scene, v)[3] == 102)); app.run("appearance.assign", json!({"bodies":[source],"color":"#336699","opacity":0.7})).unwrap(); - let scene = build_scene(&app); + let scene = build_scene(&app).merged(); let (vertices, remainder) = scene.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>(); assert!(remainder.is_empty()); - assert!(vertices.iter().all(|v| v[27] == 179)); + assert!(vertices.iter().all(|v| vertex_color(&scene, v)[3] == 179)); app.run("appearance.assign", json!({"bodies":[source]})).unwrap(); - let scene = build_scene(&app); + let scene = build_scene(&app).merged(); let (vertices, remainder) = scene.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>(); assert!(remainder.is_empty()); - assert!(vertices.iter().all(|v| v[27] == 102)); + assert!(vertices.iter().all(|v| vertex_color(&scene, v)[3] == 102)); +} + +/// The colour of a built triangle vertex: its palette index resolves through the scene. +fn vertex_color(scene: &crate::gpu::GpuScene, v: &[u8]) -> [u8; 4] { + let index = v.get(crate::gpu::TRI_SIZE - 4..crate::gpu::TRI_SIZE).and_then(|b| b.try_into().ok()).map_or(0, u32::from_le_bytes); + scene.palette.get(crate::gpu::PaletteIndex(index)).unwrap_or([0; 4]) +} + +/// The colour of a line record: its palette index resolves through the scene. +fn line_color(scene: &crate::gpu::GpuScene, line: &[u8]) -> [u8; 4] { + let index = line.get(24..28).and_then(|b| b.try_into().ok()).map_or(0, u32::from_le_bytes); + scene.palette.get(crate::gpu::PaletteIndex(index)).unwrap_or([0; 4]) +} + +/// The first vertex's palette index and its colour. +fn first_vertex(scene: &crate::gpu::GpuScene, vertices: &[u8]) -> (u32, Option<[u8; 4]>) { + let index = vertices.get(24..28).and_then(|b| b.try_into().ok()).map_or(0, u32::from_le_bytes); + (index, scene.palette.get(crate::gpu::PaletteIndex(index))) +} + +#[test] +fn selection_does_not_rebuild_the_model_scene() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.ui.ground_shadow = false; + h.app.set_origin_shown(false); + h.app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); + h.app.viewport.gpu = + Some(super::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); + h.frame(); + let key = h.app.viewport.key; + let highlight = h.app.viewport.hl_key; + // Clear the scene the first frame uploaded; an untouched model must not upload another. + let _ = h.app.viewport.slot.lock().unwrap().take(); + let name = h.app.session.world_state().bodies[0].name.clone(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name }]; + h.frame(); + assert_eq!(h.app.viewport.key, key, "a selection does not change the model scene key"); + assert!(h.app.viewport.slot.lock().unwrap().is_none(), "and does not rebuild it"); + assert_ne!(h.app.viewport.hl_key, highlight, "the highlight scene does rebuild"); +} + +#[test] +fn an_appearance_edit_resolves_only_the_bodies_it_changes() { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.ui.ground_shadow = false; + app.set_origin_shown(false); + app.run("solid.box", json!({"length": 20, "width": 15, "height": 10, "body_name": "A"})).unwrap(); + app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0], "body_name": "B"})).unwrap(); + let _ = build_scene(&app); + let before = app.viewport.appearance.lock().unwrap().resolved; + app.run("appearance.assign", json!({"bodies": ["A"], "color": "#336699"})).unwrap(); + let _ = build_scene(&app); + let after = app.viewport.appearance.lock().unwrap().resolved; + assert_eq!(after.saturating_sub(before), 1, "only the body whose look changed is resolved again"); +} + +#[test] +fn a_colour_edit_reuses_every_block_vertex() { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.ui.ground_shadow = false; + app.set_origin_shown(false); + app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); + let name = app.session.world_state().bodies[0].name.clone(); + let first = build_scene(&app); + let block = first.blocks.iter().find(|b| !b.bytes.vertices.is_empty()).expect("the box has a block"); + let (key, vertices) = (block.key, block.bytes.vertices.clone()); + app.run("appearance.assign", json!({"bodies": [name], "color": "#336699"})).unwrap(); + let second = build_scene(&app); + let block = second.blocks.iter().find(|b| b.key == key).expect("the block comes back"); + assert!(std::sync::Arc::ptr_eq(&vertices, &block.bytes.vertices), "a colour edit must not rebuild a vertex"); + assert_eq!(first_vertex(&second, &block.bytes.vertices).1, Some([51, 102, 153, 255]), "the palette carries the new colour"); +} + +#[test] +fn an_opacity_class_change_keeps_vertices_and_rewrites_only_the_runs() { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.ui.ground_shadow = false; + app.set_origin_shown(false); + app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); + let name = app.session.world_state().bodies[0].name.clone(); + let first = build_scene(&app); + let block = first.blocks.iter().find(|b| !b.bytes.vertices.is_empty()).expect("the box has a block"); + let (key, bytes) = (block.key, block.bytes.clone()); + app.run("appearance.assign", json!({"bodies": [name], "color": "#336699", "opacity": 0.5})).unwrap(); + let second = build_scene(&app); + let block = second.blocks.iter().find(|b| b.key == key).expect("the block key is geometry's"); + assert!(std::sync::Arc::ptr_eq(&bytes.vertices, &block.bytes.vertices), "the class change keeps every vertex"); + assert!(!std::sync::Arc::ptr_eq(&bytes.opaque, &block.bytes.opaque), "the opaque runs change"); + assert!(block.bytes.opaque.is_empty() && !block.bytes.glass.is_empty(), "the triangles moved to the glass runs"); + let triangles: u32 = block.bytes.glass.iter().map(|r| r.len() as u32).sum::() / 3; + assert_eq!(block.bytes.glass.len(), 1, "one body of one class is one run, drawn with no index buffer"); + assert_eq!(triangles, 12, "every triangle of the box"); + let vertex = block.bytes.glass.first().map_or(0, |r| r.start) as usize; + let at = vertex * crate::gpu::TRI_SIZE; + let colour = first_vertex(&second, block.bytes.vertices.get(at..).unwrap_or_default()).1; + assert_eq!(colour.map(|c| c[3]), Some(128), "0.5 of 255"); +} + +/// On the GPU, a colour edit writes palette rows and no geometry, also while the body is +/// see-through (the sorted glass stream of the no-OIT path is kept). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn appearance_edits_upload_palette_rows_only() { + const SIZE: u32 = 64; + let Some(mut frames) = crate::gpu::OffscreenFrames::new(SIZE, false) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut app = SolveApp::new(Session::default(), Services::default()); + app.ui.ground_shadow = false; + app.set_origin_shown(false); + app.viewport.gpu = + Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); + app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); + app.fit_view(); + let name = app.session.world_state().bodies[0].name.clone(); + let highlight: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None)); + let mut key = 0; + let mut draw = |app: &SolveApp| { + key += 1; + let slot: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(build_scene(app)))); + frames.frame(crate::scale_tests::view_frame(app, SIZE, (key, &slot), (0, &highlight))); + frames.uploads() + }; + let cold = draw(&app); + assert!(cold.geometry > 0 && cold.palette > 0, "the first scene uploads its geometry and palette: {cold:?}"); + app.run("appearance.assign", json!({"bodies": [&name], "color": "#336699"})).unwrap(); + let colour = draw(&app); + assert_eq!(colour.geometry, 0, "a colour edit uploads no geometry: {colour:?}"); + assert!(colour.palette > 0, "it writes the palette: {colour:?}"); + app.run("appearance.assign", json!({"bodies": [&name], "color": "#336699", "opacity": 0.5})).unwrap(); + let class = draw(&app); + assert!(class.geometry <= 12 * 3 * crate::gpu::TRI_SIZE as u64, "a class change uploads at most the sorted glass stream: {class:?}"); + app.run("appearance.assign", json!({"bodies": [&name], "color": "#993366", "opacity": 0.5})).unwrap(); + let glass = draw(&app); + assert_eq!(glass.geometry, 0, "a see-through body's colour edit uploads no geometry: {glass:?}"); + assert!(glass.palette > 0, "it writes the palette: {glass:?}"); } /// Exercise the live GPU scene slots: a fresh headless render always rebuilds and would hide @@ -131,7 +276,8 @@ fn theme_switches_refresh_cached_viewport_colours_without_remeshing() { h.app.ui.ground_shadow = false; h.app.set_origin_shown(false); h.app.run("solid.box", json!({"length": 20, "width": 15, "height": 10})).unwrap(); - h.app.viewport.gpu = Some(super::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false }); + h.app.viewport.gpu = + Some(super::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false }); let body = h.app.session.world_state().bodies[0].name.clone(); h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: body.clone() }]; h.frame(); @@ -153,7 +299,7 @@ fn theme_switches_refresh_cached_viewport_colours_without_remeshing() { let (vertices, remainder) = scene.tris.as_chunks::<{ crate::gpu::TRI_SIZE }>(); assert!(remainder.is_empty() && !vertices.is_empty()); let colour = super::c4(crate::theme::Tokens::get().body); - assert!(vertices.iter().all(|v| v[24..28] == colour), "{theme}: stale body colour"); + assert!(vertices.iter().all(|v| vertex_color(&scene, v) == colour), "{theme}: stale body colour"); assert_eq!(h.app.session.revision, revision, "theme changes must not edit the design"); assert!(std::sync::Arc::ptr_eq(&mesh, &h.app.session.world_state().bodies[0].cached_mesh().unwrap())); h.frame(); @@ -167,7 +313,7 @@ fn theme_switches_refresh_cached_viewport_colours_without_remeshing() { let scene = h.app.viewport.slot.lock().unwrap().take().unwrap().merged(); let (vertices, _) = scene.tris.as_chunks::<{ crate::gpu::TRI_SIZE }>(); assert!(!vertices.is_empty()); - assert!(vertices.iter().all(|v| v[24..28] == [51, 102, 153, 255]), "{theme}: explicit appearance preserved"); + assert!(vertices.iter().all(|v| vertex_color(&scene, v) == [51, 102, 153, 255]), "{theme}: explicit appearance preserved"); } }