Skip to main content

optic_color/
hsv.rs

1use crate::{RGBA, ToRgba};
2
3/// HSV color.
4///
5/// | Field | Range | Description |
6/// |-------|-------|-------------|
7/// | `h`   | 0..360 | Hue angle (wraps at 360) |
8/// | `s`   | 0..1   | Saturation |
9/// | `v`   | 0..1   | Value (brightness) |
10///
11/// # Why no arithmetic?
12///
13/// `HSV` does not implement [`ChannelArray`], [`Add`], [`Sub`], [`Mul`],
14/// or `lerp`. Hue is an angle on a circle — componentwise interpolation
15/// between 350° and 10° would pass through 180° instead of the short arc
16/// through 0°. This produces incorrect visual results.
17///
18/// To manipulate HSV colors, convert to [`RGBA`], do your math there,
19/// then convert back:
20///
21/// ```
22/// use optic_color::*;
23///
24/// let hsv = HSV::new(350.0, 0.8, 0.9);
25/// let mut rgba: RGBA = hsv.into();
26/// rgba = rgba.lighten(0.1);
27/// ```
28///
29/// For hue-aware interpolation between two colors, use [`Gradient`] with
30/// [`GradientColorSpace::Hsv`].
31///
32/// [`ChannelArray`]: crate::ChannelArray
33/// [`Gradient`]: crate::Gradient
34#[derive(Copy, Clone, Debug)]
35pub struct HSV {
36    pub h: f32,
37    pub s: f32,
38    pub v: f32,
39}
40
41impl HSV {
42    /// Construct an HSV color with clamping.
43    ///
44    /// Hue is clamped to 0..360, saturation and value to 0..1.
45    pub fn new(h: f32, s: f32, v: f32) -> Self {
46        HSV { h: h.clamp(0.0, 360.0), s: s.clamp(0.0, 1.0), v: v.clamp(0.0, 1.0) }
47    }
48
49    /// Convert to RGBA with a custom alpha, without going through [`ToRgba`].
50    ///
51    /// Equivalent to `self.to_rgba().with_alpha(alpha)`.
52    pub fn to_rgba_alpha(self, alpha: f32) -> RGBA {
53        self.to_rgba().with_alpha(alpha)
54    }
55}