1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! Traits and structs to perform encoding and decoding
//!
//! See the [`encoding`](../index.html) module level documentation for more information

use super::EncodableColor;
use crate::alpha::Rgba;
use crate::channel::{ChannelFormatCast, PosNormalChannelScalar};
use crate::color::Color;
use crate::rgb::Rgb;
use num_traits;
use std::fmt;

/// An object that can encode a color from a linear encoding to a different encoding
///
/// This is a low level trait that is unlikely to be used directly
pub trait ChannelEncoder {
    /// Encode a linearly-encoded channel
    fn encode_channel<T>(&self, val: T) -> T
    where
        T: num_traits::Float;
}
/// An object that can decode a color from some encoding to a linear encoding
///
/// This is a low level trait that is unlikely to be used directly
pub trait ChannelDecoder {
    /// Decode a channel into a linear-encoding
    fn decode_channel<T>(&self, val: T) -> T
    where
        T: num_traits::Float;
}

/// A color that can have its encoding changed
///
/// Because of the non-linear nature of encodings, only Rgb can have its encoding changed. The other
/// device-dependent colors can come from an encoding, and may be stored in `EncodedColor`, but
/// they must go through Rgb for that encoding to change.
pub trait TranscodableColor: Color + EncodableColor {
    /// The color type used internally to do conversions. This will always have floating-point channels
    type IntermediateColor;
    /// Encode `self` using the encoder `enc`
    fn encode_color<Encoder>(self, enc: &Encoder) -> Self
    where
        Encoder: ChannelEncoder;
    /// Decode `self` using the decoder `dec`
    fn decode_color<Decoder>(self, dec: &Decoder) -> Self
    where
        Decoder: ChannelDecoder;
}

/// An object able to encode and decode a color
pub trait ColorEncoding: ChannelEncoder + ChannelDecoder + Sized + Clone {}

/// An encoding scheme used by the sRGB color space.
///
/// sRGB features a small linear region at the lowest values, and then transitions to
/// a $`\gamma`$ of 2.4.
#[derive(Clone, Debug, PartialEq)]
pub struct SrgbEncoding;
/// A linear encoding scheme
#[derive(Clone, Debug, PartialEq)]
pub struct LinearEncoding;
/// A gamma encoding scheme with a given value for $`\gamma`$
#[derive(Clone, Debug, PartialEq)]
pub struct GammaEncoding<T>(pub T);

impl SrgbEncoding {
    /// Construct a new SrgbEncoding
    pub fn new() -> Self {
        SrgbEncoding {}
    }
}

impl ChannelDecoder for SrgbEncoding {
    fn decode_channel<T>(&self, val: T) -> T
    where
        T: num_traits::Float,
    {
        let one: T = num_traits::cast(1.0).unwrap();
        let a: T = num_traits::cast(0.055).unwrap();
        let k: T = num_traits::cast(12.92).unwrap();
        let gamma: T = num_traits::cast(2.4).unwrap();
        let linear_threshold: T = num_traits::cast(0.04045).unwrap();

        if val.abs() < linear_threshold {
            val / k
        } else {
            let operand = (val.abs() + a) / (one + a);
            val.signum() * operand.powf(gamma)
        }
    }
}

impl ChannelEncoder for SrgbEncoding {
    fn encode_channel<T>(&self, val: T) -> T
    where
        T: num_traits::Float,
    {
        let one: T = num_traits::cast(1.0).unwrap();
        let a: T = num_traits::cast(0.055).unwrap();
        let k: T = num_traits::cast(12.92).unwrap();
        let gamma: T = num_traits::cast(2.4).unwrap();
        let linear_threshold: T = num_traits::cast(0.0031308).unwrap();

        if val.abs() < linear_threshold {
            k * val
        } else {
            val.signum() * ((one + a) * val.abs().powf(one / gamma) - a)
        }
    }
}

impl ColorEncoding for SrgbEncoding {}

impl Default for SrgbEncoding {
    fn default() -> Self {
        SrgbEncoding {}
    }
}

impl fmt::Display for SrgbEncoding {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "sRgb")
    }
}

impl LinearEncoding {
    /// Construct a new `LinearEncoding`
    pub fn new() -> Self {
        LinearEncoding {}
    }
}

