Viewport: leave bodies out of the view out of their blocks' draws (#7436)
Instanced placements were culled per view, but a block drew every body in it whatever the camera saw. Blocks now keep each body's vertex span and box; when the view changes, each class's runs are drawn without the bodies whose boxes are out of the view. A block whose bodies are all in view draws its runs as they are. Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
+108
-1
@@ -602,6 +602,9 @@ pub enum TriClass {
|
||||
#[derive(Default, Clone)]
|
||||
pub struct BlockBytes {
|
||||
pub vertices: Arc<Vec<u8>>,
|
||||
/// Each body's share of `vertices` and the box around it: a body out of the view is left
|
||||
/// out of the draws ([`Batches::cull`]). Vertices outside every span are always drawn.
|
||||
pub bodies: Arc<Vec<BodySpan>>,
|
||||
pub opaque: Arc<Vec<std::ops::Range<u32>>>,
|
||||
pub glass: Arc<Vec<std::ops::Range<u32>>>,
|
||||
pub faded: Arc<Vec<std::ops::Range<u32>>>,
|
||||
@@ -620,6 +623,43 @@ impl BlockBytes {
|
||||
}
|
||||
}
|
||||
|
||||
/// A body's vertices in a block and the box around them.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BodySpan {
|
||||
pub vertices: std::ops::Range<u32>,
|
||||
pub bounds: [[f32; 3]; 2],
|
||||
}
|
||||
|
||||
/// `runs` without the vertices in `hidden` (both sorted and disjoint).
|
||||
fn runs_without(runs: &[std::ops::Range<u32>], hidden: &[std::ops::Range<u32>]) -> Vec<std::ops::Range<u32>> {
|
||||
let mut out = Vec::with_capacity(runs.len());
|
||||
let mut h = hidden.iter().peekable();
|
||||
for r in runs {
|
||||
let mut start = r.start;
|
||||
while let Some(x) = h.peek() {
|
||||
if x.end <= start {
|
||||
h.next();
|
||||
continue;
|
||||
}
|
||||
if x.start >= r.end {
|
||||
break;
|
||||
}
|
||||
if x.start > start {
|
||||
out.push(start..x.start);
|
||||
}
|
||||
start = start.max(x.end);
|
||||
if x.end >= r.end {
|
||||
break;
|
||||
}
|
||||
h.next();
|
||||
}
|
||||
if start < r.end {
|
||||
out.push(start..r.end);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Add a triangle starting at vertex `at` to `runs`, extending the last run when it ends there.
|
||||
pub fn extend_runs(runs: &mut Vec<std::ops::Range<u32>>, at: u32) {
|
||||
let end = at.saturating_add(3);
|
||||
@@ -638,9 +678,28 @@ pub struct BlockBuilder {
|
||||
faded: Vec<std::ops::Range<u32>>,
|
||||
lines: Vec<u8>,
|
||||
hidden: Vec<u8>,
|
||||
bodies: Vec<BodySpan>,
|
||||
/// The body being written: its first vertex and the box so far.
|
||||
open: Option<(u32, [[f32; 3]; 2])>,
|
||||
}
|
||||
|
||||
impl BlockBuilder {
|
||||
/// The triangles from here to [`BlockBuilder::end_body`] are one body's (its box is kept, so
|
||||
/// it can be left out of a view it is not in).
|
||||
pub fn begin_body(&mut self) {
|
||||
let at = u32::try_from(self.vertices.len() / TRI_SIZE).unwrap_or(u32::MAX);
|
||||
self.open = Some((at, [[f32::INFINITY; 3], [f32::NEG_INFINITY; 3]]));
|
||||
}
|
||||
|
||||
/// End the body [`BlockBuilder::begin_body`] began.
|
||||
pub fn end_body(&mut self) {
|
||||
let Some((start, bounds)) = self.open.take() else { return };
|
||||
let end = u32::try_from(self.vertices.len() / TRI_SIZE).unwrap_or(u32::MAX);
|
||||
if end > start && bounds.iter().flatten().all(|x| x.is_finite()) {
|
||||
self.bodies.push(BodySpan { vertices: start..end, bounds });
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -658,6 +717,14 @@ impl BlockBuilder {
|
||||
}
|
||||
}
|
||||
self.vertices.extend_from_slice(&record);
|
||||
if let Some((_, [lo, hi])) = &mut self.open {
|
||||
for v in p {
|
||||
for k in 0..3 {
|
||||
lo[k] = lo[k].min(v[k]);
|
||||
hi[k] = hi[k].max(v[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let runs = match class {
|
||||
TriClass::Opaque => &mut self.opaque,
|
||||
TriClass::Glass => &mut self.glass,
|
||||
@@ -704,6 +771,7 @@ impl BlockBuilder {
|
||||
pub fn freeze(self) -> Arc<BlockBytes> {
|
||||
Arc::new(BlockBytes {
|
||||
vertices: Arc::new(self.vertices),
|
||||
bodies: Arc::new(self.bodies),
|
||||
opaque: Arc::new(self.opaque),
|
||||
glass: Arc::new(self.glass),
|
||||
faded: Arc::new(self.faded),
|
||||
@@ -1210,6 +1278,9 @@ struct BlockGpu {
|
||||
faded: Option<ClassGpu>,
|
||||
lines: Option<Batch>,
|
||||
hidden: Option<Batch>,
|
||||
/// The runs of each class (opaque, glass, faded) without the bodies out of the view, while
|
||||
/// some are ([`Batches::cull`]); `None`: every body is drawn.
|
||||
culled: Option<[Vec<std::ops::Range<u32>>; 3]>,
|
||||
}
|
||||
|
||||
fn class_gpu(
|
||||
@@ -1281,7 +1352,7 @@ impl BlockGpu {
|
||||
};
|
||||
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 }
|
||||
BlockGpu { bytes, vertices, opaque, glass, faded, lines, hidden, culled: None }
|
||||
}
|
||||
|
||||
fn class(&self, class: TriClass) -> Option<&ClassGpu> {
|
||||
@@ -1298,6 +1369,7 @@ impl BlockGpu {
|
||||
Some(ClassGpu::Runs(runs)) => {
|
||||
let Some(vertices) = &self.vertices else { return };
|
||||
pass.set_vertex_buffer(0, vertices.slice(..));
|
||||
let runs = self.culled.as_ref().map_or(&runs[..], |c| &c[class as usize][..]);
|
||||
for r in runs.iter() {
|
||||
pass.draw(r.clone(), 0..1);
|
||||
tally.triangles(r.len() as u32, 1);
|
||||
@@ -1492,6 +1564,8 @@ struct Batches {
|
||||
/// The glass triangles as built, and the view direction they were last sorted for.
|
||||
glass_cpu: Vec<u8>,
|
||||
glass_sorted_for: Option<[f32; 3]>,
|
||||
/// The view the blocks' bodies were last culled for ([`Batches::cull`]).
|
||||
blocks_culled_for: Option<[[f32; 4]; 4]>,
|
||||
lines: Option<Batch>,
|
||||
hidden: Option<Batch>,
|
||||
overlays: Option<Batch>,
|
||||
@@ -1618,6 +1692,7 @@ impl Batches {
|
||||
self.glass_from = sc.glass.is_empty().then_some(from);
|
||||
}
|
||||
self.uploads.geometry += geometry;
|
||||
self.blocks_culled_for = None;
|
||||
self.key = Some(key);
|
||||
}
|
||||
}
|
||||
@@ -1664,6 +1739,23 @@ impl Batches {
|
||||
out
|
||||
}
|
||||
|
||||
/// Leave the blocks' bodies that are out of the view `vp` out of their draws: each class's
|
||||
/// runs without those bodies' vertices. Worked out again only when the view changes; a block
|
||||
/// with every body in view draws its runs as they are.
|
||||
fn cull_blocks(&mut self, vp: &[[f32; 4]; 4]) {
|
||||
if self.blocks_culled_for.as_ref() == Some(vp) {
|
||||
return;
|
||||
}
|
||||
self.blocks_culled_for = Some(*vp);
|
||||
const ROWS: [[f32; 4]; 3] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
|
||||
for block in self.blocks.values_mut() {
|
||||
let hidden: Vec<std::ops::Range<u32>> =
|
||||
block.bytes.bodies.iter().filter(|b| !placed_box_in_view(&ROWS, &b.bounds, vp)).map(|b| b.vertices.clone()).collect();
|
||||
block.culled = (!hidden.is_empty())
|
||||
.then(|| [TriClass::Opaque, TriClass::Glass, TriClass::Faded].map(|class| runs_without(block.bytes.runs(class), &hidden)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep only the placements of the instanced meshes that may be seen in the view `vp` (see
|
||||
/// [`placed_box_in_view`]): a part placed many times, most of it out of the view, draws
|
||||
/// only what is in it. The placements are written again only when that set changes.
|
||||
@@ -1671,6 +1763,7 @@ impl Batches {
|
||||
/// [`LOD_PX`] where it is drawn ([`placement_scale`], [`level_for`]), in a view of `size`
|
||||
/// pixels.
|
||||
fn cull(&mut self, queue: &wgpu::Queue, vp: &[[f32; 4]; 4], size: [f32; 2]) {
|
||||
self.cull_blocks(vp);
|
||||
let f = |b: &[u8], i: usize| b.get(i..i + 4).and_then(|x| x.try_into().ok()).map_or(0.0, f32::from_le_bytes);
|
||||
for d in &mut self.instanced {
|
||||
let errors: Vec<f32> = d.levels.iter().map(|l| l.error).collect();
|
||||
@@ -3902,6 +3995,20 @@ mod glass_tests {
|
||||
assert!(buffer_chunk(TRI_SIZE, 1) >= TRI_SIZE * 6, "a tiny limit still holds one unit");
|
||||
}
|
||||
|
||||
/// Bodies out of the view are cut out of a class's runs, wherever they fall in them: inside
|
||||
/// a run, over its ends, across two runs, or not at all.
|
||||
#[test]
|
||||
fn runs_without_hidden_bodies() {
|
||||
let r = |v: &[(u32, u32)]| v.iter().map(|&(a, b)| a..b).collect::<Vec<_>>();
|
||||
let cut = |runs: &[(u32, u32)], hidden: &[(u32, u32)]| runs_without(&r(runs), &r(hidden));
|
||||
assert_eq!(cut(&[(0, 30)], &[(9, 18)]), r(&[(0, 9), (18, 30)]));
|
||||
assert_eq!(cut(&[(0, 9), (12, 30)], &[(6, 15)]), r(&[(0, 6), (15, 30)]));
|
||||
assert_eq!(cut(&[(0, 9), (12, 30)], &[(0, 9), (27, 30)]), r(&[(12, 27)]));
|
||||
assert_eq!(cut(&[(3, 6)], &[(0, 3), (6, 9)]), r(&[(3, 6)]));
|
||||
assert_eq!(cut(&[(0, 30)], &[(0, 30)]), r(&[]));
|
||||
assert_eq!(cut(&[(0, 12), (15, 24)], &[]), r(&[(0, 12), (15, 24)]));
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -527,3 +527,47 @@ fn step_file_cost() {
|
||||
}
|
||||
println!("{line}");
|
||||
}
|
||||
|
||||
/// Zoomed onto one part of an assembly, as when editing it: the GPU frame and the triangles
|
||||
/// drawn, against the whole assembly in view. Bodies out of the view are left out of their
|
||||
/// blocks' draws. Skipped without a GPU adapter. Run with `--ignored --nocapture`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
#[ignore = "manual culling measurement"]
|
||||
fn zoomed_view_frame_cost() {
|
||||
const SIZE: u32 = 1024;
|
||||
let Some(mut frames) = crate::gpu::OffscreenFrames::new(SIZE, false) else {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
return;
|
||||
};
|
||||
let mut h = assembly(300, 500);
|
||||
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 none: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let still = |h: &Harness, frames: &mut crate::gpu::OffscreenFrames| {
|
||||
frames.frame(view_frame(&h.app, SIZE, (7, &model), (0, &none)));
|
||||
let mut t: Vec<f64> = (0..7).map(|_| frames.frame(view_frame(&h.app, SIZE, (7, &model), (0, &none)))).collect();
|
||||
t.sort_by(f64::total_cmp);
|
||||
(t[3], frames.stats().triangles)
|
||||
};
|
||||
let (whole, whole_tris) = still(&h, &mut frames);
|
||||
let st = h.app.session.world_state();
|
||||
let b = st.bodies.iter().find(|b| b.component == 0).unwrap().mesh().bounds();
|
||||
drop(st);
|
||||
h.app.cam.target = b.center();
|
||||
h.app.cam.distance = b.diagonal() * 1.5;
|
||||
let (zoomed, zoomed_tris) = still(&h, &mut frames);
|
||||
// Orbiting: a new view every frame, so the bodies are culled again each time.
|
||||
let mut t: Vec<f64> = (0..21)
|
||||
.map(|i| {
|
||||
h.app.cam.yaw += 0.01 * f64::from(i);
|
||||
frames.frame(view_frame(&h.app, SIZE, (7, &model), (0, &none)))
|
||||
})
|
||||
.collect();
|
||||
t.sort_by(f64::total_cmp);
|
||||
let orbit = t[10];
|
||||
println!(
|
||||
"ZOOMED whole_ms={whole:.2} whole_triangles={whole_tris} zoomed_ms={zoomed:.2} zoomed_triangles={zoomed_tris} zoomed_orbit_ms={orbit:.2}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1025,7 +1025,10 @@ fn build_block(draws: &[BodyDraw], shaded: bool, build: &impl Fn(&BodyDraw, &mut
|
||||
let mut spans = Vec::with_capacity(draws.len());
|
||||
for d in draws {
|
||||
let v0 = builder.vertices_len();
|
||||
// Its box goes with its triangles, so a view without it leaves them out.
|
||||
builder.begin_body();
|
||||
build(d, &mut builder);
|
||||
builder.end_body();
|
||||
spans.push(at(v0)..at(builder.vertices_len()));
|
||||
}
|
||||
let ranges = draws
|
||||
@@ -1079,6 +1082,7 @@ fn reindex_block(block: CachedBlock, draws: &[BodyDraw]) -> CachedBlock {
|
||||
let old = block.bytes;
|
||||
let bytes = std::sync::Arc::new(crate::gpu::BlockBytes {
|
||||
vertices: old.vertices.clone(),
|
||||
bodies: old.bodies.clone(),
|
||||
opaque: std::sync::Arc::new(opaque),
|
||||
glass: std::sync::Arc::new(glass),
|
||||
faded: std::sync::Arc::new(faded),
|
||||
|
||||
@@ -267,6 +267,41 @@ fn appearance_edits_upload_palette_rows_only() {
|
||||
assert!(glass.palette > 0, "it writes the palette: {glass:?}");
|
||||
}
|
||||
|
||||
/// A body out of the view is left out of its block's draws: two boxes far apart, drawn with
|
||||
/// both in view and then with the camera on one of them, draw half the triangles. Skipped
|
||||
/// without a GPU adapter.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn bodies_out_of_the_view_are_not_drawn() {
|
||||
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 = frames.target();
|
||||
app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 0], "operation": "new"})).unwrap();
|
||||
app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [1000, 0, 0], "operation": "new"})).unwrap();
|
||||
app.fit_view();
|
||||
let scene = build_scene(&app);
|
||||
let spans: usize = scene.blocks.iter().map(|b| b.bytes.bodies.len()).sum();
|
||||
assert_eq!(spans, 2, "each body's box is kept with its block");
|
||||
let slot: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(scene)));
|
||||
let none: crate::gpu::SceneSlot = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
frames.frame(crate::scale_tests::view_frame(&app, SIZE, (1, &slot), (0, &none)));
|
||||
let both = frames.stats().triangles;
|
||||
assert_eq!(both, 24, "both boxes in view");
|
||||
app.cam.target = solidcraft_engine::geom::Vec3::new(5.0, 5.0, 5.0);
|
||||
app.cam.distance = 40.0;
|
||||
frames.frame(crate::scale_tests::view_frame(&app, SIZE, (1, &slot), (0, &none)));
|
||||
assert_eq!(frames.stats().triangles, 12, "the far box is not drawn");
|
||||
app.fit_view();
|
||||
frames.frame(crate::scale_tests::view_frame(&app, SIZE, (1, &slot), (0, &none)));
|
||||
assert_eq!(frames.stats().triangles, both, "and drawn again once in view");
|
||||
}
|
||||
|
||||
/// Exercise the live GPU scene slots: a fresh headless render always rebuilds and would hide
|
||||
/// stale cached geometry. Theme changes must update bytes while retaining the model's mesh.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user