* Render: one sRGB transfer function, geom::srgb, for the hand-written copies (#7161) Twelve places wrote the sRGB encode or decode formula out by hand (doc's glass recipe, engine's render library, glTF import, the PNG film, photographic and presentation output, the ray tracer's image, the stage, the surface decoder, texture normalisation and the theme's contrast check). They now call solidcraft_geom::srgb: encode/decode on 0..1 values, encode8/decode8 for 8-bit codes. render::surface::srgb8_to_linear stays as a re-export, so its callers are unchanged. Same results: the module's tests compare it bit for bit with the formula as the callers wrote it, over all 256 codes and a dense sweep of linear values plus the knees, out-of-range values, infinities and NaN, for each way the callers clamped (after encoding, before it, or not at all), and decoded values either side of the decode knee, where no 8-bit code falls. One change: glTF import encoded in f32. Over every f32 in 0..1, 218 of 1,065,353,217 values sit on a rounding tie that f32 got wrong and now give the neighbouring code (f64 gives the nearer one). Left as they are: render/job/image.rs (replaced by exact tables in its own change), the tests and the starter-pack validator that keep their own copy as an independent reference, and the WGSL shaders (they can't call Rust). Fixes #7161 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tests: the sRGB codes of five callers that had no test of their output (#7161) The glass swatch, a library surface applied as a plain appearance, glTF's fallback for a colour channel that isn't a number, a stage panel and an empty pixel in presentation output each get an assertion with their sRGB codes worked out by hand. A planted wrong conversion at each is now caught by that test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -815,6 +815,8 @@ mod tests {
|
||||
bad.boundary = GlassBoundary::Thin { thickness_mm: 10001.0 };
|
||||
assert!(bad.validate().is_err());
|
||||
}
|
||||
// The swatch shows the transmission as sRGB codes.
|
||||
assert_eq!(find("starter.glass.smoky-neutral").unwrap().preview_color(), [160, 166, 173]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -154,10 +154,7 @@ impl VisualPreset {
|
||||
match self.recipe {
|
||||
Recipe::Opaque(r) => r.color,
|
||||
// A UI swatch of the transmission values, not rendered glass or absorption.
|
||||
Recipe::Glass(r) => r.transmission_linear_rgb.map(|v| {
|
||||
let encoded = if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
|
||||
(encoded.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}),
|
||||
Recipe::Glass(r) => r.transmission_linear_rgb.map(solidcraft_geom::srgb::encode8),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -320,12 +320,6 @@ fn triple(value: &Value, command: &str) -> Result<[f64; 3]> {
|
||||
fn number(value: &Value, command: &str) -> Result<f64> {
|
||||
value.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(command, "missing finite authored value"))
|
||||
}
|
||||
fn srgb(v: f64) -> u8 {
|
||||
let v = v.clamp(0.0, 1.0);
|
||||
let encoded = if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
|
||||
(encoded * 255.0).round().clamp(0.0, 255.0) as u8
|
||||
}
|
||||
|
||||
pub(super) fn apply_appearance(s: &mut Session, params: &Value) -> Result<Value> {
|
||||
let command = "render.library.appearance.apply";
|
||||
let input: Appearance = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
|
||||
@@ -339,7 +333,7 @@ pub(super) fn apply_appearance(s: &mut Session, params: &Value) -> Result<Value>
|
||||
let value = item("surfaces", &input.id, command)?;
|
||||
let lo = triple(&value["base_linear_low"], command)?;
|
||||
let hi = triple(&value["base_linear_high"], command)?;
|
||||
let color = std::array::from_fn::<_, 3, _>(|i| srgb((lo[i] + hi[i]) * 0.5));
|
||||
let color = std::array::from_fn::<_, 3, _>(|i| crate::geom::srgb::encode8((lo[i] + hi[i]) * 0.5));
|
||||
(
|
||||
value,
|
||||
json!({"color":color,"opacity":1.0,"pbr":{"metallic":value["metallic"],"roughness":value["roughness"],"dielectric_ior":1.5}}),
|
||||
|
||||
@@ -145,6 +145,8 @@ fn uniform_appearance_requires_acknowledged_projection_and_preserves_physical_da
|
||||
assert_eq!(s.doc.to_json(), before);
|
||||
let reply = s.execute("render.library.appearance.apply", &json!({"id":"SURF-001","variant":"uniform_opaque","bodies":["Target"]})).unwrap();
|
||||
assert_eq!(reply["engineering_properties_unchanged"], true);
|
||||
// The middle of SURF-001's linear range, as sRGB codes.
|
||||
assert_eq!(reply["appearance"]["color"], json!([196, 202, 207]));
|
||||
let after: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
|
||||
assert_eq!(after["user_materials"], before_value["user_materials"]);
|
||||
assert_eq!(s.undo.len(), undo + 1);
|
||||
|
||||
@@ -34,6 +34,7 @@ mod profile;
|
||||
pub mod section;
|
||||
pub mod simplify;
|
||||
pub mod spline_space;
|
||||
pub mod srgb;
|
||||
pub mod tess;
|
||||
pub mod title_block;
|
||||
pub mod tspline;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! The sRGB transfer function (IEC 61966-2-1), once: linear light to an sRGB value and back, and the 8-bit codes most
|
||||
//! callers want. Every encode and decode in Rust goes through here, so a change to the rule is one change. (Shaders
|
||||
//! can't call Rust and keep their own copies.)
|
||||
|
||||
/// Linear light (0..1) to an sRGB value (0..1): straight below the knee at 0.0031308, a 1/2.4 power above it.
|
||||
pub fn encode(linear: f64) -> f64 {
|
||||
if linear <= 0.003_130_8 { 12.92 * linear } else { 1.055 * linear.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
/// An sRGB value (0..1) to linear light: straight below the knee at 0.04045, a 2.4 power above it.
|
||||
pub fn decode(encoded: f64) -> f64 {
|
||||
if encoded <= 0.040_45 { encoded / 12.92 } else { ((encoded + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
/// Linear light to the nearest 8-bit sRGB code; out of range reads as the nearest end, and NaN as 0.
|
||||
pub fn encode8(linear: f64) -> u8 {
|
||||
(encode(linear).clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// An 8-bit sRGB code to linear light.
|
||||
pub fn decode8(code: u8) -> f64 {
|
||||
decode(f64::from(code) / 255.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The formulas as each caller wrote them before this module: the module must give the same results.
|
||||
fn encode_as_written(v: f64) -> f64 {
|
||||
if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
fn decode_as_written(v: f64) -> f64 {
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_code_decodes_as_before_and_encodes_back_to_itself() {
|
||||
for code in 0..=255u8 {
|
||||
let linear = decode8(code);
|
||||
assert_eq!(linear.to_bits(), decode_as_written(f64::from(code) / 255.0).to_bits(), "{code}");
|
||||
assert_eq!(encode8(linear), code, "{code}");
|
||||
}
|
||||
assert_eq!((decode8(0), decode8(255)), (0.0, 1.0));
|
||||
assert!((decode8(10) - (10.0 / 255.0) / 12.92).abs() < 1e-15, "the straight part below the knee");
|
||||
assert!((decode8(128) - 0.21586050011389926).abs() < 1e-14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_decode_as_every_caller_did() {
|
||||
// Either side of the knee (no 8-bit code falls between 0.04 and 0.04045), out of range, and a dense sweep.
|
||||
let mut values = vec![0.0404, 0.040_45, 0.040_45_f64.next_up(), -0.5, 1.5];
|
||||
values.extend((0..=100_000).map(|i| f64::from(i) / 100_000.0));
|
||||
for v in values {
|
||||
assert_eq!(decode(v).to_bits(), decode_as_written(v).to_bits(), "{v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_values_encode_as_every_caller_did() {
|
||||
// Below zero, the knees, above one, the extremes and NaN, and a dense sweep in between.
|
||||
let mut values = vec![-1.0, -0.0, 0.0, 0.003_130_8, 0.003_130_8_f64.next_up(), 0.04045, 1.0, 1.0f64.next_up(), 2.0];
|
||||
values.extend([f64::MIN_POSITIVE, f64::MAX, f64::INFINITY, f64::NEG_INFINITY, f64::NAN]);
|
||||
values.extend((0..=200_000).map(|i| f64::from(i) / 100_000.0 - 0.5));
|
||||
for v in values {
|
||||
assert_eq!(encode(v).to_bits(), encode_as_written(v).to_bits(), "{v}");
|
||||
let byte = encode8(v);
|
||||
// Clamped after encoding (film_png, raytrace, photographic, presentation, appearance_pack) ...
|
||||
assert_eq!(byte, (encode_as_written(v).clamp(0.0, 1.0) * 255.0).round() as u8, "{v}");
|
||||
// ... before it (engine's render library) ...
|
||||
let first = (encode_as_written(v.clamp(0.0, 1.0)) * 255.0).round().clamp(0.0, 255.0) as u8;
|
||||
// ... or not at all, the cast saturating (render's stage).
|
||||
let none = (encode_as_written(v) * 255.0).round() as u8;
|
||||
assert_eq!((byte, byte), (first, none), "{v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -839,17 +839,16 @@ impl<'d> Reader<'d, '_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear to sRGB (0–1).
|
||||
fn srgb(c: f32) -> f32 {
|
||||
let c = if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.8 };
|
||||
if c <= 0.003_130_8 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }
|
||||
/// A linear base colour channel as an 8-bit sRGB code; one that isn't a number reads as 0.8.
|
||||
fn srgb(c: f32) -> u8 {
|
||||
solidcraft_geom::srgb::encode8(if c.is_finite() { f64::from(c) } else { 0.8 })
|
||||
}
|
||||
|
||||
/// A material's look: base colour, alpha when blended, metallic/roughness when opaque.
|
||||
fn look_of(m: &gltf::Material<'_>) -> Look {
|
||||
let pbr = m.pbr_metallic_roughness();
|
||||
let [r, g, b, a] = pbr.base_color_factor();
|
||||
let color = [r, g, b].map(|c| (srgb(c) * 255.0).round() as u8);
|
||||
let color = [r, g, b].map(srgb);
|
||||
let opacity = match m.alpha_mode() {
|
||||
gltf::material::AlphaMode::Blend if a.is_finite() => f64::from(a).clamp(0.0, 1.0),
|
||||
_ => 1.0,
|
||||
|
||||
@@ -260,6 +260,8 @@ fn materials_give_looks() {
|
||||
let glass = g.looks[1].as_ref().unwrap();
|
||||
assert!((i32::from(glass.color[0]) - 128).abs() <= 1, "{:?}", glass.color);
|
||||
assert!(close(glass.opacity, 0.5) && glass.pbr.is_none());
|
||||
// A channel that isn't a number reads as linear 0.8, sRGB 231.
|
||||
assert_eq!([f32::NAN, f32::INFINITY].map(srgb), [231, 231]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use super::{CompletePass, MAX_BYTES, invalid, limit};
|
||||
use crate::job::encoding::PngEncoding;
|
||||
use crate::job::{CancelToken, CpuHost, ErrorCode, JobError, Phase, Progress, Reservation, Result};
|
||||
use solidcraft_geom::Vec3;
|
||||
use solidcraft_geom::{Vec3, srgb::encode8};
|
||||
|
||||
/// Encoded bytes retain the actual existing host lease. No detached byte getter.
|
||||
pub struct CompletedPng {
|
||||
@@ -154,7 +154,7 @@ impl<'a> FilmPngTask<'a> {
|
||||
let rgb = pass.film.pixel_statistics(self.pixel)?.mean;
|
||||
let mapped = crate::studio::tone_map(Vec3::new(rgb[0], rgb[1], rgb[2]) * self.scale)
|
||||
.map_err(|_| invalid("film exposure exceeds finite radiance range"))?;
|
||||
self.rgba.extend_from_slice(&[encode(mapped.x), encode(mapped.y), encode(mapped.z), 255]);
|
||||
self.rgba.extend_from_slice(&[encode8(mapped.x), encode8(mapped.y), encode8(mapped.z), 255]);
|
||||
self.pixel += 1;
|
||||
} else if self.writer.is_none() {
|
||||
charge(1)?;
|
||||
@@ -204,11 +204,6 @@ impl<'a> FilmPngTask<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(linear: f64) -> u8 {
|
||||
let srgb = if linear <= 0.0031308 { 12.92 * linear } else { 1.055 * linear.powf(1.0 / 2.4) - 0.055 };
|
||||
(srgb.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "film_png_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -83,6 +83,14 @@ fn finish(host: &ImageHost, handle: &JobHandle) {
|
||||
assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_pixel_shows_the_background_code_unchanged() {
|
||||
let display = Presentation { background: [40, 80, 120], ..Default::default() }.display(1, 1).unwrap();
|
||||
let mut rgba = [0; 4];
|
||||
display.encode(&[[0.0; 4]], &mut rgba, &CancelToken::default()).unwrap();
|
||||
assert_eq!(rgba, [40, 80, 120, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regrade_is_exact_nondestructive_geometry_free_and_flattens_repeated_master_ownership() {
|
||||
let (host, source, begins, settings) = fixture(true);
|
||||
|
||||
@@ -369,8 +369,7 @@ impl PhotographicState {
|
||||
let grain = (random(index as u32 ^ self.options.seed) - 0.5) * self.options.grain * (luminance + 0.03).sqrt();
|
||||
for channel in 0..3 {
|
||||
let linear = (rgb[channel] + flare[channel] + grain).max(0.0);
|
||||
let encoded = if linear <= 0.0031308 { linear * 12.92 } else { 1.055 * linear.powf(1.0 / 2.4) - 0.055 };
|
||||
self.output.push((encoded.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
self.output.push(solidcraft_geom::srgb::encode8(linear));
|
||||
}
|
||||
self.output.push(255);
|
||||
}
|
||||
|
||||
@@ -136,8 +136,7 @@ impl Display {
|
||||
let strength = self.finishing.bloom.map_or(0.0, |b| b.strength);
|
||||
value += strength * self.tone_map.map(f64::from(glow[channel]) * self.exposure * self.finishing.rgb_gain[channel]);
|
||||
}
|
||||
let encoded = if value <= 0.0031308 { value * 12.92 } else { 1.055 * value.powf(1. / 2.4) - 0.055 };
|
||||
*out = (encoded.clamp(0., 1.) * 255.).round() as u8;
|
||||
*out = solidcraft_geom::srgb::encode8(value);
|
||||
}
|
||||
rgba[3] = if self.transparent { (alpha * 255.0).round() as u8 } else { 255 };
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ fn nonselected_fixed_primary_matches_analytic_color_and_legacy_r_with_less_work(
|
||||
if !shadows {
|
||||
// White roughness-one conductor, constant RGB(1,.5,.25), fixed
|
||||
// 2x2 solid-angle strata: two z=.5 contributions average to1/3.
|
||||
let expected = [1.0 / 3.0, 1.0 / 6.0, 1.0 / 12.0].map(|v| encode(v / (1.0 + v)));
|
||||
let expected = [1.0 / 3.0, 1.0 / 6.0, 1.0 / 12.0].map(|v| encode8(v / (1.0 + v)));
|
||||
let image = ::image::load_from_memory(&fast).unwrap().to_rgba8();
|
||||
assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]);
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ fn real_cpu_png_conductor_matches_independent_environment_quadrature_once() {
|
||||
// Independent roughness-one white-conductor f*cos= z/(2*pi*(1+z)).
|
||||
// The fixed 8x8 solid-angle strata integrate 4 positive z rows, each 8 samples.
|
||||
let factor = [0.125, 0.375, 0.625, 0.875].into_iter().map(|z| z / (1.0 + z)).sum::<f64>() / 4.0;
|
||||
let expected = [factor, factor * 0.5, factor * 0.25].map(|r| encode(r / (1.0 + r)));
|
||||
let expected = [factor, factor * 0.5, factor * 0.25].map(|r| encode8(r / (1.0 + r)));
|
||||
assert_eq!(image.get_pixel(4, 4).0, [expected[0], expected[1], expected[2], 255]);
|
||||
assert_eq!(baseline.get_pixel(4, 4).0, [0, 0, 0, 255]);
|
||||
let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
|
||||
@@ -118,7 +118,7 @@ fn progressive_hdr_expected(samples: u32, seed: u32) -> [u8; 4] {
|
||||
let mean = sum / f64::from(samples);
|
||||
// The original HDR is constant linear RGB (1, 0.5, 0.25). Average in
|
||||
// linear space over ALL attempts, then apply the display response once.
|
||||
let rgb = [mean, mean * 0.5, mean * 0.25].map(|r| encode(r / (1.0 + r)));
|
||||
let rgb = [mean, mean * 0.5, mean * 0.25].map(|r| encode8(r / (1.0 + r)));
|
||||
[rgb[0], rgb[1], rgb[2], 255]
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ fn centre(bytes: &[u8]) -> [u8; 4] {
|
||||
::image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(4, 4).0
|
||||
}
|
||||
fn expected(radiance: [f64; 3]) -> [u8; 4] {
|
||||
let c = radiance.map(|v| encode(v / (1.0 + v)));
|
||||
let c = radiance.map(|v| encode8(v / (1.0 + v)));
|
||||
[c[0], c[1], c[2], 255]
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::{
|
||||
film::primary::PrimaryFilm,
|
||||
surface::{OpaqueSurface, srgb8_to_linear},
|
||||
};
|
||||
use solidcraft_geom::Vec3;
|
||||
use solidcraft_geom::{Vec3, srgb::encode8};
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "environment_image_tests.rs"]
|
||||
@@ -758,7 +758,7 @@ impl ImageTask {
|
||||
self.pending.clear();
|
||||
if self.sample == self.sample_count() {
|
||||
let display = map_to_display(self.pixel_radiance / self.sample as f64, self.options.exposure_ev).map_err(error)?;
|
||||
self.pixels.extend_from_slice(&[encode(display.x), encode(display.y), encode(display.z), 255]);
|
||||
self.pixels.extend_from_slice(&[encode8(display.x), encode8(display.y), encode8(display.z), 255]);
|
||||
self.pixel += 1;
|
||||
self.sample = 0;
|
||||
self.pixel_radiance = Vec3::ZERO;
|
||||
@@ -1641,7 +1641,7 @@ fn composite_spatial(premultiplied: Vec3, covered: u16, attempts: u16, backgroun
|
||||
let bg = Vec3::new(srgb8_to_linear(background[0]), srgb8_to_linear(background[1]), srgb8_to_linear(background[2]));
|
||||
geometry * coverage + bg * (1.0 - coverage)
|
||||
};
|
||||
Ok([encode(display.x), encode(display.y), encode(display.z), 255])
|
||||
Ok([encode8(display.x), encode8(display.y), encode8(display.z), 255])
|
||||
}
|
||||
|
||||
/// One sample preparation, one traversal operation OR one visible-sum operation.
|
||||
@@ -1734,11 +1734,6 @@ fn add_punctual_radiance(pending: &mut PendingPixel, contribution: Vec3, diagnos
|
||||
fn multiply(a: Vec3, b: Vec3) -> Vec3 {
|
||||
Vec3::new(a.x * b.x, a.y * b.y, a.z * b.z)
|
||||
}
|
||||
fn encode(c: f64) -> u8 {
|
||||
let s = if c <= 0.0031308 { 12.92 * c } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 };
|
||||
(s.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn shadow_ray(ray: Ray, hit: super::Hit, light: Vec3, vertices: [Vec3; 3]) -> super::Result<Ray> {
|
||||
let mut n = hit.geometry.geometric_normal;
|
||||
|
||||
@@ -59,7 +59,7 @@ fn emission_actual_png_adds_linear_radiance_once_and_never_lights_neighbor() {
|
||||
let image = ::image::load_from_memory(&emission_png(scene.clone(), request.clone(), options.clone())).unwrap().to_rgba8();
|
||||
let expected = [0.25, 0.5, 1.0].map(|c| {
|
||||
let v = c * 2.0_f64.powf(ev);
|
||||
encode(v / (1.0 + v))
|
||||
encode8(v / (1.0 + v))
|
||||
});
|
||||
assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]);
|
||||
assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255]);
|
||||
@@ -170,7 +170,7 @@ fn thirty_two_emission_bindings_resume_with_four_work_units_and_cancel_without_p
|
||||
assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_)));
|
||||
assert_eq!(task.work.used() - before, 1);
|
||||
assert_eq!(task.pixel, 1);
|
||||
assert_eq!(task.pixels, [encode(0.25 / 1.25), encode(0.5 / 1.5), encode(0.5), 255]);
|
||||
assert_eq!(task.pixels, [encode8(0.25 / 1.25), encode8(0.5 / 1.5), encode8(0.5), 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,7 +318,7 @@ fn actual_png_has_analytic_lit_and_cast_shadow_pixels() {
|
||||
// at normal view yields BRDF=1/[2*pi*(1+cosL)].
|
||||
let cosine = (0.5_f64).sqrt();
|
||||
let radiance = cosine / (2.0 * std::f64::consts::PI * (1.0 + cosine));
|
||||
let expected = encode(radiance / (1.0 + radiance));
|
||||
let expected = encode8(radiance / (1.0 + radiance));
|
||||
assert_eq!(unshadowed, [expected, expected, expected, 255]);
|
||||
assert_eq!(shadowed.get_pixel(7, 20), lit.get_pixel(7, 20), "unoccluded receiver changes when toggling shadows");
|
||||
}
|
||||
@@ -450,7 +450,7 @@ fn emission_primary_aa_and_reflection_attempts_preserve_single_linear_value() {
|
||||
samples: r,
|
||||
});
|
||||
let image = ::image::load_from_memory(&emission_png(scene, request, options)).unwrap().to_rgba8();
|
||||
assert_eq!(image.get_pixel(0, 0).0, [encode(0.25 / 1.25), encode(0.5 / 1.5), encode(0.5), 255], "S{s}/R{r}");
|
||||
assert_eq!(image.get_pixel(0, 0).0, [encode8(0.25 / 1.25), encode8(0.5 / 1.5), encode8(0.5), 255], "S{s}/R{r}");
|
||||
assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255], "emission does not illuminate the neighboring reflector");
|
||||
}
|
||||
}
|
||||
@@ -490,7 +490,7 @@ fn emission_and_directional_point_area_terms_share_one_linear_output_transform()
|
||||
// At normal incidence a white fully rough conductor has BRDF 1/(4*pi).
|
||||
// Point reference distance is 10 mm; the 4 mm² rectangle contributes 5*4/100.
|
||||
let direct = (2.0 + 3.0 + 5.0 * 4.0 / 100.0) / (4.0 * std::f64::consts::PI);
|
||||
let expected = [0.25, 0.5, 1.0].map(|e| encode((e + direct) / (1.0 + e + direct)));
|
||||
let expected = [0.25, 0.5, 1.0].map(|e| encode8((e + direct) / (1.0 + e + direct)));
|
||||
assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]);
|
||||
}
|
||||
|
||||
@@ -561,7 +561,7 @@ fn reflected_hit_adds_surface_emission_with_the_current_path_throughput() {
|
||||
let schlick = (1.0 - 0.5_f64.sqrt()).powi(5);
|
||||
let expected = [(0.2, 0.5), (0.5, 1.0), (0.75, 2.0)].map(|(f0, emitted)| {
|
||||
let radiance = (f0 + (1.0 - f0) * schlick) * emitted;
|
||||
encode(radiance / (1.0 + radiance))
|
||||
encode8(radiance / (1.0 + radiance))
|
||||
});
|
||||
assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]);
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ fn progressive_coverage_keeps_backplate_outside_exposure_and_tone_mapping() {
|
||||
let (_, half, _) = progressive_complete(progressive_fixture(64, 9, Some(true), exposure), 4);
|
||||
let covered = (0..64).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count();
|
||||
assert!(covered > 0 && covered < 64);
|
||||
let expected = encode(1.0 - covered as f64 / 64.0);
|
||||
let expected = encode8(1.0 - covered as f64 / 64.0);
|
||||
assert_eq!(::image::load_from_memory(&half).unwrap().to_rgba8().get_pixel(0, 0).0, [expected, expected, expected, 255]);
|
||||
}
|
||||
let (previews, _, _) = progressive_complete(progressive_fixture(5, 9, Some(true), 0.0), 1);
|
||||
@@ -102,12 +102,12 @@ fn progressive_resolves_the_mean_radiance_once_instead_of_averaging_display_pixe
|
||||
let mean = (left_count as f64 + (64 - left_count) as f64 * 9.0) / 64.0;
|
||||
let expected = [1.0, 0.5, 0.25].map(|color| {
|
||||
let exposed = mean * color * 2.0;
|
||||
encode(exposed / (1.0 + exposed))
|
||||
encode8(exposed / (1.0 + exposed))
|
||||
});
|
||||
let actual = ::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0;
|
||||
assert_eq!(actual, [expected[0], expected[1], expected[2], 255]);
|
||||
let fraction = left_count as f64 / 64.0;
|
||||
let prematurely_mapped = encode(fraction * (2.0 / 3.0) + (1.0 - fraction) * (18.0 / 19.0));
|
||||
let prematurely_mapped = encode8(fraction * (2.0 / 3.0) + (1.0 - fraction) * (18.0 / 19.0));
|
||||
assert_ne!(actual[0], prematurely_mapped, "each sample must remain linear until the whole pass resolves");
|
||||
}
|
||||
|
||||
@@ -281,15 +281,15 @@ fn fixed_grids_have_independent_analytic_halfplane_and_triangle_coverage() {
|
||||
#[test]
|
||||
fn compositor_keeps_conditional_scene_mean_then_display_linear_coverage() {
|
||||
// White L=1, Reinhard=1/2; half coverage over black gives1/4 display-linear.
|
||||
assert_eq!(composite_spatial(Vec3::new(0.5, 0.5, 0.5), 2, 4, [0; 3], 0.0).unwrap(), [encode(0.25), encode(0.25), encode(0.25), 255]);
|
||||
assert_ne!(encode(0.25), encode(1.0 / 3.0));
|
||||
assert_eq!(composite_spatial(Vec3::new(0.5, 0.5, 0.5), 2, 4, [0; 3], 0.0).unwrap(), [encode8(0.25), encode8(0.25), encode8(0.25), 255]);
|
||||
assert_ne!(encode8(0.25), encode8(1.0 / 3.0));
|
||||
// Full coverage of L=0 and L=2 usesT(mean)=1/2, not mean(T)=1/3.
|
||||
assert_eq!(composite_spatial(Vec3::new(1.0, 1.0, 1.0), 4, 4, [255; 3], 0.0).unwrap(), [encode(0.5), encode(0.5), encode(0.5), 255]);
|
||||
assert_eq!(composite_spatial(Vec3::new(1.0, 1.0, 1.0), 4, 4, [255; 3], 0.0).unwrap(), [encode8(0.5), encode8(0.5), encode8(0.5), 255]);
|
||||
for ev in [-16.0, 0.0, 16.0] {
|
||||
assert_eq!(composite_spatial(Vec3::ZERO, 0, 16, [13, 27, 41], ev).unwrap(), [13, 27, 41, 255]);
|
||||
}
|
||||
let gray = srgb8_to_linear(128);
|
||||
assert_eq!(composite_spatial(Vec3::ZERO, 2, 4, [128; 3], 0.0).unwrap(), [encode(gray * 0.5), encode(gray * 0.5), encode(gray * 0.5), 255]);
|
||||
assert_eq!(composite_spatial(Vec3::ZERO, 2, 4, [128; 3], 0.0).unwrap(), [encode8(gray * 0.5), encode8(gray * 0.5), encode8(gray * 0.5), 255]);
|
||||
assert!(composite_spatial(Vec3::ZERO, 5, 4, [0; 3], 0.0).is_err());
|
||||
assert!(composite_spatial(Vec3::X, 0, 4, [0; 3], 0.0).is_err());
|
||||
}
|
||||
@@ -306,7 +306,7 @@ fn real_hit_first_and_miss_first_silhouettes_keep_all_attempts_and_null_coverage
|
||||
let before = task.work.used();
|
||||
task.step(1).unwrap();
|
||||
assert_eq!(task.work.used(), before + 1);
|
||||
assert_eq!(task.pixels, [encode(0.5), encode(0.5), encode(0.5), 255]);
|
||||
assert_eq!(task.pixels, [encode8(0.5), encode8(0.5), encode8(0.5), 255]);
|
||||
assert_eq!(task.pixel, 1);
|
||||
}
|
||||
}
|
||||
@@ -439,7 +439,7 @@ fn actual_colored_lit_partial_coverage_wires_positive_radiance_exposure_and_back
|
||||
let expected: [u8; 3] = std::array::from_fn(|i| {
|
||||
let exposed = linear[i] * 2.0;
|
||||
let display = 0.5 * exposed / (1.0 + exposed) + 0.5 * srgb8_to_linear([13, 73, 139][i]);
|
||||
encode(display)
|
||||
encode8(display)
|
||||
});
|
||||
task.step(1).unwrap();
|
||||
assert_eq!(task.pixels, [expected[0], expected[1], expected[2], 255]);
|
||||
|
||||
@@ -76,7 +76,7 @@ fn actual_consumer_matches_analytic_rgb_and_finite_source_occlusion() {
|
||||
let cosine = 1.0 / 5.0_f64.sqrt();
|
||||
let l = 0.2 * cosine / (2.0 * std::f64::consts::PI * (1.0 + cosine));
|
||||
for (actual, factor) in lit.into_iter().take(3).zip([1.0, 0.5, 0.25]) {
|
||||
let expected = encode(l * factor / (1.0 + l * factor));
|
||||
let expected = encode8(l * factor / (1.0 + l * factor));
|
||||
assert!(actual.abs_diff(expected) <= 1, "actual={actual}, expected={expected}");
|
||||
}
|
||||
assert_eq!(render(task(Some((10.0, 5.0)), true)), [0, 0, 0, 255]);
|
||||
@@ -239,7 +239,7 @@ fn mixed_normal_incidence_radiance_is_summed_before_single_display_transform() {
|
||||
// White rough conductor at normal incidence: f*cos=1/(4*pi).
|
||||
// Eight unit directionals + eight unit point sources + four Le*A/r²=.08 rectangles.
|
||||
let linear = (8.0 + 8.0 + 4.0 * 0.08) / (4.0 * std::f64::consts::PI);
|
||||
let expected = encode(linear / (1.0 + linear));
|
||||
let expected = encode8(linear / (1.0 + linear));
|
||||
assert_eq!(render(task), [expected, expected, expected, 255]);
|
||||
}
|
||||
|
||||
|
||||
@@ -109,10 +109,7 @@ impl StagePanel {
|
||||
mesh.tri_face.extend([0, 0]);
|
||||
// The surface carries exact linear reflectance. This display colour is not
|
||||
// used as an additional multiplier by PBR consumers.
|
||||
let color = self.reflectance_linear.map(|x| {
|
||||
let encoded = if x <= 0.0031308 { 12.92 * x } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 };
|
||||
(encoded * 255.0).round() as u8
|
||||
});
|
||||
let color = self.reflectance_linear.map(solidcraft_geom::srgb::encode8);
|
||||
Ok(ProductMesh {
|
||||
name: format!("__render_stage__/{}", self.id),
|
||||
mesh: Arc::new(mesh),
|
||||
@@ -256,6 +253,8 @@ mod tests {
|
||||
assert_eq!(scene.meshes[0].mesh.triangles.len(), 2);
|
||||
assert_eq!(scene.meshes[0].surface.unwrap().dielectric_ior(), 1.0);
|
||||
assert!(scene.meshes[0].transmission.is_none());
|
||||
// Linear 0.18 shows as sRGB 118.
|
||||
assert_eq!(scene.meshes[0].color, [118; 3]);
|
||||
let before = scene.meshes[0].mesh.clone();
|
||||
assert!(stage.append_to(&mut scene, &CancelToken::default()).is_err());
|
||||
assert_eq!(scene.meshes.len(), 1);
|
||||
|
||||
@@ -138,11 +138,8 @@ impl OpaqueSurface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact piecewise sRGB decoding of an existing 8-bit color channel.
|
||||
pub fn srgb8_to_linear(channel: u8) -> f64 {
|
||||
let c = f64::from(channel) / 255.0;
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
/// Exact piecewise sRGB decoding of an existing 8-bit color channel ([`solidcraft_geom::srgb::decode8`]).
|
||||
pub use solidcraft_geom::srgb::decode8 as srgb8_to_linear;
|
||||
|
||||
/// Normalize finite directions without overflow or an arbitrary magnitude threshold.
|
||||
pub fn unit_direction(v: Vec3) -> Result<Vec3, SurfaceError> {
|
||||
@@ -272,12 +269,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srgb_conversion_includes_the_linear_toe() {
|
||||
assert_eq!(srgb8_to_linear(0), 0.0);
|
||||
assert_eq!(srgb8_to_linear(255), 1.0);
|
||||
assert!((srgb8_to_linear(10) - (10.0 / 255.0) / 12.92).abs() < 1e-15);
|
||||
assert!((srgb8_to_linear(128) - 0.21586050011389926).abs() < 1e-14);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ impl NormalizationSource {
|
||||
let linear = match conversion {
|
||||
ColorConversion::RawData => bounded,
|
||||
ColorConversion::PngGammaSrgbPrimaries { encoding_gamma } => bounded.powf(1.0 / encoding_gamma),
|
||||
_ => srgb_to_linear(bounded),
|
||||
_ => solidcraft_geom::srgb::decode(bounded),
|
||||
};
|
||||
if !linear.is_finite() || !(0.0..=1.0).contains(&linear) {
|
||||
return Err(invalid("normalization produced invalid linear/data channels"));
|
||||
@@ -271,9 +271,6 @@ fn digest_bytes(bytes: &[u8], cancelled: &impl Fn() -> bool) -> Result<String> {
|
||||
}
|
||||
Ok(format!("{:x}", digest.finalize()))
|
||||
}
|
||||
fn srgb_to_linear(value: f64) -> f64 {
|
||||
if value <= 0.04045 { value / 12.92 } else { ((value + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
fn destination_index(source: [u32; 2], output: [u32; 2], orientation: Orientation, x: u32, y: u32) -> Result<usize> {
|
||||
let [width, height] = source;
|
||||
if x >= width || y >= height || width == 0 || height == 0 {
|
||||
|
||||
@@ -276,10 +276,7 @@ pub(crate) fn icon_accent_for_tab(tab: &str) -> Option<&'static str> {
|
||||
/// WCAG contrast of two opaque sRGB colours.
|
||||
pub(crate) fn contrast_ratio(a: Color32, b: Color32) -> f64 {
|
||||
let luminance = |c: Color32| {
|
||||
let linear = |v: u8| {
|
||||
let v = f64::from(v) / 255.0;
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
};
|
||||
let linear = solidcraft_engine::geom::srgb::decode8;
|
||||
0.2126 * linear(c.r()) + 0.7152 * linear(c.g()) + 0.0722 * linear(c.b())
|
||||
};
|
||||
let (a, b) = (luminance(a), luminance(b));
|
||||
|
||||
Reference in New Issue
Block a user