Merge pull request #2950 from dotCooCoo/feat/craft-raster3d-aux-outputs

craft-raster3d: return camera depth, view-space normal and part ID for each pixel
This commit is contained in:
BFlat authored and GitHub committed 2026-12-01 01:16:52 +07:00
commit a83c3b4e34
11 files changed
+1799 -81

No files matched your search

+48 -9
View File
@@ -58,8 +58,8 @@ Building a scene from an app's document (layers, cameras, models, text) stays in
`TexInfo` gives a texture's offset, size and wrap modes (repeat, clamp or mirror). `sample` is a
bilinear lookup with texel centers at +0.5.
- **Shadow maps.** `try_shadow_maps(&mut scene, draft, &limits)` renders the light-space depth of
every triangle whose material casts shadows into one map per parallel or spot light, six per
point light and one orthographic map for the environment light's dominant direction, for every
every triangle whose material casts shadows into one map per parallel light, one per spot light
(six for a wide spot light, below), six per point light and one orthographic map for the environment light's dominant direction, for every
light whose `shadow` is 0 or more. The shader compares each receiver with the nearest depth in the map
(<https://developer.nvidia.com/gpugems/gpugems/part-ii-lighting-and-shadows/chapter-11-shadow-map-antialiasing>)
over a jittered grid of 5 × 5 to 10 × 10 taps, each a bilinear comparison against the receiver's
@@ -94,6 +94,33 @@ Building a scene from an app's document (layers, cameras, models, text) stays in
value the same way. Pixels with alpha of 1e-6 or less are left as they are. `try_render_cpu` renders and
resolves by `Scene::ssaa`, and rejects a factor that does not divide the raster size before it
renders.
- **Auxiliary outputs.** `try_render_with_aux`, `try_resolve_aux` and `try_render_cpu_with_aux`
return the same color as `try_render`, `try_resolve` and `try_render_cpu`, bit for bit, and
`AuxPlanes`: three planes at the color's size, row-major from the top row, that describe one
surface per pixel. `depth` is the surface's camera depth (`f32`, the units of `Scene::view`),
infinity where empty. `normal` is its unit normal in view space, `[0, 0, 0]` where empty: the
vertex normal interpolated in `f64`, with exact expansion terms through the transform on cancellation
(one of length 1e-20 or less is read as `[0, 0, −1]`),
reversed on a back face, turned by the inverse transpose of the upper-left 3 × 3 of `Scene::view` and
normalized, so it stays perpendicular to the surface when the view scales axes unequally or
shears; normal textures are not applied. `part_id` is the `Scene::part_ids` entry of the
surface's triangle (`u32`), or `NO_PART` (`u32::MAX`) where empty; a triangle cut by clipping keeps its ID. Only a fragment that
adds alpha above 0 can be the surface: the nearest opaque surface drawn at the pixel, including
the one found under a discarded fragment, or a nearer transparent fragment; of several such
fragments the nearest is kept. Equal `f32` camera depths are compared in `f64` with a rounding
bound and an exact expansion fallback. Normalized depths are compared by cross-multiplying
their total original-vertex weights, without the view translation during rendering.
Equal normalized depths keep the earlier surface.
`depth` therefore differs from `Target::depth`, which holds opaque surfaces only. The
resolve copies the depth, normal and part ID of one subsample of each block, the one with the
smallest depth (the first in row-major order on ties), so it does not average depths across
surfaces or mix IDs; a pixel holds one ID, not every surface that covers part of it. The auxiliary
resolve does not allocate a mean-depth buffer.
`try_render_with_aux` and `try_render_cpu_with_aux` need one part ID per triangle, none of them
`NO_PART`, and, for a scene with a triangle, a view whose upper-left 3 × 3 is invertible.
`try_resolve_aux` takes no scene: it needs a factor that divides both sides, as `try_resolve`
does, and planes that each hold width × height values. The other functions do not read
`Scene::part_ids` and do not allocate the planes.
- **Limits.** `Limits` caps the raster pixels (2^24), the triangles of a scene (2^22), its vertices, used or not (3 × 2^22), the lights
(1024) and the coverage tests of the visibility, transparent and fallback passes (2^31). Preparation
counts every clipped triangle's bounding-box pixels plus one per triangle; fallback tests count
@@ -123,11 +150,21 @@ 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. 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
(a discard flag and a candidate fragment) while its opaque pixels are shaded. With auxiliary
outputs, each active band holds `size_of::<Option<AuxSurface>>()` bytes per pixel for depth
comparisons (currently 56) and another 16 bytes per pixel during fallback shading for triangle
indices and weights. The auxiliary planes hold
20 bytes more per raster pixel, and `try_render_cpu_with_aux` also holds 36 bytes per output pixel
for the resolve. The byte check reserves the 72 band bytes for every raster pixel, for a total
of 136 bytes per raster pixel plus 36 bytes per resolved output pixel. This sum must fit
`isize::MAX` bytes, or the call returns `TooLarge` before it allocates. `try_render_with_aux`
returns `BadPartIdCount`, `ReservedPartId` or `BadTransform` for the part IDs and view above, and
`BadPixel` when an auxiliary depth overflows `f32`; `try_resolve_aux` returns `BadDataLength` for
a plane of the wrong length. Targets, images, auxiliary planes, 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.
@@ -206,7 +243,7 @@ Changes from those files:
sign kept, as CSS Color 4's conversion code does. EffectCraft put every negative value on the
linear segment, so red −0.25 encoded to −3.23 instead of about −0.537.
- A normal whose squared length overflows `f32`, and the direction to a point or spot light whose
squared distance overflows `f32`, are normalized in `f64`. EffectCraft divided them by an
coordinate difference or squared distance overflows `f32`, are normalized in `f64`. EffectCraft divided them by an
infinite length, so the surface took no direct light.
- A caster corner or a receiver whose light-space coordinate times the map's focal length overflows
`f32` is projected in `f64`. EffectCraft's map coordinates for it were infinite.
@@ -286,6 +323,8 @@ Changes from those files:
EffectCraft replaces `adv::raster::render` with `try_render`, `adv::resolve` with `try_resolve`,
`adv::encode` with `try_encode`, `adv::render_cpu` with `try_render_cpu`, and
`raster::shadow_maps` with `try_shadow_maps`, and maps a `RenderError` to a render failure. Its
scene builder fills `craft_raster3d::Scene`, whose fields are those of its `adv::scene::Scene`.
scene builder fills `craft_raster3d::Scene`, whose fields are those of its `adv::scene::Scene`
plus `part_ids`. A struct literal for the baseline renderers sets `part_ids: Vec::new()`; a caller
of the auxiliary renderers supplies one ID per triangle.
The BRDF and the environment BRDF stay as they are here until a separate change moves them to
`craft-pbr`, whose results differ (a roughness floor of 0.032 and a clamped environment BRDF).
+144 -22
View File
@@ -23,21 +23,28 @@
//! - **Textures.** [`Scene::texels`] holds linear straight RGBA, row-major from the top row;
//! [`TexInfo`] gives each texture's span and wrap modes.
//!
//! [`try_render`], [`try_render_cpu`] and [`try_shadow_maps`] check the scene against [`Limits`] and return a
//! [`RenderError`] before they allocate a target: malformed indices, references and spans,
//! values that are not finite, sizes, triangle counts, light counts and the coverage work of
//! 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. 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.
//! [`try_render`], [`try_render_with_aux`], [`try_render_cpu`], [`try_render_cpu_with_aux`] and
//! [`try_shadow_maps`] check the scene against [`Limits`] and return a [`RenderError`] before they
//! allocate a target: malformed indices, references and spans, values that are not finite, sizes,
//! triangle counts, light counts and the coverage work of 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_resolve_aux`],
//! [`try_encode`] and [`try_env_shadow_map`] check 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.
//!
//! **Auxiliary outputs.** [`try_render_with_aux`], [`try_resolve_aux`] and
//! [`try_render_cpu_with_aux`] also return, for each pixel, the camera depth, the unit view-space
//! normal and the part ID ([`Scene::part_ids`]) of one surface: the nearest opaque surface drawn
//! there, or a nearer transparent fragment that added color. Each plane is row-major from the top
//! row at the color's size; an empty pixel holds infinity, `[0, 0, 0]` and [`NO_PART`]. The
//! renderers without them do not allocate these planes.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -50,9 +57,9 @@ 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};
pub use raster::{AuxPlanes, AuxTarget, GUARD_BAND, Target, try_render, try_render_with_aux};
pub use resolve::{AuxImage, Image, try_encode, try_render_cpu, try_render_cpu_with_aux, try_resolve, try_resolve_aux};
pub use scene::{EnvInfo, Light, Material, NO_PART, Scene, ShadowMap, TexInfo, Vertex};
pub use shade::{linear_to_srgb, sample, srgb_to_linear};
pub use shadow::{MAX_SHADOW_TEXELS, shadow_map_size, shadow_point_face_size, shadow_sizes, try_env_shadow_map, try_shadow_maps};
@@ -93,9 +100,17 @@ pub enum RenderError {
/// A vertex's clip-space position is not finite.
#[error("vertex {0} is outside the range the clip transform can hold")]
BadClipPosition(usize),
/// The clip or view transform, the eye or the camera direction is not finite.
#[error("the camera transform is not finite")]
/// The clip or view transform, the eye or the camera direction is not finite, or (for the
/// auxiliary outputs of a scene with a triangle) the upper-left 3 × 3 of the view transform,
/// which turns normals to view space, is singular.
#[error("the camera transform is not finite or cannot turn normals to view space")]
BadTransform,
/// [`Scene::part_ids`] does not hold one ID per triangle (auxiliary outputs).
#[error("the scene holds {found} part ids where {expected} triangles need one each")]
BadPartIdCount { expected: usize, found: usize },
/// The part ID of a triangle (by index) is [`NO_PART`], which marks a pixel with no surface.
#[error("triangle {0} has the part id reserved for an empty pixel")]
ReservedPartId(usize),
/// A material value is not finite or out of range (an alpha mode other than 0 to 2, or a
/// metallic, roughness or occlusion strength outside 0 to 1, for example), or names a texture
/// that does not exist. [`try_render`] also returns it for a visible transparent material
@@ -111,7 +126,7 @@ pub enum RenderError {
/// A light has a kind or falloff mode other than 0 to 2, a value that is not finite, a cone cosine outside −1
/// to 1, (a spot light) an inner cone cosine below the outer one, a shadow darkness outside 0
/// to 1, or (a parallel or spot light) a direction whose length differs from 1 by more than
/// 0.001.
/// 0.001, or (a point or spot light) an unknown falloff mode.
#[error(
"light {0} has an unknown kind or falloff mode, a value that is not finite, a cone cosine outside -1 to 1 or out of order, a shadow darkness outside 0 to 1 or a direction that is not unit length"
)]
@@ -162,7 +177,7 @@ pub enum RenderError {
BadDataLength { expected: usize, found: usize },
/// A pixel's color is not finite, or its alpha is negative or over 1. [`try_render`] returns
/// it for a rendered pixel whose color or depth overflowed `f32` (finite inputs near the top
/// of its range).
/// of its range), and [`try_render_with_aux`] also for an auxiliary depth or normal that did.
#[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.
@@ -220,8 +235,37 @@ impl Limits {
}
usize::try_from(pixels).map_err(|_| RenderError::TooLarge(w, h))
}
/// [`Limits::check`] for a render with auxiliary outputs, which also holds
/// [`AUX_BYTES_PER_PIXEL`] more bytes per raster pixel, including concurrent band buffers,
/// and, when it is resolved by `k` per side (`resolve` is `Some(k)`),
/// [`AUX_BYTES_PER_OUTPUT`] per output pixel: the sum of all of them
/// must fit `isize::MAX`. Nothing is allocated.
pub(crate) fn check_aux(&self, w: u32, h: u32, resolve: Option<u32>) -> Result<usize, RenderError> {
let pixels = self.check(w, h)?;
let raster = u64::from(w) * u64::from(h);
let out = resolve.map_or(0, |k| raster / u64::from(k.max(1)).pow(2));
let bytes = raster
.checked_mul(BYTES_PER_PIXEL + AUX_BYTES_PER_PIXEL)
.and_then(|b| b.checked_add(out.checked_mul(AUX_BYTES_PER_OUTPUT)?))
.ok_or(RenderError::TooLarge(w, h))?;
if bytes > MAX_ALLOC_BYTES {
return Err(RenderError::TooLarge(w, h));
}
Ok(pixels)
}
}
/// Extra bytes reserved per raster pixel for auxiliary renders: depth (4), normal (12), part ID (4),
/// band depth comparisons (`size_of::<Option<raster::AuxSurface>>()`, currently 56), and
/// fallback triangle indices and weights (16), currently totaling 96 bytes.
/// The band buffers are bounded by the full raster, including when bands run in parallel.
const AUX_BYTES_PER_PIXEL: u64 = 20 + std::mem::size_of::<Option<raster::AuxSurface>>() as u64 + 16;
/// Bytes a resolve with auxiliary outputs holds per output pixel: color (16), depth (4),
/// normal (12) and part ID (4).
const AUX_BYTES_PER_OUTPUT: u64 = 36;
/// An empty `Vec` with room for `len` items, or [`RenderError::OutOfMemory`] when the
/// reservation fails.
fn try_with_capacity<T>(len: usize) -> Result<Vec<T>, RenderError> {
@@ -254,6 +298,69 @@ where
a.chunks_mut(len).zip(b.chunks_mut(len)).enumerate().try_for_each(|(i, (a, b))| f(i, a, b))
}
/// [`for_each_chunk_pair`] over one slice.
fn for_each_chunk<A, F>(a: &mut [A], len: usize, f: F) -> Result<(), RenderError>
where
A: Send,
F: Fn(usize, &mut [A]) -> Result<(), RenderError> + Sync + Send,
{
let len = len.max(1);
#[cfg(feature = "parallel")]
return a.par_chunks_mut(len).enumerate().try_for_each(|(i, a)| f(i, a));
#[cfg(not(feature = "parallel"))]
a.chunks_mut(len).enumerate().try_for_each(|(i, a)| f(i, a))
}
/// [`for_each_chunk_pair`] over three slices.
fn for_each_chunk_triple<A, B, C, F>(a: &mut [A], b: &mut [B], c: &mut [C], len: usize, f: F) -> Result<(), RenderError>
where
A: Send,
B: Send,
C: Send,
F: Fn(usize, &mut [A], &mut [B], &mut [C]) -> Result<(), RenderError> + Sync + Send,
{
let len = len.max(1);
#[cfg(feature = "parallel")]
return a.par_chunks_mut(len).zip(b.par_chunks_mut(len)).zip(c.par_chunks_mut(len)).enumerate().try_for_each(|(i, ((a, b), c))| f(i, a, b, c));
#[cfg(not(feature = "parallel"))]
a.chunks_mut(len).zip(b.chunks_mut(len)).zip(c.chunks_mut(len)).enumerate().try_for_each(|(i, ((a, b), c))| f(i, a, b, c))
}
/// The five slices [`for_each_chunk_five`] splits: a band's color, depth and auxiliary depth,
/// normal and part ID rows.
type FiveChunks<'a, A, B, C, D, E> = (&'a mut [A], &'a mut [B], &'a mut [C], &'a mut [D], &'a mut [E]);
/// [`for_each_chunk_pair`] over five slices.
fn for_each_chunk_five<A, B, C, D, E, F>(s: FiveChunks<'_, A, B, C, D, E>, len: usize, f: F) -> Result<(), RenderError>
where
A: Send,
B: Send,
C: Send,
D: Send,
E: Send,
F: Fn(usize, FiveChunks<'_, A, B, C, D, E>) -> Result<(), RenderError> + Sync + Send,
{
let len = len.max(1);
let (a, b, c, d, e) = s;
#[cfg(feature = "parallel")]
return a
.par_chunks_mut(len)
.zip(b.par_chunks_mut(len))
.zip(c.par_chunks_mut(len))
.zip(d.par_chunks_mut(len))
.zip(e.par_chunks_mut(len))
.enumerate()
.try_for_each(|(i, ((((a, b), c), d), e))| f(i, (a, b, c, d, e)));
#[cfg(not(feature = "parallel"))]
a.chunks_mut(len)
.zip(b.chunks_mut(len))
.zip(c.chunks_mut(len))
.zip(d.chunks_mut(len))
.zip(e.chunks_mut(len))
.enumerate()
.try_for_each(|(i, ((((a, b), c), d), e))| f(i, (a, b, c, d, e)))
}
/// `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.
@@ -313,6 +420,21 @@ where
mod tests {
use super::*;
#[test]
fn auxiliary_byte_check_counts_concurrent_band_buffers() {
let limits = Limits { max_pixels: u64::MAX, ..Limits::default() };
#[cfg(target_pointer_width = "64")]
let (w, h) = (1 << 30, 80_000_000);
#[cfg(target_pointer_width = "32")]
let (w, h) = (1 << 20, 20);
let pixels = u64::from(w) * u64::from(h);
assert!(limits.check(w, h).is_ok());
assert!(pixels * (40 + 20 + 8 + 16) <= MAX_ALLOC_BYTES);
assert!(pixels * (BYTES_PER_PIXEL + AUX_BYTES_PER_PIXEL) > MAX_ALLOC_BYTES);
assert_eq!(limits.check_aux(w, h, None), Err(RenderError::TooLarge(w, h)));
assert_eq!(limits.check_aux(w, h, Some(2)), Err(RenderError::TooLarge(w, h)));
}
#[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));
+698 -34
View File
@@ -9,9 +9,15 @@
use std::sync::atomic::{AtomicU64, Ordering};
use crate::scene::{Scene, Vertex, validate, validate_passes, validate_shadow_refs};
use crate::scene::{NO_PART, Scene, Vertex, validate, validate_aux, validate_passes, validate_shadow_refs};
use crate::shade::{Frag, shade};
use crate::{Limits, RenderError, filled, for_each_chunk_pair};
use crate::{Limits, RenderError, filled, for_each_chunk_five, for_each_chunk_pair};
#[cfg(test)]
std::thread_local! {
static DEPTH_TIE_KEY_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static DEPTH_TIE_EXPANSIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// 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
@@ -30,6 +36,116 @@ pub struct Target {
pub depth: Vec<f32>,
}
/// The auxiliary outputs of one surface per pixel, each row-major from the top row at the size
/// of the color they come with.
///
/// The surface of a pixel is the nearest opaque surface drawn there (after an alpha test or a
/// single-sided back face hands the pixel to the next surface), or a transparent fragment that
/// adds alpha above 0 and is nearer in camera depth than the surface before it. Equal `f32`
/// depths are compared in `f64` with a rounding bound and an exact expansion fallback. Normalized
/// depths are compared by cross-multiplying their total original-vertex weights, without the view
/// translation. Equal depths keep the earlier surface. All three planes name the same surface.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AuxPlanes {
/// Camera-space depth of the surface (the third row of [`Scene::view`]), ∞ where empty. For
/// a transparent surface this differs from [`Target::depth`], which holds opaque surfaces only.
pub depth: Vec<f32>,
/// Unit normal of the surface in view space, `[0, 0, 0]` where empty: the vertex normal
/// interpolated in `f64`, with exact expansion terms through the transform on cancellation
/// (a vector of length 1e-20 or less is read as `[0, 0, −1]`), reversed on a back face,
/// turned by the inverse transpose of the upper-left 3 × 3 of [`Scene::view`] and normalized,
/// so it stays perpendicular to the surface under a non-uniform scale or a shear. Normal
/// textures are not applied.
pub normal: Vec<[f32; 3]>,
/// [`Scene::part_ids`] of the surface's triangle, [`NO_PART`] where empty.
pub part_id: Vec<u32>,
}
/// A rendered target with its auxiliary outputs at raster size.
#[derive(Clone, Debug, PartialEq)]
pub struct AuxTarget {
pub target: Target,
pub aux: AuxPlanes,
}
/// One band's rows of the auxiliary planes.
struct AuxRow<'a> {
depth: &'a mut [f32],
surface: Vec<Option<AuxSurface>>,
normal: &'a mut [[f32; 3]],
part: &'a mut [u32],
}
#[derive(Clone, Copy)]
pub(crate) struct AuxSurface {
tri: u32,
w: [[f32; 3]; 3],
l: [f32; 3],
}
struct DepthTieKey {
terms: [(f64, f64); 27],
weights: [f64; 9],
numerator: f64,
total: f64,
magnitude: f64,
weight_magnitude: f64,
}
impl DepthTieKey {
fn is_nearer_than(&self, other: &Self) -> bool {
let difference = self.numerator * other.total - other.numerator * self.total;
// Each numerator has 27 rounded products and additions; each total has 9 additions.
// Each cross-product path has at most 38 rounding steps. With u = EPSILON / 2,
// gamma(38) < 20 * EPSILON. The computed absolute sums have at most 38 steps too.
// 128 * EPSILON bounds both paths, the subtraction, and the absolute sums' rounding.
let bound = (self.magnitude * other.weight_magnitude + other.magnitude * self.weight_magnitude) * (128.0 * f64::EPSILON);
let positive_totals =
self.total > self.weight_magnitude * (16.0 * f64::EPSILON) && other.total > other.weight_magnitude * (16.0 * f64::EPSILON);
if positive_totals && difference.abs() > bound {
return difference < 0.0;
}
#[cfg(test)]
DEPTH_TIE_EXPANSIONS.with(|calls| calls.set(calls.get() + 1));
let numerator = crate::scene::product_expansion(self.terms);
let other_numerator = crate::scene::product_expansion(other.terms);
let total = crate::scene::product_expansion(self.weights.map(|w| (w, 1.0)));
let other_total = crate::scene::product_expansion(other.weights.map(|w| (w, 1.0)));
let left = numerator.terms().iter().flat_map(|&x| other_total.terms().iter().map(move |&y| (x, y)));
let right = other_numerator.terms().iter().flat_map(|&x| total.terms().iter().map(move |&y| (-x, y)));
let sign = crate::scene::product_expansion_sign(left.chain(right));
let total_sign = total.terms().last().map_or(0.0, |x| x.signum());
let other_total_sign = other_total.terms().last().map_or(0.0, |x| x.signum());
sign * total_sign * other_total_sign < 0.0
}
}
impl AuxRow<'_> {
/// Make (camera depth `z`, normal `n` and `part`) the surface of pixel `i`.
fn set(&mut self, i: usize, z: f32, surface: (&STri, [f32; 3]), n: [f32; 3], part: u32) {
self.depth[i] = z;
self.surface[i] = Some(AuxSurface { tri: surface.0.tri, w: surface.0.w, l: surface.1 });
self.normal[i] = n;
self.part[i] = part;
}
/// Make the surface of pixel `i` the given one when its camera depth `z` is nearer than the
/// pixel's. Comparison keys are computed only for `f32` ties. A NaN depth always replaces it and is never replaced.
fn offer(&mut self, i: usize, z: f32, surface: (&STri, [f32; 3]), band: &Band<'_>, n: impl FnOnce() -> [f32; 3], part: u32) {
if !self.depth[i].is_nan()
&& (z.is_nan()
|| z < self.depth[i]
|| (z == self.depth[i]
&& self.surface[i].is_some_and(|s| {
band.fragment_depth_tie_key(surface.0.tri, &surface.0.w, surface.1)
.is_nearer_than(&band.fragment_depth_tie_key(s.tri, &s.w, s.l))
})))
{
self.set(i, z, surface, n(), part);
}
}
}
/// A clipped triangle in screen space; `w` holds, per corner, its weights over the original
/// triangle's three vertices.
#[derive(Clone, Copy)]
@@ -498,6 +614,9 @@ struct Band<'a> {
w: usize,
spent: &'a AtomicU64,
limit: u64,
/// The sign of the determinant of the view's upper-left 3 × 3, which keeps an auxiliary
/// normal on its side.
view_sign: f64,
/// The coverage tests [`Band::fallback`] has run in this render.
#[cfg(test)]
fallback_tests: &'a AtomicU64,
@@ -514,6 +633,7 @@ struct Pass<'a> {
/// covers it.
type Visibility = Vec<(u32, f32, [f32; 3])>;
/// The surviving opaque fragment that [`Band::fallback`] finds for a discarded pixel.
#[derive(Clone, Copy)]
struct FallbackFragment {
ndc_z: f32,
@@ -521,10 +641,20 @@ struct FallbackFragment {
camera_depth: f32,
}
/// The fallback fragments and, for auxiliary renders, their screen triangles and weights.
struct Fallback {
fragments: Vec<Option<FallbackFragment>>,
aux: Option<Vec<(u32, [f32; 3])>>,
}
/// The visibility depth of a pixel with no opaque surface: below the far plane's 0, so a
/// fragment on the far plane is drawn.
const EMPTY: f32 = -1.0;
/// The rounding error, relative to the largest component, below which an auxiliary normal's
/// component is used without an exact expansion: under half an `f32` step of a unit normal.
const NORMAL_ERROR: f64 = 1.0 / (1u64 << 26) as f64;
/// Whether ndc depth `z` is inside the depth range and nearer than `than`.
#[inline]
fn nearer(z: f32, than: f32) -> bool {
@@ -540,6 +670,104 @@ impl Band<'_> {
if z.is_finite() { z } else { f32::NAN }
}
/// The untranslated camera-depth dot product in `f64` for auxiliary surface comparisons.
#[cfg(test)]
fn depth_tie_key(&self, p: [f32; 3]) -> f64 {
let row = self.s.view[2].map(f64::from);
row[0] * f64::from(p[0]) + row[1] * f64::from(p[1]) + row[2] * f64::from(p[2])
}
/// The auxiliary comparison numerator and total original-vertex weight, without the view translation.
fn fragment_depth_tie_key(&self, tri: u32, w: &[[f32; 3]; 3], l: [f32; 3]) -> DepthTieKey {
#[cfg(test)]
DEPTH_TIE_KEY_CALLS.with(|calls| calls.set(calls.get() + 1));
let base = tri as usize * 3;
let positions = [0, 1, 2].map(|k| self.s.vertices[self.s.indices[base + k] as usize].pos);
// Each pair of f32 factors has an exact f64 product.
let weights: [f64; 9] = std::array::from_fn(|i| f64::from(l[i / 3]) * f64::from(w[i / 3][i % 3]));
let terms: [(f64, f64); 27] = std::array::from_fn(|i| {
let axis = i / 9;
(f64::from(self.s.view[2][axis]) * f64::from(positions[i % 3][axis]), weights[i % 9])
});
let (numerator, magnitude) = terms.iter().fold((0.0, 0.0), |(sum, magnitude), &(x, y)| {
let product = x * y;
(sum + product, magnitude + product.abs())
});
let total = weights.iter().sum();
let weight_magnitude = weights.iter().map(|w| w.abs()).sum();
DepthTieKey { terms, weights, numerator, total, magnitude, weight_magnitude }
}
/// The unit view-space normal for [`AuxPlanes::normal`] of screen triangle `t` at
/// screen-corner weights `l`. The vertex normals are interpolated, normalized and turned in
/// `f64`, so finite normals near the top of the `f32` range do not overflow.
/// [`crate::scene::validate_aux`] has checked that the view's 3 × 3 is invertible, so the
/// turned vector has a length above 0.
fn view_normal(&self, t: &STri, l: [f32; 3]) -> [f32; 3] {
let unit = |v: [f64; 3], floor: f64| {
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
(len > floor && len.is_finite()).then(|| v.map(|x| x / len))
};
let s = self.s;
let base = t.tri as usize * 3;
// The weights over the original vertices, as `frag` computes them.
let mut wv = [0.0f32; 3];
for c in 0..3 {
for k in 0..3 {
wv[k] += l[c] * t.w[c][k];
}
}
let interpolation: [[(f64, f64); 3]; 3] =
std::array::from_fn(|i| std::array::from_fn(|k| (f64::from(s.vertices[s.indices[base + k] as usize].normal[i]), f64::from(wv[k]))));
let expansion = interpolation.map(crate::scene::product_expansion);
let sum = expansion.map(|e| e.sum());
let mut expansion = if unit(sum, 1e-20).is_some() {
expansion
} else {
[0.0, 0.0, -1.0].map(|x| crate::scene::product_expansion([(x, 1.0), (0.0, 0.0), (0.0, 0.0)]))
};
if !t.front {
expansion = expansion.map(|e| e.negated());
}
let n = expansion.map(|e| e.sum());
let magnitude = expansion.map(|e| e.terms().iter().fold(0.0, |sum, x| sum + x.abs()));
// Transform the normal by the cofactor matrix and the determinant's sign.
// A row takes an exact expansion when its rounding bound is not negligible next to the
// largest row, which sets the normalized result's scale.
let row = |r: usize| -> [f64; 3] { std::array::from_fn(|c| f64::from(self.s.view[r][c])) };
let (a, b, c) = (row(0), row(1), row(2));
let pairs = [(b, c), (c, a), (a, b)];
let terms: [[(f64, f64); 6]; 3] = std::array::from_fn(|i| {
let (p, q) = pairs[i];
[(p[1] * q[2], n[0]), (-(p[2] * q[1]), n[0]), (p[2] * q[0], n[1]), (-(p[0] * q[2]), n[1]), (p[0] * q[1], n[2]), (-(p[1] * q[0]), n[2])]
});
let fast: [(f64, f64); 3] = terms.map(|t| {
let (dot, magnitude) = t.iter().enumerate().fold((0.0f64, 0.0f64), |(dot, total), (k, &(x, y))| {
let product = x * y;
(dot + product, total + x.abs() * magnitude[k / 2])
});
(dot, magnitude * (16.0 * f64::EPSILON))
});
let big = fast.iter().fold(0.0f64, |m, &(dot, _)| m.max(dot.abs()));
let r: [f64; 3] = std::array::from_fn(|i| {
let (dot, bound) = fast[i];
let dot = if bound <= big * NORMAL_ERROR {
dot
} else {
let exact: [(f64, f64); 36] =
std::array::from_fn(|k| (terms[i][k / 6].0, expansion[k / 12].terms().get(k % 6).copied().unwrap_or(0.0)));
crate::scene::sum_of_products(exact)
};
self.view_sign * dot
});
unit(r, 0.0).map_or([f32::NAN; 3], |r| r.map(|x| x as f32))
}
/// The part ID of screen triangle `t`.
fn part(&self, t: &STri) -> u32 {
self.s.part_ids.get(t.tri as usize).copied().unwrap_or(NO_PART)
}
/// The nearest opaque triangle covering each pixel of the band.
fn visibility(&self, opaque: Pass) -> Result<Visibility, RenderError> {
let (w, y0, rows) = (self.w, self.y0, self.rows);
@@ -564,7 +792,16 @@ impl Band<'_> {
/// Shade each pixel's visible opaque fragment. A discarded fragment (alpha test, back face)
/// gives way to the nearest surviving fragment under the pixel, and the pixel's visibility
/// 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> {
/// When `aux` is given, each shaded pixel's fragment with alpha above 0 becomes its auxiliary
/// surface.
fn shade_opaque(
&self,
opaque: Pass,
vis: &mut Visibility,
crow: &mut [[f32; 4]],
drow: &mut [f32],
aux: &mut Option<AuxRow<'_>>,
) -> Result<(), RenderError> {
let s = self.s;
let mut discarded = filled(self.rows * self.w, false)?;
for i in 0..self.rows * self.w {
@@ -572,11 +809,17 @@ impl Band<'_> {
if ti == u32::MAX {
continue;
}
let f = frag(s, &opaque.tris[ti as usize], l);
let t = &opaque.tris[ti as usize];
let f = frag(s, t, l);
match shade(s, &f) {
Some(c) => {
crow[i] = c;
drow[i] = self.cam_z(f.pos);
if let Some(a) = aux
&& c[3] > 0.0
{
a.set(i, drow[i], (t, l), self.view_normal(t, l), self.part(t));
}
}
None => discarded[i] = true,
}
@@ -584,7 +827,8 @@ impl Band<'_> {
if !discarded.contains(&true) {
return Ok(());
}
for (i, best) in self.fallback(opaque, vis, &discarded)?.into_iter().enumerate() {
let fallback = self.fallback(opaque, vis, &discarded, aux.is_some())?;
for (i, best) in fallback.fragments.into_iter().enumerate() {
if !discarded[i] {
continue;
}
@@ -593,6 +837,14 @@ impl Band<'_> {
crow[i] = f.color;
drow[i] = f.camera_depth;
vis[i].1 = f.ndc_z;
if let Some(a) = aux
&& f.color[3] > 0.0
&& let Some(surface) = &fallback.aux
{
let (ti, l) = surface[i];
let t = &opaque.tris[ti as usize];
a.set(i, f.camera_depth, (t, l), self.view_normal(t, l), self.part(t));
}
}
None => vis[i].1 = EMPTY,
}
@@ -604,16 +856,18 @@ impl Band<'_> {
/// triangle other than the pixel's visible one, inside the depth range as in
/// [`Band::visibility`]. Triangles are
/// visited in index order over their bounding boxes, and among fragments at equal depth the
/// first triangle's is kept. Each coverage test counts toward [`Limits::max_work`] next to the
/// first triangle's is kept. Triangle indices and weights are stored only when `aux` is true.
/// Each coverage test counts toward [`Limits::max_work`] next to the
/// work `setup` charged. A triangle's candidate pixels are gathered in batches of 256, and each
/// batch is charged before its tests run, so a band stops with [`RenderError::TooMuchWork`]
/// without testing a batch that passes the limit. A band also stops after any triangle once the
/// total of all bands is over the limit. The error reports `needed` as `limit + 1`, so it does
/// not depend on the order the bands run in.
fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result<Vec<Option<FallbackFragment>>, RenderError> {
fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool], aux: bool) -> Result<Fallback, RenderError> {
let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows);
let over = || RenderError::TooMuchWork { needed: self.limit.saturating_add(1), limit: self.limit };
let mut best: Vec<Option<FallbackFragment>> = filled(rows * w, None)?;
let mut surface = if aux { Some(filled(rows * w, (u32::MAX, [0.0; 3]))?) } else { None };
let mut batch = [(0usize, 0i32, 0i32); 256];
for &tj in opaque.bins {
let t2 = &opaque.tris[tj as usize];
@@ -631,6 +885,9 @@ impl Band<'_> {
let f2 = frag(s, t2, l2);
if let Some(c) = shade(s, &f2) {
best[i] = Some(FallbackFragment { ndc_z: z, color: c, camera_depth: self.cam_z(f2.pos) });
if let Some(surface) = &mut surface {
surface[i] = (tj, l2);
}
}
}
}
@@ -659,11 +916,13 @@ impl Band<'_> {
return Err(over());
}
}
Ok(best)
Ok(Fallback { fragments: best, aux: surface })
}
/// Transparent fragments in order, blended over the opaque result where they are nearer.
fn blend_transparent(&self, trans: Pass, vis: &Visibility, crow: &mut [[f32; 4]]) {
/// When `aux` is given, a fragment with alpha above 0 is offered as the pixel's auxiliary
/// surface.
fn blend_transparent(&self, trans: Pass, vis: &Visibility, crow: &mut [[f32; 4]], aux: &mut Option<AuxRow<'_>>) {
let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows);
for &ti in trans.bins {
let t = &trans.tris[ti as usize];
@@ -673,11 +932,17 @@ impl Band<'_> {
let i = r + x as usize;
if let Some((z, l)) = cover(t, x as f64 + 0.5, y as f64 + 0.5)
&& nearer(z, vis[i].1)
&& let Some(c) = shade(s, &frag(s, t, l))
{
let f = frag(s, t, l);
let Some(c) = shade(s, &f) else { continue };
let d = crow[i];
let k = 1.0 - c[3];
crow[i] = [c[0] + d[0] * k, c[1] + d[1] * k, c[2] + d[2] * k, c[3] + d[3] * k];
if let Some(a) = aux
&& c[3] > 0.0
{
a.offer(i, self.cam_z(f.pos), (t, l), self, || self.view_normal(t, l), self.part(t));
}
}
}
}
@@ -685,16 +950,19 @@ impl Band<'_> {
}
}
/// Rasterize and shade set-up screen triangles into a target of `pixels` pixels.
/// Rasterize and shade set-up screen triangles into a target of `pixels` pixels, with the
/// auxiliary planes when `aux` is true (empty planes otherwise). `budget` is the work already
/// charged and [`Limits::max_work`].
fn raster(
s: &Scene,
opaque: &[STri],
trans: &[STri],
pixels: usize,
work: u64,
limit: u64,
aux: bool,
budget: (u64, u64),
#[cfg(test)] fallback_tests: &AtomicU64,
) -> Result<Target, RenderError> {
) -> Result<(Target, AuxPlanes), RenderError> {
let (work, limit) = budget;
let (w, h) = (s.width as usize, s.height as usize);
let bands = (h as i32 + BAND - 1) / BAND;
let ob = bin(opaque, bands)?;
@@ -702,7 +970,9 @@ fn raster(
let mut color = filled(pixels, [0.0f32; 4])?;
let mut depth = filled(pixels, f32::INFINITY)?;
let spent = AtomicU64::new(work);
for_each_chunk_pair(&mut color, &mut depth, w * BAND as usize, |band, crow, drow| {
let band_rows = w * BAND as usize;
let view_sign = crate::scene::det_sign3(&s.view).unwrap_or(1.0);
let render = |band: usize, crow: &mut [[f32; 4]], drow: &mut [f32], mut arow: Option<AuxRow>| -> Result<(), RenderError> {
let b = Band {
s,
y0: band as i32 * BAND,
@@ -710,16 +980,56 @@ fn raster(
w,
spent: &spent,
limit,
view_sign,
#[cfg(test)]
fallback_tests,
};
let (op, tp) = (Pass { tris: opaque, bins: &ob[band] }, Pass { tris: trans, bins: &tb[band] });
let mut vis = b.visibility(op)?;
b.shade_opaque(op, &mut vis, crow, drow)?;
b.blend_transparent(tp, &vis, crow);
b.shade_opaque(op, &mut vis, crow, drow, &mut arow)?;
b.blend_transparent(tp, &vis, crow, &mut arow);
Ok(())
})?;
Ok(Target { width: s.width, height: s.height, color, depth })
};
let mut planes = if aux {
AuxPlanes { depth: filled(pixels, f32::INFINITY)?, normal: filled(pixels, [0.0; 3])?, part_id: filled(pixels, NO_PART)? }
} else {
AuxPlanes::default()
};
if aux {
let slices = (&mut color[..], &mut depth[..], &mut planes.depth[..], &mut planes.normal[..], &mut planes.part_id[..]);
for_each_chunk_five(slices, band_rows, |band, (crow, drow, depth, normal, part)| {
let surface = filled(depth.len(), None)?;
render(band, crow, drow, Some(AuxRow { depth, surface, normal, part }))
})?;
} else {
for_each_chunk_pair(&mut color, &mut depth, band_rows, |band, crow, drow| render(band, crow, drow, None))?;
}
Ok((Target { width: s.width, height: s.height, color, depth }, planes))
}
/// Checks the scene (with the checks of the auxiliary outputs when `aux` is true) and sets up
/// its screen triangles: (pixel count, opaque, transparent, preparation work).
fn prepare(s: &Scene, limits: &Limits, aux: bool) -> Result<(usize, Vec<STri>, Vec<STri>, u64), RenderError> {
if aux {
limits.check_aux(s.width, s.height, None)?;
}
let pixels = validate(s, limits)?;
validate_passes(s)?;
if aux {
validate_aux(s)?;
}
validate_shadow_refs(s)?;
let clip = clip_positions(s)?;
let mut work = 0;
let opaque = setup(s, &clip, 0..s.opaque_count as usize, &mut work, limits.max_work)?;
let trans = setup(s, &clip, s.opaque_count as usize..s.indices.len(), &mut work, limits.max_work)?;
Ok((pixels, opaque, trans, work))
}
/// The first pixel whose color is not finite or whose depth is NaN: finite inputs near the top
/// of the `f32` range can still overflow in shading.
fn bad_pixel(t: &Target) -> Option<usize> {
t.color.iter().zip(&t.depth).position(|(c, d)| !c.iter().all(|v| v.is_finite()) || d.is_nan())
}
/// Rasterize and shade the scene at its raster size.
@@ -738,38 +1048,112 @@ pub fn try_render(s: &Scene, limits: &Limits) -> Result<Target, RenderError> {
/// [`try_render`], adding the coverage tests of the search under discarded pixels to
/// `fallback_tests` in test builds.
fn render(s: &Scene, limits: &Limits, #[cfg(test)] fallback_tests: &AtomicU64) -> Result<Target, RenderError> {
let pixels = validate(s, limits)?;
validate_passes(s)?;
validate_shadow_refs(s)?;
let clip = clip_positions(s)?;
let mut work = 0;
let opaque = setup(s, &clip, 0..s.opaque_count as usize, &mut work, limits.max_work)?;
let trans = setup(s, &clip, s.opaque_count as usize..s.indices.len(), &mut work, limits.max_work)?;
let t = raster(
let (pixels, opaque, trans, work) = prepare(s, limits, false)?;
let (t, _) = raster(
s,
&opaque,
&trans,
pixels,
work,
limits.max_work,
false,
(work, limits.max_work),
#[cfg(test)]
fallback_tests,
)?;
// Finite inputs near the top of the f32 range can still overflow in shading.
if let Some(i) = t.color.iter().zip(&t.depth).position(|(c, d)| !c.iter().all(|v| v.is_finite()) || d.is_nan()) {
return Err(RenderError::BadPixel(i));
match bad_pixel(&t) {
Some(i) => Err(RenderError::BadPixel(i)),
None => Ok(t),
}
}
/// [`try_render`] with the auxiliary outputs ([`AuxPlanes`]): the same target, bit for bit, and
/// the camera depth, view-space normal and part ID of each pixel's surface.
///
/// Besides the checks of [`try_render`], [`Scene::part_ids`] must hold one ID per triangle and
/// none may be [`NO_PART`], and, when the scene has a triangle, the upper-left 3 × 3 of
/// [`Scene::view`] must be invertible. The
/// output holds 20 more bytes per raster pixel than [`try_render`]. Each active band also holds
/// `size_of::<Option<AuxSurface>>()` bytes per pixel for depth comparisons (currently 56) and,
/// during fallback shading, 16 bytes per pixel for triangle indices and weights. The byte check
/// reserves all 72 band bytes per raster pixel, for a total of 136 bytes per raster pixel that
/// must fit `isize::MAX` bytes.
pub fn try_render_with_aux(s: &Scene, limits: &Limits) -> Result<AuxTarget, RenderError> {
let (pixels, opaque, trans, work) = prepare(s, limits, true)?;
let (target, aux) = raster(
s,
&opaque,
&trans,
pixels,
true,
(work, limits.max_work),
#[cfg(test)]
&AtomicU64::new(0),
)?;
let bad_aux = || aux.depth.iter().zip(&aux.normal).position(|(d, n)| d.is_nan() || !n.iter().all(|v| v.is_finite()));
match bad_pixel(&target).or_else(bad_aux) {
Some(i) => Err(RenderError::BadPixel(i)),
None => Ok(AuxTarget { target, aux }),
}
Ok(t)
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU64, Ordering};
use super::{cover, crossing_f64, f32_crossing, fan, project, render, try_render};
use super::{AuxRow, Band, FallbackFragment, Pass, STri, cover, crossing_f64, f32_crossing, fan, project, render, try_render};
use crate::scene::{Material, Scene, Vertex};
use crate::{Limits, RenderError};
/// The coverage-test counter of the bands these tests build by hand.
static FALLBACK_TESTS: AtomicU64 = AtomicU64::new(0);
fn point_triangle(tri: u32) -> STri {
STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri,
front: true,
bbox: [0; 4],
}
}
#[test]
fn auxiliary_exact_depth_keys_are_computed_only_for_f32_ties() {
let vertices = [3.0, 2.0, 1.0].into_iter().flat_map(|z| [Vertex { pos: [0.0, 0.0, z], ..Vertex::default() }; 3]);
let mut s = Scene { vertices: vertices.collect(), indices: (0..9).collect(), ..Scene::default() };
s.view[2] = [0.0, 0.0, 1.0, 0.0];
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
let triangles = [0, 1, 2].map(point_triangle);
let surface = |i: usize| (&triangles[i], [1.0, 0.0, 0.0]);
let mut depth = [f32::INFINITY];
let mut normal = [[0.0; 3]];
let mut part = [super::NO_PART];
let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part };
let n = [0.0, 0.0, 1.0];
super::DEPTH_TIE_KEY_CALLS.with(|calls| calls.set(0));
super::DEPTH_TIE_EXPANSIONS.with(|calls| calls.set(0));
row.offer(0, 3.0, surface(0), &b, || n, 10);
row.offer(0, 2.0, surface(1), &b, || n, 20);
row.offer(0, 3.0, surface(0), &b, || panic!("farther surface replaced the nearer one"), 10);
assert_eq!(row.part[0], 20);
row.set(0, 3.0, surface(0), n, 10);
row.offer(0, 2.0, surface(1), &b, || n, 20);
assert_eq!(row.part[0], 20);
super::DEPTH_TIE_KEY_CALLS.with(|calls| assert_eq!(calls.get(), 0, "unequal depths computed an exact key"));
row.offer(0, 2.0, surface(2), &b, || n, 30);
assert_eq!(row.part[0], 30);
super::DEPTH_TIE_KEY_CALLS.with(|calls| assert_eq!(calls.get(), 2, "a tie must compare both exact keys"));
row.offer(0, 2.0, surface(1), &b, || panic!("the previous surface was compared after replacement"), 20);
assert_eq!(row.part[0], 30);
super::DEPTH_TIE_KEY_CALLS.with(|calls| assert_eq!(calls.get(), 4));
super::DEPTH_TIE_EXPANSIONS.with(|calls| assert_eq!(calls.get(), 0, "separated f64 estimates computed exact expansions"));
row.offer(0, 2.0, surface(2), &b, || panic!("equal depth replaced the surface"), 40);
super::DEPTH_TIE_EXPANSIONS.with(|calls| assert_eq!(calls.get(), 1, "equal estimates must use exact expansions"));
}
#[test]
fn the_search_under_discarded_pixels_runs_no_batch_past_the_work_limit() {
// One band of 32 × 16 pixels covered by a far quad and, nearer, a masked quad whose every
@@ -845,6 +1229,286 @@ mod tests {
assert_eq!(f32_crossing(1e38, -3e38), (false, 0.25));
}
#[test]
fn an_auxiliary_normal_near_the_top_of_f32_is_interpolated_in_f64() {
// Three normals of `[f32::MAX, 0, 0]` at weights whose sum is just above 1: the weighted
// sum overflows `f32` and must still give the normal's direction.
let v = Vertex { normal: [f32::MAX, 0.0, 0.0], ..Vertex::default() };
let id = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let s = Scene { vertices: vec![v; 3], indices: vec![0, 1, 2], view: id, ..Scene::default() };
let t = STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri: 0,
front: true,
bbox: [0; 4],
};
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
let l = [0.5, 0.25, 0.25 + 2f32.powi(-22)];
assert_eq!(b.view_normal(&t, l), [1.0, 0.0, 0.0]);
let back = STri { front: false, ..t };
assert_eq!(b.view_normal(&back, l), [-1.0, 0.0, 0.0]);
}
#[test]
fn an_interpolated_auxiliary_normal_preserves_small_components_after_cancellation() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let vertices = [2f32.powi(99), 1.0, -2f32.powi(100)].map(|x| Vertex { normal: [x, 0.0, 0.0], ..Vertex::default() });
let s = Scene { vertices: vertices.to_vec(), indices: vec![0, 1, 2], view, ..Scene::default() };
let t = STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri: 0,
front: true,
bbox: [0; 4],
};
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
assert_eq!(b.view_normal(&t, [0.5, 0.25, 0.25]), [1.0, 0.0, 0.0]);
}
#[test]
fn a_view_scale_preserves_a_small_interpolated_normal_component_after_cancellation() {
let view = [[2f32.powi(-61), 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let vertices = [2f32.powi(62), 1.0, -2f32.powi(62)].map(|x| Vertex { normal: [x, 2f32.powi(60), 0.0], ..Vertex::default() });
let s = Scene { vertices: vertices.to_vec(), indices: vec![0, 1, 2], view, ..Scene::default() };
let t = STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri: 0,
front: true,
bbox: [0; 4],
};
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
let n = b.view_normal(&t, [0.25, 0.5, 0.25]);
assert!(n.iter().all(|x| x.is_finite()));
assert!(n[0] > 0.0);
assert_eq!(n[0], n[1]);
assert_eq!(n[2], 0.0);
assert!((n[0] * n[0] + n[1] * n[1] - 1.0).abs() < 1e-6);
}
#[test]
fn a_view_transform_preserves_interpolation_residuals_through_cancellation() {
let e = 2f32.powi(-40);
let view = [[1.0, 1.0, 0.0, 0.0], [1.0, 1.0, e, 0.0], [0.0, e, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let vertices = [[1.0, 1.0, 0.0], [0.0, 2f32.powi(-58), 0.0], [0.0; 3]].map(|normal| Vertex { normal, ..Vertex::default() });
let s = Scene { vertices: vertices.to_vec(), indices: vec![0, 1, 2], view, ..Scene::default() };
let t = STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri: 0,
front: true,
bbox: [0; 4],
};
let spent = AtomicU64::new(0);
let view_sign = crate::scene::det_sign3(&s.view).unwrap();
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign, fallback_tests: &FALLBACK_TESTS };
let n = b.view_normal(&t, [0.5, 0.25, 0.25]);
let expected = [std::f32::consts::FRAC_1_SQRT_2, -std::f32::consts::FRAC_1_SQRT_2, 0.0];
assert!(n.iter().zip(expected).all(|(x, y)| (x - y).abs() < 1e-5), "{n:?}");
let back = b.view_normal(&STri { front: false, ..t }, [0.5, 0.25, 0.25]);
assert_eq!(back, n.map(|x| -x));
}
#[test]
fn a_non_auxiliary_fallback_keeps_only_the_baseline_fragment_buffer() {
type BaselineFragment = (f32, [f32; 4], f32);
assert_eq!(std::mem::size_of::<FallbackFragment>(), std::mem::size_of::<BaselineFragment>());
assert_eq!(std::mem::size_of::<Option<FallbackFragment>>(), std::mem::size_of::<Option<BaselineFragment>>());
let s = Scene::default();
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 2, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
let pass = Pass { tris: &[], bins: &[] };
let vis = vec![(u32::MAX, super::EMPTY, [0.0; 3]); 2];
let baseline = b.fallback(pass, &vis, &[true; 2], false).unwrap();
assert_eq!(baseline.fragments.len(), 2);
assert!(baseline.aux.is_none());
let auxiliary = b.fallback(pass, &vis, &[true; 2], true).unwrap();
assert_eq!(auxiliary.aux.unwrap().len(), 2);
}
#[test]
fn auxiliary_depth_ties_preserve_coordinates_until_after_interpolation() {
let large = 2f32.powi(60);
let vertices = [1.0, 2.0].into_iter().flat_map(|z| [large, -large, 0.0].map(|x| Vertex { pos: [x, 0.0, z], ..Vertex::default() }));
let mut s = Scene { vertices: vertices.collect(), indices: vec![0, 1, 2, 3, 4, 5], ..Scene::default() };
s.view[2] = [1.0, 0.0, 1.0, 0.0];
let near = STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri: 0,
front: true,
bbox: [0; 4],
};
let far = STri { tri: 1, ..near };
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
let l = [0.5, 0.5, 0.0];
assert!(b.fragment_depth_tie_key(near.tri, &near.w, l).is_nearer_than(&b.fragment_depth_tie_key(far.tri, &far.w, l)));
}
#[test]
fn auxiliary_depth_ties_normalize_original_vertex_weights() {
let near_depth = 5.0f32;
let far_depth = f32::from_bits(near_depth.to_bits() + 1);
let vertices = [near_depth, far_depth].into_iter().flat_map(|z| [Vertex { pos: [0.0, 0.0, z], ..Vertex::default() }; 3]);
let mut s = Scene { vertices: vertices.collect(), indices: vec![0, 1, 2, 3, 4, 5], ..Scene::default() };
s.view[2] = [0.0, 0.0, 1.0, 0.0];
let near = STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri: 0,
front: true,
bbox: [0; 4],
};
let far = STri { tri: 1, ..near };
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
let near_l = [0.5 + 2f32.powi(-24), 0.25 + 2f32.powi(-25), 0.25];
let far_l = [0.5 - 2f32.powi(-25), 0.25 - 2f32.powi(-26), 0.25];
let unnormalized = |z, l: [f32; 3]| crate::scene::sum_of_products(l.map(|w| (f64::from(z), f64::from(w))));
assert!(unnormalized(near_depth, near_l) > unnormalized(far_depth, far_l));
assert!(b.fragment_depth_tie_key(near.tri, &near.w, near_l).is_nearer_than(&b.fragment_depth_tie_key(far.tri, &far.w, far_l)));
let near = STri { w: [near_l; 3], ..near };
let far = STri { w: [far_l; 3], ..far };
let l = [0.5, 0.25, 0.25];
assert!(b.fragment_depth_tie_key(near.tri, &near.w, l).is_nearer_than(&b.fragment_depth_tie_key(far.tri, &far.w, l)));
}
#[test]
fn equal_normalized_auxiliary_depths_keep_the_earlier_surface() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let s =
Scene { vertices: vec![Vertex { pos: [0.0, 0.0, 0.1], ..Vertex::default() }; 6], indices: (0..6).collect(), view, ..Scene::default() };
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
let triangles = [0, 1].map(point_triangle);
let weights = [[0.47058824, 0.5, 0.029411765], [0.7352941, 0.25, 0.014705882]];
let rounded =
|l: [f32; 3]| crate::scene::sum_of_products(l.map(|w| (f64::from(0.1f32), f64::from(w)))) / l.into_iter().map(f64::from).sum::<f64>();
assert_ne!(rounded(weights[0]), rounded(weights[1]), "the fixture must distinguish rounded normalized depths");
for [first, second] in [weights, [weights[1], weights[0]]] {
let mut depth = [f32::INFINITY];
let mut normal = [[0.0; 3]];
let mut part = [super::NO_PART];
let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part };
let n = [0.0, 0.0, 1.0];
row.offer(0, 0.1, (&triangles[0], first), &b, || n, 10);
row.offer(0, 0.1, (&triangles[1], second), &b, || n, 20);
assert_eq!(row.part[0], 10, "equal normalized depths replaced the earlier surface at {first:?}, {second:?}");
}
}
#[test]
fn auxiliary_depth_ties_keep_the_nearer_surface_in_f64() {
let (far, near) = ([2f32.powi(-25), 0.0, 1.0], [0.0, 0.0, 1.0]);
let vertices = [far, near].into_iter().flat_map(|pos| [Vertex { pos, ..Vertex::default() }; 3]).collect();
let mut s = Scene { vertices, indices: (0..6).collect(), ..Scene::default() };
s.view[2] = [1.0, 0.0, 1.0, 0.0];
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
assert_eq!(b.cam_z(far), b.cam_z(near));
assert!(b.depth_tie_key(near) < b.depth_tie_key(far));
let mut depth = [f32::INFINITY];
let mut normal = [[0.0; 3]];
let mut part = [super::NO_PART];
let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part };
let (far_triangle, near_triangle) = (point_triangle(0), point_triangle(1));
let (far_surface, near_surface) = ((&far_triangle, [1.0, 0.0, 0.0]), (&near_triangle, [1.0, 0.0, 0.0]));
let n = [1.0, 0.0, 0.0];
row.offer(0, b.cam_z(far), far_surface, &b, || n, 10);
row.offer(0, b.cam_z(near), near_surface, &b, || n, 20);
assert_eq!(row.part[0], 20);
row.offer(0, b.cam_z(far), far_surface, &b, || panic!("farther surface replaced the nearer one"), 10);
assert_eq!(row.part[0], 20);
row.set(0, b.cam_z(far), far_surface, n, 30);
row.offer(0, b.cam_z(near), near_surface, &b, || n, 20);
assert_eq!(row.part[0], 20);
row.offer(0, f32::NAN, far_surface, &b, || n, 40);
row.offer(0, b.cam_z(near), near_surface, &b, || panic!("NaN surface was replaced"), 20);
assert_eq!(row.part[0], 40);
assert!(row.depth[0].is_nan());
}
#[test]
fn auxiliary_depth_ties_ignore_large_camera_translations() {
let (near, far) = ([0.0, 0.0, 0.25], [0.0, 0.0, 0.5]);
let vertices = [far, near].into_iter().flat_map(|pos| [Vertex { pos, ..Vertex::default() }; 3]).collect();
let mut s = Scene { vertices, indices: (0..6).collect(), ..Scene::default() };
s.view[2] = [0.0, 0.0, 1.0, 2f32.powi(60)];
let spent = AtomicU64::new(0);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0, fallback_tests: &FALLBACK_TESTS };
assert_eq!(b.cam_z(near), b.cam_z(far));
let mut depth = [f32::INFINITY];
let mut normal = [[0.0; 3]];
let mut part = [super::NO_PART];
let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part };
let (far_triangle, near_triangle) = (point_triangle(0), point_triangle(1));
let (far_surface, near_surface) = ((&far_triangle, [1.0, 0.0, 0.0]), (&near_triangle, [1.0, 0.0, 0.0]));
let n = [1.0, 0.0, 0.0];
row.set(0, b.cam_z(far), far_surface, n, 10);
row.offer(0, b.cam_z(near), near_surface, &b, || n, 20);
assert_eq!(row.part[0], 20);
assert_eq!(row.depth[0], b.cam_z(near));
row.offer(0, b.cam_z(far), far_surface, &b, || panic!("farther surface replaced the nearer one"), 10);
assert_eq!(row.part[0], 20);
row.offer(0, b.cam_z(near), near_surface, &b, || panic!("equal depth replaced the surface"), 30);
assert_eq!(row.part[0], 20);
}
#[test]
fn a_view_whose_cofactors_nearly_cancel_still_turns_the_normal() {
// The view's determinant is −2^-60, and the rounded cofactors give the normal [1, 1, 0] a
// dot product of 0 with every row; the exact ones turn it to [1, 0, 0].
let e = 2f32.powi(-30);
let view = [[1.0, 1.0, 0.0, 0.0], [1.0, 1.0, e, 0.0], [0.0, e, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let v = Vertex { normal: [1.0, 1.0, 0.0], ..Vertex::default() };
let s = Scene { vertices: vec![v; 3], indices: vec![0, 1, 2], view, ..Scene::default() };
let t = STri {
p: [[0.0; 2]; 3],
z: [0.0; 3],
inv_w: [1.0; 3],
wide: false,
w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
tri: 0,
front: true,
bbox: [0; 4],
};
let spent = AtomicU64::new(0);
let view_sign = crate::scene::det_sign3(&s.view).unwrap_or(f64::NAN);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign, fallback_tests: &FALLBACK_TESTS };
assert_eq!(b.view_normal(&t, [1.0 / 3.0; 3]), [1.0, 0.0, 0.0]);
// A normal whose normalized components round by different amounts still turns exactly.
let view = [[1.0, 3.0, 0.0, 0.0], [1.0, 3.0, e, 0.0], [0.0, e, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let v = Vertex { normal: [1.0, 3.0, 0.0], ..Vertex::default() };
let s = Scene { vertices: vec![v; 3], indices: vec![0, 1, 2], view, ..Scene::default() };
let view_sign = crate::scene::det_sign3(&s.view).unwrap_or(f64::NAN);
let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign, fallback_tests: &FALLBACK_TESTS };
assert_eq!(b.view_normal(&t, [1.0 / 3.0; 3]), [1.0, 0.0, 0.0]);
}
#[test]
fn both_directions_of_an_edge_cross_at_the_same_corner_when_the_distances_tie() {
let a = ([3.0, 0.1, 0.5, 1.0], [1.0, 0.0, 0.0]);
+129 -13
View File
@@ -1,9 +1,9 @@
//! The box resolve of a supersampled target and the sRGB encoding of its pixels.
use crate::raster::{Target, try_render};
use crate::scene::Scene;
use crate::raster::{AuxPlanes, AuxTarget, Target, try_render, try_render_with_aux};
use crate::scene::{NO_PART, Scene};
use crate::shade::linear_to_srgb;
use crate::{Limits, RenderError, filled, for_each_chunk_pair, map_collect};
use crate::{Limits, RenderError, filled, for_each_chunk, for_each_chunk_pair, for_each_chunk_triple, map_collect};
/// An image of premultiplied RGBA pixels, row-major from the top row.
#[derive(Clone, Debug, PartialEq)]
@@ -13,6 +13,13 @@ pub struct Image {
pub data: Vec<[f32; 4]>,
}
/// A resolved image with its auxiliary outputs at the image's size.
#[derive(Clone, Debug, PartialEq)]
pub struct AuxImage {
pub image: Image,
pub aux: AuxPlanes,
}
/// Alpha above 1 that [`try_encode`] accepts as rounding from blending.
const ALPHA_SLACK: f32 = 1e-4;
@@ -33,6 +40,12 @@ fn area(w: u32, h: u32) -> Option<usize> {
/// [`RenderError::BadDataLength`] when the color or depth buffer does not hold width × height
/// values.
pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec<f32>), RenderError> {
let (image, depth) = resolve(t, k, true)?;
Ok((image, depth.unwrap_or_default()))
}
/// Box-filter the color and optionally store the mean depth.
fn resolve(t: &Target, k: u32, mean_depth: bool) -> Result<(Image, Option<Vec<f32>>), RenderError> {
if k == 0 || !t.width.is_multiple_of(k) || !t.height.is_multiple_of(k) {
return Err(RenderError::BadFactor { k, width: t.width, height: t.height });
}
@@ -46,7 +59,7 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec<f32>), RenderError>
// Fits: at most `expected`.
let out = area(w, h).unwrap_or(0);
let mut img = Image { width: w, height: h, data: filled(out, [0.0; 4])? };
let mut depth = filled(out, f32::INFINITY)?;
let mut depth = if mean_depth { Some(filled(out, f32::INFINITY)?) } else { None };
if out == 0 {
return Ok((img, depth));
}
@@ -54,10 +67,14 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec<f32>), RenderError>
// An f32 sum drops the low bits of each sample as it grows, so a block of more than
// `F32_SAMPLES` subsamples is averaged in f64.
let wide = u64::from(k) * u64::from(k) > F32_SAMPLES;
for_each_chunk_pair(&mut img.data, &mut depth, w as usize, |y, row, drow| {
for x in 0..w as usize {
let resolve_row = |y: usize, row: &mut [[f32; 4]], mut drow: Option<&mut [f32]>| -> Result<(), RenderError> {
for (x, pixel) in row.iter_mut().enumerate() {
let mut d = f32::INFINITY;
if wide {
(row[x], drow[x]) = mean_f64(t, k as usize, x, y);
(*pixel, d) = mean_f64(t, k as usize, x, y);
if let Some(drow) = &mut drow {
drow[x] = d;
}
continue;
}
let mut acc = [0.0f32; 4];
@@ -75,18 +92,74 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec<f32>), RenderError>
}
}
}
row[x] = acc.map(|v| v / n);
*pixel = acc.map(|v| v / n);
if dn > 0.0 {
drow[x] = dz / dn;
d = dz / dn;
}
// Large finite samples can overflow the f32 sums; such a pixel is averaged in f64.
if !row[x].iter().all(|v| v.is_finite()) || drow[x].is_nan() || (dn > 0.0 && drow[x].is_infinite()) {
(row[x], drow[x]) = mean_f64(t, k as usize, x, y);
if !pixel.iter().all(|v| v.is_finite()) || d.is_nan() || (dn > 0.0 && d.is_infinite()) {
(*pixel, d) = mean_f64(t, k as usize, x, y);
}
if let Some(drow) = &mut drow {
drow[x] = d;
}
}
Ok(())
};
if let Some(depth) = &mut depth {
for_each_chunk_pair(&mut img.data, depth, w as usize, |y, row, drow| resolve_row(y, row, Some(drow)))?;
} else {
for_each_chunk(&mut img.data, w as usize, |y, row| resolve_row(y, row, None))?;
}
Ok((img, depth))
}
/// Resolve a supersampled target and its auxiliary outputs down by `k` per side. The color is
/// [`try_resolve`]'s, bit for bit. Each output pixel's depth, normal and part ID are copied
/// together from one subsample of its `k × k` block: the one with the smallest finite depth, the
/// first in row-major order on ties. A block with no surface gives ∞, `[0, 0, 0]` and
/// [`NO_PART`]; depths are not averaged and IDs are not mixed. The resolve does not allocate a
/// mean-depth buffer.
///
/// Returns the errors of [`try_resolve`], and [`RenderError::BadDataLength`] when an auxiliary
/// plane does not hold width × height values.
pub fn try_resolve_aux(t: &AuxTarget, k: u32) -> Result<AuxImage, RenderError> {
let tt = &t.target;
if k == 0 || !tt.width.is_multiple_of(k) || !tt.height.is_multiple_of(k) {
return Err(RenderError::BadFactor { k, width: tt.width, height: tt.height });
}
let expected = area(tt.width, tt.height).ok_or(RenderError::TooLarge(tt.width, tt.height))?;
for found in [tt.color.len(), tt.depth.len(), t.aux.depth.len(), t.aux.normal.len(), t.aux.part_id.len()] {
if found != expected {
return Err(RenderError::BadDataLength { expected, found });
}
}
let (image, _) = resolve(tt, k, false)?;
let (w, out) = (image.width as usize, image.data.len());
let mut aux = AuxPlanes { depth: filled(out, f32::INFINITY)?, normal: filled(out, [0.0; 3])?, part_id: filled(out, NO_PART)? };
if out == 0 {
return Ok(AuxImage { image, aux });
}
let (k, tw) = (k as usize, tt.width as usize);
for_each_chunk_triple(&mut aux.depth, &mut aux.normal, &mut aux.part_id, w, |y, drow, nrow, prow| {
for x in 0..w {
let mut best: Option<usize> = None;
for j in 0..k {
for i in 0..k {
let s = (y * k + j) * tw + x * k + i;
let z = t.aux.depth[s];
if z.is_finite() && best.is_none_or(|b| z < t.aux.depth[b]) {
best = Some(s);
}
}
}
if let Some(s) = best {
(drow[x], nrow[x], prow[x]) = (t.aux.depth[s], t.aux.normal[s], t.aux.part_id[s]);
}
}
Ok(())
})?;
Ok((img, depth))
Ok(AuxImage { image, aux })
}
/// Output pixel (`x`, `y`) of a `k`-per-side resolve, summed in `f64`.
@@ -158,9 +231,52 @@ pub fn try_render_cpu(s: &Scene, limits: &Limits) -> Result<(Image, Vec<f32>), R
try_resolve(&try_render(s, limits)?, k)
}
/// [`try_render_with_aux`] and [`try_resolve_aux`] by the scene's supersampling factor, as
/// [`try_render_cpu`]: the image is [`try_render_cpu`]'s, bit for bit. The resolve's output
/// planes count toward the byte check of [`try_render_with_aux`], which runs before anything is
/// rendered.
pub fn try_render_cpu_with_aux(s: &Scene, limits: &Limits) -> Result<AuxImage, RenderError> {
let k = s.ssaa.max(1);
if !s.width.is_multiple_of(k) || !s.height.is_multiple_of(k) {
return Err(RenderError::BadFactor { k, width: s.width, height: s.height });
}
limits.check_aux(s.width, s.height, Some(k))?;
try_resolve_aux(&try_render_with_aux(s, limits)?, k)
}
#[cfg(test)]
mod tests {
use super::{Target, try_resolve};
use super::{AuxPlanes, AuxTarget, NO_PART, Target, resolve, try_resolve, try_resolve_aux};
#[test]
fn a_color_only_resolve_does_not_allocate_mean_depth() {
for depths in [[0.5; 4], [f32::MAX; 4], [f32::INFINITY; 4]] {
let t = Target { width: 2, height: 2, color: vec![[1.0; 4], [2f32.powi(-24); 4], [2f32.powi(-24); 4], [0.0; 4]], depth: depths.to_vec() };
for k in [1, 2] {
let (image, depth) = resolve(&t, k, false).unwrap();
let (expected, _) = try_resolve(&t, k).unwrap();
assert!(depth.is_none());
assert_eq!((image.width, image.height), (expected.width, expected.height));
let bits = |pixels: Vec<[f32; 4]>| pixels.into_iter().map(|p| p.map(f32::to_bits)).collect::<Vec<_>>();
assert_eq!(bits(image.data), bits(expected.data));
}
}
let empty = Target { width: 0, height: 2, color: vec![], depth: vec![] };
let (image, depth) = resolve(&empty, 2, false).unwrap();
assert!(image.data.is_empty());
assert!(depth.is_none());
}
#[test]
fn the_auxiliary_resolve_keeps_the_color_resolve() {
let n = 4u32;
let len = (n * n) as usize;
let t = Target { width: n, height: n, color: vec![[0.7; 4]; len], depth: vec![0.5; len] };
let (img, _) = try_resolve(&t, n).unwrap_or_else(|e| panic!("{e:?}"));
let aux = AuxPlanes { depth: vec![0.5; len], normal: vec![[0.0, 0.0, -1.0]; len], part_id: vec![NO_PART - 1; len] };
let a = try_resolve_aux(&AuxTarget { target: t, aux }, n).unwrap_or_else(|e| panic!("{e:?}"));
assert_eq!(a.image, img);
}
#[test]
fn a_large_block_of_one_color_resolves_to_that_color() {
+196
View File
@@ -211,6 +211,11 @@ pub struct Scene {
/// for a shadows-only material.
pub indices: Vec<u32>,
pub opaque_count: u32,
/// The part ID of each triangle, in the order of [`Scene::indices`]: one per three indices.
/// [`crate::try_render_with_aux`] reports it for the surface of each pixel, and a triangle cut
/// by clipping keeps its ID. Any value but [`NO_PART`] is an ID, 0 included. The renderers
/// without auxiliary outputs do not read it, and it may be empty for them.
pub part_ids: Vec<u32>,
pub materials: Vec<Material>,
pub textures: Vec<TexInfo>,
pub texels: Vec<[f32; 4]>,
@@ -223,6 +228,139 @@ pub struct Scene {
pub linear_io: bool,
}
/// The part ID of a pixel with no surface; [`Scene::part_ids`] may not hold it.
pub const NO_PART: u32 = u32::MAX;
/// Checks what the auxiliary outputs need beyond [`validate`]: one part ID per triangle, none of
/// them [`NO_PART`], and, when the scene has a triangle, a view whose upper-left 3 × 3 (the
/// transform of normals) is invertible.
pub(crate) fn validate_aux(s: &Scene) -> Result<(), RenderError> {
let expected = s.indices.len() / 3;
if s.part_ids.len() != expected {
return Err(RenderError::BadPartIdCount { expected, found: s.part_ids.len() });
}
if let Some(i) = s.part_ids.iter().position(|&p| p == NO_PART) {
return Err(RenderError::ReservedPartId(i));
}
if expected == 0 {
return Ok(());
}
if det_sign3(&s.view).is_none() {
return Err(RenderError::BadTransform);
}
Ok(())
}
/// Sums products using an exact expansion, barring overflow and underflow.
pub(crate) fn sum_of_products<const N: usize>(terms: [(f64, f64); N]) -> f64 {
product_expansion(terms).sum()
}
#[derive(Clone, Copy)]
pub(crate) struct ProductExpansion<const N: usize> {
storage: [[f64; 2]; N],
len: usize,
}
impl<const N: usize> ProductExpansion<N> {
pub(crate) fn terms(&self) -> &[f64] {
&self.storage.as_flattened()[..self.len]
}
pub(crate) fn sum(&self) -> f64 {
self.terms().iter().fold(0.0, |sum, &x| sum + x)
}
pub(crate) fn negated(mut self) -> Self {
for x in &mut self.storage.as_flattened_mut()[..self.len] {
*x = -*x;
}
self
}
}
/// The exact expansion terms of a sum of products, barring overflow and underflow.
pub(crate) fn product_expansion<const N: usize>(terms: [(f64, f64); N]) -> ProductExpansion<N> {
let mut storage = [[0.0f64; 2]; N];
let e = storage.as_flattened_mut();
let mut len = 0;
for (x, y) in terms {
if x == 0.0 || y == 0.0 {
continue;
}
let hi = x * y;
for part in [hi, x.mul_add(y, -hi)] {
if part == 0.0 {
continue;
}
let (used, q) = grow_expansion(&mut e[..len], part);
len = used;
if q != 0.0 {
e[len] = q;
len += 1;
}
}
}
// The components do not overlap and grow in magnitude.
ProductExpansion { storage, len }
}
/// Adds a nonzero component with exact two-sums, returning the nonzero prefix and final component.
fn grow_expansion(e: &mut [f64], mut q: f64) -> (usize, f64) {
let mut len = 0;
for i in 0..e.len() {
let c = e[i];
let sum = q + c;
let bv = sum - q;
let err = (q - (sum - bv)) + (c - bv);
if err != 0.0 {
e[len] = err;
len += 1;
}
q = sum;
}
(len, q)
}
/// The sign of an exact sum of products, barring overflow and underflow. Zero terms are omitted.
pub(crate) fn product_expansion_sign(terms: impl IntoIterator<Item = (f64, f64)>) -> f64 {
let mut e = Vec::new();
for (x, y) in terms {
if x == 0.0 || y == 0.0 {
continue;
}
let hi = x * y;
for part in [hi, x.mul_add(y, -hi)] {
if part == 0.0 {
continue;
}
let (len, q) = grow_expansion(&mut e, part);
e.truncate(len);
if q != 0.0 {
e.push(q);
}
}
}
e.last().map_or(0.0, |x| x.signum())
}
/// The sign of the determinant of the upper-left 3 × 3 of `m` (1 or −1), or `None` when the
/// determinant is 0 or an entry is not finite. The sign is exact: each of the six terms of the
/// expansion is an `f32` times an exact `f64` product of two `f32`s, summed with
/// [`sum_of_products`]. Rounded arithmetic can cancel an invertible matrix to 0 or leave a
/// singular one nonzero.
pub(crate) fn det_sign3(m: &[[f32; 4]]) -> Option<f64> {
let a = |r: usize, c: usize| m.get(r).map_or(f64::NAN, |row| f64::from(row[c]));
if !(0..3).all(|r| (0..3).all(|c| a(r, c).is_finite())) {
return None;
}
// Exact: two 24-bit significands fit an f64's 53.
let terms = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)]
.map(|(i, j, k, s)| (s * a(0, i), a(1, j) * a(2, k)));
let det = sum_of_products(terms);
(det != 0.0 && det.is_finite()).then_some(if det < 0.0 { -1.0 } else { 1.0 })
}
fn finite<const N: usize>(v: &[f32; N]) -> bool {
v.iter().all(|x| x.is_finite())
}
@@ -409,3 +547,61 @@ fn validate_shadows(s: &Scene) -> Result<(), RenderError> {
None => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::{Light, Scene, det_sign3, validate_aux, validate_lights};
use crate::{Limits, RenderError};
#[test]
fn every_light_kind_rejects_unknown_falloff() {
let light = Light {
kind: 0,
pos: [0.0; 3],
dir: [0.0, 0.0, -1.0],
color: [1.0; 3],
cos_inner: 1.0,
cos_outer: 0.0,
falloff: 3,
radius: 0.0,
falloff_distance: 0.0,
shadow: -1,
shadow_darkness: 0.0,
shadow_diffusion: 0.0,
};
let mut s = Scene { lights: vec![light], ..Scene::default() };
let limits = Limits::default();
for kind in [0, 1, 2] {
s.lights[0].kind = kind;
assert!(matches!(validate_lights(&s, &limits), Err(RenderError::BadLight(0))));
for falloff in 0..=2 {
s.lights[0].falloff = falloff;
assert!(validate_lights(&s, &limits).is_ok());
}
s.lights[0].falloff = 3;
}
}
fn with_view(rows: [[f32; 3]; 3]) -> Scene {
let [a, b, c] = rows.map(|r| [r[0], r[1], r[2], 0.0]);
let view = [a, b, c, [0.0, 0.0, 0.0, 1.0]];
Scene { indices: vec![0, 1, 2], part_ids: vec![0], view, ..Scene::default() }
}
#[test]
fn a_view_whose_determinant_terms_cancel_is_still_invertible() {
let e = 2f32.powi(-30);
let cancel = with_view([[1.0, 1.0, 0.0], [1.0, 1.0, e], [0.0, e, 1.0]]);
assert!(validate_aux(&cancel).is_ok());
// The determinant is −2^-60.
assert_eq!(det_sign3(&cancel.view), Some(-1.0));
assert!(validate_aux(&with_view([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])).is_ok());
let dup = validate_aux(&with_view([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [0.0, 0.0, 1.0]]));
assert!(matches!(dup, Err(RenderError::BadTransform)), "{dup:?}");
// Rounded elimination leaves a nonzero pivot here: 1/49 × 49 rounds below 1.
let scaled = validate_aux(&with_view([[49.0, 49.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0]]));
assert!(matches!(scaled, Err(RenderError::BadTransform)), "{scaled:?}");
assert_eq!(det_sign3(&with_view([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]).view), Some(-1.0));
assert_eq!(det_sign3(&with_view([[2.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 0.5]]).view), Some(1.0));
}
}
+39
View File
@@ -744,6 +744,45 @@ mod tests {
}
}
fn point_light(pos: [f32; 3], falloff: u32, radius: f32) -> Light {
Light {
kind: 2,
pos,
dir: [0.0, 0.0, 1.0],
color: [1.0; 3],
cos_inner: 1.0,
cos_outer: 1.0,
falloff,
radius,
falloff_distance: 0.0,
shadow: -1,
shadow_darkness: 0.0,
shadow_diffusion: 0.0,
}
}
#[test]
fn a_light_difference_that_overflows_f32_is_taken_in_f64() {
let l = point_light([2e38, 0.0, 0.0], 0, 0.0);
let (d, len) = to_light(&l, [-2e38, 0.0, 0.0]);
assert_eq!(d, [1.0, 0.0, 0.0]);
assert!(len.is_infinite() || len > 3e38, "{len}");
}
#[test]
fn an_overflowing_perspective_denominator_compares_like_a_scaled_down_receiver() {
// Scaling the receiver, its depth and the texels by 2^126 keeps every ratio, but
// focal × z overflows f32 at that scale.
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
let m = ShadowMap { view, focal: 4.0, ortho: false, size: 16, offset: 0, bias: 0.0, radius: 0.0 };
let ng = [0.6, 0.0, -0.8];
let k = f32::from_bits(253 << 23); // 2^126
let small = shadow_factor(&m, &vec![0.95; 256], [0.0, 0.0, 1.0], ng, 1.0);
let big = shadow_factor(&m, &vec![0.95 * k; 256], [0.0, 0.0, k], ng, 1.0);
assert!(small > 0.0 && small < 1.0, "{small}");
assert!((big - small).abs() < 1e-6, "{big} vs {small}");
}
#[test]
fn overflowing_footprints_preserve_populated_shadow_comparisons() {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
+519
View File
@@ -0,0 +1,519 @@
//! The auxiliary outputs: camera depth, view-space normal and part ID of each pixel's surface.
use craft_raster3d::{
AuxImage, AuxPlanes, AuxTarget, Limits, Material, NO_PART, RenderError, Scene, TexInfo, Vertex, try_render, try_render_cpu,
try_render_cpu_with_aux, try_render_with_aux, try_resolve_aux, try_shadow_maps,
};
use crate::{bits, bits4, limits, lit_scene, quad_scene};
/// `s` with part ID `i` for triangle `i`.
fn with_ids(mut s: Scene) -> Scene {
s.part_ids = (0..s.indices.len() as u32 / 3).collect();
s
}
/// The quad scenes of `differential.rs`.
fn quad_scenes() -> Vec<(&'static str, Scene)> {
let red = [1.0, 0.0, 0.0, 1.0];
let blue = [0.0, 0.0, 1.0, 1.0];
vec![
("overlap", quad_scene(40, 30, &[([0.0, 0.0, 30.0, 20.0], 500.0, blue), ([10.0, 10.0, 40.0, 30.0], 100.0, red)])),
("half-alpha quad", quad_scene(32, 32, &[([4.0, 4.0, 20.0, 12.0], 10.0, [1.0, 1.0, 1.0, 0.5])])),
(
"two transparent layers",
quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 100.0, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 8.0, 8.0], 50.0, [0.0, 0.0, 1.0, 0.5])]),
),
(
"past the edges",
quad_scene(
24,
16,
&[
([-30.0, -5.0, 10.0, 40.0], 300.0, red),
([5.0, 3.0, 90.0, 12.0], 200.0, [0.0, 1.0, 0.0, 0.5]),
([30.0, 0.0, 40.0, 8.0], 1.0, blue),
],
),
),
]
}
/// The lit scenes of `differential.rs`, with their shadow maps.
fn lit_scenes() -> Vec<(&'static str, Scene)> {
let mut out = vec![];
for (name, out_size, ssaa, ortho, draft) in [
("lit perspective", (48, 36), 1, false, false),
("lit perspective 2x2", (32, 24), 2, false, false),
("lit orthographic draft", (40, 30), 1, true, true),
] {
let mut s = lit_scene(out_size, ssaa, ortho);
try_shadow_maps(&mut s, draft, &Limits::default()).unwrap();
out.push((name, s));
}
out
}
/// Every plane marks the same pixels as having a surface, and those are the pixels with alpha
/// above 0 in `color`.
fn assert_same_coverage(name: &str, color: &[[f32; 4]], aux: &AuxPlanes) {
assert_eq!(aux.depth.len(), color.len(), "{name}: depth length");
assert_eq!(aux.normal.len(), color.len(), "{name}: normal length");
assert_eq!(aux.part_id.len(), color.len(), "{name}: part length");
for (i, c) in color.iter().enumerate() {
let covered = c[3] > 0.0;
assert_eq!(aux.depth[i].is_finite(), covered, "{name}: depth at {i}");
assert_eq!(aux.part_id[i] != NO_PART, covered, "{name}: part at {i}");
let n = aux.normal[i];
if covered {
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
assert!((len - 1.0).abs() < 1e-5, "{name}: normal at {i} has length {len}");
} else {
assert_eq!(n, [0.0; 3], "{name}: normal at {i}");
}
}
}
/// With and without auxiliary outputs, the target, the image and its depth are the same bit for
/// bit, and the auxiliary planes cover the pixels the color covers.
fn check_scene(name: &str, s: &Scene) {
let s = with_ids(s.clone());
let t = try_render(&s, &Limits::default()).unwrap();
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
assert_eq!(bits4(&a.target.color), bits4(&t.color), "{name}: color");
assert_eq!(bits(&a.target.depth), bits(&t.depth), "{name}: depth");
assert!(a.aux.part_id.iter().any(|&p| p != NO_PART), "{name}: nothing drawn");
assert_same_coverage(name, &a.target.color, &a.aux);
let (img, _) = try_render_cpu(&s, &Limits::default()).unwrap();
let r = try_render_cpu_with_aux(&s, &Limits::default()).unwrap();
assert_eq!((r.image.width, r.image.height), (img.width, img.height), "{name}: image size");
assert_eq!(bits4(&r.image.data), bits4(&img.data), "{name}: resolved color");
assert_same_coverage(name, &r.image.data, &r.aux);
}
#[test]
fn every_output_covers_the_pixels_the_color_covers() {
for (name, s) in quad_scenes().into_iter().chain(lit_scenes()) {
check_scene(name, &s);
}
}
#[test]
fn an_empty_scene_has_no_surface() {
let s = Scene { width: 5, height: 3, ..Scene::default() };
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
assert_eq!(a.target, try_render(&s, &Limits::default()).unwrap());
assert_eq!(a.aux, AuxPlanes { depth: vec![f32::INFINITY; 15], normal: vec![[0.0; 3]; 15], part_id: vec![NO_PART; 15] });
}
/// A perspective camera at (0, 0, −500) looking along +z (+y down), as in `lit_scene`, with one
/// unlit, single-sided material.
fn perspective(w: u32, h: u32) -> Scene {
let base = lit_scene((w, h), 1, false);
let mut s = Scene {
width: w,
height: h,
ssaa: 1,
clip: base.clip,
view: base.view,
eye: base.eye,
cam_fwd: base.cam_fwd,
linear_io: true,
..Scene::default()
};
s.materials.push(Material { unlit: true, ..Material::default() });
s
}
/// Appends a front-facing quad through `c` (clockwise in world x/y with y down, so
/// counterclockwise on the screen) with `normal` and material `m` as two opaque triangles.
fn push_quad(s: &mut Scene, c: [[f32; 3]; 4], normal: [f32; 3], m: u32) {
let b = s.vertices.len() as u32;
for p in c {
s.vertices.push(Vertex { pos: p, normal, uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: m });
}
s.indices.extend([b, b + 2, b + 1, b, b + 3, b + 2]);
}
#[test]
fn depth_rises_along_a_tilted_plane() {
let mut s = perspective(64, 48);
// A plane that recedes from z = 0 on the left to z = 600 on the right.
push_quad(&mut s, [[-300.0, -200.0, 0.0], [300.0, -200.0, 600.0], [300.0, 200.0, 600.0], [-300.0, 200.0, 0.0]], [-0.707, 0.0, -0.707], 0);
s.opaque_count = s.indices.len() as u32;
let a = try_render_with_aux(&with_ids(s), &Limits::default()).unwrap();
let row: Vec<f32> = a.aux.depth[24 * 64..25 * 64].iter().copied().filter(|d| d.is_finite()).collect();
assert!(row.len() > 40, "{} pixels drawn", row.len());
assert!(row.windows(2).all(|p| p[1] > p[0]), "{row:?}");
// Camera depth is the view's z: from 500 (z = 0) toward 1100 (z = 600).
assert!(row[0] >= 500.0 && row[row.len() - 1] <= 1100.0, "{row:?}");
}
/// A sphere of radius `r` around `c`, single-sided and wound to face outward, with unit
/// outward vertex normals.
fn push_sphere(s: &mut Scene, c: [f32; 3], r: f32, m: u32) {
let (stacks, slices) = (32u32, 64u32);
let b = s.vertices.len() as u32;
for i in 0..=stacks {
let th = std::f32::consts::PI * i as f32 / stacks as f32;
for j in 0..=slices {
let ph = std::f32::consts::TAU * j as f32 / slices as f32;
let n = [th.sin() * ph.cos(), th.cos(), th.sin() * ph.sin()];
s.vertices.push(Vertex {
pos: [c[0] + r * n[0], c[1] + r * n[1], c[2] + r * n[2]],
normal: n,
uv: [0.0; 2],
tangent: [1.0, 0.0, 0.0, 1.0],
material: m,
});
}
}
let at = |i: u32, j: u32| b + i * (slices + 1) + j;
for i in 0..stacks {
for j in 0..slices {
for t in [[at(i, j), at(i + 1, j), at(i + 1, j + 1)], [at(i, j), at(i + 1, j + 1), at(i, j + 1)]] {
let p = t.map(|k| s.vertices[k as usize].pos);
let (u, v) = ([p[1][0] - p[0][0], p[1][1] - p[0][1], p[1][2] - p[0][2]], [p[2][0] - p[0][0], p[2][1] - p[0][1], p[2][2] - p[0][2]]);
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let mid = [0, 1, 2].map(|k| (p[0][k] + p[1][k] + p[2][k]) / 3.0 - c[k]);
if n == [0.0; 3] {
continue;
}
let outward = n[0] * mid[0] + n[1] * mid[1] + n[2] * mid[2] > 0.0;
s.indices.extend(if outward { t } else { [t[0], t[2], t[1]] });
}
}
}
}
/// An orthographic 32 × 32 scene (world x/y = pixels, camera depth = z) holding a sphere of
/// radius 12 around (16, 16, 500), and its expected outward unit normal at a pixel center well
/// inside the outline.
fn sphere_scene() -> (Scene, impl Fn(usize, usize) -> Option<[f32; 3]>) {
let mut s = quad_scene(32, 32, &[]);
s.materials.push(Material { unlit: true, ..Material::default() });
push_sphere(&mut s, [16.0, 16.0, 500.0], 12.0, 0);
s.opaque_count = s.indices.len() as u32;
let expected = |x: usize, y: usize| {
let (dx, dy) = ((x as f32 + 0.5 - 16.0) / 12.0, (y as f32 + 0.5 - 16.0) / 12.0);
let rr = dx * dx + dy * dy;
(rr < 0.8 * 0.8).then(|| [dx, dy, -(1.0 - rr).sqrt()])
};
(with_ids(s), expected)
}
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
#[test]
fn sphere_normals_point_outward() {
let (s, expected) = sphere_scene();
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
let mut checked = 0;
for y in 0..32 {
for x in 0..32 {
if let Some(e) = expected(x, y) {
let n = a.aux.normal[y * 32 + x];
assert!(dot(n, e) > 0.995, "({x}, {y}): {n:?} against {e:?}");
checked += 1;
}
}
}
assert!(checked > 200, "{checked} pixels checked");
}
#[test]
fn normals_are_turned_by_the_view() {
// The view turns a quarter turn about z: x → y, y → −x. Depth (the third row) is unchanged.
let (mut s, expected) = sphere_scene();
s.view = [[0.0, -1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
let e = expected(22, 16).unwrap();
let n = a.aux.normal[16 * 32 + 22];
assert!(dot(n, [-e[1], e[0], e[2]]) > 0.995, "{n:?} against {e:?}");
// A uniform scale in the view does not change the unit normal.
s.view = [[0.0, -3.0, 0.0, 0.0], [3.0, 0.0, 0.0, 0.0], [0.0, 0.0, 3.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let b = try_render_with_aux(&s, &Limits::default()).unwrap();
assert!((dot(b.aux.normal[16 * 32 + 22], n) - 1.0).abs() < 1e-6);
}
#[test]
fn a_view_that_stretches_and_mirrors_keeps_normals_perpendicular_to_the_surface() {
// The view doubles x and mirrors it. A surface's tangents turn by that 3 × 3, so its normal
// turns by the inverse transpose, diag(−1/2, 1, 1), and keeps facing outward.
let (mut s, expected) = sphere_scene();
s.view = [[-2.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
let mut checked = 0;
for y in 0..32 {
for x in 0..32 {
if let Some(e) = expected(x, y) {
let t = [-e[0] / 2.0, e[1], e[2]];
let len = dot(t, t).sqrt();
let t = t.map(|v| v / len);
let n = a.aux.normal[y * 32 + x];
assert!(dot(n, t) > 0.995, "({x}, {y}): {n:?} against {t:?}");
checked += 1;
}
}
}
assert!(checked > 200, "{checked} pixels checked");
}
#[test]
fn a_double_sided_back_face_reports_the_reversed_normal_and_a_zero_normal_reads_as_toward_the_camera() {
let mut s = quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 100.0, [1.0; 4])]);
// quad_scene's quads face the camera; reversing the winding shows their back.
for t in s.indices.chunks_mut(3) {
t.swap(1, 2);
}
s.vertices.iter_mut().for_each(|v| v.normal = [0.3, 0.0, -0.4]);
let a = try_render_with_aux(&with_ids(s.clone()), &Limits::default()).unwrap();
assert!(a.aux.normal.iter().all(|n| dot(*n, [-0.6, 0.0, 0.8]) > 0.99999), "{:?}", a.aux.normal[0]);
s.vertices.iter_mut().for_each(|v| v.normal = [0.0; 3]);
let a = try_render_with_aux(&with_ids(s), &Limits::default()).unwrap();
assert!(a.aux.normal.iter().all(|n| *n == [0.0, 0.0, 1.0]), "{:?}", a.aux.normal[0]);
}
#[test]
fn part_ids_separate_two_meshes_whatever_their_order() {
let red = [1.0, 0.0, 0.0, 1.0];
let blue = [0.0, 0.0, 1.0, 1.0];
// Blue (far, left) and red (near, right) overlap in x 10 to 30.
let mut s = quad_scene(40, 30, &[([0.0, 0.0, 30.0, 20.0], 500.0, blue), ([10.0, 10.0, 40.0, 30.0], 100.0, red)]);
s.part_ids = vec![7, 7, 0, 0];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
let at = |a: &AuxTarget, x: usize, y: usize| (a.aux.part_id[y * 40 + x], a.aux.depth[y * 40 + x]);
assert_eq!(at(&a, 5, 5), (7, 500.0));
assert_eq!(at(&a, 20, 15), (0, 100.0));
assert_eq!(at(&a, 35, 25), (0, 100.0));
assert_eq!(at(&a, 35, 5), (NO_PART, f32::INFINITY));
// The same quads in the other order.
let mut swapped = s.clone();
swapped.indices = s.indices[6..].iter().chain(&s.indices[..6]).copied().collect();
swapped.part_ids = vec![0, 0, 7, 7];
let b = try_render_with_aux(&swapped, &Limits::default()).unwrap();
assert_eq!(b.aux.part_id, a.aux.part_id);
}
#[test]
fn a_clipped_triangle_keeps_its_part_id() {
// The lit scene's floor (triangles 0 and 1) crosses the near plane and reaches past the
// viewport, so it is clipped into several triangles.
let s = with_ids(lit_scene((48, 36), 1, false));
let a = try_render_with_aux(&Scene { lights: vec![], env: None, ..s }, &Limits::default()).unwrap();
for x in 0..48 {
assert!(a.aux.part_id[35 * 48 + x] <= 1, "bottom row at {x}: {}", a.aux.part_id[35 * 48 + x]);
}
}
#[test]
fn a_transparent_fragment_that_adds_alpha_is_the_surface() {
let grey = [0.5, 0.5, 0.5, 1.0];
let glass = [0.0, 0.0, 1.0, 0.25];
// Glass in front of an opaque quad on the left half; glass over nothing on the right half.
let mut s = quad_scene(8, 4, &[([0.0, 0.0, 4.0, 4.0], 300.0, grey), ([0.0, 0.0, 8.0, 4.0], 100.0, glass)]);
s.part_ids = vec![3, 3, 9, 9];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
assert_eq!((a.aux.part_id[1], a.aux.depth[1]), (9, 100.0));
assert_eq!((a.aux.part_id[6], a.aux.depth[6]), (9, 100.0));
// The opaque depth of the target is unchanged.
assert_eq!((a.target.depth[1], a.target.depth[6]), (300.0, f32::INFINITY));
// Glass behind the opaque quad is hidden: the opaque quad stays the surface.
let mut s = quad_scene(8, 4, &[([0.0, 0.0, 4.0, 4.0], 100.0, grey), ([0.0, 0.0, 8.0, 4.0], 300.0, glass)]);
s.part_ids = vec![3, 3, 9, 9];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
assert_eq!((a.aux.part_id[1], a.aux.part_id[6]), (3, 9));
}
#[test]
fn transparent_depth_ties_use_original_positions_before_f32_interpolation() {
let (near, far) = (5.0f32, f32::from_bits(5.0f32.to_bits() + 1));
for (first, second, ids) in [(far, near, vec![10, 10, 20, 20]), (near, far, vec![20, 20, 10, 10])] {
let mut s = quad_scene(3, 3, &[([0.0, 0.0, 3.0, 3.0], first, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 3.0, 3.0], second, [0.0, 0.0, 1.0, 0.5])]);
s.part_ids = ids;
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
let pixel = 3;
assert!(a.target.color[pixel][0] > 0.0 && a.target.color[pixel][2] > 0.0);
assert_eq!(a.aux.part_id[pixel], 20);
}
}
#[test]
fn of_several_transparent_layers_the_nearest_is_the_surface() {
// Drawn back to front, and also in the wrong order: the nearer layer is the surface either way.
for (first, second) in [(100.0, 50.0), (50.0, 100.0)] {
let mut s = quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], first, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 8.0, 8.0], second, [0.0, 0.0, 1.0, 0.5])]);
s.part_ids = vec![1, 1, 2, 2];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
let id = if second < first { 2 } else { 1 };
assert!(a.aux.part_id.iter().all(|&p| p == id), "depths {first} then {second}: {:?}", a.aux.part_id);
assert!(a.aux.depth.iter().all(|&d| d == 50.0));
}
}
#[test]
fn a_fragment_that_adds_no_alpha_is_not_the_surface() {
// A shadows-only card with no light draws nothing (alpha 0) over an opaque quad and over
// nothing.
let mut s = quad_scene(8, 4, &[([0.0, 0.0, 4.0, 4.0], 300.0, [0.5, 0.5, 0.5, 1.0])]);
let m = s.materials.len() as u32;
s.materials.push(Material { shadows_only: true, double_sided: true, ..Material::default() });
s.materials[0].unlit = true;
s.ambient = [0.0; 3];
let b = s.vertices.len() as u32;
for (x, y) in [(0.0, 0.0), (8.0, 0.0), (8.0, 4.0), (0.0, 4.0)] {
s.vertices.push(Vertex { pos: [x, y, 100.0], normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: m });
}
s.indices.extend([b, b + 2, b + 1, b, b + 3, b + 2]);
s.part_ids = vec![3, 3, 9, 9];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
assert_eq!(bits4(&a.target.color), bits4(&try_render(&s, &Limits::default()).unwrap().color));
assert_eq!((a.aux.part_id[1], a.aux.depth[1]), (3, 300.0));
assert_eq!((a.aux.part_id[6], a.aux.depth[6]), (NO_PART, f32::INFINITY));
}
#[test]
fn a_masked_out_fragment_hands_the_surface_to_the_one_behind() {
// A near opaque quad whose mask texture is clear on its left half, over a far quad.
let mut s = quad_scene(8, 4, &[([0.0, 0.0, 8.0, 4.0], 100.0, [1.0; 4]), ([0.0, 0.0, 8.0, 4.0], 300.0, [0.5, 0.5, 0.5, 1.0])]);
s.texels = vec![[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0]];
s.textures = vec![TexInfo { offset: 0, width: 2, height: 1, wrap_u: 1, wrap_v: 1 }];
s.materials[0].alpha_mode = 1;
s.materials[0].tex_base = 0;
// u runs 0 to 1 across the near quad.
for (k, v) in s.vertices[..4].iter_mut().enumerate() {
v.uv = [if k == 1 || k == 2 { 1.0 } else { 0.0 }, 0.0];
v.normal = [0.0, 0.6, -0.8];
}
s.part_ids = vec![5, 5, 6, 6];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
assert_eq!((a.aux.part_id[0], a.aux.depth[0], a.aux.normal[0]), (6, 300.0, [0.0, 0.0, -1.0]));
assert_eq!((a.aux.part_id[7], a.aux.depth[7]), (5, 100.0));
assert!(dot(a.aux.normal[7], [0.0, 0.6, -0.8]) > 0.99999);
assert_eq!(a.target.depth[0], 300.0);
}
#[test]
fn a_zero_area_triangle_has_no_surface() {
let mut s = quad_scene(8, 8, &[]);
s.materials.push(Material { unlit: true, double_sided: true, ..Material::default() });
for p in [[1.0, 1.0, 10.0], [4.0, 4.0, 10.0], [7.0, 7.0, 10.0]] {
s.vertices.push(Vertex { pos: p, normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: 0 });
}
s.indices = vec![0, 1, 2];
s.opaque_count = 3;
s.part_ids = vec![4];
let a = try_render_with_aux(&s, &Limits::default()).unwrap();
assert!(a.aux.part_id.iter().all(|&p| p == NO_PART));
assert!(a.target.color.iter().all(|c| c[3] == 0.0));
}
#[test]
fn a_resolve_copies_the_nearest_subsample_of_each_block_whole() {
// At 2 × 2, a near quad's edge at x = 5 splits output pixel 2 between it and a far quad.
let mut s = quad_scene(16, 8, &[([0.0, 0.0, 16.0, 8.0], 500.0, [0.0, 0.0, 1.0, 1.0]), ([5.0, 0.0, 16.0, 8.0], 100.0, [1.0, 0.0, 0.0, 1.0])]);
s.ssaa = 2;
s.part_ids = vec![1, 1, 2, 2];
let t = try_render_with_aux(&s, &Limits::default()).unwrap();
let r = try_resolve_aux(&t, 2).unwrap();
assert_eq!(r, try_render_cpu_with_aux(&s, &Limits::default()).unwrap());
for y in 0..4 {
for x in 0..8 {
let block: Vec<usize> = (0..2).flat_map(|j| (0..2).map(move |i| (2 * y + j) * 16 + 2 * x + i)).collect();
let best = block.iter().copied().min_by(|&a, &b| t.aux.depth[a].total_cmp(&t.aux.depth[b])).unwrap();
let o = y * 8 + x;
assert_eq!(
(r.aux.depth[o], r.aux.normal[o], r.aux.part_id[o]),
(t.aux.depth[best], t.aux.normal[best], t.aux.part_id[best]),
"({x}, {y})"
);
}
}
// Pixel 2 mixes both colors but reports one surface, the near quad, with its depth.
assert_eq!((r.aux.part_id[2], r.aux.depth[2]), (2, 100.0));
assert!(r.image.data[2][0] > 0.0 && r.image.data[2][2] > 0.0);
}
#[test]
fn a_resolve_breaks_depth_ties_by_the_first_subsample() {
let planes = |ids: [u32; 4]| AuxPlanes { depth: vec![7.0; 4], normal: vec![[0.0, 0.0, -1.0]; 4], part_id: ids.to_vec() };
let t = AuxTarget {
target: craft_raster3d::Target { width: 2, height: 2, color: vec![[1.0; 4]; 4], depth: vec![7.0; 4] },
aux: planes([4, 3, 2, 1]),
};
let AuxImage { aux, .. } = try_resolve_aux(&t, 2).unwrap();
assert_eq!(aux.part_id, vec![4]);
}
#[test]
fn a_resolve_rejects_planes_of_the_wrong_length_and_a_bad_factor() {
let s = with_ids(quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 10.0, [1.0; 4])]));
let t = try_render_with_aux(&s, &Limits::default()).unwrap();
for f in [
|t: &mut AuxTarget| t.aux.depth.pop().map(drop),
|t: &mut AuxTarget| t.aux.normal.pop().map(drop),
|t: &mut AuxTarget| t.aux.part_id.pop().map(drop),
] {
let mut bad = t.clone();
f(&mut bad);
assert_eq!(try_resolve_aux(&bad, 2), Err(RenderError::BadDataLength { expected: 16, found: 15 }));
}
assert_eq!(try_resolve_aux(&t, 3), Err(RenderError::BadFactor { k: 3, width: 4, height: 4 }));
assert_eq!(try_resolve_aux(&t, 0), Err(RenderError::BadFactor { k: 0, width: 4, height: 4 }));
}
#[test]
fn part_ids_must_name_every_triangle_with_an_unreserved_id() {
let s = quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 10.0, [1.0; 4])]);
assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::BadPartIdCount { expected: 2, found: 0 }));
let s = Scene { part_ids: vec![1, 2, 3], ..s };
assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::BadPartIdCount { expected: 2, found: 3 }));
let s = Scene { part_ids: vec![0, NO_PART], ..s };
assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::ReservedPartId(1)));
assert_eq!(try_render_cpu_with_aux(&s, &Limits::default()), Err(RenderError::ReservedPartId(1)));
// The renderers without auxiliary outputs do not read them.
assert!(try_render(&s, &Limits::default()).is_ok());
}
#[test]
fn a_view_that_cannot_turn_normals_is_rejected() {
let mut s = with_ids(quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 10.0, [1.0; 4])]));
s.view = [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::BadTransform));
assert!(try_render(&s, &Limits::default()).is_ok());
}
#[test]
fn the_byte_check_counts_the_auxiliary_planes() {
// The base target's 40 bytes per pixel fit `isize::MAX`, and the auxiliary render's 136 do not.
let l = limits(|l| l.max_pixels = u64::MAX);
#[cfg(target_pointer_width = "64")]
let (w, h, resolve_h) = (1 << 30, 150_000_000, 60_000_000);
#[cfg(target_pointer_width = "32")]
let (w, h, resolve_h) = (1 << 20, 40, 12);
assert!(l.check(w, h).is_ok());
let s = Scene { width: w, height: h, ..Scene::default() };
assert_eq!(try_render_with_aux(&s, &l), Err(RenderError::TooLarge(w, h)));
assert_eq!(try_render_cpu_with_aux(&s, &l), Err(RenderError::TooLarge(w, h)));
// The smaller raster fits, and its resolve at 1 × 1 adds 36 bytes per output pixel.
let s = Scene { width: w, height: resolve_h, ..Scene::default() };
assert_eq!(try_render_cpu_with_aux(&s, &l), Err(RenderError::TooLarge(w, resolve_h)));
}
#[test]
fn the_auxiliary_pass_obeys_the_fallback_work_limit() {
let white = [1.0; 4];
let mut s = with_ids(quad_scene(4, 32, &[([0.0, 0.0, 4.0, 32.0], 100.0, white), ([0.0, 0.0, 4.0, 32.0], 50.0, white)]));
s.materials[1].alpha_mode = 1;
s.materials[1].base[3] = 0.0;
let setup = 4 * (4 * 32 + 1);
let limited = limits(|l| l.max_work = setup);
assert!(try_render_with_aux(&s, &limits(|l| l.max_work = u64::MAX)).is_ok());
assert!(matches!(try_render_with_aux(&s, &limited), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed > setup));
assert!(matches!(try_render_cpu_with_aux(&s, &limited), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed > setup));
s.materials[1].base[3] = 1.0;
assert!(try_render_with_aux(&s, &limited).is_ok());
assert!(try_render_cpu_with_aux(&s, &limited).is_ok());
}
+6 -1
View File
@@ -1024,7 +1024,12 @@ fn negative_shadow_diffusion_is_rejected() {
try_shadow_maps(&mut s, false, &Limits::default()).unwrap();
assert!(try_render(&s, &Limits::default()).is_ok());
let e = EnvInfo { sun: [0.0, -1.0, 0.0], ..s.env.unwrap() };
assert_eq!(try_env_shadow_map(e, [0.0; 3], 100.0, 512).map(|m| m.radius), Ok(8.0));
let base = try_env_shadow_map(e, [0.0; 3], 100.0, 512).map(|m| m.radius);
assert_eq!(base, Ok(8.0));
// A positive diffusion widens the penumbra past that minimum.
let wide = EnvInfo { shadow_diffusion: 4.0, ..e };
let widened = try_env_shadow_map(wide, [0.0; 3], 100.0, 512).map(|m| m.radius);
assert!(widened.as_ref().is_ok_and(|&r| r > 8.0), "{widened:?}");
}
#[test]
+13 -2
View File
@@ -3,11 +3,21 @@
//! pixel matches bit for bit; the README's Origin section lists the scenes that differ. Each test
//! prints the 64-bit FNV-1a hash of each output from both sides.
use craft_raster3d::{Limits, Scene, try_encode, try_render, try_render_cpu, try_resolve, try_shadow_maps};
use craft_raster3d::{Limits, Scene, ShadowMap, try_encode, try_render, try_render_cpu, try_resolve, try_shadow_maps};
use crate::reference::effectcraft as ec;
use crate::{bits, bits4, fnv, lit_scene, quad_scene};
/// A shadow map's fields, with each float as its bits.
type MapBits = ([[u32; 4]; 3], u32, bool, u32, u32, u32, u32);
/// The fields of each shadow map, with the floats as bits so that 0 and −0 differ.
fn map_bits(maps: &[ShadowMap]) -> Vec<MapBits> {
maps.iter()
.map(|m| (m.view.map(|r| r.map(f32::to_bits)), m.focal.to_bits(), m.ortho, m.size, m.offset, m.bias.to_bits(), m.radius.to_bits()))
.collect()
}
/// Runs both sides on `scene`: shadow maps (when `shadows`), the raster, the resolve and the
/// encoding, and asserts that every output matches bit for bit.
fn compare(name: &str, scene: &Scene, shadows: Option<bool>) {
@@ -15,7 +25,7 @@ fn compare(name: &str, scene: &Scene, shadows: Option<bool>) {
if let Some(draft) = shadows {
try_shadow_maps(&mut ours, draft, &Limits::default()).unwrap();
ec::raster::shadow_maps(&mut theirs, draft);
assert_eq!(ours.shadows, theirs.shadows, "{name}: shadow maps");
assert_eq!(map_bits(&ours.shadows), map_bits(&theirs.shadows), "{name}: shadow maps");
assert_eq!(bits(&ours.shadow_texels), bits(&theirs.shadow_texels), "{name}: shadow texels");
assert_eq!(ours.lights, theirs.lights, "{name}: light marks");
assert_eq!(ours.env, theirs.env, "{name}: environment mark");
@@ -35,6 +45,7 @@ fn compare(name: &str, scene: &Scene, shadows: Option<bool>) {
assert_eq!(bits(&depth), bits(&rdepth), "{name}: resolved depth");
let (cpu, cpu_depth) = try_render_cpu(&ours, &Limits::default()).unwrap();
let (rcpu, rcpu_depth) = ec::render_cpu(&theirs);
assert_eq!((cpu.width, cpu.height), (rcpu.width, rcpu.height), "{name}: render_cpu size");
assert_eq!(bits4(&cpu.data), bits4(&rcpu.data), "{name}: render_cpu color");
assert_eq!(bits(&cpu_depth), bits(&rcpu_depth), "{name}: render_cpu depth");
println!("{name} resolved: ours {:016x} theirs {:016x}", fnv(&img.data, &depth), fnv(&rimg.data, &rdepth));
+1
View File
@@ -2,6 +2,7 @@
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod aux_outputs;
mod bounds;
mod differential;
mod moved;
@@ -1,6 +1,12 @@
//! EffectCraft's `crates/render/src/three_d/adv/raster.rs`. Changes: the imports (the scene
//! types come from this crate, `basis_view` and `vec3` from `super::geom`), `pub` in place of
//! `pub(crate)`, comments removed, and two expressions broken over lines as rustfmt asks.
//!
//! The code keeps EffectCraft's behavior where the crate differs from it, so the differential
//! tests compare against the code EffectCraft runs. Two such points: the visibility pass reads a
//! depth of 0 as an empty pixel, so a fragment on the far plane is drawn only by the fallback under
//! a discarded fragment, and a blended caster without a base texture is drawn whatever its alpha
//! times the opacity. The README's Origin section lists both as changes.
use std::cmp::Reverse;
use std::collections::BinaryHeap;