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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//
// GLM-COLOR
//
// Copyright (c) 2015 The glm-color authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use glm::*;
use glm::ext::*;
use super::space::ColorSpace;
use super::rgb::Rgb;
use std::mem;
use rand::{ Rand, Rng, thread_rng };

/// The HSV color space.
///
/// # See
///
/// - ["HSV" in Wikipedia](http://en.wikipedia.org/wiki/HSL_and_HSV).
/// - An excellent [tutorial of color theory in worqx.com](http://www.worqx.com/color/index.htm).
/// - [How to choose colours procedurally](http://devmag.org.za/2012/07/29/how-to-choose-colours-procedurally-algorithms/).
/// - [Tints and shades](http://en.wikipedia.org/wiki/Tints_and_shades).
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Hsv {
    h: f32,
    s: f32,
    v: f32
}

impl Rand for Hsv {
    #[inline]
    fn rand<R: Rng>(rng: &mut R) -> Hsv {
        let h = rng.gen::<f32>() * f32::tau();
        let s = rng.gen();
        let b = rng.gen();
        Hsv { h: h, s: s, v: b }
    }
}

impl Hsv {
    /// Constructs an `Hsv` value from given `hue`, `saturation` and
    /// `brightness` values.
    ///
    /// Parameter `hue` is clampped to the interval _[0, 2π)_, and
    /// `saturation` and `brightness` are clampped to interval _[0, 1]_.
    ///
    /// # Example
    ///
    /// ```rust
    /// use glm_color::*;
    ///
    /// let red = Hsv::new(7., 2., 1.);
    /// assert_eq!(red.hue(), 0.);
    /// assert_eq!(red.saturation(), 1.);
    /// ```
    #[inline]
    pub fn new(hue: f32, saturation: f32, brightness: f32) -> Hsv {
        let pi2 = tau();
        let mut h = clamp(hue, 0., pi2);
        if h == pi2 {
            h = 0.
        };
        let s = clamp(saturation, 0., 1.);
        let b = clamp(brightness, 0., 1.);
        Hsv { h: h, s: s, v: b }
    }

    /// Constructs an `Hsv` value by randomly choosing values for each of the
    /// three HSV channels using the thread local RNG.
    ///
    /// # Note
    ///
    /// As the `Rgb::rand()` function, this function is not good for
    /// generating the whole color palette.
    #[inline]
    pub fn rand() -> Hsv {
        let mut rng = thread_rng();
        rng.gen()
    }

    /// Constructs an `Hsv` from hue value `degree`, which is the angle on the
    /// color wheel.
    ///
    /// Both saturation and brightness of the returned value are set to `1.0`.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate glm;
    /// # extern crate glm_color;
    /// # fn main() {
    /// use glm::*;
    /// use glm_color::*;
    ///
    /// let y = Hsv::from_hue(radians(60.));
    /// assert_eq!(y.hue(), glm::radians(60.));
    /// assert_eq!(y.saturation(), 1.);
    /// assert_eq!(y.brightness(), 1.);
    /// # }
    /// ```
    #[inline]
    pub fn from_hue(h: f32) -> Hsv {
        let mut clr = Hsv { h: 0., s: 1., v: 1. };
        clr.set_hue(h);
        clr
    }

    /// Returns the hue of _self_.
    #[inline]
    pub fn hue(&self) -> f32 {
        self.h
    }

    /// Returns the saturation of _self_.
    #[inline]
    pub fn saturation(&self) -> f32 {
        self.s
    }

    /// Returns the brightness of _self_.
    #[inline]
    pub fn brightness(&self) -> f32 {
        self.v
    }

    /// Changes _self_'s hue value to `h`.
    ///
    /// The parameter `h` is clampped to the range [0, 2π).
    #[inline]
    pub fn set_hue(&mut self, h: f32) {
        let pi2 = tau();
        let mut hv = clamp(h, 0., pi2);
        if hv == pi2 {
            hv = 0.;
        }
        self.h = hv
    }

    /// Returns a new `Hsv` value with given hue value `h`, and saturation and
    /// brightness values from _self_.
    #[inline]
    pub fn with_hue(&self, h: f32) -> Hsv {
        let mut c = *self;
        c.set_hue(h);
        c
    }

    /// Changes _self_'s saturation value to `s`.
    ///
    /// The parameter 's' is clampped to the rnage [0, 1];
    #[inline]
    pub fn set_saturation(&mut self, s: f32) {
        self.s = clamp(s, 0., 1.);
    }

    /// Returns a new `Hsv` value with given saturation value `s`, and hue and
    /// brightness values from _self_.
    #[inline]
    pub fn with_saturation(&self, s: f32) -> Hsv {
        let mut c = *self;
        c.set_saturation(s);
        c
    }

