From 7cf392d7c3edea980fe8bac15488bed2d8d1d008 Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Sat, 31 Oct 2026 10:40:53 +0100 Subject: [PATCH] Preserve every-pass CPU source and reviewed SHA-state recovery; validation pending --- proposals/render/2026-10-30/README.md | 22 +- .../c27-sha-state-recovery/README.md | 52 + .../candidate/crates/render/src/job/host.rs | 2993 ++++ .../delta-LF-review.patch | 171 + .../source-bindings.json | 27 + .../cpu-every-pass-c27-source/README.md | 70 + .../pending/cpu-progressive-passes.json | 20 + .../crates/render/src/film_primary.rs | 179 + .../candidate/crates/render/src/film_tests.rs | 632 + .../crates/render/src/job/cpu_budget.rs | 176 + .../candidate/crates/render/src/job/host.rs | 2923 ++++ .../crates/render/src/job/host_tests.rs | 2537 ++++ .../crates/render/src/job/interactive.rs | 371 + .../candidate/crates/render/src/job/mod.rs | 1903 +++ .../src/raytrace/environment_image_tests.rs | 309 + .../crates/render/src/raytrace/image.rs | 2573 ++++ .../crates/render/src/raytrace/image_tests.rs | 3579 +++++ .../crates/render/src/raytrace/mod.rs | 456 + .../render/src/raytrace/primary_aa_tests.rs | 1980 +++ .../crates/render/src/raytrace/progressive.rs | 95 + .../crates/render/src/raytrace/tests.rs | 455 + .../crates/ui-egui/src/render_workspace.rs | 2502 ++++ .../ui-egui/src/render_workspace_cpu.rs | 857 ++ .../src/render_workspace_interactive.rs | 1252 ++ .../ui-egui/src/render_workspace_tests.rs | 11590 ++++++++++++++++ .../candidate/docs/render-cpu-progressive.md | 228 + .../docs/render-cpu-resource-profiles.md | 74 + .../candidate/docs/render-cpu-workspace.md | 185 + .../candidate/docs/render-interactive.md | 146 + .../candidate/docs/render-jobs.md | 151 + .../candidate/docs/render-settings.md | 320 + .../delta-LF-review.patch | 2811 ++++ .../source-bindings.json | 229 + 33 files changed, 41867 insertions(+), 1 deletion(-) create mode 100644 proposals/render/2026-10-31/c27-sha-state-recovery/README.md create mode 100644 proposals/render/2026-10-31/c27-sha-state-recovery/candidate/crates/render/src/job/host.rs create mode 100644 proposals/render/2026-10-31/c27-sha-state-recovery/delta-LF-review.patch create mode 100644 proposals/render/2026-10-31/c27-sha-state-recovery/source-bindings.json create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/README.md create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/assets/locales/pending/cpu-progressive-passes.json create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_primary.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_tests.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/cpu_budget.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host_tests.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/interactive.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/mod.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/environment_image_tests.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image_tests.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/mod.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/primary_aa_tests.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/progressive.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/tests.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_cpu.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_interactive.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_tests.rs create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-progressive.md create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-resource-profiles.md create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-workspace.md create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-interactive.md create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-jobs.md create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-settings.md create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/delta-LF-review.patch create mode 100644 proposals/render/2026-10-31/cpu-every-pass-c27-source/source-bindings.json diff --git a/proposals/render/2026-10-30/README.md b/proposals/render/2026-10-30/README.md index 093a6166c..21d831e3a 100644 --- a/proposals/render/2026-10-30/README.md +++ b/proposals/render/2026-10-30/README.md @@ -214,4 +214,24 @@ The complete API consumer connects captured direct visibility and RGB shading to preserve the source-reviewed 1,048,576 Workstation ceiling, u32 film resolve and explicit Interactive target/seed controls. Thirteen new tests are written and UNRUN. **Producer/host per-pass and u32 adapters are still pending; not adoptable -alone, compiled, installed, ready or merged.** Existing budget limits remain. +alone, compiled, installed, ready or merged.** Existing budget limits remain. + +## CPU every-pass composition after C27 — 31 October + +[Twenty-five exact post-format source files and portable bindings](../2026-10-31/cpu-every-pass-c27-source/README.md) +preserve the complete CPU proposal and its actual failed-build source. C27 +format/check exited 0; combined compilation stopped on the existing 1,024-byte +metadata-size assertion (E0308). All 982 selected cases are UNRUN; the private +layout repair, full CI and native each-pass acceptance remain pending. This +supersedes the earlier nine-file snapshot for continuation, not production readiness. + + +## C27 metadata recovery: single active SHA state — 31 October + +[One exact host-source successor and bindings](../2026-10-31/c27-sha-state-recovery/README.md) +propose serial PNG/EXR hashing with one active SHA state and the completed PNG +digest. The 1,024-byte assertion remains unchanged. Kernel review and actual +compilation are pending at curation; the planned 983 cases are all UNRUN. +Apply only on the exact C27 failed-source composition, not arbitrary main. + +The single-host recovery has now been independently source-reviewed and adopted locally. Compilation, all 983 planned cases and native each-pass image acceptance remain pending. diff --git a/proposals/render/2026-10-31/c27-sha-state-recovery/README.md b/proposals/render/2026-10-31/c27-sha-state-recovery/README.md new file mode 100644 index 000000000..b7b9095f0 --- /dev/null +++ b/proposals/render/2026-10-31/c27-sha-state-recovery/README.md @@ -0,0 +1,52 @@ +# C27 recovery proposal: one active PNG/EXR SHA state + +31 October 2026. **Source reviewed and adopted locally; not yet formatted, +compiled, tested, installed, ready or merged. Root and independent Kernel +source reviews are closed; ABI fit and execution remain unverified.** + +The actual C27 combined build stopped with E0308 at its existing fixed metadata +assertion before any test body. This candidate is a narrow proposed repair, +**not evidence that E0308 is resolved or that the target ABI size is known**. + +## Source change + +The existing work scans PNG bytes before EXR bytes. The candidate retains one +active `Sha256` state, finalises the PNG output into +`Option>` (a 32-byte SHA256 digest, not an ABI-size +claim for the Option or surrounding structures), then uses a fresh active state +for EXR. It preserves the original chunk size, bounded advance count, byte order, +cancel/publication guards and payload/lease ownership. It adds no hidden heap +allocation and does not raise the 1,024-byte metadata allowance or either +existing size assertion. Those assertions remain compilation oracles. + +One original regression is written in the existing host module: +`sequential_png_and_exr_hashing_preserves_independent_payload_digests`. +It derives expected PNG and EXR hashes independently over distinct whole buffers +larger than one advance; units 1 and 3 exercise transitions between and within +calls. It also covers absent/empty EXR, zero-unit and repeated completed steps. +The test is **UNRUN**. Existing digest, cancellation, late-publication and lease +regressions remain unchanged and need actual-source execution. + +The proposed next selection is **983 cases, all UNRUN**: C27's 982 unexecuted +cases plus this one new regression. This is a planned selection, not an actual +inventory or a result from another run. No new compiler, runtime, native image, +physical GPU, full-CI or renderer-parity qualification follows from this patch. + +## Receiver and continuation + +Apply only after the [exact C27 failed-build 25-file composition](../cpu-every-pass-c27-source/README.md), +whose immediate host bytes hash to +`f775f4e458947b2c402fe97f10b320f7c7f4a9060cf502b5a69975e006eec71e`. +The candidate host hash is +`2c72c307ec49a94b100f4be32ab6a4af4be494199ff7ad5c87bb698e7f13ab4e`. +This single-file successor does not replace the other 24 source files and must +not be applied to arbitrary main or stacked blindly on the older nine-source +high-pass/UI snapshot. + +`candidate/` contains exact RAW source, `source-bindings.json` is portable and +`delta-LF-review.patch` contains the full readable change, including removals. +Continue with one fresh serial cached validation and actual artifact/inventory +bindings before tests; source review and local adoption are already complete. Native +per-pass display, final/export quality and the default-change/preference process +remain separate unresolved obligations. Archive preservation is not production +readiness and changes neither production PR #8938 nor the installed app. diff --git a/proposals/render/2026-10-31/c27-sha-state-recovery/candidate/crates/render/src/job/host.rs b/proposals/render/2026-10-31/c27-sha-state-recovery/candidate/crates/render/src/job/host.rs new file mode 100644 index 000000000..a8bf1d390 --- /dev/null +++ b/proposals/render/2026-10-31/c27-sha-state-recovery/candidate/crates/render/src/job/host.rs @@ -0,0 +1,2993 @@ +//! 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; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Condvar; +use std::sync::{ + Arc, Mutex, Weak, + atomic::{AtomicBool, AtomicU64, Ordering}, +}; + +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use super::{ + Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageExecutor, ImageRequest, ImageTask, ImageWork, Integrator, + JobError, JobId, JobOptions, Phase, Progress, Result, TaskPoll, admit, +}; +use crate::{ + Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout, +}; + +const MEMORY_LIMIT: u64 = 512 * 1024 * 1024; +const QUEUE_LIMIT: usize = 2; + +#[cfg(test)] +struct CpuExecutor; +#[cfg(test)] +impl ImageExecutor for CpuExecutor { + fn descriptor(&self) -> Result { + 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 { + 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> { + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } +} + +// Completion notification precedes destruction of the worker's temporary handle. +// Lease tests join their owned, idle worker before checking exact retained bytes. +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +impl ImageHost { + pub(super) fn join_worker_for_test(&mut self) -> Result<()> { + self.0.shared.stop.store(true, Ordering::Release); + self.0.shared.wake.notify_all(); + let inner = Arc::get_mut(&mut self.0).ok_or_else(|| JobError::new(ErrorCode::Internal, "test must own its host"))?; + if let Some(worker) = inner._worker.take() { + worker.join().map_err(|_| JobError::new(ErrorCode::Internal, "test worker panicked"))?; + } + Ok(()) + } +} + +#[cfg(test)] +#[path = "host_regrade_tests.rs"] +mod regrade_tests; +#[cfg(test)] +#[path = "host_tests.rs"] +mod tests; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HostKind { + NativeWorker, + Cooperative, +} + +struct Budget { + used: AtomicU64, + limit: u64, +} +pub(crate) struct Reservation { + budget: Arc, + bytes: u64, +} + +impl Budget { + fn reserve(self: &Arc, bytes: u64) -> Result { + let mut used = self.used.load(Ordering::Acquire); + loop { + let next = used.checked_add(bytes).filter(|n| *n <= self.limit).ok_or_else(|| { + JobError::new(ErrorCode::LimitExceeded, format!("image host admission pool is full ({} MiB)", self.limit / (1024 * 1024))) + })?; + match self.used.compare_exchange_weak(used, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => break, + Err(current) => used = current, + } + } + Ok(Reservation { budget: self.clone(), bytes }) + } +} +impl Reservation { + /// Merge unique portions of one admission without a second pool debit. + fn merge_from(&mut self, donor: &mut Self) -> Result<()> { + if !Arc::ptr_eq(&self.budget, &donor.budget) { + return Err(JobError::new(ErrorCode::WrongOwner, "cannot merge different image admission pools")); + } + let bytes = self + .bytes + .checked_add(donor.bytes) + .filter(|v| *v <= self.budget.limit) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "image reservation merge overflow"))?; + self.bytes = bytes; + donor.bytes = 0; + Ok(()) + } + /// Transfer an already admitted portion without changing the pool's total. + /// CPU progressive admission includes every possible checkpoint up front. + fn split(&mut self, bytes: u64) -> Result { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "preview exceeds its prepaid reservation")); + } + self.bytes -= bytes; + Ok(Self { budget: self.budget.clone(), bytes }) + } + + pub(crate) fn shrink(&mut self, bytes: u64) -> Result<()> { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "completed PNG exceeds its reservation")); + } + self.budget.used.fetch_sub(self.bytes - bytes, Ordering::AcqRel); + self.bytes = bytes; + Ok(()) + } +} +impl Drop for Reservation { + fn drop(&mut self) { + self.budget.used.fetch_sub(self.bytes, Ordering::AcqRel); + } +} + +/// Retained runtime input capacities survive work/PNG eviction through status handles. +fn retained_request_bytes(request: &ImageRequest) -> Result { + let existing = request.raytrace.as_ref().map_or(Ok(0), |options| options.retained_bytes())?; + existing + .checked_add(request.raster_lights_retained_bytes()?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request size overflow")) +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod light_union_lease_tests { + use super::super::{DirectionalLightOptions, PunctualLightOptions, RaytraceOptions, led_strip::LedStripOptions}; + use super::*; + fn request() -> Result { + let mut options = RaytraceOptions { + primary_samples: 16, + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]), + punctual_lights: Some(vec![ + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None + }; + 8 + ]), + ..Default::default() + }; + let strip = LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0; 3], + intensity: 2.0, + }; + for _ in 0..4 { + strip.append_to(&mut options, 64)?; + } + Ok(ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(options), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }) + } + fn scene() -> ProductScene { + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY } + } + #[test] + fn normalized_union_uses_one_pool_and_keeps_record_lease_after_frame_eviction() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = request().unwrap(); + let bytes = retained_request_bytes(&request).unwrap(); + let capacities = request + .raytrace + .as_ref() + .map(|o| { + (o.lights.as_ref().unwrap().capacity(), o.punctual_lights.as_ref().unwrap().capacity(), o.area_lights.as_ref().unwrap().capacity()) + }) + .unwrap(); + let job = host.submit(JobId { session: 1724, serial: 1, generation: 1 }, 1, scene(), request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Synchronize this test's completed worker before asserting final Arc release; + // publication wakes waiters just before Running drops its temporary handle. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let retained = job.0.request.raytrace.as_ref().unwrap(); + assert_eq!( + capacities, + ( + retained.lights.as_ref().unwrap().capacity(), + retained.punctual_lights.as_ref().unwrap().capacity(), + retained.area_lights.as_ref().unwrap().capacity() + ) + ); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert!(host.admitted_bytes() > bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn failed_union_metadata_reservation_releases_work_and_does_not_enqueue() { + let host = CpuHost::for_platform().unwrap(); + let request = request().unwrap(); + let work = admit(&scene(), &request).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let result = host.submit(JobId { session: 1724, serial: 2, generation: 1 }, 1, scene(), request); + assert_eq!(result.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } + + fn raster_local_pair() -> (ImageRequest, ProductScene) { + let mut input = request().unwrap(); + input.integrator = Integrator::Raster; + input.raytrace = None; + let mut points = Vec::with_capacity(8); + points.push(PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }); + let mut areas = Vec::with_capacity(4); + areas.push(super::super::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }); + input.raster_punctual_lights = Some(points); + input.raster_area_lights = Some(areas); + let mesh = solidcraft_geom::Mesh { + positions: vec![ + solidcraft_geom::Vec3::new(-2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(0.0, 2.0, 0.0), + ], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + name: "Raster local lease fixture".into(), + mesh: Arc::new(mesh), + color: [160; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + bounds, + }; + (input, scene) + } + + #[test] + fn raster_local_record_keeps_original_capacity_lease_after_real_completion_and_frame_drop() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let (input, scene) = raster_local_pair(); + let capacities = (input.raster_punctual_lights.as_ref().unwrap().capacity(), input.raster_area_lights.as_ref().unwrap().capacity()); + let bytes = (capacities.0 * std::mem::size_of::() + + capacities.1 * std::mem::size_of::()) as u64; + assert_eq!(retained_request_bytes(&input).unwrap(), bytes); + let job = host.submit(JobId { session: 1725, serial: 1, generation: 1 }, 1, scene, input).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + assert_eq!(job.0.request.raster_punctual_lights.as_ref().unwrap().capacity(), capacities.0); + assert_eq!(job.0.request.raster_area_lights.as_ref().unwrap().capacity(), capacities.1); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let copied = job.status().unwrap().request; + assert_eq!(copied.raster_punctual_lights, job.0.request.raster_punctual_lights); + assert_eq!(copied.raster_area_lights, job.0.request.raster_area_lights); + drop(copied); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + + #[test] + fn raster_local_metadata_reservation_failure_releases_work_without_enqueuing() { + let host = CpuHost::for_platform().unwrap(); + let (input, scene) = raster_local_pair(); + let work = host.admit(&scene, &input, JobOptions::default()).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let failed = host.submit(JobId { session: 1725, serial: 2, generation: 1 }, 1, scene, input); + assert_eq!(failed.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } +} + +fn admit_request_sum(work_bytes: u64, request_bytes: u64) -> Result<()> { + if work_bytes.checked_add(request_bytes).is_none_or(|sum| sum > super::image::MAX_JOB_BYTES) { + return Err(JobError::new(ErrorCode::LimitExceeded, "render work and retained request exceed 384 MiB per-job admission")); + } + Ok(()) +} + +/// Borrow encoded bytes through the frame, so retaining the data also retains its admission lease. +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearColourEncoding { + SceneLinearSrgbD65, +} +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearAlphaConvention { + CoveragePremultiplied, +} +#[derive(Clone, Debug, Serialize)] +pub struct LinearMasterInfo { + pub encoding: LinearColourEncoding, + pub alpha: LinearAlphaConvention, + pub bytes: u64, + pub sha256: String, +} +struct RetainedPresentation { + info: super::presentation::MasterPresentation, + _reservation: Reservation, +} + +pub struct RenderFrame { + // Derivatives point directly at the original, never form a retention chain. + source_master: Option>, + presentation: Option>, + pub info: FrameInfo, + png: Vec, + exr: Option<(Vec, LinearMasterInfo)>, + _reservation: Reservation, +} +impl RenderFrame { + pub fn master_source(self: &Arc) -> Result> { + if let Some(source) = &self.source_master { + return Ok(source.clone()); + } + if self.exr.is_some() { + return Ok(self.clone()); + } + Err(JobError::new(ErrorCode::InvalidRequest, "completed image has no retained raw linear master")) + } + pub fn presentation(&self) -> Option<&super::presentation::MasterPresentation> { + self.presentation.as_deref().map(|retained| &retained.info) + } + pub fn linear_exr(&self) -> Option<&[u8]> { + self.exr.as_ref().map(|(bytes, _)| bytes.as_slice()).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_exr())) + } + pub fn linear_master_info(&self) -> Option<&LinearMasterInfo> { + self.exr.as_ref().map(|(_, info)| info).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_master_info())) + } + pub fn png(&self) -> &[u8] { + &self.png + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct PreviewInfo { + pub frame_sequence: u32, + pub samples_per_pixel: u32, + pub frame: FrameInfo, +} + +/// Immutable checkpoint bytes retain their own transferred host lease. Keeping +/// an older preview alive never makes its memory disappear from pool accounting. +pub struct RenderPreview { + pub info: PreviewInfo, + png: Vec, + _reservation: CheckpointLease, +} + +/// Two reusable, immutable complete-pass slots. No consumer acknowledgement or +/// queue: externally pinned slots are diagnosed and never stall final work. +struct CheckpointCredits { + state: Mutex, + slot_bytes: u64, + capacity: u64, +} +struct CheckpointCreditState { + free: Reservation, + closed: bool, +} +impl CheckpointCredits { + fn new(reservation: &mut Reservation, slot_bytes: u64, slots: u32) -> Result> { + if !(1..=2).contains(&slots) || slot_bytes == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "checkpoint credits require one or two finite slots")); + } + let capacity = slot_bytes + .checked_mul(u64::from(slots)) + .and_then(|n| n.checked_add(1024)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit capacity overflow"))?; + let free = reservation.split(capacity)?; + Ok(Arc::new(Self { state: Mutex::new(CheckpointCreditState { free, closed: false }), slot_bytes, capacity })) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "checkpoint credit lock poisoned"))?; + if state.closed { + return Err(JobError::new(ErrorCode::Cancelled, "checkpoint credits are closed")); + } + let needed = self.slot_bytes.checked_add(1024).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit bound overflow"))?; + if state.free.bytes < needed { + return Ok(None); + } + let reservation = state.free.split(self.slot_bytes)?; + Ok(Some(CheckpointLease { reservation, credits: self.clone() })) + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + let _ = state.free.shrink(0); + } +} +struct CheckpointLease { + reservation: Reservation, + credits: Arc, +} +impl std::ops::Deref for CheckpointLease { + type Target = Reservation; + fn deref(&self) -> &Reservation { + &self.reservation + } +} +impl Drop for CheckpointLease { + fn drop(&mut self) { + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if !state.closed { + if state.free.bytes.checked_add(self.reservation.bytes).is_some_and(|n| n <= self.credits.capacity) + && state.free.merge_from(&mut self.reservation).is_ok() + { + return; + } + state.closed = true; + let _ = state.free.shrink(0); + } + } +} + +impl RenderPreview { + pub fn png(&self) -> &[u8] { + &self.png + } +} + +/// Metadata for either runtime environment contract; wire objects retain their original shape. +#[derive(Clone, Debug, Serialize)] +#[serde(untagged)] +pub enum JobEnvironmentInfo { + Cpu(crate::lighting::environment_input::EnvironmentInfo), + Gpu(crate::lighting::environment::EnvironmentInfo), +} + +#[derive(Clone, Debug, Serialize)] +pub struct JobStatus { + /// Completed CPU passes whose immutable snapshot could not be published + /// because both admitted slots remained pinned by external consumers. + pub cpu_preview_retention_skips: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub punctual_diagnostics: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub presentation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sampling: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub linear_master: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + pub textures: Option, + pub options: JobOptions, + #[serde(skip_serializing_if = "Option::is_none")] + pub environment: Option, + pub job: JobId, + pub scene_generation: u64, + pub request: ImageRequest, + pub resolved: crate::ResolvedRequest, + pub progress: Progress, + pub error: Option, + pub frame: Option, +} + +struct Data { + cpu_preview_retention_skips: u32, + partial_preview: Option>, + punctual_diagnostics: Option, + sampling: Option, + progress: Progress, + error: Option, + frame: Option>, + preview: Option>, +} +struct Record { + partial: Option>, + presentation: Option>, + textures: Option, + options: JobOptions, + environment: Option, + id: JobId, + scene_generation: u64, + request: ImageRequest, + // Rust fields drop in declaration order: payload before its retained credits. + _request_reservation: Option, + resolved: crate::ResolvedRequest, + cancel: CancelToken, + data: Mutex, + #[cfg(not(target_arch = "wasm32"))] + done: Condvar, +} + +impl Record { + fn notify(&self) { + #[cfg(not(target_arch = "wasm32"))] + self.done.notify_all(); + } +} + +#[derive(Clone)] +pub struct JobHandle(Arc); + +impl JobHandle { + /// Internal admitted-work identity. Equal public IDs need not be one record. + pub(super) fn same_record(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + + pub fn id(&self) -> JobId { + self.0.id + } + pub fn status(&self) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + Ok(JobStatus { + cpu_preview_retention_skips: data.cpu_preview_retention_skips, + punctual_diagnostics: data.punctual_diagnostics, + presentation: self.0.presentation.as_deref().map(|retained| retained.info.clone()), + sampling: data.sampling.clone(), + linear_master: data.frame.as_ref().and_then(|frame| frame.linear_master_info().cloned()), + preview: data.preview.as_ref().map(|preview| preview.info.clone()), + textures: self.0.textures.clone(), + options: self.0.options, + environment: self.0.environment.clone(), + job: self.0.id, + scene_generation: self.0.scene_generation, + request: self.0.request.try_clone_for_host()?, + resolved: self.0.resolved.clone(), + progress: data.progress, + error: data.error.clone(), + frame: data.frame.as_ref().map(|f| f.info.clone()), + }) + } + pub fn cancel(&self) -> Result { + if let Some(credits) = &self.0.partial { + credits.close(); + } + let mut released_partial = None; + { + let mut data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + if !data.progress.phase.terminal() { + self.0.cancel.cancel(); + released_partial = data.partial_preview.take(); + data.preview = None; + data.progress.phase = if data.progress.phase == Phase::Queued { Phase::Cancelled } else { Phase::Cancelling }; + } + } + drop(released_partial); + self.0.notify(); + self.status() + } + + /// Native application helper; engine status commands remain non-blocking. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, timeout: std::time::Duration) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + let (data, timed) = self + .0 + .done + .wait_timeout_while(data, timeout, |d| !d.progress.phase.terminal()) + .map_err(|_| JobError::new(ErrorCode::Internal, "render completion lock poisoned"))?; + if timed.timed_out() && !data.progress.phase.terminal() { + return Err(JobError::new(ErrorCode::TimedOut, "render wait timed out")); + } + drop(data); + self.status() + } + pub fn frame(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render result lock poisoned"))?; + let frame = data.frame.clone(); + if frame.as_ref().is_some_and(|f| f.info.job != self.0.id || f.info.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render frame identity does not match its job")); + } + Ok(frame) + } + + /// A provisional complete-pass image, never the final/export frame slot. + pub fn preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview lock poisoned"))?; + let preview = data.preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render preview identity does not match its job")); + } + Ok(preview) + } +} + +#[derive(Clone, Copy)] +enum CpuPreviewPolicy { + Shared(super::PartialPreviewPlan), + Protected(super::ProtectedPreviewPlan), +} +impl CpuPreviewPolicy { + fn preview_plan(self) -> super::PartialPreviewPlan { + match self { + Self::Shared(plan) => plan, + Self::Protected(plan) => plan.preview_plan(), + } + } +} +struct Submission { + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, +} +struct Work { + regrade: Option<(Arc, super::presentation::Presentation)>, + request: Option, + executor: Option>, + environment: Option, + scene: ProductScene, + handle: JobHandle, + reservation: Reservation, +} +// One host advance hashes at most four 16 KiB chunks, independently of the +// integrator's quantum. The unchanged work reservation covers the sole PNG and +// this fixed state until publication; it is not another image task or pool. +const PNG_HASH_CHUNK_BYTES: usize = 16_384; +const PNG_HASH_CHUNKS_PER_ADVANCE: usize = 4; +pub(crate) const FRAME_METADATA_BYTES: u64 = 1024; + +struct PendingPng { + png: Vec, + digest: Sha256, + hashed: usize, + preview_samples: Option, + exr: Option>, + png_digest: Option>, + exr_hashed: usize, +} +// Keep the new fixed completion state within the existing metadata allowance +// even if the hashing dependency's representation changes on another target. +const _: [(); 1] = [(); (std::mem::size_of::() <= 512) as usize]; +const _: [(); 1] = [(); (std::mem::size_of::() + + std::mem::size_of::() + + std::mem::size_of::() + + 64 + + 2 * crate::MAX_RENDER_ID_BYTES + + 32 + <= FRAME_METADATA_BYTES as usize) as usize]; + +impl PendingPng { + fn new(png: Vec) -> Self { + Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, png_digest: None, exr_hashed: 0 } + } + + #[cfg(feature = "raytrace-cpu")] + fn preview(png: Vec, samples: u32) -> Self { + Self { preview_samples: Some(samples), ..Self::new(png) } + } + + fn finish_png_digest(&mut self) { + if self.hashed == self.png.len() && self.png_digest.is_none() { + // PNG and EXR are scanned serially. Keep the completed PNG output, + // then reuse a fresh digest state for EXR without another allocation. + self.png_digest = Some(std::mem::take(&mut self.digest).finalize()); + } + } + + fn step(&mut self, units: usize, cancel: &CancelToken) -> Result { + cancel.check()?; + self.finish_png_digest(); + for _ in 0..units.min(PNG_HASH_CHUNKS_PER_ADVANCE) { + let (bytes, hashed) = if self.hashed < self.png.len() { + (&self.png, &mut self.hashed) + } else if let Some(exr) = self.exr.as_ref().filter(|exr| self.exr_hashed < exr.len()) { + (exr, &mut self.exr_hashed) + } else { + break; + }; + let end = hashed.saturating_add(PNG_HASH_CHUNK_BYTES).min(bytes.len()); + self.digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?); + *hashed = end; + cancel.check()?; + self.finish_png_digest(); + } + Ok(self.hashed == self.png.len() && self.exr.as_ref().is_none_or(|exr| self.exr_hashed == exr.len())) + } + fn progress(&self) -> Progress { + Progress { + phase: Phase::Encoding, + done: self.hashed as u64 + self.exr_hashed as u64, + total: self.png.len() as u64 + self.exr.as_ref().map_or(0, |bytes| bytes.len() as u64), + } + } +} + +#[cfg(test)] +#[test] +fn sequential_png_and_exr_hashing_preserves_independent_payload_digests() { + let quantum_bytes = PNG_HASH_CHUNK_BYTES * PNG_HASH_CHUNKS_PER_ADVANCE; + for units in [1, 3] { + for exr_length in [None, Some(0), Some(quantum_bytes + 29)] { + let png: Vec = (0..quantum_bytes + 13).map(|index| (index as u8).wrapping_mul(17).wrapping_add(3)).collect(); + let exr: Option> = exr_length.map(|length| (0..length).map(|index| (index as u8).wrapping_mul(29).wrapping_add(101)).collect()); + let expected_png = Sha256::digest(&png); + let expected_exr = exr.as_ref().map(Sha256::digest); + if let Some(expected_exr) = &expected_exr { + assert_ne!(&expected_png, expected_exr, "the distinct payloads must not share a digest"); + } + let png_length = png.len(); + let exr_length = exr.as_ref().map_or(0, Vec::len); + assert!(png_length > quantum_bytes); + assert!(exr_length == 0 || exr_length > quantum_bytes); + let chunks = png_length.div_ceil(PNG_HASH_CHUNK_BYTES) + exr_length.div_ceil(PNG_HASH_CHUNK_BYTES); + let steps = chunks.div_ceil(units); + let mut pending = PendingPng::new(png); + pending.exr = exr; + let cancel = CancelToken::default(); + assert!(!pending.step(0, &cancel).unwrap()); + assert_eq!((pending.hashed, pending.exr_hashed), (0, 0)); + assert!(pending.png_digest.is_none()); + let mut crossed_within_step = false; + let mut saw_png_only_boundary = false; + for step in 0..steps { + let before_png = pending.hashed; + let before_exr = pending.exr_hashed; + let done = pending.step(units, &cancel).unwrap(); + assert_eq!(done, step + 1 == steps); + let advanced = pending.hashed + pending.exr_hashed - before_png - before_exr; + assert!(advanced > 0 && advanced <= units * PNG_HASH_CHUNK_BYTES); + if pending.hashed == png_length { + assert_eq!(pending.png_digest.as_ref(), Some(&expected_png)); + saw_png_only_boundary |= pending.exr_hashed == 0; + } + crossed_within_step |= before_png < png_length && pending.hashed == png_length && pending.exr_hashed > 0; + assert_eq!(pending.progress().done, (pending.hashed + pending.exr_hashed) as u64); + assert_eq!(pending.progress().total, (png_length + exr_length) as u64); + } + assert_eq!((pending.hashed, pending.exr_hashed), (png_length, exr_length)); + if exr_length > 0 { + assert_eq!(crossed_within_step, units == 3); + assert_eq!(saw_png_only_boundary, units == 1); + } + for extra_units in [0, 1] { + assert!(pending.step(extra_units, &cancel).unwrap()); + assert_eq!(pending.png_digest.as_ref(), Some(&expected_png)); + let actual_exr = pending.exr.as_ref().map(|_| pending.digest.clone().finalize()); + assert_eq!(actual_exr, expected_exr, "EXR must start from a fresh SHA state and survive repeated completed steps"); + assert_eq!((pending.hashed, pending.exr_hashed), (png_length, exr_length)); + } + } + } +} + + +struct Running { + source_master: Option>, + task: Option, + pending_png: Option, + handle: JobHandle, + reservation: Option, + next_preview_sequence: u32, + next_checkpoint_pass: u32, + checkpoints: Option>, + // Task/PNG allocations above die before the in-flight credit below. + partial: Option>, +} + +impl Drop for Running { + fn drop(&mut self) { + if let Some(credits) = &self.checkpoints { + credits.close(); + } + } +} + +/// One fallibly allocated task, keeping the dispatch enum small in either build. +/// Its bounded metadata allocation fits the existing per-job task allowance. +struct TaskSlot(Vec); +impl TaskSlot { + fn new(task: T) -> Result { + if std::mem::size_of::() > 4096 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task metadata exceeds its admission allowance")); + } + let mut tasks = Vec::new(); + tasks.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve render task slot"))?; + if tasks.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task slot exceeds its bounded capacity")); + } + tasks.push(task); + Ok(Self(tasks)) + } + fn get_mut(&mut self) -> Result<&mut T> { + self.0.first_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task slot")) + } +} +enum WorkTask { + Regrade(TaskSlot), + Registered(Box), + Raster(TaskSlot), + #[cfg(feature = "raytrace-cpu")] + Raytrace(TaskSlot), +} + +enum WorkPoll { + #[cfg(feature = "raytrace-cpu")] + Partial { + png: Vec, + covered: Vec, + completed_passes: u32, + updated_prefix: u64, + }, + Existing(TaskPoll), + #[cfg(feature = "raytrace-cpu")] + Preview { + png: Vec, + samples_per_pixel: u32, + }, +} + +impl WorkTask { + fn protected_report(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.protected_preview_report()), + _ => None, + } + } + fn partial_ready(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => task.get_mut()?.partial_preview_ready(plan), + _ => Ok(false), + } + } + fn completed_pass_ready(&self, plan: super::PartialPreviewPlan) -> Result> { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().map_or(Ok(None), |task| task.completed_pass_preview_ready(plan)), + _ => Ok(None), + } + } + fn begin_partial(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => match task.get_mut()?.begin_partial_preview(plan)? { + crate::raytrace::image::PartialBegin::Started => Ok(true), + crate::raytrace::image::PartialBegin::Exhausted => Ok(false), + }, + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn step_partial(&mut self, units: usize) -> Result { + let _ = &units; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_partial_previews(units)? { + crate::raytrace::image::PartialImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::PartialImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix } => { + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } + } + }), + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn punctual_diagnostics(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.punctual_diagnostics()), + _ => None, + } + } + + fn source_master(&self) -> Result>> { + match self { + Self::Regrade(slot) => { + slot.0.first().map(|task| Some(task.source())).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing master task slot")) + } + _ => Ok(None), + } + } + fn sampling_report(&self) -> Option { + match self { + Self::Registered(task) => task.sampling_report(), + _ => None, + } + } + fn take_linear_exr(&mut self) -> Option> { + match self { + Self::Registered(task) => task.take_linear_exr(), + _ => None, + } + } + fn new( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + environment: Option, + job_options: JobOptions, + partial: Option, + report_sink: Option<&PartialCredits>, + ) -> Result { + let _ = (&environment, &job_options, &partial, &report_sink); + match request.integrator { + Integrator::Raster => ImageTask::new(scene, request, cancel).and_then(TaskSlot::new).map(Self::Raster), + Integrator::Raytrace => { + #[cfg(feature = "raytrace-cpu")] + { + let options = request.raytrace.clone().unwrap_or_default(); + let task = match partial { + Some(CpuPreviewPolicy::Shared(plan)) => crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ), + Some(CpuPreviewPolicy::Protected(plan)) => { + crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_protected_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ) + } + None => crate::raytrace::image::ImageTask::new_with_environment_and_nested( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + ), + }; + Self::raytrace_with_slot(task?, report_sink, TaskSlot::new) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + } + + fn step(&mut self, units: usize) -> Result { + match self { + Self::Regrade(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + Self::Registered(task) => task.step(units).map(WorkPoll::Existing), + Self::Raster(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_previews(units)? { + crate::raytrace::image::ImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::ImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::ImagePoll::Preview { png, samples_per_pixel } => WorkPoll::Preview { png, samples_per_pixel }, + }), + } + } +} + +fn terminal(handle: &JobHandle, error: JobError) { + if let Some(credits) = &handle.0.partial { + credits.close(); + } + let mut released_partial = None; + if let Ok(mut data) = handle.0.data.lock() { + if data.progress.phase == Phase::Completed { + return; + } + if handle.0.cancel.is_cancelled() || error.code == ErrorCode::Cancelled { + data.progress.phase = Phase::Cancelled; + data.error = None; + } else { + data.progress.phase = Phase::Failed; + data.error = Some(error); + } + data.frame = None; + data.preview = None; + released_partial = data.partial_preview.take(); + } + drop(released_partial); + handle.0.notify(); +} + +impl Running { + fn begin(work: Work) -> Option { + Self::begin_with_partial_factory(work, |credits| TaskSlot::new(PartialRunning::new(credits))) + } + + // The private factory keeps post-construction setup fallible without losing + // the real ledger. It runs only after report capture and outside every lock. + fn begin_with_partial_factory( + mut work: Work, + make_partial: impl FnOnce(Arc) -> Result>, + ) -> Option { + let checkpoints = (|| { + let slots = work + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .filter(|_| work.handle.0.partial.is_none() && work.executor.is_none()) + .map_or(0, |options| options.samples_per_pixel.saturating_sub(1).min(2)); + if slots == 0 { + return Ok(None); + } + let slot_bytes = u64::from(work.handle.0.request.width) + .checked_mul(u64::from(work.handle.0.request.height)) + .and_then(|n| n.checked_mul(8)) + .and_then(|n| n.checked_add(65_536 + FRAME_METADATA_BYTES)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint slot overflow"))?; + CheckpointCredits::new(&mut work.reservation, slot_bytes, slots).map(Some) + })(); + let checkpoints = match checkpoints { + Ok(credits) => credits, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + if work.handle.0.cancel.is_cancelled() { + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render cancelled")); + return None; + } + if let Ok(mut data) = work.handle.0.data.lock() + && !work.handle.0.cancel.is_cancelled() + { + data.progress.phase = Phase::Preparing; + } + let task = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if let Some((source, presentation)) = work.regrade { + super::regrade::RegradeTask::new(source, presentation, work.handle.0.cancel.clone()).and_then(TaskSlot::new).map(WorkTask::Regrade) + } else if let Some(executor) = work.executor { + let request = work.request.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing registered executor request"))?; + executor.begin(work.scene, request, work.handle.0.options, work.handle.0.cancel.clone()).map(WorkTask::Registered) + } else { + WorkTask::new( + work.scene, + work.handle.0.request.try_clone_for_host()?, + work.handle.0.cancel.clone(), + work.environment, + work.handle.0.options, + work.handle.0.partial.as_ref().map(|credits| credits.policy()), + work.handle.0.partial.as_deref(), + ) + } + })) + .unwrap_or_else(|_| Err(JobError::new(ErrorCode::Internal, "image executor failed while preparing the job"))); + let task = match task { + Ok(task) => task, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + // The raw producer report was captured before the first task-slot wrap. + // Only now attempt the additional partial runtime slot. + let partial = work.handle.0.partial.as_ref().map(|credits| make_partial(credits.clone())).transpose(); + match partial { + Ok(partial) => Some(Self { + partial, + source_master: None, + task: Some(task), + pending_png: None, + handle: work.handle, + reservation: Some(work.reservation), + next_preview_sequence: 1, + next_checkpoint_pass: 1, + checkpoints, + }), + Err(error) => { + terminal(&work.handle, error); + // The real task's buffers die before work's remaining lease. + None + } + } + } + fn advance(&mut self, units: usize) -> Result { + self.handle.0.cancel.check()?; + if self.pending_png.is_some() { + return self.advance_png(units); + } + if let Some(partial) = self.partial.as_mut() { + let partial = partial.get_mut()?; + let task = self.task.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + let uniform_pass = task.completed_pass_ready(partial.credits.plan)?; + let automatic_pass = uniform_pass.filter(|pass| *pass > partial.last_pass_attempt); + if let Some(pass) = automatic_pass { + partial.last_pass_attempt = pass; + partial.credits.request()?; + } + if partial.lease.is_none() + && partial.credits.requested.load(Ordering::Acquire) + && !partial.credits.exhausted.load(Ordering::Acquire) + && (uniform_pass.is_none() || automatic_pass.is_some()) + { + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + if task.partial_ready(partial.credits.plan)? { + let mut lease = partial.credits.acquire()?; + if lease.is_none() && automatic_pass.is_some() { + let released = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retirement lock poisoned"))? + .partial_preview + .take(); + drop(released); + lease = partial.credits.acquire()?; + } + if lease.is_none() && automatic_pass.is_some() && partial.credits.retained_slots_blocked()? { + let mut data = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retention diagnostic lock poisoned"))?; + self.handle.0.cancel.check()?; + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial retention diagnostic overflow"))?; + } + if let Some(lease) = lease { + // Keep the lease past any producer error until task buffers drop. + partial.lease = Some(lease); + let begin = task.begin_partial(partial.credits.plan); + partial.credits.store_report(task.protected_report())?; + if !begin? { + if partial.credits.protected.is_some() && !partial.credits.exhausted.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::Internal, "protected feedback refused without real quota exhaustion")); + } + partial.credits.exhaust(); + drop(partial.lease.take()); + } + } + } + } + } + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task"))?; + let result = if self.partial.is_some() { task.step_partial(units) } else { task.step(units) }; + if let Some(credits) = &self.handle.0.partial { + credits.store_report(task.protected_report())?; + } + let result = result?; + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + data.punctual_diagnostics = self.task.as_ref().and_then(WorkTask::punctual_diagnostics); + // The final publication check is under the same lock as cancellation. + if self.handle.0.cancel.is_cancelled() { + data.progress.phase = Phase::Cancelled; + data.frame = None; + data.preview = None; + let released = data.partial_preview.take(); + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + return Ok(false); + } + match result { + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } => { + drop(data); + self.capture_partial(png, covered, completed_passes, updated_prefix)?; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Pending(progress)) => { + data.progress = progress; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Complete(png)) => { + // Drop every integrator-owned capture/scratch buffer first, but + // keep the original admission lease while hashing the sole PNG. + self.source_master = self.task.as_ref().map(WorkTask::source_master).transpose()?.flatten(); + data.sampling = self.task.as_ref().and_then(WorkTask::sampling_report); + let exr = self.task.as_mut().and_then(WorkTask::take_linear_exr); + if exr.is_some() != self.handle.0.options.linear_exr { + return Err(JobError::new(ErrorCode::Internal, "linear master availability differs from the admitted request")); + } + if let Some(bytes) = &exr { + let limit = super::linear_exr::encoded_limit(self.handle.0.request.width, self.handle.0.request.height)?; + if bytes.len() < 8 || bytes.capacity() as u64 > limit || bytes.get(..8) != Some(&[0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]) { + return Err(JobError::new(ErrorCode::LimitExceeded, "linear master exceeds its bound or has an invalid signature")); + } + } + self.task = None; + let mut pending = PendingPng::new(png); + pending.exr = exr; + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Preview { png, samples_per_pixel } => { + // Retain the integrator/film and the entire remaining work lease. + // Hash the checkpoint before making immutable bytes observable. + let pending = PendingPng::preview(png, samples_per_pixel); + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + } + } + + fn advance_png(&mut self, units: usize) -> Result { + // No status/data lock is held while scanning the encoded image. + let pending = self.pending_png.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing pending PNG"))?; + if !pending.step(units, &self.handle.0.cancel)? { + let progress = pending.progress(); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + self.handle.0.cancel.check()?; + data.progress = progress; + return Ok(true); + } + let PendingPng { png, digest, preview_samples, exr, png_digest, .. } = + self.pending_png.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed PNG digest"))?; + let png_digest = png_digest.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing finalized PNG digest"))?; + if self.partial.as_ref().and_then(|slot| slot.0.first()).is_some_and(|partial| partial.pending.is_some()) { + return self.publish_partial(png, png_digest); + } + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: self.handle.0.request.width, + height: self.handle.0.request.height, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + png_sha256: format!("{:x}", png_digest), + }; + // Include the working digest/Vec metadata, completed frame layout, + // actual hex allocation, bounded copied IDs and Arc/header allowance. + // The PNG allocation itself is retained once and billed by capacity below. + let frame_layout = if preview_samples.is_some() { std::mem::size_of::() } else { std::mem::size_of::() }; + let checkpoint_metadata = + if preview_samples.is_some() { std::mem::size_of::() + 2 * std::mem::size_of::() } else { 0 }; + let fixed_metadata = std::mem::size_of::() + frame_layout + checkpoint_metadata + 2 * crate::MAX_RENDER_ID_BYTES + 32; + let linear_digest_bytes = if exr.is_some() { 64 } else { 0 }; + if fixed_metadata + .checked_add(info.png_sha256.capacity()) + .and_then(|n| n.checked_add(linear_digest_bytes)) + .is_none_or(|bytes| bytes > FRAME_METADATA_BYTES as usize) + { + return Err(JobError::new(ErrorCode::LimitExceeded, "PNG digest metadata exceeds its existing admission allowance")); + } + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + // Cancellation shares this lock; a late cancel must win before frame + // installation. The digest is complete; checkpoints retain task scratch, + // while the final-only path has already released it. + self.handle.0.cancel.check()?; + if let Some(samples_per_pixel) = preview_samples { + let options = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "preview requires CPU progressive intent"))?; + let frame_sequence = self.next_preview_sequence; + let expected = Some(self.next_checkpoint_pass); + if expected != Some(samples_per_pixel) || samples_per_pixel >= options.samples_per_pixel || self.task.is_none() { + return Err(JobError::new(ErrorCode::Internal, "invalid progressive checkpoint sequence")); + } + let next_sequence = frame_sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::Internal, "preview sequence exhausted"))?; + let credits = self.checkpoints.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing checkpoint credits"))?; + if (png.capacity() as u64).checked_add(FRAME_METADATA_BYTES).is_none_or(|bytes| bytes > credits.slot_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "checkpoint PNG exceeds its admitted slot")); + } + let mut reservation = credits.acquire()?; + if reservation.is_none() { + // Retire the host's obsolete slot before treating a consumer as + // pinned. A headless client never has to acknowledge previews. + let released = data.preview.take(); + drop(data); + drop(released); + reservation = credits.acquire()?; + data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview publication lock poisoned"))?; + self.handle.0.cancel.check()?; + } + self.next_checkpoint_pass = self + .next_checkpoint_pass + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; + let Some(reservation) = reservation else { + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint retention diagnostic overflow"))?; + return Ok(true); + }; + data.preview = Some(Arc::new(RenderPreview { + info: PreviewInfo { frame_sequence, samples_per_pixel, frame: info }, + png, + _reservation: reservation, + })); + self.next_preview_sequence = next_sequence; + let pixels = u64::from(self.handle.0.request.width) * u64::from(self.handle.0.request.height); + data.progress = + Progress { phase: Phase::Running, done: pixels * u64::from(samples_per_pixel), total: pixels * u64::from(options.samples_per_pixel) }; + self.handle.0.notify(); + return Ok(true); + } + let exr = exr.map(|bytes| { + let info = LinearMasterInfo { + bytes: bytes.len() as u64, + sha256: format!("{:x}", digest.finalize()), + encoding: LinearColourEncoding::SceneLinearSrgbD65, + alpha: LinearAlphaConvention::CoveragePremultiplied, + }; + (bytes, info) + }); + let retained = png.capacity() as u64 + exr.as_ref().map_or(0, |(bytes, _)| bytes.capacity() as u64) + FRAME_METADATA_BYTES; + let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?; + reservation.shrink(retained)?; + data.frame = Some(Arc::new(RenderFrame { + info, + png, + exr, + source_master: self.source_master.take(), + presentation: self.handle.0.presentation.clone(), + _reservation: reservation, + })); + data.preview = None; + let released = data.partial_preview.take(); + data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; + if let Some(credits) = &self.checkpoints { + credits.close(); + } + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + Ok(false) + } + + fn guarded_step(&mut self, units: usize) -> bool { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.advance(units))); + match result { + Ok(Ok(more)) => more, + Ok(Err(e)) => { + terminal(&self.handle, e); + false + } + Err(_) => { + terminal(&self.handle, JobError::new(ErrorCode::Internal, "image host encountered an internal error")); + false + } + } + } +} + +struct Shared { + queue: Mutex>, + active: Mutex>>, + stop: AtomicBool, + budget: Arc, + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar, +} + +struct Owner { + executor: Option>, + shared: Arc, + kind: HostKind, + running: Mutex>, + #[cfg(not(target_arch = "wasm32"))] + _worker: Option>, +} + +impl Drop for Owner { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Release); + if let Ok(active) = self.shared.active.lock() + && let Some(record) = active.as_ref().and_then(Weak::upgrade) + { + let _ = JobHandle(record).cancel(); + } + if let Ok(mut queue) = self.shared.queue.lock() { + for work in queue.iter() { + let _ = work.handle.cancel(); + } + queue.clear(); + } + if let Ok(mut running) = self.running.lock() + && let Some(work) = running.take() + { + let _ = work.handle.cancel(); + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render host closed")); + } + #[cfg(not(target_arch = "wasm32"))] + self.shared.wake.notify_all(); + // Detaching cannot stall the UI; the bounded worker observes stop/cancel at its next unit. + } +} + +#[derive(Clone)] +pub struct ImageHost(Arc); + +/// Builtin CPU constructors share the registered image host lifetime machinery. +pub type CpuHost = ImageHost; + +impl ImageHost { + fn shared(limit: u64) -> Arc { + Arc::new(Shared { + queue: Mutex::new(VecDeque::new()), + active: Mutex::new(None), + stop: AtomicBool::new(false), + budget: Arc::new(Budget { used: AtomicU64::new(0), limit }), + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar::new(), + }) + } + + pub fn cooperative() -> Self { + Self(Arc::new(Owner { + executor: None, + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + /// A cooperative host over `executor` (pumped by its caller). + #[cfg(test)] + fn cooperative_with(executor: Arc) -> Self { + Self(Arc::new(Owner { + executor: Some(executor), + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + pub fn for_platform() -> Result { + #[cfg(target_arch = "wasm32")] + { + Ok(Self::cooperative()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let pool = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + let shared = Self::shared(pool); + 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 { executor: None, shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + } + + /// Start an isolated bounded native worker. GPU discovery occurs before registration. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_executor(executor: Arc) -> Result { + 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 limit = executor.memory_limit_bytes(); + let ceiling = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + if limit == 0 || limit > ceiling { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image pool exceeds supported address space")); + } + let shared = Self::shared(limit); + 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: Some(executor), shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + + pub fn kind(&self) -> HostKind { + self.0.kind + } + + pub fn same_host(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + pub fn is_available(&self) -> bool { + !self.0.shared.stop.load(Ordering::Acquire) + } + pub fn admitted_bytes(&self) -> u64 { + self.0.shared.budget.used.load(Ordering::Acquire) + } + + /// Internal completed-film adapter: the existing host budget, no new pool. + pub(crate) fn reserve_film_snapshot(&self, bytes: u64) -> Result { + if self.0.executor.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU film snapshots require the builtin CPU host")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU image host has stopped")); + } + if bytes > super::image::MAX_JOB_BYTES { + return Err(JobError::new(ErrorCode::LimitExceeded, "film snapshot exceeds per-job admission")); + } + self.0.shared.budget.reserve(bytes) + } + + pub fn descriptor(&self) -> Result { + self.descriptor_for(Integrator::Raster) + } + + pub fn job_limit_bytes(&self) -> u64 { + if self.0.executor.is_some() { self.0.shared.budget.limit } else { super::image::MAX_JOB_BYTES } + } + + pub fn pool_limit_bytes(&self) -> u64 { + self.0.shared.budget.limit + } + + pub fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + self.admit_with_policy(scene, request, options, None) + } + /// Same canonical policy and complete retained/HDR accounting as protected submit. + /// Non-reserving estimate: submission still admits against the live pool. + pub fn admit_cpu_protected_partial_with_environment_and_options( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result { + self.validate_submission_environment(scene, request, environment)?; + let policy = Self::protected_preview_policy(request)?; + let (mut admission, request_bytes) = self.admit_submission(scene, request, options, environment, Some(policy))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(request_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request admission overflow"))?; + Ok(admission) + } + + fn protected_preview_policy(request: &ImageRequest) -> Result { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require CPU progressive intent"))? + .samples_per_pixel; + let plan = super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())?; + Ok(CpuPreviewPolicy::Protected(plan)) + } + + fn validate_submission_environment( + &self, + scene: &ProductScene, + request: &ImageRequest, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result<()> { + if self.0.executor.is_some() && environment.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU environments")); + } + if environment.is_some() && request.integrator != Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "environment lighting requires CPU raytrace")); + } + self.validate_integrator(request.integrator)?; + if environment.is_some() { + request.raytrace.as_ref().unwrap_or(&super::RaytraceOptions::default()).validate_environment_reflections(scene)?; + } + Ok(()) + } + + fn admit_submission( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + partial: Option, + ) -> Result<(Admission, u64)> { + if environment.is_some() && request.raytrace.as_ref().is_some_and(|options| options.directional_shadow_transmission) { + return Err(JobError::new(ErrorCode::InvalidRequest, "directional shadow transmission does not support HDR environments")); + } + let metadata_bytes = + (if environment.is_some() { std::mem::size_of::() as u64 } else { 0 }) + + request.retained_resource_metadata_bytes(); + let request_bytes = retained_request_bytes(request)? + .checked_add(metadata_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment metadata overflow"))?; + let mut admission = self.admit_with_policy(scene, request, options, partial)?; + let environment_bytes = + environment.map_or(Ok(0), |value| value.required_bytes()).map_err(|error| JobError::new(ErrorCode::InvalidRequest, error.to_string()))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + admission.preparation_bytes = admission + .preparation_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + self.check_request_sum(admission.estimated_total_bytes, request_bytes, request.cpu_budget())?; + Ok((admission, request_bytes)) + } + + fn admit_with_policy( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + partial: Option, + ) -> Result { + request.validate_raster_request()?; + if self.0.executor.is_some() && (request.has_explicit_raster_lights() || request.raster_exposure_ev != 0.0) { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept Raster-only lights or exposure")); + } + if let Some(policy) = partial { + let plan = policy.preview_plan(); + if self.0.executor.is_some() + || request.integrator != Integrator::Raytrace + || request.transparent_background + || request.environment.is_some() + || request.textures.is_some() + || request.raytrace.as_ref().and_then(|v| v.progressive).is_none() + || plan != super::PartialPreviewPlan::new(request.width, request.height)? + { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial previews require the canonical builtin CPU progressive request")); + } + if let CpuPreviewPolicy::Protected(protected) = policy { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require a progressive sample target"))? + .samples_per_pixel; + protected.validate()?; + if protected != super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan does not match its admitted request")); + } + } + } + let scatter = |t: Option| t.and_then(|v| v.subsurface()).is_some_and(|s| s.active()); + if scene.meshes.iter().any(|b| scatter(b.transmission) || b.faces.iter().any(|f| scatter(f.transmission))) + && !self.0.executor.as_ref().is_some_and(|executor| executor.supports_subsurface()) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "installed image producer does not implement interior subsurface random walks")); + } + + self.validate_integrator(request.integrator)?; + options.validate()?; + if let Some(executor) = &self.0.executor { + if request.raytrace.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept CPU raytrace options")); + } + if options.aging.active() && !executor.supports_aging() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot evaluate ordered surface aging")); + } + if options.finishing.photographic.active() && !executor.supports_photographic() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply photographic lens effects")); + } + if options.nested_media && !executor.supports_nested_media() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement certified nested media")); + } + if options.volume.is_some() && !executor.supports_volume() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement bounded homogeneous volume transport")); + } + if options.adaptive.is_some() && !executor.supports_adaptive_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement independent-pilot adaptive sampling")); + } + if options.transmission_samples != 1 && !executor.supports_transmission_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement transmission strata")); + } + if options.linear_exr && !executor.supports_linear_exr() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot retain a raw linear EXR")); + } + if options.finishing.bloom.is_some_and(|b| b.active()) && !executor.supports_bloom() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement display bloom")); + } + if (!options.finishing.is_identity() || options.backdrop.is_some()) && !executor.supports_finishing() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply the requested finishing/backdrop")); + } + let admission = executor.admit(scene, request, options)?; + if admission.estimated_total_bytes > self.job_limit_bytes() { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(admission) + } else { + request.cpu_budget().validate_execution()?; + // Only the existing nesting opt-in is admitted on the CPU raytrace path. + // Every other JobOptions field retains its exact default-only contract. + if (JobOptions { nested_media: false, ..options }) != JobOptions::default() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU images use raytrace options, not progressive sampling controls")); + } + if let Some(policy) = partial { + #[cfg(feature = "raytrace-cpu")] + { + let raytrace = request + .raytrace + .as_ref() + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "partial previews require CPU progressive options"))?; + return match policy { + CpuPreviewPolicy::Shared(plan) => { + crate::raytrace::image::admit_with_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + CpuPreviewPolicy::Protected(plan) => { + crate::raytrace::image::admit_with_protected_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + }; + } + #[cfg(not(feature = "raytrace-cpu"))] + { + let _ = policy; + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + } + if !options.nested_media { + return admit(scene, request); + } + if request.integrator != Integrator::Raytrace || request.environment.is_some() || request.textures.is_some() || scene.has_transmission() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU nested media require explicit raytrace dielectric overrides")); + } + #[cfg(feature = "raytrace-cpu")] + { + let defaults = super::RaytraceOptions::default(); + let raytrace = request.raytrace.as_ref().unwrap_or(&defaults); + crate::raytrace::image::admit_with_nested(scene, request, raytrace, true) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + + fn check_request_sum(&self, work: u64, request: u64, budget: super::CpuBudget) -> Result<()> { + if self.0.executor.is_none() { + if budget == super::CpuBudget::Compact { + return admit_request_sum(work, request); + } + if work.checked_add(request).is_none_or(|n| n > budget.limits().max_job_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "CPU work and retained request exceed the selected profile")); + } + return Ok(()); + } + if work.checked_add(request).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(()) + } + + /// Check the execution choice without capturing geometry or reserving memory. + pub fn validate_integrator(&self, integrator: Integrator) -> Result<()> { + if self.0.executor.is_some() && integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing requires the native worker host")); + } + Ok(()) + } + + /// Select exactly one executor for this request. Never rely on registry order + /// to choose between raster and raytracing implementations. + pub fn descriptor_for(&self, integrator: Integrator) -> Result { + if let Some(executor) = &self.0.executor { + if integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + let mut descriptor = executor.descriptor()?; + if !self.is_available() { + descriptor.availability = Availability::Unavailable { reason: "image host has stopped".into() }; + } + return Ok(descriptor); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + Ok(ExecutorDescriptor { + id: ExecutorId::new(match integrator { + Integrator::Raster => "cpu-product", + Integrator::Raytrace => "cpu-raytrace", + }) + .map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: if self.0.shared.stop.load(Ordering::Acquire) { + Availability::Unavailable { reason: "image host has stopped".into() } + } else if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + Availability::Unavailable { reason: "CPU raytracing requires the native worker host".into() } + } else { + Availability::Available + }, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: if integrator == Integrator::Raytrace && cfg!(feature = "raytrace-cpu") && self.kind() == HostKind::NativeWorker { + // Refraction is the certified thin-sheet/axis-aligned-box CPU preview + // contract. Admission still refuses unsupported geometry and combinations. + vec![crate::RenderFeature::Pbr, crate::RenderFeature::Hdri, crate::RenderFeature::Refraction] + } else { + vec![crate::RenderFeature::Pbr] + }, + }], + limits: if integrator == Integrator::Raytrace && self.kind() == HostKind::NativeWorker && usize::BITS >= 64 { + super::CpuBudget::Workstation.image_limits(false) + } else { + RenderLimits::default() + }, + scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }) + } + + /// Resolve a CPU request against its explicit envelope, never the largest advertised one. + pub fn descriptor_for_request(&self, request: &ImageRequest) -> Result { + let mut descriptor = self.descriptor_for(request.integrator)?; + if self.0.executor.is_none() && request.integrator == Integrator::Raytrace { + let budget = request.cpu_budget(); + budget.validate_execution()?; + budget.validate_image(request.width, request.height, request.raytrace.as_ref().and_then(|o| o.progressive))?; + descriptor.limits = budget.image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())); + } + Ok(descriptor) + } + + pub fn submit(&self, id: JobId, scene_generation: u64, scene: ProductScene, request: ImageRequest) -> Result { + self.submit_with_environment(id, scene_generation, scene, request, None) + } + + /// Captured HDR ownership stays in work, never serialized/cloned into status. + pub fn submit_with_environment( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + environment: Option, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, JobOptions::default(), environment) + } + + pub fn submit_with_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, options, None) + } + + pub fn submit_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, None) + } + /// Transient CPU presentation policy. Final request and legacy observers are unchanged. + pub fn submit_cpu_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let plan = super::PartialPreviewPlan::new(request.width, request.height)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(CpuPreviewPolicy::Shared(plan))) + } + /// Opt-in protected feedback preserves ordinary work while admitting a finite extra quota. + pub fn submit_cpu_protected_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let policy = Self::protected_preview_policy(&request)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(policy)) + } + fn submit_with_policy(&self, input: Submission, partial_plan: Option) -> Result { + let Submission { id, scene_generation, scene, request, options, environment } = input; + self.validate_submission_environment(&scene, &request, environment.as_ref())?; + if id.session == 0 || id.serial == 0 || id.generation == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); + } + let environment_info = environment + .as_ref() + .map(|e| JobEnvironmentInfo::Cpu(e.metadata())) + .or_else(|| request.environment.as_ref().map(|source| JobEnvironmentInfo::Gpu(source.info().clone()))); + let textures = request.textures.as_ref().map(|source| source.summary()); + let mut features = scene.required_features(); + if environment.is_some() || request.environment.is_some() { + features.push(crate::RenderFeature::Hdri); + } + if request.integrator == Integrator::Raytrace + && request.raytrace.as_ref().is_some_and(|options| !options.dielectrics.is_empty()) + && !features.contains(&crate::RenderFeature::Refraction) + { + features.push(crate::RenderFeature::Refraction); + } + let (Admission { estimated_total_bytes, .. }, request_bytes) = + self.admit_submission(&scene, &request, options, environment.as_ref(), partial_plan)?; + let mut backend = crate::builtin_backend(); + let descriptor = self.descriptor_for_request(&request)?; + let expected_executor = descriptor.id.clone(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(request.width), + height: u64::from(request.height), + format: Some(RenderFormat::Png), + features, + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, e.to_string()))?; + if resolved.executor != expected_executor { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product 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, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + self.check_request_sum(estimated_total_bytes, request_bytes, request.cpu_budget())?; + let mut reservation = self.0.shared.budget.reserve(estimated_total_bytes)?; + + let partial_credits = partial_plan + .map(|policy| match policy { + CpuPreviewPolicy::Shared(plan) => PartialCredits::new(plan, &mut reservation), + CpuPreviewPolicy::Protected(plan) => PartialCredits::new_protected(plan, &mut reservation), + }) + .transpose()?; + let request_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) }; + // Preserve the original CPU option capacities in the retained request and its lease. + // Registered executors instead move resource Arcs into work and keep a small public copy. + let (public_request, work_request) = if self.0.executor.is_some() { + (ImageRequest { environment: None, textures: None, ..request.clone() }, Some(request)) + } else { + (request, None) + }; + let handle = JobHandle(Arc::new(Record { + partial: partial_credits, + presentation: None, + textures, + options, + environment: environment_info, + _request_reservation: request_reservation, + id, + scene_generation, + request: public_request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: None, + request: work_request, + executor: self.0.executor.clone(), + scene, + handle: handle.clone(), + reservation, + environment, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Regrade the exact retained native master. No geometry, material, light or + /// device work is submitted. The original frame and its lease remain shared. + pub fn submit_regrade(&self, id: JobId, source: &JobHandle, presentation: super::presentation::Presentation) -> Result { + if id.session == 0 || id.serial == 0 || id.generation == 0 || id.session != source.id().session || id == source.id() { + return Err(JobError::new(ErrorCode::WrongOwner, "regrade requires a new identity in the source document session")); + } + let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; + let master = frame.master_source()?; + let bytes = super::regrade::required_bytes(&master, presentation)?; + let raw = master.linear_master_info().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "raw master metadata is missing"))?; + let origin = super::presentation::MasterPresentation { + source_job: source.id(), + master_job: master.info.job, + master_sha256: raw.sha256.clone(), + presentation, + denoise_applied: false, + }; + let metadata_bytes = (std::mem::size_of::() + origin.master_sha256.capacity() + 32) as u64; + if bytes.checked_add(metadata_bytes).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "master presentation exceeds the installed host's resource budget")); + } + let limits = RenderLimits { max_scratch_bytes: self.job_limit_bytes(), ..super::GPU_PATH_LIMITS }; + let descriptor = ExecutorDescriptor { + id: ExecutorId::new("linear-master").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::new(), + }], + limits, + scratch: ScratchLayout { sample_scale: 1, sample_bytes_per_pixel: 32, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }; + let mut backend = crate::builtin_backend(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(frame.info.width), + height: u64::from(frame.info.height), + format: Some(RenderFormat::Png), + features: Vec::new(), + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + width: frame.info.width, + height: frame.info.height, + camera: source.0.request.camera, + background: presentation.background, + transparent_background: presentation.transparent_background, + environment: None, + textures: None, + integrator: Integrator::Raster, + raytrace: None, + }; + let options = JobOptions { + finishing: presentation.finishing, + backdrop: presentation.backdrop, + exposure_ev: presentation.exposure_ev, + tone_map: presentation.tone_map, + ..Default::default() + }; + 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, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + let reservation = self.0.shared.budget.reserve(bytes)?; + let metadata = self.0.shared.budget.reserve(metadata_bytes)?; + let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); + let handle = JobHandle(Arc::new(Record { + partial: None, + presentation: Some(origin), + textures: None, + options, + environment: None, + _request_reservation: None, + id, + scene_generation: frame.info.scene_generation, + request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: Some((master, presentation)), + request: None, + executor: None, + environment: None, + scene: ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + handle: handle.clone(), + reservation, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Cooperative callers pump a small quantum independently of polling a job's status. + /// Native jobs run even when the UI is idle or a headless caller is not polling. + pub fn pump(&self, units: usize) -> Result { + if self.0.kind != HostKind::Cooperative { + return Ok(false); + } + let mut running = self.0.running.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "cooperative host lock poisoned"))?; + if running.is_none() { + let work = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.pop_front(); + if let Some(work) = work { + *running = Running::begin(work); + } + } + if let Some(work) = running.as_mut() { + if let Ok(mut active) = self.0.shared.active.lock() { + *active = Some(Arc::downgrade(&work.handle.0)); + } + if !work.guarded_step(units) { + *running = None; + if let Ok(mut active) = self.0.shared.active.lock() { + *active = None; + } + } + } + Ok(running.is_some() + || !self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.is_empty()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_worker(shared: Arc) { + loop { + let mut queue = match shared.queue.lock() { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + while queue.is_empty() && !shared.stop.load(Ordering::Acquire) { + queue = match shared.wake.wait(queue) { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + } + if shared.stop.load(Ordering::Acquire) { + return; + } + let work = queue.pop_front(); + drop(queue); + let Some(mut running) = work.and_then(Running::begin) else { continue }; + if let Ok(mut active) = shared.active.lock() { + *active = Some(Arc::downgrade(&running.handle.0)); + } + loop { + if shared.stop.load(Ordering::Acquire) { + let _ = running.handle.cancel(); + } + if !running.guarded_step(4096) { + break; + } + } + if let Ok(mut active) = shared.active.lock() { + *active = None; + } + } +} +#[cfg(test)] +mod retained_request_tests { + use super::*; + #[test] + fn retained_emitters_bill_vector_and_original_name_capacities_in_same_pool() { + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("fixture"); + let mut emissions = Vec::with_capacity(32); + emissions.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Front, + }); + let options = request.raytrace.as_mut().unwrap(); + options.emissions = Some(emissions); + let expected = 8 * std::mem::size_of::() as u64 + + 32 * std::mem::size_of::() as u64 + + 256; + assert_eq!(retained_request_bytes(&request).unwrap(), expected); + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: MEMORY_LIMIT }); + let lease = budget.reserve(expected).unwrap(); + assert_eq!(budget.used.load(Ordering::Acquire), expected); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected, expected).is_ok()); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected + 1, expected).is_err()); + drop(lease); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn emitter_request_lease_survives_real_completion_frame_eviction_and_last_handle() { + let mut host = CpuHost::for_platform().unwrap(); + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("emitter"); + let mut values = Vec::with_capacity(32); + values.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Both, + }); + request.raytrace.as_mut().unwrap().emissions = Some(values); + let expected = retained_request_bytes(&request).unwrap(); + let mesh = solidcraft_geom::Mesh { + positions: vec![solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::X, solidcraft_geom::Vec3::Y], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds, + }; + let job = host.submit(JobId { session: 1695, serial: 1, generation: 1 }, 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Completion publication precedes the worker's last temporary handle release. + // Join this test's worker before asserting exact lease ownership, as in the union test. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let held = job.clone(); + job.0.data.lock().unwrap().frame = None; + drop(job); + assert!(host.admitted_bytes() > expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + fn request() -> ImageRequest { + let mut lights = Vec::with_capacity(8); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(super::super::RaytraceOptions { lights: Some(lights), ..Default::default() }), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + } + } + #[test] + fn retained_lights_are_billed_by_original_capacity_and_sum_is_checked() { + let request = request(); + let bytes = retained_request_bytes(&request).unwrap(); + assert_eq!(bytes, 8 * std::mem::size_of::() as u64); + let cap = super::super::image::MAX_JOB_BYTES; + assert!(admit_request_sum(cap - bytes, bytes).is_ok()); + assert_eq!(admit_request_sum(cap - bytes + 1, bytes).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(admit_request_sum(u64::MAX, 1).unwrap_err().code, ErrorCode::LimitExceeded); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn retained_lights_keep_the_same_pool_lease_after_png_eviction() { + let host = CpuHost::for_platform().unwrap(); + let request = request(); + let expected = retained_request_bytes(&request).unwrap(); + let job = host + .submit( + JobId { session: 99, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + ) + .unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + let held_bytes = host.admitted_bytes(); + assert!(held_bytes > expected); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), held_bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod environment_metadata_lease_tests { + use super::*; + #[test] + fn captured_environment_metadata_survives_png_eviction_without_source_bytes() { + use crate::lighting::{ + HdrSource, + environment_input::{EnvironmentInfo, EnvironmentInput}, + }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.5, 2.0, 16).unwrap(); + let metadata = input.metadata(); + let expected = std::mem::size_of::() as u64; + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: None, + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }; + let job = host + .submit_with_environment( + JobId { session: 1693, serial: 7, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + Some(input), + ) + .unwrap(); + let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(matches!(status.environment, Some(JobEnvironmentInfo::Cpu(info)) if info.source_sha256 == metadata.source_sha256)); + host.join_worker_for_test().unwrap(); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(host); + drop(job); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod surface_request_metadata_tests { + use super::*; + use solidcraft_geom::{Aabb3, Mesh}; + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn surface_request_lease_survives_completion_frame_eviction_and_held_handles() { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use std::time::{Duration, Instant}; + fn settle(host: &CpuHost, expected: u64) { + let deadline = Instant::now() + Duration::from_secs(10); + while host.admitted_bytes() != expected && Instant::now() < deadline { + std::thread::yield_now(); + } + assert_eq!(host.admitted_bytes(), expected); + } + let mut host = CpuHost::for_platform().unwrap(); + let mut meshes = Vec::new(); + let mut effects = Vec::with_capacity(32); + for index in 0..32 { + let mut name = String::with_capacity(256); + name.push_str(&format!("{index:03}")); + name.push_str(&"x".repeat(253)); + assert_eq!(name.capacity(), 256); + meshes.push(ProductMesh { + transmission: None, + name: name.clone(), + mesh: Arc::new(Mesh::default()), + color: [100; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + effects.push(SurfaceEffect { + body: name, + frame: Default::default(), + repeat_mm: [20.0; 3], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }); + } + let scene = ProductScene { meshes, bounds: Aabb3 { min: solidcraft_geom::Vec3::ZERO, max: solidcraft_geom::Vec3::ZERO } }; + let mut request = request(); + request.integrator = Integrator::Raytrace; + request.raytrace = Some(super::super::RaytraceOptions { surface_effects: Some(effects), ..Default::default() }); + let metadata = retained_request_bytes(&request).unwrap(); + assert!(metadata >= 32 * 256); + let mut oversized = request.clone(); + let mut overallocated = Vec::with_capacity(64); + overallocated.extend(oversized.raytrace.as_mut().unwrap().surface_effects.take().unwrap()); + oversized.raytrace.as_mut().unwrap().surface_effects = Some(overallocated); + assert!(host.submit(id(40, 1), 1, scene.clone(), oversized).is_err()); + assert_eq!(host.admitted_bytes(), 0); + + let job = host.submit(id(40, 2), 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(Duration::from_secs(10)).unwrap().progress.phase, Phase::Completed); + // Wait for this host's last temporary worker handle before exact lease checks. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let png_bytes = frame._reservation.bytes; + settle(&host, metadata + png_bytes); + // Evict the record's frame under the same lock used by publication, while + // an external frame and a cloned job handle retain their independent leases. + job.0.data.lock().unwrap().frame = None; + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), metadata + png_bytes); + drop(frame); + settle(&host, metadata); + assert_eq!(held.status().unwrap().request.raytrace.unwrap().surface_effects.unwrap().len(), 32); + drop(held); + settle(&host, 0); + } + + fn request() -> ImageRequest { + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Default::default(), + raytrace: None, + camera: Default::default(), + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + } + } + + fn id(owner: u64, serial: u64) -> JobId { + JobId { session: owner, serial, generation: serial } + } +} + +/// Provisional source-film observation, separate from complete-pass previews. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PartialPreviewProjection { + TopLeftRepresentativeV1, +} +#[derive(Clone, Debug, Serialize)] +pub struct PartialPreviewInfo { + pub frame: FrameInfo, + pub sequence: u64, + pub source_width: u32, + pub source_height: u32, + pub completed_passes: u32, + pub updated_prefix: u64, + pub projection: PartialPreviewProjection, +} +/// Fields drop in declaration order: payload allocations die before credit return. +pub struct RenderPartialPreview { + pub info: PartialPreviewInfo, + png: Vec, + covered: Vec, + _lease: ReturnReservation, +} +const _: [(); 1] = [(); (std::mem::size_of::() + 2 * crate::MAX_RENDER_ID_BYTES + 256 <= 2048) as usize]; +impl RenderPartialPreview { + pub fn png(&self) -> &[u8] { + &self.png + } + pub fn covered(&self) -> &[u32] { + &self.covered + } +} +struct PartialCreditState { + report: Option, + free: Reservation, + in_flight: bool, + closed: bool, +} +struct PartialCredits { + protected: Option, + plan: super::PartialPreviewPlan, + state: Mutex, + requested: AtomicBool, + exhausted: AtomicBool, + _metadata: Reservation, +} +const _: [(); 1] = + [(); (std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::>() + 128 + <= 1024) as usize]; +impl PartialCredits { + fn new(plan: super::PartialPreviewPlan, reservation: &mut Reservation) -> Result> { + Self::new_with_protection(plan, None, reservation) + } + fn new_protected(plan: super::ProtectedPreviewPlan, reservation: &mut Reservation) -> Result> { + plan.validate()?; + Self::new_with_protection(plan.preview_plan(), Some(plan), reservation) + } + fn new_with_protection( + plan: super::PartialPreviewPlan, + protected: Option, + reservation: &mut Reservation, + ) -> Result> { + plan.validate()?; + let metadata = reservation.split(1024)?; + let bytes = plan.slot_bytes()?.checked_mul(2).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial credit overflow"))?; + let free = reservation.split(bytes)?; + Ok(Arc::new(Self { + plan, + protected, + state: Mutex::new(PartialCreditState { report: None, free, in_flight: false, closed: false }), + requested: AtomicBool::new(false), + exhausted: AtomicBool::new(false), + _metadata: metadata, + })) + } + fn request(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || self.exhausted.load(Ordering::Acquire) { + return Ok(false); + } + self.requested.store(true, Ordering::Release); + Ok(true) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + let bytes = self.plan.slot_bytes()?; + if state.closed + || state.in_flight + || self.exhausted.load(Ordering::Acquire) + || !self.requested.load(Ordering::Acquire) + || state.free.bytes < bytes + { + return Ok(None); + } + let reservation = state.free.split(bytes)?; + state.in_flight = true; + self.requested.store(false, Ordering::Release); + Ok(Some(ReturnReservation { reservation: Some(reservation), credits: self.clone(), in_flight: true })) + } + fn retained_slots_blocked(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial retention lock poisoned"))?; + Ok(!state.closed + && !state.in_flight + && !self.exhausted.load(Ordering::Acquire) + && self.requested.load(Ordering::Acquire) + && state.free.bytes < self.plan.slot_bytes()?) + } + fn exhaust(&self) { + self.exhausted.store(true, Ordering::Release); + self.requested.store(false, Ordering::Release); + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + state.in_flight = false; + self.requested.store(false, Ordering::Release); + // Atomic release only: no image destruction or user work under this lock. + let _ = state.free.shrink(0); + } +} +/// Unique lease; Arc payload clones never create another independent slot. +struct ReturnReservation { + reservation: Option, + credits: Arc, + in_flight: bool, +} +impl ReturnReservation { + fn published(&mut self) -> Result<()> { + let mut state = self.credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || !state.in_flight || !self.in_flight { + return Err(JobError::new(ErrorCode::Cancelled, "partial preview credit is no longer current")); + } + state.in_flight = false; + self.in_flight = false; + Ok(()) + } +} +impl Drop for ReturnReservation { + fn drop(&mut self) { + let Some(mut reservation) = self.reservation.take() else { return }; + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if self.in_flight { + state.in_flight = false; + } + if !state.closed { + let limit = self.credits.plan.slot_bytes().ok().and_then(|v| v.checked_mul(2)); + if state.free.bytes.checked_add(reservation.bytes).zip(limit).is_some_and(|(total, limit)| total <= limit) { + if state.free.merge_from(&mut reservation).is_err() { + state.closed = true; + let _ = state.free.shrink(0); + } + } else { + state.closed = true; + let _ = state.free.shrink(0); + } + } + drop(state); + // A closed sink releases this uniquely held reservation globally. + } +} +struct PartialPending { + covered: Vec, + completed_passes: u32, + updated_prefix: u64, +} +// Error paths preserve the same payload-before-lease destruction order. +struct PartialPublication { + png: Vec, + pending: PartialPending, + lease: ReturnReservation, +} +struct PartialRunning { + last_pass_attempt: u32, + pending: Option, + lease: Option, + credits: Arc, + next_sequence: u64, +} +impl PartialRunning { + fn new(credits: Arc) -> Self { + Self { pending: None, lease: None, credits, next_sequence: 1, last_pass_attempt: 0 } + } +} +impl JobHandle { + /// Real producer usage, unavailable until a protected task was actually constructed. + pub fn protected_preview_report(&self) -> Result> { + self.0.partial.as_ref().map_or(Ok(None), |credits| { + let state = credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + Ok(state.report) + }) + } + /// Request presentation only; this is not a visual-authority certificate. + pub fn request_partial_preview(&self) -> Result { + let terminal = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?.progress.phase.terminal(); + if terminal { + return Ok(false); + } + self.0.partial.as_ref().map_or(Ok(false), |credits| credits.request()) + } + pub fn partial_preview_exhausted(&self) -> Result { + Ok(self.0.partial.as_ref().is_some_and(|credits| credits.exhausted.load(Ordering::Acquire))) + } + pub fn partial_preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial preview lock poisoned"))?; + let preview = data.partial_preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "partial preview identity does not match its job")); + } + Ok(preview) + } +} +impl Running { + #[cfg(feature = "raytrace-cpu")] + fn capture_partial(&mut self, png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64) -> Result<()> { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without its policy"))?.get_mut()?; + let plan = partial.credits.plan; + let source_pixels = u64::from(plan.source_width()) * u64::from(plan.source_height()); + let target = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without progressive intent"))? + .samples_per_pixel; + let covered_limit = plan.covered_bytes()?; + if partial.lease.is_none() + || partial.pending.is_some() + || completed_passes >= target + || updated_prefix >= source_pixels + || (completed_passes == 0 && updated_prefix == 0) + || covered.len() as u64 != plan.pixels() + || (covered.capacity() as u64).checked_mul(4).is_none_or(|v| v > covered_limit) + || png.capacity() as u64 > plan.encoded_limit()? + { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload exceeds its admitted frontier or capacities")); + } + // This sole sidecar verification scan was included in the producer's precharge. + for (index, count) in covered.iter().enumerate() { + self.handle.0.cancel.check()?; + let source = plan.source_index(index)? as u64; + let samples = completed_passes + .checked_add(u32::from(source < updated_prefix)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial sample count overflow"))?; + if *count > samples { + return Err(JobError::new(ErrorCode::Internal, "partial coverage exceeds committed source samples")); + } + } + partial.pending = Some(PartialPending { covered, completed_passes, updated_prefix }); + self.pending_png = Some(PendingPng::new(png)); + Ok(()) + } + fn publish_partial(&mut self, png: Vec, digest: sha2::digest::Output) -> Result { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication state"))?.get_mut()?; + let pending = partial.pending.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial metadata"))?; + let lease = partial.lease.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication credit"))?; + let mut publication = PartialPublication { png, pending, lease }; + let sequence = partial.next_sequence; + let next = sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial preview sequence exhausted"))?; + let plan = partial.credits.plan; + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: plan.width(), + height: plan.height(), + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: publication.png.len() as u64, + png_sha256: format!("{:x}", digest), + }; + let metadata = std::mem::size_of::() + .checked_add(64 + 2 * crate::MAX_RENDER_ID_BYTES) + .and_then(|v| v.checked_add(info.png_sha256.capacity())); + if metadata.is_none_or(|v| v > 2048) { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload metadata exceeds its slot")); + } + // No Data lock while touching the credit coordinator. + publication.lease.published()?; + let PartialPublication { png, pending, lease } = publication; + let preview = Arc::new(RenderPartialPreview { + info: PartialPreviewInfo { + frame: info, + sequence, + source_width: plan.source_width(), + source_height: plan.source_height(), + completed_passes: pending.completed_passes, + updated_prefix: pending.updated_prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }, + png, + covered: pending.covered, + _lease: lease, + }); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial publication lock poisoned"))?; + if self.handle.0.cancel.is_cancelled() || data.progress.phase.terminal() { + drop(data); + drop(preview); + return Err(JobError::new(ErrorCode::Cancelled, "late partial preview refused")); + } + let released = data.partial_preview.replace(preview); + partial.next_sequence = next; + // A demand arriving during encoding remains pending; never clear it here. + drop(data); + drop(released); + self.handle.0.notify(); + Ok(true) + } +} + +impl PartialCredits { + fn policy(&self) -> CpuPreviewPolicy { + self.protected.map_or(CpuPreviewPolicy::Shared(self.plan), CpuPreviewPolicy::Protected) + } + fn store_report(&self, report: Option) -> Result<()> { + let (plan, report) = match (self.protected, report) { + (None, None) => return Ok(()), + (Some(plan), Some(report)) => (plan, report), + _ => return Err(JobError::new(ErrorCode::Internal, "producer work report differs from its admitted policy")), + }; + let presentation = plan.presentation_limit()?; + let aggregate = plan.aggregate_limit()?; + let expected_v = plan.snapshot_work()?.checked_mul(u64::from(report.accepted_snapshots)); + let used = report.ordinary_used.checked_add(report.presentation_used); + if report.policy_version != 1 + || report.ordinary_limit != plan.ordinary_limit() + || report.presentation_limit != presentation + || report.aggregate_limit != aggregate + || report.quota_limit != plan.quota_limit() + || report.ordinary_used > report.ordinary_limit + || report.presentation_used > presentation + || used.is_none_or(|v| v > aggregate) + || expected_v != Some(report.presentation_used) + || report.accepted_snapshots > report.next_milestone_index + || report.next_milestone_index > report.quota_limit + || report.quota_exhausted != (report.accepted_snapshots == report.quota_limit) + || report.milestones_complete != (report.next_milestone_index == report.quota_limit) + { + return Err(JobError::new(ErrorCode::Internal, "protected work report violates its actual admission")); + } + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + if state.report.is_some_and(|previous| { + previous.ordinary_used > report.ordinary_used + || previous.presentation_used > report.presentation_used + || previous.accepted_snapshots > report.accepted_snapshots + || previous.next_milestone_index > report.next_milestone_index + }) { + drop(state); + return Err(JobError::new(ErrorCode::Internal, "protected work report counters moved backwards")); + } + state.report = Some(report); + if report.quota_exhausted { + self.exhaust(); + } + Ok(()) + } +} + +impl WorkTask { + #[cfg(feature = "raytrace-cpu")] + fn raytrace_with_slot( + task: crate::raytrace::image::ImageTask, + report_sink: Option<&PartialCredits>, + make_slot: impl FnOnce(crate::raytrace::image::ImageTask) -> Result>, + ) -> Result { + // ImageTask is already real, even if its host wrapper cannot be allocated. + if let Some(credits) = report_sink { + credits.store_report(task.protected_preview_report())?; + } + make_slot(task).map(Self::Raytrace) + } +} diff --git a/proposals/render/2026-10-31/c27-sha-state-recovery/delta-LF-review.patch b/proposals/render/2026-10-31/c27-sha-state-recovery/delta-LF-review.patch new file mode 100644 index 000000000..223f74cac --- /dev/null +++ b/proposals/render/2026-10-31/c27-sha-state-recovery/delta-LF-review.patch @@ -0,0 +1,171 @@ +--- a/crates/render/src/job/host.rs ++++ b/crates/render/src/job/host.rs +@@ -725,7 +725,7 @@ + hashed: usize, + preview_samples: Option, + exr: Option>, +- exr_digest: Sha256, ++ png_digest: Option>, + exr_hashed: usize, + } + // Keep the new fixed completion state within the existing metadata allowance +@@ -741,7 +741,7 @@ + + impl PendingPng { + fn new(png: Vec) -> Self { +- Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, exr_digest: Sha256::new(), exr_hashed: 0 } ++ Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, png_digest: None, exr_hashed: 0 } + } + + #[cfg(feature = "raytrace-cpu")] +@@ -749,20 +749,30 @@ + Self { preview_samples: Some(samples), ..Self::new(png) } + } + ++ fn finish_png_digest(&mut self) { ++ if self.hashed == self.png.len() && self.png_digest.is_none() { ++ // PNG and EXR are scanned serially. Keep the completed PNG output, ++ // then reuse a fresh digest state for EXR without another allocation. ++ self.png_digest = Some(std::mem::take(&mut self.digest).finalize()); ++ } ++ } ++ + fn step(&mut self, units: usize, cancel: &CancelToken) -> Result { + cancel.check()?; ++ self.finish_png_digest(); + for _ in 0..units.min(PNG_HASH_CHUNKS_PER_ADVANCE) { +- let (bytes, hashed, digest) = if self.hashed < self.png.len() { +- (&self.png, &mut self.hashed, &mut self.digest) ++ let (bytes, hashed) = if self.hashed < self.png.len() { ++ (&self.png, &mut self.hashed) + } else if let Some(exr) = self.exr.as_ref().filter(|exr| self.exr_hashed < exr.len()) { +- (exr, &mut self.exr_hashed, &mut self.exr_digest) ++ (exr, &mut self.exr_hashed) + } else { + break; + }; + let end = hashed.saturating_add(PNG_HASH_CHUNK_BYTES).min(bytes.len()); +- digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?); ++ self.digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?); + *hashed = end; + cancel.check()?; ++ self.finish_png_digest(); + } + Ok(self.hashed == self.png.len() && self.exr.as_ref().is_none_or(|exr| self.exr_hashed == exr.len())) + } +@@ -774,6 +784,65 @@ + } + } + } ++ ++#[cfg(test)] ++#[test] ++fn sequential_png_and_exr_hashing_preserves_independent_payload_digests() { ++ let quantum_bytes = PNG_HASH_CHUNK_BYTES * PNG_HASH_CHUNKS_PER_ADVANCE; ++ for units in [1, 3] { ++ for exr_length in [None, Some(0), Some(quantum_bytes + 29)] { ++ let png: Vec = (0..quantum_bytes + 13).map(|index| (index as u8).wrapping_mul(17).wrapping_add(3)).collect(); ++ let exr: Option> = exr_length.map(|length| (0..length).map(|index| (index as u8).wrapping_mul(29).wrapping_add(101)).collect()); ++ let expected_png = Sha256::digest(&png); ++ let expected_exr = exr.as_ref().map(Sha256::digest); ++ if let Some(expected_exr) = &expected_exr { ++ assert_ne!(&expected_png, expected_exr, "the distinct payloads must not share a digest"); ++ } ++ let png_length = png.len(); ++ let exr_length = exr.as_ref().map_or(0, Vec::len); ++ assert!(png_length > quantum_bytes); ++ assert!(exr_length == 0 || exr_length > quantum_bytes); ++ let chunks = png_length.div_ceil(PNG_HASH_CHUNK_BYTES) + exr_length.div_ceil(PNG_HASH_CHUNK_BYTES); ++ let steps = chunks.div_ceil(units); ++ let mut pending = PendingPng::new(png); ++ pending.exr = exr; ++ let cancel = CancelToken::default(); ++ assert!(!pending.step(0, &cancel).unwrap()); ++ assert_eq!((pending.hashed, pending.exr_hashed), (0, 0)); ++ assert!(pending.png_digest.is_none()); ++ let mut crossed_within_step = false; ++ let mut saw_png_only_boundary = false; ++ for step in 0..steps { ++ let before_png = pending.hashed; ++ let before_exr = pending.exr_hashed; ++ let done = pending.step(units, &cancel).unwrap(); ++ assert_eq!(done, step + 1 == steps); ++ let advanced = pending.hashed + pending.exr_hashed - before_png - before_exr; ++ assert!(advanced > 0 && advanced <= units * PNG_HASH_CHUNK_BYTES); ++ if pending.hashed == png_length { ++ assert_eq!(pending.png_digest.as_ref(), Some(&expected_png)); ++ saw_png_only_boundary |= pending.exr_hashed == 0; ++ } ++ crossed_within_step |= before_png < png_length && pending.hashed == png_length && pending.exr_hashed > 0; ++ assert_eq!(pending.progress().done, (pending.hashed + pending.exr_hashed) as u64); ++ assert_eq!(pending.progress().total, (png_length + exr_length) as u64); ++ } ++ assert_eq!((pending.hashed, pending.exr_hashed), (png_length, exr_length)); ++ if exr_length > 0 { ++ assert_eq!(crossed_within_step, units == 3); ++ assert_eq!(saw_png_only_boundary, units == 1); ++ } ++ for extra_units in [0, 1] { ++ assert!(pending.step(extra_units, &cancel).unwrap()); ++ assert_eq!(pending.png_digest.as_ref(), Some(&expected_png)); ++ let actual_exr = pending.exr.as_ref().map(|_| pending.digest.clone().finalize()); ++ assert_eq!(actual_exr, expected_exr, "EXR must start from a fresh SHA state and survive repeated completed steps"); ++ assert_eq!((pending.hashed, pending.exr_hashed), (png_length, exr_length)); ++ } ++ } ++ } ++} ++ + + struct Running { + source_master: Option>, +@@ -1247,10 +1316,11 @@ + data.progress = progress; + return Ok(true); + } +- let PendingPng { png, digest, preview_samples, exr, exr_digest, .. } = ++ let PendingPng { png, digest, preview_samples, exr, png_digest, .. } = + self.pending_png.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed PNG digest"))?; ++ let png_digest = png_digest.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing finalized PNG digest"))?; + if self.partial.as_ref().and_then(|slot| slot.0.first()).is_some_and(|partial| partial.pending.is_some()) { +- return self.publish_partial(png, digest); ++ return self.publish_partial(png, png_digest); + } + let info = FrameInfo { + job: self.handle.0.id, +@@ -1262,7 +1332,7 @@ + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, +- png_sha256: format!("{:x}", digest.finalize()), ++ png_sha256: format!("{:x}", png_digest), + }; + // Include the working digest/Vec metadata, completed frame layout, + // actual hex allocation, bounded copied IDs and Arc/header allowance. +@@ -1340,7 +1410,7 @@ + let exr = exr.map(|bytes| { + let info = LinearMasterInfo { + bytes: bytes.len() as u64, +- sha256: format!("{:x}", exr_digest.finalize()), ++ sha256: format!("{:x}", digest.finalize()), + encoding: LinearColourEncoding::SceneLinearSrgbD65, + alpha: LinearAlphaConvention::CoveragePremultiplied, + }; +@@ -2799,7 +2869,7 @@ + self.pending_png = Some(PendingPng::new(png)); + Ok(()) + } +- fn publish_partial(&mut self, png: Vec, digest: Sha256) -> Result { ++ fn publish_partial(&mut self, png: Vec, digest: sha2::digest::Output) -> Result { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication state"))?.get_mut()?; + let pending = partial.pending.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial metadata"))?; +@@ -2818,7 +2888,7 @@ + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: publication.png.len() as u64, +- png_sha256: format!("{:x}", digest.finalize()), ++ png_sha256: format!("{:x}", digest), + }; + let metadata = std::mem::size_of::() + .checked_add(64 + 2 * crate::MAX_RENDER_ID_BYTES) diff --git a/proposals/render/2026-10-31/c27-sha-state-recovery/source-bindings.json b/proposals/render/2026-10-31/c27-sha-state-recovery/source-bindings.json new file mode 100644 index 000000000..f120248d0 --- /dev/null +++ b/proposals/render/2026-10-31/c27-sha-state-recovery/source-bindings.json @@ -0,0 +1,27 @@ +{ + "status": "SOURCE_ONLY_C27_SHA_STATE_RECOVERY_V2_UNFORMATTED_UNCOMPILED_UNRUN", + "required_receiver": "Exact C27 post-format failed-build 25-file composition, with every unrelated file preserved; not arbitrary main or the earlier nine-file checkpoint.", + "receiver_source_manifest_sha256": "a7b088eef563cbba4bfc5f2c26cf2d02ac6e855088710a072fdff35f889c1551", + "files": [ + { + "path": "crates/render/src/job/host.rs", + "before_sha256": "f775f4e458947b2c402fe97f10b320f7c7f4a9060cf502b5a69975e006eec71e", + "before_bytes": 131474, + "after_sha256": "2c72c307ec49a94b100f4be32ab6a4af4be494199ff7ad5c87bb698e7f13ab4e", + "after_bytes": 135425 + } + ], + "production_change": "One retained active SHA256 state plus the finalized 32-byte PNG output; the existing1024-byte metadata allowance/assertions are unchanged. No new heap-backed state is introduced.", + "new_test": "job::host::sequential_png_and_exr_hashing_preserves_independent_payload_digests", + "new_tests_written": 1, + "new_tests_run": 0, + "actual_C27_selected_cases_UNRUN": 982, + "proposed_next_selected_cases": 983, + "all_proposed_cases_state": "UNRUN", + "Kernel_independent_review": "CLOSED_NO_BLOCKING_SOURCE_FINDING_NOT_RUNTIME", + "E0308_resolved_by_compilation": false, + "exact_target_ABI_layout_known": false, + "full_CI_native_or_GPU_acceptance": false, + "local_source_adoption": "COMPLETE_NO_EXECUTION_GRANT", + "local_adopted_source_manifest_sha256": "9a2bfddacbd5a7f38ec4e4aba0e75fb99420d278a483d7ae8c2cf1cf53a359bb" +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/README.md b/proposals/render/2026-10-31/cpu-every-pass-c27-source/README.md new file mode 100644 index 000000000..4ac062950 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/README.md @@ -0,0 +1,70 @@ +# CPU progressive every-pass composition — exact C27 failed-build source + +31 October 2026. Reviewable source preservation for #6201: **25 composed files, +formatted locally, but not successfully compiled, tested, installed, ready or +merged**. All **982 selected native cases remain UNRUN**. No native per-pass +display, GPU, image-quality/parity or full repository CI pass is claimed. + +## Included source + +The composed proposal connects complete-pass publication, bounded reusable image +slots and a counted external-retention exception; u32 film/coverage consumers; +the explicit Workstation ceiling of 1,048,576 passes; and Interactive controls +that retain an explicit target/seed. Compact 64, Studio 1024, pixel-times-sample, +ordinary-work and memory limits remain binding. At 1,048,576 passes, Workstation's +unchanged 68,719,476,736 camera-sample cap permits at most 65,536 pixels. This is not +permission to combine every maximum or a promise of perfect physical quality. + +Normal production attempts an image at every complete nonfinal pass, then one +final image. If both reusable slots remain externally pinned after host credit +retirement/retry, the real retention-skip counter records the omitted snapshot; +final work continues without an acknowledgement wait or an unbounded PNG list. +Publication and a slower client's physical repaints are different observations. +The final/provisional/export, cancellation, invalidation and Nateaux UI contracts +remain acceptance obligations, not completed fixes established by this archive. + +## Actual C27 outcome + +Formatting and its check exited 0 and changed 11 of the selected Rust files. The +normal combined-library build then exited 101 with **E0308 at +`crates/render/src/job/host.rs:734`**: a compile-time aggregate metadata-size +assertion for the 1,024-byte admission allowance was false. No exact layout size +was inferred. Raising the assertion allowance is not the accepted repair. + +No test binary inventory or test body ran: **0 passed, 0 failed, 982 UNRUN**; there +was no qualified five-library artifact set. Strict affected Clippy, wasm, lists, +the full repository gate and native application acceptance were not reached. +This was a compiler/source failure, not a RAM-admission stop: the pre-build free +RAM sample was 11,556,589,568 bytes against 7,516,192,768 required; the observed +minimum was 11,035,467,776 bytes and no sticky memory-floor fault was reported. +The owned attempt terminated and its reservation was released. A private host +layout/accounting repair is pending and is **not** silently included here. + +## Relationship to the earlier checkpoint + +This supersedes the [earlier nine-source high-pass/UI snapshot](https://github.com/tangency-labs/solidcraft/blob/dbc6041ba7059ec30b11fa72b5d1abd59f5b104a/proposals/render/2026-10-31/cpu-high-pass-ui-source/README.md) +for continuation of this composed unit; it does not erase that history. That +snapshot's new cooperative UI fixture was later found invalid at the source/API +boundary. Its raw source was retained privately and the new test was explicitly +replaced with request-only coverage plus separate consumer-state coverage. This +does **not** satisfy native each-pass acceptance. The next owned desktop run must +still show real images for passes 1 → 2 → 3 → 4 in a detailed original scene, including +cancel/edit/restart and final/export authority. No synthetic counter or terminal +image may stand in for those observations. + +## Applying and continuing + +`candidate/` contains all 25 exact C27 post-format RAW files. The portable +`source-bindings.json` binds every immediate before/after byte length and digest; +the new locale has a null before binding. Verify the required receiver first. +`delta-LF-review.patch` is the full readable 25-file change, including removals; +the RAW candidates and hashes are authoritative for mixed line endings. Do not +apply this to arbitrary current main or stack it blindly over another snapshot. + +The production draft #8938 remained at +`a077906234972dbbf11e80c54893f85ece97c8b7` at this checkpoint. This archive does +not update that production head or the installed app. Continue with the separately +reviewed metadata/accounting fix, exact source composition, a fresh serial cached +validation and its own actual artifacts/inventories before tests. Default-change +classification/preference handling remains unresolved before production readiness; +source preservation does not waive that process. diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/assets/locales/pending/cpu-progressive-passes.json b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/assets/locales/pending/cpu-progressive-passes.json new file mode 100644 index 000000000..ed1393b61 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/assets/locales/pending/cpu-progressive-passes.json @@ -0,0 +1,20 @@ +{ + "de": { + "render.cpu_pass_progress": "Vollständige Durchgänge: {current} / {target} · vorläufig" + }, + "en": { + "render.cpu_pass_progress": "Complete passes: {current} / {target} · provisional" + }, + "es": { + "render.cpu_pass_progress": "Pasadas completas: {current} / {target} · provisional" + }, + "ja": { + "render.cpu_pass_progress": "完了したパス: {current} / {target} · 暫定" + }, + "ko": { + "render.cpu_pass_progress": "완료된 패스: {current} / {target} · 임시" + }, + "zh": { + "render.cpu_pass_progress": "完整遍数:{current} / {target} · 临时结果" + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_primary.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_primary.rs new file mode 100644 index 000000000..05da42ada --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_primary.rs @@ -0,0 +1,179 @@ +//! Bounded camera film: linear radiance sums and primary coverage, never display RGB. +//! Exactly one scanline-ordered update per pixel and absolute sample ordinal makes +//! a complete pass a state invariant. Initialization and updates are cancellable +//! single-pixel operations. The owning image job supplies its existing work lease. + +use super::{invalid, limit}; +use crate::job::{CancelToken, CpuBudget, CpuProgressiveOptions, ErrorCode, JobError, Result}; + +#[derive(Clone, Copy, Default, Debug, PartialEq)] +struct Pixel { + sum: [f64; 3], + covered: u32, +} + +/// Observed scanline frontier; metadata only, never a caller-supplied authority. +/// Every pixel before updated_prefix has one more sample than completed_passes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PartialFrontier { + pub completed_passes: u32, + pub updated_prefix: usize, + pub pixels: usize, +} + +/// A partial view never invents a zero sample for a pixel not yet observed. +/// Sampled linear radiance includes zero contributions from primary misses. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum PartialPixel { + Unknown, + Sampled { linear_premultiplied: [f64; 3], covered: u32, count: u32 }, +} + +pub(crate) struct PrimaryFilm { + pixels: Vec, + count: usize, + sample_limit: u32, + samples: u32, + next_pixel: usize, +} + +impl PrimaryFilm { + pub(crate) fn required_bytes(width: u32, height: u32, options: CpuProgressiveOptions, budget: CpuBudget) -> Result { + options.validate_image_with_budget(width, height, budget)?; + (u64::from(width) * u64::from(height)) + .checked_mul(std::mem::size_of::() as u64) + .and_then(|n| n.checked_add(std::mem::size_of::() as u64)) + .ok_or_else(|| limit("primary film storage overflow")) + } + + pub(crate) fn new( + width: u32, + height: u32, + options: CpuProgressiveOptions, + admitted_bytes: u64, + cancel: &CancelToken, + budget: CpuBudget, + ) -> Result { + cancel.check()?; + let required = Self::required_bytes(width, height, options, budget)?; + if admitted_bytes < required { + return Err(limit("primary film is not covered by image admission")); + } + let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|_| limit("primary film address space exceeded"))?; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(count).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve primary film"))?; + if pixels.capacity() != count { + return Err(limit("actual primary film capacity exceeds admission")); + } + cancel.check()?; + Ok(Self { pixels, count, sample_limit: options.samples_per_pixel, samples: 0, next_pixel: 0 }) + } + + pub(crate) fn initialized(&self) -> usize { + self.pixels.len() + } + + pub(crate) fn ready(&self) -> bool { + self.pixels.len() == self.count + } + + pub(crate) fn initialize_one(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> { + cancel.check()?; + if self.ready() { + return Err(invalid("primary film is already initialized")); + } + charge()?; + cancel.check()?; + self.pixels.push(Pixel::default()); + Ok(()) + } + + pub(crate) fn samples(&self) -> u32 { + self.samples + } + + /// Validate everything before the one bounded mutation. Failed/cancelled + /// updates never consume a sample ordinal or partially alter a pixel. + pub(crate) fn add( + &mut self, + index: usize, + ordinal: u32, + radiance: [f64; 3], + covered: bool, + cancel: &CancelToken, + charge: &mut impl FnMut() -> Result<()>, + ) -> Result<()> { + cancel.check()?; + if !self.ready() || index != self.next_pixel || ordinal != self.samples || ordinal >= self.sample_limit { + return Err(invalid("primary film requires the next pixel and absolute sample ordinal")); + } + if radiance.into_iter().any(|v| !v.is_finite() || !(0.0..=1e12).contains(&v)) || (!covered && radiance != [0.0; 3]) { + return Err(invalid("invalid primary linear radiance or coverage")); + } + let pixel = self.pixels.get(index).copied().ok_or_else(|| invalid("primary film pixel out of range"))?; + let sum = std::array::from_fn(|i| pixel.sum[i] + radiance[i]); + if sum.iter().any(|v| !v.is_finite() || *v < 0.0 || *v > f64::from(self.sample_limit) * 1e12) { + return Err(invalid("primary film radiance sum exceeds finite range")); + } + let hits = pixel.covered.checked_add(u32::from(covered)).filter(|n| *n <= ordinal + 1).ok_or_else(|| invalid("primary coverage overflow"))?; + charge()?; + cancel.check()?; + *self.pixels.get_mut(index).ok_or_else(|| invalid("primary film pixel disappeared"))? = Pixel { sum, covered: hits }; + self.next_pixel += 1; + if self.next_pixel == self.count { + self.next_pixel = 0; + self.samples += 1; + } + Ok(()) + } + + /// A display consumer can only read a fully completed, immutable pass. The + /// returned radiance is premultiplied by coverage; background is kept separate. + pub(crate) fn pixel(&self, index: usize) -> Result<([f64; 3], u32, u32)> { + if !self.ready() || self.next_pixel != 0 || self.samples == 0 { + return Err(invalid("primary film has no uniform complete pass")); + } + let pixel = self.pixels.get(index).ok_or_else(|| invalid("primary film resolve index out of range"))?; + Ok((pixel.sum.map(|sum| sum / f64::from(self.samples)), pixel.covered, self.samples)) + } + /// Inspect only the real committed state. This value does not freeze the film + /// or authorize a snapshot. A caller resolving several pixels must keep the + /// film immutably borrowed at one completed-pixel frontier, and must charge + /// reads/copies and check cancellation against its existing job budget. + pub(crate) fn partial_frontier(&self) -> Result { + if !self.ready() + || self.next_pixel >= self.count + || self.samples > self.sample_limit + || (self.samples == self.sample_limit && self.next_pixel != 0) + { + return Err(invalid("primary film has no initialized partial frontier")); + } + Ok(PartialFrontier { completed_passes: self.samples, updated_prefix: self.next_pixel, pixels: self.count }) + } + + /// Bounded allocation-free read, separate from the strict complete-pass pixel(). + /// Counts come from this film, never from a supplied frontier or sample count. + /// Unknown means count0/covered0; a sampled miss has count>0 and covered0. + /// No exposure, tone mapping, background, work lease or publication occurs here. + /// The caller owes cancellation checks and work charges for each read/copy; + /// this accessor creates no independent budget and never advances an ordinal. + pub(crate) fn partial_pixel(&self, index: usize) -> Result { + let frontier = self.partial_frontier()?; + let pixel = self.pixels.get(index).ok_or_else(|| invalid("primary film partial index out of range"))?; + let count = frontier + .completed_passes + .checked_add(u32::from(index < frontier.updated_prefix)) + .filter(|count| *count <= self.sample_limit) + .ok_or_else(|| limit("primary partial sample count exceeded"))?; + if pixel.covered > count { + return Err(invalid("primary partial coverage exceeds its committed count")); + } + if count == 0 { + if pixel.covered != 0 || pixel.sum != [0.0; 3] { + return Err(invalid("unobserved primary pixel has accumulated data")); + } + return Ok(PartialPixel::Unknown); + } + Ok(PartialPixel::Sampled { linear_premultiplied: pixel.sum.map(|sum| sum / f64::from(count)), covered: pixel.covered, count }) + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_tests.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_tests.rs new file mode 100644 index 000000000..a83a22b32 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/film_tests.rs @@ -0,0 +1,632 @@ +use super::*; + +#[cfg(feature = "raytrace-cpu")] +mod camera_passes { + use super::primary::PrimaryFilm; + use super::*; + use crate::job::CpuProgressiveOptions; + + fn primary() -> PrimaryFilm { + let options = CpuProgressiveOptions { samples_per_pixel: 4, seed: 7 }; + let bytes = PrimaryFilm::required_bytes(2, 1, options, crate::job::CpuBudget::Compact).unwrap(); + let mut film = PrimaryFilm::new(2, 1, options, bytes, &CancelToken::default(), crate::job::CpuBudget::Compact).unwrap(); + assert!(!film.ready()); + let mut charged = 0; + while !film.ready() { + film.initialize_one(&CancelToken::default(), &mut || { + charged += 1; + Ok(()) + }) + .unwrap(); + } + assert_eq!(charged, 2); + film + } + + #[test] + fn camera_film_keeps_linear_sums_coverage_and_uniform_absolute_passes() { + let mut film = primary(); + let cancel = CancelToken::default(); + assert!(film.pixel(0).is_err()); + for ordinal in 0..4 { + film.add(0, ordinal, [2.0, 4.0, 8.0], true, &cancel, &mut || Ok(())).unwrap(); + assert!(film.pixel(0).is_err(), "a partial pass cannot be resolved"); + assert!(film.add(0, ordinal, [0.0; 3], false, &cancel, &mut || Ok(())).is_err(), "duplicate pixel must not consume a sample"); + let covered = ordinal % 2 == 0; + film.add(1, ordinal, if covered { [6.0; 3] } else { [0.0; 3] }, covered, &cancel, &mut || Ok(())).unwrap(); + assert_eq!(film.samples(), ordinal + 1); + } + assert_eq!(film.pixel(0).unwrap(), ([2.0, 4.0, 8.0], 4, 4)); + assert_eq!(film.pixel(1).unwrap(), ([3.0; 3], 2, 4)); + assert!(film.add(0, 4, [1.0; 3], true, &cancel, &mut || Ok(())).is_err()); + } + + #[test] + fn camera_film_cancellation_invalid_radiance_and_work_failure_are_atomic() { + let mut film = primary(); + let cancel = CancelToken::default(); + let observer = cancel.clone(); + assert_eq!( + film.add(0, 0, [1.0; 3], true, &cancel, &mut || { + observer.cancel(); + Ok(()) + }) + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + for (rgb, covered) in [([1.0; 3], false), ([f64::NAN; 3], true), ([-1.0; 3], true)] { + assert!(film.add(0, 0, rgb, covered, &CancelToken::default(), &mut || Ok(())).is_err()); + } + assert!(film.add(0, 0, [1.0; 3], true, &CancelToken::default(), &mut || Err(limit("work exhausted"))).is_err()); + film.add(0, 0, [4.0; 3], true, &CancelToken::default(), &mut || Ok(())).unwrap(); + film.add(1, 0, [0.0; 3], false, &CancelToken::default(), &mut || Ok(())).unwrap(); + assert_eq!(film.pixel(0).unwrap(), ([4.0; 3], 1, 1)); + assert_eq!(film.pixel(1).unwrap(), ([0.0; 3], 0, 1)); + } +} + +fn film(width: u32, height: u32, limit: u32) -> FilmAccumulator { + let bytes = FilmAccumulator::required_bytes(width, height, limit).unwrap(); + FilmAccumulator::new(width, height, limit, bytes, &CancelToken::default(), &mut |_| Ok(())).unwrap() +} + +fn add(film: &mut FilmAccumulator, start: usize, values: &[[f64; 3]]) { + film.add_range(start, values, &CancelToken::default(), &mut |_| Ok(())).unwrap(); +} + +#[test] +fn constant_and_alternating_samples_have_analytic_statistics() { + let mut film = film(2, 1, 4); + for value in [0.0, 2.0, 0.0, 2.0] { + add(&mut film, 0, &[[7.0, 3.0, 1.0], [value; 3]]); + } + assert_eq!(film.pixel_statistics(0).unwrap(), PixelStatistics { mean: [7.0, 3.0, 1.0], variance: [0.0; 3], count: 4 }); + let statistics = film.pixel_statistics(1).unwrap(); + assert_eq!(statistics.mean, [1.0; 3]); + assert_eq!(statistics.variance, [4.0 / 3.0; 3]); +} + +#[test] +fn complete_pass_refuses_empty_or_uneven_counts_and_keeps_linear_values() { + let mut film = film(2, 1, 3); + assert!(film.complete_pass(&CancelToken::default(), &mut |_| Ok(())).is_err()); + add(&mut film, 0, &[[20.0, 2.0, 0.0]]); + assert!(film.complete_pass(&CancelToken::default(), &mut |_| Ok(())).is_err()); + add(&mut film, 1, &[[4.0, 8.0, 16.0]]); + let pass = film.complete_pass(&CancelToken::default(), &mut |_| Ok(())).unwrap(); + assert_eq!(pass.samples_per_pixel(), 1); + assert_eq!(pass.dimensions(), (2, 1)); + assert_eq!(pass.pixels().collect::>(), vec![[20.0, 2.0, 0.0], [4.0, 8.0, 16.0]]); +} + +#[test] +fn invalid_sample_at_end_leaves_entire_update_unchanged() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0] { + let mut film = film(2, 1, 3); + add(&mut film, 0, &[[1.0; 3], [2.0; 3]]); + let before = film.pixels.clone(); + assert_eq!(film.add_range(0, &[[3.0; 3], [bad; 3]], &CancelToken::default(), &mut |_| Ok(())).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(film.pixels, before); + } +} + +#[test] +fn sample_limit_and_numeric_overflow_refuse_atomically() { + let mut limited = film(2, 1, 1); + add(&mut limited, 1, &[[1.0; 3]]); + let before = limited.pixels.clone(); + assert_eq!(limited.add_range(0, &[[1.0; 3]; 2], &CancelToken::default(), &mut |_| Ok(())).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(limited.pixels, before); + let mut extreme = film(2, 1, 3); + add(&mut extreme, 0, &[[1.0; 3], [f64::MAX; 3]]); + let before = extreme.pixels.clone(); + assert!(extreme.add_range(0, &[[2.0; 3], [0.0; 3]], &CancelToken::default(), &mut |_| Ok(())).is_err()); + assert_eq!(extreme.pixels, before); +} + +#[test] +fn dimensions_bytes_and_actual_capacity_are_checked() { + for (width, height, samples) in [(0, 1, 1), (1, 0, 1), (u32::MAX, u32::MAX, 1), (1, 1, 0), (1, 1, MAX_SAMPLES + 1)] { + assert!(FilmAccumulator::required_bytes(width, height, samples).is_err()); + } + assert!(FilmAccumulator::required_bytes(MAX_DIMENSION, MAX_DIMENSION, 1).is_err()); + assert!(bytes_for_capacity(usize::MAX).is_err()); + let bytes = FilmAccumulator::required_bytes(2, 2, 1).unwrap(); + assert!(FilmAccumulator::new(2, 2, 1, bytes - 1, &CancelToken::default(), &mut |_| Ok(())).is_err()); + let film = film(2, 2, 1); + assert!(film.allocated_bytes().unwrap() <= bytes); + assert_eq!(film.allocated_bytes().unwrap(), bytes_for_capacity(film.pixels.capacity()).unwrap()); + assert!(film.allocated_bytes().unwrap() >= (std::mem::size_of::() * (4 + MAX_UPDATE)) as u64); +} + +#[test] +fn invalid_ranges_and_oversized_updates_preserve_state() { + let mut film = film(2, 1, 1); + for (start, values) in [(0, Vec::new()), (usize::MAX, vec![[1.0; 3]]), (2, vec![[1.0; 3]]), (0, vec![[1.0; 3]; MAX_UPDATE + 1])] { + assert!(film.add_range(start, &values, &CancelToken::default(), &mut |_| Ok(())).is_err()); + assert!(film.pixels.iter().all(|p| *p == Pixel::default())); + } + assert!(film.pixel_statistics(2).is_err()); +} + +#[test] +fn incremental_partitions_preserve_bitwise_results_in_sample_order() { + let mut whole = film(4, 1, 3); + let mut partitioned = film(4, 1, 3); + for values in [ + [[1.0; 3], [1e12; 3], [0.25; 3], [4.0; 3]], + [[2.0; 3], [1e12 + 1.0; 3], [0.5; 3], [2.0; 3]], + [[4.0; 3], [1e12 - 1.0; 3], [0.75; 3], [0.0; 3]], + ] { + add(&mut whole, 0, &values); + add(&mut partitioned, 0, &values[..1]); + add(&mut partitioned, 1, &values[1..3]); + add(&mut partitioned, 3, &values[3..]); + } + assert_eq!(whole.pixels, partitioned.pixels); + assert_eq!(whole.pixel_statistics(1).unwrap().variance, [1.0; 3]); +} + +#[test] +fn cancellation_and_work_failure_preserve_all_pixels() { + let mut film = film(2, 1, 3); + let cancel = CancelToken::default(); + let observer = cancel.clone(); + assert_eq!( + film.add_range(0, &[[1.0; 3]; 2], &cancel, &mut |_| { + observer.cancel(); + Ok(()) + }) + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + assert!(film.pixels.iter().all(|p| *p == Pixel::default())); + let mut charged = 0; + assert_eq!( + film.add_range(0, &[[1.0; 3]; 2], &CancelToken::default(), &mut |units| { + charged += units; + if charged > 2 { Err(limit("job work exhausted")) } else { Ok(()) } + }) + .unwrap_err() + .code, + ErrorCode::LimitExceeded + ); + assert_eq!(charged, 4); + assert!(film.pixels.iter().all(|p| *p == Pixel::default())); +} + +#[test] +fn construction_and_complete_pass_share_caller_work_and_cancel() { + let bytes = FilmAccumulator::required_bytes(2, 1, 1).unwrap(); + let cancel = CancelToken::default(); + cancel.cancel(); + assert!(FilmAccumulator::new(2, 1, 1, bytes, &cancel, &mut |_| panic!("cancelled construction charged work")).is_err()); + let mut charged = 0; + let mut film = FilmAccumulator::new(2, 1, 1, bytes, &CancelToken::default(), &mut |n| { + charged += n; + Ok(()) + }) + .unwrap(); + assert_eq!(charged, 2); + add(&mut film, 0, &[[1.0; 3]; 2]); + assert!(film.complete_pass(&CancelToken::default(), &mut |_| Err(limit("job exhausted"))).is_err()); + let pass = film + .complete_pass(&CancelToken::default(), &mut |n| { + charged += n; + Ok(()) + }) + .unwrap(); + assert_eq!(charged, 4); + assert_eq!(pass.samples_per_pixel(), 1); +} + +#[test] +fn sample_counts_reach_4096_and_the_declared_cap_without_truncation() { + for samples in [4096, MAX_SAMPLES] { + let mut film = film(1, 1, samples); + let cancel = CancelToken::default(); + let mut charged = 0u64; + for _ in 0..samples { + film.add_range(0, &[[7.0, 3.0, 1.0]], &cancel, &mut |n| { + charged += n; + Ok(()) + }) + .unwrap(); + } + assert_eq!(charged, u64::from(samples) * 2); + let expected = PixelStatistics { mean: [7.0, 3.0, 1.0], variance: [0.0; 3], count: samples }; + assert_eq!(film.pixel_statistics(0).unwrap(), expected); + assert_eq!(film.complete_pass(&cancel, &mut |_| Ok(())).unwrap().samples_per_pixel(), samples); + assert_eq!(film.add_range(0, &[[1.0; 3]], &cancel, &mut |_| Ok(())).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(film.pixel_statistics(0).unwrap(), expected); + } +} + +#[test] +fn construction_stops_on_exhausted_caller_work() { + let bytes = FilmAccumulator::required_bytes(4, 1, 1).unwrap(); + let mut charged = 0u64; + let result = FilmAccumulator::new(4, 1, 1, bytes, &CancelToken::default(), &mut |n| { + charged += n; + if charged > 2 { Err(limit("existing job budget exhausted")) } else { Ok(()) } + }); + assert!(matches!(result, Err(JobError { code: ErrorCode::LimitExceeded, .. }))); + assert_eq!(charged, 3); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn primary_film_large_profile_keeps_every_sample_and_cancels_before_mutation() { + use crate::film::primary::PrimaryFilm; + use crate::job::{CancelToken, CpuBudget, CpuProgressiveOptions}; + let options = CpuProgressiveOptions { samples_per_pixel: 512, seed: 7 }; + assert!(PrimaryFilm::required_bytes(1, 1, options, CpuBudget::Compact).is_err()); + let bytes = PrimaryFilm::required_bytes(1, 1, options, CpuBudget::Studio).unwrap(); + let cancel = CancelToken::default(); + let mut film = PrimaryFilm::new(1, 1, options, bytes, &cancel, CpuBudget::Studio).unwrap(); + film.initialize_one(&cancel, &mut || Ok(())).unwrap(); + for ordinal in 0..512 { + film.add(0, ordinal, [1e12, 2.0, 0.0], true, &cancel, &mut || Ok(())).unwrap(); + } + assert_eq!(film.pixel(0).unwrap(), ([1e12, 2.0, 0.0], 512, 512)); + cancel.cancel(); + assert!(film.add(0, 512, [0.0; 3], true, &cancel, &mut || Ok(())).is_err()); + assert_eq!(film.samples(), 512); +} + +#[cfg(feature = "raytrace-cpu")] +mod partial_camera_passes { + use super::primary::{PartialFrontier, PartialPixel, PrimaryFilm}; + use super::*; + use crate::job::{CpuBudget, CpuProgressiveOptions}; + + fn uninitialized(samples: u32, seed: u32) -> PrimaryFilm { + let options = CpuProgressiveOptions { samples_per_pixel: samples, seed }; + let bytes = PrimaryFilm::required_bytes(4, 1, options, CpuBudget::Compact).unwrap(); + PrimaryFilm::new(4, 1, options, bytes, &CancelToken::default(), CpuBudget::Compact).unwrap() + } + + fn ready(samples: u32, seed: u32) -> PrimaryFilm { + let mut film = uninitialized(samples, seed); + while !film.ready() { + film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); + } + film + } + + fn observe(film: &PrimaryFilm) -> (PartialFrontier, Vec) { + (film.partial_frontier().unwrap(), (0..4).map(|index| film.partial_pixel(index).unwrap()).collect()) + } + + fn sampled(mean: [f64; 3], covered: u32, count: u32) -> PartialPixel { + PartialPixel::Sampled { linear_premultiplied: mean, covered, count } + } + + #[test] + fn partial_frontier_distinguishes_first_prefix_miss_and_unobserved_pixels() { + let mut film = ready(2, 7); + assert_eq!(observe(&film), (PartialFrontier { completed_passes: 0, updated_prefix: 0, pixels: 4 }, vec![PartialPixel::Unknown; 4],)); + film.add(0, 0, [2.0, 0.0, 0.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); + film.add(1, 0, [0.0; 3], false, &CancelToken::default(), &mut || Ok(())).unwrap(); + assert_eq!( + observe(&film), + ( + PartialFrontier { completed_passes: 0, updated_prefix: 2, pixels: 4 }, + vec![sampled([2.0, 0.0, 0.0], 1, 1), sampled([0.0; 3], 0, 1), PartialPixel::Unknown, PartialPixel::Unknown], + ) + ); + assert!(film.pixel(0).is_err(), "legacy whole-pass reader still rejects the partial pass"); + assert!(film.pixel(1).is_err(), "a sampled miss does not imply a uniform pass"); + } + + #[test] + fn partial_counts_and_means_follow_real_interior_and_full_pass_frontiers() { + let mut film = ready(2, 0); + let cancel = CancelToken::default(); + for (index, value, covered) in [(0, [2.0, 0.0, 0.0], true), (1, [0.0; 3], false), (2, [0.0, 0.0, 4.0], true), (3, [0.0; 3], false)] { + film.add(index, 0, value, covered, &cancel, &mut || Ok(())).unwrap(); + } + assert_eq!(film.partial_frontier().unwrap(), PartialFrontier { completed_passes: 1, updated_prefix: 0, pixels: 4 }); + assert_eq!(film.partial_pixel(3).unwrap(), sampled([0.0; 3], 0, 1)); + assert_eq!(film.pixel(0).unwrap(), ([2.0, 0.0, 0.0], 1, 1)); + + film.add(0, 1, [4.0, 0.0, 0.0], true, &cancel, &mut || Ok(())).unwrap(); + film.add(1, 1, [0.0, 2.0, 0.0], true, &cancel, &mut || Ok(())).unwrap(); + assert_eq!( + observe(&film), + ( + PartialFrontier { completed_passes: 1, updated_prefix: 2, pixels: 4 }, + vec![sampled([3.0, 0.0, 0.0], 2, 2), sampled([0.0, 1.0, 0.0], 1, 2), sampled([0.0, 0.0, 4.0], 1, 1), sampled([0.0; 3], 0, 1)], + ) + ); + assert!(film.pixel(0).is_err()); + + film.add(2, 1, [0.0, 0.0, 8.0], true, &cancel, &mut || Ok(())).unwrap(); + assert_eq!(film.partial_frontier().unwrap().updated_prefix, 3); + film.add(3, 1, [0.0; 3], false, &cancel, &mut || Ok(())).unwrap(); + assert_eq!( + observe(&film), + ( + PartialFrontier { completed_passes: 2, updated_prefix: 0, pixels: 4 }, + vec![sampled([3.0, 0.0, 0.0], 2, 2), sampled([0.0, 1.0, 0.0], 1, 2), sampled([0.0, 0.0, 6.0], 2, 2), sampled([0.0; 3], 0, 2)], + ) + ); + assert_eq!(film.pixel(2).unwrap(), ([0.0, 0.0, 6.0], 2, 2)); + assert!(film.add(0, 2, [0.0; 3], false, &cancel, &mut || Ok(())).is_err()); + assert_eq!(film.partial_frontier().unwrap().completed_passes, 2); + } + + #[test] + fn partial_access_refuses_uninitialized_storage_and_invalid_indices() { + let mut film = uninitialized(2, 7); + assert!(film.partial_frontier().is_err()); + assert!(film.partial_pixel(0).is_err()); + film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); + assert!(film.partial_frontier().is_err(), "allocated prefix is not an initialized film"); + assert!(film.partial_pixel(0).is_err()); + while !film.ready() { + film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); + } + assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Unknown); + assert!(film.partial_pixel(4).is_err()); + assert!(film.partial_pixel(usize::MAX).is_err()); + assert_eq!(film.partial_frontier().unwrap().updated_prefix, 0); + } + + #[test] + fn failed_or_cancelled_updates_preserve_the_observed_partial_frontier() { + let mut film = ready(2, 7); + film.add(0, 0, [2.0, 0.0, 0.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); + let before = observe(&film); + for (index, ordinal, value, covered) in + [(0, 0, [0.0; 3], false), (2, 0, [0.0; 3], false), (1, 1, [0.0; 3], false), (1, 0, [f64::NAN; 3], true), (1, 0, [1.0; 3], false)] + { + assert!(film.add(index, ordinal, value, covered, &CancelToken::default(), &mut || Ok(())).is_err()); + assert_eq!(observe(&film), before); + } + assert_eq!( + film.add(1, 0, [4.0; 3], true, &CancelToken::default(), &mut || Err(limit("existing job exhausted"))).unwrap_err().code, + ErrorCode::LimitExceeded + ); + assert_eq!(observe(&film), before); + let cancel = CancelToken::default(); + let observer = cancel.clone(); + assert_eq!( + film.add(1, 0, [4.0; 3], true, &cancel, &mut || { + observer.cancel(); + Ok(()) + }) + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + assert_eq!(observe(&film), before); + film.add(1, 0, [4.0; 3], true, &CancelToken::default(), &mut || Ok(())).unwrap(); + assert_eq!(film.partial_frontier().unwrap().updated_prefix, 2, "failed updates did not consume the next ordinal"); + } + + #[test] + fn reading_partial_pixels_preserves_default_sum_order_bits_and_charge_count() { + for seed in [0, 7, u32::MAX] { + let mut observed = ready(4, seed); + let mut control = ready(4, seed); + let mut observed_charges = 0; + let mut control_charges = 0; + for ordinal in 0..4 { + let red = if ordinal == 0 { 1e12 } else { 2.0_f64.powi(-15) }; + for index in 0..4 { + let value = [red, red * 0.5, 2.0]; + observed + .add(index, ordinal, value, true, &CancelToken::default(), &mut || { + observed_charges += 1; + Ok(()) + }) + .unwrap(); + // These uncharged O(1) reads model only the accessor. A future + // snapshot caller still owes its own per-read/copy work charge. + let _ = observe(&observed); + control + .add(index, ordinal, value, true, &CancelToken::default(), &mut || { + control_charges += 1; + Ok(()) + }) + .unwrap(); + } + } + assert_eq!((observed_charges, control_charges), (16, 16)); + assert_eq!(observed.samples(), 4); + for index in 0..4 { + let (actual, covered, count) = observed.pixel(index).unwrap(); + let (expected, expected_covered, expected_count) = control.pixel(index).unwrap(); + assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits)); + assert_eq!( + actual.map(f64::to_bits), + [2.5e11_f64, 1.25e11_f64, 2.0_f64].map(f64::to_bits), + "ordered additions keep each sub-half-ULP contribution rounded at its original addition" + ); + assert_eq!((covered, count), (expected_covered, expected_count)); + assert_eq!(observed.partial_pixel(index).unwrap(), sampled(actual, 4, 4)); + } + } + } +} + +#[cfg(feature = "raytrace-cpu")] +mod workstation_primary_counts { + use super::primary::{PartialPixel, PrimaryFilm}; + use super::*; + use crate::job::{CpuBudget, CpuProgressiveOptions}; + + fn primary(target: u32) -> PrimaryFilm { + let options = CpuProgressiveOptions { samples_per_pixel: target, seed: 7 }; + let bytes = PrimaryFilm::required_bytes(1, 1, options, CpuBudget::Workstation).unwrap(); + let mut film = PrimaryFilm::new(1, 1, options, bytes, &CancelToken::default(), CpuBudget::Workstation).unwrap(); + film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); + film + } + + #[test] + fn workstation_cap_is_explicit_and_other_profiles_and_defaults_stay_fixed() { + assert_eq!(crate::job::MAX_CPU_SAMPLES_PER_PIXEL, 1_048_576); + assert_eq!(CpuBudget::Workstation.limits().max_samples_per_pixel, 1_048_576); + assert_eq!(CpuBudget::Studio.limits().max_samples_per_pixel, 1024); + assert_eq!(CpuBudget::Compact.limits().max_samples_per_pixel, 64); + assert_eq!(CpuBudget::default(), CpuBudget::Compact); + assert_eq!(CpuProgressiveOptions::default(), CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }); + for samples_per_pixel in [0, 1_048_577, u32::MAX] { + assert!(CpuBudget::Workstation.validate_samples(samples_per_pixel).is_err()); + } + for (budget, cap) in [(CpuBudget::Compact, 64), (CpuBudget::Studio, 1024), (CpuBudget::Workstation, 1_048_576)] { + budget.validate_samples(cap).unwrap(); + assert!(budget.validate_samples(cap + 1).is_err()); + } + let large = CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 }; + assert!(large.validate().is_err(), "the no-profile compatibility check must remain Compact"); + assert!(large.validate_image(1, 1).is_err()); + } + + #[test] + fn high_sample_intent_keeps_camera_resolution_work_and_memory_admission() { + let limits = CpuBudget::Workstation.limits(); + assert_eq!(limits.max_camera_samples, 68_719_476_736); + assert_eq!(limits.max_dimension, 16_384); + assert_eq!(limits.max_pixels, 67_108_864); + assert_eq!(limits.max_progressive_pixels, 67_108_864); + assert_eq!(limits.max_job_bytes, 12 * 1024 * 1024 * 1024); + assert_eq!(limits.max_work_units, 16_000_000_000_000); + assert_eq!(crate::job::NATIVE_CPU_POOL_BYTES, 16 * 1024 * 1024 * 1024); + let million = Some(CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 }); + CpuBudget::Workstation.validate_image(256, 256, million).unwrap(); + assert!(CpuBudget::Workstation.validate_image(257, 256, million).is_err()); + assert!(CpuBudget::Workstation.validate_image(u32::MAX, u32::MAX, million).is_err()); + // Pure admission boundaries, no large image or film allocation. + for (width, height, samples) in [(1920, 1080, 33_140), (3840, 2160, 8_285), (7680, 4320, 2_071), (8192, 8192, 1024)] { + CpuBudget::Workstation.validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 7 })).unwrap(); + assert!( + CpuBudget::Workstation + .validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: samples + 1, seed: 7 })) + .is_err() + ); + } + for budget in [CpuBudget::Studio, CpuBudget::Workstation] { + assert_eq!(budget.validate_execution().is_err(), cfg!(target_arch = "wasm32") || usize::BITS < 64); + } + CpuBudget::Compact.validate_execution().unwrap(); + } + + #[test] + fn one_pixel_million_sample_intent_does_not_allocate_a_sample_history() { + let low = CpuProgressiveOptions { samples_per_pixel: 1, seed: 7 }; + let high = CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 }; + let bytes = PrimaryFilm::required_bytes(1, 1, high, CpuBudget::Workstation).unwrap(); + assert_eq!(PrimaryFilm::required_bytes(1, 1, low, CpuBudget::Workstation).unwrap(), bytes); + assert!(PrimaryFilm::new(1, 1, high, bytes - 1, &CancelToken::default(), CpuBudget::Workstation).is_err()); + for samples_per_pixel in [0, 1_048_577, u32::MAX] { + assert!(PrimaryFilm::required_bytes(1, 1, CpuProgressiveOptions { samples_per_pixel, seed: 7 }, CpuBudget::Workstation).is_err()); + } + assert!(PrimaryFilm::required_bytes(257, 256, high, CpuBudget::Workstation).is_err()); + } + + #[test] + fn primary_resolve_keeps_exact_u32_counts_at_65535_65536_and_the_workstation_cap() { + // Real film commits, one pixel only: no ray tracing, PNG, host or million-frame render. + let mut film = primary(1_048_576); + let cancel = CancelToken::default(); + let mut charged = 0u64; + for ordinal in 0..1_048_576 { + film.add(0, ordinal, [1.0, 2.0, 4.0], true, &cancel, &mut || { + charged += 1; + Ok(()) + }) + .unwrap(); + let count = ordinal + 1; + if [4096, 65_535, 65_536, 1_048_576].contains(&count) { + let (mean, covered, samples): ([f64; 3], u32, u32) = film.pixel(0).unwrap(); + assert_eq!(mean, [1.0, 2.0, 4.0]); + assert_eq!((covered, samples), (count, count)); + assert_eq!(film.samples(), count); + assert_eq!(charged, u64::from(count)); + assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Sampled { linear_premultiplied: mean, covered: count, count }); + } + } + let before = film.pixel(0).unwrap(); + let frontier = film.partial_frontier().unwrap(); + for ordinal in [1_048_576, 1_048_577, u32::MAX] { + assert!(film.add(0, ordinal, [0.0; 3], false, &cancel, &mut || panic!("rejected ordinal charged work")).is_err()); + assert_eq!(film.pixel(0).unwrap(), before); + assert_eq!(film.partial_frontier().unwrap(), frontier); + } + } + + #[test] + fn high_counts_keep_misses_in_the_mean_and_the_real_coverage_denominator() { + let mut film = primary(65_537); + let cancel = CancelToken::default(); + for ordinal in 0..65_537 { + let covered = ordinal % 2 == 0; + film.add(0, ordinal, if covered { [2.0, 4.0, 8.0] } else { [0.0; 3] }, covered, &cancel, &mut || Ok(())).unwrap(); + let count = ordinal + 1; + if [65_535, 65_536, 65_537].contains(&count) { + let hits = count.div_ceil(2); + let expected = [2.0, 4.0, 8.0].map(|value| value * f64::from(hits) / f64::from(count)); + assert_eq!(film.pixel(0).unwrap(), (expected, hits, count)); + assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Sampled { linear_premultiplied: expected, covered: hits, count }); + } + } + } + + #[test] + fn high_count_cancellation_and_work_failure_preserve_the_exact_committed_film() { + let mut film = primary(65_537); + for ordinal in 0..65_536 { + film.add(0, ordinal, [1.0, 2.0, 4.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); + } + let before = film.pixel(0).unwrap(); + let frontier = film.partial_frontier().unwrap(); + let cancelled = CancelToken::default(); + cancelled.cancel(); + assert_eq!( + film.add(0, 65_536, [3.0; 3], true, &cancelled, &mut || panic!("cancelled input charged work")).unwrap_err().code, + ErrorCode::Cancelled + ); + let cancel = CancelToken::default(); + let observer = cancel.clone(); + let mut charged = 0; + assert_eq!( + film.add(0, 65_536, [3.0; 3], true, &cancel, &mut || { + charged += 1; + observer.cancel(); + Ok(()) + }) + .unwrap_err() + .code, + ErrorCode::Cancelled + ); + assert_eq!(charged, 1); + assert!(film.add(0, 65_536, [3.0; 3], true, &CancelToken::default(), &mut || Err(limit("same cumulative job exhausted"))).is_err()); + assert_eq!(film.pixel(0).unwrap(), before); + assert_eq!(film.partial_frontier().unwrap(), frontier); + film.add(0, 65_536, [1.0, 2.0, 4.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); + assert_eq!(film.pixel(0).unwrap(), ([1.0, 2.0, 4.0], 65_537, 65_537)); + } + + #[test] + fn changing_only_the_target_keeps_old_4096_prefix_bits_and_ordinals() { + let mut old_target = primary(4096); + let mut high_target = primary(1_048_576); + let cancel = CancelToken::default(); + for ordinal in 0..4096 { + let covered = ordinal % 3 != 0; + let sample = if covered { [0.25, 2.0, 8.0] } else { [0.0; 3] }; + old_target.add(0, ordinal, sample, covered, &cancel, &mut || Ok(())).unwrap(); + high_target.add(0, ordinal, sample, covered, &cancel, &mut || Ok(())).unwrap(); + let (old_mean, old_covered, old_count) = old_target.pixel(0).unwrap(); + let (high_mean, high_covered, high_count) = high_target.pixel(0).unwrap(); + assert_eq!(old_mean.map(f64::to_bits), high_mean.map(f64::to_bits)); + assert_eq!((old_covered, old_count), (high_covered, high_count)); + assert_eq!(old_target.partial_frontier().unwrap(), high_target.partial_frontier().unwrap()); + } + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/cpu_budget.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/cpu_budget.rs new file mode 100644 index 000000000..b3320ab83 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/cpu_budget.rs @@ -0,0 +1,176 @@ +//! Explicit CPU resource envelopes. Larger profiles are opt-in saved intent, not +//! automatic quality changes or promises about available RAM, speed or convergence. +use serde::{Deserialize, Serialize}; + +use super::{CpuProgressiveOptions, ErrorCode, JobError, Result}; +use crate::RenderLimits; + +const MIB: u64 = 1024 * 1024; +const GIB: u64 = 1024 * MIB; +/// Native CPU reservations, including retained frames, share this finite ceiling. +pub const NATIVE_CPU_POOL_BYTES: u64 = 16 * GIB; +/// Hard implementation ceilings; individual requests retain their selected envelope. +pub const MAX_CPU_WORK: u64 = 16_000_000_000_000; +pub const MAX_CPU_TRIANGLES: usize = 8_000_000; +pub const MAX_CPU_BODIES: usize = 262_144; +/// Maximum admitted primary-film samples, shared with the display resolver. +pub const MAX_CPU_SAMPLES_PER_PIXEL: u32 = 1_048_576; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CpuBudget { + #[default] + Compact, + Studio, + Workstation, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct CpuBudgetLimits { + pub max_dimension: u64, + pub max_pixels: u64, + pub max_progressive_pixels: u64, + pub max_samples_per_pixel: u32, + pub max_camera_samples: u64, + pub max_triangles: u64, + pub max_bodies: usize, + pub max_geometry_bytes: u64, + pub max_job_bytes: u64, + pub max_work_units: u64, +} + +impl CpuBudget { + pub const ALL: [Self; 3] = [Self::Compact, Self::Studio, Self::Workstation]; + + pub fn is_compact(&self) -> bool { + *self == Self::Compact + } + + pub const fn limits(self) -> CpuBudgetLimits { + match self { + Self::Compact => CpuBudgetLimits { + max_dimension: 4096, + max_pixels: 4_194_304, + max_progressive_pixels: 1_048_576, + max_samples_per_pixel: 64, + max_camera_samples: 16_777_216, + max_triangles: super::image::MAX_TRIANGLES, + max_bodies: 16_384, + max_geometry_bytes: super::image::MAX_GEOMETRY_BYTES, + max_job_bytes: super::image::MAX_JOB_BYTES, + max_work_units: 1_000_000_000, + }, + Self::Studio => CpuBudgetLimits { + max_dimension: 8192, + max_pixels: 16_777_216, + max_progressive_pixels: 16_777_216, + max_samples_per_pixel: 1024, + max_camera_samples: 4_294_967_296, + max_triangles: 2_000_000, + max_bodies: 65_536, + max_geometry_bytes: GIB, + max_job_bytes: 3 * GIB, + max_work_units: 1_000_000_000_000, + }, + Self::Workstation => CpuBudgetLimits { + max_dimension: 16_384, + max_pixels: 67_108_864, + max_progressive_pixels: 67_108_864, + max_samples_per_pixel: MAX_CPU_SAMPLES_PER_PIXEL, + max_camera_samples: 68_719_476_736, + max_triangles: MAX_CPU_TRIANGLES as u64, + max_bodies: MAX_CPU_BODIES, + max_geometry_bytes: 4 * GIB, + max_job_bytes: 12 * GIB, + max_work_units: MAX_CPU_WORK, + }, + } + } + + pub fn image_limits(self, progressive: bool) -> RenderLimits { + let limits = self.limits(); + RenderLimits { + max_dimension: limits.max_dimension, + max_pixels: if progressive { limits.max_progressive_pixels } else { limits.max_pixels }, + max_scratch_bytes: limits.max_job_bytes, + } + } + + pub fn validate_samples(self, samples: u32) -> Result<()> { + let maximum = self.limits().max_samples_per_pixel; + if samples == 0 || samples > maximum { + return Err(JobError::new(ErrorCode::InvalidRequest, format!("CPU {self:?} samples_per_pixel must be 1..{maximum}"))); + } + Ok(()) + } + + /// No geometry reads or allocations. This also validates offline saved intent. + pub fn validate_image(self, width: u32, height: u32, progressive: Option) -> Result<()> { + let (w, h) = (u64::from(width), u64::from(height)); + let limits = self.image_limits(progressive.is_some()); + let pixels = w.checked_mul(h).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "CPU pixel count overflow"))?; + if w == 0 || h == 0 || w > limits.max_dimension || h > limits.max_dimension || pixels > limits.max_pixels { + return Err(JobError::new( + ErrorCode::LimitExceeded, + format!( + "CPU {self:?} accepts dimensions 1..{} and at most {} pixels; select a larger resource profile explicitly", + limits.max_dimension, limits.max_pixels + ), + )); + } + if let Some(options) = progressive { + self.validate_samples(options.samples_per_pixel)?; + if pixels.checked_mul(u64::from(options.samples_per_pixel)).is_none_or(|n| n > self.limits().max_camera_samples) { + return Err(JobError::new( + ErrorCode::LimitExceeded, + format!("CPU {self:?} exceeds its {} camera-sample admission", self.limits().max_camera_samples), + )); + } + } + Ok(()) + } + + /// A file may preserve large intent on every platform; only execution needs + /// the native 64-bit address space. No implicit downgrade to Compact occurs. + pub fn validate_execution(self) -> Result<()> { + if self != Self::Compact && (cfg!(target_arch = "wasm32") || usize::BITS < 64) { + return Err(JobError::new(ErrorCode::HostUnavailable, "large CPU profiles require a native 64-bit host")); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn large_intent_is_explicit_and_old_intent_remains_compact() { + assert_eq!(CpuBudget::default(), CpuBudget::Compact); + let p = Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 9 }); + assert!(CpuBudget::Compact.validate_image(3840, 2160, p).is_err()); + assert!(CpuBudget::Studio.validate_image(3840, 2160, p).is_ok()); + assert!(CpuBudget::Studio.validate_image(7680, 4320, p).is_err()); + assert!(CpuBudget::Workstation.validate_image(7680, 4320, p).is_ok()); + assert_eq!(serde_json::from_str::("\"workstation\"").unwrap(), CpuBudget::Workstation); + assert!(serde_json::from_str::("\"unlimited\"").is_err()); + } + + #[test] + fn all_envelopes_have_checked_finite_bounds_and_no_automatic_resize() { + for budget in CpuBudget::ALL { + let limits = budget.limits(); + assert!(limits.max_geometry_bytes < limits.max_job_bytes); + assert!(limits.max_job_bytes < NATIVE_CPU_POOL_BYTES); + assert!(limits.max_work_units <= MAX_CPU_WORK); + assert!(budget.validate_image(0, 1, None).is_err()); + assert!(budget.validate_image(u32::MAX, u32::MAX, None).is_err()); + assert!(budget.validate_samples(0).is_err()); + assert!(budget.validate_samples(limits.max_samples_per_pixel + 1).is_err()); + assert!(budget.validate_samples(limits.max_samples_per_pixel).is_ok()); + } + let p = Some(CpuProgressiveOptions { samples_per_pixel: 4096, seed: 0 }); + assert!(CpuBudget::Workstation.validate_image(8192, 8192, p).is_err()); + assert!(CpuBudget::Workstation.validate_image(3840, 2160, p).is_ok()); + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host.rs new file mode 100644 index 000000000..8e2c64e18 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host.rs @@ -0,0 +1,2923 @@ +//! 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; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Condvar; +use std::sync::{ + Arc, Mutex, Weak, + atomic::{AtomicBool, AtomicU64, Ordering}, +}; + +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use super::{ + Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageExecutor, ImageRequest, ImageTask, ImageWork, Integrator, + JobError, JobId, JobOptions, Phase, Progress, Result, TaskPoll, admit, +}; +use crate::{ + Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout, +}; + +const MEMORY_LIMIT: u64 = 512 * 1024 * 1024; +const QUEUE_LIMIT: usize = 2; + +#[cfg(test)] +struct CpuExecutor; +#[cfg(test)] +impl ImageExecutor for CpuExecutor { + fn descriptor(&self) -> Result { + 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 { + 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> { + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } +} + +// Completion notification precedes destruction of the worker's temporary handle. +// Lease tests join their owned, idle worker before checking exact retained bytes. +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +impl ImageHost { + pub(super) fn join_worker_for_test(&mut self) -> Result<()> { + self.0.shared.stop.store(true, Ordering::Release); + self.0.shared.wake.notify_all(); + let inner = Arc::get_mut(&mut self.0).ok_or_else(|| JobError::new(ErrorCode::Internal, "test must own its host"))?; + if let Some(worker) = inner._worker.take() { + worker.join().map_err(|_| JobError::new(ErrorCode::Internal, "test worker panicked"))?; + } + Ok(()) + } +} + +#[cfg(test)] +#[path = "host_regrade_tests.rs"] +mod regrade_tests; +#[cfg(test)] +#[path = "host_tests.rs"] +mod tests; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HostKind { + NativeWorker, + Cooperative, +} + +struct Budget { + used: AtomicU64, + limit: u64, +} +pub(crate) struct Reservation { + budget: Arc, + bytes: u64, +} + +impl Budget { + fn reserve(self: &Arc, bytes: u64) -> Result { + let mut used = self.used.load(Ordering::Acquire); + loop { + let next = used.checked_add(bytes).filter(|n| *n <= self.limit).ok_or_else(|| { + JobError::new(ErrorCode::LimitExceeded, format!("image host admission pool is full ({} MiB)", self.limit / (1024 * 1024))) + })?; + match self.used.compare_exchange_weak(used, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => break, + Err(current) => used = current, + } + } + Ok(Reservation { budget: self.clone(), bytes }) + } +} +impl Reservation { + /// Merge unique portions of one admission without a second pool debit. + fn merge_from(&mut self, donor: &mut Self) -> Result<()> { + if !Arc::ptr_eq(&self.budget, &donor.budget) { + return Err(JobError::new(ErrorCode::WrongOwner, "cannot merge different image admission pools")); + } + let bytes = self + .bytes + .checked_add(donor.bytes) + .filter(|v| *v <= self.budget.limit) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "image reservation merge overflow"))?; + self.bytes = bytes; + donor.bytes = 0; + Ok(()) + } + /// Transfer an already admitted portion without changing the pool's total. + /// CPU progressive admission includes every possible checkpoint up front. + fn split(&mut self, bytes: u64) -> Result { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "preview exceeds its prepaid reservation")); + } + self.bytes -= bytes; + Ok(Self { budget: self.budget.clone(), bytes }) + } + + pub(crate) fn shrink(&mut self, bytes: u64) -> Result<()> { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "completed PNG exceeds its reservation")); + } + self.budget.used.fetch_sub(self.bytes - bytes, Ordering::AcqRel); + self.bytes = bytes; + Ok(()) + } +} +impl Drop for Reservation { + fn drop(&mut self) { + self.budget.used.fetch_sub(self.bytes, Ordering::AcqRel); + } +} + +/// Retained runtime input capacities survive work/PNG eviction through status handles. +fn retained_request_bytes(request: &ImageRequest) -> Result { + let existing = request.raytrace.as_ref().map_or(Ok(0), |options| options.retained_bytes())?; + existing + .checked_add(request.raster_lights_retained_bytes()?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request size overflow")) +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod light_union_lease_tests { + use super::super::{DirectionalLightOptions, PunctualLightOptions, RaytraceOptions, led_strip::LedStripOptions}; + use super::*; + fn request() -> Result { + let mut options = RaytraceOptions { + primary_samples: 16, + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]), + punctual_lights: Some(vec![ + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None + }; + 8 + ]), + ..Default::default() + }; + let strip = LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0; 3], + intensity: 2.0, + }; + for _ in 0..4 { + strip.append_to(&mut options, 64)?; + } + Ok(ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(options), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }) + } + fn scene() -> ProductScene { + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY } + } + #[test] + fn normalized_union_uses_one_pool_and_keeps_record_lease_after_frame_eviction() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = request().unwrap(); + let bytes = retained_request_bytes(&request).unwrap(); + let capacities = request + .raytrace + .as_ref() + .map(|o| { + (o.lights.as_ref().unwrap().capacity(), o.punctual_lights.as_ref().unwrap().capacity(), o.area_lights.as_ref().unwrap().capacity()) + }) + .unwrap(); + let job = host.submit(JobId { session: 1724, serial: 1, generation: 1 }, 1, scene(), request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Synchronize this test's completed worker before asserting final Arc release; + // publication wakes waiters just before Running drops its temporary handle. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let retained = job.0.request.raytrace.as_ref().unwrap(); + assert_eq!( + capacities, + ( + retained.lights.as_ref().unwrap().capacity(), + retained.punctual_lights.as_ref().unwrap().capacity(), + retained.area_lights.as_ref().unwrap().capacity() + ) + ); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert!(host.admitted_bytes() > bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn failed_union_metadata_reservation_releases_work_and_does_not_enqueue() { + let host = CpuHost::for_platform().unwrap(); + let request = request().unwrap(); + let work = admit(&scene(), &request).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let result = host.submit(JobId { session: 1724, serial: 2, generation: 1 }, 1, scene(), request); + assert_eq!(result.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } + + fn raster_local_pair() -> (ImageRequest, ProductScene) { + let mut input = request().unwrap(); + input.integrator = Integrator::Raster; + input.raytrace = None; + let mut points = Vec::with_capacity(8); + points.push(PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }); + let mut areas = Vec::with_capacity(4); + areas.push(super::super::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }); + input.raster_punctual_lights = Some(points); + input.raster_area_lights = Some(areas); + let mesh = solidcraft_geom::Mesh { + positions: vec![ + solidcraft_geom::Vec3::new(-2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(0.0, 2.0, 0.0), + ], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + name: "Raster local lease fixture".into(), + mesh: Arc::new(mesh), + color: [160; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + bounds, + }; + (input, scene) + } + + #[test] + fn raster_local_record_keeps_original_capacity_lease_after_real_completion_and_frame_drop() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let (input, scene) = raster_local_pair(); + let capacities = (input.raster_punctual_lights.as_ref().unwrap().capacity(), input.raster_area_lights.as_ref().unwrap().capacity()); + let bytes = (capacities.0 * std::mem::size_of::() + + capacities.1 * std::mem::size_of::()) as u64; + assert_eq!(retained_request_bytes(&input).unwrap(), bytes); + let job = host.submit(JobId { session: 1725, serial: 1, generation: 1 }, 1, scene, input).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + assert_eq!(job.0.request.raster_punctual_lights.as_ref().unwrap().capacity(), capacities.0); + assert_eq!(job.0.request.raster_area_lights.as_ref().unwrap().capacity(), capacities.1); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let copied = job.status().unwrap().request; + assert_eq!(copied.raster_punctual_lights, job.0.request.raster_punctual_lights); + assert_eq!(copied.raster_area_lights, job.0.request.raster_area_lights); + drop(copied); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + + #[test] + fn raster_local_metadata_reservation_failure_releases_work_without_enqueuing() { + let host = CpuHost::for_platform().unwrap(); + let (input, scene) = raster_local_pair(); + let work = host.admit(&scene, &input, JobOptions::default()).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let failed = host.submit(JobId { session: 1725, serial: 2, generation: 1 }, 1, scene, input); + assert_eq!(failed.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } +} + +fn admit_request_sum(work_bytes: u64, request_bytes: u64) -> Result<()> { + if work_bytes.checked_add(request_bytes).is_none_or(|sum| sum > super::image::MAX_JOB_BYTES) { + return Err(JobError::new(ErrorCode::LimitExceeded, "render work and retained request exceed 384 MiB per-job admission")); + } + Ok(()) +} + +/// Borrow encoded bytes through the frame, so retaining the data also retains its admission lease. +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearColourEncoding { + SceneLinearSrgbD65, +} +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearAlphaConvention { + CoveragePremultiplied, +} +#[derive(Clone, Debug, Serialize)] +pub struct LinearMasterInfo { + pub encoding: LinearColourEncoding, + pub alpha: LinearAlphaConvention, + pub bytes: u64, + pub sha256: String, +} +struct RetainedPresentation { + info: super::presentation::MasterPresentation, + _reservation: Reservation, +} + +pub struct RenderFrame { + // Derivatives point directly at the original, never form a retention chain. + source_master: Option>, + presentation: Option>, + pub info: FrameInfo, + png: Vec, + exr: Option<(Vec, LinearMasterInfo)>, + _reservation: Reservation, +} +impl RenderFrame { + pub fn master_source(self: &Arc) -> Result> { + if let Some(source) = &self.source_master { + return Ok(source.clone()); + } + if self.exr.is_some() { + return Ok(self.clone()); + } + Err(JobError::new(ErrorCode::InvalidRequest, "completed image has no retained raw linear master")) + } + pub fn presentation(&self) -> Option<&super::presentation::MasterPresentation> { + self.presentation.as_deref().map(|retained| &retained.info) + } + pub fn linear_exr(&self) -> Option<&[u8]> { + self.exr.as_ref().map(|(bytes, _)| bytes.as_slice()).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_exr())) + } + pub fn linear_master_info(&self) -> Option<&LinearMasterInfo> { + self.exr.as_ref().map(|(_, info)| info).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_master_info())) + } + pub fn png(&self) -> &[u8] { + &self.png + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct PreviewInfo { + pub frame_sequence: u32, + pub samples_per_pixel: u32, + pub frame: FrameInfo, +} + +/// Immutable checkpoint bytes retain their own transferred host lease. Keeping +/// an older preview alive never makes its memory disappear from pool accounting. +pub struct RenderPreview { + pub info: PreviewInfo, + png: Vec, + _reservation: CheckpointLease, +} + +/// Two reusable, immutable complete-pass slots. No consumer acknowledgement or +/// queue: externally pinned slots are diagnosed and never stall final work. +struct CheckpointCredits { + state: Mutex, + slot_bytes: u64, + capacity: u64, +} +struct CheckpointCreditState { + free: Reservation, + closed: bool, +} +impl CheckpointCredits { + fn new(reservation: &mut Reservation, slot_bytes: u64, slots: u32) -> Result> { + if !(1..=2).contains(&slots) || slot_bytes == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "checkpoint credits require one or two finite slots")); + } + let capacity = slot_bytes + .checked_mul(u64::from(slots)) + .and_then(|n| n.checked_add(1024)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit capacity overflow"))?; + let free = reservation.split(capacity)?; + Ok(Arc::new(Self { state: Mutex::new(CheckpointCreditState { free, closed: false }), slot_bytes, capacity })) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "checkpoint credit lock poisoned"))?; + if state.closed { + return Err(JobError::new(ErrorCode::Cancelled, "checkpoint credits are closed")); + } + let needed = self.slot_bytes.checked_add(1024).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit bound overflow"))?; + if state.free.bytes < needed { + return Ok(None); + } + let reservation = state.free.split(self.slot_bytes)?; + Ok(Some(CheckpointLease { reservation, credits: self.clone() })) + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + let _ = state.free.shrink(0); + } +} +struct CheckpointLease { + reservation: Reservation, + credits: Arc, +} +impl std::ops::Deref for CheckpointLease { + type Target = Reservation; + fn deref(&self) -> &Reservation { + &self.reservation + } +} +impl Drop for CheckpointLease { + fn drop(&mut self) { + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if !state.closed { + if state.free.bytes.checked_add(self.reservation.bytes).is_some_and(|n| n <= self.credits.capacity) + && state.free.merge_from(&mut self.reservation).is_ok() + { + return; + } + state.closed = true; + let _ = state.free.shrink(0); + } + } +} + +impl RenderPreview { + pub fn png(&self) -> &[u8] { + &self.png + } +} + +/// Metadata for either runtime environment contract; wire objects retain their original shape. +#[derive(Clone, Debug, Serialize)] +#[serde(untagged)] +pub enum JobEnvironmentInfo { + Cpu(crate::lighting::environment_input::EnvironmentInfo), + Gpu(crate::lighting::environment::EnvironmentInfo), +} + +#[derive(Clone, Debug, Serialize)] +pub struct JobStatus { + /// Completed CPU passes whose immutable snapshot could not be published + /// because both admitted slots remained pinned by external consumers. + pub cpu_preview_retention_skips: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub punctual_diagnostics: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub presentation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sampling: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub linear_master: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + pub textures: Option, + pub options: JobOptions, + #[serde(skip_serializing_if = "Option::is_none")] + pub environment: Option, + pub job: JobId, + pub scene_generation: u64, + pub request: ImageRequest, + pub resolved: crate::ResolvedRequest, + pub progress: Progress, + pub error: Option, + pub frame: Option, +} + +struct Data { + cpu_preview_retention_skips: u32, + partial_preview: Option>, + punctual_diagnostics: Option, + sampling: Option, + progress: Progress, + error: Option, + frame: Option>, + preview: Option>, +} +struct Record { + partial: Option>, + presentation: Option>, + textures: Option, + options: JobOptions, + environment: Option, + id: JobId, + scene_generation: u64, + request: ImageRequest, + // Rust fields drop in declaration order: payload before its retained credits. + _request_reservation: Option, + resolved: crate::ResolvedRequest, + cancel: CancelToken, + data: Mutex, + #[cfg(not(target_arch = "wasm32"))] + done: Condvar, +} + +impl Record { + fn notify(&self) { + #[cfg(not(target_arch = "wasm32"))] + self.done.notify_all(); + } +} + +#[derive(Clone)] +pub struct JobHandle(Arc); + +impl JobHandle { + /// Internal admitted-work identity. Equal public IDs need not be one record. + pub(super) fn same_record(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + + pub fn id(&self) -> JobId { + self.0.id + } + pub fn status(&self) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + Ok(JobStatus { + cpu_preview_retention_skips: data.cpu_preview_retention_skips, + punctual_diagnostics: data.punctual_diagnostics, + presentation: self.0.presentation.as_deref().map(|retained| retained.info.clone()), + sampling: data.sampling.clone(), + linear_master: data.frame.as_ref().and_then(|frame| frame.linear_master_info().cloned()), + preview: data.preview.as_ref().map(|preview| preview.info.clone()), + textures: self.0.textures.clone(), + options: self.0.options, + environment: self.0.environment.clone(), + job: self.0.id, + scene_generation: self.0.scene_generation, + request: self.0.request.try_clone_for_host()?, + resolved: self.0.resolved.clone(), + progress: data.progress, + error: data.error.clone(), + frame: data.frame.as_ref().map(|f| f.info.clone()), + }) + } + pub fn cancel(&self) -> Result { + if let Some(credits) = &self.0.partial { + credits.close(); + } + let mut released_partial = None; + { + let mut data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + if !data.progress.phase.terminal() { + self.0.cancel.cancel(); + released_partial = data.partial_preview.take(); + data.preview = None; + data.progress.phase = if data.progress.phase == Phase::Queued { Phase::Cancelled } else { Phase::Cancelling }; + } + } + drop(released_partial); + self.0.notify(); + self.status() + } + + /// Native application helper; engine status commands remain non-blocking. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, timeout: std::time::Duration) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + let (data, timed) = self + .0 + .done + .wait_timeout_while(data, timeout, |d| !d.progress.phase.terminal()) + .map_err(|_| JobError::new(ErrorCode::Internal, "render completion lock poisoned"))?; + if timed.timed_out() && !data.progress.phase.terminal() { + return Err(JobError::new(ErrorCode::TimedOut, "render wait timed out")); + } + drop(data); + self.status() + } + pub fn frame(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render result lock poisoned"))?; + let frame = data.frame.clone(); + if frame.as_ref().is_some_and(|f| f.info.job != self.0.id || f.info.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render frame identity does not match its job")); + } + Ok(frame) + } + + /// A provisional complete-pass image, never the final/export frame slot. + pub fn preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview lock poisoned"))?; + let preview = data.preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render preview identity does not match its job")); + } + Ok(preview) + } +} + +#[derive(Clone, Copy)] +enum CpuPreviewPolicy { + Shared(super::PartialPreviewPlan), + Protected(super::ProtectedPreviewPlan), +} +impl CpuPreviewPolicy { + fn preview_plan(self) -> super::PartialPreviewPlan { + match self { + Self::Shared(plan) => plan, + Self::Protected(plan) => plan.preview_plan(), + } + } +} +struct Submission { + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, +} +struct Work { + regrade: Option<(Arc, super::presentation::Presentation)>, + request: Option, + executor: Option>, + environment: Option, + scene: ProductScene, + handle: JobHandle, + reservation: Reservation, +} +// One host advance hashes at most four 16 KiB chunks, independently of the +// integrator's quantum. The unchanged work reservation covers the sole PNG and +// this fixed state until publication; it is not another image task or pool. +const PNG_HASH_CHUNK_BYTES: usize = 16_384; +const PNG_HASH_CHUNKS_PER_ADVANCE: usize = 4; +pub(crate) const FRAME_METADATA_BYTES: u64 = 1024; + +struct PendingPng { + png: Vec, + digest: Sha256, + hashed: usize, + preview_samples: Option, + exr: Option>, + exr_digest: Sha256, + exr_hashed: usize, +} +// Keep the new fixed completion state within the existing metadata allowance +// even if the hashing dependency's representation changes on another target. +const _: [(); 1] = [(); (std::mem::size_of::() <= 512) as usize]; +const _: [(); 1] = [(); (std::mem::size_of::() + + std::mem::size_of::() + + std::mem::size_of::() + + 64 + + 2 * crate::MAX_RENDER_ID_BYTES + + 32 + <= FRAME_METADATA_BYTES as usize) as usize]; + +impl PendingPng { + fn new(png: Vec) -> Self { + Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, exr_digest: Sha256::new(), exr_hashed: 0 } + } + + #[cfg(feature = "raytrace-cpu")] + fn preview(png: Vec, samples: u32) -> Self { + Self { preview_samples: Some(samples), ..Self::new(png) } + } + + fn step(&mut self, units: usize, cancel: &CancelToken) -> Result { + cancel.check()?; + for _ in 0..units.min(PNG_HASH_CHUNKS_PER_ADVANCE) { + let (bytes, hashed, digest) = if self.hashed < self.png.len() { + (&self.png, &mut self.hashed, &mut self.digest) + } else if let Some(exr) = self.exr.as_ref().filter(|exr| self.exr_hashed < exr.len()) { + (exr, &mut self.exr_hashed, &mut self.exr_digest) + } else { + break; + }; + let end = hashed.saturating_add(PNG_HASH_CHUNK_BYTES).min(bytes.len()); + digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?); + *hashed = end; + cancel.check()?; + } + Ok(self.hashed == self.png.len() && self.exr.as_ref().is_none_or(|exr| self.exr_hashed == exr.len())) + } + fn progress(&self) -> Progress { + Progress { + phase: Phase::Encoding, + done: self.hashed as u64 + self.exr_hashed as u64, + total: self.png.len() as u64 + self.exr.as_ref().map_or(0, |bytes| bytes.len() as u64), + } + } +} + +struct Running { + source_master: Option>, + task: Option, + pending_png: Option, + handle: JobHandle, + reservation: Option, + next_preview_sequence: u32, + next_checkpoint_pass: u32, + checkpoints: Option>, + // Task/PNG allocations above die before the in-flight credit below. + partial: Option>, +} + +impl Drop for Running { + fn drop(&mut self) { + if let Some(credits) = &self.checkpoints { + credits.close(); + } + } +} + +/// One fallibly allocated task, keeping the dispatch enum small in either build. +/// Its bounded metadata allocation fits the existing per-job task allowance. +struct TaskSlot(Vec); +impl TaskSlot { + fn new(task: T) -> Result { + if std::mem::size_of::() > 4096 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task metadata exceeds its admission allowance")); + } + let mut tasks = Vec::new(); + tasks.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve render task slot"))?; + if tasks.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task slot exceeds its bounded capacity")); + } + tasks.push(task); + Ok(Self(tasks)) + } + fn get_mut(&mut self) -> Result<&mut T> { + self.0.first_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task slot")) + } +} +enum WorkTask { + Regrade(TaskSlot), + Registered(Box), + Raster(TaskSlot), + #[cfg(feature = "raytrace-cpu")] + Raytrace(TaskSlot), +} + +enum WorkPoll { + #[cfg(feature = "raytrace-cpu")] + Partial { + png: Vec, + covered: Vec, + completed_passes: u32, + updated_prefix: u64, + }, + Existing(TaskPoll), + #[cfg(feature = "raytrace-cpu")] + Preview { + png: Vec, + samples_per_pixel: u32, + }, +} + +impl WorkTask { + fn protected_report(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.protected_preview_report()), + _ => None, + } + } + fn partial_ready(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => task.get_mut()?.partial_preview_ready(plan), + _ => Ok(false), + } + } + fn completed_pass_ready(&self, plan: super::PartialPreviewPlan) -> Result> { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().map_or(Ok(None), |task| task.completed_pass_preview_ready(plan)), + _ => Ok(None), + } + } + fn begin_partial(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => match task.get_mut()?.begin_partial_preview(plan)? { + crate::raytrace::image::PartialBegin::Started => Ok(true), + crate::raytrace::image::PartialBegin::Exhausted => Ok(false), + }, + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn step_partial(&mut self, units: usize) -> Result { + let _ = &units; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_partial_previews(units)? { + crate::raytrace::image::PartialImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::PartialImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix } => { + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } + } + }), + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn punctual_diagnostics(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.punctual_diagnostics()), + _ => None, + } + } + + fn source_master(&self) -> Result>> { + match self { + Self::Regrade(slot) => { + slot.0.first().map(|task| Some(task.source())).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing master task slot")) + } + _ => Ok(None), + } + } + fn sampling_report(&self) -> Option { + match self { + Self::Registered(task) => task.sampling_report(), + _ => None, + } + } + fn take_linear_exr(&mut self) -> Option> { + match self { + Self::Registered(task) => task.take_linear_exr(), + _ => None, + } + } + fn new( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + environment: Option, + job_options: JobOptions, + partial: Option, + report_sink: Option<&PartialCredits>, + ) -> Result { + let _ = (&environment, &job_options, &partial, &report_sink); + match request.integrator { + Integrator::Raster => ImageTask::new(scene, request, cancel).and_then(TaskSlot::new).map(Self::Raster), + Integrator::Raytrace => { + #[cfg(feature = "raytrace-cpu")] + { + let options = request.raytrace.clone().unwrap_or_default(); + let task = match partial { + Some(CpuPreviewPolicy::Shared(plan)) => crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ), + Some(CpuPreviewPolicy::Protected(plan)) => { + crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_protected_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ) + } + None => crate::raytrace::image::ImageTask::new_with_environment_and_nested( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + ), + }; + Self::raytrace_with_slot(task?, report_sink, TaskSlot::new) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + } + + fn step(&mut self, units: usize) -> Result { + match self { + Self::Regrade(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + Self::Registered(task) => task.step(units).map(WorkPoll::Existing), + Self::Raster(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_previews(units)? { + crate::raytrace::image::ImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::ImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::ImagePoll::Preview { png, samples_per_pixel } => WorkPoll::Preview { png, samples_per_pixel }, + }), + } + } +} + +fn terminal(handle: &JobHandle, error: JobError) { + if let Some(credits) = &handle.0.partial { + credits.close(); + } + let mut released_partial = None; + if let Ok(mut data) = handle.0.data.lock() { + if data.progress.phase == Phase::Completed { + return; + } + if handle.0.cancel.is_cancelled() || error.code == ErrorCode::Cancelled { + data.progress.phase = Phase::Cancelled; + data.error = None; + } else { + data.progress.phase = Phase::Failed; + data.error = Some(error); + } + data.frame = None; + data.preview = None; + released_partial = data.partial_preview.take(); + } + drop(released_partial); + handle.0.notify(); +} + +impl Running { + fn begin(work: Work) -> Option { + Self::begin_with_partial_factory(work, |credits| TaskSlot::new(PartialRunning::new(credits))) + } + + // The private factory keeps post-construction setup fallible without losing + // the real ledger. It runs only after report capture and outside every lock. + fn begin_with_partial_factory( + mut work: Work, + make_partial: impl FnOnce(Arc) -> Result>, + ) -> Option { + let checkpoints = (|| { + let slots = work + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .filter(|_| work.handle.0.partial.is_none() && work.executor.is_none()) + .map_or(0, |options| options.samples_per_pixel.saturating_sub(1).min(2)); + if slots == 0 { + return Ok(None); + } + let slot_bytes = u64::from(work.handle.0.request.width) + .checked_mul(u64::from(work.handle.0.request.height)) + .and_then(|n| n.checked_mul(8)) + .and_then(|n| n.checked_add(65_536 + FRAME_METADATA_BYTES)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint slot overflow"))?; + CheckpointCredits::new(&mut work.reservation, slot_bytes, slots).map(Some) + })(); + let checkpoints = match checkpoints { + Ok(credits) => credits, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + if work.handle.0.cancel.is_cancelled() { + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render cancelled")); + return None; + } + if let Ok(mut data) = work.handle.0.data.lock() + && !work.handle.0.cancel.is_cancelled() + { + data.progress.phase = Phase::Preparing; + } + let task = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if let Some((source, presentation)) = work.regrade { + super::regrade::RegradeTask::new(source, presentation, work.handle.0.cancel.clone()).and_then(TaskSlot::new).map(WorkTask::Regrade) + } else if let Some(executor) = work.executor { + let request = work.request.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing registered executor request"))?; + executor.begin(work.scene, request, work.handle.0.options, work.handle.0.cancel.clone()).map(WorkTask::Registered) + } else { + WorkTask::new( + work.scene, + work.handle.0.request.try_clone_for_host()?, + work.handle.0.cancel.clone(), + work.environment, + work.handle.0.options, + work.handle.0.partial.as_ref().map(|credits| credits.policy()), + work.handle.0.partial.as_deref(), + ) + } + })) + .unwrap_or_else(|_| Err(JobError::new(ErrorCode::Internal, "image executor failed while preparing the job"))); + let task = match task { + Ok(task) => task, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + // The raw producer report was captured before the first task-slot wrap. + // Only now attempt the additional partial runtime slot. + let partial = work.handle.0.partial.as_ref().map(|credits| make_partial(credits.clone())).transpose(); + match partial { + Ok(partial) => Some(Self { + partial, + source_master: None, + task: Some(task), + pending_png: None, + handle: work.handle, + reservation: Some(work.reservation), + next_preview_sequence: 1, + next_checkpoint_pass: 1, + checkpoints, + }), + Err(error) => { + terminal(&work.handle, error); + // The real task's buffers die before work's remaining lease. + None + } + } + } + fn advance(&mut self, units: usize) -> Result { + self.handle.0.cancel.check()?; + if self.pending_png.is_some() { + return self.advance_png(units); + } + if let Some(partial) = self.partial.as_mut() { + let partial = partial.get_mut()?; + let task = self.task.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + let uniform_pass = task.completed_pass_ready(partial.credits.plan)?; + let automatic_pass = uniform_pass.filter(|pass| *pass > partial.last_pass_attempt); + if let Some(pass) = automatic_pass { + partial.last_pass_attempt = pass; + partial.credits.request()?; + } + if partial.lease.is_none() + && partial.credits.requested.load(Ordering::Acquire) + && !partial.credits.exhausted.load(Ordering::Acquire) + && (uniform_pass.is_none() || automatic_pass.is_some()) + { + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + if task.partial_ready(partial.credits.plan)? { + let mut lease = partial.credits.acquire()?; + if lease.is_none() && automatic_pass.is_some() { + let released = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retirement lock poisoned"))? + .partial_preview + .take(); + drop(released); + lease = partial.credits.acquire()?; + } + if lease.is_none() && automatic_pass.is_some() && partial.credits.retained_slots_blocked()? { + let mut data = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retention diagnostic lock poisoned"))?; + self.handle.0.cancel.check()?; + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial retention diagnostic overflow"))?; + } + if let Some(lease) = lease { + // Keep the lease past any producer error until task buffers drop. + partial.lease = Some(lease); + let begin = task.begin_partial(partial.credits.plan); + partial.credits.store_report(task.protected_report())?; + if !begin? { + if partial.credits.protected.is_some() && !partial.credits.exhausted.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::Internal, "protected feedback refused without real quota exhaustion")); + } + partial.credits.exhaust(); + drop(partial.lease.take()); + } + } + } + } + } + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task"))?; + let result = if self.partial.is_some() { task.step_partial(units) } else { task.step(units) }; + if let Some(credits) = &self.handle.0.partial { + credits.store_report(task.protected_report())?; + } + let result = result?; + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + data.punctual_diagnostics = self.task.as_ref().and_then(WorkTask::punctual_diagnostics); + // The final publication check is under the same lock as cancellation. + if self.handle.0.cancel.is_cancelled() { + data.progress.phase = Phase::Cancelled; + data.frame = None; + data.preview = None; + let released = data.partial_preview.take(); + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + return Ok(false); + } + match result { + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } => { + drop(data); + self.capture_partial(png, covered, completed_passes, updated_prefix)?; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Pending(progress)) => { + data.progress = progress; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Complete(png)) => { + // Drop every integrator-owned capture/scratch buffer first, but + // keep the original admission lease while hashing the sole PNG. + self.source_master = self.task.as_ref().map(WorkTask::source_master).transpose()?.flatten(); + data.sampling = self.task.as_ref().and_then(WorkTask::sampling_report); + let exr = self.task.as_mut().and_then(WorkTask::take_linear_exr); + if exr.is_some() != self.handle.0.options.linear_exr { + return Err(JobError::new(ErrorCode::Internal, "linear master availability differs from the admitted request")); + } + if let Some(bytes) = &exr { + let limit = super::linear_exr::encoded_limit(self.handle.0.request.width, self.handle.0.request.height)?; + if bytes.len() < 8 || bytes.capacity() as u64 > limit || bytes.get(..8) != Some(&[0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]) { + return Err(JobError::new(ErrorCode::LimitExceeded, "linear master exceeds its bound or has an invalid signature")); + } + } + self.task = None; + let mut pending = PendingPng::new(png); + pending.exr = exr; + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Preview { png, samples_per_pixel } => { + // Retain the integrator/film and the entire remaining work lease. + // Hash the checkpoint before making immutable bytes observable. + let pending = PendingPng::preview(png, samples_per_pixel); + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + } + } + + fn advance_png(&mut self, units: usize) -> Result { + // No status/data lock is held while scanning the encoded image. + let pending = self.pending_png.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing pending PNG"))?; + if !pending.step(units, &self.handle.0.cancel)? { + let progress = pending.progress(); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + self.handle.0.cancel.check()?; + data.progress = progress; + return Ok(true); + } + let PendingPng { png, digest, preview_samples, exr, exr_digest, .. } = + self.pending_png.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed PNG digest"))?; + if self.partial.as_ref().and_then(|slot| slot.0.first()).is_some_and(|partial| partial.pending.is_some()) { + return self.publish_partial(png, digest); + } + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: self.handle.0.request.width, + height: self.handle.0.request.height, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + png_sha256: format!("{:x}", digest.finalize()), + }; + // Include the working digest/Vec metadata, completed frame layout, + // actual hex allocation, bounded copied IDs and Arc/header allowance. + // The PNG allocation itself is retained once and billed by capacity below. + let frame_layout = if preview_samples.is_some() { std::mem::size_of::() } else { std::mem::size_of::() }; + let checkpoint_metadata = + if preview_samples.is_some() { std::mem::size_of::() + 2 * std::mem::size_of::() } else { 0 }; + let fixed_metadata = std::mem::size_of::() + frame_layout + checkpoint_metadata + 2 * crate::MAX_RENDER_ID_BYTES + 32; + let linear_digest_bytes = if exr.is_some() { 64 } else { 0 }; + if fixed_metadata + .checked_add(info.png_sha256.capacity()) + .and_then(|n| n.checked_add(linear_digest_bytes)) + .is_none_or(|bytes| bytes > FRAME_METADATA_BYTES as usize) + { + return Err(JobError::new(ErrorCode::LimitExceeded, "PNG digest metadata exceeds its existing admission allowance")); + } + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + // Cancellation shares this lock; a late cancel must win before frame + // installation. The digest is complete; checkpoints retain task scratch, + // while the final-only path has already released it. + self.handle.0.cancel.check()?; + if let Some(samples_per_pixel) = preview_samples { + let options = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "preview requires CPU progressive intent"))?; + let frame_sequence = self.next_preview_sequence; + let expected = Some(self.next_checkpoint_pass); + if expected != Some(samples_per_pixel) || samples_per_pixel >= options.samples_per_pixel || self.task.is_none() { + return Err(JobError::new(ErrorCode::Internal, "invalid progressive checkpoint sequence")); + } + let next_sequence = frame_sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::Internal, "preview sequence exhausted"))?; + let credits = self.checkpoints.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing checkpoint credits"))?; + if (png.capacity() as u64).checked_add(FRAME_METADATA_BYTES).is_none_or(|bytes| bytes > credits.slot_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "checkpoint PNG exceeds its admitted slot")); + } + let mut reservation = credits.acquire()?; + if reservation.is_none() { + // Retire the host's obsolete slot before treating a consumer as + // pinned. A headless client never has to acknowledge previews. + let released = data.preview.take(); + drop(data); + drop(released); + reservation = credits.acquire()?; + data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview publication lock poisoned"))?; + self.handle.0.cancel.check()?; + } + self.next_checkpoint_pass = self + .next_checkpoint_pass + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; + let Some(reservation) = reservation else { + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint retention diagnostic overflow"))?; + return Ok(true); + }; + data.preview = Some(Arc::new(RenderPreview { + info: PreviewInfo { frame_sequence, samples_per_pixel, frame: info }, + png, + _reservation: reservation, + })); + self.next_preview_sequence = next_sequence; + let pixels = u64::from(self.handle.0.request.width) * u64::from(self.handle.0.request.height); + data.progress = + Progress { phase: Phase::Running, done: pixels * u64::from(samples_per_pixel), total: pixels * u64::from(options.samples_per_pixel) }; + self.handle.0.notify(); + return Ok(true); + } + let exr = exr.map(|bytes| { + let info = LinearMasterInfo { + bytes: bytes.len() as u64, + sha256: format!("{:x}", exr_digest.finalize()), + encoding: LinearColourEncoding::SceneLinearSrgbD65, + alpha: LinearAlphaConvention::CoveragePremultiplied, + }; + (bytes, info) + }); + let retained = png.capacity() as u64 + exr.as_ref().map_or(0, |(bytes, _)| bytes.capacity() as u64) + FRAME_METADATA_BYTES; + let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?; + reservation.shrink(retained)?; + data.frame = Some(Arc::new(RenderFrame { + info, + png, + exr, + source_master: self.source_master.take(), + presentation: self.handle.0.presentation.clone(), + _reservation: reservation, + })); + data.preview = None; + let released = data.partial_preview.take(); + data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; + if let Some(credits) = &self.checkpoints { + credits.close(); + } + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + Ok(false) + } + + fn guarded_step(&mut self, units: usize) -> bool { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.advance(units))); + match result { + Ok(Ok(more)) => more, + Ok(Err(e)) => { + terminal(&self.handle, e); + false + } + Err(_) => { + terminal(&self.handle, JobError::new(ErrorCode::Internal, "image host encountered an internal error")); + false + } + } + } +} + +struct Shared { + queue: Mutex>, + active: Mutex>>, + stop: AtomicBool, + budget: Arc, + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar, +} + +struct Owner { + executor: Option>, + shared: Arc, + kind: HostKind, + running: Mutex>, + #[cfg(not(target_arch = "wasm32"))] + _worker: Option>, +} + +impl Drop for Owner { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Release); + if let Ok(active) = self.shared.active.lock() + && let Some(record) = active.as_ref().and_then(Weak::upgrade) + { + let _ = JobHandle(record).cancel(); + } + if let Ok(mut queue) = self.shared.queue.lock() { + for work in queue.iter() { + let _ = work.handle.cancel(); + } + queue.clear(); + } + if let Ok(mut running) = self.running.lock() + && let Some(work) = running.take() + { + let _ = work.handle.cancel(); + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render host closed")); + } + #[cfg(not(target_arch = "wasm32"))] + self.shared.wake.notify_all(); + // Detaching cannot stall the UI; the bounded worker observes stop/cancel at its next unit. + } +} + +#[derive(Clone)] +pub struct ImageHost(Arc); + +/// Builtin CPU constructors share the registered image host lifetime machinery. +pub type CpuHost = ImageHost; + +impl ImageHost { + fn shared(limit: u64) -> Arc { + Arc::new(Shared { + queue: Mutex::new(VecDeque::new()), + active: Mutex::new(None), + stop: AtomicBool::new(false), + budget: Arc::new(Budget { used: AtomicU64::new(0), limit }), + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar::new(), + }) + } + + pub fn cooperative() -> Self { + Self(Arc::new(Owner { + executor: None, + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + /// A cooperative host over `executor` (pumped by its caller). + #[cfg(test)] + fn cooperative_with(executor: Arc) -> Self { + Self(Arc::new(Owner { + executor: Some(executor), + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + pub fn for_platform() -> Result { + #[cfg(target_arch = "wasm32")] + { + Ok(Self::cooperative()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let pool = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + let shared = Self::shared(pool); + 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 { executor: None, shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + } + + /// Start an isolated bounded native worker. GPU discovery occurs before registration. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_executor(executor: Arc) -> Result { + 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 limit = executor.memory_limit_bytes(); + let ceiling = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + if limit == 0 || limit > ceiling { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image pool exceeds supported address space")); + } + let shared = Self::shared(limit); + 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: Some(executor), shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + + pub fn kind(&self) -> HostKind { + self.0.kind + } + + pub fn same_host(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + pub fn is_available(&self) -> bool { + !self.0.shared.stop.load(Ordering::Acquire) + } + pub fn admitted_bytes(&self) -> u64 { + self.0.shared.budget.used.load(Ordering::Acquire) + } + + /// Internal completed-film adapter: the existing host budget, no new pool. + pub(crate) fn reserve_film_snapshot(&self, bytes: u64) -> Result { + if self.0.executor.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU film snapshots require the builtin CPU host")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU image host has stopped")); + } + if bytes > super::image::MAX_JOB_BYTES { + return Err(JobError::new(ErrorCode::LimitExceeded, "film snapshot exceeds per-job admission")); + } + self.0.shared.budget.reserve(bytes) + } + + pub fn descriptor(&self) -> Result { + self.descriptor_for(Integrator::Raster) + } + + pub fn job_limit_bytes(&self) -> u64 { + if self.0.executor.is_some() { self.0.shared.budget.limit } else { super::image::MAX_JOB_BYTES } + } + + pub fn pool_limit_bytes(&self) -> u64 { + self.0.shared.budget.limit + } + + pub fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + self.admit_with_policy(scene, request, options, None) + } + /// Same canonical policy and complete retained/HDR accounting as protected submit. + /// Non-reserving estimate: submission still admits against the live pool. + pub fn admit_cpu_protected_partial_with_environment_and_options( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result { + self.validate_submission_environment(scene, request, environment)?; + let policy = Self::protected_preview_policy(request)?; + let (mut admission, request_bytes) = self.admit_submission(scene, request, options, environment, Some(policy))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(request_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request admission overflow"))?; + Ok(admission) + } + + fn protected_preview_policy(request: &ImageRequest) -> Result { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require CPU progressive intent"))? + .samples_per_pixel; + let plan = super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())?; + Ok(CpuPreviewPolicy::Protected(plan)) + } + + fn validate_submission_environment( + &self, + scene: &ProductScene, + request: &ImageRequest, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result<()> { + if self.0.executor.is_some() && environment.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU environments")); + } + if environment.is_some() && request.integrator != Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "environment lighting requires CPU raytrace")); + } + self.validate_integrator(request.integrator)?; + if environment.is_some() { + request.raytrace.as_ref().unwrap_or(&super::RaytraceOptions::default()).validate_environment_reflections(scene)?; + } + Ok(()) + } + + fn admit_submission( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + partial: Option, + ) -> Result<(Admission, u64)> { + if environment.is_some() && request.raytrace.as_ref().is_some_and(|options| options.directional_shadow_transmission) { + return Err(JobError::new(ErrorCode::InvalidRequest, "directional shadow transmission does not support HDR environments")); + } + let metadata_bytes = + (if environment.is_some() { std::mem::size_of::() as u64 } else { 0 }) + + request.retained_resource_metadata_bytes(); + let request_bytes = retained_request_bytes(request)? + .checked_add(metadata_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment metadata overflow"))?; + let mut admission = self.admit_with_policy(scene, request, options, partial)?; + let environment_bytes = + environment.map_or(Ok(0), |value| value.required_bytes()).map_err(|error| JobError::new(ErrorCode::InvalidRequest, error.to_string()))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + admission.preparation_bytes = admission + .preparation_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + self.check_request_sum(admission.estimated_total_bytes, request_bytes, request.cpu_budget())?; + Ok((admission, request_bytes)) + } + + fn admit_with_policy( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + partial: Option, + ) -> Result { + request.validate_raster_request()?; + if self.0.executor.is_some() && (request.has_explicit_raster_lights() || request.raster_exposure_ev != 0.0) { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept Raster-only lights or exposure")); + } + if let Some(policy) = partial { + let plan = policy.preview_plan(); + if self.0.executor.is_some() + || request.integrator != Integrator::Raytrace + || request.transparent_background + || request.environment.is_some() + || request.textures.is_some() + || request.raytrace.as_ref().and_then(|v| v.progressive).is_none() + || plan != super::PartialPreviewPlan::new(request.width, request.height)? + { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial previews require the canonical builtin CPU progressive request")); + } + if let CpuPreviewPolicy::Protected(protected) = policy { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require a progressive sample target"))? + .samples_per_pixel; + protected.validate()?; + if protected != super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan does not match its admitted request")); + } + } + } + let scatter = |t: Option| t.and_then(|v| v.subsurface()).is_some_and(|s| s.active()); + if scene.meshes.iter().any(|b| scatter(b.transmission) || b.faces.iter().any(|f| scatter(f.transmission))) + && !self.0.executor.as_ref().is_some_and(|executor| executor.supports_subsurface()) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "installed image producer does not implement interior subsurface random walks")); + } + + self.validate_integrator(request.integrator)?; + options.validate()?; + if let Some(executor) = &self.0.executor { + if request.raytrace.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept CPU raytrace options")); + } + if options.aging.active() && !executor.supports_aging() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot evaluate ordered surface aging")); + } + if options.finishing.photographic.active() && !executor.supports_photographic() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply photographic lens effects")); + } + if options.nested_media && !executor.supports_nested_media() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement certified nested media")); + } + if options.volume.is_some() && !executor.supports_volume() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement bounded homogeneous volume transport")); + } + if options.adaptive.is_some() && !executor.supports_adaptive_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement independent-pilot adaptive sampling")); + } + if options.transmission_samples != 1 && !executor.supports_transmission_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement transmission strata")); + } + if options.linear_exr && !executor.supports_linear_exr() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot retain a raw linear EXR")); + } + if options.finishing.bloom.is_some_and(|b| b.active()) && !executor.supports_bloom() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement display bloom")); + } + if (!options.finishing.is_identity() || options.backdrop.is_some()) && !executor.supports_finishing() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply the requested finishing/backdrop")); + } + let admission = executor.admit(scene, request, options)?; + if admission.estimated_total_bytes > self.job_limit_bytes() { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(admission) + } else { + request.cpu_budget().validate_execution()?; + // Only the existing nesting opt-in is admitted on the CPU raytrace path. + // Every other JobOptions field retains its exact default-only contract. + if (JobOptions { nested_media: false, ..options }) != JobOptions::default() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU images use raytrace options, not progressive sampling controls")); + } + if let Some(policy) = partial { + #[cfg(feature = "raytrace-cpu")] + { + let raytrace = request + .raytrace + .as_ref() + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "partial previews require CPU progressive options"))?; + return match policy { + CpuPreviewPolicy::Shared(plan) => { + crate::raytrace::image::admit_with_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + CpuPreviewPolicy::Protected(plan) => { + crate::raytrace::image::admit_with_protected_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + }; + } + #[cfg(not(feature = "raytrace-cpu"))] + { + let _ = policy; + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + } + if !options.nested_media { + return admit(scene, request); + } + if request.integrator != Integrator::Raytrace || request.environment.is_some() || request.textures.is_some() || scene.has_transmission() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU nested media require explicit raytrace dielectric overrides")); + } + #[cfg(feature = "raytrace-cpu")] + { + let defaults = super::RaytraceOptions::default(); + let raytrace = request.raytrace.as_ref().unwrap_or(&defaults); + crate::raytrace::image::admit_with_nested(scene, request, raytrace, true) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + + fn check_request_sum(&self, work: u64, request: u64, budget: super::CpuBudget) -> Result<()> { + if self.0.executor.is_none() { + if budget == super::CpuBudget::Compact { + return admit_request_sum(work, request); + } + if work.checked_add(request).is_none_or(|n| n > budget.limits().max_job_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "CPU work and retained request exceed the selected profile")); + } + return Ok(()); + } + if work.checked_add(request).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(()) + } + + /// Check the execution choice without capturing geometry or reserving memory. + pub fn validate_integrator(&self, integrator: Integrator) -> Result<()> { + if self.0.executor.is_some() && integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing requires the native worker host")); + } + Ok(()) + } + + /// Select exactly one executor for this request. Never rely on registry order + /// to choose between raster and raytracing implementations. + pub fn descriptor_for(&self, integrator: Integrator) -> Result { + if let Some(executor) = &self.0.executor { + if integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + let mut descriptor = executor.descriptor()?; + if !self.is_available() { + descriptor.availability = Availability::Unavailable { reason: "image host has stopped".into() }; + } + return Ok(descriptor); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + Ok(ExecutorDescriptor { + id: ExecutorId::new(match integrator { + Integrator::Raster => "cpu-product", + Integrator::Raytrace => "cpu-raytrace", + }) + .map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: if self.0.shared.stop.load(Ordering::Acquire) { + Availability::Unavailable { reason: "image host has stopped".into() } + } else if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + Availability::Unavailable { reason: "CPU raytracing requires the native worker host".into() } + } else { + Availability::Available + }, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: if integrator == Integrator::Raytrace && cfg!(feature = "raytrace-cpu") && self.kind() == HostKind::NativeWorker { + // Refraction is the certified thin-sheet/axis-aligned-box CPU preview + // contract. Admission still refuses unsupported geometry and combinations. + vec![crate::RenderFeature::Pbr, crate::RenderFeature::Hdri, crate::RenderFeature::Refraction] + } else { + vec![crate::RenderFeature::Pbr] + }, + }], + limits: if integrator == Integrator::Raytrace && self.kind() == HostKind::NativeWorker && usize::BITS >= 64 { + super::CpuBudget::Workstation.image_limits(false) + } else { + RenderLimits::default() + }, + scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }) + } + + /// Resolve a CPU request against its explicit envelope, never the largest advertised one. + pub fn descriptor_for_request(&self, request: &ImageRequest) -> Result { + let mut descriptor = self.descriptor_for(request.integrator)?; + if self.0.executor.is_none() && request.integrator == Integrator::Raytrace { + let budget = request.cpu_budget(); + budget.validate_execution()?; + budget.validate_image(request.width, request.height, request.raytrace.as_ref().and_then(|o| o.progressive))?; + descriptor.limits = budget.image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())); + } + Ok(descriptor) + } + + pub fn submit(&self, id: JobId, scene_generation: u64, scene: ProductScene, request: ImageRequest) -> Result { + self.submit_with_environment(id, scene_generation, scene, request, None) + } + + /// Captured HDR ownership stays in work, never serialized/cloned into status. + pub fn submit_with_environment( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + environment: Option, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, JobOptions::default(), environment) + } + + pub fn submit_with_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, options, None) + } + + pub fn submit_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, None) + } + /// Transient CPU presentation policy. Final request and legacy observers are unchanged. + pub fn submit_cpu_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let plan = super::PartialPreviewPlan::new(request.width, request.height)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(CpuPreviewPolicy::Shared(plan))) + } + /// Opt-in protected feedback preserves ordinary work while admitting a finite extra quota. + pub fn submit_cpu_protected_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let policy = Self::protected_preview_policy(&request)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(policy)) + } + fn submit_with_policy(&self, input: Submission, partial_plan: Option) -> Result { + let Submission { id, scene_generation, scene, request, options, environment } = input; + self.validate_submission_environment(&scene, &request, environment.as_ref())?; + if id.session == 0 || id.serial == 0 || id.generation == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); + } + let environment_info = environment + .as_ref() + .map(|e| JobEnvironmentInfo::Cpu(e.metadata())) + .or_else(|| request.environment.as_ref().map(|source| JobEnvironmentInfo::Gpu(source.info().clone()))); + let textures = request.textures.as_ref().map(|source| source.summary()); + let mut features = scene.required_features(); + if environment.is_some() || request.environment.is_some() { + features.push(crate::RenderFeature::Hdri); + } + if request.integrator == Integrator::Raytrace + && request.raytrace.as_ref().is_some_and(|options| !options.dielectrics.is_empty()) + && !features.contains(&crate::RenderFeature::Refraction) + { + features.push(crate::RenderFeature::Refraction); + } + let (Admission { estimated_total_bytes, .. }, request_bytes) = + self.admit_submission(&scene, &request, options, environment.as_ref(), partial_plan)?; + let mut backend = crate::builtin_backend(); + let descriptor = self.descriptor_for_request(&request)?; + let expected_executor = descriptor.id.clone(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(request.width), + height: u64::from(request.height), + format: Some(RenderFormat::Png), + features, + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, e.to_string()))?; + if resolved.executor != expected_executor { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product 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, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + self.check_request_sum(estimated_total_bytes, request_bytes, request.cpu_budget())?; + let mut reservation = self.0.shared.budget.reserve(estimated_total_bytes)?; + + let partial_credits = partial_plan + .map(|policy| match policy { + CpuPreviewPolicy::Shared(plan) => PartialCredits::new(plan, &mut reservation), + CpuPreviewPolicy::Protected(plan) => PartialCredits::new_protected(plan, &mut reservation), + }) + .transpose()?; + let request_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) }; + // Preserve the original CPU option capacities in the retained request and its lease. + // Registered executors instead move resource Arcs into work and keep a small public copy. + let (public_request, work_request) = if self.0.executor.is_some() { + (ImageRequest { environment: None, textures: None, ..request.clone() }, Some(request)) + } else { + (request, None) + }; + let handle = JobHandle(Arc::new(Record { + partial: partial_credits, + presentation: None, + textures, + options, + environment: environment_info, + _request_reservation: request_reservation, + id, + scene_generation, + request: public_request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: None, + request: work_request, + executor: self.0.executor.clone(), + scene, + handle: handle.clone(), + reservation, + environment, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Regrade the exact retained native master. No geometry, material, light or + /// device work is submitted. The original frame and its lease remain shared. + pub fn submit_regrade(&self, id: JobId, source: &JobHandle, presentation: super::presentation::Presentation) -> Result { + if id.session == 0 || id.serial == 0 || id.generation == 0 || id.session != source.id().session || id == source.id() { + return Err(JobError::new(ErrorCode::WrongOwner, "regrade requires a new identity in the source document session")); + } + let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; + let master = frame.master_source()?; + let bytes = super::regrade::required_bytes(&master, presentation)?; + let raw = master.linear_master_info().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "raw master metadata is missing"))?; + let origin = super::presentation::MasterPresentation { + source_job: source.id(), + master_job: master.info.job, + master_sha256: raw.sha256.clone(), + presentation, + denoise_applied: false, + }; + let metadata_bytes = (std::mem::size_of::() + origin.master_sha256.capacity() + 32) as u64; + if bytes.checked_add(metadata_bytes).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "master presentation exceeds the installed host's resource budget")); + } + let limits = RenderLimits { max_scratch_bytes: self.job_limit_bytes(), ..super::GPU_PATH_LIMITS }; + let descriptor = ExecutorDescriptor { + id: ExecutorId::new("linear-master").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::new(), + }], + limits, + scratch: ScratchLayout { sample_scale: 1, sample_bytes_per_pixel: 32, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }; + let mut backend = crate::builtin_backend(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(frame.info.width), + height: u64::from(frame.info.height), + format: Some(RenderFormat::Png), + features: Vec::new(), + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + width: frame.info.width, + height: frame.info.height, + camera: source.0.request.camera, + background: presentation.background, + transparent_background: presentation.transparent_background, + environment: None, + textures: None, + integrator: Integrator::Raster, + raytrace: None, + }; + let options = JobOptions { + finishing: presentation.finishing, + backdrop: presentation.backdrop, + exposure_ev: presentation.exposure_ev, + tone_map: presentation.tone_map, + ..Default::default() + }; + 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, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + let reservation = self.0.shared.budget.reserve(bytes)?; + let metadata = self.0.shared.budget.reserve(metadata_bytes)?; + let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); + let handle = JobHandle(Arc::new(Record { + partial: None, + presentation: Some(origin), + textures: None, + options, + environment: None, + _request_reservation: None, + id, + scene_generation: frame.info.scene_generation, + request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: Some((master, presentation)), + request: None, + executor: None, + environment: None, + scene: ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + handle: handle.clone(), + reservation, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Cooperative callers pump a small quantum independently of polling a job's status. + /// Native jobs run even when the UI is idle or a headless caller is not polling. + pub fn pump(&self, units: usize) -> Result { + if self.0.kind != HostKind::Cooperative { + return Ok(false); + } + let mut running = self.0.running.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "cooperative host lock poisoned"))?; + if running.is_none() { + let work = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.pop_front(); + if let Some(work) = work { + *running = Running::begin(work); + } + } + if let Some(work) = running.as_mut() { + if let Ok(mut active) = self.0.shared.active.lock() { + *active = Some(Arc::downgrade(&work.handle.0)); + } + if !work.guarded_step(units) { + *running = None; + if let Ok(mut active) = self.0.shared.active.lock() { + *active = None; + } + } + } + Ok(running.is_some() + || !self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.is_empty()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_worker(shared: Arc) { + loop { + let mut queue = match shared.queue.lock() { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + while queue.is_empty() && !shared.stop.load(Ordering::Acquire) { + queue = match shared.wake.wait(queue) { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + } + if shared.stop.load(Ordering::Acquire) { + return; + } + let work = queue.pop_front(); + drop(queue); + let Some(mut running) = work.and_then(Running::begin) else { continue }; + if let Ok(mut active) = shared.active.lock() { + *active = Some(Arc::downgrade(&running.handle.0)); + } + loop { + if shared.stop.load(Ordering::Acquire) { + let _ = running.handle.cancel(); + } + if !running.guarded_step(4096) { + break; + } + } + if let Ok(mut active) = shared.active.lock() { + *active = None; + } + } +} +#[cfg(test)] +mod retained_request_tests { + use super::*; + #[test] + fn retained_emitters_bill_vector_and_original_name_capacities_in_same_pool() { + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("fixture"); + let mut emissions = Vec::with_capacity(32); + emissions.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Front, + }); + let options = request.raytrace.as_mut().unwrap(); + options.emissions = Some(emissions); + let expected = 8 * std::mem::size_of::() as u64 + + 32 * std::mem::size_of::() as u64 + + 256; + assert_eq!(retained_request_bytes(&request).unwrap(), expected); + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: MEMORY_LIMIT }); + let lease = budget.reserve(expected).unwrap(); + assert_eq!(budget.used.load(Ordering::Acquire), expected); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected, expected).is_ok()); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected + 1, expected).is_err()); + drop(lease); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn emitter_request_lease_survives_real_completion_frame_eviction_and_last_handle() { + let mut host = CpuHost::for_platform().unwrap(); + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("emitter"); + let mut values = Vec::with_capacity(32); + values.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Both, + }); + request.raytrace.as_mut().unwrap().emissions = Some(values); + let expected = retained_request_bytes(&request).unwrap(); + let mesh = solidcraft_geom::Mesh { + positions: vec![solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::X, solidcraft_geom::Vec3::Y], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds, + }; + let job = host.submit(JobId { session: 1695, serial: 1, generation: 1 }, 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Completion publication precedes the worker's last temporary handle release. + // Join this test's worker before asserting exact lease ownership, as in the union test. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let held = job.clone(); + job.0.data.lock().unwrap().frame = None; + drop(job); + assert!(host.admitted_bytes() > expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + fn request() -> ImageRequest { + let mut lights = Vec::with_capacity(8); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(super::super::RaytraceOptions { lights: Some(lights), ..Default::default() }), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + } + } + #[test] + fn retained_lights_are_billed_by_original_capacity_and_sum_is_checked() { + let request = request(); + let bytes = retained_request_bytes(&request).unwrap(); + assert_eq!(bytes, 8 * std::mem::size_of::() as u64); + let cap = super::super::image::MAX_JOB_BYTES; + assert!(admit_request_sum(cap - bytes, bytes).is_ok()); + assert_eq!(admit_request_sum(cap - bytes + 1, bytes).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(admit_request_sum(u64::MAX, 1).unwrap_err().code, ErrorCode::LimitExceeded); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn retained_lights_keep_the_same_pool_lease_after_png_eviction() { + let host = CpuHost::for_platform().unwrap(); + let request = request(); + let expected = retained_request_bytes(&request).unwrap(); + let job = host + .submit( + JobId { session: 99, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + ) + .unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + let held_bytes = host.admitted_bytes(); + assert!(held_bytes > expected); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), held_bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod environment_metadata_lease_tests { + use super::*; + #[test] + fn captured_environment_metadata_survives_png_eviction_without_source_bytes() { + use crate::lighting::{ + HdrSource, + environment_input::{EnvironmentInfo, EnvironmentInput}, + }; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.5, 2.0, 16).unwrap(); + let metadata = input.metadata(); + let expected = std::mem::size_of::() as u64; + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: None, + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }; + let job = host + .submit_with_environment( + JobId { session: 1693, serial: 7, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + Some(input), + ) + .unwrap(); + let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(matches!(status.environment, Some(JobEnvironmentInfo::Cpu(info)) if info.source_sha256 == metadata.source_sha256)); + host.join_worker_for_test().unwrap(); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(host); + drop(job); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod surface_request_metadata_tests { + use super::*; + use solidcraft_geom::{Aabb3, Mesh}; + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn surface_request_lease_survives_completion_frame_eviction_and_held_handles() { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use std::time::{Duration, Instant}; + fn settle(host: &CpuHost, expected: u64) { + let deadline = Instant::now() + Duration::from_secs(10); + while host.admitted_bytes() != expected && Instant::now() < deadline { + std::thread::yield_now(); + } + assert_eq!(host.admitted_bytes(), expected); + } + let mut host = CpuHost::for_platform().unwrap(); + let mut meshes = Vec::new(); + let mut effects = Vec::with_capacity(32); + for index in 0..32 { + let mut name = String::with_capacity(256); + name.push_str(&format!("{index:03}")); + name.push_str(&"x".repeat(253)); + assert_eq!(name.capacity(), 256); + meshes.push(ProductMesh { + transmission: None, + name: name.clone(), + mesh: Arc::new(Mesh::default()), + color: [100; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + effects.push(SurfaceEffect { + body: name, + frame: Default::default(), + repeat_mm: [20.0; 3], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }); + } + let scene = ProductScene { meshes, bounds: Aabb3 { min: solidcraft_geom::Vec3::ZERO, max: solidcraft_geom::Vec3::ZERO } }; + let mut request = request(); + request.integrator = Integrator::Raytrace; + request.raytrace = Some(super::super::RaytraceOptions { surface_effects: Some(effects), ..Default::default() }); + let metadata = retained_request_bytes(&request).unwrap(); + assert!(metadata >= 32 * 256); + let mut oversized = request.clone(); + let mut overallocated = Vec::with_capacity(64); + overallocated.extend(oversized.raytrace.as_mut().unwrap().surface_effects.take().unwrap()); + oversized.raytrace.as_mut().unwrap().surface_effects = Some(overallocated); + assert!(host.submit(id(40, 1), 1, scene.clone(), oversized).is_err()); + assert_eq!(host.admitted_bytes(), 0); + + let job = host.submit(id(40, 2), 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(Duration::from_secs(10)).unwrap().progress.phase, Phase::Completed); + // Wait for this host's last temporary worker handle before exact lease checks. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let png_bytes = frame._reservation.bytes; + settle(&host, metadata + png_bytes); + // Evict the record's frame under the same lock used by publication, while + // an external frame and a cloned job handle retain their independent leases. + job.0.data.lock().unwrap().frame = None; + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), metadata + png_bytes); + drop(frame); + settle(&host, metadata); + assert_eq!(held.status().unwrap().request.raytrace.unwrap().surface_effects.unwrap().len(), 32); + drop(held); + settle(&host, 0); + } + + fn request() -> ImageRequest { + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Default::default(), + raytrace: None, + camera: Default::default(), + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + } + } + + fn id(owner: u64, serial: u64) -> JobId { + JobId { session: owner, serial, generation: serial } + } +} + +/// Provisional source-film observation, separate from complete-pass previews. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PartialPreviewProjection { + TopLeftRepresentativeV1, +} +#[derive(Clone, Debug, Serialize)] +pub struct PartialPreviewInfo { + pub frame: FrameInfo, + pub sequence: u64, + pub source_width: u32, + pub source_height: u32, + pub completed_passes: u32, + pub updated_prefix: u64, + pub projection: PartialPreviewProjection, +} +/// Fields drop in declaration order: payload allocations die before credit return. +pub struct RenderPartialPreview { + pub info: PartialPreviewInfo, + png: Vec, + covered: Vec, + _lease: ReturnReservation, +} +const _: [(); 1] = [(); (std::mem::size_of::() + 2 * crate::MAX_RENDER_ID_BYTES + 256 <= 2048) as usize]; +impl RenderPartialPreview { + pub fn png(&self) -> &[u8] { + &self.png + } + pub fn covered(&self) -> &[u32] { + &self.covered + } +} +struct PartialCreditState { + report: Option, + free: Reservation, + in_flight: bool, + closed: bool, +} +struct PartialCredits { + protected: Option, + plan: super::PartialPreviewPlan, + state: Mutex, + requested: AtomicBool, + exhausted: AtomicBool, + _metadata: Reservation, +} +const _: [(); 1] = + [(); (std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::>() + 128 + <= 1024) as usize]; +impl PartialCredits { + fn new(plan: super::PartialPreviewPlan, reservation: &mut Reservation) -> Result> { + Self::new_with_protection(plan, None, reservation) + } + fn new_protected(plan: super::ProtectedPreviewPlan, reservation: &mut Reservation) -> Result> { + plan.validate()?; + Self::new_with_protection(plan.preview_plan(), Some(plan), reservation) + } + fn new_with_protection( + plan: super::PartialPreviewPlan, + protected: Option, + reservation: &mut Reservation, + ) -> Result> { + plan.validate()?; + let metadata = reservation.split(1024)?; + let bytes = plan.slot_bytes()?.checked_mul(2).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial credit overflow"))?; + let free = reservation.split(bytes)?; + Ok(Arc::new(Self { + plan, + protected, + state: Mutex::new(PartialCreditState { report: None, free, in_flight: false, closed: false }), + requested: AtomicBool::new(false), + exhausted: AtomicBool::new(false), + _metadata: metadata, + })) + } + fn request(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || self.exhausted.load(Ordering::Acquire) { + return Ok(false); + } + self.requested.store(true, Ordering::Release); + Ok(true) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + let bytes = self.plan.slot_bytes()?; + if state.closed + || state.in_flight + || self.exhausted.load(Ordering::Acquire) + || !self.requested.load(Ordering::Acquire) + || state.free.bytes < bytes + { + return Ok(None); + } + let reservation = state.free.split(bytes)?; + state.in_flight = true; + self.requested.store(false, Ordering::Release); + Ok(Some(ReturnReservation { reservation: Some(reservation), credits: self.clone(), in_flight: true })) + } + fn retained_slots_blocked(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial retention lock poisoned"))?; + Ok(!state.closed + && !state.in_flight + && !self.exhausted.load(Ordering::Acquire) + && self.requested.load(Ordering::Acquire) + && state.free.bytes < self.plan.slot_bytes()?) + } + fn exhaust(&self) { + self.exhausted.store(true, Ordering::Release); + self.requested.store(false, Ordering::Release); + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + state.in_flight = false; + self.requested.store(false, Ordering::Release); + // Atomic release only: no image destruction or user work under this lock. + let _ = state.free.shrink(0); + } +} +/// Unique lease; Arc payload clones never create another independent slot. +struct ReturnReservation { + reservation: Option, + credits: Arc, + in_flight: bool, +} +impl ReturnReservation { + fn published(&mut self) -> Result<()> { + let mut state = self.credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || !state.in_flight || !self.in_flight { + return Err(JobError::new(ErrorCode::Cancelled, "partial preview credit is no longer current")); + } + state.in_flight = false; + self.in_flight = false; + Ok(()) + } +} +impl Drop for ReturnReservation { + fn drop(&mut self) { + let Some(mut reservation) = self.reservation.take() else { return }; + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if self.in_flight { + state.in_flight = false; + } + if !state.closed { + let limit = self.credits.plan.slot_bytes().ok().and_then(|v| v.checked_mul(2)); + if state.free.bytes.checked_add(reservation.bytes).zip(limit).is_some_and(|(total, limit)| total <= limit) { + if state.free.merge_from(&mut reservation).is_err() { + state.closed = true; + let _ = state.free.shrink(0); + } + } else { + state.closed = true; + let _ = state.free.shrink(0); + } + } + drop(state); + // A closed sink releases this uniquely held reservation globally. + } +} +struct PartialPending { + covered: Vec, + completed_passes: u32, + updated_prefix: u64, +} +// Error paths preserve the same payload-before-lease destruction order. +struct PartialPublication { + png: Vec, + pending: PartialPending, + lease: ReturnReservation, +} +struct PartialRunning { + last_pass_attempt: u32, + pending: Option, + lease: Option, + credits: Arc, + next_sequence: u64, +} +impl PartialRunning { + fn new(credits: Arc) -> Self { + Self { pending: None, lease: None, credits, next_sequence: 1, last_pass_attempt: 0 } + } +} +impl JobHandle { + /// Real producer usage, unavailable until a protected task was actually constructed. + pub fn protected_preview_report(&self) -> Result> { + self.0.partial.as_ref().map_or(Ok(None), |credits| { + let state = credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + Ok(state.report) + }) + } + /// Request presentation only; this is not a visual-authority certificate. + pub fn request_partial_preview(&self) -> Result { + let terminal = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?.progress.phase.terminal(); + if terminal { + return Ok(false); + } + self.0.partial.as_ref().map_or(Ok(false), |credits| credits.request()) + } + pub fn partial_preview_exhausted(&self) -> Result { + Ok(self.0.partial.as_ref().is_some_and(|credits| credits.exhausted.load(Ordering::Acquire))) + } + pub fn partial_preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial preview lock poisoned"))?; + let preview = data.partial_preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "partial preview identity does not match its job")); + } + Ok(preview) + } +} +impl Running { + #[cfg(feature = "raytrace-cpu")] + fn capture_partial(&mut self, png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64) -> Result<()> { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without its policy"))?.get_mut()?; + let plan = partial.credits.plan; + let source_pixels = u64::from(plan.source_width()) * u64::from(plan.source_height()); + let target = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without progressive intent"))? + .samples_per_pixel; + let covered_limit = plan.covered_bytes()?; + if partial.lease.is_none() + || partial.pending.is_some() + || completed_passes >= target + || updated_prefix >= source_pixels + || (completed_passes == 0 && updated_prefix == 0) + || covered.len() as u64 != plan.pixels() + || (covered.capacity() as u64).checked_mul(4).is_none_or(|v| v > covered_limit) + || png.capacity() as u64 > plan.encoded_limit()? + { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload exceeds its admitted frontier or capacities")); + } + // This sole sidecar verification scan was included in the producer's precharge. + for (index, count) in covered.iter().enumerate() { + self.handle.0.cancel.check()?; + let source = plan.source_index(index)? as u64; + let samples = completed_passes + .checked_add(u32::from(source < updated_prefix)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial sample count overflow"))?; + if *count > samples { + return Err(JobError::new(ErrorCode::Internal, "partial coverage exceeds committed source samples")); + } + } + partial.pending = Some(PartialPending { covered, completed_passes, updated_prefix }); + self.pending_png = Some(PendingPng::new(png)); + Ok(()) + } + fn publish_partial(&mut self, png: Vec, digest: Sha256) -> Result { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication state"))?.get_mut()?; + let pending = partial.pending.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial metadata"))?; + let lease = partial.lease.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication credit"))?; + let mut publication = PartialPublication { png, pending, lease }; + let sequence = partial.next_sequence; + let next = sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial preview sequence exhausted"))?; + let plan = partial.credits.plan; + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: plan.width(), + height: plan.height(), + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: publication.png.len() as u64, + png_sha256: format!("{:x}", digest.finalize()), + }; + let metadata = std::mem::size_of::() + .checked_add(64 + 2 * crate::MAX_RENDER_ID_BYTES) + .and_then(|v| v.checked_add(info.png_sha256.capacity())); + if metadata.is_none_or(|v| v > 2048) { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload metadata exceeds its slot")); + } + // No Data lock while touching the credit coordinator. + publication.lease.published()?; + let PartialPublication { png, pending, lease } = publication; + let preview = Arc::new(RenderPartialPreview { + info: PartialPreviewInfo { + frame: info, + sequence, + source_width: plan.source_width(), + source_height: plan.source_height(), + completed_passes: pending.completed_passes, + updated_prefix: pending.updated_prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }, + png, + covered: pending.covered, + _lease: lease, + }); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial publication lock poisoned"))?; + if self.handle.0.cancel.is_cancelled() || data.progress.phase.terminal() { + drop(data); + drop(preview); + return Err(JobError::new(ErrorCode::Cancelled, "late partial preview refused")); + } + let released = data.partial_preview.replace(preview); + partial.next_sequence = next; + // A demand arriving during encoding remains pending; never clear it here. + drop(data); + drop(released); + self.handle.0.notify(); + Ok(true) + } +} + +impl PartialCredits { + fn policy(&self) -> CpuPreviewPolicy { + self.protected.map_or(CpuPreviewPolicy::Shared(self.plan), CpuPreviewPolicy::Protected) + } + fn store_report(&self, report: Option) -> Result<()> { + let (plan, report) = match (self.protected, report) { + (None, None) => return Ok(()), + (Some(plan), Some(report)) => (plan, report), + _ => return Err(JobError::new(ErrorCode::Internal, "producer work report differs from its admitted policy")), + }; + let presentation = plan.presentation_limit()?; + let aggregate = plan.aggregate_limit()?; + let expected_v = plan.snapshot_work()?.checked_mul(u64::from(report.accepted_snapshots)); + let used = report.ordinary_used.checked_add(report.presentation_used); + if report.policy_version != 1 + || report.ordinary_limit != plan.ordinary_limit() + || report.presentation_limit != presentation + || report.aggregate_limit != aggregate + || report.quota_limit != plan.quota_limit() + || report.ordinary_used > report.ordinary_limit + || report.presentation_used > presentation + || used.is_none_or(|v| v > aggregate) + || expected_v != Some(report.presentation_used) + || report.accepted_snapshots > report.next_milestone_index + || report.next_milestone_index > report.quota_limit + || report.quota_exhausted != (report.accepted_snapshots == report.quota_limit) + || report.milestones_complete != (report.next_milestone_index == report.quota_limit) + { + return Err(JobError::new(ErrorCode::Internal, "protected work report violates its actual admission")); + } + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + if state.report.is_some_and(|previous| { + previous.ordinary_used > report.ordinary_used + || previous.presentation_used > report.presentation_used + || previous.accepted_snapshots > report.accepted_snapshots + || previous.next_milestone_index > report.next_milestone_index + }) { + drop(state); + return Err(JobError::new(ErrorCode::Internal, "protected work report counters moved backwards")); + } + state.report = Some(report); + if report.quota_exhausted { + self.exhaust(); + } + Ok(()) + } +} + +impl WorkTask { + #[cfg(feature = "raytrace-cpu")] + fn raytrace_with_slot( + task: crate::raytrace::image::ImageTask, + report_sink: Option<&PartialCredits>, + make_slot: impl FnOnce(crate::raytrace::image::ImageTask) -> Result>, + ) -> Result { + // ImageTask is already real, even if its host wrapper cannot be allocated. + if let Some(credits) = report_sink { + credits.store_report(task.protected_preview_report())?; + } + make_slot(task).map(Self::Raytrace) + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host_tests.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host_tests.rs new file mode 100644 index 000000000..53ae748c3 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/host_tests.rs @@ -0,0 +1,2537 @@ +use super::*; +use solidcraft_geom::{Aabb3, Mesh}; + +#[test] +fn raster_ev_status_and_task_capture_do_not_change_dynamic_fees_or_enter_registered_work() { + for rig in [None, Some(Vec::new())] { + let host = CpuHost::cooperative(); + let mut input = request(); + input.raster_lights = rig; + let zero = host.admit(&empty(), &input, JobOptions::default()).unwrap(); + input.raster_exposure_ev = 1.0; + assert_eq!(host.admit(&empty(), &input, JobOptions::default()).unwrap().estimated_total_bytes, zero.estimated_total_bytes); + let job = host.submit(id(840, 1), 1, empty(), input).unwrap(); + assert_eq!(job.status().unwrap().request.raster_exposure_ev, 1.0); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().request.raster_exposure_ev, 1.0); + } + let (host, _) = probe_host(1024); + let mut input = request(); + input.raster_exposure_ev = 1.0; + assert_eq!(host.admit(&empty(), &input, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(host.submit(id(841, 1), 1, empty(), input).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); +} + +#[test] +fn raster_rig_charges_original_and_task_capacity_then_retains_record_through_eviction() { + let host = CpuHost::cooperative(); + let legacy = host.admit(&empty(), &request(), JobOptions::default()).unwrap(); + let mut input = request(); + let mut lights = Vec::with_capacity(1); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }); + let capacity = lights.capacity(); + input.raster_lights = Some(lights); + let retained = (capacity * std::mem::size_of::()) as u64; + let task_fee = (8 * std::mem::size_of::()) as u64; + let admitted = host.admit(&empty(), &input, JobOptions::default()).unwrap(); + assert_eq!(admitted.estimated_total_bytes, legacy.estimated_total_bytes + task_fee); + let job = host.submit(id(830, 1), 1, empty(), input).unwrap(); + assert_eq!(host.admitted_bytes(), admitted.estimated_total_bytes + retained); + let status = job.status().unwrap(); + assert_eq!(status.request.raster_lights.as_ref().unwrap().len(), 1); + assert!(status.request.raster_lights.as_ref().unwrap().capacity() <= 8); + assert_eq!(job.0.request.raster_lights.as_ref().unwrap().capacity(), capacity); + // Caller-owned status metadata is outside the host lease lifetime. + drop(status); + drain(&host); + let held_frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert!(host.admitted_bytes() > retained); + drop(held_frame); + assert_eq!(host.admitted_bytes(), retained); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + // These counters test fees/lifetimes; declaration-order source review separately + // verifies request payload destruction precedes release of request credits. +} + +#[test] +fn raster_rig_cancel_retains_only_original_request_until_last_handle() { + let host = CpuHost::cooperative(); + let mut input = request(); + input.raster_lights = Some(vec![super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + let retained = input.raster_lights_retained_bytes().unwrap(); + let job = host.submit(id(831, 1), 1, empty(), input).unwrap(); + job.cancel().unwrap(); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(host.admitted_bytes(), retained); + drop(job); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn registered_and_interactive_routes_refuse_even_empty_raster_rigs_without_work() { + let (registered, _) = probe_host(1024); + let mut input = request(); + input.raster_lights = Some(Vec::new()); + assert_eq!(registered.admit(&empty(), &input, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.submit(id(832, 1), 1, empty(), input.clone()).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(registered.admitted_bytes(), 0); + assert!(!registered.pump(1).unwrap()); + assert!(super::super::interactive::cpu_request(&input).is_err()); + input.integrator = Integrator::Raytrace; + assert!(super::super::interactive::cpu_request(&input).is_err()); +} + +mod interactive { + use super::*; + use crate::job::{RaytraceOptions, interactive::*}; + use std::time::Duration; + + fn cpu() -> ImageRequest { + ImageRequest { integrator: Integrator::Raytrace, raytrace: Some(RaytraceOptions::default()), ..request() } + } + fn revision(visual_revision: u64) -> VisualRevision { + VisualRevision { scene_generation: 19, visual_revision } + } + fn ms(value: u64) -> Duration { + Duration::from_millis(value) + } + + #[test] + fn preview_fits_landscape_portrait_square_and_small_outputs_without_mutating_final_intent() { + for (width, height, expected) in + [(3840, 2160, (1024, 576)), (2160, 3840, (576, 1024)), (4096, 4096, (1024, 1024)), (81, 53, (81, 53)), (u32::MAX, 1, (1024, 1))] + { + let mut source = cpu(); + source.width = width; + source.height = height; + source.camera.roll = 0.37; + source.background = [19, 31, 97]; + source.studio_weights = Some([0.1, 0.2, 0.9]); + source.raytrace = Some(RaytraceOptions { primary_samples: 16, exposure_ev: -2.0, shadows: false, ..Default::default() }); + let before = serde_json::to_value(&source).unwrap(); + let preview = cpu_request(&source).unwrap(); + assert_eq!((preview.width, preview.height), expected); + assert_eq!(preview.camera, source.camera); + assert_eq!(preview.background, source.background); + assert_eq!(preview.studio_weights, source.studio_weights); + let options = preview.raytrace.unwrap(); + assert_eq!(options.progressive, Some(crate::job::CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); + assert_eq!(options.primary_samples, 1); + assert_eq!(options.exposure_ev, -2.0); + assert!(!options.shadows); + assert_eq!(serde_json::to_value(source).unwrap(), before); + } + } + + #[test] + fn preview_refuses_incompatible_transport_and_invalid_input_without_erasing_it() { + let mut source = cpu(); + // A valid fixed thin sheet remains deliberately unsupported by progressive. + // Area/LED now has its positive preservation case below. + source.raytrace.as_mut().unwrap().dielectrics = vec![crate::job::DielectricOptions { + body_index: 0, + body_name: "Original sheet".into(), + boundary: crate::job::DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }]; + source.raytrace.as_ref().unwrap().validate().unwrap(); + let before = serde_json::to_value(&source).unwrap(); + assert!(cpu_request(&source).is_err()); + assert_eq!(serde_json::to_value(&source).unwrap(), before); + for source in [ + ImageRequest { transparent_background: true, ..cpu() }, + ImageRequest { width: 0, ..cpu() }, + request(), + ImageRequest { raytrace: Some(RaytraceOptions { primary_samples: 3, ..Default::default() }), ..cpu() }, + ] { + assert!(cpu_request(&source).is_err()); + } + } + + #[test] + fn preview_preserves_rectangle_and_led_sources_and_all_nonsampling_options() { + use crate::job::{ + CpuProgressiveOptions, DirectionalLightOptions, PunctualLightOptions, RaytraceEnvironmentOptions, RectangleLightOptions, ReflectionBody, + ReflectionMode, ReflectionOptions, led_strip::LedStripOptions, + }; + let rectangle = RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }; + let led = LedStripOptions { + center_mm: [5.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [0.25, 0.5, 1.0], + intensity: 3.0, + }; + for area_samples in [1, 4, 16, 64] { + let mut source = cpu(); + source.width = 3840; + source.height = 2160; + source.camera.roll = 0.37; + source.background = [19, 31, 97]; + let mut options = RaytraceOptions { + primary_samples: 16, + exposure_ev: 1.25, + shadows: false, + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]), + punctual_lights: Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 20.0], + color: [1.0; 3], + intensity: 2.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.01, + cone: None, + }]), + area_lights: Some(vec![rectangle.clone()]), + area_samples: Some(area_samples), + seed: Some(73), + environment: Some(RaytraceEnvironmentOptions { color: [0.2, 0.3, 0.4], intensity: 2.0 }), + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: "Subject".into(), mode: ReflectionMode::RoughSpecular }], + samples: 16, + max_bounces: 3, + }), + ..Default::default() + }; + led.append_to(&mut options, area_samples).unwrap(); + options.validate().unwrap(); + source.raytrace = Some(options); + let before = serde_json::to_value(&source).unwrap(); + let mut expected = source.clone(); + expected.width = 1024; + expected.height = 576; + let expected_options = expected.raytrace.as_mut().unwrap(); + expected_options.primary_samples = 1; + expected_options.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }); + expected_options.reflections.as_mut().unwrap().samples = 1; + + let preview = cpu_request(&source).unwrap(); + assert_eq!( + serde_json::to_value(&preview).unwrap(), + serde_json::to_value(&expected).unwrap(), + "all request fields must survive except the explicitly chosen preview envelope" + ); + assert_eq!(preview.raytrace, expected.raytrace); + assert!(preview.environment.is_none() && preview.textures.is_none()); + let preview_options = preview.raytrace.as_ref().unwrap(); + assert_eq!(preview_options.area_lights.as_ref().unwrap().as_slice(), &[rectangle.clone(), led.rectangle().unwrap()]); + assert_eq!(preview_options.area_samples, Some(area_samples)); + assert_eq!(preview_options.seed, Some(73), "camera seed zero must not replace the area-pattern seed"); + assert_eq!(serde_json::to_value(&source).unwrap(), before, "the final request remains immutable"); + } + } + + #[test] + fn explicit_enable_settles_edits_and_keeps_only_one_capture_even_without_cad_revision_changes() { + let mut interactive = Interactive::new(9001); + interactive.edit(revision(1), ms(0)).unwrap(); + assert_eq!(interactive.state().unwrap(), State::Off); + assert!(interactive.capture(ms(1000)).unwrap().is_none()); + interactive.enable(revision(1), ms(1000)).unwrap(); + assert!(interactive.capture(ms(1199)).unwrap().is_none()); + interactive.edit(revision(2), ms(1199)).unwrap(); + assert!(interactive.capture(ms(1398)).unwrap().is_none()); + let b = interactive.capture(ms(1399)).unwrap().unwrap(); + assert_eq!(b.revision(), revision(2)); + assert!(interactive.accepts_capture(b)); + assert!(interactive.capture(ms(9999)).unwrap().is_none()); + interactive.edit(revision(3), ms(1400)).unwrap(); + assert!(!interactive.accepts_capture(b)); + // Delayed failure of B cannot poison C. + interactive.capture_failed(b, JobError::new(ErrorCode::InvalidScene, "old capture")); + assert_eq!(interactive.state().unwrap(), State::Updating); + let c = interactive.capture(ms(1600)).unwrap().unwrap(); + interactive.capture_failed(c, JobError::new(ErrorCode::InvalidScene, "current capture")); + assert!(!interactive.accepts_capture(c)); + assert_eq!(interactive.state().unwrap(), State::Error); + assert_eq!(interactive.error().unwrap().message, "current capture"); + assert!(interactive.capture(ms(9999)).unwrap().is_none(), "no automatic failure retry loop"); + interactive.resume(ms(2000)).unwrap(); + assert!(interactive.capture(ms(2200)).unwrap().is_some()); + } + + #[test] + fn pause_edits_final_priority_workspace_departure_and_clock_regression_do_not_start_jobs() { + let mut interactive = Interactive::new(9002); + interactive.enable(revision(1), ms(1000)).unwrap(); + assert!(interactive.capture(ms(999)).unwrap().is_none()); + interactive.pause().unwrap(); + interactive.edit(revision(2), ms(2000)).unwrap(); + assert_eq!(interactive.state().unwrap(), State::Paused); + assert!(interactive.capture(ms(3000)).unwrap().is_none()); + interactive.set_final_active(true, ms(3000)).unwrap(); + interactive.resume(ms(3000)).unwrap(); + assert!(interactive.capture(ms(4000)).unwrap().is_none()); + interactive.set_final_active(false, ms(4000)).unwrap(); + assert!(interactive.capture(ms(4199)).unwrap().is_none()); + assert_eq!(interactive.capture(ms(4200)).unwrap().unwrap().revision(), revision(2)); + interactive.disable().unwrap(); + assert_eq!(interactive.state().unwrap(), State::Off); + assert!(interactive.capture(ms(9999)).unwrap().is_none()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn host() -> CpuHost { + // Real native admission/worker steps, explicitly pumped like the existing + // checkpoint tests. No test clock sleeps, mock renderer or OS race. + ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn superseded_jobs_are_cancelled_and_foreign_jobs_remain_untouched() { + let host = host(); + let mut interactive = Interactive::new(9003); + interactive.enable(revision(1), ms(0)).unwrap(); + let a = interactive.capture(ms(200)).unwrap().unwrap(); + let first = host.submit(id(9003, 1), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(a, first.clone()).unwrap()); + interactive.edit(revision(2), ms(201)).unwrap(); + assert_eq!(first.status().unwrap().progress.phase, Phase::Cancelled); + assert!(interactive.current().is_none()); + let b = interactive.capture(ms(401)).unwrap().unwrap(); + // A delayed A admission must carry A's identity, not the pending B's. + let late = host.submit(a.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert_eq!(late.id(), a.job_id()); + assert_ne!(late.id(), b.job_id()); + assert!(!interactive.attach(a, late.clone()).unwrap()); + assert_eq!(late.status().unwrap().progress.phase, Phase::Cancelled); + // Drain cancelled queue entries before admitting another real job. + while let Some(work) = host.0.shared.queue.lock().unwrap().pop_front() { + drop(work); + } + let foreign = host.submit(id(9999, 1), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(b, foreign.clone()).unwrap()); + assert_eq!(foreign.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(interactive.state().unwrap(), State::Error); + interactive.disable().unwrap(); + drop(interactive); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(16).unwrap() { + break; + } + } + assert_eq!(foreign.status().unwrap().progress.phase, Phase::Completed, "the foreign job can still finish after our controller is closed"); + assert!(foreign.frame().unwrap().is_some()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn progressive_checkpoints_reach_target_and_final_suspension_releases_owned_work() { + let host = host(); + let mut interactive = Interactive::new(9004); + interactive.enable(revision(1), ms(0)).unwrap(); + let ticket = interactive.capture(ms(200)).unwrap().unwrap(); + let job = host.submit(id(9004, 1), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(ticket, job.clone()).unwrap()); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + let mut seen = Vec::new(); + for _ in 0..100_000 { + let more = running.advance(16).unwrap(); + if let Some(preview) = interactive.current().unwrap().preview().unwrap() { + let spp = preview.info.samples_per_pixel; + if seen.last() != Some(&spp) { + seen.push(spp); + } + } + if !more { + break; + } + } + assert_eq!(seen, [1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(interactive.state().unwrap(), State::TargetReached); + assert!(job.frame().unwrap().is_some()); + assert!(!interactive.attach(ticket, job.clone()).unwrap(), "duplicate acknowledgement cannot restart or cancel the accepted job"); + interactive.set_final_active(true, ms(300)).unwrap(); + assert_eq!(interactive.state().unwrap(), State::Paused); + assert!(interactive.current().is_none()); + assert!(interactive.capture(ms(9999)).unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn same_scene_stale_serial_generation_and_delayed_success_after_failure_are_rejected() { + for mismatch in 0..3 { + let host = host(); + let mut interactive = Interactive::new(9005); + interactive.enable(revision(1), ms(0)).unwrap(); + let ticket = interactive.capture(ms(200)).unwrap().unwrap(); + let mut job_id = ticket.job_id(); + let mut scene_generation = ticket.revision().scene_generation; + match mismatch { + 0 => job_id.serial += 1, + 1 => job_id.generation += 1, + _ => scene_generation += 1, + } + let job = host.submit(job_id, scene_generation, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(ticket, job.clone()).unwrap()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(interactive.state().unwrap(), State::Error); + } + let host = host(); + let mut interactive = Interactive::new(9006); + interactive.enable(revision(1), ms(0)).unwrap(); + let ticket = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.capture_failed(ticket, JobError::new(ErrorCode::InvalidScene, "capture failed")); + let late = host.submit(ticket.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(ticket, late.clone()).unwrap()); + assert_eq!(late.status().unwrap().progress.phase, Phase::Cancelled); + assert!(interactive.current().is_none()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn delayed_ticket_cannot_cancel_the_current_handle_but_still_cancels_its_obsolete_job() { + let host = host(); + let mut interactive = Interactive::new(9007); + interactive.enable(revision(1), ms(0)).unwrap(); + let old = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.edit(revision(2), ms(201)).unwrap(); + let current = interactive.capture(ms(401)).unwrap().unwrap(); + let job = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(current, job.clone()).unwrap()); + assert!(!interactive.attach(old, job.clone()).unwrap()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Queued); + let obsolete = host.submit(old.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(old, obsolete.clone()).unwrap()); + assert_eq!(obsolete.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(job.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(interactive.current().unwrap().id(), current.job_id()); + drop(interactive); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn stale_ticket_cannot_cancel_current_job_before_acknowledgement() { + let host = host(); + let mut interactive = Interactive::new(9008); + interactive.enable(revision(1), ms(0)).unwrap(); + let old = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.edit(revision(2), ms(201)).unwrap(); + let current = interactive.capture(ms(401)).unwrap().unwrap(); + let job = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + // B is admitted but not yet acknowledged. A delayed A callback has no + // authority to cancel B, including before current() can return a handle. + assert!(interactive.current().is_none()); + assert!(interactive.accepts_capture(current)); + assert!(!interactive.accepts_capture(old)); + assert!(!interactive.attach(old, job.clone()).unwrap()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Queued); + assert!(interactive.current().is_none()); + assert_eq!(interactive.state().unwrap(), State::Updating); + assert!(interactive.attach(current, job.clone()).unwrap()); + assert!(!interactive.accepts_capture(current)); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(16).unwrap() { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert!(job.frame().unwrap().is_some()); + assert_eq!(interactive.state().unwrap(), State::TargetReached); + drop(running); + drop(interactive); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn distinct_same_id_records_are_cancelled_but_current_handle_clones_finish() { + let host = host(); + let mut interactive = Interactive::new(9009); + interactive.enable(revision(1), ms(0)).unwrap(); + let old = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.edit(revision(2), ms(201)).unwrap(); + let current = interactive.capture(ms(401)).unwrap().unwrap(); + let accepted = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(current, accepted.clone()).unwrap()); + for callback in [old, current] { + // The host accepts an explicit JobId; submitting twice creates two + // records. Metadata equality is not actual admitted-work identity. + let duplicate = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert_eq!(accepted.id(), duplicate.id()); + assert!(!Arc::ptr_eq(&accepted.0, &duplicate.0)); + assert!(!interactive.attach(callback, duplicate.clone()).unwrap()); + assert_eq!(duplicate.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(accepted.status().unwrap().progress.phase, Phase::Queued); + assert!(Arc::ptr_eq(&interactive.current().unwrap().0, &accepted.0)); + // A second callback for the original Arc is harmless for both an + // obsolete ticket and the already acknowledged current ticket. + assert!(!interactive.attach(callback, accepted.clone()).unwrap()); + assert_eq!(accepted.status().unwrap().progress.phase, Phase::Queued); + } + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(16).unwrap() { + break; + } + } + assert_eq!(accepted.status().unwrap().progress.phase, Phase::Completed); + assert!(accepted.frame().unwrap().is_some()); + assert_eq!(interactive.state().unwrap(), State::TargetReached); + while let Some(work) = host.0.shared.queue.lock().unwrap().pop_front() { + assert_eq!(work.handle.status().unwrap().progress.phase, Phase::Cancelled); + drop(work); + } + drop(running); + drop(interactive); + drop(accepted); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod progressive_checkpoints { + use super::*; + use crate::job::{CpuProgressiveOptions, RaytraceOptions}; + + // The production native admission/Running path, manually advanced so tests + // can stop exactly between hashing and the cancellation/publication lock. + fn fixture(samples: u32) -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 4, + height: 4, + ..request() + }; + let expected = admit(&empty(), &request).unwrap().estimated_total_bytes; + let job = host.submit(id(7300, 1), 19, empty(), request).unwrap(); + assert_eq!(host.admitted_bytes(), expected); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (host, job, running) + } + + fn before_preview(running: &mut Running) { + for _ in 0..100_000 { + if running.pending_png.as_ref().is_some_and(|p| p.preview_samples.is_some()) { + return; + } + assert!(running.advance(1).unwrap()); + } + panic!("small CPU job did not reach its checkpoint"); + } + + #[test] + fn checkpoints_transfer_png_allocations_and_keep_every_external_lease() { + let (host, job, mut running) = fixture(3); + let initial = host.admitted_bytes(); + let mut held = Vec::new(); + for (sequence, samples) in [(1, 1), (2, 2)] { + before_preview(&mut running); + let pointer = running.pending_png.as_ref().unwrap().png.as_ptr(); + assert!(running.task.is_some(), "a preview must retain film, BVH and task state"); + assert!(running.advance(1).unwrap()); + let preview = job.preview().unwrap().unwrap(); + assert_eq!(preview.png().as_ptr(), pointer, "PNG ownership moves without cloning its allocation"); + assert_eq!(preview.info.frame_sequence, sequence); + assert_eq!(preview.info.samples_per_pixel, samples); + assert_eq!(preview.info.frame.job, job.id()); + assert_eq!(preview.info.frame.scene_generation, 19); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + assert!(job.frame().unwrap().is_none()); + assert!(job.status().unwrap().frame.is_none()); + assert_eq!(host.admitted_bytes(), initial, "splitting a prepaid lease does not change pool usage"); + held.push(preview); + } + let mut complete = false; + for _ in 0..100_000 { + if !running.advance(1).unwrap() { + complete = true; + break; + } + } + assert!(complete); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert!(job.preview().unwrap().is_none()); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, job.id()); + let retained: u64 = held.iter().map(|p| p._reservation.bytes).sum(); + assert_eq!(host.admitted_bytes(), retained + frame._reservation.bytes); + drop(running); + drop(job); + drop(frame); + assert_eq!(host.admitted_bytes(), retained); + while let Some(preview) = held.pop() { + let before = host.admitted_bytes(); + let bytes = preview._reservation.bytes; + drop(preview); + assert_eq!(host.admitted_bytes(), before - bytes); + } + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn cancellation_before_or_after_digest_cannot_publish_a_late_preview() { + for finish_digest in [false, true] { + let (host, job, mut running) = fixture(3); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let held = job.preview().unwrap().unwrap(); + before_preview(&mut running); + if finish_digest { + let pending = running.pending_png.as_mut().unwrap(); + while !pending.step(1, &job.0.cancel).unwrap() {} + assert_eq!(pending.hashed, pending.png.len()); + } + job.cancel().unwrap(); + assert!(job.preview().unwrap().is_none(), "cancel removes the provisional slot immediately"); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), held._reservation.bytes); + assert_eq!(held.info.samples_per_pixel, 1); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + + #[test] + fn an_invalid_checkpoint_sequence_fails_without_replacing_the_old_snapshot() { + let (host, job, mut running) = fixture(4); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let held = job.preview().unwrap().unwrap(); + before_preview(&mut running); + running.pending_png.as_mut().unwrap().preview_samples = Some(3); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + assert!(job.preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(held.info.samples_per_pixel, 1); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), held._reservation.bytes); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } +} + +fn request() -> ImageRequest { + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Default::default(), + raytrace: None, + textures: None, + environment: None, + camera: Default::default(), + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + } +} + +#[test] +fn legacy_image_requests_default_to_raster_and_reject_unknown_integrators() { + let mut value = serde_json::to_value(request()).unwrap(); + value.as_object_mut().unwrap().remove("integrator"); + let decoded: ImageRequest = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(decoded.integrator, Integrator::Raster); + value["integrator"] = serde_json::json!("gpu_pathtrace"); + assert!(serde_json::from_value::(value).is_err()); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn cooperative_raytrace_descriptor_matches_native_only_validation() { + let host = CpuHost::cooperative(); + assert!(host.validate_integrator(Integrator::Raytrace).is_err()); + assert!(matches!(host.descriptor_for(Integrator::Raytrace).unwrap().availability, Availability::Unavailable { .. })); + assert!(host.validate_integrator(Integrator::Raster).is_ok()); + assert!(!host.descriptor_for(Integrator::Raytrace).unwrap().profiles.iter().any(|p| p.features.contains(&crate::RenderFeature::Refraction))); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn native_raytrace_refraction_capability_resolves_only_preview_images() { + let host = CpuHost::for_platform().unwrap(); + let descriptor = host.descriptor_for(Integrator::Raytrace).unwrap(); + assert_eq!(descriptor.availability, Availability::Available); + assert!(descriptor.profiles.iter().any(|profile| profile.features.contains(&crate::RenderFeature::Refraction))); + let mut backend = crate::builtin_backend(); + backend.executors = vec![descriptor]; + let mut request = crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: 1, + height: 1, + format: Some(RenderFormat::Png), + features: vec![crate::RenderFeature::Refraction], + policy: Default::default(), + }; + let resolved = crate::resolve_request(std::slice::from_ref(&backend), &request).unwrap(); + assert_eq!(resolved.executor.as_str(), "cpu-raytrace"); + request.mode = RenderMode::Final; + assert!(crate::resolve_request(std::slice::from_ref(&backend), &request).is_err()); + request.mode = RenderMode::Preview; + backend.executors = vec![host.descriptor_for(Integrator::Raster).unwrap()]; + assert!(crate::resolve_request(&[backend], &request).is_err(), "CPU raster must not advertise physical refraction"); + assert_eq!(host.admitted_bytes(), 0, "capability discovery never starts a render"); +} + +#[cfg(not(feature = "raytrace-cpu"))] +#[test] +fn compiled_out_raytracing_never_enters_the_host_queue() { + let host = CpuHost::cooperative(); + let mut request = request(); + request.integrator = Integrator::Raytrace; + assert!(host.validate_integrator(Integrator::Raytrace).unwrap_err().message.contains("not compiled in")); + assert!(host.descriptor_for(Integrator::Raytrace).is_err()); + let error = host.submit(JobId { session: 1, serial: 1, generation: 1 }, 0, empty(), request).err().unwrap(); + assert_eq!(error.code, ErrorCode::HostUnavailable); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); +} +fn empty() -> ProductScene { + ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY } +} +fn id(owner: u64, serial: u64) -> JobId { + JobId { session: owner, serial, generation: serial } +} +fn drain(host: &CpuHost) { + for _ in 0..10_000 { + if !host.pump(4096).unwrap() { + return; + } + } + panic!("small cooperative jobs did not drain"); +} + +#[test] +fn queue_is_bounded_and_cancelled_entries_release_their_reservations() { + let host = CpuHost::cooperative(); + let a = host.submit(id(10, 1), 100, empty(), request()).unwrap(); + let b = host.submit(id(20, 1), 200, empty(), request()).unwrap(); + let before = host.admitted_bytes(); + assert_eq!(host.submit(id(30, 1), 300, empty(), request()).err().unwrap().code, ErrorCode::QueueFull); + assert_eq!(host.admitted_bytes(), before); + assert_eq!(a.cancel().unwrap().progress.phase, Phase::Cancelled); + let c = host.submit(id(30, 1), 300, empty(), request()).unwrap(); + drain(&host); + assert_eq!(a.status().unwrap().progress.phase, Phase::Cancelled); + for (handle, owner, generation) in [(&b, 20, 200), (&c, 30, 300)] { + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, id(owner, 1)); + assert_eq!(frame.info.scene_generation, generation); + assert_eq!(frame.info.executor.as_str(), "cpu-product"); + assert_eq!(image::load_from_memory(frame.png()).unwrap().width(), 16); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(handle.status().unwrap().frame.unwrap().png_sha256, frame.info.png_sha256); + } + assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < before); + let frame = b.frame().unwrap().unwrap(); + drop(b); + drop(c); + assert!(host.admitted_bytes() > 0, "an externally retained frame retains its lease"); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn cancellation_while_encoding_cannot_publish_a_late_frame() { + let host = CpuHost::cooperative(); + let job = host.submit(id(1, 1), 8, empty(), request()).unwrap(); + for _ in 0..10_000 { + host.pump(64).unwrap(); + let status = job.status().unwrap(); + if status.progress.phase == Phase::Encoding && status.progress.done > 0 { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Encoding); + assert_eq!(job.cancel().unwrap().progress.phase, Phase::Cancelling); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn malformed_preparation_fails_the_job_without_stopping_the_host() { + let host = CpuHost::cooperative(); + let scene = ProductScene { + bounds: Aabb3::EMPTY, + meshes: vec![crate::ProductMesh { + name: "Broken".into(), + mesh: Arc::new(Mesh { triangles: vec![[99, 99, 99]], ..Default::default() }), + color: [0; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + }; + let broken = host.submit(id(1, 1), 1, scene, request()).unwrap(); + drain(&host); + let status = broken.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Failed); + assert_eq!(status.error.unwrap().code, ErrorCode::InvalidScene); + assert!(status.frame.is_none(), "a failed preparation path has no cached PNG identity"); + assert!(broken.frame().unwrap().is_none()); + assert!(host.is_available()); + let healthy = host.submit(id(1, 2), 1, empty(), request()).unwrap(); + drain(&host); + assert_eq!(healthy.status().unwrap().progress.phase, Phase::Completed); +} + +#[test] +fn closing_the_host_cancels_active_and_queued_work() { + let host = CpuHost::cooperative(); + let budget = host.0.shared.budget.clone(); + let active = host.submit(id(1, 1), 1, empty(), request()).unwrap(); + let queued = host.submit(id(2, 1), 1, empty(), request()).unwrap(); + host.pump(1).unwrap(); + drop(host); + assert_eq!(active.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(queued.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(budget.used.load(Ordering::Acquire), 0); +} + +#[test] +fn a_foreign_frame_is_rejected_even_if_a_broken_host_puts_it_in_the_result_slot() { + let host = CpuHost::cooperative(); + let job = host.submit(id(1, 1), 1, empty(), request()).unwrap(); + drain(&host); + { + let mut data = job.0.data.lock().unwrap(); + let frame = Arc::get_mut(data.frame.as_mut().unwrap()).unwrap(); + frame.info.job.session = 2; + } + assert_eq!(job.frame().err().unwrap().code, ErrorCode::WrongOwner); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_job_finishes_without_any_poll_or_ui_pump() { + let host = CpuHost::for_platform().unwrap(); + assert_eq!(host.kind(), HostKind::NativeWorker); + let job = host.submit(id(1, 1), 12, empty(), request()).unwrap(); + // A generous deadlock watchdog, not a performance assertion. + let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(job.frame().unwrap().unwrap().info.scene_generation, 12); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256); +} + +/// Isolate the existing integrator-to-host completion boundary with a real PNG +/// from the production encoder. This does not pretend to render the noisy pixels. +fn pending_digest_fixture() -> (CpuHost, JobHandle, Running, usize) { + let host = CpuHost::cooperative(); + let mut request = request(); + request.width = 256; + request.height = 128; + let mut rgba = vec![255; request.width as usize * request.height as usize * 4]; + let mut seed = 0x6a09_e667u32; + for pixel in rgba.as_chunks_mut::<4>().0 { + for channel in pixel.iter_mut().take(3) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + *channel = seed as u8; + } + } + let mut encoder = super::super::encoding::PngEncoding::new( + request.width, + request.height, + u64::from(request.width) * u64::from(request.height) * 8 + 65_536, + CancelToken::default(), + ) + .unwrap(); + let png = loop { + if let Some(png) = encoder.step(&rgba).unwrap() { + break png; + } + }; + assert!(png.len() > PNG_HASH_CHUNK_BYTES * PNG_HASH_CHUNKS_PER_ADVANCE); + let length = png.len(); + let job = host.submit(id(61, 1), 99, empty(), request).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + // Exactly the same state transition used when WorkTask returns Complete. + running.task = None; + running.pending_png = Some(PendingPng::new(png)); + (host, job, running, length) +} + +#[test] +fn png_digest_is_incremental_and_keeps_the_original_allocation_and_lease_until_completion() { + let (host, job, mut running, length) = pending_digest_fixture(); + let before = host.admitted_bytes(); + let pointer = running.pending_png.as_ref().unwrap().png.as_ptr(); + assert!(running.advance(0).unwrap()); + assert_eq!(running.pending_png.as_ref().unwrap().hashed, 0, "zero units cannot hash a chunk"); + assert_eq!(host.admitted_bytes(), before); + assert!(job.frame().unwrap().is_none()); + assert!(running.advance(usize::MAX).unwrap()); + assert_eq!(running.pending_png.as_ref().unwrap().hashed, PNG_HASH_CHUNK_BYTES * PNG_HASH_CHUNKS_PER_ADVANCE); + assert_eq!(host.admitted_bytes(), before, "hashing must retain the full original work lease"); + assert!(job.frame().unwrap().is_none()); + let mut previous = job.status().unwrap().progress.done; + while running.advance(1).unwrap() { + let progress = job.status().unwrap().progress; + assert_eq!(progress.phase, Phase::Encoding); + assert_eq!(progress.total, length as u64); + assert_eq!(progress.done - previous, PNG_HASH_CHUNK_BYTES as u64); + assert_eq!(host.admitted_bytes(), before); + assert!(job.frame().unwrap().is_none()); + previous = progress.done; + } + assert!(running.task.is_none() && running.pending_png.is_none() && running.reservation.is_none()); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.png().as_ptr(), pointer, "the original Vec moves into the retained frame without cloning"); + assert_eq!(frame.info.png_bytes, length as u64); + assert_eq!(frame.info.png_sha256.len(), 64); + assert!(frame.info.png_sha256.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256); + let decoded = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (256, 128)); + assert!(decoded.pixels().all(|p| p.0[3] == 255)); + assert!(decoded.pixels().any(|p| p.0[..3] != decoded.get_pixel(0, 0).0[..3])); + let actual_metadata = + std::mem::size_of::() + std::mem::size_of::() + frame.info.png_sha256.capacity() + 2 * crate::MAX_RENDER_ID_BYTES + 32; + assert!(actual_metadata <= FRAME_METADATA_BYTES as usize, "digest Vec/offset/state and actual hex allocation must be admitted"); + assert_eq!(host.admitted_bytes(), frame.png.capacity() as u64 + FRAME_METADATA_BYTES); + for _ in 0..3 { + let current = job.status().unwrap(); + assert_eq!(current.frame.unwrap().png_sha256, frame.info.png_sha256); + assert_eq!(frame.png().as_ptr(), pointer); + } + drop(running); + drop(job); + assert!(host.admitted_bytes() > 0); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn cancellation_during_png_hashing_and_host_disposal_cannot_publish_a_frame() { + for close_host in [false, true] { + let (host, job, running, _) = pending_digest_fixture(); + let budget = host.0.shared.budget.clone(); + *host.0.running.lock().unwrap() = Some(running); + assert!(host.pump(1).unwrap()); + assert!(host.0.running.lock().unwrap().as_ref().unwrap().pending_png.as_ref().unwrap().hashed > 0); + assert_eq!(job.status().unwrap().progress.phase, Phase::Encoding); + assert!(job.frame().unwrap().is_none()); + if close_host { + drop(host); + } else { + assert_eq!(job.cancel().unwrap().progress.phase, Phase::Cancelling); + assert!(!host.pump(1).unwrap()); + drop(host); + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } +} + +#[test] +fn a_cancel_after_the_last_digest_chunk_still_wins_the_publication_lock() { + let (host, job, mut running, _) = pending_digest_fixture(); + let pending = running.pending_png.as_mut().unwrap(); + while !pending.step(1, &job.0.cancel).unwrap() {} + assert_eq!(pending.hashed, pending.png.len()); + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + drop(running); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn png_digest_metadata_fits_the_existing_allowance_without_changing_admission() { + // Fixed digest/offset state and the completed frame (including its bounded + // hex string and backend/executor IDs) fit the existing 1024-byte allowance. + assert!(std::mem::size_of::() <= 512); + assert!( + std::mem::size_of::() + std::mem::size_of::() + 64 + 2 * crate::MAX_RENDER_ID_BYTES + 32 + <= FRAME_METADATA_BYTES as usize + ); + let host = CpuHost::cooperative(); + let expected = admit(&empty(), &request()).unwrap().estimated_total_bytes; + let job = host.submit(id(70, 1), 1, empty(), request()).unwrap(); + assert_eq!(host.admitted_bytes(), expected); + assert!(job.status().unwrap().frame.is_none()); + job.cancel().unwrap(); + drain(&host); + assert_eq!(host.admitted_bytes(), 0); +} + +/// 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, + budget: Arc>>, + estimated: u64, +} +struct ProbeTask { + admitted_at_drop: Arc, + budget: Arc>>, + 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 { + 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 { + CpuExecutor.descriptor() + } + fn admit(&self, _: &ProductScene, _: &ImageRequest, _: JobOptions) -> Result { + 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> { + 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) { + 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); +} + +#[test] +fn cpu_and_registered_hosts_keep_separate_job_limits() { + let cpu = CpuHost::cooperative(); + let (registered, _) = probe_host(400 * 1024 * 1024); + assert_eq!(cpu.job_limit_bytes(), 384 * 1024 * 1024); + assert_eq!(registered.job_limit_bytes(), 512 * 1024 * 1024); + assert_eq!(cpu.pool_limit_bytes(), registered.pool_limit_bytes()); + assert_eq!(registered.pool_limit_bytes(), 512 * 1024 * 1024); + assert_eq!(registered.admit(&empty(), &request(), JobOptions::default()).unwrap().estimated_total_bytes, 400 * 1024 * 1024); + assert_eq!(admit_request_sum(400 * 1024 * 1024, 0).unwrap_err().code, ErrorCode::LimitExceeded); + let (over_budget, _) = probe_host(512 * 1024 * 1024 + 1); + assert_eq!(over_budget.admit(&empty(), &request(), JobOptions::default()).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(registered.admitted_bytes(), 0); +} + +#[test] +fn registered_hosts_refuse_cpu_integrators_and_options_before_reservation() { + let (registered, _) = probe_host(1024 * 1024); + let mut raytrace = request(); + raytrace.integrator = Integrator::Raytrace; + assert_eq!(registered.validate_integrator(Integrator::Raytrace).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.descriptor_for(Integrator::Raytrace).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.admit(&empty(), &raytrace, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.submit(id(250, 1), 1, empty(), raytrace).err().unwrap().code, ErrorCode::InvalidRequest); + let mut options = request(); + options.raytrace = Some(super::super::RaytraceOptions::default()); + assert_eq!(registered.admit(&empty(), &options, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.admitted_bytes(), 0); + assert!(!registered.pump(1).unwrap()); +} + +#[test] +fn environment_payload_is_owned_by_admitted_work_not_retained_status() { + struct ResourceExecutor; + impl ImageExecutor for ResourceExecutor { + fn descriptor(&self) -> Result { + let mut descriptor = CpuExecutor.descriptor()?; + descriptor.profiles[0].features.push(crate::RenderFeature::Hdri); + Ok(descriptor) + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + let mut admission = admit(scene, &ImageRequest { environment: None, textures: None, ..request.clone() })?; + admission.estimated_total_bytes += request.environment.as_ref().map_or(0, |source| source.admitted_bytes()); + Ok(admission) + } + fn begin(&self, scene: ProductScene, mut request: ImageRequest, _: JobOptions, cancel: CancelToken) -> Result> { + request.environment = None; + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } + } + for cancelled in [false, true] { + let host = ImageHost(Arc::new(Owner { + executor: Some(Arc::new(ResourceExecutor)), + shared: ImageHost::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })); + let source = Arc::new(crate::lighting::environment::EnvironmentSource::sky(Default::default(), 0.0, 1.0).unwrap()); + let weak = Arc::downgrade(&source); + let mut input = request(); + input.environment = Some(source); + let job = host.submit(id(1, 1), 1, empty(), input).unwrap(); + let status = job.status().unwrap(); + assert!(status.request.environment.is_none()); + assert!(matches!(status.environment.as_ref(), Some(JobEnvironmentInfo::Gpu(info)) if info.kind == "original_gradient_sky")); + assert!(weak.upgrade().is_some(), "queuedwork owns source"); + if cancelled { + job.cancel().unwrap(); + } + drain(&host); + assert!(weak.upgrade().is_none(), "completed/cancelled work releases captured source despite retained status/job"); + assert_eq!(job.status().unwrap().progress.phase, if cancelled { Phase::Cancelled } else { Phase::Completed }); + } +} + +#[test] +fn texture_payload_is_owned_by_admitted_work_not_retained_status() { + struct ResourceExecutor; + impl ImageExecutor for ResourceExecutor { + fn descriptor(&self) -> Result { + let mut descriptor = CpuExecutor.descriptor()?; + descriptor.profiles[0].features.push(crate::RenderFeature::Hdri); + Ok(descriptor) + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + let mut admission = admit(scene, &ImageRequest { environment: None, textures: None, ..request.clone() })?; + admission.estimated_total_bytes += request.textures.as_ref().map_or(0, |source| source.working_bytes()); + Ok(admission) + } + fn begin(&self, scene: ProductScene, mut request: ImageRequest, _: JobOptions, cancel: CancelToken) -> Result> { + request.textures = None; + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } + } + for cancelled in [false, true] { + let host = ImageHost(Arc::new(Owner { + executor: Some(Arc::new(ResourceExecutor)), + shared: ImageHost::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })); + use crate::job::textures::{PlanarFrame, RuntimeTextures, TextureBinding, TextureMap}; + use image::ImageEncoder; + let mut bytes = Vec::new(); + image::codecs::png::PngEncoder::new(&mut bytes).write_image(&[128, 128, 255, 255], 1, 1, image::ExtendedColorType::Rgba8).unwrap(); + let source = Arc::new( + RuntimeTextures::new(vec![TextureBinding { + body_index: 0, + body_name: "unused test resource".into(), + frame: PlanarFrame { origin: [0.; 3], u: [1., 0., 0.], v: [0., 1., 0.] }, + normal_strength: 1., + base_color: Some(TextureMap::new(bytes, crate::texture_input::MapRole::BaseColor).unwrap()), + normal: None, + roughness: None, + metallic: None, + base_color_mode: Default::default(), + flip_v: false, + }]) + .unwrap(), + ); + let weak = Arc::downgrade(&source); + let mut input = request(); + input.textures = Some(source); + let job = host.submit(id(1, 1), 1, empty(), input).unwrap(); + let status = job.status().unwrap(); + assert!(status.request.textures.is_none()); + assert_eq!(status.textures.as_ref().unwrap().bodies, 1); + assert!(weak.upgrade().is_some(), "queuedwork owns source"); + if cancelled { + job.cancel().unwrap(); + } + drain(&host); + assert!(weak.upgrade().is_none(), "completed/cancelled work releases captured source despite retained status/job"); + assert_eq!(job.status().unwrap().progress.phase, if cancelled { Phase::Cancelled } else { Phase::Completed }); + } +} + +#[test] +fn cpu_film_snapshots_refuse_registered_executors_without_acquiring_a_lease() { + let (host, _) = probe_host(1 << 20); + let failure = host.reserve_film_snapshot(1024).err().unwrap(); + assert_eq!(failure.code, ErrorCode::InvalidRequest); + assert!(failure.message.contains("builtin CPU host")); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn native_cpu_envelopes_do_not_expand_registered_or_cooperative_pools() { + use super::super::{CpuBudget, NATIVE_CPU_POOL_BYTES, RaytraceOptions}; + let cpu = CpuHost::for_platform().unwrap(); + let cooperative = CpuHost::cooperative(); + let (registered, _) = probe_host(1024); + assert_eq!(cpu.pool_limit_bytes(), NATIVE_CPU_POOL_BYTES); + assert_eq!(cooperative.pool_limit_bytes(), 512 * 1024 * 1024); + assert_eq!(registered.pool_limit_bytes(), 512 * 1024 * 1024); + assert!(cpu.check_request_sum(400 * 1024 * 1024, 0, CpuBudget::Compact).is_err()); + assert!(cpu.check_request_sum(400 * 1024 * 1024, 0, CpuBudget::Studio).is_ok()); + assert!(cpu.check_request_sum(u64::MAX, 1, CpuBudget::Workstation).is_err()); + let mut r = request(); + r.integrator = Integrator::Raytrace; + r.width = 3840; + r.height = 2160; + r.raytrace = Some(RaytraceOptions { budget: CpuBudget::Studio, ..Default::default() }); + assert_eq!(cpu.descriptor_for_request(&r).unwrap().limits, CpuBudget::Studio.image_limits(false)); + r.raytrace.as_mut().unwrap().budget = CpuBudget::Compact; + assert!(cpu.descriptor_for_request(&r).is_err()); + assert_eq!(cpu.admitted_bytes(), 0); +} + +#[cfg(all(not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn registered_large_pool_is_explicit_finite_and_accounted() { + struct Envelope(u64); + impl ImageExecutor for Envelope { + fn memory_limit_bytes(&self) -> u64 { + self.0 + } + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, _: &ProductScene, _: &ImageRequest, _: JobOptions) -> Result { + Ok(Admission { + triangles: 0, + face_appearances: 0, + geometry_bytes: 0, + pixel_scratch_bytes: 0, + preparation_bytes: 0, + estimated_total_bytes: 600 * 1024 * 1024, + encoded_limit: 4096, + }) + } + fn begin(&self, _: ProductScene, _: ImageRequest, _: JobOptions, _: CancelToken) -> Result> { + Err(JobError::new(ErrorCode::InvalidRequest, "admission-only fixture")) + } + } + for limit in [0, super::super::NATIVE_CPU_POOL_BYTES + 1] { + assert!(ImageHost::with_executor(Arc::new(Envelope(limit))).is_err()); + } + let host = ImageHost::with_executor(Arc::new(Envelope(1024 * 1024 * 1024))).unwrap(); + assert_eq!(host.pool_limit_bytes(), 1024 * 1024 * 1024); + assert!(host.admit(&empty(), &request(), JobOptions::default()).is_ok()); + assert_eq!(host.admitted_bytes(), 0, "preflight does not allocate or reserve"); + let lease = host.0.shared.budget.reserve(600 * 1024 * 1024).unwrap(); + assert!(host.0.shared.budget.reserve(600 * 1024 * 1024).is_err()); + drop(lease); + assert_eq!(host.admitted_bytes(), 0); +} + +mod partial_preview_contract { + use super::*; + use crate::job::PartialPreviewPlan; + + fn credits() -> (Arc, Reservation, Arc) { + let plan = PartialPreviewPlan::new(4, 1).unwrap(); + let total = 2 * plan.slot_bytes().unwrap() + 1024 + 17; + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: total }); + let mut work = budget.reserve(total).unwrap(); + let credits = PartialCredits::new(plan, &mut work).unwrap(); + assert_eq!(work.bytes, 17); + (budget, work, credits) + } + fn take(credits: &Arc) -> ReturnReservation { + assert!(credits.request().unwrap()); + credits.acquire().unwrap().unwrap() + } + fn payload(mut lease: ReturnReservation, sequence: u64) -> Arc { + lease.published().unwrap(); + Arc::new(RenderPartialPreview { + info: PartialPreviewInfo { + frame: FrameInfo { + job: id(7724, 1), + scene_generation: 19, + backend: crate::builtin_backend().id, + executor: ExecutorId::new("cpu-raytrace").unwrap(), + width: 4, + height: 1, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: 4, + png_sha256: "unit-lease-fixture".into(), + }, + sequence, + source_width: 4, + source_height: 1, + completed_passes: 0, + updated_prefix: 1, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }, + png: vec![1, 2, 3, 4], + covered: vec![1, 0, 0, 0], + _lease: lease, + }) + } + #[test] + fn plan_is_canonical_no_upscale_and_maps_top_left_without_source_scan() { + for (w, h, expected) in [(16384, 4096, (1024, 256)), (2160, 3840, (576, 1024)), (4, 1, (4, 1)), (u32::MAX, 1, (1024, 1))] { + let plan = PartialPreviewPlan::new(w, h).unwrap(); + assert_eq!((plan.width(), plan.height()), expected); + assert_eq!((plan.source_width(), plan.source_height()), (w, h)); + assert_eq!(plan.source_index(0).unwrap(), 0); + assert!(plan.source_index(plan.pixels() as usize).is_err()); + assert!(plan.pixels() <= 1024 * 1024); + } + let plan = PartialPreviewPlan::new(16384, 4096).unwrap(); + assert_eq!(plan.source_index(1025).unwrap(), 16 * 16384 + 16); + assert_eq!(plan.snapshot_work().unwrap(), 14 * 1024 * 256 + 65538); + assert!(PartialPreviewPlan::new(0, 1).is_err()); + assert!(PartialPreviewPlan::new(1, 0).is_err()); + } + #[test] + fn same_budget_merge_moves_ownership_once_and_wrong_pool_preserves_both() { + let a = Arc::new(Budget { used: AtomicU64::new(0), limit: 100 }); + let b = Arc::new(Budget { used: AtomicU64::new(0), limit: 100 }); + let mut retained = a.reserve(80).unwrap(); + let mut donor = retained.split(30).unwrap(); + let mut foreign = b.reserve(9).unwrap(); + assert_eq!(retained.merge_from(&mut foreign).unwrap_err().code, ErrorCode::WrongOwner); + assert_eq!((retained.bytes, foreign.bytes), (50, 9)); + retained.merge_from(&mut donor).unwrap(); + assert_eq!((retained.bytes, donor.bytes, a.used.load(Ordering::Acquire)), (80, 0, 80)); + assert!(retained.split(81).is_err()); + assert_eq!(retained.bytes, 80); + drop(donor); + assert_eq!(a.used.load(Ordering::Acquire), 80); + drop(retained); + drop(foreign); + assert_eq!((a.used.load(Ordering::Acquire), b.used.load(Ordering::Acquire)), (0, 0)); + } + #[test] + fn two_total_slots_include_inflight_and_clones_do_not_mint_capacity() { + let (budget, work, credits) = credits(); + let total = budget.used.load(Ordering::Acquire); + let first = take(&credits); + assert!(credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none(), "one encoder even with another free slot"); + let first = payload(first, 1); + let held = first.clone(); + let second = payload(take(&credits), 2); + assert!(credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none()); + assert!(credits.requested.load(Ordering::Acquire), "full credit preserves coalesced demand"); + drop(first); + assert!(credits.acquire().unwrap().is_none(), "a clone retains the same first slot"); + assert_eq!(budget.used.load(Ordering::Acquire), total); + drop(held); + let third = credits.acquire().unwrap().unwrap(); + assert_eq!(budget.used.load(Ordering::Acquire), total, "return/transfer does not reserve globally again"); + assert_eq!(second.png(), &[1, 2, 3, 4]); + drop(third); + drop(second); + credits.close(); + assert_eq!(budget.used.load(Ordering::Acquire), 17 + 1024); + drop(credits); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn demand_during_inflight_survives_publication_and_terminal_held_frames_stay_billed() { + let (budget, work, credits) = credits(); + let first = take(&credits); + assert!(!credits.requested.load(Ordering::Acquire)); + assert!(credits.request().unwrap()); + let first = payload(first, 1); + assert!(credits.requested.load(Ordering::Acquire)); + let second = payload(credits.acquire().unwrap().unwrap(), 2); + let per_slot = credits.plan.slot_bytes().unwrap(); + credits.close(); + assert!(!credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none()); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 2 * per_slot + 1024); + drop(credits); + assert_eq!(first.covered(), &[1, 0, 0, 0]); + drop(first); + assert_eq!(budget.used.load(Ordering::Acquire), per_slot + 1024); + drop(second); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn optional_exhaustion_is_real_and_legacy_request_remains_noop() { + let (_, work, credits) = credits(); + assert!(credits.request().unwrap()); + credits.exhaust(); + assert!(credits.exhausted.load(Ordering::Acquire)); + assert!(!credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none()); + credits.close(); + drop(work); + let host = CpuHost::cooperative(); + let job = host.submit(id(7724, 2), 19, empty(), request()).unwrap(); + let before = serde_json::to_value(job.status().unwrap()).unwrap(); + assert!(!job.request_partial_preview().unwrap()); + assert!(!job.partial_preview_exhausted().unwrap()); + assert!(job.partial_preview().unwrap().is_none()); + assert_eq!(serde_json::to_value(job.status().unwrap()).unwrap(), before); + job.cancel().unwrap(); + assert!(!job.request_partial_preview().unwrap()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn real_fixture() -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(crate::job::RaytraceOptions { + progressive: Some(crate::job::CpuProgressiveOptions { samples_per_pixel: 5, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 16, + height: 16, + ..request() + }; + let job = host.submit_cpu_partial_with_environment_and_options(id(7724, 3), 19, empty(), request, JobOptions::default(), None).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (host, job, running) + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn real_partial_png_carries_unknown_and_two_held_payloads_do_not_block_final() { + let (host, job, mut running) = real_fixture(); + assert!(job.request_partial_preview().unwrap()); + let mut during = false; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if !during && running.partial.as_ref().unwrap().0[0].lease.is_some() { + assert!(job.request_partial_preview().unwrap()); + during = true; + } + if job.partial_preview().unwrap().is_some() { + break; + } + } + let first = job.partial_preview().unwrap().unwrap(); + assert!(during); + assert_eq!(first.info.sequence, 1); + assert_eq!(first.info.completed_passes, 0); + assert!(first.info.updated_prefix > 0 && first.info.updated_prefix < 256); + assert!(job.preview().unwrap().is_none(), "partial mode never publishes uncredited legacy snapshots"); + let decoded = image::load_from_memory(first.png()).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (16, 16)); + for (i, rgba) in decoded.pixels().enumerate() { + assert_eq!(rgba.0[3], if (i as u64) < first.info.updated_prefix { 255 } else { 0 }); + assert_eq!(first.covered()[i], 0, "empty scene means a real miss, never a fabricated hit"); + } + let first_hash = Sha256::digest(first.png()); + for _ in 0..100_000 { + if job.partial_preview().unwrap().is_some_and(|p| p.info.sequence == 2) { + break; + } + assert!(running.advance(1).unwrap()); + } + let second = job.partial_preview().unwrap().unwrap(); + assert_eq!(second.info.sequence, 2, "request issued during encoding must survive first publication"); + assert!(job.request_partial_preview().unwrap()); + assert_eq!(job.0.partial.as_ref().unwrap().state.lock().unwrap().free.bytes, 0); + for _ in 0..100_000 { + if !running.advance(1).unwrap() { + break; + } + assert!(job.partial_preview().unwrap().is_some_and(|p| p.info.sequence == 2)); + assert!(running.partial.as_ref().unwrap().0[0].lease.is_none()); + assert!(running.partial.as_ref().unwrap().0[0].pending.is_none()); + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let final_frame = job.frame().unwrap().unwrap(); + assert_eq!((final_frame.info.width, final_frame.info.height), (16, 16)); + assert!(job.partial_preview().unwrap().is_none()); + assert!(!job.request_partial_preview().unwrap()); + assert_eq!(Sha256::digest(first.png()), first_hash); + let per_slot = job.0.partial.as_ref().unwrap().plan.slot_bytes().unwrap(); + drop(running); + let before = host.admitted_bytes(); + drop(first); + assert_eq!(host.admitted_bytes(), before - per_slot); + drop(second); + assert_eq!(host.admitted_bytes(), before - 2 * per_slot); + drop(final_frame); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod partial_preview_terminal_errors { + use super::*; + use crate::job::{CpuProgressiveOptions, RaytraceOptions}; + + #[test] + fn cancellation_during_real_partial_hash_closes_slots_and_publishes_nothing() { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 7 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 8, + height: 8, + ..request() + }; + let job = host.submit_cpu_partial_with_environment_and_options(id(7725, 1), 19, empty(), request, JobOptions::default(), None).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if running.pending_png.is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + assert!(running.pending_png.is_some()); + assert!(job.partial_preview().unwrap().is_none()); + assert!(running.partial.as_ref().unwrap().0[0].pending.is_some()); + job.cancel().unwrap(); + assert!(!job.request_partial_preview().unwrap()); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.partial_preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[test] +fn partial_credit_last_drop_fails_closed_after_poison_without_losing_leases() { + let plan = crate::job::PartialPreviewPlan::new(1, 1).unwrap(); + let bytes = 2 * plan.slot_bytes().unwrap() + 1024; + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: bytes }); + let mut work = budget.reserve(bytes).unwrap(); + let credits = PartialCredits::new(plan, &mut work).unwrap(); + credits.request().unwrap(); + let held = credits.acquire().unwrap().unwrap(); + let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _state = credits.state.lock().unwrap(); + panic!("deliberate test-only credit lock poison"); + })); + assert!(poisoned.is_err()); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 1024); + credits.close(); + drop(credits); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 0); +} + +mod protected_feedback_contract { + use super::*; + use crate::job::{CpuBudget, MAX_CPU_WORK, MAX_PROTECTED_CPU_WORK, ProtectedPreviewPlan, ProtectedPreviewReport}; + + #[test] + fn profile_ordinary_caps_are_unchanged_and_protected_aggregate_is_explicit() { + assert_eq!(MAX_CPU_WORK, 16_000_000_000_000); + assert_eq!(MAX_PROTECTED_CPU_WORK, 31_462_813_335_678); + for (profile, ordinary) in + [(CpuBudget::Compact, 1_000_000_000), (CpuBudget::Studio, 1_000_000_000_000), (CpuBudget::Workstation, MAX_CPU_WORK)] + { + let plan = ProtectedPreviewPlan::new(1024, 1024, 16, profile).unwrap(); + plan.validate().unwrap(); + assert_eq!(plan.ordinary_limit(), ordinary); + assert_eq!(plan.quota_limit(), 79); + assert_eq!(plan.snapshot_work().unwrap(), 14_745_602); + assert_eq!(plan.presentation_limit().unwrap(), 1_164_902_558); + assert_eq!(plan.aggregate_limit().unwrap(), ordinary + 1_164_902_558); + assert_eq!(plan.preview_plan(), crate::job::PartialPreviewPlan::new(1024, 1024).unwrap()); + } + let largest = ProtectedPreviewPlan::new(1024, 1024, 16, CpuBudget::Workstation).unwrap(); + assert!( + largest.aggregate_limit().unwrap() < MAX_PROTECTED_CPU_WORK, + "the independent Cartesian ceiling need not be attained by this request" + ); + } + #[test] + fn zero_single_and_spread_milestones_are_checked_below_final_target() { + let zero = ProtectedPreviewPlan::new(1, 1, 1, CpuBudget::Compact).unwrap(); + assert_eq!((zero.total_commits(), zero.quota_limit(), zero.presentation_limit().unwrap()), (1, 0, 0)); + assert_eq!(zero.aggregate_limit().unwrap(), zero.ordinary_limit()); + assert!(zero.milestone(0).is_err()); + let single = ProtectedPreviewPlan::new(2, 1, 1, CpuBudget::Compact).unwrap(); + assert_eq!(single.quota_limit(), 1); + assert_eq!(single.milestone(0).unwrap(), 1); + assert!(single.milestone(1).is_err()); + for (w, h, spp, quota, last) in [(3, 1, 1, 2, 2), (66, 1, 1, 64, 65), (32, 32, 64, 127, 64_512)] { + let plan = ProtectedPreviewPlan::new(w, h, spp, CpuBudget::Compact).unwrap(); + assert_eq!(plan.quota_limit(), quota); + let milestones: Vec<_> = (0..quota).map(|j| plan.milestone(j).unwrap()).collect(); + assert_eq!(milestones.first(), Some(&1)); + assert_eq!(milestones.last(), Some(&last)); + assert!(milestones.windows(2).all(|pair| pair[0] < pair[1])); + assert!(plan.milestone(quota).is_err()); + assert!(plan.milestone(u32::MAX).is_err()); + } + } + #[test] + fn protected_plan_preserves_explicit_large_profiles_and_rejects_invalid_inputs() { + let large = ProtectedPreviewPlan::new(4096, 4096, 4096, CpuBudget::Workstation).unwrap(); + assert_eq!(large.samples_per_pixel(), 4096); + assert_eq!(large.budget(), CpuBudget::Workstation); + assert_eq!(large.total_commits(), 68_719_476_736); + assert_eq!((large.preview_plan().width(), large.preview_plan().height()), (1024, 1024)); + assert!(large.aggregate_limit().unwrap() <= MAX_PROTECTED_CPU_WORK); + for (w, h, spp, budget) in [ + (0, 1, 1, CpuBudget::Compact), + (1, 0, 1, CpuBudget::Compact), + (1, 1, 0, CpuBudget::Compact), + (1, 1, 65, CpuBudget::Compact), + (u32::MAX, u32::MAX, u32::MAX, CpuBudget::Workstation), + (4096, 4096, 4096, CpuBudget::Compact), + ] { + assert!(ProtectedPreviewPlan::new(w, h, spp, budget).is_err()); + } + } + + // Synthetic REPORT-validation fixtures only; real producer usage is tested below. + fn report(plan: ProtectedPreviewPlan, ordinary_used: u64, accepted: u32, next: u32) -> ProtectedPreviewReport { + ProtectedPreviewReport { + policy_version: 1, + ordinary_limit: plan.ordinary_limit(), + presentation_limit: plan.presentation_limit().unwrap(), + aggregate_limit: plan.aggregate_limit().unwrap(), + ordinary_used, + presentation_used: u64::from(accepted) * plan.snapshot_work().unwrap(), + accepted_snapshots: accepted, + quota_limit: plan.quota_limit(), + next_milestone_index: next, + quota_exhausted: accepted == plan.quota_limit(), + milestones_complete: next == plan.quota_limit(), + } + } + fn credits(plan: ProtectedPreviewPlan) -> (Arc, Reservation, Arc) { + let total = 2 * plan.preview_plan().slot_bytes().unwrap() + 1024; + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: total }); + let mut work = budget.reserve(total).unwrap(); + let credits = PartialCredits::new_protected(plan, &mut work).unwrap(); + assert_eq!(work.bytes, 0); + (budget, work, credits) + } + #[test] + fn coalesced_milestones_do_not_fabricate_spent_quota_or_permanent_exhaustion() { + let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap(); + let (budget, work, credits) = credits(plan); + assert!(credits.state.lock().unwrap().report.is_none()); + let value = report(plan, 31, 1, 127); + credits.store_report(Some(value)).unwrap(); + assert_eq!(credits.state.lock().unwrap().report, Some(value)); + assert!(value.milestones_complete && !value.quota_exhausted); + assert_eq!(value.presentation_used, 79_874); + assert!(value.presentation_used < value.presentation_limit); + assert!(!credits.exhausted.load(Ordering::Acquire)); + assert!(credits.request().unwrap()); + assert!(credits.state.lock().unwrap().report == Some(value)); + credits.close(); + drop(credits); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn actual_report_invariants_and_monotonic_refusals_preserve_the_prior_observation() { + let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap(); + let (_, work, credits) = credits(plan); + let good = report(plan, 31, 1, 2); + credits.store_report(Some(good)).unwrap(); + let bad = [ + report(plan, 30, 1, 2), + report(plan, 31, 0, 2), + report(plan, 31, 1, 1), + ProtectedPreviewReport { ordinary_used: plan.ordinary_limit() + 1, ..good }, + ProtectedPreviewReport { presentation_used: plan.presentation_limit().unwrap() + 1, ..good }, + ProtectedPreviewReport { aggregate_limit: MAX_PROTECTED_CPU_WORK + 1, ..good }, + ProtectedPreviewReport { quota_exhausted: true, ..good }, + ProtectedPreviewReport { milestones_complete: true, ..good }, + ProtectedPreviewReport { policy_version: 2, ..good }, + ]; + for value in bad { + assert!(credits.store_report(Some(value)).is_err()); + assert_eq!(credits.state.lock().unwrap().report, Some(good)); + } + assert!(credits.store_report(None).is_err()); + assert_eq!(credits.state.lock().unwrap().report, Some(good)); + let at_limits = report(plan, plan.ordinary_limit(), plan.quota_limit(), plan.quota_limit()); + credits.store_report(Some(at_limits)).unwrap(); + assert_eq!(at_limits.ordinary_used + at_limits.presentation_used, at_limits.aggregate_limit); + assert!(credits.exhausted.load(Ordering::Acquire)); + assert!(!credits.request().unwrap()); + credits.close(); + drop(credits); + drop(work); + } + #[test] + fn legacy_report_is_absent_and_rejected_protected_admission_does_not_reserve() { + let host = CpuHost::cooperative(); + let job = host.submit(id(7730, 1), 19, empty(), request()).unwrap(); + let before = serde_json::to_value(job.status().unwrap()).unwrap(); + assert!(job.protected_preview_report().unwrap().is_none()); + assert_eq!(serde_json::to_value(job.status().unwrap()).unwrap(), before); + let admitted = host.admitted_bytes(); + assert!( + host.submit_cpu_protected_partial_with_environment_and_options(id(7730, 2), 19, empty(), request(), JobOptions::default(), None).is_err() + ); + assert_eq!(host.admitted_bytes(), admitted); + assert!(job.protected_preview_report().unwrap().is_none()); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod protected_feedback_real_host { + use super::*; + use crate::job::{CpuProgressiveOptions, RaytraceOptions}; + + fn fixture(serial: u64, width: u32, height: u32, samples: u32) -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width, + height, + background: [10, 20, 30], + ..request() + }; + let job = host + .submit_cpu_protected_partial_with_environment_and_options(id(7731, serial), 19, empty(), request, JobOptions::default(), None) + .unwrap(); + assert!(job.protected_preview_report().unwrap().is_none(), "no future ledger is invented while queued"); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + assert!(job.protected_preview_report().unwrap().is_some(), "report is read from the real constructed task"); + (host, job, running) + } + fn finish(running: &mut Running) { + for _ in 0..1_000_000 { + if !running.advance(1).unwrap() { + return; + } + } + panic!("small protected CPU fixture did not finish"); + } + #[test] + fn actual_32_by_32_control_and_feedback_keep_ordinary_work_and_final_png_identical() { + let (control_host, control, mut control_run) = fixture(1, 32, 32, 64); + finish(&mut control_run); + let control_report = control.protected_preview_report().unwrap().unwrap(); + let control_frame = control.frame().unwrap().unwrap(); + assert_eq!(control_report.presentation_used, 5_032_062); + assert_eq!(control_report.accepted_snapshots, 63); + assert!(control_report.ordinary_used > 0); + let (host, job, mut running) = fixture(2, 32, 32, 64); + assert!(job.request_partial_preview().unwrap()); + finish(&mut running); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(report.ordinary_used, control_report.ordinary_used); + assert_eq!(report.ordinary_limit, 1_000_000_000); + assert_eq!(report.accepted_snapshots, 64); + assert_eq!(report.presentation_used, 5_111_936); + assert_eq!(report.ordinary_used + report.presentation_used, control_report.ordinary_used + 5_111_936); + assert_eq!(report.presentation_used - control_report.presentation_used, 79_874); + assert_eq!(report.aggregate_limit, report.ordinary_limit + report.presentation_limit); + assert!(!report.quota_exhausted); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.png(), control_frame.png()); + let decoded = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (32, 32)); + assert!(decoded.pixels().all(|p| p.0 == [10, 20, 30, 255]), "analytic all-miss final pixels"); + let terminal = job.protected_preview_report().unwrap(); + assert!(!job.request_partial_preview().unwrap()); + assert_eq!(job.protected_preview_report().unwrap(), terminal); + drop(frame); + drop(job); + drop(running); + drop(control_frame); + drop(control); + drop(control_run); + assert_eq!((host.admitted_bytes(), control_host.admitted_bytes()), (0, 0)); + } + #[test] + fn real_quota_exhaustion_does_not_remove_normal_full_pass_or_final_work() { + let (control_host, control, mut control_run) = fixture(3, 2, 1, 2); + finish(&mut control_run); + let expected = control.protected_preview_report().unwrap().unwrap(); + let control_frame = control.frame().unwrap().unwrap(); + let (host, job, mut running) = fixture(4, 2, 1, 2); + let mut exhausted_seen = false; + for _ in 0..100_000 { + job.request_partial_preview().unwrap(); + let more = running.advance(1).unwrap(); + let report = job.protected_preview_report().unwrap().unwrap(); + if report.quota_exhausted { + exhausted_seen = true; + assert!(job.partial_preview_exhausted().unwrap()); + assert!(!job.request_partial_preview().unwrap()); + } + if !more { + break; + } + } + assert!(exhausted_seen); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!((report.accepted_snapshots, report.quota_limit, report.next_milestone_index), (2, 2, 2)); + assert!(report.quota_exhausted && report.milestones_complete); + assert_eq!(report.presentation_used, report.presentation_limit); + assert_eq!(report.ordinary_used, expected.ordinary_used, "full-pass tick and final remain ordinary"); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.png(), control_frame.png()); + drop(frame); + drop(job); + drop(running); + drop(control_frame); + drop(control); + drop(control_run); + assert_eq!((host.admitted_bytes(), control_host.admitted_bytes()), (0, 0)); + } + #[test] + fn two_retained_protected_payloads_keep_their_leases_without_blocking_final() { + let (host, job, mut running) = fixture(5, 2, 1, 2); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if job.partial_preview().unwrap().is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + let first = job.partial_preview().unwrap().unwrap(); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if job.partial_preview().unwrap().is_some_and(|p| p.info.sequence == 2) { + break; + } + assert!(running.advance(1).unwrap()); + } + let second = job.partial_preview().unwrap().unwrap(); + assert_eq!(second.info.sequence, 2); + let old_hash = Sha256::digest(first.png()); + assert!(job.request_partial_preview().unwrap()); + assert_eq!(job.0.partial.as_ref().unwrap().state.lock().unwrap().free.bytes, 0); + finish(&mut running); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!((report.accepted_snapshots, report.quota_limit), (2, 2)); + assert!(report.quota_exhausted); + assert_eq!(Sha256::digest(first.png()), old_hash); + drop(running); + let slot = job.0.partial.as_ref().unwrap().plan.slot_bytes().unwrap(); + let retained = host.admitted_bytes(); + drop(first); + assert_eq!(host.admitted_bytes(), retained - slot); + drop(second); + assert_eq!(host.admitted_bytes(), retained - 2 * slot); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn charged_begin_followed_by_poll_error_retains_actual_report_without_refund() { + let (host, job, mut running) = fixture(6, 32, 32, 64); + let plan = job.0.partial.as_ref().unwrap().plan; + for _ in 0..100_000 { + if running.task.as_mut().unwrap().partial_ready(plan).unwrap() { + break; + } + assert!(running.advance(1).unwrap()); + } + assert!(running.task.as_mut().unwrap().partial_ready(plan).unwrap()); + assert!(job.request_partial_preview().unwrap()); + // Invalid zero quantum fails AFTER the host's accepted safe BEGIN/precharge. + assert!(!running.guarded_step(0)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!(report.accepted_snapshots, 1); + assert_eq!(report.presentation_used, 79_874); + assert!(job.frame().unwrap().is_none()); + assert!(!job.request_partial_preview().unwrap()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn cancellation_while_host_hashes_does_not_charge_twice_or_refund_feedback() { + let (host, job, mut running) = fixture(7, 32, 32, 64); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if running.pending_png.is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + assert!(running.pending_png.is_some()); + let before = job.protected_preview_report().unwrap().unwrap(); + assert_eq!((before.accepted_snapshots, before.presentation_used), (1, 79_874)); + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.protected_preview_report().unwrap(), Some(before)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod protected_begin_setup_errors { + use super::*; + use crate::job::{CpuProgressiveOptions, EmissionSides, RaytraceOptions, SurfaceEmission}; + use solidcraft_geom::Vec3; + + fn fixture(serial: u64) -> (CpuHost, JobHandle, Work) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let mesh = Arc::new(Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "Setup witness".into(), + mesh, + color: [0; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + }; + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 2, seed: 123 }), + lights: Some(Vec::new()), + emissions: Some(vec![SurfaceEmission { + body_index: 0, + body: "Setup witness".into(), + color: [1.0, 0.0, 0.0], + strength: 2.0, + sides: EmissionSides::Both, + }]), + ..Default::default() + }), + width: 2, + height: 1, + ..request() + }; + assert_eq!(request.raytrace.as_ref().unwrap().emissions.as_ref().unwrap().len(), 1); + let job = host + .submit_cpu_protected_partial_with_environment_and_options(id(7732, serial), 19, scene, request, JobOptions::default(), None) + .unwrap(); + assert!(job.protected_preview_report().unwrap().is_none()); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + (host, job, work) + } + fn observed_report(credits: &PartialCredits) -> crate::job::ProtectedPreviewReport { + let Ok(state) = credits.state.try_lock() else { panic!("wrapping factory must run outside the report/credit lock") }; + let actual = state.report.expect("real task report must be captured BEFORE fallible wrapping"); + assert_eq!(actual.policy_version, 1); + assert_eq!(actual.ordinary_limit, 1_000_000_000); + assert_eq!(actual.accepted_snapshots, 0); + assert_eq!(actual.ordinary_used, 1, "the single emission retains its pre-existing ordinary constructor tick"); + assert_eq!(actual.presentation_used, 0); + actual + } + fn assert_failed_report(host: CpuHost, job: JobHandle, actual: crate::job::ProtectedPreviewReport, message: &str) { + assert_eq!(job.protected_preview_report().unwrap(), Some(actual), "no invented zeros or discarded real constructor work"); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Failed); + let error = status.error.unwrap(); + assert_eq!(error.code, ErrorCode::AllocationFailed); + assert_eq!(error.message, message); + assert!(job.frame().unwrap().is_none()); + assert!(job.partial_preview().unwrap().is_none()); + assert!(!job.request_partial_preview().unwrap()); + let request_bytes = job.0._request_reservation.as_ref().map_or(0, |lease| lease.bytes); + assert_eq!(host.admitted_bytes(), request_bytes + 1024, "task/free slots released; actual report metadata retained"); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn protected_setup_failure_preserves_constructed_task_report_and_error() { + let (host, job, work) = fixture(1); + let observed = std::cell::Cell::new(None); + let running = Running::begin_with_partial_factory(work, |credits| { + // Deterministic fault AFTER the REAL producer and first host slot exist. + observed.set(Some(observed_report(&credits))); + Err(JobError::new(ErrorCode::AllocationFailed, "injected auxiliary setup failure")) + }); + assert!(running.is_none()); + let actual = observed.get().expect("post-construction factory must be reached"); + assert_failed_report(host, job, actual, "injected auxiliary setup failure"); + } + #[test] + fn first_host_slot_failure_preserves_the_raw_producer_report() { + let (host, job, work) = fixture(2); + let Work { scene, handle, reservation, environment, .. } = work; + let plan = handle.0.partial.as_ref().unwrap().protected.unwrap(); + let options = handle.0.request.raytrace.clone().unwrap(); + let task = crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_protected_partial( + scene, + handle.0.request.clone(), + handle.0.cancel.clone(), + options, + environment, + handle.0.options.nested_media, + plan, + ) + .unwrap(); + let observed = std::cell::Cell::new(None); + let result = WorkTask::raytrace_with_slot(task, handle.0.partial.as_deref(), |_task| { + // The actual producer exists even though its FIRST wrapper cannot be made. + observed.set(Some(observed_report(handle.0.partial.as_deref().unwrap()))); + Err(JobError::new(ErrorCode::AllocationFailed, "injected first host slot failure")) + }); + let error = result.err().expect("injected wrapping failure must propagate"); + let actual = observed.get().expect("first-slot factory must be reached"); + terminal(&handle, error); + drop(reservation); + drop(handle); + assert_failed_report(host, job, actual, "injected first host slot failure"); + } + #[test] + fn an_actual_constructor_refusal_keeps_report_none_and_skips_auxiliary_setup() { + let (host, job, mut work) = fixture(3); + drop(job); + // Private invalid-constructor fixture only; no public admission/cap bypass. + Arc::get_mut(&mut work.handle.0).unwrap().request.width = 0; + let job = work.handle.clone(); + let running = Running::begin_with_partial_factory(work, |_| panic!("constructor refusal must not attempt auxiliary setup")); + assert!(running.is_none()); + assert!(job.protected_preview_report().unwrap().is_none()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + assert!(job.frame().unwrap().is_none()); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod directional_shadow_contract { + use super::*; + + // Same queue-only native metadata harness as existing protected setup tests. + // No native worker is spawned; drive the real Running::begin deterministically. + // This checks host queues/leases, not native scheduling qualification. + fn queued_native_host() -> CpuHost { + ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + + fn capture() -> (ProductScene, ImageRequest) { + let mesh = Mesh { + positions: vec![ + solidcraft_geom::Vec3::new(-10.0, -10.0, 0.0), + solidcraft_geom::Vec3::new(10.0, -10.0, 0.0), + solidcraft_geom::Vec3::new(10.0, 10.0, 0.0), + solidcraft_geom::Vec3::new(-10.0, 10.0, 0.0), + ], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + bounds, + meshes: vec![crate::ProductMesh { + name: "directional glass".into(), + mesh: std::sync::Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + transmission: None, + }], + }; + let mut input = request(); + input.integrator = Integrator::Raytrace; + input.raytrace = Some(super::super::super::RaytraceOptions { + directional_shadow_transmission: true, + dielectrics: vec![super::super::super::DielectricOptions { + body_index: 0, + body_name: "directional glass".into(), + boundary: super::super::super::DielectricBoundary::ThinSheet, + ior: 1.0, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }], + ..Default::default() + }); + (scene, input) + } + + #[test] + fn external_hdr_is_refused_before_admission_or_retained_leases() { + use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 128, 128, 129]); + } + let environment = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap(); + let host = queued_native_host(); + let (scene, input) = capture(); + let error = host.admit_submission(&scene, &input, JobOptions::default(), Some(&environment), None).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(error.message, "directional shadow transmission does not support HDR environments"); + let error = host.submit_with_environment(id(9620, 1), 1, scene, input, Some(environment)).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(error.message, "directional shadow transmission does not support HDR environments"); + assert_eq!(host.admitted_bytes(), 0); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + } + + #[test] + fn cancelled_directional_request_publishes_no_frame_and_releases_work() { + let host = queued_native_host(); + let (scene, input) = capture(); + let retained = input.raytrace.as_ref().unwrap().retained_bytes().unwrap(); + let handle = host.submit(id(9621, 1), 1, scene, input).unwrap(); + assert!(handle.status().unwrap().request.raytrace.as_ref().unwrap().directional_shadow_transmission); + handle.cancel().unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + assert!(Running::begin(work).is_none()); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Cancelled); + assert!(handle.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), retained); + drop(handle); + assert_eq!(host.admitted_bytes(), 0); + } +} + +// Original fixtures for consecutive CPU publication; WRITTEN, NOT RUN. +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod every_cpu_pass { + use super::*; + use crate::job::{CpuBudget, CpuProgressiveOptions, RaytraceOptions}; + + enum Snapshot { + Complete(Arc), + Partial(Arc), + } + impl Snapshot { + fn pass(&self) -> u32 { + match self { + Self::Complete(preview) => preview.info.samples_per_pixel, + Self::Partial(preview) => { + assert_eq!(preview.info.updated_prefix, 0, "automatic publication is a uniform complete pass"); + preview.info.completed_passes + } + } + } + fn png(&self) -> &[u8] { + match self { + Self::Complete(preview) => preview.png(), + Self::Partial(preview) => preview.png(), + } + } + fn sequence(&self) -> u64 { + match self { + Self::Complete(preview) => u64::from(preview.info.frame_sequence), + Self::Partial(preview) => preview.info.sequence, + } + } + } + fn snapshot(job: &JobHandle, protected: bool) -> Option { + if protected { job.partial_preview().unwrap().map(Snapshot::Partial) } else { job.preview().unwrap().map(Snapshot::Complete) } + } + fn fixture(samples: u32, protected: bool) -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + budget: if samples > 64 { CpuBudget::Workstation } else { CpuBudget::Compact }, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 1, + height: 1, + background: [10, 20, 30], + ..request() + }; + let job = if protected { + host.submit_cpu_protected_partial_with_environment_and_options(id(7790, 1), 19, empty(), request, JobOptions::default(), None) + } else { + host.submit(id(7790, 1), 19, empty(), request) + } + .unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (host, job, running) + } + fn finish(running: &mut Running) { + for _ in 0..10_000_000 { + if !running.advance(16_384).unwrap() { + return; + } + } + panic!("one-pixel every-pass fixture exceeded its finite continuation bound"); + } + fn run_all(samples: u32, protected: bool, quantum: usize) { + let (host, job, mut running) = fixture(samples, protected); + let admission = host.admitted_bytes(); + let mut previous = 0; + let mut complete = false; + for _ in 0..10_000_000 { + let more = running.advance(quantum).unwrap(); + if let Some(preview) = snapshot(&job, protected) { + let pass = preview.pass(); + if pass != previous { + assert_eq!(pass, previous + 1, "no missing, duplicate or reordered complete pass"); + assert!(pass < samples); + match &preview { + Snapshot::Complete(value) => { + assert_eq!(value.info.frame_sequence, pass); + assert_eq!(value.info.frame.job, job.id()); + assert_eq!(value.info.frame.scene_generation, 19); + } + Snapshot::Partial(value) => { + assert_eq!(value.info.sequence, u64::from(pass)); + assert_eq!(value.info.frame.job, job.id()); + assert_eq!(value.info.frame.scene_generation, 19); + assert_eq!(value.covered(), &[0]); + } + } + assert_eq!(image::load_from_memory(preview.png()).unwrap().to_rgba8().get_pixel(0, 0).0, [10, 20, 30, 255]); + assert!(job.frame().unwrap().is_none(), "a provisional pass is not a final image"); + previous = pass; + } + } // No retained consumer Arc and no UI acknowledgement. + assert!(host.admitted_bytes() <= admission, "publication recycles the same two prepaid slots"); + if !more { + complete = true; + break; + } + } + assert!(complete); + assert_eq!(previous, samples - 1); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.cpu_preview_retention_skips, 0); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 })); + assert!(job.preview().unwrap().is_none() && job.partial_preview().unwrap().is_none()); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(image::load_from_memory(frame.png()).unwrap().to_rgba8().get_pixel(0, 0).0, [10, 20, 30, 255]); + if protected { + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!(report.accepted_snapshots, samples - 1); + assert_eq!(report.presentation_used, u64::from(samples - 1) * 65_552); + } + drop(frame); + drop(status); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn real_legacy_and_protected_hosts_publish_every_pass_without_ui_demand() { + for protected in [false, true] { + for quantum in [1, 16_384] { + for samples in [1, 7] { + run_all(samples, protected, quantum); + } + } + } + } + #[test] + #[cfg(target_pointer_width = "64")] + fn real_one_pixel_high_target_crosses_64_with_constant_slots() { + for protected in [false, true] { + run_all(65, protected, 16_384); + } + } + #[test] + fn two_external_snapshots_are_diagnosed_without_waiting_or_losing_the_final() { + for protected in [false, true] { + let (host, job, mut running) = fixture(7, protected); + let mut held = Vec::new(); + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == held.len() as u32 + 1 { + held.push(preview); + } + } + if held.len() == 2 { + break; + } + } + assert_eq!(held.len(), 2); + let hashes: Vec<_> = held.iter().map(|preview| Sha256::digest(preview.png())).collect(); + finish(&mut running); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.cpu_preview_retention_skips, 4, "passes 3,4,5,6 had both slots externally pinned"); + assert!(job.frame().unwrap().is_some()); + for (preview, hash) in held.iter().zip(hashes) { + assert_eq!(Sha256::digest(preview.png()), hash); + } + drop(running); + drop(status); + drop(job); + assert!(host.admitted_bytes() > 0, "external snapshots remain charged after their job drops"); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + #[test] + fn release_after_a_pinned_pass_keeps_publication_sequence_separate_from_actual_spp() { + for protected in [false, true] { + let (host, job, mut running) = fixture(7, protected); + let mut held = Vec::new(); + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == held.len() as u32 + 1 { + held.push(preview); + } + } + if held.len() == 2 { + break; + } + } + assert_eq!(held.len(), 2); + for _ in 0..100_000 { + if job.status().unwrap().cpu_preview_retention_skips == 1 { + break; + } + assert!(running.advance(1).unwrap()); + } + assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); + drop(held.remove(0)); // Return exactly one old consumer slot after pass 3. + let mut fourth = None; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == 4 { + fourth = Some(preview); + break; + } + } + } + let fourth = fourth.unwrap(); + assert_eq!(fourth.pass(), 4); + assert_eq!(fourth.sequence(), 3, "SPP 3 was diagnosed, not published"); + assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); + drop(fourth); + finish(&mut running); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); + drop(running); + drop(job); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + #[test] + fn cancellation_after_third_pass_and_last_digest_chunk_never_publishes_late() { + for protected in [false, true] { + let (host, job, mut running) = fixture(7, protected); + let mut held = None; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == 3 { + held = Some(preview); + break; + } + } + } + let held = held.unwrap(); + let hash = Sha256::digest(held.png()); + for _ in 0..100_000 { + if running.pending_png.is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + let pending = running.pending_png.as_mut().unwrap(); + while !pending.step(1, &job.0.cancel).unwrap() {} + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.preview().unwrap().is_none() && job.partial_preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(Sha256::digest(held.png()), hash); + drop(running); + drop(job); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + #[test] + fn third_checkpoint_is_valid_after_two_but_a_gap_still_fails() { + let (host, job, mut running) = fixture(7, false); + let mut third = None; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = job.preview().unwrap() { + if preview.info.samples_per_pixel == 3 { + third = Some(preview); + break; + } + } + } + let third = third.unwrap(); + assert_eq!(third.info.frame_sequence, 3); + for _ in 0..100_000 { + if running.pending_png.as_ref().is_some_and(|pending| pending.preview_samples == Some(4)) { + break; + } + assert!(running.advance(1).unwrap()); + } + running.pending_png.as_mut().unwrap().preview_samples = Some(5); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + assert!(job.preview().unwrap().is_none() && job.frame().unwrap().is_none()); + assert_eq!(third.info.samples_per_pixel, 3); + drop(running); + drop(job); + drop(third); + assert_eq!(host.admitted_bytes(), 0); + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/interactive.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/interactive.rs new file mode 100644 index 000000000..e98fc9274 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/interactive.rs @@ -0,0 +1,371 @@ +//! Transient CPU Interactive scheduling. The UI adapter owns visual revisions; +//! this controller owns cancellation, not document settings or final-image export. +use std::time::Duration; + +use super::{CpuProgressiveOptions, ErrorCode, ImageRequest, Integrator, JobError, JobHandle, JobId, Phase, Result}; + +const SETTLE: Duration = Duration::from_millis(200); +const MAX_EDGE: u32 = 1024; + +/// Prepare a separate low-resolution request. Never edits the final request, +/// changes renderer, removes optics/lights, or promises geometry admission. +pub fn cpu_request(final_request: &ImageRequest) -> Result { + final_request.validate_raster_request()?; + if final_request.integrator != Integrator::Raytrace || final_request.transparent_background { + return Err(JobError::new(ErrorCode::InvalidRequest, "Interactive CPU requires opaque ray tracing")); + } + let (width, height) = (final_request.width, final_request.height); + if width == 0 || height == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "Interactive output dimensions must be positive")); + } + if let Some(options) = &final_request.raytrace { + options.validate()?; + } + let edge = width.max(height); + let fit = |side: u32| { + if edge <= MAX_EDGE { side } else { ((u64::from(side) * u64::from(MAX_EDGE) + u64::from(edge) / 2) / u64::from(edge)).max(1) as u32 } + }; + let mut request = final_request.clone(); + request.width = fit(width); + request.height = fit(height); + let options = request.raytrace.get_or_insert_default(); + options.primary_samples = 1; + // Preserve explicit accumulation intent, including its deterministic seed. + // Fixed-image callers keep the original preview default. Incompatible + // transport remains an error rather than silently removing requested effects. + options.progressive.get_or_insert_with(CpuProgressiveOptions::default); + if let Some(reflections) = &mut options.reflections { + reflections.samples = 1; + } + options.validate()?; + options.budget.validate_image(request.width, request.height, options.progressive)?; + Ok(request) +} + +/// Caller increments visual_revision for every camera/draft/appearance/light/HDR +/// or output edit, even if scene_generation did not change. Never use only a CAD +/// revision, a body name, or the selected setup name as the visual identity. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct VisualRevision { + pub scene_generation: u64, + pub visual_revision: u64, +} + +/// Issued only after the edit group settles. Private fields prevent fabricating +/// a ticket for a newer request from a delayed capture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CaptureTicket { + session: u64, + serial: u64, + revision: VisualRevision, +} + +impl CaptureTicket { + pub fn revision(self) -> VisualRevision { + self.revision + } + + /// Submit this identity to the preview host, outside the final-job registry. + pub fn job_id(self) -> JobId { + JobId { session: self.session, serial: self.serial, generation: self.serial } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum State { + Off, + Updating, + Refining, + Paused, + TargetReached, + Error, +} + +/// One controller per document session. No serialization, clocks, threads, scene +/// extraction or new renderer here. Supply monotonic elapsed time from the host; +/// this keeps both browser integration and deterministic event tests possible. +pub struct Interactive { + session: u64, + serial: u64, + revision: Option, + changed_at: Duration, + enabled: bool, + paused: bool, + final_active: bool, + ticket: Option, + active: Option, + error: Option, +} + +impl Interactive { + pub fn new(session: u64) -> Self { + Self { + session, + serial: 0, + revision: None, + changed_at: Duration::ZERO, + enabled: false, + paused: false, + final_active: false, + ticket: None, + active: None, + error: None, + } + } + + fn cancel(&mut self) -> Result<()> { + // Invalidate first, including when a poisoned host refuses cancellation. + self.ticket = None; + if let Some(job) = self.active.take() { + job.cancel()?; + } + Ok(()) + } + + /// Explicit user activation. Merely entering Render must not call this. + pub fn enable(&mut self, revision: VisualRevision, now: Duration) -> Result<()> { + self.cancel()?; + self.enabled = true; + self.paused = false; + self.error = None; + self.revision = Some(revision); + self.changed_at = now; + Ok(()) + } + + /// Workspace/document departure uses disable; manually started final jobs + /// are deliberately outside this controller and are never cancelled here. + pub fn disable(&mut self) -> Result<()> { + self.enabled = false; + self.paused = false; + self.error = None; + self.cancel() + } + + pub fn edit(&mut self, revision: VisualRevision, now: Duration) -> Result<()> { + if self.revision != Some(revision) { + self.revision = Some(revision); + self.changed_at = now; + self.error = None; + self.cancel()?; + } + Ok(()) + } + + /// A view may retain an identified immutable PNG before pausing, but must + /// label it paused/stale. It is never a current or exportable final image. + pub fn pause(&mut self) -> Result<()> { + self.paused = true; + self.cancel() + } + + pub fn resume(&mut self, now: Duration) -> Result<()> { + self.cancel()?; + self.paused = false; + self.error = None; + self.changed_at = now; + Ok(()) + } + + pub fn set_final_active(&mut self, active: bool, now: Duration) -> Result<()> { + if self.final_active != active { + self.final_active = active; + self.changed_at = now; + self.cancel()?; + } + Ok(()) + } + + /// At most one unacknowledged capture; no queue of obsolete requests. + pub fn capture(&mut self, now: Duration) -> Result> { + if !self.enabled + || self.paused + || self.final_active + || self.ticket.is_some() + || self.error.is_some() + || now.checked_sub(self.changed_at).is_none_or(|elapsed| elapsed < SETTLE) + { + return Ok(None); + } + let Some(revision) = self.revision else { return Ok(None) }; + self.serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Interactive capture identity exhausted"))?; + let ticket = CaptureTicket { session: self.session, serial: self.serial, revision }; + self.ticket = Some(ticket); + Ok(Some(ticket)) + } + + /// Recheck before expensive capture/admission, including after a worker delay. + /// A ticket is not permission to prepare an obsolete or already adopted job. + pub fn accepts_capture(&self, ticket: CaptureTicket) -> bool { + self.enabled && !self.paused && !self.final_active && self.error.is_none() && self.ticket == Some(ticket) && self.active.is_none() + } + + /// Attach an admitted preview-only job after immutable capture. Delayed jobs + /// are cancelled, including a previous ticket for the same visual revision. + /// Use a separate engine job session/registry from final-image export. + pub fn attach(&mut self, ticket: CaptureTicket, job: JobHandle) -> Result { + // A misrouted callback must never cancel another document's work or a + // manual final job. Only our dedicated preview session is ours to stop. + if job.id().session != self.session { + self.capture_failed(ticket, JobError::new(ErrorCode::WrongOwner, "Interactive job belongs to another session")); + return Ok(false); + } + if self.ticket != Some(ticket) || ticket.session != self.session { + // Protect an admitted current capture even before acknowledgement. + // Once accepted, only the same record (not merely its JobId) is ours. + let current = match &self.active { + Some(active) => active.same_record(&job), + None => self.ticket.is_some_and(|ticket| ticket.job_id() == job.id()), + }; + if !current { + job.cancel()?; + } + return Ok(false); + } + let status = job.status()?; + if status.job != ticket.job_id() || status.scene_generation != ticket.revision.scene_generation { + job.cancel()?; + self.capture_failed(ticket, JobError::new(ErrorCode::WrongOwner, "Interactive job capture identity mismatch")); + return Ok(false); + } + if status.request.integrator != Integrator::Raytrace || status.request.raytrace.as_ref().is_none_or(|options| options.progressive.is_none()) { + job.cancel()?; + self.capture_failed(ticket, JobError::new(ErrorCode::InvalidRequest, "Interactive requires a CPU progressive job")); + return Ok(false); + } + // A ticket is acknowledged exactly once, even if the same capture is + // delivered twice while an earlier attached job is still running. + if self.active.is_some() { + if self.active.as_ref().is_none_or(|active| !active.same_record(&job)) { + job.cancel()?; + } + return Ok(false); + } + self.active = Some(job); + Ok(true) + } + + pub fn capture_failed(&mut self, ticket: CaptureTicket, error: JobError) { + if self.ticket == Some(ticket) && self.active.is_none() { + self.ticket = None; + self.error = Some(error); + } + } + + /// Access only the current capture. The adapter reads checkpoint/final bytes + /// through this handle, displaying both as Interactive/provisional content. + pub fn current(&self) -> Option<&JobHandle> { + self.active.as_ref() + } + + pub fn error(&self) -> Option<&JobError> { + self.error.as_ref() + } + + pub fn state(&self) -> Result { + if !self.enabled { + return Ok(State::Off); + } + if self.paused || self.final_active { + return Ok(State::Paused); + } + if self.error.is_some() { + return Ok(State::Error); + } + if let Some(job) = &self.active { + return Ok(match job.status()?.progress.phase { + Phase::Completed => State::TargetReached, + Phase::Cancelled | Phase::Failed => State::Error, + _ => State::Refining, + }); + } + Ok(State::Updating) + } +} + +impl Drop for Interactive { + fn drop(&mut self) { + let _ = self.cancel(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::job::{CpuBudget, RaytraceOptions}; + + fn request(options: RaytraceOptions) -> ImageRequest { + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Integrator::Raytrace, + raytrace: Some(options), + textures: None, + environment: None, + camera: Default::default(), + width: 81, + height: 53, + background: [40, 80, 120], + transparent_background: false, + } + } + + #[test] + fn explicit_progressive_target_and_seed_survive_interactive_conversion() { + for (budget, samples) in [(CpuBudget::Compact, 31), (CpuBudget::Studio, 997), (CpuBudget::Workstation, 1_048_576)] { + let mut source = request(RaytraceOptions { + budget, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: u32::MAX }), + primary_samples: 1, + exposure_ev: -2.0, + shadows: false, + ..Default::default() + }); + // The high target still obeys P*SPP admission; no implicit resize/profile. + if budget == CpuBudget::Workstation { + source.width = 3840; + source.height = 1; + } + let before = serde_json::to_value(&source).unwrap(); + let converted = cpu_request(&source).unwrap(); + let mut expected = source.clone(); + if budget == CpuBudget::Workstation { + expected.width = 1024; + } + assert_eq!(serde_json::to_value(converted).unwrap(), serde_json::to_value(expected).unwrap()); + assert_eq!(serde_json::to_value(&source).unwrap(), before); + } + } + + #[test] + fn fixed_interactive_keeps_original_default_and_invalid_explicit_intent_refuses() { + let source = request(RaytraceOptions { primary_samples: 16, ..Default::default() }); + let converted = cpu_request(&source).unwrap(); + let options = converted.raytrace.unwrap(); + assert_eq!(options.progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); + assert_eq!(options.primary_samples, 1); + assert!(source.raytrace.as_ref().unwrap().progressive.is_none()); + for (budget, samples) in [(CpuBudget::Compact, 65), (CpuBudget::Studio, 1025), (CpuBudget::Workstation, 1_048_577)] { + let invalid = request(RaytraceOptions { + budget, + primary_samples: 1, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 741 }), + ..Default::default() + }); + let before = serde_json::to_value(&invalid).unwrap(); + assert!(cpu_request(&invalid).is_err()); + assert_eq!(serde_json::to_value(&invalid).unwrap(), before); + } + let mut over_work = request(RaytraceOptions { + primary_samples: 1, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 741 }), + ..Default::default() + }); + over_work.width = 1024; + over_work.height = 1024; + assert!(cpu_request(&over_work).is_err(), "do not reduce the explicit target to fit the profile"); + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/mod.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/mod.rs new file mode 100644 index 000000000..b750df8fb --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/job/mod.rs @@ -0,0 +1,1903 @@ +//! Product-image work and its device-independent, session-scoped protocol. +//! Hosts own execution; documents and history never contain these values. + +use std::fmt; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; + +use serde::{Deserialize, Serialize}; + +use crate::{BackendId, Camera, ExecutorId}; + +pub mod adaptive; +pub mod aging; +pub mod bloom; +mod cpu_budget; +pub(crate) mod encoding; +pub mod finishing; +mod host; +pub(crate) mod image; +pub mod interactive; +pub mod led_strip; +mod lens; +#[cfg(test)] +mod light_union_tests; +mod lighting; +pub mod linear_exr; +mod linear_exr_decode; +pub mod looks; +pub mod photographic; +mod png; +pub mod presentation; +mod punctual; +mod raster_lights; +mod regrade; +#[cfg(test)] +mod rt2_tests; +pub mod textures; +pub mod volume; + +pub use cpu_budget::{CpuBudget, CpuBudgetLimits, MAX_CPU_BODIES, MAX_CPU_SAMPLES_PER_PIXEL, MAX_CPU_TRIANGLES, MAX_CPU_WORK, NATIVE_CPU_POOL_BYTES}; +#[cfg(feature = "raytrace-cpu")] +pub(crate) use host::FRAME_METADATA_BYTES; +pub(crate) use host::Reservation; +pub use host::{ + CpuHost, HostKind, ImageHost, JobEnvironmentInfo, JobHandle, JobStatus, LinearAlphaConvention, LinearColourEncoding, LinearMasterInfo, + PartialPreviewInfo, PartialPreviewProjection, PreviewInfo, RenderFrame, RenderPartialPreview, RenderPreview, +}; +pub use image::{Admission, ImageTask, TaskPoll, admit, admit_geometry, admit_geometry_with_limits}; +pub use lens::ThinLens; +pub use lighting::{AreaLight, AreaLights, MAX_AREA_LIGHTS, StudioLighting, Sun, ToneMap}; +pub use png::PngTask; +pub use punctual::{PunctualDiagnostics, PunctualLightOptions, SpotConeOptions}; +pub use raster_lights::{ + deserialize as deserialize_raster_lights, deserialize_areas as deserialize_raster_area_lights, + deserialize_punctual as deserialize_raster_punctual_lights, validate as validate_raster_lights, validate_areas as validate_raster_area_lights, + validate_punctual as validate_raster_punctual_lights, +}; + +/// Native path-tracing ceilings, further restricted by the actual device. +/// Kept in the device-independent layer so saved intent and UI agree with execution. +pub const GPU_PATH_LIMITS: crate::RenderLimits = + crate::RenderLimits { max_dimension: 8192, max_pixels: 16_777_216, max_scratch_bytes: 8 * 1024 * 1024 * 1024 }; +pub const MAX_GPU_PATH_TRIANGLES: u64 = 8_000_000; +pub const MAX_GPU_PATH_BODIES: usize = 65_536; +pub const MAX_GPU_DIELECTRICS: usize = 32; + +/// 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 { + #[serde(skip_serializing_if = "aging::AgingStack::is_empty")] + pub aging: aging::AgingStack, + pub nested_media: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub volume: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub adaptive: Option, + /// Conditional Fresnel strata per primary sample; one keeps the old stream. + pub transmission_samples: u32, + + #[serde(default, skip_serializing_if = "finishing::Finishing::is_identity")] + pub finishing: finishing::Finishing, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub backdrop: Option, + #[serde(default)] + pub linear_exr: bool, + pub samples: u32, + pub max_depth: u32, + pub seed: u32, + pub exposure_ev: f64, + pub lens: Option, + pub lighting: Option, + pub tone_map: ToneMap, + /// Optional final spatial filter. Raw progressive accumulation remains unchanged. + pub denoise: bool, +} + +impl Default for JobOptions { + fn default() -> Self { + Self { + aging: Default::default(), + nested_media: false, + volume: None, + adaptive: None, + transmission_samples: 1, + finishing: Default::default(), + backdrop: None, + linear_exr: false, + samples: 64, + max_depth: 8, + seed: 0, + exposure_ev: 0.0, + lens: None, + lighting: None, + tone_map: ToneMap::default(), + denoise: false, + } + } +} + +impl JobOptions { + pub fn validate(&self) -> Result<()> { + self.aging.validate()?; + if let Some(volume) = self.volume { + volume.validate()?; + if volume.active() && self.transmission_samples != 1 { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "volume transport requires one transmission stratum; glass combinations are not supported", + )); + } + if volume.active() && self.denoise { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "volume scattering has no surface-denoiser guides; disable denoising explicitly", + )); + } + } + if let Some(adaptive) = self.adaptive { + adaptive.validate(self.samples)?; + } + if !matches!(self.transmission_samples, 1 | 2 | 4) { + return Err(JobError::new(ErrorCode::InvalidRequest, "transmission_samples must be 1, 2 or 4")); + } + self.finishing.validate()?; + if let Some(backdrop) = self.backdrop { + backdrop.validate()?; + } + if let Some(lighting) = self.lighting { + lighting.validate()?; + } + if let Some(lens) = self.lens { + lens.validate()?; + } + 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 sampling_report(&self) -> Option { + None + } + /// Optional raw linear companion, moved exactly once after PNG completion. + /// The host validates intent, bounds, hashes and retains its memory lease. + fn take_linear_exr(&mut self) -> Option> { + None + } + fn step(&mut self, units: usize) -> Result; +} +impl ImageWork for ImageTask { + fn step(&mut self, units: usize) -> Result { + 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 supports_aging(&self) -> bool { + false + } + fn supports_photographic(&self) -> bool { + false + } + fn supports_subsurface(&self) -> bool { + false + } + fn supports_nested_media(&self) -> bool { + false + } + fn supports_volume(&self) -> bool { + false + } + fn supports_adaptive_sampling(&self) -> bool { + false + } + fn supports_transmission_sampling(&self) -> bool { + false + } + fn supports_bloom(&self) -> bool { + false + } + fn supports_finishing(&self) -> bool { + false + } + fn supports_linear_exr(&self) -> bool { + false + } + /// Host-owned logical allocation pool. This is a ceiling, not eager allocation. + /// Registration snapshots and validates it; unknown executors retain 512 MiB. + fn memory_limit_bytes(&self) -> u64 { + 512 * 1024 * 1024 + } + fn descriptor(&self) -> Result; + fn admit(&self, scene: &crate::ProductScene, request: &ImageRequest, options: JobOptions) -> Result; + fn begin(&self, scene: crate::ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result>; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct JobId { + pub session: u64, + pub serial: u64, + pub generation: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Phase { + Queued, + Preparing, + Running, + Encoding, + Cancelling, + Cancelled, + Completed, + Failed, +} + +impl Phase { + pub fn terminal(self) -> bool { + matches!(self, Self::Cancelled | Self::Completed | Self::Failed) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct Progress { + pub phase: Phase, + pub done: u64, + pub total: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + InvalidRequest, + LimitExceeded, + AllocationFailed, + HostUnavailable, + QueueFull, + TimedOut, + Cancelled, + InvalidScene, + EncodingFailed, + WrongOwner, + UnknownJob, + NotCompleted, + Internal, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct JobError { + pub code: ErrorCode, + pub message: String, +} + +impl JobError { + pub fn new(code: ErrorCode, message: impl Into) -> Self { + Self { code, message: message.into() } + } +} + +impl fmt::Display for JobError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}: {}", self.code, self.message) + } +} +impl std::error::Error for JobError {} + +pub type Result = std::result::Result; + +#[derive(Clone, Default)] +pub struct CancelToken(Arc); + +impl CancelToken { + pub fn cancel(&self) { + self.0.store(true, Ordering::Release); + } + pub fn is_cancelled(&self) -> bool { + self.0.load(Ordering::Acquire) + } + pub fn check(&self) -> Result<()> { + if self.is_cancelled() { Err(JobError::new(ErrorCode::Cancelled, "render cancelled")) } else { Ok(()) } + } +} + +/// Per-request execution choice, independent of viewport graphics presets. +/// Keep both variants parseable in builds without optional raytracing, so those +/// builds return an explicit capability error before capturing model geometry. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Integrator { + #[default] + Raster, + Raytrace, +} + +/// Explicit scene-reflection transport, separate from opaque roughness bounds. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReflectionMode { + Mirror, + RoughSpecular, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReflectionBody { + pub body: String, + pub mode: ReflectionMode, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ReflectionOptions { + #[serde(deserialize_with = "bounded_reflection_bodies")] + pub bodies: Vec, + pub max_bounces: u8, + pub samples: u8, +} +impl Default for ReflectionOptions { + fn default() -> Self { + Self { bodies: Vec::new(), max_bounces: 2, samples: 4 } + } +} +fn bounded_reflection_bodies<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + struct Bodies; + impl<'de> serde::de::Visitor<'de> for Bodies { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most64 reflection body overrides") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut values = Vec::new(); + while let Some(value) = seq.next_element()? { + if values.len() == 64 { + return Err(serde::de::Error::custom("at most64 reflection bodies")); + } + values.push(value); + } + Ok(values) + } + } + d.deserialize_seq(Bodies) +} +impl ReflectionOptions { + pub fn validate(&self) -> Result<()> { + if !(1..=8).contains(&self.max_bounces) || !(1..=64).contains(&self.samples) || self.bodies.len() > 64 || self.bodies.capacity() > 64 { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection bounds: 1..8 bounces, 1..64 samples, at most64 body slots")); + } + for (index, body) in self.bodies.iter().enumerate() { + if body.body.is_empty() + || body.body.len() > 128 + || body.body.capacity() > 128 + || self.bodies.iter().take(index).any(|other| other.body == body.body) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection body names must be unique, nonempty and bounded to128 bytes")); + } + } + Ok(()) + } +} + +/// Linear-light runtime inputs. These are never design settings or GPU presets. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DirectionalLightOptions { + pub direction: [f64; 3], + pub color: [f64; 3], + pub intensity: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LightingPreset { + Neutral, + WarmCool, + KeyRim, +} + +impl LightingPreset { + /// Portable source values shared by CPU transport and light inspection. + pub fn directional_lights(self) -> Vec { + let light = |direction, color, intensity| DirectionalLightOptions { direction, color, intensity }; + match self { + Self::Neutral => crate::studio::LIGHTS.into_iter().map(|(d, intensity)| light([d.x, d.y, d.z], [1.0; 3], intensity)).collect(), + Self::WarmCool => vec![ + light([0.6, 0.0, 0.8], [1.0, 0.72, 0.48], 3.0), + light([-0.8, 0.0, 0.6], [0.45, 0.65, 1.0], 1.0), + light([0.0, -0.6, 0.8], [1.0; 3], 1.5), + ], + Self::KeyRim => vec![light([0.6, -0.4, 0.8], [1.0; 3], 3.0), light([-0.6, 0.4, 0.8], [0.6, 0.8, 1.0], 2.0)], + } + } +} + +/// Full world-space side vectors; U cross V is the emitting side. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RectangleLightOptions { + pub center_mm: [f64; 3], + pub edge_u_mm: [f64; 3], + pub edge_v_mm: [f64; 3], + pub color: [f64; 3], + pub intensity: f64, +} + +impl RectangleLightOptions { + /// Canonical numerical domain shared by CPU transport and schematic Raster. + pub(crate) fn validate(&self) -> Result<()> { + use solidcraft_geom::Vec3; + let vec = |v: [f64; 3]| Vec3::new(v[0], v[1], v[2]); + let c = vec(self.center_mm); + let u = vec(self.edge_u_mm); + let v = vec(self.edge_v_mm); + if !c.is_finite() + || !u.is_finite() + || !v.is_finite() + || !self.color.iter().all(|x| x.is_finite() && (0.0..=1.0).contains(x)) + || !self.intensity.is_finite() + || !(0.0..=64.0).contains(&self.intensity) + || !(1e-6..=1e6).contains(&u.len()) + || !(1e-6..=1e6).contains(&v.len()) + || (u.dot(v) / (u.len() * v.len())).abs() > 1e-10 + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid finite rectangular light")); + } + for a in [-0.5, 0.5] { + for b in [-0.5, 0.5] { + let p = c + u * a + v * b; + if !p.is_finite() || [p.x, p.y, p.z].into_iter().any(|x| x.abs() > 1e9) { + return Err(JobError::new(ErrorCode::InvalidRequest, "rectangular light corner exceeds world bounds")); + } + } + } + Ok(()) + } +} + +/// Explicit visual rotation about a certified planar face's outward normal. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AnisotropicOrientation { + #[default] + Zero, + QuarterTurn, +} + +/// Runtime-only captured planar face selector; no persistent naming is invented. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnisotropicFaceOptions { + pub body_index: usize, + #[serde(deserialize_with = "bounded_anisotropic_body_name")] + pub body_name: String, + pub face: u32, + pub tangent: [f64; 3], + pub orientation: AnisotropicOrientation, + pub roughness_x: f64, + pub roughness_y: f64, +} + +fn bounded_anisotropic_body_name<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + struct Name; + impl serde::de::Visitor<'_> for Name { + type Value = String; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("captured body name of 1..1024 bytes") + } + fn visit_str(self, value: &str) -> std::result::Result { + if value.is_empty() || value.len() > 1024 { + return Err(E::custom("captured body name of 1..1024 bytes required")); + } + let mut name = String::new(); + name.try_reserve_exact(value.len()).map_err(E::custom)?; + name.push_str(value); + Ok(name) + } + } + d.deserialize_str(Name) +} + +/// Emission is relative linear-sRGB radiance, independent of reflected color. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EmissionSides { + #[default] + Front, + Both, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SurfaceEmission { + pub body_index: usize, + #[serde(deserialize_with = "bounded_emission_body")] + pub body: String, + pub color: [f64; 3], + pub strength: f64, + #[serde(default)] + pub sides: EmissionSides, +} + +fn bounded_emission_body<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + struct Name; + impl<'de> serde::de::Visitor<'de> for Name { + type Value = String; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a nonempty captured body name of at most 256 bytes") + } + fn visit_str(self, value: &str) -> std::result::Result { + if value.is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + return Err(E::custom("invalid surface emission body name")); + } + let mut name = String::new(); + name.try_reserve_exact(value.len()).map_err(E::custom)?; + name.push_str(value); + Ok(name) + } + } + d.deserialize_str(Name) +} + +impl SurfaceEmission { + pub fn validate(&self) -> Result<()> { + if self.body.is_empty() + || self.body.len() > 256 + || self.body.capacity() > 256 + || self.body.chars().any(char::is_control) + || !self.color.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) + || !self.strength.is_finite() + || !(0.0..=64.0).contains(&self.strength) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded surface emission")); + } + Ok(()) + } +} + +fn bounded_emissions<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { + struct Emitters; + impl<'de> serde::de::Visitor<'de> for Emitters { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most 32 surface emitters") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut values = Vec::new(); + while let Some(value) = seq.next_element::()? { + if values.len() == 32 { + return Err(serde::de::Error::custom("at most 32 surface emitters")); + } + value.validate().map_err(serde::de::Error::custom)?; + values.try_reserve_exact(1).map_err(serde::de::Error::custom)?; + values.push(value); + } + Ok(values) + } + } + deserializer.deserialize_seq(Emitters).map(Some) +} + +/// Explicit runtime optics; never inferred from opacity or saved into a design. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DielectricBoundary { + ThinSheet, + ClosedBox, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DielectricOptions { + pub body_index: usize, + #[serde(deserialize_with = "bounded_dielectric_body_name")] + pub body_name: String, + pub boundary: DielectricBoundary, + pub ior: f64, + /// Per-channel Beer-Lambert extinction, inverse millimetres. + pub absorption_per_mm: [f64; 3], + /// Virtual normal thickness for ThinSheet only; ClosedBox requires zero. + pub thickness_mm: f64, +} + +/// Explicit constant secondary-ray environment; independent of display background. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RaytraceEnvironmentOptions { + pub color: [f64; 3], + pub intensity: f64, +} + +fn bounded_dielectric_body_name<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result { + struct Name; + impl serde::de::Visitor<'_> for Name { + type Value = String; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("captured body name of 1..1024 bytes") + } + fn visit_str(self, value: &str) -> std::result::Result { + if value.is_empty() || value.len() > 1024 { + return Err(E::custom("captured body name of 1..1024 bytes required")); + } + let mut name = String::new(); + name.try_reserve_exact(value.len()).map_err(E::custom)?; + name.push_str(value); + Ok(name) + } + } + deserializer.deserialize_str(Name) +} + +fn bounded_dielectrics<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result, D::Error> { + struct Inputs; + impl<'de> serde::de::Visitor<'de> for Inputs { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most eight dielectric overrides") + } + fn visit_seq>(self, mut sequence: A) -> std::result::Result { + let mut inputs = Vec::new(); + inputs.try_reserve_exact(8).map_err(serde::de::Error::custom)?; + while let Some(input) = sequence.next_element()? { + if inputs.len() == 8 { + return Err(serde::de::Error::custom("at most eight dielectric overrides")); + } + inputs.push(input); + } + Ok(inputs) + } + } + deserializer.deserialize_seq(Inputs) +} + +/// CPU camera sampling, independent of the registered GPU's `progressive` wire flag. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct CpuProgressiveOptions { + pub samples_per_pixel: u32, + pub seed: u32, +} + +impl Default for CpuProgressiveOptions { + fn default() -> Self { + Self { samples_per_pixel: 16, seed: 0 } + } +} + +impl CpuProgressiveOptions { + pub const MAX_PIXELS: u64 = 1_048_576; + pub const MAX_CAMERA_SAMPLES: u64 = 16_777_216; + + pub fn validate(&self) -> Result<()> { + if !(1..=64).contains(&self.samples_per_pixel) { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU progressive samples_per_pixel must be 1..64")); + } + Ok(()) + } + + /// Compatibility entry point: a caller that supplies no profile retains Compact. + pub fn validate_image(&self, width: u32, height: u32) -> Result<()> { + self.validate_image_with_budget(width, height, CpuBudget::Compact) + } + + pub fn validate_image_with_budget(&self, width: u32, height: u32, budget: CpuBudget) -> Result<()> { + budget.validate_image(width, height, Some(*self)) + } + + /// At most two reusable checkpoint reservations. A pinned consumer keeps its + /// slot charged; it does not authorize a new allocation per pass. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn checkpoint_slots(&self) -> u32 { + self.samples_per_pixel.saturating_sub(1).min(2) + } +} + +/// Runtime CPU dielectric transport policy, independent of resource and preview budgets. +/// StrictTir preserves deterministic TIR and refuses positive dielectric-depth tails. +/// It does not promise convergence or general physical glass support. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CpuDielectricTransport { + #[default] + LegacyBounded, + StrictTir, +} + +impl CpuDielectricTransport { + pub fn is_legacy(&self) -> bool { + *self == Self::LegacyBounded + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct RaytraceOptions { + #[serde(skip_serializing_if = "CpuDielectricTransport::is_legacy")] + pub dielectric_transport: CpuDielectricTransport, + #[serde(skip_serializing_if = "directional_shadow_disabled")] + pub directional_shadow_transmission: bool, + #[serde(skip_serializing_if = "CpuBudget::is_compact")] + pub budget: CpuBudget, + #[serde(skip_serializing_if = "Option::is_none")] + pub progressive: Option, + #[serde(deserialize_with = "bounded_dielectrics", skip_serializing_if = "Vec::is_empty")] + pub dielectrics: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub environment: Option, + #[serde(deserialize_with = "crate::surface_patterns::deserialize_effects", skip_serializing_if = "Option::is_none")] + pub surface_effects: Option>, + #[serde(deserialize_with = "bounded_emissions", skip_serializing_if = "Option::is_none")] + pub emissions: Option>, + /// Transient spatial pixel-box samples; independent of reflection attempts. + #[serde(skip_serializing_if = "single_primary_sample")] + pub primary_samples: u8, + pub reflections: Option, + pub anisotropic_faces: [Option; 2], + #[serde(deserialize_with = "punctual::bounded_punctual", skip_serializing_if = "Option::is_none")] + pub punctual_lights: Option>, + #[serde(deserialize_with = "bounded_area_lights", skip_serializing_if = "Option::is_none")] + pub area_lights: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub area_samples: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub seed: Option, + pub preset: Option, + #[serde(deserialize_with = "bounded_lights", skip_serializing_if = "Option::is_none")] + pub lights: Option>, + pub exposure_ev: f64, + pub shadows: bool, +} + +impl Default for RaytraceOptions { + fn default() -> Self { + Self { + dielectric_transport: CpuDielectricTransport::LegacyBounded, + directional_shadow_transmission: false, + budget: CpuBudget::Compact, + progressive: None, + punctual_lights: None, + area_lights: None, + area_samples: None, + seed: None, + primary_samples: 1, + emissions: None, + surface_effects: None, + dielectrics: Vec::new(), + environment: None, + anisotropic_faces: [None, None], + reflections: None, + preset: None, + lights: None, + exposure_ev: 0.0, + shadows: true, + } + } +} + +fn directional_shadow_disabled(value: &bool) -> bool { + !*value +} + +fn single_primary_sample(samples: &u8) -> bool { + *samples == 1 +} + +fn bounded_lights<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { + struct Lights; + impl<'de> serde::de::Visitor<'de> for Lights { + type Value = Vec; + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("at most eight directional lights") + } + fn visit_seq>(self, mut sequence: A) -> std::result::Result { + let mut lights = Vec::new(); + while let Some(light) = sequence.next_element()? { + if lights.len() == 8 { + return Err(serde::de::Error::custom("at most eight directional lights")); + } + lights.push(light); + } + Ok(lights) + } + } + deserializer.deserialize_seq(Lights).map(Some) +} + +fn bounded_area_lights<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { + struct AreaLights; + impl<'de> serde::de::Visitor<'de> for AreaLights { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most four rectangular lights") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut lights = Vec::new(); + while let Some(light) = seq.next_element()? { + if lights.len() == 4 { + return Err(serde::de::Error::custom("at most four rectangular lights")); + } + if lights.is_empty() { + lights.try_reserve_exact(4).map_err(serde::de::Error::custom)?; + if lights.capacity() > 4 { + return Err(serde::de::Error::custom("rectangular light capacity exceeds four")); + } + } + lights.push(light); + } + Ok(lights) + } + } + struct Optional; + impl<'de> serde::de::Visitor<'de> for Optional { + type Value = Option>; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an optional bounded rectangular-light list") + } + fn visit_none(self) -> std::result::Result { + Ok(None) + } + fn visit_unit(self) -> std::result::Result { + Ok(None) + } + fn visit_some>(self, d: D) -> std::result::Result { + d.deserialize_seq(AreaLights).map(Some) + } + } + deserializer.deserialize_option(Optional) +} + +impl RaytraceOptions { + /// Dynamic dielectric capacities in one task or immutable request copy. + pub(crate) fn retained_dielectric_bytes(&self) -> Result { + let limit = || JobError::new(ErrorCode::LimitExceeded, "dielectric request capacity overflow"); + let mut bytes = (self.dielectrics.capacity() as u64).checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + for input in &self.dielectrics { + bytes = bytes.checked_add(input.body_name.capacity() as u64).ok_or_else(limit)?; + } + Ok(bytes) + } + /// Dynamic surface-effect capacities in one task or retained request copy. + pub(crate) fn retained_surface_effect_bytes(&self) -> Result { + let limit = || JobError::new(ErrorCode::LimitExceeded, "surface effect capacity overflow"); + let slots = self.surface_effects.as_ref().map_or(0, Vec::capacity) as u64; + let mut bytes = slots.checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + if let Some(values) = &self.surface_effects { + for value in values { + bytes = bytes.checked_add(value.body.capacity() as u64).ok_or_else(limit)?; + } + } + Ok(bytes) + } + /// Dynamic emission capacities in one options copy; included in both task and Record admission. + pub(crate) fn retained_emission_bytes(&self) -> Result { + let limit = || JobError::new(ErrorCode::LimitExceeded, "surface emission capacity overflow"); + let slots = self.emissions.as_ref().map_or(0, Vec::capacity) as u64; + let mut bytes = slots.checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + if let Some(values) = &self.emissions { + for value in values { + bytes = bytes.checked_add(value.body.capacity() as u64).ok_or_else(limit)?; + } + } + Ok(bytes) + } + /// One capacity calculation shared by host and engine preflight. + pub fn retained_bytes(&self) -> Result { + self.validate()?; + let limit = || JobError::new(ErrorCode::LimitExceeded, "raytrace request capacity overflow"); + let mut bytes = self + .lights + .as_ref() + .map_or(Some(0), |l| (l.capacity() as u64).checked_mul(std::mem::size_of::() as u64)) + .ok_or_else(limit)?; + for (capacity, size) in [ + (self.area_lights.as_ref().map_or(0, Vec::capacity), std::mem::size_of::()), + (self.punctual_lights.as_ref().map_or(0, Vec::capacity), std::mem::size_of::()), + ] { + bytes = bytes.checked_add((capacity as u64).checked_mul(size as u64).ok_or_else(limit)?).ok_or_else(limit)?; + } + if let Some(reflections) = &self.reflections { + let slots = (reflections.bodies.capacity() as u64).checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + bytes = bytes.checked_add(slots).ok_or_else(limit)?; + for body in &reflections.bodies { + bytes = bytes.checked_add(body.body.capacity() as u64).ok_or_else(limit)?; + } + } + for target in self.anisotropic_faces.iter().flatten() { + bytes = bytes.checked_add(target.body_name.capacity() as u64).ok_or_else(limit)?; + } + bytes = bytes.checked_add(self.retained_emission_bytes()?).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_surface_effect_bytes()?).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_dielectric_bytes()?).ok_or_else(limit)?; + Ok(bytes) + } + /// No environment NEE on selected reflectors; rough transport must be purely metallic. + /// Rejecting every nonmetallic effective face prevents silently dropping its diffuse HDR. + pub fn validate_environment_reflections(&self, scene: &crate::ProductScene) -> Result<()> { + self.validate()?; + if self.environment.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "choose either the HDR input or constant secondary environment")); + } + if let Some(reflections) = &self.reflections { + for selector in &reflections.bodies { + let mut bodies = scene.meshes.iter().filter(|b| b.name == selector.body); + let body = bodies.next().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "environment reflection body missing"))?; + if bodies.next().is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "ambiguous environment reflection body")); + } + if selector.mode == ReflectionMode::RoughSpecular + && (body.surface.is_none_or(|s| s.metallic() != 1.0) || body.faces.iter().any(|f| f.surface.is_none_or(|s| s.metallic() != 1.0))) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "HDR rough reflection requires fully metallic body and face surfaces; diffuse/specular partition is not supported", + )); + } + } + } + for target in self.anisotropic_faces.iter().flatten() { + let mode = self.reflections.as_ref().and_then(|r| r.bodies.iter().find(|b| b.body == target.body_name).map(|b| b.mode)); + if mode != Some(ReflectionMode::RoughSpecular) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "HDR anisotropy requires a selected fully metallic rough reflector; anisotropic HDR direct lighting is not supported", + )); + } + } + Ok(()) + } + pub fn validate(&self) -> Result<()> { + // Opaque reflection has a separate bounded continuation policy. Do not + // advertise strict dielectric tails across that unqualified consumer. + if self.dielectric_transport == CpuDielectricTransport::StrictTir && self.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "strict CPU dielectric transport does not support selected opaque reflections yet")); + } + if let Some(progressive) = self.progressive { + self.budget.validate_samples(progressive.samples_per_pixel)?; + if self.primary_samples != 1 || self.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty() && r.samples != 1) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU progressive requires primary_samples: 1 and one reflection attempt per camera sample", + )); + } + // Smooth certified dielectric trees now complete one real camera + // sample before film accumulation. Anisotropic progressive transport + // remains unsupported; geometry/identity certificates run at capture. + if self.anisotropic_faces.iter().any(Option::is_some) { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU progressive does not support anisotropic inputs; use fixed sampling")); + } + } + if self.environment.is_some_and(|environment| { + !environment.color.into_iter().all(|v| v.is_finite() && (0.0..=1.0).contains(&v)) + || !environment.intensity.is_finite() + || !(0.0..=64.0).contains(&environment.intensity) + }) { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid constant raytrace environment")); + } + if self.dielectrics.len() > 8 || self.dielectrics.capacity() > 8 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight dielectric overrides")); + } + for (index, input) in self.dielectrics.iter().enumerate() { + if input.body_name.is_empty() + || input.body_name.len() > 1024 + || input.body_name.capacity() > 1024 + || !input.ior.is_finite() + || !(1.0..=3.0).contains(&input.ior) + || !input.absorption_per_mm.into_iter().all(|v| v.is_finite() && (0.0..=100.0).contains(&v)) + || !input.thickness_mm.is_finite() + || !(0.0..=10000.0).contains(&input.thickness_mm) + || (input.boundary == DielectricBoundary::ClosedBox && input.thickness_mm != 0.0) + || self.dielectrics.iter().take(index).any(|previous| previous.body_index == input.body_index) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid or duplicate dielectric override")); + } + } + if let Some(values) = &self.surface_effects { + if values.capacity() > 32 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most 32 surface-effect reserved slots")); + } + crate::surface_patterns::validate_effects(values)?; + } + if let Some(values) = &self.emissions { + if values.len() > 32 || values.capacity() > 32 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most 32 surface emitters")); + } + for (i, value) in values.iter().enumerate() { + value.validate()?; + if values.iter().take(i).any(|other| other.body_index == value.body_index) { + return Err(JobError::new(ErrorCode::InvalidRequest, "duplicate surface emission target")); + } + } + } + let area_count = self.area_lights.as_ref().map_or(0, Vec::len); + if self.area_lights.as_ref().is_some_and(|v| v.len() > 4 || v.capacity() > 4) { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most four rectangular lights and reserved slots")); + } + if area_count == 0 && (self.area_samples.is_some() || self.seed.is_some()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "area_samples and seed require nonempty area_lights")); + } + if self.area_samples.is_some_and(|n| !matches!(n, 1 | 4 | 16 | 64)) { + return Err(JobError::new(ErrorCode::InvalidRequest, "area_samples must be 1, 4, 16 or 64")); + } + let directional_count = self.lights.as_ref().map_or_else(|| if self.preset == Some(LightingPreset::KeyRim) { 2 } else { 3 }, Vec::len); + if directional_count + .checked_add(area_count) + .and_then(|n| n.checked_add(self.punctual_lights.as_ref().map_or(0, Vec::len))) + .is_none_or(|n| n > 20) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most twenty combined directional, punctual and rectangular lights")); + } + if let Some(lights) = &self.area_lights { + for light in lights { + light.validate()?; + } + } + if let Some(lights) = &self.punctual_lights { + if lights.len() > 8 || lights.capacity() > 8 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight point/spot sources and reserved slots")); + } + for light in lights { + light.validate()?; + } + } + if !matches!(self.primary_samples, 1 | 4 | 16) { + return Err(JobError::new(ErrorCode::InvalidRequest, "primary samples must be exactly 1, 4 or 16")); + } + + if let Some(reflections) = &self.reflections { + reflections.validate()?; + } + for (i, target) in self.anisotropic_faces.iter().enumerate().filter_map(|(i, target)| target.as_ref().map(|target| (i, target))) { + if target.body_name.is_empty() + || target.body_name.len() > 1024 + || target.body_name.capacity() > 1024 + || !target.tangent.iter().all(|v| v.is_finite()) + || !target.tangent.iter().any(|v| *v != 0.0) + || ![target.roughness_x, target.roughness_y].into_iter().all(|v| v.is_finite() && (crate::surface::MIN_ROUGHNESS..=1.0).contains(&v)) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded anisotropic planar face options")); + } + if self.anisotropic_faces.iter().skip(i + 1).flatten().any(|other| target.body_index == other.body_index && target.face == other.face) { + return Err(JobError::new(ErrorCode::InvalidRequest, "duplicate anisotropic captured face")); + } + } + if self.reflections.as_ref().is_some_and(|r| { + r.bodies.iter().any(|b| b.mode == ReflectionMode::Mirror && self.anisotropic_faces.iter().flatten().any(|t| t.body_name == b.body)) + }) { + return Err(JobError::new(ErrorCode::InvalidRequest, "delta mirror cannot have anisotropic rough axes")); + } + if self.preset.is_some() && self.lights.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "choose either a lighting preset or custom lights")); + } + if !self.exposure_ev.is_finite() || !(-32.0..=32.0).contains(&self.exposure_ev) { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace exposure_ev must be finite and within -32..32")); + } + if let Some(lights) = &self.lights { + if lights.len() > 8 || lights.capacity() > 8 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight directional lights")); + } + for light in lights { + let direction_valid = light.direction.iter().all(|n| n.is_finite() && n.abs() <= 1e9) && light.direction.iter().any(|n| *n != 0.0); + if !direction_valid + || !light.color.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) + || !light.intensity.is_finite() + || !(0.0..=64.0).contains(&light.intensity) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded directional light")); + } + } + } + if self.directional_shadow_transmission + && (!self.shadows + || self.dielectrics.is_empty() + || self.reflections.is_some() + || self.anisotropic_faces.iter().any(Option::is_some) + || self.environment.is_some() + || self.punctual_lights.as_ref().is_some_and(|lights| !lights.is_empty()) + || self.area_lights.as_ref().is_some_and(|lights| !lights.is_empty())) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "directional shadow transmission requires shadows and selected dielectrics without reflections, anisotropy, environment or local lights", + )); + } + Ok(()) + } +} + +/// Fully resolved input; no mutable session, topology graph or GPU resources. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImageRequest { + /// Resolved Raster-only capture of RenderSetup.exposure_ev, never a second authority. + #[serde(default, skip_serializing_if = "zero_raster_exposure")] + pub raster_exposure_ev: f64, + /// Explicit transient opaque Raster rig; None keeps the original implicit studio. + #[serde(default, deserialize_with = "deserialize_raster_lights", skip_serializing_if = "Option::is_none")] + pub raster_lights: Option>, + /// Runtime-only local rig. Any explicit local collection suppresses implicit studio lights. + #[serde(default, deserialize_with = "deserialize_raster_punctual_lights", skip_serializing_if = "Option::is_none")] + pub raster_punctual_lights: Option>, + #[serde(default, deserialize_with = "deserialize_raster_area_lights", skip_serializing_if = "Option::is_none")] + pub raster_area_lights: Option>, + /// Transient visibility of the three implicit studio lights; never saved in a design. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub studio_weights: Option<[f64; 3]>, + /// Captured GPU resources stay in admitted work, never in status or saved data. + #[serde(skip)] + pub environment: Option>, + #[serde(skip)] + pub textures: Option>, + #[serde(default)] + pub integrator: Integrator, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub raytrace: Option, + pub camera: Camera, + pub width: u32, + pub height: u32, + pub background: [u8; 3], + pub transparent_background: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ColourEncoding { + Srgb, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum AlphaConvention { + Straight, +} + +impl ImageRequest { + pub fn has_local_raster_lights(&self) -> bool { + self.raster_punctual_lights.is_some() || self.raster_area_lights.is_some() + } + + pub fn has_explicit_raster_lights(&self) -> bool { + self.raster_lights.is_some() || self.has_local_raster_lights() + } + + /// Only the new local-rig route charges each bounded light evaluation. + /// Existing directional and implicit routes retain their original pixel budget. + pub(super) fn raster_light_work_factor(&self) -> Result { + if !self.has_local_raster_lights() { + return Ok(1); + } + self.validate_raster_request()?; + let count = self + .raster_lights + .as_ref() + .map_or(0, Vec::len) + .checked_add(self.raster_punctual_lights.as_ref().map_or(0, Vec::len)) + .and_then(|n| n.checked_add(self.raster_area_lights.as_ref().map_or(0, Vec::len))) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster light work overflow"))?; + u64::try_from(count.max(1)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "Raster light work overflow")) + } + + /// Reject explicit Raster intent before allocating or entering another producer. + pub fn validate_raster_request(&self) -> Result<()> { + if !self.raster_exposure_ev.is_finite() || !(-32.0..=32.0).contains(&self.raster_exposure_ev) { + return Err(JobError::new(ErrorCode::InvalidRequest, "Raster exposure must be finite and within -32..32 EV")); + } + if self.raster_exposure_ev != 0.0 + && (self.integrator != Integrator::Raster || self.raytrace.is_some() || self.environment.is_some() || self.textures.is_some()) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "Raster exposure cannot enter another integrator or captured GPU resources")); + } + raster_lights::validate(&self.raster_lights)?; + raster_lights::validate_punctual(&self.raster_punctual_lights)?; + raster_lights::validate_areas(&self.raster_area_lights)?; + if self.has_explicit_raster_lights() + && (self.integrator != Integrator::Raster + || self.raytrace.is_some() + || self.studio_weights.is_some() + || self.environment.is_some() + || self.textures.is_some()) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "explicit Raster lights require Raster without raytrace, GPU resources or studio_weights", + )); + } + Ok(()) + } + + pub fn raster_lights_retained_bytes(&self) -> Result { + raster_lights::retained_bytes(&self.raster_lights)? + .checked_add(raster_lights::local_retained_bytes(&self.raster_punctual_lights, &self.raster_area_lights)?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster light retained size overflow")) + } + + pub(super) fn raster_lights_task_bytes(&self) -> Result { + raster_lights::task_bytes(&self.raster_lights)? + .checked_add(raster_lights::local_task_bytes(&self.raster_punctual_lights, &self.raster_area_lights)?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster task light size overflow")) + } + + /// Internal status/task copy: the new Vec allocation is bounded and fallible. + pub(super) fn try_clone_for_host(&self) -> Result { + self.validate_raster_request()?; + // Preserve the old path, including existing unrelated payload semantics. + if !self.has_explicit_raster_lights() { + return Ok(self.clone()); + } + Ok(Self { + raster_exposure_ev: self.raster_exposure_ev, + raster_lights: raster_lights::try_copy(&self.raster_lights)?, + raster_punctual_lights: raster_lights::try_copy_punctual(&self.raster_punctual_lights)?, + raster_area_lights: raster_lights::try_copy_areas(&self.raster_area_lights)?, + studio_weights: self.studio_weights, + environment: self.environment.clone(), + textures: self.textures.clone(), + integrator: self.integrator, + raytrace: None, // validated absent above, never clone-then-clear + camera: self.camera, + width: self.width, + height: self.height, + background: self.background, + transparent_background: self.transparent_background, + }) + } + pub fn cpu_budget(&self) -> CpuBudget { + if self.integrator == Integrator::Raytrace { + self.raytrace.as_ref().map_or(CpuBudget::Compact, |options| options.budget) + } else { + CpuBudget::Compact + } + } + + /// Small GPU resource summaries survive work completion and keep their own host lease. + pub fn retained_resource_metadata_bytes(&self) -> u64 { + let environment = self + .environment + .as_ref() + .map_or(0, |source| (std::mem::size_of::() + source.info().source_sha256.len()) as u64); + environment + if self.textures.is_some() { std::mem::size_of::() as u64 } else { 0 } + } +} + +fn zero_raster_exposure(value: &f64) -> bool { + *value == 0.0 +} + +#[derive(Clone, Debug, Serialize)] +pub struct FrameInfo { + pub job: JobId, + pub scene_generation: u64, + pub backend: BackendId, + pub executor: ExecutorId, + pub width: u32, + pub height: u32, + pub encoding: ColourEncoding, + pub alpha: AlphaConvention, + /// Exact encoded PNG length, not pixel storage or reserved Vec capacity. + pub png_bytes: u64, + /// Cached lowercase SHA-256 of those encoded bytes, computed before completion. + pub png_sha256: String, +} +#[cfg(test)] +mod runtime_request_roundtrip_tests { + + fn raster_local_test_request() -> ImageRequest { + serde_json::from_value( + serde_json::json!({"camera":crate::Camera::default(),"width":8,"height":8,"background":[0,0,0],"transparent_background":false}), + ) + .unwrap() + } + + fn raster_local_test_point() -> PunctualLightOptions { + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 2.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + } + } + + fn raster_local_test_rectangle() -> RectangleLightOptions { + RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 2.0, + } + } + + #[test] + fn raster_local_wire_omission_null_empty_and_host_copy_keep_distinct_intent() { + let legacy = raster_local_test_request(); + let wire = serde_json::to_value(&legacy).unwrap(); + assert!(wire.get("raster_punctual_lights").is_none()); + assert!(wire.get("raster_area_lights").is_none()); + assert!(!legacy.has_explicit_raster_lights()); + let mut null = wire.clone(); + null["raster_punctual_lights"] = serde_json::Value::Null; + null["raster_area_lights"] = serde_json::Value::Null; + let decoded: ImageRequest = serde_json::from_value(null).unwrap(); + assert_eq!(serde_json::to_value(decoded).unwrap(), wire); + for key in ["raster_punctual_lights", "raster_area_lights"] { + let mut explicit = wire.clone(); + explicit[key] = serde_json::json!([]); + let input: ImageRequest = serde_json::from_value(explicit).unwrap(); + assert!(input.has_explicit_raster_lights() && input.has_local_raster_lights()); + assert!(input.raster_lights.is_none(), "no implicit directional materialisation"); + assert_eq!(input.raster_light_work_factor().unwrap(), 1); + let copy = input.try_clone_for_host().unwrap(); + assert_eq!(serde_json::to_value(copy).unwrap(), serde_json::to_value(input).unwrap()); + } + } + + #[test] + fn raster_local_eight_shared_point_spot_four_areas_and_directional_caps_are_independent() { + let mut input = raster_local_test_request(); + let point = raster_local_test_point(); + let mut spot = point; + spot.cone = Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); + input.raster_lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]); + assert_eq!(input.raster_light_work_factor().unwrap(), 1, "old directional work path unchanged"); + input.raster_punctual_lights = Some(vec![point, spot, point, spot, point, spot, point, spot]); + input.raster_area_lights = Some(vec![raster_local_test_rectangle(); 4]); + input.validate_raster_request().unwrap(); + assert_eq!(input.raster_light_work_factor().unwrap(), 20); + input.raster_punctual_lights.as_mut().unwrap().push(point); + assert_eq!(input.validate_raster_request().unwrap_err().code, ErrorCode::InvalidRequest); + assert!(serde_json::from_value::(serde_json::to_value(&input).unwrap()).is_err()); + input.raster_punctual_lights = Some(vec![point]); + input.raster_area_lights.as_mut().unwrap().push(raster_local_test_rectangle()); + assert!(input.validate_raster_request().is_err()); + assert!(serde_json::from_value::(serde_json::to_value(input).unwrap()).is_err()); + } + + #[test] + fn raster_local_spare_capacities_refuse_before_copy_or_task_reservation() { + let mut input = raster_local_test_request(); + input.raster_punctual_lights = Some(Vec::with_capacity(9)); + assert!(input.try_clone_for_host().is_err()); + assert!(input.raster_lights_retained_bytes().is_err()); + assert!(input.raster_lights_task_bytes().is_err()); + input.raster_punctual_lights = None; + input.raster_area_lights = Some(Vec::with_capacity(5)); + assert!(input.try_clone_for_host().is_err()); + assert!(input.raster_lights_retained_bytes().is_err()); + assert!(input.raster_lights_task_bytes().is_err()); + } + + #[test] + fn raster_local_fallible_fixed_dto_copy_preserves_values_and_accounts_both_families() { + let mut input = raster_local_test_request(); + input.raster_punctual_lights = Some(vec![raster_local_test_point()]); + input.raster_area_lights = Some(vec![raster_local_test_rectangle()]); + let expected = (input.raster_punctual_lights.as_ref().unwrap().capacity() * std::mem::size_of::() + + input.raster_area_lights.as_ref().unwrap().capacity() * std::mem::size_of::()) as u64; + assert_eq!(input.raster_lights_retained_bytes().unwrap(), expected); + let task_fee = (8 * std::mem::size_of::() + 4 * std::mem::size_of::()) as u64; + assert_eq!(input.raster_lights_task_bytes().unwrap(), task_fee); + let copy = input.try_clone_for_host().unwrap(); + assert_eq!(copy.raster_punctual_lights, input.raster_punctual_lights); + assert_eq!(copy.raster_area_lights, input.raster_area_lights); + assert!(copy.raster_lights_retained_bytes().unwrap() <= task_fee); + input.raster_punctual_lights.as_mut().unwrap()[0].intensity = 0.0; + input.raster_area_lights.as_mut().unwrap()[0].intensity = 0.0; + assert_eq!(copy.raster_punctual_lights.as_ref().unwrap()[0].intensity, 2.0); + assert_eq!(copy.raster_area_lights.as_ref().unwrap()[0].intensity, 2.0); + } + + #[test] + fn raster_local_empty_intent_still_refuses_other_producers_and_implicit_weights() { + for family in [0, 1] { + let mut input = raster_local_test_request(); + if family == 0 { + input.raster_punctual_lights = Some(Vec::new()); + } else { + input.raster_area_lights = Some(Vec::new()); + } + input.studio_weights = Some([0.0; 3]); + assert!(input.validate_raster_request().is_err()); + input.studio_weights = None; + input.raytrace = Some(Default::default()); + assert!(input.validate_raster_request().is_err()); + input.raytrace = None; + input.integrator = Integrator::Raytrace; + assert!(input.validate_raster_request().is_err()); + assert!(super::interactive::cpu_request(&input).is_err()); + } + } + + #[test] + fn raster_local_shared_rectangle_validator_preserves_canonical_bounds_and_error_order() { + let mut rectangle = raster_local_test_rectangle(); + rectangle.color = [0.0; 3]; + rectangle.intensity = 0.0; + rectangle.edge_u_mm = [1.0, 1.0, 0.0]; + assert_eq!(rectangle.validate().unwrap_err().message, "invalid finite rectangular light"); + rectangle = raster_local_test_rectangle(); + rectangle.center_mm = [1e9, 0.0, 0.0]; + assert_eq!(rectangle.validate().unwrap_err().message, "rectangular light corner exceeds world bounds"); + let mut input = raster_local_test_request(); + input.raster_area_lights = Some(vec![rectangle.clone()]); + assert!(input.validate_raster_request().is_err()); + let options = RaytraceOptions { area_lights: Some(vec![rectangle]), ..Default::default() }; + assert_eq!(options.validate().unwrap_err().message, "rectangular light corner exceeds world bounds"); + } + + #[test] + fn raster_light_wire_is_nullable_bounded_strict_and_fallibly_copied() { + #[derive(Serialize, Deserialize)] + #[serde(deny_unknown_fields)] + struct Rig { + #[serde(default, deserialize_with = "super::raster_lights::deserialize", skip_serializing_if = "Option::is_none")] + raster_lights: Option>, + } + use serde_json::json; + for value in [json!({}), json!({"raster_lights":null})] { + let rig: Rig = serde_json::from_value(value).unwrap(); + assert!(rig.raster_lights.is_none()); + assert_eq!(serde_json::to_value(rig).unwrap(), json!({})); + } + let light = json!({"direction":[0.0,0.0,1.0],"color":[0.25,0.5,1.0],"intensity":2.0}); + for count in [0, 1, 8] { + let rig: Rig = serde_json::from_value(json!({"raster_lights":vec![light.clone();count]})).unwrap(); + assert_eq!(rig.raster_lights.as_ref().unwrap().len(), count); + assert!(rig.raster_lights.as_ref().unwrap().capacity() <= 8); + let copy = super::raster_lights::try_copy(&rig.raster_lights).unwrap(); + assert_eq!(copy, rig.raster_lights); + assert!(copy.as_ref().unwrap().capacity() <= 8); + assert_eq!(serde_json::to_value(rig).unwrap(), json!({"raster_lights":vec![light.clone();count]})); + } + assert!(serde_json::from_value::(json!({"raster_lights":vec![light.clone();9]})).is_err()); + for value in [ + json!(true), + json!({}), + json!([{"direction":[0,0,0],"color":[1,1,1],"intensity":0}]), + json!([{"direction":[0,0,1],"color":[1,1,1],"intensity":1,"shadows":true}]), + ] { + assert!(serde_json::from_value::(json!({"raster_lights":value})).is_err()); + } + let mut excessive = Vec::with_capacity(9); + excessive.push(DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + assert!(super::raster_lights::try_copy(&Some(excessive)).is_err()); + for intensity in [f64::NAN, f64::INFINITY, -1.0, 65.0] { + let invalid = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity }]); + assert!(super::raster_lights::try_copy(&invalid).is_err()); + } + } + + use super::*; + + #[test] + fn dielectric_transport_wire_policy_preserves_legacy_and_rejects_hostile_values() { + let legacy: RaytraceOptions = serde_json::from_value(serde_json::json!({})).unwrap(); + assert_eq!(legacy.dielectric_transport, CpuDielectricTransport::LegacyBounded); + assert!(serde_json::to_value(&legacy).unwrap().get("dielectric_transport").is_none()); + let strict: RaytraceOptions = serde_json::from_value(serde_json::json!({"dielectric_transport":"strict_tir"})).unwrap(); + strict.validate().unwrap(); + assert_eq!(serde_json::to_value(&strict).unwrap()["dielectric_transport"], "strict_tir"); + for value in [serde_json::json!(null), serde_json::json!(true), serde_json::json!(7), serde_json::json!("unlimited"), serde_json::json!({})] { + assert!(serde_json::from_value::(serde_json::json!({"dielectric_transport":value})).is_err()); + } + } + + #[test] + fn strict_dielectric_policy_refuses_unqualified_opaque_continuations_without_mutation() { + let options = RaytraceOptions { + dielectric_transport: CpuDielectricTransport::StrictTir, + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: "Body".into(), mode: ReflectionMode::Mirror }], + ..Default::default() + }), + ..Default::default() + }; + let before = options.clone(); + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(options, before); + RaytraceOptions { dielectric_transport: CpuDielectricTransport::LegacyBounded, ..options }.validate().unwrap(); + } + #[test] + fn default_preset_and_empty_lights_requests_roundtrip_without_invalid_null_sequence() { + for options in [ + RaytraceOptions::default(), + RaytraceOptions { preset: Some(LightingPreset::Neutral), ..Default::default() }, + RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }, + ] { + let value = serde_json::to_value(&options).unwrap(); + if options.lights.is_none() { + assert!(value.get("lights").is_none()); + } else { + assert_eq!(value.get("lights").unwrap(), &serde_json::json!([])); + } + let decoded: RaytraceOptions = serde_json::from_value(value).unwrap(); + assert_eq!(decoded, options); + assert!(decoded.validate().is_ok()); + } + assert_eq!(serde_json::from_value::(serde_json::json!({})).unwrap(), RaytraceOptions::default()); + } + + #[test] + fn cpu_progressive_options_are_optional_strict_and_bounded_before_capture() { + use serde_json::json; + assert!(serde_json::to_value(RaytraceOptions::default()).unwrap().get("progressive").is_none()); + assert_eq!(serde_json::from_value::(json!({"progressive":null})).unwrap(), RaytraceOptions::default()); + let options: RaytraceOptions = serde_json::from_value(json!({"progressive":{"samples_per_pixel":3,"seed":u32::MAX}})).unwrap(); + options.validate().unwrap(); + assert_eq!(serde_json::from_value::(serde_json::to_value(&options).unwrap()).unwrap(), options); + for invalid in [json!({"seed":-1}), json!({"seed":4294967296_u64}), json!({"seed":0.5}), json!({"adaptive":true})] { + assert!(serde_json::from_value::(invalid).is_err()); + } + for samples_per_pixel in [0, 65, u32::MAX] { + assert!(CpuProgressiveOptions { samples_per_pixel, seed: 0 }.validate().is_err()); + } + for samples_per_pixel in [1, 2, 3, 16, 64] { + CpuProgressiveOptions { samples_per_pixel, seed: 0 }.validate_image(512, 512).unwrap(); + } + CpuProgressiveOptions::default().validate_image(1024, 1024).unwrap(); + assert!(CpuProgressiveOptions { samples_per_pixel: 17, seed: 0 }.validate_image(1024, 1024).is_err()); + for (width, height) in [(0, 1), (1, 0), (1025, 1024), (4097, 1), (u32::MAX, u32::MAX)] { + assert!(CpuProgressiveOptions { samples_per_pixel: 1, seed: 0 }.validate_image(width, height).is_err()); + } + } + + #[test] + fn progressive_rejects_incompatible_sampling_without_changing_fixed_aa() { + let progressive = Some(CpuProgressiveOptions::default()); + for primary_samples in [4, 16] { + let fixed = RaytraceOptions { primary_samples, ..Default::default() }; + fixed.validate().unwrap(); + assert!(RaytraceOptions { progressive, ..fixed }.validate().is_err()); + } + let reflections = ReflectionOptions { + bodies: vec![ReflectionBody { body: "Body".into(), mode: ReflectionMode::RoughSpecular }], + samples: 4, + max_bounces: 2, + }; + assert!(RaytraceOptions { progressive, reflections: Some(reflections), ..Default::default() }.validate().is_err()); + let area = RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [1.0, 0.0, 0.0], + edge_v_mm: [0.0, -1.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }; + RaytraceOptions { progressive, area_lights: Some(vec![area]), ..Default::default() }.validate().unwrap(); + let dielectric = DielectricOptions { + body_index: 0, + body_name: "Body".into(), + boundary: DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }; + // Superseded global rejection: smooth optical trees are implemented per + // camera sample; capture-time certification remains separately required. + RaytraceOptions { progressive, dielectrics: vec![dielectric], ..Default::default() }.validate().unwrap(); + let face = AnisotropicFaceOptions { + body_index: 0, + body_name: "Body".into(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: AnisotropicOrientation::Zero, + roughness_x: 0.2, + roughness_y: 0.6, + }; + assert!(RaytraceOptions { progressive, anisotropic_faces: [Some(face), None], ..Default::default() }.validate().is_err()); + RaytraceOptions { progressive, area_lights: Some(Vec::new()), ..Default::default() }.validate().unwrap(); + } + + #[test] + fn progressive_rectangle_and_led_admission_preserves_source_limits_and_atomic_rejection() { + let strip = led_strip::LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 2.0, + width_mm: 2.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }; + for samples in [1, 4, 16, 64] { + let mut options = RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 97 }), + lights: Some(Vec::new()), + ..Default::default() + }; + for count in 1..=4 { + strip.append_to(&mut options, samples).unwrap(); + options.validate().unwrap(); + assert_eq!(options.area_lights.as_ref().unwrap().len(), count); + assert_eq!( + options.retained_bytes().unwrap(), + (options.area_lights.as_ref().unwrap().capacity() * std::mem::size_of::()) as u64 + ); + } + let before = options.clone(); + let capacity = options.area_lights.as_ref().unwrap().capacity(); + assert!(strip.append_to(&mut options, samples).is_err()); + assert_eq!(options, before); + assert_eq!(options.area_lights.as_ref().unwrap().capacity(), capacity); + options.area_lights.as_mut().unwrap().pop(); + let before = options.clone(); + let conflicting = if samples == 1 { 4 } else { 1 }; + assert!(strip.append_to(&mut options, conflicting).is_err()); + assert_eq!(options, before); + for invalid in [0, 2, 65, u32::MAX] { + let mut hostile = options.clone(); + hostile.area_samples = Some(invalid); + assert!(hostile.validate().is_err()); + } + let mut hostile = options.clone(); + hostile.area_lights.as_mut().unwrap()[0].intensity = f64::NAN; + assert!(hostile.validate().is_err()); + } + let mut maximum = RaytraceOptions { + progressive: Some(CpuProgressiveOptions::default()), + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]), + punctual_lights: Some(vec![ + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }; + 8 + ]), + ..Default::default() + }; + for _ in 0..4 { + strip.append_to(&mut maximum, 16).unwrap(); + } + maximum.validate().unwrap(); + maximum.area_lights.as_mut().unwrap().push(strip.rectangle().unwrap()); + assert!(maximum.validate().is_err()); + for options in [ + RaytraceOptions { progressive: Some(CpuProgressiveOptions::default()), area_samples: Some(16), ..Default::default() }, + RaytraceOptions { progressive: Some(CpuProgressiveOptions::default()), seed: Some(7), ..Default::default() }, + ] { + assert!(options.validate().is_err()); + } + } +} + +/// Fixed representative presentation plan; fitting never grants source admission. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PartialPreviewPlan { + source_width: u32, + source_height: u32, + width: u32, + height: u32, +} +impl PartialPreviewPlan { + pub fn source_width(&self) -> u32 { + self.source_width + } + pub fn source_height(&self) -> u32 { + self.source_height + } + pub fn width(&self) -> u32 { + self.width + } + pub fn height(&self) -> u32 { + self.height + } + pub fn new(source_width: u32, source_height: u32) -> Result { + if source_width == 0 || source_height == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview source dimensions must be positive")); + } + let edge = source_width.max(source_height); + let fit = |side: u32| { + if edge <= 1024 { side } else { ((u64::from(side) * 1024 + u64::from(edge) / 2) / u64::from(edge)).max(1) as u32 } + }; + Ok(Self { source_width, source_height, width: fit(source_width), height: fit(source_height) }) + } + pub fn validate(&self) -> Result<()> { + if *self != Self::new(self.source_width, self.source_height)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview dimensions differ from the fixed plan")); + } + Ok(()) + } + pub fn pixels(&self) -> u64 { + u64::from(self.width) * u64::from(self.height) + } + pub fn source_index(&self, preview_index: usize) -> Result { + self.validate()?; + let index = u64::try_from(preview_index).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial preview index overflow"))?; + if index >= self.pixels() { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview index outside its plan")); + } + let x = (index % u64::from(self.width)) * u64::from(self.source_width) / u64::from(self.width); + let y = (index / u64::from(self.width)) * u64::from(self.source_height) / u64::from(self.height); + let source = y + .checked_mul(u64::from(self.source_width)) + .and_then(|v| v.checked_add(x)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial source index overflow"))?; + usize::try_from(source).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial source index exceeds address space")) + } + pub fn encoded_limit(&self) -> Result { + self.validate()?; + self.pixels() + .checked_mul(8) + .and_then(|v| v.checked_add(65_536)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial PNG capacity overflow")) + } + pub fn covered_bytes(&self) -> Result { + self.validate()?; + self.pixels().checked_mul(4).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial coverage capacity overflow")) + } + pub fn snapshot_work(&self) -> Result { + self.validate()?; + self.pixels() + .checked_mul(14) + .and_then(|v| v.checked_add(65_538)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial work bound overflow")) + } + /// Two retained payload slots; existing admitted RGBA/encoder scratch is reused. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn additional_bytes(&self) -> Result { + self.slot_bytes()? + .checked_mul(2) + .and_then(|v| v.checked_add(1024)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial preview admission overflow")) + } + pub(crate) fn slot_bytes(&self) -> Result { + self.encoded_limit()? + .checked_add(self.covered_bytes()?) + .and_then(|v| v.checked_add(2048)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial retained slot overflow")) + } +} + +/// Explicit protected-feedback aggregate ceiling; the ordinary MAX_CPU_WORK is unchanged. +// At most 1024² representatives: 14 work units each plus 65,538 codec/hash +// overhead. At most 64 early milestones and MAX_SPP-1 complete-pass snapshots. +// This Cartesian upper bound is deliberately conservative; ordinary work is unchanged. +pub const MAX_PROTECTED_CPU_WORK: u64 = MAX_CPU_WORK + 14_745_602 * (MAX_CPU_SAMPLES_PER_PIXEL as u64 + 63); + +/// Checked per-job feedback policy, not an admission token or an arbitrary work envelope. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProtectedPreviewPlan { + preview: PartialPreviewPlan, + samples_per_pixel: u32, + budget: CpuBudget, + total_commits: u64, + quota_limit: u32, +} +impl ProtectedPreviewPlan { + pub fn new(source_width: u32, source_height: u32, samples_per_pixel: u32, budget: CpuBudget) -> Result { + budget.validate_image(source_width, source_height, Some(CpuProgressiveOptions { samples_per_pixel, seed: 0 }))?; + let preview = PartialPreviewPlan::new(source_width, source_height)?; + let total_commits = u64::from(source_width) + .checked_mul(u64::from(source_height)) + .and_then(|v| v.checked_mul(u64::from(samples_per_pixel))) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected camera-commit count overflow"))?; + let pixels = u64::from(source_width) * u64::from(source_height); + let early = + u32::try_from(pixels.saturating_sub(1).min(64)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early quota overflow"))?; + let quota_limit = + early.checked_add(samples_per_pixel - 1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))?; + let plan = Self { preview, samples_per_pixel, budget, total_commits, quota_limit }; + plan.aggregate_limit()?; + Ok(plan) + } + pub fn validate(&self) -> Result<()> { + if *self != Self::new(self.preview.source_width(), self.preview.source_height(), self.samples_per_pixel, self.budget)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan differs from its canonical policy")); + } + Ok(()) + } + pub fn preview_plan(&self) -> PartialPreviewPlan { + self.preview + } + pub fn samples_per_pixel(&self) -> u32 { + self.samples_per_pixel + } + pub fn budget(&self) -> CpuBudget { + self.budget + } + pub fn total_commits(&self) -> u64 { + self.total_commits + } + pub fn ordinary_limit(&self) -> u64 { + self.budget.limits().max_work_units + } + pub fn quota_limit(&self) -> u32 { + self.quota_limit + } + pub fn snapshot_work(&self) -> Result { + self.preview.snapshot_work() + } + pub fn presentation_limit(&self) -> Result { + self.snapshot_work()? + .checked_mul(u64::from(self.quota_limit)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected presentation allowance overflow")) + } + pub fn aggregate_limit(&self) -> Result { + self.ordinary_limit() + .checked_add(self.presentation_limit()?) + .filter(|v| *v <= MAX_PROTECTED_CPU_WORK) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected aggregate work exceeds its explicit ceiling")) + } + /// Number of reached milestones in O(1), including a final sentinel without + /// adding a final-image snapshot. A delayed consumer cannot create a long + /// uninterruptible coalescing loop in the worker. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn reached_milestones(&self, committed: u64) -> Result { + if committed > self.total_commits { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected frontier exceeds its final target")); + } + let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); + let early = pixels.saturating_sub(1).min(64); + let reached_early = if committed == 0 || early == 0 { + 0 + } else if committed >= pixels - 1 { + early + } else if early == 1 { + 1 + } else { + committed + .checked_mul(early - 1) + .map(|n| n.div_ceil(pixels - 2)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected reached milestone overflow"))? + }; + let passes = (committed / pixels).min(u64::from(self.samples_per_pixel - 1)); + reached_early + .checked_add(passes) + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n <= self.quota_limit) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected reached quota overflow")) + } + + /// Zero-based, strictly increasing milestones below the final target. + pub fn milestone(&self, index: u32) -> Result { + if index >= self.quota_limit { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected milestone index outside its quota")); + } + let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); + let early = u32::try_from(pixels.saturating_sub(1).min(64)) + .map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early milestone overflow"))?; + if index < early { + if early == 1 { + return Ok(1); + } + return pixels + .checked_sub(2) + .and_then(|n| n.checked_mul(u64::from(index))) + .and_then(|n| n.checked_div(u64::from(early - 1))) + .and_then(|n| n.checked_add(1)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected early milestone arithmetic overflow")); + } + u64::from(index - early + 1) + .checked_mul(pixels) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected pass milestone arithmetic overflow")) + } +} + +/// Actual admitted policy and monotonic producer usage; never a saved design field. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct ProtectedPreviewReport { + pub policy_version: u32, + pub ordinary_limit: u64, + pub presentation_limit: u64, + pub aggregate_limit: u64, + pub ordinary_used: u64, + pub presentation_used: u64, + pub accepted_snapshots: u32, + pub quota_limit: u32, + pub next_milestone_index: u32, + pub quota_exhausted: bool, + pub milestones_complete: bool, +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/environment_image_tests.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/environment_image_tests.rs new file mode 100644 index 000000000..dc5448902 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/environment_image_tests.rs @@ -0,0 +1,309 @@ +use super::*; +use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +fn input() -> EnvironmentInput { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 64).unwrap() +} +fn scene() -> ProductScene { + let mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + transmission: None, + name: "Original conductor plate".into(), + mesh, + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }], + } +} +fn request() -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: job::Integrator::Raytrace, + raytrace: Some(RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }), + camera, + width: 9, + height: 9, + background: [13, 27, 41], + transparent_background: false, + } +} +fn png(source: ProductScene, environment: Option) -> Vec { + let request = request(); + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new_with_environment(source, request, CancelToken::default(), options, environment).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("bounded environment fixture did not complete"); +} + +#[test] +fn real_cpu_png_conductor_matches_independent_environment_quadrature_once() { + let baseline = ::image::load_from_memory(&png(scene(), None)).unwrap().to_rgba8(); + let rendered = png(scene(), Some(input())); + assert_eq!(rendered, png(scene(), Some(input()))); + let image = ::image::load_from_memory(&rendered).unwrap().to_rgba8(); + // Independent roughness-one white-conductor f*cos= z/(2*pi*(1+z)). + // The fixed 8x8 solid-angle strata integrate 4 positive z rows, each 8 samples. + let factor = [0.125, 0.375, 0.625, 0.875].into_iter().map(|z| z / (1.0 + z)).sum::() / 4.0; + let expected = [factor, factor * 0.5, factor * 0.25].map(|r| encode8(r / (1.0 + r))); + assert_eq!(image.get_pixel(4, 4).0, [expected[0], expected[1], expected[2], 255]); + assert_eq!(baseline.get_pixel(4, 4).0, [0, 0, 0, 255]); + let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let background = ::image::load_from_memory(&png(empty, Some(input()))).unwrap().to_rgba8(); + assert!(background.pixels().all(|p| p.0 == [13, 27, 41, 255])); +} + +struct ProgressiveHdrResult { + previews: Vec<(u32, Vec)>, + png: Vec, + work: u64, +} + +fn progressive_hdr_png(samples_per_pixel: u32, seed: u32, quantum: usize, environment: Option) -> ProgressiveHdrResult { + let mut request = request(); + let mut options = request.raytrace.clone().unwrap(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel, seed }); + options.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "Original conductor plate".into(), mode: job::ReflectionMode::RoughSpecular }], + samples: 1, + max_bounces: 2, + }); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new_with_environment(scene(), request, CancelToken::default(), options, environment).unwrap(); + let mut previews = Vec::new(); + for _ in 0..300_000 { + match task.step_with_previews(quantum).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => previews.push((samples_per_pixel, png)), + ImagePoll::Complete(png) => return ProgressiveHdrResult { previews, png, work: task.work.used() }, + } + } + panic!("bounded progressive HDR fixture did not finish"); +} + +fn progressive_hdr_expected(samples: u32, seed: u32) -> [u8; 4] { + // Independent normal-view, white-conductor reference at roughness one. + // The centre pixel (40) stays inside the plate for every camera jitter. + // GGX gives z = 1 - 2*u and weight = 2*z/(1+z) for z > 0; other + // attempts are null events, not replacement samples. Only the variate + // sequence is shared with production: no BSDF, PDF or film code is used. + let sum: f64 = (0..samples) + .map(|ordinal| { + let z = 1.0 - 2.0 * progressive::variates(seed, 40, ordinal, 0x100)[0]; + if z > 0.0 { 2.0 * z / (1.0 + z) } else { 0.0 } + }) + .sum(); + let mean = sum / f64::from(samples); + // The original HDR is constant linear RGB (1, 0.5, 0.25). Average in + // linear space over ALL attempts, then apply the display response once. + let rgb = [mean, mean * 0.5, mean * 0.25].map(|r| encode8(r / (1.0 + r))); + [rgb[0], rgb[1], rgb[2], 255] +} + +fn centre(png: &[u8]) -> [u8; 4] { + ::image::load_from_memory(png).unwrap().to_rgba8().get_pixel(4, 4).0 +} + +#[test] +fn progressive_hdr_and_rough_reflections_keep_the_same_absolute_prefix_at_every_quantum() { + for (target, checkpoints) in [(3, vec![1, 2]), (7, vec![1, 2, 3, 4, 5, 6])] { + let result = progressive_hdr_png(target, 82, 1, Some(input())); + assert_eq!(result.previews.iter().map(|(n, _)| *n).collect::>(), checkpoints); + let other = progressive_hdr_png(target, 82, 16384, Some(input())); + assert_eq!(result.previews, other.previews); + assert_eq!(result.png, other.png); + assert_eq!(result.work, other.work); + for (samples, checkpoint) in result.previews { + assert_eq!(progressive_hdr_png(samples, 82, 3, Some(input())).png, checkpoint); + assert_eq!(centre(&checkpoint), progressive_hdr_expected(samples, 82)); + } + assert_eq!(centre(&result.png), progressive_hdr_expected(target, 82)); + } +} + +#[test] +fn progressive_hdr_rough_reflections_count_null_events_in_the_linear_mean() { + // Preserve the previously failing seed rather than picking a brighter one: + // its first three attempts are all null, and later attempts receive HDR. + assert_eq!(progressive_hdr_expected(3, 82), [0, 0, 0, 255]); + assert_ne!(progressive_hdr_expected(7, 82), [0, 0, 0, 255]); + for seed in [0, 82, u32::MAX] { + for samples in [1, 3, 7] { + let result = progressive_hdr_png(samples, seed, 37, Some(input())); + assert_eq!(centre(&result.png), progressive_hdr_expected(samples, seed), "seed={seed}, samples={samples}"); + let image = ::image::load_from_memory(&result.png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [13, 27, 41, 255], "HDR must not replace the display background"); + let unlit = progressive_hdr_png(samples, seed, 37, None); + assert_eq!(centre(&unlit.png), [0, 0, 0, 255], "no direct lights or environment means zero radiance"); + } + } +} + +#[test] +fn environment_decode_and_secondary_visibility_share_cancellation_and_work_budget() { + for during_visibility in [false, true] { + let request = request(); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap(); + if during_visibility { + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some())); + } + // Cancellation must win before any image publication, including decode preparation. + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } + let request = request(); + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new_with_environment(scene(), request, CancelToken::default(), options, Some(input())).unwrap(); + task.work = WorkBudget::new(1).unwrap(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_host_captured_source_completes_and_releases_work_lease() { + let host = job::CpuHost::for_platform().unwrap(); + assert!(host.descriptor_for(job::Integrator::Raytrace).unwrap().profiles[0].features.contains(&crate::RenderFeature::Hdri)); + assert!(!host.descriptor_for(job::Integrator::Raster).unwrap().profiles[0].features.contains(&crate::RenderFeature::Hdri)); + let handle = host.submit_with_environment(job::JobId { session: 1693, serial: 1, generation: 1 }, 1, scene(), request(), Some(input())).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + assert!(host.admitted_bytes() >= frame.png().len() as u64 + 1024); + drop(host); + drop(frame); + drop(handle); +} + +#[test] +fn environment_visibility_respects_four_work_units_per_quantum_and_cancel() { + let request = request(); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some())); + for _ in 0..32 { + let before = task.work.used(); + assert!(matches!(task.step(4).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 4, "visibility continuation double-charged shading and traversal"); + } + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); +} + +#[test] +fn all_pixel_traversal_to_shading_transitions_debit_at_most_one_unit() { + for (directional, shadows) in [(false, true), (true, true), (true, false)] { + let mut request = request(); + let mut options = request.raytrace.clone().unwrap(); + options.shadows = shadows; + if directional { + options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]); + } + request.raytrace = Some(options.clone()); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap(); + while task.bvh.is_none() { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + let mut primary_transitions = 0; + let mut directional_transitions = 0; + for _ in 0..200_000 { + if task.pixel == 81 { + break; + } + let primary = task.pending.as_ref().is_some_and(|p| p.hit.is_none()); + let light_before = task.pending.as_ref().map(|p| p.light); + let before = task.work.used(); + task.pixel_one().unwrap(); + assert!(task.work.used() - before <= 1, "traversal completion must yield before shading/sample debit"); + if primary && task.pending.as_ref().is_some_and(|p| p.hit.is_some()) { + primary_transitions += 1; + } + if light_before == Some(0) && task.pending.as_ref().is_some_and(|p| p.light == 1) { + directional_transitions += 1; + } + } + assert_eq!(task.pixel, 81); + assert!(primary_transitions > 0); + if directional && shadows { + assert!(directional_transitions > 0); + } + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); + } +} + +#[test] +fn explicit_cpu_profiles_admit_large_images_without_allocating_a_film() { + let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let mut request = request(); + request.width = 3840; + request.height = 2160; + let mut options = request.raytrace.clone().unwrap(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 128, seed: 9 }); + request.raytrace = Some(options.clone()); + assert!(admit(&empty, &request, &options).is_err()); + if usize::BITS < 64 || cfg!(target_arch = "wasm32") { + return; + } + options.budget = job::CpuBudget::Studio; + request.raytrace = Some(options.clone()); + let studio = admit(&empty, &request, &options).unwrap(); + assert!(studio.estimated_total_bytes > 384 * 1024 * 1024); + assert!(studio.estimated_total_bytes < options.budget.limits().max_job_bytes); + request.width = 7680; + request.height = 4320; + assert!(admit(&empty, &request, &options).is_err()); + options.budget = job::CpuBudget::Workstation; + request.raytrace = Some(options.clone()); + let workstation = admit(&empty, &request, &options).unwrap(); + assert!(workstation.estimated_total_bytes > studio.estimated_total_bytes); + assert!(workstation.estimated_total_bytes < options.budget.limits().max_job_bytes); + for budget in [job::CpuBudget::Studio, job::CpuBudget::Workstation] { + let count = budget.limits().max_triangles as usize; + let bytes = BvhBuilder::required_bytes(count, count, limits(budget)).unwrap(); + assert!(bytes < budget.limits().max_job_bytes); + } + assert!(BvhBuilder::required_bytes(2_000_000, 2_000_000, limits(job::CpuBudget::Compact)).is_err()); +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image.rs new file mode 100644 index 000000000..ca49868d0 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image.rs @@ -0,0 +1,2573 @@ +//! Opt-in opaque direct image integration; immutable world geometry, one host reservation. +use super::anisotropic_faces::{self, PlanarTarget}; +use super::bvh::TraceCursor; +use super::dielectric::{self, Certificate, MAX_BOUNDARIES, MAX_OVERRIDES, MAX_PATHS}; +use super::lighting::{DirectionalLight, Lighting, StudioPreset, map_to_display}; +use super::prepared::{PreparedPrimitive, PreparedScene, SharedHit}; +use super::progressive::{self, Progressive}; +use super::reflection; +use super::{BuildLimits, Bvh, BvhBuilder, Ray, TraceError, Triangle, WorkBudget}; +use crate::job::{self, Admission, CancelToken, ErrorCode, ImageRequest, JobError, Phase, Progress, RaytraceOptions, TaskPoll}; +use crate::{ + ProductScene, + film::primary::PrimaryFilm, + surface::{OpaqueSurface, srgb8_to_linear}, +}; +use solidcraft_geom::{Vec3, srgb::encode8}; + +#[cfg(test)] +#[path = "environment_image_tests.rs"] +mod environment_image_tests; + +#[cfg(test)] +#[path = "environment_reflection_tests.rs"] +mod environment_reflection_tests; + +#[cfg(test)] +#[path = "anisotropic_reflection_image_tests.rs"] +mod anisotropic_reflection_tests; + +fn error(e: TraceError) -> JobError { + let code = match e { + TraceError::Cancelled => ErrorCode::Cancelled, + TraceError::MemoryLimit | TraceError::WorkLimit => ErrorCode::LimitExceeded, + TraceError::AllocationFailed => ErrorCode::AllocationFailed, + TraceError::InvalidInput(_) => ErrorCode::InvalidScene, + _ => ErrorCode::Internal, + }; + JobError::new(code, e.to_string()) +} +fn invalid(message: &'static str) -> JobError { + JobError::new(ErrorCode::InvalidScene, message) +} +fn limits(budget: job::CpuBudget) -> BuildLimits { + let limits = budget.limits(); + BuildLimits { + max_triangles: limits.max_triangles as usize, + max_memory_bytes: limits.max_job_bytes, + max_work: limits.max_work_units, + ..Default::default() + } +} +fn lighting(options: &RaytraceOptions) -> job::Result { + options.validate()?; + if let Some(preset) = options.preset { + let preset = match preset { + job::LightingPreset::Neutral => StudioPreset::Neutral, + job::LightingPreset::WarmCool => StudioPreset::WarmCool, + job::LightingPreset::KeyRim => StudioPreset::KeyRim, + }; + return Lighting::preset(preset).map_err(error); + } + match &options.lights { + None => Ok(Lighting::studio_default()), + Some(inputs) => { + let mut lights = Vec::new(); + lights.try_reserve_exact(inputs.len()).map_err(|_| error(TraceError::AllocationFailed))?; + for l in inputs { + lights.push( + DirectionalLight::new( + Vec3::new(l.direction[0], l.direction[1], l.direction[2]), + Vec3::new(l.color[0], l.color[1], l.color[2]), + l.intensity, + ) + .map_err(error)?, + ); + } + Lighting::new(lights).map_err(error) + } + } +} +type Look = PreparedPrimitive; + +fn certificates( + scene: &ProductScene, + options: &RaytraceOptions, + nested: bool, +) -> job::Result<([Option; MAX_OVERRIDES], [Option; MAX_OVERRIDES])> { + let mut result = [None; MAX_OVERRIDES]; + for (slot, input) in result.iter_mut().zip(&options.dielectrics) { + *slot = Some(dielectric::certify(scene, input).map_err(error)?); + } + let parents = dielectric::parents(&result, nested).map_err(error)?; + // Sheets within volumes are unsupported. Conservatively use the admitted + // tiny sheet's bounds, rather than pretending to resolve medium nesting. + for (i, certificate) in result.iter().enumerate() { + if let Some(Certificate::ClosedBox(a)) = certificate { + for (j, other) in result.iter().enumerate() { + if i != j && matches!(other, Some(Certificate::ThinSheet)) { + let input = options.dielectrics.get(j).ok_or_else(|| invalid("sheet override index"))?; + let body = scene.meshes.get(input.body_index).ok_or_else(|| invalid("sheet body index"))?; + let bounds = body.mesh.bounds(); + if dielectric::overlaps(*a, super::Bounds::new(bounds.min, bounds.max).map_err(error)?) { + return Err(invalid("thin sheets touching or inside dielectric volumes are unsupported")); + } + } + } + } + } + Ok((result, parents)) +} + +/// Private construction policy; protected admission is selected before allocations. +#[derive(Clone, Copy)] +enum PreviewPolicy { + Legacy, + Shared(job::PartialPreviewPlan), + Protected(job::ProtectedPreviewPlan), +} +impl PreviewPolicy { + fn partial_plan(self) -> Option { + match self { + Self::Legacy => None, + Self::Shared(plan) => Some(plan), + Self::Protected(plan) => Some(plan.preview_plan()), + } + } +} + +fn committed_frontier(frontier: crate::film::primary::PartialFrontier) -> job::Result { + let pixels = u64::try_from(frontier.pixels).map_err(|_| error(TraceError::MemoryLimit))?; + let prefix = u64::try_from(frontier.updated_prefix).map_err(|_| error(TraceError::MemoryLimit))?; + u64::from(frontier.completed_passes).checked_mul(pixels).and_then(|n| n.checked_add(prefix)).ok_or_else(|| error(TraceError::WorkLimit)) +} + +pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions) -> job::Result { + admit_with_nested(scene, request, options, false) +} + +pub(crate) fn admit_with_nested(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions, nested: bool) -> job::Result { + admit_with_policy(scene, request, options, nested, PreviewPolicy::Legacy) +} + +pub(crate) fn admit_with_partial_preview( + scene: &ProductScene, + request: &ImageRequest, + options: &RaytraceOptions, + nested: bool, + plan: job::PartialPreviewPlan, +) -> job::Result { + admit_with_policy(scene, request, options, nested, PreviewPolicy::Shared(plan)) +} + +pub(crate) fn admit_with_protected_partial_preview( + scene: &ProductScene, + request: &ImageRequest, + options: &RaytraceOptions, + nested: bool, + plan: job::ProtectedPreviewPlan, +) -> job::Result { + admit_with_policy(scene, request, options, nested, PreviewPolicy::Protected(plan)) +} + +fn admit_with_policy( + scene: &ProductScene, + request: &ImageRequest, + options: &RaytraceOptions, + nested: bool, + policy: PreviewPolicy, +) -> job::Result { + if let PreviewPolicy::Protected(plan) = policy { + plan.validate()?; + let progressive = + options.progressive.ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected feedback requires progressive CPU sampling"))?; + if plan != job::ProtectedPreviewPlan::new(request.width, request.height, progressive.samples_per_pixel, options.budget)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan differs from actual source sampling or budget")); + } + } + let partial = policy.partial_plan(); + if let Some(plan) = partial { + plan.validate()?; + if plan != job::PartialPreviewPlan::new(request.width, request.height)? + || options.progressive.is_none() + || request.environment.is_some() + || request.textures.is_some() + || scene.has_transmission() + { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview requires the exact CPU progressive source plan")); + } + } + options.validate()?; + if options.directional_shadow_transmission && nested { + return Err(invalid("directional shadow transmission does not support nested media")); + } + if let Some(original) = &request.raytrace { + original.validate()?; + } + if request.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()) != options { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace options disagree with image request")); + } + if request.integrator != job::Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace task requires raytrace integrator")); + } + if request.transparent_background { + return Err(invalid("raytrace supports opaque backgrounds only")); + } + if let Some(progressive) = options.progressive { + progressive.validate_image_with_budget(request.width, request.height, options.budget)?; + } + let mut a = job::image::admit_raytrace_source(scene, request, options.budget)?; + let r = options.reflections.as_ref().filter(|r| !r.bodies.is_empty()).map_or(1, |r| r.samples); + u64::from(request.width) + .checked_mul(u64::from(request.height)) + .and_then(|n| n.checked_mul(u64::from(options.primary_samples))) + .and_then(|n| n.checked_mul(u64::from(r))) + .ok_or_else(|| invalid("spatial attempt count overflow"))?; + for (index, body) in scene.meshes.iter().enumerate() { + if body.opacity != 1.0 || body.faces.iter().any(|f| f.opacity != 1.0) { + return Err(invalid("raytrace requires opaque body and face appearances")); + } + let has_coat = body.surface.is_some_and(|surface| surface.clear_coat().is_some()) + || body.faces.iter().any(|face| face.surface.is_some_and(|surface| surface.clear_coat().is_some())); + let selected_transport = options.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| entry.body == body.name)) + || options.anisotropic_faces.iter().flatten().any(|entry| entry.body_index == index) + || options.dielectrics.iter().any(|entry| entry.body_index == index); + if has_coat && selected_transport { + return Err(invalid("CPU reflection, anisotropy and dielectric overrides do not support clear-coat transport")); + } + } + if let Some(reflections) = &options.reflections { + for override_ in &reflections.bodies { + let count = scene.meshes.iter().filter(|body| body.name == override_.body).count(); + if count != 1 { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection body must resolve to exactly one captured body")); + } + } + } + anisotropic_faces::prepare(scene, options, || Ok(()))?; + certificates(scene, options, nested)?; + for input in &options.dielectrics { + if options.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|v| v.body == input.body_name)) + || options.anisotropic_faces.iter().flatten().any(|v| v.body_index == input.body_index) + || options.emissions.iter().flatten().any(|v| v.body_index == input.body_index) + { + return Err(invalid("dielectric boundaries cannot also select opaque reflection, anisotropy or emission")); + } + if let Some(values) = &options.surface_effects { + for value in values.iter().filter(|v| v.body == input.body_name) { + if !value.prepare()?.is_identity() { + return Err(invalid("nonidentity surface effects on dielectric boundaries are unsupported")); + } + } + } + } + if let Some(values) = &options.surface_effects { + for value in values { + let mut bodies = scene.meshes.iter().enumerate().filter(|(_, body)| body.name == value.body); + let (index, _) = bodies.next().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "surface effect body missing"))?; + if bodies.next().is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "surface effect body must resolve uniquely")); + } + if !value.prepare()?.is_identity() && options.anisotropic_faces.iter().flatten().any(|target| target.body_index == index) { + return Err(JobError::new(ErrorCode::InvalidRequest, "surface effects on a certified anisotropic body are not supported")); + } + } + } + if let Some(values) = &options.emissions { + for value in values { + if scene.meshes.get(value.body_index).is_none_or(|body| body.name != value.body) { + return Err(invalid("surface emission target does not match captured body index and name")); + } + } + } + // Bill each task-owned options copy and the prepared emission vector in addition + // to the unchanged baseline estimate. Record metadata has its independent lease. + let emission_bytes = options + .retained_emission_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_emission_bytes)?) + .and_then(|v| { + v.checked_add(options.emissions.as_ref().map_or(0, Vec::len) as u64 * std::mem::size_of::<(usize, super::emission::Emission)>() as u64) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + // The task owns two independent options copies plus its prepared effect vector. + // The original request Record remains billed by the same retained_bytes sum. + let effect_bytes = options + .retained_surface_effect_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_surface_effect_bytes)?) + .and_then(|v| { + v.checked_add( + options.surface_effects.as_ref().map_or(0, Vec::len) as u64 + * std::mem::size_of::<(usize, crate::surface_patterns::PreparedEffect)>() as u64, + ) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + let optical_bytes = options + .retained_dielectric_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_dielectric_bytes)?) + .and_then(|v| v.checked_add(if options.dielectrics.is_empty() { 0 } else { std::mem::size_of::() as u64 })) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + let n = usize::try_from(a.triangles).map_err(|_| error(TraceError::MemoryLimit))?; + let film_bytes = if let Some(progressive) = options.progressive { + let checkpoint = a.encoded_limit.checked_add(job::FRAME_METADATA_BYTES).ok_or_else(|| error(TraceError::MemoryLimit))?; + let previews = if let Some(plan) = partial { + plan.additional_bytes()? + } else { + u64::from(progressive.checkpoint_slots()) + .checked_mul(checkpoint) + .and_then(|bytes| bytes.checked_add(if progressive.checkpoint_slots() == 0 { 0 } else { 1024 })) + .ok_or_else(|| error(TraceError::MemoryLimit))? + }; + PrimaryFilm::required_bytes(request.width, request.height, progressive, options.budget)? + .checked_add(previews) + .and_then(|v| v.checked_add(std::mem::size_of::() as u64)) + .ok_or_else(|| error(TraceError::MemoryLimit))? + } else { + 0 + }; + let extra = BvhBuilder::required_bytes(n, n, limits(options.budget)) + .map_err(error)? + .checked_add(a.triangles.checked_mul(std::mem::size_of::() as u64).ok_or_else(|| error(TraceError::MemoryLimit))?) + .and_then(|v| v.checked_add(emission_bytes)) + .and_then(|v| v.checked_add(effect_bytes)) + .and_then(|v| v.checked_add(optical_bytes)) + .and_then(|v| v.checked_add(film_bytes)) + // The resumable pixel owns two traversal cursors. Its fallible, fixed + // heap slot is additional to the unchanged host/task-state allowance. + .and_then(|v| v.checked_add(PendingPixelSlot::required_bytes())) + .and_then(|v| { + v.checked_add(8192 + if options.reflections.is_some() || options.anisotropic_faces.iter().any(Option::is_some) { 32768 } else { 0 }) + }) + .and_then(|v| { + v.checked_add(options.area_lights.as_ref().map_or(0, Vec::capacity) as u64 * std::mem::size_of::() as u64) + }) + .and_then(|v| { + v.checked_add(options.punctual_lights.as_ref().map_or(0, Vec::capacity) as u64 * std::mem::size_of::() as u64) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + // Keep the conservative raster pixel/codec estimate; add every new owned buffer. + a.preparation_bytes = a.preparation_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + a.estimated_total_bytes = a.estimated_total_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + if a.estimated_total_bytes > options.budget.limits().max_job_bytes { + return Err(error(TraceError::MemoryLimit)); + } + Ok(a) +} + +struct PendingPixel { + surface_cursor: usize, + surface_index: Option, + surface_ready: bool, + emission_cursor: usize, + punctual_index: usize, + punctual_shadow: bool, + punctual_ready: bool, + punctual_value: Vec3, + area_light: usize, + area_index: u32, + area_shadow: bool, + area_ready: bool, + area_value: Vec3, + + /// Proof from the primary generator, revoked for any selected reflector. + /// A jittered/time-varying primary generator MUST supply false. + repeatable_primary: bool, + environment_sample: u32, + environment_sum: Vec3, + environment_cursor: Option, + environment_value: Vec3, + ray: Ray, + cursor: TraceCursor, + hit: Option, + visibility: [bool; 8], + directional_transmittance: [Vec3; 8], + directional_complete: u8, + directional_active: bool, + directional_required: bool, + light: usize, + bounce: u8, + throughput: Vec3, + radiance: Vec3, +} + +/// A commit/reset may abandon neither an active connection nor an unfinished rig. +fn ensure_directional_drained(pending: Option<&PendingPixel>, lights: usize) -> job::Result<()> { + if lights > super::lighting::MAX_LIGHTS { + return Err(invalid("directional light count exceeds fixed visibility storage")); + } + let required = ((1u16 << lights) - 1) as u8; + if pending.is_some_and(|pending| pending.directional_active || (pending.directional_required && pending.directional_complete != required)) { + return Err(invalid("directional visibility connection has not drained")); + } + Ok(()) +} + +fn begin_directional_shadow( + owner: &mut dielectric::DirectVisibilityOwner, + pending: &mut PendingPixel, + ray: Ray, + work: &mut WorkBudget, + cancel: &CancelToken, +) -> job::Result<()> { + if pending.light >= super::lighting::MAX_LIGHTS || pending.directional_active { + return Err(invalid("invalid directional connection start")); + } + let bit = 1u8 << pending.light; + if pending.directional_complete & bit != 0 { + return Err(invalid("directional connection already completed")); + } + pending.directional_required = true; + owner.begin(ray, dielectric::MAX_DIRECT_CROSSINGS, work, cancel).map_err(error)?; + pending.directional_active = true; + Ok(()) +} + +/// One reusable, fallibly allocated continuation. The Vec header stays in the +/// 4096-byte host slot; its exact single-element capacity is billed by admit. +/// Keeping an empty slot between samples avoids any per-ray allocation. +struct PendingPixelSlot(Vec); + +impl PendingPixelSlot { + fn required_bytes() -> u64 { + std::mem::size_of::() as u64 + } + + fn new(cancel: &CancelToken) -> job::Result { + cancel.check()?; + let mut slot = Vec::new(); + slot.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if slot.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + cancel.check()?; + Ok(Self(slot)) + } + + fn as_ref(&self) -> Option<&PendingPixel> { + self.0.first() + } + + fn as_mut(&mut self) -> Option<&mut PendingPixel> { + self.0.first_mut() + } + + fn is_none(&self) -> bool { + self.0.is_empty() + } + + #[cfg(test)] + fn is_some(&self) -> bool { + !self.is_none() + } + + fn insert(&mut self, value: PendingPixel) -> job::Result<()> { + if self.0.capacity() != 1 || !self.0.is_empty() { + return Err(invalid("pending pixel slot is unavailable")); + } + // Capacity is already admitted and reserved: this cannot allocate. + self.0.push(value); + Ok(()) + } + + fn clear(&mut self) { + self.0.clear(); + } + + fn release(&mut self) { + self.0 = Vec::new(); + } +} + +#[derive(Clone, Copy)] +struct OpticalPath { + ray: Ray, + throughput: Vec3, + medium: Option, + /// Boundary or opaque reflection position, before the numerical spawn offset. + segment_start: Vec3, + boundaries: u8, + /// Opaque reflection depth is independent of the dielectric interface count. + bounce: u8, +} + +struct DielectricPixel { + /// A whole Fresnel tree belongs to one absolute camera sample. Fixed paths + /// keep None; work quanta and presentation never enter this identity. + camera_sample: Option<(usize, u32)>, + path: OpticalPath, + stack: [Option; MAX_BOUNDARIES as usize + 1], + stack_len: usize, + paths: u16, + primary_check: usize, + selector: usize, + selected: Option, + ready: bool, +} + +/// At most2 crossings per certified convex box and1 per certified planar sheet +/// on a single straight camera segment. Equal indices preserve direction; no +/// selected opaque reflector may generate another segment. Certificates and +/// strict parent validation precede this bounded, allocation-free policy. +fn straight_boundary_limit(options: &RaytraceOptions, certificates: &[Option; MAX_OVERRIDES]) -> job::Result> { + if options.dielectrics.is_empty() + || options.dielectrics.iter().any(|input| input.ior != 1.0) + || options.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty()) + { + return Ok(None); + } + let mut limit = 0_u8; + for (index, input) in options.dielectrics.iter().enumerate() { + let certificate = certificates.get(index).copied().flatten().ok_or_else(|| invalid("missing straight optical certificate"))?; + let crossings = match (input.boundary, certificate) { + (job::DielectricBoundary::ClosedBox, Certificate::ClosedBox(_)) => 2, + (job::DielectricBoundary::ThinSheet, Certificate::ThinSheet) => 1, + _ => return Err(invalid("straight optical certificate disagrees with boundary")), + }; + limit = limit.checked_add(crossings).filter(|n| *n <= 16).ok_or_else(|| invalid("straight optical crossing bound exceeds sixteen"))?; + } + Ok(Some(limit)) +} + +/// One fallibly reserved optional slot. Branches do not copy PendingPixel, own +/// lighting state, encode pixels, or allocate outside the existing job reservation. +struct OpticalTask { + /// None retains the original eight-event branching model unchanged. + straight_limit: Option, + /// Captured runtime dielectric policy; fixed and progressive use the same transport. + deterministic_tir: bool, + /// Actual deterministic continuations CREATED, not completed rays or paths. + tir_continuations: u64, + certificates: [Option; MAX_OVERRIDES], + parents: [Option; MAX_OVERRIDES], + nested: bool, + pending: Option, +} + +impl DielectricPixel { + fn new(ray: Ray) -> Self { + Self { + path: OpticalPath { ray, throughput: Vec3::new(1.0, 1.0, 1.0), medium: None, segment_start: ray.origin(), boundaries: 0, bounce: 0 }, + camera_sample: None, + stack: [None; MAX_BOUNDARIES as usize + 1], + stack_len: 0, + paths: 1, + primary_check: 0, + selector: 0, + selected: None, + ready: false, + } + } + + fn check_camera_sample(&self, actual: Option<(usize, u32)>) -> job::Result<()> { + if self.camera_sample != actual { + return Err(invalid("optical tree differs from its absolute camera sample")); + } + Ok(()) + } + + fn push(&mut self, path: OpticalPath) -> job::Result<()> { + if !bounded_radiance(path.throughput) { + return Err(invalid("dielectric branch throughput exceeds finite bound")); + } + if path.throughput == Vec3::ZERO { + return Ok(()); + } + if self.paths >= MAX_PATHS { + return Err(error(TraceError::WorkLimit)); + } + *self.stack.get_mut(self.stack_len).ok_or_else(|| error(TraceError::MemoryLimit))? = Some(path); + self.stack_len += 1; + self.paths += 1; + Ok(()) + } + + fn advance(&mut self) -> job::Result { + if self.stack_len == 0 { + return Ok(false); + } + self.stack_len -= 1; + self.path = self.stack.get_mut(self.stack_len).and_then(Option::take).ok_or_else(|| invalid("optical path stack"))?; + self.selector = 0; + self.selected = None; + self.ready = false; + Ok(true) + } +} + +/// Reset only per-hit transport state; retain the shared sum across Fresnel leaves. +fn resume_optical_path(pending: &mut PendingPixel, path: OpticalPath, lights: usize) -> job::Result<()> { + ensure_directional_drained(Some(pending), lights)?; + pending.ray = path.ray; + pending.throughput = path.throughput; + pending.bounce = path.bounce; + pending.repeatable_primary = false; + pending.cursor = TraceCursor::new(path.ray, false); + pending.hit = None; + pending.surface_cursor = 0; + pending.surface_index = None; + pending.surface_ready = false; + pending.emission_cursor = 0; + pending.light = 0; + pending.visibility = [true; 8]; + pending.directional_transmittance = [Vec3::ZERO; 8]; + pending.directional_complete = 0; + pending.directional_active = false; + pending.directional_required = false; + pending.punctual_index = 0; + pending.punctual_shadow = false; + pending.punctual_ready = false; + pending.punctual_value = Vec3::ZERO; + pending.area_light = 0; + pending.area_index = 0; + pending.area_shadow = false; + pending.area_ready = false; + pending.area_value = Vec3::ZERO; + pending.environment_sample = 0; + pending.environment_sum = Vec3::ZERO; + pending.environment_cursor = None; + pending.environment_value = Vec3::ZERO; + Ok(()) +} + +pub struct ImageTask { + punctual_diagnostics: job::PunctualDiagnostics, + progressive: Option, + last_pass_boundary: u32, + optical: Vec, + anisotropic_targets: [Option; 2], + environment: Option, + visibility_owner: dielectric::DirectVisibilityOwner, + request: ImageRequest, + cancel: CancelToken, + admission: Admission, + lights: Lighting, + emissions: Vec<(usize, super::emission::Emission)>, + effects: Vec<(usize, crate::surface_patterns::PreparedEffect)>, + work: WorkBudget, + clip: (f64, f64), + triangles: Vec, + looks: Vec, + body: usize, + triangle: usize, + face_cursor: usize, + chosen: Option, + builder: Option, + bvh: Option, + build_used: u64, + pixels: Vec, + pixel: usize, + sample: u8, + spatial: u8, + primary_coverage: u16, + spatial_radiance: Vec3, + finish_spatial: bool, + emit_spatial_pixel: bool, + pixel_radiance: Vec3, + pending: PendingPixelSlot, + encoder: Option, + done: bool, +} +// Same host slot: a future feature build must prove the actual target layout. +const _: [(); 1] = [(); (std::mem::size_of::() <= 4096) as usize]; + +/// CPU continuations. Preview bytes are complete PNGs but acquire a transferable +/// host lease and identity only when the owning host publishes them. +pub enum ImagePoll { + Pending(Progress), + Preview { png: Vec, samples_per_pixel: u32 }, + Complete(Vec), +} + +/// Additive host-only poll; the public legacy ImagePoll contract is unchanged. +pub(crate) enum PartialImagePoll { + Pending(Progress), + Complete(Vec), + Preview { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, +} + +pub(crate) enum PartialBegin { + Started, + Exhausted, +} + +enum ImageAdvance { + Legacy(ImagePoll), + Partial { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, +} + +impl ImageTask { + pub fn punctual_diagnostics(&self) -> Option { + (!self.punctual_diagnostics.is_empty()).then_some(self.punctual_diagnostics) + } + + pub fn new(scene: ProductScene, request: ImageRequest, cancel: CancelToken, options: RaytraceOptions) -> job::Result { + Self::new_with_environment(scene, request, cancel, options, None) + } + pub fn new_with_environment( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + ) -> job::Result { + Self::new_with_environment_and_nested(scene, request, cancel, options, input, false) + } + + pub(crate) fn new_with_environment_and_nested( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + ) -> job::Result { + Self::new_with_policy(scene, request, cancel, options, input, nested, PreviewPolicy::Legacy) + } + + /// Compatibility helper for the original five regression sources. Activate + /// the real serialized production policy before ordinary admission/construction. + #[cfg(test)] + fn new_with_deterministic_tir( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + nested: bool, + ) -> job::Result { + let mut options = options; + options.dielectric_transport = job::CpuDielectricTransport::StrictTir; + let mut request = request; + request.raytrace = Some(options.clone()); + Self::new_with_environment_and_nested(scene, request, cancel, options, None, nested) + } + + pub(crate) fn new_with_environment_and_nested_and_partial( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + plan: job::PartialPreviewPlan, + ) -> job::Result { + Self::new_with_policy(scene, request, cancel, options, input, nested, PreviewPolicy::Shared(plan)) + } + + pub(crate) fn new_with_environment_and_nested_and_protected_partial( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + plan: job::ProtectedPreviewPlan, + ) -> job::Result { + Self::new_with_policy(scene, request, cancel, options, input, nested, PreviewPolicy::Protected(plan)) + } + + fn new_with_policy( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + policy: PreviewPolicy, + ) -> job::Result { + cancel.check()?; + if options.directional_shadow_transmission && input.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "directional shadow transmission does not support HDR environments")); + } + let mut admission = admit_with_policy(&scene, &request, &options, nested, policy)?; + let partial = policy.partial_plan(); + let mut optical = Vec::new(); + if !options.dielectrics.is_empty() { + let (certificates, parents) = certificates(&scene, &options, nested)?; + let straight_limit = straight_boundary_limit(&options, &certificates)?; + optical.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if optical.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + optical.push(OpticalTask { + straight_limit, + deterministic_tir: options.dielectric_transport == job::CpuDielectricTransport::StrictTir, + tir_continuations: 0, + certificates, + parents, + nested, + pending: None, + }); + } + if input.is_some() { + options.validate_environment_reflections(&scene)?; + } + let extra = input.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(environment_error)?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(extra) + .filter(|v| *v <= options.budget.limits().max_job_bytes) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + admission.preparation_bytes = admission.preparation_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + let environment = input.map(|e| e.begin()).transpose().map_err(environment_error)?; + let lights = lighting(&options)?; + let mut work = match policy { + PreviewPolicy::Protected(plan) => WorkBudget::new_protected(plan), + PreviewPolicy::Legacy | PreviewPolicy::Shared(_) => WorkBudget::new(options.budget.limits().max_work_units), + } + .map_err(error)?; + let anisotropic_targets = anisotropic_faces::prepare(&scene, &options, || work.tick(&cancel).map_err(error))?; + let mut effects = Vec::new(); + if let Some(values) = &options.surface_effects { + effects.try_reserve_exact(values.len()).map_err(|_| error(TraceError::AllocationFailed))?; + if effects.capacity() != values.len() { + return Err(error(TraceError::MemoryLimit)); + } + for value in values { + work.tick(&cancel).map_err(error)?; + let effect = value.prepare()?; + let index = scene + .meshes + .iter() + .position(|body| body.name == value.body) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "surface effect body missing"))?; + // Identity is omitted to preserve the existing pixel path and bytes. + if !effect.is_identity() { + effects.push((index, effect)); + } + } + } + let mut emissions = Vec::new(); + if let Some(values) = &options.emissions { + emissions.try_reserve_exact(values.len()).map_err(|_| error(TraceError::AllocationFailed))?; + if emissions.capacity() != values.len() { + return Err(error(TraceError::MemoryLimit)); + } + for value in values { + work.tick(&cancel).map_err(error)?; + // Skip zero terms to preserve the baseline floating-point path exactly. + if value.strength != 0.0 && value.color.iter().any(|v| *v != 0.0) { + emissions.push((value.body_index, super::emission::Emission::new(value)?)); + } + } + } + let radius = + if scene.meshes.is_empty() { 10.0 } else { scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(request.camera.target) }; + if !radius.is_finite() { + return Err(invalid("invalid product bounds")); + } + let clip = request.camera.clip(radius); + let mut triangles = Vec::new(); + let mut looks = Vec::new(); + let mut pixels = Vec::new(); + triangles.try_reserve_exact(admission.triangles as usize).map_err(|_| error(TraceError::AllocationFailed))?; + looks.try_reserve_exact(admission.triangles as usize).map_err(|_| error(TraceError::AllocationFailed))?; + pixels.try_reserve_exact(request.width as usize * request.height as usize * 4).map_err(|_| error(TraceError::AllocationFailed))?; + // Allocator capacities are checked, not assumed equal to requested capacities. + let actual = BvhBuilder::required_bytes(admission.triangles as usize, triangles.capacity(), limits(options.budget)).map_err(error)?; + if actual != BvhBuilder::required_bytes(admission.triangles as usize, admission.triangles as usize, limits(options.budget)).map_err(error)? + || looks.capacity() != admission.triangles as usize + || pixels.capacity() != request.width as usize * request.height as usize * 4 + { + return Err(error(TraceError::MemoryLimit)); + } + let pending = PendingPixelSlot::new(&cancel)?; + let budget = options.budget; + let progressive = options + .progressive + .map(|options| -> job::Result { + let bytes = PrimaryFilm::required_bytes(request.width, request.height, options, budget)?; + let film = PrimaryFilm::new(request.width, request.height, options, bytes, &cancel, budget)?; + Ok(Progressive { film, options, resolving: false, resolve_pixel: 0, partial_plan: partial, partial: None, last_partial: None }) + }) + .transpose()?; + Ok(Self { + punctual_diagnostics: Default::default(), + progressive, + last_pass_boundary: 0, + optical, + anisotropic_targets, + environment, + visibility_owner: dielectric::DirectVisibilityOwner::new(scene, options), + request, + cancel, + admission, + lights, + emissions, + effects, + clip, + work, + triangles, + looks, + body: 0, + triangle: 0, + face_cursor: 0, + chosen: None, + builder: None, + bvh: None, + build_used: 0, + pixels, + pixel: 0, + sample: 0, + spatial: 0, + primary_coverage: 0, + spatial_radiance: Vec3::ZERO, + finish_spatial: false, + emit_spatial_pixel: false, + pixel_radiance: Vec3::ZERO, + pending, + encoder: None, + done: false, + }) + } + pub fn progress(&self) -> Progress { + let (phase, done, total) = if self.done { + (Phase::Completed, 1, 1) + } else if let Some(partial) = self.progressive.as_ref().and_then(|p| p.partial.as_ref()) { + if let Some(encoder) = &self.encoder { + (Phase::Encoding, encoder.row() as u64, u64::from(partial.plan.height())) + } else { + (Phase::Encoding, partial.next as u64, partial.plan.pixels()) + } + } else if let Some(e) = &self.encoder { + (Phase::Encoding, e.row() as u64, self.request.height as u64) + } else if let Some(progressive) = &self.progressive { + let count = u64::from(self.request.width) * u64::from(self.request.height); + if !progressive.film.ready() { + (Phase::Preparing, progressive.film.initialized() as u64, count) + } else if progressive.resolving { + (Phase::Encoding, progressive.resolve_pixel as u64, count) + } else if self.bvh.is_some() { + let partial = if self.pixel as u64 == count { 0 } else { self.pixel as u64 }; + (Phase::Running, u64::from(progressive.film.samples()) * count + partial, u64::from(progressive.options.samples_per_pixel) * count) + } else { + (Phase::Preparing, self.triangles.len() as u64, self.admission.triangles) + } + } else if self.bvh.is_some() { + (Phase::Running, self.pixel as u64, self.request.width as u64 * self.request.height as u64) + } else { + (Phase::Preparing, self.triangles.len() as u64, self.admission.triangles) + }; + Progress { phase, done, total } + } + fn prepare_one(&mut self) -> job::Result<()> { + self.work.tick(&self.cancel).map_err(error)?; + let Some(body) = self.visibility_owner.source().meshes.get(self.body) else { + let triangles = std::mem::take(&mut self.triangles); + let expected = + BvhBuilder::required_bytes(triangles.len(), triangles.capacity(), limits(self.visibility_owner.options().budget)).map_err(error)?; + let builder = BvhBuilder::new(triangles, limits(self.visibility_owner.options().budget), &self.cancel).map_err(error)?; + if builder.admitted_bytes() > expected { + return Err(error(TraceError::MemoryLimit)); + } + self.builder = Some(builder); + return Ok(()); + }; + let Some(indices) = body.mesh.triangles.get(self.triangle) else { + self.body += 1; + self.triangle = 0; + return Ok(()); + }; + let mut vertices = [Vec3::ZERO; 3]; + let mut normals = [Vec3::ZERO; 3]; + for ((p, n), i) in vertices.iter_mut().zip(normals.iter_mut()).zip(indices) { + *p = *body.mesh.positions.get(*i as usize).ok_or_else(|| invalid("triangle vertex index"))?; + *n = body.mesh.normals.get(*i as usize).copied().unwrap_or(Vec3::ZERO); + } + let face = body.mesh.tri_face.get(self.triangle).copied(); + let mut color = body.color; + let mut surface = body.surface; + if let Some(look) = body.faces.get(self.face_cursor) { + self.face_cursor += 1; + if Some(look.face) == face { + self.chosen = Some(look.clone()); + self.face_cursor = body.faces.len(); + } else { + return Ok(()); + } + } + if let Some(look) = self.chosen.take() { + color = look.color; + surface = look.surface; + } + self.face_cursor = 0; + let surface = match surface { + Some(s) => s, + None => OpaqueSurface::new(Vec3::new(srgb8_to_linear(color[0]), srgb8_to_linear(color[1]), srgb8_to_linear(color[2])), 0.0, 0.7, 1.5) + .map_err(|_| invalid("invalid scalar surface"))?, + }; + self.triangles.push(Triangle::new(vertices).map_err(error)?); + self.looks.push(Look { body_index: self.body, face, surface, normals, vertices }); + self.triangle += 1; + Ok(()) + } + fn sample_count(&self) -> u8 { + self.visibility_owner.options().reflections.as_ref().filter(|r| !r.bodies.is_empty()).map_or(1, |r| r.samples) + } + fn finish_sample(&mut self, radiance: Vec3) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + // A Fresnel leaf is not a camera observation. The existing transport + // drains every reflected/transmitted branch into one linear sum first. + // Reject a premature commit rather than averaging branches into film. + if self.progressive.is_some() && self.optical.first().is_some_and(|o| o.pending.is_some()) { + return Err(invalid("progressive film cannot commit an undrained optical tree")); + } + if let Some(progressive) = &mut self.progressive { + if self.primary_coverage > 1 { + return Err(invalid("progressive camera sample has duplicate primary coverage")); + } + let ordinal = progressive.film.samples(); + progressive.film.add(self.pixel, ordinal, [radiance.x, radiance.y, radiance.z], self.primary_coverage == 1, &self.cancel, &mut || { + self.work.tick(&self.cancel).map_err(error) + })?; + self.pending.clear(); + self.primary_coverage = 0; + self.pixel += 1; + return Ok(()); + } + if self.visibility_owner.options().primary_samples != 1 { + return self.finish_spatial_sample(radiance); + } + // Only the current fixed-centre, nonselected primary path is identical + // across reflection samples: directional inputs and the environment's + // fixed u-grid do not depend on self.sample, and this path never bounces. + // Secondary nonselected hits and selected null samples still require R. + let repeats = + if self.sample == 0 && self.pending.as_ref().is_some_and(|p| p.repeatable_primary && p.bounce == 0) { self.sample_count() } else { 1 }; + // Reuse the shading result, but retain the original addition order, + // per-add bound and final divisor exactly. At most64 scalar additions, + // no repeated BVH/BSDF/environment work or new allocation/work budget. + for _ in 0..repeats { + self.pixel_radiance += radiance; + if !self.pixel_radiance.is_finite() + || [self.pixel_radiance.x, self.pixel_radiance.y, self.pixel_radiance.z].into_iter().any(|v| !(0.0..=1e12).contains(&v)) + { + return Err(invalid("reflection radiance exceeds finite transport bound")); + } + self.sample += 1; + } + self.pending.clear(); + if self.sample == self.sample_count() { + let display = map_to_display(self.pixel_radiance / self.sample as f64, self.visibility_owner.options().exposure_ev).map_err(error)?; + self.pixels.extend_from_slice(&[encode8(display.x), encode8(display.y), encode8(display.z), 255]); + self.pixel += 1; + self.sample = 0; + self.pixel_radiance = Vec3::ZERO; + } + Ok(()) + } + fn finish_spatial_sample(&mut self, radiance: Vec3) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + // Same per-R-add finite bound and denominator, including zero/null events. + self.pixel_radiance += radiance; + if !bounded_radiance(self.pixel_radiance) { + return Err(invalid("reflection radiance exceeds finite transport bound")); + } + self.sample = self.sample.checked_add(1).ok_or_else(|| invalid("reflection sample overflow"))?; + if self.sample > self.sample_count() { + return Err(invalid("reflection sample count exceeded")); + } + self.finish_spatial = self.sample == self.sample_count(); + let retain = !self.finish_spatial && self.pending.as_ref().is_some_and(|p| p.repeatable_primary && p.bounce == 0 && p.hit.is_some()); + if retain { + // A completed primary, never a traversal/shading intermediate. The + // existing light cursor has no other len+1 state (at most 8 lights). + let completed = self.lights.lights().len() + 1; + self.pending.as_mut().ok_or_else(|| invalid("missing reusable primary"))?.light = completed; + } else { + self.pending.clear(); + } + Ok(()) + } + fn spatial_transition(&mut self) -> job::Result { + if self.finish_spatial { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + self.work.tick(&self.cancel).map_err(error)?; + self.spatial_radiance += + self.pixel_radiance / f64::from(self.sample_count()) / f64::from(self.visibility_owner.options().primary_samples); + if !bounded_radiance(self.spatial_radiance) { + return Err(invalid("spatial radiance exceeds finite transport bound")); + } + self.pixel_radiance = Vec3::ZERO; + self.sample = 0; + self.spatial = self.spatial.checked_add(1).ok_or_else(|| invalid("spatial sample overflow"))?; + self.finish_spatial = false; + self.emit_spatial_pixel = self.spatial == self.visibility_owner.options().primary_samples; + return Ok(true); + } + if self.emit_spatial_pixel { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + self.work.tick(&self.cancel).map_err(error)?; + let attempts = u16::from(self.visibility_owner.options().primary_samples) + .checked_mul(u16::from(self.sample_count())) + .filter(|n| *n <= 1024) + .ok_or_else(|| invalid("spatial coverage bound"))?; + let rgba = composite_spatial( + self.spatial_radiance, + u32::from(self.primary_coverage), + u32::from(attempts), + self.request.background, + self.visibility_owner.options().exposure_ev, + )?; + self.cancel.check()?; + self.pixels.extend_from_slice(&rgba); + self.pixel += 1; + self.spatial = 0; + self.primary_coverage = 0; + self.spatial_radiance = Vec3::ZERO; + self.emit_spatial_pixel = false; + return Ok(true); + } + Ok(false) + } + fn pixel_one(&mut self) -> job::Result<()> { + if self.visibility_owner.options().primary_samples != 1 && self.pending.as_ref().is_some_and(|p| p.light > self.lights.lights().len()) { + let pending = self.pending.as_ref().ok_or_else(|| invalid("missing reusable primary"))?; + if pending.light != self.lights.lights().len() + 1 + || !pending.repeatable_primary + || pending.directional_active + || pending.bounce != 0 + || pending.hit.is_none() + || self.sample == 0 + || self.sample >= self.sample_count() + || self.spatial >= self.visibility_owner.options().primary_samples + || self.finish_spatial + || self.emit_spatial_pixel + { + return Err(invalid("invalid reusable primary state")); + } + if !pending.surface_ready + || pending.surface_cursor != self.effects.len() + || pending.emission_cursor != self.emissions.len() + || pending.punctual_index != self.visibility_owner.options().punctual_lights.as_ref().map_or(0, Vec::len) + || pending.area_light != self.visibility_owner.options().area_lights.as_ref().map_or(0, Vec::len) + || pending.punctual_shadow + || pending.punctual_ready + || pending.area_shadow + || pending.area_ready + || pending.environment_cursor.is_some() + || pending.environment_sample != self.environment.as_ref().map_or(0, |e| e.samples) + { + return Err(invalid("incomplete reusable primary shading")); + } + let radiance = pending.radiance; + // One actual scalar continuation per logical R; no bulk R loop or + // fabricated traversal debit. Check cancel/limit before mutations. + self.work.tick(&self.cancel).map_err(error)?; + let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing reusable primary BVH"))?; + ensure_directional_drained(Some(pending), self.lights.lights().len())?; + let shared = resolved_surface_hit( + &PreparedScene { bvh, primitives: &self.looks, source: self.visibility_owner.source() }, + pending, + &self.effects, + )?; + if self.optical.first().is_some_and(|o| o.pending.is_some()) + || self.visibility_owner.options().dielectrics.iter().any(|input| input.body_index == shared.body_index) + { + return Err(invalid("optical primary cannot reuse shading")); + } + if self.visibility_owner.options().reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| entry.body == shared.body_name)) { + return Err(invalid("selected primary cannot reuse shading")); + } + self.primary_coverage = + self.primary_coverage.checked_add(1).filter(|n| *n <= 1024).ok_or_else(|| invalid("spatial coverage overflow"))?; + return self.finish_spatial_sample(radiance); + } + if self.visibility_owner.options().primary_samples != 1 && self.spatial_transition()? { + return Ok(()); + } + let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing image BVH"))?; + if self.pending.is_none() { + self.work.tick(&self.cancel).map_err(error)?; + let width = self.request.width as usize; + // This proof belongs to the generator for a fixed (pixel, spatial), + // not the camera/request globally. Future per-R jitter must revoke it. + let (ray, repeatable_primary) = if let Some(progressive) = &self.progressive { + let [dx, dy] = progressive::variates(progressive.options.seed, self.pixel as u64, progressive.film.samples(), 0); + (primary_ray(&self.request, (self.pixel % width) as f64 + dx, (self.pixel / width) as f64 + dy, self.clip).map_err(error)?, false) + } else if self.visibility_owner.options().primary_samples == 1 { + // Preserve the exact legacy centre path, including its reuse proof. + (primary_ray(&self.request, (self.pixel % width) as f64 + 0.5, (self.pixel / width) as f64 + 0.5, self.clip).map_err(error)?, true) + } else { + let [dx, dy] = primary_offset(self.visibility_owner.options().primary_samples, self.spatial)?; + (primary_ray(&self.request, (self.pixel % width) as f64 + dx, (self.pixel / width) as f64 + dy, self.clip).map_err(error)?, true) + }; + if let Some(optical) = self.optical.first_mut() { + if optical.pending.is_some() { + return Err(invalid("previous optical sample was not drained")); + } + let mut state = DielectricPixel::new(ray); + state.camera_sample = self.progressive.as_ref().map(|p| (self.pixel, p.film.samples())); + optical.pending = Some(state); + } + self.pending.insert(PendingPixel { + surface_cursor: 0, + surface_index: None, + surface_ready: false, + emission_cursor: 0, + punctual_index: 0, + punctual_shadow: false, + punctual_ready: false, + punctual_value: Vec3::ZERO, + area_light: 0, + area_index: 0, + area_shadow: false, + area_ready: false, + area_value: Vec3::ZERO, + + repeatable_primary, + environment_sample: 0, + environment_sum: Vec3::ZERO, + environment_cursor: None, + environment_value: Vec3::ZERO, + ray, + cursor: TraceCursor::new(ray, false), + hit: None, + visibility: [true; 8], + directional_transmittance: [Vec3::ZERO; 8], + directional_complete: 0, + directional_active: false, + directional_required: false, + light: 0, + bounce: 0, + throughput: Vec3::new(1.0, 1.0, 1.0), + radiance: Vec3::ZERO, + })?; + return Ok(()); + } + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical primary state"))?; + state.check_camera_sample(self.progressive.as_ref().map(|p| (self.pixel, p.film.samples())))?; + if state.primary_check < self.visibility_owner.options().dielectrics.len() { + self.work.tick(&self.cancel).map_err(error)?; + if let Some(Certificate::ClosedBox(bounds)) = optical.certificates.get(state.primary_check).copied().flatten() + && (dielectric::contains(bounds, state.path.ray.origin()) || dielectric::contains(bounds, self.request.camera.eye())) + { + return Err(invalid("camera or near plane inside a dielectric volume is unsupported")); + } + state.primary_check += 1; + return Ok(()); + } + if state.primary_check != self.visibility_owner.options().dielectrics.len() { + return Err(invalid("invalid primary certificate cursor")); + } + } + if self.pending.as_ref().is_some_and(|pending| pending.directional_active) { + if !self.visibility_owner.options().directional_shadow_transmission { + return Err(invalid("directional cursor active without its runtime mode")); + } + let result = self.visibility_owner.step(&mut self.work, &self.cancel).map_err(error)?; + if let Some(transmittance) = result { + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing directional pixel state"))?; + if pending.light >= super::lighting::MAX_LIGHTS { + return Err(invalid("directional visibility light index")); + } + *pending.directional_transmittance.get_mut(pending.light).ok_or_else(|| invalid("directional visibility result index"))? = + transmittance; + pending.directional_complete |= 1u8 << pending.light; + pending.directional_active = false; + pending.light += 1; + } + return Ok(()); + } + let scene = PreparedScene { bvh, primitives: &self.looks, source: self.visibility_owner.source() }; + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing pixel state"))?; + let primary_segment = + pending.bounce == 0 && self.optical.first().and_then(|o| o.pending.as_ref()).is_none_or(|state| state.path.boundaries == 0); + if pending.hit.is_none() { + let Some(hit) = pending.cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + let Some(hit) = hit else { + if self.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|state| state.path.medium.is_some()) { + return Err(invalid("dielectric path escaped without its certified exit")); + } + if primary_segment { + if let Some(optical) = self.optical.first_mut() { + optical.pending = None; + } + if self.visibility_owner.options().primary_samples != 1 || self.progressive.is_some() { + // A miss is one of S*R attempts, never the completed pixel. + return self.finish_sample(Vec3::ZERO); + } + let [r, g, b] = self.request.background; + self.pixels.extend_from_slice(&[r, g, b, 255]); + self.pixel += 1; + self.sample = 0; + self.pixel_radiance = Vec3::ZERO; + self.pending.clear(); + return Ok(()); + } + if let Some(environment) = &self.environment { + let emitted = + environment.view().map_err(environment_error)?.radiance_linear_srgb(pending.ray.direction()).map_err(environment_error)?; + pending.radiance += multiply(pending.throughput, emitted); + } + if self.environment.is_none() + && let Some(environment) = self.visibility_owner.options().environment + { + let [r, g, b] = environment.color; + pending.radiance += multiply(pending.throughput, Vec3::new(r, g, b) * environment.intensity); + } + let radiance = pending.radiance; + if !bounded_radiance(radiance) { + return Err(invalid("secondary environment radiance exceeds finite bound")); + } + return self.finish_transport_path(radiance); + }; + if primary_segment && (self.visibility_owner.options().primary_samples != 1 || self.progressive.is_some()) { + self.primary_coverage = + self.primary_coverage.checked_add(1).filter(|n| *n <= 1024).ok_or_else(|| invalid("spatial coverage overflow"))?; + } + pending.hit = Some(hit); + pending.light = 0; + let shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + pending.repeatable_primary &= primary_segment && mode.is_none(); + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical hit state"))?; + state.selector = 0; + state.selected = None; + state.ready = false; + // Traversal consumed this continuation; selector work begins next call. + return Ok(()); + } + pending.surface_ready = self.effects.is_empty(); + if !pending.surface_ready { + // Traversal already consumed this continuation's unit. Scan one + // effect per following call, before beginning any lighting stage. + return Ok(()); + } + if self.visibility_owner.options().shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { + let light = self.lights.lights().first().ok_or_else(|| invalid("missing first light"))?; + let ray = shared.spawn(light.direction()).map_err(error)?; + if self.visibility_owner.options().directional_shadow_transmission { + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + } else { + pending.cursor = TraceCursor::new(ray, true); + } + return Ok(()); + } + pending.light = self.lights.lights().len(); + return Ok(()); + } else if self.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|state| !state.ready) { + return self.dielectric_hit_one(); + } else if !pending.surface_ready { + self.work.tick(&self.cancel).map_err(error)?; + if let Some((body_index, _)) = self.effects.get(pending.surface_cursor) { + let hit = pending.hit.ok_or_else(|| invalid("missing surface effect hit"))?; + let look = self.looks.get(hit.primitive_index).ok_or_else(|| invalid("missing surface effect appearance"))?; + let index = pending.surface_cursor; + pending.surface_cursor += 1; + if *body_index == look.body_index { + pending.surface_index = Some(index); + pending.surface_cursor = self.effects.len(); + } + return Ok(()); + } + if pending.surface_cursor != self.effects.len() { + return Err(invalid("invalid surface effect scan state")); + } + pending.surface_ready = true; + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + if self.visibility_owner.options().shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { + let light = self.lights.lights().first().ok_or_else(|| invalid("missing first surface light"))?; + let ray = shared.spawn(light.direction()).map_err(error)?; + if self.visibility_owner.options().directional_shadow_transmission { + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + } else { + pending.cursor = TraceCursor::new(ray, true); + } + } else { + pending.light = self.lights.lights().len(); + } + return Ok(()); + } else if pending.light < self.lights.lights().len() { + if self.visibility_owner.options().directional_shadow_transmission { + let light = self.lights.lights().get(pending.light).ok_or_else(|| invalid("missing directional light"))?; + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let ray = shared.spawn(light.direction()).map_err(error)?; + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + return Ok(()); + } + let Some(shadow) = pending.cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + *pending.visibility.get_mut(pending.light).ok_or_else(|| invalid("light visibility index"))? = shadow.is_none(); + pending.light += 1; + if let Some(light) = self.lights.lights().get(pending.light) { + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, true); + return Ok(()); + } + return Ok(()); + } + if let Some((body_index, emission)) = self.emissions.get(pending.emission_cursor) { + self.work.tick(&self.cancel).map_err(error)?; + let hit = pending.hit.ok_or_else(|| invalid("missing emission hit"))?; + let look = self.looks.get(hit.primitive_index).ok_or_else(|| invalid("missing emission appearance"))?; + pending.emission_cursor += 1; + if *body_index == look.body_index { + let emitted = emission.radiance(hit.geometry.geometric_normal.dot(-pending.ray.direction()) > 0.0); + pending.radiance += multiply(pending.throughput, emitted); + if !bounded_radiance(pending.radiance) { + return Err(invalid("emission path radiance exceeds finite bound")); + } + pending.emission_cursor = self.emissions.len(); + } + return Ok(()); + } + if pending.punctual_index < self.visibility_owner.options().punctual_lights.as_ref().map_or(0, Vec::len) { + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("punctual face missing"))?.face; + let target = anisotropic_faces::target_index(self.visibility_owner.options(), shared.body_index, face) + .map(|i| self.anisotropic_targets.get(i).copied().flatten().ok_or_else(|| invalid("punctual anisotropic target missing"))) + .transpose()?; + punctual_one( + pending, + self.visibility_owner.options(), + bvh, + (shared, target, mode), + &mut self.work, + &self.cancel, + &mut self.punctual_diagnostics, + )?; + return Ok(()); + } + if pending.area_light < self.visibility_owner.options().area_lights.as_ref().map_or(0, Vec::len) { + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("area face missing"))?.face; + let target = anisotropic_faces::target_index(self.visibility_owner.options(), shared.body_index, face) + .map(|i| self.anisotropic_targets.get(i).copied().flatten().ok_or_else(|| invalid("area anisotropic target missing"))) + .transpose()?; + area_one( + pending, + self.visibility_owner.options(), + bvh, + (shared, target, mode), + &mut self.work, + &self.cancel, + area_sample_key( + self.pixel as u64, + self.spatial, + self.visibility_owner.options().primary_samples, + self.progressive.as_ref().map_or(0, |progress| progress.film.samples()), + )?, + )?; + return Ok(()); + } + if let Some(cursor) = &mut pending.environment_cursor { + let Some(blocker) = cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + if blocker.is_none() { + pending.environment_sum += pending.environment_value; + } + pending.environment_cursor = None; + pending.environment_sample += 1; + return Ok(()); + } + if pending.light == self.lights.lights().len() { + self.work.tick(&self.cancel).map_err(error)?; + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + let view = -pending.ray.direction(); + let geometric = shared.oriented_geometric_normal(); + // Disjoint estimators: selected reflectors use BSDF transport to the environment; + // only nonselected opaque hits use environment next-event estimates. + if mode.is_none() + && let Some(environment) = &self.environment + { + if pending.environment_sample < environment.samples { + let side = match environment.samples { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + let i = pending.environment_sample; + let u = if let Some(progressive) = &self.progressive { + let [dx, dy] = progressive::variates( + progressive.options.seed, + self.pixel as u64, + progressive.film.samples(), + 0x1000 + u64::from(pending.bounce) * 128 + u64::from(i), + ); + [(f64::from(i / side) + dx) / f64::from(side), (f64::from(i % side) + dy) / f64::from(side)] + } else if side == 1 { + [0.25, 0.375] + } else { + [(f64::from(i / side) + 0.5) / f64::from(side), (f64::from(i % side) + 0.5) / f64::from(side)] + }; + let sample = environment + .view() + .map_err(environment_error)? + .direct_sample_linear_srgb(u, shared.surface, shared.shading_normal, geometric, view) + .map_err(environment_error)?; + pending.environment_value = sample.contribution_linear_srgb; + if self.visibility_owner.options().shadows && sample.contribution_linear_srgb.len2() > 0.0 { + pending.environment_cursor = Some(TraceCursor::new(shared.spawn(sample.direction).map_err(error)?, true)); + } else { + pending.environment_sum += pending.environment_value; + pending.environment_sample += 1; + } + return Ok(()); + } + pending.radiance += multiply(pending.throughput, pending.environment_sum / f64::from(environment.samples)); + } + let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("missing captured face"))?.face; + let target_index = anisotropic_faces::target_index(self.visibility_owner.options(), shared.body_index, face); + if mode != Some(job::ReflectionMode::Mirror) { + let direct = if self.visibility_owner.options().directional_shadow_transmission { + pending.directional_required = true; + ensure_directional_drained(Some(pending), self.lights.lights().len())?; + self.lights + .shade_linear_transmitted(shared.surface, shared.shading_normal, view, |index, light| { + if geometric.dot(light) <= 0.0 { + return Ok(Vec3::ZERO); + } + if index >= super::lighting::MAX_LIGHTS || pending.directional_complete & (1u8 << index) == 0 { + return Err(TraceError::Internal("directional visibility result is incomplete")); + } + pending.directional_transmittance.get(index).copied().ok_or(TraceError::Internal("directional visibility result index")) + }) + .map_err(error)? + } else { + let visible = |index: usize, light: Vec3| { + Ok(geometric.dot(light) > 0.0 && *pending.visibility.get(index).ok_or(TraceError::Internal("light visibility"))?) + }; + if let Some(index) = target_index { + self.anisotropic_targets + .get(index) + .copied() + .flatten() + .ok_or_else(|| invalid("missing certified anisotropic face"))? + .shade(&self.lights, shared.surface, geometric, view, visible) + .map_err(error)? + } else { + self.lights.shade_linear(shared.surface, shared.shading_normal, view, visible).map_err(error)? + } + }; + pending.radiance += multiply(pending.throughput, direct); + } + let max_bounces = self.visibility_owner.options().reflections.as_ref().map_or(0, |r| r.max_bounces); + if let Some(mode) = mode.filter(|_| pending.bounce < max_bounces) { + let samples = self.visibility_owner.options().reflections.as_ref().map_or(1, |r| u64::from(r.samples)); + let u = if let Some(progressive) = &self.progressive { + progressive::variates(progressive.options.seed, self.pixel as u64, progressive.film.samples(), 0x100 + u64::from(pending.bounce)) + } else if self.visibility_owner.options().primary_samples == 1 { + reflection::variates(self.pixel as u64, self.sample as u64, pending.bounce as u64, samples).map_err(error)? + } else { + let key = spatial_key(self.pixel as u64, self.spatial, self.visibility_owner.options().primary_samples)?; + reflection::variates(key, self.sample as u64, pending.bounce as u64, samples).map_err(error)? + }; + let sampled = match (mode, target_index) { + (job::ReflectionMode::Mirror, _) => reflection::mirror(shared.surface, shared.shading_normal, view), + (job::ReflectionMode::RoughSpecular, Some(index)) => self + .anisotropic_targets + .get(index) + .copied() + .flatten() + .ok_or_else(|| invalid("missing anisotropic reflection target"))? + .sample(shared.surface, geometric, view, u), + (job::ReflectionMode::RoughSpecular, None) => reflection::rough_specular(shared.surface, shared.shading_normal, view, u), + } + .map_err(error)?; + if let Some(sample) = sampled.filter(|s| s.direction.dot(geometric) > 0.0) { + pending.throughput = multiply(pending.throughput, sample.weight); + if !pending.throughput.is_finite() { + return Err(invalid("nonfinite reflection throughput")); + } + if pending.throughput.len2() > 0.0 { + pending.ray = shared.spawn(sample.direction).map_err(error)?; + pending.cursor = TraceCursor::new(pending.ray, false); + pending.hit = None; + pending.surface_cursor = 0; + pending.surface_index = None; + pending.surface_ready = false; + pending.emission_cursor = 0; + pending.light = 0; + pending.visibility = [true; 8]; + pending.directional_transmittance = [Vec3::ZERO; 8]; + pending.directional_complete = 0; + pending.directional_active = false; + pending.directional_required = false; + pending.punctual_index = 0; + pending.punctual_shadow = false; + pending.punctual_ready = false; + pending.punctual_value = Vec3::ZERO; + pending.area_light = 0; + pending.area_index = 0; + pending.area_shadow = false; + pending.area_ready = false; + pending.area_value = Vec3::ZERO; + + pending.environment_sample = 0; + pending.environment_sum = Vec3::ZERO; + pending.environment_cursor = None; + pending.environment_value = Vec3::ZERO; + pending.bounce += 1; + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing reflected optical path"))?; + state.path.ray = pending.ray; + state.path.throughput = pending.throughput; + state.path.segment_start = shared.position; + state.path.bounce = pending.bounce; + state.selector = 0; + state.selected = None; + state.ready = false; + } + return Ok(()); + } + } + } + let radiance = pending.radiance; + return self.finish_transport_path(radiance); + } + Ok(()) + } + /// Complete a transport branch. Only a drained optical stack completes one R sample. + fn finish_transport_path(&mut self, radiance: Vec3) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical sample"))?; + state.check_camera_sample(self.progressive.as_ref().map(|p| (self.pixel, p.film.samples())))?; + if state.advance()? { + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing optical continuation"))?; + resume_optical_path(pending, state.path, self.lights.lights().len())?; + return Ok(()); + } + optical.pending = None; + } + self.finish_sample(radiance) + } + + /// Each selector and each interface is a separate charged continuation. Traversal has + /// already yielded with the captured hit, and opaque hits rejoin the shared light stages. + fn dielectric_hit_one(&mut self) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + self.work.tick(&self.cancel).map_err(error)?; + let optical = self.optical.first_mut().ok_or_else(|| invalid("missing optical task"))?; + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical sample"))?; + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing optical hit"))?; + if state.ready { + return Err(invalid("optical hit already consumed")); + } + let hit = pending.hit.ok_or_else(|| invalid("missing captured optical hit"))?; + let look = self.looks.get(hit.primitive_index).ok_or_else(|| invalid("missing optical appearance"))?; + if let Some(input) = self.visibility_owner.options().dielectrics.get(state.selector) { + let index = state.selector; + state.selector += 1; + if input.body_index == look.body_index { + state.selected = Some(index); + state.selector = self.visibility_owner.options().dielectrics.len(); + } + return Ok(()); + } + if state.selector != self.visibility_owner.options().dielectrics.len() { + return Err(invalid("invalid optical selector state")); + } + let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing optical BVH"))?; + let scene = PreparedScene { bvh, primitives: &self.looks, source: self.visibility_owner.source() }; + // Optics always uses the certified geometric boundary, before optional opaque + // shading-normal effects. Distance starts before the numerical spawn offset. + let mut shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; + let exact_face = if optical.nested { + match state.selected.and_then(|index| optical.certificates.get(index).copied().flatten()) { + Some(Certificate::ClosedBox(bounds)) => { + let face = + dielectric::exact_box_face(bounds, shared.vertices, shared.geometric_normal, shared.position, pending.ray).map_err(error)?; + shared.position = face.point; + Some(face) + } + _ => None, + } + } else { + None + }; + if let Some(index) = state.path.medium { + let medium = self.visibility_owner.options().dielectrics.get(index).ok_or_else(|| invalid("active dielectric medium"))?; + let distance = shared.position.dist(state.path.segment_start); + pending.throughput = multiply(pending.throughput, dielectric::attenuation(medium.absorption_per_mm, distance).map_err(error)?); + if !bounded_radiance(pending.throughput) { + return Err(invalid("dielectric throughput exceeds finite bound")); + } + } + state.ready = true; + let Some(index) = state.selected else { + pending.surface_ready = self.effects.is_empty(); + if !pending.surface_ready { + return Ok(()); + } + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + if self.visibility_owner.options().shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { + let light = self.lights.lights().first().ok_or_else(|| invalid("missing optical opaque light"))?; + let ray = shared.spawn(light.direction()).map_err(error)?; + if self.visibility_owner.options().directional_shadow_transmission { + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + } else { + pending.cursor = TraceCursor::new(ray, true); + } + } else { + pending.light = self.lights.lights().len(); + } + return Ok(()); + }; + let medium = self.visibility_owner.options().dielectrics.get(index).ok_or_else(|| invalid("selected dielectric medium"))?; + if medium.body_index != shared.body_index || medium.body_name != shared.body_name { + return Err(invalid("optical captured identity changed")); + } + pending.repeatable_primary = false; + state.path.ray = pending.ray; + state.path.throughput = pending.throughput; + state.path.bounce = pending.bounce; + if let Some(limit) = optical.straight_limit { + // The active transmitted path was popped immediately; a nonzero + // stack or opaque bounce would invalidate the one-segment proof. + // Preserve all real interfaces/Beer/parent checks below. No tint or + // environment shortcut and no expansion of the branching stack. + if state.path.bounce != 0 || state.stack_len != 0 || state.paths != u16::from(state.path.boundaries) + 1 { + return Err(invalid("unexpected branch in certified straight optical transport")); + } + if state.path.boundaries >= limit { + return Err(invalid("certified straight optical crossing bound exceeded")); + } + } else { + if state.path.boundaries == MAX_BOUNDARIES && !optical.deterministic_tir { + // Unchanged legacy policy; strict mode must first + // distinguish a deterministic TIR from another real split. + let radiance = pending.radiance; + return self.finish_transport_path(radiance); + } + if state.path.boundaries > MAX_BOUNDARIES { + return Err(invalid("invalid dielectric boundary depth")); + } + } + let normal = shared.oriented_geometric_normal(); + let direction = state.path.ray.direction(); + let certificate = optical.certificates.get(index).copied().flatten().ok_or_else(|| invalid("missing dielectric certificate"))?; + let (optics, reflected_weight, transmitted_weight, next_medium) = match certificate { + Certificate::ThinSheet => { + if state.path.medium.is_some() { + return Err(invalid("thin sheet inside dielectric medium")); + } + let (optics, reflected, transmitted) = dielectric::thin_sheet(direction, normal, medium).map_err(error)?; + (optics, reflected, transmitted, None) + } + Certificate::ClosedBox(bounds) => { + let boundary_axes = (0..3) + .filter(|axis| { + let p = super::component(shared.position, *axis); + p == super::component(bounds.min(), *axis) || p == super::component(bounds.max(), *axis) + }) + .count(); + if boundary_axes > 1 { + return Err(invalid("dielectric box edge or corner has an ambiguous interface normal")); + } + let parent = optical.parents.get(index).copied().ok_or_else(|| invalid("missing dielectric parent"))?; + let parent_ior = match parent { + Some(parent) => { + self.visibility_owner.options().dielectrics.get(parent).ok_or_else(|| invalid("missing parent optical material"))?.ior + } + None => 1.0, + }; + let (incident, transmitted, next_medium) = if shared.front_face { + if state.path.medium != parent { + return Err(invalid("dielectric entry does not match certified parent")); + } + (parent_ior, medium.ior, Some(index)) + } else { + if state.path.medium != Some(index) { + return Err(invalid("dielectric exit without matching entry")); + } + (medium.ior, parent_ior, parent) + }; + let optics = dielectric::interface(direction, normal, incident, transmitted).map_err(error)?; + let f = optics.reflectance; + let t = (1.0 - f) * (incident / transmitted).powi(2); + (optics, Vec3::new(f, f, f), Vec3::new(t, t, t), next_medium) + } + }; + let spawn = |direction, reflected| match exact_face { + Some(face) => face.spawn(direction, reflected).map_err(error), + None => shared.spawn(direction).map_err(error), + }; + if optical.deterministic_tir && state.path.throughput == Vec3::ZERO { + // Exact zero after real Beer attenuation owes no outgoing ray or + // positive residual; retain all previously accumulated branches. + let radiance = pending.radiance; + return self.finish_transport_path(radiance); + } + if optical.deterministic_tir && optics.transmitted.is_none() { + if optical.straight_limit.is_some() || optics.reflectance != 1.0 || reflected_weight != Vec3::new(1.0, 1.0, 1.0) { + return Err(invalid("strict deterministic TIR disagrees with its interface")); + } + // REAL ray, normal-aware spawn and next traversal, with the same + // already-paid interface tick. Do not push/pop a one-child tree, + // consume branch depth/paths511, clear the shared radiance sum or + // reset ordinary work. The waiting Fresnel branches remain intact. + let path = OpticalPath { + ray: spawn(optics.reflected, true)?, + throughput: dielectric::multiply(state.path.throughput, reflected_weight), + medium: state.path.medium, + segment_start: shared.position, + boundaries: state.path.boundaries, + bounce: pending.bounce, + }; + optical.tir_continuations = optical.tir_continuations.checked_add(1).ok_or_else(|| error(TraceError::WorkLimit))?; + state.path = path; + state.selector = 0; + state.selected = None; + state.ready = false; + // This creates the real new TraceCursor; its following steps pay + // every original BVH/triangle operation and check cancellation. + resume_optical_path(pending, path, self.lights.lights().len())?; + return Ok(()); + } + if optical.deterministic_tir && optical.straight_limit.is_none() && state.path.boundaries == MAX_BOUNDARIES { + return Err(JobError::new(ErrorCode::LimitExceeded, "strict optical non-TIR branch-depth budget exhausted with positive continuation")); + } + let next_depth = state.path.boundaries + 1; + state.push(OpticalPath { + ray: spawn(optics.reflected, true)?, + throughput: dielectric::multiply(state.path.throughput, reflected_weight), + medium: state.path.medium, + segment_start: shared.position, + boundaries: next_depth, + bounce: pending.bounce, + })?; + if let Some(direction) = optics.transmitted { + state.push(OpticalPath { + ray: spawn(direction, false)?, + throughput: dielectric::multiply(state.path.throughput, transmitted_weight), + medium: next_medium, + segment_start: shared.position, + boundaries: next_depth, + bounce: pending.bounce, + })?; + } + let radiance = pending.radiance; + self.finish_transport_path(radiance) + } + + /// Legacy final-only callers keep their exact contract. Progressive callers + /// must consume `step_with_previews`, so no checkpoint is silently discarded. + pub fn step(&mut self, units: usize) -> job::Result { + self.cancel.check()?; + if self.progressive.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU progressive tasks require step_with_previews")); + } + match self.step_with_previews(units)? { + ImagePoll::Pending(progress) => Ok(TaskPoll::Pending(progress)), + ImagePoll::Complete(png) => Ok(TaskPoll::Complete(png)), + ImagePoll::Preview { .. } => Err(invalid("fixed image produced a progressive checkpoint")), + } + } + + fn release_completed_work(&mut self) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + let bounds = self.visibility_owner.source().bounds; + let old = self.visibility_owner.options(); + let options = RaytraceOptions { + dielectric_transport: old.dielectric_transport, + directional_shadow_transmission: old.directional_shadow_transmission, + budget: old.budget, + progressive: old.progressive, + primary_samples: old.primary_samples, + area_samples: old.area_samples, + seed: old.seed, + preset: old.preset, + exposure_ev: old.exposure_ev, + shadows: old.shadows, + ..Default::default() + }; + self.visibility_owner = dielectric::DirectVisibilityOwner::new(ProductScene { meshes: Vec::new(), bounds }, options); + self.done = true; + self.progressive = None; + self.anisotropic_targets = [None, None]; + self.environment = None; + self.looks = Vec::new(); + self.bvh = None; + self.builder = None; + self.triangles = Vec::new(); + self.pixels = Vec::new(); + self.pending.release(); + self.request.raytrace = None; + self.emissions = Vec::new(); + self.optical = Vec::new(); + self.effects = Vec::new(); + self.lights = Lighting::new(Vec::new()).map_err(error)?; + self.encoder = None; + Ok(()) + } + + pub(crate) fn protected_preview_report(&self) -> Option { + self.work.protected_report() + } + + pub(crate) fn partial_preview_ready(&self, plan: job::PartialPreviewPlan) -> job::Result { + self.cancel.check()?; + plan.validate()?; + if (plan.source_width(), plan.source_height()) != (self.request.width, self.request.height) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview source dimensions changed")); + } + let Some(progressive) = &self.progressive else { return Ok(false) }; + if progressive.partial_plan != Some(plan) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview plan differs from the task policy")); + } + if self.done + || !progressive.film.ready() + || !self.pending.is_none() + || self.optical.first().is_some_and(|o| o.pending.is_some()) + || self.encoder.is_some() + || progressive.partial.is_some() + || progressive.resolving + || !self.pixels.is_empty() + { + return Ok(false); + } + let frontier = progressive.film.partial_frontier()?; + if frontier.completed_passes >= progressive.options.samples_per_pixel { + return Ok(false); + } + let safe = if frontier.updated_prefix == 0 { + frontier.completed_passes > 0 && self.pixel == frontier.pixels + } else { + self.pixel == frontier.updated_prefix + }; + if !safe { + return Ok(false); + } + if self.work.protected.is_some() && !self.work.protected_ready(committed_frontier(frontier)?).map_err(error)? { + return Ok(false); + } + progressive::represented_changed(plan, progressive.last_partial, frontier) + } + + pub(crate) fn completed_pass_preview_ready(&self, plan: job::PartialPreviewPlan) -> job::Result> { + if self.work.protected.is_none() || !self.partial_preview_ready(plan)? { + return Ok(None); + } + let frontier = self.progressive.as_ref().ok_or_else(|| invalid("missing progressive film"))?.film.partial_frontier()?; + Ok((frontier.updated_prefix == 0 && frontier.completed_passes > 0).then_some(frontier.completed_passes)) + } + + /// Host must already hold its one in-flight credit. No host lease or clock + /// lives here; an insufficient optional debit does not mutate trace state. + pub(crate) fn begin_partial_preview(&mut self, plan: job::PartialPreviewPlan) -> job::Result { + if !self.partial_preview_ready(plan)? { + if self.protected_preview_report().is_some_and(|report| report.quota_exhausted) { + return Ok(PartialBegin::Exhausted); + } + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview requires a fresh safe completed pixel")); + } + let frontier = self.progressive.as_ref().ok_or_else(|| invalid("missing progressive film"))?.film.partial_frontier()?; + if self.work.protected.is_some() { + if !self.work.charge_presentation(committed_frontier(frontier)?, &self.cancel).map_err(error)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected snapshot has no reached unconsumed milestone")); + } + } else { + let units = plan.snapshot_work()?; + if self.work.remaining() < units { + return Ok(PartialBegin::Exhausted); + } + self.work.charge(units, &self.cancel).map_err(error)?; + } + let count = usize::try_from(plan.pixels()).map_err(|_| error(TraceError::MemoryLimit))?; + let mut covered = Vec::new(); + covered.try_reserve_exact(count).map_err(|_| error(TraceError::AllocationFailed))?; + if covered.capacity() != count { + return Err(error(TraceError::MemoryLimit)); + } + self.cancel.check()?; + let progressive = self.progressive.as_mut().ok_or_else(|| invalid("missing progressive film"))?; + progressive.partial = Some(progressive::PartialResolve { plan, frontier, resume_pixel: self.pixel, next: 0, covered }); + Ok(PartialBegin::Started) + } + + /// One prepaid representative resolve, encoder setup, or encoding row. + /// Work was debited before allocation; cancel/continuation bounds remain real. + fn partial_preview_one(&mut self) -> job::Result> { + self.cancel.check()?; + let (plan, frontier, resume_pixel, next) = { + let partial = self.progressive.as_ref().and_then(|p| p.partial.as_ref()).ok_or_else(|| invalid("missing partial resolve state"))?; + (partial.plan, partial.frontier, partial.resume_pixel, partial.next) + }; + let count = usize::try_from(plan.pixels()).map_err(|_| error(TraceError::MemoryLimit))?; + if next < count { + let index = plan.source_index(next)?; + let value = self.progressive.as_ref().ok_or_else(|| invalid("missing partial film"))?.film.partial_pixel(index)?; + let (rgba, covered) = match value { + crate::film::primary::PartialPixel::Unknown => ([0; 4], 0), + crate::film::primary::PartialPixel::Sampled { linear_premultiplied, covered, count } => { + let [r, g, b] = linear_premultiplied; + ( + composite_spatial(Vec3::new(r, g, b), covered, count, self.request.background, self.visibility_owner.options().exposure_ev)?, + covered, + ) + } + }; + if next.checked_mul(4) != Some(self.pixels.len()) { + return Err(invalid("partial RGBA cursor mismatch")); + } + self.cancel.check()?; + let partial = self.progressive.as_mut().and_then(|p| p.partial.as_mut()).ok_or_else(|| invalid("missing partial cell state"))?; + if partial.covered.len() != next || partial.covered.capacity() != count { + return Err(invalid("partial coverage cursor or capacity mismatch")); + } + self.pixels.extend_from_slice(&rgba); + partial.covered.push(covered); + partial.next += 1; + return Ok(None); + } + if next != count { + return Err(invalid("partial display cursor exceeded its plan")); + } + if self.encoder.is_none() { + let limit = plan.encoded_limit()?; + let capacity = usize::try_from(limit).map_err(|_| error(TraceError::MemoryLimit))?; + let mut output = Vec::new(); + output.try_reserve_exact(capacity).map_err(|_| error(TraceError::AllocationFailed))?; + if output.capacity() != capacity { + return Err(error(TraceError::MemoryLimit)); + } + self.cancel.check()?; + self.encoder = Some(job::encoding::PngEncoding::with_output(plan.width(), plan.height(), limit, self.cancel.clone(), output)?); + return Ok(None); + } + let png = self.encoder.as_mut().ok_or_else(|| invalid("missing partial encoder"))?.step(&self.pixels)?; + let Some(png) = png else { return Ok(None) }; + self.cancel.check()?; + let progressive = self.progressive.as_mut().ok_or_else(|| invalid("missing completed partial film"))?; + if progressive.film.partial_frontier()? != frontier || self.pixel != resume_pixel || !self.pending.is_none() { + return Err(invalid("partial snapshot changed its captured sample frontier")); + } + let partial = progressive.partial.take().ok_or_else(|| invalid("missing completed partial output"))?; + if partial.covered.len() != count || partial.covered.capacity() != count { + return Err(invalid("partial covered output differs from its plan")); + } + let updated_prefix = u64::try_from(frontier.updated_prefix).map_err(|_| error(TraceError::MemoryLimit))?; + progressive.last_partial = Some(frontier); + self.encoder = None; + self.pixels.clear(); + // Preserve the complete-pass sentinel too: after host hashing, the + // ordinary continuation must still charge its tick before P -> 0. + self.pixel = resume_pixel; + Ok(Some(ImageAdvance::Partial { png, covered: partial.covered, completed_passes: frontier.completed_passes, updated_prefix })) + } + + pub(crate) fn step_with_partial_previews(&mut self, units: usize) -> job::Result { + if self.progressive.as_ref().is_none_or(|p| p.partial_plan.is_none()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial polling requires the CPU partial policy")); + } + match self.advance_image(units)? { + ImageAdvance::Legacy(ImagePoll::Pending(progress)) => Ok(PartialImagePoll::Pending(progress)), + ImageAdvance::Legacy(ImagePoll::Complete(png)) => Ok(PartialImagePoll::Complete(png)), + ImageAdvance::Partial { png, covered, completed_passes, updated_prefix } => { + Ok(PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix }) + } + ImageAdvance::Legacy(ImagePoll::Preview { .. }) => Err(invalid("partial policy produced a legacy checkpoint")), + } + } + + fn resolve_progressive_one(&mut self) -> job::Result<()> { + self.work.tick(&self.cancel).map_err(error)?; + let progressive = self.progressive.as_mut().ok_or_else(|| invalid("missing progressive resolve state"))?; + let count = self.request.width as usize * self.request.height as usize; + if progressive.resolve_pixel < count { + let (rgb, covered, samples) = progressive.film.pixel(progressive.resolve_pixel)?; + let rgba = composite_spatial( + Vec3::new(rgb[0], rgb[1], rgb[2]), + covered, + samples, + self.request.background, + self.visibility_owner.options().exposure_ev, + )?; + self.cancel.check()?; + self.pixels.extend_from_slice(&rgba); + progressive.resolve_pixel += 1; + } else { + let capacity = usize::try_from(self.admission.encoded_limit).map_err(|_| error(TraceError::MemoryLimit))?; + let mut output = Vec::new(); + output.try_reserve_exact(capacity).map_err(|_| error(TraceError::AllocationFailed))?; + if output.capacity() != capacity { + return Err(error(TraceError::MemoryLimit)); + } + self.cancel.check()?; + self.encoder = Some(job::encoding::PngEncoding::with_output( + self.request.width, + self.request.height, + self.admission.encoded_limit, + self.cancel.clone(), + output, + )?); + } + Ok(()) + } + + /// At most four continuations/encoding rows. One cumulative work budget spans + /// geometry preparation, every absolute camera sample and every checkpoint. + pub fn step_with_previews(&mut self, units: usize) -> job::Result { + if self.progressive.as_ref().is_some_and(|p| p.partial_plan.is_some()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial CPU tasks require their additive internal poll")); + } + match self.advance_image(units)? { + ImageAdvance::Legacy(poll) => Ok(poll), + ImageAdvance::Partial { .. } => Err(invalid("legacy policy produced a partial snapshot")), + } + } + + fn advance_image(&mut self, units: usize) -> job::Result { + self.cancel.check()?; + if units == 0 || units > 16384 || self.done { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid raytrace step or completed task")); + } + for _ in 0..units.min(4) { + if self.progressive.as_ref().is_some_and(|p| p.partial.is_some()) { + if let Some(preview) = self.partial_preview_one()? { + return Ok(preview); + } + } else if self.progressive.as_ref().is_some_and(|p| !p.film.ready()) { + self.progressive + .as_mut() + .ok_or_else(|| invalid("missing progressive initialization"))? + .film + .initialize_one(&self.cancel, &mut || self.work.tick(&self.cancel).map_err(error))?; + } else if let Some(encoder) = &mut self.encoder { + if self.progressive.is_some() { + self.work + .charge(if encoder.row() < self.request.height as usize { u64::from(self.request.width) } else { 1 }, &self.cancel) + .map_err(error)?; + } + if let Some(png) = encoder.step(&self.pixels)? { + self.cancel.check()?; + if let Some(progressive) = &mut self.progressive { + // The host hashes these exact bytes incrementally. Debit + // their full scan here, before handing ownership over. + self.work.charge(png.len() as u64, &self.cancel).map_err(error)?; + let samples_per_pixel = progressive.film.samples(); + if samples_per_pixel < progressive.options.samples_per_pixel { + progressive.resolving = false; + progressive.resolve_pixel = 0; + self.encoder = None; + self.pixels.clear(); + self.pixel = 0; + return Ok(ImageAdvance::Legacy(ImagePoll::Preview { png, samples_per_pixel })); + } + } + self.release_completed_work()?; + return Ok(ImageAdvance::Legacy(ImagePoll::Complete(png))); + } + } else if self.progressive.as_ref().is_some_and(|p| p.resolving) { + self.resolve_progressive_one()?; + } else if self.environment.as_ref().is_some_and(|e| !e.ready()) { + self.work.tick(&self.cancel).map_err(error)?; + self.environment + .as_mut() + .ok_or_else(|| invalid("missing environment preparation"))? + .prepare_one(|| self.cancel.is_cancelled()) + .map_err(environment_error)?; + } else if self.bvh.is_some() { + if self.pixel == self.request.width as usize * self.request.height as usize { + if let Some(progressive) = &mut self.progressive { + let samples = progressive.film.samples(); + if progressive.partial_plan.is_some() && samples < progressive.options.samples_per_pixel && samples > self.last_pass_boundary + { + self.last_pass_boundary = samples; + return Ok(ImageAdvance::Legacy(ImagePoll::Pending(self.progress()))); + } + self.work.tick(&self.cancel).map_err(error)?; + if samples == progressive.options.samples_per_pixel || progressive.partial_plan.is_none() { + progressive.resolving = true; + } else { + self.pixel = 0; + } + } else { + self.encoder = Some(job::encoding::PngEncoding::new( + self.request.width, + self.request.height, + self.admission.encoded_limit, + self.cancel.clone(), + )?); + } + } else { + self.pixel_one()?; + } + } else if let Some(builder) = &mut self.builder { + let progress = builder.step(1, &self.cancel).map_err(error)?; + for _ in self.build_used..progress.work_used { + self.work.tick(&self.cancel).map_err(error)?; + } + self.build_used = progress.work_used; + if progress.complete { + self.bvh = Some(self.builder.take().ok_or_else(|| invalid("missing builder"))?.finish().map_err(error)?); + } + } else { + self.prepare_one()?; + } + } + Ok(ImageAdvance::Legacy(ImagePoll::Pending(self.progress()))) + } +} +/// Apply the already selected deterministic effect to the shared opaque hit. +/// The captured geometric normal, ray origin, visibility and topology are unchanged. +fn resolved_surface_hit<'a>( + scene: &PreparedScene<'a>, + pending: &PendingPixel, + effects: &[(usize, crate::surface_patterns::PreparedEffect)], +) -> job::Result> { + if !pending.surface_ready || pending.surface_cursor != effects.len() { + return Err(invalid("surface effect is not completely resolved")); + } + let mut shared = scene.resolve_hit(pending.ray, pending.hit.ok_or_else(|| invalid("missing prepared surface hit"))?).map_err(error)?; + if let Some(index) = pending.surface_index { + let (body_index, effect) = effects.get(index).ok_or_else(|| invalid("missing selected surface effect"))?; + if *body_index != shared.body_index { + return Err(invalid("selected surface effect belongs to another body")); + } + let changed = effect.apply(shared.surface, shared.shading_normal, shared.oriented_geometric_normal(), shared.position)?; + shared.surface = changed.surface; + shared.shading_normal = changed.shading_normal; + } + Ok(shared) +} + +fn bounded_radiance(v: Vec3) -> bool { + v.is_finite() && [v.x, v.y, v.z].into_iter().all(|c| (0.0..=1e12).contains(&c)) +} +fn primary_offset(samples: u8, ordinal: u8) -> job::Result<[f64; 2]> { + let side = match samples { + 1 => 1, + 4 => 2, + 16 => 4, + _ => return Err(invalid("invalid spatial sample count")), + }; + if ordinal >= samples { + return Err(invalid("invalid spatial sample ordinal")); + } + Ok([(f64::from(ordinal % side) + 0.5) / f64::from(side), (f64::from(ordinal / side) + 0.5) / f64::from(side)]) +} +fn spatial_key(pixel: u64, ordinal: u8, samples: u8) -> job::Result { + primary_offset(samples, ordinal)?; + pixel + .checked_mul(u64::from(samples)) + .and_then(|n| n.checked_add(u64::from(ordinal))) + .map(|n| n ^ 0x4141_5052_494d_4152) + .ok_or_else(|| invalid("spatial seed overflow")) +} +/// Distinguish film and spatial ordinals before sampling an emitter. The legacy +/// single-primary first pass keeps its original key and reference image bytes. +fn area_sample_key(pixel: u64, spatial: u8, spatial_samples: u8, film_sample: u32) -> job::Result { + primary_offset(spatial_samples, spatial)?; + if film_sample >= job::MAX_CPU_SAMPLES_PER_PIXEL { + return Err(invalid("area-light film sample ordinal exceeds the admitted cap")); + } + if spatial_samples == 1 && film_sample == 0 { + return Ok(pixel); + } + if film_sample < 4096 { + // Preserve every historical ordinal and fixed-primary key exactly. + return pixel + .checked_mul(4096 * 16) + .and_then(|key| key.checked_add(u64::from(film_sample) * 16 + u64::from(spatial))) + .map(|key| key ^ 0x4152_4541_5341_4d50) + .ok_or_else(|| invalid("area-light sample identity overflow")); + } + if pixel >= (1_u64 << 26) || film_sample >= (1_u32 << 20) { + return Err(invalid("area-light extended sample identity exceeds its fields")); + } + let mode = match spatial_samples { + 1 => 0_u64, + 4 => 1, + 16 => 2, + _ => return Err(invalid("area-light primary mode")), + }; + // Separate extended ordinals from old keys and reserve ten low bits for + // the existing light/emitter RNG offsets. No target/budget/cadence key. + Ok((1_u64 << 63) | (pixel << 36) | (u64::from(film_sample) << 16) | (mode << 14) | (u64::from(spatial) << 10)) +} + +fn composite_spatial(premultiplied: Vec3, covered: u32, attempts: u32, background: [u8; 3], exposure: f64) -> job::Result<[u8; 4]> { + if attempts == 0 || attempts > job::MAX_CPU_SAMPLES_PER_PIXEL || covered > attempts || !bounded_radiance(premultiplied) { + return Err(invalid("invalid spatial coverage/radiance")); + } + if covered == 0 { + if premultiplied != Vec3::ZERO { + return Err(invalid("uncovered spatial radiance")); + } + return Ok([background[0], background[1], background[2], 255]); + } + let coverage = f64::from(covered) / f64::from(attempts); + let geometry = map_to_display(premultiplied / coverage, exposure).map_err(error)?; + let display = if covered == attempts { + geometry + } else { + let bg = Vec3::new(srgb8_to_linear(background[0]), srgb8_to_linear(background[1]), srgb8_to_linear(background[2])); + geometry * coverage + bg * (1.0 - coverage) + }; + Ok([encode8(display.x), encode8(display.y), encode8(display.z), 255]) +} + +/// One sample preparation, one traversal operation OR one visible-sum operation. +/// Reuses the existing primary/directional cursor: no second task or heap state. +fn punctual_one( + pending: &mut PendingPixel, + options: &RaytraceOptions, + bvh: &Bvh, + context: (super::prepared::SharedHit<'_>, Option, Option), + work: &mut WorkBudget, + cancel: &CancelToken, + diagnostics: &mut job::PunctualDiagnostics, +) -> job::Result<()> { + let (shared, target, mode) = context; + if pending.punctual_shadow { + if let Some(blocker) = pending.cursor.step(bvh, work, cancel).map_err(error)? { + if blocker.is_some() { + pending.punctual_value = Vec3::ZERO; + } + pending.punctual_shadow = false; + pending.punctual_ready = true; + } + return Ok(()); + } + work.tick(cancel).map_err(error)?; + if pending.punctual_ready { + add_punctual_radiance(pending, pending.punctual_value, diagnostics); + pending.punctual_index += 1; + pending.punctual_ready = false; + return Ok(()); + } + let inputs = options.punctual_lights.as_ref().ok_or_else(|| invalid("punctual options missing"))?; + if mode == Some(job::ReflectionMode::Mirror) { + pending.punctual_index = inputs.len(); + return Ok(()); + } + let light = inputs.get(pending.punctual_index).copied().ok_or_else(|| invalid("punctual source index"))?.light().map_err(error)?; + let sample = light.sample(shared.position).map_err(error)?; + if let Some(reason) = sample.omitted { + match reason { + super::punctual::OmittedSample::NearSource => diagnostics.near_source = diagnostics.near_source.saturating_add(1), + super::punctual::OmittedSample::RadianceLimit => diagnostics.radiance_limit = diagnostics.radiance_limit.saturating_add(1), + } + pending.punctual_index += 1; + return Ok(()); + } + let geometric = shared.oriented_geometric_normal(); + let cosine = if target.is_some() { geometric } else { shared.shading_normal }.dot(sample.direction).max(0.0); + let contribution = if geometric.dot(sample.direction) <= 0.0 || cosine == 0.0 || sample.incident_linear_srgb == Vec3::ZERO { + Vec3::ZERO + } else { + let view = -pending.ray.direction(); + let f = if let Some(target) = target { + target.direct_brdf(shared.surface, geometric, view, sample.direction).map_err(error)? + } else { + shared.surface.brdf(shared.shading_normal, view, sample.direction).map_err(|_| invalid("punctual opaque response"))? + }; + multiply(f, sample.incident_linear_srgb) * cosine + }; + if super::lighting::validate_radiance(contribution).is_err() { + diagnostics.radiance_limit = diagnostics.radiance_limit.saturating_add(1); + pending.punctual_index += 1; + return Ok(()); + } + pending.punctual_value = contribution; + if options.shadows && contribution != Vec3::ZERO { + let Some(ray) = sample.shadow_ray(shared).map_err(error)? else { + diagnostics.shadow_offset_crossed = diagnostics.shadow_offset_crossed.saturating_add(1); + pending.punctual_index += 1; + return Ok(()); + }; + pending.cursor = TraceCursor::new(ray, true); + pending.punctual_shadow = true; + } else { + add_punctual_radiance(pending, contribution, diagnostics); + pending.punctual_index += 1; + } + Ok(()) +} + +fn add_punctual_radiance(pending: &mut PendingPixel, contribution: Vec3, diagnostics: &mut job::PunctualDiagnostics) { + let candidate = pending.radiance + multiply(pending.throughput, contribution); + if super::lighting::validate_radiance(candidate).is_ok() { + pending.radiance = candidate; + } else { + diagnostics.radiance_limit = diagnostics.radiance_limit.saturating_add(1); + } +} + +fn multiply(a: Vec3, b: Vec3) -> Vec3 { + Vec3::new(a.x * b.x, a.y * b.y, a.z * b.z) +} +#[cfg(test)] +fn shadow_ray(ray: Ray, hit: super::Hit, light: Vec3, vertices: [Vec3; 3]) -> super::Result { + let mut n = hit.geometry.geometric_normal; + if n.dot(light) < 0.0 { + n = -n; + } + let [a, b, c] = hit.geometry.barycentric; + let [va, vb, vc] = vertices; + // Reconstruct from captured vertices, not a distant camera. Component-wise + // rounding bounds avoid an unrelated large X translation displacing a Z plane. + let p = va * a + vb * b + vc * c; + let magnitude = |x: f64, y: f64, z: f64| x.abs() * a.abs() + y.abs() * b.abs() + z.abs() * c.abs(); + let e = Vec3::new(magnitude(va.x, vb.x, vc.x), magnitude(va.y, vb.y, vc.y), magnitude(va.z, vb.z, vc.z)) * (8.0 * f64::EPSILON); + let distance = n.x.abs() * e.x + n.y.abs() * e.y + n.z.abs() * e.z; + let shifted = p + n * distance; + let outward = |v: f64, n: f64| { + if n > 0.0 { + v.next_up() + } else if n < 0.0 { + v.next_down() + } else { + v + } + }; + let _ = ray; // hit position comes from geometry, independent of camera distance. + Ray::new(Vec3::new(outward(shifted.x, n.x), outward(shifted.y, n.y), outward(shifted.z, n.z)), light, 0.0_f64.next_up(), super::MAX_DISTANCE_MM) +} + +fn primary_ray(request: &ImageRequest, x: f64, y: f64, clip: (f64, f64)) -> super::Result { + let camera = &request.camera; + let (mut origin, direction) = camera.ray(x, y, request.width as f64, request.height as f64); + if camera.fov == 0.0 { + origin -= camera.back() * (camera.distance * 3.0); + } + let forward = -camera.back(); + let cosine = direction.dot(forward); + if !cosine.is_finite() || cosine <= 0.0 { + return Err(TraceError::InvalidInput("camera ray direction")); + } + let depth = (origin - camera.eye()).dot(forward); + let start = (clip.0 - depth) / cosine; + let length = (clip.1 - clip.0) / cosine; + Ray::new(origin + direction * start, direction, 0.0, length) +} + +#[cfg(test)] +#[path = "image_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "deterministic_primary_tests.rs"] +mod deterministic_primary_tests; + +#[cfg(test)] +#[path = "reflection_image_tests.rs"] +mod reflection_tests; + +fn environment_error(e: crate::lighting::HdrError) -> JobError { + use crate::lighting::HdrErrorCode; + let code = match e.code { + HdrErrorCode::Cancelled => ErrorCode::Cancelled, + HdrErrorCode::LimitExceeded => ErrorCode::LimitExceeded, + HdrErrorCode::AllocationFailed => ErrorCode::AllocationFailed, + _ => ErrorCode::InvalidRequest, + }; + JobError::new(code, e.to_string()) +} + +#[cfg(test)] +#[path = "primary_aa_tests.rs"] +mod primary_aa_tests; + +// One bounded continuation operation, using the same cursor, work accumulator and task. +fn area_one( + pending: &mut PendingPixel, + options: &RaytraceOptions, + bvh: &Bvh, + context: (super::prepared::SharedHit<'_>, Option, Option), + work: &mut WorkBudget, + cancel: &CancelToken, + pixel: u64, +) -> job::Result<()> { + let (shared, target, mode) = context; + if pending.area_shadow { + if let Some(blocker) = pending.cursor.step(bvh, work, cancel).map_err(error)? { + if blocker.is_some() { + pending.area_value = Vec3::ZERO; + } + pending.area_shadow = false; + pending.area_ready = true; + } + return Ok(()); + } + work.tick(cancel).map_err(error)?; + if pending.area_ready { + pending.radiance += multiply(pending.throughput, pending.area_value); + super::lighting::validate_radiance(pending.radiance).map_err(error)?; + pending.area_index += 1; + pending.area_ready = false; + return Ok(()); + } + let inputs = options.area_lights.as_ref().ok_or_else(|| invalid("area options missing"))?; + if mode == Some(job::ReflectionMode::Mirror) { + pending.area_light = inputs.len(); + return Ok(()); + } + let count = options.area_samples.unwrap_or(16); + if pending.area_index == count { + pending.area_light += 1; + pending.area_index = 0; + return Ok(()); + } + let input = inputs.get(pending.area_light).ok_or_else(|| invalid("area source index"))?; + let vec = |[x, y, z]: [f64; 3]| Vec3::new(x, y, z); + let light = super::area::RectangleLight::new(vec(input.center_mm), vec(input.edge_u_mm), vec(input.edge_v_mm), vec(input.color), input.intensity) + .map_err(error)?; + let Some(sample) = + light.sample(shared.position, pixel, pending.area_light as u32, pending.area_index, count, options.seed.unwrap_or(0)).map_err(error)? + else { + pending.area_index += 1; + return Ok(()); + }; + let geometric = shared.oriented_geometric_normal(); + let cosine = if target.is_some() { geometric } else { shared.shading_normal }.dot(sample.direction()).max(0.0); + let contribution = if geometric.dot(sample.direction()) <= 0.0 || cosine == 0.0 { + Vec3::ZERO + } else { + let view = -pending.ray.direction(); + let f = if let Some(target) = target { + target.direct_brdf(shared.surface, geometric, view, sample.direction()).map_err(error)? + } else { + shared.surface.brdf(shared.shading_normal, view, sample.direction()).map_err(|_| invalid("area opaque response"))? + }; + multiply(f, sample.incident()) * cosine + }; + super::lighting::validate_radiance(contribution).map_err(error)?; + pending.area_value = contribution; + if options.shadows && contribution != Vec3::ZERO { + let origin = shared.spawn(sample.direction()).map_err(error)?.origin(); + pending.cursor = TraceCursor::new(sample.shadow_ray(origin).map_err(error)?, true); + pending.area_shadow = true; + } else { + pending.radiance += multiply(pending.throughput, contribution); + super::lighting::validate_radiance(pending.radiance).map_err(error)?; + pending.area_index += 1; + } + Ok(()) +} + +#[cfg(test)] +#[path = "punctual_image_tests.rs"] +mod punctual_image_tests; diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image_tests.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image_tests.rs new file mode 100644 index 000000000..67b05b774 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/image_tests.rs @@ -0,0 +1,3579 @@ +use super::*; +use solidcraft_geom::Aabb3; +fn emission_fixture(reverse: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + use std::sync::Arc; + let mut meshes = Vec::new(); + for (name, lo, hi) in [("emitter", -20.0, 0.0), ("receiver", 0.0, 20.0)] { + let mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(lo, -10.0, 0.0), Vec3::new(hi, -10.0, 0.0), Vec3::new(hi, 10.0, 0.0), Vec3::new(lo, 10.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: if reverse { vec![[0, 2, 1], [0, 3, 2]] } else { vec![[0, 1, 2], [0, 2, 3]] }, + tri_face: vec![0; 2], + ..Default::default() + }; + meshes.push(crate::ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let mut request = request(); + request.width = 2; + request.height = 1; + request.camera.distance = 25.0; + request.camera.fov = 0.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(Vec::new()), + emissions: Some(vec![job::SurfaceEmission { + body_index: 0, + body: "emitter".into(), + color: [0.25, 0.5, 1.0], + strength: 1.0, + sides: job::EmissionSides::Front, + }]), + ..Default::default() + }; + (ProductScene { meshes, bounds }, request, options) +} +fn emission_png(scene: ProductScene, mut request: ImageRequest, options: RaytraceOptions) -> Vec { + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..10_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("emission fixture did not complete"); +} +#[test] +fn emission_actual_png_adds_linear_radiance_once_and_never_lights_neighbor() { + let (scene, request, mut options) = emission_fixture(false); + for ev in [0.0, 1.0] { + options.exposure_ev = ev; + let image = ::image::load_from_memory(&emission_png(scene.clone(), request.clone(), options.clone())).unwrap().to_rgba8(); + let expected = [0.25, 0.5, 1.0].map(|c| { + let v = c * 2.0_f64.powf(ev); + encode8(v / (1.0 + v)) + }); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); + assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255]); + } +} +#[test] +fn emission_zero_default_png_equivalence_and_geometric_sidedness() { + let (scene, request, mut options) = emission_fixture(false); + options.emissions.as_mut().unwrap()[0].strength = 0.0; + let zero = emission_png(scene.clone(), request.clone(), options.clone()); + options.emissions = None; + assert_eq!(zero, emission_png(scene, request, options)); + let (scene, request, mut options) = emission_fixture(true); + let image = ::image::load_from_memory(&emission_png(scene.clone(), request.clone(), options.clone())).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [0, 0, 0, 255], "shading normals cannot turn a back face into an emitter"); + options.emissions.as_mut().unwrap()[0].sides = job::EmissionSides::Both; + let image = ::image::load_from_memory(&emission_png(scene, request, options)).unwrap().to_rgba8(); + assert!(image.get_pixel(0, 0).0[0] > 0); +} +#[test] +fn emission_stale_duplicate_and_capacity_targets_refuse_before_work() { + let (scene, mut request, mut options) = emission_fixture(false); + options.emissions.as_mut().unwrap()[0].body = "renamed".into(); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidScene); + let (_, _, mut options) = emission_fixture(false); + let first = options.emissions.as_ref().unwrap()[0].clone(); + options.emissions.as_mut().unwrap().push(first); + assert!(options.validate().is_err()); + options.emissions = Some(Vec::with_capacity(64)); + assert!(options.validate().is_err()); +} +#[test] +fn emission_survives_face_reflectance_override_without_changing_captured_geometry() { + let (mut scene, request, options) = emission_fixture(false); + let original = scene.meshes[0].mesh.clone(); + let baseline = emission_png(scene.clone(), request.clone(), options.clone()); + scene.meshes[0].faces.push(crate::FaceAppearance { transmission: None, face: 0, color: [0; 3], opacity: 1.0, surface: None }); + assert_eq!(baseline, emission_png(scene.clone(), request, options)); + assert!(std::sync::Arc::ptr_eq(&original, &scene.meshes[0].mesh)); + assert_eq!(scene.meshes[0].faces[0].color, [0; 3]); +} +#[test] +fn emission_scan_observes_cancel_and_exhausts_shared_work_without_png() { + let (scene, mut request, options) = emission_fixture(false); + request.raytrace = Some(options.clone()); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene, request, cancel.clone(), options).unwrap(); + for _ in 0..10_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light == task.lights.lights().len() && p.emission_cursor == 0) { + task.work.limit = task.work.used() + 1; + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + assert!(!task.done); + assert!(task.pixels.is_empty()); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + return; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + panic!("fixture never reached shading"); +} +#[test] +fn thirty_two_emission_bindings_resume_with_four_work_units_and_cancel_without_publication() { + for cancel_midway in [false, true] { + let (mut scene, mut request, mut options) = emission_fixture(false); + while scene.meshes.len() < 32 { + let mut mesh = scene.meshes[1].clone(); + mesh.name = format!("receiver {}", scene.meshes.len()); + scene.meshes.push(mesh); + } + let base = options.emissions.as_ref().unwrap()[0].clone(); + let mut values = Vec::with_capacity(32); + for index in (1..32).chain(std::iter::once(0)) { + values.push(job::SurfaceEmission { body_index: index, body: scene.meshes[index].name.clone(), ..base.clone() }); + } + options.emissions = Some(values); + request.raytrace = Some(options.clone()); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene, request, cancel.clone(), options).unwrap(); + for _ in 0..100_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light == task.lights.lights().len() && p.emission_cursor == 0) { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert_eq!(task.pending.as_ref().unwrap().emission_cursor, 0); + assert_eq!(task.pending.as_ref().unwrap().radiance, Vec3::ZERO); + for expected_cursor in (4..=32).step_by(4) { + let before = task.work.used(); + assert!(matches!(task.step(16384).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 4); + let pending = task.pending.as_ref().unwrap(); + assert_eq!(pending.emission_cursor, expected_cursor); + assert_eq!(pending.radiance, if expected_cursor == 32 { Vec3::new(0.25, 0.5, 1.0) } else { Vec3::ZERO }); + assert!(task.pixels.is_empty()); + if cancel_midway && expected_cursor == 16 { + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.work.used() - before, 4); + assert!(task.pixels.is_empty()); + break; + } + } + if !cancel_midway { + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 1); + assert_eq!(task.pixel, 1); + assert_eq!(task.pixels, [encode8(0.25 / 1.25), encode8(0.5 / 1.5), encode8(0.5), 255]); + } + } +} +fn request() -> ImageRequest { + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: job::Integrator::Raytrace, + raytrace: None, + camera: Default::default(), + width: 8, + height: 8, + background: [10, 20, 30], + transparent_background: false, + } +} +#[test] +fn image_work_exhaustion_is_typed_and_never_publishes_partial_png() { + let mut task = + ImageTask::new(ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }, request(), CancelToken::default(), Default::default()).unwrap(); + task.work = WorkBudget::new(2).unwrap(); + let mut previous = 0; + for _ in 0..20 { + match task.step(1) { + Ok(TaskPoll::Pending(_)) => { + assert!(task.work.used() >= previous); + previous = task.work.used(); + } + Ok(TaskPoll::Complete(_)) => panic!("exhausted task published a frame"), + Err(e) => { + assert_eq!(e.code, ErrorCode::LimitExceeded); + assert_eq!(task.work.used(), 2); + return; + } + } + } + panic!("tiny budget did not stop image"); +} +#[test] +fn thin_shadow_occluder_survives_large_unrelated_translation() { + for x in [0.0, 1.0e12 - 100.0] { + let vertices = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 20.0, 0.0, 0.0), Vec3::new(x, 20.0, 0.0)]; + let receiver = Triangle::new(vertices).unwrap(); + let primary = Ray::new(Vec3::new(x + 5.0, 5.0, 10.0), -Vec3::Z, 0.0, 20.0).unwrap(); + let geometry = receiver.intersect(&primary).unwrap(); + let shadow = shadow_ray(primary, super::super::Hit { primitive_index: 0, geometry }, Vec3::Z, vertices).unwrap(); + assert!(shadow.interval()[0] > 0.0, "secondary rays exclude signed-zero distance after underflow"); + assert!(receiver.intersect(&shadow).is_none(), "self-shadow at translation {x}"); + let occluder = Triangle::new(vertices.map(|v| v + Vec3::Z * 0.005)).unwrap(); + assert!(occluder.intersect(&shadow).is_some(), "thin blocker was skipped at translation {x}"); + } +} +#[test] +fn primary_intervals_follow_camera_clip_planes_for_both_projections_and_up_axes() { + for fov in [0.0, 0.7] { + for up in [crate::UpAxis::Z, crate::UpAxis::Y] { + let mut request = request(); + request.camera.fov = fov; + request.camera.up = up; + let clip = request.camera.clip(20.0); + let ray = primary_ray(&request, 4.0, 4.0, clip).unwrap(); + let forward = -request.camera.back(); + let near_depth = (ray.origin() - request.camera.eye()).dot(forward); + let far_depth = (ray.at(ray.interval()[1]).unwrap() - request.camera.eye()).dot(forward); + assert!((near_depth - clip.0).abs() < 1e-9); + assert!((far_depth - clip.1).abs() < 1e-9); + } + } +} +#[test] +fn resumable_cursor_matches_original_visibility_and_charges_each_unit() { + let cancel = CancelToken::default(); + let triangle = Triangle::new([Vec3::ZERO, Vec3::X, Vec3::Y]).unwrap(); + let mut builder = BvhBuilder::new(vec![triangle], limits(job::CpuBudget::Compact), &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + let bvh = builder.finish().unwrap(); + let ray = Ray::new(Vec3::new(0.2, 0.2, 1.0), -Vec3::Z, 0.0, 2.0).unwrap(); + let expected = bvh.closest_hit(&ray, &mut WorkBudget::new(100).unwrap(), &cancel).unwrap(); + let mut cursor = TraceCursor::new(ray, false); + let mut work = WorkBudget::new(100).unwrap(); + for _ in 0..100 { + let before = work.used(); + let result = cursor.step(&bvh, &mut work, &cancel).unwrap(); + assert_eq!(work.used(), before + 1); + if let Some(actual) = result { + assert_eq!(actual, expected); + return; + } + } + panic!("cursor failed to finish"); +} +#[test] +fn actual_png_has_analytic_lit_and_cast_shadow_pixels() { + use crate::ProductMesh; + use solidcraft_geom::Mesh; + use std::sync::Arc; + fn plane(z: f64, x0: f64, x1: f64) -> ProductMesh { + let mesh = Mesh { + positions: vec![Vec3::new(x0, -10.0, z), Vec3::new(x1, -10.0, z), Vec3::new(x1, 10.0, z), Vec3::new(x0, 10.0, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + ProductMesh { + transmission: None, + name: format!("plane {z}"), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + } + } + let meshes = vec![plane(0.0, -20.0, 20.0), plane(5.0, -5.0, 5.0)]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let scene = ProductScene { meshes, bounds }; + let mut request = request(); + request.width = 40; + request.height = 40; + request.camera.distance = 50.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(vec![job::DirectionalLightOptions { direction: [-1.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]), + ..Default::default() + }; + fn render(scene: ProductScene, mut request: ImageRequest, options: RaytraceOptions) -> ::image::RgbaImage { + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return ::image::load_from_memory(&png).unwrap().to_rgba8(); + } + } + panic!("small analytic render did not complete"); + } + let shadowed = render(scene.clone(), request.clone(), options.clone()); + let lit = render(scene, request, RaytraceOptions { shadows: false, ..options }); + // Top view: screen x maps world x, width40 spans[-20,20]. Blocker[-5,5] + // at z5 casts a footprint[0,10] for the light toward(-1,0,+1). + let shadow = shadowed.get_pixel(27, 20).0; + let unshadowed = lit.get_pixel(27, 20).0; + assert_eq!(shadow, [0, 0, 0, 255]); + // White fully rough conductor: F=1, D=1/pi, Smith visibility + // at normal view yields BRDF=1/[2*pi*(1+cosL)]. + let cosine = (0.5_f64).sqrt(); + let radiance = cosine / (2.0 * std::f64::consts::PI * (1.0 + cosine)); + let expected = encode8(radiance / (1.0 + radiance)); + assert_eq!(unshadowed, [expected, expected, expected, 255]); + assert_eq!(shadowed.get_pixel(7, 20), lit.get_pixel(7, 20), "unoccluded receiver changes when toggling shadows"); +} +fn triangle_task(cancel: CancelToken) -> ImageTask { + use std::sync::Arc; + let mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, -20.0, 0.0), Vec3::new(0.0, 20.0, 0.0)], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "work fixture".into(), + mesh: Arc::new(mesh), + color: [220; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds, + }; + let mut request = request(); + request.camera.distance = 50.0; + request.camera.set_view(crate::StandardView::Top); + ImageTask::new(scene, request, cancel, Default::default()).unwrap() +} +#[test] +fn build_primary_and_shadows_share_cumulative_work_and_exhaust_atomically() { + let mut task = triangle_task(CancelToken::default()); + let mut previous = 0; + let mut built = false; + for _ in 0..10_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() >= previous); + previous = task.work.used(); + built |= task.builder.is_some(); + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light < task.lights.lights().len()) { + assert!(built); + assert!(task.build_used > 0); + assert!(task.work.used() > task.build_used); + task.work.limit = task.work.used() + 1; + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + return; + } + } + panic!("triangle fixture never reached shadow traversal"); +} +#[test] +fn cancellation_is_observed_in_every_ray_image_phase() { + for phase in 0..5 { + let cancel = CancelToken::default(); + let mut task = triangle_task(cancel.clone()); + let mut reached = false; + for _ in 0..100_000 { + let current = match phase { + 0 => task.builder.is_none() && task.bvh.is_none(), + 1 => task.builder.is_some(), + 2 => task.pending.as_ref().is_some_and(|p| p.hit.is_none()), + 3 => task.pending.as_ref().is_some_and(|p| p.hit.is_some()), + _ => task.encoder.is_some(), + }; + if current { + reached = true; + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(reached, "phase {phase}"); + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); + } +} +#[test] +fn runtime_presets_reach_the_lighting_consumer() { + for (runtime, expected) in [ + (job::LightingPreset::Neutral, StudioPreset::Neutral), + (job::LightingPreset::WarmCool, StudioPreset::WarmCool), + (job::LightingPreset::KeyRim, StudioPreset::KeyRim), + ] { + let options = RaytraceOptions { preset: Some(runtime), ..Default::default() }; + assert_eq!(lighting(&options).unwrap(), Lighting::preset(expected).unwrap()); + } + let conflict = RaytraceOptions { preset: Some(job::LightingPreset::Neutral), lights: Some(Vec::new()), ..Default::default() }; + assert_eq!(lighting(&conflict).err().unwrap().code, ErrorCode::InvalidRequest); +} +#[test] +fn warm_cool_preset_changes_actual_triangle_png() { + fn render(preset: job::LightingPreset) -> Vec { + let initial = triangle_task(CancelToken::default()); + let options = RaytraceOptions { preset: Some(preset), ..Default::default() }; + let mut request = initial.request.clone(); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(initial.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(bytes) = task.step(16384).unwrap() { + return bytes; + } + } + panic!("preset render did not complete"); + } + let neutral = ::image::load_from_memory(&render(job::LightingPreset::Neutral)).unwrap().to_rgba8(); + let warm = ::image::load_from_memory(&render(job::LightingPreset::WarmCool)).unwrap().to_rgba8(); + assert_ne!(neutral.get_pixel(4, 4), warm.get_pixel(4, 4)); + assert_eq!(neutral.get_pixel(0, 0), warm.get_pixel(0, 0), "background must remain independent of lighting preset"); +} + +#[test] +fn emission_primary_aa_and_reflection_attempts_preserve_single_linear_value() { + for s in [1, 4, 16] { + for r in [1, 4, 16] { + let (mut scene, request, mut options) = emission_fixture(false); + for body in &mut scene.meshes { + let mesh = std::sync::Arc::make_mut(&mut body.mesh); + for p in &mut mesh.positions { + p.x *= 100.0; + p.y *= 100.0; + } + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + options.primary_samples = s; + options.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "receiver".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: r, + }); + let image = ::image::load_from_memory(&emission_png(scene, request, options)).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [encode8(0.25 / 1.25), encode8(0.5 / 1.5), encode8(0.5), 255], "S{s}/R{r}"); + assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255], "emission does not illuminate the neighboring reflector"); + } + } +} + +#[test] +fn emission_and_directional_point_area_terms_share_one_linear_output_transform() { + let (mut scene, mut request, mut options) = emission_fixture(false); + scene.meshes.truncate(1); + let body = &mut scene.meshes[0]; + for p in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + p.x += 10.0; + } + body.surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()); + scene.bounds = body.mesh.bounds(); + request.width = 1; + request.height = 1; + options.shadows = false; + options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + options.punctual_lights = Some(vec![job::PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 3.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 5.0, + }]); + options.area_samples = Some(1); + let image = ::image::load_from_memory(&emission_png(scene, request, options)).unwrap().to_rgba8(); + // At normal incidence a white fully rough conductor has BRDF 1/(4*pi). + // Point reference distance is 10 mm; the 4 mm² rectangle contributes 5*4/100. + let direct = (2.0 + 3.0 + 5.0 * 4.0 / 100.0) / (4.0 * std::f64::consts::PI); + let expected = [0.25, 0.5, 1.0].map(|e| encode8((e + direct) / (1.0 + e + direct))); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); +} + +#[test] +fn reflected_hit_adds_surface_emission_with_the_current_path_throughput() { + use std::sync::Arc; + let normal = Vec3::new(1.0, 0.0, 1.0) / 2.0_f64.sqrt(); + let mirror_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, -20.0), Vec3::new(-20.0, 20.0, 20.0)], + normals: vec![normal; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let emitter_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(10.0, -4.0, -2.0), Vec3::new(10.0, -4.0, 2.0), Vec3::new(10.0, 4.0, 2.0), Vec3::new(10.0, 4.0, -2.0)], + normals: vec![-Vec3::X; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let base_color = Vec3::new(0.2, 0.5, 0.75); + let meshes = vec![ + crate::ProductMesh { + transmission: None, + name: "mirror".into(), + mesh: Arc::new(mirror_mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(base_color, 1.0, 0.1, 1.5).unwrap()), + faces: Vec::new(), + }, + crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(emitter_mesh), + color: [0; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }, + ]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let mut request = request(); + request.width = 1; + request.height = 1; + request.camera.distance = 50.0; + request.camera.fov = 0.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(Vec::new()), + shadows: false, + emissions: Some(vec![job::SurfaceEmission { + body_index: 1, + body: "emitter".into(), + color: [0.25, 0.5, 1.0], + strength: 2.0, + sides: job::EmissionSides::Front, + }]), + reflections: Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "mirror".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: 1, + }), + ..Default::default() + }; + let image = ::image::load_from_memory(&emission_png(ProductScene { meshes, bounds }, request, options)).unwrap().to_rgba8(); + let schlick = (1.0 - 0.5_f64.sqrt()).powi(5); + let expected = [(0.2, 0.5), (0.5, 1.0), (0.75, 2.0)].map(|(f0, emitted)| { + let radiance = (f0 + (1.0 - f0) * schlick) * emitted; + encode8(radiance / (1.0 + radiance)) + }); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); +} + +#[test] +fn procedural_effects_change_completed_pngs_independently_and_zero_is_byte_identical() { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use solidcraft_geom::Mesh; + use std::sync::Arc; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + let original = mesh.positions.clone(); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![ProductMesh { + transmission: None, + name: "Coupon".into(), + mesh: mesh.clone(), + color: [180; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.7, 0.5, 0.3), 1.0, 0.4, 1.5).unwrap()), + faces: Vec::new(), + }], + }; + let effect = SurfaceEffect { + body: "Coupon".into(), + frame: Default::default(), + repeat_mm: [12.0, 17.0, 20.0], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }; + let render = |effect: Option| { + let mut request = request(); + request.width = 32; + request.height = 32; + request.camera.distance = 40.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { surface_effects: effect.map(|e| vec![e]), shadows: false, ..Default::default() }; + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene.clone(), request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("small surface fixture did not complete"); + }; + let baseline = render(None); + assert_eq!(baseline, render(Some(effect.clone()))); + let rough = render(Some(SurfaceEffect { roughness_amplitude: 0.3, ..effect.clone() })); + let bump = render(Some(SurfaceEffect { bump_amplitude_mm: 0.3, ..effect })); + let base = ::image::load_from_memory(&baseline).unwrap().to_rgba8(); + for changed in [&rough, &bump] { + let decoded = ::image::load_from_memory(changed).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), base.dimensions()); + assert_ne!(decoded, base); + for (a, b) in decoded.pixels().zip(base.pixels()) { + assert_eq!(a[3], b[3]); + } + } + assert_ne!(rough, bump); + assert_eq!(mesh.positions, original); +} + +#[test] +fn surface_target_refusals_are_atomic_before_pixels_or_bvh_allocation() { + use crate::surface_patterns::SurfaceEffect; + let effect = + SurfaceEffect { body: "missing".into(), frame: Default::default(), repeat_mm: [20.0; 3], roughness_amplitude: 0.2, bump_amplitude_mm: 0.0 }; + let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + for effects in [vec![effect.clone()], vec![effect.clone(), effect]] { + let options = RaytraceOptions { surface_effects: Some(effects), ..Default::default() }; + let mut request = request(); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidRequest); + } +} + +fn surface_consumer_fixture() -> (ProductScene, ImageRequest, RaytraceOptions) { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use solidcraft_geom::Mesh; + use std::sync::Arc; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, -20.0, 0.0), Vec3::new(20.0, 20.0, 0.0), Vec3::new(-20.0, 20.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![ProductMesh { + transmission: None, + name: "Coupon".into(), + mesh, + color: [180; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.7, 0.5, 0.3), 1.0, 0.4, 1.5).unwrap()), + faces: Vec::new(), + }], + }; + let options = RaytraceOptions { + surface_effects: Some(vec![SurfaceEffect { + body: "Coupon".into(), + frame: Default::default(), + repeat_mm: [12.0, 17.0, 20.0], + roughness_amplitude: 0.2, + bump_amplitude_mm: 0.3, + }]), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = request(); + request.width = 1; + request.height = 1; + request.camera.distance = 40.0; + request.camera.set_view(crate::StandardView::Top); + request.raytrace = Some(options.clone()); + (scene, request, options) +} + +fn surface_consumer_png(mut task: ImageTask, quantum: usize) -> Vec { + for _ in 0..200_000 { + let used = task.work.used(); + let poll = task.step(quantum).unwrap(); + assert!(task.work.used() - used <= 4, "surface consumer exceeded public work quantum"); + if let TaskPoll::Complete(png) = poll { + return png; + } + } + panic!("bounded surface consumer did not complete"); +} + +fn surface_constant_environment() -> crate::lighting::environment_input::EnvironmentInput { + use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 64, 32, 129]); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap() +} + +#[test] +fn surface_effect_shared_hit_reaches_directional_point_area_and_hdr_consumers() { + use crate::job::{DirectionalLightOptions, PunctualLightOptions, RectangleLightOptions}; + use std::sync::Arc; + for mask in 1..16 { + for shadows in [false, true] { + let (scene, mut request, mut options) = surface_consumer_fixture(); + options.shadows = shadows; + if mask & 1 != 0 { + options.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + } + if mask & 2 != 0 { + options.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 3.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + } + if mask & 4 != 0 { + options.area_lights = Some(vec![RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 5.0, + }]); + options.area_samples = Some(1); + } + let effect = options.surface_effects.as_ref().unwrap()[0].prepare().unwrap(); + let changed = effect.apply(scene.meshes[0].surface.unwrap(), Vec3::Z, Vec3::Z, Vec3::ZERO).unwrap(); + let mut reference_scene = scene.clone(); + reference_scene.meshes[0].surface = Some(changed.surface); + Arc::make_mut(&mut reference_scene.meshes[0].mesh).normals.fill(changed.shading_normal); + let mut reference_options = options.clone(); + reference_options.surface_effects = None; + let reference_request = ImageRequest { raytrace: Some(reference_options.clone()), ..request.clone() }; + request.raytrace = Some(options.clone()); + let environment = || if mask & 8 != 0 { Some(surface_constant_environment()) } else { None }; + let expected = surface_consumer_png( + ImageTask::new_with_environment(reference_scene, reference_request, CancelToken::default(), reference_options, environment()) + .unwrap(), + 1, + ); + for quantum in [1, 4, 16384] { + let actual = surface_consumer_png( + ImageTask::new_with_environment(scene.clone(), request.clone(), CancelToken::default(), options.clone(), environment()).unwrap(), + quantum, + ); + assert_eq!(actual, expected, "mask={mask}, shadows={shadows}, quantum={quantum}"); + } + } + } +} + +fn surface_at_thirty_two_binding_scan() -> ImageTask { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use solidcraft_geom::Mesh; + use std::sync::Arc; + let (mut scene, mut request, mut options) = surface_consumer_fixture(); + let visible = scene.meshes.pop().unwrap(); + let mut effects = Vec::with_capacity(32); + for index in 0..31 { + let name = format!("unused-{index}"); + scene.meshes.push(ProductMesh { + transmission: None, + name: name.clone(), + mesh: Arc::new(Mesh::default()), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + effects.push(SurfaceEffect { body: name, frame: Default::default(), repeat_mm: [20.0; 3], roughness_amplitude: 0.1, bump_amplitude_mm: 0.0 }); + } + scene.meshes.push(visible); + effects.push(options.surface_effects.take().unwrap().remove(0)); + options.surface_effects = Some(effects); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..20_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && !p.surface_ready && p.surface_cursor == 0) { + return task; + } + task.step(1).unwrap(); + } + panic!("did not reach actual unresolved surface scan"); +} + +#[test] +fn thirty_two_surface_bindings_resume_and_refuse_cancel_or_work_exhaustion_without_png() { + let mut task = surface_at_thirty_two_binding_scan(); + for expected_cursor in [4, 8, 12, 16, 20, 24, 28, 32] { + let before = task.work.used(); + assert!(matches!(task.step(16384).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 4); + let pending = task.pending.as_ref().unwrap(); + assert_eq!(pending.surface_cursor, expected_cursor); + assert!(!pending.surface_ready); + assert_eq!(pending.surface_index, if expected_cursor == 32 { Some(31) } else { None }); + assert!(task.pixels.is_empty() && !task.done); + } + let png = surface_consumer_png(task, 4); + assert_eq!(::image::load_from_memory(&png).unwrap().width(), 1); + for cancel in [false, true] { + let mut task = surface_at_thirty_two_binding_scan(); + let before = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = before; + } + assert_eq!(task.step(16384).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert_eq!(task.pending.as_ref().unwrap().surface_cursor, 0); + assert!(task.pixels.is_empty() && !task.done); + } +} + +#[test] +fn surface_effects_reject_ambiguous_targets_and_active_anisotropic_overlap() { + use crate::job::{AnisotropicFaceOptions, AnisotropicOrientation}; + let (scene, mut request, mut options) = surface_consumer_fixture(); + let mut ambiguous = scene.clone(); + ambiguous.meshes.push(scene.meshes[0].clone()); + assert_eq!(admit(&ambiguous, &request, &options).unwrap_err().code, ErrorCode::InvalidRequest); + options.anisotropic_faces[0] = Some(AnisotropicFaceOptions { + body_index: 0, + body_name: "Coupon".into(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: AnisotropicOrientation::Zero, + roughness_x: 0.2, + roughness_y: 0.7, + }); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidRequest); + let identity = options.surface_effects.as_mut().unwrap().first_mut().unwrap(); + identity.roughness_amplitude = 0.0; + identity.bump_amplitude_mm = 0.0; + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).is_ok()); +} + +#[test] +fn reflected_surface_effect_uses_changed_shading_and_resets_before_emitting_secondary_hit() { + use crate::surface_patterns::SurfaceEffect; + use std::sync::Arc; + let normal = Vec3::new(1.0, 0.0, 1.0) / 2.0_f64.sqrt(); + let mirror_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, -20.0), Vec3::new(-20.0, 20.0, 20.0)], + normals: vec![normal; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let emitter_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(10.0, -20.0, -20.0), Vec3::new(10.0, -20.0, 20.0), Vec3::new(10.0, 20.0, 20.0), Vec3::new(10.0, 20.0, -20.0)], + normals: vec![-Vec3::X; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let meshes = vec![ + crate::ProductMesh { + transmission: None, + name: "mirror".into(), + mesh: Arc::new(mirror_mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.2, 0.5, 0.75), 1.0, 0.1, 1.5).unwrap()), + faces: Vec::new(), + }, + crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(emitter_mesh), + color: [0; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }, + ]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let scene = ProductScene { meshes, bounds }; + let effect = SurfaceEffect { + body: "mirror".into(), + frame: Default::default(), + repeat_mm: [12.0, 17.0, 20.0], + roughness_amplitude: 0.2, + bump_amplitude_mm: 0.3, + }; + let changed = effect.prepare().unwrap().apply(scene.meshes[0].surface.unwrap(), normal, normal, Vec3::ZERO).unwrap(); + let mut reference_scene = scene.clone(); + reference_scene.meshes[0].surface = Some(changed.surface); + Arc::make_mut(&mut reference_scene.meshes[0].mesh).normals.fill(changed.shading_normal); + let mut request = request(); + request.width = 1; + request.height = 1; + request.camera.distance = 50.0; + request.camera.fov = 0.0; + request.camera.set_view(crate::StandardView::Top); + for mode in [job::ReflectionMode::Mirror, job::ReflectionMode::RoughSpecular] { + let options = RaytraceOptions { + surface_effects: Some(vec![effect.clone()]), + lights: Some(Vec::new()), + shadows: false, + emissions: Some(vec![job::SurfaceEmission { + body_index: 1, + body: "emitter".into(), + color: [0.25, 0.5, 1.0], + strength: 2.0, + sides: job::EmissionSides::Front, + }]), + reflections: Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "mirror".into(), mode }], + max_bounces: 2, + samples: 16, + }), + ..Default::default() + }; + let mut reference_options = options.clone(); + reference_options.surface_effects = None; + let expected = emission_png(reference_scene.clone(), request.clone(), reference_options); + assert_eq!(emission_png(scene.clone(), request.clone(), options), expected, "mode={mode:?}"); + let decoded = ::image::load_from_memory(&expected).unwrap().to_rgba8(); + assert!(decoded.get_pixel(0, 0).0[..3].iter().any(|value| *value > 0)); + } +} + +fn dielectric_triangle_task(cancel: CancelToken) -> ImageTask { + let task = triangle_task(cancel.clone()); + let mut request = task.request; + let options = RaytraceOptions { + dielectrics: vec![job::DielectricOptions { + body_index: 0, + body_name: "work fixture".into(), + boundary: job::DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + }], + shadows: false, + ..Default::default() + }; + request.raytrace = Some(options.clone()); + let (fixture_scene, _) = task.visibility_owner.into_capture(); + ImageTask::new(fixture_scene, request, cancel, options).unwrap() +} + +#[test] +fn dielectric_branch_traversal_exhausts_the_same_job_work_budget() { + let mut task = dielectric_triangle_task(CancelToken::default()); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.optical.first().and_then(|optical| optical.pending.as_ref()).is_some_and(|state| state.paths > 1) { + assert!(task.work.used() > task.build_used); + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + assert!(!task.done); + return; + } + } + panic!("dielectric branch not reached"); +} + +#[test] +fn completed_dielectric_png_releases_capture_and_path_state() { + let mut task = dielectric_triangle_task(CancelToken::default()); + let weak = std::sync::Arc::downgrade(&task.visibility_owner.source().meshes[0].mesh); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + assert!(::image::load_from_memory(&png).is_ok()); + assert!(weak.upgrade().is_none()); + assert!(task.optical.is_empty()); + assert!(task.visibility_owner.options().dielectrics.is_empty()); + assert!(task.request.raytrace.is_none()); + assert!(task.bvh.is_none()); + return; + } + } + panic!("dielectric fixture did not complete"); +} + +#[test] +fn dielectric_fixed_stack_and_path_caps_return_typed_failures() { + let ray = Ray::new(Vec3::Z, -Vec3::Z, 0.0, 2.0).unwrap(); + let mut state = DielectricPixel::new(ray); + state.paths = MAX_PATHS; + assert_eq!(state.push(state.path).err().unwrap().code, ErrorCode::LimitExceeded); + state.paths = 1; + state.stack_len = state.stack.len(); + assert_eq!(state.push(state.path).err().unwrap().code, ErrorCode::LimitExceeded); +} + +#[test] +fn dielectric_image_path_applies_radiance_eta_squared_at_each_interface() { + let options = RaytraceOptions { + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.pitch = std::f64::consts::FRAC_PI_2; + let mut task = ImageTask::new(dielectric::tests::scene(dielectric::tests::box_body(2.0)), request, CancelToken::default(), options).unwrap(); + let mut entry = None; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) { + let path = state.path; + if path.boundaries == 1 && path.medium == Some(0) { + // Air -> glass at normal incidence: (1-F0)/n^2 = .96/2.25. + let expected = 0.96 / 2.25; + assert!((path.throughput.x - expected).abs() < 1e-13); + assert!((path.throughput.y - expected).abs() < 1e-13); + assert!((path.throughput.z - expected).abs() < 1e-13); + entry = Some(path.throughput.x); + } + if path.boundaries == 2 && path.medium.is_none() { + // Glass -> air independently multiplies by .96*n^2 = 2.16. + let ratio = path.throughput.x / entry.expect("entry checked before exit"); + assert!((ratio - 2.16).abs() < 1e-13); + return; + } + } + } + panic!("slab's first entry and exit were not observed"); +} + +fn optical_sheet(name: &str, x: f64, z: f64) -> crate::ProductMesh { + use std::sync::Arc; + crate::ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(solidcraft_geom::Mesh { + positions: vec![Vec3::new(x - 20.0, -20.0, z), Vec3::new(x + 20.0, -20.0, z), Vec3::new(x + 20.0, 20.0, z), Vec3::new(x - 20.0, 20.0, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + } +} + +fn optical_input(body_index: usize, body_name: &str, ior: f64) -> job::DielectricOptions { + job::DielectricOptions { + body_index, + body_name: body_name.into(), + boundary: job::DielectricBoundary::ThinSheet, + ior, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + } +} + +fn optical_png(mut task: ImageTask, quantum: usize) -> Vec { + for _ in 0..2_000_000 { + let before = task.work.used(); + let poll = task.step(quantum).unwrap(); + assert!(task.work.used() - before <= 4, "an optical continuation exceeded the shared work quantum"); + if let TaskPoll::Complete(png) = poll { + return png; + } + } + panic!("bounded optical fixture did not finish"); +} + +#[test] +fn dielectric_branches_sum_inside_each_spatial_and_reflection_attempt() { + let mut scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + scene.meshes.push(optical_sheet("unused reflector", 100.0, 0.0)); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let mut baseline = None; + for spatial in [1, 4, 16] { + for attempts in [1, 4, 16] { + let options = RaytraceOptions { + primary_samples: spatial, + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + reflections: Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "unused reflector".into(), mode: job::ReflectionMode::Mirror }], + samples: attempts, + max_bounces: 1, + }), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + for quantum in [1, 4, 16384] { + let mut task = ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(); + let mut saw_complete_coverage = false; + let mut done = None; + for _ in 0..2_000_000 { + let before = task.work.used(); + let poll = task.step(quantum).unwrap(); + assert!(task.work.used() - before <= 4); + assert!(task.primary_coverage <= u16::from(spatial) * u16::from(attempts)); + if task.emit_spatial_pixel { + assert_eq!(task.primary_coverage, u16::from(spatial) * u16::from(attempts), "branches are not coverage samples"); + saw_complete_coverage = true; + } + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) + && state.path.boundaries > 0 + { + assert!(!task.pending.as_ref().unwrap().repeatable_primary, "selected optical paths have no opaque reuse proof"); + } + if let TaskPoll::Complete(png) = poll { + done = Some(png); + break; + } + } + let png = done.expect("bounded optical AA fixture completes"); + // A four-unit call may commit/reset coverage before yielding. The + // one-unit run observes that state; every quantum checks final bytes. + if spatial != 1 && quantum == 1 { + assert!(saw_complete_coverage); + } + let rgba = ::image::load_from_memory(&png).unwrap().to_rgba8(); + let pixel = rgba.get_pixel(0, 0).0; + assert!(pixel[0] > 150 && pixel[0] == pixel[1] && pixel[1] == pixel[2]); + if let Some(expected) = &baseline { + assert_eq!(&png, expected, "S={spatial}, R={attempts}, quantum={quantum}; branches sum, S/R average"); + } else { + baseline = Some(png); + } + } + } + } +} + +#[test] +fn unit_ior_sheet_rejoins_surface_emission_and_every_existing_light_consumer() { + use job::{DirectionalLightOptions, PunctualLightOptions, RectangleLightOptions}; + for mask in 1..16 { + let (scene, mut request, mut options) = surface_consumer_fixture(); + request.camera.fov = 0.0; + request.camera.distance = 10.0; + // Shadows are deliberately off: this preview's shadow rays conservatively + // treat every dielectric boundary as an opaque blocker. + options.shadows = false; + if mask & 1 != 0 { + options.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + } + if mask & 2 != 0 { + options.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 3.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + } + if mask & 4 != 0 { + options.area_lights = Some(vec![RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 5.0, + }]); + options.area_samples = Some(4); + } + options.emissions = Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Coupon".into(), + color: [0.1, 0.2, 0.3], + strength: 0.5, + sides: job::EmissionSides::Front, + }]); + request.raytrace = Some(options.clone()); + let environment = || if mask & 8 != 0 { Some(surface_constant_environment()) } else { None }; + let expected = optical_png( + ImageTask::new_with_environment(scene.clone(), request.clone(), CancelToken::default(), options.clone(), environment()).unwrap(), + 1, + ); + let mut transmitted_scene = scene; + transmitted_scene.meshes.push(optical_sheet("sheet", 0.0, 5.0)); + transmitted_scene.bounds = transmitted_scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + options.dielectrics = vec![optical_input(1, "sheet", 1.0)]; + request.raytrace = Some(options.clone()); + for quantum in [1, 4, 16384] { + let actual = optical_png( + ImageTask::new_with_environment(transmitted_scene.clone(), request.clone(), CancelToken::default(), options.clone(), environment()) + .unwrap(), + quantum, + ); + assert_eq!(actual, expected, "the same opaque light/surface/emission consumer after transmission; mask={mask}"); + } + } +} + +fn optical_at_eight_selector_scan() -> ImageTask { + let (mut scene, mut request, mut options) = surface_consumer_fixture(); + for i in 0..8 { + let name = format!("unused sheet {i}"); + let index = scene.meshes.len(); + scene.meshes.push(optical_sheet(&name, 100.0 + 50.0 * f64::from(i), 5.0)); + options.dielectrics.push(optical_input(index, &name, 1.5)); + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some()) + && task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|p| !p.ready && p.selector == 0) + { + return task; + } + task.step(1).unwrap(); + } + panic!("actual optical selector scan not reached"); +} + +#[test] +fn eight_optical_selectors_resume_with_cancel_and_work_checks_before_mutation() { + let mut task = optical_at_eight_selector_scan(); + for expected in [4, 8] { + let before = task.work.used(); + assert!(matches!(task.step(16384).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 4); + let state = task.optical[0].pending.as_ref().unwrap(); + assert_eq!(state.selector, expected); + assert!(!state.ready); + assert!(task.pixels.is_empty()); + } + assert!(!optical_png(task, 4).is_empty()); + for cancelled in [false, true] { + let mut task = optical_at_eight_selector_scan(); + let before = task.work.used(); + if cancelled { + task.cancel.cancel(); + } else { + task.work.limit = before; + } + assert_eq!(task.step(4).err().unwrap().code, if cancelled { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert_eq!(task.optical[0].pending.as_ref().unwrap().selector, 0); + assert!(task.pixels.is_empty() && task.encoder.is_none() && !task.done); + } +} + +#[test] +fn optical_reuse_rejects_an_undrained_branch_and_a_selected_primary() { + fn reusable() -> ImageTask { + let mut task = optical_at_eight_selector_scan(); + // Start a fresh coherent request with an unreachable ordinary reflector to + // request R=4, and a spatial grid whose visible receiver remains opaque. + let mut scene = task.visibility_owner.source().clone(); + let mut request = task.request.clone(); + let mut options = task.visibility_owner.options().clone(); + scene.meshes.push(optical_sheet("unused reflector", 1000.0, 0.0)); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + options.primary_samples = 4; + options.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "unused reflector".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: 4, + }); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + request.raytrace = Some(options.clone()); + task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if task.pending.as_ref().is_some_and(|p| p.light == task.lights.lights().len() + 1) { + assert!(task.optical[0].pending.is_none(), "only drained optics reach the completed opaque marker"); + return task; + } + task.step(1).unwrap(); + } + panic!("completed nonselected primary marker not reached"); + } + for pending_branch in [false, true] { + let mut task = reusable(); + if pending_branch { + task.optical[0].pending = Some(DielectricPixel::new(task.pending.as_ref().unwrap().ray)); + } else { + let (fixture_scene, mut fixture_options) = task.visibility_owner.into_capture(); + fixture_options.dielectrics[0].body_index = 0; + fixture_options.dielectrics[0].body_name = "Coupon".into(); + task.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, fixture_options); + } + let before = task.primary_coverage; + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::InvalidScene); + assert_eq!(task.primary_coverage, before); + assert!(task.pixels.is_empty()); + } +} + +#[test] +fn optical_admission_bills_capacity_and_refuses_ambiguous_effect_and_environment_contracts() { + let scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + let mut options = RaytraceOptions { dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], ..Default::default() }; + let name = scene.meshes[0].name.clone(); + let bytes = options.retained_bytes().unwrap(); + assert_eq!( + bytes, + options.dielectrics.capacity() as u64 * std::mem::size_of::() as u64 + + options.dielectrics[0].body_name.capacity() as u64 + ); + let mut request = dielectric::tests::request(options.clone()); + let with_optics = admit(&scene, &request, &options).unwrap(); + let plain = RaytraceOptions::default(); + let plain_request = ImageRequest { raytrace: Some(plain.clone()), ..request.clone() }; + let without_optics = admit(&scene, &plain_request, &plain).unwrap(); + assert_eq!( + with_optics.estimated_total_bytes - without_optics.estimated_total_bytes, + bytes + request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() + std::mem::size_of::() as u64 + ); + options.surface_effects = Some(vec![crate::surface_patterns::SurfaceEffect { + body: name, + frame: Default::default(), + repeat_mm: [10.0; 3], + roughness_amplitude: 0.1, + bump_amplitude_mm: 0.0, + }]); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidScene); + options.surface_effects.as_mut().unwrap()[0].roughness_amplitude = 0.0; + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).is_ok(), "an identity opaque effect does not change the geometric boundary"); + options.environment = Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }); + request.raytrace = Some(options.clone()); + assert_eq!( + options.validate_environment_reflections(&scene).unwrap_err().code, + ErrorCode::InvalidRequest, + "the same guard is called by engine preflight and host admission" + ); + assert_eq!( + ImageTask::new_with_environment( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + Some(surface_constant_environment()) + ) + .err() + .unwrap() + .code, + ErrorCode::InvalidRequest + ); + options.dielectrics = Vec::with_capacity(9); + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); +} + +#[test] +fn captured_clear_coat_keeps_direct_shading_but_refuses_unmatched_cpu_transport() { + let (mut scene, mut request, mut options) = emission_fixture(false); + let coat = crate::clear_coat::ClearCoat::new(0.8, 0.2, 1.5).unwrap(); + let surface = OpaqueSurface::new(Vec3::new(0.4, 0.3, 0.2), 0.0, 0.4, 1.5).unwrap().with_clear_coat(coat); + scene.meshes[0].surface = Some(surface); + request.raytrace = Some(options.clone()); + admit(&scene, &request, &options).unwrap(); + options.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "emitter".into(), mode: job::ReflectionMode::RoughSpecular }], + max_bounces: 1, + samples: 1, + }); + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).unwrap_err().message.contains("clear-coat transport")); + scene.meshes[0].surface = None; + scene.meshes[0].faces.push(crate::FaceAppearance { face: 0, color: [255; 3], opacity: 1.0, surface: Some(surface), transmission: None }); + assert!(admit(&scene, &request, &options).unwrap_err().message.contains("clear-coat transport")); +} + +#[test] +fn pending_pixel_heap_slot_stays_single_and_reuses_storage_until_completion() { + let mut task = triangle_task(CancelToken::default()); + let initial = task.pending.0.as_ptr(); + assert_eq!(task.pending.0.capacity(), 1); + assert!(task.pending.is_none()); + assert!(std::mem::size_of::() <= 4096); + let expected = admit(task.visibility_owner.source(), &task.request, task.visibility_owner.options()).unwrap(); + assert_eq!(task.admission.estimated_total_bytes, expected.estimated_total_bytes); + assert!(expected.preparation_bytes >= PendingPixelSlot::required_bytes()); + let mut seen = false; + let mut completed = false; + for _ in 0..100_000 { + match task.step(1).unwrap() { + TaskPoll::Pending(_) => { + assert_eq!(task.pending.0.capacity(), 1); + assert_eq!(task.pending.0.as_ptr(), initial, "samples must reuse the one admitted continuation slot"); + assert!(task.pending.0.len() <= 1); + seen |= task.pending.is_some(); + } + TaskPoll::Complete(png) => { + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + assert_eq!(task.pending.0.capacity(), 0, "completed task releases continuation storage before its lease is shrunk"); + assert!(task.pending.is_none()); + completed = true; + break; + } + } + } + assert!(completed, "fixture must complete within its bounded test work"); + assert!(seen, "fixture must exercise a live resumable pixel"); +} + +#[test] +fn cancelled_pending_pixel_allocation_is_refused_before_any_continuation() { + let cancel = CancelToken::default(); + cancel.cancel(); + assert_eq!(PendingPixelSlot::new(&cancel).err().unwrap().code, ErrorCode::Cancelled); +} + +fn nested_optical_task() -> ImageTask { + let (scene, mut options) = dielectric::tests::nested_fixture(false); + for medium in &mut options.dielectrics { + medium.ior = if medium.body_name == "Outer" { 1.5 } else { 2.0 }; + medium.absorption_per_mm = [0.0; 3]; + } + ImageTask::new_with_environment_and_nested(scene, dielectric::tests::request(options.clone()), CancelToken::default(), options, None, true) + .unwrap() +} + +#[test] +fn nested_image_interfaces_use_actual_parent_ior_and_restore_it_on_exit() { + let mut task = nested_optical_task(); + let outer_entry = 0.96 / 2.25; + let inner_entry = outer_entry * (27.0 / 49.0); + let inner_exit = inner_entry * (256.0 / 147.0); + let expected = [(1, Some(0), outer_entry), (2, Some(1), inner_entry), (3, Some(0), inner_exit), (4, None, inner_exit * 2.16)]; + let mut next = 0; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) { + let (depth, medium, throughput) = expected[next]; + if state.path.boundaries == depth && state.path.medium == medium { + assert!((state.path.throughput.x - throughput).abs() < 1e-12); + assert!((state.path.throughput.y - throughput).abs() < 1e-12); + assert!((state.path.throughput.z - throughput).abs() < 1e-12); + next += 1; + if next == expected.len() { + return; + } + } + } + } + panic!("nested first transmitted path did not cross all four interfaces"); +} + +#[test] +fn nested_paths_keep_one_unit_work_cancellation_and_total_budget_contracts() { + for cancel in [false, true] { + let mut task = nested_optical_task(); + let mut observed = false; + for _ in 0..100_000 { + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 1, "one-unit continuation overspent its quantum"); + if task.optical.first().and_then(|optical| optical.pending.as_ref()).is_some_and(|state| state.path.medium == Some(1)) { + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert!(!task.done); + observed = true; + break; + } + } + assert!(observed, "nested interior was never reached"); + } +} + +#[test] +fn nested_admission_bills_parent_table_and_keeps_geometry_and_camera_refusals() { + let (scene, options) = dielectric::tests::nested_fixture(false); + let request = dielectric::tests::request(options.clone()); + let admitted = admit_with_nested(&scene, &request, &options, true).unwrap(); + let original = options.retained_dielectric_bytes().unwrap() + + request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() + + std::mem::size_of::() as u64; + assert!(admitted.preparation_bytes >= original); + assert!(std::mem::size_of::() >= std::mem::size_of::<[Option; MAX_OVERRIDES]>()); + + let mut invalid = scene.clone(); + std::sync::Arc::make_mut(&mut invalid.meshes[1].mesh).triangles.pop(); + assert!(admit_with_nested(&invalid, &request, &options, true).is_err()); + + let mut inside = request.clone(); + inside.camera.distance = 0.1; + inside.camera.target = Vec3::new(0.0, 0.0, 2.0); + let mut task = ImageTask::new_with_environment_and_nested(scene, inside, CancelToken::default(), options, None, true).unwrap(); + for _ in 0..100_000 { + match task.step(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("inside a dielectric")); + return; + } + Ok(TaskPoll::Pending(_)) => {} + Ok(TaskPoll::Complete(_)) => panic!("inside camera must not publish"), + } + } + panic!("inside camera was not refused"); +} + +fn close_gap_nested_task(gap: f64, positive: bool) -> ImageTask { + use std::sync::Arc; + let mut outer = dielectric::tests::box_body(3.0); + outer.name = "OuterGap".into(); + for p in &mut Arc::make_mut(&mut outer.mesh).positions { + *p = Vec3::new(p.x * 0.2, p.y * 0.2, p.z + 1.0); + } + let mut inner = dielectric::tests::box_body(2.0); + inner.name = "InnerGap".into(); + for p in &mut Arc::make_mut(&mut inner.mesh).positions { + *p = Vec3::new(p.x * 0.1, p.y * 0.1, if p.z == 0.0 { 1.0 + gap } else { 3.0 }); + } + let mut scene = dielectric::tests::scene(outer); + scene.meshes.push(inner); + let options = RaytraceOptions { + dielectrics: scene + .meshes + .iter() + .enumerate() + .map(|(body_index, body)| job::DielectricOptions { + body_index, + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ClosedBox, + ior: 1.0, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + }) + .collect(), + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.set_view(if positive { crate::StandardView::Bottom } else { crate::StandardView::Top }); + request.camera.target = Vec3::new(0.0, 0.0, 2.5); + request.camera.fov = 0.0; + ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap() +} + +#[test] +fn positive_one_ulp_nested_gap_and_separated_control_visit_every_real_interface() { + for gap in [f64::EPSILON, 0.25] { + for positive in [false, true] { + let mut task = close_gap_nested_task(gap, positive); + let points = if positive { [1.0, 1.0 + gap, 3.0, 4.0] } else { [4.0, 3.0, 1.0 + gap, 1.0] }; + let media = [Some(0), Some(1), Some(0), None]; + let mut next = 0; + let mut completed = false; + for _ in 0..100_000 { + match task.step(1).unwrap() { + TaskPoll::Pending(_) => { + if next < points.len() + && let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) + && state.path.boundaries == next as u8 + 1 + { + assert_eq!(state.path.medium, media[next]); + assert_eq!(state.path.segment_start.z, points[next]); + assert_eq!(state.path.ray.origin(), state.path.segment_start, "propagation and Beer start share one physical point"); + assert_eq!(state.path.throughput, Vec3::new(1.0, 1.0, 1.0)); + next += 1; + } + } + TaskPoll::Complete(png) => { + assert_eq!(next, 4, "an admitted interface was skipped"); + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [188, 188, 188, 255]); + completed = true; + break; + } + } + } + assert!(completed, "close-gap image failed to complete"); + } + } +} + +#[test] +fn nested_reflected_route_keeps_child_beer_then_restores_parent_from_both_sides() { + for positive in [false, true] { + let (scene, mut options) = dielectric::tests::nested_fixture(false); + for medium in &mut options.dielectrics { + medium.ior = if medium.body_name == "Outer" { 1.5 } else { 2.0 }; + } + let mut request = dielectric::tests::request(options.clone()); + request.camera.set_view(if positive { crate::StandardView::Bottom } else { crate::StandardView::Top }); + request.camera.target = Vec3::new(0.0, 0.0, 2.0); + request.camera.fov = 0.0; + let mut task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let (near, far) = if positive { (1.0, 3.0) } else { (3.0, 1.0) }; + let factor = (0.96 / 2.25) * (27.0 / 49.0) / 49.0; + let reflected = Vec3::new(factor * (-0.1_f64 - 0.3 * 2.0).exp(), factor * (-0.2_f64 - 0.4 * 2.0).exp(), factor); + let returned = dielectric::multiply(reflected, Vec3::new((-0.3_f64 * 2.0).exp(), (-0.4_f64 * 2.0).exp(), 1.0)) * (256.0 / 147.0); + let mut saw_reflected = false; + let mut restored = false; + for _ in 0..1_000_000 { + if let TaskPoll::Complete(_) = task.step(1).unwrap() { + break; + } + let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) else { continue }; + let path = state.path; + if path.boundaries == 3 && path.medium == Some(1) && path.segment_start.z == far { + assert!((path.throughput - reflected).len() < 1e-12); + assert_eq!(path.ray.origin(), path.segment_start); + assert!(path.ray.direction().z * if positive { -1.0 } else { 1.0 } > 0.0); + saw_reflected = true; + } + if saw_reflected && path.boundaries == 4 && path.medium == Some(0) && path.segment_start.z == near { + assert!((path.throughput - returned).len() < 1e-12); + assert_eq!(path.ray.origin(), path.segment_start); + restored = true; + break; + } + } + assert!(saw_reflected && restored, "actual reflected child route never restored its parent"); + } +} + +#[test] +fn exact_box_launch_is_opt_in_and_legacy_default_origin_is_preserved() { + for nested in [false, true] { + let mut material = dielectric::tests::input(job::DielectricBoundary::ClosedBox); + material.ior = 1.0; + let options = RaytraceOptions { dielectrics: vec![material], lights: Some(Vec::new()), shadows: false, ..Default::default() }; + let request = dielectric::tests::request(options.clone()); + let mut task = ImageTask::new_with_environment_and_nested( + dielectric::tests::scene(dielectric::tests::box_body(2.0)), + request, + CancelToken::default(), + options, + None, + nested, + ) + .unwrap(); + let mut observed = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) + && state.path.boundaries == 1 + && state.path.medium == Some(0) + { + assert_eq!(state.path.segment_start.z, 2.0); + if nested { + assert_eq!(state.path.ray.origin(), state.path.segment_start); + } else { + assert!(state.path.ray.origin().z < state.path.segment_start.z, "default must retain its original inward offset"); + } + observed = true; + break; + } + } + assert!(observed, "first box entry was not observed"); + } +} + +// Progressive smooth-optics unit: original tests WRITTEN, NOT COMPILED OR RUN. +pub(super) fn progressive_optics_source( + boundary: job::DielectricBoundary, + thickness: f64, + ior: f64, + samples: u32, +) -> (ProductScene, ImageRequest, RaytraceOptions) { + let body = match boundary { + job::DielectricBoundary::ThinSheet => optical_sheet("captured slab@occurrence-2", 0.0, 0.0), + job::DielectricBoundary::ClosedBox => dielectric::tests::box_body(thickness), + }; + let mut medium = dielectric::tests::input(boundary); + medium.ior = ior; + medium.thickness_mm = if boundary == job::DielectricBoundary::ThinSheet { thickness } else { 0.0 }; + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 97 }), + dielectrics: vec![medium], + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + request.camera.pitch = std::f64::consts::FRAC_PI_2; + (dielectric::tests::scene(body), request, options) +} + +#[derive(Debug, PartialEq)] +struct OpticalProgressiveRun { + checkpoints: Vec<(u32, Vec)>, + png: Vec, + film: Vec<[u64; 3]>, + primaries: Vec<(usize, u32, [u64; 6])>, + work: u64, +} + +fn finish_optical_progressive(mut task: ImageTask, quantum: usize) -> OpticalProgressiveRun { + let mut checkpoints = Vec::new(); + let mut film = None; + let mut primaries = Vec::new(); + let mut previous_sample = None; + let target = task.visibility_owner.options().progressive.unwrap().samples_per_pixel; + for _ in 0..2_000_000 { + if let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.samples() == target + { + film.get_or_insert_with(|| { + (0..task.request.width as usize * task.request.height as usize) + .map(|pixel| progressive.film.pixel(pixel).unwrap().0.map(f64::to_bits)) + .collect() + }); + } + let poll = task.step_with_previews(quantum).unwrap(); + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + let identity = state.camera_sample.unwrap(); + assert_eq!(identity, (task.pixel, task.progressive.as_ref().unwrap().film.samples())); + assert!(task.primary_coverage <= 1, "Fresnel branches cannot become coverage samples"); + if previous_sample != Some(identity) { + // Each fixture hits certified geometry; even the four-unit call + // yields before the first boundary can replace its camera ray. + assert_eq!(state.path.boundaries, 0); + let origin = state.path.ray.origin(); + let direction = state.path.ray.direction(); + primaries.push(( + identity.0, + identity.1, + [origin.x.to_bits(), origin.y.to_bits(), origin.z.to_bits(), direction.x.to_bits(), direction.y.to_bits(), direction.z.to_bits()], + )); + previous_sample = Some(identity); + } + } + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => { + assert!(task.pending.is_none()); + assert!(task.optical.first().unwrap().pending.is_none()); + let (_, covered, count) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!((covered, count), (samples_per_pixel, samples_per_pixel)); + checkpoints.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { + assert!(task.optical.is_empty() && task.progressive.is_none()); + return OpticalProgressiveRun { checkpoints, png, film: film.unwrap(), primaries, work: task.work.used() }; + } + } + } + panic!("original optical progressive fixture did not complete"); +} + +#[test] +fn progressive_optical_trees_commit_once_and_keep_absolute_rays_across_quanta() { + for boundary in [job::DielectricBoundary::ThinSheet, job::DielectricBoundary::ClosedBox] { + let (scene, request, options) = progressive_optics_source(boundary, 2.0, 1.5, 5); + let one = finish_optical_progressive(ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(), 1); + let four = finish_optical_progressive(ImageTask::new(scene, request, CancelToken::default(), options).unwrap(), 4); + assert_eq!(one, four, "film bits, actual primary rays, checkpoints, final and total work agree"); + assert_eq!(one.primaries.len(), 5); + assert_eq!(one.checkpoints.iter().map(|c| c.0).collect::>(), [1, 2, 3, 4]); + assert_ne!(one.primaries[0].2, one.primaries[1].2, "fresh camera jitter, no repeated completed sample"); + let linear = f64::from_bits(one.film[0][0]); + assert!(linear > 0.999 && linear <= 1.0 + 1e-12, "bounded eight-boundary lossless response, not alpha or branch averaging"); + assert_eq!(::image::load_from_memory(&one.png).unwrap().to_rgba8().get_pixel(0, 0).0, [188, 188, 188, 255]); + } +} + +#[test] +fn progressive_optical_checkpoint_is_the_exact_shorter_job_prefix() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 5); + let run = finish_optical_progressive(ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(), 1); + for (samples, png) in &run.checkpoints { + let mut prefix_options = options.clone(); + prefix_options.progressive.as_mut().unwrap().samples_per_pixel = *samples; + let prefix_request = ImageRequest { raytrace: Some(prefix_options.clone()), ..request.clone() }; + let prefix = finish_optical_progressive(ImageTask::new(scene.clone(), prefix_request, CancelToken::default(), prefix_options).unwrap(), 2); + assert_eq!(&prefix.png, png); + assert_eq!(prefix.primaries, run.primaries[..*samples as usize]); + } +} + +#[test] +fn progressive_optical_film_uses_real_beer_distance_for_thin_and_closed_controls() { + for boundary in [job::DielectricBoundary::ThinSheet, job::DielectricBoundary::ClosedBox] { + for thickness in [2.0, 8.0] { + let (scene, mut request, mut options) = progressive_optics_source(boundary, thickness, 1.0, 3); + options.dielectrics[0].absorption_per_mm = [0.1, 0.2, 0.0]; + request.raytrace = Some(options.clone()); + let run = finish_optical_progressive(ImageTask::new(scene, request, CancelToken::default(), options).unwrap(), 1); + for (actual, sigma) in run.film[0].into_iter().zip([0.1_f64, 0.2, 0.0]) { + assert!((f64::from_bits(actual) - (-sigma * thickness).exp()).abs() < 1e-10); + } + assert_eq!(run.primaries.len(), 3); + } + } +} + +#[test] +fn progressive_closed_optics_use_four_percent_fresnel_and_snell_eta_transport() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut saw_entry = false; + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + if state.path.boundaries == 1 && state.path.medium == Some(0) { + let entry = 0.96 / 2.25; + assert!((state.path.throughput.x - entry).abs() < 1e-13); + assert!((state.path.ray.direction() + Vec3::Z).len() < 1e-12); + let reflected = state.stack.iter().flatten().find(|path| path.boundaries == 1 && path.medium.is_none()).unwrap(); + assert!((reflected.throughput.x - 0.04).abs() < 1e-13); + saw_entry = true; + } + if saw_entry && state.path.boundaries == 2 && state.path.medium.is_none() { + assert!((state.path.throughput.x - 0.96 * 0.96).abs() < 1e-12); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0, "first transmitted leaf is not a complete film sample"); + return; + } + } + } + panic!("real progressive slab interfaces not reached"); +} + +#[test] +fn progressive_nested_optics_preserve_parent_beer_distance_and_require_opt_in() { + for reverse in [false, true] { + let (scene, mut options) = dielectric::tests::nested_fixture(reverse); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 19 }); + let mut request = dielectric::tests::request(options.clone()); + request.camera.target = Vec3::new(0.0, 0.0, 2.0); + request.camera.distance = 6.0; + request.camera.fov = 0.0; + assert!(admit(&scene, &request, &options).is_err()); + let run = finish_optical_progressive( + ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(), + 1, + ); + for (actual, exponent) in run.film[0].into_iter().zip([-0.8_f64, -1.2, 0.0]) { + assert!((f64::from_bits(actual) - exponent.exp()).abs() < 1e-10); + } + assert_eq!(::image::load_from_memory(&run.png).unwrap().to_rgba8().get_pixel(0, 0).0, [151, 132, 188, 255]); + } +} + +#[test] +fn progressive_optical_sample_identity_and_commit_barriers_refuse_partial_trees() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ThinSheet, 1.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some() { + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert!(task.finish_sample(Vec3::new(1.0, 1.0, 1.0)).is_err()); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + task.optical.first_mut().unwrap().pending.as_mut().unwrap().camera_sample = Some((0, 1)); + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("absolute camera sample")); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + return; + } + } + panic!("optical camera sample not reached"); +} + +#[test] +fn progressive_optics_keep_cancellation_work_exhaustion_and_geometry_refusals() { + for cancel in [false, true] { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut stopped = false; + for _ in 0..100_000 { + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.work.used() - before <= 1); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.medium.is_some()) { + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + stopped = true; + break; + } + } + assert!(stopped); + } + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut open = scene.clone(); + std::sync::Arc::make_mut(&mut open.meshes[0].mesh).triangles.pop(); + assert!(admit(&open, &request, &options).is_err()); + let mut alpha = scene.clone(); + alpha.meshes[0].opacity = 0.5; + assert!(admit(&alpha, &request, &options).is_err()); + let mut identity = options.clone(); + identity.dielectrics[0].body_name = "stale optical target".into(); + let wrong = ImageRequest { raytrace: Some(identity.clone()), ..request }; + assert!(admit(&scene, &wrong, &identity).is_err()); +} + +#[test] +fn progressive_closed_optics_tir_keeps_medium_and_generates_no_transmitted_branch() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + // Observe a real certified transmitted interior, then exercise its actual + // consumer with an analytic 3-4-5 internal direction at the top face. + // Camera-inside admission is not bypassed for any submitted request. + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.boundaries == 1 && s.path.medium == Some(0)) { + let ray = Ray::new(Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.8, 0.0, 0.6), 0.0, 100.0).unwrap(); + let state = task.optical.first_mut().unwrap().pending.as_mut().unwrap(); + state.stack.fill(None); + state.stack_len = 0; + state.path.ray = ray; + state.path.segment_start = ray.origin(); + state.ready = false; + resume_optical_path(task.pending.as_mut().unwrap(), state.path, task.lights.lights().len()).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + let state = task.optical.first().unwrap().pending.as_ref().unwrap(); + if state.path.boundaries == 2 { + assert_eq!(state.path.medium, Some(0)); + assert!(state.path.ray.direction().z < 0.0); + assert_eq!(state.stack_len, 0, "TIR cannot enqueue a transmitted path"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + return; + } + } + panic!("TIR boundary not consumed"); + } + } + panic!("certified interior not reached"); +} + +#[test] +fn progressive_oblique_box_uses_snell_direction_and_geometric_path_length() { + let (scene, mut request, mut options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + options.dielectrics[0].absorption_per_mm = [0.1, 0.0, 0.0]; + request.raytrace = Some(options.clone()); + request.camera.pitch = std::f64::consts::FRAC_PI_3; + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut incident = None; + let mut entry = None; + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) else { continue }; + if state.path.boundaries == 0 { + incident = Some(state.path.ray.direction()); + } + if state.path.boundaries == 1 && state.path.medium == Some(0) { + let d = incident.unwrap(); + let tx = d.x / 1.5; + let ty = d.y / 1.5; + let tz = -(1.0 - tx * tx - ty * ty).sqrt(); + assert!((state.path.ray.direction() - Vec3::new(tx, ty, tz)).len() < 1e-12); + entry = Some((state.path.segment_start, state.path.throughput, tz)); + } + if state.path.boundaries == 2 && state.path.medium.is_none() { + let (point, throughput, tz) = entry.unwrap(); + let distance = 2.0 / -tz; + assert!((state.path.segment_start.dist(point) - distance).abs() < 1e-10); + assert!((state.path.ray.direction() - incident.unwrap()).len() < 1e-12); + // Exit Fresnel and eta factors are achromatic. Their ratio cancels + // between red and green, leaving only exp(-sigma * REAL distance). + let attenuation = (state.path.throughput.x / state.path.throughput.y) / (throughput.x / throughput.y); + assert!((attenuation - (-0.1 * distance).exp()).abs() < 1e-10); + return; + } + } + panic!("oblique progressive entry/exit not reached"); +} + +#[test] +fn progressive_nested_optics_still_refuse_contacts_and_interior_cameras() { + let (mut scene, mut options) = dielectric::tests::nested_fixture(false); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 19 }); + let request = dielectric::tests::request(options.clone()); + for point in &mut std::sync::Arc::make_mut(&mut scene.meshes[1].mesh).positions { + point.z += 1.0; + } + assert!(admit_with_nested(&scene, &request, &options, true).is_err(), "inner top touches outer top"); + let (scene, mut request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + request.camera.target = Vec3::new(0.0, 0.0, 1.0); + request.camera.distance = 0.1; + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + match task.step_with_previews(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("inside a dielectric")); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + return; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("interior camera cannot publish a checkpoint or final"), + } + } + panic!("interior progressive camera not refused"); +} + +// Original regression implementation guided by Kernel Specialist's analytic +// identity-shell counterexample (FINDING5282bf86 / proposal dae7f679). SOURCE +// ONLY, WRITTEN NOT RUN; expectations are physical, never recorded output. +pub(super) fn straight_identity_shells_source(count: usize, progressive: bool, absorbing: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + assert!((1..=8).contains(&count)); + let mut meshes = Vec::with_capacity(8); + let mut dielectrics = Vec::with_capacity(8); + for index in 0..count { + let h = (count - index) as f64; + let mut body = dielectric::tests::box_body(2.0 * h); + body.name = format!("Straight identity shell {index}"); + for point in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + *point = Vec3::new(if point.x < 0.0 { -(16.0 + h) } else { 16.0 + h }, if point.y < 0.0 { -(16.0 + h) } else { 16.0 + h }, point.z - h); + } + let sigma = if absorbing { 0.01 * (index + 1) as f64 } else { 0.0 }; + dielectrics.push(job::DielectricOptions { + body_index: index, + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ClosedBox, + ior: 1.0, + absorption_per_mm: [sigma, 2.0 * sigma, 0.0], + thickness_mm: 0.0, + }); + meshes.push(body); + } + assert!(dielectrics.capacity() <= 8); + let bounds = meshes.iter().fold(Aabb3::EMPTY, |a, body| a.union(&body.mesh.bounds())); + let options = RaytraceOptions { + dielectrics, + progressive: progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 71 }), + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.background = [188; 3]; + request.camera.target = Vec3::ZERO; + request.camera.distance = 20.0; + request.camera.yaw = 0.0; + request.camera.pitch = std::f64::consts::FRAC_PI_2; + request.camera.fov = 0.0; + (ProductScene { meshes, bounds }, request, options) +} + +pub(super) fn straight_shells_expected_linear(count: usize, absorbing: bool) -> [f64; 3] { + // Each shell's active parent interval totals2mm, including the innermost + // 2mm slab. Sum 2*.01*(1+...+N)=.01*N*(N+1); green doubles sigma. + let tau = if absorbing { 0.01 * (count * (count + 1)) as f64 } else { 0.0 }; + [(-tau).exp(), (-2.0 * tau).exp(), 1.0] +} + +pub(super) fn straight_expected_pixel(linear: [f64; 3]) -> [u8; 4] { + // Independent documented zero-EV Reinhard and IEC sRGB equations, not the + // renderer's compositor/map_to_display/encode8 or a prior output capture. + let rgb = linear.map(|v| { + let mapped = v / (1.0 + v); + let encoded = if mapped <= 0.0031308 { 12.92 * mapped } else { 1.055 * mapped.powf(1.0 / 2.4) - 0.055 }; + (encoded * 255.0 + 0.5).floor() as u8 + }); + [rgb[0], rgb[1], rgb[2], 255] +} + +fn complete_straight_shells(mut task: ImageTask, expected_crossings: u8, expected_linear: [f64; 3]) -> Vec { + let progressive = task.visibility_owner.options().progressive; + let mut final_linear = None; + let mut maximum = 0; + let mut final_png = None; + assert_eq!(task.optical.first().unwrap().straight_limit, Some(expected_crossings)); + for _ in 0..1_000_000 { + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() == progressive.unwrap().samples_per_pixel + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (3, 3)); + final_linear = Some(rgb); + } + let before = task.work.used(); + let poll = task.step_with_previews(1).unwrap(); + // PNG row/hash charges are the unchanged resolve contract. During + // optical traversal/interface stages one unit cannot overspend. + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + assert!(task.work.used() - before <= 1); + assert_eq!(state.stack_len, 0, "zero Fresnel reflection creates no pending branch"); + assert_eq!(state.paths, u16::from(state.path.boundaries) + 1); + maximum = maximum.max(state.path.boundaries); + } + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, .. } => { + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, straight_expected_pixel(expected_linear)); + assert!(task.optical.first().unwrap().pending.is_none()); + } + ImagePoll::Complete(png) => { + final_png = Some(png); + break; + } + } + } + assert_eq!(maximum, expected_crossings, "every real geometric interface was traversed"); + if progressive.is_some() { + for (actual, expected) in final_linear.unwrap().into_iter().zip(expected_linear) { + assert!((actual - expected).abs() < 1e-11, "physical parent-only Beer path length"); + } + } + let png = final_png.expect("certified finite straight path must complete"); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, straight_expected_pixel(expected_linear)); + png +} + +#[test] +fn straight_identity_shells_four_control_five_minimum_and_eight_maximum_reach_environment() { + for progressive in [false, true] { + for count in [4, 5, 8] { + let (scene, request, options) = straight_identity_shells_source(count, progressive, false); + options.validate().unwrap(); + assert!(admit(&scene, &request, &options).is_err(), "nesting still requires explicit opt-in"); + admit_with_nested(&scene, &request, &options, true).unwrap(); + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let png = complete_straight_shells(task, (2 * count) as u8, [1.0; 3]); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [188, 188, 188, 255]); + } + } +} + +#[test] +fn straight_identity_shells_keep_actual_beer_parent_intervals_past_eight_crossings() { + for progressive in [false, true] { + for count in [4, 5, 8] { + let (scene, request, options) = straight_identity_shells_source(count, progressive, true); + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let _ = complete_straight_shells(task, (2 * count) as u8, straight_shells_expected_linear(count, true)); + } + } +} + +#[test] +fn straight_mixed_certificates_derive_two_per_box_and_one_per_sheet_without_extra_stack() { + let (mut scene, mut request, mut options) = straight_identity_shells_source(5, true, false); + for index in 0..3 { + let name = format!("Straight external sheet {index}"); + let body_index = scene.meshes.len(); + scene.meshes.push(optical_sheet(&name, 0.0, 6.0 + index as f64)); + options.dielectrics.push(optical_input(body_index, &name, 1.0)); + } + assert_eq!(options.dielectrics.len(), 8); + assert!(options.dielectrics.capacity() <= 8); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |a, body| a.union(&body.mesh.bounds())); + request.raytrace = Some(options.clone()); + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let _ = complete_straight_shells(task, 13, [1.0; 3]); +} + +#[test] +fn straight_policy_requires_exact_unit_indices_and_no_selected_opaque_reflector() { + assert_eq!(MAX_BOUNDARIES, 8); + assert_eq!(MAX_PATHS, 511); + let (scene, request, options) = straight_identity_shells_source(5, false, false); + for ior in [1.0_f64.next_up(), 1.5] { + let mut changed = options.clone(); + changed.dielectrics[2].ior = ior; + let request = ImageRequest { raytrace: Some(changed.clone()), ..request.clone() }; + let task = ImageTask::new_with_environment_and_nested(scene.clone(), request, CancelToken::default(), changed, None, true).unwrap(); + assert_eq!(task.optical.first().unwrap().straight_limit, None, "no epsilon-index shortcut or new rejection of legacy refracting input"); + } + let mut scene = scene; + let mut changed = options; + scene.meshes.push(optical_sheet("Separate opaque reflector", 100.0, 0.0)); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |a, body| a.union(&body.mesh.bounds())); + changed.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "Separate opaque reflector".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: 1, + }); + let request = ImageRequest { raytrace: Some(changed.clone()), ..request }; + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), changed, None, true).unwrap(); + assert_eq!(task.optical.first().unwrap().straight_limit, None); + assert!(task.optical.first().unwrap().pending.is_none()); +} + +#[test] +fn straight_identity_transport_still_charges_and_can_cancel_or_exhaust_inside_deep_chain() { + for cancel in [false, true] { + let (scene, request, options) = straight_identity_shells_source(8, true, true); + let mut task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let mut observed = false; + for _ in 0..200_000 { + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.work.used() - before <= 1); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.boundaries == 9) { + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + observed = true; + break; + } + } + assert!(observed, "real ninth crossing must be reached before the stop"); + } +} + +#[test] +fn straight_crossing_bound_corruption_is_typed_error_not_a_successful_black_tail() { + let (scene, request, options) = straight_identity_shells_source(5, true, false); + let mut task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + // Controlled invariant unit, distinct from the unchanged valid E2E fixtures: + // an impossible internal policy must fail at a real subsequent interface. + task.optical.first_mut().unwrap().straight_limit = Some(1); + for _ in 0..200_000 { + match task.step_with_previews(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("straight optical crossing bound exceeded")); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + return; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("bound inconsistency cannot publish success"), + } + } + panic!("unexpected extra crossing was not refused"); +} + +// Original camera-to-final TIR supplement, AFTER frozen progressive optics. +// WRITTEN NOT COMPILED/RUN. Observations below never mutate the renderer. +fn camera_tir_source(samples: Option, seed: u32, intensity: f64) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut body = dielectric::tests::box_body(2.0); + for point in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + point.x = if point.x < 0.0 { 0.0 } else { 1.0 }; + } + let options = RaytraceOptions { + progressive: samples.map(|samples_per_pixel| job::CpuProgressiveOptions { samples_per_pixel, seed }), + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity }), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera = crate::Camera { + target: Vec3::new(0.9, 0.37, 2.0), + yaw: std::f64::consts::FRAC_PI_2, + pitch: 0.8_f64.asin(), + roll: 0.0, + distance: 10.0, + fov: 1e-6, + ..Default::default() + }; + (dielectric::tests::scene(body), request, options) +} + +#[derive(Clone, Default)] +struct CameraTirEvidence { + started: bool, + first_entry: Option<(Vec3, Vec3, u16)>, + tir: bool, + transmitted_escape: bool, + truncated_top_hit: bool, + finite_scalar: f64, + physical_tail_bound: f64, +} + +/// Independent public-equation oracle, conditional on the REAL camera direction. +/// No dielectric::interface/attenuation/thin_sheet call or renderer state mutation. +fn camera_tir_oracle(ray: Ray) -> (f64, f64) { + let d = ray.direction(); + assert!((d.x - 0.6).abs() < 2e-6 && (d.z + 0.8).abs() < 2e-6 && d.y.abs() < 2e-6); + let enter = ray.origin() + d * ((2.0 - ray.origin().z) / d.z); + assert!((enter.x - 0.9).abs() < 2e-5 && (enter.y - 0.37).abs() < 2e-5); + let cosine = -d.z; + let tx = d.x / 1.5; + let ct = (1.0 - (1.0 - cosine * cosine) / 2.25).sqrt(); + assert!(2.25 * (1.0 - tx * tx) > 1.0, "glass-to-air SIDE incidence is beyond critical"); + // All possible jittered rays in this narrow public-camera cone retain one + // lateral TIR per horizontal crossing, with three escapes before depth8. + let q = 2.0 * tx / ct; + assert!((1.0..2.0).contains(&(enter.x + q))); + let bottom1 = 2.0 - enter.x - q; + assert!((-1.0..0.0).contains(&(bottom1 - q))); + let top2 = q - bottom1; + assert!((1.0..2.0).contains(&(top2 + q))); + let bottom3 = 2.0 - top2 - q; + assert!((-1.0..0.0).contains(&(bottom3 - q))); + // s/p Fresnel *power* from first principles, then the declared scalar + // unpolarized model's three-term geometric return series. Eta² cancels on + // each complete air/glass/air escape. Lossless unit exterior radiance has + // infinite-depth physical answer1; finite omission <=max(Rs,Rp)^3. + let rs = ((cosine - 1.5 * ct) / (cosine + 1.5 * ct)).powi(2); + let rp = ((1.5 * cosine - ct) / (1.5 * cosine + ct)).powi(2); + let f = (rs + rp) * 0.5; + let finite = f + (1.0 - f).powi(2) * (1.0 + f + f * f); + assert!((finite - (1.0 - (1.0 - f) * f.powi(3))).abs() < 16.0 * f64::EPSILON); + (finite, rs.max(rp).powi(3)) +} + +fn complete_camera_tir(scene: ProductScene, request: ImageRequest, options: RaytraceOptions) -> Vec { + assert_eq!(MAX_BOUNDARIES, 8, "this oracle is derived for the actual eight-event model"); + let count = options.progressive.map_or(1, |p| p.samples_per_pixel) as usize; + let intensity = options.environment.unwrap().intensity; + let progressive = options.progressive.is_some(); + let mut evidence = vec![CameraTirEvidence::default(); count]; + let mut final_linear = None; + let mut checkpoints = 0; + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + // Deliberately use the public task poll to completion. The only writes to + // task state are its own API calls, never injected rays/paths/media/cursors. + for _ in 0..2_000_000 { + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() as usize == count + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered as usize, samples as usize), (count, count)); + final_linear = Some(rgb); + } + let poll = if progressive { + task.step_with_previews(1).unwrap() + } else { + match task.step(1).unwrap() { + TaskPoll::Pending(p) => ImagePoll::Pending(p), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + } + }; + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + let ordinal = state.camera_sample.map_or(0, |identity| { + assert_eq!(identity.0, 0); + identity.1 as usize + }); + let seen = &mut evidence[ordinal]; + assert!(state.path.boundaries <= 8); + if !seen.started { + assert_eq!(state.path.boundaries, 0); + let (finite, tail) = camera_tir_oracle(state.path.ray); + seen.finite_scalar = finite; + seen.physical_tail_bound = tail; + seen.started = true; + } + if state.path.boundaries == 1 && state.path.medium == Some(0) && seen.first_entry.is_none() { + let d = state.path.ray.direction(); + assert!((d.x - 0.4).abs() < 2e-6 && (d.z + (0.84_f64).sqrt()).abs() < 2e-6); + assert!((state.path.segment_start.z - 2.0).abs() < 1e-12); + seen.first_entry = Some((d, state.path.throughput, state.paths)); + } + if state.path.boundaries == 2 && state.path.medium == Some(0) { + let (before, throughput, paths) = seen.first_entry.unwrap(); + let after = state.path.ray.direction(); + assert!((state.path.segment_start.x - 1.0).abs() < 1e-12, "real ray hit lateral face"); + assert!(2.25 * (1.0 - before.x * before.x) > 1.0); + assert!((after - Vec3::new(-before.x, before.y, before.z)).len() < 1e-12); + assert!((state.path.throughput - throughput).len() < 1e-12, "TIR retains all current branch power"); + assert_eq!(state.paths, paths + 1, "only reflected path was created at TIR"); + // The primary reflection is still waiting; TIR itself leaves no + // transmitted child in addition to this resumed internal path. + assert_eq!(state.stack_len, 1); + seen.tir = true; + } + if state.path.boundaries == 3 && state.path.medium.is_none() { + assert!(seen.tir); + assert!(state.path.segment_start.z.abs() < 1e-12, "TIR branch really escaped through bottom"); + assert!(state.path.ray.direction().z < 0.0 && state.path.ray.direction().x < 0.0); + seen.transmitted_escape = true; + } + if state.path.boundaries == 8 + && state.path.medium == Some(0) + && let Some(hit) = task.pending.as_ref().and_then(|p| p.hit) + { + let vertices = task.looks[hit.primitive_index].vertices; + if vertices.iter().all(|v| v.z == 2.0) { + seen.truncated_top_hit = true; + } + } + } + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { .. } => { + assert!(task.optical.first().unwrap().pending.is_none()); + checkpoints += 1; + } + ImagePoll::Complete(png) => { + assert!(evidence.iter().all(|s| s.started && s.tir && s.transmitted_escape && s.truncated_top_hit)); + if progressive { + assert!(checkpoints > 0); + let expected = intensity * evidence.iter().map(|s| s.finite_scalar).sum::() / count as f64; + let omitted_bound = intensity * evidence.iter().map(|s| s.physical_tail_bound).sum::() / count as f64; + // Preselected absolute roundoff allowance, independent of + // product output. This is no numerical-certification claim. + let roundoff = 4096.0 * f64::EPSILON; + for actual in final_linear.unwrap() { + assert!((actual - expected).abs() <= roundoff, "independent finite scalar Fresnel series"); + assert!(actual <= intensity + roundoff); + assert!(actual >= intensity - omitted_bound - roundoff, "physical lossless energy with explicit finite-depth omission bound"); + } + if intensity == 1.0 { + assert!(expected < 1.0, "eight-event truncation is NOT perfect conservation"); + assert!(omitted_bound > 1e-5 && omitted_bound < 1e-3); + } + } + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + let expected = if intensity == 0.0 { [0, 0, 0, 255] } else { [188, 188, 188, 255] }; + assert_eq!(image.get_pixel(0, 0).0, expected, "black/white secondary environment controls, covered pixel"); + return png; + } + } + } + panic!("public-camera TIR fixture failed to produce complete image"); +} + +#[test] +fn camera_originated_tir_survives_fixed_render_to_final_png_with_environment_controls() { + let mut outputs = Vec::new(); + for intensity in [0.0, 1.0] { + let (scene, request, options) = camera_tir_source(None, 0, intensity); + outputs.push(complete_camera_tir(scene, request, options)); + } + assert_ne!(outputs[0], outputs[1]); +} + +#[test] +fn camera_originated_tir_progressive_final_obeys_physical_energy_and_explicit_depth_tail() { + for seed in [0, 97] { + for intensity in [0.0, 1.0] { + let (scene, request, options) = camera_tir_source(Some(5), seed, intensity); + let _ = complete_camera_tir(scene, request, options); + } + } +} + +#[test] +fn exposure_full_range_fixed_spatial_and_progressive_keep_linear_film_and_one_display_gain() { + // For +17/+32, reciprocal binary source radiance exposes to [1,1/2,1/4]. + // Reinhard gives [1/2,1/3,1/5]; IEC sRGB8 rounds to [188,156,124]. + // These are preselected mathematical values, not captures from the renderer. + for (ev, unit, expected) in [ + (-32.0, 1.0, [0, 0, 0, 255]), + (-17.0, 1.0, [0, 0, 0, 255]), + (0.0, 1.0, [188, 156, 124, 255]), + (17.0, 1.0 / 131_072.0, [188, 156, 124, 255]), + (32.0, 1.0 / 4_294_967_296.0, [188, 156, 124, 255]), + ] { + let color = [unit, unit * 0.5, unit * 0.25]; + for (progressive, primary_samples) in [(false, 1), (false, 4), (true, 1)] { + let (scene, mut request, mut options) = emission_fixture(false); + // Orthographic footprint x[-16,16],y[-8,8] fits inside both patches + // x[-20,0]/[0,20],y[-10,10] for every real pixel jitter. + request.camera.distance = 20.0; + options.exposure_ev = ev; + options.primary_samples = primary_samples; + options.progressive = progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 919 }); + options.emissions.as_mut().unwrap()[0].color = color; + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut observed_linear = false; + let mut completed = false; + for _ in 0..200_000 { + if let Some(state) = &task.progressive + && state.film.ready() + && state.film.samples() == 3 + { + let (rgb, covered, count) = state.film.pixel(0).unwrap(); + assert_eq!((covered, count), (3, 3)); + assert_eq!(rgb, color, "EV must not enter the accumulated linear film"); + let (dark, covered, count) = state.film.pixel(1).unwrap(); + assert_eq!((covered, count), (3, 3)); + assert_eq!(dark, [0.0; 3]); + observed_linear = true; + } + let poll = if progressive { + task.step_with_previews(1).unwrap() + } else { + match task.step(1).unwrap() { + TaskPoll::Pending(progress) => ImagePoll::Pending(progress), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + } + }; + let (png, final_frame) = match poll { + ImagePoll::Pending(_) => continue, + ImagePoll::Preview { png, .. } => { + assert!(progressive); + (png, false) + } + ImagePoll::Complete(png) => (png, true), + }; + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, expected, "EV={ev}, progressive={progressive}, spatial={primary_samples}"); + assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255]); + if final_frame { + completed = true; + break; + } + } + assert!(completed, "real public producer must finish its bounded fixture"); + assert!(!progressive || observed_linear); + } + } +} + +// Experimental strict core successor. Original public-camera fixtures; no +// injected ray, direction, medium, hit or stack creates the TIR sequences. +fn long_tir_source(width: f64, absorber: bool, progressive: bool, sigma: [f64; 3]) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut body = dielectric::tests::box_body(2.0); + for p in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + p.x = if p.x < 0.0 { 0.0 } else { width }; + } + let mut scene = dielectric::tests::scene(body); + if absorber { + assert_eq!(width, 0.05); + let xb = 0.875 - 4.0 / 21.0_f64.sqrt(); + let xr = xb - 0.001 * 0.4 / 0.84_f64.sqrt(); + assert!(xr > 0.0001 && xr + 0.0001 < width); + scene.meshes.push(crate::ProductMesh { + transmission: None, + name: "Original return absorber".into(), + mesh: std::sync::Arc::new(solidcraft_geom::Mesh { + positions: vec![ + Vec3::new(xr - 0.0001, -0.5, 0.001), + Vec3::new(xr + 0.0001, -0.5, 0.001), + Vec3::new(xr + 0.0001, 1.5, 0.001), + Vec3::new(xr - 0.0001, 1.5, 0.001), + ], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }); + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |a, m| a.union(&m.mesh.bounds())); + let mut medium = dielectric::tests::input(job::DielectricBoundary::ClosedBox); + medium.absorption_per_mm = sigma; + let options = RaytraceOptions { + dielectrics: vec![medium], + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + progressive: progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 71 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera = crate::Camera { + target: Vec3::new(width * 0.5, 0.37, 2.0), + yaw: std::f64::consts::FRAC_PI_2, + pitch: 0.8_f64.asin(), + roll: 0.0, + distance: 10.0, + fov: 1e-9, + ..Default::default() + }; + (scene, request, options) +} + +fn long_tir_expected(ray: Ray, sigma: [f64; 3], strict: bool) -> [f64; 3] { + let c = -ray.direction().z; + assert!((c - 0.8).abs() < 2e-9); + let ct = (1.0 - (1.0 - c * c) / 2.25).sqrt(); + let rs = ((c - 1.5 * ct) / (c + 1.5 * ct)).powi(2); + let rp = ((1.5 * c - ct) / (1.5 * c + ct)).powi(2); + let f = (rs + rp) * 0.5; + if strict { sigma.map(|s| f + (1.0 - f).powi(2) * (-s * 2.0 / ct).exp()) } else { [f; 3] } +} + +fn complete_long_tir(mut task: ImageTask, sigma: [f64; 3], strict: bool) -> Vec { + let count = task.visibility_owner.options().progressive.map_or(1, |p| p.samples_per_pixel) as usize; + let progressive = task.visibility_owner.options().progressive.is_some(); + let mut oracle = vec![None; count]; + let mut previous_tir = 0; + let mut previous_direction = vec![None; count]; + let mut actual_tir_rays = 0; + let mut escaped = vec![false; count]; + let mut absorbed = vec![false; count]; + let mut maximum = 0; + let mut linear = None; + for _ in 0..2_000_000 { + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() as usize == count + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered as usize, samples as usize), (count, count)); + linear = Some(rgb); + } + let poll = task.step_with_previews(1).unwrap(); + if let Some(optical) = task.optical.first() + && let Some(state) = &optical.pending + { + let ordinal = state.camera_sample.map_or(0, |identity| identity.1 as usize); + maximum = maximum.max(state.path.boundaries); + if oracle[ordinal].is_none() { + assert_eq!(state.path.boundaries, 0); + oracle[ordinal] = Some(long_tir_expected(state.path.ray, sigma, strict)); + } + if state.path.boundaries == 1 && state.path.medium == Some(0) && previous_direction[ordinal].is_none() { + previous_direction[ordinal] = Some(state.path.ray.direction()); + } + if optical.tir_continuations > previous_tir { + assert!(strict); + assert_eq!(optical.tir_continuations, previous_tir + 1); + assert_eq!(state.path.boundaries, 1, "TIR is not another split"); + assert_eq!(state.paths, 3, "initial path and two first-interface children only"); + assert_eq!(state.stack_len, 1, "waiting primary reflection is preserved"); + let before = previous_direction[ordinal].unwrap(); + let after = state.path.ray.direction(); + assert!((after - Vec3::new(-before.x, before.y, before.z)).len() < 1e-12); + assert!(task.pending.as_ref().unwrap().hit.is_none(), "real new TraceCursor has no borrowed old hit"); + previous_direction[ordinal] = Some(after); + previous_tir = optical.tir_continuations; + actual_tir_rays += 1; + } + if strict && state.path.boundaries == 2 && state.path.medium.is_none() && state.path.segment_start.z.abs() < 1e-12 { + assert_eq!(actual_tir_rays, 17 * (ordinal + 1)); + escaped[ordinal] = true; + } + if strict + && let Some(hit) = task.pending.as_ref().and_then(|p| p.hit) + && task.looks[hit.primitive_index].body_index == 1 + { + assert!(escaped[ordinal]); + absorbed[ordinal] = true; + } + } + if let ImagePoll::Complete(png) = poll { + let mut expected = [0.0; 3]; + for value in oracle { + for (sum, v) in expected.iter_mut().zip(value.unwrap()) { + *sum += v / count as f64; + } + } + if progressive { + for (actual, expected) in linear.unwrap().into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-10); + } + } + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, straight_expected_pixel(expected)); + if strict { + assert!(escaped.into_iter().all(|v| v) && absorbed.into_iter().all(|v| v)); + assert_eq!(actual_tir_rays, 17 * count); + assert_eq!(maximum, 2); + } else { + assert!(escaped.into_iter().all(|v| !v)); + assert_eq!(maximum, 8, "pre-fix witness: entry and seven TIRs exhaust legacy events"); + assert_eq!(actual_tir_rays, 0, "legacy policy never enters the new core branch"); + } + return png; + } + } + panic!("long TIR original fixture did not complete"); +} + +#[test] +fn legacy_long_tir_counterexample_loses_the_first_real_transmitted_exit() { + // This explicitly witnesses the retained C15 limitation, not a new physical + // success oracle. Its derived F-only result is contrasted with the strict + // terminating fixture below. No old L8 assertion is edited. + let (scene, request, options) = long_tir_source(0.05, true, true, [0.0; 3]); + let task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + assert!(!task.optical.first().unwrap().deterministic_tir); + let _ = complete_long_tir(task, [0.0; 3], false); +} + +#[test] +fn strict_core_long_tir_fixed_and_progressive_reach_real_exit_and_real_absorber() { + for progressive in [false, true] { + let (scene, request, options) = long_tir_source(0.05, true, progressive, [0.0; 3]); + let task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + let _ = complete_long_tir(task, [0.0; 3], true); + } +} + +#[test] +fn strict_core_long_tir_keeps_beer_on_all_real_reflected_segments() { + for progressive in [false, true] { + let sigma = [0.1, 0.2, 0.0]; + let (scene, request, options) = long_tir_source(0.05, true, progressive, sigma); + let task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + let _ = complete_long_tir(task, sigma, true); + } +} + +#[test] +fn strict_core_tir_more_than511_real_continuations_still_use_bvh_work_and_cancellation() { + for cancel in [false, true] { + let (scene, request, options) = long_tir_source(0.0005, false, true, [0.0; 3]); + let mut task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + let mut observed = false; + for _ in 0..2_000_000 { + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.work.used() - before <= 1); + if task.optical.first().unwrap().tir_continuations == 512 { + let state = task.optical.first().unwrap().pending.as_ref().unwrap(); + assert_eq!((state.path.boundaries, state.paths, state.stack_len), (1, 3, 1)); + assert!(task.work.used() > 1024, "all previous traversals AND interfaces were real work"); + let start = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert_eq!(task.work.used(), start + 1, "newest real cursor also starts traversal before the stop"); + assert_eq!(task.optical.first().unwrap().tir_continuations, 512); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(frontier.completed_passes, 0); + assert!(!task.done); + observed = true; + break; + } + } + assert!(observed, "511 branch-state allowance must not truncate a deterministic ray sequence"); + } +} + +#[test] +fn strict_core_positive_non_tir_depth_limit_is_explicit_instead_of_black_completion() { + let (scene, request, options) = long_tir_source(0.05, false, true, [0.0; 3]); + let mut task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + for _ in 0..2_000_000 { + match task.step_with_previews(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(error.message.contains("non-TIR branch-depth budget exhausted")); + let optical = task.optical.first().unwrap(); + assert!(optical.tir_continuations >= 17); + assert!(optical.pending.as_ref().unwrap().paths <= 511); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + return; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("positive unresolved split cannot be published as a successful black tail"), + } + } + panic!("strict unresolved split was not reported"); +} + +// ORIGINAL UNAPPLIED PROPOSAL for the existing raytrace/image_tests.rs module. +// SOURCE ONLY: UNFORMATTED / UNCOMPILED / UNRUN. No new production policy API. +// This witnesses LEGACY bias; it is NOT a strict-quality success expectation. + +fn rational_depth_source(progressive: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + let scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + let mut medium = dielectric::tests::input(job::DielectricBoundary::ClosedBox); + medium.ior = 3.0; + medium.absorption_per_mm = [0.0; 3]; + let options = RaytraceOptions { + dielectrics: vec![medium], + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + progressive: progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 71 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.target = Vec3::new(0.23, 0.37, 1.0); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + (scene, request, options) +} + +fn rational_depth_real_cut(task: &ImageTask) -> bool { + let Some(optical) = task.optical.first() else { return false }; + let Some(state) = &optical.pending else { return false }; + if state.path.boundaries == 0 { + assert!((state.path.ray.direction() + Vec3::Z).len() < 1e-14); + } + if state.path.boundaries != 8 || state.path.medium != Some(0) || task.pending.as_ref().and_then(|p| p.hit).is_none() { + return false; + } + // All observed states came from the actual public camera/consumer. + // Entry plus seven true Fresnel splits, with the primary reflection waiting. + assert_eq!(state.paths, 17); + assert_eq!(state.stack_len, 1); + let expected = 1.0 / 196_608.0; + for value in [state.path.throughput.x, state.path.throughput.y, state.path.throughput.z] { + assert!(value > 0.0 && (value - expected).abs() < 1e-14); + } + true +} + +#[test] +fn legacy_public_normal_ior_three_has_a_positive_rational_depth_tail_hidden_by_png() { + const LEGACY_LINEAR: f64 = 65_533.0 / 65_536.0; + const OMITTED: f64 = 3.0 / 65_536.0; + assert_eq!(1.0 - LEGACY_LINEAR, OMITTED); + assert!(OMITTED > 1e-10); + for progressive in [false, true] { + let (scene, request, options) = rational_depth_source(progressive); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut cut_observed = false; + let mut linear = None; + let mut completed = false; + for _ in 0..200_000 { + cut_observed |= rational_depth_real_cut(&task); + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() == 3 + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (3, 3)); + linear = Some(rgb); + } + let before_work = task.work.used(); + let poll = if progressive { + task.step_with_previews(1).unwrap() + } else { + match task.step(1).unwrap() { + TaskPoll::Pending(p) => ImagePoll::Pending(p), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + } + }; + assert!(task.work.used() >= before_work, "no ordinary-work reset across paths/passes"); + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { .. } => { + assert!(progressive); + assert!(task.optical.first().unwrap().pending.is_none()); + } + ImagePoll::Complete(png) => { + assert!(cut_observed); + if progressive { + for value in linear.unwrap() { + assert!((value - LEGACY_LINEAR).abs() < 1e-10); + assert!((value - 1.0).abs() > OMITTED * 0.5); + } + } + // Both physical1 and legacy65533/65536 round to188 under + // the documented Reinhard/IEC transfer: NOT a quality proof. + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [188, 188, 188, 255]); + completed = true; + break; + } + } + } + assert!(completed, "bounded legacy witness did not complete"); + } +} + +#[test] +fn public_normal_ior_three_real_positive_tail_still_obeys_cancel_and_work_limit() { + for cancel in [false, true] { + let (scene, request, options) = rational_depth_source(true); + let token = CancelToken::default(); + let mut task = ImageTask::new(scene, request, token.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..200_000 { + if rational_depth_real_cut(&task) { + reached = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(reached, "real camera traversal must reach the unresolved positive tail"); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert_eq!(frontier.completed_passes, 0); + let used = task.work.used(); + assert!(used > 0); + if cancel { + token.cancel(); // Actual caller-held public cancellation token. + } else { + // Existing unit-test control, not a new public budget API and not + // an injected ray, medium, hit or optical path. + task.work.limit = used; + } + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used, "failed/cancelled debit cannot advance or refund work"); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + } +} + +// ORIGINAL UNAPPLIED acceptance for Worker2 policy index ee17a4bb. +// Intended for the EXISTING raytrace/image_tests.rs, after the original +// rational_depth_source / rational_depth_real_cut helpers from index1685daca. +// UNFORMATTED / UNCOMPILED / UNRUN. No cfg(test)-only policy selector is used. + +fn rational_public_strict_source(progressive: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + let (scene, mut request, mut options) = rational_depth_source(progressive); + options.dielectric_transport = job::CpuDielectricTransport::StrictTir; + request.raytrace = Some(options.clone()); + (scene, request, options) +} + +#[test] +fn public_strict_ior_three_positive_non_tir_tail_is_a_real_error_before_final_or_sample() { + for progressive in [false, true] { + let (scene, request, options) = rational_public_strict_source(progressive); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut failed = false; + for _ in 0..200_000 { + let before = task.work.used(); + let poll = if progressive { + task.step_with_previews(1) + } else { + task.step(1).map(|poll| match poll { + TaskPoll::Pending(p) => ImagePoll::Pending(p), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + }) + }; + match poll { + Ok(ImagePoll::Pending(_)) => assert!(task.work.used() >= before), + Ok(_) => panic!("strict positive rational tail cannot become preview/final quality"), + Err(error) => { + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(error.message.contains("strict optical non-TIR branch-depth budget exhausted")); + assert!(rational_depth_real_cut(&task), "actual depth8/paths17/positive internal state must exist"); + assert_eq!(task.work.used(), before + 1, "the real failing interface consumes its original tick"); + if progressive { + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap().completed_passes, 0); + } + assert!(!task.done); + failed = true; + break; + } + } + } + assert!(failed, "the actual selected strict policy must report its optical limit"); + } +} + +#[test] +fn public_strict_rational_tail_preserves_real_cancel_and_ordinary_work_accounting() { + for cancel in [false, true] { + let (scene, request, options) = rational_public_strict_source(true); + let token = CancelToken::default(); + let mut task = ImageTask::new(scene, request, token.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..200_000 { + if rational_depth_real_cut(&task) { + reached = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(reached); + let before = task.work.used(); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert_eq!(frontier.completed_passes, 0); + if cancel { + token.cancel(); + } else { + // Explicit established unit-test stop control, not a public option + // or a manufactured ray/hit/medium/branch. + task.work.limit = before; + } + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_public_final_strict_rational_tail_fails_without_a_frame_or_policy_fallback() { + use std::time::Duration; + let host = job::CpuHost::for_platform().unwrap(); + assert_eq!(host.kind(), job::HostKind::NativeWorker); + host.validate_integrator(job::Integrator::Raytrace).unwrap(); + // Exactly ONE required native branch marker; an unsupported configuration + // must fail rather than return early or switch to cooperative Raster. + eprintln!("STRICT_RATIONAL_BRANCH cpu_supported=true"); + for (index, progressive) in [false, true].into_iter().enumerate() { + let (scene, request, options) = rational_public_strict_source(progressive); + host.admit(&scene, &request, job::JobOptions::default()).unwrap(); + let id = job::JobId { session: 17361, serial: index as u64 + 1, generation: 1 }; + let handle = host.submit(id, 1, scene, request).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, job::Phase::Failed); + assert_eq!(status.request.raytrace.as_ref(), Some(&options)); + let error = status.error.as_ref().unwrap(); + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(error.message.contains("strict optical non-TIR branch-depth budget exhausted")); + assert!(handle.frame().unwrap().is_none()); + assert!(handle.preview().unwrap().is_none()); + } + // No immediate zero-pool claim: native terminal publication alone does not + // prove concurrent task/lease destruction has finished. +} + +mod original_directional_acceptance { + // Adopted W2 acceptance helpers; SOURCE ONLY / UNCOMPILED / UNRUN. + // Intended as a cfg(test) child module of raytrace::image, NOT as a crate or framework. + // Readonly OWNER getters and the real runtime flag are adapted explicitly below. + // Original donor8527 and oracle4ab12 stay sealed; registered cases follow these helpers. + use super::*; + use solidcraft_geom::{Aabb3, Mesh}; + use std::sync::Arc; + + const ORIGINAL_LINEAR: [[f64; 3]; 3] = [[0.8, 0.5, 0.25], [0.4, 0.125, 0.25], [0.2, 0.03125, 0.25]]; + const ORIGINAL_ABSOLUTE_TOLERANCE: f64 = 1e-12; + + fn original_receiver() -> crate::ProductMesh { + crate::ProductMesh { + transmission: None, + name: "Original directional receiver".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-4.0, -4.0, 0.0), Vec3::new(4.0, -4.0, 0.0), Vec3::new(4.0, 4.0, 0.0), Vec3::new(-4.0, 4.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + // IOR1 removes the normal-incidence interface term. Rough Lambert albedo + // and all original expected values were fixed before any consumer exists. + surface: Some(OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()), + faces: Vec::new(), + } + } + + fn original_box(ordinal: usize) -> crate::ProductMesh { + assert!(ordinal < 2); + let lo = if ordinal == 0 { 1.0 } else { 3.0 }; + let hi = lo + 1.0; + crate::ProductMesh { + transmission: None, + name: format!("Original directional glass {ordinal}"), + mesh: Arc::new(Mesh { + positions: (0..8) + .map(|i| Vec3::new(if i & 1 == 0 { -2.0 } else { 2.0 }, if i & 2 == 0 { -2.0 } else { 2.0 }, if i & 4 == 0 { lo } else { hi })) + .collect(), + // Outward winding of six closed rectangular faces, two triangles each. + triangles: vec![ + [0, 2, 3], + [0, 3, 1], + [4, 5, 7], + [4, 7, 6], + [0, 4, 6], + [0, 6, 2], + [1, 3, 7], + [1, 7, 5], + [0, 1, 5], + [0, 5, 4], + [2, 6, 7], + [2, 7, 3], + ], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + } + } + + /// Creates real scene/request/options with original admission. No flag or shadow mock. + /// Identity effect is a SEPARATE one-box case, not a replacement for the plain case. + pub(super) fn original_directional_fixture(boxes: usize, identity_effect: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + assert!(boxes <= 2); + assert!(!identity_effect || boxes == 1); + let mut meshes = vec![original_receiver()]; + let mut dielectrics = Vec::with_capacity(boxes); + for ordinal in 0..boxes { + let body = original_box(ordinal); + dielectrics.push(job::DielectricOptions { + body_index: meshes.len(), + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ClosedBox, + ior: 1.0, + absorption_per_mm: [std::f64::consts::LN_2, 2.0 * std::f64::consts::LN_2, 0.0], + thickness_mm: 0.0, + }); + meshes.push(body); + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |a, b| a.union(&b.mesh.bounds())); + let options = RaytraceOptions { + budget: job::CpuBudget::Compact, + primary_samples: 1, + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: 1, seed: 81 }), + lights: Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: std::f64::consts::PI }]), + shadows: true, + exposure_ev: 0.0, + dielectrics, + surface_effects: identity_effect.then(|| { + vec![crate::surface_patterns::SurfaceEffect { + body: "Original directional receiver".into(), + frame: Default::default(), + repeat_mm: [10.0; 3], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }] + }), + ..Default::default() + }; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: job::Integrator::Raytrace, + raytrace: Some(options.clone()), + camera: crate::Camera { + target: Vec3::new(0.25, 0.37, 0.0), + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + roll: 0.0, + distance: 0.5, + // Perspective avoids the orthographic 3*distance origin translation. + // Tiny positive FOV keeps every real jittered ray essentially normal. + fov: 1e-9, + ..Default::default() + }, + width: 1, + height: 1, + background: [0; 3], + transparent_background: false, + }; + (ProductScene { meshes, bounds }, request, options) + } + + /// Real constructor/certifier and generated ray, with no skipped admission. + /// Selects the real mode for N1/N2; N0 deliberately retains the legacy/default route. + pub(super) fn original_directional_task(boxes: usize, identity_effect: bool) -> ImageTask { + let (scene, mut request, mut options) = original_directional_fixture(boxes, identity_effect); + options.directional_shadow_transmission = boxes != 0; + request.raytrace = Some(options.clone()); + options.validate().unwrap(); + for input in &options.dielectrics { + assert_ne!(input.body_index, 0, "receiver must remain optically unselected"); + assert_eq!(input.body_name, scene.meshes[input.body_index].name); + assert!(matches!(dielectric::certify(&scene, input).unwrap(), Certificate::ClosedBox(_))); + } + if identity_effect { + assert!(options.surface_effects.as_ref().unwrap()[0].prepare().unwrap().is_identity()); + } + admit(&scene, &request, &options).unwrap(); + let task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + assert_eq!(task.optical.len(), usize::from(boxes != 0)); + if identity_effect { + assert!(task.visibility_owner.options().surface_effects.is_some()); + assert!(task.effects.is_empty(), "identity is validated but not retained"); + } + let [dx, dy] = progressive::variates(81, 0, 0, 0); + let ray = primary_ray(&task.request, dx, dy, task.clip).unwrap(); + assert_original_primary(ray); + // Check the actual clipped generator at every pixel-corner bound as well. + for (x, y) in [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)] { + assert_original_primary(primary_ray(&task.request, x, y, task.clip).unwrap()); + } + task + } + + fn assert_original_primary(ray: Ray) { + assert!(ray.origin().z > 0.0 && ray.origin().z < 1.0, "REAL clipped primary origin must be between receiver and first box"); + assert!(ray.direction().z < 0.0); + assert!((ray.direction() + Vec3::Z).len() < 1e-8); + let t = -ray.origin().z / ray.direction().z; + assert!(t > ray.interval()[0] && t < ray.interval()[1]); + let on_receiver = ray.at(t).unwrap(); + assert!(on_receiver.x.abs() < 1.0 && on_receiver.y.abs() < 1.0); + } + + /// Observe a REAL ImageTask supplied by the future, separately reviewed consumer. + /// No fake mode, private state injection, visibility override or expected-from-output. + /// The registered tests select the real mode and use progressive polling below. + /// The legacy one-box test separately retains the original opaque-shadow contract. + pub(super) fn assert_original_directional_linear(mut task: ImageTask, boxes: usize, identity_effect: bool, retained_effect: bool) -> [f64; 3] { + assert!(boxes <= 2 && (!identity_effect || boxes == 1)); + assert!(!retained_effect || (boxes == 1 && !identity_effect)); + if identity_effect { + assert!(task.visibility_owner.options().surface_effects.as_ref().unwrap()[0].prepare().unwrap().is_identity()); + assert!(task.effects.is_empty(), "identity is validated and deliberately pruned"); + } + if retained_effect { + assert!(!task.visibility_owner.options().surface_effects.as_ref().unwrap()[0].prepare().unwrap().is_identity()); + assert_eq!(task.effects.len(), 1, "nonidentity must reach the actual scanner"); + } + assert_eq!(task.visibility_owner.options().dielectrics.len(), boxes); + assert_eq!(task.visibility_owner.options().budget, job::CpuBudget::Compact); + assert_eq!(task.visibility_owner.options().primary_samples, 1); + assert_eq!(task.visibility_owner.options().progressive.unwrap().seed, 81); + assert!(task.visibility_owner.options().environment.is_none()); + assert!(task.visibility_owner.options().emissions.is_none()); + assert!(task.visibility_owner.options().reflections.is_none()); + assert!(task.visibility_owner.options().punctual_lights.is_none()); + assert!(task.visibility_owner.options().area_lights.is_none()); + let lights = task.visibility_owner.options().lights.as_ref().unwrap(); + assert_eq!(lights.len(), 1); + assert_eq!(lights[0].direction, [0.0, 0.0, 1.0]); + assert_eq!(lights[0].color, [1.0; 3]); + assert_eq!(lights[0].intensity, std::f64::consts::PI); + assert_eq!(task.visibility_owner.source().meshes.len(), boxes + 1); + + assert_eq!(task.visibility_owner.options().progressive.unwrap().samples_per_pixel, 1); + // Exact observer contract: Legacy constructor, one SPP, no optional feedback. + // Legacy with more SPP CAN produce checkpoints; do not generalize this guard. + assert!(task.progressive.as_ref().unwrap().partial_plan.is_none()); + assert!(task.progressive.as_ref().unwrap().partial.is_none()); + assert!(task.work.protected.is_none()); + assert_eq!(task.visibility_owner.options().exposure_ev, 0.0); + assert!(task.visibility_owner.options().shadows); + assert_eq!((task.request.width, task.request.height), (1, 1)); + let mut saw_receiver = false; + let mut saw_unselected_optical = false; + let mut saw_retained_effect_scan = false; + let mut previous_work = task.work.used(); + for _ in 0..100_000 { + assert!(task.work.used() >= previous_work, "one cumulative ledger, no resets"); + previous_work = task.work.used(); + if let Some(pending) = task.pending.as_ref() { + assert_original_primary(pending.ray); + if let Some(hit) = pending.hit { + let scene = PreparedScene { bvh: task.bvh.as_ref().unwrap(), primitives: &task.looks, source: task.visibility_owner.source() }; + let shared = scene.resolve_hit(pending.ray, hit).unwrap(); + assert_eq!(shared.body_index, 0); + assert_eq!(shared.body_name, "Original directional receiver"); + assert!(shared.front_face); + assert!((shared.geometric_normal - Vec3::Z).len() < 1e-12); + // Exercise the actual geometric spawn helper, not a hand-offset ray. + let shadow = shared.spawn(Vec3::Z).unwrap(); + assert_eq!(shadow.direction(), Vec3::Z); + assert!(shadow.origin().z > 0.0 && shadow.origin().z < 1.0); + let receiver = &task.visibility_owner.source().meshes[0].mesh; + for indices in &receiver.triangles { + let vertices = indices.map(|i| receiver.positions[i as usize]); + assert!(Triangle::new(vertices).unwrap().intersect(&shadow).is_none(), "self-hit must not hide the Beer shadow oracle"); + } + saw_receiver = true; + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + if state.ready { + assert!(state.selected.is_none(), "nonempty optical selectors must miss receiver"); + assert_eq!(state.selector, task.visibility_owner.options().dielectrics.len()); + assert_eq!(state.path.boundaries, 0, "camera must not transmit through glass"); + assert!(state.path.medium.is_none()); + saw_unselected_optical = true; + } + } + if retained_effect && pending.surface_ready && pending.surface_index.is_some() { + assert_eq!(pending.surface_cursor, task.effects.len()); + let affected = resolved_surface_hit(&scene, pending, &task.effects).unwrap(); + assert_eq!(affected.surface.base_color(), Vec3::new(0.8, 0.5, 0.25)); + assert_eq!(affected.surface.dielectric_ior(), 1.0); + assert_eq!(affected.surface.metallic(), 0.0); + assert!(affected.surface.clear_coat().is_none()); + assert!(affected.surface.roughness() < 1.0); + assert_eq!(affected.shading_normal, Vec3::Z); + saw_retained_effect_scan = true; + } + } + } + if let Some(progressive) = &task.progressive { + if progressive.film.ready() && progressive.film.samples() == 1 { + assert!(task.encoder.is_none() && task.pixels.is_empty()); + assert_eq!(progressive.resolve_pixel, 0); + assert!(task.pending.is_none()); + assert!(task.optical.first().is_none_or(|o| o.pending.is_none())); + let (linear, covered, samples) = progressive.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (1, 1)); + assert!(saw_receiver); + assert!(boxes == 0 || saw_unselected_optical); + assert!(!retained_effect || saw_retained_effect_scan); + for (actual, expected) in linear.into_iter().zip(ORIGINAL_LINEAR[boxes]) { + assert!(actual.is_finite()); + assert!( + (actual - expected).abs() <= ORIGINAL_ABSOLUTE_TOLERANCE, + "linear film {actual} differs from original oracle {expected}" + ); + } + // Return before any PNG resolve/encoding. No display inversion. + return linear; + } + } + match task.step_with_previews(1).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { samples_per_pixel, .. } => { + panic!("unexpected checkpoint at {samples_per_pixel} SPP before observing original linear film"); + } + ImagePoll::Complete(_) => panic!("completed before observing original linear film"), + } + } + panic!("original tiny fixture exceeded its fixed observation bound"); + } + + /// Separate negative validation witness for the identity case. No shortcut injection. + pub(super) fn assert_original_identity_target_is_still_validated() { + let (scene, mut request, mut options) = original_directional_fixture(1, true); + options.surface_effects.as_mut().unwrap()[0].body = "Missing identity target".into(); + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).is_err()); + assert!(ImageTask::new(scene, request, CancelToken::default(), options).is_err()); + } + + /// Additional REAL retained-effect variant for the second shadow-start route. + /// It preserves the already fixed one-box oracle, because IOR1/metallic0 is exact + /// Lambert for EVERY admitted roughness in the current surface contract. + pub(super) fn original_directional_retained_effect_fixture() -> (ProductScene, ImageRequest, RaytraceOptions) { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + let effect = crate::surface_patterns::SurfaceEffect { + body: "Original directional receiver".into(), + frame: crate::surface_patterns::MappingFrame { + // At the receiver hit(.25,.37,0), all three phases are -PI. + // Nearby tiny-FOV jitter keeps the cosine field negative; roughness + // changes below1. No tint API, normal change or geometry change. + origin_mm: [0.75, 0.87, 0.5], + ..Default::default() + }, + repeat_mm: [1.0; 3], + roughness_amplitude: 0.1, + bump_amplitude_mm: 0.0, + }; + let prepared = effect.prepare().unwrap(); + assert!(!prepared.is_identity()); + let material = scene.meshes[0].surface.unwrap(); + let applied = prepared.apply(material, Vec3::Z, Vec3::Z, Vec3::new(0.25, 0.37, 0.0)).unwrap(); + assert!(applied.surface.roughness() < material.roughness()); + assert_eq!(applied.surface.base_color(), material.base_color()); + assert_eq!(applied.surface.metallic(), 0.0); + assert_eq!(applied.surface.dielectric_ior(), 1.0); + assert_eq!(applied.shading_normal, Vec3::Z); + options.surface_effects = Some(vec![effect]); + request.raytrace = Some(options.clone()); + admit(&scene, &request, &options).unwrap(); + (scene, request, options) + } + + /// Retained-effect construction selects the real directional runtime mode. + pub(super) fn original_directional_retained_effect_task() -> ImageTask { + let (scene, mut request, mut options) = original_directional_retained_effect_fixture(); + options.directional_shadow_transmission = true; + request.raytrace = Some(options.clone()); + for input in &options.dielectrics { + assert!(matches!(dielectric::certify(&scene, input).unwrap(), Certificate::ClosedBox(_))); + } + let task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + assert_eq!(task.effects.len(), 1); + assert_eq!(task.effects[0].0, 0); + assert_eq!(task.optical.len(), 1); + let [dx, dy] = progressive::variates(81, 0, 0, 0); + assert_original_primary(primary_ray(&task.request, dx, dy, task.clip).unwrap()); + task + } + + #[test] + fn directional_real_film_matches_original_zero_one_two_box_oracles() { + for boxes in 0..=2 { + assert_original_directional_linear(original_directional_task(boxes, false), boxes, false, false); + } + } + + #[test] + fn directional_identity_is_pruned_and_retained_roughness_exercises_scanner() { + assert_original_directional_linear(original_directional_task(1, true), 1, true, false); + assert_original_identity_target_is_still_validated(); + assert_original_directional_linear(original_directional_retained_effect_task(), 1, false, true); + } + + #[test] + fn directional_default_preserves_opaque_glass_shadow_in_linear_film() { + let (scene, request, options) = original_directional_fixture(1, false); + assert!(!options.directional_shadow_transmission); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let Some(progressive) = &task.progressive { + if progressive.film.ready() && progressive.film.samples() == 1 { + assert_eq!(progressive.film.pixel(0).unwrap(), ([0.0; 3], 1, 1)); + return; + } + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + panic!("legacy opaque-shadow film was not observed"); + } + + #[test] + fn directional_scan_uses_one_tick_per_active_poll_and_keeps_fixed_storage() { + let mut task = original_directional_task(2, false); + let slot = task.pending.0.as_ptr(); + let admission = admit(task.visibility_owner.source(), &task.request, task.visibility_owner.options()).unwrap(); + assert_eq!(admission.estimated_total_bytes, task.admission.estimated_total_bytes); + assert!(admission.preparation_bytes >= PendingPixelSlot::required_bytes()); + assert!(std::mem::size_of::() <= 4096); + let mut active_polls = 0; + for _ in 0..100_000 { + if task.progressive.as_ref().is_some_and(|p| p.film.ready() && p.film.samples() == 1) { + assert!(active_polls > 0); + assert!(task.pending.is_none()); + return; + } + let active = task.pending.as_ref().is_some_and(|p| p.directional_active); + let used = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if active { + active_polls += 1; + assert_eq!(task.work.used(), used + 1); + } + assert_eq!(task.pending.0.capacity(), 1); + assert_eq!(task.pending.0.as_ptr(), slot); + } + panic!("bounded directional scan never reached committed film"); + } + + #[test] + fn directional_cancellation_or_work_limit_cannot_commit_a_pending_connection() { + for cancel in [false, true] { + let mut task = original_directional_task(1, false); + let mut reached = false; + for _ in 0..100_000 { + if task.pending.as_ref().is_some_and(|p| p.directional_active) { + reached = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(reached); + let used = task.work.used(); + assert!(task.finish_sample(Vec3::ZERO).is_err()); + assert_eq!(task.work.used(), used); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.pixels.is_empty() && task.encoder.is_none() && !task.done); + } + } + + #[test] + fn directional_context_refusals_and_completed_release_preserve_contracts() { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + request.raytrace = Some(options.clone()); + assert!(admit_with_nested(&scene, &request, &options, true).is_err()); + let mut mismatch = request.clone(); + mismatch.raytrace.as_mut().unwrap().directional_shadow_transmission = false; + assert!(admit(&scene, &mismatch, &options).is_err()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let weak = Arc::downgrade(&task.visibility_owner.source().meshes[0].mesh); + let budget = task.visibility_owner.options().budget; + for _ in 0..100_000 { + if let ImagePoll::Complete(png) = task.step_with_previews(16384).unwrap() { + assert!(::image::load_from_memory(&png).is_ok()); + assert!(weak.upgrade().is_none()); + assert!(task.visibility_owner.source().meshes.is_empty()); + assert!(task.visibility_owner.options().dielectrics.is_empty()); + assert_eq!(task.visibility_owner.options().budget, budget); + assert!(task.visibility_owner.options().directional_shadow_transmission); + assert!(task.request.raytrace.is_none() && task.optical.is_empty()); + assert!(task.step_with_previews(1).is_err()); + return; + } + } + panic!("directional completion did not release capture"); + } + + #[test] + fn directional_direct_constructor_refuses_separate_hdr_input() { + use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 128, 128, 129]); + } + let hdr = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap(); + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + request.raytrace = Some(options.clone()); + let error = ImageTask::new_with_environment(scene, request, CancelToken::default(), options, Some(hdr)).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(error.message, "directional shadow transmission does not support HDR environments"); + } + + // Added during static coverage review after the initial twelve tests/body. + // Expectations are authored from geometry/Lambert/Beer, never candidate output. + #[test] + fn directional_second_light_has_its_own_oblique_beer_connection() { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + options.lights.as_mut().unwrap().push(job::DirectionalLightOptions { + direction: [0.6, 0.0, 0.8], + color: [1.0; 3], + intensity: 1.25 * std::f64::consts::PI, + }); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + // Both box faces are hit in their interiors: x=1 at z1, x=1.75 at z2. + // Lz=4/5 gives chord5/4; intensity5*PI/4 cancels the Lambert cosine. + let oblique = [2.0_f64.powf(-1.25), 4.0_f64.powf(-1.25), 1.0]; + let expected = [0.4 + 0.8 * oblique[0], 0.125 + 0.5 * oblique[1], 0.5]; + let mut saw_both = false; + for _ in 0..100_000 { + if let Some(pending) = task.pending.as_ref() { + if pending.directional_complete == 3 { + assert!(!pending.directional_active); + let first = pending.directional_transmittance[0]; + let second = pending.directional_transmittance[1]; + assert!((first - Vec3::new(0.5, 0.25, 1.0)).len() < 1e-12); + assert!((second - Vec3::new(oblique[0], oblique[1], oblique[2])).len() < 1e-12); + saw_both = true; + } + } + if let Some(progressive) = &task.progressive { + if progressive.film.ready() && progressive.film.samples() == 1 { + assert!(saw_both); + let (linear, covered, samples) = progressive.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (1, 1)); + for (actual, expected) in linear.into_iter().zip(expected) { + assert!((actual - expected).abs() <= 1e-12); + } + return; + } + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + panic!("independent directional connections never reached film"); + } + + #[test] + fn directional_fixed_spatial_samples_encode_original_rational_radiance_once() { + for samples in [1, 4, 16] { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + options.progressive = None; + options.primary_samples = samples; + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut completed = false; + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(1).unwrap() { + // Original linear(.4,.125,.25) -> Reinhard(2/7,1/9,1/5). + // encode8 is the unchanged encoding function, not a transport oracle. + let pixel = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(pixel.get_pixel(0, 0).0, [encode8(2.0 / 7.0), encode8(1.0 / 9.0), encode8(1.0 / 5.0), 255]); + completed = true; + break; + } + } + assert!(completed); + } + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/mod.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/mod.rs new file mode 100644 index 000000000..115125185 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/mod.rs @@ -0,0 +1,456 @@ +//! Optional original CPU visibility core and opaque direct-image integration. +//! +//! Original Rust implementation from elementary slab, barycentric and binary-tree +//! mathematics. Geometry is already world-space, in millimetres. No B-rep kernel +//! or third-party ray-tracer implementation is used. See `docs/render-raytrace-core.md`. + +use crate::job::CancelToken; +use solidcraft_geom::Vec3; + +mod anisotropic_faces; +pub mod area; +mod bvh; +pub mod dielectric; +pub mod emission; +pub mod image; +pub mod lighting; +pub mod prepared; +mod progressive; +pub mod punctual; +pub mod reflection; +pub use bvh::{BuildLimits, BuildProgress, Bvh, BvhBuilder, MAX_DEPTH, MAX_MEMORY_BYTES, MAX_TRIANGLES}; + +/// Finite coordinate admission, not a CAD accuracy guarantee. +pub const MAX_COORDINATE_MM: f64 = 1e12; +/// Maximum finite ray interval endpoint in millimetres. +pub const MAX_DISTANCE_MM: f64 = 4e12; +/// Maximum work charged to one explicitly owned budget. +pub const MAX_WORK: u64 = 1_000_000_000; +/// Maximum incremental builder operations in one call. +pub const MAX_BUILD_STEP: usize = 4096; + +/// Structured failures; exhausting work never returns a truncated hit result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TraceError { + InvalidInput(&'static str), + MemoryLimit, + AllocationFailed, + WorkLimit, + Cancelled, + BuildIncomplete, + Internal(&'static str), +} + +impl std::fmt::Display for TraceError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidInput(reason) => write!(f, "invalid ray tracing input: {reason}"), + Self::MemoryLimit => f.write_str("ray tracing memory admission exceeded"), + Self::AllocationFailed => f.write_str("ray tracing allocation failed"), + Self::WorkLimit => f.write_str("ray tracing work budget exhausted"), + Self::Cancelled => f.write_str("ray tracing cancelled"), + Self::BuildIncomplete => f.write_str("ray tracing BVH build is incomplete"), + Self::Internal(reason) => write!(f, "invalid ray tracing internal state: {reason}"), + } + } +} +impl std::error::Error for TraceError {} +pub type Result = std::result::Result; + +fn check_cancel(cancel: &CancelToken) -> Result<()> { + if cancel.is_cancelled() { Err(TraceError::Cancelled) } else { Ok(()) } +} + +/// Caller-owned cumulative work; can span many rays in one image job. +#[derive(Debug)] +pub struct WorkBudget { + limit: u64, + used: u64, + protected: Option, +} + +/// One owned ledger, not another spendable budget. Keeping the policy and actual +/// counters here preserves the final report after the image task drops its film. +#[derive(Debug)] +struct ProtectedWork { + plan: crate::job::ProtectedPreviewPlan, + ordinary_used: u64, + presentation_used: u64, + presentation_limit: u64, + aggregate_limit: u64, + accepted_snapshots: u32, + next_milestone_index: u32, +} + +impl WorkBudget { + pub fn new(limit: u64) -> Result { + if limit == 0 || limit > crate::job::MAX_CPU_WORK { + return Err(TraceError::InvalidInput("work limit outside 1..=MAX_WORK")); + } + Ok(Self { limit, used: 0, protected: None }) + } + + pub(crate) fn new_protected(plan: crate::job::ProtectedPreviewPlan) -> Result { + plan.validate().map_err(|_| TraceError::InvalidInput("invalid protected feedback plan"))?; + let presentation_limit = plan.presentation_limit().map_err(|_| TraceError::WorkLimit)?; + let aggregate_limit = plan.aggregate_limit().map_err(|_| TraceError::WorkLimit)?; + if aggregate_limit > crate::job::MAX_PROTECTED_CPU_WORK { + return Err(TraceError::WorkLimit); + } + Ok(Self { + limit: plan.ordinary_limit(), + used: 0, + protected: Some(ProtectedWork { + plan, + ordinary_used: 0, + presentation_used: 0, + presentation_limit, + aggregate_limit, + accepted_snapshots: 0, + next_milestone_index: 0, + }), + }) + } + + pub fn used(&self) -> u64 { + self.used + } + + /// Legacy meaning is unchanged. Protected ordinary callers retain B-O; + /// presentation and aggregate capacity have separate, explicit getters. + pub fn remaining(&self) -> u64 { + self.ordinary_remaining() + } + + pub(crate) fn ordinary_remaining(&self) -> u64 { + self.limit - self.protected.as_ref().map_or(self.used, |state| state.ordinary_used) + } + + pub(crate) fn presentation_remaining(&self) -> u64 { + self.protected.as_ref().map_or(0, |state| state.presentation_limit - state.presentation_used) + } + + pub(crate) fn aggregate_remaining(&self) -> u64 { + self.protected.as_ref().map_or(self.limit, |state| state.aggregate_limit) - self.used + } + + pub(crate) fn protected_report(&self) -> Option { + let state = self.protected.as_ref()?; + let quota_limit = state.plan.quota_limit(); + Some(crate::job::ProtectedPreviewReport { + policy_version: 1, + ordinary_limit: self.limit, + presentation_limit: state.presentation_limit, + aggregate_limit: state.aggregate_limit, + ordinary_used: state.ordinary_used, + presentation_used: state.presentation_used, + accepted_snapshots: state.accepted_snapshots, + quota_limit, + next_milestone_index: state.next_milestone_index, + quota_exhausted: state.accepted_snapshots == quota_limit, + milestones_complete: state.next_milestone_index == quota_limit, + }) + } + + /// Read-only eligibility at a real committed camera frontier. Source progress + /// is not a work credit: it selects a milestone, never reserves ordinary work. + fn protected_ready(&self, committed: u64) -> Result { + let state = self.protected.as_ref().ok_or(TraceError::InvalidInput("protected feedback policy missing"))?; + if committed >= state.plan.total_commits() + || state.accepted_snapshots >= state.plan.quota_limit() + || state.next_milestone_index >= state.plan.quota_limit() + { + return Ok(false); + } + let milestone = state.plan.milestone(state.next_milestone_index).map_err(|_| TraceError::Internal("invalid protected milestone"))?; + let cost = state.plan.snapshot_work().map_err(|_| TraceError::WorkLimit)?; + Ok(committed >= milestone && self.presentation_remaining() >= cost && self.aggregate_remaining() >= cost) + } + + /// Debit ONE W and coalesce all reached milestones in the same transaction. + /// A wait/refusal changes no counters. Cancellation after a debit is not a refund. + fn charge_presentation(&mut self, committed: u64, cancel: &CancelToken) -> Result { + check_cancel(cancel)?; + if !self.protected_ready(committed)? { + return Ok(false); + } + let state = self.protected.as_ref().ok_or(TraceError::InvalidInput("protected feedback policy missing"))?; + let cost = state.plan.snapshot_work().map_err(|_| TraceError::WorkLimit)?; + let presentation_used = state.presentation_used.checked_add(cost).filter(|v| *v <= state.presentation_limit).ok_or(TraceError::WorkLimit)?; + let used = self.used.checked_add(cost).filter(|v| *v <= state.aggregate_limit).ok_or(TraceError::WorkLimit)?; + let accepted = state.accepted_snapshots.checked_add(1).filter(|n| *n <= state.plan.quota_limit()).ok_or(TraceError::WorkLimit)?; + let next = state.plan.reached_milestones(committed).map_err(|_| TraceError::Internal("invalid protected reached frontier"))?; + check_cancel(cancel)?; + let state = self.protected.as_mut().ok_or(TraceError::Internal("protected ledger disappeared"))?; + state.presentation_used = presentation_used; + state.accepted_snapshots = accepted; + state.next_milestone_index = next; + self.used = used; + Ok(true) + } + + fn tick(&mut self, cancel: &CancelToken) -> Result<()> { + self.charge(1, cancel) + } + + fn charge(&mut self, units: u64, cancel: &CancelToken) -> Result<()> { + check_cancel(cancel)?; + if let Some(state) = &mut self.protected { + let ordinary = state.ordinary_used.checked_add(units).filter(|v| *v <= self.limit).ok_or(TraceError::WorkLimit)?; + let used = self.used.checked_add(units).filter(|v| *v <= state.aggregate_limit).ok_or(TraceError::WorkLimit)?; + state.ordinary_used = ordinary; + self.used = used; + } else { + self.used = self.used.checked_add(units).filter(|used| *used <= self.limit).ok_or(TraceError::WorkLimit)?; + } + Ok(()) + } + + /// Private test boundary only: the ordinary allowance is fixed before any + /// real task work, preserving Q and the same O/V ledger. No production caller. + #[cfg(test)] + fn new_protected_for_test(plan: crate::job::ProtectedPreviewPlan, ordinary: u64) -> Result { + let mut work = Self::new_protected(plan)?; + if ordinary == 0 || ordinary > work.limit { + return Err(TraceError::InvalidInput("test ordinary limit outside profile")); + } + let state = work.protected.as_mut().ok_or(TraceError::Internal("test protected policy missing"))?; + state.aggregate_limit = + ordinary.checked_add(state.presentation_limit).filter(|v| *v <= crate::job::MAX_PROTECTED_CPU_WORK).ok_or(TraceError::WorkLimit)?; + work.limit = ordinary; + Ok(work) + } +} + +fn bounded(point: Vec3) -> bool { + point.is_finite() && [point.x, point.y, point.z].into_iter().all(|v| v.abs() <= MAX_COORDINATE_MM) +} + +fn unit(vector: Vec3) -> Option { + let scale = vector.x.abs().max(vector.y.abs()).max(vector.z.abs()); + if !vector.is_finite() || scale == 0.0 { + return None; + } + let scaled = vector / scale; + Some(scaled / scaled.len2().sqrt()) +} + +fn component(vector: Vec3, axis: usize) -> f64 { + match axis { + 0 => vector.x, + 1 => vector.y, + _ => vector.z, + } +} + +/// Admitted ray with a unit direction and closed finite distance interval. +/// No implicit origin offset, back-face culling or fixed world-space epsilon. +#[derive(Clone, Copy, Debug)] +pub struct Ray { + origin: Vec3, + direction: Vec3, + min: f64, + max: f64, +} + +impl Ray { + pub fn new(origin: Vec3, direction: Vec3, min: f64, max: f64) -> Result { + if !bounded(origin) || !min.is_finite() || !max.is_finite() || min < 0.0 || min > max || max > MAX_DISTANCE_MM { + return Err(TraceError::InvalidInput("ray origin or distance interval")); + } + let direction = unit(direction).ok_or(TraceError::InvalidInput("finite nonzero ray direction required"))?; + Ok(Self { origin, direction, min, max }) + } + pub fn origin(self) -> Vec3 { + self.origin + } + pub fn direction(self) -> Vec3 { + self.direction + } + pub fn interval(self) -> [f64; 2] { + [self.min, self.max] + } + pub fn at(self, distance: f64) -> Result { + if !distance.is_finite() || distance < self.min || distance > self.max { + return Err(TraceError::InvalidInput("distance outside admitted ray interval")); + } + Ok(self.origin + self.direction * distance) + } +} + +/// Conservative world-space box; empty boxes exist only inside the builder. +#[derive(Clone, Copy, Debug)] +pub struct Bounds { + min: Vec3, + max: Vec3, +} + +impl Bounds { + pub fn new(min: Vec3, max: Vec3) -> Result { + if !bounded(min) || !bounded(max) || min.x > max.x || min.y > max.y || min.z > max.z { + return Err(TraceError::InvalidInput("finite ordered bounding box required")); + } + Ok(Self { min, max }) + } + pub fn min(self) -> Vec3 { + self.min + } + pub fn max(self) -> Vec3 { + self.max + } + fn empty() -> Self { + Self { min: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), max: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY) } + } + fn include(self, other: Self) -> Self { + Self { min: self.min.min(other.min), max: self.max.max(other.max) } + } + fn point(point: Vec3) -> Self { + Self { min: point, max: point } + } + + /// Closed slab overlap. Parallel (including signed-zero) components never divide. + pub fn intersect(self, ray: &Ray) -> Option<[f64; 2]> { + self.clip(ray, ray.max) + } + + fn clip(self, ray: &Ray, maximum: f64) -> Option<[f64; 2]> { + let (mut near, mut far) = (ray.min, ray.max.min(maximum)); + for axis in 0..3 { + let (lo, hi, origin, direction) = + (component(self.min, axis), component(self.max, axis), component(ray.origin, axis), component(ray.direction, axis)); + if direction == 0.0 { + if origin < lo || origin > hi { + return None; + } + } else { + // Division may produce infinity for an almost-parallel ray; the + // finite caller interval clips it. No reciprocal times zero. + let a = (lo - origin) / direction; + let b = (hi - origin) / direction; + near = near.max(a.min(b)); + far = far.min(a.max(b)); + if near > far { + return None; + } + } + } + Some([near, far]) + } +} + +/// Validated triangle. Coincident/collinear vertices are retained but never hit. +#[derive(Clone, Copy, Debug)] +pub struct Triangle { + vertices: [Vec3; 3], + normal: Option, +} + +impl Triangle { + pub fn new(vertices: [Vec3; 3]) -> Result { + if !vertices.into_iter().all(bounded) { + return Err(TraceError::InvalidInput("triangle vertex coordinates")); + } + let [a, b, c] = vertices; + let ab = b - a; + let ac = c - a; + let scale = [ab.x, ab.y, ab.z, ac.x, ac.y, ac.z].into_iter().map(f64::abs).fold(0.0, f64::max); + let normal = if scale == 0.0 { None } else { unit((ab / scale).cross(ac / scale)) }; + Ok(Self { vertices, normal }) + } + pub fn vertices(self) -> [Vec3; 3] { + self.vertices + } + pub fn geometric_normal(self) -> Option { + self.normal + } + pub fn bounds(self) -> Bounds { + let [a, b, c] = self.vertices; + let min = a.min(b).min(c); + let max = a.max(b).max(c); + // One representable outward step, not a fixed millimetre epsilon. + Bounds { + min: Vec3::new(min.x.next_down(), min.y.next_down(), min.z.next_down()), + max: Vec3::new(max.x.next_up(), max.y.next_up(), max.z.next_up()), + } + } + fn centroid(self) -> Vec3 { + let [a, b, c] = self.vertices; + a / 3.0 + b / 3.0 + c / 3.0 + } + + /// Two-sided closed-edge barycentric intersection by dominant-direction shear. + /// At equal distance the BVH's input ordinal resolves the tie. Zero projected + /// area is a miss, including geometry collapsed by f64 arithmetic. + pub fn intersect(self, ray: &Ray) -> Option { + let normal = self.normal?; + let d = ray.direction; + let kz = if d.x.abs() >= d.y.abs() && d.x.abs() >= d.z.abs() { + 0 + } else if d.y.abs() >= d.z.abs() { + 1 + } else { + 2 + }; + let kx = (kz + 1) % 3; + let ky = (kx + 1) % 3; + let dominant = component(d, kz); + let sx = component(d, kx) / dominant; + let sy = component(d, ky) / dominant; + let projected = self.vertices.map(|v| { + let delta = v - ray.origin; + let z = component(delta, kz); + [component(delta, kx) - sx * z, component(delta, ky) - sy * z, z / dominant] + }); + let [[ax, ay, az], [bx, by, bz], [cx, cy, cz]] = projected; + let weights = [bx * cy - by * cx, cx * ay - cy * ax, ax * by - ay * bx]; + let [u, v, w] = weights; + if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) { + return None; + } + let determinant = u + v + w; + if determinant == 0.0 { + return None; + } + let barycentric = weights.map(|value| value / determinant); + let [u, v, w] = barycentric; + // Divide before multiplying by depth: very small triangle areas need not + // underflow their otherwise well-represented hit distance. + // An exact coordinate plane has a direct depth equation. Summing + // depths along another dominant ray axis can cancel large tangential + // terms into a false positive. No interval or edge policy changes. + let axis_plane = (0..3).find_map(|axis| { + let [a, b, c] = self.vertices.map(|point| component(point, axis)); + (a == b && b == c).then_some((axis, a)) + }); + let distance = if let Some((axis, coordinate)) = axis_plane { + (coordinate - component(ray.origin, axis)) / component(d, axis) + } else { + u * az + v * bz + w * cz + }; + if !distance.is_finite() || distance < ray.min || distance > ray.max { + return None; + } + Some(TriangleHit { distance, barycentric, geometric_normal: normal, front_face: d.dot(normal) < 0.0 }) + } +} + +/// Geometric hit, without material/shading-normal or persistent topology identity. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TriangleHit { + pub distance: f64, + pub barycentric: [f64; 3], + pub geometric_normal: Vec3, + pub front_face: bool, +} + +/// Captured input ordinal, not a CAD face identifier. RT2 owns the appearance mapping. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hit { + pub primitive_index: usize, + pub geometry: TriangleHit, +} + +#[cfg(test)] +mod planar_shadow_tests; +#[cfg(test)] +mod tests; diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/primary_aa_tests.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/primary_aa_tests.rs new file mode 100644 index 000000000..aa69f9f19 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/primary_aa_tests.rs @@ -0,0 +1,1980 @@ +//! Spatial AA regressions: WRITTEN NOT RUN. No historical gate is transferred. +use super::*; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::{ProductMesh, StandardView}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +fn progressive_fixture(samples: u32, seed: u32, left: Option, exposure: f64) -> ImageTask { + // Reuse the analytic half-plane camera/geometry, not fixed-AA output. + let fixed = fixture(1, 1, left); + let mut options = fixed.visibility_owner.options().clone(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed }); + options.exposure_ev = exposure; + let mut request = fixed.request.clone(); + request.raytrace = Some(options.clone()); + ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() +} + +type ProgressiveOutput = (Vec<(u32, Vec)>, Vec, u64); +fn progressive_complete(mut task: ImageTask, quantum: usize) -> ProgressiveOutput { + let mut previews = Vec::new(); + for _ in 0..200_000 { + let result = task.step_with_previews(quantum).unwrap(); + let progress = task.progress(); + assert!(progress.done <= progress.total); + match result { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => previews.push((samples_per_pixel, png)), + ImagePoll::Complete(png) => return (previews, png, task.work.used()), + } + } + panic!("bounded progressive fixture did not finish"); +} + +#[test] +fn progressive_real_png_has_stable_prefixes_quanta_and_fresh_primary_samples() { + let (previews, final_png, work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 1); + assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6, 7]); + let (other, other_final, other_work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 16_384); + assert_eq!(other, previews); + assert_eq!(other_final, final_png); + assert_eq!(other_work, work, "quanta cannot reset or change the cumulative budget"); + for (samples, checkpoint) in &previews { + let (_, prefix, _) = progressive_complete(progressive_fixture(*samples, 123, Some(true), 0.0), 3); + assert_eq!(&prefix, checkpoint, "target SPP must not alter an earlier prefix"); + } + let mut task = progressive_fixture(8, 123, Some(true), 0.0); + let mut rays = Vec::new(); + for _ in 0..200_000 { + let absent = task.pending.is_none(); + let result = task.step_with_previews(1).unwrap(); + if absent && let Some(pending) = task.pending.as_ref() { + assert!(!pending.repeatable_primary, "jittered primary samples cannot use fixed-centre reuse"); + rays.push([pending.ray.origin().x.to_bits(), pending.ray.origin().y.to_bits()]); + } + if matches!(result, ImagePoll::Complete(_)) { + break; + } + } + assert_eq!(rays.len(), 8); + rays.sort(); + rays.dedup(); + assert_eq!(rays.len(), 8, "each absolute ordinal traces a new camera sample"); +} + +#[test] +fn progressive_coverage_keeps_backplate_outside_exposure_and_tone_mapping() { + for exposure in [-16.0, 0.0, 16.0] { + let (_, background, _) = progressive_complete(progressive_fixture(5, 9, None, exposure), 4); + assert_eq!(::image::load_from_memory(&background).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); + let (_, half, _) = progressive_complete(progressive_fixture(64, 9, Some(true), exposure), 4); + let covered = (0..64).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + assert!(covered > 0 && covered < 64); + let expected = encode8(1.0 - covered as f64 / 64.0); + assert_eq!(::image::load_from_memory(&half).unwrap().to_rgba8().get_pixel(0, 0).0, [expected, expected, expected, 255]); + } + let (previews, _, _) = progressive_complete(progressive_fixture(5, 9, Some(true), 0.0), 1); + assert_eq!( + previews.iter().map(|(samples, _)| *samples).collect::>(), + [1, 2, 3, 4], + "non-power-of-two target still has an exact final pass" + ); +} + +#[test] +fn progressive_resolves_the_mean_radiance_once_instead_of_averaging_display_pixels() { + let left = fixture(1, 1, Some(true)); + let right = fixture(1, 1, Some(false)); + let mut source = left.visibility_owner.source().clone(); + let mut other = right.visibility_owner.source().meshes[0].clone(); + other.name = "Bright half".into(); + source.bounds = source.bounds.union(&other.mesh.bounds()); + source.meshes.push(other); + let mut options = left.visibility_owner.options().clone(); + options.reflections = None; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 64, seed: 9 }); + options.exposure_ev = 1.0; + options.emissions = Some(vec![ + job::SurfaceEmission { body_index: 0, body: "Black half".into(), color: [1.0, 0.5, 0.25], strength: 1.0, sides: job::EmissionSides::Both }, + job::SurfaceEmission { body_index: 1, body: "Bright half".into(), color: [1.0, 0.5, 0.25], strength: 9.0, sides: job::EmissionSides::Both }, + ]); + let request = ImageRequest { raytrace: Some(options.clone()), ..left.request.clone() }; + let task = ImageTask::new(source, request, CancelToken::default(), options).unwrap(); + let (_, png, _) = progressive_complete(task, 4); + let left_count = (0..64).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + let mean = (left_count as f64 + (64 - left_count) as f64 * 9.0) / 64.0; + let expected = [1.0, 0.5, 0.25].map(|color| { + let exposed = mean * color * 2.0; + encode8(exposed / (1.0 + exposed)) + }); + let actual = ::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0; + assert_eq!(actual, [expected[0], expected[1], expected[2], 255]); + let fraction = left_count as f64 / 64.0; + let prematurely_mapped = encode8(fraction * (2.0 / 3.0) + (1.0 - fraction) * (18.0 / 19.0)); + assert_ne!(actual[0], prematurely_mapped, "each sample must remain linear until the whole pass resolves"); +} + +#[test] +fn progressive_film_and_resolve_share_cancellation_and_one_cumulative_work_budget() { + let mut task = progressive_fixture(4, 0, Some(true), 0.0); + task.work = WorkBudget::new(1).unwrap(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert_eq!(task.step_with_previews(1).err().unwrap().code, ErrorCode::LimitExceeded); + for during_resolve in [false, true] { + let mut task = progressive_fixture(4, 0, Some(true), 0.0); + if during_resolve { + for _ in 0..200_000 { + if task.progressive.as_ref().is_some_and(|p| p.resolving) { + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(task.progressive.as_ref().unwrap().resolving); + } + task.cancel.cancel(); + assert_eq!(task.step_with_previews(4).err().unwrap().code, ErrorCode::Cancelled); + assert!(!task.done); + } +} + +fn fixture(samples: u8, r: u8, left: Option) -> ImageTask { + let mut camera = crate::Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Top); + let meshes = if let Some(left) = left { + let (x0, x1) = if left { (0.0, 0.5) } else { (0.5, 1.0) }; + let point = |x, y| { + let (o, _) = camera.ray(x, y, 1.0, 1.0); + Vec3::new(o.x, o.y, 0.0) + }; + vec![ProductMesh { + transmission: None, + name: "Black half".into(), + mesh: Arc::new(Mesh { + positions: vec![point(x0, 0.0), point(x1, 0.0), point(x1, 1.0), point(x0, 1.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }] + } else { + Vec::new() + }; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let options = RaytraceOptions { + primary_samples: samples, + lights: Some(Vec::new()), + shadows: false, + reflections: left.map(|_| ReflectionOptions { + bodies: vec![ReflectionBody { body: "Black half".into(), mode: ReflectionMode::RoughSpecular }], + samples: r, + max_bounces: 2, + }), + ..Default::default() + }; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: job::Integrator::Raytrace, + raytrace: Some(options.clone()), + camera, + width: 1, + height: 1, + background: [255; 3], + transparent_background: false, + }; + ImageTask::new(ProductScene { meshes, bounds }, request, CancelToken::default(), options).unwrap() +} +fn until_emit(task: &mut ImageTask) -> usize { + let mut primaries = 0; + let mut previous_primary = None; + for _ in 0..200_000 { + let absent = task.pending.is_none(); + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 4); + if absent && task.pending.as_ref().is_some_and(|p| p.bounce == 0) { + primaries += 1; + let pending = task.pending.as_ref().unwrap(); + assert!(pending.repeatable_primary, "fixed generator must certify only intra-spatial R invariance"); + let o = pending.ray.origin(); + let d = pending.ray.direction(); + let ray = [o.x.to_bits(), o.y.to_bits(), o.z.to_bits(), d.x.to_bits(), d.y.to_bits(), d.z.to_bits()]; + if let Some((pixel, spatial, previous_ray)) = previous_primary { + if (pixel, spatial) == (task.pixel, task.spatial) { + assert_eq!(ray, previous_ray, "fixed primary ray changed between R attempts"); + } else { + assert_ne!(ray, previous_ray, "distinct spatial samples must not reuse their primary ray"); + } + } + previous_primary = Some((task.pixel, task.spatial, ray)); + } + if let Some(p) = task.pending.as_ref() { + if p.bounce != 0 { + assert!(!p.repeatable_primary, "secondary paths must revoke primary reuse"); + } else if let Some(hit) = p.hit { + let shared = PreparedScene { bvh: task.bvh.as_ref().unwrap(), primitives: &task.looks, source: task.visibility_owner.source() } + .resolve_hit(p.ray, hit) + .unwrap(); + if task.visibility_owner.options().reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|b| b.body == shared.body_name)) { + assert!(!p.repeatable_primary, "selected primary hit must revoke reuse even when its reflection is null"); + } + } + } + assert!(task.pixels.is_empty(), "early primary hit/miss emitted pixel"); + if task.progress().phase == Phase::Running { + assert_eq!(task.progress().done, 0, "subsamples counted as completed pixels"); + } + if task.emit_spatial_pixel { + return primaries; + } + } + panic!("bounded AA fixture did not reach emission"); +} +fn complete(mut task: ImageTask, quantum: usize) -> (Vec, u64) { + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(quantum).unwrap() { + return (png, task.work.used()); + } + } + panic!("bounded AA fixture did not finish"); +} + +#[test] +fn transient_options_are_strict_default_one_and_do_not_serialize_a_new_default_field() { + let omitted: RaytraceOptions = serde_json::from_str("{}").unwrap(); + let explicit: RaytraceOptions = serde_json::from_str(r#"{"primary_samples":1}"#).unwrap(); + assert_eq!(omitted, explicit); + assert_eq!(omitted.primary_samples, 1); + assert!(!serde_json::to_value(&omitted).unwrap().as_object().unwrap().contains_key("primary_samples")); + for n in [0, 2, 8, 17, 255] { + assert!(RaytraceOptions { primary_samples: n, ..Default::default() }.validate().is_err()); + } + for raw in [ + r#"{"primary_samples":-1}"#, + r#"{"primary_samples":1.5}"#, + r#"{"primary_samples":null}"#, + r#"{"primary_samples":"4"}"#, + r#"{"primary_samples":4,"unknown":0}"#, + ] { + assert!(serde_json::from_str::(raw).is_err()); + } +} + +#[test] +fn fixed_grids_have_independent_analytic_halfplane_and_triangle_coverage() { + assert_eq!(primary_offset(1, 0).unwrap(), [0.5, 0.5]); + assert_eq!(primary_offset(4, 0).unwrap(), [0.25, 0.25]); + assert_eq!(primary_offset(4, 3).unwrap(), [0.75, 0.75]); + for (s, half, triangle) in [(4, 2, 1), (16, 8, 3)] { + let points: Vec<_> = (0..s).map(|i| primary_offset(s, i).unwrap()).collect(); + assert!(points.iter().flatten().all(|v| *v > 0.0 && *v < 1.0)); + assert_eq!(points.iter().filter(|p| p[0] < 0.5).count(), half); + assert_eq!(points.iter().filter(|p| p[0] + p[1] < 5.0 / 8.0).count(), triangle); + assert!(primary_offset(s, s).is_err()); + } + assert!(primary_offset(8, 0).is_err()); + assert!(spatial_key(u64::MAX, 0, 16).is_err()); + assert_ne!(spatial_key(7, 0, 4).unwrap(), spatial_key(7, 1, 4).unwrap()); +} + +#[test] +fn compositor_keeps_conditional_scene_mean_then_display_linear_coverage() { + // White L=1, Reinhard=1/2; half coverage over black gives1/4 display-linear. + assert_eq!(composite_spatial(Vec3::new(0.5, 0.5, 0.5), 2, 4, [0; 3], 0.0).unwrap(), [encode8(0.25), encode8(0.25), encode8(0.25), 255]); + assert_ne!(encode8(0.25), encode8(1.0 / 3.0)); + // Full coverage of L=0 and L=2 usesT(mean)=1/2, not mean(T)=1/3. + assert_eq!(composite_spatial(Vec3::new(1.0, 1.0, 1.0), 4, 4, [255; 3], 0.0).unwrap(), [encode8(0.5), encode8(0.5), encode8(0.5), 255]); + for ev in [-16.0, 0.0, 16.0] { + assert_eq!(composite_spatial(Vec3::ZERO, 0, 16, [13, 27, 41], ev).unwrap(), [13, 27, 41, 255]); + } + let gray = srgb8_to_linear(128); + assert_eq!(composite_spatial(Vec3::ZERO, 2, 4, [128; 3], 0.0).unwrap(), [encode8(gray * 0.5), encode8(gray * 0.5), encode8(gray * 0.5), 255]); + assert!(composite_spatial(Vec3::ZERO, 5, 4, [0; 3], 0.0).is_err()); + assert!(composite_spatial(Vec3::X, 0, 4, [0; 3], 0.0).is_err()); +} + +#[test] +fn real_hit_first_and_miss_first_silhouettes_keep_all_attempts_and_null_coverage() { + for s in [4, 16] { + for r in [1, 4, 16, 64] { + for left in [false, true] { + let mut task = fixture(s, r, Some(left)); + let primaries = until_emit(&mut task); + assert_eq!(primaries, usize::from(s) * usize::from(r)); + assert_eq!(task.primary_coverage, u16::from(s) * u16::from(r) / 2); + let before = task.work.used(); + task.step(1).unwrap(); + assert_eq!(task.work.used(), before + 1); + assert_eq!(task.pixels, [encode8(0.5), encode8(0.5), encode8(0.5), 255]); + assert_eq!(task.pixel, 1); + } + } + } +} + +#[test] +fn miss_only_aa_retains_exact_background_and_quantum_independent_png() { + for s in [4, 16] { + let mut task = fixture(s, 1, None); + assert_eq!(until_emit(&mut task), usize::from(s)); + assert_eq!(task.primary_coverage, 0); + let small = complete(task, 1); + let large = complete(fixture(s, 1, None), 16384); + assert_eq!(small, large); + let image = ::image::load_from_memory(&small.0).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [255; 4]); + } +} + +#[test] +fn spatial_finalization_and_emission_observe_shared_work_and_cancellation() { + for emit in [false, true] { + for cancel in [false, true] { + let mut task = fixture(16, 4, Some(false)); + for _ in 0..200_000 { + if (emit && task.emit_spatial_pixel) || (!emit && task.finish_spatial) { + break; + } + task.step(1).unwrap(); + } + assert!(if emit { task.emit_spatial_pixel } else { task.finish_spatial }); + let used = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + let code = task.step(1).err().unwrap().code; + assert_eq!(code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert!(!task.done && task.pixels.is_empty()); + } + } +} + +#[test] +fn legacy_single_primary_ignores_aa_state_and_preserves_default_bytes_work_and_order() { + for left in [None, Some(true), Some(false)] { + for r in [1, 4, 16, 64] { + let control = fixture(1, r, left); + let mut isolated = fixture(1, r, left); + isolated.spatial = 16; + isolated.primary_coverage = 1024; + isolated.spatial_radiance = Vec3::new(f64::NAN, 0.0, 0.0); + isolated.finish_spatial = true; + isolated.emit_spatial_pixel = true; + assert_eq!(complete(control, 1), complete(isolated, 16384)); + } + } + assert!(std::mem::size_of::() <= 4096); + assert_eq!(crate::raytrace::MAX_WORK, 1_000_000_000); + assert_eq!(job::image::MAX_JOB_BYTES, 384 * 1024 * 1024); + let legacy = fixture(1, 4, Some(false)); + let aa = fixture(16, 4, Some(false)); + assert_eq!(legacy.admission.estimated_total_bytes, aa.admission.estimated_total_bytes); +} + +#[test] +fn full_coverage_black_plane_never_leaks_display_background() { + for samples in [4, 16] { + let initial = fixture(samples, 16, Some(true)); + let top = initial.request.camera.ray(1.0, 0.0, 1.0, 1.0).0; + let bottom = initial.request.camera.ray(1.0, 1.0, 1.0, 1.0).0; + let (mut fixture_scene, fixture_options) = initial.visibility_owner.into_capture(); + let mesh = Arc::get_mut(&mut fixture_scene.meshes[0].mesh).unwrap(); + mesh.positions[1] = Vec3::new(top.x, top.y, 0.0); + mesh.positions[2] = Vec3::new(bottom.x, bottom.y, 0.0); + fixture_scene.bounds = mesh.bounds(); + let mut task = ImageTask::new(fixture_scene, initial.request, initial.cancel, fixture_options).unwrap(); + assert_eq!(until_emit(&mut task), usize::from(samples) * 16); + assert_eq!(task.primary_coverage, u16::from(samples) * 16); + task.step(1).unwrap(); + assert_eq!(task.pixels, [0, 0, 0, 255]); + } +} + +#[test] +fn later_spatial_attempts_do_not_reset_work_and_never_publish_when_interrupted() { + for cancel in [false, true] { + let mut task = fixture(16, 64, Some(true)); + for _ in 0..200_000 { + if task.spatial >= 1 && task.sample >= 1 { + break; + } + task.step(1).unwrap(); + } + assert!(task.spatial >= 1 && task.sample >= 1); + let used = task.work.used(); + assert!(used > 64, "no cumulative work across spatial samples"); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert!(!task.done && task.pixels.is_empty()); + } +} + +#[test] +fn actual_colored_lit_partial_coverage_wires_positive_radiance_exposure_and_background() { + for samples in [4, 16] { + for left in [false, true] { + let mut initial = fixture(samples, 1, Some(left)); + let (mut fixture_scene, mut fixture_options) = initial.visibility_owner.into_capture(); + fixture_scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()); + fixture_options.reflections = None; + fixture_options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [0.25, 0.5, 1.0], intensity: 2.0 }]); + fixture_options.exposure_ev = 1.0; + initial.request.background = [13, 73, 139]; + initial.request.raytrace = Some(fixture_options.clone()); + let mut task = ImageTask::new(fixture_scene, initial.request, initial.cancel, fixture_options).unwrap(); + assert_eq!(until_emit(&mut task), usize::from(samples)); + assert_eq!(task.primary_coverage, u16::from(samples) / 2); + // At normal incidence, unit-alpha white conductor: D=1/pi, + // G1=F=1, f=1/(4pi), incoming radiance=2*colored light. + let linear = [0.5, 1.0, 2.0].map(|v| v / (4.0 * std::f64::consts::PI)); + let expected_p = Vec3::new(linear[0], linear[1], linear[2]) * 0.5; + assert!((task.spatial_radiance - expected_p).len() < 1e-12); + let expected: [u8; 3] = std::array::from_fn(|i| { + let exposed = linear[i] * 2.0; + let display = 0.5 * exposed / (1.0 + exposed) + 0.5 * srgb8_to_linear([13, 73, 139][i]); + encode8(display) + }); + task.step(1).unwrap(); + assert_eq!(task.pixels, [expected[0], expected[1], expected[2], 255]); + } + } +} + +#[test] +fn workstation_progressive_streams_every_historical_2048_4096_checkpoint_and_checks_the_new_cap() { + let fixed = fixture(1, 1, Some(true)); + let cap = job::CpuBudget::Workstation.limits().max_samples_per_pixel; + assert_eq!(cap, 1_048_576); + for samples in [2048, 4096] { + let mut options = fixed.visibility_owner.options().clone(); + options.budget = job::CpuBudget::Workstation; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }); + let request = ImageRequest { raytrace: Some(options.clone()), ..fixed.request.clone() }; + let mut task = ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + let mut observed = Vec::new(); + let mut complete = false; + for _ in 0..200_000 { + match task.step_with_previews(16_384).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => { + observed.push(samples_per_pixel); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1, 1)); + } + ImagePoll::Complete(png) => { + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1, 1)); + complete = true; + break; + } + } + } + assert!(complete); + assert_eq!(observed, (1..samples).collect::>()); + } + assert_eq!(composite_spatial(Vec3::ZERO, 0, 4097, [0; 3], 0.0).unwrap(), [0, 0, 0, 255]); + assert!(composite_spatial(Vec3::ZERO, 0, 1_048_577, [0; 3], 0.0).is_err()); +} + +#[test] +fn area_light_points_include_spatial_and_film_sample_identity() { + let light = super::super::area::RectangleLight::new(Vec3::Z * 10.0, Vec3::X * 4.0, -Vec3::Y * 4.0, Vec3::new(1.0, 1.0, 1.0), 1.0).unwrap(); + let mut keys = std::collections::BTreeSet::new(); + let mut points = std::collections::BTreeSet::new(); + for film in [0, 1, 1023, 2047, 4095] { + for spatial in 0..16 { + let key = area_sample_key(41, spatial, 16, film).unwrap(); + assert!(keys.insert(key)); + let point = light.sample(Vec3::ZERO, key, 2, 0, 4, 73).unwrap().unwrap().position(); + assert!(points.insert((point.x.to_bits(), point.y.to_bits()))); + assert_eq!(light.sample(Vec3::ZERO, key, 2, 0, 4, 73).unwrap().unwrap().position(), point); + } + } + assert_eq!(area_sample_key(41, 0, 1, 0).unwrap(), 41); + assert_eq!(area_sample_key(41, 0, 1, 4096).unwrap(), (1_u64 << 63) | (41_u64 << 36) | (4096_u64 << 16)); + assert!(area_sample_key(41, 0, 1, 1_048_576).is_err()); + assert!(area_sample_key(41, 4, 4, 0).is_err()); + assert!(area_sample_key(u64::MAX, 0, 4, 0).is_err()); +} + +// Original receiver and rectangular source; no borrowed model or recorded image. +fn progressive_area_fixture(area_samples: u32, samples: u32, seed: u32, shadows: bool) -> ImageTask { + let original = fixture(1, 1, Some(true)); + let mut scene = original.visibility_owner.source().clone(); + scene.meshes[0].mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-100.0, -100.0, 0.0), Vec3::new(100.0, -100.0, 0.0), Vec3::new(100.0, 100.0, 0.0), Vec3::new(-100.0, 100.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 1.0, 1.0).unwrap()); + scene.bounds = scene.meshes[0].mesh.bounds(); + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 97 }), + lights: Some(Vec::new()), + area_lights: Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]), + area_samples: Some(area_samples), + seed: Some(seed), + shadows, + ..Default::default() + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} + +fn progressive_area_rebuild(source: &ImageTask, options: RaytraceOptions) -> ImageTask { + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; + ImageTask::new(source.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() +} + +#[test] +fn progressive_area_transport_uses_absolute_film_ordinal_and_seed_for_all_sample_counts() { + use super::super::area::RectangleLight; + for count in [1, 4, 16, 64] { + for seed in [7, 91] { + let mut task = progressive_area_fixture(count, 2, seed, false); + let light = RectangleLight::new(Vec3::Z * 10.0, Vec3::X * 2.0, -Vec3::Y * 2.0, Vec3::new(1.0, 0.5, 0.25), 2.0).unwrap(); + let mut inspected = 0; + let mut first_positions = Vec::new(); + let mut complete = false; + for _ in 0..200_000 { + let ordinal = task.progressive.as_ref().unwrap().film.samples(); + let before = + task.pending.as_ref().filter(|p| p.hit.is_some() && p.area_light == 0 && p.area_index < count).map(|p| (p.area_index, p.ray)); + let poll = task.step_with_previews(1).unwrap(); + if let Some((index, ray)) = before + && let Some(pending) = task.pending.as_ref() + && pending.area_light == 0 + && pending.area_index == index + 1 + { + let point = ray.origin() + ray.direction() * (-ray.origin().z / ray.direction().z); + let key = area_sample_key(0, 0, 1, ordinal).unwrap(); + let sampled = light.sample(point, key, 0, index, count, seed).unwrap().unwrap(); + // Index-matched nonmetallic white receiver is exactly Lambertian. + // Check the actual consumer, independently of its BRDF and area weight. + let delta = sampled.position() - point; + let distance_squared = delta.dot(delta); + let factor = 4.0 * delta.z * delta.z / (distance_squared * distance_squared * f64::from(count) * std::f64::consts::PI); + let expected = Vec3::new(2.0, 1.0, 0.5) * factor; + assert!((pending.area_value - expected).len() < 1e-12, "N={count}, seed={seed}, film={ordinal}, index={index}"); + if index == 0 { + first_positions.push(sampled.position()); + } + inspected += 1; + } + if matches!(poll, ImagePoll::Complete(_)) { + complete = true; + break; + } + } + assert!(complete); + assert_eq!(inspected, 2 * count); + assert_eq!(first_positions.len(), 2); + if count == 1 { + assert_eq!(first_positions[0], first_positions[1], "one sample intentionally stays at the emitter centre"); + } else { + assert_ne!(first_positions[0], first_positions[1], "later film passes must not reuse the first emitter point"); + } + } + } +} + +#[test] +fn progressive_area_center_sample_resolves_the_analytic_linear_mean_once() { + let task = progressive_area_fixture(1, 3, 7, false); + let camera = task.request.camera; + let mut sum = Vec3::ZERO; + for ordinal in 0..3 { + let [u, v] = progressive::variates(97, 0, ordinal, 0); + let (origin, direction) = camera.ray(u, v, 1.0, 1.0); + let point = origin + direction * (-origin.z / direction.z); + let delta = Vec3::Z * 10.0 - point; + let r2 = delta.dot(delta); + sum += Vec3::new(2.0, 1.0, 0.5) * (4.0 * delta.z * delta.z / (r2 * r2 * std::f64::consts::PI)); + } + let mean = sum / 3.0; + let expected = [mean.x, mean.y, mean.z].map(|value| encode8(value / (1.0 + value))); + let (_, png, _) = progressive_complete(task, 1); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); +} + +#[test] +fn progressive_area_checkpoints_and_work_are_independent_of_target_and_quantum() { + for count in [1, 4, 16, 64] { + let small = progressive_complete(progressive_area_fixture(count, 5, 23, true), 1); + let large = progressive_complete(progressive_area_fixture(count, 5, 23, true), 16_384); + assert_eq!(small, large, "area continuation must share the same cumulative work across quanta"); + assert_eq!(small.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4]); + for (samples, checkpoint) in &small.0 { + let (_, final_png, _) = progressive_complete(progressive_area_fixture(count, *samples, 23, true), 3); + assert_eq!(&final_png, checkpoint); + } + } +} + +#[test] +fn progressive_led_lowering_keeps_rectangle_power_sampling_and_final_bytes() { + let strip = job::led_strip::LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 2.0, + width_mm: 2.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }; + for count in [1, 4, 16, 64] { + let direct = progressive_area_fixture(count, 3, 7, true); + let mut options = direct.visibility_owner.options().clone(); + options.area_lights = None; + options.area_samples = None; + options.seed = None; + strip.append_to(&mut options, count).unwrap(); + options.seed = direct.visibility_owner.options().seed; + assert_eq!(options, *direct.visibility_owner.options()); + let lowered = progressive_area_rebuild(&direct, options); + assert_eq!(progressive_complete(direct, 1), progressive_complete(lowered, 7)); + } +} + +#[test] +fn progressive_area_admission_bills_source_capacity_and_reuses_bounded_scratch() { + let source = progressive_area_fixture(1, 3, 7, true); + let mut empty = source.visibility_owner.options().clone(); + empty.area_lights = None; + empty.area_samples = None; + empty.seed = None; + let baseline = progressive_area_rebuild(&source, empty); + let slots = source.visibility_owner.options().area_lights.as_ref().unwrap().capacity(); + let bytes = (slots * std::mem::size_of::()) as u64; + assert_eq!(source.visibility_owner.options().retained_bytes().unwrap(), bytes); + assert_eq!(source.admission.estimated_total_bytes - baseline.admission.estimated_total_bytes, bytes); + assert_eq!(source.admission.preparation_bytes - baseline.admission.preparation_bytes, bytes); + for count in [4, 16, 64] { + let more = progressive_area_fixture(count, 3, 7, true); + assert_eq!( + more.admission.estimated_total_bytes, source.admission.estimated_total_bytes, + "area samples reuse the same continuation, not an N-sized buffer" + ); + } + let mut over = source.request.clone(); + over.width = 1025; + over.height = 1024; + assert_eq!(admit(source.visibility_owner.source(), &over, source.visibility_owner.options()).err().unwrap().code, ErrorCode::LimitExceeded); +} + +#[test] +fn progressive_area_shadow_cancellation_and_checkpoint_do_not_reset_work() { + let mut task = progressive_area_fixture(16, 3, 7, true); + let mut pending_shadow = false; + for _ in 0..200_000 { + if task.pending.as_ref().is_some_and(|p| p.area_shadow) { + pending_shadow = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(pending_shadow); + let used = task.work.used(); + task.cancel.cancel(); + assert_eq!(task.step_with_previews(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.work.used(), used); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + + let mut reference = progressive_area_fixture(16, 3, 7, true); + let mut checkpoint_work = None; + for _ in 0..200_000 { + if let ImagePoll::Preview { samples_per_pixel, .. } = reference.step_with_previews(1).unwrap() { + assert_eq!(samples_per_pixel, 1); + checkpoint_work = Some(reference.work.used()); + break; + } + } + let limit = checkpoint_work.unwrap(); + let mut bounded = progressive_area_fixture(16, 3, 7, true); + bounded.work = WorkBudget::new(limit).unwrap(); + let mut observed_checkpoint = false; + for _ in 0..200_000 { + match bounded.step_with_previews(1) { + Ok(ImagePoll::Pending(_)) => {} + Ok(ImagePoll::Preview { samples_per_pixel, .. }) => { + assert!(!observed_checkpoint); + assert_eq!(samples_per_pixel, 1); + observed_checkpoint = true; + assert_eq!(bounded.work.used(), limit); + } + Ok(ImagePoll::Complete(_)) => panic!("work exhausted after the checkpoint must not publish a final"), + Err(error) => { + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(observed_checkpoint); + assert_eq!(bounded.work.used(), limit); + assert!(!bounded.done); + return; + } + } + } + panic!("area work ceiling was reset or the fixture did not finish"); +} + +fn partial_four_pixel_source(samples: u32, seed: u32) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut camera = crate::Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Top); + let body = |name: &str, x0: f64, x1: f64| { + let point = |x, y| { + let (origin, _) = camera.ray(x, y, 4.0, 1.0); + Vec3::new(origin.x, origin.y, 0.0) + }; + ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(Mesh { + positions: vec![point(x0, 0.0), point(x1, 0.0), point(x1, 1.0), point(x0, 1.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + } + }; + let meshes = vec![body("Partial red", 0.0, 1.0), body("Partial black", 2.0, 3.0)]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds())); + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed }), + lights: Some(Vec::new()), + shadows: false, + emissions: Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Partial red".into(), + color: [1.0, 0.0, 0.0], + strength: 2.0, + sides: job::EmissionSides::Both, + }]), + ..Default::default() + }; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: job::Integrator::Raytrace, + raytrace: Some(options.clone()), + camera, + width: 4, + height: 1, + background: [10, 20, 30], + transparent_background: false, + }; + (ProductScene { meshes, bounds }, request, options) +} + +fn partial_four_pixel_task(samples: u32, seed: u32, partial: bool) -> ImageTask { + let (scene, request, options) = partial_four_pixel_source(samples, seed); + if partial { + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + ImageTask::new_with_environment_and_nested_and_partial(scene, request, CancelToken::default(), options, None, false, plan).unwrap() + } else { + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() + } +} + +type PartialRayLog = Vec<(usize, u32, [u64; 6])>; +fn record_partial_primary(task: &ImageTask, was_empty: bool, log: &mut PartialRayLog) { + if was_empty && let Some(pending) = task.pending.as_ref() { + let origin = pending.ray.origin(); + let direction = pending.ray.direction(); + let ordinal = task.progressive.as_ref().unwrap().film.samples(); + log.push(( + task.pixel, + ordinal, + [origin.x.to_bits(), origin.y.to_bits(), origin.z.to_bits(), direction.x.to_bits(), direction.y.to_bits(), direction.z.to_bits()], + )); + } +} +fn reach_partial_frontier(task: &mut ImageTask, passes: u32, prefix: usize, rays: &mut PartialRayLog) { + for _ in 0..200_000 { + if let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.partial_frontier().unwrap().completed_passes == passes + && progressive.film.partial_frontier().unwrap().updated_prefix == prefix + && task.pending.is_none() + { + return; + } + let was_empty = task.pending.is_none(); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + record_partial_primary(task, was_empty, rays); + } + panic!("real task did not reach requested committed frontier"); +} +fn finish_partial_snapshot(task: &mut ImageTask) -> (Vec, Vec, u32, u64) { + let paid = task.work.used(); + for _ in 0..200_000 { + let poll = task.step_with_partial_previews(1).unwrap(); + assert_eq!(task.work.used(), paid, "prepaid resolve/encode must not debit the job twice"); + match poll { + PartialImagePoll::Pending(_) => {} + PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix } => return (png, covered, completed_passes, updated_prefix), + PartialImagePoll::Complete(_) => panic!("partial snapshot must not become a final frame"), + } + } + panic!("bounded partial snapshot did not finish"); +} +fn finish_partial_final(task: &mut ImageTask, partial: bool, rays: &mut PartialRayLog) -> (Vec, Vec<[u64; 3]>) { + let target = task.visibility_owner.options().progressive.unwrap().samples_per_pixel; + let mut bits = None; + for _ in 0..1_000_000 { + if bits.is_none() + && let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.samples() == target + { + bits = Some( + (0..task.request.width as usize * task.request.height as usize) + .map(|index| progressive.film.pixel(index).unwrap().0.map(f64::to_bits)) + .collect(), + ); + } + let was_empty = task.pending.is_none(); + let complete = if partial { + match task.step_with_partial_previews(1).unwrap() { + PartialImagePoll::Pending(_) => None, + PartialImagePoll::Complete(png) => Some(png), + PartialImagePoll::Preview { .. } => panic!("producer created an unrequested partial snapshot"), + } + } else { + match task.step_with_previews(1).unwrap() { + ImagePoll::Pending(_) | ImagePoll::Preview { .. } => None, + ImagePoll::Complete(png) => Some(png), + } + }; + record_partial_primary(task, was_empty, rays); + if let Some(png) = complete { + return (png, bits.expect("uniform target film must exist before final resolution")); + } + } + panic!("partial/control final did not finish"); +} + +#[test] +fn partial_real_film_png_distinguishes_unknown_miss_hit_and_known_black() { + let mut task = partial_four_pixel_task(5, 123, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + assert!(task.partial_preview_ready(plan).unwrap()); + let before = task.work.used(); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + assert_eq!(task.work.used(), before + plan.snapshot_work().unwrap()); + let (png, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix, task.pixel), (0, 2, 2)); + assert_eq!(covered, [1, 0, 0, 0]); + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (4, 1)); + assert_eq!(image.get_pixel(0, 0).0, [213, 0, 0, 255], "linear red2 -> Reinhard2/3 -> sRGB213"); + assert_eq!(image.get_pixel(1, 0).0, [10, 20, 30, 255], "observed miss is the captured backplate"); + assert_eq!(image.get_pixel(2, 0).0, [0, 0, 0, 0]); + assert_eq!(image.get_pixel(3, 0).0, [0, 0, 0, 0]); + + reach_partial_frontier(&mut task, 1, 0, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (png, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix, task.pixel), (1, 0, 4), "snapshot retains the sentinel until the normal charged transition"); + assert_eq!(covered, [1, 0, 1, 0]); + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(2, 0).0, [0, 0, 0, 255], "known black is opaque, not Unknown"); + assert_eq!(image.get_pixel(3, 0).0, [10, 20, 30, 255]); +} + +#[test] +fn partial_snapshots_preserve_interior_cursor_absolute_rays_and_final_bits() { + for seed in [0, 123] { + let mut task = partial_four_pixel_task(5, seed, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + let mut actual_rays = Vec::new(); + for (passes, prefix) in [(0, 1), (0, 3), (1, 0)] { + reach_partial_frontier(&mut task, passes, prefix, &mut actual_rays); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(task.pixel, if prefix == 0 { 4 } else { prefix }); + } + let actual = finish_partial_final(&mut task, true, &mut actual_rays); + let mut control = partial_four_pixel_task(5, seed, false); + let mut control_rays = Vec::new(); + let expected = finish_partial_final(&mut control, false, &mut control_rays); + assert_eq!(actual, expected, "final PNG and linear film bits must be exact"); + assert_eq!(actual_rays, control_rays, "snapshot timing cannot replay a camera pixel or ordinal"); + assert_eq!(actual_rays.len(), 20); + } +} + +#[test] +fn partial_work_preflight_is_optional_and_successful_debit_is_once() { + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + for enough in [false, true] { + let mut task = partial_four_pixel_task(5, 123, true); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let before = task.work.used(); + let cost = plan.snapshot_work().unwrap(); + task.work.limit = before + cost - u64::from(!enough); + if enough { + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + assert_eq!(task.work.used(), before + cost); + let _ = finish_partial_snapshot(&mut task); + assert_eq!( + task.step_with_partial_previews(1).err().unwrap().code, + ErrorCode::LimitExceeded, + "accepted presentation does not promise future trace headroom" + ); + } else { + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Exhausted)); + assert_eq!(task.work.used(), before); + assert_eq!(task.pixel, 2); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(task.progressive.as_ref().unwrap().partial.is_none()); + assert!(task.encoder.is_none() && task.pixels.is_empty()); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + } + } +} + +#[test] +fn partial_ready_requires_actual_safe_commit_plan_and_new_represented_state() { + let mut task = partial_four_pixel_task(5, 123, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + assert!(!task.partial_preview_ready(plan).unwrap()); + let mut observed_pending = false; + for _ in 0..200_000 { + let _ = task.step_with_partial_previews(1).unwrap(); + if !task.pending.is_none() { + assert!(!task.partial_preview_ready(plan).unwrap()); + let used = task.work.used(); + assert!(task.begin_partial_preview(plan).is_err()); + assert_eq!(task.work.used(), used); + observed_pending = true; + break; + } + } + assert!(observed_pending, "test must observe a real in-flight primary pixel"); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(task.partial_preview_ready(job::PartialPreviewPlan::new(8, 1).unwrap()).is_err()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert!(!task.partial_preview_ready(plan).unwrap(), "same frontier cannot be a fresh snapshot"); + + use crate::film::primary::PartialFrontier; + let reduced = job::PartialPreviewPlan::new(4096, 1).unwrap(); + let old = PartialFrontier { completed_passes: 0, updated_prefix: 1, pixels: 4096 }; + assert!(!progressive::represented_changed(reduced, Some(old), PartialFrontier { updated_prefix: 4, ..old }).unwrap()); + assert!(progressive::represented_changed(reduced, Some(old), PartialFrontier { updated_prefix: 5, ..old }).unwrap()); +} + +#[test] +fn partial_cancel_before_resolve_or_during_encoding_never_emits_payload() { + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + for during_encoding in [false, true] { + let mut task = partial_four_pixel_task(5, 123, true); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let paid = task.work.used(); + if during_encoding { + for _ in 0..20 { + if task.encoder.is_some() { + break; + } + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + } + assert!(task.encoder.is_some()); + } + task.cancel.cancel(); + assert_eq!(task.step_with_partial_previews(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.work.used(), paid, "there is no refund or second partial-stage debit"); + assert!(!task.done); + } +} + +#[test] +fn partial_reduced_resolve_is_bounded_by_display_cells_and_admission_is_not_legacy_prepay() { + let fixed = fixture(1, 1, None); + let mut options = fixed.visibility_owner.options().clone(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 5, seed: 123 }); + let mut request = fixed.request.clone(); + request.width = 1500; + request.raytrace = Some(options.clone()); + let plan = job::PartialPreviewPlan::new(1500, 1).unwrap(); + let first = admit_with_partial_preview(fixed.visibility_owner.source(), &request, &options, false, plan).unwrap(); + options.progressive.as_mut().unwrap().samples_per_pixel = 9; + request.raytrace = Some(options.clone()); + let second = admit_with_partial_preview(fixed.visibility_owner.source(), &request, &options, false, plan).unwrap(); + assert_eq!(first.estimated_total_bytes, second.estimated_total_bytes, "streaming reserves two slots, not every legacy power2 image"); + let (fixture_scene, _) = fixed.visibility_owner.into_capture(); + let mut task = + ImageTask::new_with_environment_and_nested_and_partial(fixture_scene, request, CancelToken::default(), options, None, false, plan).unwrap(); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let paid = task.work.used(); + let mut output = None; + let mut steps = 0_u64; + for _ in 0..2000 { + steps += 1; + match task.step_with_partial_previews(1).unwrap() { + PartialImagePoll::Pending(_) => {} + PartialImagePoll::Preview { png, covered, .. } => { + output = Some((png, covered)); + break; + } + PartialImagePoll::Complete(_) => panic!("display resolve cannot complete the final"), + } + assert_eq!(task.work.used(), paid); + } + let (png, covered) = output.expect("bounded reduced snapshot"); + assert_eq!(steps, plan.pixels() + u64::from(plan.height()) + 2); + assert_eq!(covered.len() as u64, plan.pixels()); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1)); + assert_eq!((task.request.width, task.request.height), (1500, 1)); + assert_eq!(task.pixel, 1); +} + +#[test] +fn partial_area_first_pass_and_final_preserve_all_existing_emitter_sample_counts() { + for area_samples in [1, 4, 16, 64] { + let source = progressive_area_fixture(area_samples, 5, 23, true); + let plan = job::PartialPreviewPlan::new(source.request.width, source.request.height).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + None, + false, + plan, + ) + .unwrap(); + reach_partial_frontier(&mut task, 1, 0, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (first, _, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (1, 0)); + let (actual, _) = finish_partial_final(&mut task, true, &mut Vec::new()); + let (legacy_previews, expected, _) = progressive_complete(source, 1); + assert_eq!(first, legacy_previews[0].1); + assert_eq!(actual, expected, "area source normalization/sampler must remain unchanged"); + } +} + +fn partial_original_hdr() -> crate::lighting::environment_input::EnvironmentInput { + use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec(); + for _ in 0..8 { + bytes.extend_from_slice(&[128, 128, 128, 129]); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap() +} + +#[test] +fn partial_hdr_rough_reflection_first_pass_and_final_match_legacy_sampling() { + let base = fixture(1, 1, Some(true)); + let mut scene = base.visibility_owner.source().clone(); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.8, 0.4, 0.2), 1.0, 0.35, 1.5).unwrap()); + let mut options = base.visibility_owner.options().clone(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 5, seed: 23 }); + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let plan = job::PartialPreviewPlan::new(request.width, request.height).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + Some(partial_original_hdr()), + false, + plan, + ) + .unwrap(); + let control = ImageTask::new_with_environment(scene, request, CancelToken::default(), options, Some(partial_original_hdr())).unwrap(); + reach_partial_frontier(&mut task, 1, 0, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (first, _, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (1, 0)); + let (actual, _) = finish_partial_final(&mut task, true, &mut Vec::new()); + let (legacy_previews, expected, _) = progressive_complete(control, 1); + assert_eq!(first, legacy_previews[0].1); + assert_eq!(actual, expected, "HDR and rough-reflection sample identity cannot depend on presentation"); +} + +#[test] +fn partial_full_pass_snapshot_preserves_regular_transition_work_and_final_ledger() { + let mut task = partial_four_pixel_task(5, 123, true); + let mut control = partial_four_pixel_task(5, 123, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + let mut actual_rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut actual_rays); + reach_partial_frontier(&mut control, 1, 0, &mut control_rays); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert_eq!(frontier, control.progressive.as_ref().unwrap().film.partial_frontier().unwrap()); + assert_eq!((task.pixel, control.pixel), (4, 4)); + let before = control.work.used(); + assert_eq!(task.work.used(), before); + let cost = plan.snapshot_work().unwrap(); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (_, _, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix, task.pixel), (1, 0, 4), "snapshot may not consume the ordinary pass transition"); + assert_eq!(task.work.used(), before + cost); + assert_eq!(control.work.used(), before); + assert!(!task.partial_preview_ready(plan).unwrap(), "unchanged frontier remains coalesced"); + + // The host hashes without stepping this task. On the next producer step, + // BOTH tasks owe the same ordinary pass-transition debit before a new ray. + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert!(matches!(control.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert_eq!((task.pixel, control.pixel), (0, 0)); + assert!(task.pending.is_none() && control.pending.is_none()); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(control.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(control.work.used(), before + 1, "the no-snapshot control owes the regular transition tick"); + assert_eq!(task.work.used(), before + cost + 1, "the snapshot must preserve that same tick in addition to W"); + + let actual = finish_partial_final(&mut task, true, &mut actual_rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected, "same partial policy: final PNG and linear film bits are exact"); + assert_eq!(actual_rays, control_rays, "presentation cannot replay or skip a primary sample"); + assert_eq!(actual_rays.len(), 20); + assert_eq!(task.work.used(), control.work.used() + cost, "the complete-job optional cost is exactly W, not W-1"); +} + +fn protected_plan(task: &ImageTask) -> job::ProtectedPreviewPlan { + job::ProtectedPreviewPlan::new( + task.request.width, + task.request.height, + task.visibility_owner.options().progressive.unwrap().samples_per_pixel, + task.visibility_owner.options().budget, + ) + .unwrap() +} +fn protected_rebuild(source: &ImageTask, input: Option) -> ImageTask { + ImageTask::new_with_environment_and_nested_and_protected_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + input, + false, + protected_plan(source), + ) + .unwrap() +} +fn shared_partial_rebuild(source: &ImageTask, input: Option) -> ImageTask { + ImageTask::new_with_environment_and_nested_and_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + input, + false, + protected_plan(source).preview_plan(), + ) + .unwrap() +} +fn empty_progressive_source() -> ImageTask { + let fixed = fixture(1, 1, None); + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: 64, seed: 123 }), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let request = ImageRequest { width: 32, height: 32, background: [10, 20, 30], raytrace: Some(options.clone()), ..fixed.request }; + let (fixture_scene, _) = fixed.visibility_owner.into_capture(); + ImageTask::new(fixture_scene, request, CancelToken::default(), options).unwrap() +} +fn initial_test_work(task: &mut ImageTask, ordinary: u64, protected: bool) { + assert_eq!(task.work.used(), 0, "test boundary is fixed BEFORE any real work, never mid-render"); + task.work = + if protected { WorkBudget::new_protected_for_test(protected_plan(task), ordinary).unwrap() } else { WorkBudget::new(ordinary).unwrap() }; +} +fn require_empty_final(png: &[u8], bits: &[[u64; 3]]) { + let image = ::image::load_from_memory(png).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (32, 32)); + assert!(image.pixels().all(|p| p.0 == [10, 20, 30, 255]), "independent all-miss backplate oracle"); + assert_eq!(bits.len(), 1024); + assert!(bits.iter().all(|p| *p == [0.0_f64.to_bits(); 3]), "no emitted or reflected radiance in the empty fixture"); +} + +#[test] +fn protected_actual_empty_counterexample_preserves_final_work_while_shared_cap_can_starve() { + let source = empty_progressive_source(); + let plan = protected_plan(&source); + assert_eq!((plan.total_commits(), plan.quota_limit(), plan.snapshot_work().unwrap()), (65536, 127, 79874)); + let mut reference = shared_partial_rebuild(&source, None); + let mut reference_rays = Vec::new(); + let expected = finish_partial_final(&mut reference, true, &mut reference_rays); + require_empty_final(&expected.0, &expected.1); + let ordinary = reference.work.used(); + assert!(ordinary > plan.snapshot_work().unwrap()); + + let mut control = shared_partial_rebuild(&source, None); + initial_test_work(&mut control, ordinary, false); + let actual = finish_partial_final(&mut control, true, &mut Vec::new()); + assert_eq!(actual, expected); + assert_eq!(control.work.used(), ordinary); + + let mut starved = shared_partial_rebuild(&source, None); + initial_test_work(&mut starved, ordinary, false); + reach_partial_frontier(&mut starved, 0, 1, &mut Vec::new()); + assert!(matches!(starved.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut starved); + let mut failure = None; + for _ in 0..1_000_000 { + match starved.step_with_partial_previews(1) { + Ok(PartialImagePoll::Pending(_)) => {} + Ok(PartialImagePoll::Complete(_)) => panic!("shared cap T cannot pay the same T ordinary work plus W"), + Ok(PartialImagePoll::Preview { .. }) => panic!("no unrequested snapshot"), + Err(error) => { + failure = Some(error.code); + break; + } + } + } + assert_eq!(failure, Some(ErrorCode::LimitExceeded)); + assert!(!starved.done); + assert!(starved.work.used() <= ordinary); + + for request_snapshot in [false, true] { + let mut task = protected_rebuild(&source, None); + initial_test_work(&mut task, ordinary, true); + let mut rays = Vec::new(); + if request_snapshot { + reach_partial_frontier(&mut task, 0, 1, &mut rays); + let before = task.protected_preview_report().unwrap(); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + let paid = task.protected_preview_report().unwrap(); + assert_eq!(paid.ordinary_used, before.ordinary_used); + assert_eq!((paid.presentation_used, paid.accepted_snapshots), (79874, 1)); + } + let actual = finish_partial_final(&mut task, true, &mut rays); + assert_eq!(actual, expected, "protected feedback cannot change PNG or linear film"); + assert_eq!(rays, reference_rays, "absolute pixel/ordinal/ray sequence is identical"); + assert_eq!(rays.len(), 65536); + let report = task.protected_preview_report().expect("actual report survives completed-film destruction"); + assert_eq!(report.ordinary_used, ordinary); + let optional = if request_snapshot { 79874 } else { 0 }; + assert_eq!(report.presentation_used, optional); + assert_eq!(task.work.used(), ordinary + optional); + assert_eq!(report.aggregate_limit, ordinary + plan.presentation_limit().unwrap()); + assert!(task.done && task.progressive.is_none()); + } +} + +#[test] +fn protected_real_milestone_wait_is_not_exhaustion_or_a_debit() { + let source = empty_progressive_source(); + let mut task = protected_rebuild(&source, None); + let plan = protected_plan(&task); + let preview = plan.preview_plan(); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(preview).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + let before = task.protected_preview_report().unwrap(); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let cursor = task.pixel; + assert!(plan.milestone(before.next_milestone_index).unwrap() > 2); + for _ in 0..4 { + assert!(!task.partial_preview_ready(preview).unwrap()); + assert_eq!(task.begin_partial_preview(preview).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(task.protected_preview_report().unwrap(), before); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(task.pixel, cursor); + assert!(task.encoder.is_none() && task.pixels.is_empty()); + assert!(task.progressive.as_ref().unwrap().partial.is_none()); + } + assert!(!before.quota_exhausted && !before.milestones_complete); + let milestone = plan.milestone(before.next_milestone_index).unwrap(); + reach_partial_frontier(&mut task, (milestone / 1024) as u32, (milestone % 1024) as usize, &mut Vec::new()); + assert!(task.partial_preview_ready(preview).unwrap(), "later real progress makes a temporary wait eligible"); +} + +#[test] +fn protected_real_coalesced_last_milestone_preserves_unspent_quota_and_final_priority() { + let source = partial_four_pixel_task(5, 123, true); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + reach_partial_frontier(&mut task, 4, 3, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + let coalesced = task.protected_preview_report().unwrap(); + assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 7, 7)); + assert!(coalesced.milestones_complete && !coalesced.quota_exhausted); + assert_eq!(coalesced.presentation_used, plan.snapshot_work().unwrap()); + assert!(coalesced.presentation_used < coalesced.presentation_limit); + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + let actual = finish_partial_final(&mut task, true, &mut rays); + let mut control_rays = Vec::new(); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected); + assert_eq!(rays, control_rays); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, control.work.used()); + assert_eq!(task.work.used(), control.work.used() + plan.snapshot_work().unwrap()); + assert!(task.done, "final never waits to spend unreachable/unused quota"); +} + +#[test] +fn protected_actual_every_pass_and_early_snapshots_exhaust_quota_without_failing_final() { + let source = empty_progressive_source(); + let mut control = shared_partial_rebuild(&source, None); + let expected = finish_partial_final(&mut control, true, &mut Vec::new()); + let ordinary = control.work.used(); + let mut task = protected_rebuild(&source, None); + initial_test_work(&mut task, ordinary, true); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + for index in 0..127 { + let milestone = plan.milestone(index).unwrap(); + reach_partial_frontier(&mut task, (milestone / 1024) as u32, (milestone % 1024) as usize, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.accepted_snapshots, index + 1); + assert_eq!(report.next_milestone_index, index + 1); + assert_eq!(report.presentation_used, u64::from(index + 1) * 79874); + } + let exhausted = task.protected_preview_report().unwrap(); + assert!(exhausted.quota_exhausted && exhausted.milestones_complete); + assert_eq!(exhausted.presentation_used, exhausted.presentation_limit); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let cursor = task.pixel; + for _ in 0..4 { + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Exhausted)); + assert_eq!(task.protected_preview_report().unwrap(), exhausted); + assert_eq!(task.pixel, cursor); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + } + let actual = finish_partial_final(&mut task, true, &mut rays); + assert_eq!(actual, expected); + require_empty_final(&actual.0, &actual.1); + assert_eq!(rays.len(), 65536); + let complete = task.protected_preview_report().unwrap(); + assert_eq!(complete.ordinary_used, ordinary); + assert_eq!(task.work.used(), complete.aggregate_limit, "O reaches its full original T and V exactly Q"); + assert_eq!(complete.presentation_used, 127 * 79874); +} + +#[test] +fn protected_full_pass_snapshot_keeps_the_ordinary_transition_tick_and_report_after_complete() { + let source = partial_four_pixel_task(5, 123, true); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut rays); + reach_partial_frontier(&mut control, 1, 0, &mut control_rays); + let before = task.protected_preview_report().unwrap(); + assert_eq!(before.ordinary_used, control.work.used()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!((task.pixel, control.pixel), (4, 4)); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert!(matches!(control.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert_eq!((task.pixel, control.pixel), (0, 0)); + let after = task.protected_preview_report().unwrap(); + assert_eq!(after.ordinary_used, before.ordinary_used + 1); + assert_eq!(after.ordinary_used, control.work.used()); + assert_eq!(after.presentation_used, plan.snapshot_work().unwrap()); + let actual = finish_partial_final(&mut task, true, &mut rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected); + assert_eq!(rays, control_rays); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, control.work.used()); + assert!(control.protected_preview_report().is_none(), "old IF1 has no protected report"); +} + +#[test] +fn protected_cancelled_begin_and_encoder_keep_the_actual_paid_report_without_refund() { + let source = partial_four_pixel_task(5, 123, true); + for debit_first in [false, true] { + let mut task = protected_rebuild(&source, None); + let plan = protected_plan(&task); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + let before = task.protected_preview_report().unwrap(); + if debit_first { + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + for _ in 0..20 { + if task.encoder.is_some() { + break; + } + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + } + assert!(task.encoder.is_some()); + } + let paid = task.protected_preview_report().unwrap(); + task.cancel.cancel(); + let code = if debit_first { + task.step_with_partial_previews(1).err().unwrap().code + } else { + task.begin_partial_preview(plan.preview_plan()).err().unwrap().code + }; + assert_eq!(code, ErrorCode::Cancelled); + assert_eq!(task.protected_preview_report().unwrap(), paid); + assert_eq!(paid.ordinary_used, before.ordinary_used); + assert_eq!(paid.presentation_used, if debit_first { plan.snapshot_work().unwrap() } else { 0 }); + assert_eq!(paid.accepted_snapshots, u32::from(debit_first)); + assert_eq!(paid.next_milestone_index, u32::from(debit_first)); + } +} + +#[test] +fn protected_admission_matches_actual_source_sampling_budget_before_constructing_the_task() { + let source = partial_four_pixel_task(5, 123, true); + let plan = protected_plan(&source); + let protected = + admit_with_protected_partial_preview(source.visibility_owner.source(), &source.request, source.visibility_owner.options(), false, plan) + .unwrap(); + let shared = + admit_with_partial_preview(source.visibility_owner.source(), &source.request, source.visibility_owner.options(), false, plan.preview_plan()) + .unwrap(); + assert_eq!( + protected.estimated_total_bytes, shared.estimated_total_bytes, + "same two slots and source/codec buffers; fixed task layout guard stays required" + ); + for wrong in [ + job::ProtectedPreviewPlan::new(8, 1, 5, source.visibility_owner.options().budget).unwrap(), + job::ProtectedPreviewPlan::new(4, 1, 3, source.visibility_owner.options().budget).unwrap(), + job::ProtectedPreviewPlan::new(4, 1, 5, job::CpuBudget::Studio).unwrap(), + ] { + assert_eq!( + admit_with_protected_partial_preview(source.visibility_owner.source(), &source.request, source.visibility_owner.options(), false, wrong) + .err() + .unwrap() + .code, + ErrorCode::InvalidRequest + ); + assert_eq!( + ImageTask::new_with_environment_and_nested_and_protected_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + None, + false, + wrong + ) + .err() + .unwrap() + .code, + ErrorCode::InvalidRequest + ); + } + assert_eq!(source.visibility_owner.options().emissions.as_ref().unwrap().len(), 1, "original fixture authors one red surface emission"); + let task = protected_rebuild(&source, None); + let report = task.protected_preview_report().unwrap(); + assert_eq!( + (report.ordinary_used, report.presentation_used, report.accepted_snapshots, report.next_milestone_index), + (1, 0, 0, 0), + "one authored emission owes one ordinary construction tick before the first camera sample" + ); + assert_eq!(report.aggregate_limit, plan.aggregate_limit().unwrap()); +} + +#[test] +fn protected_area_and_hdr_reflection_preserve_ordinary_work_absolute_rays_and_final_pixels() { + for area_samples in [1, 4, 16, 64] { + let source = progressive_area_fixture(area_samples, 5, 23, true); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(finish_partial_final(&mut task, true, &mut rays), finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, control.work.used()); + assert_eq!(task.work.used(), control.work.used() + plan.snapshot_work().unwrap()); + } + let mut source = progressive_fixture(5, 23, Some(true), 0.0); + let (mut fixture_scene, fixture_options) = source.visibility_owner.into_capture(); + fixture_scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.8, 0.4, 0.2), 1.0, 0.35, 1.5).unwrap()); + source.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, fixture_options); + let mut task = protected_rebuild(&source, Some(partial_original_hdr())); + let mut control = shared_partial_rebuild(&source, Some(partial_original_hdr())); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(finish_partial_final(&mut task, true, &mut rays), finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, control.work.used()); + assert_eq!(task.work.used(), control.work.used() + plan.snapshot_work().unwrap()); +} + +#[test] +fn protected_real_sampling_is_independent_of_quantum_and_feedback_schedule() { + for seed in [0, 123] { + let source = partial_four_pixel_task(5, seed, true); + let mut control = shared_partial_rebuild(&source, None); + let expected = finish_partial_final(&mut control, true, &mut Vec::new()); + let ordinary = control.work.used(); + for quantum in [1, 2, 4] { + let mut task = protected_rebuild(&source, None); + let plan = protected_plan(&task); + let mut snapshots = 0_u32; + let mut output = None; + let mut bits = None; + for _ in 0..200_000 { + if bits.is_none() + && let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.samples() == 5 + { + bits = Some((0..4).map(|i| progressive.film.pixel(i).unwrap().0.map(f64::to_bits)).collect::>()); + } + if snapshots < 3 && task.partial_preview_ready(plan.preview_plan()).unwrap() { + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + snapshots += 1; + } + match task.step_with_partial_previews(quantum).unwrap() { + PartialImagePoll::Pending(_) => {} + PartialImagePoll::Complete(png) => { + output = Some(png); + break; + } + PartialImagePoll::Preview { .. } => panic!("no snapshot was requested in this continuation"), + } + } + assert!(snapshots > 0, "actual safe frontiers must be observed in this original fixture"); + assert_eq!(output.unwrap(), expected.0); + assert_eq!(bits.unwrap(), expected.1); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, ordinary); + assert_eq!(report.accepted_snapshots, snapshots); + assert_eq!(report.presentation_used, u64::from(snapshots) * plan.snapshot_work().unwrap()); + assert_eq!(task.work.used(), ordinary + report.presentation_used); + } + } +} + +#[test] +fn protected_real_one_and_two_camera_commit_jobs_finish_with_exact_zero_or_one_snapshot() { + for samples in [1, 2] { + let source = progressive_fixture(samples, 123, None, 0.0); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + assert_eq!(plan.quota_limit(), samples - 1); + if samples == 1 { + let initial = task.protected_preview_report().unwrap(); + assert!(initial.quota_exhausted && initial.milestones_complete); + assert_eq!(initial.presentation_limit, 0); + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + } else { + reach_partial_frontier(&mut task, 1, 0, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(task.pixel, 1, "normal complete-pass transition remains pending"); + } + assert_eq!(finish_partial_final(&mut task, true, &mut rays), finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.accepted_snapshots, samples - 1); + assert_eq!(report.presentation_used, u64::from(samples - 1) * plan.snapshot_work().unwrap()); + assert_eq!(report.ordinary_used, control.work.used()); + assert!(report.quota_exhausted && report.milestones_complete); + } +} + +// Original progressive optics / presentation combinations. WRITTEN, NOT RUN. +fn optical_partial_source(samples: u32) -> (ProductScene, ImageRequest, RaytraceOptions) { + let (scene, mut request, options) = super::tests::progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, samples); + request.width = 2; + (scene, request, options) +} + +#[test] +fn protected_optical_partial_contains_only_whole_drained_camera_trees() { + let (scene, request, options) = optical_partial_source(3); + let plan = job::ProtectedPreviewPlan::new(2, 1, 3, options.budget).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + None, + false, + plan, + ) + .unwrap(); + let mut control = + ImageTask::new_with_environment_and_nested_and_partial(scene, request, CancelToken::default(), options, None, false, plan.preview_plan()) + .unwrap(); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + let mut saw_interior = false; + for _ in 0..100_000 { + let was_empty = task.pending.is_none(); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + record_partial_primary(&task, was_empty, &mut rays); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.medium.is_some()) { + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap().updated_prefix, 0); + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + saw_interior = true; + break; + } + } + assert!(saw_interior); + reach_partial_frontier(&mut task, 0, 1, &mut rays); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert!(task.optical.first().unwrap().pending.is_none()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let ordinary = task.protected_preview_report().unwrap().ordinary_used; + let (_, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (0, 1)); + assert_eq!(covered, [1, 0], "second pixel is Unknown, never a fabricated optical sample"); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, ordinary); + let actual = finish_partial_final(&mut task, true, &mut rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected, "exact final PNG and linear film bits with observer on/off"); + assert_eq!(rays, control_rays); + assert_eq!(rays.len(), 6); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, control.work.used()); + assert_eq!(report.presentation_used, plan.snapshot_work().unwrap()); +} + +#[test] +fn protected_optical_snapshot_cancellation_cannot_emit_or_commit_another_sample() { + let (scene, request, options) = optical_partial_source(3); + let plan = job::ProtectedPreviewPlan::new(2, 1, 3, options.budget).unwrap(); + let mut task = + ImageTask::new_with_environment_and_nested_and_protected_partial(scene, request, CancelToken::default(), options, None, false, plan).unwrap(); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let report = task.protected_preview_report().unwrap(); + task.cancel.cancel(); + assert_eq!(task.step_with_partial_previews(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(task.protected_preview_report().unwrap(), report); + assert!(!task.done); +} + +fn with_unit_optical_sheet(source: &ImageTask) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut scene = source.visibility_owner.source().clone(); + let mut options = source.visibility_owner.options().clone(); + // Original two-triangle rectangle between camera and receiver. It is + // index-matched and lossless: the independent control has no sheet at all. + scene.meshes.push(ProductMesh { + transmission: None, + name: "Progressive optical sheet".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 2.0), Vec3::new(20.0, -20.0, 2.0), Vec3::new(20.0, 20.0, 2.0), Vec3::new(-20.0, 20.0, 2.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + options.dielectrics.push(job::DielectricOptions { + body_index: scene.meshes.len() - 1, + body_name: "Progressive optical sheet".into(), + boundary: job::DielectricBoundary::ThinSheet, + ior: 1.0, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + }); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds())); + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; + (scene, request, options) +} + +#[test] +fn progressive_unit_optics_rejoin_real_area_consumers_at_every_admitted_sample_count() { + for count in [1, 4, 16, 64] { + for seed in [0, 23] { + // Conservative opaque shadow visibility is deliberately off. This + // feature does not invent transmitted illumination or caustics. + let source = progressive_area_fixture(count, 3, seed, false); + let (scene, request, options) = with_unit_optical_sheet(&source); + let optical = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let expected = progressive_complete(source, 1); + let actual = progressive_complete(optical, 4); + assert_eq!(actual.0, expected.0); + assert_eq!(actual.1, expected.1, "unit transmission preserves independently lit receiver; count={count}, seed={seed}"); + assert!(actual.2 > expected.2, "real optical traversal is charged, never bypassed"); + } + } +} + +#[test] +fn progressive_unit_optics_rejoin_hdr_receiver_and_preserve_feedback_film_and_seed() { + let mut source = progressive_area_fixture(4, 3, 23, false); + let (fixture_scene, mut fixture_options) = source.visibility_owner.into_capture(); + fixture_options.area_lights = None; + fixture_options.area_samples = None; + fixture_options.seed = None; + source.request.raytrace = Some(fixture_options.clone()); + source.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, fixture_options); + let (scene, request, options) = with_unit_optical_sheet(&source); + let plan = job::ProtectedPreviewPlan::new(1, 1, 3, options.budget).unwrap(); + let mut observed = ImageTask::new_with_environment_and_nested_and_protected_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + Some(partial_original_hdr()), + false, + plan, + ) + .unwrap(); + let mut control = ImageTask::new_with_environment_and_nested_and_partial( + scene, + request, + CancelToken::default(), + options, + Some(partial_original_hdr()), + false, + plan.preview_plan(), + ) + .unwrap(); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut observed, 1, 0, &mut rays); + assert!(matches!(observed.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let (snapshot, covered, passes, prefix) = finish_partial_snapshot(&mut observed); + assert_eq!((passes, prefix), (1, 0)); + assert_eq!(covered, [1]); + let actual = finish_partial_final(&mut observed, true, &mut rays); + assert_eq!(actual, finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + assert_eq!(observed.protected_preview_report().unwrap().ordinary_used, control.work.used()); + let without_sheet = ImageTask::new_with_environment( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + Some(partial_original_hdr()), + ) + .unwrap(); + let expected = progressive_complete(without_sheet, 1); + assert_eq!(snapshot, expected.0[0].1); + assert_eq!(actual.0, expected.1); +} + +#[test] +fn protected_deep_identity_shells_preserve_partial_final_rays_film_and_real_work() { + for absorbing in [false, true] { + let (scene, mut request, options) = super::tests::straight_identity_shells_source(8, true, absorbing); + request.width = 2; // orthographic X range[-16,16] remains inside innermost[-17,17]. + let plan = job::ProtectedPreviewPlan::new(2, 1, 3, options.budget).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + None, + true, + plan, + ) + .unwrap(); + let mut control = + ImageTask::new_with_environment_and_nested_and_partial(scene, request, CancelToken::default(), options, None, true, plan.preview_plan()) + .unwrap(); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 0, 1, &mut rays); + assert!(task.optical.first().unwrap().pending.is_none()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let ordinary = task.protected_preview_report().unwrap().ordinary_used; + let (_, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (0, 1)); + assert_eq!(covered, [1, 0]); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, ordinary); + let actual = finish_partial_final(&mut task, true, &mut rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected, "exact final PNG and film bits with optional observation"); + assert_eq!(rays, control_rays); + assert_eq!(rays.len(), 6); + let linear = super::tests::straight_shells_expected_linear(8, absorbing); + let expected_pixel = super::tests::straight_expected_pixel(linear); + for rgb in &actual.1 { + for (value, physical) in rgb.iter().copied().map(f64::from_bits).zip(linear) { + assert!((value - physical).abs() < 1e-11); + } + } + let image = ::image::load_from_memory(&actual.0).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, expected_pixel); + assert_eq!(image.get_pixel(1, 0).0, expected_pixel); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, control.work.used()); + assert_eq!(report.presentation_used, plan.snapshot_work().unwrap()); + } +} + +#[test] +fn every_cpu_pass_seven_has_exact_short_job_pngs_across_worker_quanta() { + let run = progressive_complete(progressive_fixture(7, 123, Some(true), 0.0), 1); + assert_eq!(run.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6]); + assert_eq!(run, progressive_complete(progressive_fixture(7, 123, Some(true), 0.0), 16_384)); + for (samples, png) in &run.0 { + assert_eq!(png, &progressive_complete(progressive_fixture(*samples, 123, Some(true), 0.0), 3).1); + } +} + +#[test] +fn every_cpu_pass_area_sample_keys_preserve_history_and_separate_high_ordinal_blocks() { + for (pixel, ordinal, spatial, primary, expected) in [ + (0_u64, 4095_u32, 0_u8, 1_u8, 0x4152_4541_5341_b2a0_u64), + (0, 4096, 0, 1, 0x8000_0000_1000_0000), + (1, 4096, 0, 1, 0x8000_0010_1000_0000), + (0, 4096, 0, 4, 0x8000_0000_1000_4000), + (0, 4096, 3, 4, 0x8000_0000_1000_4c00), + (0, 1_048_575, 15, 16, 0x8000_000f_ffff_bc00), + (67_108_863, 1_048_575, 15, 16, 0xbfff_ffff_ffff_bc00), + ] { + assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); + } + for pixel in [0_u64, 1, 67_108_863] { + for primary in [1_u8, 4, 16] { + for spatial in 0..primary { + for ordinal in [0_u32, 1, 63, 4095] { + let expected = if primary == 1 && ordinal == 0 { + pixel + } else { + (pixel * 65_536 + u64::from(ordinal) * 16 + u64::from(spatial)) ^ 0x4152_4541_5341_4d50 + }; + assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); + } + for ordinal in [4096_u32, 65_535, 65_536, 1_048_575] { + let mode = match primary { + 1 => 0_u64, + 4 => 1, + 16 => 2, + _ => unreachable!(), + }; + let expected = (1_u64 << 63) | (pixel << 36) | (u64::from(ordinal) << 16) | (mode << 14) | (u64::from(spatial) << 10); + assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); + assert_eq!(expected & 1023, 0); + assert_ne!( + area_sample_key(pixel, spatial, primary, ordinal).unwrap(), + area_sample_key(pixel, spatial, primary, ordinal % 4096).unwrap() + ); + } + } + } + } + assert!(area_sample_key(u64::MAX, 0, 1, 1).is_err()); + assert!(area_sample_key(0, 0, 1, 1_048_576).is_err()); + assert!(area_sample_key(1_u64 << 26, 0, 1, 4096).is_err()); + let mut states = std::collections::BTreeSet::new(); + for pixel in [0_u64, 67_108_863] { + for ordinal in [4096_u32, 65_535, 1_048_575] { + for light in 0..4_u64 { + for sample in 0..64_u64 { + let key = area_sample_key(pixel, 0, 1, ordinal).unwrap(); + let state = key.checked_add(u64::from(u32::MAX) * 65_537 + light * 104_729 + sample * 8191).unwrap(); + assert_ne!(state & (1_u64 << 63), 0); + assert!(states.insert(state), "initial RNG states, not generated UVs, stay distinct"); + } + } + } + } +} + +#[test] +fn every_cpu_pass_display_uses_full_u32_coverage_without_saturation() { + assert_eq!(composite_spatial(Vec3::ZERO, 65_536, 65_536, [13, 27, 41], 0.0).unwrap(), [0, 0, 0, 255]); + assert_eq!(composite_spatial(Vec3::ZERO, 0, 65_536, [13, 27, 41], 0.0).unwrap(), [13, 27, 41, 255]); + assert!(composite_spatial(Vec3::ZERO, 65_537, 65_536, [13, 27, 41], 0.0).is_err()); +} + +#[test] +#[cfg(target_pointer_width = "64")] +fn every_cpu_pass_actual_65536_film_resolves_one_u32_snapshot_and_unique_final() { + let source = fixture(1, 1, None); + let mut options = source.visibility_owner.options().clone(); + options.budget = job::CpuBudget::Workstation; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 65_537, seed: 123 }); + let plan = job::ProtectedPreviewPlan::new(1, 1, 65_537, job::CpuBudget::Workstation).unwrap(); + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; + let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( + source.visibility_owner.source().clone(), + request, + CancelToken::default(), + options, + None, + false, + plan, + ) + .unwrap(); + let mut reached = false; + for _ in 0..2_000_000 { + if task.progressive.as_ref().is_some_and(|state| state.film.ready() && state.film.samples() == 65_536) + && task.partial_preview_ready(plan.preview_plan()).unwrap() + { + reached = true; + break; + } + assert!(matches!(task.step_with_partial_previews(16_384).unwrap(), PartialImagePoll::Pending(_))); + } + assert!(reached); + let (linear, covered, count) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!(linear, [0.0; 3]); + assert_eq!((covered, count), (0, 65_536)); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let (png, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!(covered, [0]); + assert_eq!((passes, prefix), (65_536, 0)); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); + let report = task.protected_preview_report().unwrap(); + assert_eq!((report.accepted_snapshots, report.next_milestone_index), (1, 65_536)); + assert_eq!(report.presentation_used, 65_552); + let (final_png, bits) = finish_partial_final(&mut task, true, &mut Vec::new()); + assert_eq!(::image::load_from_memory(&final_png).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); + assert_eq!(bits, [[0.0_f64.to_bits(); 3]]); + assert!(task.done && task.progressive.is_none()); +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/progressive.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/progressive.rs new file mode 100644 index 000000000..339fd21ca --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/progressive.rs @@ -0,0 +1,95 @@ +//! Deterministic counter sampling and owned camera-film continuation. +//! No target sample count, work quantum or preview cadence enters the sampler. + +use crate::{film::primary::PrimaryFilm, job::CpuProgressiveOptions}; + +pub(super) struct Progressive { + pub film: PrimaryFilm, + pub options: CpuProgressiveOptions, + pub resolving: bool, + pub resolve_pixel: usize, + pub partial_plan: Option, + pub partial: Option, + pub last_partial: Option, +} + +pub(super) struct PartialResolve { + pub plan: crate::job::PartialPreviewPlan, + pub frontier: crate::film::primary::PartialFrontier, + pub resume_pixel: usize, + pub next: usize, + pub covered: Vec, +} + +/// Read-only O(1) test for new represented data; no scan over the source film. +/// A completed global pass is meaningful even if its last source pixels are +/// not representatives: the receiver's global Unknown authority changes then. +pub(super) fn represented_changed( + plan: crate::job::PartialPreviewPlan, + before: Option, + now: crate::film::primary::PartialFrontier, +) -> crate::job::Result { + use crate::job::{ErrorCode, JobError}; + plan.validate()?; + let source_pixels = u64::from(plan.source_width()) * u64::from(plan.source_height()); + if u64::try_from(now.pixels).ok() != Some(source_pixels) || now.updated_prefix >= now.pixels { + return Err(JobError::new(ErrorCode::InvalidScene, "partial film frontier differs from its source plan")); + } + let Some(before) = before else { return Ok(now.completed_passes != 0 || now.updated_prefix != 0) }; + if before.pixels != now.pixels + || before.completed_passes > now.completed_passes + || (before.completed_passes == now.completed_passes && before.updated_prefix > now.updated_prefix) + { + return Err(JobError::new(ErrorCode::InvalidScene, "partial film frontier went backwards")); + } + if before.completed_passes != now.completed_passes { + return Ok(true); + } + if before.updated_prefix == now.updated_prefix { + return Ok(false); + } + let w = u64::from(plan.source_width()); + let h = u64::from(plan.source_height()); + let pw = u64::from(plan.width()); + let ph = u64::from(plan.height()); + let lower = u64::try_from(before.updated_prefix).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial source index overflow"))?; + let x = lower % w; + let y = lower / w; + let mut v = y.checked_mul(ph).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial row mapping overflow"))?.div_ceil(h); + if v >= ph { + return Ok(false); + } + let mut u = if v * h / ph == y { + x.checked_mul(pw).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial column mapping overflow"))?.div_ceil(w) + } else { + 0 + }; + if u >= pw { + v += 1; + u = 0; + } + if v >= ph { + return Ok(false); + } + let display = + v.checked_mul(pw).and_then(|n| n.checked_add(u)).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial display index overflow"))?; + let display = usize::try_from(display).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial display address overflow"))?; + Ok(plan.source_index(display)? < now.updated_prefix) +} + +/// Integer-only mixing before conversion to exactly representable 53-bit unit +/// variates. Domains separate camera, BSDF and environment choices at each bounce. +pub(super) fn variates(seed: u32, pixel: u64, ordinal: u32, domain: u64) -> [f64; 2] { + fn mix(mut value: u64) -> u64 { + value ^= value >> 30; + value = value.wrapping_mul(0xbf58_476d_1ce4_e5b9); + value ^= value >> 27; + value = value.wrapping_mul(0x94d0_49bb_1331_11eb); + value ^ (value >> 31) + } + let key = mix(u64::from(seed) ^ 0x4350_5546_494c_4d00) + ^ mix(pixel.wrapping_add(0x9e37_79b9_7f4a_7c15)) + ^ mix(u64::from(ordinal).wrapping_add(0xd1b5_4a32_d192_ed03)) + ^ mix(domain.wrapping_add(0x94d0_49bb_1331_11eb)); + [0_u64, 1].map(|axis| (mix(key ^ mix(axis.wrapping_add(0x632b_e59b_d9b4_e019))) >> 11) as f64 / 9_007_199_254_740_992.0) +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/tests.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/tests.rs new file mode 100644 index 000000000..facf96f86 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/render/src/raytrace/tests.rs @@ -0,0 +1,455 @@ +use super::*; + +fn triangle(z: f64) -> Triangle { + Triangle::new([Vec3::new(0., 0., z), Vec3::new(2., 0., z), Vec3::new(0., 2., z)]).unwrap() +} +fn ray(origin: Vec3, direction: Vec3) -> Ray { + Ray::new(origin, direction, 0., 100.).unwrap() +} +fn build(triangles: Vec, limits: BuildLimits, chunk: usize) -> Bvh { + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(triangles, limits, &cancel).unwrap(); + while !builder.step(chunk, &cancel).unwrap().complete {} + builder.finish().unwrap() +} +fn closest(bvh: &Bvh, ray: &Ray) -> Option { + bvh.closest_hit(ray, &mut WorkBudget::new(MAX_WORK).unwrap(), &CancelToken::default()).unwrap() +} +fn brute(triangles: &[Triangle], ray: &Ray) -> Option { + let mut best: Option = None; + for (primitive_index, triangle) in triangles.iter().enumerate() { + if let Some(geometry) = triangle.intersect(ray) + && best.is_none_or(|old| { + geometry.distance < old.geometry.distance || (geometry.distance == old.geometry.distance && primitive_index < old.primitive_index) + }) + { + best = Some(Hit { primitive_index, geometry }); + } + } + best +} +fn close(actual: f64, expected: f64) { + assert!((actual - expected).abs() <= 1e-12 * expected.abs().max(f64::MIN_POSITIVE), "{actual} != {expected}"); +} + +#[test] +fn ray_admission_normalizes_without_overflow_or_tiny_vector_cutoff() { + for scale in [f64::from_bits(1), 1e-200, 1., 1e200, f64::MAX] { + let r = ray(Vec3::ZERO, Vec3::new(scale, 0., 0.)); + assert_eq!(r.direction(), Vec3::X); + assert_eq!(r.at(2.).unwrap(), Vec3::new(2., 0., 0.)); + } + for direction in [Vec3::ZERO, Vec3::new(f64::NAN, 0., 1.), Vec3::new(0., f64::INFINITY, 1.)] { + assert!(Ray::new(Vec3::ZERO, direction, 0., 1.).is_err()); + } + for (min, max) in [(-1., 1.), (2., 1.), (0., f64::INFINITY), (f64::NAN, 1.), (0., MAX_DISTANCE_MM.next_up())] { + assert!(Ray::new(Vec3::ZERO, Vec3::Z, min, max).is_err()); + } + assert!(Ray::new(Vec3::new(MAX_COORDINATE_MM.next_up(), 0., 0.), Vec3::Z, 0., 1.).is_err()); + assert!(ray(Vec3::ZERO, Vec3::Z).at(f64::NAN).is_err()); +} + +#[test] +fn analytic_triangle_distance_barycentrics_normal_and_two_sides() { + let t = triangle(0.); + let hit = t.intersect(&ray(Vec3::new(0.5, 0.5, 2.), -Vec3::Z)).unwrap(); + assert_eq!(hit.distance, 2.); + assert_eq!(hit.barycentric, [0.5, 0.25, 0.25]); + assert_eq!(hit.geometric_normal, Vec3::Z); + assert!(hit.front_face); + let back = t.intersect(&ray(Vec3::new(0.5, 0.5, -2.), Vec3::Z)).unwrap(); + assert_eq!(back.distance, 2.); + assert!(!back.front_face); + let boundary = Ray::new(Vec3::new(0.5, 0.5, 2.), -Vec3::Z, 2., 2.).unwrap(); + assert!(t.intersect(&boundary).is_some()); + assert!(t.intersect(&Ray::new(boundary.origin(), boundary.direction(), 0., 1.99).unwrap()).is_none()); + assert!(t.intersect(&ray(Vec3::new(2., 2., 2.), -Vec3::Z)).is_none()); +} + +#[test] +fn tiny_and_huge_geometry_have_no_fixed_world_epsilon() { + for scale in [1e-120, 1e-12, 1., 1e11] { + let t = Triangle::new([Vec3::ZERO, Vec3::X * (2. * scale), Vec3::Y * (2. * scale)]).unwrap(); + let r = Ray::new(Vec3::new(0.5 * scale, 0.5 * scale, 2. * scale), -Vec3::Z, 0., 4. * scale).unwrap(); + let hit = t.intersect(&r).unwrap(); + close(hit.distance, 2. * scale); + close(hit.barycentric[0], 0.5); + let bvh = build(vec![t], BuildLimits::default(), 1); + assert_eq!(closest(&bvh, &r).unwrap().geometry, hit); + } +} + +#[test] +fn shared_edges_vertices_and_equal_distance_use_lowest_input_ordinal() { + let a = Triangle::new([Vec3::ZERO, Vec3::X, Vec3::Y]).unwrap(); + let b = Triangle::new([Vec3::new(1., 1., 0.), Vec3::Y, Vec3::X]).unwrap(); + for triangles in [vec![a, b], vec![b, a], vec![a, a]] { + let bvh = build(triangles.clone(), BuildLimits { leaf_size: 1, ..Default::default() }, 1); + for point in [Vec3::new(0.5, 0.5, 1.), Vec3::new(1., 0., 1.)] { + let r = ray(point, -Vec3::Z); + assert_eq!(closest(&bvh, &r), brute(&triangles, &r)); + assert_eq!(closest(&bvh, &r).unwrap().primitive_index, 0); + } + } +} + +#[test] +fn degenerate_parallel_coplanar_and_grazing_cases_are_explicit() { + for vertices in [[Vec3::ZERO; 3], [Vec3::ZERO, Vec3::X, Vec3::X * 2.]] { + let t = Triangle::new(vertices).unwrap(); + assert!(t.geometric_normal().is_none()); + assert!(t.intersect(&ray(Vec3::new(0., 0., 1.), -Vec3::Z)).is_none()); + } + let t = triangle(0.); + assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 1.), Vec3::X)).is_none()); + assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 0.), Vec3::X)).is_none()); + let hit = t.intersect(&ray(Vec3::new(-1., 0.25, 1e-9), Vec3::new(1., 0., -1e-9))).unwrap(); + close(hit.distance, 1.); + assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 0.), Vec3::Z)).is_some(), "closed t=0 is a caller policy, not silently offset"); +} + +#[test] +fn slab_intervals_handle_signed_zero_boundaries_and_almost_parallel_components() { + let b = Bounds::new(Vec3::new(1., 1., 1.), Vec3::new(2., 2., 2.)).unwrap(); + assert_eq!(b.intersect(&ray(Vec3::new(1., 1., 0.), Vec3::new(-0., 0., 1.))), Some([1., 2.])); + assert!(b.intersect(&ray(Vec3::new(0., 1., 0.), Vec3::Z)).is_none()); + assert_eq!(b.intersect(&ray(Vec3::new(1.5, 1.5, 0.), Vec3::new(f64::from_bits(1), 0., 1.))), Some([1., 2.])); + assert!(b.intersect(&ray(Vec3::new(0., 1.5, 0.), Vec3::new(f64::from_bits(1), 0., 1.))).is_none()); + assert!(Bounds::new(Vec3::X, Vec3::ZERO).is_err()); + assert!(Bounds::new(Vec3::new(f64::NAN, 0., 0.), Vec3::X).is_err()); +} + +#[test] +fn builder_steps_are_bounded_and_results_do_not_depend_on_chunk_size() { + let triangles = (0..31).map(|i| triangle(f64::from(i))).collect::>(); + let cancel = CancelToken::default(); + let limits = BuildLimits { leaf_size: 1, ..Default::default() }; + let mut builder = BvhBuilder::new(triangles.clone(), limits, &cancel).unwrap(); + let mut used = 0; + loop { + let progress = builder.step(1, &cancel).unwrap(); + assert!(progress.work_used - used <= 1); + used = progress.work_used; + if progress.complete { + break; + } + } + let a = builder.finish().unwrap(); + let b = build(triangles.clone(), limits, MAX_BUILD_STEP); + assert_eq!(a.node_count(), b.node_count()); + assert!(a.node_count() < 2 * triangles.len()); + assert!(a.retained_bytes().unwrap() <= limits.max_memory_bytes); + for z in [0.5, 5.5, 50.] { + let r = ray(Vec3::new(0.5, 0.5, z), -Vec3::Z); + assert_eq!(closest(&a, &r), brute(&triangles, &r)); + assert_eq!(closest(&a, &r), closest(&b, &r)); + } +} + +#[test] +fn coincident_centroids_and_depth_cap_terminate_without_recursion() { + let triangles = vec![triangle(0.); 129]; + for depth in [1, MAX_DEPTH] { + let bvh = build(triangles.clone(), BuildLimits { max_depth: depth, leaf_size: 1, ..Default::default() }, 3); + let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z); + assert_eq!(closest(&bvh, &r), brute(&triangles, &r)); + assert_eq!(closest(&bvh, &r).unwrap().primitive_index, 0); + } +} + +#[test] +fn empty_scene_and_incomplete_build_are_distinct() { + let empty = build(Vec::new(), BuildLimits::default(), 1); + assert_eq!(empty.primitive_count(), 0); + assert_eq!(empty.node_count(), 0); + assert!(closest(&empty, &ray(Vec3::ZERO, Vec3::Z)).is_none()); + let builder = BvhBuilder::new(vec![triangle(0.)], BuildLimits::default(), &CancelToken::default()).unwrap(); + assert!(matches!(builder.finish(), Err(TraceError::BuildIncomplete))); +} + +#[test] +fn work_limit_is_an_error_not_a_partial_hit_and_can_span_many_rays() { + let bvh = build(vec![triangle(0.)], BuildLimits::default(), 1); + let cancel = CancelToken::default(); + let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z); + assert_eq!(bvh.closest_hit(&r, &mut WorkBudget::new(1).unwrap(), &cancel), Err(TraceError::WorkLimit)); + let mut work = WorkBudget::new(2).unwrap(); + assert!(bvh.any_hit(&r, &mut work, &cancel).unwrap()); + assert_eq!(work.used(), 2); + assert_eq!(work.remaining(), 0); + assert_eq!(bvh.any_hit(&r, &mut work, &cancel), Err(TraceError::WorkLimit)); + let mut builder = BvhBuilder::new(vec![triangle(0.); 20], BuildLimits { max_work: 1, ..Default::default() }, &cancel).unwrap(); + assert_eq!(builder.step(2, &cancel), Err(TraceError::WorkLimit)); +} + +#[test] +fn cancellation_covers_admission_mid_build_and_both_traversals() { + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(vec![triangle(0.); 20], BuildLimits::default(), &cancel).unwrap(); + builder.step(2, &cancel).unwrap(); + cancel.cancel(); + assert_eq!(builder.step(1, &cancel), Err(TraceError::Cancelled)); + assert!(matches!(BvhBuilder::new(vec![triangle(0.)], BuildLimits::default(), &cancel), Err(TraceError::Cancelled))); + let bvh = build(vec![triangle(0.)], BuildLimits::default(), 1); + let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z); + assert_eq!(bvh.closest_hit(&r, &mut WorkBudget::new(10).unwrap(), &cancel), Err(TraceError::Cancelled)); + assert_eq!(bvh.any_hit(&r, &mut WorkBudget::new(10).unwrap(), &cancel), Err(TraceError::Cancelled)); +} + +#[test] +fn memory_counts_input_capacity_and_hostile_limits_refuse_before_own_allocations() { + let defaults = BuildLimits::default(); + let normal = BvhBuilder::required_bytes(1, 1, defaults).unwrap(); + assert!(BvhBuilder::required_bytes(1, 100, defaults).unwrap() > normal); + assert_eq!(BvhBuilder::required_bytes(1, usize::MAX, defaults), Err(TraceError::MemoryLimit)); + assert_eq!(BvhBuilder::required_bytes(1, 1, BuildLimits { max_memory_bytes: 1, ..defaults }), Err(TraceError::MemoryLimit)); + for limits in [ + BuildLimits { max_depth: MAX_DEPTH + 1, ..defaults }, + BuildLimits { leaf_size: 0, ..defaults }, + BuildLimits { max_triangles: MAX_TRIANGLES + 1, ..defaults }, + BuildLimits { max_memory_bytes: MAX_MEMORY_BYTES + 1, ..defaults }, + BuildLimits { max_work: crate::job::MAX_CPU_WORK + 1, ..defaults }, + ] { + assert!(BvhBuilder::required_bytes(1, 1, limits).is_err()); + } + assert!(WorkBudget::new(0).is_err()); + let mut builder = BvhBuilder::new(vec![triangle(0.)], defaults, &CancelToken::default()).unwrap(); + assert!(builder.step(0, &CancelToken::default()).is_err()); + assert!(builder.step(MAX_BUILD_STEP + 1, &CancelToken::default()).is_err()); +} + +struct Seed(u64); +impl Seed { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + self.0 + } + fn scalar(&mut self) -> f64 { + (self.next() >> 11) as f64 / ((1_u64 << 53) as f64) + } + fn point(&mut self) -> Vec3 { + Vec3::new(self.scalar() * 20. - 10., self.scalar() * 20. - 10., self.scalar() * 20. - 10.) + } +} + +#[test] +fn seeded_bvh_vs_brute_force_closest_and_any_hit() { + let mut seed = Seed(0x1368_0001); + for _ in 0..16 { + let triangles = (0..64).map(|_| Triangle::new([seed.point(), seed.point(), seed.point()]).unwrap()).collect::>(); + let bvh = build(triangles.clone(), BuildLimits { leaf_size: 2, ..Default::default() }, 7); + for _ in 0..128 { + let r = ray(seed.point(), seed.point()); + let expected = brute(&triangles, &r); + assert_eq!(closest(&bvh, &r), expected); + let any = bvh.any_hit(&r, &mut WorkBudget::new(MAX_WORK).unwrap(), &CancelToken::default()).unwrap(); + assert_eq!(any, expected.is_some()); + } + } +} + +#[test] +fn seeded_hostile_float_admission_never_publishes_nonfinite_geometry() { + let mut seed = Seed(0x1368_badd); + for _ in 0..2048 { + let value = f64::from_bits(seed.next()); + let p = Vec3::new(value, 0., 0.); + let accepted = value.is_finite() && value.abs() <= MAX_COORDINATE_MM; + assert_eq!(Ray::new(p, Vec3::Z, 0., 1.).is_ok(), accepted); + assert_eq!(Triangle::new([p; 3]).is_ok(), accepted); + } +} + +#[test] +fn protected_ledger_keeps_ordinary_profiles_and_requires_the_explicit_new_envelope() { + use crate::job::{CpuBudget, MAX_CPU_WORK, MAX_PROTECTED_CPU_WORK, ProtectedPreviewPlan}; + assert_eq!(MAX_CPU_WORK, 16_000_000_000_000); + assert_eq!(MAX_PROTECTED_CPU_WORK, 31_462_813_335_678); + assert!(WorkBudget::new(MAX_CPU_WORK + 1).is_err()); + assert!(WorkBudget::new(MAX_PROTECTED_CPU_WORK).is_err()); + for budget in CpuBudget::ALL { + let plan = ProtectedPreviewPlan::new(1024, 1024, 2, budget).unwrap(); + let work = WorkBudget::new_protected(plan).unwrap(); + let report = work.protected_report().unwrap(); + assert_eq!(report.ordinary_limit, budget.limits().max_work_units); + assert_eq!(report.presentation_limit, 958_464_130); + assert_eq!(report.aggregate_limit, report.ordinary_limit + report.presentation_limit); + assert_eq!(work.remaining(), report.ordinary_limit); + assert_eq!(work.ordinary_remaining(), report.ordinary_limit); + assert_eq!(work.presentation_remaining(), report.presentation_limit); + assert_eq!(work.aggregate_remaining(), report.aggregate_limit); + assert_eq!((report.ordinary_used, report.presentation_used, work.used()), (0, 0, 0)); + } + let max = ProtectedPreviewPlan::new(1024, 1024, 2, CpuBudget::Workstation).unwrap(); + assert_eq!(max.aggregate_limit().unwrap(), MAX_CPU_WORK + 958_464_130); + assert!(WorkBudget::new(100).unwrap().protected_report().is_none()); + assert!(ProtectedPreviewPlan::new(u32::MAX, u32::MAX, u32::MAX, CpuBudget::Workstation).is_err()); +} + +#[test] +fn protected_ledger_exact_ordinary_and_aggregate_boundaries_do_not_steal_or_refund() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + let plan = ProtectedPreviewPlan::new(1, 1, 2, CpuBudget::Compact).unwrap(); + let cost = plan.snapshot_work().unwrap(); + let cancel = CancelToken::default(); + let mut work = WorkBudget::new_protected_for_test(plan, 7).unwrap(); + work.charge(6, &cancel).unwrap(); + assert!(work.charge_presentation(1, &cancel).unwrap()); + let before = work.protected_report().unwrap(); + assert_eq!((before.ordinary_used, before.presentation_used), (6, cost)); + assert_eq!(work.remaining(), 1, "presentation did not consume the last ordinary tick"); + assert_eq!(work.presentation_remaining(), 0); + assert_eq!(work.aggregate_remaining(), 1); + assert_eq!(work.charge(2, &cancel), Err(TraceError::WorkLimit)); + assert_eq!(work.protected_report().unwrap(), before); + work.tick(&cancel).unwrap(); + let complete = work.protected_report().unwrap(); + assert_eq!((complete.ordinary_used, complete.presentation_used, work.used()), (7, cost, 7 + cost)); + assert_eq!(work.aggregate_remaining(), 0); + assert_eq!(work.charge(u64::MAX, &cancel), Err(TraceError::WorkLimit)); + assert!(!work.charge_presentation(1, &cancel).unwrap()); + assert_eq!(work.protected_report().unwrap(), complete); +} + +#[test] +fn protected_milestones_coalesce_without_fabricating_accepted_snapshots_or_spent_quota() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + let plan = ProtectedPreviewPlan::new(4, 1, 5, CpuBudget::Compact).unwrap(); + let mut work = WorkBudget::new_protected(plan).unwrap(); + let initial = work.protected_report().unwrap(); + assert!(!work.charge_presentation(0, &CancelToken::default()).unwrap()); + assert_eq!(work.protected_report().unwrap(), initial); + assert!(work.charge_presentation(19, &CancelToken::default()).unwrap()); + let coalesced = work.protected_report().unwrap(); + assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 7, 7)); + assert_eq!(coalesced.presentation_used, plan.snapshot_work().unwrap()); + assert!(coalesced.presentation_used < coalesced.presentation_limit); + assert!(coalesced.milestones_complete); + assert!(!coalesced.quota_exhausted); + for progress in [19, 20, u64::MAX] { + assert!(!work.protected_ready(progress).unwrap()); + assert!(!work.charge_presentation(progress, &CancelToken::default()).unwrap()); + assert_eq!(work.protected_report().unwrap(), coalesced); + } +} + +#[test] +fn protected_zero_and_one_milestone_policies_are_real_boundaries() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + let cancel = CancelToken::default(); + let zero = ProtectedPreviewPlan::new(1, 1, 1, CpuBudget::Compact).unwrap(); + let mut work = WorkBudget::new_protected(zero).unwrap(); + let report = work.protected_report().unwrap(); + assert_eq!((report.quota_limit, report.presentation_limit), (0, 0)); + assert_eq!(report.aggregate_limit, report.ordinary_limit); + assert!(report.quota_exhausted && report.milestones_complete); + assert!(!work.charge_presentation(0, &cancel).unwrap()); + assert!(zero.milestone(0).is_err()); + let one = ProtectedPreviewPlan::new(1, 1, 2, CpuBudget::Compact).unwrap(); + assert_eq!(one.quota_limit(), 1); + assert_eq!(one.milestone(0).unwrap(), 1); + assert!(one.milestone(1).is_err()); + let mut work = WorkBudget::new_protected(one).unwrap(); + assert!(!work.charge_presentation(0, &cancel).unwrap()); + assert!(work.charge_presentation(1, &cancel).unwrap()); + assert!(work.protected_report().unwrap().quota_exhausted); +} + +#[test] +fn protected_quota_exhaustion_leaves_the_entire_ordinary_allowance_available() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap(); + let cancel = CancelToken::default(); + let mut work = WorkBudget::new_protected_for_test(plan, 17).unwrap(); + for index in 0..127 { + assert!(work.charge_presentation(plan.milestone(index).unwrap(), &cancel).unwrap()); + } + let exhausted = work.protected_report().unwrap(); + assert_eq!((exhausted.accepted_snapshots, exhausted.next_milestone_index), (127, 127)); + assert_eq!(exhausted.presentation_used, exhausted.presentation_limit); + assert!(exhausted.quota_exhausted && exhausted.milestones_complete); + assert_eq!(work.ordinary_remaining(), 17); + assert!(!work.charge_presentation(plan.total_commits() - 1, &cancel).unwrap()); + work.charge(17, &cancel).unwrap(); + let final_report = work.protected_report().unwrap(); + assert_eq!(work.used(), final_report.aggregate_limit); + assert_eq!(final_report.ordinary_used, 17); +} + +#[test] +fn protected_cancel_before_debit_is_atomic_and_after_debit_is_never_refunded() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + let plan = ProtectedPreviewPlan::new(4, 1, 5, CpuBudget::Compact).unwrap(); + let mut work = WorkBudget::new_protected(plan).unwrap(); + let before = work.protected_report().unwrap(); + let cancelled = CancelToken::default(); + cancelled.cancel(); + assert_eq!(work.charge_presentation(1, &cancelled), Err(TraceError::Cancelled)); + assert_eq!(work.protected_report().unwrap(), before); + let cancel = CancelToken::default(); + assert!(work.charge_presentation(1, &cancel).unwrap()); + let paid = work.protected_report().unwrap(); + cancel.cancel(); + assert_eq!(work.tick(&cancel), Err(TraceError::Cancelled)); + assert_eq!(work.charge_presentation(2, &cancel), Err(TraceError::Cancelled)); + assert_eq!(work.protected_report().unwrap(), paid); + assert_eq!(work.used(), plan.snapshot_work().unwrap()); +} + +#[test] +fn protected_private_test_boundary_is_chosen_before_work_and_never_changes_the_production_plan() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + let plan = ProtectedPreviewPlan::new(4, 1, 5, CpuBudget::Compact).unwrap(); + assert!(WorkBudget::new_protected_for_test(plan, 0).is_err()); + assert!(WorkBudget::new_protected_for_test(plan, plan.ordinary_limit() + 1).is_err()); + let mut first = WorkBudget::new_protected(plan).unwrap(); + first.charge_presentation(19, &CancelToken::default()).unwrap(); + let paid = first.protected_report().unwrap(); + // A distinct admitted job starts a new ledger; it does not restore/transfer + // any state in the first job. Repeated report reads do not reset either one. + let second = WorkBudget::new_protected(plan).unwrap(); + for _ in 0..4 { + assert_eq!(first.protected_report().unwrap(), paid); + } + assert_eq!(second.protected_report().unwrap().presentation_used, 0); + assert_eq!(first.protected_report().unwrap(), paid); +} + +#[test] +fn protected_reached_milestones_match_literal_small_and_first_pass_boundaries() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + for (pixels, samples, cases) in [ + (1, 1, vec![(0, 0), (1, 0)]), + (1, 7, vec![(0, 0), (1, 1), (5, 5), (6, 6), (7, 6)]), + (2, 4, vec![(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 3), (6, 4), (7, 4), (8, 4)]), + (3, 4, vec![(0, 0), (1, 1), (2, 2), (3, 3), (4, 3), (5, 3), (6, 4), (8, 4), (9, 5), (11, 5), (12, 5)]), + (65, 3, vec![(0, 0), (63, 63), (64, 64), (65, 65), (129, 65), (130, 66), (194, 66), (195, 66)]), + (66, 3, vec![(0, 0), (64, 63), (65, 64), (66, 65), (131, 65), (132, 66), (197, 66), (198, 66)]), + (67, 3, vec![(0, 0), (65, 63), (66, 64), (67, 65), (133, 65), (134, 66), (200, 66), (201, 66)]), + ] { + let plan = ProtectedPreviewPlan::new(pixels, 1, samples, CpuBudget::Compact).unwrap(); + for (committed, expected) in cases { + assert_eq!(plan.reached_milestones(committed).unwrap(), expected, "P={pixels} S={samples} c={committed}"); + } + assert!(plan.reached_milestones(plan.total_commits() + 1).is_err()); + assert!(plan.reached_milestones(u64::MAX).is_err()); + } +} + +#[test] +fn protected_large_delayed_frontier_coalesces_once_without_allocating_a_film_or_spending_ordinary_work() { + use crate::job::{CpuBudget, ProtectedPreviewPlan}; + let plan = ProtectedPreviewPlan::new(1, 1, 1_048_576, CpuBudget::Workstation).unwrap(); + assert_eq!(plan.quota_limit(), 1_048_575); + assert_eq!(plan.reached_milestones(65_536).unwrap(), 65_536); + assert_eq!(plan.reached_milestones(1_048_575).unwrap(), 1_048_575); + assert_eq!(plan.reached_milestones(1_048_576).unwrap(), 1_048_575); + let mut work = WorkBudget::new_protected_for_test(plan, 17).unwrap(); + assert!(work.charge_presentation(1_048_575, &CancelToken::default()).unwrap()); + let report = work.protected_report().unwrap(); + assert_eq!((report.accepted_snapshots, report.next_milestone_index), (1, 1_048_575)); + assert_eq!(report.presentation_used, 65_552); + assert_eq!(report.ordinary_used, 0); + assert_eq!(work.ordinary_remaining(), 17); + assert!(report.milestones_complete && !report.quota_exhausted); +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace.rs new file mode 100644 index 000000000..79676f33e --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace.rs @@ -0,0 +1,2502 @@ +//! Integrated product preview. Shares the installed device/pipelines, not Design's scene policy. + +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use egui::{Color32, Sense}; +use serde_json::json; +use solidcraft_engine::doc::render_settings::RenderSetup; +#[cfg(test)] +use solidcraft_engine::render::job::LightingPreset; +use solidcraft_engine::render::job::{ImageHost, Integrator, JobId, PartialPreviewInfo, PreviewInfo, ProtectedPreviewReport, RaytraceOptions}; +use solidcraft_engine::render::{ + Availability, Camera, ExecutorDescriptor, ExecutorId, ProductScene, RenderLimits, RenderMode, RenderOperation, RenderProfile, RenderRequest, + ScratchLayout, +}; + +use crate::gpu::{Frame, GpuScene, SceneSlot, ViewportCallback}; +use crate::{SolveApp, theme::Tokens}; + +// Vertex payload only, not an OS/GPU peak-memory promise. Native viewport +// uploads are already chunked by the installed device's buffer limit. +const MAX_GEOMETRY_BYTES: usize = + if cfg!(all(not(target_arch = "wasm32"), target_pointer_width = "64")) { 512 * 1024 * 1024 } else { 128 * 1024 * 1024 }; + +#[path = "render_workspace_ribbon.rs"] +mod ribbon; + +#[path = "render_workspace_cpu.rs"] +mod cpu; + +#[path = "render_workspace_hdr.rs"] +mod hdr; + +#[path = "render_workspace_effects.rs"] +mod effects; +#[path = "render_workspace_environment.rs"] +mod environment; +#[path = "render_workspace_inspector.rs"] +mod inspector; + +#[path = "render_workspace_interactive.rs"] +pub(crate) mod interactive; + +#[path = "render_workspace_library.rs"] +mod library; + +#[path = "render_ui/assign.rs"] +pub(crate) mod assign; +#[path = "render_workspace_light.rs"] +pub(crate) mod light; + +#[path = "render_workspace_materials.rs"] +mod materials; + +#[path = "render_workspace_setups.rs"] +mod setups; + +#[path = "render_workspace_shot.rs"] +pub(crate) mod shot; + +#[path = "render_workspace_shots.rs"] +pub(crate) mod shots; + +#[path = "render_ui/scene.rs"] +pub(crate) mod scene; + +#[path = "render_workspace_studio.rs"] +mod studio; +#[path = "render_workspace_transport.rs"] +mod transport; + +#[path = "render_workspace_thumbnails.rs"] +mod thumbnails; +#[path = "render_ui/wear.rs"] +mod wear; + +/// The browser's preview budget: WebGPU and WebGL share the tab's memory, so it stays small. +const WEB_GEOMETRY_BYTES: u64 = 128 * 1024 * 1024; +/// Desktop: at most this many of the device's largest buffers of geometry... +const DESKTOP_GEOMETRY_BUFFERS: u64 = 8; +/// ...and never more than this, whatever the device allows. +const DESKTOP_GEOMETRY_CEILING: u64 = 2 * 1024 * 1024 * 1024; + +/// The product preview's geometry budget for a device whose largest buffer is `max_buffer_size` +/// bytes (`wgpu::Device::limits`, what the device was created with). Uploads are split into +/// buffers of at most that size, so the budget bounds memory, not a single buffer: 2 GiB on a +/// device with the standard 256 MiB buffers. An allocation the device still refuses is caught +/// by the upload's error scope and reported, not a crash. +pub(crate) fn geometry_budget(max_buffer_size: u64, web: bool) -> u64 { + if web { WEB_GEOMETRY_BYTES } else { max_buffer_size.saturating_mul(DESKTOP_GEOMETRY_BUFFERS).min(DESKTOP_GEOMETRY_CEILING) } +} + +/// Apply the saved compatibility preference to the device-derived budget. +fn preferred_geometry_budget(device_budget: u64, previous: bool) -> u64 { + if previous { MAX_GEOMETRY_BYTES as u64 } else { device_budget } +} + +fn admit_geometry(bytes: u64, budget: u64) -> Result<(), String> { + if bytes > budget { + return Err(format!( + "Render preview needs {:.1} MiB of geometry; the limit is {:.1} MiB. Hide bodies in Design, then return to Render and try again.", + bytes as f64 / 1048576.0, + budget as f64 / 1048576.0 + )); + } + Ok(()) +} + +/// The message when the device refused the preview's geometry. +fn upload_refusal(bytes: u64, error: &str) -> String { + format!( + "The graphics device could not hold the Render preview's {:.1} MiB of geometry ({error}). Hide bodies in Design, then return to Render and try again.", + bytes as f64 / 1048576.0 + ) +} + +#[cfg(test)] +#[path = "render_workspace_tests.rs"] +mod tests; + +type PathFactory = Box Result + Send>; + +pub struct State { + thumbnails: thumbnails::Cache, + pending_setup: Option, + pub host: Option, + pub path_host: PathHost, + /// How long the last path tracer setup took, in seconds, per viewport adapter + /// ([`adapter_key`]); kept in the preferences to estimate the next one. + pub setup_seconds: std::collections::BTreeMap, + /// The viewport adapter the current setup runs on. + pub setup_key: Option, + pub geometry_budget: u64, + /// A GPU error the preview's last geometry upload caught. + pub upload_error: crate::gpu::UploadError, + pub image_host: Option, + pub view: ViewState, + interactive: interactive::State, + revision: u64, + design_camera: Option<(Camera, bool)>, + slot: SceneSlot, + key: Option, + scene_signature: Option<(u64, usize, u64, u64)>, + scene: Option, + scene_error: Option, + preview_upload_bytes: Option, + image: Option<(solidcraft_engine::render::job::JobId, Result)>, + image_info: Option, + preview_image: Option, + final_partial: Option, + final_partial_request: Option<(JobId, Duration)>, + final_feedback_clock: Duration, + final_feedback_report: Option<(JobId, ProtectedPreviewReport)>, + clipboard_image: Option, + clipboard_text: Option, +} + +/// Provisional pixels are never an export source and never replace the retained final image. +struct PreviewImage { + info: PreviewInfo, + image: Result, +} + +struct FinalPartialImage { + info: PartialPreviewInfo, + sampling: interactive::PartialSampling, + image: Result, +} + +struct DisplayImage<'a> { + info: &'a solidcraft_engine::render::job::FrameInfo, + image: &'a Result, + preview: Option<&'a PreviewInfo>, + partial: Option<(&'a PartialPreviewInfo, interactive::PartialSampling)>, + logical_size: [u32; 2], +} + +impl DisplayImage<'_> { + fn provisional(&self) -> bool { + self.preview.is_some() || self.partial.is_some() + } +} + +/// Application-wide setup, retained across document changes. The worker owns a +/// cloned adapter and initializes the job device; the UI receives the finished host. +#[derive(Default)] +pub enum PathHost { + #[default] + NotStarted, + /// The worker's answer, and when it started: shader compilation can take minutes. + Preparing(std::sync::mpsc::Receiver>, std::time::Instant), + Ready(ImageHost), + Failed(String), +} + +impl PathHost { + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn start(&mut self, create: impl FnOnce() -> Result + Send + 'static) { + if !matches!(self, Self::NotStarted) { + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + // Dropping the handle detaches: neither startup nor shutdown joins a driver + // that may spend minutes compiling or warming up its pipelines. + *self = match std::thread::Builder::new().name("gpu-path-setup".into()).spawn(move || { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(create)) + .unwrap_or_else(|_| Err(crate::i18n::tr("render.error_setup_panicked").into())); + let _ = tx.send(result); + }) { + Ok(_) => Self::Preparing(rx, std::time::Instant::now()), + Err(e) => Self::failed(crate::i18n::format("render.error_setup_worker", &[("error", &e.to_string())])), + }; + } + + fn failed(message: String) -> Self { + log::warn!("progressive render unavailable: {message}"); + Self::Failed(message) + } + + /// Take the worker's answer if it has come; returns how long a successful setup took. + fn poll(&mut self) -> Option { + let Self::Preparing(rx, started) = self else { return None }; + let took = started.elapsed(); + *self = match rx.try_recv() { + Ok(Ok(host)) => Self::Ready(host), + Ok(Err(error)) => Self::failed(error), + Err(std::sync::mpsc::TryRecvError::Empty) => return None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Self::failed(crate::i18n::tr("render.error_setup_stopped").into()), + }; + matches!(self, Self::Ready(_)).then_some(took) + } +} + +/// The samples slider's top end: 2^12 = 4096 samples per pixel. +#[cfg(test)] +const MAX_SAMPLES_EXPONENT: u32 = 12; + +/// Setup times kept per adapter, at most. +const MAX_SETUP_TIMES: usize = 16; + +/// The key [`State::setup_seconds`] files an adapter's setup time under: a driver update +/// usually empties the driver's shader cache, so the driver is part of it. +pub fn adapter_key(info: &egui_wgpu::wgpu::AdapterInfo) -> String { + format!("{} | {:?} | {} {}", info.name.trim(), info.backend, info.driver.trim(), info.driver_info.trim()) +} + +/// Remember how long the setup on `key` took, for the next start's estimate. +fn record_setup(state: &mut State, took: std::time::Duration) { + let Some(key) = state.setup_key.clone() else { return }; + if state.setup_seconds.len() >= MAX_SETUP_TIMES && !state.setup_seconds.contains_key(&key) { + return; + } + state.setup_seconds.insert(key, took.as_secs_f64()); +} + +/// Setup times from the preferences: finite, non-negative and at most a day each. +pub fn load_setup_seconds(value: &serde_json::Value) -> std::collections::BTreeMap { + value + .as_object() + .into_iter() + .flatten() + .filter_map(|(k, v)| Some((k.clone(), v.as_f64().filter(|s| s.is_finite() && (0.0..=86_400.0).contains(s))?))) + .take(MAX_SETUP_TIMES) + .collect() +} + +/// Minutes and seconds, as `1:05`. +fn mmss(d: std::time::Duration) -> String { + let s = d.as_secs(); + format!("{}:{:02}", s / 60, s % 60) +} + +/// The path tracer's setup as it goes: a progress bar estimated from the last setup on this +/// adapter, else a spinner with the time so far. Drivers report no progress of their own. +fn setup_progress(ui: &mut egui::Ui, app: &SolveApp, started: std::time::Instant) { + let elapsed = started.elapsed(); + let expected = app.render_workspace.setup_key.as_ref().and_then(|k| app.render_workspace.setup_seconds.get(k)).copied(); + ui.label(app.tr("render.gpu_path_preparing")); + match expected.map(|s| std::time::Duration::from_secs_f64(s.max(1.0))) { + Some(expected) if elapsed < expected.mul_f64(1.5) => { + let fraction = (elapsed.as_secs_f32() / expected.as_secs_f32()).min(0.99); + crate::ui_kit::progress(ui, "gpu_path_setup", fraction); + ui.label(format!("{} / ~{}", mmss(elapsed), mmss(expected))); + // The bar moves with time, so keep drawing while it is shown. + ui.ctx().request_repaint_after(std::time::Duration::from_millis(250)); + } + _ => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(mmss(elapsed)); + }); + if expected.is_none() { + ui.small(app.tr("render.gpu_path_first_setup")); + } + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Stage { + #[default] + Look, + Light, + Frame, + Output, +} +impl Stage { + pub(crate) const ALL: [Self; 4] = [Self::Look, Self::Light, Self::Frame, Self::Output]; + pub(crate) fn key(self) -> &'static str { + match self { + Self::Look => "look", + Self::Light => "light", + Self::Frame => "frame", + Self::Output => "output", + } + } + pub(crate) fn label(self) -> &'static str { + match self { + Self::Look => "render.stage_look", + Self::Light => "render.stage_light", + Self::Frame => "render.stage_frame", + Self::Output => "render.stage_output", + } + } + fn page(self) -> inspector::Page { + match self { + Self::Look => inspector::Page::Appearance, + Self::Light => inspector::Page::Lighting, + Self::Frame => inspector::Page::Camera, + Self::Output => inspector::Page::Output, + } + } +} + +/// Browser focus is transient per-document view state, never part of a saved design. +#[derive(Clone, Debug, Default, PartialEq)] +pub enum RenderSelection { + #[default] + Nothing, + Object(Vec), + Environment, + Wear, + Lighting, + /// Method/type/index identity until named light commands provide persistent IDs. + Light(String), + Shot(String), + Output, + Sampling, + Effects, + Check, +} + +/// Selection-driven homes introduced by E1/E7; remaining editors retain their adapters. +pub(crate) fn selection_editor(app: &mut SolveApp, selection: &RenderSelection) { + app.render_workspace.view.inspector.page = match selection { + RenderSelection::Nothing => inspector::Page::Scene, + RenderSelection::Shot(_) => inspector::Page::Camera, + RenderSelection::Output => inspector::Page::Output, + _ => return, + }; +} + +pub(crate) fn select_lighting(app: &mut SolveApp) { + app.render_workspace.view.inspector.page = inspector::Page::Lighting; +} + +/// Small per-document editor state; GPU uploads and host capabilities stay outside tabs. +#[derive(Clone, Debug)] +pub struct ViewState { + pub(crate) assign: assign::State, + pub(crate) frame: shot::Frame, + lights: light::View, + job_shot: Option, + save_shot_name: Option, + pub name: String, + pub selection: RenderSelection, + pub(crate) stage: Stage, + pub(crate) by_look: bool, + pub(crate) search_objects: bool, + pub(crate) object_query: String, + draft: RenderSetup, + dirty: bool, + clean_setup: Option, + job: Option, + completed: Option, + transparent: bool, + method: ImageMethod, + raytrace: RaytraceOptions, + samples: u32, + max_depth: u32, + seed: u32, + studio: studio::View, + materials: materials::View, + library: library::View, + inspector: inspector::View, + environment_ring: environment::RingView, + + cpu: cpu::View, + overwrite: bool, + result: bool, + result_camera: Camera, + result_scale: ResultScale, + result_job: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum ResultScale { + #[default] + Fit, + Actual, + Free, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum ImageMethod { + #[default] + Raster, + CpuRaytrace, + GpuRaytrace, +} + +impl ImageMethod { + fn label(self) -> &'static str { + match self { + Self::Raster => "render.method_raster", + Self::CpuRaytrace => "render.method_cpu", + Self::GpuRaytrace => "render.method_gpu", + } + } +} + +impl Default for ViewState { + fn default() -> Self { + Self { + assign: assign::State::default(), + lights: Default::default(), + job_shot: None, + frame: Default::default(), + save_shot_name: None, + name: "Studio".into(), + selection: RenderSelection::Nothing, + stage: Stage::Look, + by_look: false, + search_objects: false, + object_query: String::new(), + draft: RenderSetup::default(), + dirty: false, + clean_setup: None, + job: None, + completed: None, + transparent: false, + method: ImageMethod::Raster, + raytrace: RaytraceOptions::default(), + samples: 64, + max_depth: 8, + seed: 0, + studio: studio::View::default(), + materials: materials::View::default(), + library: library::View::default(), + inspector: inspector::View::default(), + environment_ring: environment::RingView::default(), + + cpu: cpu::View::default(), + overwrite: false, + result: false, + result_camera: Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, ..Default::default() }, + result_scale: ResultScale::Fit, + result_job: None, + } + } +} + +impl Default for State { + fn default() -> Self { + Self { + thumbnails: Default::default(), + host: None, + path_host: PathHost::default(), + pending_setup: None, + setup_seconds: Default::default(), + setup_key: None, + geometry_budget: WEB_GEOMETRY_BYTES, + upload_error: Arc::new(Mutex::new(None)), + image_host: None, + view: Default::default(), + interactive: Default::default(), + revision: u64::MAX, + design_camera: None, + slot: Arc::new(Mutex::new(None)), + key: None, + scene_signature: None, + scene: None, + scene_error: None, + preview_upload_bytes: None, + image: None, + image_info: None, + preview_image: None, + final_partial: None, + final_partial_request: None, + final_feedback_clock: Duration::ZERO, + final_feedback_report: None, + clipboard_image: None, + clipboard_text: None, + } + } +} + +impl State { + /// Retain the selected viewport adapter, but do not open another device or + /// compile shaders until GPU path tracing is selected in Render. Raster and + /// CPU image methods retain this factory without starting it. A later viewport + /// installation (for example safe-mode fallback) replaces only an unstarted factory. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn defer_path_host(&mut self, key: String, create: impl FnOnce() -> Result + Send + 'static) { + if matches!(self.path_host, PathHost::NotStarted) { + self.setup_key = Some(key); + self.pending_setup = Some(Box::new(create)); + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn start_deferred_path_host(&mut self) { + if self.view.method == ImageMethod::GpuRaytrace + && matches!(self.path_host, PathHost::NotStarted) + && let Some(create) = self.pending_setup.take() + { + self.path_host.start(create); + } + } +} + +pub fn active(app: &SolveApp) -> bool { + crate::workspace::render_tab(&app.ui.tab) +} + +pub(crate) fn result_active(app: &SolveApp) -> bool { + active(app) && app.render_workspace.view.result +} + +pub(crate) fn fit_result(app: &mut SolveApp) { + app.render_workspace.view.result_scale = ResultScale::Fit; +} + +/// Read-only identities for automation and diagnostics. Does not prepare a +/// request, open a device, evaluate geometry, change the selected result or pump +/// a job. Clients must use render.status for the exact identity returned here. +pub(crate) fn inspect_state(app: &SolveApp) -> serde_json::Value { + let view = &app.render_workspace.view; + let method = match view.method { + ImageMethod::Raster => "raster", + ImageMethod::CpuRaytrace => "cpu_raytrace", + ImageMethod::GpuRaytrace => "gpu_path", + }; + json!({ + "active": active(app), "stage": view.stage.key(), "setup": view.name, "draft_dirty": view.dirty, + "method": method, "job": view.job, "completed": view.completed, + "interactive": interactive::inspect(app), + "final_partial": app.render_workspace.final_partial.as_ref().map(|partial| &partial.info), + "final_feedback_report": app.render_workspace.final_feedback_report.map(|(job, report)| json!({"job":job,"report":report})), + "showing_result": view.result, "export_format": if view.studio.export_exr {"exr"} else {"png"}, + }) +} + +pub fn host_executor(max_dimension: u32, depth: bool, samples: u32) -> Result { + if !matches!(samples, 1 | 2 | 4 | 8 | 16) { + return Err(crate::i18n::tr("render.error_gpu_samples").into()); + } + Ok(ExecutorDescriptor { + id: ExecutorId::new("gpu-viewport").map_err(|e| e.to_string())?, + availability: if depth && max_dimension > 0 { + Availability::Available + } else { + Availability::Unavailable { reason: crate::i18n::tr("render.error_preview_device").into() } + }, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + formats: Vec::new(), + features: vec![solidcraft_engine::render::RenderFeature::Pbr], + }], + limits: RenderLimits { max_dimension: u64::from(max_dimension.clamp(1, 4096)), ..Default::default() }, + scratch: ScratchLayout { + sample_scale: 1, + sample_bytes_per_pixel: 8 * u64::from(samples), + output_bytes_per_pixel: 8, + encoding_bytes_per_pixel: 0, + }, + }) +} + +pub fn sync_backend(app: &mut SolveApp) { + #[cfg(not(target_arch = "wasm32"))] + if active(app) { + app.render_workspace.start_deferred_path_host(); + } + if let Some(took) = app.render_workspace.path_host.poll() { + record_setup(&mut app.render_workspace, took); + } + if let PathHost::Ready(host) = &app.render_workspace.path_host + && let Err(e) = app.session.register_render_job_host(host.clone()) + { + app.render_workspace.path_host = PathHost::failed(e.to_string()); + 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())) + { + app.set_status(e.to_string(), true); + } + if app.session.render_viewport() == app.render_workspace.host.as_ref() { + return; + } + if let Err(e) = app.session.set_render_viewport(app.render_workspace.host.clone()) { + app.set_status(e.to_string(), true); + } +} + +/// Cooperative work belongs to the frame loop, never to a status/control request. Keep +/// scheduling frames even after leaving Render so a browser job can finish in Design. +pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { + interactive::tick(app, ctx); + if let Some(text) = app.render_workspace.clipboard_text.take() { + ctx.copy_text(text); + } + if let Some(image) = app.render_workspace.clipboard_image.take() { + ctx.copy_image(image); + } + if matches!(app.render_workspace.path_host, PathHost::Preparing(..)) { + // Poll even in Design or an idle window, without continuously redrawing. + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + if let Some(host) = &app.render_workspace.image_host { + match host.pump(1024) { + Ok(true) => ctx.request_repaint(), + Ok(false) => {} + Err(e) => app.set_status(e.to_string(), true), + } + } + if app.render_workspace.view.job.is_some() { + cache_render_images(app, ctx); + } +} + +pub fn reset_document(app: &mut SolveApp) { + crate::render_ui::reset_shell(app); + app.ui.ribbon_context = None; + let host = app.render_workspace.host.clone(); + let image_host = app.render_workspace.image_host.clone(); + let geometry_budget = app.render_workspace.geometry_budget; + let path_host = std::mem::take(&mut app.render_workspace.path_host); + let setup_seconds = std::mem::take(&mut app.render_workspace.setup_seconds); + let setup_key = app.render_workspace.setup_key.take(); + let pending_setup = app.render_workspace.pending_setup.take(); + let mut interactive = std::mem::take(&mut app.render_workspace.interactive); + interactive.reset_document(); + app.render_workspace = + State { host, image_host, path_host, setup_seconds, setup_key, pending_setup, geometry_budget, interactive, ..Default::default() }; + if active(app) { + app.ui.tab = "MODEL".into(); + } + sync_backend(app); +} + +pub(crate) fn invalidate_images(app: &mut SolveApp) { + app.render_workspace.image = None; + app.render_workspace.image_info = None; + app.render_workspace.preview_image = None; + app.render_workspace.final_partial = None; +} + +pub fn invalidate_scene(app: &mut SolveApp) { + app.render_workspace.thumbnails = Default::default(); + app.render_workspace.revision = u64::MAX; + app.render_workspace.scene_signature = None; + app.render_workspace.scene = None; + app.render_workspace.scene_error = None; + app.render_workspace.preview_upload_bytes = None; + app.render_workspace.key = None; + if let Ok(mut slot) = app.render_workspace.slot.lock() { + *slot = None; + } +} + +pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> { + if render { + if app.session.active_sketch.is_some() || app.tool.is_some() || app.dialog.is_some() || app.file_load.busy() { + return Err(crate::i18n::tr("render.error_finish_operation").into()); + } + app.run("render.scene", json!({}))?; + if !active(app) { + app.render_workspace.design_camera = Some((app.cam, app.ui.perspective)); + app.ui.tab = "RENDER".into(); + select_stage(app, app.render_workspace.view.stage.key()); + if app.render_workspace.view.selection == RenderSelection::Nothing { + selection_editor(app, &RenderSelection::Nothing); + } + let scene = solidcraft_engine::product_scene::extract(&app.session).map_err(|e| e.to_string())?; + if !scene.bounds.is_empty() { + app.fit_bounds(scene.bounds); + } + } + setups::refresh_dirty(app); + if app.render_workspace.revision != app.session.revision && !app.render_workspace.view.dirty { + setups::load(app); + } + #[cfg(not(target_arch = "wasm32"))] + app.render_workspace.start_deferred_path_host(); + } else { + app.render_workspace.interactive.reset_document(); + assign::stop(app); + if let Some((camera, perspective)) = app.render_workspace.design_camera.take() { + app.cam = camera; + app.ui.up_axis = camera.up; + app.ui.perspective = perspective; + } + app.ui.tab = "MODEL".into(); + crate::render_ui::reset_shell(app); + } + app.viewport.hover = None; + app.cam_anim = None; + if !render { + app.pending_fit = None; + } + Ok(()) +} + +/// Stage navigation is transient per-document state. It never applies a resource or starts a job. +pub(crate) fn select_stage(app: &mut SolveApp, key: &str) { + let stage = match key { + "look" => Stage::Look, + "light" => Stage::Light, + "frame" => Stage::Frame, + "output" => Stage::Output, + _ => return, + }; + app.render_workspace.view.stage = stage; + app.render_workspace.view.inspector.hidden = false; + app.render_workspace.view.inspector.page = stage.page(); + let sections: &[&str] = match stage { + Stage::Look => &["objects"], + Stage::Light => &["lights", "environment"], + Stage::Frame => &["shots"], + Stage::Output => &[], + }; + for section in sections { + app.tree.collapsed.remove(&format!("render:tree:{section}")); + } + if stage == Stage::Look { + app.tree.collapsed.remove("c0"); + app.tree.collapsed.remove("c0/bodies"); + } +} + +pub(crate) fn switch_shot(app: &mut SolveApp, name: String) { + inspector::switch_shot(app, name); +} +pub(crate) fn stage_projection(app: &mut SolveApp, perspective: bool) -> Result<(), String> { + let mut camera = app.cam; + camera.fov = if perspective { 0.6 } else { 0.0 }; + inspector::apply_camera_draft(app, camera) +} + +pub(crate) fn output_summary(app: &SolveApp) -> (String, &'static str) { + let view = &app.render_workspace.view; + (format!("{} × {}", view.draft.width, view.draft.height), if view.studio.export_exr { "EXR" } else { "PNG" }) +} + +pub(crate) fn output_child_summary(app: &SolveApp, kind: &str) -> String { + let view = &app.render_workspace.view; + match kind { + "sampling" => format!( + "{} · {} spp", + app.tr("render.quality_custom"), + if view.method == ImageMethod::GpuRaytrace { + view.samples + } else { + view.raytrace.progressive.map_or(u32::from(view.raytrace.primary_samples), |p| p.samples_per_pixel) + } + ), + "effects" => crate::i18n::format( + "render.children.look_summary", + &[ + ("tone", if view.studio.tone_map == solidcraft_engine::render::job::ToneMap::AcesFitted { "ACES" } else { "Reinhard" }), + ("count", &view.studio.finishing.looks.len().to_string()), + ], + ), + "check" => inspector::check_summary(app), + _ => String::new(), + } +} + +pub(crate) fn job_busy(app: &SolveApp) -> bool { + ribbon::busy(app) +} +pub(crate) fn output_stage_tools(app: &mut SolveApp, ui: &mut egui::Ui) { + inspector::stage_tools(app, ui); +} + +pub(crate) fn job_ready(app: &SolveApp, id: &str) -> Result<(), String> { + ribbon::action_ready(app, id) +} + +pub(crate) fn set_inspector_visible(app: &mut SolveApp, visible: bool) { + app.render_workspace.view.inspector.hidden = !visible; +} + +pub fn panel(app: &mut SolveApp, ui: &mut egui::Ui) { + if crate::render_ui::focused(app) { + return; + } + inspector::panel(app, ui); +} + +/// Interactive stage-panel review. Direct engine JSON calls remain dialog-free. +/// S5 supplies its selected specification id without owning another consent form. +pub(crate) fn review_resource(app: &mut SolveApp, command: &str, id: &str) -> Result<(), String> { + match command { + "render.quality.prepare" => library::review::quality(app, id), + _ => Err("this command has no stage-panel review adapter".into()), + } +} + +pub(crate) fn apply_browser_controls(app: &mut SolveApp, value: &serde_json::Value) { + let view = &mut app.render_workspace.view; + if let Some(by_look) = value.get("by_look").and_then(serde_json::Value::as_bool) { + view.by_look = by_look; + } + if let Some(search) = value.get("search").and_then(serde_json::Value::as_bool) { + view.search_objects = search; + } + if let Some(query) = value.get("query").and_then(serde_json::Value::as_str) { + view.object_query = query.into(); + } +} + +/// Local Browser-card content, never a new workspace or an alternative model tree. +pub(crate) fn browser_mode(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + if !active(app) { + return false; + } + if app.render_workspace.view.search_objects { + let mut query = app.render_workspace.view.object_query.clone(); + crate::ui_kit::scope(ui, |ui| { + if crate::ui_kit::search_field(ui, ui.id().with("render:tree:query"), &mut query, crate::i18n::tr("render.tree_search")).changed() { + let _ = app.run("view.render_browser", json!({"query":query})); + } + }); + } + false +} + +/// Per-stage companion sharing the Browser's dock policy. +pub(crate) fn appearances_card(app: &mut SolveApp, ui: &mut egui::Ui, bounds: egui::Rect) { + library::card(app, ui, bounds); +} + +fn image_host(app: &SolveApp, method: ImageMethod) -> Result<&ImageHost, String> { + if method == ImageMethod::GpuRaytrace { + let host = match &app.render_workspace.path_host { + PathHost::Ready(host) => host, + PathHost::Failed(error) => return Err(error.clone()), + _ => return Err(app.tr("render.gpu_unavailable").to_string()), + }; + let descriptor = host.descriptor().map_err(|error| error.to_string())?; + if !host.is_available() + || !descriptor.profiles.iter().any(|profile| profile.features.contains(&solidcraft_engine::render::RenderFeature::Progressive)) + { + return Err(app.tr("render.gpu_unavailable").to_string()); + } + return Ok(host); + } + let host = app.session.render_job_host().ok_or_else(|| app.tr("render.image_host_missing").to_string())?; + host.validate_integrator(if method == ImageMethod::CpuRaytrace { Integrator::Raytrace } else { Integrator::Raster }) + .map_err(|error| error.to_string())?; + Ok(host) +} + +/// Check and Start use exactly this request, rebuilt at each click. The result camera is +/// temporarily installed only inside shared navigation; app.cam remains the product camera. +fn image_params(app: &SolveApp) -> Result { + let view = &app.render_workspace.view; + image_host(app, view.method)?; + if app.session.model.is_stale() { + return Err(app.tr("render.image_scene_stale").to_string()); + } + let mut request = image_request(app)?; + if view.method == ImageMethod::CpuRaytrace && view.raytrace.progressive.is_some() { + request + .as_object_mut() + .ok_or_else(|| app.tr("render.error_provisional_identity").to_string())? + .insert("progressive_feedback".into(), json!(true)); + } + Ok(request) +} + +/// Pure request construction is shared with offline setup editing; host checks stay above. +fn image_request(app: &SolveApp) -> Result { + light::filter_request(app, raw_image_request(app)?) +} + +fn raw_image_request(app: &SolveApp) -> Result { + cpu::validate_progressive_image(app)?; + if !setups::has_runtime_inputs(app) { + return Ok(json!({"settings":setups::snapshot(app)?})); + } + runtime_image_request(app, false) +} + +/// CPU Interactive skips final-dimension admission and the portable snapshot path. +/// The engine fits/admit/captures this complete runtime intent off the window. +fn interactive_request(app: &SolveApp) -> Result { + if app.render_workspace.view.method != ImageMethod::CpuRaytrace { + return Err(app.tr("render.interactive_requires_cpu").into()); + } + light::filter_request(app, runtime_image_request(app, true)?) +} + +/// The existing runtime branch, shared without changing Final Check/Start policy. +fn runtime_image_request(app: &SolveApp, interactive_cpu: bool) -> Result { + let view = &app.render_workspace.view; + // Temporary bindings and unsaved HDR captures use the runtime API. Embedded HDRs + // still resolve by their document resource ID when a temporary binding is present. + if !view.draft.surfaces.is_empty() { + return Err(app.tr("render.saved_maps_runtime_conflict").to_string()); + } + let settings = RenderSetup { camera: app.cam, job: None, ..view.draft.clone() }; + let mut params = json!({"settings":settings,"transparent_background":view.transparent}); + match view.method { + ImageMethod::Raster => {} + ImageMethod::CpuRaytrace => { + if view.transparent { + return Err(app.tr("render.cpu_opaque_required").to_string()); + } + if interactive_cpu { + cpu::params_interactive(app, &mut params)?; + } else { + cpu::params(app, &mut params)?; + } + } + ImageMethod::GpuRaytrace => { + params["progressive"] = json!(true); + params["samples"] = json!(view.samples); + params["max_depth"] = json!(view.max_depth); + params["seed"] = json!(view.seed); + studio::params(app, &mut params)?; + } + } + materials::params(app, &mut params)?; + Ok(params) +} + +fn select_image_method(app: &mut SolveApp, method: ImageMethod) { + app.render_workspace.view.method = method; + app.render_workspace.view.dirty = true; +} + +#[cfg(test)] +fn method_selector(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.label(app.tr("render.image_method")); + method_dropdown(app, ui); + if image_host(app, app.render_workspace.view.method).is_err() { + crate::ui_kit::text(ui, app.tr("render.setup_offline_help"), crate::ui_kit::Text::Note("render.setup_offline_help")); + } + if app.render_workspace.view.method != ImageMethod::Raster { + crate::ui_kit::text(ui, app.tr("render.preview_image_settings_help"), crate::ui_kit::Text::Note("render.preview_image_settings_help")); + } +} + +/// The same method authority in an aligned editor row or the legacy master form. +fn method_dropdown(app: &mut SolveApp, ui: &mut egui::Ui) -> egui::Response { + let current = app.render_workspace.view.method; + let label = app.tr(current.label()).to_string(); + let response = crate::ui_kit::dropdown_menu(ui, "render_image_method", &label, |ui| { + for (method, handle) in [ + (ImageMethod::Raster, "render:method-raster"), + (ImageMethod::CpuRaytrace, "render:method-cpu"), + (ImageMethod::GpuRaytrace, "render:method-gpu"), + ] { + let capability = image_host(app, method).map(|_| ()); + let label = app.tr(method.label()).to_string(); + let response = crate::ui_kit::list_picker(ui, handle, &label, method == current); + crate::scenario::publish_handle(handle, response.rect.center()); + if response.clicked() { + select_image_method(app, method); + ui.close(); + } + if let Err(reason) = capability { + response.on_hover_text(reason); + } + } + }); + crate::scenario::publish_handle("render:method", response.rect.center()); + response +} + +fn cpu_sampling_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let progressive = cpu::progressive_controls(app, ui); + if progressive { + crate::ui_kit::text(ui, app.tr("render.cpu_progressive_help"), crate::ui_kit::Text::Note("render.cpu_progressive_help")); + } + ui.add_enabled_ui(!progressive, |ui| { + crate::ui_kit::text(ui, app.tr("render.children.edge_samples"), crate::ui_kit::Text::Inline); + let samples = app.render_workspace.view.raytrace.primary_samples; + let aa = crate::ui_kit::dropdown_menu(ui, "render_cpu_samples", &format!("{samples}×"), |ui| { + for count in [1, 4, 16] { + let handle = format!("render:aa-{count}"); + let response = crate::ui_kit::list_picker(ui, &handle, &format!("{count}×"), count == samples); + crate::scenario::publish_handle(&handle, response.rect.center()); + if response.clicked() { + app.render_workspace.view.raytrace.primary_samples = count; + ui.close(); + } + } + }); + crate::scenario::publish_handle("render:aa", aa.rect.center()); + ui.small(app.tr("render.cpu_aa_help")); + }); +} + +#[cfg(test)] +fn cpu_lighting_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.label(app.tr("render.cpu_lighting")); + let presets = [ + (LightingPreset::Neutral, "render.cpu_neutral"), + (LightingPreset::WarmCool, "render.cpu_warm_cool"), + (LightingPreset::KeyRim, "render.cpu_key_rim"), + ]; + let selected = app.render_workspace.view.raytrace.preset.unwrap_or(LightingPreset::Neutral); + let label = app + .tr(match selected { + LightingPreset::Neutral => "render.cpu_neutral", + LightingPreset::WarmCool => "render.cpu_warm_cool", + LightingPreset::KeyRim => "render.cpu_key_rim", + }) + .to_string(); + crate::ui_kit::dropdown_menu(ui, "render_cpu_lighting", &label, |ui| { + for (preset, key) in presets { + if crate::ui_kit::list_picker(ui, key, app.tr(key), preset == selected).clicked() { + app.render_workspace.view.raytrace.preset = Some(preset); + app.render_workspace.view.raytrace.lights = None; + ui.close(); + } + } + }); + let shadows = app.tr("render.cpu_shadows").to_string(); + crate::ui_kit::checkbox(ui, &shadows, &mut app.render_workspace.view.raytrace.shadows); +} + +#[cfg(test)] +fn image_method_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + method_selector(app, ui); + if app.render_workspace.view.method != ImageMethod::CpuRaytrace { + return; + } + cpu_sampling_controls(app, ui); + cpu_lighting_controls(app, ui); + ui.label(app.tr("render.image_exposure")); + let exposure_help = app.tr("render.cpu_exposure_help").to_string(); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.exposure_ev, -32.0..=32.0, 0.1, " EV").on_hover_text(exposure_help); + cpu::controls(app, ui); +} + +#[cfg(test)] +fn image_edit_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.heading(app.tr("render.image_title")); + let preview = app.tr("render.result_preview").to_string(); + let result = app.tr("render.result_title").to_string(); + let mut selected = usize::from(app.render_workspace.view.result); + if crate::ui_kit::segmented(ui, &mut selected, &[&preview, &result], crate::ui_kit::Segments { compact: true, ..Default::default() }) { + let _ = app.run("render.result.view", json!({"view":if selected == 1 {"image"} else {"model"}})); + } + if app.render_workspace.view.result { + ui.horizontal(|ui| { + if crate::ui_kit::button(ui, app.tr("render.result_fit"), crate::ui_kit::Button::Normal).clicked() { + let _ = app.run("render.result.view", json!({"view":"fit"})); + } + if crate::ui_kit::button(ui, crate::i18n::tr("render.result_actual_size"), crate::ui_kit::Button::Enabled(!reduced_display(app))) + .on_hover_text(app.tr("render.result_actual_help")) + .clicked() + { + let _ = app.run("render.result.view", json!({"view":"actual"})); + } + }); + ui.small(app.tr("render.result_navigation")); + } + image_method_controls(app, ui); + ui.small(app.tr(match app.render_workspace.view.method { + ImageMethod::Raster => "render.opaque_image_summary", + ImageMethod::CpuRaytrace => "render.cpu_summary", + ImageMethod::GpuRaytrace => "render.progressive_image_summary", + })); + // The field's hard range never silently clamps a draft when its budget changes. + let side = match app.render_workspace.view.method { + ImageMethod::CpuRaytrace => 16384, + ImageMethod::GpuRaytrace => 8192, + ImageMethod::Raster => 4096, + }; + 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..=side, 1.0, "").changed() { + app.render_workspace.view.dirty = true; + } + ui.label(app.tr("render.image_height")); + if crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.height, 1..=side, 1.0, "").changed() { + app.render_workspace.view.dirty = true; + } + }); + let draft = &app.render_workspace.view.draft; + let size = (u64::from(draft.width), u64::from(draft.height)); + if let Some((w, h)) = cpu::image_limits(app).fit(size.0, size.1, None) + && (w, h) != size + { + let limit = if app.render_workspace.view.method == ImageMethod::CpuRaytrace && app.render_workspace.view.raytrace.progressive.is_some() { + "render.cpu_budget_resize" + } else { + "render.image_too_large" + }; + ui.small(app.tr(limit)); + if crate::ui_kit::button(ui, format!("{} {w} × {h}", app.tr("render.image_use_largest")), crate::ui_kit::Button::Normal).clicked() { + app.render_workspace.view.draft.width = u32::try_from(w).unwrap_or(1); + app.render_workspace.view.draft.height = u32::try_from(h).unwrap_or(1); + app.render_workspace.view.dirty = true; + } + } + match &app.render_workspace.path_host { + PathHost::Preparing(_, started) => setup_progress(ui, app, *started), + PathHost::Failed(error) => { + ui.add(egui::Label::new(format!("{}: {error}", app.tr("render.gpu_path_failed"))).wrap()); + } + _ => {} + } + if app.render_workspace.view.method == ImageMethod::GpuRaytrace { + ui.label(app.tr("render.image_samples")); + // Powers of two from 1 to 4096; requests from elsewhere keep any count. + let samples = &mut app.render_workspace.view.samples; + let mut exponent = (*samples).max(1).ilog2().min(MAX_SAMPLES_EXPONENT); + let slider = crate::ui_kit::Slider { integer: true, format: |e| format!("{}", 1u32 << (e as u32).min(31)), ..Default::default() }; + if crate::ui_kit::slider(ui, &mut exponent, 0..=MAX_SAMPLES_EXPONENT, slider).changed() { + *samples = 1 << exponent.min(MAX_SAMPLES_EXPONENT); + } + let title = app.tr("render.image_advanced").to_string(); + crate::ui_kit::section(ui, "render_gpu_advanced", &title, false, |ui| { + ui.label(app.tr("render.gpu_depth")); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.max_depth, 1..=16, 1.0, ""); + ui.label(app.tr("render.gpu_seed")); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.seed, 0..=u32::MAX, 1.0, ""); + ui.label(app.tr("render.image_exposure")); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.exposure_ev, -32.0..=32.0, 0.1, " EV"); + ui.small(app.tr("render.gpu_options_help")); + studio::controls(app, ui); + studio::backdrop_controls(app, ui); + }); + } + library::controls(app, ui); + materials::controls(app, ui); + let transparent_label = app.tr("render.image_transparent").to_string(); + crate::ui_kit::checkbox(ui, &transparent_label, &mut app.render_workspace.view.transparent); +} + +/// Dense all-controls composition, also useful to standalone/offscreen hosts. +#[cfg(test)] +fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + image_edit_controls(app, ui); + job_controls(app, ui, false); + completed_image(app, ui); +} + +fn job_controls(app: &mut SolveApp, ui: &mut egui::Ui, compact: bool) { + let params = image_params(app); + if !compact { + if let Err(error) = ¶ms { + ui.add(egui::Label::new(egui::RichText::new(error).color(Tokens::get().warning)).wrap()); + } + cpu::checked_status(app, ui, params.as_ref().ok()); + } + let mut busy = false; + let mut state = None; + if let Some(job) = app.render_workspace.view.job { + match app.session.execute("render.status", &json!({"job":job})) { + Ok(status) => { + let phase = status["progress"]["phase"].as_str().unwrap_or(crate::i18n::tr("render.property_unknown")); + busy = matches!(phase, "queued" | "preparing" | "running" | "encoding" | "cancelling"); + if phase == "completed" { + app.render_workspace.view.completed = Some(job); + } + state = Some(status); + } + Err(error) => { + if !compact { + ui.add(egui::Label::new(egui::RichText::new(error.to_string()).small()).wrap()); + } + } + } + } + ui.horizontal_wrapped(|ui| { + let check = crate::ui_kit::button( + ui, + app.tr("cmd.render_preflight"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.preflight").is_ok()), + ); + crate::scenario::publish_target("render:check", check.rect); + if check.clicked() + && let Err(error) = ribbon::perform_job(app, "render.preflight") + { + app.set_status(error, true); + } + let start = crate::ui_kit::button( + ui, + app.tr("render.image_start"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.start").is_ok()), + ); + crate::scenario::publish_target("render:start", start.rect); + if start.clicked() { + if let Err(error) = ribbon::perform_job(app, "render.start") { + app.set_status(error, true); + } + ui.ctx().request_repaint(); + } + }); + let message = state.as_ref().map_or_else( + || app.tr(if params.is_ok() { "render.studio_ready" } else { "render.studio_needs_review" }).to_string(), + |status| { + app.tr(match status["progress"]["phase"].as_str().unwrap_or("") { + "queued" => "render.image_queued", + "preparing" => "render.image_preparing", + "running" => "render.image_running", + "encoding" => "render.image_encoding", + "cancelling" => "render.image_cancelling", + "cancelled" => "render.image_cancelled", + "completed" => "render.image_completed", + "failed" => "render.image_failed", + _ => "render.image_unknown", + }) + .to_string() + }, + ); + let response = ui.add_sized([ui.available_width(), ui.text_style_height(&egui::TextStyle::Body)], egui::Label::new(message).truncate()); + crate::scenario::publish_target("render:job-summary", response.rect); + if let Err(error) = ¶ms { + response.on_hover_text(error); + } + if let Some(status) = &state { + if !compact { + cpu::captured_status(app, ui, status); + if let Some(message) = status["error"]["message"].as_str() { + ui.add(egui::Label::new(egui::RichText::new(message).small()).wrap()); + } + } + if busy { + let done = status["progress"]["done"].as_u64().unwrap_or(0); + let total = status["progress"]["total"].as_u64().unwrap_or(1).max(1); + crate::ui_kit::progress(ui, "render", (done as f64 / total as f64).clamp(0.0, 1.0) as f32); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + } + } + ui.horizontal_wrapped(|ui| { + let cancel = crate::ui_kit::button( + ui, + app.tr("cmd.render_cancel"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.cancel").is_ok()), + ); + crate::scenario::publish_target("render:cancel", cancel.rect); + if cancel.clicked() + && let Err(error) = ribbon::perform_job(app, "render.cancel") + { + app.set_status(error, true); + } + let export = crate::ui_kit::button( + ui, + app.tr("render.image_export"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.export").is_ok()), + ); + crate::scenario::publish_target("render:export", export.rect); + if export.clicked() + && let Err(error) = ribbon::perform_job(app, "render.export") + { + app.set_status(error, true); + } + }); + if !compact { + let label = app.tr("render.image_overwrite").to_string(); + crate::ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.overwrite); + } +} + +/// Decode each published sequence once. Provisional textures stay separate from the last +/// final image, so cancellation or a failed pass cannot change the export target. +#[cfg(test)] +fn completed_image(app: &mut SolveApp, ui: &mut egui::Ui) { + cache_render_images(app, ui.ctx()); + if let Some(display) = displayed_image(app) { + if display.provisional() { + ui.small(app.tr("render.result_provisional")); + } + match display.image { + Ok(texture) => { + if ui + .add(egui::Image::new(texture).max_size(egui::vec2(ui.available_width(), 240.0)).shrink_to_fit().sense(Sense::click())) + .on_hover_text(app.tr("render.result_open")) + .clicked() + { + let _ = app.run("render.result.view", json!({"view":"image"})); + } + } + Err(error) => { + ui.add(egui::Label::new(error).wrap()); + } + } + } else if let Some((_, Err(error))) = &app.render_workspace.image { + ui.add(egui::Label::new(error).wrap()); + } +} + +fn cache_completed_image(app: &mut SolveApp, ctx: &egui::Context) { + let Some(job) = app.render_workspace.view.completed else { + app.render_workspace.image = None; + app.render_workspace.image_info = None; + return; + }; + if app.render_workspace.image.as_ref().is_none_or(|(old, _)| *old != job) { + app.render_workspace.image_info = None; + let result = (|| -> Result { + let handle = app.session.render_job_handle(job).map_err(|e| e.to_string())?; + let frame = handle.frame().map_err(|e| e.to_string())?.ok_or(crate::i18n::tr("render.error_no_completed_image"))?; + let captured = handle.status().map_err(|e| e.to_string())?; + let budget = if frame.info.executor.as_str() == "gpu-path" { + solidcraft_engine::render::job::GPU_PATH_LIMITS + } else { + captured_image_limits(&captured.request) + }; + let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, budget, ctx.input(|i| i.max_texture_side))?; + app.session.execute("render.result.pin", &json!({"job":job})).map_err(|e| e.to_string())?; + app.render_workspace.image_info = Some(frame.info.clone()); + Ok(ctx.load_texture("sc_render_image", image, egui::TextureOptions::LINEAR)) + })(); + // Cache errors too, so a bad frame cannot repeatedly allocate or decode on repaint. + app.render_workspace.image = Some((job, result)); + } +} + +fn displayed_image(app: &SolveApp) -> Option> { + let state = &app.render_workspace; + let preview = state.preview_image.as_ref().filter(|image| state.view.job == Some(image.info.frame.job)); + let partial = state.final_partial.as_ref().filter(|image| state.view.job == Some(image.info.frame.job)); + if let Some(partial) = partial { + let pixels = u64::from(partial.info.source_width) * u64::from(partial.info.source_height); + let frontier = u64::from(partial.info.completed_passes) * pixels + partial.info.updated_prefix; + // Complete-pass and partial sequence numbers have different namespaces. + // Equal source evidence prefers the established complete-pass image. + if preview.is_none_or(|image| u64::from(image.info.samples_per_pixel) * pixels < frontier) { + return Some(DisplayImage { + info: &partial.info.frame, + image: &partial.image, + preview: None, + partial: Some((&partial.info, partial.sampling)), + logical_size: [partial.info.source_width, partial.info.source_height], + }); + } + } + if let Some(preview) = preview { + return Some(DisplayImage { + info: &preview.info.frame, + image: &preview.image, + preview: Some(&preview.info), + partial: None, + logical_size: [preview.info.frame.width, preview.info.frame.height], + }); + } + let info = state.image_info.as_ref()?; + Some(DisplayImage { info, image: &state.image.as_ref()?.1, preview: None, partial: None, logical_size: [info.width, info.height] }) +} + +fn cache_final_partial( + app: &mut SolveApp, + ctx: &egui::Context, + handle: &solidcraft_engine::render::job::JobHandle, + status: &solidcraft_engine::render::job::JobStatus, + partial: &solidcraft_engine::render::job::RenderPartialPreview, +) -> Result<(), String> { + let job = handle.id(); + if app.render_workspace.view.job != Some(job) { + return Ok(()); + } + let previous = app.render_workspace.final_partial.as_ref().filter(|cached| cached.info.frame.job == job).map(|cached| cached.sampling); + let expected = interactive::PartialExpectation { + job, + scene_generation: status.scene_generation, + request: &status.request, + final_dimensions: [status.request.width, status.request.height], + }; + let Some(sampling) = interactive::validate_partial_metadata(&expected, &partial.info, partial.png().len(), partial.covered().len(), previous)? + else { + return Ok(()); + }; + let image = interactive::decode_partial_image( + &status.request, + &partial.info, + partial.png(), + partial.covered(), + sampling, + ctx.input(|input| input.max_texture_side), + ) + .map(|pixels| ctx.load_texture("sc_render_final_partial", pixels, egui::TextureOptions::NEAREST)); + if app.render_workspace.view.job == Some(job) { + app.render_workspace.final_partial = Some(FinalPartialImage { info: partial.info.clone(), sampling, image }); + } + // Only texture/provenance survives: the borrowed PNG/coverage/lease is not retained. + Ok(()) +} + +fn cache_preview_frame(app: &mut SolveApp, ctx: &egui::Context, info: &PreviewInfo, png: &[u8]) { + if app.render_workspace.view.job != Some(info.frame.job) { + return; + } + if app + .render_workspace + .preview_image + .as_ref() + .is_some_and(|old| old.info.frame.job == info.frame.job && old.info.frame_sequence >= info.frame_sequence) + { + return; + } + let result = (|| -> Result { + if info.frame_sequence == 0 || !(1..=solidcraft_engine::render::job::MAX_CPU_SAMPLES_PER_PIXEL).contains(&info.samples_per_pixel) { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + let handle = app.session.render_job_handle(info.frame.job).map_err(|e| e.to_string())?; + let captured = handle.status().map_err(|e| e.to_string())?; + if captured + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .is_some_and(|target| info.samples_per_pixel > target.samples_per_pixel) + { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + if (info.frame.width, info.frame.height) != (captured.request.width, captured.request.height) { + return Err(crate::i18n::tr("render.error_checkpoint_dimensions").into()); + } + let options = solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: info.samples_per_pixel, seed: 0 }; + options.validate_image_with_budget(info.frame.width, info.frame.height, captured.request.cpu_budget()).map_err(|error| error.to_string())?; + let image = decode_render_image( + png, + info.frame.width, + info.frame.height, + captured_image_limits(&captured.request), + ctx.input(|i| i.max_texture_side), + )?; + Ok(ctx.load_texture("sc_render_preview", image, egui::TextureOptions::LINEAR)) + })(); + // Cache errors by identity too: a malformed publication cannot decode on every repaint. + app.render_workspace.preview_image = Some(PreviewImage { info: info.clone(), image: result }); +} + +// Consumer-only reconciliation of a temporarily absent latest publication. +// Status must come from the actual handle; retained pixels never imply new work. +fn reconcile_missing_cpu_preview(state: &mut State, job: JobId, status: Option<&solidcraft_engine::render::job::JobStatus>) { + let retain = state.preview_image.as_ref().is_some_and(|cached| { + cached.image.is_ok() + && status.is_some_and(|current| { + current.job == job + && cached.info.frame.job == current.job + && cached.info.frame.scene_generation == current.scene_generation + && (cached.info.frame.width, cached.info.frame.height) == (current.request.width, current.request.height) + && current.request.integrator == Integrator::Raytrace + && current.request.raytrace.as_ref().is_some_and(|options| options.progressive.is_some()) + && current.cpu_preview_retention_skips > 0 + && !current.progress.phase.terminal() + && current.progress.phase != solidcraft_engine::render::job::Phase::Cancelling + && current.error.is_none() + && current.frame.is_none() + }) + }); + if !retain { + state.preview_image = None; + } +} + +fn cache_preview_image(app: &mut SolveApp, ctx: &egui::Context) { + if let Some(job) = app.render_workspace.view.job + && let Ok(handle) = app.session.render_job_handle(job) + && let Ok(status) = handle.status() + { + if app.render_workspace.final_partial.as_ref().is_some_and(|cached| cached.info.frame.job != job) { + app.render_workspace.final_partial = None; + } + let now = interactive::monotonic(app.render_workspace.final_feedback_clock, ctx.input(|input| input.time)); + app.render_workspace.final_feedback_clock = now; + if !status.progress.phase.terminal() + && status.request.integrator == Integrator::Raytrace + && status.request.raytrace.as_ref().and_then(|options| options.progressive).is_some() + && interactive::partial_request_due(app.render_workspace.final_partial_request, job, now) + { + app.render_workspace.final_partial_request = Some((job, now)); + if let Err(error) = handle.request_partial_preview() { + app.set_status(error.to_string(), true); + } + } + app.render_workspace.final_feedback_report = handle.protected_preview_report().ok().flatten().map(|report| (job, report)); + let preview = handle.preview().ok().flatten(); + let partial = handle.partial_preview().ok().flatten(); + // Read completion AFTER both provisional slots: neither can be promoted to a final. + if handle.frame().ok().flatten().is_some() { + app.render_workspace.view.completed = Some(job); + } else if !status.progress.phase.terminal() { + if let Some(preview) = preview { + cache_preview_frame(app, ctx, &preview.info, preview.png()); + } else { + // Re-read after observing None: the producer may have certified + // a retention skip after the earlier status snapshot. + let current = handle.status().ok(); + reconcile_missing_cpu_preview(&mut app.render_workspace, job, current.as_ref()); + } + if let Some(partial) = partial + && let Err(error) = cache_final_partial(app, ctx, &handle, &status, &partial) + { + app.set_status(error, true); + } + // Decoding can race final publication/cancellation. Recheck the real job. + if handle.frame().ok().flatten().is_some() { + app.render_workspace.view.completed = Some(job); + } else if final_job_still_running(app, &handle) { + return; + } + } + } else { + app.render_workspace.final_feedback_report = None; + } + app.render_workspace.preview_image = None; + app.render_workspace.final_partial = None; +} + +/// Reconcile a terminal observation made after a frame read returned None. +/// Complete publishes its real frame under the same host data lock; read that +/// frame again before the caller clears provisional caches or falls back. +fn final_job_still_running(app: &mut SolveApp, handle: &solidcraft_engine::render::job::JobHandle) -> bool { + let job = handle.id(); + if app.render_workspace.view.job != Some(job) { + return false; + } + let status = match handle.status() { + Ok(status) => status, + Err(error) => { + app.set_status(error.to_string(), true); + return false; + } + }; + if status.progress.phase == solidcraft_engine::render::job::Phase::Completed { + match handle.frame() { + Ok(Some(frame)) if app.render_workspace.view.job == Some(frame.info.job) => { + app.render_workspace.view.completed = Some(frame.info.job); + } + Err(error) => app.set_status(error.to_string(), true), + _ => {} + } + return false; + } + !status.progress.phase.terminal() +} + +fn remember_displayed_job(app: &mut SolveApp, preserve_view: bool) { + let Some(job) = displayed_image(app).map(|display| display.info.job) else { return }; + if app.render_workspace.view.result_job != Some(job) { + app.render_workspace.view.result_job = Some(job); + if !preserve_view { + app.render_workspace.view.result_scale = ResultScale::Fit; + } + } +} + +fn cache_render_images(app: &mut SolveApp, ctx: &egui::Context) { + let preserve_view = displayed_image(app).is_some_and(|display| { + display.provisional() + && app.render_workspace.view.result_job == Some(display.info.job) + && app.render_workspace.view.job == Some(display.info.job) + }); + cache_preview_image(app, ctx); + cache_completed_image(app, ctx); + // Checkpoint updates and preview→final/cancel transitions preserve shared pan/zoom. + remember_displayed_job(app, preserve_view); +} + +fn captured_image_limits(request: &solidcraft_engine::render::job::ImageRequest) -> RenderLimits { + if request.integrator == Integrator::Raytrace { + request.cpu_budget().image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())) + } else { + RenderLimits::default() + } +} + +/// This is a display cache only: the authoritative PNG/frame and export remain +/// full resolution. Avoid asking a viewport device for an unsupported texture. +fn display_dimensions(width: u32, height: u32, max_texture_side: usize) -> Result<(u32, u32), String> { + if width == 0 || height == 0 || max_texture_side == 0 { + return Err(crate::i18n::tr("render.error_display_dimensions").into()); + } + let max_side = max_texture_side.min(8192) as u64; + let display = RenderLimits { max_dimension: max_side, max_pixels: 16_777_216, max_scratch_bytes: 512 * 1024 * 1024 }; + let (w, h) = display.fit(u64::from(width), u64::from(height), None).ok_or(crate::i18n::tr("render.error_display_fit"))?; + Ok(( + u32::try_from(w).map_err(|_| crate::i18n::tr("render.error_display_width"))?, + u32::try_from(h).map_err(|_| crate::i18n::tr("render.error_display_height"))?, + )) +} + +#[cfg(test)] +fn decode_image(png: &[u8], width: u32, height: u32) -> Result { + decode_render_image(png, width, height, RenderLimits::default(), 8192) +} + +fn decode_render_image(png: &[u8], width: u32, height: u32, budget: RenderLimits, max_texture_side: usize) -> Result { + let size = (u64::from(width), u64::from(height)); + if budget.fit(size.0, size.1, None) != Some(size) { + return Err(crate::i18n::tr("render.error_image_profile").into()); + } + let display_size = display_dimensions(width, height, max_texture_side)?; + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(width); + limits.max_image_height = Some(height); + limits.max_alloc = Some(size.0.checked_mul(size.1).and_then(|n| n.checked_mul(16)).ok_or(crate::i18n::tr("render.error_decode_budget"))?); + reader.limits(limits); + let image = reader.decode().map_err(|e| e.to_string())?.to_rgba8(); + if image.dimensions() != (width, height) { + return Err(crate::i18n::tr("render.error_image_dimensions").into()); + } + let image = if display_size != (width, height) { + image::imageops::resize(&image, display_size.0, display_size.1, image::imageops::FilterType::Triangle) + } else { + image + }; + Ok(egui::ColorImage::from_rgba_unmultiplied([display_size.0 as usize, display_size.1 as usize], image.as_raw())) +} + +fn reduced_display(app: &SolveApp) -> bool { + displayed_image(app).is_some_and(|display| { + display.image.as_ref().is_ok_and(|texture| texture.size() != [display.logical_size[0] as usize, display.logical_size[1] as usize]) + }) +} + +/// The image has its own per-document orthographic camera. Shared navigation can temporarily +/// drive it without changing the product camera, saved setup, or a pending Design view. +pub(crate) fn with_result_camera(app: &mut SolveApp, navigate: impl FnOnce(&mut SolveApp)) { + let preview = std::mem::replace(&mut app.cam, app.render_workspace.view.result_camera); + let before = app.cam; + let draft = app.render_workspace.view.draft.clone(); + let dirty = app.render_workspace.view.dirty; + let perspective = std::mem::replace(&mut app.ui.perspective, false); + let up = app.ui.up_axis; + let animation = app.cam_anim.take(); + let pending = app.pending_fit.take(); + let request = app.session.camera.take(); + let free = app.viewport.orbit_free.take(); + let spin = std::mem::replace(&mut app.viewport.spin, false); + navigate(app); + app.render_workspace.view.result_camera = std::mem::replace(&mut app.cam, preview); + if app.render_workspace.view.result_camera != before { + app.render_workspace.view.result_scale = ResultScale::Free; + } + app.render_workspace.view.draft = draft; + app.render_workspace.view.dirty = dirty; + app.ui.perspective = perspective; + app.ui.up_axis = up; + app.cam_anim = animation; + app.pending_fit = pending; + app.session.camera = request; + app.viewport.orbit_free = free; + app.viewport.spin = spin; +} + +fn result_camera(size: [u32; 2], rect: egui::Rect, pixels_per_point: f32, scale: ResultScale) -> Camera { + let width = f64::from(size[0].max(1)); + let height = f64::from(size[1].max(1)); + let scale = if scale == ResultScale::Actual { + 1.0 / f64::from(pixels_per_point.max(0.1)) + } else { + (f64::from((rect.width() - 32.0).max(1.0)) / width).min(f64::from((rect.height() - 32.0).max(1.0)) / height) + }; + Camera { + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + distance: (f64::from(rect.height().max(1.0)) / (0.8 * scale)).clamp(1e-3, 1e7), + ..Default::default() + } +} + +fn result_rect(camera: Camera, size: [u32; 2], canvas: egui::Rect) -> egui::Rect { + let scale = f64::from(canvas.height().max(1.0)) / (2.0 * camera.half_height()); + let center = canvas.center() + egui::vec2((-camera.target.x * scale) as f32, (camera.target.y * scale) as f32); + egui::Rect::from_center_size(center, egui::vec2((f64::from(size[0]) * scale) as f32, (f64::from(size[1]) * scale) as f32)) +} + +fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { + for (view, key) in [("model", "render.state_model"), ("fit", "render.output_fit"), ("actual", "render.result_actual")] { + let enabled = view != "actual" || !reduced_display(app); + if crate::ui_kit::button(ui, app.tr(key), crate::ui_kit::Button::Enabled(enabled)).clicked() { + let _ = app.run("render.result.view", json!({"view":view})); + } + } + let copy = crate::ui_kit::button( + ui, + app.tr("render.output_copy"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.result.copy").is_ok()), + ); + crate::scenario::publish_target("render:result-copy", copy.rect); + if copy.clicked() { + app.start("render.result.copy"); + } + let export = + crate::ui_kit::button(ui, studio::export_label(app), crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.export").is_ok())); + crate::scenario::publish_target("render:result-export", export.rect); + if export.clicked() { + app.start("render.export"); + } + let close = crate::ui_kit::StageBar::icon_action(ui, "close", app.tr("cmd.render_result_close")); + crate::scenario::publish_target("render:result-close", close.rect); + if close.clicked() { + app.start("render.result.close"); + } +} + +fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { + cache_render_images(app, ui.ctx()); + let t = Tokens::get(); + ui.painter().rect_filled(ui.max_rect(), 0.0, t.viewport_bottom); + // The floating shell paints after this canvas. Keep image actions in its free + // content area so neither ribbon nor Browser can cover their hit targets. + let mut free = crate::render_ui::canvas(app, ui.max_rect()); + if ribbon::busy(app) { + free = crate::ui_kit::Container::below_navigation_row(free); + } + let mut content = ui.new_child(egui::UiBuilder::new().max_rect(free).id_salt("render_result_content")); + let ui = &mut content; + let Some((info, preview, partial, logical_size)) = displayed_image(app).map(|display| { + (display.info.clone(), display.preview.cloned(), display.partial.map(|(info, sampling)| (info.clone(), sampling)), display.logical_size) + }) else { + let message = match &app.render_workspace.image { + Some((_, Err(error))) => error.clone(), + _ if ribbon::busy(app) => app.tr("render.state_in_progress").to_string(), + _ => app.tr("render.result_empty").to_string(), + }; + crate::ui_kit::Container::navigation_contents(ui, |ui| { + ui.horizontal_wrapped(|ui| { + crate::ui_kit::text( + ui, + app.tr(if ribbon::busy(app) { "render.state_in_progress" } else { "render.result_title" }), + crate::ui_kit::Text::Inline, + ); + result_actions(app, ui); + }); + }); + let canvas = ui.available_rect_before_wrap(); + ui.centered_and_justified(|ui| { + ui.add(egui::Label::new(egui::RichText::new(message).size(t.font_heading).color(t.text)).wrap()); + }); + app.viewport.rect = Some(canvas); + return; + }; + crate::ui_kit::Container::navigation_contents(ui, |ui| { + ui.horizontal_wrapped(|ui| { + crate::ui_kit::text( + ui, + app.tr(if preview.is_some() || partial.is_some() { "render.state_in_progress" } else { "render.state_completed" }), + crate::ui_kit::Text::Inline, + ); + result_actions(app, ui); + }); + if let Some(preview) = &preview { + ui.colored_label( + t.warning, + format!( + "{} · {} {} · {} {}", + app.tr("render.result_provisional"), + preview.samples_per_pixel, + app.tr("render.cpu_progressive_spp"), + app.tr("render.result_sequence"), + preview.frame_sequence + ), + ); + if let Ok(handle) = app.session.render_job_handle(preview.frame.job) + && let Ok(status) = handle.status() + && let Some(target) = status.request.raytrace.as_ref().and_then(|options| options.progressive) + { + ui.small(crate::i18n::format( + "render.cpu_pass_progress", + &[("current", &preview.samples_per_pixel.to_string()), ("target", &target.samples_per_pixel.to_string())], + )); + } + ui.small(app.tr("render.result_provisional_help")); + } + if let Some((info, sampling)) = &partial { + ui.colored_label(t.warning, app.tr("render.result_provisional")); + if let Ok(handle) = app.session.render_job_handle(info.frame.job) + && let Ok(status) = handle.status() + && let Some(target) = status.request.raytrace.as_ref().and_then(|options| options.progressive) + { + ui.small(crate::i18n::format( + "render.cpu_pass_progress", + &[("current", &info.completed_passes.to_string()), ("target", &target.samples_per_pixel.to_string())], + )); + } + let (min, max) = sampling.sample_range(); + ui.small(crate::i18n::format( + "render.interactive_partial_samples", + &[ + ("min", &min.to_string()), + ("max", &max.to_string()), + ("known", &sampling.sampled_source_pixels().to_string()), + ("pixels", &(u64::from(info.source_width) * u64::from(info.source_height)).to_string()), + ], + )); + ui.small(crate::i18n::format( + "render.interactive_partial_dimensions", + &[ + ("display_width", &info.frame.width.to_string()), + ("display_height", &info.frame.height.to_string()), + ("source_width", &info.source_width.to_string()), + ("source_height", &info.source_height.to_string()), + ("final_width", &logical_size[0].to_string()), + ("final_height", &logical_size[1].to_string()), + ], + )); + ui.small(app.tr("render.result_provisional_help")); + } + if let Some((job, report)) = app.render_workspace.final_feedback_report + && job == info.job + && (preview.is_some() || partial.is_some()) + { + ui.small(crate::i18n::format( + "render.interactive_feedback_usage", + &[("started", &report.accepted_snapshots.to_string()), ("limit", &report.quota_limit.to_string())], + )); + let reason = if report.quota_exhausted { + Some("render.interactive_feedback_quota_exhausted") + } else if report.milestones_complete { + Some("render.interactive_feedback_milestones_complete") + } else { + None + }; + if let Some(reason) = reason { + ui.small(app.tr(reason)); + } + } + if let Some(display) = displayed_image(app) + && let Err(error) = display.image + { + ui.colored_label(t.warning, error); + } + ui.horizontal_wrapped(|ui| { + ui.strong(format!("{} × {} px · PNG · {}", logical_size[0], logical_size[1], info.executor.as_str())); + ui.label(format!( + "{} {}:{}:{} · {} {}", + app.tr("render.result_job"), + info.job.session, + info.job.serial, + info.job.generation, + app.tr("render.result_capture"), + info.scene_generation + )); + }); + if reduced_display(app) { + ui.colored_label(t.warning, app.tr("render.result_reduced_display")); + } + let stale = info.scene_generation != app.session.revision; + ui.colored_label(if stale { t.warning } else { t.text_dim }, app.tr(if stale { "render.image_stale" } else { "render.result_current" })); + if app.render_workspace.view.job.is_some_and(|job| job != info.job) { + ui.small(app.tr("render.result_retained")); + } + }); + let rect = ui.available_rect_before_wrap(); + if rect.width() < 1.0 || rect.height() < 1.0 { + return; + } + let response = ui.allocate_rect(rect, Sense::click_and_drag()); + app.viewport.rect = Some(rect); + crate::viewport::refresh_layout(app, ui.ctx()); + let size = logical_size; + let scale = app.render_workspace.view.result_scale; + if scale != ResultScale::Free { + app.render_workspace.view.result_camera = result_camera(size, rect, ui.ctx().pixels_per_point(), scale); + } + with_result_camera(app, |app| { + crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps { orbit: false, pick: false }); + }); + let after = app.render_workspace.view.result_scale; + if after != scale && after != ResultScale::Free { + app.render_workspace.view.result_camera = result_camera(size, rect, ui.ctx().pixels_per_point(), after); + } + let camera = app.render_workspace.view.result_camera; + let mut image_rect = result_rect(camera, size, rect); + if after == ResultScale::Actual { + let dpi = ui.ctx().pixels_per_point(); + let min = egui::pos2((image_rect.min.x * dpi).round() / dpi, (image_rect.min.y * dpi).round() / dpi); + image_rect = image_rect.translate(min - image_rect.min); + } + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + let visible = image_rect.intersect(rect); + if visible.is_positive() { + // Bound checker work by the visible canvas, even for an extremely magnified image. + painter.rect_filled(visible, 0.0, t.panel); + let cell = 24.0f32.max(visible.width().max(visible.height()) / 128.0); + for row in 0..(visible.height() / cell).ceil() as u32 { + for column in 0..(visible.width() / cell).ceil() as u32 { + if (row + column) % 2 == 0 { + let square = egui::Rect::from_min_size(visible.min + egui::vec2(column as f32 * cell, row as f32 * cell), egui::vec2(cell, cell)); + painter.rect_filled(square.intersect(visible), 0.0, t.control_fill); + } + } + } + if let Some(display) = displayed_image(app) + && let Ok(texture) = display.image + { + painter.image(texture.id(), image_rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Tokens::get().file_image_tint); + } + painter.rect_stroke(image_rect, 0.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Outside); + } + let percent = f64::from(rect.height() * ui.ctx().pixels_per_point()) / (2.0 * camera.half_height()) * 100.0; + let label = painter.layout_no_wrap(format!("{percent:.1}%"), egui::FontId::proportional(t.font_label), t.text); + let badge = egui::Rect::from_min_size( + rect.left_bottom() + egui::vec2(t.space_8, -label.size().y - t.space_8 * 2.0), + label.size() + egui::vec2(t.space_8 * 2.0, t.space_8), + ); + painter.rect_filled(badge, t.control_radius, t.panel); + painter.galley(badge.min + egui::vec2(t.space_8, t.space_8 * 0.5), label, t.text); + crate::navigation_bar_view::show(app, ui, rect); +} + +impl State { + fn prepare_preview(&mut self, signature: (u64, usize, u64, u64), capture: impl FnOnce() -> Result) -> Result<(), String> { + if self.scene_signature != Some(signature) { + let prepared = capture().and_then(|scene| gpu_scene_with_budget(&scene, signature.3).map(|(key, gpu)| (scene, key, gpu))); + self.scene_signature = Some(signature); + match prepared { + Ok((scene, key, gpu)) => { + let bytes = gpu.pbr.len() + gpu.tris.len() + gpu.glass.len(); + if self.key != Some(key) { + let uploaded = match self.slot.lock() { + Ok(mut slot) => { + *slot = Some(gpu); + true + } + Err(_) => false, + }; + if !uploaded { + let error = crate::i18n::tr("render.error_upload_slot").to_string(); + self.scene = None; + self.key = None; + self.preview_upload_bytes = None; + self.scene_error = Some(error.clone()); + return Err(error); + } + self.key = Some(key); + if let Ok(mut error) = self.upload_error.lock() { + *error = None; + } + } + self.scene = Some(scene); + self.scene_error = None; + self.preview_upload_bytes = Some(bytes); + } + Err(error) => { + self.scene = None; + self.key = None; + self.preview_upload_bytes = None; + if let Ok(mut slot) = self.slot.lock() { + *slot = None; + } + self.scene_error = Some(error); + } + } + } + match &self.scene_error { + Some(error) => Err(error.clone()), + None => Ok(()), + } + } +} + +/// Use the shared kit's wrapped, themed error surface, not text painted directly +/// on the user-selected background (which may have the opposite theme contrast). +fn preview_error(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, error: &str) { + let t = Tokens::get(); + let bounded = crate::shell::workspace_content(app, crate::shell::panel_bounds(app, rect)).shrink(t.space_12); + // At tiny window sizes the shell may leave no room for the shared error card. + if !bounded.is_finite() || bounded.width() < t.control_height + 2.0 * t.space_8 || bounded.height() < t.control_height + 2.0 * t.space_8 { + return; + } + ui.scope_builder(egui::UiBuilder::new().max_rect(bounded), |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(bounded)); + ui.set_max_width(bounded.width().min(t.form_card_width * 2.0)); + crate::ui_kit::Panel::feature_frame(ui.ctx(), crate::shell::LayoutMode::Floating, crate::frame::Side::Left).inner_margin(t.space_8).show( + ui, + |ui| { + crate::ui_kit::text(ui, error, crate::ui_kit::Text::Error("render.preview_failure")); + crate::ui_kit::text(ui, app.tr("render.preview_unavailable_help"), crate::ui_kit::Text::Note("render.preview_unavailable_help")); + let retry = crate::ui_kit::button(ui, app.tr("render.preview_retry"), crate::ui_kit::Button::Normal); + crate::scenario::publish_target("render:preview-retry", retry.rect); + if retry.clicked() { + invalidate_scene(app); + ui.ctx().request_repaint(); + } + }, + ); + }); +} + +/// Keep the selected image and overwrite consent fixed while the upstream picker holds model input. +fn export_image(app: &mut SolveApp, job: solidcraft_engine::render::job::JobId, overwrite: bool) { + let origin = app.session.doc.clone(); + app.pick_save("render.png", &["png"], move |app, path| { + let Some(path) = path else { return }; + if !Arc::ptr_eq(&origin, &app.session.doc) { + app.set_status(crate::i18n::tr("render.error_export_document"), true); + return; + } + let _ = app.run("render.export", json!({"job":job,"path":path,"overwrite":overwrite})); + }); +} + +/// Captures format and completed identity before the asynchronous picker opens. +fn export_linear_image(app: &mut SolveApp, job: solidcraft_engine::render::job::JobId, overwrite: bool) { + let origin = app.session.doc.clone(); + app.pick_save("render.exr", &["exr"], move |app, path| { + let Some(path) = path else { + return; + }; + if !Arc::ptr_eq(&origin, &app.session.doc) { + app.set_status(crate::i18n::tr("render.error_export_document"), true); + return; + } + let _ = app.run("render.export", json!({"job":job,"path":path,"overwrite":overwrite,"format":"exr"})); + }); +} + +/// An exact expanded vertex payload, counted before allocating its buffers. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct PreviewUploadPlan { + pbr: usize, + tris: usize, + glass: usize, + source_triangles: usize, +} +impl PreviewUploadPlan { + fn bytes(self) -> Result { + self.pbr.checked_add(self.tris).and_then(|n| n.checked_add(self.glass)).ok_or_else(|| crate::i18n::tr("render.error_geometry_size").into()) + } + fn add(&mut self, pbr: bool, glass: bool, triangles: usize, limit: usize) -> Result<(), String> { + let stride = if pbr { crate::gpu::PBR_SIZE } else { crate::gpu::TRI_SIZE }; + let bytes = triangles.checked_mul(3).and_then(|n| n.checked_mul(stride)).ok_or(crate::i18n::tr("render.error_geometry_size"))?; + let count = if pbr { + &mut self.pbr + } else if glass { + &mut self.glass + } else { + &mut self.tris + }; + *count = count.checked_add(bytes).ok_or(crate::i18n::tr("render.error_geometry_size"))?; + admit_geometry(self.bytes()? as u64, limit as u64) + } +} + +fn preview_upload_plan(scene: &ProductScene, limit: usize) -> Result { + if scene.meshes.len() > solidcraft_engine::render::job::MAX_CPU_BODIES { + return Err(crate::i18n::tr("render.error_body_bound").into()); + } + let mut plan = PreviewUploadPlan::default(); + for body in &scene.meshes { + plan.source_triangles = plan.source_triangles.checked_add(body.mesh.triangles.len()).ok_or(crate::i18n::tr("render.error_triangle_count"))?; + if plan.source_triangles > solidcraft_engine::render::job::MAX_CPU_TRIANGLES { + return Err(crate::i18n::tr("render.error_triangle_bound").into()); + } + if body.faces.len() > 262_144 { + return Err(crate::i18n::tr("render.error_face_cap").into()); + } + if !body.opacity.is_finite() + || !(0.0..=1.0).contains(&body.opacity) + || body.faces.iter().any(|face| !face.opacity.is_finite() || !(0.0..=1.0).contains(&face.opacity)) + { + return Err(crate::i18n::tr("render.error_opacity").into()); + } + let looks: std::collections::BTreeMap<_, _> = body.faces.iter().map(|face| (face.face, face)).collect(); + if looks.len() != body.faces.len() { + return Err(crate::i18n::tr("render.error_duplicate_face").into()); + } + for index in 0..body.mesh.triangles.len() { + let face = body.mesh.tri_face.get(index).and_then(|id| looks.get(id)); + let (opacity, pbr) = face.map_or((body.opacity, body.surface.is_some() && body.transmission.is_none()), |face| { + (face.opacity, face.surface.is_some() && face.transmission.is_none()) + }); + if pbr && opacity != 1.0 { + return Err(crate::i18n::tr("render.error_pbr_opacity").into()); + } + if opacity > 0.0 { + plan.add(pbr, opacity < 0.999, 1, usize::MAX)?; + } + } + } + admit_geometry(plan.bytes()? as u64, limit as u64)?; + Ok(plan) +} + +/// Convert all captured surfaces, without decimation. The finite, exact payload +/// plan is admitted first; each output vector is reserved once rather than grown +/// once per triangle. Device uploads retain their existing chunked buffer path. +#[cfg(test)] +fn gpu_scene(scene: &ProductScene) -> Result<(u64, GpuScene), String> { + gpu_scene_with_budget(scene, MAX_GEOMETRY_BYTES as u64) +} + +fn gpu_scene_with_budget(scene: &ProductScene, budget: u64) -> Result<(u64, GpuScene), String> { + let limit = usize::try_from(budget).unwrap_or(usize::MAX); + let plan = preview_upload_plan(scene, limit)?; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + let mut gpu = GpuScene::default(); + for (buffer, bytes) in [(&mut gpu.pbr, plan.pbr), (&mut gpu.tris, plan.tris), (&mut gpu.glass, plan.glass)] { + buffer.try_reserve_exact(bytes).map_err(|_| crate::i18n::tr("render.error_vertex_allocation").to_string())?; + } + for body in &scene.meshes { + if body.faces.len() > 262_144 { + return Err(crate::i18n::tr("render.error_face_cap").into()); + } + if !body.opacity.is_finite() + || !(0.0..=1.0).contains(&body.opacity) + || body.faces.iter().any(|f| !f.opacity.is_finite() || !(0.0..=1.0).contains(&f.opacity)) + { + return Err(crate::i18n::tr("render.error_opacity").into()); + } + (Arc::as_ptr(&body.mesh) as usize).hash(&mut hash); + body.name.hash(&mut hash); + body.color.hash(&mut hash); + body.opacity.to_bits().hash(&mut hash); + body.transmission.is_some().hash(&mut hash); + hash_surface(body.surface, &mut hash); + let looks: std::collections::BTreeMap<_, _> = body.faces.iter().map(|l| (l.face, l)).collect(); + for face in &body.faces { + face.face.hash(&mut hash); + face.color.hash(&mut hash); + face.opacity.to_bits().hash(&mut hash); + face.transmission.is_some().hash(&mut hash); + hash_surface(face.surface, &mut hash); + } + for (index, triangle) in body.mesh.triangles.iter().enumerate() { + let face = body.mesh.tri_face.get(index).and_then(|f| looks.get(f)); + let (color, opacity, surface) = face.map_or((body.color, body.opacity, body.surface.filter(|_| body.transmission.is_none())), |l| { + (l.color, l.opacity, l.surface.filter(|_| l.transmission.is_none())) + }); + if surface.is_some() && opacity != 1.0 { + return Err(crate::i18n::tr("render.error_pbr_opacity").into()); + } + if opacity <= 0.0 { + continue; + } + let vertices = triangle.map(|i| { + let p = body.mesh.positions.get(i as usize)?.to_f32(); + let n = *body.mesh.normals.get(i as usize)?; + let n = if surface.is_some() { solidcraft_engine::render::surface::unit_direction(n).ok()? } else { n }.to_f32(); + p.into_iter().chain(n).all(f32::is_finite).then_some((p, n)) + }); + let [Some(a), Some(b), Some(c)] = vertices else { return Err(crate::i18n::tr("render.error_product_triangle").into()) }; + let rgba = [color[0], color[1], color[2], (opacity * 255.0).round() as u8]; + let index = gpu.color(rgba); + for (p, n) in [a, b, c] { + if let Some(surface) = surface { + if n.iter().all(|v| *v == 0.0) { + return Err(crate::i18n::tr("render.error_surface_normals").into()); + } + gpu.pbr_tri(p, n, surface); + } else if opacity < 0.999 { + gpu.glass_tri(p, n, index); + } else { + gpu.tri(p, n, index); + } + } + } + } + if (gpu.pbr.len(), gpu.tris.len(), gpu.glass.len()) != (plan.pbr, plan.tris, plan.glass) { + return Err(crate::i18n::tr("render.error_vertex_packing").into()); + } + Ok((hash.finish(), gpu)) +} + +fn hash_surface(surface: Option, hash: &mut impl Hasher) { + surface.is_some().hash(hash); + if let Some(s) = surface { + let c = s.base_color(); + for value in [c.x, c.y, c.z, s.metallic(), s.roughness(), s.dielectric_ior()] { + value.to_bits().hash(hash); + } + } +} + +/// The size the product preview draws at for a viewport of `full` physical pixels: the full +/// size when the viewport executor admits it, else the largest size at the same aspect it does. +/// Without an executor the request is left for resolution to report. +pub fn preview_size(executor: Option<&ExecutorDescriptor>, full: (u64, u64)) -> (u64, u64) { + executor.and_then(|e| e.fit(full.0, full.1)).unwrap_or(full) +} + +/// Model Preview presents the common exposure regardless of the selected final method. +/// Already captured Interactive and Result pixels return before this product-frame path. +fn product_preview_exposure(app: &SolveApp) -> Result { + solidcraft_gpu::view::ProductExposureEv::from_ev(app.render_workspace.view.draft.exposure_ev) + .ok_or_else(|| app.tr("render.product_exposure_invalid").to_string()) +} + +pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { + if app.render_workspace.view.result { + interactive::before_paint(app, ui.ctx()); + app.render_workspace.view.environment_ring = environment::RingView::default(); + assign::stop(app); + show_result(app, ui); + return; + } + let viewport = ui.max_rect(); + app.viewport.rect = Some(viewport); + // Framing uses the output camera's own aspect, including navigation and picking. + let rect = shot::preview_rect(app, viewport).unwrap_or(viewport); + crate::viewport::refresh_layout(app, ui.ctx()); + let response = ui.interact(rect, ui.id().with("render_preview"), Sense::click_and_drag()); + if !environment::ring_input(app, ui, rect, &response) { + let input = crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps::RENDER); + // Navigation can invalidate the displayed image in this frame. Observe before + // any geometry interaction, and observe again below after visible UI actions. + interactive::before_paint(app, ui.ctx()); + let waiting = interactive::blocks_geometry_input(app); + let geometry_rect = interactive::geometry_input_rect(app, rect); + let geometry_inside = input.inside && input.hover.is_some_and(|pos| geometry_rect.contains(pos)); + let navigating = input.scroll != 0.0 + || input.pinch != 1.0 + || input.pan != egui::Vec2::ZERO + || input.middle + || input.secondary_down + || (input.primary_nav.is_some() && input.primary_down) + || input.mode.is_some() + || app.viewport.axis_drag.is_some() + || app.viewport.spin + || app.cam_anim.is_some(); + let hits = input + .hover + .filter(|_| geometry_inside && !navigating && !waiting) + .map(|p| crate::viewport::pick_cached(app, &crate::viewport::projection(app, geometry_rect), p)) + .unwrap_or_default(); + let candidate = assign::candidate(app, &hits, input.mods); + app.viewport.hover = candidate.as_ref().map(|(hit, _)| hit.clone()); + // No target while blank or misaligned; still drain drag release / Escape. + let assigning = assign::input(app, ui, &response, candidate.as_ref(), geometry_inside && !navigating && !waiting); + if !waiting && !assigning && geometry_inside && !navigating { + assign::hover_tooltip(app, &response, candidate.as_ref()); + } + if !waiting && !assigning && response.clicked_by(egui::PointerButton::Primary) && geometry_inside && !navigating { + let (add, toggle) = crate::tool_modifiers::selection_click( + crate::tool_modifiers::Held::from_modifiers(input.mods), + app.preferences.selection_shift_add_only, + ); + crate::viewport::select(app, candidate.as_ref().map(|(_, sel)| sel.clone()), add, toggle); + } + if !waiting + && response.secondary_clicked() + && let Some((crate::viewport::Hit::Face { body, .. }, _)) = &candidate + { + if let Some(candidate) = &candidate { + assign::context(app, candidate); + } + crate::context_menu::open_for(app, input.hover.unwrap_or(rect.center()), crate::context_menu::Target::Body { name: body.clone() }); + } + } else { + app.viewport.hover = None; + } + let bg = app.render_workspace.view.draft.background; + ui.painter().rect_filled(viewport, 0.0, Color32::from_rgb(bg[0], bg[1], bg[2])); + // Reobserve after the existing shared navigation path, before any pixel paint. + interactive::before_paint(app, ui.ctx()); + if interactive::paint(app, ui, rect) || interactive::blocks_geometry_input(app) { + shot::overlay(app, ui, viewport); + crate::viewport::axis_view(app, ui, viewport); + crate::navigation_bar_view::show(app, ui, viewport); + return; + } + let result = (|| -> Result<(), String> { + let exposure = product_preview_exposure(app)?; + if app.viewport.gpu.is_none() { + return Err(crate::i18n::tr("render.error_gpu_preview").into()); + } + let ppp = ui.ctx().pixels_per_point(); + let setup = &app.render_workspace.view.draft; + if setup.environment_rotation != 0.0 || setup.environment_intensity != 1.0 { + return Err(crate::i18n::tr("render.preview_environment_fixed").into()); + } + // A 4K or 5K viewport is past the preview's pixel budget: draw it smaller and filter it + // up into the viewport rather than refusing the frame. + let full = ((rect.width() * ppp).max(1.0) as u64, (rect.height() * ppp).max(1.0) as u64); + let (width, height) = preview_size(app.session.render_viewport(), full); + let mut request = RenderRequest { + backend: Some(setup.backend.clone()), + mode: setup.mode, + operation: RenderOperation::Viewport, + width, + height, + format: None, + features: Vec::new(), + policy: Default::default(), + }; + solidcraft_engine::render::resolve_request(&[app.session.render_backend()], &request).map_err(|e| e.to_string())?; + if app.session.model.is_stale() { + return Err(crate::i18n::tr("render.error_finish_gesture").into()); + } + let mut visibility = std::collections::hash_map::DefaultHasher::new(); + app.session.visibility.hidden_bodies.hash(&mut visibility); + app.session.visibility.hidden_occurrences.hash(&mut visibility); + let budget = preferred_geometry_budget(app.render_workspace.geometry_budget, app.preferences.render_previous_geometry_budget); + let signature = + (app.session.revision, Arc::as_ptr(&app.session.world_state()) as usize, visibility.finish() ^ assign::preview_key(app), budget); + let preview = assign::preview(app); + let previous_key = app.render_workspace.key; + app.render_workspace.prepare_preview(signature, || { + let mut scene = solidcraft_engine::product_scene::extract(&app.session).map_err(|error| error.to_string())?; + assign::preview_scene(&mut scene, preview.as_ref())?; + Ok(scene) + })?; + if app.render_workspace.key != previous_key { + ui.ctx().request_repaint(); + } + let scene = app.render_workspace.scene.as_ref().ok_or(crate::i18n::tr("render.error_no_scene"))?; + if let Some(error) = app.render_workspace.upload_error.lock().ok().and_then(|e| e.clone()) { + return Err(upload_refusal(app.render_workspace.preview_upload_bytes.unwrap_or(0) as u64, &error)); + } + request.features = scene.required_features(); + solidcraft_engine::render::resolve_request(&[app.session.render_backend()], &request).map_err(|e| e.to_string())?; + let key = app.render_workspace.key.ok_or(crate::i18n::tr("render.error_no_geometry"))?; + if scene.bounds.is_empty() { + return Err(crate::i18n::tr("render.error_visible_solid").into()); + } + let camera = app.cam; + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye(); + let highlight_key = crate::viewport::highlight_key(app); + if highlight_key != app.viewport.hl_key { + let overlay = crate::viewport::build_highlight(app); + if let Ok(mut slot) = app.viewport.hl_slot.lock() { + *slot = Some(overlay); + } + app.viewport.hl_key = highlight_key; + } + let slot = app.render_workspace.slot.clone(); + let callback = ViewportCallback(Frame { + product_lights: Some(light::preview(app)?), + product_exposure_ev: exposure, + product: true, + upload_error: Some(app.render_workspace.upload_error.clone()), + key, + slot: slot.clone(), + sketch_key: 0, + sketch_slot: slot.clone(), + hl_key: app.viewport.hl_key, + hl_slot: app.viewport.hl_slot.clone(), + pv_key: 0, + pv_slot: slot, + pv_hide: false, + view_proj: camera.view_proj(f64::from(rect.width() / rect.height().max(1.0)), radius).to_f32(), + back: camera.back().to_f32(), + size_px: [rect.width() * ppp, rect.height() * ppp], + clip: [0.0; 4], + cap: [0.0; 4], + images: Vec::new(), + points: Vec::new(), + analysis: [0.0; 8], + analysis_colors: [0.0; 36], + access: None, + outline: false, + // Product rendering has its own lighting; AO is a Design viewport setting. + ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, + eye: [eye.x as f32, eye.y as f32, eye.z as f32, if camera.fov > 0.0 { 1.0 } else { 0.0 }], + ssaa: if width < full.0 { width as f32 / full.0 as f32 } else { 1.0 }, + hover_tint: [f32::from(Tokens::get().hover_face_lift) / 255.0; 3], + selection_tint: { + let c = Tokens::get().body_selected; + [f32::from(c.r()) / 255.0, f32::from(c.g()) / 255.0, f32::from(c.b()) / 255.0] + }, + }); + ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, callback)); + Ok(()) + })(); + if let Err(error) = result { + preview_error(app, ui, rect, &error); + } + shot::overlay(app, ui, viewport); + crate::viewport::axis_view(app, ui, viewport); + crate::navigation_bar_view::show(app, ui, viewport); +} + +/// Apply validated UI requests after the same registry call used by automation. +pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Value) -> Result<(), String> { + match id { + "render.interactive" => { + let input: solidcraft_engine::schema::render_ui::InteractiveParams = + serde_json::from_value(reply.clone()).map_err(|error| error.to_string())?; + interactive::apply_command(app, input.action)?; + } + "render.preflight.copy" => { + app.render_workspace.clipboard_text = Some(reply["text"].as_str().ok_or("invalid check report")?.to_string()); + } + "render.output.size" => { + let width = reply["width"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output width")?; + let height = reply["height"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output height")?; + if cpu::image_limits(app).fit(u64::from(width), u64::from(height), None) != Some((u64::from(width), u64::from(height))) { + return Err(app.tr("render.output_over_budget").into()); + } + app.render_workspace.view.inspector.resolution.custom = reply["custom"].as_bool().unwrap_or(false); + app.render_workspace.view.draft.width = width; + app.render_workspace.view.draft.height = height; + app.render_workspace.view.dirty = true; + } + "render.result.view" | "render.result.close" => { + let view = reply["view"].as_str().ok_or("invalid result view")?; + if view == "actual" && reduced_display(app) { + return Err(app.tr("render.result_reduced_display").into()); + } + app.render_workspace.view.result = view != "model"; + match view { + "fit" => fit_result(app), + "actual" => app.render_workspace.view.result_scale = ResultScale::Actual, + _ => {} + } + app.cancel_view_animation(); + app.viewport.nav = None; + app.viewport.key_hold = None; + app.viewport.orbit_free = None; + } + "render.result.copy" => { + let job = serde_json::from_value(reply["frame"]["job"].clone()).map_err(|e| e.to_string())?; + let frame = app + .session + .render_job_handle(job) + .map_err(|e| e.to_string())? + .frame() + .map_err(|e| e.to_string())? + .ok_or_else(|| app.tr("render.ribbon_no_result").to_string())?; + let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, RenderLimits::default(), 4096)?; + app.render_workspace.clipboard_image = Some(image); + } + _ => {} + } + Ok(()) +} + +pub(crate) fn progress_pill(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + if !ribbon::busy(app) { + return false; + } + let Some(job) = app.render_workspace.view.job else { return false }; + let Ok(status) = app.session.execute("render.status", &json!({"job":job})) else { return false }; + let phase = status["progress"]["phase"].as_str().unwrap_or("unknown"); + if !matches!(phase, "queued" | "preparing" | "running" | "encoding" | "cancelling") { + return false; + } + let done = status["progress"]["done"].as_u64().unwrap_or(0); + let total = status["progress"]["total"].as_u64().unwrap_or(1).max(1); + let fraction = (done as f64 / total as f64).clamp(0.0, 1.0) as f32; + let phase_key = format!("render.image_{phase}"); + let name = app.render_workspace.view.job_shot.as_ref().unwrap_or(&app.render_workspace.view.name).clone(); + let cancel = + crate::ui_kit::progress_action(ui, &format!("{name} · {} · {:.0}%", app.tr(&phase_key), fraction * 100.0), fraction, app.tr_label("Cancel")); + crate::scenario::publish_target("render:progress-cancel", cancel.rect); + if cancel.clicked() { + app.start("render.cancel"); + } + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + true +} + +pub(crate) fn environment_overlay(app: &mut SolveApp, ui: &mut egui::Ui, viewport: egui::Rect) { + environment::ring_overlay(app, ui, viewport); +} + +pub(crate) fn interactive_command_info(app: &SolveApp, command: &solidcraft_engine::CommandSpec) -> solidcraft_engine::CommandInfo { + let mut info = ribbon::command_info(app, command); + // A drawing tool on the SKETCH tab kept shown outside a sketch starts one (#7904). + if crate::workspace::starts_a_sketch(app, command.id) { + info.enabled = true; + info.disabled_reason = None; + } + info +} +pub(crate) fn start_interactive(app: &mut SolveApp, id: &str) -> bool { + let handled = assign::start(app, id) || ribbon::start(app, id); + // Opening Appearance Advanced must still reach its atmosphere controls after leaving Wear. + if handled + && id == "render.aging.describe" + && app.render_workspace.view.inspector.page == inspector::Page::Appearance + && app.render_workspace.view.selection == RenderSelection::Wear + { + let _ = app.run("view.render_select", json!({"kind":"nothing"})); + // Clearing semantic focus routes to Scene; retain the explicit Advanced destination. + app.render_workspace.view.inspector.page = inspector::Page::Appearance; + } + handled +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_cpu.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_cpu.rs new file mode 100644 index 000000000..2140552ed --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_cpu.rs @@ -0,0 +1,857 @@ +//! Transient CPU image controls; engine commands own file capture and admission. +use serde_json::{Value, json}; +use solidcraft_engine::render::job::{CpuBudget, CpuDielectricTransport, RaytraceEnvironmentOptions, ReflectionBody, ReflectionMode}; + +use super::hdr; +use crate::{SolveApp, ui_kit}; + +pub(super) fn validate_progressive_image(app: &SolveApp) -> Result<(), String> { + if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace { + let view = &app.render_workspace.view; + view.raytrace.budget.validate_image(view.draft.width, view.draft.height, view.raytrace.progressive).map_err(|error| error.to_string())?; + } + Ok(()) +} + +pub(super) fn image_limits(app: &SolveApp) -> solidcraft_engine::render::RenderLimits { + if app.render_workspace.view.method == super::ImageMethod::GpuRaytrace { + return solidcraft_engine::render::job::GPU_PATH_LIMITS; + } + if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace { + return Default::default(); + } + let options = &app.render_workspace.view.raytrace; + let mut limits = options.budget.image_limits(options.progressive.is_some()); + if let Some(progressive) = options.progressive { + limits.max_pixels = limits.max_pixels.min(options.budget.limits().max_camera_samples / u64::from(progressive.samples_per_pixel.max(1))); + } + limits +} + +fn budget_key(budget: CpuBudget) -> &'static str { + match budget { + CpuBudget::Compact => "render.children.compact", + CpuBudget::Studio => "render.children.studio", + CpuBudget::Workstation => "render.children.workstation", + } +} + +fn budget_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let budgets = CpuBudget::ALL; + let mut selected = budgets.iter().position(|b| *b == app.render_workspace.view.raytrace.budget).unwrap_or(0); + let labels = budgets.map(|b| app.tr(budget_key(b)).to_string()); + let response = ui.scope(|ui| { + ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { + compact: true, + targets: &["render.cpu_budget_compact", "render.cpu_budget_studio", "render.cpu_budget_workstation"], + ..Default::default() + }, + ) + }); + crate::scenario::publish_rect("render:cpu-budget", response.response.rect); + if response.inner + && let Some(budget) = budgets.get(selected) + { + app.render_workspace.view.raytrace.budget = *budget; + app.render_workspace.view.dirty = true; + } + let limits = app.render_workspace.view.raytrace.budget.limits(); + let note = format!( + "{}: {:.2} GiB · {}: {} · {}: {} · {}: {}. {}", + app.tr("render.cpu_budget_memory"), + limits.max_job_bytes as f64 / 1_073_741_824.0, + app.tr("render.cpu_budget_triangles"), + limits.max_triangles, + app.tr("render.cpu_budget_bodies"), + limits.max_bodies, + app.tr("render.cpu_progressive_spp"), + limits.max_samples_per_pixel, + app.tr("render.cpu_budget_not_guarantee") + ); + ui_kit::text(ui, ¬e, ui_kit::Text::Note("render.cpu_budget_help")); +} +fn set_progressive(app: &mut SolveApp, enabled: bool) { + let options = &mut app.render_workspace.view.raytrace; + if enabled { + options.progressive.get_or_insert_default(); + options.primary_samples = 1; + } else { + options.progressive = None; + } + app.render_workspace.view.dirty = true; +} + +/// The saved CPU choice is independent of sampling, profiles and material bindings. +fn set_dielectric_transport(app: &mut SolveApp, policy: CpuDielectricTransport) -> bool { + let view = &mut app.render_workspace.view; + if view.raytrace.dielectric_transport == policy { + return false; + } + view.raytrace.dielectric_transport = policy; + view.dirty = true; + true +} + +fn dielectric_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let mut selected = usize::from(app.render_workspace.view.raytrace.dielectric_transport == CpuDielectricTransport::StrictTir); + let labels = [app.tr("render.cpu_glass_standard").to_string(), app.tr("render.cpu_glass_continue").to_string()]; + let label = app.tr("render.cpu_glass_label").to_string(); + if ui_kit::row(ui, &label, |ui| { + ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { compact: true, targets: &["render:cpu-glass-standard", "render:cpu-glass-continue"], ..Default::default() }, + ) + }) { + set_dielectric_transport(app, if selected == 1 { CpuDielectricTransport::StrictTir } else { CpuDielectricTransport::LegacyBounded }); + } + ui_kit::text(ui, app.tr("render.cpu_glass_help"), ui_kit::Text::Note("render.cpu_glass_help")); +} + +pub(super) fn progressive_controls(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + budget_controls(app, ui); + dielectric_controls(app, ui); + let mut selected = usize::from(app.render_workspace.view.raytrace.progressive.is_some()); + let labels = [app.tr("render.children.single_image").to_string(), app.tr("render.cpu_progressive").to_string()]; + let response = ui.scope(|ui| { + ui_kit::row(ui, app.tr("render.children.sampling"), |ui| { + ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { compact: true, targets: &["render:cpu-fixed", "render:cpu-progressive"], ..Default::default() }, + ) + }) + }); + crate::scenario::publish_target("render:cpu-sampling", response.response.rect); + if response.inner { + set_progressive(app, selected == 1); + } + let enabled = app.render_workspace.view.raytrace.progressive.is_some(); + let mut options = app.render_workspace.view.raytrace.progressive.unwrap_or_default(); + if !enabled { + ui_kit::text(ui, app.tr("render.children.progressive_reason"), ui_kit::Text::Note("render.children.progressive_reason")); + } + ui.add_enabled_ui(enabled, |ui| { + let response = ui_kit::row(ui, app.tr("render.cpu_progressive_spp"), |ui| { + ui_kit::number_field(ui, &mut options.samples_per_pixel, 1..=solidcraft_engine::render::job::MAX_CPU_SAMPLES_PER_PIXEL, 1.0, "") + }); + app.render_workspace.view.dirty |= response.changed(); + crate::scenario::publish_target("render:cpu-spp", response.rect); + let response = + ui_kit::row(ui, app.tr("render.cpu_progressive_seed"), |ui| ui_kit::number_field(ui, &mut options.seed, 0..=u32::MAX, 1.0, "")); + app.render_workspace.view.dirty |= response.changed(); + crate::scenario::publish_target("render:cpu-seed", response.rect); + }); + if enabled { + app.render_workspace.view.raytrace.progressive = Some(options); + } + ui_kit::text(ui, app.tr("render.cpu_progressive_help"), ui_kit::Text::Note("render.cpu_progressive_help")); + enabled +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Environment { + #[default] + None, + Constant, + Hdr, +} + +#[derive(Clone, Debug)] +pub(super) struct View { + #[cfg(test)] + pub selected_body: Option, + #[cfg(test)] + pub body_filter: String, + pub environment: Environment, + pub hdr: hdr::Input, + pub rotation_rad: f64, + pub intensity: f64, + pub samples: u32, + pub color: [f64; 3], + pub checked: Option, + /// Request-local, explicitly selected certified-box nesting; never inferred from GPU state. + pub nested_media: bool, + bindings: std::collections::BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Target { + ordinal: usize, + feature: u64, + component: u64, +} + +#[derive(Clone, Debug)] +struct Binding { + target: Target, + revision: u64, + document: std::sync::Weak, + // Interactive may follow appearance/render-only edits only while this exact + // evaluated world survives in the same open document. Weak ownership avoids + // retaining old geometry and prevents pointer reuse after the world drops. + session_uid: u64, + world: std::sync::Weak, +} + +#[derive(Clone, Debug)] +pub(super) struct Checked { + pub request: Value, + pub revision: u64, + pub environment: Value, + document: std::sync::Weak, +} + +impl Default for View { + fn default() -> Self { + Self { + #[cfg(test)] + selected_body: None, + #[cfg(test)] + body_filter: String::new(), + environment: Environment::None, + hdr: hdr::Input::default(), + rotation_rad: 0.0, + intensity: 1.0, + samples: 16, + color: [1.0; 3], + checked: None, + nested_media: false, + bindings: Default::default(), + } + } +} + +fn valid_name(name: &str) -> bool { + !name.is_empty() && name.len() <= 128 && !name.chars().any(char::is_control) +} + +fn target(app: &SolveApp, name: &str) -> Option { + if !valid_name(name) || app.session.model.is_stale() { + return None; + } + let world = app.session.world_state(); + let mut matches = world.bodies.iter().filter(|body| app.session.body_visible(&body.name)).enumerate().filter(|(_, body)| body.name == name); + let (ordinal, body) = matches.next()?; + if matches.next().is_some() { + return None; + } + Some(Target { ordinal, feature: body.feature, component: body.component }) +} + +fn unique_visible_body(app: &SolveApp, name: &str) -> bool { + target(app, name).is_some() +} + +fn binding_current(app: &SolveApp, name: &str) -> bool { + app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| { + binding.revision == app.session.revision + && std::sync::Weak::ptr_eq(&binding.document, &std::sync::Arc::downgrade(&app.session.doc)) + && target(app, name).as_ref() == Some(&binding.target) + }) +} + +// Unlike final Check/Start, Interactive may refresh harmless appearance/render +// edits. The engine retains the exact world Arc for those edits (refresh_render). +// No geometry extraction, cold meshing, name-only rebinding or revision stamping. +fn binding_interactive_world_current(app: &SolveApp, name: &str) -> bool { + app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| { + binding.session_uid == app.session.uid + && !app.session.model.is_stale() + && app + .session + .interactive_cached_world_state() + .is_some_and(|world| std::sync::Weak::ptr_eq(&binding.world, &std::sync::Arc::downgrade(&world))) + }) +} + +fn binding_interactive_current(app: &SolveApp, name: &str) -> bool { + binding_interactive_world_current(app, name) + && app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| target(app, name).as_ref() == Some(&binding.target)) +} + +pub(super) fn revalidate(app: &mut SolveApp, name: &str) -> Result<(), String> { + let current = target(app, name).ok_or_else(|| app.tr("render.cpu_body_missing").to_string())?; + if app.render_workspace.view.cpu.bindings.get(name).is_none_or(|binding| binding.target != current) { + return Err(app.tr("render.cpu_body_missing").to_string()); + } + let revision = app.session.revision; + let document = std::sync::Arc::downgrade(&app.session.doc); + let world = std::sync::Arc::downgrade(&app.session.world_state()); + let session_uid = app.session.uid; + if let Some(binding) = app.render_workspace.view.cpu.bindings.get_mut(name) { + binding.revision = revision; + binding.document = document; + binding.session_uid = session_uid; + binding.world = world; + } + Ok(()) +} + +/// A removed, hidden or ambiguous body never silently becomes a different target. +pub(super) fn set_reflection(app: &mut SolveApp, name: &str, mode: Option) -> Result<(), String> { + let selected = if mode.is_some() { Some(target(app, name).ok_or_else(|| app.tr("render.cpu_body_missing").to_string())?) } else { None }; + // Changing the mode of an existing row is not a new body selection. Only an + // explicit confirmation of the same target, or Off followed by Add, may + // establish a fresh binding after the document or body identity changes. + if mode.is_some() + && app.render_workspace.view.raytrace.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| entry.body == name)) + && !binding_current(app, name) + { + return Err(app.tr("render.cpu_binding_stale").to_string()); + } + let message = app.tr("render.cpu_reflection_limit").to_string(); + let options = &mut app.render_workspace.view.raytrace; + if let Some(mode) = mode { + let mut reflections = options.reflections.clone().unwrap_or_default(); + if let Some(entry) = reflections.bodies.iter_mut().find(|entry| entry.body == name) { + entry.mode = mode; + } else { + if reflections.bodies.len() >= 64 { + return Err(message); + } + reflections.bodies.try_reserve_exact(1).map_err(|_| message.clone())?; + if reflections.bodies.capacity() > 64 { + return Err(message); + } + reflections.bodies.push(ReflectionBody { body: name.to_string(), mode }); + } + options.reflections = Some(reflections); + } else if let Some(reflections) = &mut options.reflections { + reflections.bodies.retain(|entry| entry.body != name); + if reflections.bodies.is_empty() { + options.reflections = None; + } + } + if let Some(target) = selected { + app.render_workspace.view.cpu.bindings.insert( + name.to_string(), + Binding { + target, + revision: app.session.revision, + document: std::sync::Arc::downgrade(&app.session.doc), + session_uid: app.session.uid, + world: std::sync::Arc::downgrade(&app.session.world_state()), + }, + ); + } else { + app.render_workspace.view.cpu.bindings.remove(name); + } + Ok(()) +} + +/// Shared by the parent Check and Start builder. This does not read an HDR file. +pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> { + params_with_binding_policy(app, params, binding_current) +} + +/// Interactive-only wire lowering. This does not requalify final Check/Start, +/// change a stored binding or read an HDR file; the engine still captures and admits it. +pub(super) fn params_interactive(app: &SolveApp, params: &mut Value) -> Result<(), String> { + // runtime_image_request composes the explicit material DTO immediately + // after these numerical controls, exactly once. The engine then converts + // the separate Interactive request to progressive sampling and admits its + // complete optics; a Fixed editor never licenses dropping that intent. + // Refuse unproved bound worlds before shared lowering checks visibility via + // target()/world_state(). Empty reflections never require a warm world. + if app + .render_workspace + .view + .raytrace + .reflections + .as_ref() + .is_some_and(|r| r.bodies.iter().any(|entry| !binding_interactive_world_current(app, &entry.body))) + { + return Err(app.tr("render.cpu_binding_stale").to_string()); + } + params_with_binding_policy(app, params, binding_interactive_current) +} + +fn params_with_binding_policy(app: &SolveApp, params: &mut Value, current: fn(&SolveApp, &str) -> bool) -> Result<(), String> { + let base = &app.render_workspace.view.raytrace; + if base.anisotropic_faces.iter().any(Option::is_some) + || !base.dielectrics.is_empty() + || base.environment.is_some() + || base.surface_effects.is_some() + || base.emissions.is_some() + { + return Err(app.tr("render.cpu_options_pending").to_string()); + } + if base.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| !unique_visible_body(app, &entry.body))) { + return Err(app.tr("render.cpu_body_missing").to_string()); + } + if base.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| !current(app, &entry.body))) { + return Err(app.tr("render.cpu_binding_stale").to_string()); + } + let view = &app.render_workspace.view.cpu; + let mut options = base.clone(); + if options.area_samples.is_some_and(|n| !matches!(n, 1 | 4 | 16 | 64)) { + return Err(crate::i18n::tr("render.error_area_samples").into()); + } + if options.area_lights.as_ref().is_none_or(Vec::is_empty) { + options.area_samples = None; + options.seed = None; + } + options.exposure_ev = app.render_workspace.view.draft.exposure_ev; + // Runtime CPU requests keep the same single saved EV authority as typed jobs. + params["settings"]["exposure_ev"] = json!(0.0); + if view.environment != Environment::None { + if !view.intensity.is_finite() || !(0.0..=64.0).contains(&view.intensity) { + return Err(app.tr("render.cpu_environment_bounds").to_string()); + } + match view.environment { + Environment::Constant => options.environment = Some(RaytraceEnvironmentOptions { color: view.color, intensity: view.intensity }), + Environment::Hdr => { + if !view.rotation_rad.is_finite() || view.rotation_rad.abs() > 1e6 || !matches!(view.samples, 1 | 4 | 16 | 64) { + return Err(app.tr("render.cpu_environment_bounds").to_string()); + } + let mut environment = hdr::request(app, hdr::Target::Cpu)?; + environment["rotation_radians"] = json!(view.rotation_rad); + environment["intensity"] = json!(view.intensity); + environment["samples"] = json!(view.samples); + params["environment"] = environment; + } + Environment::None => {} + } + } + options.validate().map_err(|error| error.to_string())?; + params["integrator"] = json!("raytrace"); + params["raytrace"] = json!(options); + Ok(()) +} + +#[cfg(test)] +pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { + for (id, key, section) in [ + ("render_cpu_reflections", "render.cpu_reflections", 0), + ("render_cpu_environment", "render.cpu_environment", 1), + ("render_cpu_lights", "render.cpu_lights", 2), + ] { + let title = app.tr(key).to_string(); + ui_kit::section(ui, id, &title, false, |ui| match section { + 0 => reflection_controls(app, ui), + 1 => environment_controls(app, ui), + _ => light_controls(app, ui), + }); + } + ui.small(app.tr("render.cpu_runtime_help")); +} + +#[cfg(test)] +pub(super) fn reflection_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.small(app.tr("render.cpu_reflection_help")); + let entries = app.render_workspace.view.raytrace.reflections.as_ref().map(|r| r.bodies.clone()).unwrap_or_default(); + for entry in entries { + ui.label(&entry.body); + if !binding_current(app, &entry.body) { + ui.small(app.tr("render.cpu_binding_stale")); + if ui_kit::button(ui, app.tr("render.cpu_binding_confirm"), ui_kit::Button::Normal).clicked() + && let Err(error) = revalidate(app, &entry.body) + { + app.set_status(error, true); + } + } + let selected = match entry.mode { + ReflectionMode::Mirror => "render.cpu_reflection_mirror", + ReflectionMode::RoughSpecular => "render.cpu_reflection_rough", + }; + let label = app.tr(selected).to_string(); + let mode_control = ui_kit::dropdown_menu(ui, ("cpu_reflection_mode", &entry.body), &label, |ui| { + for (mode, key) in [ + (None, "render.cpu_reflection_off"), + (Some(ReflectionMode::Mirror), "render.cpu_reflection_mirror"), + (Some(ReflectionMode::RoughSpecular), "render.cpu_reflection_rough"), + ] { + let enabled = mode.is_none() || binding_current(app, &entry.body); + if ui.add_enabled_ui(enabled, |ui| ui_kit::list_picker(ui, key, app.tr(key), mode == Some(entry.mode))).inner.clicked() { + if let Err(error) = set_reflection(app, &entry.body, mode) { + app.set_status(error, true); + } + ui.close(); + } + } + }); + crate::scenario::publish_handle(&format!("render:cpu-reflection-mode:{}", entry.body), mode_control.rect.center()); + } + let hint = app.tr("render.cpu_body_filter").to_string(); + ui_kit::bounded_cell_editor(ui, ui.id().with("cpu_body_filter"), &mut app.render_workspace.view.cpu.body_filter, &hint, false, 128); + let selected = app.render_workspace.view.cpu.selected_body.clone(); + let label = selected.clone().unwrap_or_else(|| app.tr("render.cpu_body_choose").to_string()); + let world = app.session.world_state(); + let filter = app.render_workspace.view.cpu.body_filter.to_lowercase(); + let candidates: Vec<_> = world + .bodies + .iter() + .filter(|body| app.session.body_visible(&body.name) && body.name.to_lowercase().contains(&filter)) + .take(257) + .map(|body| body.name.as_str()) + .collect(); + let dropdown = ui_kit::dropdown_menu(ui, "cpu_reflection_body", &label, |ui| { + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for (shown, name) in candidates.iter().enumerate() { + if shown == 256 { + ui.small(app.tr("render.cpu_body_filter_more")); + break; + } + let response = + ui.add_enabled_ui(valid_name(name), |ui| ui_kit::list_picker(ui, name, name, selected.as_deref() == Some(*name))).inner; + if response.clicked() { + app.render_workspace.view.cpu.selected_body = Some((*name).to_string()); + ui.close(); + } + } + }); + }); + crate::scenario::publish_handle("render:cpu-reflection-body", dropdown.rect.center()); + let can_add = selected.as_ref().is_some_and(|name| unique_visible_body(app, name)) + && app.render_workspace.view.raytrace.reflections.as_ref().is_none_or(|r| r.bodies.len() < 64); + let add = ui_kit::button(ui, app.tr("render.cpu_reflection_add"), ui_kit::Button::Enabled(can_add)); + crate::scenario::publish_handle("render:cpu-reflection-add", add.rect.center()); + if add.clicked() + && let Some(name) = selected + && let Err(error) = set_reflection(app, &name, Some(ReflectionMode::RoughSpecular)) + { + app.set_status(error, true); + } + reflection_sampling_controls(app, ui); +} + +/// Existing global reflection budget, shared during the Sampling-editor migration. +pub(super) fn reflection_sampling_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let depth = app.tr("render.cpu_reflection_depth").to_string(); + let samples = app.tr("render.cpu_reflection_samples").to_string(); + if let Some(reflections) = &mut app.render_workspace.view.raytrace.reflections { + ui_kit::row(ui, &depth, |ui| ui_kit::number_field(ui, &mut reflections.max_bounces, 1..=8, 1.0, "")); + ui_kit::row(ui, &samples, |ui| ui_kit::number_field(ui, &mut reflections.samples, 1..=64, 1.0, "")); + } else { + ui.small(app.tr("render.cpu_reflection_empty")); + } +} + +#[cfg(test)] +pub(super) fn environment_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let selected = app.render_workspace.view.cpu.environment; + let key = match selected { + Environment::None => "render.cpu_environment_none", + Environment::Constant => "render.cpu_environment_constant", + Environment::Hdr => "render.studio_hdr", + }; + let label = app.tr(key).to_string(); + ui_kit::dropdown_menu(ui, "cpu_environment_kind", &label, |ui| { + for (value, key) in [ + (Environment::None, "render.cpu_environment_none"), + (Environment::Constant, "render.cpu_environment_constant"), + (Environment::Hdr, "render.studio_hdr"), + ] { + if ui_kit::list_picker(ui, key, app.tr(key), value == selected).clicked() { + app.render_workspace.view.cpu.environment = value; + ui.close(); + } + } + }); + if app.render_workspace.view.cpu.environment == Environment::None { + return; + } + if app.render_workspace.view.cpu.environment == Environment::Constant { + let color = app.tr("render.cpu_linear_color").to_string(); + vector(ui, &color, &mut app.render_workspace.view.cpu.color, 0.0..=1.0, 0.01, ""); + ui.small(app.tr("render.cpu_constant_help")); + } else { + hdr::controls(app, ui, hdr::Target::Cpu); + ui.small(app.tr("render.cpu_hdr_help")); + ui.label(app.tr("render.studio_rotation")); + let mut degrees = app.render_workspace.view.cpu.rotation_rad.to_degrees(); + if ui_kit::number_field(ui, &mut degrees, -1e6_f64.to_degrees()..=1e6_f64.to_degrees(), 1.0, "°").changed() { + app.render_workspace.view.cpu.rotation_rad = degrees.to_radians(); + } + ui.label(app.tr("render.cpu_environment_samples")); + let samples = app.render_workspace.view.cpu.samples; + ui_kit::dropdown_menu(ui, "cpu_hdr_samples", &samples.to_string(), |ui| { + for value in [1, 4, 16, 64] { + if ui_kit::list_picker(ui, &value.to_string(), &value.to_string(), value == samples).clicked() { + app.render_workspace.view.cpu.samples = value; + ui.close(); + } + } + }); + ui.small(app.tr("render.cpu_hdr_reflection_help")); + } + ui.label(app.tr("render.studio_intensity")); + ui_kit::number_field(ui, &mut app.render_workspace.view.cpu.intensity, 0.0..=64.0, 0.1, ""); + ui.small(app.tr("render.cpu_environment_background")); +} + +#[cfg(test)] +fn vector(ui: &mut egui::Ui, label: &str, value: &mut [f64; 3], range: std::ops::RangeInclusive, speed: f64, suffix: &str) { + ui.label(label); + ui.horizontal(|ui| { + for component in value { + ui_kit::number_field(ui, component, range.clone(), speed, suffix); + } + }); +} + +#[cfg(test)] +pub(super) fn light_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + super::light::lighting(app, ui); +} + +pub(super) fn record_checked(app: &mut SolveApp, params: &Value, reply: &Value) { + if params["integrator"] == "raytrace" || params["settings"]["job"]["method"] == "cpu_raytrace" { + app.render_workspace.view.cpu.checked = Some(Checked { + request: params.clone(), + revision: app.session.revision, + environment: reply["environment"].clone(), + document: std::sync::Arc::downgrade(&app.session.doc), + }); + } +} + +fn metadata(app: &SolveApp, ui: &mut egui::Ui, info: &Value) { + let Some(hash) = info["source_sha256"].as_array().filter(|hash| hash.len() == 32) else { return }; + let digest: Option> = hash.iter().map(|byte| byte.as_u64().and_then(|n| u8::try_from(n).ok())).collect(); + let Some(digest) = digest else { return }; + let digest: String = digest.into_iter().map(|byte| format!("{byte:02x}")).collect(); + let width = info["header"]["width"].as_u64().unwrap_or(0); + let height = info["header"]["height"].as_u64().unwrap_or(0); + ui.label(format!("{width} × {height} px")); + ui.label(format!("{}: {}", app.tr("render.cpu_environment_samples"), info["samples"].as_u64().unwrap_or(0))); + ui.label(format!("{}: {:.2}", app.tr("render.studio_intensity"), info["intensity"].as_f64().unwrap_or(0.0))); + ui.label(format!("{}: {:.1}°", app.tr("render.studio_rotation"), info["rotation_radians"].as_f64().unwrap_or(0.0).to_degrees())); + ui.label(format!("SHA-256: {digest}")); +} + +pub(super) fn checked_status(app: &SolveApp, ui: &mut egui::Ui, params: Option<&Value>) { + if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace { + return; + } + if let Some(checked) = &app.render_workspace.view.cpu.checked { + let title = app.tr("render.cpu_last_check").to_string(); + ui_kit::section(ui, "cpu_last_check", &title, false, |ui| { + if params != Some(&checked.request) + || checked.revision != app.session.revision + || !std::sync::Weak::ptr_eq(&checked.document, &std::sync::Arc::downgrade(&app.session.doc)) + { + ui.small(app.tr("render.cpu_check_changed")); + } + metadata(app, ui, &checked.environment); + ui.small(app.tr("render.cpu_check_capture_help")); + }); + } +} + +pub(super) fn captured_status(app: &SolveApp, ui: &mut egui::Ui, status: &Value) { + if status["request"]["integrator"] == "raytrace" && status["environment"]["source_sha256"].is_array() { + let title = app.tr("render.cpu_captured_hdr").to_string(); + ui_kit::section(ui, "cpu_captured_hdr", &title, false, |ui| metadata(app, ui, &status["environment"])); + } +} + +#[cfg(test)] +fn dielectric_policy_harness() -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = super::ImageMethod::CpuRaytrace; + h.app.render_workspace.view.result = false; + h.app.render_workspace.view.name = "Policy".into(); + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.exposure_ev = 0.0; + h.app.render_workspace.view.raytrace = Default::default(); + h.app.render_workspace.view.cpu = View::default(); + h +} + +#[cfg(test)] +#[test] +fn cpu_glass_policy_no_binding_ui_snapshot_save_reopen_load_preserves_portable_choice() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = dielectric_policy_harness(); + assert!(!set_dielectric_transport(&mut h.app, CpuDielectricTransport::LegacyBounded)); + assert!(set_dielectric_transport(&mut h.app, CpuDielectricTransport::StrictTir)); + assert!(h.app.render_workspace.view.dirty); + assert!(!super::setups::has_runtime_inputs(&h.app), "the choice itself is portable"); + let saved = super::setups::snapshot(&h.app).unwrap(); + let Some(RenderJob::CpuRaytrace { options }) = &saved.job else { panic!("CPU draft changed method") }; + assert_eq!(options.dielectric_transport, CpuDielectricTransport::StrictTir); + let wire = super::image_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["job"]["options"]["dielectric_transport"], "strict_tir"); + super::setups::save(&mut h.app).unwrap(); + let document = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = solidcraft_engine::Session::new(document); + h.app.render_workspace.view.raytrace.dielectric_transport = CpuDielectricTransport::LegacyBounded; + super::setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.raytrace.dielectric_transport, CpuDielectricTransport::StrictTir); + assert_eq!(super::setups::snapshot(&h.app).unwrap(), saved); + assert_eq!(super::image_request(&h.app).unwrap()["settings"]["job"]["options"]["dielectric_transport"], "strict_tir"); + assert!(set_dielectric_transport(&mut h.app, CpuDielectricTransport::LegacyBounded)); + assert!(serde_json::to_value(super::setups::snapshot(&h.app).unwrap()).unwrap()["job"]["options"].get("dielectric_transport").is_none()); +} + +#[cfg(test)] +#[test] +fn cpu_glass_policy_numeric_lowering_and_active_light_filter_preserve_the_exact_choice() { + use solidcraft_engine::render::job::DirectionalLightOptions; + let mut h = dielectric_policy_harness(); + h.app.render_workspace.view.raytrace.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + h.app.render_workspace.view.lights.visibility.muted.insert("directional:0".into()); + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + set_dielectric_transport(&mut h.app, policy); + let source = h.app.render_workspace.view.raytrace.clone(); + for interactive in [false, true] { + let mut wire = json!({"settings":{"job":null}}); + if interactive { + params_interactive(&h.app, &mut wire).unwrap(); + } else { + params(&h.app, &mut wire).unwrap(); + } + super::materials::params(&h.app, &mut wire).unwrap(); + let wire = super::light::filter_request(&h.app, wire).unwrap(); + let options: solidcraft_engine::render::job::RaytraceOptions = serde_json::from_value(wire["raytrace"].clone()).unwrap(); + assert_eq!(options.dielectric_transport, policy); + assert_eq!(options.lights.as_ref().unwrap()[0].intensity, 0.0); + assert_eq!(h.app.render_workspace.view.raytrace, source, "transient visibility must not rewrite authored input"); + } + let portable = super::image_request(&h.app).unwrap(); + let options: solidcraft_engine::doc::render_settings::CpuJob = + serde_json::from_value(portable["settings"]["job"]["options"].clone()).unwrap(); + assert_eq!(options.dielectric_transport, policy); + } +} + +#[cfg(test)] +#[test] +fn cpu_glass_policy_selection_preserves_unsupported_opaque_reflection_and_advanced_intent() { + use solidcraft_engine::render::job::{EmissionSides, SurfaceEmission}; + let mut h = dielectric_policy_harness(); + h.app.session.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap(); + h.app.session.execute("render.scene", &json!({})).unwrap(); + let target = super::materials::read_targets(&mut h.app).unwrap().remove(0); + set_reflection(&mut h.app, &target.name, Some(ReflectionMode::Mirror)).unwrap(); + let authored = h.app.render_workspace.view.raytrace.clone(); + set_dielectric_transport(&mut h.app, CpuDielectricTransport::StrictTir); + assert_eq!(h.app.render_workspace.view.raytrace.reflections, authored.reflections); + assert!(super::image_request(&h.app).is_err()); + assert!(super::interactive_request(&h.app).is_err()); + assert_eq!(h.app.render_workspace.view.raytrace.reflections, authored.reflections); + assert_eq!(h.app.render_workspace.view.raytrace.dielectric_transport, CpuDielectricTransport::StrictTir); + h.app.render_workspace.view.raytrace.reflections = None; + h.app.render_workspace.view.raytrace.emissions = Some(vec![SurfaceEmission { + body_index: target.ordinal, + body: target.name, + color: [1.0, 0.5, 0.25], + strength: 1.0, + sides: EmissionSides::Front, + }]); + let authored = h.app.render_workspace.view.raytrace.clone(); + assert!(super::image_request(&h.app).is_err()); + assert!(super::interactive_request(&h.app).is_err()); + assert_eq!(h.app.render_workspace.view.raytrace, authored); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[test] +fn native_cpu_glass_policy_public_ui_check_start_and_interactive_preserve_real_material_and_visibility() { + use solidcraft_engine::render::job::interactive::VisualRevision; + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, DirectionalLightOptions, HostKind, Integrator, JobId, Phase}; + use solidcraft_engine::schema::render_ui::Action; + use std::time::Duration; + let host = CpuHost::for_platform().unwrap(); + assert_eq!(host.kind(), HostKind::NativeWorker); + host.validate_integrator(Integrator::Raytrace).unwrap(); + eprintln!("CPU_GLASS_POLICY_UI_BRANCH cpu_supported=true"); + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + let mut h = dielectric_policy_harness(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.session.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap(); + h.app.session.execute("render.scene", &json!({})).unwrap(); + set_dielectric_transport(&mut h.app, policy); + h.app.render_workspace.view.raytrace.lights = + Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + h.app.render_workspace.view.lights.visibility.muted.insert("directional:0".into()); + let target = super::materials::read_targets(&mut h.app).unwrap().remove(0); + let mut binding = super::materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.cpu_optics = true; + // Explicit index-matched certified box: this is capture/consumer + // acceptance, not a new oracle for general reflective glass quality. + binding.glass.ior = 1.0; + binding.glass.boundary = super::materials::Boundary::Box; + binding.glass.thickness = 0.0; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + assert!(super::setups::snapshot(&h.app).is_err(), "captured body bindings remain runtime-only"); + for progressive in [false, true] { + h.app.render_workspace.view.raytrace.progressive = progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 }); + let wire = super::image_request(&h.app).unwrap(); + assert_eq!(wire["raytrace"]["dielectrics"].as_array().unwrap().len(), 1); + let checked = h.app.session.execute("render.preflight", &wire).unwrap(); + record_checked(&mut h.app, &wire, &checked); + let revision = h.app.session.revision; + let other = + if policy == CpuDielectricTransport::StrictTir { CpuDielectricTransport::LegacyBounded } else { CpuDielectricTransport::StrictTir }; + set_dielectric_transport(&mut h.app, other); + assert_ne!(Some(&super::image_request(&h.app).unwrap()), h.app.render_workspace.view.cpu.checked.as_ref().map(|c| &c.request)); + assert_eq!(h.app.session.revision, revision); + set_dielectric_transport(&mut h.app, policy); + let started = h.app.session.execute("render.start", &wire).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let final_handle = h.app.session.render_job_handle(id).unwrap(); + let final_status = final_handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(final_status.progress.phase, Phase::Completed, "{:?}", final_status.error); + assert_eq!(json!(final_status.request), checked["request"]); + assert_eq!(final_status.request.raytrace.as_ref().unwrap().dielectric_transport, policy); + assert!(final_handle.frame().unwrap().is_some()); + let preview_wire = super::interactive_request(&h.app).unwrap(); + let context = h.app.session.interactive_render().unwrap(); + context.enable(VisualRevision { scene_generation: revision, visual_revision: 1 }, Duration::ZERO).unwrap(); + let ticket = context.capture(Duration::from_millis(201)).unwrap().unwrap(); + assert!(context.snapshot(&h.app.session, ticket, &preview_wire).unwrap().run().unwrap()); + let preview_handle = context.current().unwrap().unwrap(); + let status = preview_handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let captured = status.request.raytrace.as_ref().unwrap(); + assert_eq!(captured.dielectric_transport, policy); + assert_eq!(captured.dielectrics, final_status.request.raytrace.as_ref().unwrap().dielectrics); + assert_eq!(captured.lights.as_ref().unwrap()[0].intensity, 0.0); + assert_ne!(status.job, final_status.job); + assert!(final_handle.frame().unwrap().is_some(), "Interactive cannot replace the final source"); + context.disable().unwrap(); + } + // Exercise actual UI intent observation while paused, without a fake + // receiver or a second capture worker. No timer result is asserted. + super::interactive::apply_command(&mut h.app, Action::On).unwrap(); + let before = super::interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + super::interactive::apply_command(&mut h.app, Action::Pause).unwrap(); + let revision = h.app.session.revision; + set_dielectric_transport( + &mut h.app, + if policy == CpuDielectricTransport::StrictTir { CpuDielectricTransport::LegacyBounded } else { CpuDielectricTransport::StrictTir }, + ); + super::interactive::apply_command(&mut h.app, Action::Resume).unwrap(); + assert!(super::interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > before); + assert_eq!(h.app.session.revision, revision); + super::interactive::apply_command(&mut h.app, Action::Off).unwrap(); + h.app.render_workspace.view.materials.bindings[0].glass.shadows = true; + let shadow_wire = super::image_request(&h.app).unwrap(); + let shadow_options: solidcraft_engine::render::job::RaytraceOptions = serde_json::from_value(shadow_wire["raytrace"].clone()).unwrap(); + assert!(shadow_options.directional_shadow_transmission); + assert!(shadow_options.shadows); + assert_eq!(shadow_options.dielectric_transport, h.app.render_workspace.view.raytrace.dielectric_transport); + assert_eq!(shadow_options.dielectrics[0].ior, 1.0); + let shadow_check = h.app.session.execute("render.preflight", &shadow_wire).unwrap(); + let shadow_request: solidcraft_engine::render::job::ImageRequest = serde_json::from_value(shadow_check["request"].clone()).unwrap(); + assert_eq!(shadow_request.raytrace.as_ref(), Some(&shadow_options)); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission, "the bridge is request-local"); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + h.app.render_workspace.view.materials.bindings[0].glass.shadows = false; + h.app.render_workspace.view.materials.bindings[0].maps_enabled = true; + assert!(super::interactive_request(&h.app).is_err()); + assert!(h.app.render_workspace.view.materials.bindings[0].maps_enabled); + } +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_interactive.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_interactive.rs new file mode 100644 index 000000000..b54256052 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_interactive.rs @@ -0,0 +1,1252 @@ +//! Opt-in CPU checkpoints. This cache and its capture receiver are app-wide, +//! never part of saved setups, final results or export ownership. +use super::ImageMethod; +use crate::{SolveApp, theme::Tokens, ui_kit}; +use serde_json::{Value, json}; +#[cfg(not(target_arch = "wasm32"))] +use solidcraft_engine::render_interactive::Snapshot; +use solidcraft_engine::{ + render::job::{ + FrameInfo, HostKind, Integrator, JobId, + interactive::{CaptureTicket, State as Phase, VisualRevision}, + }, + render_interactive::{InteractiveRender, SceneIdentity}, + schema::render_ui::Action, +}; +use std::{sync::mpsc, time::Duration}; + +struct Intent { + scene: SceneIdentity, + uid: u64, + revision: u64, + camera: solidcraft_engine::render::Camera, + stale: bool, + request: Result, +} + +pub(super) struct Pending { + pub(super) uid: u64, + pub(super) ticket: CaptureTicket, + pub(super) receiver: mpsc::Receiver>, +} +#[derive(Clone, Copy, PartialEq, Eq)] +struct PixelKey { + job: JobId, + sequence: u32, + complete: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PartialCursor { + sequence: u64, + completed_passes: u32, + updated_prefix: u64, +} + +/// The source frontier is not a uniform samples-per-pixel count. +pub(super) fn partial_sample_count(completed_passes: u32, updated_prefix: u64, index: u64, pixels: u64, target: u32) -> Result { + if pixels == 0 + || index >= pixels + || updated_prefix >= pixels + || target == 0 + || completed_passes > target + || (completed_passes == target && updated_prefix != 0) + { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + completed_passes + .checked_add(u32::from(index < updated_prefix)) + .filter(|count| *count <= target) + .ok_or_else(|| crate::i18n::tr("render.error_provisional_identity").into()) +} + +/// Alpha denotes knowledge only in this additive provisional PNG contract. +/// Physical primary coverage has already been composited by the renderer. +pub(super) fn validate_partial_pixel(count: u32, covered: u32, pixel: egui::Color32, background: [u8; 3]) -> Result<(), String> { + if covered > count + || (count == 0 && pixel.a() != 0) + || (count > 0 && pixel.a() != 255) + || (count > 0 && covered == 0 && pixel != egui::Color32::from_rgb(background[0], background[1], background[2])) + { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + Ok(()) +} + +fn partial_advances(previous: Option, next: PartialCursor) -> bool { + next.sequence != 0 + && previous.is_none_or(|old| { + next.sequence > old.sequence && (next.completed_passes, next.updated_prefix) > (old.completed_passes, old.updated_prefix) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct PartialSampling { + plan: solidcraft_engine::render::job::PartialPreviewPlan, + cursor: PartialCursor, +} + +impl PartialSampling { + pub(super) fn source_unknown(&self) -> bool { + self.cursor.completed_passes == 0 + } + + pub(super) fn sample_range(&self) -> (u32, u32) { + (self.cursor.completed_passes, self.cursor.completed_passes + u32::from(self.cursor.updated_prefix != 0)) + } + + pub(super) fn sampled_source_pixels(&self) -> u64 { + if self.source_unknown() { self.cursor.updated_prefix } else { u64::from(self.plan.source_width()) * u64::from(self.plan.source_height()) } + } + + fn uniform_samples(&self) -> Option { + (self.cursor.completed_passes != 0 && self.cursor.updated_prefix == 0).then_some(self.cursor.completed_passes) + } +} + +pub(super) struct PartialExpectation<'a> { + pub(super) job: JobId, + pub(super) scene_generation: u64, + pub(super) request: &'a solidcraft_engine::render::job::ImageRequest, + pub(super) final_dimensions: [u32; 2], +} + +/// Only the actual caller's current job/ticket may construct this expectation. +/// Validating a descriptor is not authorization to attach a renderer or final. +pub(super) fn validate_partial_metadata( + expected: &PartialExpectation<'_>, + info: &solidcraft_engine::render::job::PartialPreviewInfo, + png_len: usize, + covered_len: usize, + previous: Option, +) -> Result, String> { + use solidcraft_engine::render::job::{AlphaConvention, ColourEncoding, PartialPreviewPlan, PartialPreviewProjection}; + let invalid = || crate::i18n::tr("render.error_provisional_identity").to_string(); + let progressive = expected.request.raytrace.as_ref().and_then(|options| options.progressive).ok_or_else(invalid)?; + progressive + .validate_image_with_budget(expected.request.width, expected.request.height, expected.request.cpu_budget()) + .map_err(|error| error.to_string())?; + let plan = PartialPreviewPlan::new(expected.request.width, expected.request.height).map_err(|error| error.to_string())?; + plan.validate().map_err(|error| error.to_string())?; + let source_pixels = u64::from(plan.source_width()) * u64::from(plan.source_height()); + if expected.request.integrator != Integrator::Raytrace + || expected.request.transparent_background + || expected.final_dimensions.contains(&0) + || info.frame.job != expected.job + || info.frame.scene_generation != expected.scene_generation + || info.frame.executor.as_str() != "cpu-raytrace" + || info.frame.encoding != ColourEncoding::Srgb + || info.frame.alpha != AlphaConvention::Straight + || (info.source_width, info.source_height) != (plan.source_width(), plan.source_height()) + || (info.frame.width, info.frame.height) != (plan.width(), plan.height()) + || info.projection != PartialPreviewProjection::TopLeftRepresentativeV1 + || u64::try_from(covered_len).map_err(|_| invalid())? != plan.pixels() + || info.frame.png_bytes != u64::try_from(png_len).map_err(|_| invalid())? + || info.frame.png_bytes > plan.encoded_limit().map_err(|error| error.to_string())? + || info.frame.png_sha256.len() != 64 + || !info.frame.png_sha256.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + || (info.completed_passes == 0 && info.updated_prefix == 0) + { + return Err(invalid()); + } + // This validates the global frontier even when reduced representatives hide + // the last unobserved source pixel. No fake uniform SPP from the preview size. + partial_sample_count(info.completed_passes, info.updated_prefix, 0, source_pixels, progressive.samples_per_pixel)?; + let cursor = PartialCursor { sequence: info.sequence, completed_passes: info.completed_passes, updated_prefix: info.updated_prefix }; + if cursor.sequence == 0 { + return Err(invalid()); + } + if let Some(old) = previous { + if old.plan != plan { + return Err(invalid()); + } + if cursor.sequence <= old.cursor.sequence { + return Ok(None); + } + } + if !partial_advances(previous.map(|old| old.cursor), cursor) { + return Err(invalid()); + } + Ok(Some(PartialSampling { plan, cursor })) +} + +/// Bounded O(M) borrowed-sidecar check. The shared plan supplies every source index. +pub(super) fn validate_partial_pixels( + sampling: PartialSampling, + target: u32, + covered: &[u32], + image: &egui::ColorImage, + background: [u8; 3], +) -> Result<(), String> { + let invalid = || crate::i18n::tr("render.error_provisional_identity").to_string(); + if image.size != [sampling.plan.width() as usize, sampling.plan.height() as usize] + || u64::try_from(image.pixels.len()).map_err(|_| invalid())? != sampling.plan.pixels() + || covered.len() != image.pixels.len() + { + return Err(invalid()); + } + let source_pixels = u64::from(sampling.plan.source_width()) * u64::from(sampling.plan.source_height()); + for (index, (pixel, coverage)) in image.pixels.iter().zip(covered).enumerate() { + let source_index = sampling.plan.source_index(index).map_err(|error| error.to_string())?; + let count = partial_sample_count( + sampling.cursor.completed_passes, + sampling.cursor.updated_prefix, + u64::try_from(source_index).map_err(|_| invalid())?, + source_pixels, + target, + )?; + validate_partial_pixel(count, *coverage, *pixel, background)?; + } + Ok(()) +} + +pub(super) fn decode_partial_image( + request: &solidcraft_engine::render::job::ImageRequest, + info: &solidcraft_engine::render::job::PartialPreviewInfo, + png: &[u8], + covered: &[u32], + sampling: PartialSampling, + max_texture_side: usize, +) -> Result { + let invalid = || crate::i18n::tr("render.error_provisional_identity").to_string(); + if (info.frame.width, info.frame.height) != (sampling.plan.width(), sampling.plan.height()) + || super::display_dimensions(info.frame.width, info.frame.height, max_texture_side)? != (info.frame.width, info.frame.height) + { + return Err(crate::i18n::tr("render.error_display_fit").into()); + } + let image = super::decode_render_image(png, info.frame.width, info.frame.height, super::captured_image_limits(request), max_texture_side)?; + let target = request.raytrace.as_ref().and_then(|options| options.progressive).ok_or_else(invalid)?.samples_per_pixel; + validate_partial_pixels(sampling, target, covered, &image, request.background)?; + Ok(image) +} + +pub(super) fn partial_request_due(previous: Option<(JobId, Duration)>, job: JobId, now: Duration) -> bool { + previous.is_none_or(|(old, when)| old != job || now.saturating_sub(when) >= Duration::from_millis(250)) +} + +fn capture_dimensions(request: &Value) -> Result<[u32; 2], String> { + let invalid = || crate::i18n::tr("render.error_provisional_identity").to_string(); + let settings = request.get("settings").ok_or_else(invalid)?; + let dimension = |key: &str| { + settings.get(key).and_then(Value::as_u64).and_then(|value| u32::try_from(value).ok()).filter(|value| *value != 0).ok_or_else(invalid) + }; + Ok([dimension("width")?, dimension("height")?]) +} + +/// Frozen with the real issued ticket; never refreshed to bless paused pixels. +/// A weak prepared-world identity does not retain CAD or prepare cold placements. +struct GeometryAlignment { + ticket: CaptureTicket, + uid: u64, + world: std::sync::Weak, + document: std::sync::Weak, + visibility: solidcraft_engine::doc::Visibility, + pending_moves: std::collections::BTreeMap, + active_component: u64, + active_occurrence_path: Option>, + active_sketch: Option, +} + +impl GeometryAlignment { + #[cfg(not(target_arch = "wasm32"))] + fn capture(app: &SolveApp, ticket: CaptureTicket) -> Option { + if !geometry_context_supported(app) { + return None; + } + let world = app.session.interactive_cached_world_state()?; + Some(Self { + ticket, + uid: app.session.uid, + world: std::sync::Arc::downgrade(&world), + document: std::sync::Arc::downgrade(&app.session.doc), + visibility: app.session.visibility.clone(), + pending_moves: app.session.pending_moves.clone(), + active_component: app.session.active_component, + active_occurrence_path: app.session.active_occurrence_path.clone(), + active_sketch: app.session.active_sketch, + }) + } + + fn is_current(&self, app: &SolveApp, job: JobId, revision: VisualRevision) -> bool { + self.ticket.job_id() == job + && self.ticket.revision() == revision + && geometry_context_supported(app) + && self.uid == app.session.uid + && self.document.upgrade().is_some_and(|accepted| { + // Render/appearance revisions may differ. Only ownership, placement + // and folder membership metadata can change the pickable scene. + std::sync::Arc::ptr_eq(&accepted, &app.session.doc) + || (accepted.marker == app.session.doc.marker + && accepted.occurrences == app.session.doc.occurrences + && accepted.body_components == app.session.doc.body_components + && accepted.body_offsets == app.session.doc.body_offsets + && accepted.browser_groups == app.session.doc.browser_groups + && accepted.components.iter().map(|component| (component.id, component.parent)).eq(app + .session + .doc + .components + .iter() + .map(|component| (component.id, component.parent)))) + }) + && self.visibility == app.session.visibility + && self.pending_moves == app.session.pending_moves + && self.active_component == app.session.active_component + && self.active_occurrence_path == app.session.active_occurrence_path + && self.active_sketch == app.session.active_sketch + && app + .session + .interactive_cached_world_state() + .is_some_and(|world| std::sync::Weak::ptr_eq(&self.world, &std::sync::Arc::downgrade(&world))) + } +} + +/// These paths can substitute pickable geometry outside the accepted product +/// world. Without a cache-only shown-world authority they cannot certify input. +fn geometry_context_supported(app: &SolveApp) -> bool { + !app.session.model.is_stale() + && app.session.active_sketch.is_none() + && app.open_meshing.is_none() + && !app.open_meshing_next + && app.session.section.is_none() + && app.render_workspace.view.draft.stage.is_empty() + && !app.preview.active + && !app.preview.busy + && !app.preview.rolled_back + && app.preview.bounds.is_empty() + && app.preview.effective_replaced().is_empty() +} + +struct Cached { + key: PixelKey, + revision: VisualRevision, + info: FrameInfo, + samples: u32, + target_samples: u32, + partial: Option, + final_dimensions: [u32; 2], + // Accepted job camera, never the latest observed intent after Pause. + camera: solidcraft_engine::render::Camera, + geometry: Option>, + stale: bool, + texture: Result, +} + +pub(super) struct State { + context: Option, + pub(super) pending: Option, + issued: Option, + issued_dimensions: Option<[u32; 2]>, + issued_geometry: Option>, + partial_request: Option<(JobId, Duration)>, + partial_exhausted: bool, + protected_feedback_snapshot: Option<(JobId, solidcraft_engine::render::job::ProtectedPreviewReport)>, + observed: Option, + visual: u64, + clock: Duration, + phase: Phase, + user_paused: bool, + final_active: bool, + error: Option, + frame: Option, +} +impl Default for State { + fn default() -> Self { + Self { + context: None, + pending: None, + issued: None, + issued_dimensions: None, + issued_geometry: None, + partial_request: None, + partial_exhausted: false, + protected_feedback_snapshot: None, + observed: None, + visual: 0, + clock: Duration::ZERO, + phase: Phase::Off, + user_paused: false, + final_active: false, + error: None, + frame: None, + } + } +} +impl State { + /// Never drop a live receiver to make room for a second capture thread. + pub(super) fn reset_document(&mut self) { + if let Some(context) = self.context.take() { + let _ = context.disable(); + } + self.issued = None; + self.issued_dimensions = None; + self.issued_geometry = None; + self.partial_request = None; + self.partial_exhausted = false; + self.protected_feedback_snapshot = None; + self.observed = None; + self.phase = Phase::Off; + self.user_paused = false; + self.final_active = false; + self.error = None; + self.frame = None; + } + #[cfg(test)] + pub(super) fn pending(&self) -> bool { + self.pending.is_some() + } + fn revision(&self) -> Option { + self.observed.as_ref().map(|intent| VisualRevision { scene_generation: intent.revision, visual_revision: self.visual }) + } + fn drain(&mut self, app: &SolveApp) { + let Some(pending) = self.pending.take() else { return }; + let reply = match pending.receiver.try_recv() { + Ok(reply) => reply, + Err(mpsc::TryRecvError::Empty) => { + self.pending = Some(pending); + return; + } + Err(mpsc::TryRecvError::Disconnected) => Err(app.tr("render.interactive_error").into()), + }; + if pending.uid != app.session.uid + || self.issued != Some(pending.ticket) + || self.revision() != Some(pending.ticket.revision()) + || self.context.as_ref().is_none_or(|context| !context.is_current(&app.session)) + { + return; + } + // Final preemption or a user pause invalidates the outstanding ticket; + // an expected rejected capture is not a fresh preparation failure. + if self.user_paused + || self.final_active + || self.context.as_ref().is_some_and(|context| matches!(context.state(), Ok(Phase::Paused | Phase::Off))) + { + return; + } + match reply { + Err(error) => { + if let Some(context) = &self.context { + let _ = context.capture_failed(pending.ticket, error.clone()); + } + self.error = Some(error); + self.phase = Phase::Error; + } + Ok(false) => { + self.error = Some(app.tr("render.interactive_error").into()); + self.phase = Phase::Error; + } + Ok(true) => {} + } + } + fn observe(&mut self, app: &SolveApp) -> Result<(), String> { + // The exact-input stamp never computes world placements/meshes. + // Preserve a current stamp across request-only edits; its weak identities + // prevent pointer reuse without retaining CAD data or changing COW behavior. + let stale = app.session.model.is_stale(); + let request = if stale { Err(app.tr("render.error_finish_gesture").into()) } else { super::interactive_request(app) }; + let current_scene = self.observed.as_ref().is_some_and(|old| old.scene.is_current(&app.session)); + if current_scene + && self.observed.as_ref().is_some_and(|old| { + old.uid == app.session.uid + && old.revision == app.session.revision + && old.camera == app.cam + && old.stale == stale + && old.request == request + }) + { + return Ok(()); + } + let scene = match self.observed.take() { + Some(old) if current_scene => old.scene, + _ => app.session.interactive_scene_identity(), + }; + let intent = Intent { scene, uid: app.session.uid, revision: app.session.revision, camera: app.cam, stale, request }; + let recovering = self.error.is_some() || self.phase == Phase::Error; + self.visual = self.visual.checked_add(1).ok_or_else(|| app.tr("render.interactive_error").to_string())?; + self.observed = Some(intent); + self.issued = None; + self.issued_dimensions = None; + self.issued_geometry = None; + self.partial_request = None; + self.partial_exhausted = false; + self.protected_feedback_snapshot = None; + self.error = None; + if self.user_paused { + if let Some(frame) = &mut self.frame { + frame.stale = true; + } + } else { + self.frame = None; + } + if let (Some(context), Some(revision)) = (&self.context, self.revision()) { + context.edit(revision, self.clock).map_err(|error| error.to_string())?; + if recovering && !self.user_paused { + context.resume(self.clock).map_err(|error| error.to_string())?; + } + } + if !stale && let Some(Err(error)) = self.observed.as_ref().map(|intent| &intent.request) { + self.error = Some(error.clone()); + } + Ok(()) + } + fn update(&mut self, app: &mut SolveApp, ctx: &egui::Context, dispatch: bool) -> Result<(), String> { + self.clock = monotonic(self.clock, ctx.input(|input| input.time)); + self.drain(app); + if self.context.is_none() { + return Ok(()); + } + if !super::active(app) + || app.render_workspace.view.method != ImageMethod::CpuRaytrace + || self.context.as_ref().is_some_and(|context| !context.is_current(&app.session)) + { + self.reset_document(); + return Ok(()); + } + self.observe(app)?; + let final_active = finals_active(app); + let suspend = final_active.as_ref().copied().unwrap_or(true) || app.render_workspace.view.result; + self.final_active = suspend; + let waiting_for_model = self.observed.as_ref().is_some_and(|intent| intent.stale); + let context = self.context.as_ref().ok_or_else(|| app.tr("render.interactive_error").to_string())?; + context.set_final_active(suspend || waiting_for_model, self.clock).map_err(|error| error.to_string())?; + if suspend || waiting_for_model { + self.issued = None; + self.issued_dimensions = None; + self.issued_geometry = None; + self.partial_request = None; + self.partial_exhausted = false; + self.protected_feedback_snapshot = None; + } + if suspend && !self.user_paused { + self.frame = None; + } + if let Err(error) = final_active { + self.error = Some(error); + } + if waiting_for_model { + self.phase = if self.user_paused || suspend { Phase::Paused } else { Phase::Updating }; + if let Some(frame) = &mut self.frame { + frame.stale = true; + } + return Ok(()); + } + if self.error.is_some() { + // Request errors must cancel an already attached old capture, too. + context.pause().map_err(|error| error.to_string())?; + self.phase = Phase::Error; + return Ok(()); + } + self.phase = context.state().map_err(|error| error.to_string())?; + if self.phase == Phase::Error { + self.error = context.error().map_err(|error| error.to_string())?.or_else(|| Some(app.tr("render.interactive_error").into())); + self.frame = None; + return Ok(()); + } + self.cache(ctx)?; + if !dispatch || self.pending.is_some() || suspend || self.user_paused { + return Ok(()); + } + #[cfg(not(target_arch = "wasm32"))] + if let Some(ticket) = self + .context + .as_ref() + .ok_or_else(|| app.tr("render.interactive_error").to_string())? + .capture(self.clock) + .map_err(|error| error.to_string())? + { + let request = self + .observed + .as_ref() + .and_then(|intent| intent.request.as_ref().ok()) + .ok_or_else(|| app.tr("render.interactive_error").to_string())?; + let snapshot = self + .context + .as_ref() + .ok_or_else(|| app.tr("render.interactive_error").to_string())? + .snapshot(&app.session, ticket, request) + .map_err(|error| error.to_string())?; + self.issued_dimensions = Some(capture_dimensions(request)?); + self.issued_geometry = GeometryAlignment::capture(app, ticket).map(std::sync::Arc::new); + self.partial_request = None; + self.partial_exhausted = false; + self.protected_feedback_snapshot = None; + self.issued = Some(ticket); + self.pending = Some(spawn(snapshot)?); + self.phase = Phase::Updating; + } + Ok(()) + } + fn cache(&mut self, ctx: &egui::Context) -> Result<(), String> { + if self.user_paused || self.final_active { + return Ok(()); + } + let Some(context) = &self.context else { return Ok(()) }; + let Some(job) = context.current().map_err(|error| error.to_string())? else { return Ok(()) }; + let Some(ticket) = self.issued else { return Ok(()) }; + if job.id() != ticket.job_id() || self.revision() != Some(ticket.revision()) { + return Ok(()); + } + let status = job.status().map_err(|error| error.to_string())?; + if status.request.integrator != Integrator::Raytrace || status.scene_generation != ticket.revision().scene_generation { + return Err(crate::i18n::tr("render.interactive_error").into()); + } + // Demand is advisory, not capture authority. False attempts still throttle. + if !status.progress.phase.terminal() && partial_request_due(self.partial_request, job.id(), self.clock) { + self.partial_request = Some((job.id(), self.clock)); + let _ = job.request_partial_preview().map_err(|error| error.to_string())?; + } + // Report counters belong to this actual admitted job. None is not a + // theoretical zero ledger; old/shared-cap routes retain their own cause. + let report = job.protected_preview_report().map_err(|error| error.to_string())?; + self.protected_feedback_snapshot = report.map(|report| (job.id(), report)); + self.partial_exhausted = + if let Some(report) = report { report.quota_exhausted } else { job.partial_preview_exhausted().map_err(|error| error.to_string())? }; + let partial = job.partial_preview().map_err(|error| error.to_string())?; + // Read the real terminal after the partial slot: completion can race the + // earlier status. Terminal16 stays provisional, never a final export. + if let Some(frame) = job.frame().map_err(|error| error.to_string())? { + let key = PixelKey { job: job.id(), sequence: 0, complete: true }; + let samples = status.request.raytrace.as_ref().and_then(|options| options.progressive).map_or(0, |options| options.samples_per_pixel); + self.cache_png(ctx, key, ticket.revision(), &frame.info, samples, (frame.png(), &status.request))?; + } else if let Some(partial) = partial { + self.cache_partial_png(ctx, &job, ticket, &status.request, &partial)?; + } else if let Some(preview) = job.preview().map_err(|error| error.to_string())? { + let key = PixelKey { job: job.id(), sequence: preview.info.frame_sequence, complete: false }; + self.cache_png(ctx, key, ticket.revision(), &preview.info.frame, preview.info.samples_per_pixel, (preview.png(), &status.request))?; + } + Ok(()) + } + fn cache_partial_png( + &mut self, + ctx: &egui::Context, + job: &solidcraft_engine::render::job::JobHandle, + ticket: CaptureTicket, + request: &solidcraft_engine::render::job::ImageRequest, + publication: &solidcraft_engine::render::job::RenderPartialPreview, + ) -> Result<(), String> { + let invalid = || crate::i18n::tr("render.error_provisional_identity").to_string(); + let final_dimensions = self.issued_dimensions.ok_or_else(invalid)?; + let expected = PartialExpectation { job: job.id(), scene_generation: ticket.revision().scene_generation, request, final_dimensions }; + let previous = self.frame.as_ref().filter(|old| old.key.job == job.id() && old.revision == ticket.revision()).and_then(|old| old.partial); + let Some(sampling) = validate_partial_metadata(&expected, &publication.info, publication.png().len(), publication.covered().len(), previous)? + else { + return Ok(()); + }; + let info = &publication.info.frame; + let image = decode_partial_image( + request, + &publication.info, + publication.png(), + publication.covered(), + sampling, + ctx.input(|input| input.max_texture_side), + )?; + // Decoding can overlap worker cancellation/completion. Do not adopt a + // late partial, and leave a real terminal for the next normal refresh. + let status = job.status().map_err(|error| error.to_string())?; + if status.progress.phase.terminal() + || self.issued != Some(ticket) + || self.revision() != Some(ticket.revision()) + || self.context.as_ref().ok_or_else(invalid)?.current().map_err(|error| error.to_string())?.is_none_or(|current| current.id() != job.id()) + { + return Ok(()); + } + let texture = ctx.load_texture("sc_render_interactive_partial", image, egui::TextureOptions::NEAREST); + self.frame = Some(Cached { + key: PixelKey { job: job.id(), sequence: 0, complete: false }, + revision: ticket.revision(), + info: info.clone(), + samples: 0, + target_samples: request.raytrace.as_ref().and_then(|options| options.progressive).ok_or_else(invalid)?.samples_per_pixel, + partial: Some(sampling), + final_dimensions, + camera: request.camera, + geometry: self.issued_geometry.clone(), + stale: false, + texture: Ok(texture), + }); + // The cache retains neither source Arc, PNG nor covered sidecar. Ending + // this borrow is not a credit ACK: host/external owners may still retain it. + Ok(()) + } + + fn cache_png( + &mut self, + ctx: &egui::Context, + key: PixelKey, + revision: VisualRevision, + info: &FrameInfo, + samples: u32, + payload: (&[u8], &solidcraft_engine::render::job::ImageRequest), + ) -> Result<(), String> { + let (png, request) = payload; + let progressive = request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .ok_or_else(|| crate::i18n::tr("render.error_provisional_identity").to_string())?; + progressive.validate_image_with_budget(request.width, request.height, request.cpu_budget()).map_err(|error| error.to_string())?; + if self.frame.as_ref().is_some_and(|frame| frame.partial.is_none() && frame.key == key && frame.revision == revision) { + return Ok(()); + } + if info.job != key.job + || info.scene_generation != revision.scene_generation + || !(1..=progressive.samples_per_pixel).contains(&samples) + || (info.width, info.height) != (request.width, request.height) + || info.width > 1024 + || info.height > 1024 + { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + let texture = super::decode_render_image( + png, + info.width, + info.height, + super::captured_image_limits(request), + ctx.input(|input| input.max_texture_side), + ) + .map(|image| ctx.load_texture("sc_render_interactive", image, egui::TextureOptions::LINEAR)); + let error = texture.as_ref().err().cloned(); + self.frame = Some(Cached { + key, + revision, + info: info.clone(), + samples, + target_samples: progressive.samples_per_pixel, + partial: None, + final_dimensions: self.issued_dimensions.ok_or_else(|| crate::i18n::tr("render.error_provisional_identity").to_string())?, + camera: request.camera, + geometry: self.issued_geometry.clone(), + stale: false, + texture, + }); + if let Some(error) = error { + return Err(error); + } + Ok(()) + } +} + +pub(super) fn monotonic(previous: Duration, seconds: f64) -> Duration { + if !seconds.is_finite() || seconds < 0.0 { + return previous; + } + match Duration::try_from_secs_f64(seconds) { + Ok(now) => previous.max(now), + Err(_) => previous, + } +} +fn finals_active(app: &SolveApp) -> Result { + let mut active = false; + for session in std::iter::once(&app.session).chain(app.docs.background()) { + active |= session.render_final_active().map_err(|error| error.to_string())?; + } + Ok(active) +} + +pub(super) fn ready(app: &SolveApp) -> Result<(), String> { + if cfg!(target_arch = "wasm32") || !super::active(app) || app.render_workspace.view.method != ImageMethod::CpuRaytrace { + return Err(app.tr("render.interactive_requires_cpu").into()); + } + let host = app.session.render_job_host().ok_or_else(|| app.tr("render.interactive_requires_cpu").to_string())?; + if host.kind() != HostKind::NativeWorker || !host.is_available() || host.validate_integrator(Integrator::Raytrace).is_err() { + return Err(app.tr("render.interactive_requires_cpu").into()); + } + if finals_active(app)? || app.render_workspace.view.result { + return Err(app.tr("render.interactive_final_active").into()); + } + Ok(()) +} + +pub(super) fn apply_command(app: &mut SolveApp, action: Action) -> Result<(), String> { + if matches!(action, Action::On | Action::Resume) { + ready(app)?; + } + let mut state = std::mem::take(&mut app.render_workspace.interactive); + let result = (|| { + match action { + Action::Off => state.reset_document(), + Action::On => { + state.reset_document(); + state.context = Some(app.session.interactive_render().map_err(|error| error.to_string())?); + state.observe(app)?; + let revision = state.revision().ok_or_else(|| app.tr("render.interactive_error").to_string())?; + state + .context + .as_ref() + .ok_or_else(|| app.tr("render.interactive_error").to_string())? + .enable(revision, state.clock) + .map_err(|error| error.to_string())?; + state.phase = Phase::Updating; + } + Action::Pause => { + let context = state.context.as_ref().ok_or_else(|| app.tr("render.interactive_requires_cpu").to_string())?; + context.pause().map_err(|error| error.to_string())?; + state.user_paused = true; + state.issued = None; + state.issued_dimensions = None; + state.issued_geometry = None; + state.partial_request = None; + state.partial_exhausted = false; + state.protected_feedback_snapshot = None; + state.phase = Phase::Paused; + } + Action::Resume => { + state.observe(app)?; + if let Some(Err(error)) = state.observed.as_ref().map(|intent| &intent.request) { + return Err(error.clone()); + } + let context = state.context.as_ref().ok_or_else(|| app.tr("render.interactive_requires_cpu").to_string())?; + context.resume(state.clock).map_err(|error| error.to_string())?; + state.user_paused = false; + state.issued = None; + state.issued_dimensions = None; + state.issued_geometry = None; + state.partial_request = None; + state.partial_exhausted = false; + state.protected_feedback_snapshot = None; + state.error = None; + state.frame = None; + state.phase = Phase::Updating; + } + } + Ok(()) + })(); + app.render_workspace.interactive = state; + result +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn(snapshot: Snapshot) -> Result { + let uid = snapshot.document_uid(); + let ticket = snapshot.ticket(); + let (sender, receiver) = mpsc::channel(); + let _worker = std::thread::Builder::new() + .name("solidcraft-interactive-capture".into()) + .spawn(move || { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| snapshot.run())) + .map_err(|_| crate::i18n::tr("render.interactive_error").to_string()) + .and_then(|result| result.map_err(|error| error.to_string())); + let _ = sender.send(result); + }) + .map_err(|error| error.to_string())?; + Ok(Pending { uid, ticket, receiver }) +} + +fn refresh(app: &mut SolveApp, ctx: &egui::Context, dispatch: bool) { + let mut state = std::mem::take(&mut app.render_workspace.interactive); + if let Err(error) = state.update(app, ctx, dispatch) { + if let Some(context) = &state.context { + let _ = context.pause(); + } + state.error = Some(error); + state.phase = Phase::Error; + state.frame = None; + } + let poll = state.pending.is_some() || matches!(state.phase, Phase::Updating | Phase::Refining); + app.render_workspace.interactive = state; + if poll { + ctx.request_repaint_after(Duration::from_millis(100)); + } +} +pub(super) fn tick(app: &mut SolveApp, ctx: &egui::Context) { + refresh(app, ctx, true); +} +pub(super) fn before_paint(app: &mut SolveApp, ctx: &egui::Context) { + refresh(app, ctx, false); +} + +/// Reserve the canvas while an active CPU preview awaits its current pixels. +/// This never turns a waiting state into a painted image or retains old pixels. +pub(super) fn awaiting_current_frame(app: &SolveApp) -> bool { + let state = &app.render_workspace.interactive; + super::active(app) + && app.render_workspace.view.method == ImageMethod::CpuRaytrace + && !app.render_workspace.view.result + && state.context.as_ref().is_some_and(|context| context.is_current(&app.session)) + && !state.user_paused + && !state.final_active + && state.error.is_none() + && matches!(state.phase, Phase::Updating | Phase::Refining) + && state.frame.is_none() +} + +/// Pausing an Unknown source must not restore invisible geometry hit targets. +/// Pure UI visibility policy, shared by pixel paint and the Unknown-only guard. +/// These flags describe an existing cached frame, never a renderer/job capability. +#[derive(Clone, Copy)] +pub(super) struct FrameVisibility { + pub(super) has_context: bool, + pub(super) final_active: bool, + pub(super) has_error: bool, + pub(super) paused: bool, + pub(super) stale: bool, + pub(super) revision_matches: bool, + pub(super) texture_ok: bool, +} + +impl FrameVisibility { + pub(super) fn paintable(self) -> bool { + self.has_context && !self.final_active && !self.has_error && self.texture_ok && (self.paused || (!self.stale && self.revision_matches)) + } + + pub(super) fn blocks_unknown(self, source_unknown: bool) -> bool { + source_unknown && self.paintable() + } +} + +fn frame_visibility(state: &State, frame: &Cached) -> FrameVisibility { + FrameVisibility { + has_context: state.context.is_some(), + final_active: state.final_active, + has_error: state.error.is_some(), + paused: state.user_paused, + stale: frame.stale, + revision_matches: state.revision() == Some(frame.revision), + texture_ok: frame.texture.is_ok(), + } +} + +fn input_frame(app: &SolveApp) -> Option<&Cached> { + let state = &app.render_workspace.interactive; + (super::active(app) + && app.render_workspace.view.method == ImageMethod::CpuRaytrace + && !app.render_workspace.view.result + && state.context.as_ref().is_some_and(|context| context.is_current(&app.session))) + .then_some(state.frame.as_ref()) + .flatten() +} + +/// Match accepted camera and authored aspect without using the latest visual +/// revision: a paused appearance/light edit alone need not move geometry targets. +fn camera_framing_matches(app: &SolveApp, frame: &Cached) -> bool { + let [width, height] = frame.final_dimensions; + let draft = &app.render_workspace.view.draft; + frame.camera == app.cam + && width != 0 + && height != 0 + && draft.width != 0 + && draft.height != 0 + && u64::from(width) * u64::from(draft.height) == u64::from(height) * u64::from(draft.width) +} + +pub(super) fn blocks_geometry_input(app: &SolveApp) -> bool { + awaiting_current_frame(app) + || input_frame(app).is_some_and(|frame| { + let visibility = frame_visibility(&app.render_workspace.interactive, frame); + visibility.blocks_unknown(frame.partial.is_some_and(|sampling| sampling.source_unknown())) + || (visibility.paintable() + && (!camera_framing_matches(app, frame) + || frame.geometry.as_ref().is_none_or(|geometry| !geometry.is_current(app, frame.key.job, frame.revision)))) + }) +} + +/// Use exactly the painted pixel rectangle for CAD projection and pointer bounds. +/// Shared navigation keeps its existing viewport; no cached camera is installed. +pub(super) fn geometry_input_rect(app: &SolveApp, rect: egui::Rect) -> egui::Rect { + input_frame(app) + .filter(|frame| frame_visibility(&app.render_workspace.interactive, frame).paintable()) + .and_then(|frame| pixel_rect(&frame.info, rect)) + .unwrap_or(rect) +} + +fn pixel_rect(info: &FrameInfo, rect: egui::Rect) -> Option { + if info.width == 0 || info.height == 0 || !rect.is_finite() || !rect.is_positive() { + return None; + } + let scale = (rect.width() / info.width as f32).min(rect.height() / info.height as f32); + let target = egui::Rect::from_center_size(rect.center(), egui::vec2(info.width as f32, info.height as f32) * scale); + (target.is_finite() && target.is_positive()).then_some(target) +} + +fn paint_unknown_underlay(ui: &egui::Ui, rect: egui::Rect) { + let tokens = Tokens::get(); + let painter = ui.painter().with_clip_rect(rect); + painter.rect_filled(rect, 0.0, tokens.file_background); + // Fixed64 theme cells independent of source pixel count; no model or final fill. + for y in 0..8 { + for x in 0..8 { + if (x + y) % 2 == 0 { + let min = rect.min + egui::vec2(rect.width() * x as f32 / 8.0, rect.height() * y as f32 / 8.0); + let max = rect.min + egui::vec2(rect.width() * (x + 1) as f32 / 8.0, rect.height() * (y + 1) as f32 / 8.0); + painter.rect_filled(egui::Rect::from_min_max(min, max), 0.0, tokens.file_border); + } + } + } +} + +pub(super) fn paint(app: &SolveApp, ui: &egui::Ui, rect: egui::Rect) -> bool { + let state = &app.render_workspace.interactive; + let Some(frame) = &state.frame else { return false }; + if !frame_visibility(state, frame).paintable() { + return false; + } + let Ok(texture) = &frame.texture else { return false }; + let Some(target) = pixel_rect(&frame.info, rect) else { return false }; + if frame.partial.is_some_and(|sampling| sampling.source_unknown()) { + paint_unknown_underlay(ui, target); + } + ui.painter().with_clip_rect(rect).image( + texture.id(), + target, + egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), + Tokens::get().file_image_tint, + ); + true +} + +/// Place only our card in current-frame space; never move another workspace surface. +pub(super) fn overlay_bounds(app: &SolveApp, free: egui::Rect) -> egui::Rect { + if !free.is_finite() || !free.is_positive() { + return egui::Rect::NOTHING; + } + let gap = Tokens::get().space_8; + let available = crate::shell::workspace_content(app, free).shrink(gap); + let mut obstacles = Vec::new(); + for (id, (rect, edge)) in &app.shell.workspace_panels { + if *id != "render:interactive-card" && edge.is_none() { + obstacles.push(rect.expand(gap)); + } + } + if let Some(layout) = &app.viewport.layout { + obstacles.extend([layout.axis_view, layout.navigation, layout.confirm].map(|rect| rect.expand(gap))); + } + crate::viewport_layout::free_rect(available, &obstacles) +} + +pub(crate) fn overlay(app: &mut SolveApp, ui: &egui::Ui, free: egui::Rect) { + let bounds = overlay_bounds(app, free); + let t = Tokens::get(); + // Match navigation_card's real chrome, including theme-dependent borders. + let chrome = ui_kit::Container::new(ui.ctx(), ui_kit::Surface::Navigation) + .frame(ui.ctx(), t.overlay, crate::frame::Side::Left) + .inner_margin(t.space_4) + .total_margin() + .sum(); + let width = (bounds.width() - chrome.x).min(t.form_card_width); + let height = bounds.height() - chrome.y; + if !bounds.is_finite() || width < t.control_height || height < t.control_height { + return; + } + let card = ui_kit::Container::navigation_card( + ui.ctx(), + egui::Id::new("sc_render_interactive_controls"), + bounds.left_top(), + egui::Align2::LEFT_TOP, + |ui| { + ui.set_width(width); + ui.set_max_width(width); + ui.set_max_height(height); + ui.set_clip_rect(ui.clip_rect().intersect(bounds)); + controls(app, ui); + }, + ); + crate::shell::register_panel(app, "render:interactive-card", Some(card.response.rect.intersect(bounds)), None); + crate::scenario::publish_rect("render:interactive-card", card.response.rect.intersect(bounds)); +} +pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let state = &app.render_workspace.interactive; + let phase = state.phase; + let running = state.context.is_some(); + let paused = state.user_paused; + let key = match phase { + Phase::Off => "render.interactive_off", + Phase::Updating => "render.interactive_updating", + Phase::Refining => "render.interactive_refining", + Phase::Paused => "render.interactive_paused", + Phase::TargetReached => "render.interactive_target", + Phase::Error => "render.interactive_error", + }; + let label = app.tr(key).to_string(); + let error = state.error.clone(); + let partial = state.frame.as_ref().and_then(|frame| frame.partial); + let samples = state.frame.as_ref().and_then(|frame| frame.partial.map_or(Some(frame.samples), |sampling| sampling.uniform_samples())); + let target_samples = state.frame.as_ref().map(|frame| frame.target_samples); + let dimensions = state.frame.as_ref().map(|frame| (frame.info.width, frame.info.height)); + let stale = state.frame.as_ref().is_some_and(|frame| frame.stale); + let final_active = state.final_active; + let final_dimensions = state.frame.as_ref().map(|frame| frame.final_dimensions); + let partial_exhausted = state.partial_exhausted; + let protected_feedback = + state.protected_feedback_snapshot.filter(|(job, _)| state.issued.is_some_and(|ticket| ticket.job_id() == *job)).map(|(_, report)| report); + let reason = ready(app).err(); + let mut action = None; + ui.horizontal_wrapped(|ui| { + for (action_value, name, key, enabled) in if !running { + vec![(Action::On, "on", "render.interactive_on", reason.is_none())] + } else { + vec![ + ( + if paused || phase == Phase::Error { Action::Resume } else { Action::Pause }, + if paused || phase == Phase::Error { "resume" } else { "pause" }, + if paused || phase == Phase::Error { "render.interactive_resume" } else { "render.interactive_pause" }, + !final_active && (reason.is_none() || !(paused || phase == Phase::Error)), + ), + (Action::Off, "off", "render.interactive_off", true), + ] + } { + let label = app.tr(key).to_string(); + let response = ui_kit::button(ui, label, ui_kit::Button::Enabled(enabled)); + crate::scenario::publish_target(&format!("render:interactive:{name}"), response.rect); + if response.clicked() { + action = Some(action_value); + } + } + }); + if let Some(action) = action { + if let Err(error) = app.run("render.interactive", json!({"action":action})) { + app.set_status(error, true); + } + ui.ctx().request_repaint(); + } + // Actions remain outside the scroller. In a short free rectangle, status + // text may scroll but must not push Pause/Resume/Off below the visible clip. + let height = ui.available_height().max(0.0); + if height > 0.0 { + egui::ScrollArea::vertical() + .id_salt("sc_render_interactive_controls_scroll") + .min_scrolled_height(0.0) + .max_height(height) + .auto_shrink([false, true]) + .show(ui, |ui| { + ui_kit::text(ui, &label, ui_kit::Text::Inline); + if running { + ui_kit::text(ui, app.tr("render.interactive_provisional"), ui_kit::Text::Note("render.interactive_provisional")); + } + if let Some(sampling) = partial { + if let Some(target) = target_samples { + let label = crate::i18n::format( + "render.cpu_pass_progress", + &[("current", &sampling.cursor.completed_passes.to_string()), ("target", &target.to_string())], + ); + ui_kit::text(ui, &label, ui_kit::Text::Inline); + } + let (min, max) = sampling.sample_range(); + let pixels = u64::from(sampling.plan.source_width()) * u64::from(sampling.plan.source_height()); + let label = crate::i18n::format( + "render.interactive_partial_samples", + &[ + ("min", &min.to_string()), + ("max", &max.to_string()), + ("known", &sampling.sampled_source_pixels().to_string()), + ("pixels", &pixels.to_string()), + ], + ); + ui_kit::text(ui, &label, ui_kit::Text::Inline); + } else if let (Some(samples), Some(target)) = (samples, target_samples) { + let label = crate::i18n::format("render.interactive_samples", &[("done", &samples.to_string()), ("total", &target.to_string())]); + ui_kit::text(ui, &label, ui_kit::Text::Inline); + } + if let Some(sampling) = partial { + if let (Some((width, height)), Some(final_dimensions)) = (dimensions, final_dimensions) { + let label = crate::i18n::format( + "render.interactive_partial_dimensions", + &[ + ("display_width", &width.to_string()), + ("display_height", &height.to_string()), + ("source_width", &sampling.plan.source_width().to_string()), + ("source_height", &sampling.plan.source_height().to_string()), + ("final_width", &final_dimensions[0].to_string()), + ("final_height", &final_dimensions[1].to_string()), + ], + ); + ui_kit::text(ui, &label, ui_kit::Text::Inline); + } + } else if let Some((width, height)) = dimensions { + ui_kit::text(ui, &format!("{width} × {height} px"), ui_kit::Text::Inline); + } + if let Some(report) = protected_feedback.filter(|_| matches!(phase, Phase::Updating | Phase::Refining)) { + let label = crate::i18n::format( + "render.interactive_feedback_usage", + &[("started", &report.accepted_snapshots.to_string()), ("limit", &report.quota_limit.to_string())], + ); + ui_kit::text(ui, &label, ui_kit::Text::Inline); + ui_kit::text(ui, app.tr("render.interactive_feedback_policy"), ui_kit::Text::Note("render.interactive_feedback_policy")); + let reason = if report.quota_exhausted { + Some("render.interactive_feedback_quota_exhausted") + } else if report.milestones_complete { + Some("render.interactive_feedback_milestones_complete") + } else { + None + }; + if let Some(reason) = reason { + ui_kit::text(ui, app.tr(reason), ui_kit::Text::Note(reason)); + } + } else if protected_feedback.is_none() && partial_exhausted && phase != Phase::TargetReached { + ui_kit::text(ui, app.tr("render.interactive_partial_exhausted"), ui_kit::Text::Note("render.interactive_partial_exhausted")); + } + if stale { + ui_kit::text(ui, app.tr("render.interactive_stale"), ui_kit::Text::Note("render.interactive_stale")); + } + if final_active { + ui_kit::text(ui, app.tr("render.interactive_final_active"), ui_kit::Text::Note("render.interactive_final_active")); + } + if let Some(error) = error { + ui_kit::text(ui, &error, ui_kit::Text::Error("render.interactive_error")); + } + if let Some(reason) = &reason { + ui_kit::text(ui, reason, ui_kit::Text::Note("render.interactive_requires_cpu")); + } + }); + } +} +pub(super) fn command_ready(app: &SolveApp) -> Result<(), String> { + if app.render_workspace.interactive.context.is_some() { Ok(()) } else { ready(app) } +} +pub(super) fn activate(app: &mut SolveApp) { + let state = &app.render_workspace.interactive; + let action = if state.context.is_none() { + Action::On + } else if state.user_paused || state.phase == Phase::Error { + Action::Resume + } else { + Action::Pause + }; + if let Err(error) = app.run("render.interactive", json!({"action":action})) { + app.set_status(error, true); + } +} +pub(super) fn inspect(app: &SolveApp) -> Value { + let state = &app.render_workspace.interactive; + // A diagnostic of the actual admitted capture, never a synthetic zero from + // a missing context, pending ticket or failed status read. + let retention_skips = state + .context + .as_ref() + .and_then(|context| context.current().ok().flatten()) + .and_then(|job| job.status().ok()) + .map(|status| status.cpu_preview_retention_skips); + json!({"enabled":state.context.is_some(),"phase":format!("{:?}",state.phase),"visual_revision":state.visual, + "pending_capture":state.pending.is_some(),"paused":state.user_paused,"error":state.error, + "cpu_preview_retention_skips":retention_skips, + "samples":state.frame.as_ref().and_then(|frame|frame.partial.map_or(Some(frame.samples), |sampling|sampling.uniform_samples())), + "partial":state.frame.as_ref().and_then(|frame|frame.partial).map(|sampling|json!({ + "sequence":sampling.cursor.sequence,"completed_passes":sampling.cursor.completed_passes,"updated_prefix":sampling.cursor.updated_prefix, + "source_width":sampling.plan.source_width(),"source_height":sampling.plan.source_height(), + "sample_min":sampling.sample_range().0,"sample_max":sampling.sample_range().1, + "source_sampled_pixels":sampling.sampled_source_pixels(),"source_unknown":sampling.source_unknown() + })), + "final_dimensions":state.frame.as_ref().map(|frame|frame.final_dimensions), + // Diagnostic snapshot only, never a terminal audit or a new JobStatus field. + "protected_feedback_snapshot":state.protected_feedback_snapshot.map(|(job, report)|json!({"job":job,"report":report})), + "partial_exhausted":state.partial_exhausted,"stale":state.frame.as_ref().is_some_and(|frame|frame.stale), + "job":state.frame.as_ref().map(|frame|frame.info.job),"provisional":true}) +} + +// Read-only private observations for original UI acceptance tests. No production +// command/API, host factory, renderer injection, worker gate or timing hook. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(super) fn test_current(app: &SolveApp) -> solidcraft_engine::Result> { + let Some(context) = app.render_workspace.interactive.context.as_ref() else { return Ok(None) }; + context.current() +} +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(super) fn test_cache(app: &SolveApp) -> Option<(FrameInfo, u32, bool, egui::TextureId)> { + let frame = app.render_workspace.interactive.frame.as_ref()?; + Some((frame.info.clone(), frame.samples, frame.key.complete, frame.texture.as_ref().ok()?.id())) +} + +// Harness frames advance this clock even while Interactive is Off. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(super) fn test_clock(app: &SolveApp) -> Duration { + app.render_workspace.interactive.clock +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_tests.rs b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_tests.rs new file mode 100644 index 000000000..71addc927 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_tests.rs @@ -0,0 +1,11590 @@ +use super::*; +use crate::scenario::Harness; +use solidcraft_engine::Session; + +fn environment_editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 1800.0))), events, ..Default::default() }, + |ui| { + ui.set_width(308.0); + environment::editor(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +fn environment_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"gpu_path","options":{"environment":{"kind":"sky"}}}}})).unwrap(); + setups::load(&mut h.app); + h +} + +#[test] +fn environment_editor_e4_variants_keep_all_five_sections_in_order() { + for variant in ["embedded", "sky", "file"] { + let mut h = environment_editor_fixture(); + if variant == "embedded" { + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + } else if variant == "file" { + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "C:/hdr/studio.hdr".into() }; + } else { + h.app.render_workspace.view.studio.backdrop_enabled = true; + } + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let mut previous = -1.0; + let source_row = crate::scenario::rect_of("dialog:control:Source").unwrap(); + let change = crate::scenario::rect_of("render:environment:change").unwrap(); + assert!(source_row.contains_rect(change), "{variant}: Change must fit beside Source"); + for key in [ + "render.env_source", + "render.environment.orientation", + "render.env_backdrop", + "render.environment.ground", + "render.environment.atmosphere", + ] { + let rect = crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap(); + assert!(rect.top() > previous, "{variant}: {key} out of order"); + previous = rect.top(); + } + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.replace", + "render.environment.fit", + "render.environment.floor_wall", + "render.environment.cyclorama", + "render.environment.medium", + "render.environment.phase", + ] { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}: {text}"); + } + for key in match variant { + "embedded" => &["render.environment.embedded", "render.environment.builtin"][..], + "file" => &["render.environment.choose", "render.environment.check"][..], + _ => &[ + "render.environment.zenith", + "render.environment.horizon", + "render.environment.sky_ground", + "render.environment.start", + "render.environment.end", + ][..], + } { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}"); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "opening {variant} must never save"); + output.textures_delta.clear(); + } +} + +#[test] +fn environment_editor_unsupported_methods_keep_controls_and_reasons_without_switching() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = environment_editor_fixture(); + h.app.render_workspace.view.method = method; + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.needs_gpu", + "render.environment.gradient_gpu", + "render.environment.blur_pending", + "render.environment.world_pending", + "render.environment.medium", + "render.environment.min", + "render.environment.max", + ] { + assert!(text.contains(h.app.tr(key)), "missing {key}: {text}"); + } + output.textures_delta.clear(); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_none()); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn environment_editor_gradient_and_atmosphere_refuse_hostile_values_atomically() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for value in [f64::NAN, f64::INFINITY, -1.0, 1e300] { + let mut gradient = h.app.render_workspace.view.studio.backdrop; + gradient.radius = value; + assert!(environment::commit_gradient(&mut h.app, true, gradient).is_err()); + h.app.render_workspace.view.studio.volume = + Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: value, ..Default::default() }); + assert!(setups::save(&mut h.app).is_err()); + h.app.render_workspace.view.studio.volume = None; + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + environment::commit_gradient(&mut h.app, true, Default::default()).unwrap(); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_editor_stage_removal_requires_confirm_and_rejects_stale_answers() { + for stale in [false, true] { + let mut h = environment_editor_fixture(); + environment::commit_ground(&mut h.app, true, environment::Ground { margin: 1.0, gap: 0.1, color: [0.18; 3] }).unwrap(); + let before = h.app.session.doc.clone(); + environment::request_stage_removal(&h.app, &h.ctx); + for _ in 0..3 { + environment_editor_frame(&mut h, vec![]); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(crate::scenario::rect_of("dialog:ok").is_some()); + if stale { + h.app.run("render.settings.set", json!({"name":"Other","set":{"width":42}})).unwrap(); + } + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("dialog:ok").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert_eq!(h.app.session.undo.len(), undo + usize::from(!stale)); + assert_eq!(h.app.render_workspace.view.draft.stage.is_empty(), !stale); + } +} + +#[test] +fn environment_editor_checked_file_embeds_bytes_and_keeps_the_recheck_banner() { + let mut h = environment_editor_fixture(); + let path = h.dir.join("environment-editor.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + environment::persist(&mut h.app); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + assert!(matches!(h.app.render_workspace.view.studio.hdr, hdr::Input::FileCaptured { .. })); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.job.text.contains(h.app.tr("render.environment.checked")))); + output.textures_delta.clear(); + let before = h.app.session.doc.clone(); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + environment::persist(&mut h.app); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "changed bytes require rechecking"); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_medium_toggle_saves_one_command_without_a_gpu_host() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + let undo = h.app.session.undo.len(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_some()); + assert_eq!(h.app.session.undo.len(), undo + 1); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(h.app.session.doc.render.setups[&h.app.render_workspace.view.name], expected); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.studio.volume.is_none()); +} + +#[test] +fn environment_ring_angles_snap_wrap_and_refuse_hostile_geometry() { + let center = egui::pos2(100.0, 200.0); + for (point, expected) in + [(egui::pos2(150.0, 200.0), 0.0), (egui::pos2(100.0, 250.0), 90.0), (egui::pos2(50.0, 200.0), 180.0), (egui::pos2(100.0, 150.0), -90.0)] + { + assert_eq!(environment::pointer_angle(point, center, 50.0), Some(expected)); + } + assert_eq!(environment::drag_rotation(170.0, 170.0, -170.0, false), Some(-170.0)); + assert_eq!(environment::drag_rotation(170.0, 0.0, 30.0, true), Some(-165.0)); + assert_eq!(environment::drag_rotation(-170.0, 0.0, -30.0, true), Some(165.0)); + assert_eq!(environment::drag_rotation(0.0, 0.0, 180.0, false), Some(-180.0)); + assert_eq!(environment::pointer_angle(center, center, 50.0), None); + for radius in [0.0, -1.0, f32::NAN, f32::INFINITY, 1e9] { + assert_eq!(environment::pointer_angle(egui::pos2(150.0, 200.0), center, radius), None); + } + for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(environment::pointer_angle(egui::pos2(value, 200.0), center, 50.0), None); + assert_eq!(environment::pointer_angle(center, egui::pos2(100.0, value), 50.0), None); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300] { + assert_eq!(environment::drag_rotation(value, 0.0, 20.0, false), None); + assert_eq!(environment::drag_rotation(0.0, value, 20.0, true), None); + assert_eq!(environment::drag_rotation(0.0, 0.0, value, false), None); + } +} + +fn environment_ring_frame(h: &mut Harness, mods: egui::Modifiers, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + focused: true, + events: std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(), + ..Default::default() + }, + |ui| { + let viewport = ui.max_rect(); + show(&mut h.app, ui); + environment_overlay(&mut h.app, ui, viewport); + }, + ); + output.textures_delta.clear(); +} + +fn environment_ring_fixture() -> Harness { + let mut h = environment_editor_fixture(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.preferences.nav = crate::prefs::OPENSCAD_NAV.into(); + h.app.cam.fit(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap().bounds); + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + h +} + +#[test] +fn render_workspace_frame_rect_fits_centres_and_refuses_hostile_sizes() { + let viewport = egui::Rect::from_min_size(egui::pos2(100.0, 40.0), egui::vec2(800.0, 600.0)); + for aspect in [16.0 / 9.0, 1.5, 1.0, 0.8, 9.0 / 16.0, 0.01, 100.0] { + let frame = shot::frame_rect(aspect, viewport).unwrap(); + assert!(viewport.contains_rect(frame)); + assert_eq!(frame.center(), viewport.center()); + assert!((f64::from(frame.width() / frame.height()) - aspect).abs() < 0.001); + assert!(frame.width() == viewport.width() || frame.height() == viewport.height()); + } + for aspect in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::MAX, 1e-300] { + assert!(shot::frame_rect(aspect, viewport).is_none()); + } + for size in [egui::Vec2::ZERO, egui::vec2(0.0, 400.0), egui::vec2(f32::NAN, 10.0), egui::vec2(f32::MAX, f32::MAX), egui::vec2(-10.0, 20.0)] { + assert!(shot::frame_rect(1.5, egui::Rect::from_min_size(egui::Pos2::ZERO, size)).is_none()); + } +} + +fn frame_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1200})); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"width":800,"height":600,"camera":h.app.cam}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h +} + +#[test] +fn environment_ring_drag_is_one_undo_snaps_and_never_navigates_the_camera() { + use egui::{Event, Modifiers, PointerButton}; + let mut h = environment_ring_fixture(); + environment::commit_environment(&mut h.app, json!({"rotation_deg":170})).unwrap(); + environment_ring_frame(&mut h, Modifiers::NONE, vec![]); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let at = |degrees: f32| ring.center + egui::vec2(degrees.to_radians().cos(), degrees.to_radians().sin()) * ring.radius; + let press = at(0.0); + let before = h.app.session.doc.clone(); + let camera = h.app.cam; + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + for pressed in [true, false] { + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }, + ], + ); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "a Shift click without a drag does not snap or save"); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + for angle in [10.0, 20.0, 30.0] { + environment_ring_frame(&mut h, Modifiers::SHIFT, vec![Event::PointerMoved(at(angle))]); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "drag is temporary"); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera, "OpenSCAD left-drag must not orbit through the ring"); + } + let end = at(30.0); + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::SHIFT }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!((h.app.render_workspace.view.studio.rotation_rad.to_degrees() + 165.0).abs() < 1e-6); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert!(crate::scenario::rect_of("render:environment:ring-degrees").is_some()); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_ring_cancel_or_stale_revision_discards_the_drag() { + use egui::{Event, Modifiers, PointerButton}; + for stale in [false, true] { + let mut h = environment_ring_fixture(); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let start = ring.center + egui::vec2(ring.radius, 0.0); + let end = ring.center + egui::vec2(0.0, ring.radius); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(start), + Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(end)]); + if stale { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":640}})).unwrap(); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + let cancel = if stale { + vec![] + } else { + vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }] + }; + environment_ring_frame(&mut h, Modifiers::NONE, cancel); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(start)]); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], + ); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn environment_ring_visibility_follows_editor_target_and_live_canvas() { + let mut h = environment_ring_fixture(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.app.render_workspace.view.selection = RenderSelection::Environment; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_some()); + h.app.render_workspace.view.selection = RenderSelection::Nothing; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.render_workspace.view.result = true; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); +} + +#[test] +fn environment_editor_opening_pages_and_sources_preserves_design_and_history() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for page in [inspector::Page::Environment, inspector::Page::Background] { + h.app.render_workspace.view.inspector.page = page; + environment_editor_frame(&mut h, vec![]); + assert!(crate::scenario::rect_of("render:environment:rotation-slider").is_some()); + h.app.ui.show_browser = false; + environment::open_sources(&mut h.app); + assert!(h.app.ui.show_browser); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +#[test] +fn environment_editor_controls_commit_one_undo_each_and_refuse_hostile_edits() { + let mut h = environment_editor_fixture(); + for request in [json!({"rotation_deg":215}), json!({"intensity":2.5})] { + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + } + for (color, transparent) in [([40, 80, 120], false), ([40, 80, 120], true), ([40, 80, 120], false)] { + let undo = h.app.session.undo.len(); + environment::commit_backdrop(&mut h.app, color, transparent).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let mut ground = environment::Ground { margin: 0.25, gap: 0.1, color: [0.18; 3] }; + for edit in 0..5 { + match edit { + 1 => ground.margin = 1.0, + 2 => ground.gap = 0.25, + 3 => ground.color = [0.1, 0.3, 0.5], + _ => {} + } + let undo = h.app.session.undo.len(); + environment::commit_ground(&mut h.app, edit != 4, ground.clone()).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for request in [json!({"rotation_deg":1e300}), json!({"intensity":-1}), json!({"rotation_deg":"NaN"}), json!(null), json!([])] { + assert!(environment::commit_environment(&mut h.app, request).is_err()); + } + assert!(environment::commit_ground(&mut h.app, true, environment::Ground { gap: f64::NAN, ..ground }).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn environment_editor_slider_drag_commits_only_on_release() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let rect = crate::scenario::rect_of("render:environment:rotation-slider").unwrap(); + let start = rect.center(); + let end = egui::pos2(rect.right() - 20.0, start.y); + let undo = h.app.session.undo.len(); + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(start), + egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + ], + ); + environment_editor_frame(&mut h, vec![egui::Event::PointerMoved(end)]); + assert_eq!(h.app.session.undo.len(), undo, "dragging is temporary"); + environment_editor_frame( + &mut h, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1, "release saves one edit"); + environment_editor_frame(&mut h, vec![]); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_hdr_header_reads_catalog_without_applying_or_saving() { + let mut h = environment_editor_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(305.0, 1600.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let named = crate::test_support::text_shapes(&output).any(|text| text.galley.job.text.contains("Neutral side softbox")); + output.textures_delta.clear(); + assert!(named); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for request in [json!({"rotation_deg":540}), json!({"intensity":0})] { + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } +} + +#[test] +fn render_workspace_frame_opening_editor_and_presets_never_mutates_or_starts_a_job() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + h.frames(4); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(crate::scenario::rect_of("render:shot:name").is_some()); + assert!(crate::scenario::rect_of("render:frame:aspect:16:9").is_some()); + assert!(crate::scenario::rect_of("render:frame:overlay").is_some()); + assert_eq!(shot::selected(&h.app), Some("Hero")); + h.step(&json!({"click":{"handle":"render:frame:thirds"}})).unwrap(); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + let mut h = frame_editor_fixture(); + let camera = Camera { fov: 175f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.frames(4); + assert_eq!(h.app.cam, camera, "opening must preserve valid FOVs outside the slider's usual editing range"); +} + +#[test] +fn render_workspace_frame_guides_are_transient_and_overlay_visibility_is_contextual() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.app.run("view.render_frame", json!({"aspect":"16:9","thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + assert!(shot::overlay_visible(&h.app)); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)); + let frame = shot::preview_rect(&h.app, viewport).unwrap(); + assert!((frame.width() / frame.height() - 16.0 / 9.0).abs() < 0.001); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + assert!(!shot::overlay_visible(&h.app)); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + assert!(shot::overlay_visible(&h.app)); + h.app.render_workspace.view.result = true; + assert!(!shot::overlay_visible(&h.app)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.doc.render.setups["Hero"].width, 800); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert!(h.app.render_workspace.view.frame.guides.safe_area); + assert!(h.app.render_workspace.view.frame.guides.centre_mark); +} + +#[test] +fn render_workspace_frame_exposure_drag_is_one_saved_edit_and_undoes() { + let mut h = frame_editor_fixture(); + shot::edit_settings(&mut h.app, "Hero", json!({"job":{"method":"cpu_raytrace"}})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0, "exposure track: {track:?}"); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + assert_ne!( + h.app.session.doc.render.setups["Hero"].exposure_ev, 0.0, + "track: {track:?}; state: {:?}; status: {:?}", + h.app.render_workspace.view.frame, h.app.status + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +#[test] +fn render_workspace_scene_render_shot_captures_current_size_and_live_camera_without_saving() { + let mut h = frame_editor_fixture(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + shot::edit_settings(&mut h.app, "Hero", json!({"width":16,"height":12})).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = Camera { distance: 85.0, fov: 35f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.app.run("view.render_frame", json!({"thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Hero")); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16384).unwrap(); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().unwrap(); + assert_eq!((frame.info.width, frame.info.height), (16, 12)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_frame_aspect_click_edits_only_selected_shot_size_once_and_undoes() { + let mut h = frame_editor_fixture(); + h.frames(4); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:frame:aspect:16:9"}})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), (1920, 1080)); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + for (index, expected) in [(1, (1620, 1080)), (2, (1080, 1080)), (3, (864, 1080)), (4, (1080, 1920))] { + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", index).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), expected); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", 5).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(shot::choose_aspect(&mut h.app, "Hero", usize::MAX).is_err()); +} + +#[test] +fn render_workspace_frame_shot_edits_revert_duplicate_and_rename_use_existing_commands() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.render.setups["Hero"].clone(); + let camera = Camera { distance: before.camera.distance * 2.0, ..before.camera }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + let undo = h.app.session.undo.len(); + assert!(shots::camera_modified(&h.app, "Hero")); + shot::edit_settings(&mut h.app, "Hero", json!({"camera":camera})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(!shots::camera_modified(&h.app, "Hero")); + h.app.run("edit.undo", json!({})).unwrap(); + shot::revert(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.cam, before.camera); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + shot::duplicate(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + let copied = h.app.session.doc.render.setups.iter().find(|(name, _)| name.as_str() != "Hero").unwrap().1; + assert_eq!(copied, &h.app.session.doc.render.setups["Hero"]); + shot::rename(&mut h.app, "Hero", "Renamed").unwrap(); + assert_eq!(shot::selected(&h.app), Some("Renamed")); + assert_eq!(h.app.session.undo.len(), undo + 3); + let before = h.app.session.doc.to_json(); + for patch in [json!({"width":0}), json!({"width":u32::MAX}), json!({"height":1e300}), json!({"exposure_ev":33}), json!({"exposure_ev":null})] { + assert!(shot::edit_settings(&mut h.app, "Renamed", patch).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + } +} + +fn render_lights_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"cpu_raytrace","options":{"lights":[ + {"direction":[0.6,0,0.8],"color":[1,0.5,0.25],"intensity":3}, + {"direction":[-0.8,0,0.6],"color":[0.25,0.5,1],"intensity":2} + ]}}}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + setups::load(&mut h.app); + h.app.pending_fit = None; + h +} + +#[test] +fn render_lights_solo_and_mute_filter_preview_and_render_copies_without_saving_or_history() { + let mut h = render_lights_fixture(); + let original = setups::snapshot(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let json = document.to_json(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + assert_eq!(light::preview(&h.app).unwrap().len(), 1); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["lights"][0]["intensity"], 0.0); + assert_eq!(request["settings"]["job"]["options"]["lights"][1]["intensity"], 2.0); + h.app.run("render.lights.mute", json!({"id":"directional:1","mute":true})).unwrap(); + assert!(light::preview(&h.app).unwrap().is_empty()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["lights"][1]["intensity"], 0.0); + assert_eq!(setups::snapshot(&h.app).unwrap(), original); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.doc.to_json(), json); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + assert!(h.app.run("render.lights.mute", json!({"id":"area:0","mute":true})).is_err()); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.active()); +} + +#[test] +fn render_lights_editor_opening_and_disabled_gpu_types_never_edit_or_start_a_job() { + let mut h = render_lights_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{"area_lights":[ + {"center":[0,0,100],"u":[1000000,0,0],"v":[0,-1000000,0],"radiance":[0,0,0]} + ]}}}}}), + ) + .unwrap(); + setups::load(&mut h.app); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + h.step(&json!({"click":{"handle":"render:light:type:point"}})).unwrap(); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); + assert_eq!(light::rows(&h.app).unwrap()[0].geometry.kind(), "area"); +} + +#[test] +fn render_lights_edit_commands_refresh_selected_editor_and_keep_visibility_separate_from_undo() { + let mut h = render_lights_fixture(); + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + light::edit(&mut h.app, "render.lights.set", Some("directional:0"), Some(json!({"intensity_ev":2}))).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 4.0); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, document); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 3.0); + light::edit(&mut h.app, "render.lights.duplicate", Some("directional:0"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:2".into())); + light::edit(&mut h.app, "render.lights.remove", Some("directional:2"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); +} + +#[test] +fn render_lights_fixed_studio_requests_carry_transient_weights_without_saving_them() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + let raster = image_request(&h.app).unwrap(); + assert_eq!(raster["studio_weights"], json!([0.0, 1.0, 0.0])); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + assert_eq!(image_request(&h.app).unwrap()["studio_weights"], json!([0.0, 1.0, 0.0])); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + assert!(serde_json::to_value(setups::snapshot(&h.app).unwrap()).unwrap().get("studio_weights").is_none()); +} + +#[test] +fn render_lights_list_inspects_unsaved_ui_draft_without_applying_or_opening_anything() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = + Some(vec![solidcraft_engine::render::job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 7.0 }]); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + let camera = h.app.cam; + let page = h.app.render_workspace.view.inspector.page; + let snapshot = setups::snapshot(&h.app).unwrap(); + let reply = h.app.run("render.lights.list", json!({"settings":snapshot})).unwrap(); + assert_eq!(reply["lights"].as_array().unwrap().len(), 1); + assert_eq!(reply["lights"][0]["id"], "directional:0"); + assert_eq!(reply["lights"][0]["name"], "Key"); + assert_eq!(reply["lights"][0]["intensity"], 7.0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert_eq!(setups::snapshot(&h.app).unwrap(), snapshot); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +mod async_path_host { + + #[test] + fn cpu_and_raster_render_entries_keep_gpu_setup_unstarted_across_document_reset() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + h.app.render_workspace.defer_path_host("not requested".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("a CPU/Raster method must not call this GPU factory".into()) + }); + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + enter(&mut h.app, true).unwrap(); + for _ in 0..3 { + sync_backend(&mut h.app); + } + // The synchronous state and retained factory prove that no worker was + // launched, even if a wrongly launched thread had not been scheduled yet. + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + + crate::documents::adopt(&mut h.app, Session::default()); + select_image_method(&mut h.app, method); + enter(&mut h.app, true).unwrap(); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("not requested")); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + } + + #[test] + fn explicit_gpu_selection_starts_once_and_keeps_its_receiver_across_document_changes() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let (started, seen) = mpsc::channel(); + let (release, wait) = mpsc::channel(); + h.app.render_workspace.defer_path_host("explicit request".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + started.send(()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + Err("deliberate device-free refusal".into()) + }); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + seen.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + // A real in-progress factory is not abandoned or duplicated when a new + // document defaults back to Raster, or the user changes methods meanwhile. + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + let duplicate_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not duplicate".into(), move || { + duplicate_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected duplicate preparation".into()) + }); + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + release.send(()).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("expected deliberate refusal") }; + assert_eq!(error, "deliberate device-free refusal"); + + // A method change or new document does not become an automatic retry. + crate::documents::adopt(&mut h.app, Session::default()); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("document reset lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("GPU selection lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + let retry_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not retry".into(), move || { + retry_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected replacement after terminal failure".into()) + }); + sync_backend(&mut h.app); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("terminal failure was replaced") }; + assert_eq!(error, "deliberate device-free refusal"); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + use super::*; + use solidcraft_engine::render::job; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + /// Advertise the path capability without opening a device or rendering anything. + struct TestExecutor; + impl job::ImageExecutor for TestExecutor { + fn descriptor(&self) -> job::Result { + let mut descriptor = job::CpuHost::cooperative().descriptor()?; + descriptor.id = ExecutorId::new("test-path").unwrap(); + descriptor.profiles[0].features.push(solidcraft_engine::render::RenderFeature::Progressive); + Ok(descriptor) + } + fn admit(&self, _: &ProductScene, _: &job::ImageRequest, _: job::JobOptions) -> job::Result { + panic!("setup tests must not render") + } + fn begin(&self, _: ProductScene, _: job::ImageRequest, _: job::JobOptions, _: job::CancelToken) -> job::Result> { + panic!("setup tests must not render") + } + } + + fn panel_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h + } + + fn finish_setup(h: &mut Harness) { + let deadline = Instant::now() + Duration::from_secs(10); + while matches!(h.app.render_workspace.path_host, PathHost::Preparing(..)) { + assert!(Instant::now() < deadline, "test setup worker did not finish"); + h.frames(1); + std::thread::sleep(Duration::from_millis(1)); + } + h.frames(3); + } + + #[test] + fn design_frames_and_document_reset_never_start_the_deferred_path_host() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(5); + crate::documents::adopt(&mut h.app, Session::default()); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn first_render_before_adapter_install_starts_once_when_the_adapter_arrives() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = panel_fixture(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + h.app.render_workspace.defer_path_host("late selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("deliberate device refusal".into()) + }); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + h.app.render_workspace.defer_path_host("must not retry".into(), || panic!("failed setup retried")); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_fallback_viewport_replaces_an_unstarted_factory_without_opening_the_old_device() { + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("old hardware adapter".into(), || panic!("superseded device opened")); + h.app.render_workspace.defer_path_host("selected safe-mode adapter".into(), || Err("selected adapter unavailable".into())); + h.frames(5); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("selected safe-mode adapter")); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("expected selected adapter result") }; + assert_eq!(message, "selected adapter unavailable"); + } + + #[test] + fn preparing_keeps_frames_responsive_then_registers_ready_host() { + let mut h = panel_fixture(); + let cpu_host = h.app.session.render_job_host().unwrap().clone(); + let (release, wait) = mpsc::channel(); + let (started, thread) = mpsc::channel(); + h.app.render_workspace.path_host.start(move || { + started.send(std::thread::current().id()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + assert_ne!(thread.recv_timeout(Duration::from_secs(10)).unwrap(), std::thread::current().id()); + // A second viewport installation cannot replace or duplicate setup. + h.app.render_workspace.path_host.start(|| panic!("setup started twice")); + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(!h.app.session.render_backend().executors.iter().any(|e| e.id.as_str() == "test-path")); + let transparent = h.app.tr("render.image_transparent").to_string(); + h.step(&json!({"widget":transparent})).unwrap(); + assert!(h.app.render_workspace.view.transparent); + // Replacing the current document must retain the receiver while setup waits. + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + enter(&mut h.app, false).unwrap(); + release.send(()).unwrap(); + finish_setup(&mut h); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_ok()); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + assert!(h.app.session.render_job_host().unwrap().same_host(&cpu_host)); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + } + + /// The first setup on an adapter shows a spinner, the time so far and a note; a later one + /// a bar estimated from the time the first took, which the preferences keep. + #[test] + fn setup_progress_is_estimated_from_the_last_setup_on_the_adapter() { + let mut h = panel_fixture(); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + let first = h.app.tr("render.gpu_path_first_setup").to_string(); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(h.widget(&first).is_some(), "the first setup explains the wait"); + assert!(h.widget("0:00").is_some(), "and counts the time"); + release.send(()).unwrap(); + finish_setup(&mut h); + let took = h.app.render_workspace.setup_seconds.get("Test GPU | Vulkan | 1.0").copied(); + assert!(took.is_some_and(|s| (0.0..10.0).contains(&s)), "{took:?}"); + + // The next start on the same adapter has an estimate, kept in the preferences. + let mut h = panel_fixture(); + h.app.load_prefs(&json!({"gpu_path_setup_seconds": {"Test GPU | Vulkan | 1.0": 120.0}}).to_string()); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + assert!(h.widget(&first).is_none()); + assert!(h.widget("0:00 / ~2:00").is_some(), "a bar with the estimate"); + release.send(()).unwrap(); + finish_setup(&mut h); + let prefs: serde_json::Value = serde_json::from_str(&h.app.prefs()).unwrap(); + assert!(prefs["gpu_path_setup_seconds"]["Test GPU | Vulkan | 1.0"].as_f64().is_some_and(|s| s < 10.0)); + } + + #[test] + fn hostile_setup_times_are_ignored() { + let times = load_setup_seconds(&json!({"a": -1.0, "b": 1e300, "c": "slow", "d": 30.0})); + assert_eq!(times.into_iter().collect::>(), [("d".to_string(), 30.0)]); + let many: serde_json::Map = (0..100).map(|i| (format!("gpu {i}"), json!(1.0))).collect(); + assert_eq!(load_setup_seconds(&serde_json::Value::Object(many)).len(), MAX_SETUP_TIMES); + } + + #[test] + fn setup_error_is_visible_and_survives_document_reset() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| Err("test driver refused the device".into())); + finish_setup(&mut h); + let message = "GPU path tracer unavailable: test driver refused the device"; + assert!(h.widget(message).is_some()); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(h.app.session.render_job_host().is_some()); + completed_preview(&mut h, [200, 210, 220]); + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget(message).is_some()); + h.app.render_workspace.path_host.start(|| panic!("failed setup retried on viewport install")); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + } + + #[test] + fn disconnected_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + let (tx, rx) = mpsc::channel(); + h.app.render_workspace.path_host = PathHost::Preparing(rx, Instant::now()); + drop(tx); + h.frames(3); + assert!(h.widget("GPU path tracer unavailable: setup worker stopped without returning a host").is_some()); + } + + #[test] + fn panicking_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| panic!("simulated driver panic")); + finish_setup(&mut h); + assert!(h.widget("GPU path tracer unavailable: GPU path tracer setup panicked").is_some()); + } + + #[test] + fn registration_failure_is_reported_in_the_panel() { + let mut h = panel_fixture(); + // A different host with the same CPU descriptor cannot be registered twice. + h.app.render_workspace.path_host.start(|| Ok(job::CpuHost::cooperative())); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("duplicate executor must fail") }; + assert!(h.widget(&format!("GPU path tracer unavailable: {message}")).is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn opaque_pbr_product_gpu_and_cpu_share_color_and_material_semantics() { + use solidcraft_engine::render::{ + StandardView, + job::{CancelToken, ImageRequest, ImageTask, TaskPoll}, + }; + let mut s = Session::default(); + s.execute("solid.sphere", &json!({"radius":10,"body_name":"Original sphere"})).unwrap(); + const SIZE: u32 = 256; + let mut previous = None; + for (metallic, roughness) in [(0.0, 0.2), (0.0, 0.65), (1.0, 0.2), (1.0, 0.65)] { + s.execute( + "appearance.assign", + &json!({"bodies":["Original sphere"],"color":"#b47846", + "pbr":{"metallic":metallic,"roughness":roughness,"dielectric_ior":1.5}}), + ) + .unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(!gpu.pbr.is_empty() && gpu.tris.is_empty()); + assert_ne!(previous, Some(key)); + previous = Some(key); + let mut camera = Camera { fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Iso); + camera.fit(&scene.bounds); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let mut task = ImageTask::new( + scene, + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera, + width: SIZE, + height: SIZE, + background: [255; 3], + transparent_background: false, + integrator: Default::default(), + raytrace: None, + }, + CancelToken::default(), + ) + .unwrap(); + let mut png = None; + for _ in 0..100_000 { + if let TaskPoll::Complete(bytes) = task.step(4096).unwrap() { + png = Some(bytes); + break; + } + } + let cpu = image::load_from_memory(&png.expect("bounded original fixture completes")).unwrap().to_rgba8(); + assert_eq!(cpu.dimensions(), (SIZE, SIZE)); + let cpu = cpu.into_raw(); + for srgb in [false, true] { + let Some(gpu) = crate::gpu::render_product_offscreen( + gpu.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 0.0], + SIZE, + srgb, + ) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let at = |pixels: &[u8], x: usize, y: usize| { + let i = (y * SIZE as usize + x) * 4; + [pixels[i], pixels[i + 1], pixels[i + 2]] + }; + let mut core = 0usize; + let mut error = 0usize; + let mut outliers = 0usize; + for y in 2..SIZE as usize - 2 { + for x in 2..SIZE as usize - 2 { + // Exclude antialiased silhouettes: CPU uses 2x supersampling, GPU uses 1x. + if (y - 1..=y + 1).any(|ny| (x - 1..=x + 1).any(|nx| at(&cpu, nx, ny) == [255; 3] || at(&gpu, nx, ny) == [255; 3])) { + continue; + } + let delta = at(&cpu, x, y).into_iter().zip(at(&gpu, x, y)).map(|(a, b)| usize::from(a.abs_diff(b))).collect::>(); + error += delta.iter().sum::(); + outliers += usize::from(delta.iter().any(|d| *d > 12)); + core += 1; + } + } + assert!(core > 1000); + let mean = error as f64 / (3 * core) as f64; + eprintln!("PBR m={metallic} r={roughness} srgb={srgb}: core={core}, mean={mean}, outliers={outliers}"); + assert!(mean < 2.0 && outliers * 100 < core * 2, "CPU/GPU color or material interpretation differs"); + } + } +} + +#[test] +fn control_render_export_respects_upstream_file_scope() { + let mut h = Harness::new(); + let root = h.dir.join("allowed"); + let outside = h.dir.join("outside"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let roots = json!([root.to_string_lossy()]); + let response = h.call("ui.workspace", json!({"workspace":"render","allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let response = h.call("engine.execute", json!({"command":"render.start","params":{"settings":{"width":16,"height":16}},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let job = response["result"]["job"].clone(); + for _ in 0..50 { + h.frames(1); + } + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); + for path in [outside.join("denied.png"), root.join("../outside/traversal.png")] { + for overwrite in [false, true] { + let response = h.call( + "engine.execute", + json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":overwrite},"allow_paths":roots}), + ); + assert_eq!(response["ok"], false, "{response}"); + assert!(response.to_string().contains("outside the folders this agent may use"), "{response}"); + } + } + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + let path = root.join("allowed.png"); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert!(path.is_file()); + let original = std::fs::read(&path).unwrap(); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":true},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(std::fs::read(&path).unwrap(), original); +} + +#[test] +fn adopting_into_blank_document_resets_render_draft_and_preserves_hosts() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.render_workspace.view.name = "Old draft".into(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let mut incoming = Session::default(); + incoming.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + crate::documents::adopt(&mut h.app, incoming); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + assert!(h.app.session.render_job_host().is_some()); + assert_eq!(h.app.session.model.state().bodies.len(), 1); +} + +#[test] +fn clicked_image_controls_complete_cancel_and_export_without_dirtying_the_design() { + for language in ["en", "de", "ko", "ru"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.frames(1); + let check = h.app.tr("cmd.render_preflight").to_string(); + let start = h.app.tr("render.image_start").to_string(); + let export = h.app.tr("render.image_export").to_string(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":check})).unwrap(); + h.step(&json!({"widget":start})).unwrap(); + for _ in 0..50 { + h.frames(1); + if h.app.render_workspace.view.completed.is_some() { + break; + } + } + let good = h.app.render_workspace.view.completed.unwrap(); + h.step(&json!({"widget":export})).unwrap(); + assert!(h.dir.join("render.png").is_file()); + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 768; + h.step(&json!({"widget":start})).unwrap(); + assert!(job_ready(&h.app, "render.cancel").is_ok()); + h.step(&json!({"click":{"handle":"render:stage:render.cancel"}})).unwrap(); + h.frames(5); + assert_eq!(h.app.render_workspace.view.completed, Some(good)); + assert_eq!( + h.app.session.execute("render.status", &json!({"job":h.app.render_workspace.view.job})).unwrap()["progress"]["phase"], + "cancelled" + ); + 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 saved_camera_survives_frames_and_product_fit_ignores_selection() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Product"})).unwrap(); + h.app.run("solid.box", json!({"corner":[100,0,0],"length":10,"width":20,"height":5,"body_name":"Other"})).unwrap(); + let camera = Camera { up: solidcraft_engine::render::UpAxis::Y, roll: 0.2, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"camera":camera,"background":[21,43,65]}})).unwrap(); + h.frames(3); + let design = h.app.cam; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h.step(&json!({"widget":"Restore Saved Camera"})).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.background, [21, 43, 65]); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Product".into() }]; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + let selected_fit = h.app.cam; + assert_product_fits_canvas(&h.app); + h.app.session.selection.clear(); + h.app.cam = camera; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + assert_eq!(h.app.cam, selected_fit, "Fit Product ignores the selected subset"); + enter(&mut h.app, false).unwrap(); + 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) => { + let expected = !solidcraft_gpu::select::path_backends().is_empty(); + assert!(!expected || 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 = PathHost::Ready(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.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.samples = 4; + h.app.render_workspace.view.max_depth = 3; + h.app.render_workspace.view.seed = 7; + h.app.render_workspace.view.draft.exposure_ev = 0.5; + h.app.render_workspace.view.studio.tone_map = solidcraft_engine::render::job::ToneMap::AcesFitted; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.studio.lens.aperture_radius_mm = 0.0; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.ambient = [0.75; 3]; + // The UI request reaches the real registered host with a coat and captured map. + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut material = materials::Binding::new(target, &h.app); + material.coat_enabled = true; + material.maps_enabled = true; + let map_path = h.dir.join("original-color.png"); + image::RgbaImage::from_pixel(1, 1, image::Rgba([80, 160, 220, 255])).save(&map_path).unwrap(); + material.maps.color = map_path.to_string_lossy().into_owned(); + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(material); + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + let checked = image_params(&h.app).unwrap(); + assert_eq!(checked["raytrace"]["clear_coats"][0]["weight"], 1.0); + assert_eq!(checked["raytrace"]["textures"][0]["base_color_srgb"], map_path.to_string_lossy().as_ref()); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + 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); + assert_eq!(status["options"]["max_depth"], 3); + assert_eq!(status["options"]["seed"], 7); + assert_eq!(status["options"]["exposure_ev"], 0.5); + assert_eq!(status["options"]["tone_map"], "aces_fitted"); + assert_eq!(status["options"]["lens"]["aperture_radius_mm"], 0.0); + assert_eq!(status["options"]["lighting"]["environment"], json!([0.75, 0.75, 0.75])); + assert_eq!(status["textures"]["bodies"], 1); + 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()); + // A pack glass recipe follows the same production request and passes actual + // closed-mesh preparation. It never calls scalar appearance assignment. + let material = &mut h.app.render_workspace.view.materials.bindings[0]; + material.coat_enabled = false; + material.maps_enabled = false; + material.glass_enabled = true; + material.glass = materials::Glass::recipe("starter.glass.clear-soda-lime").unwrap(); + let checked = image_params(&h.app).unwrap(); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + let started = h.app.run("render.start", checked).unwrap(); + let job = serde_json::from_value(started["job"].clone()).unwrap(); + let status = h.app.session.render_job_handle(job).unwrap().wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_engine::render::job::Phase::Completed, "{:?}", status.error); + 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"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + h.frames(3); + let camera = h.app.cam; + let flags = (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective); + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("workspace_switcher").unwrap().center(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + h.step(&json!({"click":{"handle":"menu:ui.workspace.render"}})).unwrap(); + assert!(active(&h.app)); + let heading = h.app.tr("render.page_scene").to_string(); + let perspective = h.app.tr("render.perspective").to_string(); + let save = h.app.tr("render.save_setup").to_string(); + let back = h.app.tr("render.return_design").to_string(); + assert!(h.widget(&heading).is_some(), "{language}"); + h.step(&json!({"click":{"handle":"render:scene:frame"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Camera); + h.step(&json!({"widget":perspective})).unwrap(); + assert!(!h.app.session.is_dirty(), "preview edits are staged"); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["Studio"].camera, h.app.cam); + h.step(&json!({"widget":back})).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.cam, camera); + assert_eq!(flags, (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective)); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!h.app.session.is_dirty()); + } +} + +#[test] +fn render_drafts_and_capabilities_are_isolated_across_document_switches() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.render_workspace.view.name = "First draft".into(); + h.app.render_workspace.view.draft.background = [20, 40, 60]; + h.app.render_workspace.view.dirty = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.name, "First draft"); + assert_eq!(h.app.render_workspace.view.draft.background, [20, 40, 60]); + assert!(h.app.render_workspace.view.dirty); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + h.app.run("file.new", json!({})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); +} + +#[test] +fn product_gpu_buffers_preserve_opacity_and_never_contain_overlays() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(gpu.tris.is_empty()); + assert!(!gpu.glass.is_empty()); + let color = |v: &[u8]| { + let i = v.get(crate::gpu::TRI_SIZE - 4..).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; + gpu.palette.get(crate::gpu::PaletteIndex(i)) + }; + assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| color(v) == Some([51, 102, 153, 102]))); + assert!(gpu.lines.is_empty() && gpu.overlay.is_empty() && gpu.under.is_empty() && gpu.hidden.is_empty() && gpu.ghost.is_empty()); + s.selection = vec![solidcraft_engine::Sel::Body { name: "Glass".into() }]; + s.section = Some((solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::X)); + let after = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(gpu_scene(&after).unwrap().0, key); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.0})).unwrap(); + let invisible = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(invisible.meshes[0].opacity, 0.0); + let (_, empty) = gpu_scene(&invisible).unwrap(); + assert!(empty.tris.is_empty() && empty.glass.is_empty()); +} + +#[test] +fn transmission_uses_legacy_preview_buffers_and_invalidates_the_opaque_cache() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + let appearance = json!({"bodies":["Glass"],"color":"#336699", + "pbr":{"metallic":0,"roughness":0.1,"dielectric_ior":1.5}}); + s.execute("appearance.assign", &appearance).unwrap(); + let (opaque_key, opaque) = gpu_scene(&solidcraft_engine::product_scene::extract(&s).unwrap()).unwrap(); + assert!(!opaque.pbr.is_empty()); + let mut scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + scene.meshes[0].transmission = + Some(solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::ZERO, None).unwrap()); + let (glass_key, glass) = gpu_scene(&scene).unwrap(); + assert_ne!(opaque_key, glass_key); + assert!(glass.pbr.is_empty()); + assert!(!glass.tris.is_empty()); + scene.meshes[0].opacity = 0.4; + let (_, transparent) = gpu_scene(&scene).unwrap(); + assert!(transparent.pbr.is_empty()); + assert!(!transparent.glass.is_empty()); +} + +#[test] +fn host_profiles_advertise_only_installed_opaque_pbr_not_hdri_refraction_or_final() { + use solidcraft_engine::render::*; + let host = host_executor(512, true, 4).unwrap(); + assert_eq!(host.limits.max_dimension, 512); + assert_eq!(host.profiles.len(), 1); + assert_eq!(host.profiles[0].features, vec![RenderFeature::Pbr]); + assert!(host.profiles[0].formats.is_empty()); + let mut s = Session::default(); + s.set_render_viewport(Some(host)).unwrap(); + let mut request = RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width: 512, + height: 512, + format: None, + features: Vec::new(), + policy: Default::default(), + }; + assert_eq!(resolve_request(&[s.render_backend()], &request).unwrap().executor.as_str(), "gpu-viewport"); + request.features = vec![RenderFeature::Pbr]; + assert!(resolve_request(&[s.render_backend()], &request).is_ok()); + for unsupported in [RenderFeature::Hdri, RenderFeature::Refraction, RenderFeature::Progressive] { + request.features = vec![unsupported]; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + } + request.features.clear(); + request.width = 513; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + request.width = 512; + request.mode = RenderMode::Final; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + assert!(host_executor(1024, false, 1).unwrap().availability != Availability::Available); + assert!(host_executor(1024, true, 0).is_err()); +} + +fn completed_preview(h: &mut Harness, background: [u8; 3]) -> solidcraft_engine::render::job::JobId { + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":16,"height":16,"background":background}})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..100 { + host.pump(16384).unwrap(); + if h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" { + return job; + } + } + panic!("small cooperative image did not complete within the work budget"); +} + +fn image_panel_frame(app: &mut SolveApp, ctx: &egui::Context) -> egui::FullOutput { + ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(285.0, 1200.0))), ..Default::default() }, + |ui| image_controls(app, ui), + ) +} + +#[test] +fn completed_image_is_painted_once_available_and_upload_is_cached() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none()); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + let texture = texture.as_ref().unwrap(); + let id = texture.id(); + assert_eq!(*cached_job, job); + assert_eq!(texture.size(), [16, 16]); + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert!(pixels.pixels.iter().all(|p| *p == Color32::from_rgb(20, 40, 60))); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!( + ctx.tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| { matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty()) }) + ); + let mut output = image_panel_frame(&mut h.app, &ctx); + assert!(!output.textures_delta.set.contains_key(&id), "repaint must reuse the texture"); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let path = h.dir.join("displayed.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png(), "displaying the image must not change export bytes"); +} + +#[test] +fn completed_image_keeps_last_export_during_work_and_updates_for_the_next_job() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(first); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + let old_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + assert_eq!(*cached_job, second); + assert_ne!(texture.as_ref().unwrap().id(), old_texture); + assert!(output.textures_delta.free.contains(&old_texture)); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 42.0; + let framing = h.app.render_workspace.view.result_camera; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none(), "another document must not show this image"); + assert!(!h.app.render_workspace.view.result); + crate::documents::switch(&mut h.app, 0); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, second); + assert!(h.app.render_workspace.view.result); + assert_eq!(h.app.render_workspace.view.result_camera, framing); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + reset_document(&mut h.app); + assert!(h.app.render_workspace.image.is_none()); + assert!(!h.app.render_workspace.view.result); +} + +#[test] +fn completed_image_decoder_preserves_alpha_and_rejects_invalid_sizes_and_pngs() { + let mut png = std::io::Cursor::new(Vec::new()); + let pixels = image::RgbaImage::from_pixel(2, 1, image::Rgba([80, 120, 160, 128])); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + let decoded = decode_image(png.get_ref(), 2, 1).unwrap(); + assert_eq!(decoded.size, [2, 1]); + assert_eq!(decoded.pixels, vec![Color32::from_rgba_unmultiplied(80, 120, 160, 128); 2]); + for (width, height) in [(0, 1), (u32::MAX, 1), (4096, 4096), (1, 1), (3, 1)] { + assert!(decode_image(png.get_ref(), width, height).is_err(), "{width}x{height}"); + } + assert!(decode_image(b"invalid PNG", 2, 1).is_err()); +} + +#[test] +fn cpu_checkpoints_replace_only_the_provisional_texture_and_keep_final_export_and_framing() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(first); + h.app.render_workspace.view.job = Some(first); + cache_render_images(&mut h.app, &ctx); + let final_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let second = completed_preview(&mut h, [80, 100, 120]); + let frame = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.job = Some(second); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + assert_eq!(displayed_image(&h.app).unwrap().info.job, second); + assert!(displayed_image(&h.app).unwrap().preview.is_some()); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 123.0; + h.app.render_workspace.view.result_camera.target.x = 5.0; + let camera = h.app.render_workspace.view.result_camera; + let first_checkpoint = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + // Repeated or older metadata never re-decodes bytes, even if passed bad data. + cache_preview_frame(&mut h.app, &ctx, &info, b"must not decode again"); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), first_checkpoint); + info.frame_sequence = 2; + info.samples_per_pixel = 2; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + let newer = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + assert_ne!(newer, first_checkpoint); + info.frame_sequence = 1; + cache_preview_frame(&mut h.app, &ctx, &info, b"out of order"); + remember_displayed_job(&mut h.app, false); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().info.frame_sequence, 2); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), newer); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), final_texture); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + let path = h.dir.join("checkpoint-export-is-final.png"); + h.app.run("render.export", json!({"job":h.app.render_workspace.view.completed,"path":path})).unwrap(); + let retained = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), retained.png()); + // A final can arrive after the panel read a still-running status. The cached + // completed ID deliberately remains the old job until publication is sampled. + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(displayed_image(&h.app).unwrap().preview.is_none()); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().job, second); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free, "a subsequent status refresh must not refit the new final"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn cancelling_a_preview_returns_to_the_final_image_without_resetting_pan_or_export() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let final_job = completed_preview(&mut h, [30, 50, 70]); + h.app.render_workspace.view.completed = Some(final_job); + h.app.render_workspace.view.job = Some(final_job); + cache_render_images(&mut h.app, &ctx); + let frame = h.app.session.render_job_handle(final_job).unwrap().frame().unwrap().unwrap(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_none(), "a different job's checkpoint must be ignored"); + info.frame.job = pending; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.target.x = 12.0; + h.app.render_workspace.view.result_camera.distance = 87.0; + let camera = h.app.render_workspace.view.result_camera; + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert_eq!(displayed_image(&h.app).unwrap().info.job, final_job); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.view.completed, Some(final_job)); + assert!(h.app.run("render.export", json!({"job":pending,"path":h.dir.join("not-final.png")})).is_err()); + let path = h.dir.join("after-preview-cancel.png"); + h.app.run("render.export", json!({"job":final_job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + // Document adoption must also release a provisional texture without leaking it into a tab. + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_some()); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(displayed_image(&h.app).is_none()); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn result_framing_fits_both_axes_and_actual_size_respects_display_pixels() { + let canvas = egui::Rect::from_min_size(egui::pos2(40.0, 80.0), egui::vec2(800.0, 500.0)); + for size in [[1920, 1080], [100, 4000], [16, 16]] { + for dpi in [1.0, 1.5, 2.0] { + let fit = result_camera(size, canvas, dpi, ResultScale::Fit); + assert!(fit.is_valid()); + let fitted = result_rect(fit, size, canvas); + assert!(canvas.contains_rect(fitted), "{size:?} at {dpi}: {fitted:?}"); + assert_eq!(fitted.center(), canvas.center()); + let actual = result_rect(result_camera(size, canvas, dpi, ResultScale::Actual), size, canvas); + assert!((actual.width() * dpi - size[0] as f32).abs() < 0.01); + assert!((actual.height() * dpi - size[1] as f32).abs() < 0.01); + } + } +} + +#[test] +fn result_canvas_paints_large_capture_reports_staleness_and_preserves_export() { + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let preview = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + let draw = |app: &mut SolveApp| { + let mut out = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(app, ui), + ); + out.textures_delta.clear(); + out + }; + let out = draw(&mut h.app); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let current = h.app.tr("render.result_current"); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == current)); + let identity = format!("{}:{}:{}", job.session, job.serial, job.generation); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text().contains(&identity))); + let image_bounds = ctx + .tessellate(out.shapes, out.pixels_per_point) + .iter() + .filter_map(|p| match &p.primitive { + egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id => { + Some(mesh.vertices.iter().fold(egui::Rect::NOTHING, |r, v| r.union(egui::Rect::from_min_max(v.pos, v.pos)))) + } + _ => None, + }) + .fold(egui::Rect::NOTHING, |a, b| a.union(b)); + assert!(image_bounds.width() > 240.0 && image_bounds.height() > 240.0, "{image_bounds:?}"); + assert_eq!(h.app.cam, preview); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.session.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + let out = draw(&mut h.app); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == h.app.tr("render.image_stale"))); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().scene_generation, frame.info.scene_generation); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), id); + let path = h.dir.join("result-canvas.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); +} + +#[test] +fn result_navigation_uses_shared_pan_zoom_and_leaves_product_camera_unchanged() { + use egui::{Event, Key, Modifiers, PointerButton, vec2}; + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.ui.perspective = true; + h.app.preferences.smooth_wheel_zoom = false; + h.app.preferences.zoom_reverse = false; + let preview = h.app.cam; + let draft = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let dirty = h.app.render_workspace.view.dirty; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut time = 0.0; + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let fitted = h.app.render_workspace.view.result_camera; + let p = h.app.viewport.rect.unwrap().center() + vec2(80.0, 20.0); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p)]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 3.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert!(h.app.render_workspace.view.result_camera.distance < fitted.distance); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + let before_pan = h.app.render_workspace.view.result_camera.target; + let space = |pressed| Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![space(true), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], + ); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p + vec2(40.0, -20.0))]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![ + Event::PointerButton { pos: p + vec2(40.0, -20.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + space(false), + ], + ); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_pan); + assert_eq!(h.app.render_workspace.view.result_camera.pitch, fitted.pitch); + assert_eq!(h.app.render_workspace.view.result_camera.yaw, fitted.yaw); + let before_key = h.app.render_workspace.view.result_camera.target; + assert!(crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::CTRL, false)); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_key); + assert!(!crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::NONE, false)); + for command in ["view.fit", "view.home"] { + h.app.render_workspace.view.result_camera.target.x += 20.0; + h.app.run(command, json!({})).unwrap(); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + assert_eq!(h.app.render_workspace.view.result_camera, fitted); + } + assert_eq!(h.app.cam, preview); + assert!(h.app.ui.perspective); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), draft); + assert_eq!(h.app.render_workspace.view.dirty, dirty); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_params(&h.app).unwrap()["settings"]["camera"], json!(preview)); +} + +#[test] +fn clicked_result_controls_switch_canvas_and_frame_without_changing_the_setup() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let result = h.app.tr("render.result_title").to_string(); + h.step(&json!({"widget":result})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.result); + h.step(&json!({"widget":"100%"})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Actual); + let fit = h.app.tr("render.result_fit").to_string(); + h.step(&json!({"widget":fit})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Fit); + let preview = h.app.tr("render.result_preview").to_string(); + h.step(&json!({"widget":preview})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn image_method_requests_never_fall_back_or_mix_cpu_and_gpu_options() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = h.app.cam.distance * 3.0; + h.app.render_workspace.view.raytrace.exposure_ev = f64::NAN; + h.app.render_workspace.view.samples = 256; + h.app.render_workspace.view.max_depth = 12; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.draft.exposure_ev = 0.0; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "never-opened.hdr".into() }; + h.app.render_workspace.view.studio.denoise = true; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "never-opened-cpu.hdr".into() }; + let params = image_params(&h.app).unwrap(); + assert_eq!(params["settings"]["camera"], json!(h.app.cam)); + assert_eq!(params["settings"]["exposure_ev"], 0.0); + for key in ["progressive", "samples", "max_depth", "seed", "integrator", "raytrace", "environment", "lighting", "tone_map", "lens", "denoise"] { + assert!(params.get(key).is_none(), "raster must omit {key}"); + } + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert!(image_params(&h.app).is_err(), "missing GPU cannot silently render on CPU"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "unsupported CPU options or host must be refused"); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_params(&h.app).is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_cpu_controls_check_and_start_the_same_capture_and_keep_it_exportable() { + use solidcraft_engine::render::job::{CpuHost, Phase}; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-cpu"}})).unwrap(); + if !available { + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(image_params(&h.app).is_err()); + return; + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.step(&json!({"click":{"handle":"render:aa"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:aa-4"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + h.app.render_workspace.view.raytrace.preset = Some(LightingPreset::WarmCool); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let numeric = image_params(&h.app).unwrap(); + assert_eq!(numeric["settings"]["job"]["method"], "cpu_raytrace"); + assert!(numeric.get("raytrace").is_none()); + let numeric_check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":numeric_check})).unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, numeric); + let reflected = h.app.session.world_state().bodies.first().unwrap().name.clone(); + let reflection_section = format!("dialog:section:{}", h.app.tr("render.cpu_reflections")); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-body"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-add"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("render:cpu-reflection-mode:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render.cpu_reflection_mirror"}})).unwrap(); + assert_eq!( + h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().bodies[0].mode, + solidcraft_engine::render::job::ReflectionMode::Mirror + ); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + let hdr_path = h.dir.join("cpu-captured.hdr"); + let mut hdr = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 1 +X 2\n".to_vec(); + hdr.extend_from_slice(&[128, 128, 128, 129, 128, 128, 128, 129]); + std::fs::write(&hdr_path, &hdr).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, hdr_path.to_string_lossy().into_owned()).unwrap(); + h.app.render_workspace.view.cpu.samples = 4; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = 42.0; + h.frames(2); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let params = image_params(&h.app).unwrap(); + let preflight = h.app.session.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(preflight["resolved"]["executor"], "cpu-raytrace"); + let check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":check})).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), params); + let checked = h.app.render_workspace.view.cpu.checked.as_ref().unwrap(); + assert_eq!(checked.request, params); + assert_eq!(checked.environment, preflight["environment"]); + let start = h.app.tr("render.image_start").to_string(); + h.step(&json!({"widget":start})).unwrap(); + let id = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + // The job owns the source bytes captured by Start, even if the file changes. + std::fs::write(&hdr_path, b"changed after capture").unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(json!(status.environment), preflight["environment"]); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(json!(status.request.camera), params["settings"]["camera"]); + assert_eq!(json!(status.request.raytrace), params["raytrace"]); + assert_eq!(status.request.width, 16); + assert_eq!(status.request.height, 16); + h.frames(3); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + let path = h.dir.join("cpu-result-canvas.png"); + h.app.run("render.export", json!({"job":id,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + h.app.render_workspace.view.transparent = true; + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_opaque_required"))); + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.primary_samples = 3; + assert!(image_params(&h.app).is_err()); + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.area_lights = Some(Vec::new()); + assert_eq!(image_params(&h.app).unwrap()["raytrace"]["area_lights"], json!([])); +} + +fn async_export_fixture() -> (Harness, solidcraft_engine::render::job::JobId) { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + let job = completed_preview(&mut h, [200, 210, 220]); + (h, job) +} + +#[test] +fn delayed_image_export_holds_its_document_without_changing_history() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("delayed.png"); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy() && !path.exists()); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], true); + crate::documents::new_design(&mut h.app); + let other = h.app.session.doc.clone(); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.docs.active, 0, "upstream holds tab changes while a picker is pending"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], false); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); + assert_eq!(&std::fs::read(&path).unwrap()[..8], b"\x89PNG\r\n\x1a\n"); + crate::documents::switch(&mut h.app, 0); + 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 delayed_image_export_cancel_and_overwrite_choice_preserve_existing_files() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("existing.png"); + std::fs::write(&path, b"existing contents").unwrap(); + let doc = h.app.session.doc.clone(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!h.app.file_picker_busy()); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents"); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + h.app.render_workspace.view.overwrite = true; + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents", "a later checkbox change is not overwrite consent for the pending export"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); +} + +#[test] +fn delayed_image_export_never_substitutes_a_newer_retained_image() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("old-image.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + let newer = completed_preview(&mut h, [20, 30, 40]); + h.app.render_workspace.view.completed = Some(newer); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists(), "the evicted requested image must fail instead of exporting the newer image"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert_eq!(h.app.render_workspace.view.completed, Some(newer)); + let newer_path = h.dir.join("new-image.png"); + h.app.run("render.export", json!({"job":newer,"path":newer_path})).unwrap(); + assert!(newer_path.is_file()); +} + +#[test] +fn delayed_image_export_holds_close_and_new_document_until_cancel() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("closed.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + crate::documents::new_design(&mut h.app); + crate::documents::close(&mut h.app, 0, true); + let other = h.app.session.doc.clone(); + assert_eq!(h.app.docs.count(), 1); + assert!(h.app.file_picker_busy()); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists() && !h.app.file_picker_busy()); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); +} + +#[test] +fn delayed_image_export_refuses_an_internally_replaced_document_even_with_overwrite() { + use crate::picker_test_support::{Slot, save}; + for overwrite in [false, true] { + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("keep.png"); + std::fs::write(&path, b"keep this file").unwrap(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, overwrite); + assert!(h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":[1,2,3]})).is_err()); + // Internal host/session changes are outside the input hold; never export them by accident. + h.app.session.execute("appearance.assign", &json!({"bodies":["Body1"],"color":[1,2,3]})).unwrap(); + let changed = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.revision); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &crate::fonts::test_context()); + assert_eq!(std::fs::read(path).unwrap(), b"keep this file"); + assert!(Arc::ptr_eq(&changed, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.revision), history); + assert!(matches!(&h.app.status, Some((_, _, true)))); + } +} + +/// One frame of either the modelling viewport or the Render preview, over the same rectangle. +fn nav_frame(app: &mut crate::SolveApp, ctx: &egui::Context, render: bool, time: &mut f64, mods: egui::Modifiers, events: Vec) { + *time += 1.0 / 60.0; + let events = std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + if render { + show(app, ui); + } else { + crate::viewport::show(app, ui); + } + }); + out.textures_delta.clear(); +} + +fn nav_app(render: bool, preset: &str, around: crate::prefs::OrbitAround) -> crate::SolveApp { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + let mut app = crate::SolveApp::new(s, crate::Services::default()); + if render { + enter(&mut app, true).unwrap(); + assert!(active(&app)); + } + app.preferences.nav = preset.into(); + app.preferences.orbit_around = around; + app.preferences.zoom_to_cursor = true; + app.ui.perspective = true; + let mut cam = Camera { fov: 0.6, ..Default::default() }; + cam.set_view(solidcraft_engine::render::StandardView::Iso); + cam.fit(&solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds); + app.cam = cam; + app +} + +/// #1454: the same mouse, wheel and modifier input moves the Render preview's camera exactly as +/// it moves the modelling viewport's, under every navigation preset and Orbit around setting. +#[test] +fn render_preview_navigates_like_the_modelling_viewport_in_every_preset() { + use egui::{Event, Modifiers, PointerButton, pos2, vec2}; + let none = Modifiers::NONE; + let chords = [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT]; + let arounds = [crate::prefs::OrbitAround::ViewCentre, crate::prefs::OrbitAround::Cursor, crate::prefs::OrbitAround::Origin]; + for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { + for around in arounds { + let (design_ctx, render_ctx) = (crate::fonts::test_context(), crate::fonts::test_context()); + let mut design = nav_app(false, preset, around); + let mut render = nav_app(true, preset, around); + let (mut design_time, mut render_time) = (0.0, 0.0); + let mut both = |events: Vec, mods: Modifiers, design: &mut crate::SolveApp, render: &mut crate::SolveApp| { + nav_frame(design, &design_ctx, false, &mut design_time, mods, events.clone()); + nav_frame(render, &render_ctx, true, &mut render_time, mods, events); + }; + both(vec![], none, &mut design, &mut render); + assert_eq!(design.viewport.rect, render.viewport.rect); + // Presses start on empty space in both workspaces, and the wheel + // turns over the model, so zoom to the cursor anchors on its surface. + let empty = pos2(90.0, 520.0); + let proj = crate::viewport::projection(&design, design.viewport.rect.unwrap()); + assert!(crate::viewport::pick(&design, &proj, empty).is_empty()); + let model = proj.to_screen(design.cam.target).unwrap(); + assert!(!crate::viewport::pick(&design, &proj, model).is_empty()); + let mut moved = 0; + for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { + for mods in chords { + let before = design.cam; + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerButton { pos: empty, button, pressed: true, modifiers: mods }], mods, &mut design, &mut render); + let mut at = empty; + for _ in 0..5 { + at += vec2(14.0, -9.0); + both(vec![Event::PointerMoved(at)], mods, &mut design, &mut render); + } + both(vec![Event::PointerButton { pos: at, button, pressed: false, modifiers: mods }], mods, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_eq!(design.cam, render.cam, "{preset} {around:?}: {button:?} drag with {mods:?}"); + moved += usize::from(design.cam != before); + // Let any snap settle and start the next gesture from the same view. + design.cam = render.cam; + } + } + assert!(moved >= 2, "{preset}: the preset's drags move the camera ({moved})"); + // Wheel over the model, then modifier-only motion (Touchpad: Shift pans, Alt orbits). + let before = design.cam; + both(vec![Event::PointerMoved(model)], none, &mut design, &mut render); + let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; + both(vec![wheel], none, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_ne!(design.cam, before, "{preset}: the wheel zooms"); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: wheel zoom to the cursor"); + for mods in [Modifiers::SHIFT, Modifiers::ALT] { + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty + vec2(25.0, 15.0))], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty)], none, &mut design, &mut render); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: modifier motion with {mods:?}"); + } + assert!(render.session.selection.is_empty(), "camera navigation must not select"); + } + } +} + +/// #1454: Fit (F6), a middle double-click, and the axis view's and navigation cube's Home and +/// view controls all work in the Render workspace, framing the product scene. +#[test] +fn render_workspace_view_keys_double_middle_click_and_navigators_work() { + for style in [crate::prefs::NavigatorStyle::Axes, crate::prefs::NavigatorStyle::Cube] { + let mut h = Harness::new(); + h.app.preferences.navigator_style = style; + h.app.preferences.look_at_anim = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let mut home = h.app.cam; + home.set_view(solidcraft_engine::render::StandardView::Iso); + let off = |h: &mut Harness| { + h.app.cam.yaw += 0.7; + h.app.cam.pitch = 0.1; + h.app.cam.distance *= 3.0; + h.app.cam.target.x += 25.0; + h.frames(2); + }; + // F6 fits, keeping the direction. + off(&mut h); + let before = h.app.cam; + h.step(&json!({"key":"F6"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (before.yaw, before.pitch, before.roll, before.up), + "{style:?}: F6 retains orientation" + ); + assert!(h.app.cam.distance < before.distance, "{style:?}: F6 frames the product"); + assert_product_fits_canvas(&h.app); + // A middle double-click goes Home. + off(&mut h); + let centre = h.app.viewport.rect.unwrap().center(); + h.step(&json!({"click":[centre.x, centre.y], "double":true, "button":"middle"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (home.yaw, home.pitch, home.roll, home.up), + "{style:?}: middle double-click" + ); + assert_product_fits_canvas(&h.app); + // The navigator's Home control. + off(&mut h); + let handle = match style { + crate::prefs::NavigatorStyle::Axes => "axis_view:home", + crate::prefs::NavigatorStyle::Cube => "navigation_cube:control:home", + }; + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.settle(); + assert!( + (h.app.cam.yaw - home.yaw).abs() < 1e-6 && (h.app.cam.pitch - home.pitch).abs() < 1e-6, + "{style:?}: navigator Home turns to the home view" + ); + // A standard view from the navigator. + h.step(&json!({"click":{"handle":"axis_view:z"}})).unwrap(); + h.settle(); + assert!(h.app.cam.back().dot(solidcraft_engine::geom::Vec3::Z) > 0.999, "{style:?}: view from +Z, got {:?}", h.app.cam.back()); + assert!(h.app.session.selection.is_empty()); + } +} + +/// #1464: a maximised 4K or 5K window is past the preview's pixel budget. The preview draws +/// smaller at the same aspect instead of refusing every frame. +#[test] +fn four_and_five_k_viewports_preview_downscaled_within_the_limits() { + use solidcraft_engine::render::*; + for samples in [1, 4, 16] { + let host = host_executor(16384, true, samples).unwrap(); + let mut s = Session::default(); + s.set_render_viewport(Some(host.clone())).unwrap(); + let request = |width, height| RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width, + height, + format: None, + features: vec![RenderFeature::Pbr], + policy: Default::default(), + }; + if samples <= 4 { + assert_eq!(preview_size(s.render_viewport(), (1920, 1080)), (1920, 1080), "fits: drawn at full size"); + } + // 16× MSAA's scratch cost brings even 1080p under the budget. + let sizes: &[(u64, u64)] = if samples == 16 { &[(1920, 1080), (3840, 2160), (5120, 2880)] } else { &[(3840, 2160), (5120, 2880)] }; + for &full in sizes { + assert!(resolve_request(&[s.render_backend()], &request(full.0, full.1)).is_err(), "{full:?} at full size is over the limit"); + let (w, h) = preview_size(s.render_viewport(), full); + assert!(w < full.0 && h < full.1 && w * h <= host.limits.max_pixels, "{full:?} -> {w}x{h}"); + assert!((w as f64 / h as f64 - 16.0 / 9.0).abs() < 0.01, "{w}x{h} keeps the aspect"); + let resolved = resolve_request(&[s.render_backend()], &request(w, h)).unwrap(); + assert_eq!(resolved.executor.as_str(), "gpu-viewport"); + assert!(resolved.estimated_scratch_bytes <= host.limits.max_scratch_bytes); + } + } + assert_eq!(preview_size(None, (5120, 2880)), (5120, 2880), "no executor: resolution reports it"); +} + +/// Backend failures must remain readable in the fixed-width Render panel, not +/// disappear into an ellipsis before the reason and recovery guidance are shown. +#[test] +fn backend_diagnostics_wrap_without_elision_in_bounded_image_controls() { + fn collect<'a>(shape: &'a egui::Shape, texts: &mut Vec<&'a egui::epaint::TextShape>) { + match shape { + egui::Shape::Text(text) => texts.push(text), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, texts)), + _ => {} + } + } + for mode in ["floating", "compact"] { + for dark in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1400,"height":1800})); + h.app.run("view.layout", json!({"mode":mode})).unwrap(); + enter(&mut h.app, true).unwrap(); + let reason = "The selected viewport adapter has no compatible Vulkan path device. Images remain available on the CPU; keep the original design and review the driver before retrying."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + h.frames(3); + let expected = format!("{}: {reason}", h.app.tr("render.gpu_path_failed")); + let mut out = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1800.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + ui.set_max_width(285.0); + image_controls(&mut h.app, ui); + }, + ); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|shape| collect(&shape.shape, &mut texts)); + { + let message = &expected; + let text = texts.iter().find(|text| text.galley.job.text == *message).expect("the complete diagnostic is painted"); + assert!(!text.galley.elided, "{mode}, dark={dark}: {message}"); + assert!(text.galley.rows.len() > 1, "long messages must wrap in the narrow panel"); + assert!(text.galley.rect.width() <= 285.0, "the message must not expand the panel"); + } + } + } +} + +#[test] +fn gpu_material_recipes_use_exact_linear_absorption_without_changing_saved_appearance() { + use solidcraft_engine::doc::appearance_pack::{GlassBoundary, Recipe, STARTER_PACK}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + h.app.session.mark_saved(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(preset.id).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding]; + let mut params = json!({"progressive":true}); + materials::params(&h.app, &mut params).unwrap(); + let wire = ¶ms["raytrace"]["dielectrics"][0]; + assert_eq!(wire["body_name"], "Optics"); + assert_eq!(wire["ior"], recipe.dielectric_ior); + let [r, g, b]: [f64; 3] = serde_json::from_value(wire["absorption_per_mm"].clone()).unwrap(); + let medium = solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + let transmitted = medium.attenuation(recipe.reference_path_mm).unwrap(); + for (actual, expected) in [transmitted.x, transmitted.y, transmitted.z].into_iter().zip(recipe.transmission_linear_rgb) { + assert!((actual - expected).abs() < 1e-12, "the actual optical consumer must reproduce the recipe's linear transmittance"); + } + match recipe.boundary { + GlassBoundary::Closed => { + assert_eq!(wire["boundary"], "closed_mesh"); + assert_eq!(wire["thickness_mm"], 0.0); + } + GlassBoundary::Thin { thickness_mm } => { + assert_eq!(wire["boundary"], "thin_sheet"); + assert_eq!(wire["thickness_mm"], thickness_mm); + } + } + assert!(wire.get("opacity").is_none()); + count += 1; + } + assert_eq!(count, 6); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.materials.enabled = false; + let mut raster = json!({}); + materials::params(&h.app, &mut raster).unwrap(); + assert!(raster.get("raytrace").is_none()); +} + +#[test] +fn gpu_material_identity_requires_explicit_revalidation_and_never_retargets() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.coat_enabled = true; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[20,0,0],"body_name":"Other","operation":"new"})).unwrap(); + let scene = h.app.run("render.scene", json!({})).unwrap(); + let target: materials::Target = + serde_json::from_value(scene["bodies"].as_array().unwrap().iter().find(|body| body["name"] == "Other").unwrap().clone()).unwrap(); + let mut moved = materials::Binding::new(target.clone(), &h.app); + moved.coat_enabled = true; + h.app.render_workspace.view.materials.bindings = vec![moved.clone()]; + h.app.run("browser.visibility", json!({"items":["Optics"],"visible":false})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + assert!(materials::revalidate(&mut h.app, &mut moved).is_err(), "a surviving body with a new ordinal must be selected explicitly"); + assert_eq!(moved.target, target); + let scene = h.app.run("render.scene", json!({})).unwrap(); + assert_eq!(scene["bodies"][0]["name"], "Other"); + assert_ne!(scene["bodies"][0]["ordinal"], target.ordinal); + binding.target.name = "Different body".into(); + assert!(materials::revalidate(&mut h.app, &mut binding).is_err()); + assert_eq!(binding.target.name, "Different body"); + reset_document(&mut h.app); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); +} + +#[test] +fn clicked_gpu_glass_recipe_stays_temporary_and_blocks_cpu_rendering() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.session.mark_saved(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.frames(3); + let doc = h.app.session.doc.clone(); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render:material-body-0"}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let glass = h.app.tr("render.appearance_editor.glass").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.material_custom")})).unwrap(); + h.step(&json!({"click":{"handle":"render:glass:starter.glass.amber-tint"}})).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert!(binding.glass_enabled && !binding.coat_enabled && !binding.maps_enabled); + assert_eq!(binding.glass.recipe, Some("starter.glass.amber-tint")); + assert_eq!(binding.target.name, "Optics"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "CPU must not silently ignore active GPU material assignments"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn clicked_gpu_material_at_assignment_limit_edits_existing_but_cannot_add_another_body() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1,"body_name":"Optics"})).unwrap(); + h.app.run("solid.pattern.rectangular", json!({"bodies":["Optics"],"dir1":[1,0,0],"count1":129,"spacing1":3})).unwrap(); + let targets: Vec = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"].clone()).unwrap(); + assert_eq!(targets.len(), 129); + h.app.session.mark_saved(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.materials.bindings = targets.iter().skip(1).cloned().map(|target| materials::Binding::new(target, &h.app)).collect(); + h.frames(3); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[1].ordinal)}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let include = h.app.tr("render.material_binding_enable").to_string(); + h.step(&json!({"widget":include})).unwrap(); + assert!(!h.app.render_workspace.view.materials.bindings[0].enabled, "the existing assignment remains editable at the limit"); + assert!(h.app.render_workspace.view.materials.bindings.iter().skip(1).all(|binding| binding.enabled)); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + + // The first scene body has no assignment: selecting it cannot create a 129th entry. + h.step(&json!({"widget":refresh})).unwrap(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[0].ordinal)}})).unwrap(); + h.step(&json!({"widget":add})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + assert!(h.app.render_workspace.view.materials.bindings.iter().all(|binding| binding.target != targets[0])); + 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 cpu_reflection_controls_preserve_exact_targets_and_engine_bounds() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let reflections = h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap(); + assert_eq!(reflections.bodies.len(), 1); + reflections.max_bounces = 8; + reflections.samples = 64; + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"rough_specular"}])); + assert_eq!(params["raytrace"]["reflections"]["max_bounces"], 8); + assert_eq!(params["raytrace"]["reflections"]["samples"], 64); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 9; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 8; + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 65; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 64; + h.app.session.visibility.hidden_bodies.push("Reflector".into()); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + assert!(h.app.render_workspace.view.raytrace.reflections.is_none()); + assert!(cpu::set_reflection(&mut h.app, "Missing", Some(ReflectionMode::Mirror)).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn cpu_reflection_binding_requires_confirmation_and_never_follows_a_reused_name() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("solid.box", json!({"length":5,"width":5,"height":5,"body_name":"Other"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")) + ); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err(), "confirmation cannot move a binding to a different feature"); + let before = json!(h.app.render_workspace.view.raytrace.reflections); + for mode in [ReflectionMode::Mirror, ReflectionMode::RoughSpecular] { + assert!(cpu::set_reflection(&mut h.app, "Reflector", Some(mode)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before, "a stale row's mode cannot rebind its body"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + } + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + // Isolate document identity: the cloned document has the same bodies, IDs and revision. + let previous_doc = h.app.session.doc.clone(); + let previous_revision = h.app.session.revision; + h.app.session = Session::new((*previous_doc).clone()); + h.app.session.revision = previous_revision; + assert!(!Arc::ptr_eq(&previous_doc, &h.app.session.doc)); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); +} + +#[test] +fn cpu_interactive_reflection_binding_accepts_appearance_and_render_intent_without_qualifying_final() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let world = h.app.session.world_state(); + let mesh = world.body("Reflector").unwrap().cached_mesh().unwrap(); + let document = h.app.session.doc.clone(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Reflector"],"color":"#123456"})).unwrap(); + assert!(!Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(Arc::ptr_eq(&mesh, &h.app.session.world_state().body("Reflector").unwrap().cached_mesh().unwrap())); + h.app.run("render.settings.set", json!({"name":"Interactive target proof","set":{"width":800,"height":600}})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-interactive-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.25; + h.app.render_workspace.view.cpu.intensity = 2.0; + let before = json!(h.app.render_workspace.view.raytrace.reflections); + let mut interactive = json!({}); + cpu::params_interactive(&h.app, &mut interactive).unwrap(); + assert_eq!(interactive["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"mirror"}])); + assert_eq!(interactive["raytrace"]["exposure_ev"], 1.5); + assert_eq!(interactive["environment"]["rotation_radians"], 0.25); + assert_eq!(interactive["environment"]["expected_sha256"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before); + assert!( + cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")), + "Interactive refresh cannot qualify final Check/Start" + ); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).is_err(), + "mode changes still require explicit confirmation" + ); +} + +#[test] +fn cpu_interactive_binding_keeps_cold_meshes_cold_and_refuses_another_world_until_confirmation() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + let retained = Arc::strong_count(&world); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none(), "request lowering must not tessellate"); + assert_eq!(Arc::strong_count(&world), retained, "the binding must not retain the evaluated world"); + h.app.session.execute("appearance.assign", &json!({"bodies":["Reflector"],"color":"#654321"})).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + h.app.session.execute("solid.box", &json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_interactive_binding_refuses_reused_names_and_same_revision_in_a_new_document() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let uid = h.app.session.uid; + h.app.session = Session::new((*document).clone()); + h.app.session.revision = revision; + assert_ne!(h.app.session.uid, uid); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); +} + +#[test] +fn cpu_interactive_binding_refuses_moved_occurrences_and_hidden_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.run("component.create", json!({"name":"Part","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let name = world.bodies[0].name.clone(); + let mesh = world.bodies[0].mesh(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let moved = h.app.session.world_state(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(!Arc::ptr_eq(&mesh, &moved.bodies[0].mesh())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "same creator and name cannot certify a moved instance"); + cpu::revalidate(&mut h.app, &name).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + h.app.session.visibility.hidden_bodies.push(name); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); +} + +#[test] +fn cpu_interactive_binding_refuses_deleted_then_recreated_equal_looking_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let feature = world.body("Reflector").unwrap().feature; + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("timeline.delete", json!({"feature":feature.to_string()})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + assert!(h.app.session.world_state().body("Reflector").is_some(), "the recreated case must actually reuse the selected name"); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "identical names/dimensions cannot certify recreated geometry"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_environment_controls_keep_wire_schemas_separate_without_reading_files() { + let mut h = Harness::new(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + let mut hdr = json!({}); + cpu::params(&h.app, &mut hdr).unwrap(); + assert_eq!( + hdr["environment"], + json!({"path":"not-opened-by-ui.hdr","expected_sha256":h.app.render_workspace.view.cpu.hdr.resource().unwrap(),"rotation_radians":std::f64::consts::FRAC_PI_2,"intensity":2.0,"samples":64}) + ); + assert!(hdr["raytrace"].get("environment").is_none()); + for gpu_key in ["progressive", "tone_map", "denoise", "lighting", "lens"] { + assert!(hdr.get(gpu_key).is_none()); + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.2, 0.4, 0.8]; + let mut constant = json!({}); + cpu::params(&h.app, &mut constant).unwrap(); + assert!(constant.get("environment").is_none()); + assert_eq!(constant["raytrace"]["environment"], json!({"color":[0.2,0.4,0.8],"intensity":2.0})); + assert!(h.app.render_workspace.view.raytrace.environment.is_none(), "request building must not mutate the editable base"); + h.app.render_workspace.view.cpu.color[0] = f64::NAN; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.samples = 3; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.samples = 16; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("bad\npath.hdr"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + let mut none = json!({}); + cpu::params(&h.app, &mut none).unwrap(); + assert!(none.get("environment").is_none()); + assert!(none["raytrace"].get("environment").is_none()); +} + +#[test] +fn cpu_light_controls_preserve_hidden_spot_fields_and_validate_runtime_bounds() { + use solidcraft_engine::render::job::{DirectionalLightOptions, PunctualLightOptions, SpotConeOptions}; + let mut h = Harness::new(); + h.app.render_workspace.view.raytrace.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + h.app.render_workspace.view.raytrace.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 100.0], + color: [1.0, 0.5, 0.25], + intensity: 4.0, + reference_distance_mm: 100.0, + minimum_distance_mm: 0.01, + cone: None, + }]); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["lights"][0]["intensity"], 2.0); + assert_eq!(params["raytrace"]["punctual_lights"][0]["reference_distance_mm"], 100.0); + assert!(params.get("lighting").is_none(), "CPU must not emit GPU studio lighting"); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0; 3]; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0, 0.0, 1.0]; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 101.0; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 0.01; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].cone = + Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.1, outer_half_angle_radians: 0.2 }); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!( + params["raytrace"]["punctual_lights"][0]["cone"], + json!(h.app.render_workspace.view.raytrace.punctual_lights.as_ref().unwrap()[0].cone) + ); +} + +#[test] +fn delayed_cpu_hdr_picker_cannot_write_into_another_document_or_revision() { + use crate::picker_test_support::{Slot, open}; + for other_document in [false, true] { + let mut h = Harness::new(); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "original.hdr".into() }; + hdr::pick(&mut h.app, hdr::Target::Cpu); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy()); + if other_document { + h.app.session = Session::default(); + } else { + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5})).unwrap(); + } + *slot.borrow_mut() = Some(Some("late.hdr".into())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.cpu.hdr, hdr::Input::FilePending { path: "original.hdr".into() }); + } +} + +#[test] +fn clicked_setup_save_reload_and_switch_keep_gpu_numeric_intent_without_a_host() { + use solidcraft_engine::doc::render_settings::{GpuJob, RenderJob, SkyEnvironment}; + use solidcraft_engine::render::job::{AreaLight, AreaLights, StudioLighting, Sun, ThinLens, ToneMap}; + use solidcraft_engine::render::lighting::environment::SkyGradient; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.frames(3); + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + h.app.cam.fov = 0.7; + h.app.ui.perspective = true; + // The positive UI fixture uses the admitted document boundary. Coordinates + // beyond it must still refuse before a setup that cannot reopen is created. + for x in [-2e9, 2e9, 1e9_f64.next_up()] { + assert!( + AreaLights::new(&[AreaLight { center: [x, 0.0, 100.0], u: [2.0, 0.0, 0.0], v: [0.0, -3.0, 0.0], radiance: [3.0, 5.0, 7.0] }]).is_err() + ); + } + let expected = RenderSetup { + camera: h.app.cam, + exposure_ev: 1.25, + width: 48, + height: 32, + job: Some(RenderJob::GpuPath { + transparent_background: true, + options: Box::new(GpuJob { + aging: Default::default(), + nested_media: true, + volume: Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..Default::default() }), + adaptive: Some(solidcraft_engine::render::job::adaptive::AdaptiveSampling { + pilot_samples: 16, + min_samples: 16, + relative_error: 0.1, + absolute_error: 0.003, + coverage_error: 0.02, + }), + transmission_samples: 4, + finishing: Default::default(), + backdrop: None, + linear_exr: false, + samples: 37, + max_depth: 11, + seed: 1977, + tone_map: ToneMap::AcesFitted, + denoise: true, + lens: Some(ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 123.0 }), + lighting: Some(StudioLighting { + environment: [0.25, 0.5, 0.75], + sun: Some(Sun { direction: [2.0, 3.0, 4.0], angular_radius_rad: 0.0123456789, radiance: [11.0, 22.0, 33.0] }), + area_lights: AreaLights::new(&[AreaLight { + center: [1e9, 0.0, 100.0], + u: [2.0, 0.0, 0.0], + v: [0.0, -3.0, 0.0], + radiance: [3.0, 5.0, 7.0], + }]) + .unwrap(), + }), + environment: Some(SkyEnvironment::Sky { + gradient: SkyGradient { zenith: [0.3, 0.4, 0.5], horizon: [0.6, 0.7, 0.8], ground: [0.1, 0.2, 0.3] }, + rotation_rad: std::f64::consts::PI, + intensity: 1.75, + }), + hdr: None, + }), + }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"GPU saved","set":expected})).unwrap(); + h.app.render_workspace.view.name = "GPU saved".into(); + setups::load(&mut h.app); + let completed = h.app.render_workspace.view.completed; + let result_camera = h.app.render_workspace.view.result_camera; + h.frames(3); + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(image_params(&h.app).is_err(), "offline editing must not claim an executable GPU"); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.step(&json!({"click":{"handle":"render:setup-name"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"GPU copy"})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "GPU copy"); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "typing Save As must not reset the settings"); + assert!(h.app.render_workspace.view.dirty); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["GPU copy"], expected); + h.app.render_workspace.view.seed = 8; + h.app.render_workspace.view.studio.ambient[1] = 0.125; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.render_workspace.view.name = "Raster saved".into(); + setups::save(&mut h.app).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:setups"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:setup:GPU copy"}})).unwrap(); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.completed, completed); + assert_eq!(h.app.render_workspace.view.result_camera, result_camera); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the boundary setup must reopen from JSON"); + let native = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + let reopened = solidcraft_engine::io::read_design(&native).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the native container keeps exact numeric intent"); +} + +#[test] +fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":4,"shadows":false, + "lights":[{"direction":[2.0,-4.0,8.0],"color":[0.2,0.4,0.6],"intensity":3.0}], + "punctual_lights":[{"position_mm":[10.0,20.0,30.0],"color":[1.0,0.5,0.25],"intensity":4.0, + "reference_distance_mm":100.0,"minimum_distance_mm":0.01, + "cone":{"emitted_axis":[0.0,0.0,-2.0],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.3}}], + "area_lights":[{"center_mm":[0.0,0.0,100.0],"edge_u_mm":[20.0,0.0,0.0],"edge_v_mm":[0.0,-30.0,0.0],"color":[0.3,0.5,0.7],"intensity":5.0}], + "area_samples":16,"seed":9123,"environment":{"color":[0.0,0.0,0.0],"intensity":2.0} + })) + .unwrap(); + let mut expected = RenderSetup { camera: h.app.cam, exposure_ev: 1.5, job: Some(RenderJob::CpuRaytrace { options }), ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + h.app.render_workspace.view.name = "CPU numeric".into(); + setups::load(&mut h.app); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"directional:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0, "the UI has one exposure authority"); + h.app.render_workspace.view.draft.background = [2, 4, 8]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + expected.background = [2, 4, 8]; + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(json!(expected)["job"]["options"].get("exposure_ev").is_none()); + for value in [json!({}), json!({"lights":[],"punctual_lights":[],"area_lights":[],"environment":{"color":[0.0,0.0,0.0],"intensity":0.0}})] { + let options: CpuJob = serde_json::from_value(value).unwrap(); + expected.job = Some(RenderJob::CpuRaytrace { options }); + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + } +} + +#[test] +fn cpu_progressive_controls_resize_only_on_request_and_save_reload_without_a_host() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.raytrace.primary_samples = 16; + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 1024; + h.frames(3); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-progressive"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 1); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions::default())); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: u32::MAX }); + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.name = "Progressive CPU".into(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(image_request(&h.app).is_err()); + assert!(setups::save(&mut h.app).is_err()); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let resize = format!("{} 512 × 512", h.app.tr("render.image_use_largest")); + assert!(h.widget(&resize).is_some(), "the proposed dimensions must be visible before accepting them"); + h.step(&json!({"widget":resize})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (512, 512)); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert!(image_request(&h.app).unwrap().get("progressive").is_none(), "CPU sampling must not select the GPU executor"); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Progressive CPU"], expected); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-fixed"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + h.app.render_workspace.view.name = "Progressive CPU copy".into(); + setups::save(&mut h.app).unwrap(); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 1.25); +} + +#[test] +fn cpu_progressive_setup_preserves_hidden_values_empty_lists_and_one_exposure() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.app.session.set_render_job_host(None).unwrap(); + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":1,"progressive":{"samples_per_pixel":7,"seed":321},"preset":null, + "lights":[],"punctual_lights":null,"area_lights":[],"area_samples":16,"seed":9123, + "shadows":false,"environment":{"color":[0.0,0.0,0.0],"intensity":0.0} + })) + .unwrap(); + let expected = RenderSetup { + camera: h.app.cam, + width: 32, + height: 16, + exposure_ev: -1.5, + job: Some(RenderJob::CpuRaytrace { options }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"Progressive hidden","set":expected})).unwrap(); + h.app.render_workspace.view.name = "Progressive hidden".into(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["method"], "gpu_path"); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().seed = 654; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + let undo = h.app.session.undo.len(); + setups::save(&mut h.app).unwrap(); + assert_eq!(h.app.session.undo.len(), undo, "a no-op Save must preserve all nonedited intent"); +} + +#[test] +fn setup_save_refuses_nonportable_state_atomically_and_tracks_invalid_legacy_edits() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Target"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + setups::load(&mut h.app); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + setups::save(&mut h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "must-not-be-read.hdr".into() }; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.hdr_inspect_required"))); + h.app.render_workspace.view.studio.environment = studio::Environment::None; + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.render_workspace.view.materials.enabled = false; + assert!(setups::save(&mut h.app).is_err(), "disabled assignments must not be silently lost either"); + h.app.render_workspace.view.materials.bindings.clear(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.run("render.settings.set", json!({"name":"Legacy","set":{"job":null,"environment_rotation":0.25,"environment_intensity":2.0}})).unwrap(); + h.app.render_workspace.view.name = "Legacy".into(); + setups::load(&mut h.app); + assert!(!h.app.render_workspace.view.dirty); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.draft.background = [1, 3, 5]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty, "invalid saved intent still needs complete dirty tracking"); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.setup_legacy_environment"))); + assert_eq!(h.app.render_workspace.view.draft.environment_rotation, 0.25); + assert_eq!(h.app.render_workspace.view.draft.environment_intensity, 2.0); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +fn original_hdr_bytes(value: u8, declared_primaries: bool) -> Vec { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n".to_vec(); + if declared_primaries { + bytes.extend_from_slice(b"PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n"); + } + bytes.extend_from_slice(b"\n-Y 1 +X 2\n"); + bytes.extend_from_slice(&[value, 128, 128, 129, 128, value, 128, 129]); + bytes +} + +/// A verified selector for pure request tests. No file exists or is read by the builder. +fn captured_hdr_input(path: &str) -> hdr::Input { + let bytes = original_hdr_bytes(128, true); + hdr::Input::FileCaptured { + path: path.into(), + metadata: hdr::Metadata { + sha256: solidcraft_engine::doc::render_resources::HdrId::of(&bytes), + width: 2, + height: 1, + encoded_bytes: bytes.len() as u64, + primaries: Some(solidcraft_engine::doc::render_resources::SRGB_D65_PRIMARIES), + }, + } +} + +#[test] +fn hdr_ui_save_embeds_once_without_a_host_and_reload_never_reopens_the_source_path() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"HDR target","length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + let path = h.dir.join("original-embedded.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + let resource = solidcraft_engine::doc::render_resources::HdrId::of(&bytes); + let save = h.app.tr("render.save_setup").to_string(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.render_workspace.view.name = "HDR GPU".into(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.rotation_rad = 1234.567890123; + h.app.render_workspace.view.studio.intensity = 1.75; + h.app.render_workspace.view.samples = 37; + let before = (h.app.session.revision, h.app.session.undo.len()); + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert!(h.app.session.doc.render.resources.is_empty()); + let unsaved = image_request(&h.app).unwrap(); + assert_eq!(unsaved["environment"]["expected_sha256"], json!(resource)); + h.frames(3); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), before.1 + 1); + assert_eq!(h.app.render_workspace.view.studio.hdr, hdr::Input::EmbeddedResource { resource }); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + let gpu = h.app.session.doc.render.setups.get("HDR GPU").unwrap().clone(); + assert!(matches!(&gpu.job, Some(RenderJob::GpuPath { options, .. }) if options.hdr.unwrap().resource == resource && options.samples == 37)); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":gpu})); + assert!(!h.app.render_workspace.view.dirty); + + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "HDR CPU".into(); + h.app.render_workspace.view.raytrace.progressive = Some(solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: 7, seed: 84 }); + h.app.render_workspace.view.draft.exposure_ev = 1.75; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.rotation_rad = -1234.567890123; + h.app.render_workspace.view.cpu.intensity = 2.5; + h.app.render_workspace.view.cpu.samples = 64; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + h.frames(2); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1, "both setups share one source payload"); + assert_eq!(h.app.session.doc.render.resources.total_bytes(), bytes.len()); + let cpu = h.app.session.doc.render.setups.get("HDR CPU").unwrap().clone(); + assert!(matches!(&cpu.job, Some(RenderJob::CpuRaytrace { options }) + if options.hdr.unwrap().samples == 64 && options.progressive.unwrap().samples_per_pixel == 7 && options.progressive.unwrap().seed == 84)); + let encoded = h.app.session.doc.to_json(); + assert!(!encoded.contains("original-embedded.hdr"), "the document never stores the source path"); + std::fs::remove_file(&path).unwrap(); + + for (name, expected, target) in [("HDR GPU", gpu, hdr::Target::Gpu), ("HDR CPU", cpu, hdr::Target::Cpu)] { + let loaded = solidcraft_engine::doc::Document::from_json(&encoded).unwrap(); + h.app.session = Session::new(loaded); + h.app.render_workspace.view.name = name.into(); + setups::load(&mut h.app); + let camera = expected.camera; + h.app.cam = camera; + assert_eq!(hdr::input(&h.app, target), &hdr::Input::EmbeddedResource { resource }); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + let before = (h.app.session.revision, h.app.session.undo.len()); + let section = if target == hdr::Target::Cpu { "render.cpu_environment" } else { "render.studio_environment" }; + h.frames(2); + if target == hdr::Target::Gpu { + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr("render.image_advanced"))}})).unwrap(); + } + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr(section))}})).unwrap(); + h.frames(2); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "displaying degrees must preserve saved radians"); + setups::save(&mut h.app).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn changed_hdr_bytes_reject_save_atomically_and_check_start_keep_the_expected_digest() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Pinned HDR".into(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + let path = h.dir.join("changing.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let input = h.app.render_workspace.view.cpu.hdr.clone(); + let request = image_request(&h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let draft = h.app.render_workspace.view.draft.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), before); + assert_eq!(h.app.render_workspace.view.cpu.hdr, input); + assert_eq!(h.app.render_workspace.view.draft, draft); + assert_eq!(image_request(&h.app).unwrap(), request, "both buttons keep the verified digest, never silently accept new bytes"); + assert!(h.app.session.doc.render.resources.is_empty()); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert_ne!(h.app.render_workspace.view.cpu.hdr.resource(), input.resource()); + setups::save(&mut h.app).unwrap(); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + assert_eq!(h.app.session.doc.render.resources.len(), 1); +} + +#[test] +fn hdr_picker_cancel_and_late_setup_method_or_input_answers_preserve_the_selection() { + use crate::picker_test_support::{Slot, open}; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + for change in ["cancel", "setup", "method", "input"] { + let mut h = Harness::new(); + h.app.render_workspace.view.method = if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("original.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("original.hdr"); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + hdr::pick(&mut h.app, target); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + match change { + "setup" => h.app.render_workspace.view.name = "another setup".into(), + "method" => h.app.render_workspace.view.method = ImageMethod::Raster, + "input" => { + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("newer.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("newer.hdr"); + } + _ => {} + } + let before = hdr::input(&h.app, target).clone(); + let doc = h.app.session.doc.clone(); + let status = h.app.status.clone(); + *slot.borrow_mut() = Some(if change == "cancel" { None } else { Some("never-read-late.hdr".into()) }); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(hdr::input(&h.app, target), &before, "{target:?}: {change}"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status, status, "the stale path must be discarded before trying to inspect it"); + } + } +} + +#[test] +fn embedded_hdr_runtime_requests_preserve_temporary_bindings_without_serializing_them() { + use solidcraft_engine::render::job::ReflectionMode; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"Target","length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + let path = h.dir.join("bindings.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, target, path.to_string_lossy().into_owned()).unwrap(); + setups::save(&mut h.app).unwrap(); + let resource = hdr::input(&h.app, target).resource().unwrap(); + std::fs::remove_file(&path).unwrap(); + if target == hdr::Target::Cpu { + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + } else { + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + // Even disabled, this assignment must not be lost on Save. It still + // selects the runtime path and exercises the embedded HDR selector. + h.app.render_workspace.view.materials.enabled = false; + } + let params = image_request(&h.app).unwrap(); + assert_eq!(params["environment"]["resource"], json!(resource)); + assert!(params["environment"].get("path").is_none()); + assert!(params["environment"].get("expected_sha256").is_none()); + if target == hdr::Target::Cpu { + assert!(params["environment"].get("kind").is_none()); + assert_eq!(params["raytrace"]["reflections"]["bodies"][0]["body"], "Target"); + } else { + assert_eq!(params["environment"]["kind"], "embedded_hdr"); + } + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_request(&h.app).unwrap(), params); + } +} + +#[test] +fn cpu_resource_profile_edits_preserve_resolution_samples_and_saved_intent() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Studio output".into(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.raytrace.budget = CpuBudget::Studio; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 82 }); + h.frames(3); + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + + h.step(&json!({"click":{"handle":"render.cpu_budget_compact"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (3840, 2160)); + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 128); + assert!(setups::snapshot(&h.app).is_err()); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); +} + +#[test] +fn large_image_display_uses_captured_profile_and_keeps_export_pixels_unchanged() { + use solidcraft_engine::render::job::{CpuBudget, ImageRequest, RaytraceOptions}; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { budget: CpuBudget::Studio, ..Default::default() }), + camera: Camera::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + environment: None, + textures: None, + }; + let limits = captured_image_limits(&request); + assert_eq!(limits, CpuBudget::Studio.image_limits(false)); + assert_eq!(display_dimensions(7680, 4320, 4096).unwrap(), (4096, 2304)); + assert_eq!(display_dimensions(1920, 1080, 4096).unwrap(), (1920, 1080)); + assert!(display_dimensions(u32::MAX, 1, 0).is_err()); + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(8200, 2, image::Rgba([42, 88, 123, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let encoded = png.into_inner(); + let before = encoded.clone(); + assert!(decode_image(&encoded, 8200, 2).is_err(), "legacy default remains compact"); + let display = decode_render_image(&encoded, 8200, 2, CpuBudget::Workstation.image_limits(false), 1024).unwrap(); + assert!(display.size[0] <= 1024 && display.size[1] >= 1); + assert_eq!(encoded, before, "the retained image is not rewritten for its display cache"); + assert!(decode_render_image(&encoded, 8199, 2, CpuBudget::Workstation.image_limits(false), 1024).is_err()); +} + +#[test] +fn setup_actions_and_return_design_stay_visible_with_long_render_controls() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.frames(3); + for key in ["render.save_setup", "render.reload_settings", "render.return_design"] { + let label = h.app.tr(key).to_string(); + assert!(h.widget(&label).is_some(), "sticky action {key}"); + } + h.step(&json!({"widget":h.app.tr("render.return_design")})).unwrap(); + assert!(!active(&h.app)); +} + +#[test] +fn dirty_indication_preserves_reload_and_resource_picker_hit_targets() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + h.frames(3); + let reload = h.app.tr("render.reload_settings").to_string(); + let clean_reload = h.widget(&reload).unwrap(); + let clean_picker = crate::scenario::rect_of("render:cpu-budget").unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.frames(3); + assert_eq!(h.widget(&reload).unwrap(), clean_reload, "dirty text must not move Reload"); + assert_eq!(crate::scenario::rect_of("render:cpu-budget").unwrap(), clean_picker, "dirty text must not move the CPU resource picker"); + h.step(&json!({"widget":reload})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert!(!h.app.render_workspace.view.dirty); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 0.0); +} + +#[test] +fn product_preview_exact_payload_preserves_mixed_surfaces_and_refuses_overflow() { + let mut session = Session::default(); + for (name, x) in [("Paint", 0), ("Legacy", 20), ("Glass", 40)] { + session.execute("solid.box", &json!({"base":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + session + .execute("appearance.assign", &json!({"bodies":["Paint"],"color":"#c07030","pbr":{"metallic":0,"roughness":0.4,"dielectric_ior":1.5}})) + .unwrap(); + session.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let original = session.doc.to_json(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + let (_, gpu) = gpu_scene(&scene).unwrap(); + assert_eq!((plan.pbr, plan.tris, plan.glass), (gpu.pbr.len(), gpu.tris.len(), gpu.glass.len())); + assert!(plan.pbr > 0 && plan.tris > 0 && plan.glass > 0); + assert_eq!(plan.source_triangles, scene.meshes.iter().map(|b| b.mesh.triangles.len()).sum::()); + assert!(preview_upload_plan(&scene, plan.bytes().unwrap() - 1).is_err()); + assert!(PreviewUploadPlan::default().add(true, false, usize::MAX, MAX_GEOMETRY_BYTES).is_err()); + assert_eq!(session.doc.to_json(), original); + let mut invalid = scene.clone(); + let source = invalid.meshes[0].mesh.clone(); + Arc::make_mut(&mut invalid.meshes[0].mesh).triangles[0][0] = u32::MAX; + assert!(gpu_scene(&invalid).is_err()); + assert!(gpu_scene(&scene).is_ok()); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &source)); +} + +#[cfg(all(not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn full_detail_preview_source_can_exceed_legacy_128_mib_without_mesh_reduction() { + use solidcraft_engine::geom::{Mesh, Vec3}; + use solidcraft_engine::render::{ProductMesh, surface::OpaqueSurface}; + // One immutable original triangle repeated in the index list; this tests + // payload admission only. Actual SELENE upload is separate native evidence. + let count = (128 * 1024 * 1024) / (3 * crate::gpu::PBR_SIZE) + 1; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]; count], + ..Default::default() + }); + let body = ProductMesh { + name: "Original admission fixture".into(), + mesh: mesh.clone(), + color: [200, 100, 50], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.4, 0.2, 0.1), 0.0, 0.4, 1.5).unwrap()), + transmission: None, + faces: Vec::new(), + }; + let scene = ProductScene { meshes: vec![body], bounds: mesh.bounds() }; + assert!(preview_upload_plan(&scene, 128 * 1024 * 1024).is_err()); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + assert_eq!(plan.source_triangles, count); + assert_eq!(plan.bytes().unwrap(), count * 3 * crate::gpu::PBR_SIZE); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &mesh)); + let mut maximum = PreviewUploadPlan::default(); + assert!(maximum.add(true, false, MAX_GEOMETRY_BYTES / (3 * crate::gpu::PBR_SIZE) + 1, MAX_GEOMETRY_BYTES).is_err()); +} + +#[test] +fn refused_product_capture_is_cached_until_identity_changes_or_explicit_retry() { + let mut h = Harness::new(); + let calls = std::cell::Cell::new(0); + let signature = (7, 123, 99, MAX_GEOMETRY_BYTES as u64); + for _ in 0..8 { + assert_eq!( + h.app + .render_workspace + .prepare_preview(signature, || { + calls.set(calls.get() + 1); + Err("original bounded refusal".into()) + }) + .unwrap_err(), + "original bounded refusal" + ); + } + assert_eq!(calls.get(), 1, "same refused source is not rebuilt every frame"); + assert!(h.app.render_workspace.scene.is_none() && h.app.render_workspace.key.is_none()); + assert!(h.app.render_workspace.slot.lock().unwrap().is_none()); + assert!( + h.app + .render_workspace + .prepare_preview((8, 123, 99, MAX_GEOMETRY_BYTES as u64), || { + calls.set(calls.get() + 1); + Err("new revision".into()) + }) + .is_err() + ); + assert_eq!(calls.get(), 2); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.scene_signature.is_none() && h.app.render_workspace.scene_error.is_none()); + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + h.app.render_workspace.prepare_preview(signature, || solidcraft_engine::product_scene::extract(&session).map_err(|e| e.to_string())).unwrap(); + assert!(h.app.render_workspace.scene_error.is_none()); + assert!(h.app.render_workspace.preview_upload_bytes.unwrap() > 0); + assert!(h.app.render_workspace.key.is_some() && h.app.render_workspace.scene.is_some()); +} + +#[test] +fn product_preview_error_uses_shared_wrapped_surface_and_explicit_retry_target() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":800})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rect = egui::Rect::from_min_size(egui::pos2(260.0, 200.0), egui::vec2(550.0, 360.0)); + let message = "The original captured product geometry exceeds its bounded preview admission. The renderer must preserve all exact body identities and cannot silently simplify or drop geometry to paint this view."; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0))), ..Default::default() }, + |ui| preview_error(&mut h.app, ui, rect, message), + ); + output.textures_delta.clear(); + let note = crate::scenario::rect_of("dialog:report:render.preview_failure").unwrap(); + let retry = crate::scenario::rect_of("render:preview-retry").unwrap(); + assert!(rect.contains_rect(note) && rect.contains_rect(retry)); + assert!(note.height() > Tokens::get().font_body, "the detailed failure wraps instead of escaping the viewport"); + assert!(crate::theme::contrast_ratio(Tokens::get().form_error, Tokens::get().form_error_fill) >= 3.0); +} + +#[test] +fn finishing_backdrop_and_raw_retention_save_reload_without_a_gpu_or_hidden_transport_edits() { + use solidcraft_engine::render::job::finishing::{Backdrop, BackdropMode, Finishing}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.render_workspace.view.name = "Linear studio".into(); + h.app.render_workspace.view.studio.finishing = + Finishing { rgb_gain: [1.3, 0.8, 0.9], saturation: 0.4, contrast: 1.2, vignette: 0.3, ..Default::default() }; + h.app.render_workspace.view.studio.backdrop_enabled = true; + h.app.render_workspace.view.studio.backdrop = Backdrop { mode: BackdropMode::Radial, center: [0.25, 0.7], ..Default::default() }; + h.app.render_workspace.view.studio.linear_exr = true; + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.studio = studio::View::default(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(!studio::linear_export_available(&h.app)); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["linear_exr"], true); + assert_eq!(request["settings"]["job"]["options"]["finishing"]["rgb_gain"], json!([1.3, 0.8, 0.9])); + assert!(image_params(&h.app).is_err(), "offline editing is not a claim of executable GPU capabilities"); + h.app.render_workspace.view.transparent = true; + assert!(setups::snapshot(&h.app).is_err(), "gradient cannot silently disappear behind alpha mode"); + h.app.render_workspace.view.transparent = false; + let before = h.app.session.doc.to_json(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:post-reset"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.studio.finishing, Finishing::default()); + assert!(h.app.render_workspace.view.studio.linear_exr); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + assert!(h.app.render_workspace.view.dirty); + assert_ne!(h.app.session.doc.to_json(), before, "Effects saves its job patch through the shared editor"); + let reset = setups::snapshot(&h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), reset); +} + +#[test] +fn missing_linear_master_is_never_reconstructed_from_a_finished_png() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + let id = completed_preview(&mut h, [21, 37, 55]); + let bytes = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.completed = Some(id); + h.app.render_workspace.view.studio.export_exr = true; + assert!(!studio::linear_export_available(&h.app)); + let temp = std::env::temp_dir().join(format!("solidcraft-missing-linear-{}.exr", std::process::id())); + assert!(h.app.session.execute("render.export", &json!({"job":id,"path":temp,"format":"exr"})).is_err()); + assert!(!temp.exists()); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), bytes); +} + +#[test] +fn render_workspace_stage_commands_keep_registered_actions_without_a_ribbon() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + assert!(crate::workspace::visible_tabs(&h.app).is_empty()); + for command in solidcraft_engine::command_specs() + .into_iter() + .filter(|c| c.id.starts_with("render.") || c.tab.starts_with("RENDER") || c.id == "view.shots_strip") + { + assert!(solidcraft_engine::find_command(command.id).is_some()); + assert!(crate::workspace::destination(command).is_none(), "{} has a ribbon destination", command.id); + } + for tab in ["RENDER", "RENDER APPEARANCE", "RENDER SCENE", "RENDER CAMERA"] { + assert!(crate::workspace::panels(tab).is_empty()); + } + h.frames(3); + assert!(crate::scenario::rect_of("ribbon:card").is_none()); + assert!(crate::scenario::rect_of("tab:RENDER").is_none()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); +} + +#[test] +fn render_workspace_stage_chips_dispatch_without_mutations_and_remember_each_document() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for stage in Stage::ALL { + h.frames(3); + h.step(&json!({"click":{"handle":format!("render:stage:{}",stage.key())}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.stage, stage); + assert_eq!(h.app.render_workspace.view.inspector.page, stage.page()); + assert_eq!(crate::scenario::rect_of("render:pick").is_some(), stage == Stage::Look); + assert_eq!(crate::scenario::rect_of("render:preview_note").is_some(), stage == Stage::Look); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + // Registered editor navigation remains available independently of the stage. + for command in ["render.status", "render.backends"] { + h.app.start(command); + h.frames(2); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Diagnostics); + } + } + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Frame); + crate::documents::switch(&mut h.app, 1); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); +} + +#[test] +fn render_workspace_stage_shell_degrades_without_overlap_at_small_window_sizes() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.ui.layout = mode; + for (width, height) in [ + (1440, 900), + (1400, 900), + (1100, 700), + (900, 700), + (800, 600), + (700, 600), + (640, 480), + (320, 240), + (240, 160), + (120, 80), + (32, 32), + (1, 1), + ] { + h.call("ui.resize", json!({"width":width,"height":height})); + for stage in Stage::ALL { + h.app.run("view.render_stage", json!({"stage":stage.key()})).unwrap(); + h.frames(3); + let bar = crate::scenario::rect_of("render:stage_bar").unwrap(); + let workspace = crate::scenario::rect_of("ribbon:workspace").unwrap(); + assert!(bar.is_finite() && workspace.is_finite()); + assert_eq!(bar.top(), workspace.top()); + assert_eq!(bar.height(), workspace.height()); + assert!(!bar.intersect(workspace).is_positive()); + if width >= 1100 { + assert_eq!(bar.height(), 88.0); + assert_eq!(workspace.width(), 104.0); + assert_eq!(bar.left() - workspace.right(), 8.0); + let header = crate::scenario::rect_of("render:stage_header").unwrap(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert_eq!(header.height(), 36.0); + assert_eq!(tools.height(), 52.0); + assert_eq!(header.bottom(), tools.top()); + assert_eq!(header.top(), bar.top()); + assert_eq!(tools.bottom(), bar.bottom()); + } + let docks: Vec<_> = + ["render:browser", "render:inspector"].iter().filter_map(|id| h.app.shell.workspace_panels.get(id).map(|(r, _)| *r)).collect(); + if let [browser, inspector] = docks.as_slice() { + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!(browser.bottom() < inspector.bottom()); + assert!(!browser.intersect(*inspector).is_positive()); + if width >= 800 { + let compact = crate::render_ui::compact(&h.app, width as f32); + assert_eq!(browser.width(), if compact { crate::frame::DIALOG_MIN_W } else { 266.0 }); + assert_eq!(inspector.width(), if compact { crate::frame::DIALOG_MIN_W } else { 305.0 }); + assert_eq!(browser.top() - bar.bottom(), 8.0); + let (strip, _) = h.app.shell.workspace_panels.get("render:shots_strip").unwrap(); + let library = h.app.shell.workspace_panels["render:appearances"].0; + assert_eq!(strip.top() - library.bottom(), 8.0); + assert_eq!(library.top() - browser.bottom(), 8.0); + assert_eq!(strip.height(), 48.0); + } + } + if (640..800).contains(&width) { + assert!(crate::scenario::rect_of("render:browser:show").is_some()); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + if width >= 700 { + for dock in &docks { + assert!(!dock.x_range().contains(h.app.viewport.rect.unwrap().center().x), "{width}: {dock:?}"); + } + } + let mut docks = docks; + if let Some((panel, _)) = h.app.shell.workspace_panels.get("render:appearances") { + for dock in &docks { + assert!(!panel.intersect(*dock).is_positive()); + } + docks.push(*panel); + } + for dock in docks { + assert!(!dock.intersect(bar).is_positive(), "{width}×{height}: {dock:?} {bar:?}"); + if let Some((strip, _)) = h.app.shell.workspace_panels.get("render:shots_strip") { + assert!(!dock.intersect(*strip).is_positive(), "{width}×{height}: {dock:?} {strip:?}"); + } + } + } + } + } +} + +#[test] +fn render_workspace_focus_restores_docks_without_design_history_or_camera_changes() { + for (side, folded, shots) in [("left", false, true), ("right", true, false)] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 350.0; + h.app.preferences.render_inspector_width = 390.0; + h.app.preferences.render_shots_strip = shots; + h.app.preferences.browser_collapsed = folded; + h.app.shell.render_browser_open = folded; + h.frames(3); + let dock_preferences = h.app.prefs(); + let docks = h.app.shell.workspace_panels.clone(); + let camera = (h.app.cam, h.app.session.camera); + let document = h.app.session.doc.clone(); + let state = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let before = h.app.viewport.layout.as_ref().unwrap().content; + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + assert!(crate::render_ui::focused(&h.app)); + crate::shell::register_panel(&mut h.app, "render:stage_panel", Some(before), Some(crate::ui_kit::Edge::Left)); + assert!(!h.app.shell.workspace_panels.contains_key("render:stage_panel")); + for id in ["render:browser", "render:appearances", "render:inspector", "render:shots_strip", "render:shots:show"] { + assert!(!h.app.shell.workspace_panels.contains_key(id)); + assert!(crate::scenario::rect_of(id).is_none()); + } + for id in ["render:focus:exit", "render:stage_bar", "ribbon:workspace"] { + assert!(crate::scenario::rect_of(id).is_some(), "{id}"); + } + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(layout.content.width() > before.width()); + assert!(layout.axis_view.is_positive() && layout.navigation.is_positive()); + assert_eq!(h.app.prefs(), dock_preferences); + h.step(&json!({"click":{"handle":"render:focus:exit"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.render_focus); + assert_eq!(h.app.shell.workspace_panels.len(), docks.len()); + for (id, (rect, edge)) in docks { + let (restored_rect, restored_edge) = h.app.shell.workspace_panels.get(id).unwrap(); + assert_eq!(*restored_rect, rect); + assert_eq!(restored_edge.as_ref().map(std::mem::discriminant), edge.as_ref().map(std::mem::discriminant)); + } + assert_eq!(h.app.prefs(), dock_preferences); + assert_eq!(h.app.preferences.browser_collapsed, folded); + assert_eq!(h.app.shell.render_browser_open, folded); + assert_eq!((h.app.cam, h.app.session.camera), camera); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), state); + assert!(!Harness::new().app.shell.render_focus); + } +} + +#[test] +fn render_workspace_focus_tab_only_toggles_render_without_text_focus() { + let mut h = Harness::new(); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.ctx.memory_mut(|memory| { + if let Some(id) = memory.focused() { + memory.surrender_focus(id); + } + }); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(h.app.shell.render_focus); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + h.frames(3); + h.step(&json!({"click":{"handle":"render:library-search"}})).unwrap(); + assert!(h.ctx.egui_wants_keyboard_input()); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); +} + +#[test] +fn render_workspace_compact_browser_card_and_focus_preserve_remembered_widths() { + for side in ["left", "right"] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 320.0; + h.app.preferences.render_inspector_width = 360.0; + h.frames(3); + for width in [1100, 900, 700] { + h.call("ui.resize", json!({"width":width,"height":700})); + h.frames(3); + if width == 700 { + h.step(&json!({"click":{"handle":"render:browser:show"}})).unwrap(); + h.frames(3); + let (browser, reservation) = h.app.shell.workspace_panels["render:browser"]; + let (inspector, _) = h.app.shell.workspace_panels["render:inspector"]; + assert!(reservation.is_none(), "narrow Browser overlays the canvas"); + assert!(!browser.intersect(inspector).is_positive()); + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + h.app.run("view.render_focus", json!({"on":false})).unwrap(); + h.frames(3); + assert!(h.app.shell.render_browser_open); + assert!(h.app.shell.workspace_panels.contains_key("render:browser")); + h.step(&json!({"click":{"handle":"render:browser:hide"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + assert_eq!(h.app.preferences.render_browser_width, 320.0); + assert_eq!(h.app.preferences.render_inspector_width, 360.0); + } + h.call("ui.resize", json!({"width":1400,"height":900})); + h.frames(3); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0.width(), 320.0); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), 360.0); + } +} + +#[test] +fn render_workspace_focus_messages_have_five_complete_locales() { + let keys = [ + "cmd.view.render_focus", + "cmd.view.render_browser", + "render.exit_focus", + "render.fold_browser", + "render.spot_cone", + "render.emitted_axis", + "render.inner_half_angle", + "render.outer_half_angle", + "render.layer_off_suffix", + "render.tone_reinhard", + "render.tone_aces_fitted", + "render.size_hd", + "render.size_full_hd", + "render.size_4k_uhd", + "render.result_actual_size", + "render.property_unknown", + "render.property_fallback", + "render.property_source", + "render.property_qualifier", + "render.property_conditions", + "render.property_uncertainty", + "render.error_setup_panicked", + "render.error_setup_worker", + "render.error_setup_stopped", + "render.error_gpu_samples", + "render.error_preview_device", + "render.error_finish_operation", + "render.error_no_completed_image", + "render.error_provisional_identity", + "render.error_checkpoint_dimensions", + "render.error_display_dimensions", + "render.error_display_fit", + "render.error_display_width", + "render.error_display_height", + "render.error_image_profile", + "render.error_decode_budget", + "render.error_image_dimensions", + "render.error_upload_slot", + "render.error_export_document", + "render.error_geometry_size", + "render.error_vertex_envelope", + "render.error_body_bound", + "render.error_triangle_count", + "render.error_triangle_bound", + "render.error_face_cap", + "render.error_opacity", + "render.error_duplicate_face", + "render.error_pbr_opacity", + "render.error_vertex_allocation", + "render.error_product_triangle", + "render.error_surface_normals", + "render.error_vertex_packing", + "render.error_gpu_preview", + "render.error_fixed_preview", + "render.error_finish_gesture", + "render.error_no_scene", + "render.error_no_geometry", + "render.error_visible_solid", + "render.error_area_samples", + "render.error_quality_method", + "render.error_quality_projection", + "render.error_denoise_setting", + "render.error_quality_bounds", + "render.error_library_reply", + "render.error_source_preview", + "render.error_glass_recipe", + "render.error_physical_glass", + "render.error_scene_bodies", + "render.error_scene_body_limit", + "render.error_scene_identity", + "render.error_material_binding", + "render.error_surface_reply", + "render.error_binding_allocation", + "render.error_job_identity", + "render.error_regrade_identity", + "render.error_job_action", + "render.error_interactive_command", + ]; + for (language, source) in [ + ("en", include_str!(concat!(env!("OUT_DIR"), "/locales/en.json"))), + ("ja", include_str!(concat!(env!("OUT_DIR"), "/locales/ja.json"))), + ("zh", include_str!(concat!(env!("OUT_DIR"), "/locales/zh.json"))), + ("de", include_str!(concat!(env!("OUT_DIR"), "/locales/de.json"))), + ("ko", include_str!(concat!(env!("OUT_DIR"), "/locales/ko.json"))), + ] { + let translated: std::collections::BTreeMap = serde_json::from_str(source).unwrap(); + let locale = crate::i18n::Locale::for_language(language); + for key in keys { + let value = translated.get(key).unwrap_or_else(|| panic!("{language}: missing {key}")); + assert!(!value.is_empty()); + assert_eq!(locale.text(key), value); + } + let sentence = locale.format("render.property_source", &[("id", "A"), ("locator", "B")]); + assert!(sentence.contains('A') && sentence.contains('B') && !sentence.contains('{')); + } +} + +#[test] +fn render_workspace_chrome_uses_tokens_instead_of_literal_colours() { + use syn::visit::{self, Visit}; + #[derive(Default)] + struct Colours(Vec); + impl<'ast> Visit<'ast> for Colours { + fn visit_expr_path(&mut self, expr: &'ast syn::ExprPath) { + let names: Vec<_> = expr.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") && names.last().is_some_and(|s| matches!(s.as_str(), "WHITE" | "BLACK" | "GRAY")) { + self.0.push(names.join("::")); + } + visit::visit_expr_path(self, expr); + } + fn visit_expr_call(&mut self, expr: &'ast syn::ExprCall) { + if let syn::Expr::Path(path) = expr.func.as_ref() { + let names: Vec<_> = path.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") + && names.last().is_some_and(|s| s.starts_with("from_rgb") || s == "from_gray") + && expr.args.iter().all(|arg| matches!(arg, syn::Expr::Lit(_))) + { + self.0.push(names.join("::")); + } + } + visit::visit_expr_call(self, expr); + } + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files: Vec<_> = std::fs::read_dir(&root) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|path| { + let name = path.file_name().unwrap().to_string_lossy(); + name.starts_with("render_workspace") && name.ends_with(".rs") && !name.contains("tests") + }) + .collect(); + let mut folders = vec![root.join("render_ui")]; + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + folders.push(path); + } else if path.extension().is_some_and(|e| e == "rs") { + files.push(path); + } + } + } + for path in files { + let source = std::fs::read_to_string(&path).unwrap(); + let mut colours = Colours::default(); + colours.visit_file(&syn::parse_file(&source).unwrap()); + assert!(colours.0.is_empty(), "{}: {:?}", path.display(), colours.0); + } +} + +#[test] +fn render_workspace_shots_toggle_persists_and_design_roundtrip_preserves_state() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Subject".into() }]; + h.app.cam.yaw = 0.71; + h.app.cam.pitch = 0.23; + h.app.cam.roll = 0.17; + let camera = h.app.cam; + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let state = ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed, + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() <= 1.0, "{strip:?}"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert_eq!(h.app.session.doc, document); + assert_eq!( + state, + ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed + ) + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_none()); + assert!(crate::scenario::rect_of("render:shots:show").is_some()); + h.step(&json!({"click":{"handle":"render:shots:show"}})).unwrap(); + assert!(h.app.preferences.render_shots_strip); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + let saved = h.app.prefs(); + let mut next = Harness::new(); + next.app.load_prefs(&saved); + assert!(!next.app.preferences.render_shots_strip); + h.frames(2); + h.app.start("view.shots_strip"); + assert!(h.app.preferences.render_shots_strip); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_some()); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), state.0); +} + +#[test] +fn render_workspace_canvas_controls_and_fit_respect_panels_and_shots_in_both_layouts() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":60,"width":40,"height":30})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.cam.fov = 0.9; + h.app.start("render.camera.fit"); + h.frames(4); + assert_eq!(h.app.cam.fov, 0.9); + let free = crate::shell::content_rect(&h.app, h.app.viewport.rect.unwrap()); + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(free.contains_rect(layout.navigation), "{free:?} {layout:?}"); + assert!((layout.navigation.center().x - free.center().x).abs() < 1.0); + assert_product_fits_canvas(&h.app); + } +} + +#[test] +fn render_workspace_old_personal_pins_migrate_once_to_task_tabs() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER/SCENE":["render.settings.get","render.preset.resolve","solid.box"], + "DESIGN/RENDER/LIGHTING":["render.library.studio.apply"], + "DESIGN/RENDER/CAMERA":["render.settings.apply","render.camera.fit"], + "DESIGN/RENDER/IMAGE":["render.export","render.start"], + "DESIGN/RENDER/OUTPUT":["render.preflight"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/SHOTS"], ["render.settings.get", "solid.box"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.preset.resolve", "render.library.studio.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/VIEW"], ["render.settings.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.start", "render.preflight"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +#[test] +fn render_workspace_scene_vocabulary_migrates_previous_shell_pins_once() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER LIGHTING/LIGHTING":["render.library.studio.apply","render.lights.solo"], + "DESIGN/RENDER LIGHTING/ENVIRONMENT":["render.library.environment.apply","render.hdr.inspect"], + "DESIGN/RENDER/OUTPUT":["render.preflight","render.quality.prepare"], + "DESIGN/RENDER/RESULTS":["render.export","render.effects.describe"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.library.studio.apply", "render.library.environment.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/LIGHTS"], ["render.lights.solo"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STAGE"], ["render.hdr.inspect"]); + assert_eq!(custom.panels["DESIGN/RENDER/IMAGE"], ["render.quality.prepare", "render.effects.describe"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.preflight"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +fn assert_product_fits_canvas(app: &SolveApp) { + let layout = app.viewport.layout.as_ref().unwrap(); + let free = crate::shell::content_rect(app, layout.viewport); + assert!(free.contains_rect(layout.drawable), "fit region {:?} outside canvas {free:?}", layout.drawable); + let bounds = solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + let (sx, sy, _) = app + .cam + .to_screen( + solidcraft_engine::geom::Vec3::new(x, y, z), + f64::from(layout.viewport.width()), + f64::from(layout.viewport.height()), + bounds.diagonal().max(10.0), + ) + .unwrap(); + let at = layout.viewport.min + egui::vec2(sx as f32, sy as f32); + assert!(layout.drawable.contains(at), "product corner {at:?} outside {:?}", layout.drawable); + } + } + } +} + +#[test] +fn render_workspace_hosts_float_and_shield_input_in_both_ribbon_layouts() { + for (layout, page) in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] + .into_iter() + .flat_map(|layout| [inspector::Page::Scene, inspector::Page::Appearance].map(|page| (layout, page))) + { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":30,"width":20,"height":10})).unwrap(); + h.frames(4); + + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = page; + h.frames(4); + let viewport = h.app.viewport.rect.unwrap(); + let history = crate::timeline::floating_rect(viewport); + let shots = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((shots.height() - 48.0).abs() <= 1.0, "{layout:?}: {shots:?}"); + assert!( + (shots.left() - history.left()).abs() < 1.0 + && (shots.right() - history.right()).abs() < 1.0 + && (shots.bottom() - history.bottom()).abs() < 1.0, + "Shots must reuse History's floating placement: {shots:?} {history:?}" + ); + for key in ["render:inspector", "render:browser", "render:appearances", "render:shots_strip"] { + let (card, _) = h.app.shell.workspace_panels.get(key).unwrap(); + assert!(viewport.contains_rect(*card), "{layout:?} {key}: {card:?} outside {viewport:?}"); + assert!(crate::shell::covered(&h.app, card.center()), "{key} must shield the viewport"); + } + let inspector = h.app.shell.workspace_panels["render:inspector"].0; + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + let ribbon_bottom = h.app.shell.cards.iter().map(|r| r.bottom()).fold(0.0, f32::max); + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!((appearances.bottom() - inspector.bottom()).abs() < 1.0); + assert!(browser.height() <= 330.0, "Browser must stay within the fixed tree height: {browser:?}"); + for key in ["render:browser", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + assert!( + (card.top() - ribbon_bottom - Tokens::get().space_8).abs() < 1.0, + "{layout:?} {key}: gap {} must be 8 pt", + card.top() - ribbon_bottom + ); + } + for key in ["render:browser", "render:appearances", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + let header = crate::scenario::rect_of(&format!("{key}:header")).unwrap(); + assert!((header.height() - crate::ui_kit::header_height()).abs() < 0.1, "{key}: {header:?}"); + assert!((header.top() - card.top()).abs() <= 1.0, "header must have no outer content padding"); + let control = crate::scenario::rect_of(if key == "render:browser" { + "render:tree:by-look" + } else if key == "render:appearances" { + "render:library-search" + } else if page == inspector::Page::Appearance { + "dialog:editor_footer" + } else { + "render:scene:look" + }) + .unwrap(); + if key == "render:browser" { + assert!(header.contains_rect(control), "Scene lens belongs in the title band"); + } else { + assert!(control.top() >= header.bottom(), "editor controls must be below the standard header: {control:?} {header:?}"); + } + } + + assert!((browser.width() - appearances.width()).abs() < 1.0); + assert!((appearances.top() - browser.bottom() - Tokens::get().space_8).abs() < 1.0); + assert!(appearances.bottom() < shots.top()); + assert!(browser.left() > viewport.left() && inspector.right() < viewport.right()); + assert!(inspector.bottom() < shots.top() && browser.bottom() < shots.top()); + let camera = h.app.cam; + h.step( + &json!({"drag":[[inspector.center().x,inspector.center().y],[inspector.center().x-30.0,inspector.center().y+20.0]],"button":"middle"}), + ) + .unwrap(); + assert_eq!(h.app.cam, camera, "middle dragging over the card must not reach the model"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.viewport.rect, Some(viewport), "floating strips must preserve the viewport projection"); + let pill = h.app.shell.workspace_panels["render:shots:show"].0; + assert!(crate::shell::covered(&h.app, pill.center())); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert!(h.app.shell.workspace_panels.is_empty(), "Render card reservations must not leak into Design"); + } +} + +#[test] +fn render_workspace_assignment_footer_fits_stacked_card_with_shots_shown_and_hidden() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + for shown in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shown})).unwrap(); + h.frames(4); + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + // Assignment help is the shared footer's tooltip; its visible anchor stays in the card. + let footer = crate::scenario::rect_of("catalog:footer").unwrap(); + assert!(appearances.contains_rect(footer), "{layout:?}, Shots {shown}: footer {footer:?} outside {appearances:?}"); + let gap = Tokens::get().space_8; + assert!((appearances.top() - browser.bottom() - gap).abs() < 1.0); + let bounds = crate::shell::panel_bounds(&h.app, h.app.viewport.rect.unwrap()); + assert!((bounds.bottom() - appearances.bottom() - gap).abs() < 1.0, "{layout:?}, Shots {shown}: {appearances:?}, {bounds:?}"); + } + } +} + +#[test] +fn render_workspace_card_grips_swap_sides_and_resize_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + h.step(&json!({"drag":[{"handle":"render:inspector:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, "left"); + assert_eq!(h.app.preferences.render_browser_side, "right"); + assert!(h.app.shell.workspace_panels["render:inspector"].0.right() < h.app.shell.workspace_panels["render:browser"].0.left()); + let width = h.app.preferences.render_inspector_width; + let card_width = h.app.shell.workspace_panels["render:inspector"].0.width(); + let rail = crate::scenario::handle_at("render:inspector:resize").unwrap(); + h.step(&json!({"drag":[[rail.x,rail.y],[rail.x+50.0,rail.y]],"steps":8})).unwrap(); + h.frames(3); + // A compact dock keeps its minimum width and leaves the remembered width alone. + if layout == crate::shell::LayoutMode::Docked { + assert_eq!(h.app.preferences.render_inspector_width, width); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), card_width); + } else { + assert!(h.app.preferences.render_inspector_width > width); + assert!(h.app.shell.workspace_panels["render:inspector"].0.width() > card_width); + } + h.step(&json!({"click":{"handle":"render:tree:by-look"}})).unwrap(); + h.frames(3); + h.step(&json!({"drag":[{"handle":"render:browser:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_browser_side, "left"); + assert_eq!(h.app.preferences.render_inspector_side, "right"); + assert!(h.app.shell.workspace_panels["render:browser"].0.right() < h.app.shell.workspace_panels["render:inspector"].0.left()); + assert_eq!(h.app.cam, camera, "card gestures must not move the camera"); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } +} + +/// A small public-safe model, built through the sample recipe inside an occurrence. +fn render_pick_sample() -> (Harness, u64) { + let mut h = Harness::new(); + let part = h.app.run("component.create", json!({"name":"Sample","grounded":false})).unwrap(); + let occurrence = part["occurrence"].as_u64().unwrap(); + h.app.session.run_script(&solidcraft_engine::sample::script()).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.start("render.camera.fit"); + h.settle(); + (h, occurrence) +} + +fn product_pick_point(h: &Harness) -> egui::Pos2 { + let rect = h.app.viewport.layout.as_ref().unwrap().drawable; + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + for y in 2..18 { + for x in 2..18 { + let at = rect.min + egui::vec2(rect.width() * x as f32 / 20.0, rect.height() * y as f32 / 20.0); + if !crate::shell::covered(&h.app, at) + && crate::viewport::pick(&h.app, &proj, at).iter().any(|h| matches!(h, crate::viewport::Hit::Face { .. })) + { + return at; + } + } + } + panic!("sample must offer a visible product face outside the floating panels"); +} + +#[test] +fn render_workspace_pick_stage_tools_filter_sample_clicks_with_shots_shown_and_hidden() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for shots in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shots})).unwrap(); + h.frames(3); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert!(tools.contains_rect(crate::scenario::rect_of("render:pick").unwrap())); + assert!(tools.contains_rect(crate::scenario::rect_of("render:preview_note").unwrap())); + assert!(crate::scenario::rect_of("render:hud").is_none()); + for mode in ["body", "face", "component"] { + assert!(crate::scenario::handle_at(&format!("render:pick:{mode}")).is_some(), "Pick must be enabled"); + h.step(&json!({"click":{"handle":format!("render:pick:{mode}")}})).unwrap(); + h.frames(2); + let at = product_pick_point(&h); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + assert!(matches!(h.app.viewport.hover, Some(crate::viewport::Hit::Face { .. }))); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + match h.app.session.selection.as_slice() { + [Sel::Body { name }] if mode == "body" => assert_eq!(name, "Plate"), + [Sel::Face { body, .. }] if mode == "face" => assert_eq!(body, "Plate"), + [Sel::Occurrence { path }] if mode == "component" => assert_eq!(path, &[occurrence]), + other => panic!("{mode}, Shots {shots}: wrong selection {other:?}"), + } + let selected = h.app.session.selection.clone(); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.session.selection, selected); + enter(&mut h.app, true).unwrap(); + h.settle(); + assert_eq!(h.app.session.selection, selected); + } + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.tool.is_none() && h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_click_modifiers_clear_and_browser_share_selection() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + for (name, x) in [("Left", -30), ("Right", 30)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":20,"width":20,"height":20,"body_name":name})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.settle(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let left = proj.to_screen(solidcraft_engine::geom::Vec3::new(-20.0, 10.0, 20.0)).unwrap(); + let right = proj.to_screen(solidcraft_engine::geom::Vec3::new(40.0, 10.0, 20.0)).unwrap(); + h.step(&json!({"click":[left.x,left.y]})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection.len(), 2); + h.step(&json!({"click":[left.x,left.y],"ctrl":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + h.app.preferences.selection_shift_add_only = true; + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + // A Browser body row writes the same selection and immediately feeds the product overlay. + h.step(&json!({"click":{"handle":"row:Left"}})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + assert!(!crate::viewport::build_highlight(&h.app).merged().tris.is_empty()); + let empty = h.app.viewport.layout.as_ref().unwrap().drawable.left_bottom() + egui::vec2(10.0, -10.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.session.selection.is_empty()); + assert!(h.app.viewport.hover.is_none()); +} + +#[test] +fn render_workspace_selection_overlay_never_changes_started_frames_png_or_retained_results() { + use solidcraft_engine::Sel; + let (mut h, _) = render_pick_sample(); + let at = product_pick_point(&h); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let hit = crate::viewport::pick(&h.app, &proj, at).into_iter().next().unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let first = completed_preview(&mut h, [230, 230, 230]); + let clean = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + let clean_scene = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + h.app.run("select.set", json!({"items":[face]})).unwrap(); + let face_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(!face_overlay.tris.is_empty()); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Plate".into() }]})).unwrap(); + let body_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(body_overlay.tris.len() > face_overlay.tris.len(), "Face must only tint the selected face"); + h.app.viewport.hover = Some(hit); + let second = completed_preview(&mut h, [230, 230, 230]); + let selected = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + assert_eq!(clean.png(), selected.png(), "started image job must never capture selection or hover pixels"); + let after = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + assert_eq!(clean_scene.0, after.0); + assert_eq!(clean_scene.1.tris, after.1.tris); + h.app.render_workspace.view.completed = Some(second); + h.app.render_workspace.view.result = true; + h.frames(3); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + h.step(&json!({"click":{"handle":"render:pick:body"}})).unwrap(); + assert!(!h.app.ui.pick_bodies && !h.app.ui.pick_components, "result canvas must disable the stage's Pick control"); + let path = h.dir.join("overlay-free.png"); + h.app.run("render.export", json!({"job":second,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), clean.png()); + assert_eq!(h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap().png(), clean.png()); +} + +#[test] +fn render_workspace_pick_filter_rejects_invalid_requests_atomically() { + let mut h = Harness::new(); + let doc = h.app.session.doc.clone(); + for mode in ["body", "face", "component"] { + assert_eq!(h.app.run("select.filter", json!({"mode":mode})).unwrap()["mode"], mode); + assert_eq!(h.app.ui.pick_bodies, mode == "body"); + assert_eq!(h.app.ui.pick_components, mode == "component"); + } + for request in [json!({}), json!({"mode":"edge"}), json!({"mode":"body","extra":true})] { + assert!(h.app.run("select.filter", request).is_err()); + assert!(!h.app.ui.pick_bodies && h.app.ui.pick_components); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(h.app.session.undo.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_product_pass_draws_only_requested_face_or_body_overlay() { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(256.0, 256.0)); + app.viewport.rect = Some(rect); + let proj = crate::viewport::projection(&app, rect); + let hit = crate::viewport::pick(&app, &proj, rect.center()).into_iter().find(|h| matches!(h, crate::viewport::Hit::Face { .. })).unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&app.session).unwrap(); + let gpu = gpu_scene(&scene).unwrap().1; + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(app.cam.target); + let eye = app.cam.eye().to_f32(); + let camera = app.cam; + let draw = |overlay| { + crate::gpu::render_product_offscreen( + gpu.clone(), + overlay, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 1.0], + 256, + false, + ) + }; + let Some(clean) = draw(None) else { + eprintln!("skipping: no GPU adapter for product overlay pixels"); + return; + }; + app.run("select.set", json!({"items":[face]})).unwrap(); + let face_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + app.run("select.set", json!({"items":[{"type":"body","name":"Product"}]})).unwrap(); + let body_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + let changed = |image: &[u8]| clean.as_chunks::<4>().0.iter().zip(image.as_chunks::<4>().0).filter(|(a, b)| a != b).count(); + assert!(changed(&face_pixels) > 100, "Face overlay must reach the product pass"); + assert!(changed(&body_pixels) > changed(&face_pixels) + 100, "Face must leave the other faces untouched"); +} + +#[test] +fn render_workspace_pick_projection_matches_orthographic_and_custom_perspective_camera() { + use egui::{Event, Modifiers, PointerButton}; + use solidcraft_engine::geom::Vec3; + for fov in [0.0, 0.6, 1.1] { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + app.cam.fov = fov; + let ctx = crate::fonts::test_context(); + let mut time = 0.0; + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let rect = app.viewport.rect.unwrap(); + let proj = crate::viewport::projection(&app, rect); + assert_eq!(proj.cam.fov, fov); + let (x, y, _) = app.cam.to_screen(Vec3::new(20.0, 15.0, 20.0), f64::from(rect.width()), f64::from(rect.height()), 100.0).unwrap(); + let pos = rect.min + egui::vec2(x as f32, y as f32); + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(pos)]); + assert!(matches!(app.viewport.hover, Some(crate::viewport::Hit::Face { .. })), "FOV {fov}"); + for pressed in [true, false] { + nav_frame( + &mut app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], + ); + } + assert!(matches!(app.session.selection.as_slice(), [solidcraft_engine::Sel::Face { body, .. }] if body == "Product"), "FOV {fov}"); + } +} + +#[test] +fn render_workspace_component_filter_keeps_nested_repeated_occurrences_distinct() { + use crate::viewport::{Hit, candidate}; + use solidcraft_engine::{Sel, geom::Vec3}; + let mut h = Harness::new(); + let parent = h.app.run("component.create", json!({"name":"Parent"})).unwrap(); + let child = h.app.run("component.create", json!({"name":"Part"})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Solid"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let second = h.app.run("occurrence.copy", json!({"occurrence":parent["occurrence"],"translate":[50,0,0]})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"component"})).unwrap(); + for top in [parent["occurrence"].as_u64().unwrap(), second["occurrence"].as_u64().unwrap()] { + let path = vec![top, child["occurrence"].as_u64().unwrap()]; + let names = h.app.session.occurrence_bodies(&path, true).unwrap(); + assert_eq!(names.len(), 1); + let hit = Hit::Face { body: names[0].clone(), index: 0, point: Vec3::ZERO }; + assert_eq!(candidate(&h.app, &[hit]).unwrap().1, Sel::Occurrence { path }); + } +} + +#[test] +fn navigation_bar_render_canvases_filter_slots_and_keep_product_fit() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.preferences.look_at_anim = false; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps::RENDER); + // The product preview picks (#6426), so the slots that need a pick are on the bar there too. + for slot in ["orbit", "pan", "zoom", "fit", "look_at", "home", "visual_style", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } + h.app.cam.pan(100.0, 50.0, 600.0); + let panned = h.app.cam; + h.step(&json!({"click":{"handle":"nav:slot:fit"}})).unwrap(); + assert_ne!(h.app.cam.target, panned.target, "Fit recentres the product"); + assert_product_fits_canvas(&h.app); + let mut iso = h.app.cam; + iso.set_view(solidcraft_engine::render::StandardView::Iso); + h.app.cam.orbit(0.4, 0.2); + h.step(&json!({"click":{"handle":"nav:slot:home"}})).unwrap(); + assert_eq!((h.app.cam.yaw, h.app.cam.pitch), (iso.yaw, iso.pitch), "Home returns to the isometric view"); + assert_product_fits_canvas(&h.app); + + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.result = true; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps { orbit: false, pick: false }); + for slot in ["orbit", "look_at", "visual_style"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_none(), "{slot}"); + } + for slot in ["pan", "zoom", "fit", "home", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } +} + +#[test] +fn render_lights_browser_sections_and_lights_describe_current_job_entries() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rows: Vec<_> = crate::browser::drawn_rows().into_iter().map(|r| r.0).collect(); + for section in ["Environment", "Lights", "Shots", "Objects"] { + assert!(rows.iter().any(|label| label == section), "{section}: {rows:?}"); + } + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3]); + assert_eq!(scene::environment(&h.app).0, "Fixed studio"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "lights":[{"direction":[0,0,-1],"color":[1,1,1],"intensity":1}], + "punctual_lights":[ + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1}, + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1, + "cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}} + ], + "area_lights":[{"center_mm":[0,0,10],"edge_u_mm":[1,0,0],"edge_v_mm":[0,-1,0],"color":[1,1,1],"intensity":1}] + })) + .unwrap(); + assert_eq!(scene::light_types(&h.app), ["render.tree_directional", "render.tree_point", "render.tree_spot", "render.tree_rectangle"]); + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.punctual_lights = None; + h.app.render_workspace.view.raytrace.area_lights = None; + assert!(scene::light_types(&h.app).is_empty(), "empty explicit rig must stay empty"); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let studio = &mut h.app.render_workspace.view.studio; + studio.sun_enabled = true; + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3], "implicit studio sources are listed"); + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app + .render_workspace + .view + .studio + .area_lights + .push(serde_json::from_value(json!({"center":[0,0,10],"u":[1,0,0],"v":[0,-1,0],"radiance":[1,1,1]})).unwrap()); + assert_eq!(scene::light_types(&h.app), ["render.tree_sun", "render.tree_rectangle"]); + h.app.render_workspace.view.studio.environment = studio::Environment::Sky; + h.app.render_workspace.view.studio.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.studio.intensity = 2.5; + assert_eq!(scene::environment(&h.app), ("Sky".into(), "90° · 2.50×".into())); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:environment:current"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + h.step(&json!({"click":{"browser":"Key"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); +} + +#[test] +fn render_workspace_browser_look_lens_counts_distinct_objects_and_selects_them() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + for (name, x) in [("A", 0), ("B", 20), ("C", 40)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + h.app.run("appearance.assign", json!({"bodies":["A","B"],"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["C"],"appearance":"ABS - Blue"})).unwrap(); + // Two faces on C use the same look as A and B: still only one additional user. + h.app.run("appearance.assign", json!({"body":"C","faces":[[40,5,5],[45,0,5]],"appearance":"ABS - Red"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let groups = scene::groups(&h.app); + let red = groups.iter().position(|g| g.look.as_ref().is_some_and(|l| l.name == "ABS - Red")).unwrap(); + assert_eq!(groups[red].objects, ["A", "B", "C"]); + assert_eq!(groups.len(), 2); + h.app.render_workspace.view.by_look = true; + // Keep the object rows inside the ten-row Browser viewport while testing their hover. + crate::browser::toggle(&mut h.app, "render:tree:lights", true); + h.frames(3); + let at = crate::scenario::handle_at("row:A").unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.frames(2); + assert_eq!(h.app.viewport.hover_bodies, ["A"], "By look rows retain Browser hover outlines"); + h.step(&json!({"move":[1000.0,800.0]})).unwrap(); + h.frames(2); + assert!(h.app.viewport.hover_bodies.is_empty(), "leaving the row clears its hover outline"); + h.step(&json!({"click":{"handle":format!("render:tree:look:{red}")}})).unwrap(); + assert_eq!(h.app.session.selection.len(), 3); + for name in ["A", "B", "C"] { + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: name.into() })); + } + h.step(&json!({"click":{"handle":"eye:A"}})).unwrap(); + assert!(h.app.session.visibility.hidden_bodies.contains(&"A".into())); + let menu = crate::context_menu::items(&h.app, &crate::context_menu::Target::Body { name: "A".into() }); + for id in ["select.set", "select.same_look", "ui.isolate", "ui.show"] { + assert!(menu.iter().any(|i| i.id == id)); + } +} + +#[test] +fn render_workspace_dock_command_swaps_sides_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + let product_camera = h.app.render_workspace.view.draft.camera; + let widths = (h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width); + assert!(crate::shortcut_box::search(&h.app, "view.render_dock").iter().any(|row| row.0 == "view.render_dock")); + for (panel, side, inspector, browser) in [ + ("inspector", "left", "left", "right"), + ("browser", "left", "right", "left"), + ("inspector", "right", "right", "left"), + ("browser", "right", "left", "right"), + ] { + h.app.run("view.render_dock", json!({"panel":panel,"side":side})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, inspector); + assert_eq!(h.app.preferences.render_browser_side, browser); + let a = h.app.shell.workspace_panels["render:inspector"].0; + let b = h.app.shell.workspace_panels["render:browser"].0; + assert_eq!(a.center().x < b.center().x, inspector == "left"); + let view = h.app.viewport.layout.as_ref().unwrap(); + assert!(view.content.contains_rect(view.axis_view)); + let edge = if inspector == "left" { view.axis_view.left() - view.content.left() } else { view.content.right() - view.axis_view.right() }; + assert!(edge.abs() < 0.1); + assert!(!view.navigation.intersects(a)); + assert!(!view.navigation.intersects(b)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.camera, product_camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + assert_eq!((h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width), widths); + } + } +} + +#[test] +fn render_workspace_dock_grip_menus_dispatch_the_other_side() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + for panel in ["inspector", "inspector", "browser", "browser"] { + let before = h.app.preferences.render_inspector_side.clone(); + let at = crate::scenario::handle_at(&format!("render:{panel}:grip")).unwrap(); + for pressed in [true, false] { + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }, + ]); + } + h.frames(2); + // Opening the menu must not move either panel. + assert_eq!(h.app.preferences.render_inspector_side, before); + h.step(&json!({"click":{"handle":format!("render:{panel}:move_side")}})).unwrap(); + h.frames(3); + assert_ne!(h.app.preferences.render_inspector_side, before); + assert_ne!(h.app.preferences.render_inspector_side, h.app.preferences.render_browser_side); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + } + } +} + +#[test] +fn render_workspace_browser_shot_switch_keeps_the_existing_dirty_confirmation() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{"width":321,"job":{"method":"raster"}}})).unwrap(); + h.app.render_workspace.view.draft.width = 123; + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "A"); + assert!(inspector::confirmation_open(&h.app)); + h.step(&json!({"widget":h.app.tr("render.keep_editing")})).unwrap(); + assert_eq!(h.app.render_workspace.view.draft.width, 123); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "B"); + assert_eq!(h.app.render_workspace.view.draft.width, 321); + assert!(!h.app.render_workspace.view.dirty); +} + +#[test] +fn render_lights_browser_focus_covers_each_kind_without_design_edits() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + h.app.run("render.settings.set", json!({"name":"Shot","set":{"job":{"method":"raster"}}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.sun_enabled = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for label in ["Environment", "Lights", "Shots", "Objects", "Output"] { + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == label), "{label}"); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.step(&json!({"click":{"handle":"row:Object"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Object(vec![Sel::Body { name: "Object".into() }])); + h.step(&json!({"click":{"handle":"render:tree:environment"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + assert!(crate::scenario::rect_of("dialog:section:Source").is_some()); + assert!(h.app.session.selection.is_empty()); + let focused_revision = h.app.session.revision; + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Light(id) if id=="directional:0")); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:Shot"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Shot("Shot".into())); + // The browser is height-capped even in a tall window. Output is its last row, + // and published targets can lie below the scroll clip as more rows are added. + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + h.call("ui.scroll", json!({"x":browser.center().x,"y":(header.bottom()+browser.bottom())/2.0,"delta":-2000})); + h.frames(20); + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + let output = crate::scenario::handle_at("render:tree:output").unwrap(); + assert!( + browser.shrink(Tokens::get().space_8).contains(output) && output.y > header.bottom(), + "Output click must be inside the visible browser body" + ); + h.step(&json!({"click":{"handle":"render:tree:output"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert_eq!(h.app.session.revision, focused_revision, "semantic selection only refreshes the view when clearing object picks"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[test] +fn render_lights_browser_eye_and_solo_are_view_state_and_editor_opening_is_read_only() { + let mut h = render_lights_fixture(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Key")); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Fill")); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.step(&json!({"click":{"handle":"eye:Key"}})).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.step(&json!({"click":{"handle":"render:tree:light:1:solo"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.lights.visibility.solo.as_deref(), Some("directional:1")); + h.step(&json!({"click":{"handle":"render:tree:light:1"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + assert!(crate::scenario::handle_at("render:tree:shots:add").is_some()); + h.step(&json!({"click":{"handle":"render:tree:shots:add"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_browser_stage_expansion_never_locks_rows_or_changes_focus() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + let doc = h.app.session.doc.clone(); + let sections = ["objects", "lights", "environment", "shots"]; + for (stage, expanded) in [("look", vec!["objects"]), ("light", vec!["lights", "environment"]), ("frame", vec!["shots"]), ("output", vec![])] { + for section in sections { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + for section in sections { + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), expanded.contains(§ion), "{stage}/{section}"); + crate::browser::toggle(&mut h.app, &format!("render:tree:{section}"), true); + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), !expanded.contains(§ion)); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn render_workspace_browser_semantic_focus_survives_clearing_object_picks() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let doc = h.app.session.doc.clone(); + let evaluated = h.app.session.world_state(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for (request, expected) in [ + (json!({"kind":"environment"}), RenderSelection::Environment), + (json!({"kind":"lighting"}), RenderSelection::Lighting), + (json!({"kind":"light","id":"sun"}), RenderSelection::Light("sun".into())), + (json!({"kind":"shot","id":"Shot"}), RenderSelection::Shot("Shot".into())), + (json!({"kind":"output"}), RenderSelection::Output), + (json!({"kind":"nothing"}), RenderSelection::Nothing), + ] { + h.app.run("select.set", json!({"items":[Sel::Body { name:"Object".into() }]})).unwrap(); + assert!(matches!(h.app.render_workspace.view.selection, RenderSelection::Object(_))); + h.app.run("view.render_select", request.clone()).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.selection, expected, "{request}"); + assert!(h.app.session.selection.is_empty()); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(Arc::ptr_eq(&evaluated, &h.app.session.world_state())); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); +} + +#[test] +fn render_workspace_browser_focus_is_per_document_and_invalid_selection_is_atomic() { + let mut h = Harness::new(); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let doc = h.app.session.doc.clone(); + for request in [ + json!({}), + json!({"kind":"object"}), + json!({"kind":"light"}), + json!({"kind":"shot","id":""}), + json!({"kind":"lighting","id":"extra"}), + json!({"kind":"output","id":"x"}), + json!({"kind":"shot","id":"x".repeat(1025)}), + json!({"kind":"nothing","extra":1}), + ] { + assert!(h.app.run("view.render_select", request).is_err()); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + crate::documents::switch(&mut h.app, 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); +} + +#[test] +fn render_workspace_wear_tree_selects_the_scene_stack_and_counts_layers_in_both_lenses() { + use solidcraft_engine::render::job::aging::{AgingKind, AgingLayer}; + fn has_text(shape: &egui::Shape, needle: &str) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.text().contains(needle), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| has_text(shape, needle)), + _ => false, + } + } + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body { name: "Subject".into() }]})).unwrap(); + let document = h.app.session.doc.clone(); + assert_eq!(scene::wear_subtitle(&h.app), h.app.tr("render.wear_no_layers")); + h.frames(3); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, h.app.tr("render.wear_no_layers")))); + h.step(&json!({"click":{"handle":"render:tree:wear"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Wear); + assert!(h.app.session.selection.is_empty()); + assert!(crate::scenario::rect_of("render:wear:controls").is_some()); + assert!(!crate::icon_svg::resolve("appearance").placeholder); + for count in 1..=2 { + h.app.render_workspace.view.studio.aging.push(AgingLayer::preset(AgingKind::Dust)).unwrap(); + h.app.render_workspace.view.dirty = true; + let label = + crate::i18n::format(if count == 1 { "render.wear_layer_one" } else { "render.wear_layer_count" }, &[("count", &count.to_string())]); + assert_eq!(scene::wear_subtitle(&h.app), label); + for by_look in [false, true] { + h.app.run("view.render_browser", json!({"by_look":by_look})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:tree:wear").is_some()); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, &label))); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +/// Actual application tree at the approved card width, in both themes and both task states. +#[test] +fn render_workspace_browser_compact_geometry_search_and_theme_evidence() { + let previous = crate::theme::is_dark(); + let mut themes = Vec::new(); + for dark in [false, true] { + let mut h = Harness::new(); + for (name, x, appearance) in [ + ("Plate", 0, "Aluminum - Satin"), + ("Boss", 20, "Aluminum - Anodized Blue"), + ("Knob", 40, "Copper"), + ("Cover", 60, "Glass - Clear"), + ("Spacer", 80, "Aluminum - Satin"), + ("Bolt", 100, "Aluminum - Satin"), + ("Nut", 120, "Aluminum - Satin"), + ] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":[name],"appearance":appearance})).unwrap(); + } + let group = + h.app.run("browser.group", json!({"folder":"bodies","name":"Spacer, fasteners","items":["Spacer","Bolt","Nut"]})).unwrap()["group"] + .as_u64() + .unwrap(); + h.app.tree.collapsed.insert(format!("c0/g{group}")); + for name in ["Hero", "Front", "Detail"] { + h.app.run("render.settings.set", json!({"name":name,"set":{"width":1920,"height":1080}})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_width = 266.0; + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + h.app.ui.dark = dark; + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + let mut images = Vec::new(); + for stage in ["look", "light"] { + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = Some(serde_json::from_value(json!([{"direction":[0,0,-1],"color":[1,1,1],"intensity":1},{"direction":[1,0,0],"color":[1,1,1],"intensity":1},{"direction":[0,1,0],"color":[1,1,1],"intensity":1}])).unwrap()); + for section in ["lights", "shots", "objects"] { + if (stage == "look" && section == "objects") || (stage == "light" && section == "lights") { + h.app.tree.collapsed.remove(&format!("render:tree:{section}")); + } else { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + } + if stage == "light" { + h.app + .run( + "view.render_select", + json!({"kind":"light","id":format!("{}:render.tree_directional:0",h.app.render_workspace.view.method.label())}), + ) + .unwrap(); + } + let mut image = None; + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(bounds), + time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), + focused: true, + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let card = crate::scenario::rect_of("browser:card").unwrap(); + assert!((card.width() - 266.0).abs() < 0.1); + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + let stage_panel = h.app.shell.workspace_panels["render:appearances"].0; + assert!((card.top() - inspector.top()).abs() < 0.1); + assert!((stage_panel.bottom() - inspector.bottom()).abs() < 0.1); + assert!((stage_panel.top() - card.bottom() - Tokens::get().space_8).abs() < 0.1); + assert!(card.height() <= 330.0, "Browser must stay within the fixed tree height: {card:?}"); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + assert!(header.contains_rect(crate::scenario::rect_of("render:tree:by-look").unwrap())); + assert!(crate::scenario::handle_at("render:browser-model").is_none()); + assert!(crate::scenario::handle_at("render:browser-library").is_none()); + for (name, row, _, _) in crate::browser::drawn_rows() { + assert!((row.height() - 28.0).abs() < 0.1, "{name}: {row:?}"); + } + if stage == "look" { + let row = crate::browser::drawn_rows().into_iter().find(|r| r.0 == "Boss").unwrap().1; + assert!((row.width() - (card.width() - 2.0)).abs() < 0.1); + assert!(crate::scenario::handle_at("eye:Boss").unwrap().x > row.right() - 24.0); + } + if std::env::var_os("SOLIDCRAFT_BROWSER_EVIDENCE").is_some() { + let full = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image = Some( + image::imageops::crop_imm(&full, card.left() as u32, card.top() as u32, card.width() as u32, card.height() as u32) + .to_image(), + ); + } + } + } + if let (Some(image), Ok(dir)) = (image, std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + std::fs::create_dir_all(&dir).unwrap(); + image.save(std::path::Path::new(&dir).join(format!("scene-{stage}-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + images.push(image); + } + } + if let (Some(look), Some(light), Ok(dir)) = (images.first(), images.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + let mut pair = image::RgbaImage::new(look.width() + light.width(), look.height().max(light.height())); + image::imageops::overlay(&mut pair, look, 0, 0); + image::imageops::overlay(&mut pair, light, 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-stages-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + themes.push(images); + h.app.run("view.render_browser", json!({"search":true,"query":"Copper"})).unwrap(); + h.app.tree.collapsed.remove("render:tree:objects"); + h.frames(4); + let rows = crate::browser::drawn_rows(); + assert!(rows.iter().any(|r| r.0 == "Knob")); + assert!(!rows.iter().any(|r| r.0 == "Boss")); + h.app.run("view.render_browser", json!({"search":false})).unwrap(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == "Boss")); + for hidden in [true, false] { + h.step(&json!({"click":{"handle":"eye:Boss"}})).unwrap(); + assert_eq!(h.app.session.visibility.hidden_bodies.iter().any(|name| name == "Boss"), hidden); + } + } + if let (Some(light), Some(dark), Ok(dir)) = (themes.first(), themes.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + for (index, stage) in ["look", "light"].iter().enumerate() { + let mut pair = image::RgbaImage::new(light[index].width() + dark[index].width(), light[index].height().max(dark[index].height())); + image::imageops::overlay(&mut pair, &light[index], 0, 0); + image::imageops::overlay(&mut pair, &dark[index], 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-{stage}-themes.png"))).unwrap(); + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_workspace_shots_modified_dot_update_and_revert_follow_only_camera() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + h.frames(3); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + h.app.render_workspace.view.draft.width = 317; + h.frames(2); + assert!(!shots::camera_modified(&h.app, "Studio"), "output settings must not mark the camera"); + h.app.cam.yaw += 0.3; + h.frames(3); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_some()); + assert!(crate::scenario::handle_at("render:shots:update").is_some()); + h.step(&json!({"click":{"handle":"render:shots:update"}})).unwrap(); + h.frames(2); + let mut expected = saved.clone(); + expected.camera = h.app.cam; + assert_eq!(h.app.session.doc.render.setups["Studio"], expected, "Update must preserve saved output and lighting"); + assert_eq!(h.app.render_workspace.view.draft.width, 317, "Update must preserve the editor draft"); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + assert!(crate::scenario::handle_at("render:shots:update").is_none()); + h.app.cam.roll += 0.2; + h.frames(3); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:revert"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.cam, expected.camera); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_shots_save_prompt_and_size_dropdown_use_existing_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:shots:save"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + h.app.render_workspace.view.save_shot_name = Some("Hero".into()); + h.frames(3); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(1.0)); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(h.app.session.doc.render.setups.contains_key("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.render.setups["Hero"].camera, h.app.cam); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:size"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:Full HD"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1920, 1080)); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_shots_thumbnails_bound_invalidate_and_never_replace_results_or_history() { + use std::time::{Duration, Instant}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + for index in 0..20 { + h.app.run("render.settings.set", json!({"name":format!("Shot {index:02}"),"set":{"camera":h.app.cam}})).unwrap(); + } + // A real completed frame stays available, including its exact PNG and retained texture. + let id = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + let png = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + let retained = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let deadline = Instant::now() + Duration::from_secs(20); + while h.app.render_workspace.thumbnails.entries.len() < thumbnails::LIMIT { + assert!(Instant::now() < deadline, "thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(h.app.render_workspace.thumbnails.entries.len(), 16); + assert!(h.app.render_workspace.thumbnails.entries.values().all(|texture| texture.as_ref().is_some_and(|texture| texture.size() == [104, 60]))); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), retained); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), png); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); + // Later shots must get previews on selection/scrolling rather than keeping the first 16 forever. + h.app.render_workspace.view.name = "Shot 19".into(); + h.app.render_workspace.thumbnails.show(vec!["Shot 18".into(), "Shot 19".into()], &h.ctx); + thumbnails::refresh(&mut h.app, &h.ctx); + while h.app.render_workspace.thumbnails.texture("Shot 19").is_none() || h.app.render_workspace.thumbnails.texture("Shot 18").is_none() { + assert!(Instant::now() < deadline, "visible thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.len() <= 16); + std::thread::sleep(Duration::from_millis(2)); + } + let old = h.app.render_workspace.thumbnails.entries.keys().cloned().collect::>(); + // Camera, scene revision and visibility invalidate stale previews. + let camera = Camera { yaw: 0.7, ..h.app.cam }; + h.app.run("render.settings.set", json!({"name":"Shot 00","set":{"camera":camera}})).unwrap(); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.keys().all(|key| !old.contains(key))); + h.app.session.visibility.hidden_bodies.push("Body1".into()); + thumbnails::refresh(&mut h.app, &h.ctx); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); + thumbnails::refresh(&mut h.app, &h.ctx); + reset_document(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); +} + +#[test] +fn render_workspace_shots_running_ring_stays_with_the_submitted_shot() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{}})).unwrap(); + h.app.start("render.start"); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("A")); + h.app.render_workspace.view.name = "B".into(); + h.frames(2); + assert!(crate::scenario::rect_of("dialog:list:shot:A:progress").is_some()); + assert!(crate::scenario::rect_of("dialog:list:shot:B:progress").is_none()); + h.app.start("render.cancel"); +} + +#[test] +fn render_workspace_shots_thumbnail_keys_include_name_scene_revision_and_complete_camera() { + let camera = Camera::default(); + let key = thumbnails::Key::new("Hero".into(), 1, 2, camera); + assert_eq!(key, thumbnails::Key::new("Hero".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Front".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 2, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 3, camera)); + for changed in [ + Camera { yaw: camera.yaw + 0.1, ..camera }, + Camera { roll: camera.roll + 0.1, ..camera }, + Camera { fov: 0.7, ..camera }, + Camera { up: solidcraft_engine::render::UpAxis::Y, ..camera }, + ] { + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 2, changed)); + } +} + +#[test] +fn render_workspace_shots_heading_matches_design_history_typography_and_strip_baseline() { + fn heading(h: &mut Harness, title: &str, strip: &str) -> (egui::FontId, Color32) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 1000.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + let rect = crate::scenario::rect_of(strip).unwrap(); + let text = crate::test_support::text_shapes(&output).find(|text| text.galley.text() == title && rect.contains(text.pos)).unwrap(); + let format = &text.galley.job.sections.first().unwrap().format; + assert!((text.pos.y + text.galley.size().y / 2.0 - rect.center().y).abs() <= 1.0, "{title} centred on its strip"); + let appearance = (format.font_id.clone(), format.color); + output.textures_delta.clear(); + appearance + } + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.ui.layout = crate::shell::LayoutMode::Docked; + h.app.preferences.timeline_left = false; + h.app.ui.show_timeline = true; + h.frames(3); + let history = heading(&mut h, "History", "history:strip"); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert_eq!(heading(&mut h, "Shots", "render:shots_strip"), history); +} + +#[test] +fn render_workspace_frame_save_shot_dispatches_without_a_ribbon_or_document_edits() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(3); + assert!(crate::scenario::handle_at("render:stage:save_shot").is_none()); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:stage:save_shot"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); + h.app.render_workspace.view.save_shot_name = Some("Frame shot".into()); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Frame shot"].camera, h.app.cam); + h.app.render_workspace.view.save_shot_name = None; + assert!(h.app.run("render.settings.set", json!({})).is_err()); + assert!(!inspector::confirmation_open(&h.app)); + assert!(crate::workspace::destination(solidcraft_engine::find_command("view.shots_strip").unwrap()).is_none()); + assert!(crate::workspace::RIBBON_LABELS.iter().all(|(id, _)| *id != "view.shots_strip")); +} + +#[test] +fn render_workspace_shots_strip_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.pending_fit = None; + for (name, yaw) in [("Hero", 0.5), ("Front", 0.0), ("Detail", 0.8)] { + h.app.run("render.settings.set", json!({"name":name,"set":{"camera":Camera {yaw,..h.app.cam}}})).unwrap(); + } + switch_shot(&mut h.app, "Hero".into()); + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":1920,"height":1080}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..10_000 { + host.pump(16_384).unwrap(); + if h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some() { + break; + } + } + assert!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some()); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(bounds), time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() < 1.0, "{strip:?}"); + let mut last = crate::scenario::rect_of("render:shots:heading").unwrap(); + for target in [ + "render:shots:save", + "render:shots:setup:Detail", + "render:shots:setup:Front", + "render:shots:setup:Hero", + "render:shots:status", + "render:shots:size", + "render:shots:render", + "render:shots:hide", + ] { + let rect = crate::scenario::rect_of(target).unwrap(); + assert!(strip.contains_rect(rect), "{target}: {rect:?} in {strip:?}"); + assert!(rect.left() >= last.right(), "{target} overlaps preceding control"); + last = rect; + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_SHOTS_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("shots-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn appearance_editor_hostile_optics_stay_finite_and_never_panic() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target = materials::read_targets(&mut h.app).unwrap().remove(0); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1e300] { + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass.ior = value; + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_err(), "hostile IOR {value}"); + } + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_ok(), "box boundaries are closed dielectrics too"); +} + +fn output_viewer_fixture() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.frames(3); + h +} + +#[test] +fn output_viewer_size_chips_obey_limits_and_largest_upscales_at_the_current_aspect() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for (key, expected) in [("720", (1280, 720)), ("1080", (1920, 1080))] { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + let draft = &h.app.render_workspace.view.draft; + assert_eq!((draft.width, draft.height), expected); + } + let largest = inspector::largest_output(&h.app).unwrap(); + assert!(largest.0 > 1920); + assert_eq!(cpu::image_limits(&h.app).fit(largest.0, largest.1, None), Some(largest)); + assert!((largest.0 as f64 / largest.1 as f64 - 16.0 / 9.0).abs() < 0.002); + h.step(&json!({"click":{"handle":"render:size:largest"}})).unwrap(); + assert_eq!((u64::from(h.app.render_workspace.view.draft.width), u64::from(h.app.render_workspace.view.draft.height)), largest); + let before = h.app.render_workspace.view.draft.clone(); + assert!(h.app.run("render.output.size", json!({"width":4096,"height":4096})).is_err()); + assert_eq!(h.app.render_workspace.view.draft, before); + assert_eq!(h.app.session.doc.features, document.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_check_lists_preflight_results_without_starting_and_marks_edits_stale() { + let mut h = output_viewer_fixture(); + let host = h.app.session.render_job_host().unwrap().clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:stage:check"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.checked.is_none()); + h.step(&json!({"click":{"handle":"render:check"}})).unwrap(); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + h.app.run("render.output.size", json!({"width":32,"height":16})).unwrap(); + h.frames(2); + assert!(crate::scenario::rect_of("render:check:stale").is_some()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_copy_uses_retained_final_pixels_and_refuses_missing_or_oversized_images() { + let mut h = output_viewer_fixture(); + assert!(ribbon::perform_job(&mut h.app, "render.result.copy").is_err()); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(decode_render_image(&[], 4097, 1, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + assert!(decode_render_image(&[], 4096, 4096, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + let first = completed_preview(&mut h, [12, 34, 56]); + h.app.render_workspace.view.completed = Some(first); + // A new queued render must not become the source for Copy. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + ribbon::perform_job(&mut h.app, "render.result.copy").unwrap(); + let image = h.app.render_workspace.clipboard_image.as_ref().unwrap(); + assert_eq!(image.size, [16, 16]); + assert_eq!(image.pixels[0], egui::Color32::from_rgb(12, 34, 56)); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame(); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(h.output.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyImage(image) if image.size == [16,16]))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); +} + +#[test] +fn output_viewer_progress_keeps_stage_tools_and_cancel_cancels_without_closing_viewer() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.result = true; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_some()); + assert!(crate::scenario::rect_of("render:stage:size").is_some()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + h.step(&json!({"click":{"handle":"render:progress-cancel"}})).unwrap(); + h.app.session.render_job_host().unwrap().pump(1024).unwrap(); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "cancelled"); + assert!(h.app.render_workspace.view.result); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_none()); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at("render:pick").is_some()); +} + +#[test] +fn output_viewer_r_starts_active_setup_and_escape_returns_to_model_without_cancelling() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.name = "Active shot".into(); + h.app.render_workspace.view.draft.width = 32; + h.app.render_workspace.view.draft.height = 24; + assert_eq!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); + h.step(&json!({"key":"R"})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Active shot")); + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(status["request"]["width"], 32); + assert_eq!(status["request"]["height"], 24); + // A repeated R while busy cannot fall through to Rectangle/Create Sketch. + h.step(&json!({"key":"R"})).unwrap(); + assert_eq!(h.app.render_workspace.view.job, Some(job)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.frames(2); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert!(ribbon::busy(&h.app), "closing the image never cancels the job"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.app.viewport.nav = Some(crate::viewport::NavMode::Pan); + crate::keymap::press(&mut h.app, "Escape", false); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.viewport.nav.is_none(), "closing the image releases its navigation capture"); + enter(&mut h.app, false).unwrap(); + assert_ne!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); +} + +/// Actual app controls and retained pixels, rasterized from egui without a window. +#[test] +fn output_viewer_evidence() { + let Some(dir) = std::env::var_os("SOLIDCRAFT_OUTPUT_EVIDENCE") else { return }; + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.run("solid.box", json!({"length":24,"width":18,"height":12})).unwrap(); + inspector::fit_subject(&mut h.app).unwrap(); + h.app.pending_fit = None; + h.app.cancel_view_animation(); + h.app.preferences.render_inspector_width = 305.0; + h.app.run("render.output.size", json!({"width":1280,"height":720})).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + h.ctx = crate::fonts::test_context(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + crate::theme::set_dark(dark); + crate::theme::apply(&h.ctx); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for (index, state) in ["settings", "check", "effects", "running", "completed"].into_iter().enumerate() { + if state == "check" { + h.app.run("view.render_select", json!({"kind":"check"})).unwrap(); + h.app.cancel_view_animation(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + if state == "effects" { + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.start("render.effects.describe"); + } + if state == "running" { + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + // Retain a real first image while the next job makes bounded progress. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.completed.is_some()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + host.pump(327680).unwrap(); + assert!(ribbon::busy(&h.app)); + } + if state == "completed" { + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + } + for frame in 0..10 { + let mut events = Vec::new(); + if frame == 0 { + events.push(egui::Event::PointerMoved(egui::pos2(700.0, 500.0))); + } + let mut input = egui::RawInput { + screen_rect: Some(bounds), + focused: true, + time: Some((index * 10 + frame) as f64 / 60.0), + events, + ..Default::default() + }; + h.app.raw_input_hook(&mut input); + let mut output = h.ctx.run_ui(input, |ui| { + h.app.logic(ui.ctx()); + if state == "check" && frame == 9 { + // Check the settled, scrolled view immediately before capturing it. + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + h.app.ui(ui); + }); + crate::ui_kit::update_test_textures(&mut textures, &output.textures_delta); + if frame == 9 { + if state == "check" { + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + assert!(h.app.render_workspace.view.job.is_none()); + } + crate::ui_kit::raster_ui(&h.ctx, output.shapes.clone(), output.pixels_per_point, bounds, &textures) + .save(dir.join(format!("output-{state}-{}.png", if dark { "dark" } else { "light" }))) + .unwrap(); + } + output.textures_delta.clear(); + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled() { + let h = output_viewer_fixture(); + let expected = [ + "render.start", + "appearance.assign", + "render.lights.add", + "render.settings.set", + "render.camera.fit", + "render.compare", + "ui.workspace.design", + "undo", + ]; + assert_eq!(crate::mouse_gesture::Studio::Render.defaults(), expected); + assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); + assert!(!crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); +} + +#[test] +fn output_viewer_presets_are_commands_with_limits_and_custom_keeps_the_size() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(6); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "opening Size presets does not apply anything"); + for (index, (key, expected)) in [("720", (1280, 720)), ("1080", (1920, 1080)), ("square", (2048, 2048))].into_iter().enumerate() { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), expected); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + let saved = &h.app.session.doc.render.setups[&h.app.render_workspace.view.name]; + assert_eq!((saved.width, saved.height), expected); + } + h.step(&json!({"click":{"handle":"render:preset:4k"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + h.step(&json!({"click":{"handle":"render:preset:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.resolution.custom); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + assert_eq!(document.features, h.app.session.doc.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to_output() { + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1440,"height":900})); + h.frames(3); + for key in ["render.children.renderer", "render.output_image", "render.output_destination", "render.children.render"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).is_some(), "{key}"); + } + assert!(crate::scenario::rect_of("render:job-footer").is_none()); + for page in ["output", "effects", "all"] { + assert!(crate::scenario::rect_of(&format!("render:page:{page}")).is_none()); + } + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for target in ["render:stage:size", "render:stage:check"] { + assert!(tools.contains_rect(crate::scenario::rect_of(target).unwrap())); + } + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:output-width").is_some(), "selected Output keeps its editor when the stage changes"); + } +} + +#[test] +fn render_assign_gestures_selection_sizes_are_atomic_and_undoable() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + for mode in ["body", "face", "component"] { + h.app.run("select.filter", json!({"mode":mode})).unwrap(); + let at = product_pick_point(&h); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), false).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + match mode { + "body" => assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"), + "face" => assert!(h.app.session.doc.appearances.faces.iter().any(|f| f.look.name == "ABS - Blue")), + _ => { + let id = h.app.session.doc.path_placement(&[occurrence]).unwrap().0; + assert_eq!(h.app.session.doc.appearances.components[&id].name, "ABS - Blue"); + } + } + assert!(h.app.status_undo); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Plate".into() }, Sel::Body { name: "missing".into() }]; + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assert!(assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_assign_gestures_paint_sample_copy_paste_escape_and_failed_pick() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let before = h.app.session.doc.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + h.frames(3); + let at = product_pick_point(&h); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + h.step(&json!({"widget":"Undo"})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1, "toast Undo must not paint through to the canvas"); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.run("appearance.assign", json!({"body":"Plate","faces":[[20,20,8]],"appearance":"ABS - Blue"})).ok(); + h.app.start("appearance.pick_up"); + let candidate = crate::viewport::pick(&h.app, &crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()), at) + .into_iter() + .find(|hit| matches!(hit, crate::viewport::Hit::Face { .. })) + .unwrap(); + let source = match candidate { + crate::viewport::Hit::Face { body, index, .. } => Some((body, index)), + _ => None, + }; + let (body, index) = source.unwrap(); + let expected = h.app.run("appearance.pick_up", json!({"target":{"body":body,"face":index}})).unwrap()["look"].clone(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert_eq!(h.app.render_workspace.view.assign.look, Some(expected.clone())); + h.step(&json!({"widget":"Done"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.start("appearance.paint"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Plate".into() }]; + h.app.start("appearance.copy"); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Yellow"})).unwrap(); + let undo = h.app.session.undo.len(); + h.app.start("appearance.paste"); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); + h.app.start("appearance.pick_up"); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + // Empty view: a failed pick neither paints nor exits sampling. + let free = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + let empty = egui::pos2(free.right() - 20.0, free.bottom() - 50.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.sampling); +} + +#[test] +fn render_assign_gestures_drag_preview_and_release_use_no_document_draft() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let at = product_pick_point(&h); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + ]); + h.frames(2); + assert!(assign::preview(&h.app).is_some()); + let mut scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let before = scene.meshes.iter().map(|m| m.color).collect::>(); + assign::preview_scene(&mut scene, assign::preview(&h.app).as_ref()).unwrap(); + assert_ne!(scene.meshes.iter().map(|m| m.color).collect::>(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.frame_with(vec![egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }]); + h.frames(2); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), document.to_json()); +} + +#[test] +fn render_assign_gestures_shortcuts_are_scoped_and_commands_are_not_stubs() { + let mut h = Harness::new(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("inspect.measure")); + enter(&mut h.app, true).unwrap(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("appearance.pick_up")); + assert_eq!(crate::keymap::command_for(&h.app, "B"), Some("appearance.paint")); + for (id, key) in [("appearance.copy", "Ctrl+Alt+C"), ("appearance.paste", "Ctrl+Alt+V")] { + assert_eq!(crate::keymap::command_for(&h.app, key), Some(id)); + } + for id in ["appearance.paint", "appearance.pick_up", "appearance.copy", "appearance.paste"] { + assert!(solidcraft_engine::find_command(id).unwrap().planned.is_none()); + } + let before = h.app.session.doc.clone(); + h.app.run("appearance.paint", json!({"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.pick_up", json!({})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(h.app.dialog.is_none()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[test] +fn render_assign_gestures_grid_drag_modifiers_cancel_and_context_menu() { + let (mut h, occurrence) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"name":"Gesture blue","color":"#1234dd"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + h.step(&json!({"click":{"handle":"render:library-scope:in-design"}})).unwrap(); + h.frames(3); + let id = json!(["Gesture blue", "#1234dd", 1.0, null]).to_string(); + let source = crate::scenario::rect_of(&format!("render:library:{id}")).unwrap().center(); + let at = product_pick_point(&h); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::PointerMoved(source)]); + h.frame_with(vec![egui::Event::PointerButton { + pos: source, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }]); + h.frame_with(vec![egui::Event::PointerMoved(source + egui::vec2(20.0, 0.0))]); + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frames(2); + assert!(assign::preview(&h.app).is_some(), "grid drag must arm a live preview over geometry"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for mods in [egui::Modifiers::SHIFT, egui::Modifiers::CTRL, egui::Modifiers::COMMAND] { + h.frame_with(vec![egui::Event::ModifiersChanged(mods)]); + h.frames(2); + let hover = assign::hover(&h.app).unwrap(); + if mods.shift { + assert!(matches!(hover, solidcraft_engine::Sel::Face { .. })); + } else { + assert_eq!(hover, &solidcraft_engine::Sel::Occurrence { path: vec![occurrence] }); + } + assert!(assign::preview(&h.app).is_some()); + } + h.frame_with(vec![ + egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::SHIFT }, + ]); + h.frames(2); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.faces.last().unwrap().look.name, "Gesture blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + let menu = assign::menu(&h.app, "Plate"); + for id in ["appearance.library", "appearance.pick_up", "appearance.copy", "appearance.paste", "appearance.assign"] { + assert!(menu.children.iter().any(|item| item.id == id), "missing menu action {id}"); + } + let browse = menu.children.iter().find(|item| item.id == "appearance.library").unwrap(); + crate::context_menu::run_item(&mut h.app, browse, at); + assert!(h.app.dialog.is_none()); + assert!(!h.app.render_workspace.view.assign.painting); +} + +#[test] +fn render_assign_gestures_labels_translate_in_all_five_catalogs() { + for language in ["en", "ja", "zh", "de", "ko"] { + let locale = crate::i18n::Locale::for_language(language); + for id in [ + "cmd.appearance_copy", + "cmd.appearance_paste", + "render.assign_help", + "render.browse_looks", + "render.choose_look", + "render.look_applied", + "render.painting_with", + "render.pick_up_prompt", + "render.recent_looks", + "render.remove_override", + "cmd.appearance_favorite", + "render.replace_all", + "render.replace_with", + "render.look_material", + "render.hover_look", + ] { + assert_ne!(locale.text(id), id, "{language}: {id}"); + } + assert!(locale.format("render.painting_with", &[("name", "Sample")]).contains("Sample")); + } +} + +#[test] +fn render_lighting_group_selection_opens_ordered_editor_and_plus_still_adds() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + let before = h.app.session.doc.clone(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:lighting:editor").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + let sections: Vec<_> = ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] + .iter() + .map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()) + .collect(); + assert!(sections.windows(2).all(|pair| pair[0].bottom() <= pair[1].top())); + h.step(&json!({"click":{"handle":"render:tree:lights:add"}})).unwrap(); + assert!(light::rows(&h.app).unwrap().iter().any(|l| l.geometry.kind() == "area")); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("area:0".into())); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_methods_show_reasons_and_budgets_without_changing_method_or_design() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + if method == ImageMethod::GpuRaytrace { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{}}}}})).unwrap(); + setups::load(&mut h.app); + } else { + h.app.render_workspace.view.method = method; + } + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + let before = h.app.session.doc.clone(); + let revision = h.app.session.revision; + h.frames(3); + for section in ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(section))).is_some()); + } + let reason = match method { + ImageMethod::Raster => "render.method_limit_raster", + ImageMethod::CpuRaytrace => "render.lighting_samples_need_area", + ImageMethod::GpuRaytrace => "render.light_gpu_punctual", + }; + assert!(crate::scenario::rect_of(&format!("dialog:note:{reason}")).is_some()); + if method == ImageMethod::GpuRaytrace { + assert!(crate::scenario::rect_of("dialog:note:render.lighting_shadow_cpu").is_some()); + assert!(crate::scenario::rect_of("dialog:note:render.lighting_samples_cpu").is_some()); + } + assert!(h.widget(h.app.tr("render.lighting_budget_help")).is_some()); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.session.revision, revision); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn render_assign_gestures_stage_tools_and_selection_actions_use_commands() { + let (mut h, _) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + assert!(crate::workspace::destination(solidcraft_engine::find_command(id).unwrap()).is_none()); + } + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!(pill.width() < 200.0, "{pill:?}"); + for index in 0..4 { + assert!(pill.contains_rect(crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap())); + } + h.step(&json!({"click":{"handle":"render:stage:appearance.pick_up"}})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"click":{"handle":"selection:action:0"}})).unwrap(); + assert!(crate::scenario::rect_of("render:look_chain").is_some()); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), 1); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert!(h.app.preferences.render_library_favorites.is_empty()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"selection:action:1"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.step(&json!({"click":{"handle":"dialog:Replace with"}})).unwrap(); + h.step(&json!({"widget":"Copper"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "Copper"); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"selection:action:3"}})).unwrap(); + assert!(!h.app.session.body_visible("Plate")); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:selection").is_none()); + assert!(crate::scenario::rect_of("render:stage:appearance.paint").is_none()); +} + +#[test] +fn render_assign_gestures_replacement_draft_cannot_cross_a_document_edit() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.app.start("appearance.replace"); + assert!(assign::replacement_open(&h.app)); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Red"})).unwrap(); + h.frames(3); + assert!(!assign::replacement_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); +} + +#[test] +fn render_assign_gestures_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.cylinder", json!({"body_name":"Boss","radius":10,"height":20})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Boss"],"appearance":"Aluminum - Anodized Blue"})).unwrap(); + h.app.run("solid.sphere", json!({"body_name":"Knob","center":[0,0,28],"radius":8})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Knob"],"appearance":"Copper"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + h.app.pending_fit = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..48 { + crate::scenario::clear_handles(); + let events = h + .app + .viewport + .rect + .and_then(|rect| crate::viewport::projection(&h.app, rect).to_screen(solidcraft_engine::geom::Vec3::new(0.0, 0.0, 28.0))) + .filter(|_| frame == 1) + .map(|at| vec![egui::Event::PointerMoved(at)]) + .unwrap_or_default(); + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), time: Some(frame as f64 / 60.0), events, ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 47 { + assert!( + crate::scenario::rect_of("kit:tooltip").is_some(), + "the model hover uses the standard kit tooltip; hover: {:?}, pointer: {:?}", + h.app.viewport.hover, + ctx.pointer_hover_pos() + ); + let tooltip = crate::scenario::rect_of("kit:tooltip").unwrap(); + assert!(tooltip.distance_to_pos(ctx.pointer_hover_pos().unwrap()) < Tokens::get().control_height, "{tooltip:?}"); + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!((150.0..170.0).contains(&pill.width()), "{pill:?}"); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_GESTURES_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("look-controls-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_lights_each_kind_contains_design_sections_and_real_parameter_fields_in_order() { + for (method, kind) in + [("cpu_raytrace", "area"), ("cpu_raytrace", "point"), ("cpu_raytrace", "directional"), ("gpu_path", "area"), ("gpu_path", "directional")] + { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + let options = if method == "gpu_path" { json!({"lighting":{}}) } else { json!({"lights":[],"punctual_lights":[],"area_lights":[]}) }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":method,"options":options}}})).unwrap(); + setups::load(&mut h.app); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":kind}))).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let before = h.app.session.doc.clone(); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + let mut sections = vec!["render.light_position"]; + if kind == "area" { + sections.push("render.lighting_shape"); + } + if kind == "point" { + sections.push("render.lighting_falloff"); + } + sections.push("render.light_behaviour"); + let rects: Vec<_> = sections.iter().map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()).collect(); + assert!(rects.windows(2).all(|pair| pair[0].bottom() <= pair[1].top()), "{method}/{kind}"); + let fields: &[&str] = match kind { + "area" => &["width_mm", "height_mm", "radiance:0", "edge_u_mm:0", "edge_v_mm:0", "position_mm:0"], + "point" => &["reference_distance_mm", "minimum_distance_mm", "position_mm:0"], + _ => &["direction:0", "direction:1", "direction:2"], + }; + for field in fields { + assert!(crate::scenario::rect_of(&format!("render:light:{field}")).is_some(), "{method}/{kind}: {field}"); + } + for key in ["render.lighting_solo", "render.lighting_mute", "render.light_duplicate", "render.light_delete"] { + assert!(h.widget(h.app.tr(key)).is_some(), "{method}/{kind}: {key}"); + } + assert!(crate::scenario::rect_of("dialog:note:render.light_place_pending").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn render_lighting_preset_materialises_values_and_replacement_requires_review_consent() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + // Confirm's primary action is disabled until its explicit acknowledgement. + h.step(&json!({"widget":h.app.tr("render.lighting_consent")})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_apply")})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_some()); + assert!(h.app.render_workspace.view.raytrace.lights.is_none()); + let lights = light::rows(&h.app).unwrap(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:lighting:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.lights.as_ref().unwrap().len(), lights.len()); + let materialised = light::rows(&h.app).unwrap(); + for (before, after) in lights.iter().zip(materialised) { + assert_eq!(before.colour, after.colour); + assert_eq!(before.intensity, after.intensity); + } + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); +} + +#[test] +fn render_lighting_hostile_numeric_edits_refuse_without_panics_or_partial_state() { + let mut h = render_lights_fixture(); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":"point"}))).unwrap(); + let before = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + for set in + [json!({"reference_distance_mm":1e300}), json!({"minimum_distance_mm":-1}), json!({"position_mm":[1e300,0,0]}), json!({"direction":[0,0,0]})] + { + assert!(light::edit(&mut h.app, "render.lights.set", Some("point:0"), Some(set)).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + } + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_shadow_edits_are_undoable_and_preset_reviews_reject_changed_drafts() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.lighting_shadows")})).unwrap(); + assert!(!h.app.render_workspace.view.raytrace.shadows); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(matches!(&h.app.session.doc.render.setups["Studio"].job, + Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options }) if !options.shadows)); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, before); + h.frames(3); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_some()); + h.app.render_workspace.view.draft.width = 1200; + h.frames(3); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_none()); + assert_eq!(h.app.session.doc, before); + assert_eq!(h.app.render_workspace.view.draft.width, 1200); +} + +#[test] +fn geometry_budget_follows_the_device_buffer_limit_and_keeps_the_web_cap() { + // The standard 256 MiB device buffers: 2 GiB, far past the old fixed 128 MiB. + assert_eq!(geometry_budget(256 << 20, false), 2 << 30); + assert!(admit_geometry(129 << 20, geometry_budget(256 << 20, false)).is_ok()); + // A smaller device gets less, a larger one no more than the ceiling. + assert_eq!(geometry_budget(64 << 20, false), 512 << 20); + assert_eq!(geometry_budget(u64::MAX, false), DESKTOP_GEOMETRY_CEILING); + for device in [0, 256 << 20, u64::MAX] { + let budget = geometry_budget(device, true); + assert_eq!(budget, 128 << 20); + assert!(admit_geometry(budget, budget).is_ok()); + assert!(admit_geometry(budget + 1, budget).is_err()); + } +} + +#[test] +fn geometry_refusal_reports_scene_size_limit_and_recovery() { + use solidcraft_engine::{ + geom::{Aabb3, Mesh}, + render::ProductMesh, + }; + let scene = ProductScene { + meshes: vec![ProductMesh { + name: "Synthetic assembly".into(), + mesh: Arc::new(Mesh { triangles: vec![[0; 3]; 1 << 20], ..Default::default() }), + color: [128; 3], + opacity: 1.0, + surface: Some( + solidcraft_engine::render::surface::OpaqueSurface::new(solidcraft_engine::geom::Vec3::new(0.5, 0.5, 0.5), 0.0, 0.5, 1.5).unwrap(), + ), + transmission: None, + faces: Vec::new(), + }], + bounds: Aabb3::EMPTY, + }; + let error = gpu_scene_with_budget(&scene, WEB_GEOMETRY_BYTES).err().unwrap(); + assert!(error.contains("144.0 MiB"), "{error}"); + assert!(error.contains("128.0 MiB"), "{error}"); + assert!(error.contains("Hide bodies in Design"), "{error}"); + let refused = upload_refusal(144 << 20, "Out of Memory"); + assert!(refused.contains("144.0 MiB") && refused.contains("Out of Memory") && refused.contains("Hide bodies in Design"), "{refused}"); +} + +#[test] +fn previous_geometry_budget_restores_the_fixed_limit() { + for web in [false, true] { + for device in [64 << 20, 256 << 20, u64::MAX] { + let device_budget = geometry_budget(device, web); + assert_eq!(preferred_geometry_budget(device_budget, false), device_budget); + let previous = preferred_geometry_budget(device_budget, true); + assert_eq!(previous, MAX_GEOMETRY_BYTES as u64); + assert!(admit_geometry(previous, previous).is_ok()); + assert!(admit_geometry(previous + 1, previous).is_err()); + } + } +} + +#[test] +fn geometry_budget_change_retries_cached_admission_without_document_changes() { + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let bytes = preview_upload_plan(&scene, usize::MAX).unwrap().bytes().unwrap() as u64; + let mut state = State::default(); + assert!(state.prepare_preview((7, 123, 99, bytes - 1), || Ok(scene.clone())).is_err()); + state.prepare_preview((7, 123, 99, bytes), || Ok(scene)).unwrap(); + assert_eq!(state.preview_upload_bytes, Some(bytes as usize)); + assert!(state.scene_error.is_none()); +} + +#[test] +fn cpu_interactive_cold_assembly_binding_refuses_without_preparing_world() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.session.execute("component.create", &json!({"name":"Part","grounded":false})).unwrap(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let initial = h.app.session.world_state(); + let name = initial.bodies[0].name.clone(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + // Exact placement metadata changes without running a UI paint or world query. + let occurrence: u64 = serde_json::from_value(component["occurrence"].clone()).unwrap(); + h.app.session.pending_moves.insert(occurrence, solidcraft_engine::doc::IDENTITY); + assert!(h.app.session.interactive_cached_world_state().is_none()); + let model = h.app.session.model.state(); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(h.app.session.interactive_cached_world_state().is_none(), "binding proof must not prepare cold placements"); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + cpu::set_reflection(&mut h.app, &name, None).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(h.app.session.interactive_cached_world_state().is_none(), "empty reflections need no prepared world"); +} + +#[test] +fn interactive_egui_clock_is_finite_monotonic_and_requires_no_platform_instant() { + use std::time::Duration; + let mark = Duration::from_secs(2); + for time in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1.0, f64::MAX] { + assert_eq!(interactive::monotonic(mark, time), mark); + } + assert_eq!(interactive::monotonic(mark, 3.5), Duration::from_millis(3500)); +} + +fn interactive_control_frame(h: &mut Harness, time: f64, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + events, + ..Default::default() + }, + |ui| { + ui.set_width(300.0); + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +#[test] +fn interactive_is_opt_in_and_refuses_raster_or_cooperative_hosts_without_fallback() { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + let document = h.app.session.doc.clone(); + let path = matches!(h.app.render_workspace.path_host, PathHost::NotStarted); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted), path); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_ui_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":8,"height":4,"body_name":"Subject"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host)).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + // Do not enter through a deferred GPU factory in CPU-only adapter tests. + h.app.ui.tab = "RENDER".into(); + h +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_test_cpu_branch(h: &mut Harness, case: &str) -> bool { + let host = h.app.session.render_job_host().unwrap(); + let supported = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + if supported { + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=true"); + return true; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + false +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_runtime_builder_preserves_hdr_ev_and_muted_lights_without_final_dimension_admission() { + let mut h = interactive_ui_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"cpu_raytrace"}}})).unwrap(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.raytrace.shadows = false; + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let before = h.app.session.doc.clone(); + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["width"], 3840, "engine must fit before admission"); + assert!(wire["settings"]["job"].is_null()); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.5); + assert_eq!(wire["raytrace"]["shadows"], false); + assert_eq!(wire["raytrace"]["lights"][0]["intensity"], 0.0); + assert_eq!(wire["environment"]["resource"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert!(wire["environment"].get("path").is_none()); + assert!(raw_image_request(&h.app).is_err(), "final admission must remain unchanged"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_control_frame(&mut h, 0.0, vec![]); + let first = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_control_frame(&mut h, 0.5, vec![]); + let camera = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(camera > first); + h.app.render_workspace.view.raytrace.shadows = false; + interactive_control_frame(&mut h, 1.0, vec![]); + let transport = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(transport > camera); + h.app.session.visibility.hidden_bodies.push("Subject".into()); + interactive_control_frame(&mut h, 1.5, vec![]); + let visibility = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(visibility > transport); + assert_eq!(h.app.session.revision, revision, "all three edits deliberately bypass CAD revision"); + assert_eq!(interactive::inspect(&h.app)["pending_capture"], false, "before_paint never dispatches a worker"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots") { + return; + } + interactive_control_frame(&mut h, 0.0, vec![]); + let mut time = 0.01; + for action in ["on", "pause", "resume", "off"] { + let rect = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + let at = rect.center(); + interactive_control_frame( + &mut h, + time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }, + ], + ); + time += 0.01; + interactive_control_frame(&mut h, time, vec![]); + time += 0.01; + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + enter(&mut h.app, false).unwrap(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); +} + +#[test] +fn interactive_reset_retains_one_real_receiver_and_discards_its_late_foreign_error() { + use solidcraft_engine::render::job::interactive::{Interactive, VisualRevision}; + use std::{sync::mpsc, time::Duration}; + let mut h = Harness::new(); + let mut controller = Interactive::new(7001); + controller.enable(VisualRevision { scene_generation: 0, visual_revision: 1 }, Duration::ZERO).unwrap(); + let ticket = controller.capture(Duration::from_millis(200)).unwrap().unwrap(); + let (sender, receiver) = mpsc::channel(); + h.app.render_workspace.interactive.pending = Some(interactive::Pending { uid: h.app.session.uid, ticket, receiver }); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending()); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending(), "a second document reset cannot orphan the pending worker"); + sender.send(Err("late old capture".into())).unwrap(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(interactive::inspect(&h.app)["error"].is_null()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_background_final_metadata_suspends_without_cancelling_queued_final() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_background_final_metadata_suspends_without_cancelling_queued_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + let job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + serde_json::from_value::(reply["job"].clone()).unwrap() + }; + let retained = host.admitted_bytes(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + let background = h.app.docs.background().next().unwrap(); + assert_eq!(background.render_job_handle(job).unwrap().status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert_eq!(host.admitted_bytes(), retained); + assert!(!h.app.render_workspace.interactive.pending()); +} + +// Native CPU acceptance of the real M3 dispatcher; no native window or GPU. +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveHeldCallback { + job: solidcraft_engine::render::job::JobHandle, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool, paint: bool) -> (egui::FullOutput, bool) { + let mut painted = false; + let output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + ..Default::default() + }, + |ui| { + // tick dispatches through the actual production spawn(Snapshot) path. + // Do not run a second refresh here: the callback must be held before UI delivery. + if dispatch { + interactive::tick(&mut h.app, ui.ctx()); + } else { + interactive::before_paint(&mut h.app, ui.ctx()); + } + if paint { + painted = interactive::paint(&h.app, ui, ui.max_rect()); + } + }, + ); + (output, painted) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_clear_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool) { + let (mut output, painted) = interactive_acceptance_frame(h, time, dispatch, false); + assert!(!painted); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_hold_real_completed_callback(h: &mut Harness) -> InteractiveHeldCallback { + use solidcraft_engine::render::job::Phase; + use std::{sync::mpsc, time::Duration}; + // The actual capture thread owns and invokes the real engine Snapshot.run. + // This test only withholds its actual returned message from the UI consumer. + // No tick/paint is called while the receiver is temporarily removed. + let mut pending = h.app.render_workspace.interactive.pending.take().expect("production tick must start a capture"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("real snapshot worker did not return"); + assert!(matches!(&reply, Ok(true)), "real snapshot must be adopted: {reply:?}"); + let job = + interactive::test_current(&h.app).expect("Interactive controller access must succeed").expect("Snapshot.run must attach the real CPU job"); + assert_eq!(job.id(), pending.ticket.job_id()); + assert_eq!(pending.uid, h.app.session.uid); + let status = job.wait_timeout(Duration::from_secs(60)).expect("real CPU job did not finish"); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(status.error.is_none()); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive.unwrap().samples_per_pixel, 16); + assert_eq!((status.request.width, status.request.height), (16, 16)); + let frame = job.frame().unwrap().expect("Completed requires real frame bytes"); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert_eq!(frame.info.job, job.id()); + assert_eq!(frame.info.scene_generation, pending.ticket.revision().scene_generation); + assert!(!frame.png().is_empty()); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + { + use sha2::{Digest, Sha256}; + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + } + assert!(job.preview().unwrap().is_none(), "terminal image is distinct from the intermediate preview slot"); + // The renderer's Completed progress is normalized to 1/1, not an SPP counter. + assert_eq!((status.progress.done, status.progress.total), (1, 1)); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveHeldCallback { job, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_assert_final_export_isolation(h: &mut Harness, job: &solidcraft_engine::render::job::JobHandle) { + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.render_workspace.image.is_none()); + assert!(!studio::linear_export_available(&h.app)); + let registry_error = h.app.session.render_job_handle(job.id()).err().expect("preview must not enter the final registry"); + assert!(registry_error.to_string().contains("WrongOwner"), "{registry_error}"); + let path = h.dir.join(format!("interactive-not-exportable-{}-{}.png", job.id().session, job.id().serial)); + assert!(!path.exists()); + let error = h.app.session.execute("render.export", &json!({"job":job.id(),"path":path,"format":"png"})).unwrap_err(); + // Require the actual preview/final ownership guard, rather than accepting a + // path/format/refusal error which would not prove final-registry isolation. + assert!(error.to_string().contains("WrongOwner"), "{error}"); + assert!(!path.exists()); + assert!(job.frame().unwrap().is_some(), "export refusal must not consume preview pixels"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported") { + return; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + assert!(!h.app.render_workspace.interactive.pending()); + // Explicit egui time relative to the inherited clock crosses the 200 ms group; + // this does not wait on wall time or sleep to make a race likely. + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(interactive::test_cache(&h.app).is_none(), "worker completion alone must not fabricate a UI cache"); + let frame = held.job.frame().unwrap().unwrap(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + assert!(!h.app.render_workspace.interactive.pending()); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.job, held.job.id()); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!(samples, 16); + assert!(complete, "completed16 must use the completed key, still only in the provisional UI cache"); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + let uploaded = &output.textures_delta.set.get(&texture).expect("first real PNG publication must upload a texture").first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty())) + ); + let (mut repaint, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted); + assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); + assert!(!repaint.textures_delta.set.contains_key(&texture), "unchanged JobId/sequence/revision must reuse its texture"); + repaint.textures_delta.clear(); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending(), "Off retains the single undrained receiver"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 1.0, true); + let pending = h.app.render_workspace.interactive.pending.as_ref().unwrap(); + assert_eq!(pending.ticket.job_id(), held.job.id(), "reactivation cannot replace an undrained capture"); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 1.1, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(!painted, "Pause may retain already displayed pixels, but cannot adopt this unseen callback"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let old = held.job.id(); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert_eq!(h.app.session.revision, revision); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + let newer = interactive_hold_real_completed_callback(&mut h); + assert_ne!(newer.job.id(), old); + newer.sender.send(newer.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, newer.job.id()); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &newer.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveRecoveryReply { + id: solidcraft_engine::render::job::JobId, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_hold_reply(h: &mut Harness) -> InteractiveRecoveryReply { + use std::{sync::mpsc, time::Duration}; + let mut pending = h.app.render_workspace.interactive.pending.take().expect("actual tick must dispatch a Snapshot"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("actual capture worker did not return"); + let id = pending.ticket.job_id(); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveRecoveryReply { id, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_missing_hdr(h: &mut Harness) -> (std::path::PathBuf, Vec) { + let path = h.dir.join("interactive-recovery-original.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert!(interactive_request(&h.app).is_ok(), "valid inspected metadata must reach actual worker preparation"); + std::fs::remove_file(&path).unwrap(); + (path, bytes) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_error(h: &mut Harness, time: f64) -> serde_json::Value { + interactive_clear_acceptance_frame(h, time, true); + let status = interactive::inspect(&h.app); + assert_eq!(status["phase"], "Error"); + assert!(status["error"].as_str().is_some_and(|error| !error.is_empty())); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + status["error"].clone() +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_success(h: &mut Harness, dispatch_time: f64, paint_time: f64) -> solidcraft_engine::render::job::JobId { + interactive_clear_acceptance_frame(h, dispatch_time, true); + let held = interactive_hold_real_completed_callback(h); + let id = held.job.id(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(h, paint_time, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, id); + interactive_assert_final_export_isolation(h, &held.job); + id +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover") { + return; + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 2.0), error); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 2.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_recovery_require_success(&mut h, epoch + 2.301, epoch + 2.4); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit() { + for recovery in ["resume", "edit"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let request = interactive_request(&h.app).unwrap(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.as_ref().is_err_and(|error| !error.is_empty()), "missing HDR must fail actual preparation: {:?}", failed.reply); + assert!( + interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none(), + "preparation failure is not an admitted job-status failure" + ); + let failed_id = failed.id; + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + for offset in [0.6, 1.0] { + assert_eq!(interactive_recovery_require_error(&mut h, epoch + offset), error, "unchanged input must not retry"); + } + if recovery == "resume" { + std::fs::write(&path, bytes).unwrap(); + assert_eq!(interactive_request(&h.app).unwrap(), request, "repairing external bytes is not a UI intent edit"); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.1), error, "file repair alone cannot silently resume"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } else { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + } + let new_id = interactive_recovery_require_success(&mut h, epoch + 1.301, epoch + 1.4); + assert_ne!(new_id, failed_id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_user_pause_survives_error_fixing_edit_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_user_pause_survives_error_fixing_edit_until_explicit_resume") { + return; + } + let _ = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + interactive_recovery_require_error(&mut h, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.4, false); + interactive_clear_acceptance_frame(&mut h, epoch + 2.0, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 2.201, epoch + 2.3); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(held.reply.unwrap(), "native Snapshot/CPU work really finished before transport failure"); + // Deliberately close the actual std channel instead of fabricating an Err. + // This covers consumer Disconnected, not a claim that the native worker crashed. + drop(held.sender); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert_eq!(error, h.app.tr("render.interactive_error")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent() { + for recovery in ["edit", "resume"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + if recovery == "edit" { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + } else { + std::fs::write(path, bytes).unwrap(); + // First consume clock input without consuming the still-held reply. + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + assert_eq!( + h.app.render_workspace.interactive.pending.as_ref().unwrap().ticket.job_id(), + failed.id, + "one old receiver still blocks new dispatch" + ); + failed.sender.send(failed.reply).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.6, false); + assert!(interactive::inspect(&h.app)["error"].is_null(), "actual old failure must be discarded"); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + let new_id = interactive_recovery_require_success(&mut h, epoch + 0.7, epoch + 0.8); + assert_ne!(new_id, failed.id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.4), error); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).unwrap_err().contains(h.app.tr("render.interactive_final_active"))); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + // Only the test's explicit owner cancellation ends its queued final. + final_job.cancel().unwrap(); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.5), error); + std::fs::write(path, bytes).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.701, epoch + 0.8); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Cancelled); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_actual_png_display_cap_error_latches_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_actual_png_display_cap_error_latches_until_explicit_resume") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + held.sender.send(held.reply).unwrap(); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.3), + ..Default::default() + }, + |ui| { + // Real decoder admission against an invalid display capability; retain + // the real CPU PNG and restore input before fonts/end-frame processing. + let previous = ui.ctx().input(|input| input.max_texture_side); + ui.ctx().input_mut(|input| input.max_texture_side = 0); + interactive::before_paint(&mut h.app, ui.ctx()); + ui.ctx().input_mut(|input| input.max_texture_side = previous); + assert!(!interactive::paint(&h.app, ui, ui.max_rect())); + }, + ); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.4); + assert_eq!(error, h.app.tr("render.error_display_dimensions")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error, "restoring display cap alone cannot rearm capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4), + ..Default::default() + }, + |ui| { + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + assert!(text.contains("16 × 16 px"), "actual cached dimensions must be visible: {text}"); + assert!(!text.contains("3840 × 2160 px"), "final draft cannot relabel the captured preview"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + let (info, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((info.width, info.height, samples, complete), (16, 16, 16, true)); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn interactive_card_bounds_avoid_current_selection_docks_and_navigation_at_wide_and_narrow_sizes() { + for (width, height) in [(1600.0, 1000.0), (760.0, 700.0)] { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.shell.workspace_panels.clear(); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + let content = egui::Rect::from_min_max(egui::pos2(0.0, 132.0), egui::pos2(width, height - 56.0)); + let left = egui::Rect::from_min_max(egui::pos2(8.0, 140.0), egui::pos2(274.0, height - 64.0)); + let right = egui::Rect::from_min_max(egui::pos2(width - 313.0, 140.0), egui::pos2(width - 8.0, height - 64.0)); + crate::shell::register_panel(&mut h.app, "render:browser", Some(left), Some(crate::ui_kit::Edge::Left)); + crate::shell::register_panel(&mut h.app, "render:inspector", Some(right), Some(crate::ui_kit::Edge::Right)); + let centre = (left.right() + right.left()) / 2.0; + let navigation = egui::Rect::from_center_size(egui::pos2(centre, content.bottom() - 28.0), egui::vec2(120.0, 40.0)); + let axis = egui::Rect::from_min_size(egui::pos2(right.left() - 110.0, content.top()), egui::vec2(110.0, 110.0)); + h.app.viewport.layout = + Some(crate::viewport_layout::Layout { viewport, drawable: content, content, axis_view: axis, navigation, confirm: egui::Rect::NOTHING }); + // A new measured selection replaces the old one in this very frame. + // Both positions cut across the old top-centre status/action region. + for y in [content.top() + 90.0, content.top() + 180.0] { + let selection = egui::Rect::from_center_size(egui::pos2(centre, y), egui::vec2(180.0, 34.0)); + crate::shell::register_panel(&mut h.app, "render:selection", Some(selection), None); + let available = interactive::overlay_bounds(&h.app, content); + assert!(available.is_positive(), "{width}: no space for the Interactive card"); + assert!(content.contains_rect(available), "{width}: {available:?} outside {content:?}"); + for occupied in [selection, left, right, navigation, axis] { + assert!(!available.intersect(occupied).is_positive(), "{width}: {available:?} overlaps {occupied:?}"); + } + assert!(available.width() >= Tokens::get().control_height + Tokens::get().space_8); + } + assert!(!interactive::overlay_bounds(&h.app, egui::Rect::NOTHING).is_positive()); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0, left); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0, right); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_overlay_keeps_real_selection_actions_and_pause_off_targets_accessible_without_dispatch() { + fn overlay_frame(h: &mut Harness, size: egui::Vec2, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, + |ui| { + // The shell clears Render reservations at the start of a real frame. + // Keep the already measured docks but never leave a previous selection + // rectangle that could make the moved-call regression pass by accident. + h.app.shell.workspace_panels.remove("render:selection"); + crate::render_ui::overlays(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); + } + for size in [egui::vec2(1600.0, 1000.0), egui::vec2(760.0, 700.0)] { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_overlay_selection_controls") { + return; + } + h.call("ui.resize", json!({"width":size.x as u32,"height":size.y as u32})); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Subject".into()}]})).unwrap(); + h.frames(4); + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let selection_before = crate::scenario::rect_of("render:selection").unwrap(); + let actions_before: Vec<_> = (0..4).map(|index| crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap()).collect(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let docks = h.app.shell.workspace_panels.clone(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Paint the production overlays, but never tick or run a Snapshot worker. + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let card = crate::scenario::rect_of("render:interactive-card").unwrap(); + let selection = crate::scenario::rect_of("render:selection").unwrap(); + assert_eq!(selection, selection_before, "our card must not move the author's toolbar"); + assert!(!card.intersect(selection).is_positive()); + let content = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + assert!(content.contains_rect(card), "{size:?}: {card:?} outside {content:?}"); + for (index, before) in actions_before.iter().enumerate() { + let action = crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap(); + assert_eq!(&action, before); + assert!(selection.contains_rect(action)); + assert!(!card.intersect(action).is_positive(), "author action {index} is occluded"); + } + for action in ["pause", "off"] { + let target = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + assert!(card.contains_rect(target), "{size:?}: {action} clipped outside {card:?}: {target:?}"); + assert!(!selection.intersect(target).is_positive()); + } + for action in ["pause", "off"] { + let at = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap().center(); + for pressed in [true, false] { + overlay_frame( + &mut h, + size, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + overlay_frame(&mut h, size, vec![]); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert!(!h.app.render_workspace.interactive.pending()); + } + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + for id in ["render:browser", "render:inspector", "render:appearances", "render:shots_strip"] { + let current = h.app.shell.workspace_panels.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + let before = docks.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + assert_eq!(current, before, "{id}"); + } + // With Interactive Off, the author's real hit target still dispatches. + let favorite_count = h.app.preferences.render_library_favorites.len(); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), favorite_count + 1); + assert_eq!(crate::scenario::rect_of("render:selection").unwrap(), selection_before); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_waiting_show_text(h: &mut Harness, time: f64) -> String { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(time), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + output.textures_delta.clear(); + text +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "the fallback refusal is the real no-GPU positive control"); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + let fallback = h.app.tr("render.error_gpu_preview").to_string(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.01).contains(&fallback)); + + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let waiting = interactive_waiting_show_text(&mut h, epoch + 0.02); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!waiting.contains(&fallback), "real show must not enter the model-preview refusal while waiting"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "show/before_paint must not dispatch"); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.025, false, true); + assert!(!painted, "reserving the canvas does not claim an image was painted"); + output.textures_delta.clear(); + + h.app.render_workspace.view.result = true; + assert!(!interactive::awaiting_current_frame(&h.app), "the result view keeps priority"); + h.app.render_workspace.view.result = false; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.ui.tab = "MODEL".into(); + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.ui.tab = "RENDER".into(); + + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.03).contains(&fallback), "pause before any image keeps its existing fallback"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + assert!(!interactive_waiting_show_text(&mut h, epoch + 0.04).contains(&fallback)); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let error = interactive_waiting_show_text(&mut h, epoch + 0.05); + assert_eq!(interactive::inspect(&h.app)["phase"], "Error"); + assert!(!interactive::inspect(&h.app)["error"].is_null()); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(error.contains(&fallback), "an input error keeps the existing model-preview route"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.06).contains(&fallback)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let old = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + assert!(!interactive::awaiting_current_frame(&h.app)); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let document = h.app.session.doc.clone(); + + h.app.render_workspace.view.raytrace.shadows = false; + let text = interactive_waiting_show_text(&mut h, epoch + 0.4); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_cache(&h.app).is_none(), "the previously accepted image must be dropped"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.41, false, true); + assert!(!painted, "old pixels cannot become current while the new request waits"); + output.textures_delta.clear(); + + let new = interactive_recovery_require_success(&mut h, epoch + 0.901, epoch + 1.0); + assert_ne!(new, old); + assert!(!interactive::awaiting_current_frame(&h.app)); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), new); + assert!(!job.status().unwrap().request.raytrace.as_ref().unwrap().shadows); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "presentation and runtime settings do not author CAD state"); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let (before, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.raytrace.shadows = false; + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted, "explicit pause still permits the already displayed image"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app)); + let (after, after_samples, after_complete, after_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((after.job, after.png_sha256), (before.job, before.png_sha256)); + assert_eq!((after_samples, after_complete, after_texture), (samples, complete, texture)); + + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let text = interactive_waiting_show_text(&mut h, epoch + 0.5); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.51, false, true); + assert!(!painted); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.cam.yaw += 0.2; + let text = interactive_waiting_show_text(&mut h, epoch + 0.3); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::awaiting_current_frame(&h.app)); + interactive_assert_final_export_isolation(&mut h, &held.job); + + let old_uid = h.app.session.uid; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_ne!(h.app.session.uid, old_uid); + assert!(!interactive::awaiting_current_frame(&h.app), "a foreign context cannot reserve the canvas even before refresh"); + h.app.ui.tab = "RENDER".into(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.5, false); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(!painted, "neither the old image nor its waiting presentation belongs to another document"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + assert!(interactive::awaiting_current_frame(&h.app)); + let before = interactive::inspect(&h.app); + assert_eq!(before["enabled"], true); + assert_eq!(before["phase"], "Updating"); + assert_eq!(before["paused"], false); + assert!(before["error"].is_null()); + assert!(!h.app.render_workspace.view.result); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + + let uid = h.app.session.uid; + let document = h.app.session.doc.clone(); + let mut foreign = Session::new((*document).clone()); + assert_ne!(foreign.uid, uid); + // Use real engine Sessions and the same ownership swap as documents::swap_in. + // Deliberately omit the UI reset: it would otherwise mask is_current's guard. + // Retain the original Session so its registry/controller lifetime stays live. + std::mem::swap(&mut h.app.session, &mut foreign); + assert_ne!(h.app.session.uid, uid); + assert_eq!(h.app.session.doc, document, "equal design contents do not confer session ownership"); + assert_eq!(interactive::inspect(&h.app), before, "the context is still enabled, not reset or refreshed"); + assert!(active(&h.app)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(!h.app.render_workspace.view.result); + assert!(!interactive::awaiting_current_frame(&h.app), "a live context owned by another Session cannot reserve the canvas"); + assert_eq!(interactive::inspect(&h.app), before, "the predicate must remain read-only"); + + std::mem::swap(&mut h.app.session, &mut foreign); + assert_eq!(h.app.session.uid, uid); + assert_eq!(interactive::inspect(&h.app), before); + assert!(interactive::awaiting_current_frame(&h.app), "restoring the real owner proves the same context remained live"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!h.app.render_workspace.interactive.pending()); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_frame(h: &mut Harness, time: &mut f64, events: Vec) { + *time += 1.0 / 60.0; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_fixture(case: &str) -> Option<(Harness, f64, egui::Pos2)> { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, case) { + return None; + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + h.app.preferences.nav = "fusion".into(); + h.app.preferences.zoom_to_cursor = false; + h.app.preferences.smooth_wheel_zoom = false; + let mut time = interactive::test_clock(&h.app).as_secs_f64(); + for _ in 0..3 { + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + } + let rect = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, rect); + let at = projection.to_screen(h.app.cam.target).unwrap(); + assert!(!crate::shell::covered(&h.app, at)); + assert!( + crate::viewport::pick(&h.app, &projection, at).iter().any(|hit| matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject")) + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + Some((h, time, at)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_click(h: &mut Harness, time: &mut f64, at: egui::Pos2, button: egui::PointerButton, mods: egui::Modifiers) { + interactive_canvas_input_frame(h, time, vec![egui::Event::ModifiersChanged(mods), egui::Event::PointerMoved(at)]); + for pressed in [true, false] { + interactive_canvas_input_frame(h, time, vec![egui::Event::PointerButton { pos: at, button, pressed, modifiers: mods }]); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none(), "hidden geometry cannot advertise a hover target"); + assert!(h.app.session.selection.is_empty(), "plain/add/toggle clicks cannot select invisible geometry"); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none(), "a right click cannot open a menu for hidden geometry"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending(), "show never dispatches a capture"); + + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_some(), "the same real hit remains available with Interactive Off"); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_some(), "the same native canvas click still opens the normal body menu"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work() { + for sampling in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work") + else { + return; + }; + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let look = h.app.render_workspace.view.assign.look.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.assign.look, look, "no hidden face is sampled"); + assert_eq!(h.app.render_workspace.view.assign.sampling, sampling); + assert_eq!(h.app.render_workspace.view.assign.painting, !sampling); + + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + if sampling { + assert!(!h.app.render_workspace.view.assign.sampling); + assert!(h.app.render_workspace.view.assign.painting, "Off permits real sampling to arm paint"); + } else { + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target") + else { + return; + }; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "positive control: real Off drag reached geometry"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_current_and_paused_images_keep_canvas_paint_and_final_observation() { + for paused in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_current_and_paused_images_keep_canvas_paint_and_final_observation") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + if paused { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + let undo = h.app.session.undo.len(); + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + if paused { + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::awaiting_current_frame(&h.app)); + } else { + assert!(interactive::test_cache(&h.app).is_none(), "the final observation sees the appearance edit made by this canvas click"); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + assert!(interactive::test_cache(&h.app).is_some(), "before show, old UI state has not yet observed the visible setting edit"); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.session.selection.is_empty(), "the release cannot pick using the previous frame's cache/phase"); + assert!(h.app.viewport.hover.is_none()); + + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, 3.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert_ne!(h.app.cam, camera, "the waiting guard must not swallow real shared camera navigation"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "neither observation dispatches Snapshot"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(accepted.job, job); + assert_eq!((samples, complete), (16, true)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(!h.app.render_workspace.interactive.pending()); + + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let selection = h.app.session.selection.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "the real drag must start over the accepted CPU image"); + assert!(assign::hover(&h.app).is_some()); + let (pressed, pressed_samples, pressed_complete, pressed_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((pressed.job, &pressed.png_sha256), (job, &accepted.png_sha256)); + assert_eq!((pressed_samples, pressed_complete, pressed_texture), (samples, complete, texture)); + assert!(!interactive::awaiting_current_frame(&h.app)); + + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + // No tick, show, refresh, move or other UI frame between this edit and release. + // The old image/drag are still present, so only same-frame observation can reject the drop. + let (before_release, _, _, before_release_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((before_release.job, &before_release.png_sha256, before_release_texture), (job, &accepted.png_sha256, texture)); + assert!(assign::preview(&h.app).is_some()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert_eq!(h.app.session.selection, selection); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch Snapshot to consume this release"); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "show must not attach a replacement CPU job"); + assert!(active(&h.app)); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(!assign::cancel(&mut h.app), "the release must consume the drag; nothing may remain for Escape to cancel"); + + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert_eq!(h.app.session.selection, selection, "blank-canvas clicks cannot clear, add to or toggle the existing selection"); + assert!(h.app.viewport.hover.is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn gpu_failed_host_keeps_specific_reason_in_image_params_and_disabled_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for reason in ["This Direct3D 12 session has not tested Vulkan.", "Vulkan device creation failed: deliberate independent diagnostic 47."] { + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_ne!(reason, h.app.tr("render.gpu_unavailable")); + assert_eq!(image_params(&h.app).unwrap_err(), reason); + for id in ["render.preflight", "render.start"] { + let command = solidcraft_engine::find_command(id).unwrap(); + assert!(command.info(&h.app.session).enabled, "the engine must not hide the UI readiness check"); + let info = interactive_command_info(&h.app, command); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(reason), "{id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn gpu_pending_hosts_keep_generic_disabled_reason_without_starting_setup() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let generic = h.app.tr("render.gpu_unavailable").to_string(); + // This channel represents a still-pending answer; no worker or GPU factory is created. + let (_sender, receiver) = std::sync::mpsc::channel(); + for host in [PathHost::NotStarted, PathHost::Preparing(receiver, std::time::Instant::now())] { + let preparing = matches!(&host, PathHost::Preparing(..)); + h.app.render_workspace.path_host = host; + assert_eq!(image_params(&h.app).unwrap_err(), generic); + for id in ["render.preflight", "render.start"] { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(generic.as_str()), "{id}"); + } + assert_eq!(matches!(&h.app.render_workspace.path_host, PathHost::Preparing(..)), preparing); + assert!(matches!(&h.app.render_workspace.path_host, PathHost::NotStarted | PathHost::Preparing(..))); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn gpu_failed_host_preserves_raster_readiness_and_cooperative_cpu_refusal() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":12,"height":3})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + h.app.render_workspace.view.method = method; + h.app.render_workspace.path_host = PathHost::NotStarted; + let baseline = image_params(&h.app); + if method == ImageMethod::Raster { + assert!(baseline.is_ok(), "cooperative Raster must be available: {baseline:?}"); + } else { + assert_eq!(method, ImageMethod::CpuRaytrace); + let error = baseline.as_ref().unwrap_err(); + assert!(error.contains("CPU raytracing"), "cooperative CPU must retain its own host refusal: {error}"); + assert_ne!(error, h.app.tr("render.gpu_unavailable")); + } + let baseline_commands = ["render.preflight", "render.start"].map(|id| { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, method == ImageMethod::Raster, "{method:?}: {id}"); + assert_eq!(info.disabled_reason.as_deref(), baseline.as_ref().err().map(String::as_str), "{method:?}: {id}"); + (id, info.enabled, info.disabled_reason) + }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let reason = "Deliberate GPU-only refusal must not replace another method's readiness."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_eq!(image_params(&h.app), baseline, "{method:?}: preserve the exact success or rejection"); + for (id, enabled, disabled_reason) in baseline_commands { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, enabled, "{method:?}: {id}"); + assert_eq!(info.disabled_reason, disabled_reason, "{method:?}: {id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export() { + use solidcraft_engine::render::job::{RectangleLightOptions, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export") { + return; + } + h.app.render_workspace.view.raytrace.area_lights = Some(vec![RectangleLightOptions { + center_mm: [5.0, 4.0, 20.0], + edge_u_mm: [4.0, 0.0, 0.0], + edge_v_mm: [0.0, -4.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]); + h.app.render_workspace.view.raytrace.area_samples = Some(4); + h.app.render_workspace.view.raytrace.seed = Some(73); + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [0.25, 0.5, 1.0], + intensity: 3.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 0.75; + let expected = h.app.render_workspace.view.raytrace.area_lights.clone().unwrap(); + assert_eq!(expected.len(), 2); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Existing helper dispatches the real Snapshot, receives its real reply, + // validates real native PNG bytes/hash, drains the reply and paints the cache. + let id = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), id); + let status = job.status().unwrap(); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(options.area_lights.as_ref(), Some(&expected)); + assert_eq!(options.area_samples, Some(4)); + assert_eq!(options.seed, Some(73)); + assert_eq!(options.exposure_ev, 0.75); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + let (cached, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + let frame = job.frame().unwrap().unwrap(); + assert_eq!((cached.job, cached.png_sha256), (id, frame.info.png_sha256.clone())); + assert_eq!((cached.width, cached.height, samples, complete), (16, 16, 16, true)); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final() { + use solidcraft_engine::render::job::{CpuHost, JobId, Phase, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.raytrace.seed = Some(91); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let first = interactive_hold_real_completed_callback(&mut h); + let old = first.job.id(); + let old_options = first.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(old_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 2.0); + assert_eq!((old_options.area_samples, old_options.seed), (Some(4), Some(91))); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.area_lights.as_mut().unwrap().first_mut().unwrap().intensity = 1.5; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "light edit must detach the old owned job"); + first.sender.send(first.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &first.job); + + interactive_clear_acceptance_frame(&mut h, epoch + 0.601, true); + let second = interactive_hold_real_completed_callback(&mut h); + assert_ne!(second.job.id(), old); + let new_options = second.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(new_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 1.5); + assert_eq!((new_options.area_samples, new_options.seed), (Some(4), Some(91))); + let final_host = CpuHost::cooperative(); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(final_host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + let retained = final_host.admitted_bytes(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.7, false); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + second.sender.send(second.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.8, false, true); + assert!(!painted, "a final-suspended late LED reply cannot fill the preview cache"); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &second.job); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(final_host.admitted_bytes(), retained); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued, "Off cannot cancel the unrelated final"); + final_job.cancel().unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle() { + use solidcraft_engine::render::job::DirectionalLightOptions; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle") { + return; + } + h.app + .run( + "appearance.assign", + json!({"bodies":["Subject"],"color":"#808080","opacity":1.0, + "pbr":{"metallic":0.0,"roughness":1.0,"dielectric_ior":1.0}}), + ) + .unwrap(); + // Front view sees the y=0 face normally. All jittered rays through the + // central pixel stay inside that face, so neither coverage nor noise is an oracle. + h.app.cam.target = solidcraft_engine::geom::Vec3::new(5.0, 4.0, 2.0); + h.app.cam.yaw = 0.0; + h.app.cam.pitch = 0.0; + h.app.cam.roll = 0.0; + h.app.cam.distance = 10.0; + h.app.cam.fov = 0.0; + h.app.cam.up = solidcraft_engine::render::UpAxis::Z; + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + h.app.render_workspace.view.raytrace = solidcraft_engine::render::job::RaytraceOptions { + lights: Some(vec![DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 0.5 }]), + shadows: false, + ..Default::default() + }; + let camera = h.app.cam; + let final_options = h.app.render_workspace.view.raytrace.clone(); + let final_size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let mut previous_job = None; + let mut baseline_png = None; + let mut previous_visual = None; + for (step, ev) in [0.0_f64, 1.0, -1.0, 0.0].into_iter().enumerate() { + let time = epoch + step as f64; + h.app.render_workspace.view.draft.exposure_ev = ev; + interactive_clear_acceptance_frame(&mut h, time, false); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + if let Some(previous) = previous_visual { + assert!(visual > previous, "each committed EV must invalidate the previous image"); + } + previous_visual = Some(visual); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + // This is the real runtime request, not a test-only renderer request. + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["exposure_ev"], 0.0, "outer EV must not duplicate the CPU EV"); + assert_eq!(wire["raytrace"]["exposure_ev"], ev); + interactive_clear_acceptance_frame(&mut h, time + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.camera, camera); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, ev, "actual admitted job must carry EV exactly once"); + if let Some(previous) = previous_job { + assert_ne!(held.job.id(), previous, "an EV edit must not reuse the old admitted job"); + } + previous_job = Some(held.job.id()); + let frame = held.job.frame().unwrap().unwrap(); + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + // Original closed-form oracle: index-matched opaque dielectric has no + // Fresnel/specular term, so L = IEC-sRGB(128) * 0.5 / pi at normal incidence. + // Apply 2^EV once, Reinhard once, then IEC sRGB once and round to eight bits. + // No renderer BRDF/transfer helper or measured baseline supplies expectations. + let encoded = 128.0_f64 / 255.0; + let albedo = ((encoded + 0.055) / 1.055).powf(2.4); + let exposed = albedo * 0.5 / std::f64::consts::PI * 2.0_f64.powf(ev); + let mapped = exposed / (1.0 + exposed); + let srgb = if mapped <= 0.0031308 { 12.92 * mapped } else { 1.055 * mapped.powf(1.0 / 2.4) - 0.055 }; + let expected = (255.0 * srgb).round() as u8; + assert!(expected > 0 && expected < 255, "fixture must stay away from black and clipping"); + assert_eq!(png.get_pixel(7, 7).0, [expected, expected, expected, 255], "EV={ev}: actual native CPU PNG must match analytic radiance"); + if step == 0 { + baseline_png = Some(frame.png().to_vec()); + } else if step == 3 { + assert_eq!(frame.png(), baseline_png.as_ref().unwrap().as_slice(), "EV reversal must return the deterministic original PNG"); + } + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.3, false, true); + assert!(painted); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256), (held.job.id(), frame.info.png_sha256.clone())); + assert_eq!((samples, complete), (16, true)); + let uploaded = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert_eq!(pixels.size, [16, 16]); + assert_eq!( + pixels.pixels[7 * 16 + 7], + Color32::from_rgb(expected, expected, expected), + "the accepted texture must contain the analytic pixel" + ); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert_eq!(h.app.render_workspace.view.raytrace, final_options); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), final_size); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery") { + return; + } + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let original = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let original_visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let path = h.dir.join("interactive-accepted-to-pending-original.hdr"); + let bytes = original_hdr_bytes(192, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: path.to_string_lossy().into_owned() }; + // Even a real valid file is not admitted until inspected. An already + // displayed CPU frame must disappear, not masquerade as the new HDR intent. + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, true, true); + assert!(!painted); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.5); + assert_eq!(error, h.app.tr("render.hdr_inspect_required")); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > original_visual); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + // A correcting inspection must respect explicit user pause. Resume then + // captures the actual checked HDR through Snapshot/CPU, rather than falling + // back to the old frame or manufacturing a successful callback. + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let checked = interactive_request(&h.app).unwrap(); + { + use sha2::{Digest, Sha256}; + assert_eq!(checked["environment"]["expected_sha256"], format!("{:x}", Sha256::digest(&bytes))); + } + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + interactive_clear_acceptance_frame(&mut h, epoch + 1.5, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(interactive::test_cache(&h.app).is_none(), "the earlier accepted image cannot return after correcting HDR"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let recovered = interactive_recovery_require_success(&mut h, epoch + 1.701, epoch + 1.8); + assert_ne!(recovered, original); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), recovered); + let frame = job.frame().unwrap().unwrap(); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!((cached.job, samples, complete), (recovered, 16, true)); + assert_eq!(interactive_request(&h.app).unwrap(), checked); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 2.0, true, true); + assert!(painted, "Pause retains the newly recovered actual frame"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + let (paused, paused_samples, paused_complete, paused_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (paused.job, paused.png_sha256, paused_samples, paused_complete, paused_texture), + (recovered, frame.info.png_sha256.clone(), 16, true, texture) + ); + assert!(!output.textures_delta.set.contains_key(&texture), "Pause reuses the recovered texture"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(job.frame().unwrap().unwrap().png(), frame.png()); + interactive_assert_final_export_isolation(&mut h, &job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +fn partial_png_contract_encode(width: u32, height: u32, pixels: Vec) -> Vec { + // Original unit input for the real decoder/receiver, not a CPU render receipt. + let pixels = image::RgbaImage::from_raw(width, height, pixels).unwrap(); + let mut png = std::io::Cursor::new(Vec::new()); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + png.into_inner() +} + +fn partial_png_contract_request() -> solidcraft_engine::render::job::ImageRequest { + use solidcraft_engine::render::job::{CpuProgressiveOptions, ImageRequest, RaytraceOptions}; + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera: Default::default(), + width: 2, + height: 2, + background: [32, 64, 96], + transparent_background: false, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { progressive: Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 291 }), ..Default::default() }), + } +} + +fn partial_png_contract_info(png: &[u8]) -> solidcraft_engine::render::job::PartialPreviewInfo { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::{ + ExecutorId, + job::{AlphaConvention, ColourEncoding, FrameInfo, JobId, PartialPreviewInfo, PartialPreviewProjection}, + }; + // Synthetic descriptor for pure contract tests. No Host/JobHandle, capture, + // native executor or final registry is installed or claimed by this helper. + PartialPreviewInfo { + frame: FrameInfo { + job: JobId { session: 100, serial: 1, generation: 1 }, + scene_generation: 7, + backend: solidcraft_engine::render::builtin_backend().id, + executor: ExecutorId::new("cpu-raytrace").unwrap(), + width: 2, + height: 2, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + png_sha256: format!("{:x}", Sha256::digest(png)), + }, + sequence: 1, + source_width: 2, + source_height: 2, + completed_passes: 0, + updated_prefix: 3, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + } +} + +#[test] +fn partial_png_contract_four_pixels_separate_hit_miss_black_and_unknown() { + let request = partial_png_contract_request(); + // Independently derived IEC/Reinhard bytes for linear(.25,.5,1) at EV0: + // encode(1/5), encode(1/3), encode(1/2) = (124,156,188). + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 8192).unwrap(); + assert_eq!(decoded.pixels, vec![Color32::from_rgb(124, 156, 188), Color32::from_rgb(32, 64, 96), Color32::BLACK, Color32::TRANSPARENT,]); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 3); + assert!(sampling.source_unknown(), "global Unknown drives the added geometry gate"); + assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(0, 1, Color32::TRANSPARENT, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 1, Color32::BLACK, request.background).is_ok()); +} + +#[test] +fn partial_png_contract_second_prefix_keeps_nonuniform_counts_and_resolved_coverage() { + let request = partial_png_contract_request(); + // Original second-prefix source means are(.5,.25,1) and(0,1,0). + // The second has C/N=.5, so covered green2 is mapped BEFORE coverage: + // linear(.5*decode8(32), 1/3+.5*decode8(64), .5*decode8(96)), + // encoded once = (20,162,68). These PNG inputs must never be regraded by UI. + let png = partial_png_contract_encode(2, 2, vec![156, 124, 188, 255, 20, 162, 68, 255, 0, 0, 0, 255, 32, 64, 96, 255]); + let mut info = partial_png_contract_info(&png); + info.sequence = 2; + info.completed_passes = 1; + info.updated_prefix = 2; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[2, 1, 1, 0], sampling, 8192).unwrap(); + assert_eq!( + decoded.pixels, + vec![Color32::from_rgb(156, 124, 188), Color32::from_rgb(20, 162, 68), Color32::BLACK, Color32::from_rgb(32, 64, 96),] + ); + let counts: Vec<_> = (0..4).map(|index| interactive::partial_sample_count(1, 2, index, 4, 16).unwrap()).collect(); + assert_eq!(counts, vec![2, 2, 1, 1]); + assert_eq!(sampling.sample_range(), (1, 2), "this is not uniform2SPP"); + assert_eq!(sampling.sampled_source_pixels(), 4); + assert!(!sampling.source_unknown(), "only the additional Unknown block ends; all M3 gates still apply"); +} + +#[test] +fn partial_png_contract_frontier_bounds_keep_full_pass_sentinel_and_never_wrap() { + for index in 0..4 { + assert_eq!(interactive::partial_sample_count(0, 0, index, 4, 16).unwrap(), 0); + assert_eq!(interactive::partial_sample_count(1, 0, index, 4, 16).unwrap(), 1); + assert_eq!(interactive::partial_sample_count(16, 0, index, 4, 16).unwrap(), 16); + } + for (s, k, i, p, target) in [ + (0, 4, 0, 4, 16), + (0, 0, 4, 4, 16), + (0, 0, u64::MAX, 4, 16), + (0, 0, 0, 0, 16), + (0, 0, 0, 4, 0), + (17, 0, 0, 4, 16), + (16, 1, 0, 4, 16), + (u32::MAX, 1, 0, 4, u32::MAX), + ] { + assert!(interactive::partial_sample_count(s, k, i, p, target).is_err()); + } +} + +#[test] +fn partial_png_contract_rejects_high_invalid_identity_without_burning_accepted_sequence() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let accepted = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::validate_partial_metadata(&expected, &info, png.len(), 4, Some(accepted)).unwrap().is_none()); + let mut invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.job.generation += 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.width = 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; // advancing sequence with unchanged frontier is not new work + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + let mut next = info.clone(); + next.sequence = 2; // legitimate lower-than-rejected99 publication + next.completed_passes = 1; + next.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).unwrap().is_some()); + next.sequence = 0; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).is_err()); +} + +#[test] +fn partial_png_contract_decoder_refuses_unknown_blur_coverage_and_malformed_png() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 1).is_err(), "no implicit Triangle resize of Unknown"); + assert!(interactive::decode_partial_image(&request, &info, b"not a PNG", &[1, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 1], sampling, 8192).is_err(), "Unknown has no covered sample"); + assert!(interactive::decode_partial_image(&request, &info, &png, &[2, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1], sampling, 8192).is_err()); + let bad_alpha = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 128, 0, 0, 0, 255, 0, 0, 0, 0]); + let bad_info = partial_png_contract_info(&bad_alpha); + let bad_sampling = interactive::validate_partial_metadata(&expected, &bad_info, bad_alpha.len(), 4, None).unwrap().unwrap(); + assert!( + interactive::decode_partial_image(&request, &bad_info, &bad_alpha, &[1, 0, 1, 0], bad_sampling, 8192).is_err(), + "metadata admitted; sampled physical coverage must already be opaque" + ); +} + +#[test] +fn partial_png_contract_shared_plan_keeps_unrepresented_unknown_globally_blocked() { + use sha2::{Digest, Sha256}; + let mut request = partial_png_contract_request(); + request.width = 2048; + request.height = 1; + let png = partial_png_contract_encode(1024, 1, [0, 0, 0, 255].repeat(1024)); + let mut info = partial_png_contract_info(&png); + info.source_width = 2048; + info.source_height = 1; + info.frame.width = 1024; + info.frame.height = 1; + info.frame.png_bytes = png.len() as u64; + info.frame.png_sha256 = format!("{:x}", Sha256::digest(&png)); + info.updated_prefix = 2047; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2048, 1] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 1024, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1; 1024], sampling, 8192).unwrap(); + assert!(decoded.pixels.iter().all(|pixel| *pixel == Color32::BLACK)); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 2047); + assert!(sampling.source_unknown(), "all1024 representatives known does not observe source pixel2047"); + let plan = solidcraft_engine::render::job::PartialPreviewPlan::new(2048, 1).unwrap(); + assert_eq!(plan.source_index(0).unwrap(), 0); + assert_eq!(plan.source_index(1023).unwrap(), 2046); + assert!(plan.source_index(1024).is_err()); +} + +#[test] +fn partial_png_contract_egui_clock_throttles_attempts_without_wall_time_or_fake_frames() { + use solidcraft_engine::render::job::JobId; + use std::time::Duration; + let job = JobId { session: 100, serial: 1, generation: 1 }; + assert!(interactive::partial_request_due(None, job, Duration::ZERO)); + let first = Some((job, Duration::ZERO)); // caller records every attempt, including false + assert!(!interactive::partial_request_due(first, job, Duration::from_millis(249))); + assert!(interactive::partial_request_due(first, job, Duration::from_millis(250))); + let second = Some((job, Duration::from_millis(250))); + assert!(!interactive::partial_request_due(second, job, Duration::from_millis(499))); + assert!(interactive::partial_request_due(second, job, Duration::from_millis(500))); + let mut newer = job; + newer.serial += 1; + assert!(interactive::partial_request_due(second, newer, Duration::from_millis(251))); + let clock = interactive::monotonic(Duration::from_millis(500), 0.499); + assert_eq!(clock, Duration::from_millis(500)); + assert!(!interactive::partial_request_due(Some((job, clock)), job, Duration::from_millis(499))); +} + +#[test] +fn partial_frame_visibility_paused_unknown_yields_to_final_priority() { + use interactive::FrameVisibility; + // Policy inputs only: no Host/JobHandle, fake CPU output or native receipt. + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + assert!(paused.paintable(), "normal M3 paused/stale image remains visible"); + assert!(paused.blocks_unknown(true), "source Unknown still blocks geometry while paused"); + assert!(!paused.blocks_unknown(false), "known source does not gain an extra gate"); + let preempted = FrameVisibility { final_active: true, ..paused }; + assert!(!preempted.paintable()); + assert!(!preempted.blocks_unknown(true), "an image hidden by a manual final cannot reserve the Model canvas"); + // This is the nonwaiting case: both production paint and the Unknown arm + // decline it, so the existing parent can reach its visible Raster fallback. +} + +#[test] +fn partial_frame_visibility_error_or_missing_texture_cannot_claim_unknown_canvas() { + use interactive::FrameVisibility; + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + for hidden in [ + FrameVisibility { has_error: true, ..paused }, + FrameVisibility { texture_ok: false, ..paused }, + FrameVisibility { has_context: false, ..paused }, + FrameVisibility { paused: false, ..paused }, + ] { + assert!(!hidden.paintable()); + assert!(!hidden.blocks_unknown(true), "hidden pixels cannot suppress visible Raster or its geometry targets"); + } + let current = FrameVisibility { paused: false, stale: false, revision_matches: true, ..paused }; + assert!(current.paintable()); + assert!(current.blocks_unknown(true), "all-known representatives cannot erase global source Unknown"); + assert!(!FrameVisibility { stale: true, ..current }.blocks_unknown(true)); + assert!(!FrameVisibility { revision_matches: false, ..current }.blocks_unknown(true)); + // Existing waiting/input-cleanup regressions stay in the untouched222 prefix. + // The production awaiting_current_frame arm is not gated by this predicate. +} + +mod cpu_optical_material_routing { + use super::*; + + fn bind_recipe(h: &mut Harness, name: &str, recipe: &str, boundary: materials::Boundary) { + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == name).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(recipe).unwrap(); + // These represent explicit author actions, not a converter's guesses. + binding.glass.boundary = boundary; + binding.cpu_optics = true; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + } + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"center":[0,0,2],"body_name":"Optics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.shadows = false; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [1.0; 3]; + h.app.render_workspace.view.cpu.intensity = 1.0; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.background = [255; 3]; + h.app.cam = Camera { distance: 50.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + h.app.session.mark_saved(); + h + } + + fn wire(h: &Harness) -> Value { + runtime_image_request(&h.app, false).unwrap() + } + + fn directional_shadow_fixture(choices: &[bool]) -> Harness { + use solidcraft_engine::render::job::DirectionalLightOptions; + assert!(!choices.is_empty() && choices.len() <= 2); + let mut h = Harness::new(); + for index in 0..choices.len() { + h.app + .run("solid.box", json!({"length":2,"width":2,"height":2,"center":[index as f64 * 4.0,0,2],"body_name":format!("Shadow{index}")})) + .unwrap(); + } + h.app.run("render.scene", json!({})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.shadows = true; + h.app.render_workspace.view.raytrace.lights = + Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 2.0 }]); + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.materials.enabled = true; + let targets = materials::read_targets(&mut h.app).unwrap(); + for (index, shadows) in choices.iter().copied().enumerate() { + let target = targets.iter().find(|target| target.name == format!("Shadow{index}")).unwrap().clone(); + let mut binding = materials::Binding::new(target, &h.app); + binding.cpu_optics = true; + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.shadows = shadows; + h.app.render_workspace.view.materials.bindings.push(binding); + } + h.app.session.mark_saved(); + h + } + + fn directional_shadow_refusal_is_atomic(h: &Harness, key: Option<&str>) { + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"preserve"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let options = json!(h.app.render_workspace.view.raytrace); + let error = materials::params(&h.app, &mut request).unwrap_err(); + if let Some(key) = key { + assert!(error.contains(h.app.tr(key)), "{key}: {error}"); + } + assert_eq!(request, before); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert_eq!(json!(h.app.render_workspace.view.raytrace), options); + } + + #[test] + fn cpu_directional_shadow_uniform_assignments_lower_typed_wire_without_changing_authored_options() { + use solidcraft_engine::render::job::{CpuDielectricTransport, CpuProgressiveOptions, RaytraceOptions}; + for shadows in [false, true] { + for progressive in [false, true] { + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + let mut h = directional_shadow_fixture(&[shadows, shadows]); + h.app.render_workspace.view.raytrace.dielectric_transport = policy; + h.app.render_workspace.view.raytrace.progressive = + progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let mut expected = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut expected).unwrap(); + let request = runtime_image_request(&h.app, false).unwrap(); + let mut options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + options.validate().unwrap(); + assert_eq!(options.directional_shadow_transmission, shadows); + assert!(options.shadows); + assert_eq!(options.dielectrics.len(), 2); + assert_eq!(options.dielectric_transport, policy); + assert_eq!(options.progressive, h.app.render_workspace.view.raytrace.progressive); + assert!(options.dielectrics.iter().all(|body| body.ior == 1.5 && body.absorption_per_mm == [0.0; 3])); + assert!(request["raytrace"]["dielectrics"].as_array().unwrap().iter().all(|body| body.get("shadow_transmission").is_none())); + if !shadows { + assert!(request["raytrace"].get("directional_shadow_transmission").is_none()); + } + options.dielectrics.clear(); + options.directional_shadow_transmission = false; + assert_eq!(json!(options), expected["raytrace"], "no other CPU option may change"); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + } + } + } + } + + #[test] + fn cpu_directional_shadow_mixed_body_choices_refuse_both_orders_without_erasing_off() { + for choices in [[false, true], [true, false]] { + let h = directional_shadow_fixture(&choices); + directional_shadow_refusal_is_atomic(&h, Some("render.cpu_shadow_mixed")); + } + } + + #[test] + fn cpu_directional_shadow_all_on_keeps_global_shadows_environment_nesting_and_light_refusals() { + for case in ["global_off", "constant", "hdr", "nested", "reflections", "punctual", "area"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "global_off" => h.app.render_workspace.view.raytrace.shadows = false, + "constant" => h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant, + "hdr" => { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-shadow-adapter.hdr"); + } + "nested" => h.app.render_workspace.view.cpu.nested_media = true, + "reflections" => h.app.render_workspace.view.raytrace.reflections = Some(Default::default()), + "punctual" => { + h.app.render_workspace.view.raytrace.punctual_lights = Some( + serde_json::from_value(json!([{ + "position_mm":[0,0,100],"color":[1,1,1],"intensity":2,"reference_distance_mm":100,"minimum_distance_mm":0.01 + }])) + .unwrap(), + ); + } + "area" => { + h.app.render_workspace.view.raytrace.area_lights = Some( + serde_json::from_value(json!([{ + "center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3 + }])) + .unwrap(), + ); + } + _ => unreachable!(), + } + h.app.render_workspace.view.raytrace.validate().unwrap(); + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_all_on_preserves_identity_permission_duplicate_and_boundary_gates() { + for case in ["stale", "duplicate", "closed", "permission"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "stale" => { + h.app.run("appearance.assign", json!({"bodies":["Shadow0"],"color":"#123456"})).unwrap(); + } + "duplicate" => { + let duplicate = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(duplicate); + } + "closed" => h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Closed, + "permission" => h.app.render_workspace.view.materials.bindings[0].cpu_optics = false, + _ => unreachable!(), + } + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_inactive_off_body_is_not_selected_for_transmission() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.bindings[1].enabled = false; + let request = runtime_image_request(&h.app, false).unwrap(); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert!(options.directional_shadow_transmission); + assert_eq!(options.dielectrics.len(), 1); + assert_eq!(options.dielectrics[0].body_name, "Shadow0"); + assert!(!h.app.render_workspace.view.materials.bindings[1].glass.shadows); + assert!(!h.app.render_workspace.view.materials.bindings[1].enabled); + } + + #[test] + fn cpu_directional_shadow_default_false_and_conflicting_global_intent_are_preserved() { + use solidcraft_engine::render::job::RaytraceOptions; + assert!(!RaytraceOptions::default().directional_shadow_transmission); + assert!(json!(RaytraceOptions::default()).get("directional_shadow_transmission").is_none()); + let h = directional_shadow_fixture(&[false, false]); + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + request["raytrace"]["directional_shadow_transmission"] = json!(true); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_shadow_conflict"))); + assert_eq!(request, before); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.enabled = false; + let before = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + assert_eq!(request, before, "disabled materials do not rewrite an unrelated request"); + } + + #[test] + fn cpu_directional_shadow_adapter_messages_are_delivered_in_nine_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in ["render.cpu_directional_shadow_help", "render.cpu_shadow_conflict", "render.cpu_shadow_mixed"] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + #[test] + fn explicit_cpu_recipe_builds_typed_optics_with_independent_linear_units_and_no_design_edit() { + use solidcraft_engine::render::{ + job::{DielectricBoundary, RaytraceOptions}, + transmission::Transmission, + }; + let h = fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let request = wire(&h); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(options.dielectrics.len(), 1); + let material = &options.dielectrics[0]; + assert_eq!((material.body_index, material.body_name.as_str()), (0, "Optics")); + assert_eq!(material.boundary, DielectricBoundary::ClosedBox); + assert_eq!(material.ior, 1.5); + assert_eq!(material.thickness_mm, 0.0); + let [r, g, b] = material.absorption_per_mm; + assert!((r - 0.005050676829379866).abs() < 1e-15); + assert!((g - 0.0025125839633753626).abs() < 1e-15); + assert_eq!(b, 0.0); + // This tests coefficient lowering only. Native pixel tests below test transport. + let medium = Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + for (distance, expected) in [(4.0, [0.98, 0.99, 1.0]), (8.0, [0.9604, 0.9801, 1.0])] { + let t = medium.attenuation(distance).unwrap(); + for (actual, expected) in [t.x, t.y, t.z].into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-12); + } + } + assert!(request["raytrace"].get("clear_coats").is_none()); + assert!(request["raytrace"].get("textures").is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(setups::snapshot(&h.app).is_err(), "transient CPU optics are not portable GPU saved optics"); + } + + #[test] + fn legacy_gpu_binding_and_closed_recipe_still_need_explicit_cpu_route_and_box_choice() { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = false; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_explicit"))); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_boundary"))); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let mut gpu = json!({}); + materials::params(&h.app, &mut gpu).unwrap(); + assert_eq!(gpu["raytrace"]["dielectrics"][0]["boundary"], "closed_mesh"); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + } + + #[test] + fn thin_recipe_preserves_authored_shadow_intent_until_explicit_edit() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].glass = materials::Glass::recipe("starter.glass.thin-clear").unwrap(); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_unsupported"))); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + // User deliberately disables the distinct GPU transmitted-shadow approximation. + h.app.render_workspace.view.materials.bindings[0].glass.shadows = false; + let request = wire(&h); + assert_eq!(request["raytrace"]["dielectrics"][0]["boundary"], "thin_sheet"); + assert_eq!(request["raytrace"]["dielectrics"][0]["thickness_mm"], 2.0); + assert!(request["raytrace"]["dielectrics"][0].get("shadow_transmission").is_none()); + // The box fixture is NOT a certified thin surface; native admission must refuse below. + } + + #[test] + fn unsupported_optical_intent_refuses_atomically_instead_of_erasing_flags_or_maps() { + for case in ["coat", "maps", "shadows", "subsurface", "no_glass"] { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + match case { + "coat" => binding.coat_enabled = true, + "maps" => { + binding.maps_enabled = true; + binding.maps.normal = "authored-normal.png".into(); + } + "shadows" => binding.glass.shadows = true, + "subsurface" => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => { + binding.glass_enabled = false; + binding.coat_enabled = true; + } + } + let intent = format!("{:?}", h.app.render_workspace.view.materials); + let mut request = json!({"settings":{"exposure_ev":0},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).is_err(), "{case}"); + assert_eq!(request, before, "failed lowering must not partially replace CPU options: {case}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), intent, "{case}"); + } + } + + #[test] + fn cpu_optical_request_preserves_hdr_and_all_preexisting_cpu_numeric_options() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = fixture(); + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "budget":"studio","primary_samples":4,"shadows":true, + "lights":[{"direction":[0,0,1],"color":[1,0.5,0.25],"intensity":2}], + "punctual_lights":[{"position_mm":[0,0,100],"color":[0.25,0.5,1],"intensity":4, + "reference_distance_mm":100,"minimum_distance_mm":0.01,"cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}}], + "area_lights":[{"center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3}], + "area_samples":16,"seed":42 + })).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-optical-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.75; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + let base = json!(h.app.render_workspace.view.raytrace); + let mut request = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut request).unwrap(); + let cpu_request = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + let mut decoded: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(decoded.dielectrics.len(), 1); + decoded.dielectrics.clear(); + assert_eq!(json!(decoded), cpu_request["raytrace"], "only typed dielectrics may change"); + assert_eq!(request["environment"], cpu_request["environment"]); + assert_eq!(request["environment"]["path"], "not-read-by-optical-ui.hdr"); + assert_eq!(request["settings"]["exposure_ev"], 0.0); + assert_eq!(request["raytrace"]["exposure_ev"], 1.25); + assert_eq!(json!(h.app.render_workspace.view.raytrace), base); + } + + #[test] + fn optical_binding_refuses_hidden_changed_ordinal_wrong_feature_and_wrong_document() { + let mut h = fixture(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(runtime_image_request(&h.app, false).is_err(), "visibility need not change revision"); + h.app.session.visibility.hidden_bodies.clear(); + assert!(runtime_image_request(&h.app, false).is_ok()); + h.app.render_workspace.view.materials.bindings[0].target.ordinal = 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().feature += 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().occurrence_path = vec![999]; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + let document = h.app.session.doc.clone(); + h.app.session.doc = Arc::new((*document).clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "same numerical revision is not same document"); + } + + #[test] + fn optical_revalidation_is_explicit_and_same_body_only() { + let mut h = fixture(); + let mut original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + materials::revalidate(&mut h.app, &mut original).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + assert!(runtime_image_request(&h.app, false).is_ok()); + original.target.name = "Same name is insufficient".into(); + assert!(materials::revalidate(&mut h.app, &mut original).is_err()); + assert_eq!(original.target.name, "Same name is insufficient"); + } + + #[test] + fn optical_limits_duplicates_and_hostile_coefficients_keep_original_request_intact() { + let mut h = fixture(); + for bad in [f64::NAN, f64::INFINITY, -1.0, 3.01] { + h.app.render_workspace.view.materials.bindings[0].glass.ior = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.ior = 1.5; + for bad in [f64::NAN, f64::INFINITY, -0.1, 100.01] { + h.app.render_workspace.view.materials.bindings[0].glass.absorption[0] = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.absorption = [0.0; 3]; + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(original.clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "duplicate target is not two media"); + h.app.render_workspace.view.materials.bindings = vec![original; 9]; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn progressive_optics_preserves_identity_and_saved_gpu_conflicts_without_mutation() { + let mut h = fixture(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + let progressive_final = runtime_image_request(&h.app, false).unwrap(); + let final_options: RaytraceOptions = serde_json::from_value(progressive_final["raytrace"].clone()).unwrap(); + final_options.validate().unwrap(); + assert_eq!(final_options.primary_samples, 1); + assert_eq!(final_options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(final_options.progressive.unwrap().seed, 0); + let optics = progressive_final["raytrace"]["dielectrics"].clone(); + assert_eq!(optics.as_array().unwrap().len(), 1); + assert_eq!(optics[0]["body_name"], "Optics"); + assert_eq!(optics[0]["boundary"], "closed_box"); + assert_eq!(optics[0]["ior"], 1.5); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + let from_progressive = interactive_request(&h.app).unwrap(); + assert_eq!(from_progressive["raytrace"]["dielectrics"], optics, "preview conversion cannot erase or replace the authored optical material"); + assert!(h.app.render_workspace.view.materials.bindings[0].glass_enabled); + h.app.render_workspace.view.raytrace.progressive = None; + let from_fixed = interactive_request(&h.app).unwrap(); + assert_eq!(from_fixed["raytrace"]["dielectrics"], optics, "Fixed editor preview still carries certified optics"); + let progressive_input: RaytraceOptions = serde_json::from_value(from_progressive["raytrace"].clone()).unwrap(); + progressive_input.validate().unwrap(); + assert_eq!(progressive_input.primary_samples, 1); + assert_eq!(progressive_input.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(progressive_input.progressive.unwrap().seed, 0); + let fixed_input: RaytraceOptions = serde_json::from_value(from_fixed["raytrace"].clone()).unwrap(); + fixed_input.validate().unwrap(); + assert_eq!(fixed_input.primary_samples, 1); + assert!(fixed_input.progressive.is_none(), "the UI Fixed DTO stays Fixed until the engine preview conversion"); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none(), "constructing preview intent cannot change the manual-final editor"); + #[cfg(not(target_arch = "wasm32"))] + if native_host(&mut h, "progressive_bridge_obsolete_guard_adaptation") { + use solidcraft_engine::render::job::{JobId, Phase, interactive::VisualRevision}; + use std::time::Duration; + // Same original20x20/one-pixel/50-distance inputs: this is actual + // capture/admission/completion, not a Beer pixel oracle (jitter may miss). + let mut final_params = progressive_final.clone(); + final_params["progressive_feedback"] = json!(true); + let checked = h.app.run("render.preflight", final_params.clone()).unwrap(); + let started = h.app.run("render.start", final_params).unwrap(); + let final_id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let final_job = h.app.session.render_job_handle(final_id).unwrap(); + let final_status = final_job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(final_status.progress.phase, Phase::Completed, "{:?}", final_status.error); + assert_eq!(serde_json::to_value(&final_status.request).unwrap(), checked["request"]); + assert_eq!(json!(final_status.request.raytrace), progressive_final["raytrace"]); + assert!(!final_status.options.nested_media); + assert!(final_job.protected_preview_report().unwrap().is_some()); + let final_bytes = final_job.frame().unwrap().unwrap().png().to_vec(); + for (index, params) in [&from_progressive, &from_fixed].into_iter().enumerate() { + let context = h.app.session.interactive_render().unwrap(); + context + .enable(VisualRevision { scene_generation: h.app.session.revision, visual_revision: index as u64 + 1 }, Duration::ZERO) + .unwrap(); + let ticket = context.capture(Duration::from_millis(200)).unwrap().unwrap(); + let snapshot = context.snapshot(&h.app.session, ticket, params).unwrap(); + assert!(snapshot.run().unwrap(), "real optical snapshot must be admitted/adopted"); + let job = context.current().unwrap().unwrap(); + let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(serde_json::to_value(&options.dielectrics).unwrap(), optics); + assert_eq!(options.primary_samples, 1); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(options.progressive.unwrap().seed, 0); + assert_eq!((status.request.width, status.request.height), (1, 1)); + assert!(!status.options.nested_media); + assert_eq!(job.id(), ticket.job_id()); + assert!(job.frame().unwrap().is_some()); + assert!(h.app.session.render_job_handle(job.id()).is_err(), "Interactive keeps a separate non-export owner"); + context.disable().unwrap(); + assert_eq!(h.app.session.render_job_handle(final_id).unwrap().frame().unwrap().unwrap().png(), final_bytes.as_slice()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), authored); + let mut request = wire(&h); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_optics_conflict"))); + assert_eq!(request, before); + let target = h.app.render_workspace.view.materials.bindings[0].target.stable_target.clone().unwrap(); + h.app + .render_workspace + .view + .draft + .optics + .set( + solidcraft_engine::doc::render_optics::SavedOptics { + target, + optics: solidcraft_engine::doc::render_optics::OpticalMaterial { + ior: 1.5, + absorption_per_mm: [0.0; 3], + boundary: solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedMesh, + thickness_mm: 0.0, + shadow_transmission: false, + subsurface: None, + }, + }, + false, + ) + .unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + assert_eq!(h.app.render_workspace.view.draft.optics.len(), 1); + } + + #[test] + fn nested_cpu_route_is_an_explicit_cpu_choice_independent_of_gpu_legacy_state() { + let mut h = fixture(); + h.app.render_workspace.view.studio.nested_media = true; + assert_eq!(wire(&h)["nested_media"], false); + h.app.render_workspace.view.cpu.nested_media = true; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.studio.nested_media = false; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.cpu.nested_media = false; + assert_eq!(wire(&h)["nested_media"], false); + } + + #[cfg(not(target_arch = "wasm32"))] + fn native_host(h: &mut Harness, case: &str) -> bool { + use solidcraft_engine::render::job::CpuHost; + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + if !available { + let request = wire(h); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", request.clone()).is_err()); + assert!(h.app.run("render.start", request).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return false; + } + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=true"); + true + } + + #[cfg(not(target_arch = "wasm32"))] + fn check_start_pixel(h: &mut Harness, expected: [u8; 4]) { + use solidcraft_engine::render::job::{JobId, Phase}; + let request = image_params(&h.app).unwrap(); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"], request["raytrace"]["dielectrics"]); + assert_eq!(image_params(&h.app).unwrap(), request, "Check and Start must capture identical optical intent"); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert_eq!(status.options.nested_media, request["nested_media"].as_bool().unwrap()); + let frame = handle.frame().unwrap().unwrap(); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(*image.get_pixel(0, 0), image::Rgba(expected)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_box_reaches_same_cpu_check_start_and_real_beer_pixels() { + let mut h = fixture(); + if !native_host(&mut h, "library_box") { + return; + } + // Explicit author edit isolates Beer: index-matched boundaries have zero + // Fresnel reflection, 4 mm actual distance yields [.98,.99,1]. + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.ior = 1.0; + glass.recipe = None; + check_start_pixel(&mut h, [187, 187, 188, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_admission_preserves_opacity_and_refuses_false_thin_certificate() { + let mut h = fixture(); + if !native_host(&mut h, "opacity_and_certificate") { + return; + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Thin; + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "twelve triangles are not a thin-sheet certificate"); + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].opacity, 0.25); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_thin_library_recipe_uses_actual_imported_planar_certificate_and_virtual_distance() { + let mut h = fixture(); + if !native_host(&mut h, "library_thin") { + return; + } + let path = h.dir.join("original-optical-sheet.stl"); + // Original one-triangle geometry, not a box proxy or commercial fixture. + std::fs::write(&path, b"solid OriginalSheet\nfacet normal 0 0 1\nouter loop\nvertex -20 -20 2\nvertex 20 -20 2\nvertex 0 20 2\nendloop\nendfacet\nendsolid OriginalSheet\n").unwrap(); + h.app.run("file.insert_mesh", json!({"path":path,"name":"OriginalSheet"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + let targets = materials::read_targets(&mut h.app).unwrap(); + assert_eq!(targets.len(), 1); + let name = targets[0].name.clone(); + bind_recipe(&mut h, &name, "starter.glass.thin-clear", materials::Boundary::Thin); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "do not silently delete the recipe's shadow intent"); + glass.shadows = false; // explicit compatible user policy + glass.ior = 1.0; // explicit index-matched Beer experiment + glass.recipe = None; + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].mesh.triangles.len(), 1); + // 2 mm virtual normal distance -> [.95,.98,.99]; Reinhard+sRGB bytes. + check_start_pixel(&mut h, [185, 187, 187, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_nested_opt_in_preserves_real_child_medium_and_default_refusal() { + let mut h = fixture(); + if !native_host(&mut h, "library_nested") { + return; + } + h.app.run("solid.box", json!({"length":10,"width":10,"height":2,"center":[0,0,2],"operation":"new","body_name":"Inner"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + bind_recipe(&mut h, "Inner", "starter.glass.amber-tint", materials::Boundary::Box); + for binding in &mut h.app.render_workspace.view.materials.bindings { + binding.glass.ior = 1.0; // explicit index-matched experiment, not renderer conversion + binding.glass.recipe = None; + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["nested_media"], false); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("nested, touching or overlapping"), "{error}"); + } + h.app.render_workspace.view.cpu.nested_media = true; + // Geometry gives 2 mm outer + 2 mm inner, replacing rather than adding + // parent extinction inside the child. Linear RGB: + // sqrt(.98)*.84^(2/3), sqrt(.99)*.38^(2/3), .08^(2/3). + // Independent Reinhard+sRGB quantisation -> [182,158,110]. + check_start_pixel(&mut h, [182, 158, 110, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_refuses_face_alpha_and_general_closed_geometry_without_repairs() { + let mut h = fixture(); + if !native_host(&mut h, "face_alpha_and_sphere") { + return; + } + h.app.run("appearance.assign", json!({"body":"Optics","faces":[[0,0,4]],"color":"#abcdef","opacity":0.5})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + assert_eq!(scene.meshes[0].opacity, 1.0); + assert!(scene.meshes[0].faces.iter().any(|face| face.opacity == 0.5)); + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.app.run("solid.sphere", json!({"radius":3,"center":[30,0,3],"body_name":"Sphere","operation":"new"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Sphere", "starter.glass.low-iron-clear", materials::Boundary::Box); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "an explicitly selected Box still needs an actual box certificate"); + } + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Box); + } + + #[test] + fn cpu_optics_preserves_reflection_intent_for_existing_transport_conflict() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + cpu::set_reflection(&mut h.app, "Optics", Some(ReflectionMode::Mirror)).unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Optics"); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + // Retaining both preserves the engine's explicit same-target transport + // refusal; the adapter does not silently delete the reflection binding. + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + } + + #[test] + fn cpu_optics_keeps_reflections_on_a_separate_exact_body() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"corner":[30,0,0],"body_name":"Reflector","operation":"new"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let before = h.app.render_workspace.view.raytrace.reflections.clone().unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"], json!(before)); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Reflector"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_original_library_ior_and_hdr_survive_check_start_and_captured_file_change() { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::job::{JobId, Phase}; + let mut h = fixture(); + if !native_host(&mut h, "library_ior_hdr") { + return; + } + let path = h.dir.join("original-optical-white.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input(path.to_str().unwrap()); + h.app.render_workspace.view.cpu.samples = 4; + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"][0]["ior"], 1.5, "the original recipe's IOR reaches the real consumer"); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["request"]["raytrace"], request["raytrace"]); + assert_eq!(image_params(&h.app).unwrap(), request); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + // Start has captured immutable bytes; this does not depend on whether + // its tiny job has already finished by the time the file is replaced. + std::fs::write(&path, b"changed after capture").unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + // CPU status carries exactly 32 byte values; the captured request uses + // the canonical lowercase hex HdrId wire form. Normalize independently + // of HdrId's production serializer/parser and keep absent/type failures. + let captured_sha256: [u8; 32] = serde_json::from_value(json!(status.environment).get("source_sha256").unwrap().clone()).unwrap(); + let expected_hex = request["environment"]["expected_sha256"].as_str().unwrap(); + assert_eq!(expected_hex.len(), 64); + assert!(expected_hex.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))); + let expected_sha256: [u8; 32] = std::array::from_fn(|index| u8::from_str_radix(&expected_hex[index * 2..index * 2 + 2], 16).unwrap()); + let original_sha256: [u8; 32] = Sha256::digest(&bytes).into(); + assert_eq!(captured_sha256, expected_sha256); + assert_eq!(captured_sha256, original_sha256); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + assert!(pixels.get_pixel(0, 0).0[..3].iter().all(|channel| *channel > 0), "real optical output must not be black"); + assert!(h.app.run("render.preflight", request).is_err(), "a fresh capture must detect the changed HDR"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_eight_optical_library_targets_admit_without_raising_the_ninth_target_limit() { + let mut h = fixture(); + if !native_host(&mut h, "eight_library_targets") { + return; + } + for index in 1..=8 { + h.app + .run( + "solid.box", + json!({"length":2,"width":2,"height":2,"corner":[30*index,0,0],"body_name":format!("Optics{index}"),"operation":"new"}), + ) + .unwrap(); + } + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + for index in 1..8 { + bind_recipe(&mut h, &format!("Optics{index}"), "starter.glass.low-iron-clear", materials::Boundary::Box); + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"].as_array().unwrap().len(), 8); + h.app.run("render.preflight", request).unwrap(); + bind_recipe(&mut h, "Optics8", "starter.glass.low-iron-clear", materials::Boundary::Box); + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn all_original_glass_recipes_keep_their_authored_coefficients_on_the_explicit_cpu_route() { + use solidcraft_engine::doc::appearance_pack::{Recipe, STARTER_PACK}; + let mut h = fixture(); + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let glass = materials::Glass::recipe(preset.id).unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.glass = glass; + if binding.glass.boundary == materials::Boundary::Closed { + binding.glass.boundary = materials::Boundary::Box; // explicit subset selection + } else { + assert!(binding.glass.shadows); + binding.glass.shadows = false; // explicit unsupported-policy edit + } + let request = wire(&h); + let material = &request["raytrace"]["dielectrics"][0]; + assert_eq!(material["ior"], recipe.dielectric_ior); + let sigma: [f64; 3] = serde_json::from_value(material["absorption_per_mm"].clone()).unwrap(); + for (sigma, transmission) in sigma.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + count += 1; + } + assert_eq!(count, 6); + assert!(materials::Glass::recipe("SELENE-AP-029").is_err(), "an opaque vial surrogate does not become physical glass"); + } + + #[test] + fn cpu_optical_route_messages_are_present_in_all_nine_delivered_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in [ + "render.cpu_optics_boundary", + "render.cpu_optics_conflict", + "render.cpu_optics_enable", + "render.cpu_optics_explicit", + "render.cpu_optics_fixed", + "render.cpu_optics_help", + "render.cpu_optics_limit", + "render.cpu_optics_request", + "render.cpu_optics_saved", + "render.cpu_optics_unsupported", + ] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + fn editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 2400.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("Optics")); + }, + ); + output.textures_delta.clear(); + } + + fn editor_click(h: &mut Harness, id: &str) { + let at = crate::scenario::rect_of(id).unwrap().center(); + for pressed in [true, false] { + editor_frame( + h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + editor_frame(h, vec![]); + } + + #[test] + fn clicked_cpu_optics_uses_existing_selection_editor_without_reinterpreting_gpu_binding() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = false; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + assert!(runtime_image_request(&h.app, false).is_err(), "opening the editor grants no CPU intent"); + editor_click(&mut h, "render:glass-recipe-select"); + editor_click(&mut h, "render:glass:starter.glass.low-iron-clear"); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert!(runtime_image_request(&h.app, false).is_err(), "Closed recipe cannot turn itself into a Box"); + editor_click(&mut h, "render:optics-boundary-box"); + assert_eq!(wire(&h)["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + editor_click(&mut h, "render:cpu-optics-nested"); + assert_eq!(wire(&h)["nested_media"], true); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(runtime_image_request(&h.app, false).is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn clicked_cpu_boundary_does_not_silently_clear_transmitted_shadow_or_subsurface_intent() { + let mut h = fixture(); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.shadows = true; + glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + editor_click(&mut h, "render:optics-boundary-thin"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows); + assert!(glass.subsurface.is_some(), "selecting a different CPU boundary is not consent to remove scattering"); + assert!(runtime_image_request(&h.app, false).is_err()); + editor_click(&mut h, "render:optics-boundary-box"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "the GPU boundary default must not erase unsupported CPU shadow intent"); + assert!(glass.subsurface.is_some()); + assert!(runtime_image_request(&h.app, false).is_err()); + } +} + +// Additive scope imports for the sealed optical fixtures; UI247 stays byte-identical. +use serde_json::Value; +use solidcraft_engine::render::StandardView; + +#[cfg(not(target_arch = "wasm32"))] +mod manual_final_cpu_feedback_tests { + use super::*; + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, HostKind, JobHandle, PartialPreviewPlan, PartialPreviewProjection, Phase}; + + fn fixture(width: u32, height: u32, samples: u32, background: [u8; 3], case: &str) -> Option { + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == HostKind::NativeWorker && host.is_available() && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = width; + view.draft.height = height; + view.draft.background = background; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.draft.exposure_ev = 0.0; + view.transparent = false; + view.raytrace = RaytraceOptions { + primary_samples: 1, + lights: Some(Vec::new()), + shadows: false, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 83 }), + ..Default::default() + }; + h.ctx.input_mut(|input| input.max_texture_side = 8192); + if !available { + let wire = json!({"integrator":"raytrace","progressive_feedback":true, + "settings":{"width":width,"height":height,"background":background}, + "raytrace":{"primary_samples":1,"lights":[],"shadows":false, + "progressive":{"samples_per_pixel":samples,"seed":83}}}); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", wire.clone()).is_err()); + assert!(h.app.run("render.start", wire).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.final_partial.is_none()); + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return None; + } + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=true"); + Some(h) + } + + fn actual_final(h: &mut Harness) -> JobHandle { + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + assert!(handle.frame().unwrap().is_some()); + assert!(handle.protected_preview_report().unwrap().is_some()); + handle + } + + // POLICY INPUTS ONLY, not a host-published PartialArc or a while-running receipt. + // Derive bounded display pixels from an actual completed native final, then + // author an explicit source-frontier descriptor to exercise the UI policy. + // No JobHandle, host status, PreviewInfo or GPU executor is fabricated. + fn install_policy_partial(h: &mut Harness, handle: &JobHandle, passes: u32, prefix: u64, sequence: u64) -> interactive::PartialSampling { + use sha2::{Digest, Sha256}; + let status = handle.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + let source = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + let plan = PartialPreviewPlan::new(status.request.width, status.request.height).unwrap(); + let mut pixels = Vec::new(); + for index in 0..usize::try_from(plan.pixels()).unwrap() { + let source_index = plan.source_index(index).unwrap(); + let count = passes + u32::from((source_index as u64) < prefix); + if count == 0 { + pixels.extend_from_slice(&[0, 0, 0, 0]); + } else { + let x = source_index % status.request.width as usize; + let y = source_index / status.request.width as usize; + pixels.extend_from_slice(&source.get_pixel(x as u32, y as u32).0); + } + } + let png = super::partial_png_contract_encode(plan.width(), plan.height(), pixels); + let mut frame_info = frame.info.clone(); + frame_info.width = plan.width(); + frame_info.height = plan.height(); + frame_info.png_bytes = png.len() as u64; + frame_info.png_sha256 = format!("{:x}", Sha256::digest(&png)); + let info = PartialPreviewInfo { + frame: frame_info, + sequence, + source_width: status.request.width, + source_height: status.request.height, + completed_passes: passes, + updated_prefix: prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }; + let covered = vec![0; usize::try_from(plan.pixels()).unwrap()]; // committed misses have zero hit coverage + let expected = interactive::PartialExpectation { + job: handle.id(), + scene_generation: status.scene_generation, + request: &status.request, + final_dimensions: [status.request.width, status.request.height], + }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), covered.len(), None).unwrap().unwrap(); + let image = + interactive::decode_partial_image(&status.request, &info, &png, &covered, sampling, h.ctx.input(|input| input.max_texture_side)).unwrap(); + let texture = h.ctx.load_texture("manual_final_policy_partial", image, egui::TextureOptions::NEAREST); + h.app.render_workspace.final_partial = Some(FinalPartialImage { info, sampling, image: Ok(texture) }); + sampling + } + + #[test] + fn native_manual_final_gui_opt_in_preserves_request_and_promotes_only_real_final() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "gui_opt_in") else { return }; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let stored = setups::snapshot(&h.app).unwrap(); + assert!(serde_json::to_value(&stored).unwrap().get("progressive_feedback").is_none()); + let offline = image_request(&h.app).unwrap(); + assert!(offline.get("progressive_feedback").is_none()); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + h.app.render_workspace.view.raytrace.progressive = None; + assert!(image_params(&h.app).unwrap().get("progressive_feedback").is_none()); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 9, seed: 83 }); + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, request); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!((status.request.width, status.request.height), (13, 7)); + let progressive = status.request.raytrace.as_ref().unwrap().progressive.unwrap(); + assert_eq!((progressive.samples_per_pixel, progressive.seed), (9, 83)); + let image = image::load_from_memory(handle.frame().unwrap().unwrap().png()).unwrap().to_rgba8(); + assert!(image.pixels().all(|pixel| pixel.0 == [17, 89, 203, 255])); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert!(display.preview.is_none() && display.partial.is_none()); + assert_eq!(display.logical_size, [13, 7]); + assert_eq!(display.info.job, handle.id()); + assert_eq!(setups::snapshot(&h.app).unwrap(), stored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn native_final_partial_policy_keeps_global_unknown_full_framing_and_real_final_priority() { + let Some(mut h) = fixture(1025, 1, 3, [17, 89, 203], "partial_policy") else { return }; + let handle = actual_final(&mut h); + assert!(h.app.render_workspace.view.completed.is_none()); + // The top-left 1024 representatives are known, but source pixel1024 is not. + let sampling = install_policy_partial(&mut h, &handle, 0, 1024, 1); + assert!(sampling.source_unknown()); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 1024); + let display = displayed_image(&h.app).unwrap(); + assert!(display.provisional() && display.partial.is_some() && display.preview.is_none()); + assert_eq!(display.logical_size, [1025, 1]); + assert_eq!((display.info.width, display.info.height), (1024, 1)); + assert_eq!(display.image.as_ref().unwrap().size(), [1024, 1]); + assert!(reduced_display(&h.app)); + let camera = Camera { distance: 37.0, ..Default::default() }; + h.app.render_workspace.view.result_camera = camera; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_job = Some(handle.id()); + let report = handle.protected_preview_report().unwrap(); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert_eq!(display.logical_size, [1025, 1]); + assert!(!reduced_display(&h.app)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + invalidate_images(&mut h.app); + assert!(h.app.render_workspace.final_partial.is_none()); + assert_eq!(handle.protected_preview_report().unwrap(), report, "presentation invalidation cannot reset the actual ledger"); + } + + #[test] + fn native_late_complete_policy_preserves_retained_export_then_reconciles_actual_frame() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "late_complete") else { return }; + let first = actual_final(&mut h); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + let first_bytes = first.frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.draft.background = [91, 33, 187]; + let second = actual_final(&mut h); + assert_eq!(h.app.render_workspace.view.completed, Some(first.id())); + install_policy_partial(&mut h, &second, 0, 5, 1); + assert!(displayed_image(&h.app).unwrap().provisional()); + let old_path = h.dir.join("manual-final-retained.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":old_path})).unwrap(); + assert_eq!(std::fs::read(&old_path).unwrap(), first_bytes); + // Regression oracle for the observed event order: + // frame read absent -> later real status Completed -> real frame promoted + // BEFORE provisional clear/fallback. This calls the production policy on + // an actual completed native handle; it does not fake the earlier read. + assert!(!final_job_still_running(&mut h.app, &second)); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + cache_render_images(&mut h.app, &ctx); + assert!(!displayed_image(&h.app).unwrap().provisional()); + assert!(h.app.render_workspace.final_partial.is_none()); + let new_path = h.dir.join("manual-final-current.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":new_path})).unwrap(); + assert_eq!(std::fs::read(&new_path).unwrap(), second.frame().unwrap().unwrap().png()); + let final_pixels = image::load_from_memory(&std::fs::read(&new_path).unwrap()).unwrap().to_rgba8(); + assert!(final_pixels.pixels().all(|pixel| pixel.0 == [91, 33, 187, 255])); + assert!(!final_job_still_running(&mut h.app, &first), "a different selected final cannot be reconciled through an old handle"); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + } + fn author_box_optics(h: &mut Harness) { + h.app.run("solid.box", json!({"length":200,"width":200,"height":4,"center":[0,0,2],"body_name":"ManualOptics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = 1; + view.draft.height = 1; + view.draft.background = [255; 3]; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.transparent = false; + view.draft.exposure_ev = 0.0; + view.raytrace.primary_samples = 1; + view.raytrace.lights = Some(Vec::new()); + view.raytrace.shadows = false; + view.cpu.environment = cpu::Environment::Constant; + view.cpu.color = [1.0; 3]; + view.cpu.intensity = 1.0; + h.app.cam = Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "ManualOptics").unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.cpu_optics = true; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + binding.glass.boundary = materials::Boundary::Box; // explicit author choice, not inferred geometry + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.session.mark_saved(); + } + + fn editor_text(h: &mut Harness, events: Vec) -> String { + fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(shape) => { + text.push_str(shape.galley.text()); + text.push('\n'); + } + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, text); + } + } + _ => {} + } + } + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 3200.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("ManualOptics")); + }, + ); + let mut text = String::new(); + for clipped in &output.shapes { + collect(&clipped.shape, &mut text); + } + output.textures_delta.clear(); + text + } + + #[test] + fn certification_note_draws_cpu_check_guidance_in_both_sampling_modes_and_legacy_gpu_note() { + let pending: Value = + serde_json::from_str(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pending/cpu-optical-certification.json"))) + .unwrap(); + let key = "render.cpu_optics_certification"; + for locale in ["ar", "de", "en", "es", "he", "ja", "ko", "vi", "zh"] { + assert_eq!(pending[locale].as_object().unwrap().len(), 1); + assert!(!pending[locale][key].as_str().unwrap().trim().is_empty()); + } + let mut h = Harness::new(); + h.ctx.global_style_mut(|style| style.animation_time = 0.0); + author_box_optics(&mut h); + h.app.render_workspace.view.raytrace.progressive = None; + let cpu_note = h.app.tr(key).to_string(); + let gpu_note = h.app.tr("render.material_certification").to_string(); + assert_ne!(cpu_note, key, "a missing catalog fallback is not a translated note"); + assert_ne!(gpu_note, "render.material_certification"); + let document = h.app.session.doc.clone(); + let before = ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed, + ); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let initial = editor_text(&mut h, Vec::new()); + if !initial.contains(&cpu_note) { + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + let at = crate::scenario::rect_of(&heading).unwrap().center(); + for pressed in [true, false] { + editor_text( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + } + for progressive in [None, Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 })] { + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = progressive; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&cpu_note), "{text}"); + assert!(!text.contains(&gpu_note), "{text}"); + } + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&gpu_note), "{text}"); + assert!(!text.contains(&cpu_note), "{text}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + before, + ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed + ) + ); + // Text/layout evidence only: selecting a note never certifies a CPU/GPU render. + } + + #[test] + fn native_progressive_optical_recipe_keeps_authored_ior_certificate_and_final_capture() { + let Some(mut h) = fixture(1, 1, 5, [255; 3], "progressive_optics") else { return }; + author_box_optics(&mut h); + // This optical capture fixture requires normal incidence. StandardView::Top + // intentionally stops short of the pole; author an exact canonical view + // locally, preserving the shared helper's real near-pole GUI path. + h.app.cam = Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, up: solidcraft_engine::render::UpAxis::Z, ..h.app.cam }; + assert!(h.app.cam.is_valid()); + assert_eq!(h.app.cam.fov, 0.0); + assert_eq!(h.app.cam.distance, 10.0); + assert_eq!(h.app.cam.target, solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0)); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (0.0, std::f64::consts::FRAC_PI_2, 0.0, solidcraft_engine::render::UpAxis::Z) + ); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 }); + // The orthographic pixel's entire jitter support lies in +/-4mm, + // strictly inside the independently authored +/-100mm box footprint. + assert_eq!(h.app.cam.half_height(), 4.0); + for (x, y) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { + let (origin, direction) = h.app.cam.ray(x, y, 1.0, 1.0); + assert!(direction.x.abs() < 1e-12 && direction.y.abs() < 1e-12); + assert!((direction.z.abs() - 1.0).abs() < 1e-12); + let point = origin + direction * ((4.0 - origin.z) / direction.z); + assert!(point.x.abs() <= 4.0 + 1e-9 && point.y.abs() <= 4.0 + 1e-9); + assert!(point.x.abs() < 100.0 && point.y.abs() < 100.0); + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + let optics = &request["raytrace"]["dielectrics"][0]; + assert_eq!(optics["body_name"], "ManualOptics"); + assert_eq!(optics["boundary"], "closed_box"); + assert_eq!(optics["ior"], 1.5, "the production recipe IOR is not reduced for this case"); + for (index, transmission) in [0.98_f64, 0.99, 1.0].into_iter().enumerate() { + let expected = -transmission.ln() / 4.0; + assert!((optics["absorption_per_mm"][index].as_f64().unwrap() - expected).abs() < 1e-15); + } + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert!(!status.options.nested_media); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + let pixel = pixels.get_pixel(0, 0).0; + assert_eq!(pixel[3], 255); + assert!(pixel[..3].iter().any(|value| *value > 0)); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + // Actual CPU capture/completion + nonblack optical smoke, not a full + // Fresnel/TIR oracle or a partial-optical-tree while-running receipt. + } +} + +// These exercise GUI navigation against the real cooperative Raster host. +// They do not qualify CPU raytracing, progressive cadence or GPU rendering. +fn auto_result_raster_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":3,"width":4,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.render_workspace.view.draft.width = 13; + h.app.render_workspace.view.draft.height = 7; + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h +} + +#[test] +fn auto_result_success_opens_once_and_explicit_model_survives_real_completion() { + use solidcraft_engine::render::job::Phase; + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + assert!(!h.app.render_workspace.view.result); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(h.app.render_workspace.view.result); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(ribbon::action_ready(&h.app, "render.export").is_err()); + let request = handle.status().unwrap().request; + assert_eq!((request.width, request.height, request.integrator), (13, 7, Integrator::Raster)); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.result); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result, "publication/repaint must respect an explicit Model selection"); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded cooperative Raster work must complete"); + assert_eq!((frame.info.width, frame.info.height), (13, 7)); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + assert!(ribbon::action_ready(&h.app, "render.export").is_ok()); + for _ in 0..3 { + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn auto_result_disabled_keeps_both_selected_views_through_start_and_completion() { + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + crate::prefs::set(&mut h.app, &json!({"render_open_result_on_start":false})).unwrap(); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(handle.frame().unwrap().is_none()); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + if handle.frame().unwrap().is_some() { + break; + } + } + assert!(handle.frame().unwrap().is_some(), "bounded cooperative Raster work must complete"); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + } +} + +#[test] +fn auto_result_check_invalid_start_and_real_queue_full_preserve_selected_view() { + use solidcraft_engine::render::job::Phase; + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.render_workspace.view.draft.width = 0; + assert!(ribbon::perform_job(&mut h.app, "render.preflight").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(ribbon::perform_job(&mut h.app, "render.start").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + h.app.render_workspace.view.draft.width = 13; + let request = image_params(&h.app).unwrap(); + let mut jobs = Vec::new(); + // Queue two real jobs without registering a GUI job. + // No pump or worker thread runs between admission and the third Start. + for _ in 0..2 { + let reply = h.app.session.execute("render.start", &request).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + jobs.push(handle); + } + ribbon::action_ready(&h.app, "render.start").unwrap(); + let error = ribbon::perform_job(&mut h.app, "render.start").unwrap_err(); + assert!(error.contains("this document already has an active and pending render"), "expected real document QueueFull: {error}"); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + for handle in jobs { + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn product_preview_exposure_is_bounded_without_rewriting_method_or_advanced_intent() { + let mut h = Harness::new(); + h.app.render_workspace.view.samples = 512; + h.app.render_workspace.view.max_depth = 8; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.shadows = false; + let cpu = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + let gpu = (h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len()); + let camera = h.app.cam; + for ev in [-32.0, -3.5, -0.0, 0.0, 1.75, 32.0] { + h.app.render_workspace.view.draft.exposure_ev = ev; + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, ev, "method selection cannot silently reset saved exposure intent"); + let preview = product_preview_exposure(&h.app).unwrap(); + // Model uses the common EV for every final method, even with Interactive Off. + // This intentionally supersedes this unpublished test's Raster-only helper contract. + assert_eq!(preview.ev(), ev as f32); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), cpu); + assert_eq!((h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed), gpu); + } + } + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -32.001, 32.001] { + h.app.render_workspace.view.draft.exposure_ev = invalid; + let error = product_preview_exposure(&h.app).unwrap_err(); + assert_eq!(error, h.app.tr("render.product_exposure_invalid")); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev.to_bits(), invalid.to_bits(), "a refusal must not clamp or replace intent"); + // The real Model show route must report the typed exposure refusal before + // its no-GPU fallback, without starting a final or Interactive capture. + let mut output = h.ctx.run_ui(Default::default(), |ui| show(&mut h.app, ui)); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.text() == error)); + output.textures_delta.clear(); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), history); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn raster_shot_exposure_uses_the_existing_slider_and_one_undoable_saved_command() { + let mut h = frame_editor_fixture(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Exposure subject"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + select_image_method(&mut h.app, ImageMethod::Raster); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 0.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), saved.exposure_ev as f32); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + #[cfg(not(target_arch = "wasm32"))] + { + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let (_, geometry) = gpu_scene(&scene).unwrap(); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let capture = |exposure| { + crate::gpu::render_product_offscreen_exposure( + geometry.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], if camera.fov > 0.0 { 1.0 } else { 0.0 }], + 64, + false, + exposure, + ) + }; + if let Some(zero) = capture(Default::default()) { + let exposed = capture(product_preview_exposure(&h.app).unwrap()).expect("the same supported capture route must complete"); + assert_ne!(exposed, zero, "saved GUI exposure must reach actual product-shader pixels"); + assert_eq!(&exposed[..4], &zero[..4], "the capture backplate is not exposed"); + assert_eq!(capture(Default::default()).unwrap(), zero, "returning to zero restores the exact captured response"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=true"); + } else { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GUI product capture is unavailable"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=false"); + } + } + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Original F1 regressions: real native accepted pixels, no injected cache/frame. +// This first alignment block covers accepted camera and framing, not a new +// proof of all possible scene/placement/visibility changes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let handle = interactive::test_current(&h.app).unwrap().unwrap(); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((accepted.job, samples, complete), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let end = at + egui::vec2(28.0, 12.0); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed: true, modifiers: egui::Modifiers::NONE }, + ], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(end)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Middle, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_ne!(h.app.cam.target, camera.target, "the real shared middle-pan must have moved the camera"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app), "this is known paused evidence, not the existing blank/Unknown guard"); + assert!(interactive::blocks_geometry_input(&h.app)); + let viewport = h.app.viewport.rect.unwrap(); + let geometry_rect = interactive::geometry_input_rect(&h.app, viewport); + let projection = crate::viewport::projection(&h.app, geometry_rect); + let current_hit = projection.to_screen(camera.target).unwrap(); + assert!(geometry_rect.contains(current_hit)); + assert!( + crate::viewport::pick(&h.app, &projection, current_hit) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }), + "prove there really is a current-camera target for the new guard to reject" + ); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none() && h.app.session.selection.is_empty()); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + let (retained, retained_samples, retained_complete, retained_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (retained.job, retained.png_sha256, retained_samples, retained_complete, retained_texture), + (job, accepted.png_sha256, samples, complete, texture) + ); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.01, false, true); + assert!(painted, "the retained image stays visible as a reference"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + interactive_assert_final_export_isolation(&mut h, &handle); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let viewport = h.app.viewport.rect.unwrap(); + let pixels = interactive::geometry_input_rect(&h.app, viewport); + assert!(pixels.width() < viewport.width(), "the original square image is letterboxed in this landscape viewport"); + assert!((pixels.width() - pixels.height()).abs() <= f32::EPSILON * pixels.height().max(1.0)); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assert!(!interactive::blocks_geometry_input(&h.app), "Pause alone and an earlier appearance edit cannot block aligned input"); + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Subject"].name, name); + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::blocks_geometry_input(&h.app)); + } + assign::stop(&mut h.app); + let selection = h.app.session.selection.clone(); + let outside_pixels = egui::pos2(viewport.left() + 1.0, viewport.center().y); + assert!(!pixels.contains(outside_pixels)); + interactive_canvas_input_click(&mut h, &mut time, outside_pixels, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection, "letterbox margins are not pixel-aligned CAD targets"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let width = h.app.render_workspace.view.draft.width; + assert!(!interactive::blocks_geometry_input(&h.app)); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "start a real drag against aligned accepted pixels"); + h.app.render_workspace.view.draft.width = width * 2; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(!assign::cancel(&mut h.app), "the blocked release must drain the real drag"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + (h.app.session.revision, h.app.session.undo.len()), + (revision, undo), + "the guard must stop a framing-only drag without relying on the document revision guard" + ); + h.app.render_workspace.view.draft.width = width; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the accepted aspect restores aligned same-camera input"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app), "the manual Result path owns its own camera and input policy"); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app) && interactive::blocks_geometry_input(&h.app)); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +// Geometry/placement/visibility successor: original native snapshots and CAD +// commands only. No injected publications, host factory or scheduling barrier. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels") + else { + return; + }; + let world = h.app.session.interactive_cached_world_state().unwrap(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let retained = interactive::test_cache(&h.app).unwrap(); + assert_eq!((retained.0.job, retained.1, retained.2), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("solid.move", json!({"bodies":["Subject"],"translate":[2,0,0]})).unwrap(); + let moved = h.app.session.interactive_cached_world_state().unwrap(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "must reject before observed is refreshed, using accepted capture authority"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let center = moved.body("Subject").unwrap().mesh().bounds().center(); + let at = projection.to_screen(center).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }) + ); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let after = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (after.0.job, after.0.png_sha256, after.1, after.2, after.3), + (retained.0.job, retained.0.png_sha256, retained.1, retained.2, retained.3) + ); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned") + else { + return; + }; + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"center":[22,0,2],"body_name":"Other"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + let world = h.app.session.interactive_cached_world_state().unwrap(); + let camera = h.app.cam; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":false})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "unchanged world alone cannot certify a changed visible body set"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(world.body("Other").unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Other") }), + "a still-visible current-world target exists" + ); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":true})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the exact accepted visibility can restore alignment without recapture"); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Other".into() })); + assert!(!interactive::blocks_geometry_input(&h.app), "selection is not a scene invalidation"); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.doc.appearances.bodies["Other"].name, name); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert!(!interactive::blocks_geometry_input(&h.app), "render-only refresh must keep the accepted geometric identity usable"); + } + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world() { + for capture in [true, false] { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world") + else { + return; + }; + let component = h.app.run("component.create", json!({"name":"AlignmentPart","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"body_name":"Placed"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let world = h.app.session.world_state(); // Explicit real test preparation, never performed by the guard. + let placed = world.bodies.iter().find(|body| body.name != "Subject").unwrap().name.clone(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[3,0,0],"capture":capture})).unwrap(); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "a missing/stale prepared world is not accepted-scene authority"); + let moved = h.app.session.world_state(); // Warm through the ordinary API only in the original test. + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(interactive::blocks_geometry_input(&h.app), "warming a new current world must not bless the old accepted pixels"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(moved.body(&placed).unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == &placed) }) + ); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let new_job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + assert_ne!(new_job, job); + assert!(!interactive::blocks_geometry_input(&h.app), "only the new accepted capture can establish the moved scene"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +// Common Model EV must stop at captured-image boundaries; these use real producers. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "real show has no product-GPU fallback in this fixture"); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, false); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.raster_exposure_ev, 0.0, "CPU request must not gain a second Raster EV"); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, 1.0); + let frame = held.job.frame().unwrap().unwrap(); + let original = frame.png().to_vec(); + held.sender.send(held.reply).unwrap(); + let (mut accepted, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + let texture = interactive::test_cache(&h.app).unwrap().3; + let uploaded = &accepted.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [16, 16]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + accepted.textures_delta.clear(); + + // Current capture first, then a paused image after a different common EV edit. + // Both must paint their captured texture, without entering the live Model branch. + for (step, ev) in [1.0, 2.0].into_iter().enumerate() { + if step == 1 { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.exposure_ev = ev; + } + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), ev as f32); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4 + step as f64 * 0.1), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.error_gpu_preview"))); + assert!(!output.textures_delta.set.contains_key(&texture), "captured PNG is not uploaded or graded again"); + output.textures_delta.clear(); + assert!( + h.ctx.tessellate(output.shapes, output.pixels_per_point).iter().any( + |shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty()) + ) + ); + let (cached, samples, complete, id) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256, samples, complete, id), (held.job.id(), frame.info.png_sha256.clone(), 16, true, texture)); + assert_eq!(held.job.frame().unwrap().unwrap().png(), original.as_slice()); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch a replacement capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn product_preview_exposure_does_not_regrade_or_validate_a_retained_real_result() { + let mut h = auto_result_raster_fixture(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded real cooperative Raster result"); + let original = frame.png().to_vec(); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + let mut texture = None; + for ev in [1.0, -1.0, f64::NAN] { + h.app.render_workspace.view.draft.exposure_ev = ev; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(&mut h.app, ui), + ); + assert!(h.app.render_workspace.view.result); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + if let Some(prior) = texture { + assert_eq!(id, prior); + assert!(!output.textures_delta.set.contains_key(&id)); + } else { + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [13, 7]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels + .pixels + .iter() + .zip(png.pixels()) + .all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + } + texture = Some(id); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.product_exposure_invalid"))); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty())) + ); + assert_eq!(handle.frame().unwrap().unwrap().png(), original.as_slice()); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + } + let path = h.dir.join("common-model-ev-retained-result.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), original); +} + +#[test] +fn editing_an_inactive_selected_shot_keeps_the_active_setup_draft_and_camera() { + let mut h = frame_editor_fixture(); + assert_eq!(shot::selected(&h.app), Some("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Studio", "selection does not activate a saved setup"); + let active = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let camera = h.app.cam; + let before = h.app.session.doc.to_json(); + let studio = h.app.session.doc.render.setups.get("Studio").cloned(); + let mut expected_hero = h.app.session.doc.render.setups["Hero"].clone(); + expected_hero.exposure_ev = 1.5; + let undo = h.app.session.undo.len(); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Hero"], expected_hero); + assert_eq!(h.app.session.doc.render.setups.get("Studio").cloned(), studio); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1, "only the saved Hero edit enters history"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); +} + +// Integration of the common ±32 EV contract with the existing Shot editor. +// This exercises egui input and the saved command, without opening a GPU device. +#[test] +fn cpu_shot_exposure_reaches_extended_range_via_slider_and_one_saved_command() { + let mut h = frame_editor_fixture(); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"job":{"method":"cpu_raytrace"},"exposure_ev":0.0}})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.875, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 16.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + // The shared production constructor captures portable intent without host admission. + assert!(!setups::has_runtime_inputs(&h.app)); + assert_eq!(image_request(&h.app).unwrap()["settings"]["exposure_ev"], json!(saved.exposure_ev)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Explicit catalogue staging, not a scalar appearance assignment or transport oracle. +mod glass_library_bridge { + use super::*; + use solidcraft_engine::{ + Sel, + doc::appearance_pack::{Recipe, STARTER_PACK}, + }; + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"body_name":"Optics"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Optics".into() }]})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.stage = Stage::Look; + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 64; + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.session.mark_saved(); + h + } + + #[test] + fn library_bridge_stages_all_six_authored_recipes_without_cpu_permission_or_design_changes() { + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut h = fixture(); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let options = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + library::stage_glass(&mut h.app, preset.id).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert_eq!(binding.target.name, "Optics"); + assert!(binding.target.stable_target.is_some()); + assert!(binding.glass_enabled && !binding.cpu_optics && !binding.maps_enabled && !binding.coat_enabled); + assert_eq!(binding.glass.recipe, Some(preset.id)); + assert_eq!(binding.glass.ior, recipe.dielectric_ior); + for (sigma, transmission) in binding.glass.absorption.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + match recipe.boundary { + solidcraft_engine::doc::appearance_pack::GlassBoundary::Closed => { + assert_eq!(binding.glass.boundary, materials::Boundary::Closed); + assert!(!binding.glass.shadows); + } + solidcraft_engine::doc::appearance_pack::GlassBoundary::Thin { thickness_mm } => { + assert_eq!(binding.glass.boundary, materials::Boundary::Thin); + assert_eq!(binding.glass.thickness, thickness_mm); + assert!(binding.glass.shadows, "preparing a Thin recipe is not consent to remove transmitted shadows"); + } + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), options); + assert!(runtime_image_request(&h.app, false).is_err(), "CPU permission is still explicit"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if items == &h.app.session.selection)); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + count += 1; + } + assert_eq!(count, 6); + } + + #[test] + fn library_bridge_requires_stable_glass_id_and_keeps_scalar_assignment_guards() { + let mut h = fixture(); + let opaque = STARTER_PACK.iter().find(|p| matches!(p.recipe, Recipe::Opaque(_))).unwrap(); + for id in ["Glass - Clear", "Glass Recipe - Low Iron Clear", opaque.id, "starter.glass.not-a-recipe"] { + assert!(library::stage_glass(&mut h.app, id).is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + let catalog = h.app.run("appearance.library", json!({})).unwrap(); + let glass = catalog["appearances"].as_array().unwrap().iter().find(|p| p["id"] == "starter.glass.low-iron-clear").unwrap(); + assert_eq!(glass["available"], false); + for appearance in ["starter.glass.low-iron-clear", "Glass Recipe - Low Iron Clear"] { + assert!(h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":appearance,"color":"#ffffff","opacity":1.0})).is_err()); + } + h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":"Glass - Clear"})).unwrap(); + assert!(h.app.session.doc.appearances.bodies["Optics"].opacity < 1.0); + assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "legacy alpha is never promoted to physical glass"); + } + + #[test] + fn library_bridge_refuses_face_component_empty_multiple_and_raster_targets() { + let mut h = fixture(); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + let hit = crate::viewport::Hit::Face { body: "Optics".into(), index: 0, point: solidcraft_engine::geom::Vec3::ZERO }; + let face = crate::viewport::candidate(&h.app, &[hit]).unwrap().1; + assert!(matches!(face, Sel::Face { .. })); + let component = h.app.run("component.create", json!({"name":"Unassigned component"})).unwrap(); + let occurrence = component["occurrence"].as_u64().unwrap(); + for selection in [ + vec![], + vec![face], + vec![Sel::Occurrence { path: vec![occurrence] }], + vec![Sel::Body { name: "Optics".into() }, Sel::Body { name: "Optics".into() }], + ] { + h.app.session.selection = selection; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + h.app.session.selection = vec![Sel::Body { name: "Optics".into() }]; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + } + + #[test] + fn library_bridge_hidden_stale_document_and_changed_target_never_refresh_a_binding() { + let mut h = fixture(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + h.app.session.visibility.hidden_bodies.clear(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings[0].target.ordinal += 1; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].target.ordinal, original.target.ordinal + 1); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.session.doc = Arc::new((*h.app.session.doc).clone()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err(), "CAD revision is not silently revalidated"); + } + + #[test] + fn library_bridge_conflicts_preserve_permission_shadows_scattering_and_other_material_intent() { + for conflict in 0..4 { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.thin-clear").unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = true; + match conflict { + 0 => binding.coat_enabled = true, + 1 => binding.maps_enabled = true, + 2 => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => binding.glass.ior = 1.7, + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_exact_repeat_preserves_existing_cpu_permission_disabled_state_and_values() { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + h.app.render_workspace.view.materials.bindings[0].enabled = false; + h.app.render_workspace.view.materials.enabled = false; + let before = format!("{:?}", h.app.render_workspace.view.materials); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + } + + #[test] + fn library_bridge_respects_authoring_and_cpu_target_caps_without_activating_other_bindings() { + for (method, count, active) in [(ImageMethod::GpuRaytrace, 128, false), (ImageMethod::CpuRaytrace, 8, true)] { + let mut h = fixture(); + h.app.render_workspace.view.method = method; + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|t| t.name == "Optics").unwrap(); + for i in 0..count { + let mut other = target.clone(); + other.name = format!("Other{i}"); + let mut binding = materials::Binding::new(other, &h.app); + binding.glass_enabled = active; + h.app.render_workspace.view.materials.bindings.push(binding); + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_keeps_closed_thin_and_strict_cpu_choices_explicit_without_a_transport_claim() { + let mut h = fixture(); + h.app.render_workspace.view.raytrace.dielectric_transport = solidcraft_engine::render::job::CpuDielectricTransport::StrictTir; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.25, 0.5, 0.75]; + h.app.render_workspace.view.cpu.intensity = 2.0; + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).is_err(), "Closed is not silently certified Box"); + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + let wire = runtime_image_request(&h.app, false).unwrap(); + assert_eq!(wire["raytrace"]["dielectric_transport"], "strict_tir"); + assert_eq!(wire["raytrace"]["dielectrics"][0]["ior"], 1.5); + assert_eq!(wire["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.25); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["environment"]["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(wire["raytrace"]["environment"]["intensity"], 2.0); + assert!(setups::snapshot(&h.app).is_err(), "transient staging never becomes saved CPU optics"); + // This checks routing only. A real StrictTir LimitExceeded remains FAIL for G02-C. + } + + #[test] + fn clicked_library_glass_action_reaches_existing_body_editor_and_never_reports_applied() { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + let mut view = std::mem::take(&mut h.app.render_workspace.view.library); + library::choose(&mut h.app, &mut view, "appearances", "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.library = view; + h.frames(3); + let doc = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:library:prepare-glass"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + assert!(!h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert!( + matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if matches!(items.as_slice(), [Sel::Body {name}] if name == "Optics")) + ); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + } + + #[test] + fn library_bridge_messages_cover_every_current_delivered_locale() { + let messages: Value = serde_json::from_str(include_str!("../../../assets/locales/pending/render-glass-library-route.json")).unwrap(); + for locale in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + for id in [ + "render.glass_library_conflict", + "render.glass_library_edit", + "render.glass_library_help", + "render.glass_library_method", + "render.glass_library_prepared", + ] { + assert!(messages[locale][id].as_str().is_some_and(|s| !s.is_empty()), "{locale}/{id}"); + } + } + } +} + +#[test] +fn cpu_partial_coverage_crosses_u16_boundary_without_relaxing_alpha_or_sample_frontier() { + for count in [65_535, 65_536, 1_048_576] { + assert!(interactive::validate_partial_pixel(count, count, Color32::BLACK, [40, 80, 120]).is_ok()); + assert!(interactive::validate_partial_pixel(count, count + 1, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(count, count, Color32::TRANSPARENT, [40, 80, 120]).is_err()); + assert_eq!(interactive::partial_sample_count(count, 0, 0, 1, 1_048_576).unwrap(), count); + } + assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(65_536, 0, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(65_536, 0, Color32::from_rgb(40, 80, 120), [40, 80, 120]).is_ok()); + assert!(interactive::partial_sample_count(65_536, 1, 0, 1, 65_536).is_err()); +} + +#[test] +fn cpu_progressive_editor_preserves_high_intent_without_resizing_or_changing_profile_seed_or_mode() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.raytrace.budget = CpuBudget::Workstation; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: u32::MAX }); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + for budget in [CpuBudget::Workstation, CpuBudget::Compact, CpuBudget::Studio] { + h.app.render_workspace.view.raytrace.budget = budget; + let before = json!(h.app.render_workspace.view.raytrace); + let ctx = egui::Context::default(); + let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(cpu::progressive_controls(&mut h.app, ui)); + }); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before, "painting cannot clamp retained intent to a different profile"); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1, 1)); + assert_eq!(cpu::validate_progressive_image(&h.app).is_ok(), budget == CpuBudget::Workstation); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); +} + +// Request/consumer coverage only. Real native per-pass presentation remains +// mandatory acceptance; see the archived unsupported cooperative-host fixture. +#[test] +fn cpu_progressive_request_keeps_explicit_target_seed_without_claiming_native_pass_presentation() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 4, seed: 741 }); + let document = h.app.session.doc.clone(); + let before = json!(h.app.render_workspace.view.raytrace); + let request = interactive_request(&h.app).unwrap(); + assert_eq!(request["raytrace"]["progressive"]["samples_per_pixel"], 4); + assert_eq!(request["raytrace"]["progressive"]["seed"], 741); + assert_ne!(request["progressive"], json!(true), "CPU intent cannot select a registered GPU executor"); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation() { + use solidcraft_engine::render::job::{CpuProgressiveOptions, Phase}; + use std::{sync::mpsc, time::Duration}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation") { + return; + } + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); + let before = json!(h.app.render_workspace.view.raytrace); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + // Withhold only the real worker reply. All frame bytes come from the renderer. + let mut pending = h.app.render_workspace.interactive.pending.take().unwrap(); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).unwrap(); + assert!(matches!(&reply, Ok(true)), "{reply:?}"); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 })); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert!(!frame.png().is_empty()); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + sender.send(reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, samples, complete), (job.id(), 31, true)); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + let egui::ImageData::Color(pixels) = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + output.textures_delta.clear(); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 47, seed: 999 }); + let expected = crate::i18n::format("render.interactive_samples", &[("done", "31"), ("total", "31")]); + let controls = h.ctx.run_ui(egui::RawInput::default(), |ui| interactive::controls(&mut h.app, ui)); + assert!(crate::test_support::text_shapes(&controls).any(|shape| shape.galley.text() == expected)); + assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn interactive_retention_skip_inspect_is_null_without_an_admitted_capture() { + let h = Harness::new(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off() { + let mut h = interactive_ui_fixture(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); + if !interactive_test_cpu_branch(&mut h, "interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off") { + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null(), "enabling without an admitted job cannot fabricate zero"); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let captured = held.job.status().unwrap(); + assert_eq!(captured.cpu_preview_retention_skips, 0); + assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(captured.cpu_preview_retention_skips)); + interactive_assert_final_export_isolation(&mut h, &held.job); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(0)); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); +} + +// Typed consumer state only: this texture is input to the absent-slot policy. +// It is not a renderer PNG, a CPU admission fixture, or per-pass UI acceptance. +fn cpu_preview_consumer_fixture(ctx: &egui::Context) -> (State, JobId, solidcraft_engine::render::job::JobStatus) { + use solidcraft_engine::render::job::{ + AlphaConvention, ColourEncoding, CpuProgressiveOptions, FrameInfo, ImageRequest, JobOptions, JobStatus, Phase, Progress, RaytraceOptions, + }; + use solidcraft_engine::render::{BackendId, ExecutorId, RenderMode, RenderOperation, RenderProfile, ResolvedRequest}; + let job = JobId { session: 9012, serial: 1, generation: 1 }; + let backend = BackendId::new("consumer-fixture").unwrap(); + let executor = ExecutorId::new("consumer-fixture").unwrap(); + let frame = FrameInfo { + job, + scene_generation: 19, + backend: backend.clone(), + executor: executor.clone(), + width: 1, + height: 1, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: 0, + png_sha256: String::new(), + }; + let texture = + ctx.load_texture("consumer-only-input", egui::ColorImage::new([1, 1], vec![Color32::from_rgb(40, 80, 120)]), egui::TextureOptions::LINEAR); + let mut state = State::default(); + state.view.job = Some(job); + state.preview_image = Some(PreviewImage { info: PreviewInfo { frame_sequence: 2, samples_per_pixel: 2, frame }, image: Ok(texture) }); + let request = ImageRequest { + raster_exposure_ev: 0.0, + raster_lights: None, + raster_punctual_lights: None, + raster_area_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + primary_samples: 1, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 7, seed: 741 }), + ..Default::default() + }), + camera: Default::default(), + width: 1, + height: 1, + background: [40, 80, 120], + transparent_background: false, + }; + let status = JobStatus { + cpu_preview_retention_skips: 1, + punctual_diagnostics: None, + presentation: None, + sampling: None, + linear_master: None, + preview: None, + textures: None, + options: JobOptions::default(), + environment: None, + job, + scene_generation: 19, + request, + resolved: ResolvedRequest { + backend, + executor, + profile: RenderProfile { mode: RenderMode::Preview, operation: RenderOperation::Image, formats: Vec::new(), features: Vec::new() }, + width: 1, + height: 1, + format: None, + estimated_scratch_bytes: 0, + warnings: Vec::new(), + }, + progress: Progress { phase: Phase::Running, done: 3, total: 7 }, + error: None, + frame: None, + }; + (state, job, status) +} + +#[test] +fn cpu_missing_snapshot_consumer_keeps_exact_pixels_identity_and_pass_only_for_certified_live_capture() { + let ctx = egui::Context::default(); + let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); + let before = state.preview_image.as_ref().unwrap(); + let texture = before.image.as_ref().unwrap().id(); + let identity = (before.info.frame.job, before.info.frame.scene_generation, before.info.frame_sequence, before.info.samples_per_pixel); + status.progress.done = 4; + reconcile_missing_cpu_preview(&mut state, job, Some(&status)); + let kept = state.preview_image.as_ref().unwrap(); + assert_eq!(kept.image.as_ref().unwrap().id(), texture); + assert_eq!((kept.info.frame.job, kept.info.frame.scene_generation, kept.info.frame_sequence, kept.info.samples_per_pixel), identity); + assert_eq!(kept.info.samples_per_pixel, 2, "producer progress cannot relabel accepted pixels"); + assert!(state.view.completed.is_none(), "retention cannot manufacture final authority"); +} + +#[test] +fn cpu_missing_snapshot_consumer_clears_wrong_capture_cancel_error_final_and_lookup_failure() { + use solidcraft_engine::render::job::{ErrorCode, JobError, Phase}; + let ctx = egui::Context::default(); + for case in 0..13 { + let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); + let mut lookup_ok = true; + match case { + 0 => status.job.serial += 1, + 1 => status.scene_generation += 1, + 2 => status.request.width += 1, + 3 => status.progress.phase = Phase::Cancelling, + 4 => status.progress.phase = Phase::Cancelled, + 5 => status.progress.phase = Phase::Failed, + 6 => status.progress.phase = Phase::Completed, + 7 => status.error = Some(JobError::new(ErrorCode::Internal, "consumer fixture status error")), + 8 => status.frame = Some(state.preview_image.as_ref().unwrap().info.frame.clone()), + 9 => status.cpu_preview_retention_skips = 0, + 10 => status.request.raytrace.as_mut().unwrap().progressive = None, + 11 => state.preview_image.as_mut().unwrap().image = Err("consumer fixture decode error".into()), + 12 => lookup_ok = false, + _ => unreachable!(), + } + reconcile_missing_cpu_preview(&mut state, job, lookup_ok.then_some(&status)); + assert!(state.preview_image.is_none(), "case {case}"); + assert!(state.view.completed.is_none()); + } + let mut h = Harness::new(); + let (mut state, job, _) = cpu_preview_consumer_fixture(&ctx); + state.view.job = None; + h.app.render_workspace = state; + cache_preview_image(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + let (state, _, _) = cpu_preview_consumer_fixture(&ctx); + h.app.render_workspace = state; + assert!(h.app.session.render_job_handle(job).is_err(), "consumer fixture is deliberately not an admitted job"); + cache_preview_image(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); +} diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-progressive.md b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-progressive.md new file mode 100644 index 000000000..b7e49602e --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-progressive.md @@ -0,0 +1,228 @@ +# CPU progressive camera sampling + +The limits below describe the compatibility **Compact** profile. Explicit Studio and Workstation envelopes are documented in [CPU resource profiles](render-cpu-resource-profiles.md); their implementation batch still requires consolidated validation. + +The every-pass cadence and bounded snapshot policy below describe a composed +source proposal awaiting integration and validation, not a new native display or +CI result. The earlier published policy used powers-of-two checkpoints. This is +an intentional requested behavior change; its default-change classification and +preference handling remain unresolved before production readiness. This document +does not settle that process question. + +CPU progressive rendering repeatedly traces fresh camera samples into a bounded +linear-light film. Each complete nonfinal pass, 1 through the requested count +minus one, is a checkpoint boundary. Normal consumption publishes each boundary; +the diagnosed external-retention exception is defined below. The exact requested +count produces one final PNG, including non-powers of two such as 3 or 5. A +one-sample job has no nonfinal complete-pass checkpoint. Optional first-pass +partial-coverage feedback is separate from a uniform checkpoint. Publication +does not guarantee that a slower client physically repaints every image. + +This mode uses the native `cpu-raytrace` executor and its existing direct-light +and selected-reflection transport. It does not add diffuse global illumination, +caustics, adaptive convergence, a denoiser, or general glass path tracing. + +## Request and saved intent + +The CPU option is nested inside `raytrace`. The top-level `progressive: true` +request continues to select the registered GPU path executor. + +```json +{ + "integrator": "raytrace", + "settings": { "width": 512, "height": 512 }, + "raytrace": { + "progressive": { "samples_per_pixel": 32, "seed": 81 }, + "primary_samples": 1, + "exposure_ev": 0, + "shadows": true + } +} +``` + +Both `render.preflight` and `render.start` use this request. Missing or null +`raytrace.progressive` preserves the existing fixed 1/4/16 spatial AA route. +An explicit empty progressive object defaults to 16 samples and seed 0. The +seed is an unsigned 32-bit integer. Unknown fields are rejected. + +The corresponding portable setup is: + +```json +{ + "name": "CPU film", + "set": { + "width": 512, + "height": 512, + "exposure_ev": 1, + "job": { + "method": "cpu_raytrace", + "options": { + "progressive": { "samples_per_pixel": 32, "seed": 81 }, + "primary_samples": 1 + } + } + } +} +``` + +This is a `render.settings.set` request. Exposure is stored once in the setup; +normalization transfers it into the CPU request. Film storage, checkpoint PNGs, +job identities, cancellation state and host reservations are never serialized +into the design. Saving validates pixel and camera-sample bounds even when no +render host is installed. + +## Supported combinations and limits + +| Control | CPU progressive contract | +| --- | --- | +| Dimensions | Each side 1..4096; at most 1,048,576 pixels | +| Samples per pixel | 1..64 | +| Total camera samples | At most 16,777,216 (`width × height × samples_per_pixel`) | +| Fixed spatial AA | `primary_samples` must be 1 | +| Selected mirror / isotropic rough reflection | Existing bounded depth; `reflections.samples` must be 1 when bodies are selected | +| Directional / point / spot sources | Existing CPU light contracts and limits | +| Constant / captured HDR environment | Existing CPU contracts; HDR plus rough reflections still requires certified fully metallic selected bodies and effective faces | +| Surface emission / isotropic surface effects | Existing CPU appearance contracts; emission is visible radiance | +| Area / LED sources | Existing bounded rectangle direct-light transport; continuous LED recipes lower to the same sources | +| Dielectric overrides | Smooth `thin_sheet` / `closed_box` intent retained; capture certifies geometry, identity and supported combinations | +| Anisotropic face overrides | Explicitly rejected in progressive mode; use fixed sampling | +| Output | Opaque PNG with the existing display background | + +An incompatible request fails; it does not remove settings or switch methods. +The fixed CPU route retains its existing area, dielectric and anisotropy support. +Numerically valid dielectric selectors also survive progressive and Interactive +lowering for capture-time certification. Successful lowering is not scene or job +admission: existing boundary tessellation, captured identity, opacity, camera, +medium and transport-policy limits still apply. The same dielectric body cannot +also select opaque reflection, anisotropy, surface emission or nonidentity surface +effects. Unsupported combinations remain errors; no general glass path is added. +Progressive area/LED uses at most four shared rectangle slots, with +`area_samples` of 1/4/16/64 (default 16) and the existing combined light caps. +Each film pass uses the existing area-power normalization and cumulative work +budget; increasing emitter samples does not multiply emitted power. The area +pattern uses `raytrace.seed`, separately from the camera-jitter seed +`raytrace.progressive.seed`. One emitter sample still uses its centre. This is +direct lighting, with no MIS or diffuse GI; general glass and anisotropic +progressive transport remain unsupported. Host-pool and profile limits are unchanged. +At 1024 × 1024 the camera-sample cap allows at most 16 samples per pixel; at +512 × 512 it allows 64. Requests are also subject to the selected CPU resource profile's geometry, +job-memory and shared-host pool limits; see [CPU resource profiles](render-cpu-resource-profiles.md). Traversal, +shading, film updates and ordinary output work retain the selected profile's +cumulative work ceiling: Compact 1,000,000,000, Studio 1,000,000,000,000 and +Workstation 16,000,000,000,000. The count is not reset at a pass boundary. +Presentation has a separate finite precharge for the bounded early feedback and +nonfinal complete-pass opportunities; increasing the target is not an unbounded +codec/work grant. The camera-sample limit is a cold upper bound, not a promise +that every scene will finish below cumulative work or host-memory limits. + +## Sampling, linear film and display + +Camera jitter is a deterministic counter sequence keyed by the u32 seed, pixel +index and absolute sample ordinal. Reflection and HDR-direct variates use +separate domains of the same counter. Target sample count, worker quantum and +checkpoint cadence are not keys. Consequently, for an unchanged captured +request and scene, a checkpoint at N samples has exactly the same sample prefix +and PNG bytes as a job whose final target is N. + +Each pixel stores three f64 sums and a primary coverage count. Only complete, +uniform passes can be resolved. Camera misses add zero scene radiance and zero +coverage. The resolve computes the mean scene radiance, applies exposure and +the existing tone curve once to covered radiance, composites the display-linear +backplate by coverage, and encodes sRGB once. The background is not illuminated +or exposed. Averaging already tone-mapped sample pixels is not equivalent and +is not used. + +`film::primary::PrimaryFilm` is a compact camera-specific accumulator alongside +the existing statistical `FilmAccumulator`. It has incremental initialization +and requires the exact next scanline pixel and absolute ordinal on every update. +The existing general `FilmAccumulator`/borrowed `FilmPngTask` APIs are retained; +the owned image job uses the shared `PngEncoding` pipeline without a +self-referential borrowed task or a second independent pool. + +## Preview publication and final export + +`JobStatus.preview`, when present, contains: + +```text +PreviewInfo { + frame_sequence: u32, + samples_per_pixel: u32, + frame: FrameInfo +} +``` + +`JobHandle::preview()` returns an `Arc` whose `png()` is the +immutable encoded snapshot. The first checkpoint has sequence 1. The job's +`JobId { session, serial, generation }` and captured `scene_generation` remain +unchanged across every pass. `frame_sequence` counts actual publications, not +samples or skipped boundaries. Clients cache previews by `(JobId, frame_sequence)` +and may retain an older snapshot without mutating it. For example, publications +SPP1/sequence1 and SPP2/sequence2 can be followed by a diagnosed retained-slot +skip at SPP3, then SPP4/sequence3 when a slot returns. The producer still processes +each real pass in order; this exception does not license a fabricated producer +jump from pass1 to pass3. + +The runtime `JobStatus.cpu_preview_retention_skips: u32` counts nonfinal uniform +boundaries whose snapshot could not be published because both reusable slots +were externally retained. Retire an obsolete host-owned snapshot and retry the +credit before diagnosing that condition. Count that boundary once, not each +poll or a later retry of the same boundary. Closed pools, in-flight buffers, +unrequested feedback or an exhausted optional feedback quota are not themselves +evidence of external retention. Cancellation is checked before the diagnostic +update. This counter is runtime metadata, never saved +intent, and does not count frames physically displayed by a client. + +The preview slot is separate from `JobStatus.frame`/`JobHandle::frame()`. A +preview cannot be exported through `render.export`, cannot become the session's +last completed image, and does not release the running task or film. The final +PNG is published only after its digest is complete; it clears the preview slot +and is the only new exportable result. `render.export` writes those exact PNG +bytes and does not render or re-encode them. + +Cancellation clears the preview slot immediately. Failure and completion also +clear it. Publication checks the cancellation token while holding the same +record lock used for cancellation, including after the final digest chunk. +The worker cannot publish a late checkpoint into a cancelled or replaced job. +An externally retained preview remains an immutable snapshot of its original +job, but cannot replace a previous successfully completed final frame. + +## Allocation and retained snapshots + +Admission reserves the working film, existing RGBA/encoder/final-PNG capacity, +and at most two reusable immutable checkpoint slots with their metadata. It no +longer reserves a separate PNG for every possible pass. Protected feedback uses +its existing two partial-snapshot slots. Actual film, sidecar and PNG capacities +remain checked against admitted capacities after fallible allocation; there is +no full-film clone or growing production list of checkpoint PNGs. + +A published snapshot retains a lease for its admitted slot. Replacing or clearing +the host's `Arc` cannot mutate externally held bytes or release their charge. +When the last consumer releases a snapshot, its credit can be reused while the +job is active. Terminal cleanup closes free credits; externally retained leases +stay billed until their last release. Existing working codec and final-image +buffers remain accounted separately. + +If both slots are externally pinned, the diagnosed boundary produces no new +snapshot. The renderer continues sampling and final work without waiting for an +acknowledgement, failing the final merely because of retention, allocating an +extra slot or inventing a frame. Returning a credit permits a later real pass to +publish again. Final-only export, cancellation and captured identity are unchanged. +Even without pinned consumers, a latest-image client can coalesce observations +when it repaints more slowly than the worker; no latency or unconditional +physical-display guarantee follows from every-pass publication. + +## Regression coverage + +The source includes regressions for deterministic prefixes and worker quanta, +fresh primary rays, non-power-of-two targets, actual HDR/rough-reflection PNGs, +linear averaging before tone mapping, coverage and unexposed backgrounds, +bounded/cancelled film mutations, and the single cumulative work budget. + +Host tests manually advance the worker to the digest/publication boundary. They +hold multiple preview `Arc`s through replacement, cancellation and completion, +check allocation identity and exact pool release, and reject an invalid +checkpoint sequence. Document tests cover offline limits and saved round trips. +Engine tests cover Check/Start equality, cold rejection before HDR capture, +session ownership, exact final export, and retention of the previous completed +image after a progressive job is cancelled. Execution evidence belongs to the +integrated CI receipts; this source handoff does not claim those gates passed. diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-resource-profiles.md b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-resource-profiles.md new file mode 100644 index 000000000..0bdf74800 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-resource-profiles.md @@ -0,0 +1,74 @@ +# Explicit CPU resource profiles + +**Composed-source proposal: integration, consolidated validation and large-scene native acceptance are pending.** The raised Workstation target requires the coordinated CPU accumulation, publication and UI adapters. These envelopes are admission limits, not measured performance or a final-quality certification. + +## Intent + +A CPU image must not inherit a small interactive-preview ceiling when the owner explicitly asks for a large still or a heavy assembly. Conversely, opening an old file must not silently authorize substantially more memory or work. + +`job.options.budget` in a saved `cpu_raytrace` setup, or `raytrace.budget` in a runtime CPU request, selects one of three finite profiles. Omission means `compact`, preserving the previous policy. Unknown names, including `unlimited`, are rejected. The CPU dropdown preserves dimensions and sample count when changing profiles; an incompatible draft remains visible until the user corrects it or explicitly accepts proposed dimensions. + +| Envelope | Compact | Studio | Workstation | +|---|---:|---:|---:| +| Maximum side | 4,096 px | 8,192 px | 16,384 px | +| Fixed-sampling pixels | 4,194,304 | 16,777,216 | 67,108,864 | +| Progressive pixels | 1,048,576 | 16,777,216 | 67,108,864 | +| Progressive samples/pixel | 64 | 1,024 | 1,048,576 | +| Total camera samples | 16,777,216 | 4,294,967,296 | 68,719,476,736 | +| Captured triangles | 262,144 | 2,000,000 | 8,000,000 | +| Visible bodies | 16,384 | 65,536 | 262,144 | +| Retained source geometry | 128 MiB | 1 GiB | 4 GiB | +| Complete job admission | 384 MiB | 3 GiB | 12 GiB | +| Cumulative work units | 1,000,000,000 | 1,000,000,000,000 | 16,000,000,000,000 | + +Every column is an intersection of limits: a scene that fits the triangle count may still exceed its complete byte estimate. Similarly, a sample count within the per-pixel limit may exceed the total camera-sample or cumulative traversal-work limit. At 1,048,576 SPP, 256 × 256 already reaches Workstation's unchanged 68,719,476,736 camera-sample ceiling; the high target is not permission to use every resolution. Compact 64 and Studio 1024 remain unchanged. No claim is made that all maxima can be reached simultaneously or within a particular time. + +Examples of cardinality admission, before geometry and memory are considered: Studio permits 3840 × 2160 at 128 samples/pixel; Workstation permits 7680 × 4320 at 128 samples/pixel. Compact rejects both instead of silently resizing them. + +## Example saved intent + +```json +{ + "name": "CPU studio still", + "set": { + "width": 3840, + "height": 2160, + "job": { + "method": "cpu_raytrace", + "options": { + "budget": "studio", + "primary_samples": 1, + "progressive": { "samples_per_pixel": 128, "seed": 82 } + } + } + } +} +``` + +Submit this to `render.settings.set`. `render.preflight` and `render.start` accept the resulting named setup. The preflight reply identifies the CPU budget, all of its limits, and the estimated job admission. `render.backends` also lists the profiles without starting a device or allocating an image. + +Large intent can be saved and reopened without a render host. Executing Studio or Workstation requires a native 64-bit host. A missing feature, unavailable host, unsupported optical combination or exceeded profile is an error, never a switch to another executor. + +## Accounting and responsiveness + +The source-capture gate, dimensions, camera-sample bound, BVH construction, film, encoded checkpoints, environment input, retained request and host reservation consume the same selected policy. Ray tracing no longer adds raster projected-triangle lists to its estimate: its own BVH, captured looks and film are charged instead, alongside a conservative pixel/codec allowance. + +The native CPU host has a finite 16 GiB logical reservation pool on 64-bit platforms, including retained results and previews. It does not allocate that amount at startup, promise that physical RAM is available, or account for the rest of the CAD application or other processes. Per-job profiles remain smaller. Cooperative and registered GPU host pools retain their original 512 MiB limit; this change is not a GPU-memory expansion. + +Fallible allocation, actual vector-capacity checks, checked arithmetic, bounded work quanta, cancellation checks and final-only publication remain required. A failed or cancelled job must release its working reservations and preserve the previous completed result. Progressive publication prepays two reusable snapshot slots plus existing working codec/final capacity, not one PNG per pass. Externally held snapshots keep their leases charged; if both slots are pinned, a diagnosed boundary can be skipped without blocking or failing final work. See [CPU progressive sampling](render-cpu-progressive.md#allocation-and-retained-snapshots). + +Ordinary cumulative work caps remain exactly 1e9 / 1e12 / 16e12 for Compact / Studio / Workstation. The presentation allowance is separate and finite: with P output pixels and target H, at most min(P−1,64)+(H−1) early/uniform opportunities are precharged, each at 14 × preview_pixels + 65,538 units, with preview_pixels at most 1024². This allowance is not extra ordinary traversal work, an admission promise, or a display-latency guarantee. This increment does not implement tiled/out-of-core rendering or unbounded preview retention. + +## Compatibility and limits + +The new pending-format descriptor is `render-cpu-budget`. Old intent has Compact semantics; larger intent is not discarded on reopen. The independent GPU sampling flag remains separate from CPU progressive sampling. Visual material edits still do not change engineering material properties. + +This increment does not introduce CPU diffuse global illumination, adaptive sampling, multithreaded transport, arbitrary dielectric geometry, texture displacement or EXR output. The existing optical-combination restrictions remain explicit. Raising an admission ceiling is not a performance optimization or a claim that every large scene is practical yet. + +## Prepared regression coverage + +Tests cover explicit 4K/8K admission without allocating a large film, BVH cardinality estimates for larger profiles, old/unknown profile handling, offline saved round trips, preservation of incompatible UI drafts, host-pool isolation, arithmetic overflow and linear film accumulation above 64 samples. Their execution belongs to the consolidated batch gate; formatting or static source checks alone do not constitute a passing test run. + +## Display is separate from output + +The result canvas validates image dimensions against the captured job, not a subsequently edited profile. The exported PNG is never resized or re-encoded for display. If a viewport's texture-side limit or the finite display-cache pixel limit is smaller than the result, only its UI preview is reduced, with an explicit warning and native 100% inspection disabled. Full-resolution tiled inspection remains pending. One displayed completed result may be pinned while a newer job completes, preserving exact export and accounting for its retained memory. diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-workspace.md b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-workspace.md new file mode 100644 index 000000000..49de26932 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-cpu-workspace.md @@ -0,0 +1,185 @@ +# CPU controls in the Render workspace + +This incremental panel is built on advanced CPU source tree +`6e5db1e64376164878918eb68f1e5b311740afcd`. It prepares the same existing +`render.preflight` and `render.start` commands. It does not add a renderer, material asset or rendering dependency. The subsequent +numeric setup unit persists the portable subset through `RenderSetup.job`; see +[workspace settings](render-workspace.md#settings-and-product-camera). + +Choose **CPU ray tracing** in Render. Three collapsible sections provide the +following controls; the existing AA 1/4/16, lighting presets, shadows and exposure +remain available in **Single image** sampling mode. + +## Progressive CPU sampling + +**CPU sampling mode → CPU progressive** accumulates samples of the existing CPU +integrator. In the coordinated source proposal, **samples per pixel** is bounded +by the selected profile: Compact 64, Studio 1024 or Workstation 1,048,576, together +with the unchanged pixel/camera-sample and other admission intersections. The +separate CPU sampling seed and explicit target are preserved on save/reopen; +Interactive uses those captured values rather than forcing every request to +16/0. The fallback 16/0 applies only without explicit progressive intent. These +changes require integration, validation and native acceptance. + +Selecting the mode explicitly chooses one primary sample per pass; returning to +**Single image** restores the AA selector without discarding lights or HDR controls. +This is camera sampling of the existing integrator, not diffuse global illumination, +adaptive sampling or CPU denoising. + +The initial progressive path accepts isotropic opaque surfaces and the supported +directional, point and spot lighting. Selected reflections require one reflection +sample. Area lights, LEDs, dielectric overrides and anisotropy must use Single image; +switching modes never silently removes these inputs. Check and Start report an +incompatible combination through the same request validation. + +The compatibility Compact profile allows at most 1,048,576 progressive pixels, +dimensions up to 4096, and 16,777,216 pixel × sample evaluations. For example, +1024 × 1024 supports 16 SPP, whereas 64 SPP requires at most 262,144 pixels. +Explicit larger profiles retain their own intersecting limits; see +[CPU resource profiles](render-cpu-resource-profiles.md). Increasing SPP or loading +a setup never changes its dimensions automatically. If needed, the panel displays a +**Use the largest size at this aspect: W × H** action; only clicking it resizes +the draft. Save applies the same numeric limits without requiring a renderer and +leaves invalid drafts intact. Traversal, sampling and image encoding also share +the backend's cumulative work budget. + +Normal source publication attempts a provisional snapshot at every complete +nonfinal pass 1, 2, 3, …, followed by the unique final at the requested target. Two +reusable snapshot slots bound retention. If both are externally pinned, the +actual runtime `cpu_preview_retention_skips` counter diagnoses that skipped +boundary while final work continues; it does not fabricate an image or sample. +The current-handle inspection diagnostic uses a real count, including zero, or +null when unavailable/failed; lookup errors are not included, and other reported errors are independent. + +Publication is distinct from physical canvas repaint: a fast worker and slower +client can coalesce visible images. A provisional label includes actual SPP and +publication sequence; these need not be equal after a diagnosed skip. Job identity +and captured revision remain unchanged. Checkpoint updates reuse current pan/zoom. +Neither a counter nor the source change proves native 1→2→3→4 display or a latency +bound. Completion replaces the preview with its final image; cancellation or +failure removes the preview and returns to the previous completed +result with the same framing. **Export final PNG** always exports a completed frame, +even while a different provisional image is visible. With no completed frame, export +remains disabled. The UI keeps one decoded provisional texture and metadata, not +additional retained HDR/PNG buffers. + +`CpuJob.progressive` persists the selected sample count and seed. Its absence or +`null` keeps Single image mode. Save As, Reload, setup switching and design reopen +preserve this option together with embedded HDR, nonedited numeric fields and the +setup's single exposure. The runtime CPU request nests it under +`raytrace.progressive`; the top-level `progressive: true` continues to select GPU +path tracing. + +## CPU controls + +| Section | Controls | Runtime limits | +| --- | --- | --- | +| Reflections | Visible body picker and filter, Off / Mirror / Rough, reflection depth and samples | At most 64 exact body names; 1–8 bounces; 1–64 reflection samples. Rough uses each body's existing opaque surface. | +| Environment | None, constant linear RGB radiance, or a checked/embedded Radiance HDR; intensity, HDR rotation and sampling | Intensity 0–64; RGB 0–1; finite rotation within ±1,000,000 radians (displayed as degrees); HDR samples 1/4/16/64. | +| Lights | Preset lighting or custom directional lights; additional point lights | At most eight directional and eight point lights; nonzero directions; linear RGB 0–1 and intensity 0–64. | + +Numeric lighting, AA, shadows and constant-environment values are saved with the +active CPU method. Exposure uses the setup's one exposure field. Checked HDR bytes +and their controls can be embedded through the engine's atomic capture command; +body reflection bindings still cause Save to refuse a full job without discarding +those inputs. None of these controls changes a body's physical +material, geometry or mass. Raster CPU and GPU requests omit the CPU panel's options. +Switching methods retains local numeric drafts; Reload or choosing another setup +replaces them with the saved active method. Only the selected method's schema is sent. + +## Body identity and validation + +The picker lists visible evaluated bodies and narrows long lists with a filter; +it shows at most 256 rows per opening. Empty names, control characters and names +longer than 128 UTF-8 bytes cannot be selected. Duplicate visible names and stale +model evaluation are refused. + +A reflection selection records its document pointer, scene revision and the +visible body's ordinal, creator feature and component. Check and Start refuse a +binding after a scene change. **Confirm this body** can refresh the revision only +when the same target still occupies the selected identity. If another body has +reused its name, remove the old selection and select the desired body explicitly. +This prevents a name-only runtime selector from silently following a replacement. +The engine still performs final capture and surface compatibility validation. + +CPU reflections do not implement a general layered clear-coat transport model. +The engine rejects a coated body or face selected for an incompatible reflection +path. This panel does not claim diffuse global illumination, caustics or a general +glass renderer. + +## Environment capture + +**Constant** environment supplies secondary reflected/transmitted radiance. It +is not direct diffuse lighting and does not replace the image background. +**HDR** uses the CPU environment contract: Radiance `.hdr`, 2:1 panorama, at most +2048 × 1024 pixels and 16 MiB of source bytes, with explicit supported sRGB/D65 +primaries. EXR and files without those primaries are refused. Selected rough +reflectors with HDR must meet the engine's fully metallic body/face constraints. + +The picker uses the application's existing file dialog. A delayed answer is +accepted only by the same document, revision, setup, method and input selection. +Selecting a file runs `render.hdr.inspect`; typed paths require **Check HDR file**. +This checks the full bounded stream without a renderer or document mutation and +records its digest and metadata. Request construction itself does not read files. +**Check**, **Start** and **Save** send the same expected digest, so a changed source +is rejected until an explicit recheck. Cancellation and inspection failure retain +the prior selection. Once a job is captured, later file changes cannot alter its +pixels or export. + +**Save Setup** uses `render.settings.capture_hdr` for a checked local source, saving +the immutable bytes and complete setup in one undo step. Only success switches the +panel to **HDR saved inside this design**. Further saves use `render.settings.set`; +Reload, setup switching and design reopen never need the original path. The CPU +HDR's rotation, intensity and sample count are saved separately from its source +ID. Rotation remains in radians internally; drawing the degree editor does not +round-trip or clamp it. A constant environment and HDR are mutually exclusive. +CPU still requires explicit sRGB/D65 primaries; it never inherits the GPU's optional +assumption for an undeclared source. + +The last CPU check stores its exact request and revision and displays the captured +HDR dimensions, intensity, rotation, samples and SHA-256. It marks itself stale +when the scene or editable request changes. The active job displays its own +captured HDR descriptor. These UI records retain metadata, not image buffers or +HDR source bytes. Saved HDR bytes belong to the document resource table, not those +view records. An embedded source can be used with temporary reflection bindings +through the same runtime renderer, but the bindings themselves remain unsaveable. +PNG export remains the existing retained-frame export. + +## Light units and precedence + +Directions point toward a light and are normalized by the runtime; a zero vector +is invalid. Custom directional lighting replaces the preset directions; an empty +custom list deliberately has no directional lights. Selecting a preset clears +that custom list. Point lights are added to the chosen directional setup. + +Point positions and distances are world millimetres. The reference distance is +where the specified intensity applies; the minimum distance bounds inverse-square +attenuation and must not exceed the reference. Both distances range from 0.001 to +1,000,000 mm in this panel. Intensities are relative renderer values, not a claim +of lumens, watts or calibrated photometric measurements. + +Area lights, their sampling/seed and spot cones remain without dedicated panel +editors, but valid values loaded from a setup are preserved in Save, Check and Start. +Directions retain their original nonzero magnitude; showing a field does not normalize +or clamp it. Emission, surface effects, dielectric bindings and anisotropic faces +remain runtime API capabilities that this panel explicitly refuses to edit. A later +material/optics editor can expose those contracts separately. + +## Integration and acceptance + +This unit includes EN/ES/JA/ZH strings, request-contract regressions for body +identity and method isolation, environment bounds and light validation, delayed +picker protection, and an extended native UI test that selects a reflection mode, +checks and starts the same request, changes the HDR source after capture and +compares exported PNG bytes with the retained frame. The progressive UI adds +regressions for sequence caching, final publication racing the status read, +cancellation/export retention, explicit resolution adjustment, offline Save/Reload, +hidden values and reopening progressive setups with embedded HDR. + +The author checked Rust formatting, locale-key coverage, whitespace and exact +patch replay. No Cargo build, test execution, native launch or visual quality +acceptance was performed for this incremental source unit. The integrator must +run the combined revision's CI and the native UI/render tests before treating +those regressions as passing. CPU controls and the GPU material editor have +separate modules and request builders; both must retain their final admission +guards when mounted together. diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-interactive.md b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-interactive.md new file mode 100644 index 000000000..d614c4665 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-interactive.md @@ -0,0 +1,146 @@ +# CPU Interactive preview + +The workspace adapter connects `job::interactive` to the Render canvas and the +Interactive card. Select **CPU ray tracing** in Output and use **On** to enable +the provisional native CPU preview. Entering Render or changing stages does not +enable it or start a final image. The registered `render.interactive` command +uses explicit on, pause, resume and off actions. + +Interactive requires an available native worker host supporting CPU ray tracing; +it is not the web/cooperative Raster path or a GPU path-tracing preview. An +unsupported method, host or request reports a reason rather than changing +methods or discarding settings. The final renderer's settings, document format +and export registry remain separate. + +## Workspace behavior + +After On, committed camera, appearance, visibility, lighting and request edits +invalidate the current preview automatically. Capture groups edits after 200 ms +without a newer change; this is a scheduling rule, not a promised display +latency. The card exposes Updating, Refining preview, Sample target reached, +Pause/Resume and Off. A completed Interactive image is still labelled +Provisional preview; reaching its target does not make it a final result. + +Pause cancels owned preview work and may retain accepted pixels as a reference. +Edits mark that reference Out of date. Resume uses the latest input identity. +An appearance or lighting edit alone does not prohibit repeated aligned +selection/material editing. Geometry targets require the accepted image's +camera, authored aspect, visibility, evaluated world and placement metadata to +match the current view. A changed camera, hidden body or changed geometry must +not authorize picking or Paint from stale pixels, including after a navigation +button is released. Unknown source pixels also cannot claim geometry targets. +A missing alignment certificate fails closed; painting a retained image does +not certify its geometry. + +The image is fitted without stretching; painting and geometry input share its +actual pixel rectangle. Empty letterbox space is not a geometry target. +Navigation and release/Escape handling remain available when geometry input is +blocked. While an enabled preview awaits its current image, the canvas reserves +that route rather than painting the fast Model preview as current CPU pixels. + +Off, leaving Render or changing documents disables/cancels the owned preview +context. A manual final temporarily suspends preview capture; it does not +export an Interactive image or cancel the final job. Result has canvas priority. +A failed capture waits for a relevant edit or explicit Resume instead of +starting an unbounded retry loop. + +## Preview envelope + +In the coordinated source proposal, `cpu_request` clones an immutable final +request and preserves its camera, background, shadows, exposure, lighting, +resources and transport. If that captured request has explicit CPU progressive +intent, its target and seed are retained; they are not replaced by the current +live draft or silently reduced to 16/0. Only an absent progressive intent uses +the existing fallback of 16 SPP and seed 0. One primary and one selected +reflection attempt are used per camera sample. The original final request stays +untouched. + +Preview dimensions remain bounded to 1024 pixels along the longest edge, +rounded to the nearest pixel without enlargement. Integer aspect rounding is at +most half a pixel (or one pixel for an extreme aspect). Preserving a high target +does not remove the selected profile's pixel, total camera-sample, geometry, +traversal or memory intersections. Transparent output, another integrator or +unsupported progressive transport returns an error instead of dropping effects. +These changes still require integrated validation and native observation. +Rectangle/LED direct-light inputs, their emitter-sample count and area-pattern +seed survive preview lowering unchanged. Only camera/reflection sampling uses +the preview envelope; dielectric intent is retained for capture and transport +certification, while unsupported progressive combinations, including anisotropy, +still fail explicitly. This is not a promise of general glass support. +See [CPU progressive sampling](render-cpu-progressive.md) and +[CPU resource profiles](render-cpu-resource-profiles.md) for the separate final +request and admission contracts. + +The coordinated retention diagnostic is read from the actual current job handle. +A successful status supplies `Some(count)`, including `Some(0)`; an absent handle +or failed status lookup supplies no count (`null` in the inspection reply), not +a fabricated zero. Lookup errors are not included; other reported errors are independent. A nonzero count +reports skipped snapshot boundaries caused by externally retained slots, not +missing samples or a count of physical canvas repaints; see +[CPU progressive publication](render-cpu-progressive.md#preview-publication-and-final-export). + +## Exposure and image ownership + +The saved setup's common exposure is finite and bounded to -32..32 EV. +With Interactive Off, Model uses that exposure in its fast product preview for +all final-method choices: CPU ray tracing, GPU path tracing and Raster. Editing +it does not require Start or enable the selected final executor. This Model +path still requires its viewport device and retains its current environment +restriction (rotation 0, intensity 1); it is not a promise of Model/final pixel +parity or of every final effect being represented. + +Interactive receives exposure through its captured CPU request. Retained Result +and Interactive PNGs return through their own image-display routes before the +live Model exposure is applied. Editing the current draft must not grade those +captured pixels a second time. An explicit Effects/regrade action is a separate +operation. Design's viewport does not inherit product exposure. See +[Scene and Shot editors](render-shot-scene.md) for active versus selected setup +semantics and the saved Exposure control. + +## Adapter contract + +- Allocate a distinct transient job session for each document's Interactive + controller. Never recreate a controller with the same session while callbacks + from its previous instance can arrive. Do not register its jobs in the engine's + final/export registry. Reaching its captured sample target still produces + provisional content, not an exportable final. +- Increment `VisualRevision.visual_revision` whenever camera, draft, material, + visibility, lighting, HDR/resource, method or output intent changes. Include + changes that leave the document revision unchanged. Capture this counter and + `scene_generation` atomically with the full request and scene. This core does + not infer that identity from a setup name or a partial hash. +- Explicit activation calls `enable`; edits call `edit`. Supply monotonic elapsed + `Duration` values. `capture` issues one ticket after 200 ms without a newer edit. + Do not evaluate geometry or read files every frame just to compare identity. +- Recheck `accepts_capture(ticket)` before expensive capture/admission and after + worker preparation. This avoids preparing an already obsolete request; it does + not replace the mandatory identity checks in `attach` after admission. +- Capture through the existing authoritative engine boundary, prepare the CPU + request, then admit/submit through the installed CPU host using + `CaptureTicket::job_id()`. Pass the resulting handle to `attach` + with the original ticket. Delayed jobs are cancelled, including a wrong serial + or generation in our dedicated preview session. A foreign session is rejected + without cancelling its work, even if its handle arrived through a misrouted + callback. Final jobs must keep their distinct engine session. + Report a failed capture through `capture_failed`; failure waits for an edit or + explicit resume, rather than retrying every frame. +- Read only `current()` to publish checkpoint pixels. The existing host provides + immutable previews, sample counts, sequence and final target bytes. Their job + and revision must remain attached to the displayed image. A copied handle or + retained texture is not permission to display it as current after an edit. +- Pause may retain an immutable checkpoint in the adapter, explicitly labelled + paused and stale after edits. It cancels work. Resume uses the latest revision. + Leave Render or change documents with `disable`; Drop also cancels owned work. +- Before a manual final starts, call `set_final_active(true)`. This cancels only + Interactive work and prevents new capture tickets. Call it with false after the + final finishes; an enabled, unpaused controller then groups the latest edits + again. No method here cancels a final job or exports an image. + +## Validation scope + +These routes describe the current source contract, including the connected UI; +they are not a statement that native visual acceptance or GPU qualification has +passed on this revision. Core/headless regression coverage does not replace a +supported native build and admitted runtime checks. Pending integration gates, +Model/final numeric parity and the installed application's reported shadow +defect are not declared resolved by this document. diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-jobs.md b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-jobs.md new file mode 100644 index 000000000..444ee5bd1 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-jobs.md @@ -0,0 +1,151 @@ +# 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 +[opaque PBR consumer](render-opaque-pbr.md) adds opt-in direct-lit surfaces through +the same host. Legacy scalar looks and the Design snapshot renderer retain their +existing shading. + +## One command path + +`render.preflight` and `render.start` take `setup` (a saved name) OR `settings` (a +RenderSetup object; omitted fields use its documented defaults), plus optional +`transparent_background` and `replace` booleans, both false by default. Without either +setup/settings, the current requested camera is used, or the camera is fitted to the +product. Saving a setup is independent of starting a job. Unknown fields are errors. + +Both commands reject stale geometry without settling a live modelling gesture. Finish +the gesture or use the explicit `render.scene` boundary first. Capture uses R3's +authoritative visible meshes, placements and appearances, without selection, edges, +axes, grids, sections or analysis overlays. A cold capture can prepare world geometry +and meshes synchronously; it is not a promise of bounded CAD evaluation latency. +Preflight validates capabilities and estimates admission, but does not reserve a queue +slot or the host memory pool. Start checks those resources again. + +Start returns a typed `job: {session, serial, generation}`. Keep all three fields when +calling `render.status`, `render.cancel` or `render.export`. IDs are never accepted by +another document session, scratch copy, or a newly opened/recovered document. Status +does no rendering and never waits for completion. It reports queued, preparing, +running, encoding, cancelling, cancelled, completed or failed, with phase-local +`done/total`, structured job errors and completed frame metadata. Progress restarts +when a phase changes; it is not a time estimate. + +The captured `scene_generation` is the session revision at start. Later edits, undo, +camera changes and tab switches do not mutate the snapshot. An image continues to +describe that captured scene; the UI labels a revision mismatch conservatively (view +cache invalidation can also advance a revision). Runtime state is outside the document, +undo, checkpoints and the design format. Closing/replacing a session cancels its work; +the worker cannot publish a cancelled frame. Direct host-side document replacement +preserves the installed image service while allocating fresh job ownership; old IDs +and completed images never cross into the new document. `replace: true` cancels retained active +and pending jobs before submitting the new request. A cancelled generation cannot +publish late. A successful older generation never replaces a newer successful result. + +Each document retains at most two live jobs, four recent terminal status records and +one last successful image. Cancellation/failure preserves that image. A new successful +image releases the previous image; old terminal metadata can still report completion, +but it does not promise that its bytes remain exportable. Export requires an explicit +retained completed job ID; it never silently exports a different/newer job. + +Native CPU raytracing can separately enable +[progressive camera sampling](render-cpu-progressive.md). A status may then include +`preview: {frame_sequence, samples_per_pixel, frame}`. Its complete-pass PNG is +available through the in-process `JobHandle::preview()` consumer; the JSON status +contains metadata only. The preview keeps the same job and capture identity, +but remains separate from the retained final image and `render.export`. +Cancellation, failure and final publication clear the provisional slot while +preserving the previous successful result when no newer final exists. Each +externally retained preview keeps the lease for its reusable admitted snapshot +slot until release; the composed every-pass policy reserves two slots rather +than one PNG for every pass. Publication may outpace physical client repaint. + +The composed CPU source adds runtime `cpu_preview_retention_skips: u32` to job +status. It increments once for a real nonfinal uniform boundary that cannot +publish because both reusable slots remain externally pinned after retiring the +obsolete host snapshot and retrying its credit. Polling does not increment it; +closed pools, in-flight buffers, unrequested feedback or an exhausted optional +feedback quota are not themselves retention skips. +Sampling and final work continue without observer acknowledgements or an extra +snapshot allocation. SPP1/sequence1, SPP2/sequence2, skipped SPP3/count1, then +SPP4/sequence3/count1 is a valid publication history after one slot returns. +Actual producer passes must still be processed in order. + +Zero is a value from a real status, not a substitute status after lookup failure. +The separate Interactive inspection diagnostic is nullable when there is no +current handle or its status lookup fails; lookup errors are not included and other reported errors are independent. Neither +form is saved in the design or proves that every snapshot was physically shown. +This is a source proposal pending integrated validation, not a native result. + +## Native and browser execution + +Each application installs one CPU host, shared by its documents. Native execution uses +one worker and at most two queued inputs across documents; it runs without UI polling. +The browser uses the same incremental task, pumped by UI frames, without threads. +Preparation, stable transparency sorting, clearing, pixel tests and downsampling check +cancellation between small units. A step admits at most 16384 units; PNG encoding +additionally yields after four rows. The UI pumps 1024 units per frame. These are work +bounds, not hard real-time guarantees: allocation, codec compression and OS scheduling +still have platform-dependent latency. + +Admission caps output at 4096 per dimension and 4 million pixels; pixel scratch is +estimated at 48 bytes per output pixel (2x supersampling). Other limits: 262144 +triangles/face overrides/edge polylines, 128 MiB retained source geometry, 384 MiB total +estimated memory per job, 512 MiB shared host admission including retained PNGs, and +128 million projected pixel tests. The projected-work limit is checked during bounded +preparation and may fail an admitted job. Encoded PNG bytes have an additional +`8 * output_pixels + 65536` cap. Allocator and codec internals are estimates, not an +operating-system memory quota. Limits fail with errors rather than allocating unbounded +buffers. Completed frames keep their memory reservation while bytes are retained. + +The CPU path shades in linear light, blends sorted triangle alpha approximately, then +encodes 8-bit sRGB with straight alpha and an sRGB PNG chunk. Transparent shared edges +use a consistent fill rule. Intersecting transparent surfaces and triangle sorting +remain raster approximations. This is not a glass/refraction renderer. Native GPU +preview and CPU export can differ in shading and transparency. + +PNG uses the already-transitive Rust `png` crate (MIT OR Apache-2.0), now an explicit +render dependency. No external render engine or third-party art is introduced. + +## Export and automation + +`render.export` takes `job`, `path` ending in `.png`, and `overwrite` (default false). +The destination is checked against the caller's existing file-access scope before +reading the retained frame or calling either native writer. Disallowed folders and +traversal are refused in both overwrite modes. Native no-clobber export writes/syncs a temporary beside the target and publishes it +with an atomic hard link; an existing destination wins even in a race. Filesystems +without that operation return an error. Explicit overwrite uses the existing atomic +writer without reading or backing up the previous target. Failed writes preserve the completed +image and CAD state. Browser export uses the existing virtual file/download service; +image-export paths or frame payloads are not persisted in the design. Saved HDR +input resources use their separate [document contract](render-hdr-resources.md). + +The Render panel provides Check Render Request, Start Render, phase progress, +Cancel Render and Export PNG. Replace existing file is an explicit opt-in. A failed or +cancelled new render leaves the previous successful export available. + +Native PNG export in the combined integration uses the document-bound asynchronous +picker from #1114. The requested job ID and overwrite choice are captured before the +dialog opens: cancellation writes nothing, closing the originating document drops +the answer, and an evicted image fails instead of substituting a newer result. A tab +switch does not redirect the export to another document. + +Controls and phase messages use stable offline catalog IDs in English, Japanese, Chinese, +German and Korean; command IDs and scenario handles remain unchanged. + +```sh +solidcraft-cli render examples/render-studio.json --out product.png --width 800 --height 600 +solidcraft-cli render design.sc --setup Studio --out product.png --transparent +``` + +The CLI follows preflight/start/native wait/export, with a default 120-second wait +limit (`--timeout 1..3600`). Timeout requests cancellation. `--overwrite` is required +to replace an existing target. A persistent headless MCP session installs the same +host: use the ordinary `execute` tool with the five commands and returned job ID. +Closing the CLI/MCP process ends its session; a one-shot `exec render.start` is not a +durable background service. In a browser, leave the app running so frames can pump work. + +Validation evidence and responsiveness measurements are recorded in the R4a issue/PR; +passing native tests or a wasm compile does not establish browser visual performance. diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-settings.md b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-settings.md new file mode 100644 index 000000000..98a46ef1f --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/candidate/docs/render-settings.md @@ -0,0 +1,320 @@ +# Persistent render settings + +Named setups save common render settings and, optionally, the complete numerical +configuration of one selected image method, including an optional embedded HDR. +Saving does not start a render, apply +the navigation camera or require an installed CPU/GPU executor. `render.preflight` +and `render.start` consume the same saved configuration and still check the current +host, geometry, capabilities and memory limits. + +## Commands + +```json +{"command":"render.settings.set","params":{"name":"Studio","set":{"width":1600,"height":900,"exposure_ev":1.5}}} +{"command":"render.settings.get","params":{"name":"Studio"}} +{"command":"render.settings.get","params":{}} +``` + +`set` creates a named setup from defaults or replaces supplied top-level fields in an +existing setup. A supplied `camera` or `job` replaces the whole value; it is not a recursive +patch. Omitted fields retain their values. `job: null` explicitly clears the job and +restores the legacy request protocol. Unknown fields (including camera/job fields), +invalid types and invalid values fail before document mutation. A new empty `set` +saves the defaults; setting an existing setup to identical values is a no-op, +preserving redo history and revision. +Each effective edit is one undo step and marks the document dirty. There is no delete +or rename command in this slice. + +Named `get` returns `{name, setup}` or an error for a missing name. Without a name, +it returns `{setups, defaults}`. Reads do not evaluate the model or change history. + +`render.lights.list {setup: "Studio"}` returns a uniform `{lights: [...]}` read +model without applying or saving anything. An unsaved client draft can instead +pass `{settings: }`; `{}` inspects the default setup. +Neither form selects a UI shot. Unknown parameters, null selectors, both selectors, +missing setup names and invalid settings refuse without mutation or evaluation. +CPU directional/point/spot/rectangle sources and GPU sun/rectangle sources expose +`id`, `kind`, `name`, `name_key`, `number`, `implicit`, `intensity`, `colour` and +their world-space geometry. Background and environment illumination are separate +from this source list. Implicit fixed studios and CPU presets are expanded; +explicit empty lists remain empty. GPU sky/HDR suppresses its implicit studio. + +Light IDs use the kind and zero-based source slot (`directional:0`, `point:0`, +`spot:1`, `area:0`); point and spot share indices in the punctual list. IDs survive +numerical edits and repeated reads, but changing kind, reordering/removing lights +or replacing a rig can change them. These are setup-local addresses, not durable +document identities. Unnamed lights display Key, Fill, Rim, then Light 4, etc.; +clients translate `name_key`, substituting `number` for later lights. Names are +not persisted by this command. + +Colour is linear RGB. CPU colour/intensity retain their saved values. GPU RGB +radiance is factored into its largest channel as intensity and normalized colour +(black uses intensity zero and white colour). Their product recovers radiance; +no photometric equivalence between methods is implied. All rectangle edges are +full side vectors in millimetres, including GPU half-edges multiplied by two. +Directional vectors point towards a source; spot axes point from it. The optional +directional `angular_radius_rad` identifies a finite GPU sun. + +`render.lights.add`, `.set`, `.duplicate` and `.remove` edit a named setup in one +undo step. They accept `name`, `id` except for add, optional complete `settings` +as an unsaved starting point, and optional `expected_revision`. Add/set accept +`set` with `kind`, `intensity_ev`, `temperature_k`, `softness`, `azimuth_deg`, +`elevation_deg`, `distance_mm`, `size_mm`, `aim_at`, `width_mm`, `height_mm`, +`position_mm`, `direction`, `edge_u_mm`, `edge_v_mm`, `radiance`, `colour`, +`reference_distance_mm` and `minimum_distance_mm`. These lower into the existing +light fields; there is no new saved light metadata. Temperature is an original +three-band, 6500 K white-balanced Planck tint approximation stored as linear RGB. +Area softness changes emitter size; GPU Sun softness changes angular radius. +Hard CPU directional and point/spot sources refuse unsupported emitter softness. +CPU admits 8 directional, 8 point/spot and 4 areas; GPU admits one Sun and four +areas. GPU Point/Spot controls and the legacy three-directional GPU studio editor +remain unavailable with reasons, rather than silently losing light sources. + +`render.lights.solo {id?, solo}` and `render.lights.mute {id, mute}` validate and +echo view requests. Enabling solo requires an id; disabling solo clears it. +The UI also verifies that the address exists in its current lighting draft. +`SolveApp::run` applies these replies to per-document `ViewState.lights`, never +to a design or undo history. Shot changes clear this transient scope. Saving, +undoing and reopening settings retain the unfiltered numerical setup. + +`render_workspace_light::filter_request` filters copied settings at both +`image_request` and `SolveApp::run`'s Check/Render boundary. Explicit sources keep +their geometry and have zero intensity/radiance while off. Raster and the legacy +GPU studio carry three optional `studio_weights` in the captured `ImageRequest`; +they are finite 0..1 runtime values, never fields of `RenderSetup`. CPU raster +uses them in `studio::shade_weighted`; the GPU path uses its captured uniform. +CPU ray tracing and explicit GPU rigs refuse these fixed-studio weights. + +The selectable Lights group runs `view.render_select {kind: "lighting"}` and opens +Lighting: Light source, Shadows and sampling, then Budget. Its + still adds a +light. CPU presets require review and consent before replacing directional lights; +Custom materialises their existing values. GPU budgets show one Sun and four +Areas; CPU eight directional and eight point/spot plus four Areas. Counts are +read-only sliders. Unsupported controls stay faded with a reason. No rig identity +is saved, so there is no Rig row. + +Browser eyes and solo actions run the same view commands. A selected light mounts +`render_workspace_light::editor` in the Inspector's Lighting page. Without a +selected light, that page calls the same group editor. Light has a name/type +header, Area/Point/Sun segments, intensity, temperature and softness; Position; +Shape for areas; Falloff for points; and Behaviour (Solo, Mute, Duplicate, Delete). +Distances displayed as subject-size multiples lower to millimetres. Width U and +Height V are full side lengths (GPU storage uses half-edges). Independent vector +edits preserve the other side. Radiance and temperature lower to existing linear +RGB fields. Sun directions remain world vectors. Every edit is bounded and finite, +with the renderer validating the complete candidate. Opening an editor +does not apply or save anything. Edits run the four light commands; Place by +highlight stays disabled with its viewport-picking reason. The live product view +receives bounded analytic light samples in `Frame.product_lights`; both PBR and +non-PBR/transparent batches use them. This is an unshadowed preview, with area +emitters sampled at their centre and constant ambient illumination. HDR transport +and full emitter sampling remain the image renderer's responsibility. + +| Field | Default | Saved contract | +|---|---|---| +| `backend` | `builtin` | Valid R1 backend ID, at most 64 ASCII bytes; unavailable IDs survive reopen | +| `mode` | `preview` | R1 `preview` / `final` mode; availability checked by a future render request | +| `camera` | Existing `Camera::default()` | Snapshot of target, yaw, pitch, roll, distance, fov and up; mm/radians, existing Z-up default | +| `width`, `height` | 1024, 768 | Positive, each at most 4096; product at most 4,194,304 pixels | +| `format` | `png` | R1 output format (`png` / `exr`); saving EXR does not add an encoder | +| `exposure_ev` | 0 | One exposure authority: Raster accepts -32 through 32; CPU raytrace accepts -32 through 32; GPU path accepts -32 through 32. Legacy setups retain -32 through 32. | +| `environment_rotation` | 0 | Legacy finite radians, magnitude at most 1,000,000. A typed `job` requires 0. | +| `environment_intensity` | 1 | Legacy finite value, 0 through 100. A typed `job` requires 1. | +| `background` | [236, 240, 245] | Three sRGB byte values; display backplate, independent of illumination | +| `job` | absent | Optional typed active `raster`, `cpu_raytrace` or `gpu_path` configuration; absent/null keeps the legacy protocol | + +Camera target coordinates and positive distance are bounded to magnitude 1e9 mm; +angles to 1e6 radians. FOV is finite, `0 <= fov < pi`; zero means orthographic in +the existing camera model. Both existing camera up axes are retained. Setup names +are trimmed, nonempty, at most 128 UTF-8 bytes, without control characters. A document +has at most 32 setups. Validation also runs during document deserialization. + +The raster product-image executor (`render.preflight` / `render.start` without `progressive`) +applies the existing `exposure_ev` to shaded product colour, preserving EV0 exactly. +PBR and explicit/weighted studio paths scale linear radiance by 2^EV before their +single Reinhard map and sRGB encoding. The plain historical scalar shader already +returns clamped display-linear shading here: it is scaled before its original +encoding without adding Reinhard or recovering clipped highlights. Backplate, +alpha, framing and geometry remain unchanged. `ignored_controls` still reports +unsupported legacy environment controls, but never lists applied exposure. +CPU and GPU keep their existing exposure authorities; the Raster-only resolved +request scalar refuses other producers. Model preview is a separate UI/GPU path. + +## Complete numerical job intent + +`job` is tagged by `method`. It saves the active method, rather than separate CPU +and GPU drafts. All numbers use the existing renderer contracts: world distances +are millimetres, angles are radians and light colours/radiances are linear RGB. + +| Method | Saved fields | Main limits and defaults | +|---|---|---| +| `raster` | `transparent_background`, optional `lights` | Transparency defaults to false. Omitted/null lights retain the original fixed studio; `lights: []` is explicitly dark. At most eight hard directional sources; exposure uses the existing common field and raytrace controls remain unsupported. | +| `cpu_raytrace` | `options`: optional `progressive`, `primary_samples`, `preset`, `lights`, `punctual_lights`, `area_lights`, `area_samples`, `seed`, `shadows`, constant `environment`, embedded `hdr` | Primary samples 1/4/16 (default 1); shadows true; optional progressive/lists/preset/environment/HDR absent. At most 8 directional, 8 point/spot and 4 rectangular lights; progressive has the narrower contract below. | +| `gpu_path` | `transparent_background`, `options`: `samples`, `max_depth`, `seed`, `tone_map`, `denoise`, `lens`, `lighting`, sky `environment`, embedded `hdr` | Samples 1..4096 (default 64), depth 1..16 (default 8), seed u32 (default 0), Reinhard tone map, denoise false, optional values absent | + +Raster sources use `{direction:[x,y,z], color:[linear r,g,b], intensity:number}`. +Directions point towards the source, are finite/nonzero and bounded by 1e9 per +component; linear RGB is 0..1 and relative intensity is 0..64. Saved values are +not normalized or display-encoded. Existing `render.lights.*` editing commands +persist directional edits in the Raster job. Point/spot/area and finite-disk sun +controls remain unsupported, including softness, position, falloff and radiance +edits. This is schematic opaque direct lighting and scalar alpha blending, with +no shadows, HDRI, physical glass or indirect transport. + +A saved explicit Raster rig is authoritative: a simultaneous runtime +`raster_lights` key, including null, refuses instead of overriding saved intent. +Visibility filters a rendering copy; saving/reopening retains the authored rig. +The new saved field uses a pending design-format marker, without manual changes +to shared format numbers. Legacy Raster jobs omit the field unchanged. + +CPU `preset` and explicit `lights` are mutually exclusive. An omitted/null light +list remains unspecified; `lights: []` explicitly removes the default directional +lights. Point lights retain their optional spot cone, its world emission axis and +both half angles. Rectangular lights retain full side vectors, sample count and +seed; `area_samples` and `seed` require a nonempty rectangular-light list. Area +samples are 1/4/16/64. Lists are bounded while deserializing and are never truncated. +The CPU constant environment retains `{color, intensity}` independently of the +backplate. See [CPU light union](render-light-union.md) for the spatial and light +validation contracts. + +CPU `progressive: {samples_per_pixel, seed}` stores bounded camera accumulation +using the existing CPU transport. An absent/null value preserves fixed AA; an +empty object defaults to 16 samples and seed 0. The seed is u32 and +`primary_samples` must be 1. In the coordinated source proposal, per-pixel targets +are 1..64 for omitted/explicit Compact, 1..1024 for Studio and 1..1,048,576 for +explicit Workstation. Each remains subject to its profile's unchanged dimensions, +pixels, total camera-sample and other admission limits; see +[CPU resource profiles](render-cpu-resource-profiles.md). The compatibility +Compact limits remain 1,048,576 progressive pixels and 16,777,216 total camera +samples. Saving validates the selected intersection without a render host; +reopen preserves the explicit target, seed and budget rather than clamping intent. +Snapshots, checkpoint leases and the runtime retention-skip counter are not +saved fields. These source changes await integrated validation/native acceptance. +Area/LED direct lights retain the existing four +shared rectangle slots, emitter-sample counts and power normalization. Dielectric +and anisotropic-face overrides remain refused; the fixed CPU route retains them. +Embedded HDR and one setup exposure remain compatible. See +[CPU progressive sampling](render-cpu-progressive.md) for reflection limits, +work admission and provisional/final publication. The top-level runtime +`progressive: true` continues to select GPU. + +GPU `lighting` retains the complete RGB ambient radiance, optional sun and at most +four rectangular lights. Omitted/null lighting keeps the renderer's legacy studio; +an explicit all-zero lighting object means a black studio. Those values are not +interchangeable. `lens` retains aperture radius and axial focus distance; nonzero +aperture requires a perspective camera. An explicit zero-aperture lens remains +explicit. Tone mapping and denoising retain their existing meanings and do not +create new executor capabilities. + +The portable procedural GPU `environment` is: + +```json +{"kind":"sky","gradient":{"zenith":[0.16,0.32,0.7],"horizon":[0.8,0.9,1],"ground":[0.12,0.1,0.08]},"rotation_rad":0,"intensity":1} +``` + +Gradient entries are finite linear RGB in 0..1,000,000; rotation is finite within +±1,000,000 radians; intensity is 0..100. Omitted gradient/rotation/intensity use the +shown defaults. The original procedural gradient is not a calibrated atmosphere. +An environment replaces the constant ambient-light term; it does not replace the +display background. See [environment rendering](render-environment.md), +[thin lens](render-thin-lens.md) and [studio lighting](render-studio-lighting.md). + +An embedded HDR uses the separate `options.hdr` field and cannot coexist with a +constant CPU environment or a GPU sky. It references immutable bytes in +`render.resources`, not a file name. [Saved HDR resources](render-hdr-resources.md) +documents atomic file capture, CPU/GPU colour policies, strict container hydration +and the offline save/reopen contract. Optional `hdr` absent/null means no HDR; +when an HDR object is supplied, its resource and controls are required. + +`RenderSetup.exposure_ev` is the only saved EV. CPU lowering copies it into the +runtime `raytrace.exposure_ev` and resets the legacy common-settings EV to zero; +GPU lowering uses it in `JobOptions`. CPU/GPU `options.exposure_ev` is rejected. +The two legacy common environment fields must stay at 0/1 when `job` is present; +the method's typed environment owns those values. Existing legacy values are +preserved, and a conflicting conversion fails instead of clearing them. + +### Save, check and start + +```json +{"command":"render.settings.set","params":{"name":"CPU studio","set":{"width":1600,"height":900,"exposure_ev":1,"job":{"method":"cpu_raytrace","options":{"primary_samples":4,"preset":"warm_cool","shadows":true}}}}} +{"command":"render.preflight","params":{"setup":"CPU studio"}} +{"command":"render.start","params":{"setup":"CPU studio","replace":true}} +{"command":"render.settings.set","params":{"name":"GPU studio","set":{"width":1600,"height":900,"exposure_ev":0.5,"job":{"method":"gpu_path","options":{"samples":256,"max_depth":8,"seed":42,"tone_map":"aces_fitted","lighting":{"environment":[0.1,0.2,0.3],"area_lights":[]},"environment":{"kind":"sky","intensity":0.5}}}}}} +{"command":"render.preflight","params":{"setup":"GPU studio"}} +``` + +An inline `{"settings": full_setup}` has the same semantics as a saved `setup` name. +The engine resolves the typed job **before** choosing CPU or GPU dispatch. A saved +`gpu_path` method requires the `gpu-path` executor; another executor announcing +progressive sampling cannot replace it. A missing or unsupported host blocks +Check/Start while leaving the saved intent intact. + +For a complete job, additional request fields are `replace` and optional transient +`studio_weights` for a fixed studio. Parallel +runtime controls such as `progressive`, `integrator`, `raytrace`, `lens`, +`environment` or `transparent_background` fail, including explicit null/false +values. They cannot silently override a setup. For legacy `job` absent/null, the +existing runtime request API remains available; it has no inferred CPU/GPU method. + +### Explicit portability boundary + +External HDR paths, texture maps, GPU dielectric/clear-coat/texture body bindings and CPU +reflection, anisotropy, emission, surface-effect and dielectric bindings are not +part of this saved job format. Their fields are rejected, even when an unsupported +list is empty. Runtime requests can still use those existing features with an +inline setup whose `job` is null. Saving a complete setup must not discard them or +turn a current body name/ordinal into a persistent identity. HDR bytes are portable +through `render.settings.capture_hdr`; portable maps and durable body/face bindings +still require separate contracts. Runtime requests can reference an existing HDR +resource while supplying temporary bindings, without persisting those bindings. + +No captured scene revision, worker, device, image result, `JobId`, host availability +or external path is serialized. Reproducible input configuration does not promise +bit-identical pixels across devices or renderer versions. + +## Persistence and evaluation + +Named setups live in `render: {setups: {name: setup}, resources?: {sha256: resource}}`; +empty render state is omitted. +The optional numerical job adds the `render-job-intent` pending format descriptor. +Embedded HDR adds its own `render-hdr-resources` descriptor. +The optional CPU sampling field adds `render-cpu-progressive`. +No historical format number or migration step is rewritten. Older designs need no +job transformation: an absent job keeps their common settings and runtime API. +Pending builds without the descriptor refuse the newer design instead of silently +losing its saved options. Plain JSON, design containers and document autosave +snapshots carry all HDR bytes. A command-only crash replay before a new checkpoint +still needs the source path recorded by `capture_hdr`; it must match the recorded +digest. This unit does not make that journal self-contained. + +The engine avoids geometry evaluation only after proving that the document differs +solely in validated render settings, with unchanged active sketch and pending moves. +The proof compares the complete document after normalizing the render field, so mixed +geometry/appearance/placement edits take the usual conservative refresh path. It uses +a document clone/comparison, not a constant-time or whole-application speedup claim. +Unchanged render pointers short-circuit the check for normal modelling commands. + +Render-only edits, undo/redo and checkpoint restore preserve model state, its stale +marker, cached tessellation and the prepared world state. A stale live-drag result never +becomes authoritative through a settings edit; the next model-reading command still +settles it normally. Revision advances for consumers that track document changes. +Geometry, physical materials and appearances retain their existing representations; +the setup stores image configuration, not material assignments. + +No new third-party dependency or asset is introduced. `doc` depends on the existing +pure `render` crate for its shared camera and R1 identifiers, within the L2 → L1 rule. + +### Saved CPU dielectric policy + +CPU `job.options.dielectric_transport` accepts `legacy_bounded` or `strict_tir`. +Missing/default values retain Legacy and are omitted on serialization. The UI +edits that CPU field and preserves it on Save, reopen, load and request capture; +there is no common RenderSetup policy field or implicit renderer/profile change. +The format records this new meaning through its own pending change. It does not +make captured body identities or temporary optical/material bindings portable. + +Strict transport continues deterministic internal glass reflections and errors +on an unresolved positive non-TIR depth tail. Unsupported selected opaque +reflections, effects and geometry remain explicit refusals, with authored intent +preserved. The ordinary command/host validation still applies to each captured +request; Check is not a promise of successful tracing or a memory reservation. diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/delta-LF-review.patch b/proposals/render/2026-10-31/cpu-every-pass-c27-source/delta-LF-review.patch new file mode 100644 index 000000000..54b3f7b12 --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/delta-LF-review.patch @@ -0,0 +1,2811 @@ +--- a/assets/locales/pending/cpu-progressive-passes.json ++++ b/assets/locales/pending/cpu-progressive-passes.json +@@ -0,0 +1,20 @@ ++{ ++ "de": { ++ "render.cpu_pass_progress": "Vollständige Durchgänge: {current} / {target} · vorläufig" ++ }, ++ "en": { ++ "render.cpu_pass_progress": "Complete passes: {current} / {target} · provisional" ++ }, ++ "es": { ++ "render.cpu_pass_progress": "Pasadas completas: {current} / {target} · provisional" ++ }, ++ "ja": { ++ "render.cpu_pass_progress": "完了したパス: {current} / {target} · 暫定" ++ }, ++ "ko": { ++ "render.cpu_pass_progress": "완료된 패스: {current} / {target} · 임시" ++ }, ++ "zh": { ++ "render.cpu_pass_progress": "完整遍数:{current} / {target} · 临时结果" ++ } ++} +--- a/crates/render/src/film_primary.rs ++++ b/crates/render/src/film_primary.rs +@@ -129,14 +129,12 @@ + + /// A display consumer can only read a fully completed, immutable pass. The + /// returned radiance is premultiplied by coverage; background is kept separate. +- pub(crate) fn pixel(&self, index: usize) -> Result<([f64; 3], u16, u16)> { ++ pub(crate) fn pixel(&self, index: usize) -> Result<([f64; 3], u32, u32)> { + if !self.ready() || self.next_pixel != 0 || self.samples == 0 { + return Err(invalid("primary film has no uniform complete pass")); + } + let pixel = self.pixels.get(index).ok_or_else(|| invalid("primary film resolve index out of range"))?; +- let covered = u16::try_from(pixel.covered).map_err(|_| limit("primary coverage exceeds resolve representation"))?; +- let samples = u16::try_from(self.samples).map_err(|_| limit("primary sample count exceeds resolve representation"))?; +- Ok((pixel.sum.map(|sum| sum / f64::from(self.samples)), covered, samples)) ++ Ok((pixel.sum.map(|sum| sum / f64::from(self.samples)), pixel.covered, self.samples)) + } + /// Inspect only the real committed state. This value does not freeze the film + /// or authorize a snapshot. A caller resolving several pixels must keep the +--- a/crates/render/src/film_tests.rs ++++ b/crates/render/src/film_tests.rs +@@ -452,3 +452,181 @@ + } + } + } ++ ++#[cfg(feature = "raytrace-cpu")] ++mod workstation_primary_counts { ++ use super::primary::{PartialPixel, PrimaryFilm}; ++ use super::*; ++ use crate::job::{CpuBudget, CpuProgressiveOptions}; ++ ++ fn primary(target: u32) -> PrimaryFilm { ++ let options = CpuProgressiveOptions { samples_per_pixel: target, seed: 7 }; ++ let bytes = PrimaryFilm::required_bytes(1, 1, options, CpuBudget::Workstation).unwrap(); ++ let mut film = PrimaryFilm::new(1, 1, options, bytes, &CancelToken::default(), CpuBudget::Workstation).unwrap(); ++ film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); ++ film ++ } ++ ++ #[test] ++ fn workstation_cap_is_explicit_and_other_profiles_and_defaults_stay_fixed() { ++ assert_eq!(crate::job::MAX_CPU_SAMPLES_PER_PIXEL, 1_048_576); ++ assert_eq!(CpuBudget::Workstation.limits().max_samples_per_pixel, 1_048_576); ++ assert_eq!(CpuBudget::Studio.limits().max_samples_per_pixel, 1024); ++ assert_eq!(CpuBudget::Compact.limits().max_samples_per_pixel, 64); ++ assert_eq!(CpuBudget::default(), CpuBudget::Compact); ++ assert_eq!(CpuProgressiveOptions::default(), CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }); ++ for samples_per_pixel in [0, 1_048_577, u32::MAX] { ++ assert!(CpuBudget::Workstation.validate_samples(samples_per_pixel).is_err()); ++ } ++ for (budget, cap) in [(CpuBudget::Compact, 64), (CpuBudget::Studio, 1024), (CpuBudget::Workstation, 1_048_576)] { ++ budget.validate_samples(cap).unwrap(); ++ assert!(budget.validate_samples(cap + 1).is_err()); ++ } ++ let large = CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 }; ++ assert!(large.validate().is_err(), "the no-profile compatibility check must remain Compact"); ++ assert!(large.validate_image(1, 1).is_err()); ++ } ++ ++ #[test] ++ fn high_sample_intent_keeps_camera_resolution_work_and_memory_admission() { ++ let limits = CpuBudget::Workstation.limits(); ++ assert_eq!(limits.max_camera_samples, 68_719_476_736); ++ assert_eq!(limits.max_dimension, 16_384); ++ assert_eq!(limits.max_pixels, 67_108_864); ++ assert_eq!(limits.max_progressive_pixels, 67_108_864); ++ assert_eq!(limits.max_job_bytes, 12 * 1024 * 1024 * 1024); ++ assert_eq!(limits.max_work_units, 16_000_000_000_000); ++ assert_eq!(crate::job::NATIVE_CPU_POOL_BYTES, 16 * 1024 * 1024 * 1024); ++ let million = Some(CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 }); ++ CpuBudget::Workstation.validate_image(256, 256, million).unwrap(); ++ assert!(CpuBudget::Workstation.validate_image(257, 256, million).is_err()); ++ assert!(CpuBudget::Workstation.validate_image(u32::MAX, u32::MAX, million).is_err()); ++ // Pure admission boundaries, no large image or film allocation. ++ for (width, height, samples) in [(1920, 1080, 33_140), (3840, 2160, 8_285), (7680, 4320, 2_071), (8192, 8192, 1024)] { ++ CpuBudget::Workstation.validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 7 })).unwrap(); ++ assert!( ++ CpuBudget::Workstation ++ .validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: samples + 1, seed: 7 })) ++ .is_err() ++ ); ++ } ++ for budget in [CpuBudget::Studio, CpuBudget::Workstation] { ++ assert_eq!(budget.validate_execution().is_err(), cfg!(target_arch = "wasm32") || usize::BITS < 64); ++ } ++ CpuBudget::Compact.validate_execution().unwrap(); ++ } ++ ++ #[test] ++ fn one_pixel_million_sample_intent_does_not_allocate_a_sample_history() { ++ let low = CpuProgressiveOptions { samples_per_pixel: 1, seed: 7 }; ++ let high = CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 }; ++ let bytes = PrimaryFilm::required_bytes(1, 1, high, CpuBudget::Workstation).unwrap(); ++ assert_eq!(PrimaryFilm::required_bytes(1, 1, low, CpuBudget::Workstation).unwrap(), bytes); ++ assert!(PrimaryFilm::new(1, 1, high, bytes - 1, &CancelToken::default(), CpuBudget::Workstation).is_err()); ++ for samples_per_pixel in [0, 1_048_577, u32::MAX] { ++ assert!(PrimaryFilm::required_bytes(1, 1, CpuProgressiveOptions { samples_per_pixel, seed: 7 }, CpuBudget::Workstation).is_err()); ++ } ++ assert!(PrimaryFilm::required_bytes(257, 256, high, CpuBudget::Workstation).is_err()); ++ } ++ ++ #[test] ++ fn primary_resolve_keeps_exact_u32_counts_at_65535_65536_and_the_workstation_cap() { ++ // Real film commits, one pixel only: no ray tracing, PNG, host or million-frame render. ++ let mut film = primary(1_048_576); ++ let cancel = CancelToken::default(); ++ let mut charged = 0u64; ++ for ordinal in 0..1_048_576 { ++ film.add(0, ordinal, [1.0, 2.0, 4.0], true, &cancel, &mut || { ++ charged += 1; ++ Ok(()) ++ }) ++ .unwrap(); ++ let count = ordinal + 1; ++ if [4096, 65_535, 65_536, 1_048_576].contains(&count) { ++ let (mean, covered, samples): ([f64; 3], u32, u32) = film.pixel(0).unwrap(); ++ assert_eq!(mean, [1.0, 2.0, 4.0]); ++ assert_eq!((covered, samples), (count, count)); ++ assert_eq!(film.samples(), count); ++ assert_eq!(charged, u64::from(count)); ++ assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Sampled { linear_premultiplied: mean, covered: count, count }); ++ } ++ } ++ let before = film.pixel(0).unwrap(); ++ let frontier = film.partial_frontier().unwrap(); ++ for ordinal in [1_048_576, 1_048_577, u32::MAX] { ++ assert!(film.add(0, ordinal, [0.0; 3], false, &cancel, &mut || panic!("rejected ordinal charged work")).is_err()); ++ assert_eq!(film.pixel(0).unwrap(), before); ++ assert_eq!(film.partial_frontier().unwrap(), frontier); ++ } ++ } ++ ++ #[test] ++ fn high_counts_keep_misses_in_the_mean_and_the_real_coverage_denominator() { ++ let mut film = primary(65_537); ++ let cancel = CancelToken::default(); ++ for ordinal in 0..65_537 { ++ let covered = ordinal % 2 == 0; ++ film.add(0, ordinal, if covered { [2.0, 4.0, 8.0] } else { [0.0; 3] }, covered, &cancel, &mut || Ok(())).unwrap(); ++ let count = ordinal + 1; ++ if [65_535, 65_536, 65_537].contains(&count) { ++ let hits = count.div_ceil(2); ++ let expected = [2.0, 4.0, 8.0].map(|value| value * f64::from(hits) / f64::from(count)); ++ assert_eq!(film.pixel(0).unwrap(), (expected, hits, count)); ++ assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Sampled { linear_premultiplied: expected, covered: hits, count }); ++ } ++ } ++ } ++ ++ #[test] ++ fn high_count_cancellation_and_work_failure_preserve_the_exact_committed_film() { ++ let mut film = primary(65_537); ++ for ordinal in 0..65_536 { ++ film.add(0, ordinal, [1.0, 2.0, 4.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); ++ } ++ let before = film.pixel(0).unwrap(); ++ let frontier = film.partial_frontier().unwrap(); ++ let cancelled = CancelToken::default(); ++ cancelled.cancel(); ++ assert_eq!( ++ film.add(0, 65_536, [3.0; 3], true, &cancelled, &mut || panic!("cancelled input charged work")).unwrap_err().code, ++ ErrorCode::Cancelled ++ ); ++ let cancel = CancelToken::default(); ++ let observer = cancel.clone(); ++ let mut charged = 0; ++ assert_eq!( ++ film.add(0, 65_536, [3.0; 3], true, &cancel, &mut || { ++ charged += 1; ++ observer.cancel(); ++ Ok(()) ++ }) ++ .unwrap_err() ++ .code, ++ ErrorCode::Cancelled ++ ); ++ assert_eq!(charged, 1); ++ assert!(film.add(0, 65_536, [3.0; 3], true, &CancelToken::default(), &mut || Err(limit("same cumulative job exhausted"))).is_err()); ++ assert_eq!(film.pixel(0).unwrap(), before); ++ assert_eq!(film.partial_frontier().unwrap(), frontier); ++ film.add(0, 65_536, [1.0, 2.0, 4.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); ++ assert_eq!(film.pixel(0).unwrap(), ([1.0, 2.0, 4.0], 65_537, 65_537)); ++ } ++ ++ #[test] ++ fn changing_only_the_target_keeps_old_4096_prefix_bits_and_ordinals() { ++ let mut old_target = primary(4096); ++ let mut high_target = primary(1_048_576); ++ let cancel = CancelToken::default(); ++ for ordinal in 0..4096 { ++ let covered = ordinal % 3 != 0; ++ let sample = if covered { [0.25, 2.0, 8.0] } else { [0.0; 3] }; ++ old_target.add(0, ordinal, sample, covered, &cancel, &mut || Ok(())).unwrap(); ++ high_target.add(0, ordinal, sample, covered, &cancel, &mut || Ok(())).unwrap(); ++ let (old_mean, old_covered, old_count) = old_target.pixel(0).unwrap(); ++ let (high_mean, high_covered, high_count) = high_target.pixel(0).unwrap(); ++ assert_eq!(old_mean.map(f64::to_bits), high_mean.map(f64::to_bits)); ++ assert_eq!((old_covered, old_count), (high_covered, high_count)); ++ assert_eq!(old_target.partial_frontier().unwrap(), high_target.partial_frontier().unwrap()); ++ } ++ } ++} +--- a/crates/render/src/job/cpu_budget.rs ++++ b/crates/render/src/job/cpu_budget.rs +@@ -14,7 +14,7 @@ + pub const MAX_CPU_TRIANGLES: usize = 8_000_000; + pub const MAX_CPU_BODIES: usize = 262_144; + /// Maximum admitted primary-film samples, shared with the display resolver. +-pub const MAX_CPU_SAMPLES_PER_PIXEL: u32 = 4096; ++pub const MAX_CPU_SAMPLES_PER_PIXEL: u32 = 1_048_576; + + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] + #[serde(rename_all = "snake_case")] +--- a/crates/render/src/job/host.rs ++++ b/crates/render/src/job/host.rs +@@ -438,7 +438,84 @@ + pub struct RenderPreview { + pub info: PreviewInfo, + png: Vec, +- _reservation: Reservation, ++ _reservation: CheckpointLease, ++} ++ ++/// Two reusable, immutable complete-pass slots. No consumer acknowledgement or ++/// queue: externally pinned slots are diagnosed and never stall final work. ++struct CheckpointCredits { ++ state: Mutex, ++ slot_bytes: u64, ++ capacity: u64, ++} ++struct CheckpointCreditState { ++ free: Reservation, ++ closed: bool, ++} ++impl CheckpointCredits { ++ fn new(reservation: &mut Reservation, slot_bytes: u64, slots: u32) -> Result> { ++ if !(1..=2).contains(&slots) || slot_bytes == 0 { ++ return Err(JobError::new(ErrorCode::InvalidRequest, "checkpoint credits require one or two finite slots")); ++ } ++ let capacity = slot_bytes ++ .checked_mul(u64::from(slots)) ++ .and_then(|n| n.checked_add(1024)) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit capacity overflow"))?; ++ let free = reservation.split(capacity)?; ++ Ok(Arc::new(Self { state: Mutex::new(CheckpointCreditState { free, closed: false }), slot_bytes, capacity })) ++ } ++ fn acquire(self: &Arc) -> Result> { ++ let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "checkpoint credit lock poisoned"))?; ++ if state.closed { ++ return Err(JobError::new(ErrorCode::Cancelled, "checkpoint credits are closed")); ++ } ++ let needed = self.slot_bytes.checked_add(1024).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit bound overflow"))?; ++ if state.free.bytes < needed { ++ return Ok(None); ++ } ++ let reservation = state.free.split(self.slot_bytes)?; ++ Ok(Some(CheckpointLease { reservation, credits: self.clone() })) ++ } ++ fn close(&self) { ++ let mut state = match self.state.lock() { ++ Ok(state) => state, ++ Err(error) => error.into_inner(), ++ }; ++ state.closed = true; ++ let _ = state.free.shrink(0); ++ } ++} ++struct CheckpointLease { ++ reservation: Reservation, ++ credits: Arc, ++} ++impl std::ops::Deref for CheckpointLease { ++ type Target = Reservation; ++ fn deref(&self) -> &Reservation { ++ &self.reservation ++ } ++} ++impl Drop for CheckpointLease { ++ fn drop(&mut self) { ++ let mut state = match self.credits.state.lock() { ++ Ok(state) => state, ++ Err(error) => { ++ let mut state = error.into_inner(); ++ state.closed = true; ++ let _ = state.free.shrink(0); ++ state ++ } ++ }; ++ if !state.closed { ++ if state.free.bytes.checked_add(self.reservation.bytes).is_some_and(|n| n <= self.credits.capacity) ++ && state.free.merge_from(&mut self.reservation).is_ok() ++ { ++ return; ++ } ++ state.closed = true; ++ let _ = state.free.shrink(0); ++ } ++ } + } + + impl RenderPreview { +@@ -457,6 +534,9 @@ + + #[derive(Clone, Debug, Serialize)] + pub struct JobStatus { ++ /// Completed CPU passes whose immutable snapshot could not be published ++ /// because both admitted slots remained pinned by external consumers. ++ pub cpu_preview_retention_skips: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub punctual_diagnostics: Option, + #[serde(skip_serializing_if = "Option::is_none")] +@@ -481,6 +561,7 @@ + } + + struct Data { ++ cpu_preview_retention_skips: u32, + partial_preview: Option>, + punctual_diagnostics: Option, + sampling: Option, +@@ -529,6 +610,7 @@ + pub fn status(&self) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + Ok(JobStatus { ++ cpu_preview_retention_skips: data.cpu_preview_retention_skips, + punctual_diagnostics: data.punctual_diagnostics, + presentation: self.0.presentation.as_deref().map(|retained| retained.info.clone()), + sampling: data.sampling.clone(), +@@ -700,8 +782,18 @@ + handle: JobHandle, + reservation: Option, + next_preview_sequence: u32, ++ next_checkpoint_pass: u32, ++ checkpoints: Option>, + // Task/PNG allocations above die before the in-flight credit below. + partial: Option>, ++} ++ ++impl Drop for Running { ++ fn drop(&mut self) { ++ if let Some(credits) = &self.checkpoints { ++ credits.close(); ++ } ++ } + } + + /// One fallibly allocated task, keeping the dispatch enum small in either build. +@@ -736,7 +828,7 @@ + #[cfg(feature = "raytrace-cpu")] + Partial { + png: Vec, +- covered: Vec, ++ covered: Vec, + completed_passes: u32, + updated_prefix: u64, + }, +@@ -762,6 +854,14 @@ + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => task.get_mut()?.partial_preview_ready(plan), + _ => Ok(false), ++ } ++ } ++ fn completed_pass_ready(&self, plan: super::PartialPreviewPlan) -> Result> { ++ let _ = &plan; ++ match self { ++ #[cfg(feature = "raytrace-cpu")] ++ Self::Raytrace(slot) => slot.0.first().map_or(Ok(None), |task| task.completed_pass_preview_ready(plan)), ++ _ => Ok(None), + } + } + fn begin_partial(&mut self, plan: super::PartialPreviewPlan) -> Result { +@@ -919,7 +1019,37 @@ + + // The private factory keeps post-construction setup fallible without losing + // the real ledger. It runs only after report capture and outside every lock. +- fn begin_with_partial_factory(work: Work, make_partial: impl FnOnce(Arc) -> Result>) -> Option { ++ fn begin_with_partial_factory( ++ mut work: Work, ++ make_partial: impl FnOnce(Arc) -> Result>, ++ ) -> Option { ++ let checkpoints = (|| { ++ let slots = work ++ .handle ++ .0 ++ .request ++ .raytrace ++ .as_ref() ++ .and_then(|options| options.progressive) ++ .filter(|_| work.handle.0.partial.is_none() && work.executor.is_none()) ++ .map_or(0, |options| options.samples_per_pixel.saturating_sub(1).min(2)); ++ if slots == 0 { ++ return Ok(None); ++ } ++ let slot_bytes = u64::from(work.handle.0.request.width) ++ .checked_mul(u64::from(work.handle.0.request.height)) ++ .and_then(|n| n.checked_mul(8)) ++ .and_then(|n| n.checked_add(65_536 + FRAME_METADATA_BYTES)) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint slot overflow"))?; ++ CheckpointCredits::new(&mut work.reservation, slot_bytes, slots).map(Some) ++ })(); ++ let checkpoints = match checkpoints { ++ Ok(credits) => credits, ++ Err(error) => { ++ terminal(&work.handle, error); ++ return None; ++ } ++ }; + if work.handle.0.cancel.is_cancelled() { + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render cancelled")); + return None; +@@ -967,6 +1097,8 @@ + handle: work.handle, + reservation: Some(work.reservation), + next_preview_sequence: 1, ++ next_checkpoint_pass: 1, ++ checkpoints, + }), + Err(error) => { + terminal(&work.handle, error); +@@ -982,21 +1114,58 @@ + } + if let Some(partial) = self.partial.as_mut() { + let partial = partial.get_mut()?; +- if partial.lease.is_none() && partial.credits.requested.load(Ordering::Acquire) && !partial.credits.exhausted.load(Ordering::Acquire) { ++ let task = self.task.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; ++ let uniform_pass = task.completed_pass_ready(partial.credits.plan)?; ++ let automatic_pass = uniform_pass.filter(|pass| *pass > partial.last_pass_attempt); ++ if let Some(pass) = automatic_pass { ++ partial.last_pass_attempt = pass; ++ partial.credits.request()?; ++ } ++ if partial.lease.is_none() ++ && partial.credits.requested.load(Ordering::Acquire) ++ && !partial.credits.exhausted.load(Ordering::Acquire) ++ && (uniform_pass.is_none() || automatic_pass.is_some()) ++ { + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; +- if task.partial_ready(partial.credits.plan)? +- && let Some(lease) = partial.credits.acquire()? +- { +- // Keep the lease past any producer error until task buffers drop. +- partial.lease = Some(lease); +- let begin = task.begin_partial(partial.credits.plan); +- partial.credits.store_report(task.protected_report())?; +- if !begin? { +- if partial.credits.protected.is_some() && !partial.credits.exhausted.load(Ordering::Acquire) { +- return Err(JobError::new(ErrorCode::Internal, "protected feedback refused without real quota exhaustion")); ++ if task.partial_ready(partial.credits.plan)? { ++ let mut lease = partial.credits.acquire()?; ++ if lease.is_none() && automatic_pass.is_some() { ++ let released = self ++ .handle ++ .0 ++ .data ++ .lock() ++ .map_err(|_| JobError::new(ErrorCode::Internal, "partial retirement lock poisoned"))? ++ .partial_preview ++ .take(); ++ drop(released); ++ lease = partial.credits.acquire()?; ++ } ++ if lease.is_none() && automatic_pass.is_some() && partial.credits.retained_slots_blocked()? { ++ let mut data = self ++ .handle ++ .0 ++ .data ++ .lock() ++ .map_err(|_| JobError::new(ErrorCode::Internal, "partial retention diagnostic lock poisoned"))?; ++ self.handle.0.cancel.check()?; ++ data.cpu_preview_retention_skips = data ++ .cpu_preview_retention_skips ++ .checked_add(1) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial retention diagnostic overflow"))?; ++ } ++ if let Some(lease) = lease { ++ // Keep the lease past any producer error until task buffers drop. ++ partial.lease = Some(lease); ++ let begin = task.begin_partial(partial.credits.plan); ++ partial.credits.store_report(task.protected_report())?; ++ if !begin? { ++ if partial.credits.protected.is_some() && !partial.credits.exhausted.load(Ordering::Acquire) { ++ return Err(JobError::new(ErrorCode::Internal, "protected feedback refused without real quota exhaustion")); ++ } ++ partial.credits.exhaust(); ++ drop(partial.lease.take()); + } +- partial.credits.exhaust(); +- drop(partial.lease.take()); + } + } + } +@@ -1099,7 +1268,9 @@ + // actual hex allocation, bounded copied IDs and Arc/header allowance. + // The PNG allocation itself is retained once and billed by capacity below. + let frame_layout = if preview_samples.is_some() { std::mem::size_of::() } else { std::mem::size_of::() }; +- let fixed_metadata = std::mem::size_of::() + frame_layout + 2 * crate::MAX_RENDER_ID_BYTES + 32; ++ let checkpoint_metadata = ++ if preview_samples.is_some() { std::mem::size_of::() + 2 * std::mem::size_of::() } else { 0 }; ++ let fixed_metadata = std::mem::size_of::() + frame_layout + checkpoint_metadata + 2 * crate::MAX_RENDER_ID_BYTES + 32; + let linear_digest_bytes = if exr.is_some() { 64 } else { 0 }; + if fixed_metadata + .checked_add(info.png_sha256.capacity()) +@@ -1123,16 +1294,37 @@ + .and_then(|options| options.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "preview requires CPU progressive intent"))?; + let frame_sequence = self.next_preview_sequence; +- let expected = frame_sequence.checked_sub(1).and_then(|n| 1_u32.checked_shl(n)); ++ let expected = Some(self.next_checkpoint_pass); + if expected != Some(samples_per_pixel) || samples_per_pixel >= options.samples_per_pixel || self.task.is_none() { + return Err(JobError::new(ErrorCode::Internal, "invalid progressive checkpoint sequence")); + } + let next_sequence = frame_sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::Internal, "preview sequence exhausted"))?; +- let reservation = self +- .reservation +- .as_mut() +- .ok_or_else(|| JobError::new(ErrorCode::Internal, "missing progressive reservation"))? +- .split(png.capacity() as u64 + FRAME_METADATA_BYTES)?; ++ let credits = self.checkpoints.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing checkpoint credits"))?; ++ if (png.capacity() as u64).checked_add(FRAME_METADATA_BYTES).is_none_or(|bytes| bytes > credits.slot_bytes) { ++ return Err(JobError::new(ErrorCode::LimitExceeded, "checkpoint PNG exceeds its admitted slot")); ++ } ++ let mut reservation = credits.acquire()?; ++ if reservation.is_none() { ++ // Retire the host's obsolete slot before treating a consumer as ++ // pinned. A headless client never has to acknowledge previews. ++ let released = data.preview.take(); ++ drop(data); ++ drop(released); ++ reservation = credits.acquire()?; ++ data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview publication lock poisoned"))?; ++ self.handle.0.cancel.check()?; ++ } ++ self.next_checkpoint_pass = self ++ .next_checkpoint_pass ++ .checked_add(1) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; ++ let Some(reservation) = reservation else { ++ data.cpu_preview_retention_skips = data ++ .cpu_preview_retention_skips ++ .checked_add(1) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint retention diagnostic overflow"))?; ++ return Ok(true); ++ }; + data.preview = Some(Arc::new(RenderPreview { + info: PreviewInfo { frame_sequence, samples_per_pixel, frame: info }, + png, +@@ -1168,6 +1360,9 @@ + data.preview = None; + let released = data.partial_preview.take(); + data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; ++ if let Some(credits) = &self.checkpoints { ++ credits.close(); ++ } + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); +@@ -1817,6 +2012,7 @@ + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { ++ cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, +@@ -1940,6 +2136,7 @@ + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { ++ cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, +@@ -2357,7 +2554,7 @@ + pub struct RenderPartialPreview { + pub info: PartialPreviewInfo, + png: Vec, +- covered: Vec, ++ covered: Vec, + _lease: ReturnReservation, + } + const _: [(); 1] = [(); (std::mem::size_of::() + 2 * crate::MAX_RENDER_ID_BYTES + 256 <= 2048) as usize]; +@@ -2365,7 +2562,7 @@ + pub fn png(&self) -> &[u8] { + &self.png + } +- pub fn covered(&self) -> &[u16] { ++ pub fn covered(&self) -> &[u32] { + &self.covered + } + } +@@ -2436,6 +2633,14 @@ + self.requested.store(false, Ordering::Release); + Ok(Some(ReturnReservation { reservation: Some(reservation), credits: self.clone(), in_flight: true })) + } ++ fn retained_slots_blocked(&self) -> Result { ++ let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial retention lock poisoned"))?; ++ Ok(!state.closed ++ && !state.in_flight ++ && !self.exhausted.load(Ordering::Acquire) ++ && self.requested.load(Ordering::Acquire) ++ && state.free.bytes < self.plan.slot_bytes()?) ++ } + fn exhaust(&self) { + self.exhausted.store(true, Ordering::Release); + self.requested.store(false, Ordering::Release); +@@ -2501,7 +2706,7 @@ + } + } + struct PartialPending { +- covered: Vec, ++ covered: Vec, + completed_passes: u32, + updated_prefix: u64, + } +@@ -2512,6 +2717,7 @@ + lease: ReturnReservation, + } + struct PartialRunning { ++ last_pass_attempt: u32, + pending: Option, + lease: Option, + credits: Arc, +@@ -2519,7 +2725,7 @@ + } + impl PartialRunning { + fn new(credits: Arc) -> Self { +- Self { pending: None, lease: None, credits, next_sequence: 1 } ++ Self { pending: None, lease: None, credits, next_sequence: 1, last_pass_attempt: 0 } + } + } + impl JobHandle { +@@ -2552,7 +2758,7 @@ + } + impl Running { + #[cfg(feature = "raytrace-cpu")] +- fn capture_partial(&mut self, png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64) -> Result<()> { ++ fn capture_partial(&mut self, png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64) -> Result<()> { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without its policy"))?.get_mut()?; + let plan = partial.credits.plan; +@@ -2573,7 +2779,7 @@ + || updated_prefix >= source_pixels + || (completed_passes == 0 && updated_prefix == 0) + || covered.len() as u64 != plan.pixels() +- || (covered.capacity() as u64).checked_mul(2).is_none_or(|v| v > covered_limit) ++ || (covered.capacity() as u64).checked_mul(4).is_none_or(|v| v > covered_limit) + || png.capacity() as u64 > plan.encoded_limit()? + { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload exceeds its admitted frontier or capacities")); +@@ -2585,7 +2791,7 @@ + let samples = completed_passes + .checked_add(u32::from(source < updated_prefix)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial sample count overflow"))?; +- if u32::from(*count) > samples { ++ if *count > samples { + return Err(JobError::new(ErrorCode::Internal, "partial coverage exceeds committed source samples")); + } + } +--- a/crates/render/src/job/host_tests.rs ++++ b/crates/render/src/job/host_tests.rs +@@ -362,7 +362,7 @@ + break; + } + } +- assert_eq!(seen, [1, 2, 4, 8]); ++ assert_eq!(seen, [1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(interactive.state().unwrap(), State::TargetReached); + assert!(job.frame().unwrap().is_some()); + assert!(!interactive.attach(ticket, job.clone()).unwrap(), "duplicate acknowledgement cannot restart or cancel the accepted job"); +@@ -1376,7 +1376,7 @@ + } + let plan = PartialPreviewPlan::new(16384, 4096).unwrap(); + assert_eq!(plan.source_index(1025).unwrap(), 16 * 16384 + 16); +- assert_eq!(plan.snapshot_work().unwrap(), 12 * 1024 * 256 + 65538); ++ assert_eq!(plan.snapshot_work().unwrap(), 14 * 1024 * 256 + 65538); + assert!(PartialPreviewPlan::new(0, 1).is_err()); + assert!(PartialPreviewPlan::new(1, 0).is_err()); + } +@@ -1640,21 +1640,24 @@ + #[test] + fn profile_ordinary_caps_are_unchanged_and_protected_aggregate_is_explicit() { + assert_eq!(MAX_CPU_WORK, 16_000_000_000_000); +- assert_eq!(MAX_PROTECTED_CPU_WORK, 16_000_809_500_800); ++ assert_eq!(MAX_PROTECTED_CPU_WORK, 31_462_813_335_678); + for (profile, ordinary) in + [(CpuBudget::Compact, 1_000_000_000), (CpuBudget::Studio, 1_000_000_000_000), (CpuBudget::Workstation, MAX_CPU_WORK)] + { + let plan = ProtectedPreviewPlan::new(1024, 1024, 16, profile).unwrap(); + plan.validate().unwrap(); + assert_eq!(plan.ordinary_limit(), ordinary); +- assert_eq!(plan.quota_limit(), 64); +- assert_eq!(plan.snapshot_work().unwrap(), 12_648_450); +- assert_eq!(plan.presentation_limit().unwrap(), 809_500_800); +- assert_eq!(plan.aggregate_limit().unwrap(), ordinary + 809_500_800); ++ assert_eq!(plan.quota_limit(), 79); ++ assert_eq!(plan.snapshot_work().unwrap(), 14_745_602); ++ assert_eq!(plan.presentation_limit().unwrap(), 1_164_902_558); ++ assert_eq!(plan.aggregate_limit().unwrap(), ordinary + 1_164_902_558); + assert_eq!(plan.preview_plan(), crate::job::PartialPreviewPlan::new(1024, 1024).unwrap()); + } + let largest = ProtectedPreviewPlan::new(1024, 1024, 16, CpuBudget::Workstation).unwrap(); +- assert_eq!(largest.aggregate_limit().unwrap(), MAX_PROTECTED_CPU_WORK); ++ assert!( ++ largest.aggregate_limit().unwrap() < MAX_PROTECTED_CPU_WORK, ++ "the independent Cartesian ceiling need not be attained by this request" ++ ); + } + #[test] + fn zero_single_and_spread_milestones_are_checked_below_final_target() { +@@ -1666,12 +1669,12 @@ + assert_eq!(single.quota_limit(), 1); + assert_eq!(single.milestone(0).unwrap(), 1); + assert!(single.milestone(1).is_err()); +- for (w, h, spp, quota) in [(3, 1, 1, 2), (66, 1, 1, 64), (32, 32, 64, 64)] { ++ for (w, h, spp, quota, last) in [(3, 1, 1, 2, 2), (66, 1, 1, 64, 65), (32, 32, 64, 127, 64_512)] { + let plan = ProtectedPreviewPlan::new(w, h, spp, CpuBudget::Compact).unwrap(); + assert_eq!(plan.quota_limit(), quota); + let milestones: Vec<_> = (0..quota).map(|j| plan.milestone(j).unwrap()).collect(); + assert_eq!(milestones.first(), Some(&1)); +- assert_eq!(milestones.last(), Some(&(plan.total_commits() - 1))); ++ assert_eq!(milestones.last(), Some(&last)); + assert!(milestones.windows(2).all(|pair| pair[0] < pair[1])); + assert!(plan.milestone(quota).is_err()); + assert!(plan.milestone(u32::MAX).is_err()); +@@ -1726,11 +1729,11 @@ + let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap(); + let (budget, work, credits) = credits(plan); + assert!(credits.state.lock().unwrap().report.is_none()); +- let value = report(plan, 31, 1, 64); ++ let value = report(plan, 31, 1, 127); + credits.store_report(Some(value)).unwrap(); + assert_eq!(credits.state.lock().unwrap().report, Some(value)); + assert!(value.milestones_complete && !value.quota_exhausted); +- assert_eq!(value.presentation_used, 77_826); ++ assert_eq!(value.presentation_used, 79_874); + assert!(value.presentation_used < value.presentation_limit); + assert!(!credits.exhausted.load(Ordering::Acquire)); + assert!(credits.request().unwrap()); +@@ -1836,8 +1839,8 @@ + finish(&mut control_run); + let control_report = control.protected_preview_report().unwrap().unwrap(); + let control_frame = control.frame().unwrap().unwrap(); +- assert_eq!(control_report.presentation_used, 0); +- assert_eq!(control_report.accepted_snapshots, 0); ++ assert_eq!(control_report.presentation_used, 5_032_062); ++ assert_eq!(control_report.accepted_snapshots, 63); + assert!(control_report.ordinary_used > 0); + let (host, job, mut running) = fixture(2, 32, 32, 64); + assert!(job.request_partial_preview().unwrap()); +@@ -1846,9 +1849,10 @@ + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(report.ordinary_used, control_report.ordinary_used); + assert_eq!(report.ordinary_limit, 1_000_000_000); +- assert_eq!(report.accepted_snapshots, 1); +- assert_eq!(report.presentation_used, 77_826); +- assert_eq!(report.ordinary_used + report.presentation_used, control_report.ordinary_used + 77_826); ++ assert_eq!(report.accepted_snapshots, 64); ++ assert_eq!(report.presentation_used, 5_111_936); ++ assert_eq!(report.ordinary_used + report.presentation_used, control_report.ordinary_used + 5_111_936); ++ assert_eq!(report.presentation_used - control_report.presentation_used, 79_874); + assert_eq!(report.aggregate_limit, report.ordinary_limit + report.presentation_limit); + assert!(!report.quota_exhausted); + let frame = job.frame().unwrap().unwrap(); +@@ -1891,7 +1895,7 @@ + assert!(exhausted_seen); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let report = job.protected_preview_report().unwrap().unwrap(); +- assert_eq!((report.accepted_snapshots, report.quota_limit, report.next_milestone_index), (3, 3, 3)); ++ assert_eq!((report.accepted_snapshots, report.quota_limit, report.next_milestone_index), (2, 2, 2)); + assert!(report.quota_exhausted && report.milestones_complete); + assert_eq!(report.presentation_used, report.presentation_limit); + assert_eq!(report.ordinary_used, expected.ordinary_used, "full-pass tick and final remain ordinary"); +@@ -1931,8 +1935,8 @@ + finish(&mut running); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let report = job.protected_preview_report().unwrap().unwrap(); +- assert_eq!((report.accepted_snapshots, report.quota_limit), (2, 3)); +- assert!(!report.quota_exhausted); ++ assert_eq!((report.accepted_snapshots, report.quota_limit), (2, 2)); ++ assert!(report.quota_exhausted); + assert_eq!(Sha256::digest(first.png()), old_hash); + drop(running); + let slot = job.0.partial.as_ref().unwrap().plan.slot_bytes().unwrap(); +@@ -1961,7 +1965,7 @@ + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!(report.accepted_snapshots, 1); +- assert_eq!(report.presentation_used, 77_826); ++ assert_eq!(report.presentation_used, 79_874); + assert!(job.frame().unwrap().is_none()); + assert!(!job.request_partial_preview().unwrap()); + drop(running); +@@ -1980,7 +1984,7 @@ + } + assert!(running.pending_png.is_some()); + let before = job.protected_preview_report().unwrap().unwrap(); +- assert_eq!((before.accepted_snapshots, before.presentation_used), (1, 77_826)); ++ assert_eq!((before.accepted_snapshots, before.presentation_used), (1, 79_874)); + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.protected_preview_report().unwrap(), Some(before)); +@@ -2230,3 +2234,304 @@ + assert_eq!(host.admitted_bytes(), 0); + } + } ++ ++// Original fixtures for consecutive CPU publication; WRITTEN, NOT RUN. ++#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] ++mod every_cpu_pass { ++ use super::*; ++ use crate::job::{CpuBudget, CpuProgressiveOptions, RaytraceOptions}; ++ ++ enum Snapshot { ++ Complete(Arc), ++ Partial(Arc), ++ } ++ impl Snapshot { ++ fn pass(&self) -> u32 { ++ match self { ++ Self::Complete(preview) => preview.info.samples_per_pixel, ++ Self::Partial(preview) => { ++ assert_eq!(preview.info.updated_prefix, 0, "automatic publication is a uniform complete pass"); ++ preview.info.completed_passes ++ } ++ } ++ } ++ fn png(&self) -> &[u8] { ++ match self { ++ Self::Complete(preview) => preview.png(), ++ Self::Partial(preview) => preview.png(), ++ } ++ } ++ fn sequence(&self) -> u64 { ++ match self { ++ Self::Complete(preview) => u64::from(preview.info.frame_sequence), ++ Self::Partial(preview) => preview.info.sequence, ++ } ++ } ++ } ++ fn snapshot(job: &JobHandle, protected: bool) -> Option { ++ if protected { job.partial_preview().unwrap().map(Snapshot::Partial) } else { job.preview().unwrap().map(Snapshot::Complete) } ++ } ++ fn fixture(samples: u32, protected: bool) -> (CpuHost, JobHandle, Running) { ++ let host = ImageHost(Arc::new(Owner { ++ executor: None, ++ shared: CpuHost::shared(MEMORY_LIMIT), ++ kind: HostKind::NativeWorker, ++ running: Mutex::new(None), ++ _worker: None, ++ })); ++ let request = ImageRequest { ++ integrator: Integrator::Raytrace, ++ raytrace: Some(RaytraceOptions { ++ budget: if samples > 64 { CpuBudget::Workstation } else { CpuBudget::Compact }, ++ progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), ++ lights: Some(Vec::new()), ++ ..Default::default() ++ }), ++ width: 1, ++ height: 1, ++ background: [10, 20, 30], ++ ..request() ++ }; ++ let job = if protected { ++ host.submit_cpu_protected_partial_with_environment_and_options(id(7790, 1), 19, empty(), request, JobOptions::default(), None) ++ } else { ++ host.submit(id(7790, 1), 19, empty(), request) ++ } ++ .unwrap(); ++ let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); ++ let running = Running::begin(work).unwrap(); ++ (host, job, running) ++ } ++ fn finish(running: &mut Running) { ++ for _ in 0..10_000_000 { ++ if !running.advance(16_384).unwrap() { ++ return; ++ } ++ } ++ panic!("one-pixel every-pass fixture exceeded its finite continuation bound"); ++ } ++ fn run_all(samples: u32, protected: bool, quantum: usize) { ++ let (host, job, mut running) = fixture(samples, protected); ++ let admission = host.admitted_bytes(); ++ let mut previous = 0; ++ let mut complete = false; ++ for _ in 0..10_000_000 { ++ let more = running.advance(quantum).unwrap(); ++ if let Some(preview) = snapshot(&job, protected) { ++ let pass = preview.pass(); ++ if pass != previous { ++ assert_eq!(pass, previous + 1, "no missing, duplicate or reordered complete pass"); ++ assert!(pass < samples); ++ match &preview { ++ Snapshot::Complete(value) => { ++ assert_eq!(value.info.frame_sequence, pass); ++ assert_eq!(value.info.frame.job, job.id()); ++ assert_eq!(value.info.frame.scene_generation, 19); ++ } ++ Snapshot::Partial(value) => { ++ assert_eq!(value.info.sequence, u64::from(pass)); ++ assert_eq!(value.info.frame.job, job.id()); ++ assert_eq!(value.info.frame.scene_generation, 19); ++ assert_eq!(value.covered(), &[0]); ++ } ++ } ++ assert_eq!(image::load_from_memory(preview.png()).unwrap().to_rgba8().get_pixel(0, 0).0, [10, 20, 30, 255]); ++ assert!(job.frame().unwrap().is_none(), "a provisional pass is not a final image"); ++ previous = pass; ++ } ++ } // No retained consumer Arc and no UI acknowledgement. ++ assert!(host.admitted_bytes() <= admission, "publication recycles the same two prepaid slots"); ++ if !more { ++ complete = true; ++ break; ++ } ++ } ++ assert!(complete); ++ assert_eq!(previous, samples - 1); ++ let status = job.status().unwrap(); ++ assert_eq!(status.progress.phase, Phase::Completed); ++ assert_eq!(status.cpu_preview_retention_skips, 0); ++ assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 })); ++ assert!(job.preview().unwrap().is_none() && job.partial_preview().unwrap().is_none()); ++ let frame = job.frame().unwrap().unwrap(); ++ assert_eq!(image::load_from_memory(frame.png()).unwrap().to_rgba8().get_pixel(0, 0).0, [10, 20, 30, 255]); ++ if protected { ++ let report = job.protected_preview_report().unwrap().unwrap(); ++ assert_eq!(report.accepted_snapshots, samples - 1); ++ assert_eq!(report.presentation_used, u64::from(samples - 1) * 65_552); ++ } ++ drop(frame); ++ drop(status); ++ drop(running); ++ drop(job); ++ assert_eq!(host.admitted_bytes(), 0); ++ } ++ ++ #[test] ++ fn real_legacy_and_protected_hosts_publish_every_pass_without_ui_demand() { ++ for protected in [false, true] { ++ for quantum in [1, 16_384] { ++ for samples in [1, 7] { ++ run_all(samples, protected, quantum); ++ } ++ } ++ } ++ } ++ #[test] ++ #[cfg(target_pointer_width = "64")] ++ fn real_one_pixel_high_target_crosses_64_with_constant_slots() { ++ for protected in [false, true] { ++ run_all(65, protected, 16_384); ++ } ++ } ++ #[test] ++ fn two_external_snapshots_are_diagnosed_without_waiting_or_losing_the_final() { ++ for protected in [false, true] { ++ let (host, job, mut running) = fixture(7, protected); ++ let mut held = Vec::new(); ++ for _ in 0..100_000 { ++ assert!(running.advance(1).unwrap()); ++ if let Some(preview) = snapshot(&job, protected) { ++ if preview.pass() == held.len() as u32 + 1 { ++ held.push(preview); ++ } ++ } ++ if held.len() == 2 { ++ break; ++ } ++ } ++ assert_eq!(held.len(), 2); ++ let hashes: Vec<_> = held.iter().map(|preview| Sha256::digest(preview.png())).collect(); ++ finish(&mut running); ++ let status = job.status().unwrap(); ++ assert_eq!(status.progress.phase, Phase::Completed); ++ assert_eq!(status.cpu_preview_retention_skips, 4, "passes 3,4,5,6 had both slots externally pinned"); ++ assert!(job.frame().unwrap().is_some()); ++ for (preview, hash) in held.iter().zip(hashes) { ++ assert_eq!(Sha256::digest(preview.png()), hash); ++ } ++ drop(running); ++ drop(status); ++ drop(job); ++ assert!(host.admitted_bytes() > 0, "external snapshots remain charged after their job drops"); ++ drop(held); ++ assert_eq!(host.admitted_bytes(), 0); ++ } ++ } ++ #[test] ++ fn release_after_a_pinned_pass_keeps_publication_sequence_separate_from_actual_spp() { ++ for protected in [false, true] { ++ let (host, job, mut running) = fixture(7, protected); ++ let mut held = Vec::new(); ++ for _ in 0..100_000 { ++ assert!(running.advance(1).unwrap()); ++ if let Some(preview) = snapshot(&job, protected) { ++ if preview.pass() == held.len() as u32 + 1 { ++ held.push(preview); ++ } ++ } ++ if held.len() == 2 { ++ break; ++ } ++ } ++ assert_eq!(held.len(), 2); ++ for _ in 0..100_000 { ++ if job.status().unwrap().cpu_preview_retention_skips == 1 { ++ break; ++ } ++ assert!(running.advance(1).unwrap()); ++ } ++ assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); ++ drop(held.remove(0)); // Return exactly one old consumer slot after pass 3. ++ let mut fourth = None; ++ for _ in 0..100_000 { ++ assert!(running.advance(1).unwrap()); ++ if let Some(preview) = snapshot(&job, protected) { ++ if preview.pass() == 4 { ++ fourth = Some(preview); ++ break; ++ } ++ } ++ } ++ let fourth = fourth.unwrap(); ++ assert_eq!(fourth.pass(), 4); ++ assert_eq!(fourth.sequence(), 3, "SPP 3 was diagnosed, not published"); ++ assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); ++ drop(fourth); ++ finish(&mut running); ++ assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); ++ assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); ++ drop(running); ++ drop(job); ++ drop(held); ++ assert_eq!(host.admitted_bytes(), 0); ++ } ++ } ++ #[test] ++ fn cancellation_after_third_pass_and_last_digest_chunk_never_publishes_late() { ++ for protected in [false, true] { ++ let (host, job, mut running) = fixture(7, protected); ++ let mut held = None; ++ for _ in 0..100_000 { ++ assert!(running.advance(1).unwrap()); ++ if let Some(preview) = snapshot(&job, protected) { ++ if preview.pass() == 3 { ++ held = Some(preview); ++ break; ++ } ++ } ++ } ++ let held = held.unwrap(); ++ let hash = Sha256::digest(held.png()); ++ for _ in 0..100_000 { ++ if running.pending_png.is_some() { ++ break; ++ } ++ assert!(running.advance(1).unwrap()); ++ } ++ let pending = running.pending_png.as_mut().unwrap(); ++ while !pending.step(1, &job.0.cancel).unwrap() {} ++ job.cancel().unwrap(); ++ assert!(!running.guarded_step(1)); ++ assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); ++ assert!(job.preview().unwrap().is_none() && job.partial_preview().unwrap().is_none()); ++ assert!(job.frame().unwrap().is_none()); ++ assert_eq!(Sha256::digest(held.png()), hash); ++ drop(running); ++ drop(job); ++ drop(held); ++ assert_eq!(host.admitted_bytes(), 0); ++ } ++ } ++ #[test] ++ fn third_checkpoint_is_valid_after_two_but_a_gap_still_fails() { ++ let (host, job, mut running) = fixture(7, false); ++ let mut third = None; ++ for _ in 0..100_000 { ++ assert!(running.advance(1).unwrap()); ++ if let Some(preview) = job.preview().unwrap() { ++ if preview.info.samples_per_pixel == 3 { ++ third = Some(preview); ++ break; ++ } ++ } ++ } ++ let third = third.unwrap(); ++ assert_eq!(third.info.frame_sequence, 3); ++ for _ in 0..100_000 { ++ if running.pending_png.as_ref().is_some_and(|pending| pending.preview_samples == Some(4)) { ++ break; ++ } ++ assert!(running.advance(1).unwrap()); ++ } ++ running.pending_png.as_mut().unwrap().preview_samples = Some(5); ++ assert!(!running.guarded_step(1)); ++ assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); ++ assert!(job.preview().unwrap().is_none() && job.frame().unwrap().is_none()); ++ assert_eq!(third.info.samples_per_pixel, 3); ++ drop(running); ++ drop(job); ++ drop(third); ++ assert_eq!(host.admitted_bytes(), 0); ++ } ++} +--- a/crates/render/src/job/interactive.rs ++++ b/crates/render/src/job/interactive.rs +@@ -30,9 +30,10 @@ + request.height = fit(height); + let options = request.raytrace.get_or_insert_default(); + options.primary_samples = 1; +- // These are preview sampling choices only. Incompatible transport remains an +- // explicit error, rather than silently removing the user's requested effects. +- options.progressive = Some(CpuProgressiveOptions::default()); ++ // Preserve explicit accumulation intent, including its deterministic seed. ++ // Fixed-image callers keep the original preview default. Incompatible ++ // transport remains an error rather than silently removing requested effects. ++ options.progressive.get_or_insert_with(CpuProgressiveOptions::default); + if let Some(reflections) = &mut options.reflections { + reflections.samples = 1; + } +@@ -287,3 +288,84 @@ + let _ = self.cancel(); + } + } ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use crate::job::{CpuBudget, RaytraceOptions}; ++ ++ fn request(options: RaytraceOptions) -> ImageRequest { ++ ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, ++ raster_exposure_ev: 0.0, ++ raster_lights: None, ++ studio_weights: None, ++ integrator: Integrator::Raytrace, ++ raytrace: Some(options), ++ textures: None, ++ environment: None, ++ camera: Default::default(), ++ width: 81, ++ height: 53, ++ background: [40, 80, 120], ++ transparent_background: false, ++ } ++ } ++ ++ #[test] ++ fn explicit_progressive_target_and_seed_survive_interactive_conversion() { ++ for (budget, samples) in [(CpuBudget::Compact, 31), (CpuBudget::Studio, 997), (CpuBudget::Workstation, 1_048_576)] { ++ let mut source = request(RaytraceOptions { ++ budget, ++ progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: u32::MAX }), ++ primary_samples: 1, ++ exposure_ev: -2.0, ++ shadows: false, ++ ..Default::default() ++ }); ++ // The high target still obeys P*SPP admission; no implicit resize/profile. ++ if budget == CpuBudget::Workstation { ++ source.width = 3840; ++ source.height = 1; ++ } ++ let before = serde_json::to_value(&source).unwrap(); ++ let converted = cpu_request(&source).unwrap(); ++ let mut expected = source.clone(); ++ if budget == CpuBudget::Workstation { ++ expected.width = 1024; ++ } ++ assert_eq!(serde_json::to_value(converted).unwrap(), serde_json::to_value(expected).unwrap()); ++ assert_eq!(serde_json::to_value(&source).unwrap(), before); ++ } ++ } ++ ++ #[test] ++ fn fixed_interactive_keeps_original_default_and_invalid_explicit_intent_refuses() { ++ let source = request(RaytraceOptions { primary_samples: 16, ..Default::default() }); ++ let converted = cpu_request(&source).unwrap(); ++ let options = converted.raytrace.unwrap(); ++ assert_eq!(options.progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); ++ assert_eq!(options.primary_samples, 1); ++ assert!(source.raytrace.as_ref().unwrap().progressive.is_none()); ++ for (budget, samples) in [(CpuBudget::Compact, 65), (CpuBudget::Studio, 1025), (CpuBudget::Workstation, 1_048_577)] { ++ let invalid = request(RaytraceOptions { ++ budget, ++ primary_samples: 1, ++ progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 741 }), ++ ..Default::default() ++ }); ++ let before = serde_json::to_value(&invalid).unwrap(); ++ assert!(cpu_request(&invalid).is_err()); ++ assert_eq!(serde_json::to_value(&invalid).unwrap(), before); ++ } ++ let mut over_work = request(RaytraceOptions { ++ primary_samples: 1, ++ progressive: Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 741 }), ++ ..Default::default() ++ }); ++ over_work.width = 1024; ++ over_work.height = 1024; ++ assert!(cpu_request(&over_work).is_err(), "do not reduce the explicit target to fit the profile"); ++ } ++} +--- a/crates/render/src/job/mod.rs ++++ b/crates/render/src/job/mod.rs +@@ -694,10 +694,11 @@ + budget.validate_image(width, height, Some(*self)) + } + +- /// Nonfinal checkpoints whose PNG allocations may remain externally retained. ++ /// At most two reusable checkpoint reservations. A pinned consumer keeps its ++ /// slot charged; it does not authorize a new allocation per pass. + #[cfg(feature = "raytrace-cpu")] +- pub(crate) fn preview_count(&self) -> u32 { +- if self.samples_per_pixel <= 1 { 0 } else { (self.samples_per_pixel - 1).ilog2() + 1 } ++ pub(crate) fn checkpoint_slots(&self) -> u32 { ++ self.samples_per_pixel.saturating_sub(1).min(2) + } + } + +@@ -1735,12 +1736,12 @@ + } + pub fn covered_bytes(&self) -> Result { + self.validate()?; +- self.pixels().checked_mul(2).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial coverage capacity overflow")) ++ self.pixels().checked_mul(4).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial coverage capacity overflow")) + } + pub fn snapshot_work(&self) -> Result { + self.validate()?; + self.pixels() +- .checked_mul(12) ++ .checked_mul(14) + .and_then(|v| v.checked_add(65_538)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial work bound overflow")) + } +@@ -1761,7 +1762,10 @@ + } + + /// Explicit protected-feedback aggregate ceiling; the ordinary MAX_CPU_WORK is unchanged. +-pub const MAX_PROTECTED_CPU_WORK: u64 = 16_000_809_500_800; ++// At most 1024² representatives: 14 work units each plus 65,538 codec/hash ++// overhead. At most 64 early milestones and MAX_SPP-1 complete-pass snapshots. ++// This Cartesian upper bound is deliberately conservative; ordinary work is unchanged. ++pub const MAX_PROTECTED_CPU_WORK: u64 = MAX_CPU_WORK + 14_745_602 * (MAX_CPU_SAMPLES_PER_PIXEL as u64 + 63); + + /// Checked per-job feedback policy, not an admission token or an arbitrary work envelope. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] +@@ -1780,11 +1784,11 @@ + .checked_mul(u64::from(source_height)) + .and_then(|v| v.checked_mul(u64::from(samples_per_pixel))) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected camera-commit count overflow"))?; +- let quota_limit = if total_commits <= 1 { +- 0 +- } else { +- u32::try_from((total_commits - 1).min(64)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))? +- }; ++ let pixels = u64::from(source_width) * u64::from(source_height); ++ let early = ++ u32::try_from(pixels.saturating_sub(1).min(64)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early quota overflow"))?; ++ let quota_limit = ++ early.checked_add(samples_per_pixel - 1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))?; + let plan = Self { preview, samples_per_pixel, budget, total_commits, quota_limit }; + plan.aggregate_limit()?; + Ok(plan) +@@ -1827,20 +1831,58 @@ + .filter(|v| *v <= MAX_PROTECTED_CPU_WORK) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected aggregate work exceeds its explicit ceiling")) + } ++ /// Number of reached milestones in O(1), including a final sentinel without ++ /// adding a final-image snapshot. A delayed consumer cannot create a long ++ /// uninterruptible coalescing loop in the worker. ++ #[cfg(feature = "raytrace-cpu")] ++ pub(crate) fn reached_milestones(&self, committed: u64) -> Result { ++ if committed > self.total_commits { ++ return Err(JobError::new(ErrorCode::InvalidRequest, "protected frontier exceeds its final target")); ++ } ++ let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); ++ let early = pixels.saturating_sub(1).min(64); ++ let reached_early = if committed == 0 || early == 0 { ++ 0 ++ } else if committed >= pixels - 1 { ++ early ++ } else if early == 1 { ++ 1 ++ } else { ++ committed ++ .checked_mul(early - 1) ++ .map(|n| n.div_ceil(pixels - 2)) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected reached milestone overflow"))? ++ }; ++ let passes = (committed / pixels).min(u64::from(self.samples_per_pixel - 1)); ++ reached_early ++ .checked_add(passes) ++ .and_then(|n| u32::try_from(n).ok()) ++ .filter(|n| *n <= self.quota_limit) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected reached quota overflow")) ++ } ++ + /// Zero-based, strictly increasing milestones below the final target. + pub fn milestone(&self, index: u32) -> Result { + if index >= self.quota_limit { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected milestone index outside its quota")); + } +- if self.quota_limit == 1 { +- return Ok(1); +- } +- self.total_commits +- .checked_sub(2) +- .and_then(|v| v.checked_mul(u64::from(index))) +- .and_then(|v| v.checked_div(u64::from(self.quota_limit - 1))) +- .and_then(|v| v.checked_add(1)) +- .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected milestone arithmetic overflow")) ++ let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); ++ let early = u32::try_from(pixels.saturating_sub(1).min(64)) ++ .map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early milestone overflow"))?; ++ if index < early { ++ if early == 1 { ++ return Ok(1); ++ } ++ return pixels ++ .checked_sub(2) ++ .and_then(|n| n.checked_mul(u64::from(index))) ++ .and_then(|n| n.checked_div(u64::from(early - 1))) ++ .and_then(|n| n.checked_add(1)) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected early milestone arithmetic overflow")); ++ } ++ u64::from(index - early + 1) ++ .checked_mul(pixels) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected pass milestone arithmetic overflow")) + } + } + +--- a/crates/render/src/raytrace/environment_image_tests.rs ++++ b/crates/render/src/raytrace/environment_image_tests.rs +@@ -133,7 +133,7 @@ + + #[test] + fn progressive_hdr_and_rough_reflections_keep_the_same_absolute_prefix_at_every_quantum() { +- for (target, checkpoints) in [(3, vec![1, 2]), (7, vec![1, 2, 4])] { ++ for (target, checkpoints) in [(3, vec![1, 2]), (7, vec![1, 2, 3, 4, 5, 6])] { + let result = progressive_hdr_png(target, 82, 1, Some(input())); + assert_eq!(result.previews.iter().map(|(n, _)| *n).collect::>(), checkpoints); + let other = progressive_hdr_png(target, 82, 16384, Some(input())); +--- a/crates/render/src/raytrace/image.rs ++++ b/crates/render/src/raytrace/image.rs +@@ -302,7 +302,10 @@ + let previews = if let Some(plan) = partial { + plan.additional_bytes()? + } else { +- u64::from(progressive.preview_count()).checked_mul(checkpoint).ok_or_else(|| error(TraceError::MemoryLimit))? ++ u64::from(progressive.checkpoint_slots()) ++ .checked_mul(checkpoint) ++ .and_then(|bytes| bytes.checked_add(if progressive.checkpoint_slots() == 0 { 0 } else { 1024 })) ++ .ok_or_else(|| error(TraceError::MemoryLimit))? + }; + PrimaryFilm::required_bytes(request.width, request.height, progressive, options.budget)? + .checked_add(previews) +@@ -618,6 +621,7 @@ + pub struct ImageTask { + punctual_diagnostics: job::PunctualDiagnostics, + progressive: Option, ++ last_pass_boundary: u32, + optical: Vec, + anisotropic_targets: [Option; 2], + environment: Option, +@@ -667,7 +671,7 @@ + pub(crate) enum PartialImagePoll { + Pending(Progress), + Complete(Vec), +- Preview { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, ++ Preview { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, + } + + pub(crate) enum PartialBegin { +@@ -677,7 +681,7 @@ + + enum ImageAdvance { + Legacy(ImagePoll), +- Partial { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, ++ Partial { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, + } + + impl ImageTask { +@@ -868,6 +872,7 @@ + Ok(Self { + punctual_diagnostics: Default::default(), + progressive, ++ last_pass_boundary: 0, + optical, + anisotropic_targets, + environment, +@@ -1087,8 +1092,8 @@ + .ok_or_else(|| invalid("spatial coverage bound"))?; + let rgba = composite_spatial( + self.spatial_radiance, +- self.primary_coverage, +- attempts, ++ u32::from(self.primary_coverage), ++ u32::from(attempts), + self.request.background, + self.visibility_owner.options().exposure_ev, + )?; +@@ -1960,6 +1965,14 @@ + progressive::represented_changed(plan, progressive.last_partial, frontier) + } + ++ pub(crate) fn completed_pass_preview_ready(&self, plan: job::PartialPreviewPlan) -> job::Result> { ++ if self.work.protected.is_none() || !self.partial_preview_ready(plan)? { ++ return Ok(None); ++ } ++ let frontier = self.progressive.as_ref().ok_or_else(|| invalid("missing progressive film"))?.film.partial_frontier()?; ++ Ok((frontier.updated_prefix == 0 && frontier.completed_passes > 0).then_some(frontier.completed_passes)) ++ } ++ + /// Host must already hold its one in-flight credit. No host lease or clock + /// lives here; an insufficient optional debit does not mutate trace state. + pub(crate) fn begin_partial_preview(&mut self, plan: job::PartialPreviewPlan) -> job::Result { +@@ -2008,8 +2021,6 @@ + let (rgba, covered) = match value { + crate::film::primary::PartialPixel::Unknown => ([0; 4], 0), + crate::film::primary::PartialPixel::Sampled { linear_premultiplied, covered, count } => { +- let covered = u16::try_from(covered).map_err(|_| error(TraceError::MemoryLimit))?; +- let count = u16::try_from(count).map_err(|_| error(TraceError::MemoryLimit))?; + let [r, g, b] = linear_premultiplied; + ( + composite_spatial(Vec3::new(r, g, b), covered, count, self.request.background, self.visibility_owner.options().exposure_ev)?, +@@ -2180,9 +2191,14 @@ + } else if self.bvh.is_some() { + if self.pixel == self.request.width as usize * self.request.height as usize { + if let Some(progressive) = &mut self.progressive { ++ let samples = progressive.film.samples(); ++ if progressive.partial_plan.is_some() && samples < progressive.options.samples_per_pixel && samples > self.last_pass_boundary ++ { ++ self.last_pass_boundary = samples; ++ return Ok(ImageAdvance::Legacy(ImagePoll::Pending(self.progress()))); ++ } + self.work.tick(&self.cancel).map_err(error)?; +- let samples = progressive.film.samples(); +- if samples == progressive.options.samples_per_pixel || (progressive.partial_plan.is_none() && samples.is_power_of_two()) { ++ if samples == progressive.options.samples_per_pixel || progressive.partial_plan.is_none() { + progressive.resolving = true; + } else { + self.pixel = 0; +@@ -2270,15 +2286,30 @@ + if spatial_samples == 1 && film_sample == 0 { + return Ok(pixel); + } +- pixel +- .checked_mul(u64::from(job::MAX_CPU_SAMPLES_PER_PIXEL) * 16) +- .and_then(|key| key.checked_add(u64::from(film_sample) * 16 + u64::from(spatial))) +- .map(|key| key ^ 0x4152_4541_5341_4d50) +- .ok_or_else(|| invalid("area-light sample identity overflow")) +-} +- +-fn composite_spatial(premultiplied: Vec3, covered: u16, attempts: u16, background: [u8; 3], exposure: f64) -> job::Result<[u8; 4]> { +- if attempts == 0 || u32::from(attempts) > job::MAX_CPU_SAMPLES_PER_PIXEL || covered > attempts || !bounded_radiance(premultiplied) { ++ if film_sample < 4096 { ++ // Preserve every historical ordinal and fixed-primary key exactly. ++ return pixel ++ .checked_mul(4096 * 16) ++ .and_then(|key| key.checked_add(u64::from(film_sample) * 16 + u64::from(spatial))) ++ .map(|key| key ^ 0x4152_4541_5341_4d50) ++ .ok_or_else(|| invalid("area-light sample identity overflow")); ++ } ++ if pixel >= (1_u64 << 26) || film_sample >= (1_u32 << 20) { ++ return Err(invalid("area-light extended sample identity exceeds its fields")); ++ } ++ let mode = match spatial_samples { ++ 1 => 0_u64, ++ 4 => 1, ++ 16 => 2, ++ _ => return Err(invalid("area-light primary mode")), ++ }; ++ // Separate extended ordinals from old keys and reserve ten low bits for ++ // the existing light/emitter RNG offsets. No target/budget/cadence key. ++ Ok((1_u64 << 63) | (pixel << 36) | (u64::from(film_sample) << 16) | (mode << 14) | (u64::from(spatial) << 10)) ++} ++ ++fn composite_spatial(premultiplied: Vec3, covered: u32, attempts: u32, background: [u8; 3], exposure: f64) -> job::Result<[u8; 4]> { ++ if attempts == 0 || attempts > job::MAX_CPU_SAMPLES_PER_PIXEL || covered > attempts || !bounded_radiance(premultiplied) { + return Err(invalid("invalid spatial coverage/radiance")); + } + if covered == 0 { +--- a/crates/render/src/raytrace/image_tests.rs ++++ b/crates/render/src/raytrace/image_tests.rs +@@ -1758,7 +1758,7 @@ + assert!(task.pending.is_none()); + assert!(task.optical.first().unwrap().pending.is_none()); + let (_, covered, count) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); +- assert_eq!((u32::from(covered), u32::from(count)), (samples_per_pixel, samples_per_pixel)); ++ assert_eq!((covered, count), (samples_per_pixel, samples_per_pixel)); + checkpoints.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { +@@ -1778,7 +1778,7 @@ + let four = finish_optical_progressive(ImageTask::new(scene, request, CancelToken::default(), options).unwrap(), 4); + assert_eq!(one, four, "film bits, actual primary rays, checkpoints, final and total work agree"); + assert_eq!(one.primaries.len(), 5); +- assert_eq!(one.checkpoints.iter().map(|c| c.0).collect::>(), [1, 2, 4]); ++ assert_eq!(one.checkpoints.iter().map(|c| c.0).collect::>(), [1, 2, 3, 4]); + assert_ne!(one.primaries[0].2, one.primaries[1].2, "fresh camera jitter, no repeated completed sample"); + let linear = f64::from_bits(one.film[0][0]); + assert!(linear > 0.999 && linear <= 1.0 + 1e-12, "bounded eight-boundary lossless response, not alpha or branch averaging"); +--- a/crates/render/src/raytrace/mod.rs ++++ b/crates/render/src/raytrace/mod.rs +@@ -179,13 +179,7 @@ + let presentation_used = state.presentation_used.checked_add(cost).filter(|v| *v <= state.presentation_limit).ok_or(TraceError::WorkLimit)?; + let used = self.used.checked_add(cost).filter(|v| *v <= state.aggregate_limit).ok_or(TraceError::WorkLimit)?; + let accepted = state.accepted_snapshots.checked_add(1).filter(|n| *n <= state.plan.quota_limit()).ok_or(TraceError::WorkLimit)?; +- let mut next = state.next_milestone_index; +- while next < state.plan.quota_limit() { +- if state.plan.milestone(next).map_err(|_| TraceError::Internal("invalid protected milestone"))? > committed { +- break; +- } +- next = next.checked_add(1).ok_or(TraceError::WorkLimit)?; +- } ++ let next = state.plan.reached_milestones(committed).map_err(|_| TraceError::Internal("invalid protected reached frontier"))?; + check_cancel(cancel)?; + let state = self.protected.as_mut().ok_or(TraceError::Internal("protected ledger disappeared"))?; + state.presentation_used = presentation_used; +--- a/crates/render/src/raytrace/primary_aa_tests.rs ++++ b/crates/render/src/raytrace/primary_aa_tests.rs +@@ -35,7 +35,7 @@ + #[test] + fn progressive_real_png_has_stable_prefixes_quanta_and_fresh_primary_samples() { + let (previews, final_png, work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 1); +- assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 4]); ++ assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6, 7]); + let (other, other_final, other_work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 16_384); + assert_eq!(other, previews); + assert_eq!(other_final, final_png); +@@ -75,7 +75,11 @@ + assert_eq!(::image::load_from_memory(&half).unwrap().to_rgba8().get_pixel(0, 0).0, [expected, expected, expected, 255]); + } + let (previews, _, _) = progressive_complete(progressive_fixture(5, 9, Some(true), 0.0), 1); +- assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 4], "non-power-of-two target still has an exact final pass"); ++ assert_eq!( ++ previews.iter().map(|(samples, _)| *samples).collect::>(), ++ [1, 2, 3, 4], ++ "non-power-of-two target still has an exact final pass" ++ ); + } + + #[test] +@@ -456,25 +460,37 @@ + } + + #[test] +-fn workstation_progressive_resolves_every_checkpoint_through_its_admitted_cap() { ++fn workstation_progressive_streams_every_historical_2048_4096_checkpoint_and_checks_the_new_cap() { + let fixed = fixture(1, 1, Some(true)); + let cap = job::CpuBudget::Workstation.limits().max_samples_per_pixel; +- assert_eq!(cap, 4096); +- for samples in [2048, cap] { ++ assert_eq!(cap, 1_048_576); ++ for samples in [2048, 4096] { + let mut options = fixed.visibility_owner.options().clone(); + options.budget = job::CpuBudget::Workstation; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }); + let request = ImageRequest { raytrace: Some(options.clone()), ..fixed.request.clone() }; +- let task = ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); +- let (previews, final_png, _) = progressive_complete(task, 16_384); +- let expected: Vec<_> = (0..samples.ilog2()).map(|power| 1_u32 << power).collect(); +- assert_eq!(previews.iter().map(|(n, _)| *n).collect::>(), expected); +- for (_, png) in &previews { +- assert_eq!(::image::load_from_memory(png).unwrap().to_rgba8().dimensions(), (1, 1)); +- } +- assert_eq!(::image::load_from_memory(&final_png).unwrap().to_rgba8().dimensions(), (1, 1)); +- } +- assert!(composite_spatial(Vec3::ZERO, 0, 4097, [0; 3], 0.0).is_err()); ++ let mut task = ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); ++ let mut observed = Vec::new(); ++ let mut complete = false; ++ for _ in 0..200_000 { ++ match task.step_with_previews(16_384).unwrap() { ++ ImagePoll::Pending(_) => {} ++ ImagePoll::Preview { png, samples_per_pixel } => { ++ observed.push(samples_per_pixel); ++ assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1, 1)); ++ } ++ ImagePoll::Complete(png) => { ++ assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1, 1)); ++ complete = true; ++ break; ++ } ++ } ++ } ++ assert!(complete); ++ assert_eq!(observed, (1..samples).collect::>()); ++ } ++ assert_eq!(composite_spatial(Vec3::ZERO, 0, 4097, [0; 3], 0.0).unwrap(), [0, 0, 0, 255]); ++ assert!(composite_spatial(Vec3::ZERO, 0, 1_048_577, [0; 3], 0.0).is_err()); + } + + #[test] +@@ -492,7 +508,8 @@ + } + } + assert_eq!(area_sample_key(41, 0, 1, 0).unwrap(), 41); +- assert!(area_sample_key(41, 0, 1, 4096).is_err()); ++ assert_eq!(area_sample_key(41, 0, 1, 4096).unwrap(), (1_u64 << 63) | (41_u64 << 36) | (4096_u64 << 16)); ++ assert!(area_sample_key(41, 0, 1, 1_048_576).is_err()); + assert!(area_sample_key(41, 4, 4, 0).is_err()); + assert!(area_sample_key(u64::MAX, 0, 4, 0).is_err()); + } +@@ -611,7 +628,7 @@ + let small = progressive_complete(progressive_area_fixture(count, 5, 23, true), 1); + let large = progressive_complete(progressive_area_fixture(count, 5, 23, true), 16_384); + assert_eq!(small, large, "area continuation must share the same cumulative work across quanta"); +- assert_eq!(small.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 4]); ++ assert_eq!(small.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4]); + for (samples, checkpoint) in &small.0 { + let (_, final_png, _) = progressive_complete(progressive_area_fixture(count, *samples, 23, true), 3); + assert_eq!(&final_png, checkpoint); +@@ -821,7 +838,7 @@ + } + panic!("real task did not reach requested committed frontier"); + } +-fn finish_partial_snapshot(task: &mut ImageTask) -> (Vec, Vec, u32, u64) { ++fn finish_partial_snapshot(task: &mut ImageTask) -> (Vec, Vec, u32, u64) { + let paid = task.work.used(); + for _ in 0..200_000 { + let poll = task.step_with_partial_previews(1).unwrap(); +@@ -1217,7 +1234,7 @@ + fn protected_actual_empty_counterexample_preserves_final_work_while_shared_cap_can_starve() { + let source = empty_progressive_source(); + let plan = protected_plan(&source); +- assert_eq!((plan.total_commits(), plan.quota_limit(), plan.snapshot_work().unwrap()), (65536, 64, 77826)); ++ assert_eq!((plan.total_commits(), plan.quota_limit(), plan.snapshot_work().unwrap()), (65536, 127, 79874)); + let mut reference = shared_partial_rebuild(&source, None); + let mut reference_rays = Vec::new(); + let expected = finish_partial_final(&mut reference, true, &mut reference_rays); +@@ -1263,7 +1280,7 @@ + let _ = finish_partial_snapshot(&mut task); + let paid = task.protected_preview_report().unwrap(); + assert_eq!(paid.ordinary_used, before.ordinary_used); +- assert_eq!((paid.presentation_used, paid.accepted_snapshots), (77826, 1)); ++ assert_eq!((paid.presentation_used, paid.accepted_snapshots), (79874, 1)); + } + let actual = finish_partial_final(&mut task, true, &mut rays); + assert_eq!(actual, expected, "protected feedback cannot change PNG or linear film"); +@@ -1271,7 +1288,7 @@ + assert_eq!(rays.len(), 65536); + let report = task.protected_preview_report().expect("actual report survives completed-film destruction"); + assert_eq!(report.ordinary_used, ordinary); +- let optional = if request_snapshot { 77826 } else { 0 }; ++ let optional = if request_snapshot { 79874 } else { 0 }; + assert_eq!(report.presentation_used, optional); + assert_eq!(task.work.used(), ordinary + optional); + assert_eq!(report.aggregate_limit, ordinary + plan.presentation_limit().unwrap()); +@@ -1319,7 +1336,7 @@ + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + let coalesced = task.protected_preview_report().unwrap(); +- assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 19, 19)); ++ assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 7, 7)); + assert!(coalesced.milestones_complete && !coalesced.quota_exhausted); + assert_eq!(coalesced.presentation_used, plan.snapshot_work().unwrap()); + assert!(coalesced.presentation_used < coalesced.presentation_limit); +@@ -1336,7 +1353,7 @@ + } + + #[test] +-fn protected_actual_sixty_four_snapshots_exhaust_quota_without_failing_final() { ++fn protected_actual_every_pass_and_early_snapshots_exhaust_quota_without_failing_final() { + let source = empty_progressive_source(); + let mut control = shared_partial_rebuild(&source, None); + let expected = finish_partial_final(&mut control, true, &mut Vec::new()); +@@ -1345,7 +1362,7 @@ + initial_test_work(&mut task, ordinary, true); + let plan = protected_plan(&task); + let mut rays = Vec::new(); +- for index in 0..64 { ++ for index in 0..127 { + let milestone = plan.milestone(index).unwrap(); + reach_partial_frontier(&mut task, (milestone / 1024) as u32, (milestone % 1024) as usize, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); +@@ -1353,7 +1370,7 @@ + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.accepted_snapshots, index + 1); + assert_eq!(report.next_milestone_index, index + 1); +- assert_eq!(report.presentation_used, u64::from(index + 1) * 77826); ++ assert_eq!(report.presentation_used, u64::from(index + 1) * 79874); + } + let exhausted = task.protected_preview_report().unwrap(); + assert!(exhausted.quota_exhausted && exhausted.milestones_complete); +@@ -1374,7 +1391,7 @@ + let complete = task.protected_preview_report().unwrap(); + assert_eq!(complete.ordinary_used, ordinary); + assert_eq!(task.work.used(), complete.aggregate_limit, "O reaches its full original T and V exactly Q"); +- assert_eq!(complete.presentation_used, 64 * 77826); ++ assert_eq!(complete.presentation_used, 127 * 79874); + } + + #[test] +@@ -1837,3 +1854,127 @@ + assert_eq!(report.presentation_used, plan.snapshot_work().unwrap()); + } + } ++ ++#[test] ++fn every_cpu_pass_seven_has_exact_short_job_pngs_across_worker_quanta() { ++ let run = progressive_complete(progressive_fixture(7, 123, Some(true), 0.0), 1); ++ assert_eq!(run.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6]); ++ assert_eq!(run, progressive_complete(progressive_fixture(7, 123, Some(true), 0.0), 16_384)); ++ for (samples, png) in &run.0 { ++ assert_eq!(png, &progressive_complete(progressive_fixture(*samples, 123, Some(true), 0.0), 3).1); ++ } ++} ++ ++#[test] ++fn every_cpu_pass_area_sample_keys_preserve_history_and_separate_high_ordinal_blocks() { ++ for (pixel, ordinal, spatial, primary, expected) in [ ++ (0_u64, 4095_u32, 0_u8, 1_u8, 0x4152_4541_5341_b2a0_u64), ++ (0, 4096, 0, 1, 0x8000_0000_1000_0000), ++ (1, 4096, 0, 1, 0x8000_0010_1000_0000), ++ (0, 4096, 0, 4, 0x8000_0000_1000_4000), ++ (0, 4096, 3, 4, 0x8000_0000_1000_4c00), ++ (0, 1_048_575, 15, 16, 0x8000_000f_ffff_bc00), ++ (67_108_863, 1_048_575, 15, 16, 0xbfff_ffff_ffff_bc00), ++ ] { ++ assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); ++ } ++ for pixel in [0_u64, 1, 67_108_863] { ++ for primary in [1_u8, 4, 16] { ++ for spatial in 0..primary { ++ for ordinal in [0_u32, 1, 63, 4095] { ++ let expected = if primary == 1 && ordinal == 0 { ++ pixel ++ } else { ++ (pixel * 65_536 + u64::from(ordinal) * 16 + u64::from(spatial)) ^ 0x4152_4541_5341_4d50 ++ }; ++ assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); ++ } ++ for ordinal in [4096_u32, 65_535, 65_536, 1_048_575] { ++ let mode = match primary { ++ 1 => 0_u64, ++ 4 => 1, ++ 16 => 2, ++ _ => unreachable!(), ++ }; ++ let expected = (1_u64 << 63) | (pixel << 36) | (u64::from(ordinal) << 16) | (mode << 14) | (u64::from(spatial) << 10); ++ assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); ++ assert_eq!(expected & 1023, 0); ++ assert_ne!( ++ area_sample_key(pixel, spatial, primary, ordinal).unwrap(), ++ area_sample_key(pixel, spatial, primary, ordinal % 4096).unwrap() ++ ); ++ } ++ } ++ } ++ } ++ assert!(area_sample_key(u64::MAX, 0, 1, 1).is_err()); ++ assert!(area_sample_key(0, 0, 1, 1_048_576).is_err()); ++ assert!(area_sample_key(1_u64 << 26, 0, 1, 4096).is_err()); ++ let mut states = std::collections::BTreeSet::new(); ++ for pixel in [0_u64, 67_108_863] { ++ for ordinal in [4096_u32, 65_535, 1_048_575] { ++ for light in 0..4_u64 { ++ for sample in 0..64_u64 { ++ let key = area_sample_key(pixel, 0, 1, ordinal).unwrap(); ++ let state = key.checked_add(u64::from(u32::MAX) * 65_537 + light * 104_729 + sample * 8191).unwrap(); ++ assert_ne!(state & (1_u64 << 63), 0); ++ assert!(states.insert(state), "initial RNG states, not generated UVs, stay distinct"); ++ } ++ } ++ } ++ } ++} ++ ++#[test] ++fn every_cpu_pass_display_uses_full_u32_coverage_without_saturation() { ++ assert_eq!(composite_spatial(Vec3::ZERO, 65_536, 65_536, [13, 27, 41], 0.0).unwrap(), [0, 0, 0, 255]); ++ assert_eq!(composite_spatial(Vec3::ZERO, 0, 65_536, [13, 27, 41], 0.0).unwrap(), [13, 27, 41, 255]); ++ assert!(composite_spatial(Vec3::ZERO, 65_537, 65_536, [13, 27, 41], 0.0).is_err()); ++} ++ ++#[test] ++#[cfg(target_pointer_width = "64")] ++fn every_cpu_pass_actual_65536_film_resolves_one_u32_snapshot_and_unique_final() { ++ let source = fixture(1, 1, None); ++ let mut options = source.visibility_owner.options().clone(); ++ options.budget = job::CpuBudget::Workstation; ++ options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 65_537, seed: 123 }); ++ let plan = job::ProtectedPreviewPlan::new(1, 1, 65_537, job::CpuBudget::Workstation).unwrap(); ++ let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; ++ let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( ++ source.visibility_owner.source().clone(), ++ request, ++ CancelToken::default(), ++ options, ++ None, ++ false, ++ plan, ++ ) ++ .unwrap(); ++ let mut reached = false; ++ for _ in 0..2_000_000 { ++ if task.progressive.as_ref().is_some_and(|state| state.film.ready() && state.film.samples() == 65_536) ++ && task.partial_preview_ready(plan.preview_plan()).unwrap() ++ { ++ reached = true; ++ break; ++ } ++ assert!(matches!(task.step_with_partial_previews(16_384).unwrap(), PartialImagePoll::Pending(_))); ++ } ++ assert!(reached); ++ let (linear, covered, count) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); ++ assert_eq!(linear, [0.0; 3]); ++ assert_eq!((covered, count), (0, 65_536)); ++ assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); ++ let (png, covered, passes, prefix) = finish_partial_snapshot(&mut task); ++ assert_eq!(covered, [0]); ++ assert_eq!((passes, prefix), (65_536, 0)); ++ assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); ++ let report = task.protected_preview_report().unwrap(); ++ assert_eq!((report.accepted_snapshots, report.next_milestone_index), (1, 65_536)); ++ assert_eq!(report.presentation_used, 65_552); ++ let (final_png, bits) = finish_partial_final(&mut task, true, &mut Vec::new()); ++ assert_eq!(::image::load_from_memory(&final_png).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); ++ assert_eq!(bits, [[0.0_f64.to_bits(); 3]]); ++ assert!(task.done && task.progressive.is_none()); ++} +--- a/crates/render/src/raytrace/progressive.rs ++++ b/crates/render/src/raytrace/progressive.rs +@@ -18,7 +18,7 @@ + pub frontier: crate::film::primary::PartialFrontier, + pub resume_pixel: usize, + pub next: usize, +- pub covered: Vec, ++ pub covered: Vec, + } + + /// Read-only O(1) test for new represented data; no scan over the source film. +--- a/crates/render/src/raytrace/tests.rs ++++ b/crates/render/src/raytrace/tests.rs +@@ -264,7 +264,7 @@ + fn protected_ledger_keeps_ordinary_profiles_and_requires_the_explicit_new_envelope() { + use crate::job::{CpuBudget, MAX_CPU_WORK, MAX_PROTECTED_CPU_WORK, ProtectedPreviewPlan}; + assert_eq!(MAX_CPU_WORK, 16_000_000_000_000); +- assert_eq!(MAX_PROTECTED_CPU_WORK, 16_000_809_500_800); ++ assert_eq!(MAX_PROTECTED_CPU_WORK, 31_462_813_335_678); + assert!(WorkBudget::new(MAX_CPU_WORK + 1).is_err()); + assert!(WorkBudget::new(MAX_PROTECTED_CPU_WORK).is_err()); + for budget in CpuBudget::ALL { +@@ -272,7 +272,7 @@ + let work = WorkBudget::new_protected(plan).unwrap(); + let report = work.protected_report().unwrap(); + assert_eq!(report.ordinary_limit, budget.limits().max_work_units); +- assert_eq!(report.presentation_limit, 64 * 12_648_450); ++ assert_eq!(report.presentation_limit, 958_464_130); + assert_eq!(report.aggregate_limit, report.ordinary_limit + report.presentation_limit); + assert_eq!(work.remaining(), report.ordinary_limit); + assert_eq!(work.ordinary_remaining(), report.ordinary_limit); +@@ -281,7 +281,7 @@ + assert_eq!((report.ordinary_used, report.presentation_used, work.used()), (0, 0, 0)); + } + let max = ProtectedPreviewPlan::new(1024, 1024, 2, CpuBudget::Workstation).unwrap(); +- assert_eq!(max.aggregate_limit().unwrap(), MAX_PROTECTED_CPU_WORK); ++ assert_eq!(max.aggregate_limit().unwrap(), MAX_CPU_WORK + 958_464_130); + assert!(WorkBudget::new(100).unwrap().protected_report().is_none()); + assert!(ProtectedPreviewPlan::new(u32::MAX, u32::MAX, u32::MAX, CpuBudget::Workstation).is_err()); + } +@@ -321,7 +321,7 @@ + assert_eq!(work.protected_report().unwrap(), initial); + assert!(work.charge_presentation(19, &CancelToken::default()).unwrap()); + let coalesced = work.protected_report().unwrap(); +- assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 19, 19)); ++ assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 7, 7)); + assert_eq!(coalesced.presentation_used, plan.snapshot_work().unwrap()); + assert!(coalesced.presentation_used < coalesced.presentation_limit); + assert!(coalesced.milestones_complete); +@@ -361,11 +361,11 @@ + let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap(); + let cancel = CancelToken::default(); + let mut work = WorkBudget::new_protected_for_test(plan, 17).unwrap(); +- for index in 0..64 { ++ for index in 0..127 { + assert!(work.charge_presentation(plan.milestone(index).unwrap(), &cancel).unwrap()); + } + let exhausted = work.protected_report().unwrap(); +- assert_eq!((exhausted.accepted_snapshots, exhausted.next_milestone_index), (64, 64)); ++ assert_eq!((exhausted.accepted_snapshots, exhausted.next_milestone_index), (127, 127)); + assert_eq!(exhausted.presentation_used, exhausted.presentation_limit); + assert!(exhausted.quota_exhausted && exhausted.milestones_complete); + assert_eq!(work.ordinary_remaining(), 17); +@@ -414,3 +414,42 @@ + assert_eq!(second.protected_report().unwrap().presentation_used, 0); + assert_eq!(first.protected_report().unwrap(), paid); + } ++ ++#[test] ++fn protected_reached_milestones_match_literal_small_and_first_pass_boundaries() { ++ use crate::job::{CpuBudget, ProtectedPreviewPlan}; ++ for (pixels, samples, cases) in [ ++ (1, 1, vec![(0, 0), (1, 0)]), ++ (1, 7, vec![(0, 0), (1, 1), (5, 5), (6, 6), (7, 6)]), ++ (2, 4, vec![(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 3), (6, 4), (7, 4), (8, 4)]), ++ (3, 4, vec![(0, 0), (1, 1), (2, 2), (3, 3), (4, 3), (5, 3), (6, 4), (8, 4), (9, 5), (11, 5), (12, 5)]), ++ (65, 3, vec![(0, 0), (63, 63), (64, 64), (65, 65), (129, 65), (130, 66), (194, 66), (195, 66)]), ++ (66, 3, vec![(0, 0), (64, 63), (65, 64), (66, 65), (131, 65), (132, 66), (197, 66), (198, 66)]), ++ (67, 3, vec![(0, 0), (65, 63), (66, 64), (67, 65), (133, 65), (134, 66), (200, 66), (201, 66)]), ++ ] { ++ let plan = ProtectedPreviewPlan::new(pixels, 1, samples, CpuBudget::Compact).unwrap(); ++ for (committed, expected) in cases { ++ assert_eq!(plan.reached_milestones(committed).unwrap(), expected, "P={pixels} S={samples} c={committed}"); ++ } ++ assert!(plan.reached_milestones(plan.total_commits() + 1).is_err()); ++ assert!(plan.reached_milestones(u64::MAX).is_err()); ++ } ++} ++ ++#[test] ++fn protected_large_delayed_frontier_coalesces_once_without_allocating_a_film_or_spending_ordinary_work() { ++ use crate::job::{CpuBudget, ProtectedPreviewPlan}; ++ let plan = ProtectedPreviewPlan::new(1, 1, 1_048_576, CpuBudget::Workstation).unwrap(); ++ assert_eq!(plan.quota_limit(), 1_048_575); ++ assert_eq!(plan.reached_milestones(65_536).unwrap(), 65_536); ++ assert_eq!(plan.reached_milestones(1_048_575).unwrap(), 1_048_575); ++ assert_eq!(plan.reached_milestones(1_048_576).unwrap(), 1_048_575); ++ let mut work = WorkBudget::new_protected_for_test(plan, 17).unwrap(); ++ assert!(work.charge_presentation(1_048_575, &CancelToken::default()).unwrap()); ++ let report = work.protected_report().unwrap(); ++ assert_eq!((report.accepted_snapshots, report.next_milestone_index), (1, 1_048_575)); ++ assert_eq!(report.presentation_used, 65_552); ++ assert_eq!(report.ordinary_used, 0); ++ assert_eq!(work.ordinary_remaining(), 17); ++ assert!(report.milestones_complete && !report.quota_exhausted); ++} +--- a/crates/ui-egui/src/render_workspace.rs ++++ b/crates/ui-egui/src/render_workspace.rs +@@ -1424,11 +1424,20 @@ + return; + } + let result = (|| -> Result { +- if info.frame_sequence == 0 || !(1..=4096).contains(&info.samples_per_pixel) { ++ if info.frame_sequence == 0 || !(1..=solidcraft_engine::render::job::MAX_CPU_SAMPLES_PER_PIXEL).contains(&info.samples_per_pixel) { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + let handle = app.session.render_job_handle(info.frame.job).map_err(|e| e.to_string())?; + let captured = handle.status().map_err(|e| e.to_string())?; ++ if captured ++ .request ++ .raytrace ++ .as_ref() ++ .and_then(|options| options.progressive) ++ .is_some_and(|target| info.samples_per_pixel > target.samples_per_pixel) ++ { ++ return Err(crate::i18n::tr("render.error_provisional_identity").into()); ++ } + if (info.frame.width, info.frame.height) != (captured.request.width, captured.request.height) { + return Err(crate::i18n::tr("render.error_checkpoint_dimensions").into()); + } +@@ -1447,6 +1456,30 @@ + app.render_workspace.preview_image = Some(PreviewImage { info: info.clone(), image: result }); + } + ++// Consumer-only reconciliation of a temporarily absent latest publication. ++// Status must come from the actual handle; retained pixels never imply new work. ++fn reconcile_missing_cpu_preview(state: &mut State, job: JobId, status: Option<&solidcraft_engine::render::job::JobStatus>) { ++ let retain = state.preview_image.as_ref().is_some_and(|cached| { ++ cached.image.is_ok() ++ && status.is_some_and(|current| { ++ current.job == job ++ && cached.info.frame.job == current.job ++ && cached.info.frame.scene_generation == current.scene_generation ++ && (cached.info.frame.width, cached.info.frame.height) == (current.request.width, current.request.height) ++ && current.request.integrator == Integrator::Raytrace ++ && current.request.raytrace.as_ref().is_some_and(|options| options.progressive.is_some()) ++ && current.cpu_preview_retention_skips > 0 ++ && !current.progress.phase.terminal() ++ && current.progress.phase != solidcraft_engine::render::job::Phase::Cancelling ++ && current.error.is_none() ++ && current.frame.is_none() ++ }) ++ }); ++ if !retain { ++ state.preview_image = None; ++ } ++} ++ + fn cache_preview_image(app: &mut SolveApp, ctx: &egui::Context) { + if let Some(job) = app.render_workspace.view.job + && let Ok(handle) = app.session.render_job_handle(job) +@@ -1477,7 +1510,10 @@ + if let Some(preview) = preview { + cache_preview_frame(app, ctx, &preview.info, preview.png()); + } else { +- app.render_workspace.preview_image = None; ++ // Re-read after observing None: the producer may have certified ++ // a retention skip after the earlier status snapshot. ++ let current = handle.status().ok(); ++ reconcile_missing_cpu_preview(&mut app.render_workspace, job, current.as_ref()); + } + if let Some(partial) = partial + && let Err(error) = cache_final_partial(app, ctx, &handle, &status, &partial) +@@ -1745,10 +1781,28 @@ + preview.frame_sequence + ), + ); ++ if let Ok(handle) = app.session.render_job_handle(preview.frame.job) ++ && let Ok(status) = handle.status() ++ && let Some(target) = status.request.raytrace.as_ref().and_then(|options| options.progressive) ++ { ++ ui.small(crate::i18n::format( ++ "render.cpu_pass_progress", ++ &[("current", &preview.samples_per_pixel.to_string()), ("target", &target.samples_per_pixel.to_string())], ++ )); ++ } + ui.small(app.tr("render.result_provisional_help")); + } + if let Some((info, sampling)) = &partial { + ui.colored_label(t.warning, app.tr("render.result_provisional")); ++ if let Ok(handle) = app.session.render_job_handle(info.frame.job) ++ && let Ok(status) = handle.status() ++ && let Some(target) = status.request.raytrace.as_ref().and_then(|options| options.progressive) ++ { ++ ui.small(crate::i18n::format( ++ "render.cpu_pass_progress", ++ &[("current", &info.completed_passes.to_string()), ("target", &target.samples_per_pixel.to_string())], ++ )); ++ } + let (min, max) = sampling.sample_range(); + ui.small(crate::i18n::format( + "render.interactive_partial_samples", +--- a/crates/ui-egui/src/render_workspace_cpu.rs ++++ b/crates/ui-egui/src/render_workspace_cpu.rs +@@ -138,8 +138,9 @@ + ui_kit::text(ui, app.tr("render.children.progressive_reason"), ui_kit::Text::Note("render.children.progressive_reason")); + } + ui.add_enabled_ui(enabled, |ui| { +- let response = +- ui_kit::row(ui, app.tr("render.cpu_progressive_spp"), |ui| ui_kit::number_field(ui, &mut options.samples_per_pixel, 1..=4096, 1.0, "")); ++ let response = ui_kit::row(ui, app.tr("render.cpu_progressive_spp"), |ui| { ++ ui_kit::number_field(ui, &mut options.samples_per_pixel, 1..=solidcraft_engine::render::job::MAX_CPU_SAMPLES_PER_PIXEL, 1.0, "") ++ }); + app.render_workspace.view.dirty |= response.changed(); + crate::scenario::publish_target("render:cpu-spp", response.rect); + let response = +--- a/crates/ui-egui/src/render_workspace_interactive.rs ++++ b/crates/ui-egui/src/render_workspace_interactive.rs +@@ -62,8 +62,8 @@ + + /// Alpha denotes knowledge only in this additive provisional PNG contract. + /// Physical primary coverage has already been composited by the renderer. +-pub(super) fn validate_partial_pixel(count: u32, covered: u16, pixel: egui::Color32, background: [u8; 3]) -> Result<(), String> { +- if u32::from(covered) > count ++pub(super) fn validate_partial_pixel(count: u32, covered: u32, pixel: egui::Color32, background: [u8; 3]) -> Result<(), String> { ++ if covered > count + || (count == 0 && pixel.a() != 0) + || (count > 0 && pixel.a() != 255) + || (count > 0 && covered == 0 && pixel != egui::Color32::from_rgb(background[0], background[1], background[2])) +@@ -174,7 +174,7 @@ + pub(super) fn validate_partial_pixels( + sampling: PartialSampling, + target: u32, +- covered: &[u16], ++ covered: &[u32], + image: &egui::ColorImage, + background: [u8; 3], + ) -> Result<(), String> { +@@ -204,7 +204,7 @@ + request: &solidcraft_engine::render::job::ImageRequest, + info: &solidcraft_engine::render::job::PartialPreviewInfo, + png: &[u8], +- covered: &[u16], ++ covered: &[u32], + sampling: PartialSampling, + max_texture_side: usize, + ) -> Result { +@@ -321,6 +321,7 @@ + revision: VisualRevision, + info: FrameInfo, + samples: u32, ++ target_samples: u32, + partial: Option, + final_dimensions: [u32; 2], + // Accepted job camera, never the latest observed intent after Pause. +@@ -655,6 +656,7 @@ + revision: ticket.revision(), + info: info.clone(), + samples: 0, ++ target_samples: request.raytrace.as_ref().and_then(|options| options.progressive).ok_or_else(invalid)?.samples_per_pixel, + partial: Some(sampling), + final_dimensions, + camera: request.camera, +@@ -677,12 +679,18 @@ + payload: (&[u8], &solidcraft_engine::render::job::ImageRequest), + ) -> Result<(), String> { + let (png, request) = payload; ++ let progressive = request ++ .raytrace ++ .as_ref() ++ .and_then(|options| options.progressive) ++ .ok_or_else(|| crate::i18n::tr("render.error_provisional_identity").to_string())?; ++ progressive.validate_image_with_budget(request.width, request.height, request.cpu_budget()).map_err(|error| error.to_string())?; + if self.frame.as_ref().is_some_and(|frame| frame.partial.is_none() && frame.key == key && frame.revision == revision) { + return Ok(()); + } + if info.job != key.job + || info.scene_generation != revision.scene_generation +- || !(1..=16).contains(&samples) ++ || !(1..=progressive.samples_per_pixel).contains(&samples) + || (info.width, info.height) != (request.width, request.height) + || info.width > 1024 + || info.height > 1024 +@@ -703,6 +711,7 @@ + revision, + info: info.clone(), + samples, ++ target_samples: progressive.samples_per_pixel, + partial: None, + final_dimensions: self.issued_dimensions.ok_or_else(|| crate::i18n::tr("render.error_provisional_identity").to_string())?, + camera: request.camera, +@@ -1051,6 +1060,7 @@ + let error = state.error.clone(); + let partial = state.frame.as_ref().and_then(|frame| frame.partial); + let samples = state.frame.as_ref().and_then(|frame| frame.partial.map_or(Some(frame.samples), |sampling| sampling.uniform_samples())); ++ let target_samples = state.frame.as_ref().map(|frame| frame.target_samples); + let dimensions = state.frame.as_ref().map(|frame| (frame.info.width, frame.info.height)); + let stale = state.frame.as_ref().is_some_and(|frame| frame.stale); + let final_active = state.final_active; +@@ -1103,6 +1113,13 @@ + ui_kit::text(ui, app.tr("render.interactive_provisional"), ui_kit::Text::Note("render.interactive_provisional")); + } + if let Some(sampling) = partial { ++ if let Some(target) = target_samples { ++ let label = crate::i18n::format( ++ "render.cpu_pass_progress", ++ &[("current", &sampling.cursor.completed_passes.to_string()), ("target", &target.to_string())], ++ ); ++ ui_kit::text(ui, &label, ui_kit::Text::Inline); ++ } + let (min, max) = sampling.sample_range(); + let pixels = u64::from(sampling.plan.source_width()) * u64::from(sampling.plan.source_height()); + let label = crate::i18n::format( +@@ -1115,8 +1132,8 @@ + ], + ); + ui_kit::text(ui, &label, ui_kit::Text::Inline); +- } else if let Some(samples) = samples { +- let label = crate::i18n::format("render.interactive_samples", &[("done", &samples.to_string()), ("total", "16")]); ++ } else if let (Some(samples), Some(target)) = (samples, target_samples) { ++ let label = crate::i18n::format("render.interactive_samples", &[("done", &samples.to_string()), ("total", &target.to_string())]); + ui_kit::text(ui, &label, ui_kit::Text::Inline); + } + if let Some(sampling) = partial { +@@ -1190,8 +1207,17 @@ + } + pub(super) fn inspect(app: &SolveApp) -> Value { + let state = &app.render_workspace.interactive; ++ // A diagnostic of the actual admitted capture, never a synthetic zero from ++ // a missing context, pending ticket or failed status read. ++ let retention_skips = state ++ .context ++ .as_ref() ++ .and_then(|context| context.current().ok().flatten()) ++ .and_then(|job| job.status().ok()) ++ .map(|status| status.cpu_preview_retention_skips); + json!({"enabled":state.context.is_some(),"phase":format!("{:?}",state.phase),"visual_revision":state.visual, + "pending_capture":state.pending.is_some(),"paused":state.user_paused,"error":state.error, ++ "cpu_preview_retention_skips":retention_skips, + "samples":state.frame.as_ref().and_then(|frame|frame.partial.map_or(Some(frame.samples), |sampling|sampling.uniform_samples())), + "partial":state.frame.as_ref().and_then(|frame|frame.partial).map(|sampling|json!({ + "sequence":sampling.cursor.sequence,"completed_passes":sampling.cursor.completed_passes,"updated_prefix":sampling.cursor.updated_prefix, +--- a/crates/ui-egui/src/render_workspace_tests.rs ++++ b/crates/ui-egui/src/render_workspace_tests.rs +@@ -11304,3 +11304,287 @@ + } + } + } ++ ++#[test] ++fn cpu_partial_coverage_crosses_u16_boundary_without_relaxing_alpha_or_sample_frontier() { ++ for count in [65_535, 65_536, 1_048_576] { ++ assert!(interactive::validate_partial_pixel(count, count, Color32::BLACK, [40, 80, 120]).is_ok()); ++ assert!(interactive::validate_partial_pixel(count, count + 1, Color32::BLACK, [40, 80, 120]).is_err()); ++ assert!(interactive::validate_partial_pixel(count, count, Color32::TRANSPARENT, [40, 80, 120]).is_err()); ++ assert_eq!(interactive::partial_sample_count(count, 0, 0, 1, 1_048_576).unwrap(), count); ++ } ++ assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, [40, 80, 120]).is_err()); ++ assert!(interactive::validate_partial_pixel(65_536, 0, Color32::BLACK, [40, 80, 120]).is_err()); ++ assert!(interactive::validate_partial_pixel(65_536, 0, Color32::from_rgb(40, 80, 120), [40, 80, 120]).is_ok()); ++ assert!(interactive::partial_sample_count(65_536, 1, 0, 1, 65_536).is_err()); ++} ++ ++#[test] ++fn cpu_progressive_editor_preserves_high_intent_without_resizing_or_changing_profile_seed_or_mode() { ++ use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; ++ let mut h = Harness::new(); ++ h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; ++ h.app.render_workspace.view.draft.width = 1; ++ h.app.render_workspace.view.draft.height = 1; ++ h.app.render_workspace.view.raytrace.budget = CpuBudget::Workstation; ++ h.app.render_workspace.view.raytrace.primary_samples = 1; ++ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: u32::MAX }); ++ let doc = h.app.session.doc.clone(); ++ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); ++ for budget in [CpuBudget::Workstation, CpuBudget::Compact, CpuBudget::Studio] { ++ h.app.render_workspace.view.raytrace.budget = budget; ++ let before = json!(h.app.render_workspace.view.raytrace); ++ let ctx = egui::Context::default(); ++ let _ = ctx.run_ui(egui::RawInput::default(), |ui| { ++ assert!(cpu::progressive_controls(&mut h.app, ui)); ++ }); ++ assert_eq!(json!(h.app.render_workspace.view.raytrace), before, "painting cannot clamp retained intent to a different profile"); ++ assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1, 1)); ++ assert_eq!(cpu::validate_progressive_image(&h.app).is_ok(), budget == CpuBudget::Workstation); ++ } ++ assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); ++ assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); ++} ++ ++// Request/consumer coverage only. Real native per-pass presentation remains ++// mandatory acceptance; see the archived unsupported cooperative-host fixture. ++#[test] ++fn cpu_progressive_request_keeps_explicit_target_seed_without_claiming_native_pass_presentation() { ++ use solidcraft_engine::render::job::CpuProgressiveOptions; ++ let mut h = Harness::new(); ++ h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; ++ h.app.render_workspace.view.draft.width = 1; ++ h.app.render_workspace.view.draft.height = 1; ++ h.app.render_workspace.view.raytrace.primary_samples = 1; ++ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 4, seed: 741 }); ++ let document = h.app.session.doc.clone(); ++ let before = json!(h.app.render_workspace.view.raytrace); ++ let request = interactive_request(&h.app).unwrap(); ++ assert_eq!(request["raytrace"]["progressive"]["samples_per_pixel"], 4); ++ assert_eq!(request["raytrace"]["progressive"]["seed"], 741); ++ assert_ne!(request["progressive"], json!(true), "CPU intent cannot select a registered GPU executor"); ++ assert_eq!(json!(h.app.render_workspace.view.raytrace), before); ++ assert!(Arc::ptr_eq(&document, &h.app.session.doc)); ++ assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); ++} ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation() { ++ use solidcraft_engine::render::job::{CpuProgressiveOptions, Phase}; ++ use std::{sync::mpsc, time::Duration}; ++ let mut h = interactive_ui_fixture(); ++ if !interactive_test_cpu_branch(&mut h, "interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation") { ++ return; ++ } ++ h.app.render_workspace.view.raytrace.primary_samples = 1; ++ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); ++ let before = json!(h.app.render_workspace.view.raytrace); ++ let epoch = interactive::test_clock(&h.app).as_secs_f64(); ++ h.app.run("render.interactive", json!({"action":"on"})).unwrap(); ++ interactive_clear_acceptance_frame(&mut h, epoch, true); ++ interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); ++ // Withhold only the real worker reply. All frame bytes come from the renderer. ++ let mut pending = h.app.render_workspace.interactive.pending.take().unwrap(); ++ let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).unwrap(); ++ assert!(matches!(&reply, Ok(true)), "{reply:?}"); ++ let job = interactive::test_current(&h.app).unwrap().unwrap(); ++ let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); ++ assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); ++ assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 })); ++ let frame = job.frame().unwrap().unwrap(); ++ assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); ++ assert!(!frame.png().is_empty()); ++ let (sender, receiver) = mpsc::channel(); ++ pending.receiver = receiver; ++ h.app.render_workspace.interactive.pending = Some(pending); ++ sender.send(reply).unwrap(); ++ let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); ++ assert!(painted); ++ let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); ++ assert_eq!((cached.job, samples, complete), (job.id(), 31, true)); ++ assert_eq!(cached.png_sha256, frame.info.png_sha256); ++ let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); ++ let egui::ImageData::Color(pixels) = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; ++ assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); ++ assert!( ++ pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) ++ ); ++ output.textures_delta.clear(); ++ assert_eq!(json!(h.app.render_workspace.view.raytrace), before); ++ h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); ++ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 47, seed: 999 }); ++ let expected = crate::i18n::format("render.interactive_samples", &[("done", "31"), ("total", "31")]); ++ let controls = h.ctx.run_ui(egui::RawInput::default(), |ui| interactive::controls(&mut h.app, ui)); ++ assert!(crate::test_support::text_shapes(&controls).any(|shape| shape.galley.text() == expected)); ++ assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); ++ interactive_assert_final_export_isolation(&mut h, &job); ++ h.app.run("render.interactive", json!({"action":"off"})).unwrap(); ++} ++ ++#[test] ++fn interactive_retention_skip_inspect_is_null_without_an_admitted_capture() { ++ let h = Harness::new(); ++ assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); ++} ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off() { ++ let mut h = interactive_ui_fixture(); ++ assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); ++ if !interactive_test_cpu_branch(&mut h, "interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off") { ++ assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); ++ return; ++ } ++ let epoch = interactive::test_clock(&h.app).as_secs_f64(); ++ h.app.run("render.interactive", json!({"action":"on"})).unwrap(); ++ assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null(), "enabling without an admitted job cannot fabricate zero"); ++ interactive_clear_acceptance_frame(&mut h, epoch, true); ++ interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); ++ let held = interactive_hold_real_completed_callback(&mut h); ++ let captured = held.job.status().unwrap(); ++ assert_eq!(captured.cpu_preview_retention_skips, 0); ++ assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(captured.cpu_preview_retention_skips)); ++ interactive_assert_final_export_isolation(&mut h, &held.job); ++ held.sender.send(held.reply).unwrap(); ++ let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); ++ assert!(painted); ++ output.textures_delta.clear(); ++ assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(0)); ++ h.app.run("render.interactive", json!({"action":"off"})).unwrap(); ++ assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); ++} ++ ++// Typed consumer state only: this texture is input to the absent-slot policy. ++// It is not a renderer PNG, a CPU admission fixture, or per-pass UI acceptance. ++fn cpu_preview_consumer_fixture(ctx: &egui::Context) -> (State, JobId, solidcraft_engine::render::job::JobStatus) { ++ use solidcraft_engine::render::job::{ ++ AlphaConvention, ColourEncoding, CpuProgressiveOptions, FrameInfo, ImageRequest, JobOptions, JobStatus, Phase, Progress, RaytraceOptions, ++ }; ++ use solidcraft_engine::render::{BackendId, ExecutorId, RenderMode, RenderOperation, RenderProfile, ResolvedRequest}; ++ let job = JobId { session: 9012, serial: 1, generation: 1 }; ++ let backend = BackendId::new("consumer-fixture").unwrap(); ++ let executor = ExecutorId::new("consumer-fixture").unwrap(); ++ let frame = FrameInfo { ++ job, ++ scene_generation: 19, ++ backend: backend.clone(), ++ executor: executor.clone(), ++ width: 1, ++ height: 1, ++ encoding: ColourEncoding::Srgb, ++ alpha: AlphaConvention::Straight, ++ png_bytes: 0, ++ png_sha256: String::new(), ++ }; ++ let texture = ++ ctx.load_texture("consumer-only-input", egui::ColorImage::new([1, 1], vec![Color32::from_rgb(40, 80, 120)]), egui::TextureOptions::LINEAR); ++ let mut state = State::default(); ++ state.view.job = Some(job); ++ state.preview_image = Some(PreviewImage { info: PreviewInfo { frame_sequence: 2, samples_per_pixel: 2, frame }, image: Ok(texture) }); ++ let request = ImageRequest { ++ raster_exposure_ev: 0.0, ++ raster_lights: None, ++ raster_punctual_lights: None, ++ raster_area_lights: None, ++ studio_weights: None, ++ environment: None, ++ textures: None, ++ integrator: Integrator::Raytrace, ++ raytrace: Some(RaytraceOptions { ++ primary_samples: 1, ++ progressive: Some(CpuProgressiveOptions { samples_per_pixel: 7, seed: 741 }), ++ ..Default::default() ++ }), ++ camera: Default::default(), ++ width: 1, ++ height: 1, ++ background: [40, 80, 120], ++ transparent_background: false, ++ }; ++ let status = JobStatus { ++ cpu_preview_retention_skips: 1, ++ punctual_diagnostics: None, ++ presentation: None, ++ sampling: None, ++ linear_master: None, ++ preview: None, ++ textures: None, ++ options: JobOptions::default(), ++ environment: None, ++ job, ++ scene_generation: 19, ++ request, ++ resolved: ResolvedRequest { ++ backend, ++ executor, ++ profile: RenderProfile { mode: RenderMode::Preview, operation: RenderOperation::Image, formats: Vec::new(), features: Vec::new() }, ++ width: 1, ++ height: 1, ++ format: None, ++ estimated_scratch_bytes: 0, ++ warnings: Vec::new(), ++ }, ++ progress: Progress { phase: Phase::Running, done: 3, total: 7 }, ++ error: None, ++ frame: None, ++ }; ++ (state, job, status) ++} ++ ++#[test] ++fn cpu_missing_snapshot_consumer_keeps_exact_pixels_identity_and_pass_only_for_certified_live_capture() { ++ let ctx = egui::Context::default(); ++ let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); ++ let before = state.preview_image.as_ref().unwrap(); ++ let texture = before.image.as_ref().unwrap().id(); ++ let identity = (before.info.frame.job, before.info.frame.scene_generation, before.info.frame_sequence, before.info.samples_per_pixel); ++ status.progress.done = 4; ++ reconcile_missing_cpu_preview(&mut state, job, Some(&status)); ++ let kept = state.preview_image.as_ref().unwrap(); ++ assert_eq!(kept.image.as_ref().unwrap().id(), texture); ++ assert_eq!((kept.info.frame.job, kept.info.frame.scene_generation, kept.info.frame_sequence, kept.info.samples_per_pixel), identity); ++ assert_eq!(kept.info.samples_per_pixel, 2, "producer progress cannot relabel accepted pixels"); ++ assert!(state.view.completed.is_none(), "retention cannot manufacture final authority"); ++} ++ ++#[test] ++fn cpu_missing_snapshot_consumer_clears_wrong_capture_cancel_error_final_and_lookup_failure() { ++ use solidcraft_engine::render::job::{ErrorCode, JobError, Phase}; ++ let ctx = egui::Context::default(); ++ for case in 0..13 { ++ let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); ++ let mut lookup_ok = true; ++ match case { ++ 0 => status.job.serial += 1, ++ 1 => status.scene_generation += 1, ++ 2 => status.request.width += 1, ++ 3 => status.progress.phase = Phase::Cancelling, ++ 4 => status.progress.phase = Phase::Cancelled, ++ 5 => status.progress.phase = Phase::Failed, ++ 6 => status.progress.phase = Phase::Completed, ++ 7 => status.error = Some(JobError::new(ErrorCode::Internal, "consumer fixture status error")), ++ 8 => status.frame = Some(state.preview_image.as_ref().unwrap().info.frame.clone()), ++ 9 => status.cpu_preview_retention_skips = 0, ++ 10 => status.request.raytrace.as_mut().unwrap().progressive = None, ++ 11 => state.preview_image.as_mut().unwrap().image = Err("consumer fixture decode error".into()), ++ 12 => lookup_ok = false, ++ _ => unreachable!(), ++ } ++ reconcile_missing_cpu_preview(&mut state, job, lookup_ok.then_some(&status)); ++ assert!(state.preview_image.is_none(), "case {case}"); ++ assert!(state.view.completed.is_none()); ++ } ++ let mut h = Harness::new(); ++ let (mut state, job, _) = cpu_preview_consumer_fixture(&ctx); ++ state.view.job = None; ++ h.app.render_workspace = state; ++ cache_preview_image(&mut h.app, &ctx); ++ assert!(h.app.render_workspace.preview_image.is_none()); ++ let (state, _, _) = cpu_preview_consumer_fixture(&ctx); ++ h.app.render_workspace = state; ++ assert!(h.app.session.render_job_handle(job).is_err(), "consumer fixture is deliberately not an admitted job"); ++ cache_preview_image(&mut h.app, &ctx); ++ assert!(h.app.render_workspace.preview_image.is_none()); ++} +--- a/docs/render-cpu-progressive.md ++++ b/docs/render-cpu-progressive.md +@@ -2,11 +2,21 @@ + + The limits below describe the compatibility **Compact** profile. Explicit Studio and Workstation envelopes are documented in [CPU resource profiles](render-cpu-resource-profiles.md); their implementation batch still requires consolidated validation. + ++The every-pass cadence and bounded snapshot policy below describe a composed ++source proposal awaiting integration and validation, not a new native display or ++CI result. The earlier published policy used powers-of-two checkpoints. This is ++an intentional requested behavior change; its default-change classification and ++preference handling remain unresolved before production readiness. This document ++does not settle that process question. ++ + CPU progressive rendering repeatedly traces fresh camera samples into a bounded +-linear-light film. Checkpoints are complete image passes, at 1, 2, 4, 8, 16 and +-32 samples per pixel when below the requested final sample count. The exact +-requested count produces the final PNG, including non-powers of two such as 3 +-or 5. A one-sample job has no provisional checkpoint. ++linear-light film. Each complete nonfinal pass, 1 through the requested count ++minus one, is a checkpoint boundary. Normal consumption publishes each boundary; ++the diagnosed external-retention exception is defined below. The exact requested ++count produces one final PNG, including non-powers of two such as 3 or 5. A ++one-sample job has no nonfinal complete-pass checkpoint. Optional first-pass ++partial-coverage feedback is separate from a uniform checkpoint. Publication ++does not guarantee that a slower client physically repaints every image. + + This mode uses the native `cpu-raytrace` executor and its existing direct-light + and selected-reflection transport. It does not add diffuse global illumination, +@@ -97,10 +107,13 @@ + At 1024 × 1024 the camera-sample cap allows at most 16 samples per pixel; at + 512 × 512 it allows 64. Requests are also subject to the selected CPU resource profile's geometry, + job-memory and shared-host pool limits; see [CPU resource profiles](render-cpu-resource-profiles.md). Traversal, +-shading, film updates, resolve, PNG encoding and hashing share one cumulative +-1,000,000,000-unit work ceiling. The count is not reset at a pass boundary. +-The camera-sample limit is a cold upper bound, not a promise that every scene +-will finish below the cumulative runtime work ceiling. ++shading, film updates and ordinary output work retain the selected profile's ++cumulative work ceiling: Compact 1,000,000,000, Studio 1,000,000,000,000 and ++Workstation 16,000,000,000,000. The count is not reset at a pass boundary. ++Presentation has a separate finite precharge for the bounded early feedback and ++nonfinal complete-pass opportunities; increasing the target is not an unbounded ++codec/work grant. The camera-sample limit is a cold upper bound, not a promise ++that every scene will finish below cumulative work or host-memory limits. + + ## Sampling, linear film and display + +@@ -141,9 +154,23 @@ + `JobHandle::preview()` returns an `Arc` whose `png()` is the + immutable encoded snapshot. The first checkpoint has sequence 1. The job's + `JobId { session, serial, generation }` and captured `scene_generation` remain +-unchanged across every pass. `frame_sequence` is a separate monotonic counter. +-Clients cache previews by `(JobId, frame_sequence)` and may retain an older +-snapshot without mutating it. ++unchanged across every pass. `frame_sequence` counts actual publications, not ++samples or skipped boundaries. Clients cache previews by `(JobId, frame_sequence)` ++and may retain an older snapshot without mutating it. For example, publications ++SPP1/sequence1 and SPP2/sequence2 can be followed by a diagnosed retained-slot ++skip at SPP3, then SPP4/sequence3 when a slot returns. The producer still processes ++each real pass in order; this exception does not license a fabricated producer ++jump from pass1 to pass3. ++ ++The runtime `JobStatus.cpu_preview_retention_skips: u32` counts nonfinal uniform ++boundaries whose snapshot could not be published because both reusable slots ++were externally retained. Retire an obsolete host-owned snapshot and retry the ++credit before diagnosing that condition. Count that boundary once, not each ++poll or a later retry of the same boundary. Closed pools, in-flight buffers, ++unrequested feedback or an exhausted optional feedback quota are not themselves ++evidence of external retention. Cancellation is checked before the diagnostic ++update. This counter is runtime metadata, never saved ++intent, and does not count frames physically displayed by a client. + + The preview slot is separate from `JobStatus.frame`/`JobHandle::frame()`. A + preview cannot be exported through `render.export`, cannot become the session's +@@ -162,18 +189,27 @@ + ## Allocation and retained snapshots + + Admission reserves the working film, existing RGBA/encoder/final-PNG capacity, +-and the maximum encoded capacity plus metadata for every possible nonfinal +-checkpoint. This conservative upper bound covers a consumer retaining all +-checkpoints at once. Actual film and PNG capacities are checked against their +-admitted capacities after fallible allocation. +- +-A completed checkpoint moves its PNG allocation into the preview object. +-`Reservation::split` transfers that allocation's share of the running lease +-without increasing or decreasing the pool total. Replacing or clearing the host +-preview drops only the host's `Arc`; any external `Arc` keeps its memory billed. +-At final completion the task releases its working buffers before the remaining +-lease shrinks to the final PNG. Dropping each last external snapshot releases +-only that snapshot's reservation. There is no full-film clone per checkpoint. ++and at most two reusable immutable checkpoint slots with their metadata. It no ++longer reserves a separate PNG for every possible pass. Protected feedback uses ++its existing two partial-snapshot slots. Actual film, sidecar and PNG capacities ++remain checked against admitted capacities after fallible allocation; there is ++no full-film clone or growing production list of checkpoint PNGs. ++ ++A published snapshot retains a lease for its admitted slot. Replacing or clearing ++the host's `Arc` cannot mutate externally held bytes or release their charge. ++When the last consumer releases a snapshot, its credit can be reused while the ++job is active. Terminal cleanup closes free credits; externally retained leases ++stay billed until their last release. Existing working codec and final-image ++buffers remain accounted separately. ++ ++If both slots are externally pinned, the diagnosed boundary produces no new ++snapshot. The renderer continues sampling and final work without waiting for an ++acknowledgement, failing the final merely because of retention, allocating an ++extra slot or inventing a frame. Returning a credit permits a later real pass to ++publish again. Final-only export, cancellation and captured identity are unchanged. ++Even without pinned consumers, a latest-image client can coalesce observations ++when it repaints more slowly than the worker; no latency or unconditional ++physical-display guarantee follows from every-pass publication. + + ## Regression coverage + +--- a/docs/render-cpu-resource-profiles.md ++++ b/docs/render-cpu-resource-profiles.md +@@ -1,6 +1,6 @@ + # Explicit CPU resource profiles + +-**Implementation batch: source prepared; consolidated compilation and large-scene runtime acceptance are pending.** These envelopes are admission limits, not measured performance or a final-quality certification. ++**Composed-source proposal: integration, consolidated validation and large-scene native acceptance are pending.** The raised Workstation target requires the coordinated CPU accumulation, publication and UI adapters. These envelopes are admission limits, not measured performance or a final-quality certification. + + ## Intent + +@@ -13,7 +13,7 @@ + | Maximum side | 4,096 px | 8,192 px | 16,384 px | + | Fixed-sampling pixels | 4,194,304 | 16,777,216 | 67,108,864 | + | Progressive pixels | 1,048,576 | 16,777,216 | 67,108,864 | +-| Progressive samples/pixel | 64 | 1,024 | 4,096 | ++| Progressive samples/pixel | 64 | 1,024 | 1,048,576 | + | Total camera samples | 16,777,216 | 4,294,967,296 | 68,719,476,736 | + | Captured triangles | 262,144 | 2,000,000 | 8,000,000 | + | Visible bodies | 16,384 | 65,536 | 262,144 | +@@ -21,7 +21,7 @@ + | Complete job admission | 384 MiB | 3 GiB | 12 GiB | + | Cumulative work units | 1,000,000,000 | 1,000,000,000,000 | 16,000,000,000,000 | + +-Every column is an intersection of limits: a scene that fits the triangle count may still exceed its complete byte estimate. Similarly, a sample count within the per-pixel limit may exceed the total camera-sample or cumulative traversal-work limit. No claim is made that all maxima can be reached simultaneously or within a particular time. ++Every column is an intersection of limits: a scene that fits the triangle count may still exceed its complete byte estimate. Similarly, a sample count within the per-pixel limit may exceed the total camera-sample or cumulative traversal-work limit. At 1,048,576 SPP, 256 × 256 already reaches Workstation's unchanged 68,719,476,736 camera-sample ceiling; the high target is not permission to use every resolution. Compact 64 and Studio 1024 remain unchanged. No claim is made that all maxima can be reached simultaneously or within a particular time. + + Examples of cardinality admission, before geometry and memory are considered: Studio permits 3840 × 2160 at 128 samples/pixel; Workstation permits 7680 × 4320 at 128 samples/pixel. Compact rejects both instead of silently resizing them. + +@@ -55,7 +55,9 @@ + + The native CPU host has a finite 16 GiB logical reservation pool on 64-bit platforms, including retained results and previews. It does not allocate that amount at startup, promise that physical RAM is available, or account for the rest of the CAD application or other processes. Per-job profiles remain smaller. Cooperative and registered GPU host pools retain their original 512 MiB limit; this change is not a GPU-memory expansion. + +-Fallible allocation, actual vector-capacity checks, checked arithmetic, bounded work quanta, cancellation checks and final-only publication remain required. A failed or cancelled job must release its working reservations and preserve the previous completed result. Every retained progressive checkpoint is still conservatively charged; this increment does not implement tiled/out-of-core rendering or unbounded preview retention. ++Fallible allocation, actual vector-capacity checks, checked arithmetic, bounded work quanta, cancellation checks and final-only publication remain required. A failed or cancelled job must release its working reservations and preserve the previous completed result. Progressive publication prepays two reusable snapshot slots plus existing working codec/final capacity, not one PNG per pass. Externally held snapshots keep their leases charged; if both slots are pinned, a diagnosed boundary can be skipped without blocking or failing final work. See [CPU progressive sampling](render-cpu-progressive.md#allocation-and-retained-snapshots). ++ ++Ordinary cumulative work caps remain exactly 1e9 / 1e12 / 16e12 for Compact / Studio / Workstation. The presentation allowance is separate and finite: with P output pixels and target H, at most min(P−1,64)+(H−1) early/uniform opportunities are precharged, each at 14 × preview_pixels + 65,538 units, with preview_pixels at most 1024². This allowance is not extra ordinary traversal work, an admission promise, or a display-latency guarantee. This increment does not implement tiled/out-of-core rendering or unbounded preview retention. + + ## Compatibility and limits + +--- a/docs/render-cpu-workspace.md ++++ b/docs/render-cpu-workspace.md +@@ -13,9 +13,16 @@ + ## Progressive CPU sampling + + **CPU sampling mode → CPU progressive** accumulates samples of the existing CPU +-integrator. Set **samples per pixel** from 1 to 64 and the separate CPU sampling +-seed. Selecting the mode explicitly chooses one primary sample per pass; returning +-to **Single image** restores the AA selector without discarding lights or HDR controls. ++integrator. In the coordinated source proposal, **samples per pixel** is bounded ++by the selected profile: Compact 64, Studio 1024 or Workstation 1,048,576, together ++with the unchanged pixel/camera-sample and other admission intersections. The ++separate CPU sampling seed and explicit target are preserved on save/reopen; ++Interactive uses those captured values rather than forcing every request to ++16/0. The fallback 16/0 applies only without explicit progressive intent. These ++changes require integration, validation and native acceptance. ++ ++Selecting the mode explicitly chooses one primary sample per pass; returning to ++**Single image** restores the AA selector without discarding lights or HDR controls. + This is camera sampling of the existing integrator, not diffuse global illumination, + adaptive sampling or CPU denoising. + +@@ -25,20 +32,32 @@ + switching modes never silently removes these inputs. Check and Start report an + incompatible combination through the same request validation. + +-Admission allows at most 1,048,576 pixels, dimensions up to 4096, and +-16,777,216 pixel × sample evaluations. For example, 1024 × 1024 supports 16 SPP, +-whereas 64 SPP requires at most 262,144 pixels. Increasing SPP or loading a setup +-never changes its dimensions automatically. If needed, the panel displays a ++The compatibility Compact profile allows at most 1,048,576 progressive pixels, ++dimensions up to 4096, and 16,777,216 pixel × sample evaluations. For example, ++1024 × 1024 supports 16 SPP, whereas 64 SPP requires at most 262,144 pixels. ++Explicit larger profiles retain their own intersecting limits; see ++[CPU resource profiles](render-cpu-resource-profiles.md). Increasing SPP or loading ++a setup never changes its dimensions automatically. If needed, the panel displays a + **Use the largest size at this aspect: W × H** action; only clicking it resizes + the draft. Save applies the same numeric limits without requiring a renderer and + leaves invalid drafts intact. Traversal, sampling and image encoding also share + the backend's cumulative work budget. + +-The result canvas shows provisional PNG checkpoints after 1, 2, 4, … samples, +-before the requested final count. A provisional label includes its SPP and checkpoint +-sequence; the job identity and captured revision remain unchanged. Checkpoint updates +-reuse the current pan/zoom. Completion replaces the preview with its final image; +-cancellation or failure removes the preview and returns to the previous completed ++Normal source publication attempts a provisional snapshot at every complete ++nonfinal pass 1, 2, 3, …, followed by the unique final at the requested target. Two ++reusable snapshot slots bound retention. If both are externally pinned, the ++actual runtime `cpu_preview_retention_skips` counter diagnoses that skipped ++boundary while final work continues; it does not fabricate an image or sample. ++The current-handle inspection diagnostic uses a real count, including zero, or ++null when unavailable/failed; lookup errors are not included, and other reported errors are independent. ++ ++Publication is distinct from physical canvas repaint: a fast worker and slower ++client can coalesce visible images. A provisional label includes actual SPP and ++publication sequence; these need not be equal after a diagnosed skip. Job identity ++and captured revision remain unchanged. Checkpoint updates reuse current pan/zoom. ++Neither a counter nor the source change proves native 1→2→3→4 display or a latency ++bound. Completion replaces the preview with its final image; cancellation or ++failure removes the preview and returns to the previous completed + result with the same framing. **Export final PNG** always exports a completed frame, + even while a different provisional image is visible. With no completed frame, export + remains disabled. The UI keeps one decoded provisional texture and metadata, not +--- a/docs/render-interactive.md ++++ b/docs/render-interactive.md +@@ -46,15 +46,22 @@ + + ## Preview envelope + +-`cpu_request` clones an immutable final request. It preserves the camera, +-background, shadows, exposure, lighting, resources and transport. Only preview +-dimensions and camera/reflection sampling change: maximum 1024 pixels along the +-longest edge, rounded to the nearest pixel without enlargement, 16 SPP, seed 0, +-one primary and one selected reflection attempt per camera sample. The original +-final request stays untouched. Integer aspect rounding is at most half a pixel +-(or one pixel for an extreme aspect). Transparent output, another integrator or ++In the coordinated source proposal, `cpu_request` clones an immutable final ++request and preserves its camera, background, shadows, exposure, lighting, ++resources and transport. If that captured request has explicit CPU progressive ++intent, its target and seed are retained; they are not replaced by the current ++live draft or silently reduced to 16/0. Only an absent progressive intent uses ++the existing fallback of 16 SPP and seed 0. One primary and one selected ++reflection attempt are used per camera sample. The original final request stays ++untouched. ++ ++Preview dimensions remain bounded to 1024 pixels along the longest edge, ++rounded to the nearest pixel without enlargement. Integer aspect rounding is at ++most half a pixel (or one pixel for an extreme aspect). Preserving a high target ++does not remove the selected profile's pixel, total camera-sample, geometry, ++traversal or memory intersections. Transparent output, another integrator or + unsupported progressive transport returns an error instead of dropping effects. +-The existing profile and host still enforce geometry, traversal and memory limits. ++These changes still require integrated validation and native observation. + Rectangle/LED direct-light inputs, their emitter-sample count and area-pattern + seed survive preview lowering unchanged. Only camera/reflection sampling uses + the preview envelope; dielectric intent is retained for capture and transport +@@ -63,6 +70,14 @@ + See [CPU progressive sampling](render-cpu-progressive.md) and + [CPU resource profiles](render-cpu-resource-profiles.md) for the separate final + request and admission contracts. ++ ++The coordinated retention diagnostic is read from the actual current job handle. ++A successful status supplies `Some(count)`, including `Some(0)`; an absent handle ++or failed status lookup supplies no count (`null` in the inspection reply), not ++a fabricated zero. Lookup errors are not included; other reported errors are independent. A nonzero count ++reports skipped snapshot boundaries caused by externally retained slots, not ++missing samples or a count of physical canvas repaints; see ++[CPU progressive publication](render-cpu-progressive.md#preview-publication-and-final-export). + + ## Exposure and image ownership + +@@ -87,7 +102,8 @@ + - Allocate a distinct transient job session for each document's Interactive + controller. Never recreate a controller with the same session while callbacks + from its previous instance can arrive. Do not register its jobs in the engine's +- final/export registry. Even its 16-SPP completed image is provisional content. ++ final/export registry. Reaching its captured sample target still produces ++ provisional content, not an exportable final. + - Increment `VisualRevision.visual_revision` whenever camera, draft, material, + visibility, lighting, HDR/resource, method or output intent changes. Include + changes that leave the document revision unchanged. Capture this counter and +--- a/docs/render-jobs.md ++++ b/docs/render-jobs.md +@@ -58,7 +58,26 @@ + but remains separate from the retained final image and `render.export`. + Cancellation, failure and final publication clear the provisional slot while + preserving the previous successful result when no newer final exists. Each +-externally retained preview keeps its own admitted memory reservation. ++externally retained preview keeps the lease for its reusable admitted snapshot ++slot until release; the composed every-pass policy reserves two slots rather ++than one PNG for every pass. Publication may outpace physical client repaint. ++ ++The composed CPU source adds runtime `cpu_preview_retention_skips: u32` to job ++status. It increments once for a real nonfinal uniform boundary that cannot ++publish because both reusable slots remain externally pinned after retiring the ++obsolete host snapshot and retrying its credit. Polling does not increment it; ++closed pools, in-flight buffers, unrequested feedback or an exhausted optional ++feedback quota are not themselves retention skips. ++Sampling and final work continue without observer acknowledgements or an extra ++snapshot allocation. SPP1/sequence1, SPP2/sequence2, skipped SPP3/count1, then ++SPP4/sequence3/count1 is a valid publication history after one slot returns. ++Actual producer passes must still be processed in order. ++ ++Zero is a value from a real status, not a substitute status after lookup failure. ++The separate Interactive inspection diagnostic is nullable when there is no ++current handle or its status lookup fails; lookup errors are not included and other reported errors are independent. Neither ++form is saved in the design or proves that every snapshot was physically shown. ++This is a source proposal pending integrated validation, not a native result. + + ## Native and browser execution + +--- a/docs/render-settings.md ++++ b/docs/render-settings.md +@@ -179,10 +179,18 @@ + + CPU `progressive: {samples_per_pixel, seed}` stores bounded camera accumulation + using the existing CPU transport. An absent/null value preserves fixed AA; an +-empty object defaults to 16 samples and seed 0. Samples are 1..64 and the seed is +-u32. `primary_samples` must be 1, output is at most 1,048,576 pixels, and +-`width × height × samples_per_pixel` is at most 16,777,216. Saving checks these +-limits without a render host. Area/LED direct lights retain the existing four ++empty object defaults to 16 samples and seed 0. The seed is u32 and ++`primary_samples` must be 1. In the coordinated source proposal, per-pixel targets ++are 1..64 for omitted/explicit Compact, 1..1024 for Studio and 1..1,048,576 for ++explicit Workstation. Each remains subject to its profile's unchanged dimensions, ++pixels, total camera-sample and other admission limits; see ++[CPU resource profiles](render-cpu-resource-profiles.md). The compatibility ++Compact limits remain 1,048,576 progressive pixels and 16,777,216 total camera ++samples. Saving validates the selected intersection without a render host; ++reopen preserves the explicit target, seed and budget rather than clamping intent. ++Snapshots, checkpoint leases and the runtime retention-skip counter are not ++saved fields. These source changes await integrated validation/native acceptance. ++Area/LED direct lights retain the existing four + shared rectangle slots, emitter-sample counts and power normalization. Dielectric + and anisotropic-face overrides remain refused; the fixed CPU route retains them. + Embedded HDR and one setup exposure remain compatible. See diff --git a/proposals/render/2026-10-31/cpu-every-pass-c27-source/source-bindings.json b/proposals/render/2026-10-31/cpu-every-pass-c27-source/source-bindings.json new file mode 100644 index 000000000..3b4080e5e --- /dev/null +++ b/proposals/render/2026-10-31/cpu-every-pass-c27-source/source-bindings.json @@ -0,0 +1,229 @@ +{ + "status": "SOURCE_PRESERVATION_C27_POSTFORMAT_BUILD_FAILED_ALL_SELECTED_TESTS_UNRUN", + "base": "Exact per-file before RAW bindings below, not arbitrary main or the earlier nine-file snapshot. Preserve unrelated files.", + "before_source_manifest_sha256": "2f39172dd42414588fb0c88cb23d30c2d5f626592ab3d4632b032701e85edbf1", + "after_source_manifest_sha256": "a7b088eef563cbba4bfc5f2c26cf2d02ac6e855088710a072fdff35f889c1551", + "files": [ + { + "path": "assets/locales/pending/cpu-progressive-passes.json", + "before_sha256": null, + "before_bytes": null, + "after_sha256": "7d11a688edad617ae6da92e8460f8833e121167ddb1b296001807f585e7b8c12", + "after_bytes": 619, + "formatted_in_actual_C27": false + }, + { + "path": "crates/render/src/film_primary.rs", + "before_sha256": "2c8b7cf8b1d6aff1d58f4137b05973467b23072c2caff9467256606058fb8f88", + "before_bytes": 8361, + "after_sha256": "d65f9fda36674199aac47ef9c393d59fe59d193addbb7423e324f0795211d1c5", + "after_bytes": 8123, + "formatted_in_actual_C27": false + }, + { + "path": "crates/render/src/film_tests.rs", + "before_sha256": "3fc4f5251f04f63a2a43a1f141fdccd3f66c50d3d8d42eff77754d21c4bdb2b7", + "before_bytes": 20416, + "after_sha256": "7e184b0c71f73bdeda036930c3e5a6a775a448b779283fde46b32c65ab3e9f20", + "after_bytes": 29879, + "formatted_in_actual_C27": true + }, + { + "path": "crates/render/src/job/cpu_budget.rs", + "before_sha256": "7756fedf76658a1eedd0c0194aa98141d33464c0f7df85fe86f9e255fd8b8ce2", + "before_bytes": 7771, + "after_sha256": "e02df70cd48a5116a42363431839c0c4d6f25f041e761f7ce01c04dc998a8aca", + "after_bytes": 7776, + "formatted_in_actual_C27": false + }, + { + "path": "crates/render/src/job/host.rs", + "before_sha256": "58147bb99311a07182a75e9e28aeb7f1aca752dff43724234225715479b741f2", + "before_bytes": 122246, + "after_sha256": "f775f4e458947b2c402fe97f10b320f7c7f4a9060cf502b5a69975e006eec71e", + "after_bytes": 131474, + "formatted_in_actual_C27": true + }, + { + "path": "crates/render/src/job/host_tests.rs", + "before_sha256": "c46cddeafe1816f0c479a9c68482ff86ccd8e124c2f5fc1bb7cd6e3509ef7f8e", + "before_bytes": 106536, + "after_sha256": "f159bd988beb8055b7d6e80a89eef5ba1e967e982c97d5480b80c93d19509ef0", + "after_bytes": 119544, + "formatted_in_actual_C27": true + }, + { + "path": "crates/render/src/job/interactive.rs", + "before_sha256": "5fb7062276adfdc22d1fa651750119feb90870b31d12fb0fc0b852c4b430468d", + "before_bytes": 11135, + "after_sha256": "97395da5b097d9283ac080e197f6de612b6123d9a90396e1850ca911d6ca5812", + "after_bytes": 14389, + "formatted_in_actual_C27": true + }, + { + "path": "crates/render/src/job/mod.rs", + "before_sha256": "87c5b59cf171009c3f3261e7d7a7691f84fc3e9ddd25f8458e6b1098e1a45543", + "before_bytes": 82216, + "after_sha256": "ad442c55f9a3edeeac359ca4c91c2dc5028bee36b981f6953e6399daf65c7c12", + "after_bytes": 84674, + "formatted_in_actual_C27": true + }, + { + "path": "crates/render/src/raytrace/environment_image_tests.rs", + "before_sha256": "9ee820799d6da59f8518197116984035d0292b86db4bbecb01135529590d1f53", + "before_bytes": 14628, + "after_sha256": "42442aaa4bcdda016b4349e096fd389e731df13683dbef9938925298432912b9", + "after_bytes": 14637, + "formatted_in_actual_C27": false + }, + { + "path": "crates/render/src/raytrace/image.rs", + "before_sha256": "d833890ff3fde61b22993b2a736a0914c6675a8d810b2f396d0b611ef66f51e4", + "before_bytes": 124736, + "after_sha256": "4e8f63765ca35f305e3caa0946fceba90573be243717bd08b54deeb948f59326", + "after_bytes": 126260, + "formatted_in_actual_C27": true + }, + { + "path": "crates/render/src/raytrace/image_tests.rs", + "before_sha256": "8af684984fce86ee3d8b8eff35c6a70efd88b0b9b7bbfefd42d082584bc9aa91", + "before_bytes": 173377, + "after_sha256": "5e6724dfe01a583b880862e24a2bfada40052bda09388e977f28f70f55029f89", + "after_bytes": 173358, + "formatted_in_actual_C27": false + }, + { + "path": "crates/render/src/raytrace/mod.rs", + "before_sha256": "d7f8ed95a60384d1e8f896ec0637af39682778adf4546c646104ae22ab53fbb8", + "before_bytes": 18244, + "after_sha256": "cf1a6ebf707d86552bdb62bb94b80910eca1709682c8e7133c1ae54ce1af4c15", + "after_bytes": 18040, + "formatted_in_actual_C27": false + }, + { + "path": "crates/render/src/raytrace/primary_aa_tests.rs", + "before_sha256": "693af2028d9446f95b61b002644649d5c9a945a049ec019508849712be06ea7e", + "before_bytes": 91756, + "after_sha256": "9366a35fa85e3b04eca01438da697979a1be4528fbc57a21d13da4b69aa175fc", + "after_bytes": 98436, + "formatted_in_actual_C27": true + }, + { + "path": "crates/render/src/raytrace/progressive.rs", + "before_sha256": "8ee8fd60c78d93d02ab3b15270b27491bd993d5fc4e0e36217f8653c4881993a", + "before_bytes": 4252, + "after_sha256": "04b0431ba2b06c910ab884bdcd2fe7945b8211acc6527f4006fcc35b415c19d3", + "after_bytes": 4252, + "formatted_in_actual_C27": false + }, + { + "path": "crates/render/src/raytrace/tests.rs", + "before_sha256": "2a105d16f476821e15962c6014d3b8fa8e124447ba36a8ee1d393bb2715d8e79", + "before_bytes": 20569, + "after_sha256": "a47fd554d0cd504d64237de7e160e89f89f53181eed4e30a9e0092ee7869fec7", + "after_bytes": 22825, + "formatted_in_actual_C27": true + }, + { + "path": "crates/ui-egui/src/render_workspace.rs", + "before_sha256": "6262d926d6e3dae4d6ed92fee6f429b413cf1de9f9185da2701cd351e5b20ab1", + "before_bytes": 108186, + "after_sha256": "1434d0b576ab7c8a94ca7f23b9f0bb617f755509cd6f16bfafb3a86cfed05263", + "after_bytes": 111146, + "formatted_in_actual_C27": true + }, + { + "path": "crates/ui-egui/src/render_workspace_cpu.rs", + "before_sha256": "3a06929c32104559374f62f4dd5134333c785345e4ba62762445f587a722daf9", + "before_bytes": 42638, + "after_sha256": "fd6de0f8121dc4d1bfce308c376901f65e2d920b68a756c38a25f82679db64ad", + "after_bytes": 42703, + "formatted_in_actual_C27": true + }, + { + "path": "crates/ui-egui/src/render_workspace_interactive.rs", + "before_sha256": "41dfccef77b9079af801bcfa3998dadc4976e20e7b1000f2666e1c75a3cf3332", + "before_bytes": 56174, + "after_sha256": "b0ecc5211491343015ca3b69749d707bcafd9826c3a7e90d9fc3cce89ade9d9d", + "after_bytes": 57748, + "formatted_in_actual_C27": false + }, + { + "path": "crates/ui-egui/src/render_workspace_tests.rs", + "before_sha256": "e7ff1b00bc5462db698096712965cb47f4177682bdb39ac0b6850d9c26710535", + "before_bytes": 619102, + "after_sha256": "28ddafe4a8f133c522ddf6f1e0eaaaf70f954d7b8acdb7cca44aabef9a512e47", + "after_bytes": 634699, + "formatted_in_actual_C27": true + }, + { + "path": "docs/render-cpu-progressive.md", + "before_sha256": "d5eb9a24058ae465529539768a3885cd14e38f2de14597e2eecb64ae5a099821", + "before_bytes": 10324, + "after_sha256": "8bbd70ac09e49585ad266d44d5c4034cae811e9e266a54b7979a202db20d81aa", + "after_bytes": 12920, + "formatted_in_actual_C27": false + }, + { + "path": "docs/render-cpu-resource-profiles.md", + "before_sha256": "b7c0a7101dba8906dbdc40994539dc558a97e8d32f8b363eea4ec83459e7a7b8", + "before_bytes": 6149, + "after_sha256": "acd230a198874f627df5d2e191a1c471e8dde744e4b7b3fad27618ac464e0063", + "after_bytes": 7218, + "formatted_in_actual_C27": false + }, + { + "path": "docs/render-cpu-workspace.md", + "before_sha256": "75e77c82e266f9b58eba8e1a09bc27d3ade505394ad9c34cb1d583bae098fe8e", + "before_bytes": 10769, + "after_sha256": "f87351e1b28849e74a5fb7e6027caeac724eb9665c7a0d135ac3ff25d589b39f", + "after_bytes": 12121, + "formatted_in_actual_C27": false + }, + { + "path": "docs/render-interactive.md", + "before_sha256": "f98decbcdb5d91568e103c794a0b785b31d127d6dc439eb8911270534b13be82", + "before_bytes": 8333, + "after_sha256": "6ee032d7e595e7402d235d45cc6719f3ec0e2309680e3ae87cea4baef122a58e", + "after_bytes": 9354, + "formatted_in_actual_C27": false + }, + { + "path": "docs/render-jobs.md", + "before_sha256": "c54c1e0d6376874faefc9b2f64ae21ea2658006fae557c8c048b0f0fb9282b81", + "before_bytes": 8826, + "after_sha256": "f07479ae20c57baa025809c298a8adc005e96f28a3f9ad05a78233406bc5cc8b", + "after_bytes": 10187, + "formatted_in_actual_C27": false + }, + { + "path": "docs/render-settings.md", + "before_sha256": "fee45ded12b0b4f62765b06e05ff4d2cdbe9a28b1cd2588f3f18165797c3c1d0", + "before_bytes": 21700, + "after_sha256": "6887fb62faf5e82731ba9849f76445cd66cdf1539cc81f054db2068b3359276d", + "after_bytes": 22284, + "formatted_in_actual_C27": false + } + ], + "selected_paths": 25, + "actual_formatter_changed_paths": 11, + "C27_result": { + "formatter_exit": 0, + "format_check_exit": 0, + "combined_build_exit": 101, + "coded_error": "E0308", + "location": "crates/render/src/job/host.rs:734", + "meaning": "A compile-time aggregate metadata-size bound is false; exact layout bytes were not inferred and the bound was not relaxed", + "native_selected": 982, + "native_executed": 0, + "native_passed": 0, + "native_failed": 0, + "native_unrun": 982, + "inventories_executed": 0, + "qualified_five_library_artifact_set": false, + "full_CI_or_native_acceptance": false + }, + "supersedes_for_continuation": "dbc6041ba7059ec30b11fa72b5d1abd59f5b104a nine-file high-pass/UI source snapshot; earlier files remain historical alternatives, not patches to stack blindly", + "producer_host_fix": "Private successor pending, not included in this exact failed-source snapshot", + "default_change_process": "Unresolved before production readiness; this preservation does not waive a preference/default rule" +}