bevy_color/
lib.rs

1#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2#![forbid(unsafe_code)]
3#![doc(
4    html_logo_url = "https://bevyengine.org/assets/icon.png",
5    html_favicon_url = "https://bevyengine.org/assets/icon.png"
6)]
7
8//! Representations of colors in various color spaces.
9//!
10//! This crate provides a number of color representations, including:
11//!
12//! - [`Srgba`] (standard RGBA, with gamma correction)
13//! - [`LinearRgba`] (linear RGBA, without gamma correction)
14//! - [`Hsla`] (hue, saturation, lightness, alpha)
15//! - [`Hsva`] (hue, saturation, value, alpha)
16//! - [`Hwba`] (hue, whiteness, blackness, alpha)
17//! - [`Laba`] (lightness, a-axis, b-axis, alpha)
18//! - [`Lcha`] (lightness, chroma, hue, alpha)
19//! - [`Oklaba`] (lightness, a-axis, b-axis, alpha)
20//! - [`Oklcha`] (lightness, chroma, hue, alpha)
21//! - [`Xyza`] (x-axis, y-axis, z-axis, alpha)
22//!
23//! Each of these color spaces is represented as a distinct Rust type.
24//!
25//! # Color Space Usage
26//!
27//! Rendering engines typically use linear RGBA colors, which allow for physically accurate
28//! lighting calculations. However, linear RGBA colors are not perceptually uniform, because
29//! both human eyes and computer monitors have non-linear responses to light. "Standard" RGBA
30//! represents an industry-wide compromise designed to encode colors in a way that looks good to
31//! humans in as few bits as possible, but it is not suitable for lighting calculations.
32//!
33//! Most image file formats and scene graph formats use standard RGBA, because graphic design
34//! tools are intended to be used by humans. However, 3D lighting calculations operate in linear
35//! RGBA, so it is important to convert standard colors to linear before sending them to the GPU.
36//! Most Bevy APIs will handle this conversion automatically, but if you are writing a custom
37//! shader, you will need to do this conversion yourself.
38//!
39//! HSL and LCH are "cylindrical" color spaces, which means they represent colors as a combination
40//! of hue, saturation, and lightness (or chroma). These color spaces are useful for working
41//! with colors in an artistic way - for example, when creating gradients or color palettes.
42//! A gradient in HSL space from red to violet will produce a rainbow. The LCH color space is
43//! more perceptually accurate than HSL, but is less intuitive to work with.
44//!
45//! HSV and HWB are very closely related to HSL in their derivation, having identical definitions for
46//! hue. Where HSL uses saturation and lightness, HSV uses a slightly modified definition of saturation,
47//! and an analog of lightness in the form of value. In contrast, HWB instead uses whiteness and blackness
48//! parameters, which can be used to lighten and darken a particular hue respectively.
49//!
50//! Oklab and Oklch are perceptually uniform color spaces that are designed to be used for tasks such
51//! as image processing. They are not as widely used as the other color spaces, but are useful
52//! for tasks such as color correction and image analysis, where it is important to be able
53//! to do things like change color saturation without causing hue shifts.
54//!
55//! XYZ is a foundational space commonly used in the definition of other more modern color
56//! spaces. The space is more formally known as CIE 1931, where the `x` and `z` axes represent
57//! a form of chromaticity, while `y` defines an illuminance level.
58//!
59//! See also the [Wikipedia article on color spaces](https://en.wikipedia.org/wiki/Color_space).
60#![doc = include_str!("../docs/conversion.md")]
61//! <div>
62#![doc = include_str!("../docs/diagrams/model_graph.svg")]
63//! </div>
64//!
65//! # Other Utilities
66//!
67//! The crate also provides a number of color operations, such as blending, color difference,
68//! and color range operations.
69//!
70//! In addition, there is a [`Color`] enum that can represent any of the color
71//! types in this crate. This is useful when you need to store a color in a data structure
72//! that can't be generic over the color type.
73//!
74//! Color types that are either physically or perceptually linear also implement `Add<Self>`, `Sub<Self>`, `Mul<f32>` and `Div<f32>`
75//! allowing you to use them with splines.
76//!
77//! Please note that most often adding or subtracting colors is not what you may want.
78//! Please have a look at other operations like blending, lightening or mixing colors using e.g. [`Mix`] or [`Luminance`] instead.
79//!
80//! # Example
81//!
82//! ```
83//! use bevy_color::{Srgba, Hsla};
84//!
85//! let srgba = Srgba::new(0.5, 0.2, 0.8, 1.0);
86//! let hsla: Hsla = srgba.into();
87//!
88//! println!("Srgba: {:?}", srgba);
89//! println!("Hsla: {:?}", hsla);
90//! ```
91
92mod color;
93pub mod color_difference;
94mod color_gradient;
95mod color_ops;
96mod color_range;
97mod hsla;
98mod hsva;
99mod hwba;
100mod laba;
101mod lcha;
102mod linear_rgba;
103mod oklaba;
104mod oklcha;
105pub mod palettes;
106mod srgba;
107#[cfg(test)]
108mod test_colors;
109#[cfg(test)]
110mod testing;
111mod xyza;
112
113/// The color prelude.
114///
115/// This includes the most common types in this crate, re-exported for your convenience.
116pub mod prelude {
117    pub use crate::{
118        color::*, color_ops::*, hsla::*, hsva::*, hwba::*, laba::*, lcha::*, linear_rgba::*,
119        oklaba::*, oklcha::*, srgba::*, xyza::*,
120    };
121}
122
123pub use color::*;
124pub use color_gradient::*;
125pub use color_ops::*;
126pub use color_range::*;
127pub use hsla::*;
128pub use hsva::*;
129pub use hwba::*;
130pub use laba::*;
131pub use lcha::*;
132pub use linear_rgba::*;
133pub use oklaba::*;
134pub use oklcha::*;
135pub use srgba::*;
136pub use xyza::*;
137
138/// Describes the traits that a color should implement for consistency.
139#[allow(dead_code)] // This is an internal marker trait used to ensure that our color types impl the required traits
140pub(crate) trait StandardColor
141where
142    Self: core::fmt::Debug,
143    Self: Clone + Copy,
144    Self: PartialEq,
145    Self: Default,
146    Self: From<Color> + Into<Color>,
147    Self: From<Srgba> + Into<Srgba>,
148    Self: From<LinearRgba> + Into<LinearRgba>,
149    Self: From<Hsla> + Into<Hsla>,
150    Self: From<Hsva> + Into<Hsva>,
151    Self: From<Hwba> + Into<Hwba>,
152    Self: From<Laba> + Into<Laba>,
153    Self: From<Lcha> + Into<Lcha>,
154    Self: From<Oklaba> + Into<Oklaba>,
155    Self: From<Oklcha> + Into<Oklcha>,
156    Self: From<Xyza> + Into<Xyza>,
157    Self: Alpha,
158{
159}
160
161macro_rules! impl_componentwise_vector_space {
162    ($ty: ident, [$($element: ident),+]) => {
163        impl core::ops::Add<Self> for $ty {
164            type Output = Self;
165
166            fn add(self, rhs: Self) -> Self::Output {
167                Self::Output {
168                    $($element: self.$element + rhs.$element,)+
169                }
170            }
171        }
172
173        impl core::ops::AddAssign<Self> for $ty {
174            fn add_assign(&mut self, rhs: Self) {
175                *self = *self + rhs;
176            }
177        }
178
179        impl core::ops::Neg for $ty {
180            type Output = Self;
181
182            fn neg(self) -> Self::Output {
183                Self::Output {
184                    $($element: -self.$element,)+
185                }
186            }
187        }
188
189        impl core::ops::Sub<Self> for $ty {
190            type Output = Self;
191
192            fn sub(self, rhs: Self) -> Self::Output {
193                Self::Output {
194                    $($element: self.$element - rhs.$element,)+
195                }
196            }
197        }
198
199        impl core::ops::SubAssign<Self> for $ty {
200            fn sub_assign(&mut self, rhs: Self) {
201                *self = *self - rhs;
202            }
203        }
204
205        impl core::ops::Mul<f32> for $ty {
206            type Output = Self;
207
208            fn mul(self, rhs: f32) -> Self::Output {
209                Self::Output {
210                    $($element: self.$element * rhs,)+
211                }
212            }
213        }
214
215        impl core::ops::Mul<$ty> for f32 {
216            type Output = $ty;
217
218            fn mul(self, rhs: $ty) -> Self::Output {
219                Self::Output {
220                    $($element: self * rhs.$element,)+
221                }
222            }
223        }
224
225        impl core::ops::MulAssign<f32> for $ty {
226            fn mul_assign(&mut self, rhs: f32) {
227                *self = *self * rhs;
228            }
229        }
230
231        impl core::ops::Div<f32> for $ty {
232            type Output = Self;
233
234            fn div(self, rhs: f32) -> Self::Output {
235                Self::Output {
236                    $($element: self.$element / rhs,)+
237                }
238            }
239        }
240
241        impl core::ops::DivAssign<f32> for $ty {
242            fn div_assign(&mut self, rhs: f32) {
243                *self = *self / rhs;
244            }
245        }
246
247        impl bevy_math::VectorSpace for $ty {
248            const ZERO: Self = Self {
249                $($element: 0.0,)+
250            };
251        }
252    };
253}
254
255pub(crate) use impl_componentwise_vector_space;