impl ChannelDecoder for LinearEncoding {
    fn decode_channel<T>(&self, val: T) -> T
    where
        T: num_traits::Float,
    {
        val
    }
}

impl ChannelEncoder for LinearEncoding {
    fn encode_channel<T>(&self, val: T) -> T
    where
        T: num_traits::Float,
    {
        val
    }
}

impl ColorEncoding for LinearEncoding {}

impl Default for LinearEncoding {
    fn default() -> Self {
        LinearEncoding {}
    }
}

impl fmt::Display for LinearEncoding {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Linear")
    }
}

impl<T> GammaEncoding<T>
where
    T: num_traits::Float,
{
    /// Construct a new `GammaEncoding`
    pub fn new(val: T) -> Self {
        GammaEncoding(val)
    }
    /// Return the gamma exponent value
    pub fn exponent(&self) -> T {
        self.0
    }
}

impl<T> ChannelDecoder for GammaEncoding<T>
where
    T: num_traits::Float,
{
    fn decode_channel<U>(&self, val: U) -> U
    where
        U: num_traits::Float,
    {
        val.signum() * val.abs().powf(num_traits::cast(self.0).unwrap())
    }
}
impl<T> ChannelEncoder for GammaEncoding<T>
where
    T: num_traits::Float,
{
    fn encode_channel<U>(&self, val: U) -> U
    where
        U: num_traits::Float,
    {
        let one: T = num_traits::cast(1.0).unwrap();
        val.signum() * val.abs().powf(num_traits::cast(one / self.0).unwrap())
    }
}

impl<T: num_traits::Float> ColorEncoding for GammaEncoding<T> {}

impl<T: num_traits::Float> Default for GammaEncoding<T> {
    fn default() -> Self {
        GammaEncoding::new(num_traits::cast(2.2).unwrap())
    }
}

impl<T> fmt::Display for GammaEncoding<T>
where
    T: num_traits::Float + fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "γ={}", self.0)
    }
}

impl<T> TranscodableColor for Rgb<T>
where
    T: PosNormalChannelScalar + ChannelFormatCast<f64>,
    f64: ChannelFormatCast<T>,
{
    type IntermediateColor = Rgb<f64>;
    fn encode_color<Encoder>(self, enc: &Encoder) -> Self
    where
        Encoder: ChannelEncoder,
    {
        let flt_color: Self::IntermediateColor = self.color_cast();

        let enc_r = enc.encode_channel(flt_color.red());
        let enc_g = enc.encode_channel(flt_color.green());
        let enc_b = enc.encode_channel(flt_color.blue());

        let out_color: Rgb<T> = Rgb::new(enc_r, enc_g, enc_b).color_cast();

        out_color
    }

    fn decode_color<Decoder>(self, dec: &Decoder) -> Self
    where
        Decoder: ChannelDecoder,
    {
        let flt_color: Self::IntermediateColor = self.color_cast();

        let linear_r = dec.decode_channel(flt_color.red());
        let linear_g = dec.decode_channel(flt_color.green());
        let linear_b = dec.decode_channel(flt_color.blue());

        let out_color: Rgb<T> = Rgb::new(linear_r, linear_g, linear_b).color_cast();

        out_color
    }
}

