//! Physical surface geometry shared by the nearest blit and pointer normalization. #[derive(Clone, Copy, Debug)] pub(crate) struct Viewport { pub x: f32, pub y: f32, pub width: f32, pub height: f32, pub scale: f32, native: (usize, usize), } impl Viewport { pub fn new(surface: (u32, u32), native: (usize, usize)) -> Option { if surface.0 == 0 || surface.1 == 0 || native.0 == 0 || native.1 == 0 { return None; } let fit = (surface.0 as f32 / native.0 as f32).min(surface.1 as f32 / native.1 as f32); let scale = if fit >= 1.0 { fit.floor() } else { fit }; let width = native.0 as f32 * scale; let height = native.1 as f32 * scale; Some(Self { x: ((surface.0 as f32 - width) / 2.0).floor(), y: ((surface.1 as f32 - height) / 2.0).floor(), width, height, scale, native, }) } pub fn inverse(self, x: f64, y: f64) -> Option<(i32, i32)> { let (x, y) = (x - self.x as f64, y - self.y as f64); if !x.is_finite() || !y.is_finite() || x < 0.0 || y < 0.0 || x >= self.width as f64 || y >= self.height as f64 { return None; } Some(( ((x / self.scale as f64).floor() as i32).min(self.native.0 as i32 - 1), ((y / self.scale as f64).floor() as i32).min(self.native.1 as i32 - 1), )) } } #[cfg(test)] mod tests { use super::*; #[test] fn physical_scaling_and_inverse_share_bounds() { for (surface, scale, offset) in [ ((1280, 720), 2.0, (0.0, 0.0)), ((1920, 1080), 3.0, (0.0, 0.0)), ((1000, 700), 1.0, (180.0, 170.0)), ((320, 240), 0.5, (0.0, 30.0)), ((2560, 1440), 4.0, (0.0, 0.0)), ] { let v = Viewport::new(surface, (640, 360)).unwrap(); assert_eq!((v.scale, v.x, v.y), (scale, offset.0, offset.1)); assert_eq!(v.inverse(v.x as f64, v.y as f64), Some((0, 0))); assert_eq!( v.inverse((v.x + v.width - 0.01) as f64, (v.y + v.height - 0.01) as f64), Some((639, 359)) ); assert_eq!(v.inverse((v.x + v.width) as f64, v.y as f64), None); assert_eq!(v.inverse(v.x as f64, (v.y + v.height) as f64), None); assert_eq!(v.inverse(v.x as f64 - 0.01, v.y as f64), None); } assert!(Viewport::new((0, 0), (640, 360)).is_none()); } }