From 453e0e4fc1ef669bc702dce20111e83b341b4041 Mon Sep 17 00:00:00 2001 From: ickshonpe Date: Mon, 22 Jul 2024 19:22:26 +0100 Subject: [PATCH] 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 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 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> --- crates/bevy_color/src/hsva.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/bevy_color/src/hsva.rs b/crates/bevy_color/src/hsva.rs index 3e6fefce05..e708ccf67e 100644 --- a/crates/bevy_color/src/hsva.rs +++ b/crates/bevy_color/src/hsva.rs @@ -157,7 +157,11 @@ impl From for Hsva { ) -> Self { // Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion 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) }