impl<T> TranscodableColor for Rgba<T>
where
    T: PosNormalChannelScalar + ChannelFormatCast<f64>,
    f64: ChannelFormatCast<T>,
{
    type IntermediateColor = Rgba<f64>;

    fn encode_color<Encoder>(self, enc: &Encoder) -> Self
    where
        Encoder: ChannelEncoder,
    {
        let (color, alpha) = self.decompose();
        let inner_color = color.encode_color(enc);
        Rgba::new(inner_color, alpha)
    }

    fn decode_color<Decoder>(self, dec: &Decoder) -> Self
    where
        Decoder: ChannelDecoder,
    {
        let (color, alpha) = self.decompose();
        let inner_color = color.decode_color(dec);
        Rgba::new(inner_color, alpha)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::color::*;
    use crate::encoding::EncodableColor;
    use crate::rgb::Rgb;
    use approx::*;

    #[test]
    fn test_gamma_encoding() {
        let c1 = Rgb::new(0.0, 0.0, 0.0).encoded_as(LinearEncoding::new());
        let t1 = c1.clone().encode(GammaEncoding::new(2.0));
        assert_relative_eq!(t1.color(), c1.color(), epsilon = 1e-6);

        let c2 = Rgb::new(1.0, 1.0, 1.0).encoded_as(LinearEncoding::new());
        let t2 = c2.clone().encode(GammaEncoding::new(2.2));
        assert_relative_eq!(t2.color(), c2.color(), epsilon = 1e-6);

        let c3 = Rgb::new(0.5, 0.5, 0.5).encoded_as(LinearEncoding::new());
        let t3 = c3.clone().encode(GammaEncoding::new(2.2));
        assert_relative_eq!(*t3.color(), Rgb::broadcast(0.72974005), epsilon = 1e-6);
        assert_relative_eq!(t3.decode(), c3, epsilon = 1e-6);

        let c4 = Rgb::new(0.2, 0.8, 0.66).encoded_as(LinearEncoding::new());
        let t4 = c4.clone().encode(GammaEncoding::new(1.8));
        assert_relative_eq!(
            *t4.color(),
            Rgb::new(0.4089623, 0.88340754, 0.793864955),
            epsilon = 1e-6
        );
        assert_relative_eq!(t4.decode(), c4, epsilon = 1e-6);

        let c5 = Rgb::new(0.5, 0.5, 0.5).encoded_as(GammaEncoding::new(2.4));
        let t5 = c5.clone().decode();
        assert_relative_eq!(*t5.color(), Rgb::broadcast(0.18946457), epsilon = 1e-6);

        let c6 = Rgb::new(-0.3, 0.0, -1.0).encoded_as(GammaEncoding::new(2.2));
        let t6 = c6.clone().decode();
        assert_relative_eq!(*t6.color(), Rgb::new(-0.0707403, 0.0, -1.0), epsilon = 1e-6);
        assert_relative_eq!(t6.encode(GammaEncoding::new(2.2)), c6, epsilon = 1e-6);
    }

    #[test]
    fn test_srgb_encoding() {
        let c1 = Rgb::new(0.0, 0.0, 0.0).encoded_as(LinearEncoding::new());
        let t1 = c1.clone().encode(SrgbEncoding::new());
        assert_relative_eq!(t1.color(), c1.color(), epsilon = 1e-6);

        let c2 = Rgb::new(1.0, 1.0, 1.0).encoded_as(LinearEncoding::new());
        let t2 = c2.clone().encode(SrgbEncoding::new());
        assert_relative_eq!(t2.color(), c2.color(), epsilon = 1e-6);

        let c3 = Rgb::new(0.5, 0.5, 0.5).encoded_as(LinearEncoding::new());
        let t3 = c3.clone().encode(SrgbEncoding::new());
        assert_relative_eq!(*t3.color(), Rgb::broadcast(0.735356983052), epsilon = 1e-6);
        assert_relative_eq!(t3.decode(), c3, epsilon = 1e-6);

        let c4 = Rgb::new(0.2, 0.8, 0.66).encoded_as(LinearEncoding::new());
        let t4 = c4.clone().encode(SrgbEncoding::new());
        assert_relative_eq!(
            *t4.color(),
            Rgb::new(0.4845292044, 0.90633175, 0.83228355590),
            epsilon = 1e-6
        );
        assert_relative_eq!(t4.decode(), c4, epsilon = 1e-6);

        let c5 = Rgb::new(0.5, 0.5, 0.5).encoded_as(SrgbEncoding::new());
        let t5 = c5.clone().decode();
        assert_relative_eq!(*t5.color(), Rgb::broadcast(0.21404114048), epsilon = 1e-6);

        let c6 = Rgb::new(-0.25, -0.74, -1.00).encoded_as(LinearEncoding::new());
        let t6 = c6.clone().encode(SrgbEncoding::new());
        assert_relative_eq!(
            *t6.color(),
            Rgb::new(-0.5370987, -0.8756056, -1.00),
            epsilon = 1e-6
        );
        assert_relative_eq!(t6.decode(), c6, epsilon = 1e-6);
    }
}