Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clamp NaN to white when converting to integer #2381

Merged
merged 5 commits into from
Nov 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,17 +385,24 @@ impl<T: Primitive> FromPrimitive<T> for T {
// Note that in to-integer-conversion we are performing rounding but NumCast::from is implemented
// as truncate towards zero. We emulate rounding by adding a bias.

// All other special values are clamped inbetween 0.0 and 1.0 (infinities and subnormals)
// NaN however always maps to NaN therefore we have to force it towards some value.
// 1.0 (white) was picked as firefox and chrome choose to map NaN to that.
#[inline]
fn normalize_float(float: f32, max: f32) -> f32 {
let clamped = if !(float < 1.0) { 1.0 } else { float.max(0.0) };
(clamped * max).round()
}

impl FromPrimitive<f32> for u8 {
fn from_primitive(float: f32) -> Self {
let inner = (float.clamp(0.0, 1.0) * u8::MAX as f32).round();
NumCast::from(inner).unwrap()
NumCast::from(normalize_float(float, u8::MAX as f32)).unwrap()
}
}

impl FromPrimitive<f32> for u16 {
fn from_primitive(float: f32) -> Self {
let inner = (float.clamp(0.0, 1.0) * u16::MAX as f32).round();
NumCast::from(inner).unwrap()
NumCast::from(normalize_float(float, u16::MAX as f32)).unwrap()
}
}

Expand Down
Loading