From 529571a92aeaaed04acaaef6511082302e2e1bd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:02:13 -0800 Subject: [PATCH] craft-raster3d: rayon is optional behind a parallel feature rayon becomes an optional dependency behind a new parallel feature, off by default, as in craft-texture, craft-dds and craft-jpeg. The default build is serial, uses no rayon and builds for wasm32-unknown-unknown. The craft facade forwards it as raster3d-parallel. - With parallel, bands of rows, resolved rows, encoded pixels and shadow maps run on several threads with rayon, as before. Without it, the same per-item code runs in order on one thread, through small helpers in lib.rs. Both stop at the first error. - Outputs are the same either way. When several bands or shadow maps fail, the serial build returns the first one's error and the threaded build the error of one of them, and the needed count of TooMuchWork can differ. - Targets, images, shadow maps and the working buffers that grow with the raster or the vertex or triangle count are reserved fallibly, and a failed reservation returns the new RenderError::OutOfMemory. - rayon is added as a dev-dependency. The differential tests in tests/it/reference/effectcraft use it. - CI's default-feature test pass also runs craft-raster3d, so the serial build is tested. - The README and the crate docs describe the feature. --- crates/craft/Cargo.toml | 1 + crates/raster3d/Cargo.toml | 10 ++- crates/raster3d/README.md | 19 ++++- crates/raster3d/src/lib.rs | 135 +++++++++++++++++++++++++++++++- crates/raster3d/src/raster.rs | 78 +++++++++--------- crates/raster3d/src/resolve.rs | 41 +++++----- crates/raster3d/src/shadow.rs | 58 ++++++++------ scripts/ci-workspace-tests.sh | 8 +- scripts/test-workspace-tests.py | 2 +- 9 files changed, 255 insertions(+), 97 deletions(-) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index ebba43bc8e..af7d471a53 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -818,6 +818,7 @@ quit = ["dep:craft-quit"] raster-codecs = ["dep:craft-raster-codecs"] raster3d = ["dep:craft-raster3d"] +raster3d-parallel = ["raster3d", "craft-raster3d/parallel"] raw = ["dep:craft-raw"] raw-arw = ["raw", "craft-raw/arw"] diff --git a/crates/raster3d/Cargo.toml b/crates/raster3d/Cargo.toml index 69a4ed6184..d649afeed7 100644 --- a/crates/raster3d/Cargo.toml +++ b/crates/raster3d/Cargo.toml @@ -7,9 +7,17 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[features] +default = [] +parallel = ["dep:rayon"] + [lints] workspace = true [dependencies] -rayon = { workspace = true } +rayon = { workspace = true, optional = true } thiserror = { workspace = true } + +[dev-dependencies] +# The differential tests run a verbatim copy of the app's previous code, which uses rayon. +rayon = { workspace = true } diff --git a/crates/raster3d/README.md b/crates/raster3d/README.md index 4e0e9600ed..ea9809efde 100644 --- a/crates/raster3d/README.md +++ b/crates/raster3d/README.md @@ -11,7 +11,8 @@ Building a scene from an app's document (layers, cameras, models, text) stays in premultiplied linear RGBA and the camera-space depth of the nearest opaque surface, infinity where no opaque surface is drawn. `Scene::clip` maps world to clip space with reversed depth (a larger normalized device z is nearer); `Scene::view` maps world to camera space, and its third row gives - the depth. Rows are rasterized on several threads with rayon. + the depth. Rows are rasterized one band of 16 rows at a time, or on several threads with the + `parallel` feature. - **Clipping.** Triangles are clipped against the depth range `0 ≤ z ≤ w` before the perspective divide, the clip volume WebGPU uses (), and against a guard band of @@ -122,10 +123,20 @@ Building a scene from an app's document (layers, cameras, models, text) stays in division by alpha overflows, and changes no pixel then; the error names the first such pixel. The renderer holds 40 bytes per raster pixel (color, depth and visibility) and up to seven clipped triangles of about 140 bytes per scene triangle. A band of 16 rows that has a discarded opaque pixel also holds 29 bytes per pixel - (a discard flag and a candidate fragment) while its opaque pixels are shaded. The search for a + (a discard flag and a candidate fragment) while its opaque pixels are shaded. Targets, images, + shadow maps and the working buffers that grow with the raster or the vertex or triangle count + are reserved fallibly: when a reservation fails, the `try_` function returns `OutOfMemory`. A + triangle's clipped polygon, at most nine corners, and the shadow pass's lists of lights and + maps, a few entries per light, are allocated as usual. The search for a surviving fragment under discarded opaque pixels visits each opaque triangle's bounding box once more, so it runs no more coverage tests than the visibility pass. Its tests count toward `max_work`, and it can return `TooMuchWork` after the target is allocated. +- **Features.** `parallel` rasterizes bands of rows, resolves and encodes rows and pixels, and + renders shadow maps on several threads with rayon. The default build is serial and builds for + `wasm32-unknown-unknown`. Every output is the same either way. When several bands of rows or + shadow maps fail, the serial build returns the first one's error and the threaded build the + error of one of them, and the `needed` count of `TooMuchWork` from the fallback search or the + shadow maps can differ, since each thread stops counting at its own point. ## Origin @@ -157,6 +168,9 @@ Changes from those files: level range that overflowed, a zero raster width and a resolve factor of 0. It returned a cropped image for a factor that did not divide the size, NaN or infinite pixels for values that were not finite, and black environment light for levels that did not exist. +- Targets, images, shadow maps and the working buffers that grow with the raster or the vertex + or triangle count are reserved fallibly, and a failed reservation gives `OutOfMemory`. EffectCraft's allocations + stopped the process when memory ran out. - Triangles are clipped against the guard band, and clipped in `f64` when the depth clip in `f32` overflows. EffectCraft clipped only the depth range, so a triangle with corners far past the viewport that crossed the depth range could be dropped. Triangles leaving the band can shade @@ -258,6 +272,7 @@ Changes from those files: same order of operations. - The camera basis of the shadow maps is computed in this crate from the same operations as EffectCraft's `camera::basis_view`. +- Bands, rows, pixels and shadow maps run on several threads only with the `parallel` feature. ## Migration diff --git a/crates/raster3d/src/lib.rs b/crates/raster3d/src/lib.rs index a5d25d295a..ade2027d1c 100644 --- a/crates/raster3d/src/lib.rs +++ b/crates/raster3d/src/lib.rs @@ -29,7 +29,15 @@ //! setup. A light kind or falloff mode outside 0 to 2 returns [`RenderError::BadLight`]. //! A pass that runs over `max_work` while rendering also returns //! [`RenderError::TooMuchWork`]. [`try_resolve`], [`try_encode`] and [`try_env_shadow_map`] check -//! their own inputs and sizes before they allocate. Rows run on several threads with rayon. +//! their own inputs and sizes before they allocate. Buffers whose size grows with the raster, +//! the vertex or triangle count or a shadow map's texels are reserved fallibly and give +//! [`RenderError::OutOfMemory`] when the reservation fails. A triangle's clipped polygon (at most +//! nine corners) and the shadow pass's lists of lights and maps (a few entries per light of the +//! scene) are allocated as usual. Rows and shadow maps are computed on several threads only with +//! the `parallel` feature. The outputs are the same either way. When several bands or shadow maps +//! fail, the serial build returns the first one's error and the threaded build the error of one +//! of them, and the `needed` count of [`RenderError::TooMuchWork`] can differ, since each thread +//! stops counting at its own point. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -39,6 +47,9 @@ mod scene; mod shade; mod shadow; +#[cfg(feature = "parallel")] +use rayon::prelude::*; + pub use raster::{GUARD_BAND, Target, try_render}; pub use resolve::{Image, try_encode, try_render_cpu, try_resolve}; pub use scene::{EnvInfo, Light, Material, Scene, ShadowMap, TexInfo, Vertex}; @@ -137,8 +148,9 @@ pub enum RenderError { #[error("the shadow texels do not fit 32-bit offsets")] TooManyShadowTexels, /// Rasterizing or rendering shadow maps would take more coverage or depth tests than - /// [`Limits::max_work`]. Preparation stops at the first triangle past the limit. Fallback - /// and shadow-map work may be counted on several threads, within one triangle per thread, so `needed` is at least + /// [`Limits::max_work`]. Preparation stops at the first triangle past the limit. With the + /// `parallel` feature, fallback and shadow-map work may be counted on several threads, within + /// one triangle per thread, so `needed` is at least /// `limit + 1` and may be below the scene's total. #[error("the render needs at least {needed} tests, over the limit of {limit}")] TooMuchWork { needed: u64, limit: u64 }, @@ -153,6 +165,9 @@ pub enum RenderError { /// of its range). #[error("pixel {0} has a color that is not finite or an alpha out of range")] BadPixel(usize), + /// Memory for a target, an image, a shadow map or a working buffer could not be reserved. + #[error("not enough memory for the render")] + OutOfMemory, } /// Caps on sizes and work. Scene and size checks precede target allocation; fallback coverage @@ -206,3 +221,117 @@ impl Limits { usize::try_from(pixels).map_err(|_| RenderError::TooLarge(w, h)) } } + +/// An empty `Vec` with room for `len` items, or [`RenderError::OutOfMemory`] when the +/// reservation fails. +fn try_with_capacity(len: usize) -> Result, RenderError> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| RenderError::OutOfMemory)?; + Ok(v) +} + +/// A `Vec` of `len` copies of `value`, reserved fallibly. +fn filled(len: usize, value: T) -> Result, RenderError> { + let mut v = try_with_capacity(len)?; + v.resize(len, value); + Ok(v) +} + +/// Runs `f(chunk index, chunk of a, chunk of b)` over `a` and `b` split into chunks of `len` +/// items, on several threads with the `parallel` feature. `len` is at least 1. Stops at the first +/// error and returns it: without `parallel`, the error of the chunk with the lowest index that +/// fails; with it, the error of a failing chunk, and chunks not yet started are not run. +fn for_each_chunk_pair(a: &mut [A], b: &mut [B], len: usize, f: F) -> Result<(), RenderError> +where + A: Send, + B: Send, + F: Fn(usize, &mut [A], &mut [B]) -> Result<(), RenderError> + Sync + Send, +{ + let len = len.max(1); + #[cfg(feature = "parallel")] + return a.par_chunks_mut(len).zip(b.par_chunks_mut(len)).enumerate().try_for_each(|(i, (a, b))| f(i, a, b)); + #[cfg(not(feature = "parallel"))] + a.chunks_mut(len).zip(b.chunks_mut(len)).enumerate().try_for_each(|(i, (a, b))| f(i, a, b)) +} + +/// `f` of each item, in the order of `items`, on several threads with the `parallel` feature. +/// Stops at an error and returns it: the first item's error without `parallel`, and the error +/// of one failing item with it. +fn try_map_collect(items: &[T], f: F) -> Result, RenderError> +where + T: Sync, + U: Send, + F: Fn(&T) -> Result + Sync + Send, +{ + #[cfg(feature = "parallel")] + return items.par_iter().map(f).collect(); + #[cfg(not(feature = "parallel"))] + items.iter().map(f).collect() +} + +/// Runs `f` on each item, on several threads with the `parallel` feature, otherwise in the order +/// of `items`. +fn for_each_item(items: &[T], f: F) +where + T: Sync, + F: Fn(&T) + Sync + Send, +{ + #[cfg(feature = "parallel")] + items.par_iter().for_each(f); + #[cfg(not(feature = "parallel"))] + items.iter().for_each(f); +} + +/// `f` of each item, in the order of `items`, on several threads. The output is reserved +/// fallibly. +#[cfg(feature = "parallel")] +fn map_collect(items: &[T], f: F) -> Result, RenderError> +where + T: Sync, + U: Send, + F: Fn(&T) -> U + Sync + Send, +{ + let mut out = try_with_capacity(items.len())?; + out.par_extend(items.par_iter().map(f)); + Ok(out) +} + +/// `f` of each item, in the order of `items`. The output is reserved fallibly. +#[cfg(not(feature = "parallel"))] +fn map_collect(items: &[T], f: F) -> Result, RenderError> +where + T: Sync, + U: Send, + F: Fn(&T) -> U + Sync + Send, +{ + let mut out = try_with_capacity(items.len())?; + out.extend(items.iter().map(f)); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_buffer_that_cannot_be_reserved_is_out_of_memory() { + assert_eq!(filled(usize::MAX / 2, [0.0f32; 4]).err(), Some(RenderError::OutOfMemory)); + assert_eq!(try_with_capacity::(usize::MAX / 2).err(), Some(RenderError::OutOfMemory)); + assert_eq!(map_collect(&[1u8, 2, 3], |&x| u32::from(x) * 2), Ok(vec![2, 4, 6])); + assert_eq!(filled(3, 1.5f32), Ok(vec![1.5; 3])); + } + + #[test] + fn the_first_failing_chunk_gives_the_error() { + let (mut a, mut b) = (vec![0u8; 10], vec![0u8; 10]); + let r = for_each_chunk_pair(&mut a, &mut b, 2, |i, a, _| { + a.fill(1); + if i >= 2 { Err(RenderError::BadPixel(i)) } else { Ok(()) } + }); + #[cfg(not(feature = "parallel"))] + assert_eq!(r, Err(RenderError::BadPixel(2))); + #[cfg(feature = "parallel")] + assert!(matches!(r, Err(RenderError::BadPixel(2..=4))), "{r:?}"); + assert_eq!(for_each_chunk_pair(&mut a, &mut b, 2, |_, _, _| Ok(())), Ok(())); + } +} diff --git a/crates/raster3d/src/raster.rs b/crates/raster3d/src/raster.rs index b03cbf4987..42b983da8e 100644 --- a/crates/raster3d/src/raster.rs +++ b/crates/raster3d/src/raster.rs @@ -1,19 +1,17 @@ //! The triangle rasterizer. //! //! Triangles are clipped against the depth range (`0 ≤ z ≤ w`) and a guard band in x and y, -//! set up in screen space and scanned per band of rows in parallel with edge -//! functions (pixel centers, top-left fill rule) and perspective-correct barycentrics. Opaque -//! triangles resolve visibility first (reversed depth: larger ndc z is nearer) and each pixel is -//! shaded once; transparent triangles (already sorted back to front) are then shaded per -//! fragment and blended over, depth-tested against the opaque surfaces. +//! set up in screen space and scanned per band of rows (in parallel with the `parallel` +//! feature) with edge functions (pixel centers, top-left fill rule) and perspective-correct +//! barycentrics. Opaque triangles resolve visibility first (reversed depth: larger ndc z is +//! nearer) and each pixel is shaded once; transparent triangles (already sorted back to front) +//! are then shaded per fragment and blended over, depth-tested against the opaque surfaces. use std::sync::atomic::{AtomicU64, Ordering}; -use rayon::prelude::*; - use crate::scene::{Scene, Vertex, validate, validate_passes, validate_shadow_refs}; use crate::shade::{Frag, shade}; -use crate::{Limits, RenderError}; +use crate::{Limits, RenderError, filled, for_each_chunk_pair}; /// Half-width of the clip guard band in units of clip w: a triangle reaching past /// `|x| > GUARD_BAND × w` or `|y| > GUARD_BAND × w` is clipped there before the perspective @@ -226,8 +224,8 @@ fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec, } /// The screen triangles of a projected polygon, fanned from its first corner and clamped to the -/// viewport, appended to `out`. -fn fan(s: &Scene, scr: &[ScreenCorner], wide: bool, tri: u32, out: &mut Vec) { +/// viewport, appended to `out`. Returns [`RenderError::OutOfMemory`] when `out` cannot grow. +fn fan(s: &Scene, scr: &[ScreenCorner], wide: bool, tri: u32, out: &mut Vec) -> Result<(), RenderError> { // Facing from the polygon's screen-space winding (y down: negative = front). let mut area = 0.0; for i in 0..scr.len() { @@ -235,7 +233,7 @@ fn fan(s: &Scene, scr: &[ScreenCorner], wide: bool, tri: u32, out: &mut Vec= bbox[2] || bbox[1] >= bbox[3] { continue; } + out.try_reserve(1).map_err(|_| RenderError::OutOfMemory)?; out.push(STri { p: [c[0].0, c[1].0, c[2].0], z: [c[0].1, c[1].1, c[2].1], @@ -272,6 +271,7 @@ fn fan(s: &Scene, scr: &[ScreenCorner], wide: bool, tri: u32, out: &mut Vec, work: &mut } if let Some((scr, wide)) = project(s, clip, t) { let first = out.len(); - fan(s, &scr, wide, (t / 3) as u32, &mut out); + fan(s, &scr, wide, (t / 3) as u32, &mut out)?; for st in &out[first..] { let area = (st.bbox[2] - st.bbox[0]) as u64 * (st.bbox[3] - st.bbox[1]) as u64; *work = work.saturating_add(area + 1); @@ -376,25 +376,29 @@ const BAND: i32 = 16; /// The clip coordinates of every vertex, or the first vertex whose clip position is not finite. fn clip_positions(s: &Scene) -> Result, RenderError> { - s.vertices - .iter() - .enumerate() - .map(|(i, v)| { - let c = mat_mul(&s.clip, v.pos); - if c.iter().all(|x| x.is_finite()) { Ok(c) } else { Err(RenderError::BadClipPosition(i)) } - }) - .collect() + let mut out = vec![]; + for (i, v) in s.vertices.iter().enumerate() { + let c = mat_mul(&s.clip, v.pos); + if !c.iter().all(|x| x.is_finite()) { + return Err(RenderError::BadClipPosition(i)); + } + out.try_reserve(1).map_err(|_| RenderError::OutOfMemory)?; + out.push(c); + } + Ok(out) } /// The screen triangles of each band of `BAND` rows, by index into `ts`. -fn bin(ts: &[STri], bands: i32) -> Vec> { - let mut b = vec![vec![]; bands.max(0) as usize]; +fn bin(ts: &[STri], bands: i32) -> Result>, RenderError> { + let mut b: Vec> = filled(bands.max(0) as usize, vec![])?; for (i, t) in ts.iter().enumerate() { for band in (t.bbox[1] / BAND)..((t.bbox[3] + BAND - 1) / BAND).min(bands) { - b[band as usize].push(i as u32); + let list = &mut b[band as usize]; + list.try_reserve(1).map_err(|_| RenderError::OutOfMemory)?; + list.push(i as u32); } } - b + Ok(b) } /// One band of rows being rendered: its first row, its row count and the raster width. @@ -445,9 +449,9 @@ impl Band<'_> { } /// The nearest opaque triangle covering each pixel of the band. - fn visibility(&self, opaque: Pass) -> Visibility { + fn visibility(&self, opaque: Pass) -> Result { let (w, y0, rows) = (self.w, self.y0, self.rows); - let mut vis: Visibility = vec![(u32::MAX, EMPTY, [0.0; 3]); rows * w]; + let mut vis: Visibility = filled(rows * w, (u32::MAX, EMPTY, [0.0; 3]))?; for &ti in opaque.bins { let t = &opaque.tris[ti as usize]; for y in t.bbox[1].max(y0)..t.bbox[3].min(y0 + rows as i32) { @@ -462,7 +466,7 @@ impl Band<'_> { } } } - vis + Ok(vis) } /// Shade each pixel's visible opaque fragment. A discarded fragment (alpha test, back face) @@ -470,7 +474,7 @@ impl Band<'_> { /// depth becomes that fragment's ([`EMPTY`] when none survives). fn shade_opaque(&self, opaque: Pass, vis: &mut Visibility, crow: &mut [[f32; 4]], drow: &mut [f32]) -> Result<(), RenderError> { let s = self.s; - let mut discarded = vec![false; self.rows * self.w]; + let mut discarded = filled(self.rows * self.w, false)?; for i in 0..self.rows * self.w { let (ti, _, l) = vis[i]; if ti == u32::MAX { @@ -511,7 +515,7 @@ impl Band<'_> { /// first triangle's is kept. Coverage tests count toward [`Limits::max_work`]. fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result>, RenderError> { let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows); - let mut best: Vec> = vec![None; rows * w]; + let mut best: Vec> = filled(rows * w, None)?; for &tj in opaque.bins { let t2 = &opaque.tris[tj as usize]; let mut tests = 0u64; @@ -568,18 +572,18 @@ impl Band<'_> { fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, work: u64, limit: u64) -> Result { let (w, h) = (s.width as usize, s.height as usize); let bands = (h as i32 + BAND - 1) / BAND; - let ob = bin(opaque, bands); - let tb = bin(trans, bands); - let mut color = vec![[0.0f32; 4]; pixels]; - let mut depth = vec![f32::INFINITY; pixels]; + let ob = bin(opaque, bands)?; + let tb = bin(trans, bands)?; + let mut color = filled(pixels, [0.0f32; 4])?; + let mut depth = filled(pixels, f32::INFINITY)?; let spent = AtomicU64::new(work); - color.par_chunks_mut(w * BAND as usize).zip(depth.par_chunks_mut(w * BAND as usize)).enumerate().try_for_each(|(band, (crow, drow))| { + for_each_chunk_pair(&mut color, &mut depth, w * BAND as usize, |band, crow, drow| { let b = Band { s, y0: band as i32 * BAND, rows: crow.len() / w, w, spent: &spent, limit }; let (op, tp) = (Pass { tris: opaque, bins: &ob[band] }, Pass { tris: trans, bins: &tb[band] }); - let mut vis = b.visibility(op); + let mut vis = b.visibility(op)?; b.shade_opaque(op, &mut vis, crow, drow)?; b.blend_transparent(tp, &vis, crow); - Ok::<(), RenderError>(()) + Ok(()) })?; Ok(Target { width: s.width, height: s.height, color, depth }) } @@ -620,7 +624,7 @@ mod tests { ]; let (scr, wide) = project(&s, &clip, 0).unwrap(); let mut tris = Vec::new(); - fan(&s, &scr, wide, 0, &mut tris); + fan(&s, &scr, wide, 0, &mut tris).unwrap(); assert_eq!(tris.len(), 1); let (_, weights) = cover(&tris[0], 1.5, 0.5).unwrap(); assert_eq!(weights, [0.0, 0.75, 0.25]); diff --git a/crates/raster3d/src/resolve.rs b/crates/raster3d/src/resolve.rs index 1b348dca5f..3c273920a3 100644 --- a/crates/raster3d/src/resolve.rs +++ b/crates/raster3d/src/resolve.rs @@ -1,11 +1,9 @@ //! The box resolve of a supersampled target and the sRGB encoding of its pixels. -use rayon::prelude::*; - use crate::raster::{Target, try_render}; use crate::scene::Scene; use crate::shade::linear_to_srgb; -use crate::{Limits, RenderError}; +use crate::{Limits, RenderError, filled, for_each_chunk_pair, map_collect}; /// An image of premultiplied RGBA pixels, row-major from the top row. #[derive(Clone, Debug, PartialEq)] @@ -44,15 +42,15 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> let (w, h) = (t.width / k, t.height / k); // Fits: at most `expected`. let out = area(w, h).unwrap_or(0); - let mut img = Image { width: w, height: h, data: vec![[0.0; 4]; out] }; - let mut depth = vec![f32::INFINITY; out]; + let mut img = Image { width: w, height: h, data: filled(out, [0.0; 4])? }; + let mut depth = filled(out, f32::INFINITY)?; if out == 0 { return Ok((img, depth)); } let n = (u64::from(k) * u64::from(k)) as f32; // An f32 count stops at 2^24, so a larger block is averaged in f64. let wide = u64::from(k) * u64::from(k) > 1 << 24; - img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| { + for_each_chunk_pair(&mut img.data, &mut depth, w as usize, |y, row, drow| { for x in 0..w as usize { if wide { (row[x], drow[x]) = mean_f64(t, k as usize, x, y); @@ -82,7 +80,8 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> (row[x], drow[x]) = mean_f64(t, k as usize, x, y); } } - }); + Ok(()) + })?; Ok((img, depth)) } @@ -124,23 +123,19 @@ pub fn try_encode(img: &mut Image) -> Result<(), RenderError> { }; // A pixel that fails the checks above is written as NaN, so the first invalid pixel is // reported. - let encoded: Vec<[f32; 4]> = img - .data - .par_iter() - .map(|&p| { - if bad(&p) { - return [f32::NAN; 4]; + let encoded: Vec<[f32; 4]> = map_collect(&img.data, |&p| { + if bad(&p) { + return [f32::NAN; 4]; + } + let mut p = p; + let a = p[3]; + if a > 1e-6 { + for c in &mut p[..3] { + *c = linear_to_srgb(*c / a) * a; } - let mut p = p; - let a = p[3]; - if a > 1e-6 { - for c in &mut p[..3] { - *c = linear_to_srgb(*c / a) * a; - } - } - p - }) - .collect(); + } + p + })?; if let Some(i) = encoded.iter().position(|p| !p.iter().all(|c| c.is_finite())) { return Err(RenderError::BadPixel(i)); } diff --git a/crates/raster3d/src/shadow.rs b/crates/raster3d/src/shadow.rs index b18049f663..7b92b288a1 100644 --- a/crates/raster3d/src/shadow.rs +++ b/crates/raster3d/src/shadow.rs @@ -5,12 +5,10 @@ use std::cmp::Reverse; use std::collections::BinaryHeap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use rayon::prelude::*; - use crate::raster::f32_crossing; use crate::scene::{EnvInfo, Light, Material, Scene, ShadowMap, TexInfo, unit, validate}; use crate::shade::sample; -use crate::{Limits, RenderError}; +use crate::{Limits, RenderError, filled, for_each_item, try_map_collect, try_with_capacity}; /// Hard cap on the shadow depth texels (`f32`) of one scene, about 104 MB. It holds one point /// light's full 2048-texel cube (6 × 2048² ≈ 25.2 M texels). @@ -254,10 +252,10 @@ fn triangle_texels(m: &ShadowMap, tri: [MapCorner; 3]) -> u64 { /// The depth tests rendering `maps` takes: one per caster and map, plus each map triangle's /// bounding-box texels. When the casters times the maps already exceed `limit`, that product. -/// The maps are counted on several threads into one total, and each stops at the first caster -/// after the total passes `limit`. Returns [`RenderError::BadShadowInputs`] when the total stays -/// within `limit` and a caster's corners in a map are not finite, since the rasterizer would skip -/// that caster. +/// The maps are counted into one total, on several threads with the `parallel` feature, and each +/// stops at the first caster after the total passes `limit`. Returns +/// [`RenderError::BadShadowInputs`] when the total stays within `limit` and a caster's corners in +/// a map are not finite, since the rasterizer would skip that caster. fn shadow_work(s: &Scene, maps: &[ShadowMap], casters: &[usize], limit: u64) -> Result { let pairs = (maps.len() as u64).saturating_mul(casters.len() as u64); if pairs > limit { @@ -266,7 +264,7 @@ fn shadow_work(s: &Scene, maps: &[ShadowMap], casters: &[usize], limit: u64) -> let finite = |c: &MapCorner| c.0.iter().all(|v| v.is_finite()) && c.1.is_finite() && c.2.is_finite(); let total = AtomicU64::new(0); let not_finite = AtomicBool::new(false); - maps.par_iter().for_each(|m| { + for_each_item(maps, |m| { for &t in casters { if total.load(Ordering::Relaxed) > limit { return; @@ -294,9 +292,9 @@ fn shadow_work(s: &Scene, maps: &[ShadowMap], casters: &[usize], limit: u64) -> } /// Rasterize the shadow-casting triangles' light-space depth into `m`'s texels. -fn shadow_raster(s: &Scene, m: &ShadowMap, casters: &[usize]) -> Vec { +fn shadow_raster(s: &Scene, m: &ShadowMap, casters: &[usize]) -> Result, RenderError> { let n = m.size as usize; - let mut d = vec![f32::INFINITY; n * n]; + let mut d = filled(n * n, f32::INFINITY)?; for &t in casters { let ids = [s.indices[3 * t] as usize, s.indices[3 * t + 1] as usize, s.indices[3 * t + 2] as usize]; let mat = &s.materials[s.vertices[ids[0]].material as usize]; @@ -318,7 +316,7 @@ fn shadow_raster(s: &Scene, m: &ShadowMap, casters: &[usize]) -> Vec { raster_triangle(s, m, [scr[0], scr[k], scr[k + 1]], alpha.as_ref(), &mut d); } } - d + Ok(d) } /// Long side of a quality shadow map: one map texel per pixel of the `width × height` raster @@ -425,10 +423,15 @@ fn env_shadow_map(e: EnvInfo, centre: [f64; 3], radius: f64, size: u32) -> Shado } /// The triangles whose material casts shadows. -fn caster_list(s: &Scene) -> Vec { - (0..s.indices.len() / 3) - .filter(|&t| s.materials.get(s.vertices[s.indices[3 * t] as usize].material as usize).is_some_and(|m| m.casts_shadows)) - .collect() +fn caster_list(s: &Scene) -> Result, RenderError> { + let mut out = vec![]; + for t in 0..s.indices.len() / 3 { + if s.materials.get(s.vertices[s.indices[3 * t] as usize].material as usize).is_some_and(|m| m.casts_shadows) { + out.try_reserve(1).map_err(|_| RenderError::OutOfMemory)?; + out.push(t); + } + } + Ok(out) } /// The bounding sphere of the scene's vertices: (center, radius + 1). @@ -518,7 +521,7 @@ pub fn try_shadow_maps(s: &mut Scene, draft: bool, limits: &Limits) -> Result<() } fn shadow_maps_checked(s: &mut Scene, draft: bool, limits: &Limits) -> Result<(), RenderError> { - let casters = caster_list(s); + let casters = caster_list(s)?; // The environment light casts a shadow when marked and its image has a dominant direction; // with nothing to cast one, its mark is cleared either way. let env_shadow = !casters.is_empty() && s.env.is_some_and(|e| e.shadow >= 0 && e.sun != [0.0; 3]); @@ -590,8 +593,9 @@ fn shadow_maps_checked(s: &mut Scene, draft: bool, limits: &Limits) -> Result<() if needed > limits.max_work { return Err(RenderError::TooMuchWork { needed, limit: limits.max_work }); } - let texels: Vec> = maps.par_iter().map(|m| shadow_raster(s, m, &casters)).collect(); - let mut all = Vec::with_capacity(texels.iter().map(Vec::len).sum()); + let texels = try_map_collect(&maps, |m| shadow_raster(s, m, &casters))?; + let total = texels.iter().map(Vec::len).fold(0, usize::saturating_add); + let mut all = try_with_capacity(total)?; for (m, t) in maps.iter_mut().zip(texels) { m.offset = u32::try_from(all.len()).map_err(|_| RenderError::TooManyShadowTexels)?; all.extend(t); @@ -604,7 +608,7 @@ fn shadow_maps_checked(s: &mut Scene, draft: bool, limits: &Limits) -> Result<() #[cfg(test)] mod tests { use super::{NEAR, light_poly, shadow_raster}; - use crate::{Material, Scene, ShadowMap, TexInfo, Vertex}; + use crate::{Material, RenderError, Scene, ShadowMap, TexInfo, Vertex}; fn perspective_map() -> ShadowMap { ShadowMap { @@ -619,7 +623,7 @@ mod tests { } #[test] - fn perspective_casters_with_subnormal_reciprocals_keep_finite_depth() { + fn perspective_casters_with_subnormal_reciprocals_keep_finite_depth() -> Result<(), RenderError> { for z in [1e38, f32::MAX] { let s = Scene { vertices: [[-0.25 * z, -0.25 * z, z], [0.25 * z, -0.25 * z, z], [0.0, 0.25 * z, z]] @@ -629,14 +633,15 @@ mod tests { materials: vec![Material::default()], ..Scene::default() }; - let depths = shadow_raster(&s, &perspective_map(), &[0]); + let depths = shadow_raster(&s, &perspective_map(), &[0])?; assert!(depths[3 * 8 + 3].is_finite(), "caster depth {z}"); assert!(depths.iter().filter(|d| d.is_finite()).all(|&d| d == z)); } + Ok(()) } #[test] - fn clipped_caster_uvs_with_overflowing_differences_keep_the_alpha_test() { + fn clipped_caster_uvs_with_overflowing_differences_keep_the_alpha_test() -> Result<(), RenderError> { let covered = |u: f32, alphas: [f32; 2], indices: Vec| { let s = Scene { vertices: [([-NEAR, 0.0, 0.0], u), ([NEAR, -NEAR, 2.0 * NEAR], -u), ([NEAR, NEAR, 2.0 * NEAR], -u)] @@ -651,12 +656,13 @@ mod tests { let map = perspective_map(); let ids = [s.indices[0] as usize, s.indices[1] as usize, s.indices[2] as usize]; assert!(light_poly(&s, &map, ids).iter().all(|(_, uv)| uv.iter().all(|u| u.is_finite()))); - shadow_raster(&s, &map, &[0]).iter().filter(|d| d.is_finite()).count() + shadow_raster(&s, &map, &[0]).map(|d| d.iter().filter(|d| d.is_finite()).count()) }; for indices in [vec![0, 1, 2], vec![0, 2, 1]] { - assert!(covered(f32::MAX, [1.0; 2], indices.clone()) > 0); - assert_eq!(covered(1e20, [0.0, 1.0], indices.clone()), 0); - assert_eq!(covered(f32::MAX, [0.0, 1.0], indices), 0); + assert!(covered(f32::MAX, [1.0; 2], indices.clone())? > 0); + assert_eq!(covered(1e20, [0.0, 1.0], indices.clone())?, 0); + assert_eq!(covered(f32::MAX, [0.0, 1.0], indices)?, 0); } + Ok(()) } } diff --git a/scripts/ci-workspace-tests.sh b/scripts/ci-workspace-tests.sh index ee67e0c24c..dc0ce721ba 100755 --- a/scripts/ci-workspace-tests.sh +++ b/scripts/ci-workspace-tests.sh @@ -25,10 +25,10 @@ config=(--config .config/cargo-dev.toml --config .config/cargo-ci.toml) all_features=(--workspace --all-features --locked --profile ci "${config[@]}") targets=(--lib --bins --tests) examples=(-p craft-aep -p craft-video --example stubicc --example h264_h264enc_bench) -# The crate whose tests check behaviour with a feature off, which an all-features build cannot reach. -# craft-text is not here: its tests all need features, and its craft-ui dev-dependency would build -# the whole UI stack a second time with default features. -default_features=(-p craft-image-codecs --locked --profile ci "${config[@]}") +# The crates whose tests check behavior with a feature off, which an all-features build cannot reach. +# craft-raster3d's default build is serial. craft-text is not here: its tests all need features, and +# its craft-ui dev-dependency would build the whole UI stack a second time with default features. +default_features=(-p craft-image-codecs -p craft-raster3d --locked --profile ci "${config[@]}") # The replay audit (craft-libs#2336): these crates' tests again, with every memoized view that would # replay also run for real and compared with its replay. audit_packages=(craft-ui-contract craft-ui-widgets craft-ui-panels craft-ui-patterns craft-ui-shell craft-ui-gallery craft-menu) diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py index 9a926eb5a6..cbc8b56cc5 100644 --- a/scripts/test-workspace-tests.py +++ b/scripts/test-workspace-tests.py @@ -108,7 +108,7 @@ COMMON = [ ] CONFIG = "--config .config/cargo-dev.toml --config .config/cargo-ci.toml" ALL = f"--workspace --all-features --locked --profile ci {CONFIG}" -DEFAULT = f"-p craft-image-codecs --locked --profile ci {CONFIG}" +DEFAULT = f"-p craft-image-codecs -p craft-raster3d --locked --profile ci {CONFIG}" TARGETS = "--lib --bins --tests" EXAMPLES = "--example stubicc --example h264_h264enc_bench" AUDIT_PACKAGES = ("craft-ui-contract", "craft-ui-widgets", "craft-ui-panels", "craft-ui-patterns",