    /// Changes _self_'s brightness value to `b`.
    ///
    /// The parameter 'b' will be clampped to the rnage [0, 1];
    #[inline]
    pub fn set_brightness(&mut self, b: f32) {
        self.v = clamp(b, 0., 1.);
    }

    /// Returns a new `Hsv` value with given brightness value `b`, and hue and
    /// saturation values from _self_.
    #[inline]
    pub fn with_brightness(&self, b: f32) -> Hsv {
        let mut c = *self;
        c.set_brightness(b);
        c
    }

    /// Re-interpret the reference of `Hsv` to `Vec3`.
    #[inline(always)]
    pub fn as_vec3(&self) -> &Vec3 {
        let vec: &Vec3 = unsafe { mem::transmute(self) };
        vec
    }

    /// Returns the complementary color of _self_.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate glm;
    /// # extern crate glm_color;
    /// # fn main() {
    /// use glm::*;
    /// use glm::ext::pi;
    /// use glm_color::*;
    ///
    /// let red = Hsv::from_hue(0.);
    /// let green = Hsv::from_hue(pi());
    /// assert_eq!(red.complement(), green);
    /// # }
    /// ```
    #[inline]
    pub fn complement(&self) -> Hsv {
        self.with_hue(fmod(self.hue() + f32::pi(), tau()))
    }

    /// Returns a pair of colors that are splited from the complementary color
    /// of _self_,
    ///
    /// The 2 colors have same distances to the complementary color on the
    /// color wheel. In our implementation, this distance is fixed to `30`
    /// degrees.
    #[inline]
    pub fn split_complement(&self) -> (Self, Self) {
        let pi2 = tau();
        let h1 = fmod(self.hue() + radians(150.), pi2);
        let h2 = fmod(self.hue() + radians(210.), pi2);
        (self.with_hue(h1), self.with_hue(h2))
    }

    /// Returns 2 pairs of complementary colors. The first colors of both pairs
    /// are the result of `split_complement` of _self_.
    ///
    // TODO: Example
    #[inline]
    pub fn double_complement(&self) -> ((Self, Self), (Self, Self)) {
        let (c1, c2) = self.split_complement();
        ((c1.complement(), c1), (c2.complement(), c2))
    }

    /// Returns other 2 colors of triad colors that includes _self_.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate glm;
    /// # extern crate glm_color;
    /// # fn main() {
    /// use glm::*;
    /// use glm_color::*;
    ///
    /// let red = Hsv::from_rgb(RED);
    /// let (green, blue) = red.triad();
    ///
    /// assert!(is_close_to(&green.hue(), &radians(120.), 0.000001));
    /// assert!(is_close_to(&blue.hue(), &radians(240.), 0.000001));
    /// # }
    /// ```
    #[inline]
    pub fn triad(&self) -> (Hsv, Hsv) {
        let pi2 = tau();
        let d120 = radians(120.);
        let h1 = fmod(self.hue() + d120, pi2);
        let h2 = fmod(self.hue() + d120 + d120, pi2);
        (self.with_hue(h1), self.with_hue(h2))
    }

    /// Returns `n` colors that are analogous to the receiver.
    ///
    // TODO: Example
    #[inline]
    pub fn analogs(&self, n: usize, span: f32) -> Vec<Hsv> {
        if span == 0. || n == 0 {
            vec!()
        } else {
            let d = span / (n as f32);
            let h = self.hue();
            (0..n).map(|i| -> Hsv {
                let hue = fmod(h + d * (i as f32), tau());
                Hsv { h: hue, s: self.s, v: self.v }
            }).collect()
        }
    }

    /// Returns `n` colors distributed on the color wheel evenly.
    ///
    /// The returned colors have full saturation and lightness. Red is the
    /// first color in the vector.
    ///
    /// If `n` is `0`, an empty vector is returned.
    ///
    /// # Example
    ///
    /// ```rust
    /// use glm_color::*;
    ///
    /// let cs0 = Hsv::color_wheel(0);
    /// assert_eq!(cs0.len(), 0);
    /// let cs1 = Hsv::color_wheel(1);
    /// assert_eq!(cs1[0], Hsv::from_hue(0.));
    /// let csn = Hsv::color_wheel(3);
    /// assert_eq!(csn.len(), 3);
    /// ```
    #[inline]
    pub fn color_wheel(n: usize) -> Vec<Hsv> {
        let red = Hsv::from_hue(0.);
        red.analogs(n, tau())
    }

    /// Produces a color by adding white to the receiver.
    ///
    /// For `Hsv` color model, adding white means increasing the lightness.
    ///
    /// Parameter `amt` specifies absolute lightness to be added.
    ///
    /// # Example
    ///
    /// ```rust
    /// use glm_color::*;
    ///
    /// let red = Hsv::new(1., 0.5, 0.2);
    /// assert_eq!(red.tint(1.), Hsv::new(1., 0.5, 1.));
    /// ```
    #[inline]
    pub fn tint(&self, amt: f32) -> Hsv {
        let b = clamp(amt, 0., 1.);
        self.with_brightness(self.brightness() + b)
    }

