bevy/crates/bevy_color
ickshonpe 453e0e4fc1
Prevent division by zero in HWBA to HSVA conversions (#14256)
# Problem

Division by zero in `crates/bevy_color/src/hsva.rs` when `blackness` is
`1`:

```rust
impl From<Hwba> for Hsva {
    fn from(
        Hwba {
            hue,
            whiteness,
            blackness,
            alpha,
        }: Hwba,
    ) -> Self {
        // Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion
        let value = 1. - blackness;
        let saturation = 1. - (whiteness / value);

        Hsva::new(hue, saturation, value, alpha)
    }
}
```

## Solution
With `Hsva` colors if the `value` component is set to `0.` the output
will be pure black regardless of the values of the `hue` or `saturation`
components.

So if `value` is `0`, we don't need to calculate a `saturation` value
and can just set it to `0`:

```rust
impl From<Hwba> for Hsva {
    fn from(
        Hwba {
            hue,
            whiteness,
            blackness,
            alpha,
        }: Hwba,
    ) -> Self {
        // Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion
        let value = 1. - blackness;
        let saturation = if value != 0. {
            1. - (whiteness / value)
        } else {
            0.
        };

        Hsva::new(hue, saturation, value, alpha)
    }
}

```

---------

Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
2024-07-22 18:22:26 +00:00
..
crates/gen_tests bevy_color: Add Oklch Color Space (#12168) 2024-02-28 01:22:55 +00:00
docs bevy_color: Added Color Conversion Mermaid Diagram (#12147) 2024-02-27 06:03:34 +00:00
src Prevent division by zero in HWBA to HSVA conversions (#14256) 2024-07-22 18:22:26 +00:00
Cargo.toml Bump Version after Release (#14219) 2024-07-08 12:54:08 +00:00
README.md Add README.md to all crates (#13184) 2024-05-02 18:56:00 +00:00

Bevy Color

License Crates.io Downloads Docs Discord