use core::fmt;
use core::ops::{Add, Div, Mul, Sub};
use crate::geometry::{Point, Rect, Size, Vector};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Logical<T>(pub T);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Physical<T>(T);
impl<T> Logical<T> {
pub fn get(self) -> T {
self.0
}
}
impl<T> Physical<T> {
pub const fn new(value: T) -> Self {
Self(value)
}
pub fn get(self) -> T {
self.0
}
}
impl From<(f32, f32)> for Logical<Size> {
fn from((width, height): (f32, f32)) -> Self {
Logical(Size::new(width, height))
}
}
impl<A: Add<B>, B> Add<Logical<B>> for Logical<A> {
type Output = Logical<A::Output>;
fn add(self, other: Logical<B>) -> Self::Output {
Logical(self.0 + other.0)
}
}
impl<A: Sub<B>, B> Sub<Logical<B>> for Logical<A> {
type Output = Logical<A::Output>;
fn sub(self, other: Logical<B>) -> Self::Output {
Logical(self.0 - other.0)
}
}
impl<A: Add<B>, B> Add<Physical<B>> for Physical<A> {
type Output = Physical<A::Output>;
fn add(self, other: Physical<B>) -> Self::Output {
Physical(self.0 + other.0)
}
}
impl<A: Sub<B>, B> Sub<Physical<B>> for Physical<A> {
type Output = Physical<A::Output>;
fn sub(self, other: Physical<B>) -> Self::Output {
Physical(self.0 - other.0)
}
}
mod sealed {
pub trait Sealed {}
}
pub trait Scalable: sealed::Sealed + Sized {
#[must_use]
fn scaled(self, factor: f32) -> Self;
}
impl sealed::Sealed for f32 {}
impl Scalable for f32 {
fn scaled(self, factor: f32) -> Self {
self * factor
}
}
impl sealed::Sealed for Point {}
impl Scalable for Point {
fn scaled(self, factor: f32) -> Self {
Point::new(self.x * factor, self.y * factor)
}
}
impl sealed::Sealed for Vector {}
impl Scalable for Vector {
fn scaled(self, factor: f32) -> Self {
self * factor
}
}
impl sealed::Sealed for Size {}
impl Scalable for Size {
fn scaled(self, factor: f32) -> Self {
self * factor
}
}
impl sealed::Sealed for Rect {}
impl Scalable for Rect {
fn scaled(self, factor: f32) -> Self {
Rect::new(self.position().scaled(factor), self.size().scaled(factor))
}
}
impl<T: Scalable> Mul<ScaleFactor> for Logical<T> {
type Output = Physical<T>;
fn mul(self, factor: ScaleFactor) -> Physical<T> {
Physical(self.0.scaled(factor.0))
}
}
impl<T: Scalable> Div<ScaleFactor> for Physical<T> {
type Output = Logical<T>;
fn div(self, factor: ScaleFactor) -> Logical<T> {
Logical(self.0.scaled(1.0 / factor.0))
}
}
impl Logical<Size> {
#[must_use]
pub fn to_physical_pixels(self, factor: ScaleFactor) -> Physical<Size<u32>> {
let round = |value: f32| (f64::from(value) * f64::from(factor.0)).round() as u32;
Physical(Size::new(round(self.0.width), round(self.0.height)))
}
}
impl Physical<Size<u32>> {
#[must_use]
pub fn to_logical(self, factor: ScaleFactor) -> Logical<Size> {
let divide = |value: u32| (f64::from(value) / f64::from(factor.0)) as f32;
Logical(Size::new(divide(self.0.width), divide(self.0.height)))
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
pub struct ScaleFactor(f32);
impl ScaleFactor {
pub const MIN: f32 = 0.5;
pub const MAX: f32 = 4.0;
pub const ONE: Self = Self(1.0);
pub const X1_25: Self = Self(1.25);
pub const X1_5: Self = Self(1.5);
pub const TWO: Self = Self(2.0);
pub const THREE: Self = Self(3.0);
pub const fn new(factor: f32) -> Result<Self, InvalidScaleFactor> {
if factor >= Self::MIN && factor <= Self::MAX {
return Ok(Self(factor));
}
Err(InvalidScaleFactor { factor })
}
#[must_use]
pub const fn get(self) -> f32 {
self.0
}
}
impl Default for ScaleFactor {
fn default() -> Self {
Self::ONE
}
}
impl TryFrom<f32> for ScaleFactor {
type Error = InvalidScaleFactor;
fn try_from(factor: f32) -> Result<Self, InvalidScaleFactor> {
Self::new(factor)
}
}
impl From<ScaleFactor> for f32 {
fn from(factor: ScaleFactor) -> f32 {
factor.0
}
}
impl fmt::Display for ScaleFactor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}x", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct InvalidScaleFactor {
factor: f32,
}
impl InvalidScaleFactor {
#[must_use]
pub const fn factor(self) -> f32 {
self.factor
}
}
impl fmt::Display for InvalidScaleFactor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"scale {} is outside {} to {}",
self.factor,
ScaleFactor::MIN,
ScaleFactor::MAX
)
}
}
impl std::error::Error for InvalidScaleFactor {}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "f32", into = "f32"))]
pub struct Ratio(f32);
impl Ratio {
pub const ZERO: Self = Self(0.0);
pub const ONE: Self = Self(1.0);
pub const fn new(value: f32) -> Result<Self, InvalidRatio> {
if value >= 0.0 && value <= 1.0 {
return Ok(Self(value));
}
Err(InvalidRatio { value })
}
#[must_use]
pub const fn get(self) -> f32 {
self.0
}
}
impl TryFrom<f32> for Ratio {
type Error = InvalidRatio;
fn try_from(value: f32) -> Result<Self, InvalidRatio> {
Self::new(value)
}
}
impl From<Ratio> for f32 {
fn from(ratio: Ratio) -> f32 {
ratio.0
}
}
impl fmt::Display for Ratio {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct InvalidRatio {
value: f32,
}
impl InvalidRatio {
#[must_use]
pub const fn value(self) -> f32 {
self.value
}
}
impl fmt::Display for InvalidRatio {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ratio {} is outside 0 to 1", self.value)
}
}
impl std::error::Error for InvalidRatio {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scale_factor_rejects_out_of_range_and_non_finite() {
for bad in [
0.0,
-1.0,
0.49,
4.01,
f32::NAN,
f32::INFINITY,
f32::NEG_INFINITY,
] {
assert!(ScaleFactor::new(bad).is_err(), "{bad}");
}
for good in [0.5, 1.0, 1.25, 4.0] {
assert_eq!(ScaleFactor::new(good).map(ScaleFactor::get), Ok(good));
}
assert_eq!(ScaleFactor::try_from(2.0), Ok(ScaleFactor::TWO));
assert_eq!(f32::from(ScaleFactor::X1_5), 1.5);
assert_eq!(ScaleFactor::default(), ScaleFactor::ONE);
}
#[test]
fn scale_factor_new_is_usable_in_const_items() {
const CUSTOM: Result<ScaleFactor, InvalidScaleFactor> = ScaleFactor::new(1.75);
assert_eq!(CUSTOM.map(ScaleFactor::get), Ok(1.75));
}
#[test]
fn named_scale_factors_are_valid() {
for factor in [
ScaleFactor::ONE,
ScaleFactor::X1_25,
ScaleFactor::X1_5,
ScaleFactor::TWO,
ScaleFactor::THREE,
] {
assert_eq!(ScaleFactor::new(factor.get()), Ok(factor));
}
}
#[test]
fn scale_factor_errors_and_display() {
assert_eq!(ScaleFactor::TWO.to_string(), "2x");
assert_eq!(ScaleFactor::X1_25.to_string(), "1.25x");
let error = ScaleFactor::new(0.2).err();
assert_eq!(error.map(InvalidScaleFactor::factor), Some(0.2));
assert_eq!(
error.map(|e| e.to_string()).as_deref(),
Some("scale 0.2 is outside 0.5 to 4")
);
}
#[test]
fn logical_times_scale_is_physical_and_back() {
let logical = Logical(Size::new(100.0, 50.0));
let physical = logical * ScaleFactor::TWO;
assert_eq!(physical, Physical::new(Size::new(200.0, 100.0)));
assert_eq!(physical / ScaleFactor::TWO, logical);
assert_eq!(
Logical(Point::new(1.0, 2.0)) * ScaleFactor::THREE,
Physical::new(Point::new(3.0, 6.0))
);
assert_eq!(
Logical(Vector::new(1.0, -2.0)) * ScaleFactor::TWO,
Physical::new(Vector::new(2.0, -4.0))
);
assert_eq!(
Logical(Rect::new(Point::new(1.0, 2.0), Size::new(3.0, 4.0))) * ScaleFactor::TWO,
Physical::new(Rect::new(Point::new(2.0, 4.0), Size::new(6.0, 8.0)))
);
assert_eq!(Logical(4.0_f32) * ScaleFactor::X1_5, Physical::new(6.0));
}
#[test]
fn physical_pixels_round_like_winit() {
let size = Logical(Size::new(101.0, 33.0)).to_physical_pixels(ScaleFactor::X1_25);
assert_eq!(size, Physical::new(Size::new(126, 41)));
let size = Logical(Size::new(100.2, 100.5)).to_physical_pixels(ScaleFactor::ONE);
assert_eq!(size, Physical::new(Size::new(100, 101)));
assert_eq!(
Physical::new(Size::new(126_u32, 40)).to_logical(ScaleFactor::X1_25),
Logical(Size::new(100.8, 32.0))
);
}
#[test]
fn same_unit_arithmetic() {
assert_eq!(
Logical(Point::new(1.0, 1.0)) + Logical(Vector::new(2.0, 3.0)),
Logical(Point::new(3.0, 4.0))
);
assert_eq!(
Logical(Point::new(3.0, 4.0)) - Logical(Point::new(1.0, 1.0)),
Logical(Vector::new(2.0, 3.0))
);
assert_eq!(
Physical::new(2_u32) + Physical::new(3_u32),
Physical::new(5_u32)
);
assert_eq!(Physical::new(5_i32) - Physical::new(3), Physical::new(2));
assert_eq!(Logical(3.0_f32).get(), 3.0);
}
#[test]
fn tuples_make_logical_sizes() {
let size: Logical<Size> = (1280.0, 820.0).into();
assert_eq!(size, Logical(Size::new(1280.0, 820.0)));
}
#[test]
fn ratio_is_checked() {
for bad in [-0.01, 1.01, 10.0, f32::NAN] {
assert!(Ratio::new(bad).is_err(), "{bad}");
}
assert_eq!(Ratio::new(0.1).map(Ratio::get), Ok(0.1));
assert_eq!(Ratio::new(0.0), Ok(Ratio::ZERO));
assert_eq!(Ratio::new(1.0), Ok(Ratio::ONE));
assert_eq!(Ratio::try_from(0.5).map(f32::from), Ok(0.5));
assert_eq!(Ratio::default(), Ratio::ZERO);
assert_eq!(
Ratio::new(0.25).map(|r| r.to_string()),
Ok("0.25".to_owned())
);
let error = Ratio::new(10.0).err();
assert_eq!(error.map(InvalidRatio::value), Some(10.0));
assert_eq!(
error.map(|e| e.to_string()).as_deref(),
Some("ratio 10 is outside 0 to 1")
);
}
#[cfg(feature = "serde")]
#[test]
fn checked_numbers_validate_when_deserialised() -> Result<(), serde_json::Error> {
assert_eq!(serde_json::to_string(&ScaleFactor::TWO)?, "2.0");
assert_eq!(
serde_json::from_str::<ScaleFactor>("1.5")?,
ScaleFactor::X1_5
);
assert!(serde_json::from_str::<ScaleFactor>("0.1").is_err());
assert_eq!(
serde_json::from_str::<Ratio>("0.5")?,
Ratio::new(0.5).unwrap_or_default()
);
assert!(serde_json::from_str::<Ratio>("2").is_err());
assert_eq!(
serde_json::to_string(&Logical(Point::new(1.0, 2.0)))?,
r#"{"x":1.0,"y":2.0}"#
);
Ok(())
}
}