#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct Vector2 {
pub x: f32,
pub y: f32,
}
impl Vector2 {
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
impl From<(f32, f32)> for Vector2 {
fn from(value: (f32, f32)) -> Self {
Self::new(value.0, value.1)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct Dimensions {
pub width: f32,
pub height: f32,
}
impl Dimensions {
pub fn new(width: f32, height: f32) -> Self {
Self { width, height }
}
}
impl From<(f32, f32)> for Dimensions {
fn from(value: (f32, f32)) -> Self {
Self::new(value.0, value.1)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(
feature = "serialization",
derive(serde::Serialize, serde::Deserialize)
)]
pub struct BoundingBox {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
}
impl BoundingBox {
pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
Self {
x,
y,
width,
height,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vector2_and_dimensions_from_tuple() {
let vector = Vector2::from((3.0, 4.0));
assert_eq!(vector.x, 3.0);
assert_eq!(vector.y, 4.0);
let size = Dimensions::from((800.0, 600.0));
assert_eq!(size.width, 800.0);
assert_eq!(size.height, 600.0);
}
#[cfg(feature = "serialization")]
#[test]
fn math_types_roundtrip_through_json() {
use serde_json;
let vector = Vector2::new(1.0, 2.0);
let decoded: Vector2 =
serde_json::from_str(&serde_json::to_string(&vector).unwrap()).unwrap();
assert_eq!(decoded, vector);
let size = Dimensions::new(10.0, 20.0);
let decoded: Dimensions =
serde_json::from_str(&serde_json::to_string(&size).unwrap()).unwrap();
assert_eq!(decoded, size);
let bounds = BoundingBox::new(1.0, 2.0, 3.0, 4.0);
let decoded: BoundingBox =
serde_json::from_str(&serde_json::to_string(&bounds).unwrap()).unwrap();
assert_eq!(decoded, bounds);
}
}