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>
This commit is contained in:
ickshonpe 2024-07-22 19:22:26 +01:00 committed by GitHub
parent bc36b4e561
commit 453e0e4fc1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

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