Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Issue #136: a non-waiting GPU query starts the device; Settings repaints while it starts

OneSlips9a6ac9aea7ea
diff --git a/Cargo.lock b/Cargo.lock
index 78de058c3..60b893afe 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3141,6 +3141,7 @@ dependencies = [
"lightcraft-merge",
"lightcraft-raster",
"lightcraft-sysmem",
+ "lightcraft-testkit",
"lightcraft-ui-egui",
"serde_json",
]
diff --git a/apps/lightcraft-cli/Cargo.toml b/apps/lightcraft-cli/Cargo.toml
index b82aca1d5..e55d458b3 100644
--- a/apps/lightcraft-cli/Cargo.toml
+++ b/apps/lightcraft-cli/Cargo.toml
@@ -25,6 +25,9 @@ lightcraft-merge = { workspace = true }
serde_json = { workspace = true }
dhat = { workspace = true, optional = true }
+[dev-dependencies]
+lightcraft-testkit = { workspace = true }
+
[features]
default = ["denoise"]
denoise = ["lightcraft-engine/denoise"]
diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs
index 78ee42561..4ea499cf1 100644
--- a/apps/lightcraft-cli/tests/it/cli.rs
+++ b/apps/lightcraft-cli/tests/it/cli.rs
@@ -466,6 +466,41 @@ fn snapshot_defaults_to_cpu_without_gpu_environment_overrides() {
assert_eq!((decoded.width, decoded.height), (480, 320));
}
+/// Issue #136: `app.gpu {enabled: true, wait: false}` (what the UI sends on its first frame) answers
+/// at once while the device is still being created: enabled, and nothing known yet (`null`), instead
+/// of waiting for the driver. It starts creating the device (off the calling thread), so this test
+/// touches the GPU driver and skips when the environment turns the GPU off.
+#[test]
+fn enabling_the_gpu_without_waiting_answers_before_the_device_exists() {
+ if std::env::var("LIGHTCRAFT_GPU").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")) {
+ lightcraft_testkit::skip!(Gpu, "LIGHTCRAFT_GPU=0: enabling the GPU starts creating a device");
+ return;
+ }
+ let script = tmp("gpu-starting.jsonl");
+ std::fs::write(
+ &script,
+ format!("{}\n", json!({"method": "engine.execute", "params": {"command": "app.gpu", "params": {"enabled": true, "wait": false}}})),
+ )
+ .unwrap();
+ let image = tmp("gpu-starting.png");
+ let output = Command::new(BIN)
+ .env_remove("LIGHTCRAFT_GPU")
+ .env_remove("LIGHTCRAFT_GPU_BACKEND")
+ .env_remove("WGPU_BACKEND")
+ .args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", image.to_str().unwrap(), "--size", "480x320"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "status {}: {}", output.status, String::from_utf8_lossy(&output.stderr));
+ let replies: Vec<Value> = String::from_utf8_lossy(&output.stdout).lines().map(|line| serde_json::from_str(line).unwrap()).collect();
+ assert_eq!(replies.len(), 1, "{replies:?}");
+ assert_eq!(replies[0]["ok"], true, "{replies:?}");
+ let gpu = &replies[0]["result"];
+ assert_eq!(gpu["enabled"], true, "{gpu}");
+ for field in ["available", "adapter", "reason"] {
+ assert_eq!(gpu[field], Value::Null, "{field} is not known while the device is created: {gpu}");
+ }
+}
+
/// Issue #136: with the GPU switched off from the environment the UI starts and renders on the CPU,
/// without creating a GPU device (no driver is loaded), and says why.
#[test]
diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs
index b50bc72a1..469253805 100644
--- a/crates/engine/src/cmd/query.rs
+++ b/crates/engine/src/cmd/query.rs
@@ -230,7 +230,7 @@ pub fn specs() -> Vec<CommandSpec> {
"versions": ph.versions.iter().map(|v| json!({"name": v.name, "created": v.created})).collect::<Vec<_>>(),
}))
}),
- cmd!(query "app.gpu", "GPU Rendering", [], None, "{enabled?: bool, wait?: bool} — allow/forbid GPU rendering (CPU fallback; LIGHTCRAFT_GPU=0 forbids it for the process); returns {enabled, available, adapter, reason (why the GPU is off), lastFallback (latest render redone on the CPU, and why)}. wait: false never waits for a device still being created (available, adapter and reason are then null; with GPU rendering off they say so at once)", always, |_, p| {
+ cmd!(query "app.gpu", "GPU Rendering", [], None, "{enabled?: bool, wait?: bool} — allow/forbid GPU rendering (CPU fallback; LIGHTCRAFT_GPU=0 forbids it for the process); returns {enabled, available, adapter, reason (why the GPU is off), lastFallback (latest render redone on the CPU, and why)}. wait: false never waits for a device still being created (available, adapter and reason are then null and the device is created in the background; with GPU rendering off they say so at once)", always, |_, p| {
if let Some(on) = p.get("enabled").and_then(Value::as_bool) {
lightcraft_gpu::set_enabled(on);
}
@@ -240,6 +240,11 @@ pub fn specs() -> Vec<CommandSpec> {
// off (preference, environment): known at once, and asking the adapter would
// create the device; on: still being created, so nothing is known yet
let on = lightcraft_gpu::enabled();
+ if on {
+ // a caller that never waits still gets an answer later (off the UI thread;
+ // starts at most once)
+ lightcraft_gpu::warm_up();
+ }
return Ok(json!({
"enabled": on,
"available": if on { Value::Null } else { Value::Bool(false) },
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 452e2dd67..58aa1d967 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -308,13 +308,24 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> {
/// Create the device and compile the kernels on a background thread now (once the window is up),
/// so the first render doesn't wait ~0.3–0.4 s for it and the UI thread never does. Does nothing
-/// while GPU rendering is turned off.
+/// while GPU rendering is turned off. Repeated calls start one thread at most.
pub fn warm_up() {
#[cfg(not(target_arch = "wasm32"))]
if !env_disabled() && ENABLED.load(Ordering::Relaxed) && GPU.get().is_none() {
- let _ = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(|| {
+ static STARTED: AtomicBool = AtomicBool::new(false);
+ if STARTED.swap(true, Ordering::AcqRel) {
+ return;
+ }
+ let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(|| {
let _ = device();
+ // turned off before the thread ran (nothing created): a later call may start again
+ if GPU.get().is_none() {
+ STARTED.store(false, Ordering::Release);
+ }
});
+ if spawned.is_err() {
+ STARTED.store(false, Ordering::Release);
+ }
}
}
diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs
index 95d09c306..555aa349c 100644
--- a/crates/ui-egui/src/panels/settings.rs
+++ b/crates/ui-egui/src/panels/settings.rs
@@ -588,6 +588,8 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
check(ui, "settings.gpu", &mut app.ui.settings.gpu, "Use the GPU for rendering");
// `available` would wait for a device still being created (issue #136)
let status = if gpu::enabled() && !gpu::ready() {
+ // the device is created on another thread, which doesn't wake the UI when it's done
+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(250));
"GPU: starting…".to_string()
} else if !gpu::available() {
match gpu::unavailable_reason() {