Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Headless pictures: draw counts come back with the picture they count (#7521) (#7522)

JK3D8a6a064d374f
diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs
index e7626e7e8e..c67cfd2992 100644
--- a/crates/gpu/src/capture.rs
+++ b/crates/gpu/src/capture.rs
@@ -15,7 +15,7 @@ use solidcraft_geom::Vec3;
use solidcraft_render::{AnalysisMode, Camera, Rgb, SECTION_CAP, Scene};
use wgpu::util::DeviceExt;
-use crate::view::{AccessMap, Frame, GpuScene, GpuTarget, Renderer, analysis_colors, analysis_uniform};
+use crate::view::{AccessMap, DrawStats, Frame, GpuScene, GpuTarget, Renderer, analysis_colors, analysis_uniform};
use crate::{GpuError, Result, caught, error_scopes};
/// The colour format pictures are drawn in: sRGB bytes as they are, like the viewport's usual
@@ -176,6 +176,17 @@ impl Capturer {
/// [`Capturer::rgba`] with `highlight` drawn as the viewport draws its highlight scene
/// (selection and hover feedback), over the model scene.
pub fn rgba_highlighted(&self, scene: &Scene, highlight: Option<GpuScene>, cam: &Camera, width: u32, height: u32) -> Result<Vec<u8>> {
+ self.draw(scene, highlight, cam, width, height).map(|(rgba, _)| rgba)
+ }
+
+ /// [`Capturer::rgba`] and what the picture drew ([`DrawStats`]). Both come from the same
+ /// turn on the device, so another thread's picture can't put its counts in their place.
+ pub fn rgba_with_stats(&self, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result<(Vec<u8>, DrawStats)> {
+ self.draw(scene, None, cam, width, height)
+ }
+
+ /// The picture and what it drew, both read while this call has the device to itself.
+ fn draw(&self, scene: &Scene, highlight: Option<GpuScene>, cam: &Camera, width: u32, height: u32) -> Result<(Vec<u8>, DrawStats)> {
if !(1..=self.max_side).contains(&width) || !(1..=self.max_side).contains(&height) {
return Err(GpuError::Render(format!("a picture is 1 to {} pixels a side, not {width} × {height}", self.max_side)));
}
@@ -288,11 +299,7 @@ impl Capturer {
device
.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(TIMEOUT) })
.map_err(|e| GpuError::Render(format!("waiting for the picture: {e}")))?;
- match rx.try_recv() {
- Ok(Ok(())) => {}
- Ok(Err(e)) => return Err(GpuError::Render(format!("reading the picture back: {e}"))),
- Err(_) => return Err(GpuError::Unsupported("reading a picture back without waiting for the browser".into())),
- }
+ read_back(&rx)?;
let data = slice.get_mapped_range().map_err(|e| GpuError::Render(format!("reading the picture back: {e}")))?;
let mut rgba = Vec::with_capacity((row as usize) * (height as usize));
for r in data.chunks(padded as usize).take(height as usize) {
@@ -301,13 +308,8 @@ impl Capturer {
if rgba.len() != (row as usize) * (height as usize) {
return Err(GpuError::Render("the picture read back short".into()));
}
- Ok(rgba)
- }
-
- /// What the last picture drew ([`crate::view::DrawStats`]).
- pub fn last_stats(&self) -> crate::view::DrawStats {
- let Ok(state) = self.state.lock() else { return Default::default() };
- state.renderer.stats().lock().map(|s| *s).unwrap_or_default()
+ let stats = state.renderer.stats().lock().map(|s| *s).unwrap_or_default();
+ Ok((rgba, stats))
}
/// [`Capturer::rgba`] as PNG bytes.
@@ -464,6 +466,19 @@ fn watch_lost(device: &wgpu::Device) -> Arc<AtomicBool> {
lost
}
+/// The answer to a picture's read-back, once the wait for its submission is over. The read-back
+/// is ready by then, but its answer may still be on its way: any other submit or poll on the
+/// device (the window's frames, another picture's device check) can pick it up and answer it on
+/// its own thread once it lets go of the device. So a native picture waits for the answer; a
+/// browser answers later, on its own, and a picture can't wait for it there.
+fn read_back(answer: &std::sync::mpsc::Receiver<std::result::Result<(), wgpu::BufferAsyncError>>) -> Result<()> {
+ #[cfg(not(target_arch = "wasm32"))]
+ let answer = answer.recv_timeout(TIMEOUT).map_err(|e| GpuError::Render(format!("reading the picture back: {e}")))?;
+ #[cfg(target_arch = "wasm32")]
+ let answer = answer.try_recv().map_err(|_| GpuError::Unsupported("reading a picture back without waiting for the browser".into()))?;
+ answer.map_err(|e| GpuError::Render(format!("reading the picture back: {e}")))
+}
+
/// The background gradient: the viewport's top colour at the top, its bottom one at the bottom,
/// mixed in sRGB as the window paints it.
const BACKGROUND_SHADER: &str = r#"
diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rs
index 130982d381..03927f4ba4 100644
--- a/crates/gpu/tests/capture.rs
+++ b/crates/gpu/tests/capture.rs
@@ -105,8 +105,8 @@ fn the_renderer_counts_what_it_draws() {
let cam = view::home_camera(s);
let scene = view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false });
let triangles: usize = scene.meshes.iter().map(|m| m.mesh.triangles.len()).sum();
- c.rgba(&scene, &cam, 160, 100).unwrap();
- (c.last_stats(), triangles as u64)
+ let (_, stats) = c.rgba_with_stats(&scene, &cam, 160, 100).unwrap();
+ (stats, triangles as u64)
};
let (empty, _) = drawn(&Session::default());
assert_eq!((empty.triangles, empty.line_segments), (0, 0), "{empty:?}");
@@ -121,6 +121,32 @@ fn the_renderer_counts_what_it_draws() {
assert!(two.line_segments > one.line_segments, "{two:?}");
}
+/// Each picture's counts are its own while other threads draw on the same capturer: an empty
+/// design never reports another thread's box, and a box never reports an empty design's
+/// nothing. The counts were once read in a second call after the picture, and another thread's
+/// picture could land in between.
+#[test]
+fn pictures_drawn_at_once_each_count_their_own() {
+ let Some(c) = capturer() else { return };
+ let scene = |s: &Session| {
+ let cam = view::home_camera(s);
+ (view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false }), cam)
+ };
+ let empty = scene(&Session::default());
+ let solid = scene(&session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]));
+ std::thread::scope(|t| {
+ for k in 0..8 {
+ let (name, (sc, cam), drawn) = if k % 2 == 0 { ("empty", &empty, false) } else { ("box", &solid, true) };
+ t.spawn(move || {
+ for i in 0..50 {
+ let (_, stats) = c.rgba_with_stats(sc, cam, 64, 48).unwrap();
+ assert_eq!(stats.triangles > 0, drawn, "{name}, picture {i}: {stats:?}");
+ }
+ });
+ }
+ });
+}
+
/// The ground grid and the origin's axes each change the picture.
#[test]
fn guides_change_the_picture() {
@@ -318,5 +344,44 @@ fn bad_picture_sizes_are_errors() {
assert!(c.rgba(&sc, &Camera::default(), w, h).is_err(), "{w} x {h}");
}
// And the device still draws.
- assert!(c.rgba(&sc, &Camera::default(), 8, 8).is_ok());
+ let drawn = c.rgba(&sc, &Camera::default(), 8, 8);
+ assert!(drawn.is_ok(), "{:?}", drawn.err());
+}
+
+/// Pictures read back while another thread uses their device: the app's window submits its
+/// frames on the device its thumbnails and `ui.render` pictures are drawn on, and on the shared
+/// capturer every picture checks its device while another one reads back. Any submit or poll can
+/// take a picture's finished read-back and answer it on its own thread a moment after the
+/// picture's wait is over; the picture used to give up then ("reading a picture back without
+/// waiting for the browser", now and then in this binary's other tests).
+#[test]
+fn pictures_read_back_while_another_thread_uses_the_device() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ let policy = solidcraft_gpu::select::Policy::from_env().unwrap();
+ let Some((adapter, _)) = solidcraft_gpu::select::pick(policy) else {
+ assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "no GPU adapter under the {} policy", policy.name());
+ eprintln!("skipping: no GPU adapter under the {} policy", policy.name());
+ return;
+ };
+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
+ required_features: solidcraft_gpu::depth_features(&adapter),
+ required_limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()),
+ ..Default::default()
+ }))
+ .unwrap();
+ let c = Capturer::new(&adapter, device.clone(), queue).unwrap();
+ let sc = solidcraft_engine::render::Scene::default();
+ const PICTURES: usize = 2000;
+ let done = AtomicBool::new(false);
+ let failed: Vec<String> = std::thread::scope(|t| {
+ t.spawn(|| {
+ while !done.load(Ordering::Relaxed) {
+ let _ = device.poll(wgpu::PollType::Poll);
+ }
+ });
+ let failed = (0..PICTURES).filter_map(|i| c.rgba(&sc, &Camera::default(), 8, 8).err().map(|e| format!("picture {i}: {e}"))).collect();
+ done.store(true, Ordering::Relaxed);
+ failed
+ });
+ assert!(failed.is_empty(), "{} of {PICTURES} pictures failed, the first: {:?}", failed.len(), failed.first());
}