Extend viewport AO to the existing virtual ground (#3413) (#11979)

* claim: #3413

* feat(gpu): extend viewport AO to the virtual ground

* test(gpu): retain measured AO render attachments

* perf: initialize ground AO pipeline with concurrent jobs

* fix(gpu): size ground AO receiver for the current frame radius

* fix(viewport): retain orbit caches when ground AO visibility changes
This commit is contained in:
takuto-NA
2026-11-04 19:42:01 +00:00
committed by GitHub
parent a43cd99e55
commit ef2f485e15
13 changed files with 621 additions and 11 deletions
+1
View File
@@ -397,6 +397,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces
pv_key: 0,
pv_slot: empty(),
pv_hide: false,
preview_bounds: None,
view_proj: cam.view_proj(f64::from(width) / f64::from(height.max(1)), scene.radius.max(1.0)).to_f32(),
back: cam.back().to_f32(),
size_px: [width as f32, height as f32],
+57 -2
View File
@@ -18,6 +18,7 @@ use crate::pbr;
use wgpu::util::DeviceExt;
mod ao;
pub use ao::GroundAo;
mod clouds;
pub use clouds::{CloudFilter, CloudStyle, ColorMode, DOT_SIZE, Dot, FILTERS, GpuCloud, cloud_dot};
#[cfg(not(target_arch = "wasm32"))]
@@ -494,6 +495,8 @@ impl InstancedMesh {
pub struct GpuScene {
/// The colours every vertex, line and instance index into.
pub palette: Arc<Palette>,
/// Non-selectable virtual ground receiving viewport AO, separate from model triangles.
pub ground_ao: Option<GroundAo>,
/// Opaque triangles. A zero normal draws the colour flat (unlit).
pub tris: Vec<u8>,
/// Opaque triangles of open bodies, drawn as `tris` but left out of a section's crossing
@@ -1017,6 +1020,9 @@ pub struct Frame {
pub pv_slot: SceneSlot,
/// Preview reselect: skip drawing the preview while Primary rolls it back.
pub pv_hide: bool,
/// World bounds of the active preview. Ground effects update their small receiver without
/// changing the model scene's key or re-uploading model geometry/colours.
pub preview_bounds: Option<solidcraft_geom::Aabb3>,
/// Column-major view-projection.
pub view_proj: [[f32; 4]; 4],
/// Direction toward the eye (for lighting).
@@ -1700,6 +1706,8 @@ struct Batches {
tris: Option<Batch>,
/// [`GpuScene::open_tris`].
open_tris: Option<Batch>,
ground_ao: Option<Batch>,
ground_input: Option<GroundAo>,
pbr: Option<Batch>,
trans: Option<Batch>,
shadow: Option<Batch>,
@@ -1792,6 +1800,7 @@ impl Batches {
geometry += data.len() as u64;
upload(device, label, data, stride)
};
self.ground_input = sc.ground_ao;
self.tris = own("sc_tris", &sc.tris, TRI_SIZE);
self.open_tris = own("sc_open_tris", &sc.open_tris, TRI_SIZE);
self.pbr = own("sc_pbr", &sc.pbr, PBR_SIZE);
@@ -2077,6 +2086,8 @@ pub struct Renderer {
ss_stats: DrawStats,
/// The AO depth prepass resources (a 1 × 1 stand-in while ambient occlusion is off).
ao: ao::Resources,
ground_ao: wgpu::RenderPipeline,
ground_ao_key: Option<(u64, u64, bool, u32, bool)>,
tri: wgpu::RenderPipeline,
/// `tri` and `tri_cut` for planned bodies (positions and normals from the GPU evaluation,
/// colours per vertex, indexed).
@@ -2737,6 +2748,29 @@ impl Renderer {
bind_group_layouts: &[Some(&bgl), Some(&access_bgl), Some(&ao_layout)],
immediate_size: 0,
});
let ground_ao = || {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("sc_ground_ao"),
layout: Some(&solid_layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs_tri"),
buffers: &[Some(tri_layout())],
compilation_options: Default::default(),
},
primitive: wgpu::PrimitiveState { cull_mode: Some(wgpu::Face::Back), ..Default::default() },
depth_stencil: depth(wgpu::CompareFunction::LessEqual, false),
multisample: wgpu::MultisampleState { count: t.samples.max(1), ..Default::default() },
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_ground_ao"),
targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: alpha, write_mask: wgpu::ColorWrites::ALL })],
compilation_options: Default::default(),
}),
multiview_mask: None,
cache: None,
})
};
let built = [Some(tri_layout())];
let evaluated = [Some(planned_layout()), Some(color_layout())];
let placed = [Some(shared_layout()), Some(instance_layout())];
@@ -2982,6 +3016,7 @@ impl Renderer {
let cloud_pipes = jobs.spawn(cloud_pipes);
let image = jobs.spawn(image);
let ao = jobs.spawn(ao);
let ground_ao = jobs.spawn(ground_ao);
let oit = jobs.spawn(oit);
let blits = jobs.spawn(blits);
let resets = jobs.spawn(resets);
@@ -3000,6 +3035,8 @@ impl Renderer {
let oit = oit.join();
Renderer {
ao: ao.join(),
ground_ao: ground_ao.join(),
ground_ao_key: None,
depth_reset,
section_stencil,
#[cfg(test)]
@@ -3484,6 +3521,17 @@ impl Renderer {
res.model.sort_glass(queue, cb.back);
}
res.model.cull(queue, &cb.view_proj, cb.size_px);
let ground_visible = res.model.ground_input.is_some_and(|ground| ground.visible_from(cb.back));
let ground_key = (cb.key, cb.pv_key, cb.pv_hide, cb.ao_radius.to_bits(), ground_visible);
if res.ground_ao_key != Some(ground_key) {
let preview = if cb.pv_hide { None } else { cb.preview_bounds };
res.model.ground_ao = res
.model
.ground_input
.filter(|_| ground_visible)
.and_then(|ground| upload(device, "sc_ground_ao", &ground.vertices_with_radius(preview, cb.ao_radius), TRI_SIZE));
res.ground_ao_key = Some(ground_key);
}
queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out, res.target.reversed_depth()));
if let Some(a) = &cb.access
&& a.version != res.access_version
@@ -3491,8 +3539,9 @@ impl Renderer {
res.access_bind = access_texture(device, Some(queue), &res.access_bgl, a.size, &a.depth);
res.access_version = a.version;
}
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]);
let preview = if cb.pv_hide { &res.empty } else { &res.preview };
let ao_binds = [scene_bind(&res.model, &res.bind), scene_bind(preview, &res.bind)];
res.ao.prepare(device, encoder, ao_binds, cb.ao_radius, cb.size_px, res.target.reversed_depth(), [&res.model, 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();
@@ -3838,6 +3887,9 @@ impl Renderer {
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), &[]);
if !cb.product && cb.ao_radius > 0.0 {
tris(pass, &res.ground_ao, &m.ground_ao);
}
for (id, q) in res.quads.iter().filter(|_| !cb.product) {
if let Some((_, bind)) = res.textures.get(id) {
pass.set_pipeline(&res.image);
@@ -4514,6 +4566,7 @@ mod tests {
pv_key: 4,
pv_slot: slot(),
pv_hide: false,
preview_bounds: None,
view_proj: [[0.0; 4]; 4],
back: [0.0; 3],
size_px: [800.0, 600.0],
@@ -4973,6 +5026,7 @@ mod glass_tests {
pv_key: 0,
pv_slot: none(),
pv_hide: false,
preview_bounds: None,
view_proj: [[0.1, 0.0, 0.0, 0.0], [0.0, 0.1, 0.0, 0.0], [0.0, 0.0, -0.01, 0.0], [0.0, 0.0, 0.5, 1.0]],
back: [0.0, 0.0, 1.0],
size_px: [SIZE as f32; 2],
@@ -5150,6 +5204,7 @@ mod glass_tests {
pv_key: 0,
pv_slot: none(),
pv_hide: false,
preview_bounds: None,
view_proj: [[0.1, 0.0, 0.0, 0.0], [0.0, 0.1, 0.0, 0.0], [0.0, 0.0, -0.01, 0.0], [0.0, 0.0, 0.5, 1.0]],
back: [0.0, 0.0, 1.0],
size_px: [SIZE as f32; 2],
+109 -3
View File
@@ -1,4 +1,4 @@
//! The optional AO passes. Only opaque model and preview triangles participate: their depth is
//! The optional AO passes. Opaque model, preview and virtual ground triangles participate: their depth is
//! drawn once into a single-sample depth map, and the occlusion term of the surface that depth
//! holds is drawn into a texture of the same size and blurred by depth (#9327), which the lit
//! fragment reads. The maps are independent of the window's MSAA, and the depth runs the same way
@@ -30,6 +30,78 @@ pub(super) struct Maps {
smooth: wgpu::TextureView,
}
/// A virtual receiver in the camera's up-axis frame. Geometry is built independently of the
/// model batches, so moving a preview never re-uploads unchanged model colours or vertices.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GroundAo {
bounds: solidcraft_geom::Aabb3,
height: f64,
up: solidcraft_render::UpAxis,
radius: f32,
}
impl GroundAo {
pub(super) fn visible_from(&self, back: [f32; 3]) -> bool {
if !back.iter().all(|v| v.is_finite()) {
return false;
}
let cam = solidcraft_render::Camera { up: self.up, ..Default::default() };
cam.to_frame(solidcore_record::Vec3::new(f64::from(back[0]), f64::from(back[1]), f64::from(back[2]))).z > 0.0
}
pub fn new(bounds: solidcraft_geom::Aabb3, height: f64, up: solidcraft_render::UpAxis, radius: f32) -> Option<Self> {
if bounds.is_empty() || !bounds.min.is_finite() || !bounds.max.is_finite() || !height.is_finite() || !radius.is_finite() || radius <= 0.0 {
return None;
}
Some(Self { bounds, height, up, radius })
}
/// Two triangles (168 bytes), extended to cover an optional preview without moving the
/// existing ground height. Invalid preview bounds are ignored.
pub fn vertices(&self, preview: Option<solidcraft_geom::Aabb3>) -> Vec<u8> {
self.vertices_with_radius(preview, self.radius)
}
/// Cover the preview plus the current frame's sampling margin. Invalid radii draw nothing.
pub fn vertices_with_radius(&self, preview: Option<solidcraft_geom::Aabb3>, radius: f32) -> Vec<u8> {
use solidcore_record::Vec3;
if !radius.is_finite() || radius <= 0.0 {
return Vec::new();
}
let cam = solidcraft_render::Camera { up: self.up, ..Default::default() };
let mut coverage = self.bounds;
if let Some(bb) = preview.filter(|b| !b.is_empty() && b.min.is_finite() && b.max.is_finite()) {
for i in 0..8 {
coverage.add(cam.to_frame(Vec3::new(
if i & 1 == 0 { bb.min.x } else { bb.max.x },
if i & 2 == 0 { bb.min.y } else { bb.max.y },
if i & 4 == 0 { bb.min.z } else { bb.max.z },
)));
}
}
let margin = f64::from(radius) * 2.0;
let points = [
Vec3::new(coverage.min.x - margin, coverage.min.y - margin, self.height),
Vec3::new(coverage.max.x + margin, coverage.min.y - margin, self.height),
Vec3::new(coverage.max.x + margin, coverage.max.y + margin, self.height),
Vec3::new(coverage.min.x - margin, coverage.max.y + margin, self.height),
]
.map(|p| cam.from_frame(p).to_f32());
if !points.iter().flatten().all(|v| v.is_finite()) {
return Vec::new();
}
let normal = cam.from_frame(Vec3::Z).to_f32();
let mut bytes = Vec::with_capacity(6 * super::TRI_SIZE);
for i in [0, 1, 2, 0, 2, 3] {
for value in points[i].iter().chain(&normal) {
bytes.extend_from_slice(&value.to_le_bytes());
}
bytes.extend_from_slice(&0u32.to_le_bytes());
}
bytes
}
}
pub(super) struct Resources {
pub layout: wgpu::BindGroupLayout,
pub maps: Maps,
@@ -87,7 +159,7 @@ fn draw_opaque(pass: &mut wgpu::RenderPass<'_>, pipelines: &OpaquePipelines, bin
for (batch, bind) in batches.into_iter().zip(binds) {
pass.set_bind_group(0, bind, &[]);
pass.set_pipeline(&pipelines.built);
for tris in [&batch.tris, &batch.open_tris].into_iter().flatten() {
for tris in [&batch.tris, &batch.open_tris, &batch.ground_ao].into_iter().flatten() {
for (buffer, count) in &tris.parts {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw(0..*count, 0..1);
@@ -299,7 +371,41 @@ fn target_size(enabled: bool, pixels: [f32; 2], device_limit: u32) -> [u32; 2] {
#[cfg(test)]
mod tests {
use super::target_size;
use super::{GroundAo, target_size};
#[test]
fn receiver_visibility_follows_the_camera_side_in_both_up_axes() {
use solidcore_record::Vec3;
let bounds = solidcraft_geom::Aabb3 { min: Vec3::ZERO, max: Vec3::new(3.0, 4.0, 12.0) };
for up in [solidcraft_render::UpAxis::Y, solidcraft_render::UpAxis::Z] {
let cam = solidcraft_render::Camera { up, ..Default::default() };
let ground = GroundAo::new(bounds, 0.0, up, 1.0).unwrap();
assert!(ground.visible_from(cam.from_frame(Vec3::Z).to_f32()));
assert!(!ground.visible_from(cam.from_frame(-Vec3::Z).to_f32()));
assert!(!ground.visible_from(cam.from_frame(Vec3::X).to_f32()));
assert!(!ground.visible_from([f32::NAN; 3]));
}
}
#[test]
fn a_growing_preview_keeps_the_current_sampling_margin_at_the_fixed_ground_height() {
use solidcore_record::Vec3;
use solidcraft_geom::Aabb3;
let bounds = Aabb3 { min: Vec3::ZERO, max: Vec3::new(3.0, 4.0, 12.0) };
let ground = GroundAo::new(bounds, -0.014, solidcraft_render::UpAxis::Z, 1.0).unwrap();
let preview = Aabb3 { min: Vec3::new(100.0, 200.0, -40.0), max: Vec3::new(103.0, 204.0, -28.0) };
let mut drawn = Aabb3::EMPTY;
for vertex in ground.vertices_with_radius(Some(preview), 10.0).as_chunks::<{ crate::view::TRI_SIZE }>().0 {
let read = |i| f64::from(f32::from_le_bytes(vertex[i..i + 4].try_into().unwrap()));
drawn.add(Vec3::new(read(0), read(4), read(8)));
}
assert_eq!((drawn.min.x, drawn.min.y, drawn.max.x, drawn.max.y), (-20.0, -20.0, 123.0, 224.0));
assert!((drawn.min.z + 0.014).abs() < 1e-6 && (drawn.max.z + 0.014).abs() < 1e-6);
assert_eq!(ground.vertices(Some(preview)), ground.vertices_with_radius(Some(preview), 1.0));
for radius in [f32::NAN, f32::INFINITY, -1.0, 0.0] {
assert!(ground.vertices_with_radius(Some(preview), radius).is_empty());
}
}
#[test]
fn depth_map_is_bounded_and_released_when_disabled() {
assert_eq!(target_size(true, [6000.0, 3000.0], 8192), [2048, 1024]);
+1
View File
@@ -107,6 +107,7 @@ impl Renderer {
pv_key: 4,
pv_slot: slot(None),
pv_hide: false,
preview_bounds: None,
view_proj: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.5, 1.0]],
back: [0.0, 0.0, 1.0],
size_px: [SIZE as f32; 2],