Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ The [architecture page](docs/architecture.md) has the layer table. The short ver
- Non-test code never uses `unwrap`, `expect`, `panic!` or indexing on input-derived data.
There's no `unsafe` outside `apps/solidcraft/src/open_documents.rs` (macOS file-open events),
`apps/solidcraft/src/native_crash.rs` (Windows native crash capture) and
`crates/threedx-client/src/macos.rs` (the 3Dconnexion driver's client API on macOS), and the
`crates/threedx-client/src/macos.rs` (the 3Dconnexion driver's client API on macOS) and
`crates/gpu-native/src/pipeline_cache.rs` (the persistent GPU pipeline cache, #3236), and the
compiler denies it.
- An unsupported case returns an error ("not supported yet: …"); it never panics.
- Every call into truck goes through `solidcraft_kernel::guard`.
Expand Down
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ solidcraft-sketch = { path = "crates/sketch" }
solidcraft-kernel = { path = "crates/kernel" }
solidcraft-render = { path = "crates/render" }
solidcraft-gpu = { path = "crates/gpu" }
solidcraft-gpu-native = { path = "crates/gpu-native" }
solidcraft-doc = { path = "crates/doc" }
solidcraft-io = { path = "crates/io" }
solidcraft-engine = { path = "crates/engine" }
Expand Down
21 changes: 21 additions & 0 deletions crates/gpu-native/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[package]
name = "solidcraft-gpu-native"
description = "SolidCraft's native-only wgpu calls that wgpu marks unsafe (the persistent pipeline cache), kept out of solidcraft-gpu, which forbids unsafe code"
version.workspace = true
edition.workspace = true
license.workspace = true

# The workspace lints, except unsafe_code: denied, not forbidden, so that src/pipeline_cache.rs can
# allow it (#3236). Keep the rest in sync with [workspace.lints].
[lints.rust]
unsafe_code = "deny"

[lints.clippy]
dbg_macro = "warn"
todo = "warn"
too_many_arguments = "allow"
type_complexity = "allow"
neg_cmp_op_on_partial_ord = "allow"

[dependencies]
wgpu = { workspace = true }
9 changes: 9 additions & 0 deletions crates/gpu-native/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//! wgpu calls that wgpu marks `unsafe` although SolidCraft can meet their contract, kept out of
//! `solidcraft-gpu`, which forbids unsafe code (#3236). Native only: nothing here builds for the
//! browser. Each call lives in one module that allows `unsafe_code` and states its contract.
#![deny(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]

mod pipeline_cache;

pub use pipeline_cache::pipeline_cache;
22 changes: 22 additions & 0 deletions crates/gpu-native/src/pipeline_cache.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! A pipeline cache seeded with data from an earlier run (#3433).
//!
//! `Device::create_pipeline_cache` is `unsafe` because wgpu cannot prove that seed data came from
//! `PipelineCache::get_data`. wgpu checks its own header (format version, backend, adapter and
//! driver) and, with `fallback`, starts empty when that doesn't match; it does not check the
//! data itself. The caller (`solidcraft_gpu::shader_cache`) only passes data it wrote itself from
//! `get_data`, behind a SHA-256 of the data that it checks first, so corrupted or truncated files
//! never reach the driver.
#![allow(unsafe_code)]

/// A pipeline cache for `device`, seeded with `data` that an earlier run's
/// [`wgpu::PipelineCache::get_data`] returned; `None` when the device lacks
/// [`wgpu::Features::PIPELINE_CACHE`].
pub fn pipeline_cache(device: &wgpu::Device, label: &str, data: Option<&[u8]>) -> Option<wgpu::PipelineCache> {
if !device.features().contains(wgpu::Features::PIPELINE_CACHE) {
return None;
}
// SAFETY: `data` is `get_data` output written by this program and verified against its
// checksum by the caller (see the module documentation); `fallback: true` makes wgpu start
// an empty cache instead of failing when the data is for another adapter, driver or format.
Some(unsafe { device.create_pipeline_cache(&wgpu::PipelineCacheDescriptor { label: Some(label), data, fallback: true }) })
}
3 changes: 3 additions & 0 deletions crates/gpu/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ robust = { workspace = true }
pollster = { workspace = true }
# Native backends, so tests and the CLI can open a device without a window.
wgpu = { workspace = true, features = ["metal", "vulkan", "dx12", "gles"] }
# The persistent pipeline cache (src/shader_cache.rs): wgpu's unsafe call, and the file checksum.
solidcraft-gpu-native = { workspace = true }
sha2 = { workspace = true }

[dev-dependencies]
image = { workspace = true }
Expand Down
2 changes: 2 additions & 0 deletions crates/gpu/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub mod path;
mod pbr;
#[cfg(not(target_arch = "wasm32"))]
pub mod select;
#[cfg(not(target_arch = "wasm32"))]
pub mod shader_cache;
pub mod view;

/// The tessellation compute shader (WGSL).
Expand Down
7 changes: 5 additions & 2 deletions crates/gpu/src/path/denoise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl Pipelines {
module: &guide_shader,
entry_point: Some("denoise_guides"),
compilation_options: Default::default(),
cache: None,
cache: context.cache.as_ref().map(crate::shader_cache::ShaderCache::get),
});
let entries: Vec<_> = (0..4)
.map(|binding| wgpu::BindGroupLayoutEntry {
Expand Down Expand Up @@ -64,11 +64,14 @@ impl Pipelines {
module: &shader,
entry_point: Some("atrous"),
compilation_options: Default::default(),
cache: None,
cache: context.cache.as_ref().map(crate::shader_cache::ShaderCache::get),
});
checked(error_scopes)?;
warm_up(device, &context.queue, &guide, &placeholder_bind(device, &context.layout, 7)?, &context.healthy)?;
warm_up(device, &context.queue, &filter, &placeholder_bind(device, &filter_layout, 4)?, &context.healthy)?;
if let Some(cache) = &context.cache {
cache.save();
}
Ok(Self { guide, filter, filter_layout })
}

Expand Down
4 changes: 2 additions & 2 deletions crates/gpu/src/path/denoise_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ fn f64_atrous_preserves_body_normal_depth_and_albedo_edges() {
}
}
fn context() -> Option<Arc<Context>> {
let (_, device, queue) = match open_headless() {
let (adapter, device, queue) = match open_headless() {
Ok(v) => v,
Err(e) => {
// The path tracer runs on Vulkan or Metal only: where the backends in use leave both out
Expand All @@ -151,7 +151,7 @@ fn context() -> Option<Arc<Context>> {
return None;
}
};
Some(Executor::new(device, queue).unwrap().context)
Some(Executor::new(device, queue, &adapter.get_info()).unwrap().context)
}
fn request(size: u32) -> ImageRequest {
let mut camera = Camera { distance: 4.0, ..Default::default() };
Expand Down
21 changes: 14 additions & 7 deletions crates/gpu/src/path/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ fn checked_creation<T>(device: &wgpu::Device, create: impl FnOnce() -> Result<T>
pub fn host() -> Result<ImageHost> {
let (adapter, device, queue) = open_headless()?;
log::info!("gpu-path adapter: {} ({:?})", adapter.get_info().name, adapter.get_info().device_type);
ImageHost::with_executor(Arc::new(Executor::new(device, queue)?))
ImageHost::with_executor(Arc::new(Executor::new(device, queue, &adapter.get_info())?))
}

/// Open an independent job device on the viewport's selected adapter. In particular,
Expand All @@ -108,13 +108,14 @@ pub fn host_on_adapter(adapter: &wgpu::Adapter) -> Result<ImageHost> {
if !matches!(info.backend, wgpu::Backend::Vulkan | wgpu::Backend::Metal) {
let (picked, _) = crate::select::pick_path(policy, |i| i.vendor == info.vendor && i.device == info.device)
.ok_or_else(|| gpu(format!("{VULKAN_ONLY}; the viewport uses {:?}", info.backend)))?;
let picked_info = picked.get_info();
let (device, queue) = open_device(&picked)?;
log::info!("gpu-path viewport GPU: {} through Vulkan or Metal", info.name);
return ImageHost::with_executor(Arc::new(Executor::new(device, queue)?));
return ImageHost::with_executor(Arc::new(Executor::new(device, queue, &picked_info)?));
}
let (device, queue) = open_device(adapter)?;
log::info!("gpu-path viewport adapter: {} ({:?})", info.name, info.device_type);
ImageHost::with_executor(Arc::new(Executor::new(device, queue)?))
ImageHost::with_executor(Arc::new(Executor::new(device, queue, &info)?))
}

// D3D12 shader compilation is avoided; the user can select a CPU image method instead.
Expand Down Expand Up @@ -147,7 +148,7 @@ fn open_device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue)> {
let required_limits = device_limits(adapter.limits())?;
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("solidcraft progressive path"),
required_features: crate::depth_features(adapter),
required_features: crate::depth_features(adapter) | (adapter.features() & wgpu::Features::PIPELINE_CACHE),
required_limits,
..Default::default()
}))
Expand All @@ -166,6 +167,8 @@ struct Context {
device: wgpu::Device,
queue: wgpu::Queue,
pipeline: wgpu::ComputePipeline,
// Compiled pipelines kept between runs, where the backend has a pipeline cache (#3433).
cache: Option<crate::shader_cache::ShaderCache>,
// Built and warmed by the first denoised job, then shared by later ones.
denoise: std::sync::OnceLock<denoise::Pipelines>,
layout: wgpu::BindGroupLayout,
Expand Down Expand Up @@ -204,8 +207,9 @@ struct Executor {
context: Arc<Context>,
}
impl Executor {
fn new(device: wgpu::Device, queue: wgpu::Queue) -> Result<Self> {
fn new(device: wgpu::Device, queue: wgpu::Queue, adapter: &wgpu::AdapterInfo) -> Result<Self> {
device_limits(device.limits())?;
let cache = crate::shader_cache::ShaderCache::open(&device, adapter, "gpu-path");
let healthy = Arc::new(AtomicBool::new(true));
let uncaptured = healthy.clone();
device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| {
Expand Down Expand Up @@ -248,11 +252,14 @@ impl Executor {
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
cache: cache.as_ref().map(crate::shader_cache::ShaderCache::get),
});
checked(scopes)?;
warm_up(&device, &queue, &pipeline, &placeholder_bind(&device, &layout, 7)?, &healthy)?;
Ok(Self { context: Arc::new(Context { healthy, device, queue, pipeline, layout, denoise: std::sync::OnceLock::new() }) })
if let Some(cache) = &cache {
cache.save();
}
Ok(Self { context: Arc::new(Context { healthy, device, queue, pipeline, layout, cache, denoise: std::sync::OnceLock::new() }) })
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/gpu/src/path/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn executor() -> Option<Executor> {
}
};
eprintln!("gpu-path tests on {} ({:?}, {:?})", adapter.get_info().name, adapter.get_info().device_type, adapter.get_info().backend);
Some(Executor::new(device, queue).unwrap())
Some(Executor::new(device, queue, &adapter.get_info()).unwrap())
}
fn request(size: u32) -> ImageRequest {
let mut camera = Camera { distance: 4.0, ..Default::default() };
Expand Down
Loading
Loading