arc-flow-core 0.4.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, Size2, Vec2};

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MinimapTransform {
    /// 映射到框内的世界区域(已含内边距)。
    pub world: Rect,
    /// 世界 → 小地图的缩放。
    pub scale: f32,
    /// 世界区域左上角在框内的位置(等比缩放后居中留白)。
    pub inset: Vec2,
}

impl MinimapTransform {
    /// `content` 通常为图包围盒与当前可见区域的并集;`padding` 为世界坐标。
    pub fn new(content: Rect, frame: Size2, padding: f32) -> Self {
        let world = content.inflate(padding);
        let (w, h) = (world.width().max(1.0), world.height().max(1.0));
        let scale = (frame.w / w).min(frame.h / h);
        let inset = Vec2::new((frame.w - w * scale) * 0.5, (frame.h - h * scale) * 0.5);
        Self {
            world,
            scale,
            inset,
        }
    }

    pub fn to_frame(&self, p: Vec2) -> Vec2 {
        p.minus(self.world.min).scale(self.scale).plus(self.inset)
    }

    pub fn rect_to_frame(&self, r: &Rect) -> Rect {
        Rect::from_corners(self.to_frame(r.min), self.to_frame(r.max))
    }

    pub fn to_world(&self, p: Vec2) -> Vec2 {
        p.minus(self.inset)
            .scale(1.0 / self.scale)
            .plus(self.world.min)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fits_and_centres_content_and_round_trips() {
        let content = Rect::from_origin_size(Vec2::new(0.0, 0.0), Size2::new(400.0, 100.0));
        let t = MinimapTransform::new(content, Size2::new(200.0, 140.0), 0.0);
        assert_eq!(t.scale, 0.5);
        assert_eq!(t.inset, Vec2::new(0.0, 45.0));
        assert_eq!(t.to_frame(Vec2::new(400.0, 100.0)), Vec2::new(200.0, 95.0));
        let p = Vec2::new(123.0, 45.0);
        let back = t.to_world(t.to_frame(p));
        assert!(back.distance(p) < 1e-3);
    }
}