From a4d1b5b6a9fbb61fdbdb7a809d63cff976b07997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=27tite=20T=C3=AAte?= Date: Wed, 28 Oct 2026 15:05:34 +0000 Subject: [PATCH] Viewport: fewer ambient occlusion samples while the view moves (#7165) (#7214) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Fewer ambient occlusion samples while the view moves (#7165) - Draw AO with 8 samples while the view moves, 32 once it has held still for 0.25 s - Share the settle tracking with adaptive supersampling and repaint when it settles - ui.screenshot waits for the full-quality frame (at most half a second) - Test the sample choice, the uniform slot, and ghosting at both counts * fix: Set the AO sample count in the scale test frame - scale_tests.rs, new on main, builds a gpu::Frame without ao_samples - Use AO_SAMPLES, as the other still-frame builders do --------- Co-authored-by: P'tite Tête --- assets/shaders/viewport.wgsl | 11 +- crates/gpu/src/capture.rs | 1 + crates/gpu/src/view.rs | 38 ++++++- crates/gpu/src/view/msaa_check.rs | 1 + crates/ui-egui/src/gpu.rs | 43 ++++++-- crates/ui-egui/src/lib.rs | 5 +- crates/ui-egui/src/render_workspace.rs | 1 + crates/ui-egui/src/scale_tests.rs | 1 + crates/ui-egui/src/viewport.rs | 135 +++++++++++++++++++------ docs/ambient-occlusion.md | 25 ++++- 10 files changed, 219 insertions(+), 42 deletions(-) diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index d4c0c46ad..37d2383d0 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -10,7 +10,7 @@ struct U { acc_u: vec4, // accessibility map axes (xyz, offset) acc_v: vec4, eye: vec4, // eye position, w = 1 for perspective (0: orthographic, looking along -back) - ao: vec4, // radius in world units (zero: disabled) + ao: vec4, // x: radius in world units (zero: disabled), y: samples per pixel // analysis colours (`theme::AnalysisColors`): draft positive, between, negative; reachable, // blocked; curvature flat, middle, tight ana_c: array, 8>, @@ -333,9 +333,12 @@ fn occlusion(i: TOut) -> f32 { // the buffer runs reversed). The map is cleared to its far plane either way, so a texel // with nothing in it reads as 1 and the `d < 1.0` test below skips it. let flip = reversed(); + // Fewer samples while the view moves (#7165), spread over the same hemisphere. 32 is the + // still picture's count, `AO_SAMPLES` in view.rs. + let count = u32(clamp(u.ao.y, 1.0, 32.0)); var blocked = 0.0; - for (var j = 0u; j < 32u; j = j + 1u) { - let f = (f32(j) + 0.5) / 32.0; + for (var j = 0u; j < count; j = j + 1u) { + let f = (f32(j) + 0.5) / f32(count); let angle = f32(j) * 2.39996323; let direction = t * (cos(angle) * sqrt(f)) + b * (sin(angle) * sqrt(f)) + n * sqrt(1.0 - f); let reach = radius * (0.2 + 0.8 * fract(f32(j) * 0.61803399 + 0.5)); @@ -356,7 +359,7 @@ fn occlusion(i: TOut) -> f32 { blocked = blocked + smoothstep(0.005, 0.15, delta) * (1.0 - smoothstep(0.5, 1.0, delta)); } } - return 1.0 - 0.85 * blocked / 32.0; + return 1.0 - 0.85 * blocked / f32(count); } /// How fast the normal turns across the pixel (per mm). diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index f7df85b55..4ef46b252 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -399,6 +399,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces outline: true, eye: [eye[0], eye[1], eye[2], if cam.fov > 0.0 { 1.0 } else { 0.0 }], ao_radius: 0.0, + ao_samples: crate::view::AO_SAMPLES, ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index 1d09d41fe..8cd223ee6 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -908,6 +908,14 @@ pub struct GpuImage { /// Image vertex: position (3 × f32), uv (2 × f32), opacity (f32). const IMG_SIZE: usize = 24; +/// Ambient occlusion samples per shaded pixel in a still picture (the shader's most). +pub const AO_SAMPLES: u32 = 32; + +/// Ambient occlusion samples per shaded pixel while the view moves (#7165): a quarter of the +/// still picture's, on the same turned pattern, so orbiting costs less and shows no copies of +/// nearby parts (#4167). +pub const AO_SAMPLES_MOVING: u32 = 8; + /// Per-frame parameters. pub struct Frame { /// Product preview uses its own batches, retaining the Design viewport's uploads. @@ -950,6 +958,9 @@ pub struct Frame { pub eye: [f32; 4], /// World-space occlusion radius; zero skips the depth prepass and all AO sampling. pub ao_radius: f32, + /// Occlusion samples per shaded pixel: [`AO_SAMPLES`] for a still picture, + /// [`AO_SAMPLES_MOVING`] while the view moves (#7165). + pub ao_samples: u32, /// Supersampling (#1288): draw the frame this many times the viewport's pixels in each /// direction and filter it down (1: off). Under 1 the frame is drawn smaller and filtered up /// (the product preview past its pixel budget, #1464). @@ -3190,6 +3201,7 @@ fn frame_key(cb: &Frame) -> u64 { cb.selection_tint.map(f32::to_bits).hash(&mut h); cb.outline.hash(&mut h); cb.ao_radius.to_bits().hash(&mut h); + cb.ao_samples.hash(&mut h); cb.ssaa.to_bits().hash(&mut h); for img in &cb.images { img.id.hash(&mut h); @@ -4000,7 +4012,7 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) - None => v.extend([0.0; 8]), } v.extend(cb.eye); - v.extend([cb.ao_radius, 0.0, 0.0, 0.0]); + v.extend([cb.ao_radius, cb.ao_samples.clamp(1, AO_SAMPLES) as f32, 0.0, 0.0]); v.extend(cb.analysis_colors); v.extend([if reversed { 1.0 } else { 0.0 }, FACE_STEPS as f32, FACE_SLOPE, 0.0]); v.extend([cb.hover_tint[0], cb.hover_tint[1], cb.hover_tint[2], 0.0]); @@ -4166,6 +4178,25 @@ mod tests { naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap(); } + /// The ambient occlusion sample count rides in the uniform's `ao.y`, beside the radius, kept + /// within the 1 to 32 samples the shader draws (#7165). + #[test] + fn ambient_occlusion_samples_follow_the_radius_in_the_uniform() { + let samples_sent = |samples: u32| { + let mut f = cached_frame(); + f.ao_radius = 123.5; + f.ao_samples = samples; + let bytes = super::uniform_bytes(&f, 64.0, 64.0, false, false); + let v: Vec = bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); + let radius = v.iter().position(|&x| x == 123.5).unwrap(); + v[radius + 1] + }; + assert_eq!(samples_sent(super::AO_SAMPLES), 32.0); + assert_eq!(samples_sent(super::AO_SAMPLES_MOVING), 8.0); + assert_eq!(samples_sent(0), 1.0, "at least one sample"); + assert_eq!(samples_sent(1000), 32.0, "at most the shader's 32"); + } + /// A frame with a fixed picture, and a key that names everything it shows. fn cached_frame() -> super::Frame { use std::sync::{Arc, Mutex}; @@ -4195,6 +4226,7 @@ mod tests { outline: false, eye: [0.0; 4], ao_radius: 0.0, + ao_samples: crate::view::AO_SAMPLES, ssaa: 1.0, } } @@ -4238,6 +4270,8 @@ mod tests { ("selection tint", key(|f| f.selection_tint = [0.4, 0.5, 0.6])), ("outline", key(|f| f.outline = true)), ("ambient occlusion", key(|f| f.ao_radius = 1.0)), + // The settled view's full count replaces the moving view's picture (#7165). + ("ambient occlusion samples", key(|f| f.ao_samples = super::AO_SAMPLES_MOVING)), ("supersampling", key(|f| f.ssaa = 2.0)), ("image", key(|f| f.images.push(image(1)))), ("image pixels", key(|f| f.images.push(image(2)))), @@ -4517,6 +4551,7 @@ mod glass_tests { outline: false, eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, + ao_samples: crate::view::AO_SAMPLES, ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], @@ -4690,6 +4725,7 @@ mod glass_tests { outline: false, eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, + ao_samples: crate::view::AO_SAMPLES, ssaa, } } diff --git a/crates/gpu/src/view/msaa_check.rs b/crates/gpu/src/view/msaa_check.rs index 0f392f4ba..019e24e5f 100644 --- a/crates/gpu/src/view/msaa_check.rs +++ b/crates/gpu/src/view/msaa_check.rs @@ -117,6 +117,7 @@ impl Renderer { outline: false, eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, + ao_samples: crate::view::AO_SAMPLES, ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 7f8fe8489..bfb360073 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -279,7 +279,16 @@ pub(crate) fn render_offscreen( back, eye, size, - Offscreen { tess, product: false, srgb: false, analysis, analysis_colors: colors, ssaa: 1.0, ao_radius: 0.0 }, + Offscreen { + tess, + product: false, + srgb: false, + analysis, + analysis_colors: colors, + ssaa: 1.0, + ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, + }, ) } @@ -300,7 +309,16 @@ pub(crate) fn render_product_offscreen( back, eye, size, - Offscreen { tess: None, product: true, srgb, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa: 1.0, ao_radius: 0.0 }, + Offscreen { + tess: None, + product: true, + srgb, + analysis: [0.0; 8], + analysis_colors: [0.0; 36], + ssaa: 1.0, + ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, + }, ) } @@ -313,6 +331,7 @@ struct Offscreen<'a> { analysis_colors: [f32; 36], ssaa: f32, ao_radius: f32, + ao_samples: u32, } /// [`render_offscreen`] of a scene supersampled `ssaa` times (1: off). @@ -332,11 +351,21 @@ pub(crate) fn render_offscreen_ssaa( back, eye, size, - Offscreen { tess: None, product: false, srgb: false, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa, ao_radius: 0.0 }, + Offscreen { + tess: None, + product: false, + srgb: false, + analysis: [0.0; 8], + analysis_colors: [0.0; 36], + ssaa, + ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, + }, ) } -/// [`render_offscreen`] of a scene with ambient occlusion of `ao_radius` (world units; 0: off). +/// [`render_offscreen`] of a scene with ambient occlusion of `ao_radius` (world units; 0: off), +/// `ao_samples` samples per pixel. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn render_offscreen_ao( scene: GpuScene, @@ -345,6 +374,7 @@ pub(crate) fn render_offscreen_ao( eye: [f32; 4], size: u32, ao_radius: f32, + ao_samples: u32, ) -> Option> { offscreen( scene, @@ -353,7 +383,7 @@ pub(crate) fn render_offscreen_ao( back, eye, size, - Offscreen { tess: None, product: false, srgb: false, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa: 1.0, ao_radius }, + Offscreen { tess: None, product: false, srgb: false, analysis: [0.0; 8], analysis_colors: [0.0; 36], ssaa: 1.0, ao_radius, ao_samples }, ) } @@ -367,7 +397,7 @@ fn offscreen( size: u32, options: Offscreen<'_>, ) -> Option> { - let Offscreen { tess, product, srgb, analysis, analysis_colors, ssaa, ao_radius } = options; + let Offscreen { tess, product, srgb, analysis, analysis_colors, ssaa, ao_radius, ao_samples } = options; let (adapter, device, queue) = offscreen_device()?; eprintln!("offscreen adapter: {:?}", adapter.get_info().backend); let format = if srgb { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }; @@ -400,6 +430,7 @@ fn offscreen( outline: false, eye, ao_radius, + ao_samples, ssaa, hover_tint: [0.0; 3], selection_tint: [0.0; 3], diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e5d99be24..ea8c44ab9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2575,9 +2575,12 @@ impl SolveApp { fn issue_screenshots(&mut self, ctx: &egui::Context) { let now = now_ms(); + // A view that just moved is drawn with fewer AO samples: shoot the full-quality frame + // that follows (#7165), or after half a second a view that keeps moving as it is. + let settled = viewport::ao_settled(self, ctx); self.queued_shots.retain_mut(|(token, at, frames)| { *frames += 1; - if now >= *at && *frames >= 3 { + if now >= *at && *frames >= 3 && (settled || now >= *at + 500.0) { ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(*token))); false } else { diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index b351de479..a3a71d5d4 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -1808,6 +1808,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { outline: false, // Product rendering has its own lighting; AO is a Design viewport setting. ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, eye: [eye.x as f32, eye.y as f32, eye.z as f32, if camera.fov > 0.0 { 1.0 } else { 0.0 }], ssaa: if width < full.0 { width as f32 / full.0 as f32 } else { 1.0 }, hover_tint: [f32::from(Tokens::get().hover_face_lift) / 255.0; 3], diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs index 47e7e739d..314e3b710 100644 --- a/crates/ui-egui/src/scale_tests.rs +++ b/crates/ui-egui/src/scale_tests.rs @@ -287,6 +287,7 @@ pub(crate) fn view_frame( outline: false, eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }], ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, ssaa: 1.0, hover_tint: [f32::from(t.hover_face_lift) / 255.0; 3], selection_tint: [0.4, 0.6, 0.9], diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 8cf0a1302..5b7c8bd17 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -189,8 +189,8 @@ pub struct ViewportState { /// Unsnapped camera while Shift-orbit previews a standard or diagonal view. pub orbit_free: Option, pub build_ms: f64, - /// Adaptive supersampling (#1288): the view drawn last (its view-projection and pixels) and - /// since when it has held still (app time, s). + /// Adaptive supersampling (#1288) and ambient occlusion while moving (#7165): the view drawn + /// last (its view-projection and pixels) and since when it has held still (app time, s). pub(crate) ss_view: (u64, f64), /// The right-click menu, open at this screen position. pub context_menu: Option, @@ -539,6 +539,30 @@ fn supersampling(app: &mut SolveApp, ctx: &egui::Context, view_proj: [[f32; 4]; if !app.preferences.supersampling_adaptive { return factor; } + if view_settled(app, ctx, view_proj, size_px) { factor } else { 1.0 } +} + +/// Ambient occlusion samples per pixel this frame (#7165): the full count once the view has held +/// still for a moment, fewer while it moves, so orbiting with AO on stays quick. +fn ao_samples(app: &mut SolveApp, ctx: &egui::Context, view_proj: [[f32; 4]; 4], size_px: [f32; 2]) -> u32 { + // Without AO (off, or wireframe) the count is unused: no repaint is asked for it. + if !app.preferences.ambient_occlusion || app.ui.visual_style == 2 || view_settled(app, ctx, view_proj, size_px) { + solidcraft_gpu::view::AO_SAMPLES + } else { + solidcraft_gpu::view::AO_SAMPLES_MOVING + } +} + +/// Whether the frame on screen is the full-quality one a screenshot should wait for: with +/// ambient occlusion drawn, the view has held still for [`SS_SETTLE`], so the picture has all +/// its samples (#7165). Reads the state the last painted frame left. +pub(crate) fn ao_settled(app: &SolveApp, ctx: &egui::Context) -> bool { + !app.preferences.ambient_occlusion || app.ui.visual_style == 2 || ctx.input(|i| i.time) - app.viewport.ss_view.1 >= SS_SETTLE +} + +/// Whether the view (its view-projection and pixels) has held still for [`SS_SETTLE`]. Until it +/// has, a repaint is asked for when it will have, so the full-quality frame follows by itself. +fn view_settled(app: &mut SolveApp, ctx: &egui::Context, view_proj: [[f32; 4]; 4], size_px: [f32; 2]) -> bool { let mut h = std::collections::hash_map::DefaultHasher::new(); view_proj.iter().flatten().chain(&size_px).for_each(|x| x.to_bits().hash(&mut h)); let view = h.finish(); @@ -547,16 +571,14 @@ fn supersampling(app: &mut SolveApp, ctx: &egui::Context, view_proj: [[f32; 4]; app.viewport.ss_view = (view, now); } let still = now - app.viewport.ss_view.1; - if still >= SS_SETTLE { - factor - } else { - // Draw it supersampled once the view settles. + if still < SS_SETTLE { ctx.request_repaint_after(std::time::Duration::from_secs_f64(SS_SETTLE - still + 0.01)); - 1.0 } + still >= SS_SETTLE } -/// How long the view holds still before adaptive supersampling draws it at full quality (s). +/// How long the view holds still before adaptive supersampling and ambient occlusion draw it at +/// full quality (s). const SS_SETTLE: f64 = 0.25; /// How far (screen points) a press must be dragged for its release to draw a rectangle, circle @@ -3938,8 +3960,10 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let ppp = ui.ctx().pixels_per_point(); let size_px = [rect.width() * ppp, rect.height() * ppp]; let ssaa = supersampling(app, ui.ctx(), proj.vp.to_f32(), size_px); + let ao_samples = ao_samples(app, ui.ctx(), proj.vp.to_f32(), size_px); let cb = ViewportCallback(Frame { ssaa, + ao_samples, product: false, key: app.viewport.key, slot: app.viewport.slot.clone(), @@ -5960,6 +5984,43 @@ mod tests { assert!(drawn > n / 20, "the model is drawn: {drawn} pixels"); } + /// Ambient occlusion while the view moves (#7165): fewer samples for a moving view, the full + /// count once it has held still for `SS_SETTLE`, and the full count whenever AO is off. + #[test] + fn ambient_occlusion_takes_fewer_samples_while_the_view_moves() { + use solidcraft_gpu::view::{AO_SAMPLES, AO_SAMPLES_MOVING}; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let ctx = egui::Context::default(); + let size = [800.0, 600.0]; + let view = |x: f32| { + let mut m = [[0.0; 4]; 4]; + (0..4).for_each(|i| m[i][i] = 1.0); + m[3][0] = x; + m + }; + // The samples drawn, and whether the frame asks to be drawn again by the time the view + // will have settled (with no input to wake the window, the full count must follow). + let at = |app: &mut SolveApp, time: f64, x: f32| { + let mut n = 0; + let out = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| n = ao_samples(app, ui.ctx(), view(x), size)); + let delay = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); + (n, delay <= std::time::Duration::from_secs_f64(SS_SETTLE + 0.02)) + }; + // A new context asks for its own first repaints: let it settle. + for _ in 0..3 { + let _ = ctx.run_ui(egui::RawInput { time: Some(0.0), ..Default::default() }, |_| {}); + } + app.preferences.ambient_occlusion = false; + assert_eq!(at(&mut app, 0.0, 0.0), (AO_SAMPLES, false), "AO off"); + app.preferences.ambient_occlusion = true; + assert_eq!(at(&mut app, 1.0, 1.0), (AO_SAMPLES_MOVING, true), "the view just moved"); + assert_eq!(at(&mut app, 1.1, 1.0), (AO_SAMPLES_MOVING, true), "still for less than the settling time"); + assert_eq!(at(&mut app, 1.0 + SS_SETTLE + 0.01, 1.0), (AO_SAMPLES, false), "settled"); + assert_eq!(at(&mut app, 1.4, 2.0), (AO_SAMPLES_MOVING, true), "moved again"); + app.ui.visual_style = 2; + assert_eq!(at(&mut app, 1.45, 3.0), (AO_SAMPLES, false), "wireframe draws no AO"); + } + /// Supersampling (#1288): the sample design drawn at 2× and filtered down shows the same /// model (the same pixels covered, give or take its outline) with smoothed edges: pixels part /// model, part background, which a single-sampled frame does not have. Skipped without a GPU @@ -6023,6 +6084,7 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn ambient_occlusion_draws_no_copies_of_a_part() { + use solidcraft_gpu::view::{AO_SAMPLES, AO_SAMPLES_MOVING}; let mut s = solidcraft_engine::Session::default(); s.execute("solid.box", &json!({"length": 300, "width": 300, "height": 4, "corner": [-150, -150, -4], "body_name": "plate"})).unwrap(); s.execute("solid.box", &json!({"length": 30, "width": 160, "height": 16, "corner": [0, -80, 0], "operation": "new", "body_name": "block"})) @@ -6041,9 +6103,10 @@ mod tests { let proj = projection(&app, rect); let e = proj.cam.eye().to_f32(); let eye = [e[0], e[1], e[2], 0.0]; - let render = - |radius: f32| crate::gpu::render_offscreen_ao(build_scene(&app).merged(), proj.vp.to_f32(), proj.cam.back().to_f32(), eye, SIZE, radius); - let (Some(off), Some(on)) = (render(0.0), render(RADIUS)) else { + let render = |radius: f32, samples: u32| { + crate::gpu::render_offscreen_ao(build_scene(&app).merged(), proj.vp.to_f32(), proj.cam.back().to_f32(), eye, SIZE, radius, samples) + }; + let Some(off) = render(0.0, AO_SAMPLES) else { eprintln!("skipping: no GPU adapter"); return; }; @@ -6057,24 +6120,37 @@ mod tests { let (y0, y1) = (a.min(b), a.max(b)); assert!(reach > 100.0 && y1 > y0 + 20, "{reach} px, rows {y0}..{y1}"); let lum = |img: &[u8], x: usize, y: usize| img[(y * SIZE as usize + x) * 4..][..3].iter().map(|&c| f64::from(c)).sum::(); - // The plate's visibility in each column: its brightness with AO over its brightness - // without, averaged over the rows. - let column = |x: usize| (y0..y1).map(|y| lum(&on, x, y) / lum(&off, x, y).max(1.0)).sum::() / (y1 - y0) as f64; - // From 30 px beyond the radius up to 4 px from the block (its outline). - let from = (edge - reach - 30.0) as usize; - let profile: Vec = (from..=(edge - 4.0) as usize).map(column).collect(); - let (clear, shaded) = (&profile[..20], &profile[30..]); - let step = shaded.windows(2).map(|p| (p[1] - p[0]).abs()).fold(0.0, f64::max); - eprintln!( - "plate {} without AO; edge {edge:.1} px, radius {reach:.1} px, rows {y0}..{y1}; clear {:.4}..{:.4}; next to the block {:.4}; largest step {step:.4}", - lum(&off, from, y0) / 3.0, - clear.iter().copied().fold(f64::INFINITY, f64::min), - clear.iter().copied().fold(0.0, f64::max), - profile[profile.len() - 1], - ); - assert!(profile[profile.len() - 1] < 0.98, "the plate darkens beside the block: {:.4}", profile[profile.len() - 1]); - assert!(clear.iter().all(|v| (v - 1.0).abs() < 0.004), "the plate is clear beyond the radius: {clear:?}"); - assert!(step < 0.005, "no copies of the block's outline: a step of {step:.4} between neighbouring columns"); + // The still picture's samples, and the fewer drawn while the view moves (#7165). + let mut beside = Vec::new(); + let mut pictures = Vec::new(); + for samples in [AO_SAMPLES, AO_SAMPLES_MOVING] { + let Some(on) = render(RADIUS, samples) else { return }; + let on = &on; + // The plate's visibility in each column: its brightness with AO over its brightness + // without, averaged over the rows. + let column = |x: usize| (y0..y1).map(|y| lum(on, x, y) / lum(&off, x, y).max(1.0)).sum::() / (y1 - y0) as f64; + // From 30 px beyond the radius up to 4 px from the block (its outline). + let from = (edge - reach - 30.0) as usize; + let profile: Vec = (from..=(edge - 4.0) as usize).map(column).collect(); + let (clear, shaded) = (&profile[..20], &profile[30..]); + let step = shaded.windows(2).map(|p| (p[1] - p[0]).abs()).fold(0.0, f64::max); + eprintln!( + "{samples} samples: plate {} without AO; edge {edge:.1} px, radius {reach:.1} px, rows {y0}..{y1}; clear {:.4}..{:.4}; next to the block {:.4}; largest step {step:.4}", + lum(&off, from, y0) / 3.0, + clear.iter().copied().fold(f64::INFINITY, f64::min), + clear.iter().copied().fold(0.0, f64::max), + profile[profile.len() - 1], + ); + assert!(profile[profile.len() - 1] < 0.98, "{samples} samples: the plate darkens beside the block: {:.4}", profile[profile.len() - 1]); + assert!(clear.iter().all(|v| (v - 1.0).abs() < 0.004), "{samples} samples: the plate is clear beyond the radius: {clear:?}"); + assert!(step < 0.005, "{samples} samples: no copies of the block's outline: a step of {step:.4} between neighbouring columns"); + beside.push(profile[profile.len() - 1]); + pictures.push(on.clone()); + } + // The shader takes the count it is given (the moving frame is a different picture), and + // spreads it over the same hemisphere: both darken the contact alike. + assert_ne!(pictures[0], pictures[1], "8 samples draw another grain than 32"); + assert!((beside[0] - beside[1]).abs() < 0.02, "the same darkening beside the block at 32 and 8 samples: {beside:?}"); } /// Faded and see-through bodies are drawn from their plans where the renderer blends them @@ -7000,6 +7076,7 @@ mod tests { outline: true, eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }], ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], diff --git a/docs/ambient-occlusion.md b/docs/ambient-occlusion.md index 8e8d53ded..3bee560d0 100644 --- a/docs/ambient-occlusion.md +++ b/docs/ambient-occlusion.md @@ -34,7 +34,11 @@ The GPU viewport uses 32 hemisphere samples per shaded pixel against an opaque d prepass (at most 2048 pixels on its longest side), the sample pattern turned by a different angle at each pixel. One pattern for every pixel drew faint shifted copies of nearby parts (#4167) and stepped bands along contacts (#3407); turned, they become an -even fine grain, which 2× supersampling smooths further. The radius follows +even fine grain, which 2× supersampling smooths further. While the view moves (orbit, pan, +zoom, resize), frames take 8 samples on the same turned pattern, and the full 32 follow once +the view has held still for 0.25 s, the settling time adaptive supersampling uses (#7165). +The AO grain changes when the full count arrives, as the edges do when adaptive supersampling +does. `ui.screenshot` waits for that full-quality frame (at most half a second). The radius follows model size, and depth-range rejection avoids shadows from distant foreground objects. It supports orthographic and perspective cameras and respects section clipping. Wireframe, transparent bodies, overlays and surface-analysis colours are unaffected. @@ -102,3 +106,22 @@ Per-trial medians (ms), in chronological order: - sample-quality: 5.82, 4.48, 7.08. - 25-plates-performance: 3.13, 3.16, 3.14. - 25-plates-quality: 6.80, 7.02, 6.95. + +## AO while the view moves (2026-10-26, #7165) + +Apple M4 Max, macOS 27, release build, MSAA 4x, ground shadow on, normal display quality, +supersampling off. The design is `solidcraft-cli bench-agent --save` (1,280 bodies, 767,476 +triangles), fitted to a 1600 x 960 point viewport. The camera was turned through `ui.camera` +every 8 ms for 6 seconds while a Metal System Trace recorded the window. The figure is the +median fragment time of the command buffers that drew the scene (over 1 ms of GPU work), one +trace per configuration, three interleaved series. + +| | Series 1 | Series 2 | Series 3 | +|---|---:|---:|---:| +| AO off | 3.79 ms | 4.16 ms | 3.82 ms | +| AO on, 32 samples while moving (before) | 4.48 ms | 5.41 ms | 4.70 ms | +| AO on, 8 samples while moving | 3.96 ms | 3.80 ms | 4.17 ms | + +AO added about 0.9 ms of fragment time to each moving frame before, and adds about 0.06 ms +now. The still frame and its cost are unchanged. This is one machine and one design; the +ratio, not the milliseconds, is what carries over to slower GPUs.