#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Point {
pub x: f64,
pub y: f64,
}
impl Point {
#[must_use]
pub const fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
#[must_use]
pub fn lerp(self, other: Self, t: f64) -> Self {
Self::new((other.x - self.x).mul_add(t, self.x), (other.y - self.y).mul_add(t, self.y))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Size {
pub width: f64,
pub height: f64,
}
impl Size {
#[must_use]
pub const fn new(width: f64, height: f64) -> Self {
Self { width, height }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Rect {
pub origin: Point,
pub size: Size,
}
impl Rect {
#[must_use]
pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
Self { origin: Point::new(x, y), size: Size::new(width, height) }
}
#[must_use]
pub const fn min_x(&self) -> f64 {
self.origin.x
}
#[must_use]
pub const fn min_y(&self) -> f64 {
self.origin.y
}
#[must_use]
pub fn max_x(&self) -> f64 {
self.origin.x + self.size.width
}
#[must_use]
pub fn max_y(&self) -> f64 {
self.origin.y + self.size.height
}
#[must_use]
pub fn center(&self) -> Point {
Point::new(self.size.width.mul_add(0.5, self.origin.x), self.size.height.mul_add(0.5, self.origin.y))
}
#[must_use]
pub fn area(&self) -> f64 {
self.size.width.max(0.0) * self.size.height.max(0.0)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.size.width <= 0.0 || self.size.height <= 0.0
}
#[must_use]
pub fn contains(&self, point: Point) -> bool {
point.x >= self.min_x() && point.x < self.max_x() && point.y >= self.min_y() && point.y < self.max_y()
}
#[must_use]
pub fn intersection(&self, other: &Self) -> Option<Self> {
let x0 = self.min_x().max(other.min_x());
let y0 = self.min_y().max(other.min_y());
let x1 = self.max_x().min(other.max_x());
let y1 = self.max_y().min(other.max_y());
(x1 > x0 && y1 > y0).then(|| Self::new(x0, y0, x1 - x0, y1 - y0))
}
#[must_use]
pub fn offset(&self, dx: f64, dy: f64) -> Self {
Self::new(self.origin.x + dx, self.origin.y + dy, self.size.width, self.size.height)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn contains_and_center() {
let r = Rect::new(10.0, 20.0, 100.0, 50.0);
assert!(r.contains(Point::new(10.0, 20.0)));
assert!(!r.contains(Point::new(110.0, 20.0)));
assert_eq!(r.center(), Point::new(60.0, 45.0));
}
#[test]
fn intersection() {
let a = Rect::new(0.0, 0.0, 10.0, 10.0);
let b = Rect::new(5.0, 5.0, 10.0, 10.0);
assert_eq!(a.intersection(&b), Some(Rect::new(5.0, 5.0, 5.0, 5.0)));
assert_eq!(a.intersection(&Rect::new(20.0, 20.0, 1.0, 1.0)), None);
}
}