From 88478ebecf67fe4a3e65c009780e6ff3e40644b9 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Thu, 26 Mar 2020 23:43:22 +0100 Subject: [PATCH 1/2] library: core: linearcolor: fix must_use attributes --- pathtracer/src/core/color.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pathtracer/src/core/color.rs b/pathtracer/src/core/color.rs index 5a90730..be62c37 100644 --- a/pathtracer/src/core/color.rs +++ b/pathtracer/src/core/color.rs @@ -49,6 +49,7 @@ impl LinearColor { /// } /// ); /// ``` + #[must_use] pub fn black() -> Self { LinearColor { r: 0., @@ -66,11 +67,11 @@ impl LinearColor { /// # /// let color = LinearColor::new(1.0, 0.0, 0.0); // bright red! /// ``` + #[must_use] pub fn new(r: f32, g: f32, b: f32) -> Self { LinearColor { r, g, b } } - #[must_use] /// Clamps the color's RGB components between 0.0 and 1.0. /// /// # Examples @@ -81,6 +82,7 @@ impl LinearColor { /// let color = LinearColor::new(1.5, -1.0, 0.5); /// assert_eq!(color.clamp(), LinearColor::new(1.0, 0.0, 0.5)) /// ``` + #[must_use] pub fn clamp(self) -> Self { fn clamp(v: f32) -> f32 { if v > 1. { From 0cfd9ee81d6374ce8c589cbb10b2b4fe4673551e Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Thu, 26 Mar 2020 23:43:38 +0100 Subject: [PATCH 2/2] library: core: linearcolor: gamma correct on output --- pathtracer/src/core/color.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/pathtracer/src/core/color.rs b/pathtracer/src/core/color.rs index be62c37..8db83b0 100644 --- a/pathtracer/src/core/color.rs +++ b/pathtracer/src/core/color.rs @@ -29,6 +29,8 @@ pub struct LinearColor { pub b: f32, } +const GAMMA: f32 = 2.2; + impl LinearColor { /// Creates the color black. /// @@ -95,6 +97,26 @@ impl LinearColor { }; LinearColor::new(clamp(self.r), clamp(self.g), clamp(self.b)) } + + /// Encode the linear color into the gamma corrected space, as expected by most picture + /// formats. + #[must_use] + pub fn gamma_encode(self) -> Self { + fn gamma(val: f32) -> f32 { + val.powf(1.0 / GAMMA) + }; + LinearColor::new(gamma(self.r), gamma(self.g), gamma(self.b)) + } + + /// Decode the linear color from the gamma corrected space, which is used in most picture + /// formats. + #[must_use] + pub fn gamma_decode(self) -> Self { + fn gamma(val: f32) -> f32 { + val.powf(GAMMA) + }; + LinearColor::new(gamma(self.r), gamma(self.g), gamma(self.b)) + } } impl Default for LinearColor { @@ -140,8 +162,8 @@ impl DivAssign for LinearColor { } impl From for image::Rgb { - fn from(mut color: LinearColor) -> Self { - color = color.clamp(); + fn from(color: LinearColor) -> Self { + let color = color.clamp().gamma_encode(); image::Rgb([ (color.r * 255.) as u8, (color.g * 255.) as u8,