Skip to main content

arc_flow_core/
align.rs

1//! 对齐吸附与参考线:拖动的矩形与其他节点的左 / 中 / 右、上 / 中 / 下线对齐。本地设计。
2//!
3//! 每个轴独立取距离最近、且在容差内的一对线;同一距离下优先靠前的线(左、上)。
4
5use crate::geometry::{Rect, Vec2};
6
7/// 一条参考线(世界坐标线段)。
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct Guide {
10    pub from: Vec2,
11    pub to: Vec2,
12}
13
14/// 吸附结果:对拖动增量的修正量与要绘制的参考线。
15#[derive(Clone, Debug, Default, PartialEq)]
16pub struct AlignSnap {
17    pub dx: f32,
18    pub dy: f32,
19    pub guides: Vec<Guide>,
20}
21
22fn lines_x(r: &Rect) -> [f32; 3] {
23    [r.min.x, (r.min.x + r.max.x) * 0.5, r.max.x]
24}
25
26fn lines_y(r: &Rect) -> [f32; 3] {
27    [r.min.y, (r.min.y + r.max.y) * 0.5, r.max.y]
28}
29
30/// 在 `others` 中为一个轴找最近对齐:返回 (修正量, 对齐到的坐标, 对齐的矩形下标)。
31fn best_axis(
32    moving: [f32; 3],
33    others: &[Rect],
34    lines: fn(&Rect) -> [f32; 3],
35    tolerance: f32,
36) -> Option<(f32, f32, Vec<usize>)> {
37    let mut best: Option<(f32, f32)> = None;
38    for o in others {
39        for target in lines(o) {
40            for m in moving {
41                let d = target - m;
42                if d.abs() <= tolerance && best.is_none_or(|(bd, _)| d.abs() < bd.abs()) {
43                    best = Some((d, target));
44                }
45            }
46        }
47    }
48    let (d, target) = best?;
49    // 所有与该坐标对齐的矩形都参与画线(一条线可贯穿多个节点)。
50    let hits = others
51        .iter()
52        .enumerate()
53        .filter(|(_, o)| lines(o).iter().any(|t| (t - target).abs() <= 0.01))
54        .map(|(i, _)| i)
55        .collect();
56    Some((d, target, hits))
57}
58
59/// 计算 `moving` 相对 `others` 的对齐吸附。`tolerance` 为世界坐标距离。
60pub fn align_snap(moving: Rect, others: &[Rect], tolerance: f32) -> AlignSnap {
61    let bx = best_axis(lines_x(&moving), others, lines_x, tolerance);
62    let by = best_axis(lines_y(&moving), others, lines_y, tolerance);
63    let mut out = AlignSnap {
64        dx: bx.as_ref().map_or(0.0, |b| b.0),
65        dy: by.as_ref().map_or(0.0, |b| b.0),
66        guides: Vec::new(),
67    };
68    // 参考线跨越修正后的拖动矩形与所有对齐的节点。
69    let snapped = Rect {
70        min: moving.min.plus(Vec2::new(out.dx, out.dy)),
71        max: moving.max.plus(Vec2::new(out.dx, out.dy)),
72    };
73    if let Some((_, x, hits)) = bx {
74        let (y0, y1) = hits
75            .iter()
76            .fold((snapped.min.y, snapped.max.y), |(a, b), &i| {
77                (a.min(others[i].min.y), b.max(others[i].max.y))
78            });
79        out.guides.push(Guide {
80            from: Vec2::new(x, y0),
81            to: Vec2::new(x, y1),
82        });
83    }
84    if let Some((_, y, hits)) = by {
85        let (x0, x1) = hits
86            .iter()
87            .fold((snapped.min.x, snapped.max.x), |(a, b), &i| {
88                (a.min(others[i].min.x), b.max(others[i].max.x))
89            });
90        out.guides.push(Guide {
91            from: Vec2::new(x0, y),
92            to: Vec2::new(x1, y),
93        });
94    }
95    out
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::geometry::Size2;
102
103    fn r(x: f32, y: f32, w: f32, h: f32) -> Rect {
104        Rect::from_origin_size(Vec2::new(x, y), Size2::new(w, h))
105    }
106
107    #[test]
108    fn snaps_each_axis_to_nearest_line_within_tolerance() {
109        let others = [r(0.0, 0.0, 100.0, 40.0), r(300.0, 200.0, 80.0, 40.0)];
110        // 左边 103 → 对齐另一节点的右边 100(-3);上 / 中 / 下三条线都差 +2,取靠前的上边 200。
111        let s = align_snap(r(103.0, 198.0, 60.0, 40.0), &others, 5.0);
112        assert_eq!((s.dx, s.dy), (-3.0, 2.0));
113        assert_eq!(s.guides.len(), 2);
114        assert_eq!(s.guides[0].from, Vec2::new(100.0, 0.0));
115        assert_eq!(s.guides[0].to, Vec2::new(100.0, 240.0));
116        // 水平线横跨修正后的拖动矩形与目标节点。
117        assert_eq!(s.guides[1].from, Vec2::new(100.0, 200.0));
118        assert_eq!(s.guides[1].to, Vec2::new(380.0, 200.0));
119    }
120
121    #[test]
122    fn nothing_outside_tolerance() {
123        let s = align_snap(r(150.0, 90.0, 20.0, 20.0), &[r(0.0, 0.0, 100.0, 40.0)], 5.0);
124        assert_eq!(s, AlignSnap::default());
125    }
126}