    /// Produces a vector of `n` colors whose brightness increase monotonically
    /// and evenly.
    ///
    /// If `n` is `0`, returns an empty vector.
    ///
    /// Other wise, the receiver is the first element of the vector and a
    /// color with full brightness is the last.
    ///
    /// # Example
    ///
    /// ```rust
    /// use glm_color::*;
    ///
    /// let red: Hsv = from_rgb(RED);
    /// let clrs = red.tints(3);
    ///
    /// ```
    #[inline]
    pub fn tints(&self, n: usize) -> Vec<Hsv> {
        if n == 0 {
            vec!()
        } else {
            let b = self.brightness();
            let d = (1. - b) / (n as f32);
            (0..n).map(|i| {
                self.with_brightness(b + d * (i as f32))
            }).collect()
        }
    }

    /// Produces a color by adding black to the receiver.
    #[inline]
    pub fn shade(&self, amt: f32) -> Hsv {
        let b = clamp(amt, 0., 1.);
        self.with_brightness(self.brightness() - b)
    }

    /// Produces`n` colors whose brightness decrease monotonically and evenly.
    #[inline]
    pub fn shades(&self, n: usize) -> Vec<Hsv> {
        if n == 0 {
            vec!()
        } else {
            let b = self.brightness();
            let d = self.brightness() / (n as f32);
            (0..n).map(|i| {
                self.with_brightness(b - d * (i as f32))
            }).collect()
        }
    }

    /// Produces a color by adding gray to the receiver.
    #[inline]
    pub fn tone(&self, amt: f32) -> Hsv {
        let s = clamp(amt, 0., 1.);
        self.with_saturation(self.saturation() - s)
    }

    /// Produces `n` colors whose saturation decrease monotonically and evenly.
    #[inline]
    pub fn tones(&self, n: usize) -> Vec<Hsv> {
        if n == 0 {
            vec!()
        } else {
            let s = self.saturation();
            let d = (1. - s) / (n as f32);
            (0..n).map(|i| {
                self.with_brightness(s + d * (i as f32))
            }).collect()
        }
    }
}

/// Equivalent to call `Hsv::new(h, s, v)`.
#[inline]
pub fn hsv(h: f32, s: f32, v: f32) -> Hsv {
    Hsv::new(h, s, v)
}

impl Eq for Hsv {}

impl ApproxEq for Hsv {
    type BaseType = f32;
    #[inline]
    fn is_close_to(&self, other: &Hsv, max_diff: f32) -> bool {
        self.as_vec3().is_close_to(other.as_vec3(), max_diff)
    }
}

impl ColorSpace for Hsv {
    #[inline]
    fn from_rgb(rgb: Rgb) -> Hsv {
        Hsv { h: rgb.hue(), s: rgb.saturation(), v: rgb.brightness() }
    }
    #[inline]
    fn to_rgb(&self) -> Rgb {
        let Hsv { h, s, v } = *self;
        if is_approx_eq(&s, &0.) {
            Rgb::new(v, v, v)
        } else {
            let hv = degrees(h) / 60.;
            let hi = floor(hv) % 6.;
            let f = hv - hi;
            let p = v * (1. - s);
            let q = v * (1. - f * s);
            let t = v * (1. - (1. - f) * s);
            match hi {
                0. => Rgb::new(v, t, p),
                1. => Rgb::new(q, v, p),
                2. => Rgb::new(p, v, t),
                3. => Rgb::new(p, q, v),
                4. => Rgb::new(t, p, v),
                5. => Rgb::new(v, p, q),
                _ => unreachable!(),
            }
        }
    }
}

#[cfg(test)]
mod test {

    use glm::*;
    use space::ColorSpace;
    use rgb::{ Rgb, gray };
    use super::Hsv;
    use quickcheck::*;

    #[test]
    fn test_to_rgb() {
        fn prop(clr: Rgb) -> bool {
            let hsv: Hsv = ColorSpace::from_rgb(clr);
            hsv.to_rgb().is_close_to(&clr, 0.000001)
        }
        quickcheck(prop as fn(Rgb) -> bool)
    }

    #[test]
    fn test_to_rgb_gray() {
        fn prop(v: f32) -> bool {
            let gray = Rgb::new(v, v, v);
            let hsv: Hsv = ColorSpace::from_rgb(gray);
            hsv.saturation() == 0. &&
            hsv.to_rgb().is_close_to(&gray, 0.000001)
        }
        quickcheck(prop as fn(f32) -> bool)
    }
}