Skip to main content

sui_core/
geometry.rs

1use std::ops::{Add, AddAssign, Sub, SubAssign};
2
3#[derive(Debug, Clone, Copy, PartialEq, Default)]
4pub struct Point {
5    pub x: f32,
6    pub y: f32,
7}
8
9impl Point {
10    pub const ZERO: Self = Self::new(0.0, 0.0);
11
12    pub const fn new(x: f32, y: f32) -> Self {
13        Self { x, y }
14    }
15
16    pub const fn to_vector(self) -> Vector {
17        Vector::new(self.x, self.y)
18    }
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Default)]
22pub struct Vector {
23    pub x: f32,
24    pub y: f32,
25}
26
27impl Vector {
28    pub const ZERO: Self = Self::new(0.0, 0.0);
29
30    pub const fn new(x: f32, y: f32) -> Self {
31        Self { x, y }
32    }
33}
34
35impl Add<Vector> for Point {
36    type Output = Point;
37
38    fn add(self, rhs: Vector) -> Self::Output {
39        Point::new(self.x + rhs.x, self.y + rhs.y)
40    }
41}
42
43impl AddAssign<Vector> for Point {
44    fn add_assign(&mut self, rhs: Vector) {
45        self.x += rhs.x;
46        self.y += rhs.y;
47    }
48}
49
50impl Sub<Point> for Point {
51    type Output = Vector;
52
53    fn sub(self, rhs: Point) -> Self::Output {
54        Vector::new(self.x - rhs.x, self.y - rhs.y)
55    }
56}
57
58impl Add for Vector {
59    type Output = Vector;
60
61    fn add(self, rhs: Vector) -> Self::Output {
62        Vector::new(self.x + rhs.x, self.y + rhs.y)
63    }
64}
65
66impl AddAssign for Vector {
67    fn add_assign(&mut self, rhs: Vector) {
68        self.x += rhs.x;
69        self.y += rhs.y;
70    }
71}
72
73impl Sub for Vector {
74    type Output = Vector;
75
76    fn sub(self, rhs: Vector) -> Self::Output {
77        Vector::new(self.x - rhs.x, self.y - rhs.y)
78    }
79}
80
81impl SubAssign for Vector {
82    fn sub_assign(&mut self, rhs: Vector) {
83        self.x -= rhs.x;
84        self.y -= rhs.y;
85    }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Default)]
89pub struct Size {
90    pub width: f32,
91    pub height: f32,
92}
93
94impl Size {
95    pub const ZERO: Self = Self::new(0.0, 0.0);
96
97    pub const fn new(width: f32, height: f32) -> Self {
98        Self { width, height }
99    }
100
101    pub fn is_empty(self) -> bool {
102        self.width <= 0.0 || self.height <= 0.0
103    }
104
105    pub fn clamp(self, min: Size, max: Size) -> Self {
106        Self::new(
107            self.width.clamp(min.width, max.width),
108            self.height.clamp(min.height, max.height),
109        )
110    }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Default)]
114pub struct Rect {
115    pub origin: Point,
116    pub size: Size,
117}
118
119impl Rect {
120    pub const ZERO: Self = Self::new(0.0, 0.0, 0.0, 0.0);
121
122    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
123        Self {
124            origin: Point::new(x, y),
125            size: Size::new(width, height),
126        }
127    }
128
129    pub const fn from_origin_size(origin: Point, size: Size) -> Self {
130        Self { origin, size }
131    }
132
133    pub fn from_points(min: Point, max: Point) -> Self {
134        Self::new(
135            min.x,
136            min.y,
137            (max.x - min.x).max(0.0),
138            (max.y - min.y).max(0.0),
139        )
140    }
141
142    pub const fn x(self) -> f32 {
143        self.origin.x
144    }
145
146    pub const fn y(self) -> f32 {
147        self.origin.y
148    }
149
150    pub const fn width(self) -> f32 {
151        self.size.width
152    }
153
154    pub const fn height(self) -> f32 {
155        self.size.height
156    }
157
158    pub fn max_x(self) -> f32 {
159        self.origin.x + self.size.width
160    }
161
162    pub fn max_y(self) -> f32 {
163        self.origin.y + self.size.height
164    }
165
166    pub fn is_empty(self) -> bool {
167        self.size.is_empty()
168    }
169
170    pub fn contains(self, point: Point) -> bool {
171        point.x >= self.x()
172            && point.x <= self.max_x()
173            && point.y >= self.y()
174            && point.y <= self.max_y()
175    }
176
177    pub fn translate(self, delta: Vector) -> Self {
178        Self::from_origin_size(self.origin + delta, self.size)
179    }
180
181    pub fn inflate(self, x: f32, y: f32) -> Self {
182        Self::new(
183            self.origin.x - x,
184            self.origin.y - y,
185            self.size.width + (x * 2.0),
186            self.size.height + (y * 2.0),
187        )
188    }
189
190    pub fn intersection(self, other: Rect) -> Option<Self> {
191        let min_x = self.x().max(other.x());
192        let min_y = self.y().max(other.y());
193        let max_x = self.max_x().min(other.max_x());
194        let max_y = self.max_y().min(other.max_y());
195
196        if min_x >= max_x || min_y >= max_y {
197            return None;
198        }
199
200        Some(Self::from_points(
201            Point::new(min_x, min_y),
202            Point::new(max_x, max_y),
203        ))
204    }
205
206    pub fn union(self, other: Rect) -> Self {
207        if self.is_empty() {
208            return other;
209        }
210
211        if other.is_empty() {
212            return self;
213        }
214
215        Self::from_points(
216            Point::new(self.x().min(other.x()), self.y().min(other.y())),
217            Point::new(
218                self.max_x().max(other.max_x()),
219                self.max_y().max(other.max_y()),
220            ),
221        )
222    }
223}
224
225#[derive(Debug, Clone, PartialEq)]
226pub enum PathElement {
227    MoveTo(Point),
228    LineTo(Point),
229    QuadTo {
230        ctrl: Point,
231        to: Point,
232    },
233    CubicTo {
234        ctrl1: Point,
235        ctrl2: Point,
236        to: Point,
237    },
238    Close,
239}
240
241#[derive(Debug, Clone, PartialEq, Default)]
242pub struct Path {
243    elements: Vec<PathElement>,
244    bounds: Rect,
245}
246
247impl Path {
248    pub fn new() -> Self {
249        Self::default()
250    }
251
252    pub fn builder() -> PathBuilder {
253        PathBuilder::new()
254    }
255
256    pub fn rect(rect: Rect) -> Self {
257        let mut builder = Self::builder();
258        builder.push_rect(rect);
259        builder.build()
260    }
261
262    pub fn circle(center: Point, radius: f32) -> Self {
263        let mut builder = Self::builder();
264        builder.push_circle(center, radius);
265        builder.build()
266    }
267
268    pub fn rounded_rect(rect: Rect, radius: f32) -> Self {
269        let mut builder = Self::builder();
270        builder.push_rounded_rect(rect, radius);
271        builder.build()
272    }
273
274    pub fn arc(center: Point, radius: f32, start_angle: f32, sweep_angle: f32) -> Self {
275        let mut builder = Self::builder();
276        builder.push_arc(center, radius, start_angle, sweep_angle);
277        builder.build()
278    }
279
280    pub fn elements(&self) -> &[PathElement] {
281        &self.elements
282    }
283
284    pub const fn bounds(&self) -> Rect {
285        self.bounds
286    }
287
288    pub fn is_empty(&self) -> bool {
289        self.elements.is_empty()
290    }
291}
292
293impl From<Rect> for Path {
294    fn from(value: Rect) -> Self {
295        Self::rect(value)
296    }
297}
298
299#[derive(Debug, Clone, Default)]
300pub struct PathBuilder {
301    elements: Vec<PathElement>,
302    min: Option<Point>,
303    max: Option<Point>,
304}
305
306impl PathBuilder {
307    pub fn new() -> Self {
308        Self::default()
309    }
310
311    pub fn move_to(&mut self, to: Point) -> &mut Self {
312        self.include_point(to);
313        self.elements.push(PathElement::MoveTo(to));
314        self
315    }
316
317    pub fn line_to(&mut self, to: Point) -> &mut Self {
318        self.include_point(to);
319        self.elements.push(PathElement::LineTo(to));
320        self
321    }
322
323    pub fn quad_to(&mut self, ctrl: Point, to: Point) -> &mut Self {
324        self.include_point(ctrl);
325        self.include_point(to);
326        self.elements.push(PathElement::QuadTo { ctrl, to });
327        self
328    }
329
330    pub fn cubic_to(&mut self, ctrl1: Point, ctrl2: Point, to: Point) -> &mut Self {
331        self.include_point(ctrl1);
332        self.include_point(ctrl2);
333        self.include_point(to);
334        self.elements
335            .push(PathElement::CubicTo { ctrl1, ctrl2, to });
336        self
337    }
338
339    pub fn close(&mut self) -> &mut Self {
340        self.elements.push(PathElement::Close);
341        self
342    }
343
344    pub fn push_rect(&mut self, rect: Rect) -> &mut Self {
345        if rect.is_empty() {
346            return self;
347        }
348
349        self.move_to(rect.origin)
350            .line_to(Point::new(rect.max_x(), rect.y()))
351            .line_to(Point::new(rect.max_x(), rect.max_y()))
352            .line_to(Point::new(rect.x(), rect.max_y()))
353            .close();
354        self
355    }
356
357    pub fn push_circle(&mut self, center: Point, radius: f32) -> &mut Self {
358        if radius <= 0.0 {
359            return self;
360        }
361
362        self.append_arc_segments(center, radius, 0.0, std::f32::consts::TAU, true);
363        self.close()
364    }
365
366    pub fn push_rounded_rect(&mut self, rect: Rect, radius: f32) -> &mut Self {
367        if rect.is_empty() {
368            return self;
369        }
370
371        let radius = radius
372            .max(0.0)
373            .min(rect.width() * 0.5)
374            .min(rect.height() * 0.5);
375        if radius <= 0.0 {
376            return self.push_rect(rect);
377        }
378
379        let min_x = rect.x();
380        let min_y = rect.y();
381        let max_x = rect.max_x();
382        let max_y = rect.max_y();
383
384        self.move_to(Point::new(min_x + radius, min_y))
385            .line_to(Point::new(max_x - radius, min_y));
386        self.append_arc_segments(
387            Point::new(max_x - radius, min_y + radius),
388            radius,
389            -std::f32::consts::FRAC_PI_2,
390            std::f32::consts::FRAC_PI_2,
391            false,
392        );
393        self.line_to(Point::new(max_x, max_y - radius));
394        self.append_arc_segments(
395            Point::new(max_x - radius, max_y - radius),
396            radius,
397            0.0,
398            std::f32::consts::FRAC_PI_2,
399            false,
400        );
401        self.line_to(Point::new(min_x + radius, max_y));
402        self.append_arc_segments(
403            Point::new(min_x + radius, max_y - radius),
404            radius,
405            std::f32::consts::FRAC_PI_2,
406            std::f32::consts::FRAC_PI_2,
407            false,
408        );
409        self.line_to(Point::new(min_x, min_y + radius));
410        self.append_arc_segments(
411            Point::new(min_x + radius, min_y + radius),
412            radius,
413            std::f32::consts::PI,
414            std::f32::consts::FRAC_PI_2,
415            false,
416        );
417        self.close()
418    }
419
420    pub fn push_arc(
421        &mut self,
422        center: Point,
423        radius: f32,
424        start_angle: f32,
425        sweep_angle: f32,
426    ) -> &mut Self {
427        if radius <= 0.0 || sweep_angle == 0.0 {
428            return self;
429        }
430
431        self.append_arc_segments(center, radius, start_angle, sweep_angle, true);
432        self
433    }
434
435    pub fn build(self) -> Path {
436        let bounds = match (self.min, self.max) {
437            (Some(min), Some(max)) => Rect::from_points(min, max),
438            _ => Rect::ZERO,
439        };
440
441        Path {
442            elements: self.elements,
443            bounds,
444        }
445    }
446
447    fn include_point(&mut self, point: Point) {
448        match (self.min.as_mut(), self.max.as_mut()) {
449            (Some(min), Some(max)) => {
450                min.x = min.x.min(point.x);
451                min.y = min.y.min(point.y);
452                max.x = max.x.max(point.x);
453                max.y = max.y.max(point.y);
454            }
455            _ => {
456                self.min = Some(point);
457                self.max = Some(point);
458            }
459        }
460    }
461
462    fn append_arc_segments(
463        &mut self,
464        center: Point,
465        radius: f32,
466        start_angle: f32,
467        sweep_angle: f32,
468        move_to_start: bool,
469    ) {
470        if radius <= 0.0 || sweep_angle == 0.0 {
471            return;
472        }
473
474        let segment_count = (sweep_angle.abs() / std::f32::consts::FRAC_PI_2).ceil() as usize;
475        let segment_count = segment_count.max(1);
476        let delta = sweep_angle / segment_count as f32;
477
478        for index in 0..segment_count {
479            let start = start_angle + (delta * index as f32);
480            let end = start + delta;
481            let start_point = arc_point(center, radius, start);
482            let end_point = arc_point(center, radius, end);
483            let tangent_scale = (4.0 / 3.0) * ((end - start) * 0.25).tan();
484            let ctrl1 = Point::new(
485                start_point.x - (start.sin() * radius * tangent_scale),
486                start_point.y + (start.cos() * radius * tangent_scale),
487            );
488            let ctrl2 = Point::new(
489                end_point.x + (end.sin() * radius * tangent_scale),
490                end_point.y - (end.cos() * radius * tangent_scale),
491            );
492
493            if index == 0 && move_to_start {
494                self.move_to(start_point);
495            }
496            self.cubic_to(ctrl1, ctrl2, end_point);
497        }
498    }
499}
500
501fn arc_point(center: Point, radius: f32, angle: f32) -> Point {
502    Point::new(
503        center.x + (radius * angle.cos()),
504        center.y + (radius * angle.sin()),
505    )
506}
507
508#[derive(Debug, Clone, Copy, PartialEq)]
509pub struct Transform {
510    pub xx: f32,
511    pub yx: f32,
512    pub xy: f32,
513    pub yy: f32,
514    pub dx: f32,
515    pub dy: f32,
516}
517
518impl Transform {
519    pub const IDENTITY: Self = Self::new(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
520
521    pub const fn new(xx: f32, yx: f32, xy: f32, yy: f32, dx: f32, dy: f32) -> Self {
522        Self {
523            xx,
524            yx,
525            xy,
526            yy,
527            dx,
528            dy,
529        }
530    }
531
532    pub const fn translation(x: f32, y: f32) -> Self {
533        Self::new(1.0, 0.0, 0.0, 1.0, x, y)
534    }
535
536    pub const fn translation_vector(delta: Vector) -> Self {
537        Self::translation(delta.x, delta.y)
538    }
539
540    pub const fn scale(x: f32, y: f32) -> Self {
541        Self::new(x, 0.0, 0.0, y, 0.0, 0.0)
542    }
543
544    pub fn rotation(radians: f32) -> Self {
545        let (sin, cos) = radians.sin_cos();
546        Self::new(cos, sin, -sin, cos, 0.0, 0.0)
547    }
548
549    pub const fn is_identity(self) -> bool {
550        self.xx == 1.0
551            && self.yx == 0.0
552            && self.xy == 0.0
553            && self.yy == 1.0
554            && self.dx == 0.0
555            && self.dy == 0.0
556    }
557
558    pub fn then(self, next: Self) -> Self {
559        Self::new(
560            (next.xx * self.xx) + (next.xy * self.yx),
561            (next.yx * self.xx) + (next.yy * self.yx),
562            (next.xx * self.xy) + (next.xy * self.yy),
563            (next.yx * self.xy) + (next.yy * self.yy),
564            (next.xx * self.dx) + (next.xy * self.dy) + next.dx,
565            (next.yx * self.dx) + (next.yy * self.dy) + next.dy,
566        )
567    }
568
569    pub fn transform_point(self, point: Point) -> Point {
570        Point::new(
571            (self.xx * point.x) + (self.xy * point.y) + self.dx,
572            (self.yx * point.x) + (self.yy * point.y) + self.dy,
573        )
574    }
575
576    pub fn transform_vector(self, vector: Vector) -> Vector {
577        Vector::new(
578            (self.xx * vector.x) + (self.xy * vector.y),
579            (self.yx * vector.x) + (self.yy * vector.y),
580        )
581    }
582
583    pub fn transform_rect_bbox(self, rect: Rect) -> Rect {
584        if rect.is_empty() {
585            return rect;
586        }
587
588        let top_left = self.transform_point(rect.origin);
589        let top_right = self.transform_point(Point::new(rect.max_x(), rect.y()));
590        let bottom_left = self.transform_point(Point::new(rect.x(), rect.max_y()));
591        let bottom_right = self.transform_point(Point::new(rect.max_x(), rect.max_y()));
592
593        let min_x = top_left
594            .x
595            .min(top_right.x)
596            .min(bottom_left.x)
597            .min(bottom_right.x);
598        let min_y = top_left
599            .y
600            .min(top_right.y)
601            .min(bottom_left.y)
602            .min(bottom_right.y);
603        let max_x = top_left
604            .x
605            .max(top_right.x)
606            .max(bottom_left.x)
607            .max(bottom_right.x);
608        let max_y = top_left
609            .y
610            .max(top_right.y)
611            .max(bottom_left.y)
612            .max(bottom_right.y);
613
614        Rect::from_points(Point::new(min_x, min_y), Point::new(max_x, max_y))
615    }
616}
617
618#[cfg(test)]
619mod path_tests {
620    use super::{Path, PathElement, Point, Rect};
621
622    fn assert_rect_approx_eq(actual: Rect, expected: Rect) {
623        assert!((actual.x() - expected.x()).abs() < 0.001);
624        assert!((actual.y() - expected.y()).abs() < 0.001);
625        assert!((actual.width() - expected.width()).abs() < 0.001);
626        assert!((actual.height() - expected.height()).abs() < 0.001);
627    }
628
629    #[test]
630    fn path_builder_tracks_elements_and_bounds() {
631        let mut builder = Path::builder();
632        builder
633            .move_to(Point::new(2.0, 3.0))
634            .quad_to(Point::new(12.0, 1.0), Point::new(18.0, 9.0))
635            .line_to(Point::new(6.0, 15.0))
636            .close();
637
638        let path = builder.build();
639
640        assert_eq!(path.bounds(), Rect::new(2.0, 1.0, 16.0, 14.0));
641        assert_eq!(path.elements().len(), 4);
642        assert!(matches!(path.elements()[0], PathElement::MoveTo(_)));
643        assert!(matches!(path.elements()[1], PathElement::QuadTo { .. }));
644        assert!(matches!(path.elements()[3], PathElement::Close));
645    }
646
647    #[test]
648    fn rect_conversion_builds_closed_path() {
649        let path = Path::from(Rect::new(4.0, 5.0, 12.0, 8.0));
650
651        assert_eq!(path.bounds(), Rect::new(4.0, 5.0, 12.0, 8.0));
652        assert_eq!(path.elements().len(), 5);
653        assert!(matches!(path.elements()[4], PathElement::Close));
654    }
655
656    #[test]
657    fn circle_builder_emits_closed_cubic_path() {
658        let path = Path::circle(Point::new(10.0, 20.0), 8.0);
659
660        assert_rect_approx_eq(path.bounds(), Rect::new(2.0, 12.0, 16.0, 16.0));
661        assert_eq!(path.elements().len(), 6);
662        assert!(matches!(path.elements()[0], PathElement::MoveTo(_)));
663        assert!(matches!(path.elements()[1], PathElement::CubicTo { .. }));
664        assert!(matches!(path.elements()[5], PathElement::Close));
665    }
666
667    #[test]
668    fn rounded_rect_builder_preserves_bounds() {
669        let path = Path::rounded_rect(Rect::new(4.0, 6.0, 24.0, 12.0), 3.0);
670
671        assert_rect_approx_eq(path.bounds(), Rect::new(4.0, 6.0, 24.0, 12.0));
672        assert_eq!(path.elements().len(), 10);
673        assert!(matches!(path.elements()[2], PathElement::CubicTo { .. }));
674        assert!(matches!(path.elements()[9], PathElement::Close));
675    }
676
677    #[test]
678    fn arc_builder_emits_open_curved_path() {
679        let path = Path::arc(
680            Point::new(20.0, 20.0),
681            10.0,
682            0.0,
683            std::f32::consts::FRAC_PI_2,
684        );
685
686        assert_eq!(path.bounds(), Rect::new(20.0, 20.0, 10.0, 10.0));
687        assert_eq!(path.elements().len(), 2);
688        assert!(matches!(path.elements()[0], PathElement::MoveTo(_)));
689        assert!(matches!(path.elements()[1], PathElement::CubicTo { .. }));
690    }
691}
692
693impl Default for Transform {
694    fn default() -> Self {
695        Self::IDENTITY
696    }
697}
698
699#[cfg(test)]
700mod tests {
701    use super::{Point, Rect, Transform, Vector};
702
703    #[test]
704    fn point_and_vector_math_is_stable() {
705        let origin = Point::new(10.0, 20.0);
706        let delta = Vector::new(5.0, -2.0);
707
708        assert_eq!(origin + delta, Point::new(15.0, 18.0));
709        assert_eq!((origin + delta) - origin, delta);
710    }
711
712    #[test]
713    fn rect_intersection_returns_overlap() {
714        let left = Rect::new(0.0, 0.0, 10.0, 10.0);
715        let right = Rect::new(8.0, 2.0, 10.0, 10.0);
716
717        assert_eq!(
718            left.intersection(right),
719            Some(Rect::new(8.0, 2.0, 2.0, 8.0))
720        );
721    }
722
723    #[test]
724    fn transform_composition_applies_in_order() {
725        let transform = Transform::scale(2.0, 3.0).then(Transform::translation(5.0, 7.0));
726
727        assert_eq!(
728            transform.transform_point(Point::new(4.0, 2.0)),
729            Point::new(13.0, 13.0)
730        );
731    }
732
733    #[test]
734    fn transform_rect_bbox_covers_rotated_rect() {
735        let rect = Rect::new(0.0, 0.0, 10.0, 4.0);
736        let bbox = Transform::rotation(std::f32::consts::FRAC_PI_2).transform_rect_bbox(rect);
737
738        assert!((bbox.x() + 4.0).abs() < 0.001);
739        assert!(bbox.y().abs() < 0.001);
740        assert!((bbox.width() - 4.0).abs() < 0.001);
741        assert!((bbox.height() - 10.0).abs() < 0.001);
742    }
743}