use crate::geometry::{Rect, Vec2};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Guide {
pub from: Vec2,
pub to: Vec2,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AlignSnap {
pub dx: f32,
pub dy: f32,
pub guides: Vec<Guide>,
}
fn lines_x(r: &Rect) -> [f32; 3] {
[r.min.x, (r.min.x + r.max.x) * 0.5, r.max.x]
}
fn lines_y(r: &Rect) -> [f32; 3] {
[r.min.y, (r.min.y + r.max.y) * 0.5, r.max.y]
}
fn best_axis(
moving: [f32; 3],
others: &[Rect],
lines: fn(&Rect) -> [f32; 3],
tolerance: f32,
) -> Option<(f32, f32, Vec<usize>)> {
let mut best: Option<(f32, f32)> = None;
for o in others {
for target in lines(o) {
for m in moving {
let d = target - m;
if d.abs() <= tolerance && best.is_none_or(|(bd, _)| d.abs() < bd.abs()) {
best = Some((d, target));
}
}
}
}
let (d, target) = best?;
let hits = others
.iter()
.enumerate()
.filter(|(_, o)| lines(o).iter().any(|t| (t - target).abs() <= 0.01))
.map(|(i, _)| i)
.collect();
Some((d, target, hits))
}
pub fn align_snap(moving: Rect, others: &[Rect], tolerance: f32) -> AlignSnap {
let bx = best_axis(lines_x(&moving), others, lines_x, tolerance);
let by = best_axis(lines_y(&moving), others, lines_y, tolerance);
let mut out = AlignSnap {
dx: bx.as_ref().map_or(0.0, |b| b.0),
dy: by.as_ref().map_or(0.0, |b| b.0),
guides: Vec::new(),
};
let snapped = Rect {
min: moving.min.plus(Vec2::new(out.dx, out.dy)),
max: moving.max.plus(Vec2::new(out.dx, out.dy)),
};
if let Some((_, x, hits)) = bx {
let (y0, y1) = hits
.iter()
.fold((snapped.min.y, snapped.max.y), |(a, b), &i| {
(a.min(others[i].min.y), b.max(others[i].max.y))
});
out.guides.push(Guide {
from: Vec2::new(x, y0),
to: Vec2::new(x, y1),
});
}
if let Some((_, y, hits)) = by {
let (x0, x1) = hits
.iter()
.fold((snapped.min.x, snapped.max.x), |(a, b), &i| {
(a.min(others[i].min.x), b.max(others[i].max.x))
});
out.guides.push(Guide {
from: Vec2::new(x0, y),
to: Vec2::new(x1, y),
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Size2;
fn r(x: f32, y: f32, w: f32, h: f32) -> Rect {
Rect::from_origin_size(Vec2::new(x, y), Size2::new(w, h))
}
#[test]
fn snaps_each_axis_to_nearest_line_within_tolerance() {
let others = [r(0.0, 0.0, 100.0, 40.0), r(300.0, 200.0, 80.0, 40.0)];
let s = align_snap(r(103.0, 198.0, 60.0, 40.0), &others, 5.0);
assert_eq!((s.dx, s.dy), (-3.0, 2.0));
assert_eq!(s.guides.len(), 2);
assert_eq!(s.guides[0].from, Vec2::new(100.0, 0.0));
assert_eq!(s.guides[0].to, Vec2::new(100.0, 240.0));
assert_eq!(s.guides[1].from, Vec2::new(100.0, 200.0));
assert_eq!(s.guides[1].to, Vec2::new(380.0, 200.0));
}
#[test]
fn nothing_outside_tolerance() {
let s = align_snap(r(150.0, 90.0, 20.0, 20.0), &[r(0.0, 0.0, 100.0, 40.0)], 5.0);
assert_eq!(s, AlignSnap::default());
}
}