arc-flow-core 0.1.0

Framework-free graph model for arc-flow: nodes, typed ports, edges, reversible ops, history, validation, edge geometry and spatial index.
Documentation
//! 对齐吸附与参考线:拖动的矩形与其他节点的左 / 中 / 右、上 / 中 / 下线对齐。本地设计。
//!
//! 每个轴独立取距离最近、且在容差内的一对线;同一距离下优先靠前的线(左、上)。

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]
}

/// 在 `others` 中为一个轴找最近对齐:返回 (修正量, 对齐到的坐标, 对齐的矩形下标)。
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))
}

/// 计算 `moving` 相对 `others` 的对齐吸附。`tolerance` 为世界坐标距离。
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)];
        // 左边 103 → 对齐另一节点的右边 100(-3);上 / 中 / 下三条线都差 +2,取靠前的上边 200。
        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());
    }
}