diff --git a/crates/render/src/anisotropic_surface.rs b/crates/render/src/anisotropic_surface.rs new file mode 100644 index 000000000..d2f696605 --- /dev/null +++ b/crates/render/src/anisotropic_surface.rs @@ -0,0 +1,294 @@ +//! Original anisotropic GGX reflection with separable Smith masking and Schlick Fresnel. +//! +//! Mathematics: Heitz, JCGT 7(4), 2018, equations 1 and 2, +//! . No external implementation adapted. +//! Sampling here uses the **NDF**, not Heitz's visible-normal (VNDF) sampler: +//! `p(h) = D(h) * n.h`, then `p(l) = p(h) / (4 * v.h)`. +//! Rejected reflections are null events, never resampled or renormalized. +//! +//! This numerical module does not install a renderer, persist a material or alter +//! engineering axes. The visual frame's normal may be a shading normal, but the +//! original geometric normal is required separately to reject below-surface rays. +//! Consumers retain geometric normals for ray spawning and optical boundaries. +//! No shading-normal energy correction, multiple scattering or transmission is modeled. + +use std::f64::consts::{PI, TAU}; + +use solidcraft_geom::Vec3; + +use crate::surface::{MIN_ROUGHNESS, OpaqueSurface, SurfaceError, unit_direction}; + +/// Admission or finite-arithmetic failure in the anisotropic numerical contract. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AnisotropicError { + /// An existing opaque-surface parameter or direction was invalid. + Surface(SurfaceError), + /// A visual frame was not orthogonal, or opposed its geometric normal. + Frame, + /// A variate was not finite in the half-open interval [0, 1). + Variates, + /// A computed density, response or sample weight was not finite/nonnegative. + Arithmetic, +} + +impl From for AnisotropicError { + fn from(value: SurfaceError) -> Self { + Self::Surface(value) + } +} + +impl std::fmt::Display for AnisotropicError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Surface(e) => std::fmt::Display::fmt(e, f), + Self::Frame => f.write_str("visual frame must be orthogonal and face the geometric normal"), + Self::Variates => f.write_str("anisotropic variates must be finite in [0, 1)"), + Self::Arithmetic => f.write_str("anisotropic result must be finite and nonnegative"), + } + } +} +impl std::error::Error for AnisotropicError {} + +type Result = std::result::Result; + +/// Right-handed orthonormal visual axes; independent of engineering material axes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VisualFrame { + normal: Vec3, + tangent: Vec3, + bitangent: Vec3, +} + +impl VisualFrame { + /// Normalize finite nonzero orthogonal inputs. An arbitrary oblique tangent is + /// refused rather than silently choosing a different brushed direction. + /// Roundoff within 1e-10 of perpendicular is removed by orthogonalization. + pub fn new(normal: Vec3, tangent: Vec3) -> Result { + let normal = unit_direction(normal)?; + let tangent = unit_direction(tangent)?; + let dot = normal.dot(tangent); + if dot.abs() > 1e-10 { + return Err(AnisotropicError::Frame); + } + let tangent = unit_direction(tangent - normal * dot)?; + let bitangent = unit_direction(normal.cross(tangent))?; + Ok(Self { normal, tangent, bitangent }) + } + + /// Shading normal, never a replacement for an original geometric normal. + pub fn normal(self) -> Vec3 { + self.normal + } + + /// Visual X axis, associated with the first roughness. + pub fn tangent(self) -> Vec3 { + self.tangent + } + + /// Visual Y axis, associated with the second roughness. + pub fn bitangent(self) -> Vec3 { + self.bitangent + } + + fn local(self, direction: Vec3) -> Vec3 { + Vec3::new(self.tangent.dot(direction), self.bitangent.dot(direction), self.normal.dot(direction)) + } + + fn world(self, local: Vec3) -> Vec3 { + self.tangent * local.x + self.bitangent * local.y + self.normal * local.z + } + + fn geometric(self, normal: Vec3) -> Result { + let normal = unit_direction(normal)?; + if normal.dot(self.normal) <= 0.0 { + return Err(AnisotropicError::Frame); + } + Ok(normal) + } +} + +/// A bounded opaque response with two perceptual roughness axes in [0.045, 1]. +/// Alpha is roughness squared, matching [`OpaqueSurface`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AnisotropicSurface { + base: OpaqueSurface, + roughness_y: f64, +} + +/// One reflected **specular-only** NDF sample. Fields are in world coordinates. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ReflectionSample { + /// Outgoing direction, pointing away from the surface. + pub direction: Vec3, + /// Unconditional density per steradian, without renormalizing null events. + pub pdf: f64, + /// `specular_brdf * shading_cosine / pdf`, in linear RGB. + /// Diffuse response is excluded; its sampling strategy belongs to the consumer. + pub weight: Vec3, +} + +impl AnisotropicSurface { + /// Linear-sRGB reflectance, metal fraction and IOR use the opaque contract. + /// Perfect delta mirrors and out-of-range roughness are refused, not clamped. + pub fn new(base_color: Vec3, metallic: f64, roughness_x: f64, roughness_y: f64, dielectric_ior: f64) -> Result { + let base = OpaqueSurface::new(base_color, metallic, roughness_x, dielectric_ior)?; + if !roughness_y.is_finite() || !(MIN_ROUGHNESS..=1.0).contains(&roughness_y) { + return Err(SurfaceError::Roughness.into()); + } + Ok(Self { base, roughness_y }) + } + + /// Admitted perceptual roughness along visual X and Y. + pub fn roughness(self) -> [f64; 2] { + [self.base.roughness(), self.roughness_y] + } + + fn alpha(self) -> [f64; 2] { + [self.base.roughness().powi(2), self.roughness_y.powi(2)] + } + + fn fresnel(self, cosine: f64) -> Vec3 { + let f0 = self.base.normal_reflectance(); + f0 + (Vec3::new(1.0, 1.0, 1.0) - f0) * (1.0 - cosine.clamp(0.0, 1.0)).powi(5) + } + + fn distribution_local(self, h: Vec3) -> f64 { + if h.z <= 0.0 { + return 0.0; + } + let [ax, ay] = self.alpha(); + let q = (h.x / ax).powi(2) + (h.y / ay).powi(2) + h.z * h.z; + 1.0 / (PI * ax * ay * q * q) + } + + // Smith G1 / cosine, avoiding division by tiny cosines and tan(theta). + fn visibility(self, w: Vec3) -> f64 { + let [ax, ay] = self.alpha(); + 2.0 / (w.z + (w.z * w.z + (ax * w.x).powi(2) + (ay * w.y).powi(2)).sqrt()) + } + + /// GGX normal distribution D, per steradian of microfacet normal. + /// This is not a normalized probability density: [`Self::normal_pdf`] is. + pub fn distribution(self, frame: VisualFrame, half: Vec3) -> Result { + finite_scalar(self.distribution_local(frame.local(unit_direction(half)?))) + } + + /// Projected NDF density `D(h) * n.h` on the upper shading hemisphere. + /// Its integral over that hemisphere is one. + pub fn normal_pdf(self, frame: VisualFrame, half: Vec3) -> Result { + let h = frame.local(unit_direction(half)?); + finite_scalar(self.distribution_local(h) * h.z.max(0.0)) + } + + /// Sample the projected NDF by stretching a radial GGX slope distribution. + /// The inverse radial CDF is `r = sqrt(u/(1-u))`; homogeneous coordinates + /// `(alpha_x*sqrt(u)*cos(phi), alpha_y*sqrt(u)*sin(phi), sqrt(1-u))` + /// avoid a large intermediate radius. No heap, rejection loop or RNG is used. + pub fn sample_normal(self, frame: VisualFrame, variates: [f64; 2]) -> Result { + let [u, azimuth] = variates; + if !variates.into_iter().all(|v| v.is_finite() && (0.0..1.0).contains(&v)) { + return Err(AnisotropicError::Variates); + } + let [ax, ay] = self.alpha(); + let phi = TAU * azimuth; + let radial = u.sqrt(); + let h = unit_direction(Vec3::new(ax * radial * phi.cos(), ay * radial * phi.sin(), (1.0 - u).sqrt()))?; + Ok(unit_direction(frame.world(h))?) + } + + fn directions(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result> { + let geometric = frame.geometric(geometric)?; + let view = unit_direction(view)?; + let light = unit_direction(light)?; + let (v, l) = (frame.local(view), frame.local(light)); + if v.z <= 0.0 || l.z <= 0.0 || geometric.dot(view) <= 0.0 || geometric.dot(light) <= 0.0 { + return Ok(None); + } + let h = unit_direction(view + light)?; + Ok(Some((v, l, frame.local(h)))) + } + + fn specular_local(self, v: Vec3, l: Vec3, h: Vec3) -> Result { + finite_rgb(self.fresnel(v.dot(h)) * (self.distribution_local(h) * 0.25 * self.visibility(v) * self.visibility(l))) + } + + /// Specular component only, with independent geometric hemisphere rejection. + /// All input directions point away from the surface. + pub fn specular_brdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result { + let Some((v, l, h)) = self.directions(frame, geometric, view, light)? else { return Ok(Vec3::ZERO) }; + self.specular_local(v, l, h) + } + + /// Full opaque BRDF, including the same symmetric attenuated Lambert term as + /// [`OpaqueSurface`]. No radiance, cosine, exposure or display transform included. + /// Equal roughness axes delegate to the existing isotropic numerical contract. + pub fn brdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result { + let Some((v, l, h)) = self.directions(frame, geometric, view, light)? else { return Ok(Vec3::ZERO) }; + if self.base.roughness() == self.roughness_y { + return Ok(self.base.brdf(frame.normal, view, light)?); + } + let specular = self.specular_local(v, l, h)?; + let fv = self.fresnel(v.z); + let fl = self.fresnel(l.z); + let diffuse = self.base.base_color() * ((1.0 - self.base.metallic()) / PI); + finite_rgb( + specular + + Vec3::new( + (1.0 - fv.x) * (1.0 - fl.x) * diffuse.x, + (1.0 - fv.y) * (1.0 - fl.y) * diffuse.y, + (1.0 - fv.z) * (1.0 - fl.z) * diffuse.z, + ), + ) + } + + /// Unconditional reflected-direction density for the specular NDF sampler. + /// Integrates to the acceptance probability, not necessarily one: invalid + /// microfacets and below-geometric/shading-hemisphere reflections are null events. + /// A mixture with a diffuse or environment sampler must use its own mixture PDF. + pub fn reflection_pdf(self, frame: VisualFrame, geometric: Vec3, view: Vec3, light: Vec3) -> Result { + let Some((v, _, h)) = self.directions(frame, geometric, view, light)? else { return Ok(0.0) }; + finite_scalar(self.distribution_local(h) * h.z.max(0.0) / (4.0 * v.dot(h).max(0.0))) + } + + /// One specular NDF attempt. `None` is a zero-contribution event and must + /// still count towards the consumer's sample denominator. Never retry until + /// success. Ray origins/visibility use the consumer's original geometric data. + pub fn sample_reflection(self, frame: VisualFrame, geometric: Vec3, view: Vec3, variates: [f64; 2]) -> Result> { + let geometric = frame.geometric(geometric)?; + let view = unit_direction(view)?; + let half = self.sample_normal(frame, variates)?; + let v = frame.local(view); + if v.z <= 0.0 || geometric.dot(view) <= 0.0 { + return Ok(None); + } + let vh = view.dot(half); + if vh <= 0.0 { + return Ok(None); + } + let light = unit_direction(half * (2.0 * vh) - view)?; + let l = frame.local(light); + if l.z <= 0.0 || geometric.dot(light) <= 0.0 { + return Ok(None); + } + let h = frame.local(half); + let pdf = self.reflection_pdf(frame, geometric, view, light)?; + if pdf <= 0.0 { + return Err(AnisotropicError::Arithmetic); + } + // Cancel D algebraically in f_spec * cos / pdf. No tiny-cosine division. + let weight = finite_rgb(self.fresnel(vh) * (self.visibility(v) * (self.visibility(l) * l.z) * vh / h.z))?; + Ok(Some(ReflectionSample { direction: light, pdf, weight })) + } +} + +fn finite_scalar(value: f64) -> Result { + if value.is_finite() && value >= 0.0 { Ok(value) } else { Err(AnisotropicError::Arithmetic) } +} + +fn finite_rgb(value: Vec3) -> Result { + if value.is_finite() && [value.x, value.y, value.z].into_iter().all(|c| c >= 0.0) { Ok(value) } else { Err(AnisotropicError::Arithmetic) } +} + +#[cfg(test)] +#[path = "anisotropic_surface_tests.rs"] +mod tests; diff --git a/crates/render/src/anisotropic_surface_tests.rs b/crates/render/src/anisotropic_surface_tests.rs new file mode 100644 index 000000000..6e963aebb --- /dev/null +++ b/crates/render/src/anisotropic_surface_tests.rs @@ -0,0 +1,277 @@ +use super::*; + +fn frame() -> VisualFrame { + VisualFrame::new(Vec3::Z, Vec3::X).unwrap() +} + +fn surface(rx: f64, ry: f64) -> AnisotropicSurface { + AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), 1.0, rx, ry, 1.5).unwrap() +} + +fn close(a: f64, b: f64, tolerance: f64) { + assert!((a - b).abs() <= tolerance * (1.0 + a.abs().max(b.abs())), "{a} != {b}"); +} + +fn close_rgb(a: Vec3, b: Vec3, tolerance: f64) { + close(a.x, b.x, tolerance); + close(a.y, b.y, tolerance); + close(a.z, b.z, tolerance); +} + +fn hemisphere(mu: f64, phi: f64) -> Vec3 { + let radius = (1.0 - mu * mu).sqrt(); + Vec3::new(radius * phi.cos(), radius * phi.sin(), mu) +} + +#[test] +fn constructor_rejects_hostile_parameters_on_both_axes() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, MIN_ROUGHNESS.next_down(), 1.01] { + assert!(AnisotropicSurface::new(Vec3::X, 1.0, bad, 0.5, 1.5).is_err()); + assert!(AnisotropicSurface::new(Vec3::X, 1.0, 0.5, bad, 1.5).is_err()); + } + for bad in [f64::NAN, f64::INFINITY, -0.1, 1.1] { + assert!(AnisotropicSurface::new(Vec3::new(bad, 0.0, 0.0), 1.0, 0.5, 0.8, 1.5).is_err()); + assert!(AnisotropicSurface::new(Vec3::X, bad, 0.5, 0.8, 1.5).is_err()); + } + for bad in [f64::NAN, 0.99, 3.01] { + assert!(AnisotropicSurface::new(Vec3::X, 1.0, 0.5, 0.8, bad).is_err()); + } + assert_eq!(surface(MIN_ROUGHNESS, 1.0).roughness(), [MIN_ROUGHNESS, 1.0]); +} + +#[test] +fn frame_is_right_handed_and_requires_an_explicit_orthogonal_axis() { + let f = VisualFrame::new(Vec3::new(0.0, 0.0, 1e308), Vec3::new(1e-300, 0.0, 0.0)).unwrap(); + assert_eq!(f.normal(), Vec3::Z); + assert_eq!(f.tangent(), Vec3::X); + assert_eq!(f.bitangent(), Vec3::Y); + for (n, t) in [(Vec3::ZERO, Vec3::X), (Vec3::Z, Vec3::Z), (Vec3::Z, Vec3::X + Vec3::Z), (Vec3::Z, Vec3::new(f64::NAN, 0.0, 0.0))] { + assert!(VisualFrame::new(n, t).is_err()); + } + let tilted = VisualFrame::new(Vec3::new(0.3, 0.4, 1.0), Vec3::new(0.8, -0.6, 0.0)).unwrap(); + close(tilted.tangent().dot(tilted.normal()), 0.0, 1e-14); + close_rgb(tilted.tangent().cross(tilted.bitangent()), tilted.normal(), 1e-14); +} + +#[test] +fn normal_incidence_matches_independent_ggx_peak() { + let s = surface(0.3, 0.7); + let d = 1.0 / (PI * 0.3_f64.powi(2) * 0.7_f64.powi(2)); + close(s.distribution(frame(), Vec3::Z).unwrap(), d, 1e-14); + close(s.normal_pdf(frame(), Vec3::Z).unwrap(), d, 1e-14); + close_rgb(s.brdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap(), Vec3::new(0.8, 0.5, 0.2) * (d / 4.0), 1e-14); +} + +#[test] +fn isotropic_limit_matches_existing_opaque_contract() { + for r in [MIN_ROUGHNESS, 0.3, 0.7, 1.0] { + for metallic in [0.0, 0.5, 1.0] { + let color = Vec3::new(0.8, 0.5, 0.2); + let a = AnisotropicSurface::new(color, metallic, r, r, 1.5).unwrap(); + let opaque = OpaqueSurface::new(color, metallic, r, 1.5).unwrap(); + for (v, l) in [(Vec3::Z, Vec3::Z), (Vec3::new(0.4, 0.2, 0.8), Vec3::new(-0.2, 0.7, 0.6))] { + assert_eq!(a.brdf(frame(), Vec3::Z, v, l).unwrap(), opaque.brdf(Vec3::Z, v, l).unwrap()); + if metallic == 1.0 { + close_rgb(a.specular_brdf(frame(), Vec3::Z, v, l).unwrap(), opaque.brdf(Vec3::Z, v, l).unwrap(), 1e-10); + } + } + } + } +} + +#[test] +fn reciprocal_for_unequal_axes_and_mixed_metal_fraction() { + for metallic in [0.0, 0.4, 1.0] { + let s = AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), metallic, 0.2, 0.9, 2.0).unwrap(); + for (v, l) in [(Vec3::new(0.4, 0.1, 1.0), Vec3::new(-0.3, 0.2, 0.8)), (Vec3::new(1.0, 0.0, 1e-300), Vec3::new(-1.0, 0.0, 1e-300))] { + close_rgb(s.brdf(frame(), Vec3::Z, v, l).unwrap(), s.brdf(frame(), Vec3::Z, l, v).unwrap(), 1e-12); + } + } +} + +#[test] +fn ninety_degree_visual_rotation_swaps_the_brushed_response() { + let s = surface(0.25, 0.8); + let swapped = surface(0.8, 0.25); + let rotated = VisualFrame::new(Vec3::Z, Vec3::Y).unwrap(); + let light = Vec3::new(0.6, 0.0, 0.8); + let initial = s.brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap(); + let turned = s.brdf(rotated, Vec3::Z, Vec3::Z, light).unwrap(); + assert!((initial - turned).len() > 0.01); + close_rgb(turned, swapped.brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap(), 1e-13); + let h = s.sample_normal(frame(), [0.3, 0.2]).unwrap(); + let rotated_h = s.sample_normal(rotated, [0.3, 0.2]).unwrap(); + close_rgb(rotated_h, Vec3::new(-h.y, h.x, h.z), 1e-14); +} + +#[test] +fn geometric_and_shading_hemispheres_are_independent() { + let shading = VisualFrame::new(Vec3::new(0.8, 0.0, 0.6), Vec3::Y).unwrap(); + let light = Vec3::new(0.99, 0.0, -0.1); + let s = surface(0.5, 0.8); + assert!(shading.normal().dot(light) > 0.0); + assert_eq!(s.brdf(shading, Vec3::Z, Vec3::Z, light).unwrap(), Vec3::ZERO); + assert_eq!(s.reflection_pdf(shading, Vec3::Z, Vec3::Z, light).unwrap(), 0.0); + assert!(s.brdf(frame(), -Vec3::Z, Vec3::Z, Vec3::Z).is_err()); + assert_eq!(s.brdf(frame(), Vec3::Z, Vec3::Z, Vec3::X).unwrap(), Vec3::ZERO); + assert_eq!(s.brdf(frame(), Vec3::Z, -Vec3::Z, Vec3::Z).unwrap(), Vec3::ZERO); +} + +#[test] +fn grazing_and_extreme_finite_direction_magnitudes_remain_finite() { + for (rx, ry) in [(MIN_ROUGHNESS, 1.0), (1.0, MIN_ROUGHNESS), (MIN_ROUGHNESS, MIN_ROUGHNESS)] { + let s = surface(rx, ry); + for (v, l) in [(Vec3::new(1.0, 0.0, 1e-300), Vec3::new(-1.0, 0.0, 1e-300)), (Vec3::new(1e308, 1e308, 1e308), Vec3::new(-1e-300, 0.0, 1e-300))] + { + let b = s.brdf(frame(), Vec3::Z, v, l).unwrap(); + assert!(b.is_finite() && b.x >= 0.0 && b.y >= 0.0 && b.z >= 0.0); + } + for u in [0.0, f64::from_bits(1), 0.5, 1.0_f64.next_down()] { + let h = s.sample_normal(frame(), [u, 0.5]).unwrap(); + assert!(h.is_finite() && h.z > 0.0); + assert!(s.normal_pdf(frame(), h).unwrap().is_finite()); + } + let view = Vec3::new(1.0, 0.0, 1e-300); + let sample = s.sample_reflection(frame(), Vec3::Z, view, [0.0, 0.0]).unwrap().unwrap(); + assert!(sample.pdf.is_finite() && sample.pdf > 0.0 && sample.weight.is_finite()); + // A mathematical density beyond f64 is a typed refusal, never clamped. + assert_eq!(s.sample_reflection(frame(), Vec3::Z, Vec3::new(1.0, 0.0, f64::from_bits(1)), [0.0, 0.0]), Err(AnisotropicError::Arithmetic)); + } +} + +#[test] +fn malformed_directions_and_variates_fail_without_clamping() { + let s = surface(0.5, 0.8); + for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(f64::INFINITY, 0.0, 1.0)] { + assert!(s.brdf(frame(), Vec3::Z, bad, Vec3::Z).is_err()); + assert!(s.brdf(frame(), bad, Vec3::Z, Vec3::Z).is_err()); + assert!(s.brdf(frame(), Vec3::Z, Vec3::Z, bad).is_err()); + assert!(s.normal_pdf(frame(), bad).is_err()); + } + for bad in [-0.1, 1.0, f64::NAN, f64::INFINITY] { + assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [bad, 0.5]).is_err()); + assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.5, bad]).is_err()); + } +} + +#[test] +fn sampled_slopes_follow_the_independent_inverse_radial_cdf() { + let s = surface(0.3, 0.7); + for u in [0.0, 0.01, 0.3, 0.8, 0.9999] { + for azimuth in [0.0, 0.2, 0.5, 0.8] { + let h = s.sample_normal(frame(), [u, azimuth]).unwrap(); + let sx = h.x / (0.3_f64.powi(2) * h.z); + let sy = h.y / (0.7_f64.powi(2) * h.z); + let radius2 = sx * sx + sy * sy; + close(radius2 / (1.0 + radius2), u, 1e-13); + close_rgb(h, s.sample_normal(frame(), [u, azimuth]).unwrap(), 0.0); + } + } +} + +#[test] +fn reflection_samples_match_pdf_and_specular_throughput() { + let s = surface(0.4, 0.8); + let view = unit_direction(Vec3::new(0.2, 0.3, 1.0)).unwrap(); + let mut accepted = 0; + let mut null = 0; + for i in 0..32 { + for j in 0..32 { + let uv = [(i as f64 + 0.5) / 32.0, (j as f64 + 0.5) / 32.0]; + match s.sample_reflection(frame(), Vec3::Z, view, uv).unwrap() { + Some(sample) => { + accepted += 1; + close(sample.pdf, s.reflection_pdf(frame(), Vec3::Z, view, sample.direction).unwrap(), 1e-13); + let expected = s.specular_brdf(frame(), Vec3::Z, view, sample.direction).unwrap() * (sample.direction.z / sample.pdf); + close_rgb(sample.weight, expected, 1e-10); + } + None => null += 1, + } + } + } + assert!(accepted > 0 && null > 0); + assert_eq!(accepted + null, 1024); +} + +#[test] +fn unit_roughness_normal_view_has_half_null_mass_and_uniform_reflection_pdf() { + let s = surface(1.0, 1.0); + assert!(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.75, 0.3]).unwrap().is_none()); + let sample = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.25, 0.3]).unwrap().unwrap(); + close(sample.pdf, 1.0 / (4.0 * PI), 1e-14); + let mut accepted = 0; + for i in 0..1024 { + accepted += usize::from(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [(i as f64 + 0.5) / 1024.0, 0.3]).unwrap().is_some()); + } + assert_eq!(accepted, 512); + // p(l)=1/(4*pi) over the upper hemisphere: valid mass exactly1/2. + close(s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, Vec3::Z).unwrap() * (2.0 * PI), 0.5, 1e-14); + assert_eq!(s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, -Vec3::Z).unwrap(), 0.0); +} + +#[test] +fn invisible_microfacets_are_null_and_weights_exclude_the_diffuse_substrate() { + let s = AnisotropicSurface::new(Vec3::new(0.8, 0.5, 0.2), 0.0, 1.0, 1.0, 1.5).unwrap(); + let view = unit_direction(Vec3::new(0.99, 0.0, 0.1)).unwrap(); + assert!(s.sample_reflection(frame(), Vec3::Z, view, [0.9, 0.5]).unwrap().is_none()); + let sample = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [0.1, 0.2]).unwrap().unwrap(); + let scale = sample.direction.z / sample.pdf; + let specular = s.specular_brdf(frame(), Vec3::Z, Vec3::Z, sample.direction).unwrap() * scale; + let total = s.brdf(frame(), Vec3::Z, Vec3::Z, sample.direction).unwrap() * scale; + close_rgb(sample.weight, specular, 1e-13); + assert!(total.x > sample.weight.x + 0.1); + assert_eq!(s.normal_pdf(frame(), -Vec3::Z).unwrap(), 0.0); + assert_eq!(s.normal_pdf(frame(), Vec3::X).unwrap(), 0.0); +} + +#[test] +fn quadrature_distinguishes_normal_pdf_mass_from_valid_reflection_mass() { + // Finite midpoint grids resolve these broad lobes only. Narrowest admitted + // roughness is tested analytically and with inverse-CDF samples elsewhere. + const N: usize = 256; + for (rx, ry) in [(1.0, 1.0), (0.6, 0.9)] { + let s = surface(rx, ry); + let mut normal_mass = 0.0; + let mut valid_mass = 0.0; + let mut accepted = 0; + for i in 0..N { + for j in 0..N { + let u = (i as f64 + 0.5) / N as f64; + let azimuth = (j as f64 + 0.5) / N as f64; + let l = hemisphere(u, TAU * azimuth); + normal_mass += s.normal_pdf(frame(), l).unwrap(); + valid_mass += s.reflection_pdf(frame(), Vec3::Z, Vec3::Z, l).unwrap(); + accepted += usize::from(s.sample_reflection(frame(), Vec3::Z, Vec3::Z, [u, azimuth]).unwrap().is_some()); + } + } + let domega = TAU / (N * N) as f64; + close(normal_mass * domega, 1.0, 0.001); + close(valid_mass * domega, accepted as f64 / (N * N) as f64, 0.003); + assert!(valid_mass * domega < 1.0); + } +} + +#[test] +fn broad_lobe_importance_estimate_agrees_with_integrated_energy() { + // White metal, normal view, deterministic256² grids. A scoped consistency + // check, not universal energy certification or a variance/convergence claim. + const N: usize = 256; + let s = AnisotropicSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 0.6, 0.9, 1.5).unwrap(); + let mut integrated = Vec3::ZERO; + let mut sampled = Vec3::ZERO; + for i in 0..N { + for j in 0..N { + let uv = [(i as f64 + 0.5) / N as f64, (j as f64 + 0.5) / N as f64]; + let light = hemisphere(uv[0], TAU * uv[1]); + integrated += s.specular_brdf(frame(), Vec3::Z, Vec3::Z, light).unwrap() * light.z; + if let Some(sample) = s.sample_reflection(frame(), Vec3::Z, Vec3::Z, uv).unwrap() { + sampled += sample.weight; + } + } + } + integrated = integrated * (TAU / (N * N) as f64); + sampled = sampled / (N * N) as f64; // Includes ALL null attempts. + assert!(integrated.x > 0.0 && integrated.x <= 1.001); + assert!(sampled.x > 0.0 && sampled.x <= 1.001); + close_rgb(integrated, sampled, 0.003); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2991682c0..4e14b3e36 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,6 +5,7 @@ #![forbid(unsafe_code)] mod analysis; +pub mod anisotropic_surface; mod backend; mod camera; pub mod clear_coat; diff --git a/docs/render-anisotropic-ggx.md b/docs/render-anisotropic-ggx.md new file mode 100644 index 000000000..f239c6b3f --- /dev/null +++ b/docs/render-anisotropic-ggx.md @@ -0,0 +1,46 @@ +# Anisotropic GGX numerical core + +`render::anisotropic_surface` supplies the independent optical core tracked in +#1694/#1699. This constituent extracts the original source and analytic tests +already published in #1698 at `463a3e0daaa6b84f169ba5f8f215fba4642c194a`. +It adds no renderer registration, saved field, command, device dependency or +engineering-material assignment. Runtime consumers remain separate work. + +## Contract + +`VisualFrame::new` admits finite, nonzero, perpendicular normal/tangent inputs, +normalizes them, and constructs a right-handed visual frame. This is not a physical +material-axis assignment. An original geometric normal is supplied separately; +response and reflected samples reject either hemisphere when appropriate. + +Both perceptual roughness axes use the opaque surface range `[0.045, 1]`; alpha is +roughness squared. Linear-sRGB reflectance, metal fraction and dielectric IOR use +the existing `OpaqueSurface` admission. Invalid data is refused, not clamped. +Equal roughness axes preserve the isotropic opaque BRDF contract exactly. + +Sampling uses the projected **normal distribution (NDF)**, not a visible-normal +sampler. `normal_pdf` is `D(h) * n.h`; the unconditional reflected-direction PDF +includes the `1 / (4 * v.h)` Jacobian. A rejected microfacet is a null event that +must remain in the sample denominator. Never retry until a sample succeeds. +Reflection weights contain the specular component only. Diffuse/environment +mixtures, visibility, ray spawning, image budgets and multiple scattering belong +to the consumer; this module does not claim to implement them. + +The implementation is original Rust using elementary GGX/Smith/Schlick equations. +The public mathematical reference is Heitz, JCGT 7(4), 2018, equations 1 and 2: +https://jcgt.org/published/0007/04/01/. No external implementation was adapted. + +## Reproduce the focused checks + +```sh +cargo test --profile ci -p solidcraft-render --lib anisotropic_surface +cargo clippy --profile ci -p solidcraft-render --all-targets -- -D warnings +cargo check --target wasm32-unknown-unknown -p solidcraft-render +``` + +Analytic and deterministic quadrature tests cover hostile inputs, orthonormality, +normal-incidence peaks, isotropic equivalence, reciprocity, 90-degree visual-axis +rotation, geometric/shading hemisphere separation, grazing directions, inverse-CDF +sampling, PDF/throughput agreement and retained null-event mass. Broad-lobe energy +checks are scoped consistency tests, not universal energy certification, measured +material data or evidence of an integrated rendered image.