pub const INSTANCE_BYTES: usize = 36;
pub const KIND_ARC: u32 = 1;
pub const START_JOINT: u32 = 1 << 2;
pub const END_JOINT: u32 = 1 << 3;
pub fn pack_direction(x: f64, y: f64) -> u32 {
let snorm = |v: f64| u32::from((v.clamp(-1., 1.) * 32767.).round() as i16 as u16);
snorm(x) | (snorm(y) << 16)
}
pub const fn premultiply(color: [u8; 4]) -> [u8; 4] {
let [r, g, b, a] = color;
match a {
0 => [0, 0, 0, 0],
255 => color,
_ => [mul(r, a), mul(g, a), mul(b, a), a],
}
}
const fn mul(value: u8, frac: u8) -> u8 {
let p = (value as u16) * (frac as u16) + 128;
((p + (p >> 8)) >> 8) as u8
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn premultiply_rounds_like_floating_point() {
for value in 0..=255u8 {
for alpha in 1..=254u8 {
let exact = (f64::from(value) * f64::from(alpha) / 255.).round() as u8;
assert_eq!(mul(value, alpha), exact, "{value} * {alpha}");
}
}
assert_eq!(premultiply([10, 20, 30, 0]), [0; 4]);
assert_eq!(premultiply([10, 20, 30, 255]), [10, 20, 30, 255]);
}
#[test]
fn directions_saturate_and_keep_sign() {
assert_eq!(pack_direction(1., -1.), 0x8001_7fff);
assert_eq!(pack_direction(2., f64::NAN), 0x7fff);
assert_eq!(pack_direction(0., 0.), 0);
}
}