use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
pub struct Rect {
pub x0: f32,
pub y0: f32,
pub x1: f32,
pub y1: f32,
}
impl Rect {
pub const EMPTY: Rect = Rect {
x0: f32::INFINITY,
y0: f32::INFINITY,
x1: f32::NEG_INFINITY,
y1: f32::NEG_INFINITY,
};
pub fn new(x0: f32, y0: f32, x1: f32, y1: f32) -> Self {
Self { x0, y0, x1, y1 }
}
pub fn is_empty(&self) -> bool {
self.x1 <= self.x0 || self.y1 <= self.y0
}
pub fn is_unset(&self) -> bool {
self.x1 < self.x0 || self.y1 < self.y0
}
pub fn width(&self) -> f32 {
(self.x1 - self.x0).max(0.0)
}
pub fn height(&self) -> f32 {
(self.y1 - self.y0).max(0.0)
}
pub fn area(&self) -> f32 {
self.width() * self.height()
}
pub fn cx(&self) -> f32 {
(self.x0 + self.x1) * 0.5
}
pub fn cy(&self) -> f32 {
(self.y0 + self.y1) * 0.5
}
pub fn union(&self, other: &Rect) -> Rect {
Rect {
x0: self.x0.min(other.x0),
y0: self.y0.min(other.y0),
x1: self.x1.max(other.x1),
y1: self.y1.max(other.y1),
}
}
pub fn intersect(&self, other: &Rect) -> Rect {
Rect {
x0: self.x0.max(other.x0),
y0: self.y0.max(other.y0),
x1: self.x1.min(other.x1),
y1: self.y1.min(other.y1),
}
}
pub fn intersects(&self, other: &Rect) -> bool {
self.x0 < other.x1 && other.x0 < self.x1 && self.y0 < other.y1 && other.y0 < self.y1
}
pub fn contains(&self, other: &Rect) -> bool {
self.x0 <= other.x0 && self.y0 <= other.y0 && self.x1 >= other.x1 && self.y1 >= other.y1
}
pub fn contains_point(&self, x: f32, y: f32) -> bool {
x >= self.x0 && x <= self.x1 && y >= self.y0 && y <= self.y1
}
pub fn inflate(&self, dx: f32, dy: f32) -> Rect {
Rect {
x0: self.x0 - dx,
y0: self.y0 - dy,
x1: self.x1 + dx,
y1: self.y1 + dy,
}
}
pub fn x_overlap(&self, other: &Rect) -> f32 {
self.x1.min(other.x1) - self.x0.max(other.x0)
}
pub fn y_overlap(&self, other: &Rect) -> f32 {
self.y1.min(other.y1) - self.y0.max(other.y0)
}
pub fn coverage_of(&self, other: &Rect) -> f32 {
let other_area = other.area();
if other_area <= 0.0 {
return if self.contains_point(other.cx(), other.cy()) {
1.0
} else {
0.0
};
}
let overlap = self.intersect(other);
if overlap.is_empty() {
0.0
} else {
overlap.area() / other_area
}
}
}
pub fn median(values: &[f32], default: f32) -> f32 {
if values.is_empty() {
return default;
}
let mut sorted = values.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
sorted[sorted.len() / 2]
}
pub fn weighted_mode(values: impl Iterator<Item = (f32, f32)>, step: f32, default: f32) -> f32 {
let mut hist: HashMap<i32, f32> = HashMap::new();
for (value, weight) in values {
*hist.entry((value / step).round() as i32).or_insert(0.0) += weight;
}
hist.into_iter()
.max_by(|a, b| a.1.total_cmp(&b.1).then(b.0.cmp(&a.0)))
.map(|(bucket, _)| bucket as f32 * step)
.unwrap_or(default)
}