microcad_core/geo2d/
align.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Builtin align for 2D geometries.
5
6use crate::*;
7
8/// Trait to align a 2D geometry collection with spacing along an axis.
9pub trait Align2D<T = Self> {
10    /// Align geometry.
11    fn align_2d(&self, direction: Vec2, spacing: Length) -> T;
12}
13
14impl Align2D for Geometries2D {
15    fn align_2d(&self, direction: Vec2, spacing: Length) -> Self {
16        Geometries2D::from_iter(self.iter().scan(0.0_f64, |pos, geo2d| {
17            use cgmath::InnerSpace;
18
19            let bounds = geo2d.calc_bounds_2d();
20            let dist = *bounds.distance_center_to_boundary(direction);
21            let dir = if direction.magnitude() > f64::EPSILON {
22                direction.normalize()
23            } else {
24                Vec2::new(0.0, 0.0)
25            };
26            let d = (*pos + dist) * dir
27                - Vec2::new(dir.x * bounds.center().x, dir.y * bounds.center().y);
28            *pos += 2.0 * dist + *spacing;
29
30            Some(std::rc::Rc::new(
31                geo2d.transformed_2d(&Mat3::from_translation(d)),
32            ))
33        }))
34    }
35}