Render: progressive GPU path-tracing executor (#2067)

Land the unchanged contributor GPU foundation into render under the maintainer policy in #5493. Fresh quick gate 39993339605 passed. Original author and co-author attribution retained; no workflow file changes. Final render-to-main CI and jyviko sign-off remain separate.

Co-Authored-By: Christian Svensson <blue@cmd.nu>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Christian SvenssonandClaude Opus 5.5 authored and GitHub committed 2026-10-23 21:10:55 +02:00
1 parent 95a56ca00e
commit 30449418ac
33 files changed
+1964 -93

No files matched your search

+2
View File
@@ -18,6 +18,8 @@ Editable drawing code, native projects and shipped exports are collected under `
| examples/material-card.json | SolidCraft contributors | original analytic box and explicitly synthetic engineering card; invented illustrative constants, no external material dataset | MIT OR Apache-2.0 |
| examples/render-studio.json | SolidCraft contributors | original procedural box/cylinder enclosure script for the integrated Render workspace | MIT OR Apache-2.0 |
| examples/render-opaque-studio.json | SolidCraft contributors | original procedural sphere study varying opaque metal fraction and roughness independently; no external assets or engineering data | MIT OR Apache-2.0 |
| examples/render-path-studio.json | SolidCraft contributors | original procedural opaque enclosure, teal insert and metal fasteners for progressive rendering; no imported models | MIT OR Apache-2.0 |
| crates/gpu/src/path/path.wgsl | SolidCraft contributors | original software BVH traversal and path integration using the existing SolidCraft surface/studio equations; no external shader source | MIT OR Apache-2.0 |
| crates/gpu/src/pbr.rs | SolidCraft contributors | original WGSL translation of SolidCraft's opaque surface and fixed studio reference, embedded as Rust source; no external shader code | MIT OR Apache-2.0 |
| assets/icons/app/macos/source/SolidCraft.icon/icon.json | SolidCraft contributors | approved Icon Composer composition and appearance settings for the original SolidCraft artwork | MIT OR Apache-2.0 |
| assets/icons/app/macos/source/SolidCraft.icon/Assets/02-grid.svg | SolidCraft contributors | original perspective grid with elliptical radial alpha, exported from VectorCraft | MIT OR Apache-2.0 |
+1
View File
@@ -71,6 +71,7 @@ const USAGE: &str = "usage:
--section: cut the model as inspect.section does, so the inside shows: z=27 (the plane through that world
coordinate, keeping the smaller side), add ,flip to keep the other side, or XY, XZ, YZ, or its own JSON)
solidcraft-cli render <script|design> --out image.png [--setup NAME] [--width W] [--height H] [--transparent] [--overwrite] [--timeout SECONDS]
[--progressive] [--samples N] [--max-depth N] [--seed N] [--exposure EV]
solidcraft-cli exec <command> [json-params]
solidcraft-cli commands
solidcraft-cli recipe <recipe.json>
+18 -2
View File
@@ -11,15 +11,21 @@ pub fn run(args: &[String]) -> Result<(), String> {
let mut setup = None;
let mut width = None;
let mut height = None;
let mut progressive = false;
let mut samples = None;
let mut max_depth = None;
let mut seed = None;
let mut exposure = None;
let mut transparent = false;
let mut overwrite = false;
let mut timeout = 120u64;
let mut i = 1;
while let Some(arg) = args.get(i) {
match arg.as_str() {
"--progressive" => progressive = true,
"--transparent" => transparent = true,
"--overwrite" => overwrite = true,
"--out" | "--setup" | "--width" | "--height" | "--timeout" => {
"--out" | "--setup" | "--width" | "--height" | "--timeout" | "--samples" | "--max-depth" | "--seed" | "--exposure" => {
i += 1;
let value = args.get(i).ok_or_else(|| format!("missing value for {arg}"))?;
match arg.as_str() {
@@ -27,6 +33,10 @@ pub fn run(args: &[String]) -> Result<(), String> {
"--setup" => setup = Some(value.clone()),
"--width" => width = Some(value.parse::<u32>().map_err(|_| "invalid width")?),
"--height" => height = Some(value.parse::<u32>().map_err(|_| "invalid height")?),
"--samples" => samples = Some(value.parse::<u32>().map_err(|_| "invalid samples")?),
"--max-depth" => max_depth = Some(value.parse::<u32>().map_err(|_| "invalid depth")?),
"--seed" => seed = Some(value.parse::<u32>().map_err(|_| "invalid seed")?),
"--exposure" => exposure = Some(value.parse::<f64>().map_err(|_| "invalid exposure")?),
_ => timeout = value.parse::<u64>().map_err(|_| "invalid timeout")?,
}
}
@@ -40,6 +50,9 @@ pub fn run(args: &[String]) -> Result<(), String> {
let out = out.ok_or("render requires --out FILE.png")?;
let mut session = crate::load(input)?;
session.set_render_job_host(Some(CpuHost::for_platform().map_err(|e| e.to_string())?)).map_err(|e| e.to_string())?;
if progressive {
session.register_render_job_host(solidcraft_gpu::path::host().map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
}
session.execute("render.scene", &json!({})).map_err(|e| e.to_string())?;
let mut settings = if let Some(name) = setup {
session.doc.render.setups.get(&name).cloned().ok_or("no saved render setup with that name")?
@@ -58,7 +71,10 @@ pub fn run(args: &[String]) -> Result<(), String> {
if let Some(height) = height {
settings.height = height;
}
let params = json!({"settings":settings,"transparent_background":transparent});
if let Some(exposure) = exposure {
settings.exposure_ev = exposure;
}
let params = json!({"settings":settings,"transparent_background":transparent,"progressive":progressive,"samples":samples,"max_depth":max_depth,"seed":seed});
let preflight = session.execute("render.preflight", &params).map_err(|e| e.to_string())?;
let started = session.execute("render.start", &params).map_err(|e| e.to_string())?;
let id: JobId = serde_json::from_value(started["job"].clone()).map_err(|e| e.to_string())?;
+3
View File
@@ -1008,9 +1008,11 @@
"render.image_help": "Náhledový obrázek z CPU · PNG · přibližná průhlednost",
"render.image_overwrite": "Nahradit existující soubor",
"render.image_preparing": "Příprava obrázku",
"render.image_progressive": "Progresivní render",
"render.image_queued": "Čeká na render",
"render.image_reduce": "Zkuste menší obrázek nebo jednodušší scénu.",
"render.image_running": "Renderování obrázku",
"render.image_samples": "Vzorků na pixel",
"render.image_stale": "Tento obrázek používá scénu zachycenou před pozdějšími změnami.",
"render.image_start": "Spustit render",
"render.image_supported": "Požadavek na render je podporován; fronta a paměť se znovu ověří při spuštění.",
@@ -1026,6 +1028,7 @@
"render.perspective": "Perspektivní kamera",
"render.preview": "Integrovaný náhled",
"render.preview_help": "Rastrové stínování a smíšená průhlednost. Lom světla, HDRI a finální render zatím nejsou k dispozici.",
"render.progressive_image_summary": "Náhledové PNG · neprůhledné PBR · postupné vzorkování",
"render.reload_settings": "Znovu načíst uložené nastavení",
"render.restore_camera": "Obnovit uloženou kameru",
"render.return_design": "Zpět k návrhu",
+3
View File
@@ -1305,9 +1305,11 @@
"render.image_help": "CPU preview image · PNG · approximate transparency",
"render.image_overwrite": "Replace existing file",
"render.image_preparing": "Preparing image",
"render.image_progressive": "Progressive rendering",
"render.image_queued": "Waiting to render",
"render.image_reduce": "Try a smaller image or simpler scene.",
"render.image_running": "Rendering image",
"render.image_samples": "Samples per pixel",
"render.image_stale": "This image uses the scene captured before subsequent changes.",
"render.image_start": "Start Render",
"render.image_supported": "Render request is supported; the queue and memory pool are checked again at start.",
@@ -1323,6 +1325,7 @@
"render.perspective": "Perspective camera",
"render.preview": "Integrated preview",
"render.preview_help": "Raster shading and blended transparency. Refraction, HDRI and final rendering are not available yet.",
"render.progressive_image_summary": "Preview PNG · opaque PBR · progressive samples",
"render.reload_settings": "Reload Saved Settings",
"render.restore_camera": "Restore Saved Camera",
"render.return_design": "Return to Design",
+3
View File
@@ -1305,9 +1305,11 @@
"render.image_help": "CPUプレビュー画像 · PNG · 近似透過",
"render.image_overwrite": "既存のファイルを置換",
"render.image_preparing": "画像を準備中",
"render.image_progressive": "プログレッシブレンダリング",
"render.image_queued": "レンダリング待機中",
"render.image_reduce": "画像を小さくするかシーンを簡略化してください。",
"render.image_running": "画像をレンダリング中",
"render.image_samples": "ピクセルあたりのサンプル数",
"render.image_stale": "この画像は後続の変更前に取得したシーンを使用しています。",
"render.image_start": "レンダリングを開始",
"render.image_supported": "レンダリング要求に対応しています。開始時にキューとメモリを再確認します。",
@@ -1323,6 +1325,7 @@
"render.perspective": "透視投影カメラ",
"render.preview": "統合プレビュー",
"render.preview_help": "ラスタシェーディングとブレンド透明度を使用します。屈折、HDRI、最終レンダリングはまだ利用できません。",
"render.progressive_image_summary": "プレビューPNG · 不透明PBR · プログレッシブサンプリング",
"render.reload_settings": "保存した設定を再読み込み",
"render.restore_camera": "保存したカメラを復元",
"render.return_design": "設計に戻る",
+3
View File
@@ -1305,9 +1305,11 @@
"render.image_help": "CPU 预览图像 · PNG · 近似透明度",
"render.image_overwrite": "替换现有文件",
"render.image_preparing": "正在准备图像",
"render.image_progressive": "渐进式渲染",
"render.image_queued": "等待渲染",
"render.image_reduce": "请尝试更小的图像或更简单的场景。",
"render.image_running": "正在渲染图像",
"render.image_samples": "每像素采样数",
"render.image_stale": "此图像使用后续更改之前捕获的场景。",
"render.image_start": "开始渲染",
"render.image_supported": "支持此渲染请求;开始时将再次检查队列和内存池。",
@@ -1323,6 +1325,7 @@
"render.perspective": "透视相机",
"render.preview": "集成预览",
"render.preview_help": "光栅着色和混合透明度。暂不支持折射、HDRI 和最终渲染。",
"render.progressive_image_summary": "预览 PNG · 不透明 PBR · 渐进采样",
"render.reload_settings": "重新加载已保存设置",
"render.restore_camera": "恢复已保存相机",
"render.return_design": "返回设计",
+1 -1
View File
@@ -14,7 +14,7 @@ mod jobs;
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).icon("inspect").noundo().doc_only()
.params("setup?: saved name OR settings?: full RenderSetup; transparent_background?: false; replace?: false. Validates the installed image host and bounded captured product scene without starting work. Stale geometry is rejected. See docs/render-jobs.md"),
.params("setup?: saved name OR settings?: full RenderSetup; transparent_background?: false; replace?: false; progressive?: false; samples?: 1..4096 (64); max_depth?: 1..16 (8); seed?: u32 (0). Sampling controls and exposure require progressive rendering. Validates the installed image host and bounded captured product scene without starting work. Stale geometry is rejected. See docs/render-jobs.md"),
CommandSpec::new("render.start", "Render Image", jobs::start).noundo().doc_only().at("RENDER", "IMAGE").icon("render_image")
.params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"),
CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only()
+64
View File
@@ -23,6 +23,70 @@ fn finish(host: &CpuHost) {
panic!("cooperative job did not finish");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn additional_executor_routes_by_capability_and_survives_document_adoption() {
use solidcraft_render::job::{Admission, CancelToken, ImageExecutor, ImageHost, ImageRequest, ImageTask, ImageWork, JobOptions};
struct Progressive;
impl ImageExecutor for Progressive {
fn descriptor(&self) -> solidcraft_render::job::Result<solidcraft_render::ExecutorDescriptor> {
let mut descriptor = CpuHost::cooperative().descriptor()?;
descriptor.id = solidcraft_render::ExecutorId::new("test-progressive").unwrap();
descriptor.profiles[0].features.push(solidcraft_render::RenderFeature::Progressive);
Ok(descriptor)
}
fn admit(
&self,
scene: &solidcraft_render::ProductScene,
request: &ImageRequest,
options: JobOptions,
) -> solidcraft_render::job::Result<Admission> {
options.validate()?;
solidcraft_render::job::admit(scene, request)
}
fn begin(
&self,
scene: solidcraft_render::ProductScene,
request: ImageRequest,
_: JobOptions,
cancel: CancelToken,
) -> solidcraft_render::job::Result<Box<dyn ImageWork>> {
Ok(Box::new(ImageTask::new(scene, request, cancel)?))
}
}
let (mut session, cpu) = session();
let additional = ImageHost::with_executor(Arc::new(Progressive)).unwrap();
session.register_render_job_host(additional.clone()).unwrap();
assert!(
session.register_render_job_host(ImageHost::with_executor(Arc::new(Progressive)).unwrap()).is_err(),
"duplicate executor IDs must be rejected"
);
let cpu_id = start(&mut session);
let request = json!({"settings":{"width":16,"height":16},"progressive":true,"samples":3});
let preflight = session.execute("render.preflight", &request).unwrap();
assert_eq!(preflight["resolved"]["executor"], "test-progressive");
assert_eq!(additional.admitted_bytes(), 0);
let started = session.execute("render.start", &request).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let status = session.render_job_handle(id).unwrap().wait_timeout(std::time::Duration::from_secs(10)).unwrap();
assert_eq!(status.resolved.executor.as_str(), "test-progressive");
assert_eq!(status.options.samples, 3);
assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed);
finish(&cpu);
assert_eq!(session.execute("render.status", &json!({"job":cpu_id})).unwrap()["frame"]["executor"], "cpu-product");
assert!(session.scratch().execute("render.status", &json!({"job":id})).is_err());
session.execute("file.new", &json!({})).unwrap();
assert_eq!(session.execute("render.preflight", &request).unwrap()["resolved"]["executor"], "test-progressive");
assert!(session.execute("render.status", &json!({"job":id})).is_err());
for bad in [json!({"samples":0}), json!({"max_depth":17}), json!({"seed":-1}), json!({"samples":4097})] {
let mut params = request.clone();
for (key, value) in bad.as_object().unwrap() {
params[key] = value.clone();
}
assert!(session.execute("render.start", &params).is_err());
}
}
#[test]
fn runtime_commands_preserve_document_history_and_evaluation() {
let (mut s, host) = session();
+44 -15
View File
@@ -14,9 +14,22 @@ struct Start {
settings: Option<RenderSetup>,
transparent_background: bool,
replace: bool,
progressive: bool,
samples: Option<u32>,
max_depth: Option<u32>,
seed: Option<u32>,
}
fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcraft_render::ProductScene, ImageRequest, Value)> {
struct Prepared {
input: Start,
scene: solidcraft_render::ProductScene,
request: ImageRequest,
reply: Value,
executor: solidcraft_render::ExecutorId,
options: solidcraft_render::job::JobOptions,
}
fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
let input: Start = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
if input.setup.is_some() && input.settings.is_some() {
return Err(bad(command, "choose either setup or settings"));
@@ -36,12 +49,27 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcr
settings
};
settings.validate().map_err(|e| bad(command, e.to_string()))?;
if settings.exposure_ev != 0.0 || settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0 {
return Err(bad(command, "exposure and environment controls are not supported by the R4a CPU image executor"));
if settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0 {
return Err(bad(command, "environment controls are not supported by the installed image executors"));
}
let host = s.render_job_host().ok_or_else(|| bad(command, "no image host is installed"))?;
if !host.is_available() {
return Err(bad(command, "image host is unavailable"));
if !input.progressive && (input.samples.is_some() || input.max_depth.is_some() || input.seed.is_some() || settings.exposure_ev != 0.0) {
return Err(bad(command, "sampling and exposure controls require progressive rendering"));
}
let mut options = solidcraft_render::job::JobOptions::default();
if let Some(samples) = input.samples {
options.samples = samples;
}
if let Some(depth) = input.max_depth {
options.max_depth = depth;
}
if let Some(seed) = input.seed {
options.seed = seed;
}
options.exposure_ev = settings.exposure_ev;
options.validate().map_err(job_error)?;
let mut features = scene.required_features();
if input.progressive {
features.push(solidcraft_render::RenderFeature::Progressive);
}
let resolved = solidcraft_render::resolve_request(
&[s.render_backend()],
@@ -52,13 +80,14 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcr
width: u64::from(settings.width),
height: u64::from(settings.height),
format: Some(settings.format),
features: scene.required_features(),
features,
policy: Default::default(),
},
)
.map_err(|e| bad(command, e.to_string()))?;
if resolved.executor.as_str() != "cpu-product" {
return Err(bad(command, "resolved executor is not installed as an image job host"));
let host = s.render_jobs.host_for(&resolved.executor).ok_or_else(|| bad(command, "resolved executor is not installed as an image job host"))?;
if !host.is_available() {
return Err(bad(command, "image host is unavailable"));
}
let request = ImageRequest {
camera: settings.camera,
@@ -67,18 +96,18 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<(Start, solidcr
background: settings.background,
transparent_background: input.transparent_background,
};
let admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?;
let reply = json!({"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":"sorted_alpha_approximation","refraction":false});
Ok((input, scene, request, reply))
let admission = host.admit(&scene, &request, options).map_err(job_error)?;
let reply = json!({"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":if input.progressive {"opaque_only"} else {"sorted_alpha_approximation"},"options":options,"refraction":false});
Ok(Prepared { input, scene, request, reply, executor: resolved.executor, options })
}
pub(super) fn preflight(s: &mut Session, params: &Value) -> Result<Value> {
prepare(s, params, "render.preflight").map(|(_, _, _, reply)| reply)
prepare(s, params, "render.preflight").map(|prepared| prepared.reply)
}
pub(super) fn start(s: &mut Session, params: &Value) -> Result<Value> {
let (input, scene, request, _) = prepare(s, params, "render.start")?;
let status = s.render_jobs.start(s.revision, scene, request, input.replace).map_err(job_error)?;
let p = prepare(s, params, "render.start")?;
let status = s.render_jobs.start(s.revision, p.scene, p.request, p.input.replace, &p.executor, p.options).map_err(job_error)?;
Ok(json!(status))
}
+12
View File
@@ -495,6 +495,13 @@ impl Session {
}
backend.executors.push(executor);
}
for (host, descriptor) in &self.render_jobs.additional {
let mut descriptor = descriptor.clone();
if !host.is_available() {
descriptor.availability = render::Availability::Unavailable { reason: "image host is unavailable".into() };
}
backend.executors.push(descriptor);
}
backend
}
@@ -515,6 +522,7 @@ impl Session {
if let Some(executor) = &self.render_jobs.descriptor {
backend.executors.push(executor.clone());
}
backend.executors.extend(self.render_jobs.additional.iter().map(|(_, d)| d.clone()));
backend.executors.push(executor.clone());
// Resolution validates the whole registry, including duplicate executor IDs.
let request = render::RenderRequest {
@@ -789,6 +797,7 @@ impl Session {
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
let host_viewport = self.render_viewport.clone();
let host_jobs = self.render_jobs.host.clone();
let additional_jobs = self.render_jobs.additional.clone();
let live = spec.live.filter(|_| params.get("live").and_then(Value::as_bool) == Some(true));
if live.is_none() && spec.reads_model && self.model.is_stale() {
self.refresh();
@@ -830,6 +839,9 @@ impl Session {
if self.render_jobs.host.is_none() && host_jobs.is_some() {
self.set_render_job_host(host_jobs)?;
}
for (host, _) in additional_jobs {
self.register_render_job_host(host)?;
}
if outermost && crash::enabled() {
// A failed command leaves the design as it was (restored below).
let failed = r.as_ref().err().map(ToString::to_string);
+55 -3
View File
@@ -30,6 +30,7 @@ pub(crate) struct Jobs {
generation: u64,
pub(crate) host: Option<CpuHost>,
pub(crate) descriptor: Option<ExecutorDescriptor>,
pub(crate) additional: Vec<(CpuHost, ExecutorDescriptor)>,
live: Vec<JobHandle>,
history: VecDeque<JobStatus>,
last_good: Option<JobHandle>,
@@ -37,7 +38,17 @@ pub(crate) struct Jobs {
impl Default for Jobs {
fn default() -> Self {
Self { owner: owner(), serial: 0, generation: 0, host: None, descriptor: None, live: Vec::new(), history: VecDeque::new(), last_good: None }
Self {
owner: owner(),
serial: 0,
generation: 0,
host: None,
descriptor: None,
additional: Vec::new(),
live: Vec::new(),
history: VecDeque::new(),
last_good: None,
}
}
}
@@ -50,10 +61,18 @@ impl Drop for Jobs {
}
impl Jobs {
pub(crate) fn host_for(&self, executor: &solidcraft_render::ExecutorId) -> Option<&CpuHost> {
if self.descriptor.as_ref().is_some_and(|d| &d.id == executor) {
return self.host.as_ref();
}
self.additional.iter().find(|(_, d)| &d.id == executor).map(|(host, _)| host)
}
pub(crate) fn scratch(&self) -> Self {
let mut jobs = Self::default();
jobs.host = self.host.clone();
jobs.descriptor = self.descriptor.clone();
jobs.additional = self.additional.clone();
jobs
}
@@ -83,9 +102,11 @@ impl Jobs {
scene: solidcraft_render::ProductScene,
request: solidcraft_render::job::ImageRequest,
replace: bool,
executor: &solidcraft_render::ExecutorId,
options: solidcraft_render::job::JobOptions,
) -> Result<JobStatus, JobError> {
self.collect()?;
let host = self.host.as_ref().ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "no image host is installed"))?.clone();
let host = self.host_for(executor).ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))?.clone();
if replace {
for job in self.live.drain(..) {
let mut status = job.cancel()?;
@@ -109,7 +130,7 @@ impl Jobs {
}
let serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render job identity exhausted"))?;
let generation = self.generation.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render generation exhausted"))?;
let handle = host.submit(JobId { session: self.owner, serial, generation }, revision, scene, request)?;
let handle = host.submit_with_options(JobId { session: self.owner, serial, generation }, revision, scene, request, options)?;
let status = handle.status()?;
self.serial = serial;
self.generation = generation;
@@ -176,12 +197,43 @@ impl crate::Session {
)
.map_err(|e| crate::EngineError::Other(e.to_string()))?;
let mut jobs = Jobs::default();
jobs.additional = self.render_jobs.additional.clone();
jobs.host = host;
jobs.descriptor = descriptor;
self.render_jobs = jobs;
Ok(())
}
/// Add an executor without replacing CPU jobs or their ownership. Applications share
/// this host across document sessions; descriptor IDs must be unique in the registry.
pub fn register_render_job_host(&mut self, host: solidcraft_render::job::ImageHost) -> crate::Result<()> {
let descriptor = host.descriptor().map_err(job_error)?;
if self.render_jobs.additional.iter().any(|(old, _)| old.same_host(&host)) {
return Ok(());
}
if descriptor.profiles.iter().any(|p| p.operation != solidcraft_render::RenderOperation::Image) {
return Err(crate::EngineError::Other("image host must only register image profiles".into()));
}
let mut registry = self.render_backend();
registry.executors.push(descriptor.clone());
solidcraft_render::resolve_request(
&[registry],
&solidcraft_render::RenderRequest {
backend: None,
mode: solidcraft_render::RenderMode::Preview,
operation: solidcraft_render::RenderOperation::Image,
width: 1,
height: 1,
format: Some(solidcraft_render::RenderFormat::Png),
features: Vec::new(),
policy: Default::default(),
},
)
.map_err(|e| crate::EngineError::Other(e.to_string()))?;
self.render_jobs.additional.push((host, descriptor));
Ok(())
}
pub fn render_job_host(&self) -> Option<&CpuHost> {
self.render_jobs.host.as_ref()
}
+11 -4
View File
@@ -20,6 +20,8 @@ use solidcraft_geom::tess::{EvalCurve, EvalSurface, TessPlan};
use wgpu::util::DeviceExt;
pub mod capture;
#[cfg(not(target_arch = "wasm32"))]
pub mod path;
mod pbr;
#[cfg(not(target_arch = "wasm32"))]
pub mod select;
@@ -65,14 +67,19 @@ fn popped(f: impl std::future::Future<Output = Option<wgpu::Error>>) -> Option<w
fn open_headless() -> Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> {
let policy = select::Policy::from_env().map_err(GpuError::Policy)?;
let (adapter, _) = select::pick(policy).ok_or(GpuError::NoAdapter(policy.name()))?;
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
let (device, queue) = open_device(&adapter)?;
Ok((adapter, device, queue))
}
#[cfg(not(target_arch = "wasm32"))]
fn open_device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue)> {
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("solidcraft headless"),
required_features: depth_features(&adapter),
required_features: depth_features(adapter),
required_limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()),
..Default::default()
}))
.map_err(|e| GpuError::Device(e.to_string()))?;
Ok((adapter, device, queue))
.map_err(|e| GpuError::Device(e.to_string()))
}
/// Most vertices evaluated in one dispatch (bounds the buffers; larger plans go in batches).
+374
View File
@@ -0,0 +1,374 @@
//! Native progressive opaque product rendering. Software BVH traversal needs no ray-query
//! features. Every worker quantum submits at most 256K paths, then checks cancellation.
use solidcraft_geom::Vec3;
use solidcraft_render::{
Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFeature, RenderFormat, RenderLimits, RenderMode, RenderOperation,
RenderProfile, ScratchLayout,
job::{
Admission, CancelToken, ErrorCode, ImageExecutor, ImageHost, ImageRequest, ImageWork, JobError, JobOptions, Phase, PngTask, Progress, Result,
TaskPoll, admit_geometry,
},
};
use std::{
sync::Arc,
time::{Duration, Instant},
};
use wgpu::util::DeviceExt;
mod scene;
#[cfg(test)]
mod tests;
const SHADER: &str = include_str!("path.wgsl");
const MAX_TRIANGLES: u64 = 1_048_576;
const TILE: u32 = 262_144;
const TIMEOUT: Duration = Duration::from_secs(30);
fn gpu(e: impl std::fmt::Display) -> JobError {
JobError::new(ErrorCode::HostUnavailable, e.to_string())
}
fn scopes(device: &wgpu::Device) -> [wgpu::ErrorScopeGuard; 3] {
[wgpu::ErrorFilter::Validation, wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal].map(|f| device.push_error_scope(f))
}
fn checked(scopes: [wgpu::ErrorScopeGuard; 3]) -> Result<()> {
let mut error = None;
for scope in scopes.into_iter().rev() {
if let Some(e) = pollster::block_on(scope.pop()) {
error = Some(e);
}
}
error.map_or(Ok(()), |e| Err(gpu(e)))
}
/// Open and validate a native device before advertising the executor. Failure leaves the
/// caller's CPU host usable. Respects SOLIDCRAFT_GPU, including the software adapter policy.
pub fn host() -> Result<ImageHost> {
let (adapter, device, queue) = crate::open_headless().map_err(gpu)?;
log::info!("gpu-path adapter: {} ({:?})", adapter.get_info().name, adapter.get_info().device_type);
ImageHost::with_executor(Arc::new(Executor::new(device, queue)?))
}
/// Open an independent job device on the viewport's selected adapter. In particular,
/// software fallback and safe mode must not rediscover a failing hardware driver.
/// An explicit incompatible SOLIDCRAFT_GPU policy leaves this executor unavailable.
pub fn host_on_adapter(adapter: &wgpu::Adapter) -> Result<ImageHost> {
let policy = crate::select::Policy::from_env().map_err(gpu)?;
let info = adapter.get_info();
if !policy.admits(crate::select::tier_of(info.device_type)) {
return Err(gpu(format!("viewport adapter does not satisfy SOLIDCRAFT_GPU={}", policy.name())));
}
let (device, queue) = crate::open_device(adapter).map_err(gpu)?;
log::info!("gpu-path viewport adapter: {} ({:?})", info.name, info.device_type);
ImageHost::with_executor(Arc::new(Executor::new(device, queue)?))
}
struct Context {
device: wgpu::Device,
queue: wgpu::Queue,
pipeline: wgpu::ComputePipeline,
layout: wgpu::BindGroupLayout,
}
struct Executor {
context: Arc<Context>,
}
impl Executor {
fn new(device: wgpu::Device, queue: wgpu::Queue) -> Result<Self> {
device.on_uncaptured_error(Arc::new(|e: wgpu::Error| log::error!("gpu-path: {e}")));
let scopes = scopes(&device);
let shader =
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("gpu-path"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let entries: Vec<_> = (0..4)
.map(|binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: if binding == 0 { wgpu::BufferBindingType::Uniform } else { wgpu::BufferBindingType::Storage { read_only: binding != 3 } },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
})
.collect();
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("gpu-path"), entries: &entries });
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("gpu-path"),
bind_group_layouts: &[Some(&layout)],
immediate_size: 0,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("gpu-path"),
layout: Some(&pipeline_layout),
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
checked(scopes)?;
Ok(Self { context: Arc::new(Context { device, queue, pipeline, layout }) })
}
}
fn descriptor() -> Result<ExecutorDescriptor> {
Ok(ExecutorDescriptor {
id: ExecutorId::new("gpu-path").map_err(gpu)?,
availability: Availability::Available,
profiles: vec![RenderProfile {
mode: RenderMode::Preview,
operation: RenderOperation::Image,
formats: vec![RenderFormat::Png],
features: vec![RenderFeature::Pbr, RenderFeature::Progressive],
}],
limits: RenderLimits::default(),
scratch: ScratchLayout { sample_scale: 1, sample_bytes_per_pixel: 16, output_bytes_per_pixel: 16, encoding_bytes_per_pixel: 16 },
})
}
fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result<Admission> {
options.validate()?;
let camera = request.camera;
if !camera.fov.is_finite()
|| !(0.0..std::f64::consts::PI).contains(&camera.fov)
|| !camera.half_height().is_finite()
|| camera.half_height() > 1e12
|| camera.distance > 1e9
{
return Err(JobError::new(ErrorCode::InvalidRequest, "gpu-path requires a bounded finite camera"));
}
let mut admission = admit_geometry(scene, request, MAX_TRIANGLES)?;
if scene.meshes.iter().any(|m| m.opacity != 1.0 || m.faces.iter().any(|f| f.opacity != 1.0)) {
return Err(JobError::new(ErrorCode::InvalidScene, "gpu-path supports opaque surfaces only; refraction is not implemented"));
}
// Peak preparation: f64 triangles + nodes + serialized upload. After preparation:
// serialized + device geometry + accumulation/readback/RGBA/PNG. These phases don't overlap.
let pixels = u64::from(request.width) * u64::from(request.height);
admission.pixel_scratch_bytes = pixels * 64;
let vertex_bytes = scene.meshes.iter().map(|m| m.mesh.positions.len() as u64 * 32).sum::<u64>();
admission.preparation_bytes = (admission.triangles * 400 + vertex_bytes * 2 + admission.face_appearances * 8)
.max(admission.triangles * 160 + vertex_bytes * 2 + pixels * 32)
.max(admission.triangles * 80 + vertex_bytes + admission.pixel_scratch_bytes)
+ 1_048_576;
admission.estimated_total_bytes = admission.geometry_bytes + admission.preparation_bytes;
if admission.estimated_total_bytes > 512 * 1024 * 1024 {
return Err(JobError::new(ErrorCode::LimitExceeded, "gpu-path job exceeds its 512 MiB admission estimate"));
}
Ok(admission)
}
impl ImageExecutor for Executor {
fn descriptor(&self) -> Result<ExecutorDescriptor> {
descriptor()
}
fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result<Admission> {
let a = admission(scene, request, options)?;
let limit = self.context.device.limits().max_storage_buffer_binding_size;
let geometry_bytes = 16 + a.triangles.max(1) * 48 + scene.meshes.iter().map(|m| m.mesh.positions.len() as u64 * 32).sum::<u64>();
if geometry_bytes > limit || u64::from(request.width) * u64::from(request.height) * 16 > limit {
return Err(JobError::new(ErrorCode::LimitExceeded, "gpu-path storage buffer exceeds this device's limit"));
}
Ok(a)
}
fn begin(&self, scene: ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result<Box<dyn ImageWork>> {
self.admit(&scene, &request, options)?;
Ok(Box::new(Task::new(self.context.clone(), scene, request, options, cancel)?))
}
}
struct Task {
context: Arc<Context>,
request: ImageRequest,
options: JobOptions,
cancel: CancelToken,
uniform: wgpu::Buffer,
accumulation: wgpu::Buffer,
readback: wgpu::Buffer,
bind: wgpu::BindGroup,
sample: u32,
offset: u32,
epsilon: f32,
png: Option<PngTask>,
started: Instant,
// Uniform environment is used only by the numerical furnace test, never advertised as HDRI.
environment: f32,
studio: f32,
#[cfg(test)]
metrics: (f64, u64, f64),
}
impl Task {
fn new(context: Arc<Context>, scene: ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result<Self> {
cancel.check()?;
let start = Instant::now();
let upload = scene::flatten(&scene, request.camera.target, &cancel)?;
let bvh_ms = start.elapsed().as_secs_f64() * 1000.0;
let upload_bytes = (upload.geometry.len() + upload.nodes.len()) as u64;
let uploading = Instant::now();
drop(scene);
let device = &context.device;
let scopes = [wgpu::ErrorFilter::Validation, wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal].map(|f| device.push_error_scope(f));
let make =
|label, bytes: &[u8], usage| device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage });
let triangles = make("path triangles", &upload.geometry, wgpu::BufferUsages::STORAGE);
let nodes = make("path BVH", &upload.nodes, wgpu::BufferUsages::STORAGE);
let uniform = make("path parameters", &[0; 112], wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST);
let size = u64::from(request.width) * u64::from(request.height) * 16;
let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("path accumulation"),
size,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("path readback"),
size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let entries: Vec<_> = [&uniform, &triangles, &nodes, &accumulation]
.iter()
.enumerate()
.map(|(binding, buffer)| wgpu::BindGroupEntry { binding: binding as u32, resource: buffer.as_entire_binding() })
.collect();
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("gpu-path"), layout: &context.layout, entries: &entries });
let mut error = None;
for scope in scopes.into_iter().rev() {
if let Some(e) = pollster::block_on(scope.pop()) {
error = Some(e);
}
}
if let Some(e) = error {
return Err(gpu(e));
}
let submission = context.queue.submit([]);
device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(TIMEOUT) }).map_err(gpu)?;
let upload_ms = uploading.elapsed().as_secs_f64() * 1000.0;
log::info!("gpu-path BVH {bvh_ms:.3} ms, upload {upload_bytes} bytes in {upload_ms:.3} ms");
cancel.check()?;
Ok(Self {
context,
request,
options,
cancel,
uniform,
accumulation,
readback,
bind,
sample: 0,
offset: 0,
epsilon: upload.epsilon,
png: None,
started: Instant::now(),
environment: 0.0,
studio: 1.0,
#[cfg(test)]
metrics: (bvh_ms, upload_bytes, upload_ms),
})
}
fn parameters(&self, count: u32) -> Vec<u8> {
let mut bytes = Vec::with_capacity(112);
for x in [self.request.width, self.request.height, self.sample, self.offset, self.options.seed, self.options.max_depth, count, 0] {
bytes.extend_from_slice(&x.to_le_bytes());
}
let camera = self.request.camera;
let (right, up, back) = camera.basis();
let perspective = camera.fov > 0.0;
let eye = back * (camera.distance * if perspective { 1.0 } else { 4.0 });
scene::vector(&mut bytes, eye, if perspective { 1.0 } else { 0.0 });
scene::vector(&mut bytes, right * camera.half_height() * (f64::from(self.request.width) / f64::from(self.request.height)), 0.0);
scene::vector(&mut bytes, up * camera.half_height(), 0.0);
scene::vector(&mut bytes, back, camera.distance as f32);
scene::vector(&mut bytes, Vec3::new(f64::from(self.epsilon), f64::from(self.environment), f64::from(self.studio)), 0.0);
bytes
}
fn dispatch(&mut self) -> Result<()> {
self.cancel.check()?;
let pixels = self.request.width * self.request.height;
let count = (pixels - self.offset).min(TILE);
let context = &self.context;
let scopes = scopes(&context.device);
context.queue.write_buffer(&self.uniform, 0, &self.parameters(count));
let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("path tile") });
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("path tile"), timestamp_writes: None });
pass.set_pipeline(&context.pipeline);
pass.set_bind_group(0, &self.bind, &[]);
pass.dispatch_workgroups(count.div_ceil(64), 1, 1);
}
let submission = context.queue.submit([encoder.finish()]);
checked(scopes)?;
context.device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(TIMEOUT) }).map_err(gpu)?;
self.cancel.check()?;
self.offset += count;
if self.offset == pixels {
self.sample += 1;
self.offset = 0;
}
Ok(())
}
fn read_linear(&self) -> Result<Vec<[f32; 4]>> {
self.cancel.check()?;
let context = &self.context;
let scopes = scopes(&context.device);
let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("path readback") });
encoder.copy_buffer_to_buffer(&self.accumulation, 0, &self.readback, 0, self.accumulation.size());
let submission = context.queue.submit([encoder.finish()]);
checked(scopes)?;
let slice = self.readback.slice(..);
let (tx, rx) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |result| {
let _ = tx.send(result);
});
context.device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(TIMEOUT) }).map_err(gpu)?;
rx.try_recv().map_err(gpu)?.map_err(gpu)?;
let data = slice.get_mapped_range().map_err(gpu)?;
let mut values = scene::reserved((self.request.width * self.request.height) as usize)?;
for pixel in data.as_chunks::<16>().0 {
let mut value = [0.0; 4];
for (v, bytes) in value.iter_mut().zip(pixel.as_chunks::<4>().0) {
*v = f32::from_le_bytes(*bytes) / self.sample as f32;
if !v.is_finite() || *v < 0.0 {
return Err(JobError::new(ErrorCode::Internal, "nonfinite or negative path radiance"));
}
}
values.push(value);
}
drop(data);
self.readback.unmap();
self.cancel.check()?;
Ok(values)
}
}
impl ImageWork for Task {
fn step(&mut self, units: usize) -> Result<TaskPoll> {
self.cancel.check()?;
if let Some(png) = &mut self.png {
return png.step(units);
}
if self.sample < self.options.samples {
self.dispatch()?;
return Ok(TaskPoll::Pending(Progress { phase: Phase::Running, done: u64::from(self.sample), total: u64::from(self.options.samples) }));
}
log::info!("gpu-path {} spp, {:.3} ms/spp", self.sample, self.started.elapsed().as_secs_f64() * 1000.0 / f64::from(self.sample));
let linear = self.read_linear()?;
let mut rgba = scene::reserved(linear.len() * 4)?;
let exposure = 2.0f64.powf(self.options.exposure_ev);
for (index, pixel) in linear.iter().enumerate() {
if index % 4096 == 0 {
self.cancel.check()?;
}
let alpha = f64::from(pixel[3]).clamp(0.0, 1.0);
for (radiance, background) in pixel.iter().take(3).zip(self.request.background) {
let c = if alpha > 0.0 { f64::from(*radiance) * exposure / alpha } else { 0.0 };
let mapped = c / (1.0 + c);
let value = if self.request.transparent_background {
mapped
} else {
mapped * alpha + solidcraft_render::surface::srgb8_to_linear(background) * (1.0 - alpha)
};
let encoded = if value <= 0.0031308 { value * 12.92 } else { 1.055 * value.powf(1.0 / 2.4) - 0.055 };
rgba.push((encoded.clamp(0.0, 1.0) * 255.0).round() as u8);
}
rgba.push(if self.request.transparent_background { (alpha * 255.0).round() as u8 } else { 255 });
}
self.png = Some(PngTask::new(&self.request, rgba, self.cancel.clone())?);
Ok(TaskPoll::Pending(Progress { phase: Phase::Encoding, done: 0, total: u64::from(self.request.height) }))
}
}
+212
View File
@@ -0,0 +1,212 @@
// Original software BVH and unidirectional Monte Carlo integrator. All directions
// at a surface point away from it, matching render::surface's GGX/Smith oracle.
struct Triangle {
p0: vec4<f32>, p1: vec4<f32>, p2: vec4<f32>,
n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>,
base: vec4<f32>, parameters: vec4<f32>,
};
struct Node { lo: vec3<f32>, first: u32, hi: vec3<f32>, count: u32 };
struct Params {
// width, height, sample index, pixel offset
image: vec4<u32>,
// seed, maximum depth, tile length, reserved
sampling: vec4<u32>,
eye: vec4<f32>, right: vec4<f32>, up: vec4<f32>, back: vec4<f32>,
// ray epsilon, test environment radiance, studio scale, reserved
lighting: vec4<f32>,
};
@group(0) @binding(0) var<uniform> u: Params;
@group(0) @binding(1) var<storage, read> geometry: array<u32>;
@group(0) @binding(2) var<storage, read> nodes: array<Node>;
@group(0) @binding(3) var<storage, read_write> accumulation: array<vec4<f32>>;
const PI: f32 = 3.141592653589793;
const FAR: f32 = 1e30;
// Header: triangle count, vertex offset (words), material offset (words), vertex count.
// Indexed triangles contain three vertex indices and one resolved material ID.
fn vector_at(word: u32) -> vec4<f32> {
return bitcast<vec4<f32>>(vec4<u32>(geometry[word],geometry[word+1u],geometry[word+2u],geometry[word+3u]));
}
fn triangle(index: u32) -> Triangle {
let word = 4u+index*4u;
let a = geometry[1]+geometry[word]*8u;
let b = geometry[1]+geometry[word+1u]*8u;
let c = geometry[1]+geometry[word+2u]*8u;
let material = geometry[2]+geometry[word+3u]*8u;
return Triangle(vector_at(a),vector_at(b),vector_at(c),vector_at(a+4u),vector_at(b+4u),vector_at(c+4u),vector_at(material),vector_at(material+4u));
}
fn random(state: ptr<function, u32>) -> f32 {
*state = *state * 747796405u + 2891336453u;
let word = ((*state >> ((*state >> 28u) + 4u)) ^ *state) * 277803737u;
return f32(((word >> 22u) ^ word) >> 8u) * (1.0 / 16777216.0);
}
fn unit(v: vec3<f32>) -> vec3<f32> {
let scale = max(max(abs(v.x), abs(v.y)), abs(v.z));
if scale == 0.0 { return vec3<f32>(0.0, 0.0, 1.0); }
return normalize(v / scale);
}
fn fresnel(f0: vec3<f32>, c: f32) -> vec3<f32> {
let t = 1.0 - clamp(c, 0.0, 1.0);
return f0 + (vec3<f32>(1.0) - f0) * (t*t*t*t*t);
}
fn distribution(nh: f32, a2: f32) -> f32 {
let d = (1.0 - nh*nh) + nh*nh*a2;
return a2 / (PI*d*d);
}
fn brdf(t: Triangle, n: vec3<f32>, v: vec3<f32>, l: vec3<f32>) -> vec3<f32> {
let nv = clamp(dot(n,v), -1.0, 1.0);
let nl = clamp(dot(n,l), -1.0, 1.0);
if nv <= 0.0 || nl <= 0.0 { return vec3<f32>(0.0); }
let h = unit(v+l);
let a = t.parameters.y*t.parameters.y;
let a2 = a*a;
let d = distribution(clamp(dot(n,h), 0.0, 1.0), a2);
let gv = 2.0 / (nv + sqrt(a2 + (1.0-a2)*nv*nv));
let gl = 2.0 / (nl + sqrt(a2 + (1.0-a2)*nl*nl));
let ratio = (t.parameters.z - 1.0) / (t.parameters.z + 1.0);
let f0 = mix(vec3<f32>(ratio*ratio), t.base.xyz, t.parameters.x);
let diffuse = t.base.xyz * ((1.0-t.parameters.x)/PI);
return fresnel(f0, dot(v,h)) * (d*0.25*gv*gl)
+ (vec3<f32>(1.0)-fresnel(f0,nv)) * (vec3<f32>(1.0)-fresnel(f0,nl)) * diffuse;
}
// Explicit parallel slab handling avoids 0*infinity/NaN at box boundaries.
fn box_hit(node: Node, o: vec3<f32>, d: vec3<f32>, limit: f32) -> bool {
var near = 0.0;
var far = limit;
for (var k = 0u; k < 3u; k += 1u) {
if abs(d[k]) < 1e-20 {
if o[k] < node.lo[k] || o[k] > node.hi[k] { return false; }
} else {
let a = (node.lo[k]-o[k])/d[k];
let b = (node.hi[k]-o[k])/d[k];
near = max(near, min(a,b)); far = min(far, max(a,b));
}
}
return far >= near;
}
struct Hit { distance: f32, triangle: u32, uv: vec2<f32> };
fn trace(o: vec3<f32>, d: vec3<f32>, any_hit: bool) -> Hit {
var hit = Hit(FAR, 0xffffffffu, vec2<f32>(0.0));
// A balanced tree over <= 2^20 triangles needs <= 21 pending nodes.
var stack: array<u32, 32>;
stack[0] = 0u;
var size = 1u;
loop {
if size == 0u { break; }
size -= 1u;
let node = nodes[stack[size]];
if node.first == 0xffffffffu || !box_hit(node, o, d, hit.distance) { continue; }
if node.count == 0u {
if size + 2u > 32u { break; }
stack[size] = node.first; stack[size+1u] = node.first+1u; size += 2u;
continue;
}
for (var i = node.first; i < node.first + node.count; i += 1u) {
let t = triangle(i);
let e1 = t.p1.xyz-t.p0.xyz; let e2 = t.p2.xyz-t.p0.xyz;
let h = cross(d,e2); let det = dot(e1,h);
if abs(det) <= 1e-20 { continue; }
let s = o-t.p0.xyz; let b1 = dot(s,h)/det;
if b1 < 0.0 || b1 > 1.0 { continue; }
let q = cross(s,e1); let b2 = dot(d,q)/det;
if b2 < 0.0 || b1+b2 > 1.0 { continue; }
let distance = dot(e2,q)/det;
if distance > u.lighting.x && distance < hit.distance {
hit = Hit(distance,i,vec2<f32>(b1,b2));
if any_hit { return hit; }
}
}
}
return hit;
}
fn from_local(p: vec3<f32>, n: vec3<f32>) -> vec3<f32> {
let axis = select(vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,1.0,0.0),abs(n.z)>0.9);
let x = unit(cross(axis,n));
return unit(x*p.x + cross(n,x)*p.y + n*p.z);
}
fn continuation(t: Triangle, n: vec3<f32>, v: vec3<f32>, rng: ptr<function,u32>) -> vec3<f32> {
let component = random(rng);
let x = random(rng); let phi = 2.0*PI*random(rng);
if component < 0.5 {
let radius = sqrt(x);
return from_local(vec3<f32>(radius*cos(phi),radius*sin(phi),sqrt(1.0-x)),n);
}
let alpha = t.parameters.y*t.parameters.y;
let cosine = sqrt((1.0-x)/(1.0+(alpha*alpha-1.0)*x));
let sine = sqrt(max(0.0,1.0-cosine*cosine));
let h = from_local(vec3<f32>(sine*cos(phi),sine*sin(phi),cosine),n);
return reflect(-v,h);
}
fn sample_path(pixel: u32) -> vec4<f32> {
var rng = pixel ^ (u.image.z * 0x9e3779b9u) ^ u.sampling.x;
let xy = vec2<f32>(f32(pixel % u.image.x)+random(&rng), f32(pixel / u.image.x)+random(&rng));
let uv = vec2<f32>(xy.x/f32(u.image.x)*2.0-1.0, 1.0-xy.y/f32(u.image.y)*2.0);
let offset = u.right.xyz*uv.x + u.up.xyz*uv.y;
var o = u.eye.xyz + offset;
var d = -u.back.xyz;
if u.eye.w > 0.5 { o = u.eye.xyz; d = unit(offset-u.back.xyz*u.back.w); }
var throughput = vec3<f32>(1.0);
var radiance = vec3<f32>(0.0);
var coverage = 0.0;
let lights = array<vec4<f32>,3>(vec4<f32>(0.6,0.0,0.8,3.0),vec4<f32>(-0.8,0.0,0.6,1.0),vec4<f32>(0.0,-0.6,0.8,1.5));
for (var bounce = 0u; bounce < u.sampling.y; bounce += 1u) {
let hit = trace(o,d,false);
if hit.triangle == 0xffffffffu {
radiance += throughput * u.lighting.y;
break;
}
coverage = 1.0;
let t = triangle(hit.triangle); let v = -d;
var geometric = unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));
if dot(geometric,v)<0.0 { geometric = -geometric; }
var n = unit(t.n0.xyz*(1.0-hit.uv.x-hit.uv.y)+t.n1.xyz*hit.uv.x+t.n2.xyz*hit.uv.y);
if dot(n,geometric)<0.0 { n = -n; }
if dot(n,v)<=0.0 { n = geometric; }
// Recover the surface point from barycentrics. A distant ray's f32 distance
// loses precision on skinny triangles; o+d*t can land behind the surface
// and make the next shadow ray intersect the same face.
o = t.p0.xyz*(1.0-hit.uv.x-hit.uv.y) + t.p1.xyz*hit.uv.x + t.p2.xyz*hit.uv.y
+ geometric*(u.lighting.x*2.0);
for (var i=0u; i<3u; i+=1u) {
let light = lights[i];
if u.lighting.z > 0.0 && dot(geometric,light.xyz)>0.0 && dot(n,light.xyz)>0.0 {
if trace(o,light.xyz,true).triangle == 0xffffffffu {
radiance += throughput * brdf(t,n,v,light.xyz) * (light.w*dot(n,light.xyz)*u.lighting.z);
}
}
}
d = continuation(t,n,v,&rng);
let nl = dot(n,d);
if nl<=0.0 || dot(geometric,d)<=0.0 { break; }
let h = unit(v+d); let vh = max(dot(v,h),1e-20);
let alpha = t.parameters.y*t.parameters.y;
let nh = max(dot(n,h),0.0);
let pdf = 0.5*nl/PI + 0.5*distribution(nh,alpha*alpha)*nh/(4.0*vh);
throughput *= brdf(t,n,v,d) * (nl/pdf);
if bounce>=3u {
let survive = clamp(max(max(throughput.x,throughput.y),throughput.z),0.05,0.95);
if random(&rng)>survive { break; }
throughput /= survive;
}
}
return vec4<f32>(radiance,coverage);
}
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let pixel = u.image.w + gid.x;
if gid.x >= u.sampling.z || pixel >= u.image.x*u.image.y { return; }
let sample = sample_path(pixel);
if u.image.z == 0u { accumulation[pixel] = sample; }
else { accumulation[pixel] += sample; }
}
// Validation entry point: exact same BRDF used by production paths, read back in tests.
@compute @workgroup_size(1)
fn reference() {
accumulation[0] = vec4<f32>(brdf(triangle(0u),u.up.xyz,u.back.xyz,u.right.xyz),1.0);
}
+194
View File
@@ -0,0 +1,194 @@
//! Original median-split BVH. World geometry is rebased around the camera target for f32.
use solidcraft_geom::Vec3;
use solidcraft_render::{
ProductScene,
job::{CancelToken, ErrorCode, JobError, Result},
surface::{OpaqueSurface, srgb8_to_linear},
};
pub(super) struct Triangle {
pub p: [Vec3; 3],
pub indices: [u32; 3],
pub surface: OpaqueSurface,
}
impl Triangle {
fn centre(&self, axis: usize) -> f64 {
self.p.iter().map(|p| [p.x, p.y, p.z].get(axis).copied().unwrap_or(0.0)).sum::<f64>() / 3.0
}
}
#[derive(Default)]
struct Node {
lo: [f32; 3],
hi: [f32; 3],
first: u32,
count: u32,
}
pub(super) struct Upload {
pub geometry: Vec<u8>,
pub nodes: Vec<u8>,
pub epsilon: f32,
}
fn invalid(message: &str) -> JobError {
JobError::new(ErrorCode::InvalidScene, message)
}
pub(super) fn reserved<T>(count: usize) -> Result<Vec<T>> {
let mut v = Vec::new();
v.try_reserve_exact(count).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "path tracer allocation failed"))?;
Ok(v)
}
pub(super) fn flatten(scene: &ProductScene, origin: Vec3, cancel: &CancelToken) -> Result<Upload> {
let count = scene.meshes.iter().map(|m| m.mesh.triangles.len()).sum::<usize>();
let mut triangles = reserved(count)?;
let vertex_count = scene.meshes.iter().map(|m| m.mesh.positions.len()).sum::<usize>();
let mut vertices = reserved(vertex_count * 32)?;
let mut vertex_offset = 0u32;
for body in &scene.meshes {
cancel.check()?;
let mut faces = reserved(body.faces.len())?;
faces.extend(body.faces.iter());
faces.sort_unstable_by_key(|f| f.face);
if faces.windows(2).any(|f| f[0].face == f[1].face) {
return Err(invalid("duplicate face appearance"));
}
let mesh = &body.mesh;
if mesh.normals.len() != mesh.positions.len() || mesh.tri_face.len() != mesh.triangles.len() {
return Err(invalid("path tracer requires normals and a face ID for every triangle"));
}
for (index, (position, normal)) in mesh.positions.iter().zip(&mesh.normals).enumerate() {
if index % 1024 == 0 {
cancel.check()?;
}
let position = *position - origin;
if !position.is_finite() || [position.x, position.y, position.z].iter().any(|x| x.abs() > 1e7) {
return Err(invalid("path geometry must be finite and within 1e7 mm of the camera target"));
}
let normal = solidcraft_render::surface::unit_direction(*normal).map_err(|_| invalid("invalid mesh normal"))?;
vector(&mut vertices, position, 0.0);
vector(&mut vertices, normal, 0.0);
}
for (index, indices) in mesh.triangles.iter().enumerate() {
if index % 1024 == 0 {
cancel.check()?;
}
let face = mesh.tri_face.get(index).copied().ok_or_else(|| invalid("missing triangle face"))?;
let look = faces.binary_search_by_key(&face, |f| f.face).ok().and_then(|i| faces.get(i));
let opacity = look.map_or(body.opacity, |f| f.opacity);
if opacity != 1.0 {
return Err(invalid("gpu-path currently requires opaque surfaces; refraction is not implemented"));
}
let color = look.map_or(body.color, |f| f.color);
let surface = look
.map_or(body.surface, |f| f.surface)
.map(Ok)
.unwrap_or_else(|| {
OpaqueSurface::new(Vec3::new(srgb8_to_linear(color[0]), srgb8_to_linear(color[1]), srgb8_to_linear(color[2])), 0.0, 0.5, 1.5)
})
.map_err(|e| invalid(&e.to_string()))?;
let mut p = [Vec3::ZERO; 3];
let mut global_indices = [0u32; 3];
for (corner, &vertex) in indices.iter().enumerate() {
let position = *mesh.positions.get(vertex as usize).ok_or_else(|| invalid("triangle index out of bounds"))? - origin;
if !position.is_finite() || [position.x, position.y, position.z].iter().any(|x| x.abs() > 1e7) {
return Err(invalid("path geometry must be finite and within 1e7 mm of the camera target"));
}
if let Some(v) = p.get_mut(corner) {
*v = position;
}
if let Some(v) = global_indices.get_mut(corner) {
*v = vertex.checked_add(vertex_offset).ok_or_else(|| invalid("vertex offset overflow"))?;
}
}
if (p[1] - p[0]).cross(p[2] - p[0]).len() <= 1e-12 {
continue;
}
triangles.push(Triangle { p, indices: global_indices, surface });
}
vertex_offset = vertex_offset.checked_add(mesh.positions.len() as u32).ok_or_else(|| invalid("vertex offset overflow"))?;
}
let mut nodes = reserved(triangles.len().saturating_mul(2).max(1))?;
nodes.push(Node::default());
build(&mut triangles, 0, &mut nodes, 0, cancel)?;
let extent = nodes.first().map_or(1.0, |n| n.lo.iter().zip(n.hi).map(|(a, b)| b - a).fold(0.0f32, f32::max));
let mut geometry = reserved(16 + triangles.len().max(1) * 48 + vertices.len())?;
let mut materials = reserved(triangles.len().max(1) * 32)?;
let vertex_word = 4 + triangles.len().max(1) * 4;
let material_word = vertex_word + vertices.len() / 4;
for word in [triangles.len() as u32, vertex_word as u32, material_word as u32, vertex_count as u32] {
geometry.extend_from_slice(&word.to_le_bytes());
}
for (material, t) in triangles.into_iter().enumerate() {
if material % 1024 == 0 {
cancel.check()?;
}
for index in t.indices {
geometry.extend_from_slice(&index.to_le_bytes());
}
geometry.extend_from_slice(&(material as u32).to_le_bytes());
vector(&mut materials, t.surface.base_color(), 0.0);
vector(&mut materials, Vec3::new(t.surface.metallic(), t.surface.roughness(), t.surface.dielectric_ior()), 0.0);
}
if geometry.len() == 16 {
geometry.resize(32, 0);
materials.resize(32, 0);
}
geometry.extend_from_slice(&vertices);
drop(vertices);
geometry.extend_from_slice(&materials);
drop(materials);
let mut node_bytes = reserved(nodes.len() * 32)?;
for node in nodes {
for x in node.lo {
node_bytes.extend_from_slice(&x.to_le_bytes());
}
node_bytes.extend_from_slice(&node.first.to_le_bytes());
for x in node.hi {
node_bytes.extend_from_slice(&x.to_le_bytes());
}
node_bytes.extend_from_slice(&node.count.to_le_bytes());
}
Ok(Upload { geometry, nodes: node_bytes, epsilon: (extent * 1e-7).max(1e-5) })
}
fn build(triangles: &mut [Triangle], offset: usize, nodes: &mut Vec<Node>, index: usize, cancel: &CancelToken) -> Result<()> {
cancel.check()?;
let mut lo = [f32::INFINITY; 3];
let mut hi = [f32::NEG_INFINITY; 3];
for t in triangles.iter() {
for p in t.p {
for ((low, high), value) in lo.iter_mut().zip(hi.iter_mut()).zip([p.x as f32, p.y as f32, p.z as f32]) {
*low = low.min(value);
*high = high.max(value);
}
}
}
let mut node = Node { lo, hi, first: offset as u32, count: triangles.len() as u32 };
if triangles.is_empty() {
node = Node { first: u32::MAX, ..Default::default() };
}
if triangles.len() > 4 {
let axis = (0..3).max_by(|&a, &b| (hi[a] - lo[a]).total_cmp(&(hi[b] - lo[b]))).unwrap_or(0);
let middle = triangles.len() / 2;
triangles.select_nth_unstable_by(middle, |a, b| a.centre(axis).total_cmp(&b.centre(axis)));
let first = nodes.len();
nodes.push(Node::default());
nodes.push(Node::default());
node.first = first as u32;
node.count = 0;
let (left, right) = triangles.split_at_mut(middle);
build(left, offset, nodes, first, cancel)?;
build(right, offset + middle, nodes, first + 1, cancel)?;
}
*nodes.get_mut(index).ok_or_else(|| invalid("missing BVH node"))? = node;
Ok(())
}
pub(super) fn vector(bytes: &mut Vec<u8>, v: Vec3, w: f32) {
for value in [v.x as f32, v.y as f32, v.z as f32, w] {
bytes.extend_from_slice(&value.to_le_bytes());
}
}
+345
View File
@@ -0,0 +1,345 @@
use super::*;
use solidcraft_geom::{Aabb3, Mesh};
use solidcraft_render::{Camera, ProductMesh, StandardView, surface::OpaqueSurface};
fn executor() -> Option<Executor> {
let (adapter, device, queue) = match crate::open_headless() {
Ok(device) => device,
Err(e) => {
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GPU unavailable: {e}");
eprintln!("gpu-path device test skipped: {e}");
return None;
}
};
eprintln!("gpu-path tests on {} ({:?}, {:?})", adapter.get_info().name, adapter.get_info().device_type, adapter.get_info().backend);
Some(Executor::new(device, queue).unwrap())
}
fn request(size: u32) -> ImageRequest {
let mut camera = Camera { distance: 4.0, ..Default::default() };
camera.set_view(StandardView::Top);
ImageRequest { camera, width: size, height: size, background: [10, 20, 30], transparent_background: false }
}
fn sphere(surface: OpaqueSurface) -> ProductScene {
sphere_grid(surface, 48, 96)
}
fn sphere_grid(surface: OpaqueSurface, rows: u32, columns: u32) -> ProductScene {
sphere_section(surface, rows, columns, rows)
}
fn sphere_section(surface: OpaqueSurface, rows: u32, columns: u32, rings: u32) -> ProductScene {
// Original unit sphere, deliberately triangulated here rather than imported test data.
let mut mesh = Mesh::default();
for i in 0..=rings {
let theta = f64::from(i) * std::f64::consts::PI / f64::from(rows);
for j in 0..=columns {
let phi = f64::from(j) * std::f64::consts::TAU / f64::from(columns);
let n = Vec3::new(theta.sin() * phi.cos(), theta.sin() * phi.sin(), theta.cos());
mesh.positions.push(n);
mesh.normals.push(n);
}
}
for i in 0..rings {
for j in 0..columns {
let a = i * (columns + 1) + j;
let b = a + columns + 1;
mesh.triangles.extend([[a, b, a + 1], [a + 1, b, b + 1]]);
mesh.tri_face.extend([0, 0]);
}
}
let bounds = mesh.bounds();
ProductScene {
meshes: vec![ProductMesh {
name: "original sphere".into(),
mesh: Arc::new(mesh),
color: [255; 3],
opacity: 1.0,
surface: Some(surface),
faces: Vec::new(),
}],
bounds,
}
}
fn white() -> OpaqueSurface {
OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 1.0, 1.0).unwrap()
}
#[test]
fn shader_validates_without_a_device() {
let module = naga::front::wgsl::parse_str(SHADER).unwrap();
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap();
}
#[test]
fn admission_rejects_hostile_parameters_and_transparency() {
let mut scene = sphere(white());
let mut r = request(16);
for size in [0, 4097, u32::MAX] {
r.width = size;
assert!(admission(&scene, &r, JobOptions::default()).is_err());
}
r.width = 16;
for samples in [0, 4097, u32::MAX] {
assert!(admission(&scene, &r, JobOptions { samples, ..Default::default() }).is_err());
}
for depth in [0, 17, u32::MAX] {
assert!(admission(&scene, &r, JobOptions { max_depth: depth, ..Default::default() }).is_err());
}
for ev in [f64::NAN, f64::INFINITY, 33.0] {
assert!(admission(&scene, &r, JobOptions { exposure_ev: ev, ..Default::default() }).is_err());
}
scene.meshes[0].opacity = 0.5;
assert!(admission(&scene, &r, JobOptions::default()).is_err());
scene.meshes[0].opacity = 1.0;
Arc::make_mut(&mut scene.meshes[0].mesh).triangles[0][0] = u32::MAX;
assert!(scene::flatten(&scene, Vec3::ZERO, &CancelToken::default()).is_err());
}
#[test]
fn admission_applies_the_gpu_estimate_instead_of_the_cpu_raster_budget() {
// A library-bounded source (not an ordinary UI scene): about 100 MiB of face appearances
// on a small mesh at the largest image. Its CPU raster estimate is above 384 MiB (covered
// in the render crate); the GPU's own estimate stays within its 512 MiB job cap.
let count = (100 * 1024 * 1024 / std::mem::size_of::<solidcraft_render::FaceAppearance>()).min(1_000_000);
let mut scene = sphere(white());
let appearance = solidcraft_render::FaceAppearance { face: 0, color: [255; 3], opacity: 1.0, surface: None };
scene.meshes[0].faces = vec![appearance; count];
let r = request(2048);
let a = admission(&scene, &r, JobOptions::default()).unwrap();
assert!(a.estimated_total_bytes <= 512 * 1024 * 1024, "{a:?}");
assert_eq!(a.face_appearances, count as u64);
// The CPU host still rejects the same source.
assert_eq!(solidcraft_render::job::admit(&scene, &r).unwrap_err().code, ErrorCode::LimitExceeded);
}
#[test]
fn bvh_handles_empty_and_cancelled_scenes() {
let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
let upload = scene::flatten(&empty, Vec3::ZERO, &CancelToken::default()).unwrap();
assert_eq!(upload.nodes.len(), 32);
assert_eq!(&upload.nodes[12..16], &u32::MAX.to_le_bytes());
let cancel = CancelToken::default();
cancel.cancel();
assert_eq!(scene::flatten(&sphere(white()), Vec3::ZERO, &cancel).err().unwrap().code, ErrorCode::Cancelled);
}
#[test]
fn gpu_brdf_matches_f64_surface_oracle() {
let Some(executor) = executor() else { return };
let context = &executor.context;
let shader = context
.device
.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("path BRDF reference"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&context.layout)],
immediate_size: 0,
});
let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: Some(&layout),
module: &shader,
entry_point: Some("reference"),
compilation_options: Default::default(),
cache: None,
});
for metallic in [0.0, 0.5, 1.0] {
for roughness in [0.045, 0.25, 1.0] {
for ior in [1.0, 1.5, 3.0] {
let surface = OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.2), metallic, roughness, ior).unwrap();
let mut task = Task::new(context.clone(), sphere(surface), request(1), JobOptions::default(), CancelToken::default()).unwrap();
for (view, light) in [
(Vec3::Z, Vec3::Z),
(Vec3::new(0.5, 0.2, 1.0), Vec3::new(-0.4, 0.3, 0.8)),
(Vec3::new(1.0, 0.0, 0.02), Vec3::new(-1.0, 0.1, 0.02)),
] {
let view = view.normalized().unwrap();
let light = light.normalized().unwrap();
let mut params = vec![0; 48];
scene::vector(&mut params, light, 0.0);
scene::vector(&mut params, Vec3::Z, 0.0);
scene::vector(&mut params, view, 0.0);
scene::vector(&mut params, Vec3::ZERO, 0.0);
context.queue.write_buffer(&task.uniform, 0, &params);
let mut encoder = context.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &task.bind, &[]);
pass.dispatch_workgroups(1, 1, 1);
}
context.queue.submit([encoder.finish()]);
task.sample = 1;
let actual = task.read_linear().unwrap()[0];
let expected = surface.brdf(Vec3::Z, view, light).unwrap();
for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) {
assert!((f64::from(*a) - b).abs() <= 3e-3 * b.abs() + 2e-5, "m={metallic}, r={roughness}, ior={ior}: {a} vs {b}");
}
}
}
}
}
}
#[test]
fn gpu_tiny_scene_matches_cpu_studio_with_face_appearance() {
let Some(executor) = executor() else { return };
let surface = OpaqueSurface::new(Vec3::new(0.7, 0.2, 0.1), 0.5, 0.3, 1.5).unwrap();
let mesh = Mesh {
positions: vec![Vec3::new(-3.0, -3.0, 0.0), Vec3::new(3.0, -3.0, 0.0), Vec3::new(3.0, 3.0, 0.0), Vec3::new(-3.0, 3.0, 0.0)],
normals: vec![Vec3::Z; 4],
triangles: vec![[0, 1, 2], [0, 2, 3]],
tri_face: vec![7, 9],
..Default::default()
};
let bounds = mesh.bounds();
let scene = ProductScene {
meshes: vec![ProductMesh {
name: "reference plane".into(),
mesh: Arc::new(mesh),
color: [255; 3],
opacity: 1.0,
surface: Some(white()),
faces: [7, 9].map(|face| solidcraft_render::FaceAppearance { face, color: [0; 3], opacity: 1.0, surface: Some(surface) }).to_vec(),
}],
bounds,
};
let mut task =
Task::new(executor.context.clone(), scene, request(4), JobOptions { samples: 4, max_depth: 1, ..Default::default() }, CancelToken::default())
.unwrap();
for _ in 0..4 {
task.dispatch().unwrap();
}
let actual = task.read_linear().unwrap();
let expected = solidcraft_render::studio::shade(surface, Vec3::Z, Vec3::Z).unwrap();
for pixel in actual {
assert_eq!(pixel[3], 1.0);
for (a, b) in pixel.iter().zip([expected.x, expected.y, expected.z]) {
assert!((f64::from(*a) - b).abs() < 3e-3 * b.abs() + 2e-5, "{a} vs {b}");
}
}
}
#[test]
fn gpu_furnace_fixed_seed_and_cancellation() {
let Some(executor) = executor() else { return };
let options = JobOptions { samples: 4096, max_depth: 8, seed: 37, ..Default::default() };
let mut task = Task::new(executor.context.clone(), sphere(white()), request(8), options, CancelToken::default()).unwrap();
task.environment = 1.0;
task.studio = 0.0;
for _ in 0..options.samples {
task.dispatch().unwrap();
}
let result = task.read_linear().unwrap();
eprintln!("furnace centre {:?}; BVH {:.3} ms; upload {} bytes / {:.3} ms", result[27], task.metrics.0, task.metrics.1, task.metrics.2);
// The oracle includes Schlick entry/exit attenuation even at IOR=1, plus single-
// scattering GGX. It is near-white, not an exactly energy-preserving Lambert model.
for index in [27, 28, 35, 36] {
assert!((result[index][0] - 1.0).abs() < 0.07, "furnace radiance: {:?}", result[index]);
}
let mut repeat = Task::new(executor.context.clone(), sphere(white()), request(8), options, CancelToken::default()).unwrap();
repeat.environment = 1.0;
repeat.studio = 0.0;
for _ in 0..options.samples {
repeat.dispatch().unwrap();
}
assert_eq!(result, repeat.read_linear().unwrap(), "fixed sample indices and seed must repeat on the same adapter");
let token = CancelToken::default();
let mut cancelled = Task::new(executor.context.clone(), sphere(white()), request(16), options, token.clone()).unwrap();
cancelled.dispatch().unwrap();
token.cancel();
assert_eq!(cancelled.step(4096).err().unwrap().code, ErrorCode::Cancelled);
}
#[test]
fn skinny_polar_triangles_do_not_shadow_themselves() {
let Some(executor) = executor() else { return };
let mut image = request(32);
image.camera.distance = 16.0;
image.camera.fov = 0.0005;
let mut task = Task::new(
executor.context.clone(),
sphere_section(white(), 512, 1024, 1),
image,
JobOptions { samples: 1, max_depth: 1, ..Default::default() },
CancelToken::default(),
)
.unwrap();
task.dispatch().unwrap();
let pixels = task.read_linear().unwrap();
for (index, pixel) in pixels.iter().enumerate() {
assert_eq!(pixel[3], 1.0, "polar cap covers the image: {index} {pixel:?}");
assert!(pixel[0] > 0.1, "outward-facing cap must receive unobstructed studio light: {index} {pixel:?}");
}
}
#[test]
fn native_host_cancel_never_publishes_a_frame() {
let Some(executor) = executor() else { return };
let host = ImageHost::with_executor(Arc::new(executor)).unwrap();
let job = host
.submit_with_options(
solidcraft_render::job::JobId { session: 1, serial: 1, generation: 1 },
1,
sphere(white()),
request(64),
JobOptions { samples: 4096, ..Default::default() },
)
.unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let status = job.status().unwrap();
if status.progress.phase == Phase::Running {
break;
}
assert!(!status.progress.phase.terminal(), "{status:?}");
assert!(Instant::now() < deadline);
std::thread::sleep(Duration::from_millis(5));
}
job.cancel().unwrap();
assert_eq!(job.wait_timeout(Duration::from_secs(30)).unwrap().progress.phase, Phase::Cancelled);
assert!(job.frame().unwrap().is_none());
}
/// Explicit benchmark: large allocation and sustained GPU load must not run in ordinary CI.
#[test]
#[ignore = "manual 1M-triangle 1920x1080 GPU performance measurement"]
fn path_performance() {
let executor = executor().expect("benchmark requires an adapter");
let samples = std::env::var("SOLIDCRAFT_PATH_BENCH_SAMPLES").ok().map(|s| s.parse::<u32>().unwrap()).unwrap_or(1);
let options = JobOptions { samples, ..Default::default() };
options.validate().unwrap();
let surface = OpaqueSurface::new(Vec3::new(0.8, 0.4, 0.2), 0.25, 0.4, 1.5).unwrap();
let scene = sphere_grid(surface, 512, 1024);
let mut request = request(1920);
request.height = 1080;
let admitted = executor.admit(&scene, &request, options).unwrap();
let mut task = Task::new(executor.context.clone(), scene, request, options, CancelToken::default()).unwrap();
let started = Instant::now();
while task.sample < samples {
task.dispatch().unwrap();
}
let seconds = started.elapsed().as_secs_f64();
let linear = task.read_linear().unwrap();
assert!(linear.iter().all(|p| p.iter().all(|v| v.is_finite())));
let coverage = linear.iter().map(|p| f64::from(p[3])).sum::<f64>() / linear.len() as f64;
assert!((0.16..0.19).contains(&coverage), "sphere must occupy the expected projected area: {coverage}");
let centre = linear[540 * 1920 + 960];
let lit = linear.iter().filter(|p| p[0] > 0.01).count();
eprintln!(
"PATH_BENCH_DIAGNOSTIC coverage={coverage:.6} centre={centre:?} lit_pixels={lit} nearby={:?}",
[linear[500 * 1920 + 960], linear[540 * 1920 + 1000], linear[580 * 1920 + 960]]
);
assert_eq!(centre[3], 1.0);
assert!(centre[0] > 0.01, "benchmark must actually shade the sphere: {centre:?}");
eprintln!("PATH_BENCH_IMAGE coverage={coverage:.6} centre={centre:?}");
eprintln!(
"PATH_BENCH input_triangles={} resolution=1920x1080 spp={} bvh_ms={:.3} upload_bytes={} upload_ms={:.3} admitted_bytes={} render_seconds={:.6} ms_per_spp={:.3}",
admitted.triangles,
samples,
task.metrics.0,
task.metrics.1,
task.metrics.2,
admitted.estimated_total_bytes,
seconds,
seconds * 1000.0 / f64::from(samples)
);
}
+2 -2
View File
@@ -91,7 +91,7 @@ impl Policy {
}
}
fn admits(self, tier: Tier) -> bool {
pub(crate) fn admits(self, tier: Tier) -> bool {
match self {
Policy::Auto => true,
Policy::Hardware => tier == Tier::Hardware,
@@ -139,7 +139,7 @@ pub fn native_backends() -> wgpu::Backends {
}
}
fn tier_of(t: wgpu::DeviceType) -> Tier {
pub(crate) fn tier_of(t: wgpu::DeviceType) -> Tier {
match t {
wgpu::DeviceType::Cpu => Tier::Software,
wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu | wgpu::DeviceType::VirtualGpu | wgpu::DeviceType::Other => Tier::Hardware,
+114 -41
View File
@@ -1,4 +1,4 @@
//! Caller-owned CPU execution host. One worker, two bounded queued inputs; browser pumping
//! Caller-owned image execution host. One worker, two bounded queued inputs; browser pumping
//! uses the same incremental task without threads. Shared ownership never includes CAD state.
use std::collections::VecDeque;
@@ -12,8 +12,8 @@ use std::sync::{
use serde::Serialize;
use super::{
Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageRequest, ImageTask, JobError, JobId, Phase, Progress, Result,
TaskPoll, admit,
Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageExecutor, ImageRequest, ImageTask, ImageWork, JobError,
JobId, JobOptions, Phase, Progress, Result, TaskPoll, admit,
};
use crate::{
Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout,
@@ -48,7 +48,7 @@ impl Budget {
let next = used
.checked_add(bytes)
.filter(|n| *n <= MEMORY_LIMIT)
.ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "CPU image host's 512 MiB admission pool is full"))?;
.ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "image host's 512 MiB admission pool is full"))?;
match self.used.compare_exchange_weak(used, next, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => break,
Err(current) => used = current,
@@ -91,6 +91,7 @@ pub struct JobStatus {
pub scene_generation: u64,
pub request: ImageRequest,
pub resolved: crate::ResolvedRequest,
pub options: JobOptions,
pub progress: Progress,
pub error: Option<JobError>,
pub frame: Option<FrameInfo>,
@@ -107,6 +108,7 @@ struct Record {
request: ImageRequest,
resolved: crate::ResolvedRequest,
cancel: CancelToken,
options: JobOptions,
data: Mutex<Data>,
#[cfg(not(target_arch = "wasm32"))]
done: Condvar,
@@ -133,6 +135,7 @@ impl JobHandle {
scene_generation: self.0.scene_generation,
request: self.0.request.clone(),
resolved: self.0.resolved.clone(),
options: self.0.options,
progress: data.progress,
error: data.error.clone(),
frame: data.frame.as_ref().map(|f| f.info.clone()),
@@ -176,12 +179,15 @@ impl JobHandle {
}
struct Work {
executor: Arc<dyn ImageExecutor>,
scene: ProductScene,
handle: JobHandle,
reservation: Reservation,
}
struct Running {
task: ImageTask,
/// Taken and dropped as the frame completes, before the reservation shrinks to the PNG: the
/// task owns its scratch (pixels, device buffers), which the full reservation pays for.
task: Option<Box<dyn ImageWork>>,
handle: JobHandle,
reservation: Option<Reservation>,
}
@@ -214,9 +220,12 @@ impl Running {
{
data.progress.phase = Phase::Preparing;
}
let task = ImageTask::new(work.scene, work.handle.0.request.clone(), work.handle.0.cancel.clone());
let task = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
work.executor.begin(work.scene, work.handle.0.request.clone(), work.handle.0.options, work.handle.0.cancel.clone())
}))
.unwrap_or_else(|_| Err(JobError::new(ErrorCode::Internal, "image executor failed while preparing the job")));
match task {
Ok(task) => Some(Self { task, handle: work.handle, reservation: Some(work.reservation) }),
Ok(task) => Some(Self { task: Some(task), handle: work.handle, reservation: Some(work.reservation) }),
Err(e) => {
terminal(&work.handle, e);
None
@@ -225,7 +234,8 @@ impl Running {
}
fn advance(&mut self, units: usize) -> Result<bool> {
let result = self.task.step(units)?;
let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "render task already finished"))?;
let result = task.step(units)?;
let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?;
// The final publication check is under the same lock as cancellation.
if self.handle.0.cancel.is_cancelled() {
@@ -240,6 +250,8 @@ impl Running {
Ok(true)
}
TaskPoll::Complete(png) => {
// The task's scratch goes before its charge does (still under the publication lock).
drop(self.task.take());
let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?;
reservation.shrink(png.capacity() as u64 + 1024)?;
let info = FrameInfo {
@@ -269,7 +281,7 @@ impl Running {
false
}
Err(_) => {
terminal(&self.handle, JobError::new(ErrorCode::Internal, "CPU image host encountered an internal error"));
terminal(&self.handle, JobError::new(ErrorCode::Internal, "image host encountered an internal error"));
false
}
}
@@ -286,6 +298,7 @@ struct Shared {
}
struct Owner {
executor: Arc<dyn ImageExecutor>,
shared: Arc<Shared>,
kind: HostKind,
running: Mutex<Option<Running>>,
@@ -320,9 +333,12 @@ impl Drop for Owner {
}
#[derive(Clone)]
pub struct CpuHost(Arc<Owner>);
pub struct ImageHost(Arc<Owner>);
impl CpuHost {
/// Backwards-compatible CPU host constructors. Additional executors use `ImageHost::with_executor`.
pub type CpuHost = ImageHost;
impl ImageHost {
fn shared() -> Arc<Shared> {
Arc::new(Shared {
queue: Mutex::new(VecDeque::new()),
@@ -335,7 +351,13 @@ impl CpuHost {
}
pub fn cooperative() -> Self {
Self::cooperative_with(Arc::new(CpuExecutor))
}
/// A cooperative host over `executor` (pumped by its caller).
fn cooperative_with(executor: Arc<dyn ImageExecutor>) -> Self {
Self(Arc::new(Owner {
executor,
shared: Self::shared(),
kind: HostKind::Cooperative,
running: Mutex::new(None),
@@ -351,16 +373,31 @@ impl CpuHost {
}
#[cfg(not(target_arch = "wasm32"))]
{
let shared = Self::shared();
let worker_shared = shared.clone();
let worker = std::thread::Builder::new()
.name("solidcraft-render".into())
.spawn(move || native_worker(worker_shared))
.map_err(|e| JobError::new(ErrorCode::HostUnavailable, format!("could not start CPU image worker: {e}")))?;
Ok(Self(Arc::new(Owner { shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) })))
Self::with_executor(Arc::new(CpuExecutor))
}
}
/// Start an isolated bounded native worker. GPU discovery occurs before registration.
#[cfg(not(target_arch = "wasm32"))]
pub fn with_executor(executor: Arc<dyn ImageExecutor>) -> Result<Self> {
let descriptor = executor.descriptor()?;
if descriptor.profiles.len() != 1
|| descriptor
.profiles
.iter()
.any(|p| p.mode != RenderMode::Preview || p.operation != RenderOperation::Image || p.formats != [RenderFormat::Png])
{
return Err(JobError::new(ErrorCode::InvalidRequest, "image worker currently accepts one Preview/Image/PNG profile"));
}
let shared = Self::shared();
let worker_shared = shared.clone();
let worker = std::thread::Builder::new()
.name("solidcraft-render".into())
.spawn(move || native_worker(worker_shared))
.map_err(|e| JobError::new(ErrorCode::HostUnavailable, format!("could not start image worker: {e}")))?;
Ok(Self(Arc::new(Owner { executor, shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) })))
}
pub fn kind(&self) -> HostKind {
self.0.kind
}
@@ -376,31 +413,38 @@ impl CpuHost {
}
pub fn descriptor(&self) -> Result<ExecutorDescriptor> {
Ok(ExecutorDescriptor {
id: ExecutorId::new("cpu-product").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?,
availability: if self.0.shared.stop.load(Ordering::Acquire) {
Availability::Unavailable { reason: "CPU image host has stopped".into() }
} else {
Availability::Available
},
profiles: vec![RenderProfile {
mode: RenderMode::Preview,
operation: RenderOperation::Image,
formats: vec![RenderFormat::Png],
features: vec![crate::RenderFeature::Pbr],
}],
limits: RenderLimits::default(),
scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 },
})
let mut descriptor = self.0.executor.descriptor()?;
if !self.is_available() {
descriptor.availability = Availability::Unavailable { reason: "image host has stopped".into() };
}
Ok(descriptor)
}
pub fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result<Admission> {
options.validate()?;
self.0.executor.admit(scene, request, options)
}
pub fn submit(&self, id: JobId, scene_generation: u64, scene: ProductScene, request: ImageRequest) -> Result<JobHandle> {
self.submit_with_options(id, scene_generation, scene, request, JobOptions::default())
}
pub fn submit_with_options(
&self,
id: JobId,
scene_generation: u64,
scene: ProductScene,
request: ImageRequest,
options: JobOptions,
) -> Result<JobHandle> {
if id.session == 0 || id.serial == 0 || id.generation == 0 {
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity"));
}
let Admission { estimated_total_bytes, .. } = admit(&scene, &request)?;
let Admission { estimated_total_bytes, .. } = self.admit(&scene, &request, options)?;
let mut backend = crate::builtin_backend();
backend.executors.push(self.descriptor()?);
let descriptor = self.descriptor()?;
let executor = descriptor.id.clone();
backend.executors = vec![descriptor];
let resolved = crate::resolve_request(
&[backend],
&crate::RenderRequest {
@@ -415,16 +459,16 @@ impl CpuHost {
},
)
.map_err(|e| JobError::new(ErrorCode::HostUnavailable, e.to_string()))?;
if resolved.executor.as_str() != "cpu-product" {
return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product executor is unavailable"));
if resolved.executor != executor {
return Err(JobError::new(ErrorCode::HostUnavailable, "image executor is unavailable"));
}
let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?;
if self.0.shared.stop.load(Ordering::Acquire) {
return Err(JobError::new(ErrorCode::HostUnavailable, "CPU image host has stopped"));
return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped"));
}
queue.retain(|work| !work.handle.0.cancel.is_cancelled());
if queue.len() >= QUEUE_LIMIT {
return Err(JobError::new(ErrorCode::QueueFull, "CPU image queue is full"));
return Err(JobError::new(ErrorCode::QueueFull, "image queue is full"));
}
let reservation = self.0.shared.budget.reserve(estimated_total_bytes)?;
let handle = JobHandle(Arc::new(Record {
@@ -433,11 +477,12 @@ impl CpuHost {
request,
resolved,
cancel: CancelToken::default(),
options,
data: Mutex::new(Data { progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, error: None, frame: None }),
#[cfg(not(target_arch = "wasm32"))]
done: Condvar::new(),
}));
queue.push_back(Work { scene, handle: handle.clone(), reservation });
queue.push_back(Work { executor: self.0.executor.clone(), scene, handle: handle.clone(), reservation });
drop(queue);
#[cfg(not(target_arch = "wasm32"))]
self.0.shared.wake.notify_one();
@@ -514,3 +559,31 @@ fn native_worker(shared: Arc<Shared>) {
}
}
}
struct CpuExecutor;
impl ImageExecutor for CpuExecutor {
fn descriptor(&self) -> Result<ExecutorDescriptor> {
Ok(ExecutorDescriptor {
id: ExecutorId::new("cpu-product").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?,
availability: Availability::Available,
profiles: vec![RenderProfile {
mode: RenderMode::Preview,
operation: RenderOperation::Image,
formats: vec![RenderFormat::Png],
features: vec![crate::RenderFeature::Pbr],
}],
limits: RenderLimits::default(),
scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 },
})
}
fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result<Admission> {
if options != JobOptions::default() {
return Err(JobError::new(ErrorCode::InvalidRequest, "CPU product does not support sampling or exposure controls"));
}
admit(scene, request)
}
fn begin(&self, scene: ProductScene, request: ImageRequest, _options: JobOptions, cancel: CancelToken) -> Result<Box<dyn ImageWork>> {
Ok(Box::new(ImageTask::new(scene, request, cancel)?))
}
}
+88
View File
@@ -129,3 +129,91 @@ fn native_job_finishes_without_any_poll_or_ui_pump() {
assert_eq!(status.progress.phase, Phase::Completed);
assert_eq!(job.frame().unwrap().unwrap().info.scene_generation, 12);
}
/// An executor whose task reports, as it is dropped, how much of the pool is admitted, and
/// completes after `steps` steps (or never, cancelled on its last one with `cancel_last`).
struct DropProbe {
admitted_at_drop: Arc<AtomicU64>,
budget: Arc<std::sync::OnceLock<Arc<Budget>>>,
estimated: u64,
}
struct ProbeTask {
admitted_at_drop: Arc<AtomicU64>,
budget: Arc<std::sync::OnceLock<Arc<Budget>>>,
steps: u32,
}
impl Drop for ProbeTask {
fn drop(&mut self) {
let used = self.budget.get().map_or(u64::MAX, |b| b.used.load(Ordering::Acquire));
self.admitted_at_drop.store(used, Ordering::Release);
}
}
impl ImageWork for ProbeTask {
fn step(&mut self, _units: usize) -> Result<TaskPoll> {
self.steps += 1;
if self.steps < 3 {
return Ok(TaskPoll::Pending(Progress { phase: Phase::Running, done: u64::from(self.steps), total: 3 }));
}
Ok(TaskPoll::Complete(vec![0u8; 100]))
}
}
impl ImageExecutor for DropProbe {
fn descriptor(&self) -> Result<ExecutorDescriptor> {
CpuExecutor.descriptor()
}
fn admit(&self, _: &ProductScene, _: &ImageRequest, _: JobOptions) -> Result<Admission> {
Ok(Admission {
triangles: 0,
face_appearances: 0,
geometry_bytes: 0,
pixel_scratch_bytes: self.estimated,
preparation_bytes: 0,
estimated_total_bytes: self.estimated,
encoded_limit: 4096,
})
}
fn begin(&self, _: ProductScene, _: ImageRequest, _: JobOptions, _: CancelToken) -> Result<Box<dyn ImageWork>> {
Ok(Box::new(ProbeTask { admitted_at_drop: self.admitted_at_drop.clone(), budget: self.budget.clone(), steps: 0 }))
}
}
fn probe_host(estimated: u64) -> (CpuHost, Arc<AtomicU64>) {
let admitted_at_drop = Arc::new(AtomicU64::new(0));
let budget = Arc::new(std::sync::OnceLock::new());
let host = CpuHost::cooperative_with(Arc::new(DropProbe { admitted_at_drop: admitted_at_drop.clone(), budget: budget.clone(), estimated }));
let _ = budget.set(host.0.shared.budget.clone());
(host, admitted_at_drop)
}
#[test]
fn a_completed_task_is_dropped_while_its_full_reservation_still_pays_for_it() {
let estimated = 1 << 20;
let (host, admitted_at_drop) = probe_host(estimated);
let job = host.submit(id(1, 1), 1, empty(), request()).unwrap();
drain(&host);
assert_eq!(job.status().unwrap().progress.phase, Phase::Completed);
// While the task (and its scratch) was being dropped, its whole charge was still held.
assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated);
// Afterwards only the PNG's lease remains, and the frame keeps it.
let frame = job.frame().unwrap().unwrap();
assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < estimated, "{}", host.admitted_bytes());
drop(job);
drop(frame);
assert_eq!(host.admitted_bytes(), 0);
}
#[test]
fn a_cancel_on_the_final_step_publishes_no_frame_and_drops_the_task() {
let estimated = 1 << 20;
let (host, admitted_at_drop) = probe_host(estimated);
let job = host.submit(id(1, 1), 1, empty(), request()).unwrap();
// Two pending steps, then cancel before the step that would complete.
host.pump(1).unwrap();
host.pump(1).unwrap();
job.cancel().unwrap();
drain(&host);
assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled);
assert!(job.frame().unwrap().is_none());
assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated, "the task went before its charge");
assert_eq!(host.admitted_bytes(), 0);
}
+54 -17
View File
@@ -49,7 +49,29 @@ fn add_bytes(sum: &mut u64, count: usize, size: usize) -> Result<()> {
/// Conservative admission before allocating pixels or projected-work lists. Source Arcs are
/// counted even when another owner already holds them. Allocator and codec internals are estimates.
/// Includes the CPU raster work estimate and its 384 MiB per-job check.
pub fn admit(scene: &ProductScene, request: &ImageRequest) -> Result<Admission> {
admit_raster(admit_source(scene, request, MAX_TRIANGLES)?)
}
/// Common camera, dimension and source admission for registered executors, without any CPU
/// raster estimate: the returned admission counts retained source geometry only
/// (`pixel_scratch_bytes` and `preparation_bytes` are zero). Executors budget their own
/// preparation and pixel storage, apply their own job limit, and validate triangle contents
/// before uploading anything to a device.
pub fn admit_geometry(scene: &ProductScene, request: &ImageRequest, max_triangles: u64) -> Result<Admission> {
Ok(admit_source(scene, request, max_triangles)?.admission)
}
/// A validated source with its geometry accounting, and the builtin raster scratch estimate
/// for the requested dimensions (used only by the CPU estimate).
struct Source {
admission: Admission,
bodies: u64,
raster_scratch_bytes: u64,
}
fn admit_source(scene: &ProductScene, request: &ImageRequest, max_triangles: u64) -> Result<Source> {
if !request.camera.is_valid() {
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid image camera"));
}
@@ -77,8 +99,8 @@ pub fn admit(scene: &ProductScene, request: &ImageRequest) -> Result<Admission>
triangles = triangles.checked_add(m.triangles.len() as u64).ok_or_else(|| limit("triangle count overflow"))?;
faces = faces.checked_add(body.faces.len() as u64).ok_or_else(|| limit("appearance count overflow"))?;
polylines = polylines.checked_add(m.edges.len() as u64 + m.edge_faces.len() as u64).ok_or_else(|| limit("edge count overflow"))?;
if triangles > MAX_TRIANGLES || faces > MAX_TRIANGLES || polylines > MAX_TRIANGLES {
return Err(limit("product image exceeds the 262144 triangle/appearance/polyline admission cap"));
if triangles > max_triangles || faces > max_triangles || polylines > max_triangles {
return Err(limit("product image exceeds its triangle/appearance/polyline admission cap"));
}
add_bytes(&mut geometry, m.positions.capacity(), std::mem::size_of::<Vec3>())?;
add_bytes(&mut geometry, m.normals.capacity(), std::mem::size_of::<Vec3>())?;
@@ -104,29 +126,44 @@ pub fn admit(scene: &ProductScene, request: &ImageRequest) -> Result<Admission>
return Err(invalid("invalid body opacity"));
}
}
let encoded_limit = u64::from(request.width) * u64::from(request.height) * 8 + 65_536;
Ok(Source {
admission: Admission {
triangles,
face_appearances: faces,
geometry_bytes: geometry,
pixel_scratch_bytes: 0,
preparation_bytes: 0,
estimated_total_bytes: geometry,
encoded_limit,
},
bodies: scene.meshes.len() as u64,
raster_scratch_bytes: resolved.estimated_scratch_bytes,
})
}
/// The CPU raster scratch/preparation estimate and its 384 MiB per-job check.
fn admit_raster(source: Source) -> Result<Admission> {
let mut a = source.admission;
// Three bounded 16-byte lists, a conservative map-node allowance, and codec overhead.
let preparation = triangles
let preparation = a
.triangles
.checked_mul(48)
.and_then(|n| faces.checked_mul(160).and_then(|f| n.checked_add(f)))
.and_then(|n| n.checked_add(scene.meshes.len() as u64 * 128 + 262_144))
.and_then(|n| a.face_appearances.checked_mul(160).and_then(|f| n.checked_add(f)))
.and_then(|n| n.checked_add(source.bodies * 128 + 262_144))
.ok_or_else(|| limit("work list size overflow"))?;
let total = geometry
let total = a
.geometry_bytes
.checked_add(preparation)
.and_then(|n| n.checked_add(resolved.estimated_scratch_bytes))
.and_then(|n| n.checked_add(source.raster_scratch_bytes))
.ok_or_else(|| limit("image memory overflow"))?;
if total > MAX_JOB_BYTES {
return Err(limit("product job exceeds its 384 MiB admission estimate"));
}
let encoded_limit = u64::from(request.width) * u64::from(request.height) * 8 + 65_536;
Ok(Admission {
triangles,
face_appearances: faces,
geometry_bytes: geometry,
pixel_scratch_bytes: resolved.estimated_scratch_bytes,
preparation_bytes: preparation,
estimated_total_bytes: total,
encoded_limit,
})
a.pixel_scratch_bytes = source.raster_scratch_bytes;
a.preparation_bytes = preparation;
a.estimated_total_bytes = total;
Ok(a)
}
fn reserve<T>(count: usize) -> Result<Vec<T>> {
+22
View File
@@ -145,3 +145,25 @@ fn png_output_budget_and_cancellation_fail_without_partial_publication() {
assert!(writer.flush().is_err());
assert_eq!(*bytes.lock().unwrap(), b"PNG");
}
#[test]
fn registered_executor_geometry_admission_excludes_the_cpu_raster_estimate() {
// A library-bounded source: about 100 MiB of face appearances on a small mesh at the
// largest image. Its CPU raster estimate is above 384 MiB at a registered executor's cap.
let count = (100 * 1024 * 1024 / std::mem::size_of::<FaceAppearance>()).min(1_000_000);
let mut body = square("appearances", [200; 3], 1.0, Vec3::ZERO);
body.faces = vec![FaceAppearance { face: 0, color: [200; 3], opacity: 1.0, surface: None }; count];
let source = scene(vec![body]);
let mut r = request();
r.width = 2048;
r.height = 2048;
let cpu = admit_raster(admit_source(&source, &r, 1_048_576).unwrap()).unwrap_err();
assert_eq!(cpu.code, ErrorCode::LimitExceeded);
assert!(cpu.message.contains("384 MiB"), "{}", cpu.message);
let geometry = admit_geometry(&source, &r, 1_048_576).unwrap();
assert_eq!((geometry.pixel_scratch_bytes, geometry.preparation_bytes), (0, 0));
assert_eq!(geometry.estimated_total_bytes, geometry.geometry_bytes);
assert_eq!(geometry.face_appearances, count as u64);
// The CPU host itself keeps rejecting the source.
assert_eq!(admit(&source, &r).unwrap_err().code, ErrorCode::LimitExceeded);
}
+52 -3
View File
@@ -1,4 +1,4 @@
//! CPU product-image work and its device-independent, session-scoped protocol.
//! Product-image work and its device-independent, session-scoped protocol.
//! Hosts own execution; documents and history never contain these values.
use std::fmt;
@@ -13,8 +13,57 @@ use crate::{BackendId, Camera, ExecutorId};
mod host;
mod image;
pub use host::{CpuHost, HostKind, JobHandle, JobStatus, RenderFrame};
pub use image::{Admission, ImageTask, TaskPoll, admit};
mod png;
pub use host::{CpuHost, HostKind, ImageHost, JobHandle, JobStatus, RenderFrame};
pub use image::{Admission, ImageTask, TaskPoll, admit, admit_geometry};
pub use png::PngTask;
/// Runtime sampling intent, separate from saved documents and device resources.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct JobOptions {
pub samples: u32,
pub max_depth: u32,
pub seed: u32,
pub exposure_ev: f64,
}
impl Default for JobOptions {
fn default() -> Self {
Self { samples: 64, max_depth: 8, seed: 0, exposure_ev: 0.0 }
}
}
impl JobOptions {
pub fn validate(&self) -> Result<()> {
if !(1..=4096).contains(&self.samples)
|| !(1..=16).contains(&self.max_depth)
|| !self.exposure_ev.is_finite()
|| !(-32.0..=32.0).contains(&self.exposure_ev)
{
return Err(JobError::new(ErrorCode::InvalidRequest, "samples must be 1..4096, depth 1..16 and exposure -32..32 EV"));
}
Ok(())
}
}
/// One bounded quantum of image work. Implementations check cancellation between quanta.
pub trait ImageWork: Send {
fn step(&mut self, units: usize) -> Result<TaskPoll>;
}
impl ImageWork for ImageTask {
fn step(&mut self, units: usize) -> Result<TaskPoll> {
self.step(units)
}
}
/// Device-independent executor boundary. The host owns admission leases and publication;
/// an executor owns computation only. GPU implementations live above the render crate.
pub trait ImageExecutor: Send + Sync {
fn descriptor(&self) -> Result<crate::ExecutorDescriptor>;
fn admit(&self, scene: &crate::ProductScene, request: &ImageRequest, options: JobOptions) -> Result<Admission>;
fn begin(&self, scene: crate::ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result<Box<dyn ImageWork>>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
+81
View File
@@ -0,0 +1,81 @@
//! Bounded PNG encoding shared by native image executors.
use super::{CancelToken, ErrorCode, ImageRequest, ImageWork, JobError, Phase, Progress, Result, TaskPoll};
use std::{
io::Write,
sync::{Arc, Mutex},
};
struct Output {
bytes: Arc<Mutex<Vec<u8>>>,
limit: usize,
cancel: CancelToken,
}
impl Write for Output {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
if self.cancel.is_cancelled() {
return Err(std::io::Error::other("render cancelled"));
}
let mut out = self.bytes.lock().map_err(|_| std::io::Error::other("PNG lock poisoned"))?;
if out.len().checked_add(bytes.len()).is_none_or(|n| n > self.limit) {
return Err(std::io::Error::other("PNG byte limit exceeded"));
}
out.try_reserve_exact(bytes.len()).map_err(|_| std::io::Error::other("PNG allocation failed"))?;
out.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Owns admitted RGBA bytes and yields after at most four scanlines.
pub struct PngTask {
rgba: Vec<u8>,
row: usize,
width: usize,
height: usize,
bytes: Arc<Mutex<Vec<u8>>>,
writer: Option<png::StreamWriter<'static, Output>>,
cancel: CancelToken,
}
impl PngTask {
pub fn new(request: &ImageRequest, rgba: Vec<u8>, cancel: CancelToken) -> Result<Self> {
let pixels = u64::from(request.width) * u64::from(request.height);
if !(1..=4096).contains(&request.width) || !(1..=4096).contains(&request.height) || pixels > 4_194_304 || rgba.len() as u64 != pixels * 4 {
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid PNG dimensions or RGBA length"));
}
cancel.check()?;
let bytes = Arc::new(Mutex::new(Vec::new()));
let output = Output { bytes: bytes.clone(), limit: (pixels * 8 + 65_536) as usize, cancel: cancel.clone() };
let mut encoder = png::Encoder::new(output, request.width, request.height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual);
let writer = encoder.write_header().and_then(|w| w.into_stream_writer()).map_err(encoding)?;
Ok(Self { rgba, row: 0, width: request.width as usize, height: request.height as usize, bytes, writer: Some(writer), cancel })
}
}
fn encoding(e: impl std::fmt::Display) -> JobError {
JobError::new(ErrorCode::EncodingFailed, e.to_string())
}
impl ImageWork for PngTask {
fn step(&mut self, _units: usize) -> Result<TaskPoll> {
self.cancel.check()?;
for _ in 0..4 {
if self.row == self.height {
break;
}
let start = self.row * self.width * 4;
let row = self.rgba.get(start..start + self.width * 4).ok_or_else(|| encoding("missing PNG row"))?;
self.writer.as_mut().ok_or_else(|| encoding("PNG already completed"))?.write_all(row).map_err(encoding)?;
self.row += 1;
}
if self.row != self.height {
return Ok(TaskPoll::Pending(Progress { phase: Phase::Encoding, done: self.row as u64, total: self.height as u64 }));
}
self.writer.take().ok_or_else(|| encoding("PNG already completed"))?.finish().map_err(encoding)?;
self.cancel.check()?;
let mut bytes = self.bytes.lock().map_err(|_| encoding("PNG lock poisoned"))?;
Ok(TaskPoll::Complete(std::mem::take(&mut *bytes)))
}
}
+7
View File
@@ -668,6 +668,13 @@ impl SolveApp {
None
}
};
#[cfg(not(target_arch = "wasm32"))]
if self.render_workspace.path_host.is_none() {
match solidcraft_gpu::path::host_on_adapter(&rs.adapter) {
Ok(host) => self.render_workspace.path_host = Some(host),
Err(e) => log::warn!("progressive render unavailable: {e}"),
}
}
render_workspace::sync_backend(self);
self.msaa_supported = rs.msaa_supported.clone();
let info = rs.adapter.get_info();
+34 -5
View File
@@ -23,6 +23,7 @@ mod tests;
pub struct State {
pub host: Option<ExecutorDescriptor>,
pub path_host: Option<solidcraft_engine::render::job::ImageHost>,
pub image_host: Option<solidcraft_engine::render::job::CpuHost>,
pub view: ViewState,
revision: u64,
@@ -42,12 +43,24 @@ pub struct ViewState {
job: Option<solidcraft_engine::render::job::JobId>,
completed: Option<solidcraft_engine::render::job::JobId>,
transparent: bool,
progressive: bool,
samples: u32,
overwrite: bool,
}
impl Default for ViewState {
fn default() -> Self {
Self { name: "Studio".into(), draft: RenderSetup::default(), dirty: false, job: None, completed: None, transparent: false, overwrite: false }
Self {
name: "Studio".into(),
draft: RenderSetup::default(),
dirty: false,
job: None,
completed: None,
transparent: false,
progressive: false,
samples: 64,
overwrite: false,
}
}
}
@@ -55,6 +68,7 @@ impl Default for State {
fn default() -> Self {
Self {
host: None,
path_host: None,
image_host: None,
view: Default::default(),
revision: u64::MAX,
@@ -99,6 +113,12 @@ pub fn host_executor(max_dimension: u32, depth: bool, samples: u32) -> Result<Ex
}
pub fn sync_backend(app: &mut SolveApp) {
if let Some(host) = app.render_workspace.path_host.clone()
&& let Err(e) = app.session.register_render_job_host(host)
{
app.set_status(e.to_string(), true);
}
if app.session.render_job_host().is_none()
&& let Some(host) = &app.render_workspace.image_host
&& let Err(e) = app.session.set_render_job_host(Some(host.clone()))
@@ -129,7 +149,8 @@ pub fn reset_document(app: &mut SolveApp) {
app.ui.ribbon_context = None;
let host = app.render_workspace.host.clone();
let image_host = app.render_workspace.image_host.clone();
app.render_workspace = State { host, image_host, ..Default::default() };
let path_host = app.render_workspace.path_host.clone();
app.render_workspace = State { host, image_host, path_host, ..Default::default() };
if active(app) {
app.ui.tab = "MODEL".into();
}
@@ -264,7 +285,7 @@ pub fn panel(app: &mut SolveApp, ui: &mut egui::Ui) {
fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
ui.heading(app.tr("render.image_title"));
ui.small(app.tr("render.opaque_image_summary"));
ui.small(app.tr(if app.render_workspace.view.progressive { "render.progressive_image_summary" } else { "render.opaque_image_summary" }));
ui.horizontal(|ui| {
ui.label(app.tr("render.image_width"));
if crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.width, 1..=4096, 1.0, "").changed() {
@@ -287,11 +308,19 @@ fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
app.render_workspace.view.dirty = true;
}
}
if app.render_workspace.path_host.is_some() {
let label = app.tr("render.image_progressive").to_string();
ui.checkbox(&mut app.render_workspace.view.progressive, label);
if app.render_workspace.view.progressive {
let label = app.tr("render.image_samples").to_string();
ui.add(egui::Slider::new(&mut app.render_workspace.view.samples, 1..=4096).logarithmic(true).text(label));
}
}
let transparent_label = app.tr("render.image_transparent").to_string();
crate::ui_kit::checkbox(ui, &transparent_label, &mut app.render_workspace.view.transparent);
if crate::ui_kit::button(ui, app.tr("cmd.render_preflight"), crate::ui_kit::Button::Normal).clicked() {
let settings = RenderSetup { camera: app.cam, ..app.render_workspace.view.draft.clone() };
if app.run("render.preflight", json!({"settings":settings,"transparent_background":app.render_workspace.view.transparent})).is_ok() {
if app.run("render.preflight", json!({"settings":settings,"transparent_background":app.render_workspace.view.transparent,"progressive":app.render_workspace.view.progressive,"samples":app.render_workspace.view.progressive.then_some(app.render_workspace.view.samples)})).is_ok() {
app.set_status(app.tr("render.image_supported").to_string(), false);
}
}
@@ -343,7 +372,7 @@ fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
}
if crate::ui_kit::button(ui, app.tr("render.image_start"), crate::ui_kit::Button::Enabled(!busy)).clicked() {
let settings = RenderSetup { camera: app.cam, ..app.render_workspace.view.draft.clone() };
if let Ok(reply) = app.run("render.start", json!({"settings":settings,"transparent_background":app.render_workspace.view.transparent})) {
if let Ok(reply) = app.run("render.start", json!({"settings":settings,"transparent_background":app.render_workspace.view.transparent,"progressive":app.render_workspace.view.progressive,"samples":app.render_workspace.view.progressive.then_some(app.render_workspace.view.samples)})) {
app.render_workspace.view.job = serde_json::from_value(reply["job"].clone()).ok();
ui.ctx().request_repaint();
}
@@ -211,6 +211,55 @@ fn saved_camera_survives_frames_and_product_fit_ignores_selection() {
assert_eq!(h.app.cam, design);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn progressive_image_controls_route_to_the_registered_host() {
let host = solidcraft_gpu::select::Policy::from_env()
.and_then(|policy| solidcraft_gpu::select::pick(policy).ok_or_else(|| "no qualifying adapter".to_string()))
.and_then(|(adapter, _)| solidcraft_gpu::path::host_on_adapter(&adapter).map_err(|e| e.to_string()));
let host = match host {
Ok(host) => host,
Err(e) => {
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GPU unavailable: {e}");
eprintln!("skipping progressive UI device test: {e}");
return;
}
};
let mut h = Harness::new();
h.app.render_workspace.path_host = Some(host);
sync_backend(&mut h.app);
h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap();
h.app.session.mark_saved();
h.call("ui.resize", json!({"width":1600,"height":1600}));
enter(&mut h.app, true).unwrap();
h.app.render_workspace.view.draft.width = 16;
h.app.render_workspace.view.draft.height = 16;
h.app.render_workspace.view.samples = 4;
h.frames(3);
let doc = h.app.session.doc.clone();
let undo = h.app.session.undo.len();
h.step(&json!({"widget":"Progressive rendering"})).unwrap();
assert!(h.app.render_workspace.view.progressive);
let start = h.app.tr("render.image_start").to_string();
h.step(&json!({"widget":start})).unwrap();
let job = h.app.render_workspace.view.job.unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while h.app.render_workspace.view.completed.is_none() {
assert!(std::time::Instant::now() < deadline, "progressive UI job did not complete");
std::thread::sleep(std::time::Duration::from_millis(5));
h.frames(1);
}
let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap();
assert_eq!(status["frame"]["executor"], "gpu-path", "{status}");
assert_eq!(status["options"]["samples"], 4);
let export = h.app.tr("render.image_export").to_string();
h.step(&json!({"widget":export})).unwrap();
assert!(h.dir.join("render.png").is_file());
assert!(Arc::ptr_eq(&doc, &h.app.session.doc));
assert_eq!(h.app.session.undo.len(), undo);
assert!(!h.app.session.is_dirty());
}
#[test]
fn clicked_render_workspace_saves_one_setup_and_restores_design_view() {
for language in ["en", "de", "ko", "ru"] {
+2
View File
@@ -1,5 +1,7 @@
# Render backend capabilities (R1)
Native progressive opaque PNG rendering is described in [Progressive product images](render-path.md). It registers alongside the CPU executor.
This page describes the R1 metadata contract. The installed GPU viewport and CPU
product-job hosts extend it through complete profiles; HDR input preparation adds
no lighting capability. See [the integrated phase boundaries](render-integration.md).
+2
View File
@@ -1,5 +1,7 @@
# Phased render and material integration
Native progressive opaque PNG rendering is described in [Progressive product images](render-path.md). It registers alongside the CPU executor.
Tracked in #842, with parent render design #620 and physical/visual material roadmap
#922. The combined integration keeps contribution ancestry; it is an alternative
review path, not evidence that the individual PRs have merged. Each result in GitHub
+2
View File
@@ -1,5 +1,7 @@
# Product-image jobs (R4a)
Native progressive opaque PNG rendering is described in [Progressive product images](render-path.md). It registers alongside the CPU executor.
R4a adds bounded CPU preview images to the Render workspace. The installed `builtin` /
`cpu-product` executor supports Preview, Image and PNG. It does not promise refraction,
HDRI, exposure, final mode or EXR; those requests fail explicitly. The subsequent
+90
View File
@@ -0,0 +1,90 @@
# Progressive opaque product images
Native applications can register `solidcraft_gpu::path::host()` alongside the
existing CPU image host. `render.backends` then exposes `builtin/gpu-path` with
Preview, Image, PNG, Pbr and Progressive. The browser keeps its CPU image host.
Device discovery follows `SOLIDCRAFT_GPU` and `WGPU_BACKEND`; a device which cannot
create the compute pipeline does not register an available path executor.
The native UI opens its independent job device on the viewport's selected adapter,
so software fallback and safe mode do not rediscover a failing hardware driver.
An incompatible explicit GPU policy leaves progressive rendering unavailable there.
In the Render workspace, enable **Progressive rendering** and select samples per
pixel before checking or starting an image. These controls are transient image-job
intent. Existing saved setup/camera/material formats are unchanged.
The interactive canvas keeps its existing product preview; this first image-job
integration reports sample progress and exports the completed PNG, without displaying
partial accumulation buffers on the canvas.
```json
{"command":"render.start","params":{"settings":{"width":800,"height":600,"exposure_ev":0},"progressive":true,"samples":64,"max_depth":8,"seed":0}}
```
`render.preflight` accepts the same input. It resolves the Progressive capability
to the installed GPU host and performs admission without reserving memory. Start
checks again and returns the existing session/serial/generation identity. Progress
reports complete samples per pixel; a partially computed sample is not counted.
Cancel, status, retained-image ownership and atomic PNG export use the same host
protocol as CPU jobs. Defaults are 64 samples, depth 8 and seed 0; the bounds are
1–4096 samples and 1–16 bounces. Sampling controls require `progressive: true`.
```sh
solidcraft-cli render examples/render-path-studio.json --out enclosure.png --progressive --samples 64 --max-depth 8 --seed 0 --width 800 --height 600
```
The CLI explicitly fails if a progressive request has no suitable device. Ordinary
CPU requests retain their prior behavior. GPU PNG export averages linear radiance,
applies saved exposure and the existing Reinhard map, then encodes sRGB once. A
transparent background uses straight alpha; background color is independent of
illumination.
The original integrator uses software BVH traversal, opaque GGX/Smith/Schlick and
the symmetric diffuse attenuation defined by `render::surface`. Each hit evaluates
the three existing directional studio lights with shadow visibility. Continuation
samples a mixture of cosine-weighted diffuse and GGX normals with the combined
PDF; Russian roulette begins after four hits. There are indirect bounces, but no
environment illumination in the production profile. All legacy opaque colors use
linear-sRGB base color, metallic 0, roughness 0.5, IOR 1.5. Explicit face appearances
take precedence over body appearances.
This initial executor rejects opacity below one. It does not implement refraction,
absorption, HDRI, area lights, denoising, textures, EXR or Final mode. A path-traced
preview is not a declaration of those capabilities. The uniform environment used
by the numerical furnace test is deliberately not exposed as an HDRI feature.
Each job builds a balanced median-split BVH over its immutable captured meshes;
there is no cross-document cache to confuse scene generations. Positions are
rebased around the camera target before f32 upload. The upload packs indexed 32-byte position/normal vertices, 16-byte triangle records
(including material IDs), 32-byte resolved materials and 32-byte BVH nodes. The
geometry arrays share one buffer so traversal fits baseline storage-binding limits.
Geometry must be
within 1e7 mm of the camera target; ray offsets are max(1e-5 mm, extent × 1e-7).
This is a bounded preview precision policy, not a robust CAD intersection oracle.
Each GPU dispatch computes at most 262,144 pixel paths at one sample index. The
worker waits for that dispatch before checking cancellation and issuing another.
A driver wait has a 30-second timeout; cancellation cannot preempt a stalled GPU
dispatch. Encoding yields every four rows. Invalid indices/normals, nonfinite
geometry, excessive dimensions and sampling controls are errors.
The GPU host admits at most 1,048,576 input triangles, 4096 pixels per side and
4,194,304 pixels in all. The actual storage-buffer limit may lower these caps.
The source geometry cap is 128 MiB and the per-host pool is 512 MiB, including
retained PNG leases. Conservative estimates account for CPU BVH construction,
serialized and device geometry, accumulation, readback, RGBA and PNG buffers.
Allocator/driver bookkeeping is not an OS quota. CPU and GPU workers have separate
pools and each retains the established two-entry queue bound; a document still
has at most two live jobs across both executors.
Validation lives in `gpu::path::tests` and engine render job tests. Set
`SOLIDCRAFT_REQUIRE_GPU=1` to make absence of an adapter fail device tests rather
than skip them. BRDF parity is checked against the f64 oracle with 0.3% relative
plus 2e-5 absolute tolerance. The near-white furnace allows 0.07 absolute error:
the existing single-scattering Schlick model is not a perfectly conserving pure
Lambertian surface, even at IOR 1. Same-adapter determinism compares the actual
linear buffers bit-for-bit; cross-adapter bitwise identity is not promised.
The ignored `path_performance` test builds a 1,048,576-triangle procedural sphere
and measures 1920×1080 dispatches, BVH construction and upload. Select sample count
with `SOLIDCRAFT_PATH_BENCH_SAMPLES` (default 1). Run it explicitly with a clear GPU
timing window; it is excluded from normal CI.
+2
View File
@@ -1,5 +1,7 @@
# Integrated Render workspace (R3)
The native image panel also offers [progressive opaque rendering](render-path.md) when its compute executor is available.
R4a builds on this viewport contract with a separately advertised CPU product-image
executor and Check/Start/Cancel/Export controls. See [render jobs](render-jobs.md) for
the asynchronous protocol, image limits, captured revisions and PNG export. The legacy
+18
View File
@@ -0,0 +1,18 @@
{
"commands": [
{"command":"file.new","params":{"name":"Original opaque enclosure"}},
{"command":"solid.box","params":{"body_name":"Base","corner":[-48,-32,0],"length":96,"width":64,"height":4}},
{"command":"solid.box","params":{"body_name":"Left wall","corner":[-48,-32,4],"length":4,"width":64,"height":14}},
{"command":"solid.box","params":{"body_name":"Right wall","corner":[44,-32,4],"length":4,"width":64,"height":14}},
{"command":"solid.box","params":{"body_name":"Back wall","corner":[-44,28,4],"length":88,"width":4,"height":14}},
{"command":"solid.box","params":{"body_name":"Front wall","corner":[-44,-32,4],"length":88,"width":4,"height":14}},
{"command":"solid.box","params":{"body_name":"Teal insert","corner":[-33,-19,4],"length":66,"width":38,"height":10}},
{"command":"solid.cylinder","params":{"body_name":"Fastener A","base":[-39,-23,4],"radius":3,"height":11}},
{"command":"solid.cylinder","params":{"body_name":"Fastener B","base":[39,-23,4],"radius":3,"height":11}},
{"command":"solid.cylinder","params":{"body_name":"Fastener C","base":[-39,23,4],"radius":3,"height":11}},
{"command":"solid.cylinder","params":{"body_name":"Fastener D","base":[39,23,4],"radius":3,"height":11}},
{"command":"appearance.assign","params":{"bodies":["Base","Left wall","Right wall","Back wall","Front wall"],"color":"#c5c9d2","pbr":{"metallic":0,"roughness":0.6,"dielectric_ior":1.5}}},
{"command":"appearance.assign","params":{"bodies":["Teal insert"],"color":"#218e9b","pbr":{"metallic":0,"roughness":0.35,"dielectric_ior":1.5}}},
{"command":"appearance.assign","params":{"bodies":["Fastener A","Fastener B","Fastener C","Fastener D"],"color":"#d2d4d8","pbr":{"metallic":1,"roughness":0.25,"dielectric_ior":1.5}}}
]
}