physdes-rs 0.1.6

Physical Design in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
#![allow(clippy::type_complexity)]

use num_traits::Num;
use std::cmp::Ordering;
use std::ops::{AddAssign, SubAssign};

use crate::point::Point;
use crate::vector2::Vector2;

/// Represents an arbitrary polygon with coordinates of type T
///
/// The `Polygon` struct stores the origin point and a vector of edges that define the polygon.
/// It provides various operations and functionalities for working with polygons, such as
/// area calculation, point containment checks, and geometric property verification.
///
/// ```svgbob
///       *-----*-----*
///      /     / \   \
///     /     /   \   \
///    *-----*     *---*
///    |  origin
///    *--> vecs[0]
/// ```
///
/// Properties:
///
/// * `origin`: The origin point of the polygon
/// * `vecs`: Vector of displacement vectors from origin to other vertices
///
/// # Examples
///
/// ```
/// use physdes::point::Point;
/// use physdes::polygon::Polygon;
/// use physdes::vector2::Vector2;
///
/// let origin = Point::new(0, 0);
/// let vecs = vec![Vector2::new(1, 0), Vector2::new(1, 1), Vector2::new(0, 1)];
/// let poly = Polygon::from_origin_and_vectors(origin, vecs);
/// assert_eq!(poly.origin, Point::new(0, 0));
/// assert_eq!(poly.vecs.len(), 3);
/// ```
#[derive(Eq, Clone, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct Polygon<T> {
    pub origin: Point<T, T>,
    pub vecs: Vec<Vector2<T, T>>,
}

impl<T: Clone + Num + Ord + Copy + std::ops::AddAssign> Polygon<T> {
    /// Constructs a new Polygon from a set of points
    ///
    /// The first point in the slice is used as the origin, and the remaining points
    /// are used to construct displacement vectors relative to the origin.
    ///
    /// # Arguments
    ///
    /// * `coords` - A slice of points representing the vertices of the polygon
    ///
    /// # Examples
    ///
    /// ```
    /// use physdes::point::Point;
    /// use physdes::polygon::Polygon;
    /// use physdes::vector2::Vector2;
    ///
    /// let p1 = Point::new(1, 1);
    /// let p2 = Point::new(2, 2);
    /// let p3 = Point::new(3, 3);
    /// let p4 = Point::new(4, 4);
    /// let p5 = Point::new(5, 5);
    /// let poly = Polygon::new(&[p1, p2, p3, p4, p5]);
    /// assert_eq!(poly.origin, Point::new(1, 1));
    /// assert_eq!(poly.vecs.len(), 4);
    /// assert_eq!(poly.vecs[0], Vector2::new(1, 1));
    /// ```
    pub fn new(coords: &[Point<T, T>]) -> Self {
        let (&origin, coords) = coords.split_first().unwrap();
        let vecs = coords.iter().map(|pt| *pt - origin).collect();
        Polygon { origin, vecs }
    }

    /// Constructs a new Polygon from origin and displacement vectors
    ///
    /// # Arguments
    ///
    /// * `origin` - The origin point of the polygon
    /// * `vecs` - Vector of displacement vectors from origin
    pub fn from_origin_and_vectors(origin: Point<T, T>, vecs: Vec<Vector2<T, T>>) -> Self {
        Polygon { origin, vecs }
    }

    /// Constructs a new Polygon from a point set
    ///
    /// The first point in the set is used as the origin, and the remaining points
    /// are used to construct displacement vectors relative to the origin.
    pub fn from_pointset(pointset: &[Point<T, T>]) -> Self {
        Self::new(pointset)
    }

    /// Calculates the area of the polygon
    ///
    /// Uses the shoelace formula (signed area):
    ///
    /// $$A = \frac{1}{2} \sum_{i=0}^{n-1} (x_i y_{i+1} - x_{i+1} y_i)$$
    ///
    /// # Returns
    ///
    /// The area of the polygon as a value of type T
    ///
    /// # Examples
    ///
    /// ```
    /// use physdes::point::Point;
    /// use physdes::polygon::Polygon;
    ///
    /// // Create a unit square
    /// let points = vec![
    ///     Point::new(0, 0),
    ///     Point::new(1, 0),
    ///     Point::new(1, 1),
    ///     Point::new(0, 1),
    /// ];
    /// let poly = Polygon::new(&points);
    /// let area = poly.area();
    /// // Note: area returns signed area (may be negative depending on vertex order)
    /// ```
    pub fn area(&self) -> T
    where
        T: std::ops::Sub<Output = T> + std::ops::AddAssign + std::ops::Mul<Output = T> + Copy,
    {
        let n = self.vecs.len();
        if n < 2 {
            return T::zero();
        }

        let vec0 = self.vecs[0];
        let vec1 = self.vecs[1];
        let itr = self.vecs.iter().skip(2);

        let mut res = vec0.x_ * vec1.y_ - self.vecs[n - 1].x_ * self.vecs[n - 2].y_;

        let mut vec0 = vec0;
        let mut vec1 = vec1;

        for vec2 in itr {
            res += vec1.x_ * (vec2.y_ - vec0.y_);
            vec0 = vec1;
            vec1 = *vec2;
        }

        res
    }

    /// Gets all vertices of the polygon as points
    ///
    /// # Returns
    ///
    /// A vector of all polygon vertices in order
    ///
    /// # Examples
    ///
    /// ```
    /// use physdes::point::Point;
    /// use physdes::polygon::Polygon;
    ///
    /// let points = vec![
    ///     Point::new(0, 0),
    ///     Point::new(1, 0),
    ///     Point::new(1, 1),
    ///     Point::new(0, 1),
    /// ];
    /// let poly = Polygon::new(&points);
    /// let vertices = poly.vertices();
    /// assert_eq!(vertices.len(), 4);
    /// assert_eq!(vertices[0], Point::new(0, 0));
    /// ```
    pub fn vertices(&self) -> Vec<Point<T, T>> {
        let mut result = Vec::with_capacity(self.vecs.len() + 1);
        result.push(self.origin);

        for vec in &self.vecs {
            result.push(self.origin + *vec);
        }

        result
    }

    /// Translates the polygon by adding a vector to its origin.
    pub fn add_assign(&mut self, rhs: Vector2<T, T>)
    where
        T: AddAssign,
    {
        self.origin += rhs;
    }

    /// Translates the polygon by subtracting a vector from its origin.
    pub fn sub_assign(&mut self, rhs: Vector2<T, T>)
    where
        T: SubAssign,
    {
        self.origin -= rhs;
    }

    /// Calculates the signed area of the polygon multiplied by 2
    ///
    /// Computes twice the signed area via the shoelace formula:
    ///
    /// $$2A = \sum_{i=0}^{n-1} (x_i y_{i+1} - x_{i+1} y_i)$$
    ///
    /// This avoids the need for floating-point arithmetic by omitting the $\frac{1}{2}$ factor.
    ///
    /// # Returns
    ///
    /// The signed area of the polygon multiplied by 2
    ///
    /// # Examples
    ///
    /// ```
    /// use physdes::point::Point;
    /// use physdes::polygon::Polygon;
    /// use physdes::vector2::Vector2;
    ///
    /// let p1 = Point::new(1, 1);
    /// let p2 = Point::new(2, 2);
    /// let p3 = Point::new(3, 3);
    /// let p4 = Point::new(4, 4);
    /// let p5 = Point::new(5, 5);
    /// let poly = Polygon::new(&[p1, p2, p3, p4, p5]);
    /// assert_eq!(poly.signed_area_x2(), 0);
    /// ```
    pub fn signed_area_x2(&self) -> T {
        let vecs = &self.vecs;
        let n = vecs.len();
        if n < 2 {
            return T::zero();
        }

        let mut itr = vecs.iter();
        let vec0 = itr.next().unwrap();
        let vec1 = itr.next().unwrap();
        let mut res = vec0.x_ * vec1.y_ - vecs[n - 1].x_ * vecs[n - 2].y_;

        let mut vec0 = vec0;
        let mut vec1 = vec1;

        for vec2 in itr {
            res += vec1.x_ * (vec2.y_ - vec0.y_);
            vec0 = vec1;
            vec1 = vec2;
        }

        res
    }

    /// Returns all vertices of the polygon as points.
    pub fn get_vertices(&self) -> Vec<Point<T, T>> {
        let mut result = Vec::with_capacity(self.vecs.len() + 1);
        result.push(self.origin);

        for vec in &self.vecs {
            result.push(self.origin + *vec);
        }

        result
    }

    /// Gets the bounding box of the polygon
    ///
    /// # Returns
    ///
    /// A tuple of (min_point, max_point) representing the bounding box
    ///
    /// # Examples
    ///
    /// ```
    /// use physdes::point::Point;
    /// use physdes::polygon::Polygon;
    ///
    /// let points = vec![
    ///     Point::new(0, 0),
    ///     Point::new(2, 0),
    ///     Point::new(2, 2),
    ///     Point::new(0, 2),
    /// ];
    /// let poly = Polygon::new(&points);
    /// let (min_pt, max_pt) = poly.bounding_box();
    /// assert_eq!(min_pt, Point::new(0, 0));
    /// assert_eq!(max_pt, Point::new(2, 2));
    /// ```
    pub fn bounding_box(&self) -> (Point<T, T>, Point<T, T>)
    where
        T: Ord + Copy,
    {
        let vertices = self.vertices();
        let mut min_x = vertices[0].xcoord;
        let mut min_y = vertices[0].ycoord;
        let mut max_x = vertices[0].xcoord;
        let mut max_y = vertices[0].ycoord;

        for pt in &vertices {
            if pt.xcoord < min_x {
                min_x = pt.xcoord;
            }
            if pt.ycoord < min_y {
                min_y = pt.ycoord;
            }
            if pt.xcoord > max_x {
                max_x = pt.xcoord;
            }
            if pt.ycoord > max_y {
                max_y = pt.ycoord;
            }
        }

        (Point::new(min_x, min_y), Point::new(max_x, max_y))
    }

    /// Checks if the polygon is rectilinear
    ///
    /// A polygon is rectilinear if all its edges are either horizontal or vertical.
    ///
    /// # Returns
    ///
    /// `true` if the polygon is rectilinear, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```
    /// use physdes::point::Point;
    /// use physdes::polygon::Polygon;
    ///
    /// let p1 = Point::new(0, 0);
    /// let p2 = Point::new(0, 1);
    /// let p3 = Point::new(1, 1);
    /// let p4 = Point::new(1, 0);
    /// let poly = Polygon::new(&[p1, p2, p3, p4]);
    /// assert!(poly.is_rectilinear());
    ///
    /// let p5 = Point::new(0, 0);
    /// let p6 = Point::new(1, 1);
    /// let p7 = Point::new(0, 2);
    /// let poly2 = Polygon::new(&[p5, p6, p7]);
    /// assert!(!poly2.is_rectilinear());
    /// ```
    pub fn is_rectilinear(&self) -> bool {
        if self.vecs.is_empty() {
            return true;
        }

        // Check from origin to vecs[0]
        if self.vecs[0].x_ != T::zero() && self.vecs[0].y_ != T::zero() {
            return false;
        }

        // Check between vecs
        for i in 0..self.vecs.len() - 1 {
            let v1 = self.vecs[i];
            let v2 = self.vecs[i + 1];
            if v1.x_ != v2.x_ && v1.y_ != v2.y_ {
                return false;
            }
        }

        // Check from vecs[-1] to origin
        let last_vec = self.vecs.last().unwrap();
        last_vec.x_ == T::zero() || last_vec.y_ == T::zero()
    }

    /// Checks if the polygon is oriented anticlockwise
    ///
    /// Uses the cross product sign at the minimum-coordinate vertex:
    ///
    /// $$\vec{p_{prev}} \times \vec{p_{next}} > 0$$
    /// where $\vec{p} = (current - prev)$ and $\vec{q} = (next - current)$
    pub fn is_anticlockwise(&self) -> bool
    where
        T: PartialOrd,
    {
        let mut pointset = Vec::with_capacity(self.vecs.len() + 1);
        pointset.push(Vector2::new(T::zero(), T::zero()));
        pointset.extend(self.vecs.iter().cloned());

        if pointset.len() < 3 {
            panic!("Polygon must have at least 3 points");
        }

        // Find the point with minimum coordinates
        let (min_index, _) = pointset
            .iter()
            .enumerate()
            .min_by(|(_, a), (_, b)| {
                a.x_.partial_cmp(&b.x_)
                    .unwrap_or(Ordering::Equal)
                    .then(a.y_.partial_cmp(&b.y_).unwrap_or(Ordering::Equal))
            })
            .unwrap();

        // Get previous and next points with wrap-around
        let n = pointset.len();
        let prev_point = pointset[(min_index + n - 1) % n];
        let current_point = pointset[min_index];
        let next_point = pointset[(min_index + 1) % n];

        // Calculate cross product
        (current_point - prev_point).cross(&(next_point - current_point)) > T::zero()
    }

    /// Checks if the polygon is convex
    ///
    /// A polygon is convex if all its interior angles are less than 180 degrees
    /// and no edges bend inward. All consecutive cross products must have the same sign:
    ///
    /// $$(v_i - v_{i-1}) \times (v_{i+1} - v_i) \text{ has consistent sign for all } i$$
    ///
    /// # Returns
    ///
    /// `true` if the polygon is convex, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```
    /// use physdes::point::Point;
    /// use physdes::polygon::Polygon;
    ///
    /// // Convex square
    /// let convex_points = vec![
    ///     Point::new(0, 0),
    ///     Point::new(1, 0),
    ///     Point::new(1, 1),
    ///     Point::new(0, 1),
    /// ];
    /// let convex_poly = Polygon::new(&convex_points);
    /// assert!(convex_poly.is_convex());
    ///
    /// // Concave polygon (L-shape)
    /// let concave_points = vec![
    ///     Point::new(0, 0),
    ///     Point::new(2, 0),
    ///     Point::new(2, 1),
    ///     Point::new(1, 1),
    ///     Point::new(1, 2),
    ///     Point::new(0, 2),
    /// ];
    /// let concave_poly = Polygon::new(&concave_points);
    /// assert!(!concave_poly.is_convex());
    /// ```
    pub fn is_convex(&self) -> bool
    where
        T: PartialOrd,
    {
        let n = self.vecs.len();
        if n < 2 {
            return false;
        }
        if n == 2 {
            return true;
        }

        // Compute initial cross product sign using vecs[N-2] and vecs[0].
        // In pointset terms: pointset[N-2] = vecs[N-2], pointset[1] = vecs[0].
        // cross = -a.x*b.y + a.y*b.x  (rearranged to avoid unary negation)
        let cross_product_sign =
            self.vecs[n - 2].y_ * self.vecs[0].x_ - self.vecs[n - 2].x_ * self.vecs[0].y_;

        for i in 0..n - 1 {
            let v0 = if i == 0 {
                Vector2::new(T::zero(), T::zero())
            } else {
                self.vecs[i - 1]
            };
            let v1 = self.vecs[i];
            let v2 = self.vecs[i + 1];

            let current_cross =
                (v1.x_ - v0.x_) * (v2.y_ - v1.y_) - (v1.y_ - v0.y_) * (v2.x_ - v1.x_);

            if (cross_product_sign > T::zero()) != (current_cross > T::zero()) {
                return false;
            }
        }

        true
    }
}

/// Creates a monotone polygon from a set of points using a custom comparison function
///
/// Partitions points using a cross product test relative to the extremal points:
///
/// $$\vec{diff} \times (p - min) \le 0$$
///
/// # Arguments
///
/// * `pointset` - A slice of points to create the polygon from
/// * `f` - A closure that defines the ordering of points
pub fn create_mono_polygon<T, F>(pointset: &[Point<T, T>], func: F) -> Vec<Point<T, T>>
where
    T: Clone + Num + Ord + Copy + PartialOrd,
    F: Fn(&Point<T, T>) -> (T, T),
{
    let max_pt = pointset
        .iter()
        .max_by(|a, b| func(a).partial_cmp(&func(b)).unwrap())
        .unwrap();
    let min_pt = pointset
        .iter()
        .min_by(|a, b| func(a).partial_cmp(&func(b)).unwrap())
        .unwrap();
    let diff = *max_pt - *min_pt;

    let (mut lst1, mut lst2): (Vec<Point<T, T>>, Vec<Point<T, T>>) = pointset
        .iter()
        .partition(|&a| diff.cross(&(*a - *min_pt)) <= T::zero());

    lst1.sort_by_key(|a| func(a));
    lst2.sort_by_key(|a| func(a));
    lst2.reverse();
    lst1.append(&mut lst2);
    lst1
}

/// Creates an x-monotone polygon from a set of points
///
/// Points are ordered primarily by x-coordinate, secondarily by y-coordinate
///
/// # Arguments
///
/// * `pointset` - A slice of points to order
///
/// # Returns
///
/// A vector of points ordered to form an x-monotone polygon
///
/// # Examples
///
/// ```
/// use physdes::point::Point;
/// use physdes::polygon::create_xmono_polygon;
///
/// let points = vec![
///     Point::new(1, 1),
///     Point::new(3, 2),
///     Point::new(2, 0),
///     Point::new(0, 2),
/// ];
/// let ordered = create_xmono_polygon(&points);
/// // Result is ordered to create x-monotone polygon
/// assert_eq!(ordered.len(), 4);
/// ```
#[inline]
pub fn create_xmono_polygon<T>(pointset: &[Point<T, T>]) -> Vec<Point<T, T>>
where
    T: Clone + Num + Ord + Copy + PartialOrd,
{
    create_mono_polygon(pointset, |a| (a.xcoord, a.ycoord))
}

/// Creates a y-monotone polygon from a set of points
///
/// Points are ordered primarily by y-coordinate, secondarily by x-coordinate
///
/// # Arguments
///
/// * `pointset` - A slice of points to order
///
/// # Returns
///
/// A vector of points ordered to form a y-monotone polygon
///
/// # Examples
///
/// ```
/// use physdes::point::Point;
/// use physdes::polygon::create_ymono_polygon;
///
/// let points = vec![
///     Point::new(1, 1),
///     Point::new(2, 3),
///     Point::new(0, 2),
///     Point::new(2, 0),
/// ];
/// let ordered = create_ymono_polygon(&points);
/// // Result is ordered to create y-monotone polygon
/// assert_eq!(ordered.len(), 4);
/// ```
#[inline]
pub fn create_ymono_polygon<T>(pointset: &[Point<T, T>]) -> Vec<Point<T, T>>
where
    T: Clone + Num + Ord + Copy + PartialOrd,
{
    create_mono_polygon(pointset, |a| (a.ycoord, a.xcoord))
}

/// Checks if a polygon is monotone in a given direction
///
/// A polygon is monotone in direction $d$ if the two chains from the minimum
/// to maximum vertex in direction $d$ are both monotonic (non-decreasing in $d$).
pub fn polygon_is_monotone<T, F>(lst: &[Point<T, T>], dir: F) -> bool
where
    T: Clone + Num + Ord + Copy + PartialOrd,
    F: Fn(&Point<T, T>) -> (T, T),
{
    if lst.len() <= 3 {
        return true;
    }

    let (min_index, _) = lst
        .iter()
        .enumerate()
        .min_by(|(_, a), (_, b)| dir(a).partial_cmp(&dir(b)).unwrap())
        .unwrap();

    let (max_index, _) = lst
        .iter()
        .enumerate()
        .max_by(|(_, a), (_, b)| dir(a).partial_cmp(&dir(b)).unwrap())
        .unwrap();

    let n = lst.len();

    // Chain from min to max
    let mut i = min_index;
    while i != max_index {
        let next_i = (i + 1) % n;
        if dir(&lst[i]).0 > dir(&lst[next_i]).0 {
            return false;
        }
        i = next_i;
    }

    // Chain from max to min
    let mut i = max_index;
    while i != min_index {
        let next_i = (i + 1) % n;
        if dir(&lst[i]).0 < dir(&lst[next_i]).0 {
            return false;
        }
        i = next_i;
    }

    true
}

/// Checks if a polygon is x-monotone
pub fn polygon_is_xmonotone<T>(lst: &[Point<T, T>]) -> bool
where
    T: Clone + Num + Ord + Copy + PartialOrd,
{
    polygon_is_monotone(lst, |pt| (pt.xcoord, pt.ycoord))
}

/// Checks if a polygon is y-monotone
pub fn polygon_is_ymonotone<T>(lst: &[Point<T, T>]) -> bool
where
    T: Clone + Num + Ord + Copy + PartialOrd,
{
    polygon_is_monotone(lst, |pt| (pt.ycoord, pt.xcoord))
}

/// Determines if a point is inside a polygon using the winding number algorithm
///
/// Counts edge crossings using a cross product test:
///
/// $$\vec{(q-p_0)} \times \vec{(p_1-p_0)} \text{ determines which side of the edge the point lies on}$$
pub fn point_in_polygon<T>(pointset: &[Point<T, T>], ptq: &Point<T, T>) -> bool
where
    T: Clone + Num + Ord + Copy + PartialOrd,
{
    let n = pointset.len();
    if n == 0 {
        return false;
    }

    let mut pt0 = &pointset[n - 1];
    let mut res = false;

    for pt1 in pointset.iter() {
        if (pt1.ycoord <= ptq.ycoord && ptq.ycoord < pt0.ycoord)
            || (pt0.ycoord <= ptq.ycoord && ptq.ycoord < pt1.ycoord)
        {
            let det = (*ptq - *pt0).cross(&(*pt1 - *pt0));
            if pt1.ycoord > pt0.ycoord {
                if det < T::zero() {
                    res = !res;
                }
            } else if det > T::zero() {
                res = !res;
            }
        }
        pt0 = pt1;
    }

    res
}

/// Determines if a polygon represented by points is oriented anticlockwise
///
/// $$\vec{p_{prev}} \times \vec{p_{next}} > 0$$
/// at the minimum-coordinate vertex.
pub fn polygon_is_anticlockwise<T>(pointset: &[Point<T, T>]) -> bool
where
    T: Clone + Num + Ord + Copy + PartialOrd,
{
    if pointset.len() < 3 {
        panic!("Polygon must have at least 3 points");
    }

    // Find the point with minimum coordinates
    let (min_index, _) = pointset
        .iter()
        .enumerate()
        .min_by(|(_, a), (_, b)| {
            a.xcoord
                .partial_cmp(&b.xcoord)
                .unwrap_or(Ordering::Equal)
                .then(a.ycoord.partial_cmp(&b.ycoord).unwrap_or(Ordering::Equal))
        })
        .unwrap();

    // Get previous and next points with wrap-around
    let n = pointset.len();
    let prev_point = pointset[(min_index + n - 1) % n];
    let current_point = pointset[min_index];
    let next_point = pointset[(min_index + 1) % n];

    // Calculate cross product
    (current_point - prev_point).cross(&(next_point - current_point)) > T::zero()
}

// Implement PartialEq for Polygon
impl<T: PartialEq> PartialEq for Polygon<T> {
    /// Returns `true` if two polygons have the same origin and vectors.
    fn eq(&self, other: &Self) -> bool {
        self.origin == other.origin && self.vecs == other.vecs
    }
}

// Implement AddAssign and SubAssign for Polygon
impl<T: AddAssign + Clone + Num> AddAssign<Vector2<T, T>> for Polygon<T> {
    /// Translates the polygon by adding a vector to its origin.
    fn add_assign(&mut self, rhs: Vector2<T, T>) {
        self.origin += rhs;
    }
}

impl<T: SubAssign + Clone + Num> SubAssign<Vector2<T, T>> for Polygon<T> {
    /// Translates the polygon by subtracting a vector from its origin.
    fn sub_assign(&mut self, rhs: Vector2<T, T>) {
        self.origin -= rhs;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::point::Point;
    use crate::vector2::Vector2;

    #[test]
    fn test_polygon() {
        let coords = [
            (-2, 2),
            (0, -1),
            (-5, 1),
            (-2, 4),
            (0, -4),
            (-4, 3),
            (-6, -2),
            (5, 1),
            (2, 2),
            (3, -3),
            (-3, -3),
            (3, 3),
            (-3, -4),
            (1, 4),
        ];

        let mut pointset = Vec::new();
        for (x_coord, y_coord) in coords.iter() {
            pointset.push(Point::new(*x_coord, *y_coord));
        }

        let poly_points = create_xmono_polygon(&pointset);
        assert!(polygon_is_anticlockwise(&poly_points));

        let poly = Polygon::from_pointset(&poly_points);
        let mut poly2 = Polygon::from_pointset(&poly_points);
        poly2.add_assign(Vector2::new(4, 5));
        poly2.sub_assign(Vector2::new(4, 5));
        assert_eq!(poly2, poly);
    }

    #[test]
    fn test_ymono_polygon() {
        let coords = [
            (-2, 2),
            (0, -1),
            (-5, 1),
            (-2, 4),
            (0, -4),
            (-4, 3),
            (-6, -2),
            (5, 1),
            (2, 2),
            (3, -3),
            (-3, -3),
            (3, 3),
            (-3, -4),
            (1, 4),
        ];

        let mut pointset = Vec::new();
        for (x_coord, y_coord) in coords.iter() {
            pointset.push(Point::new(*x_coord, *y_coord));
        }

        let poly_points = create_ymono_polygon(&pointset);
        assert!(polygon_is_ymonotone(&poly_points));
        assert!(!polygon_is_xmonotone(&poly_points));
        assert!(polygon_is_anticlockwise(&poly_points));

        let poly = Polygon::from_pointset(&poly_points);
        assert_eq!(poly.signed_area_x2(), 102);
        assert!(poly.is_anticlockwise());
    }

    #[test]
    fn test_xmono_polygon() {
        let coords = [
            (-2, 2),
            (0, -1),
            (-5, 1),
            (-2, 4),
            (0, -4),
            (-4, 3),
            (-6, -2),
            (5, 1),
            (2, 2),
            (3, -3),
            (-3, -3),
            (3, 3),
            (-3, -4),
            (1, 4),
        ];

        let mut pointset = Vec::new();
        for (x_coord, y_coord) in coords.iter() {
            pointset.push(Point::new(*x_coord, *y_coord));
        }

        let poly_points = create_xmono_polygon(&pointset);
        assert!(polygon_is_xmonotone(&poly_points));
        assert!(!polygon_is_ymonotone(&poly_points));
        assert!(polygon_is_anticlockwise(&poly_points));

        let poly = Polygon::from_pointset(&poly_points);
        assert_eq!(poly.signed_area_x2(), 111);
        assert!(poly.is_anticlockwise());
    }

    #[test]
    fn test_is_rectilinear() {
        // Create a rectilinear polygon
        let rectilinear_coords = [(0, 0), (0, 1), (1, 1), (1, 0)];
        let rectilinear_points: Vec<Point<i32, i32>> = rectilinear_coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        let rectilinear_polygon = Polygon::from_pointset(&rectilinear_points);
        assert!(rectilinear_polygon.is_rectilinear());

        // Create a non-rectilinear polygon
        let non_rectilinear_coords = [(0, 0), (1, 1), (2, 0)];
        let non_rectilinear_points: Vec<Point<i32, i32>> = non_rectilinear_coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        let non_rectilinear_polygon = Polygon::from_pointset(&non_rectilinear_points);
        assert!(!non_rectilinear_polygon.is_rectilinear());
    }

    #[test]
    fn test_is_convex() {
        // Test case 1: Convex polygon
        let convex_coords = [(0, 0), (2, 0), (2, 2), (0, 2)];
        let convex_points: Vec<Point<i32, i32>> = convex_coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        let convex_polygon = Polygon::from_pointset(&convex_points);
        assert!(convex_polygon.is_convex());

        // Test case 2: Non-convex polygon
        let non_convex_coords = [(0, 0), (2, 0), (1, 1), (2, 2), (0, 2)];
        let non_convex_points: Vec<Point<i32, i32>> = non_convex_coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        let non_convex_polygon = Polygon::from_pointset(&non_convex_points);
        assert!(!non_convex_polygon.is_convex());

        // Test case 3: Triangle (always convex)
        let triangle_coords = [(0, 0), (2, 0), (1, 2)];
        let triangle_points: Vec<Point<i32, i32>> = triangle_coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        let triangle = Polygon::from_pointset(&triangle_points);
        assert!(triangle.is_convex());
    }

    #[test]
    fn test_is_anticlockwise() {
        // Clockwise polygon
        let clockwise_coords = [(0, 0), (0, 1), (1, 1), (1, 0)];
        let clockwise_points: Vec<Point<i32, i32>> = clockwise_coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        let clockwise_polygon = Polygon::from_pointset(&clockwise_points);
        assert!(!clockwise_polygon.is_anticlockwise());

        // Counter-clockwise polygon
        let counter_clockwise_coords = [(0, 0), (1, 0), (1, 1), (0, 1)];
        let counter_clockwise_points: Vec<Point<i32, i32>> = counter_clockwise_coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        let counter_clockwise_polygon = Polygon::from_pointset(&counter_clockwise_points);
        assert!(counter_clockwise_polygon.is_anticlockwise());
    }

    #[test]
    fn test_is_convex_clockwise() {
        // Convex clockwise polygon
        let convex_coords = [(0, 0), (0, 2), (2, 2), (2, 0)];
        let convex_points: Vec<Point<i32, i32>> = convex_coords
            .iter()
            .map(|(x, y)| Point::new(*x, *y))
            .collect();
        let convex_polygon = Polygon::from_pointset(&convex_points);
        assert!(convex_polygon.is_convex());

        // Non-convex clockwise polygon
        let non_convex_coords = [(0, 0), (0, 2), (1, 1), (2, 2), (2, 0)];
        let non_convex_points: Vec<Point<i32, i32>> = non_convex_coords
            .iter()
            .map(|(x, y)| Point::new(*x, *y))
            .collect();
        let non_convex_polygon = Polygon::from_pointset(&non_convex_points);
        assert!(!non_convex_polygon.is_convex());
    }

    #[test]
    fn test_point_in_polygon_missed_branches() {
        let coords = [(0, 0), (10, 0), (10, 10), (0, 10)];
        let pointset: Vec<Point<i32, i32>> = coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();

        // Test case where ptq.ycoord == pt0.ycoord
        assert!(!point_in_polygon(&pointset, &Point::new(5, 10)));

        // Test case where ptq.ycoord == pt1.ycoord
        assert!(point_in_polygon(&pointset, &Point::new(5, 0)));

        // Test case where det == 0 (point on edge)
        assert!(point_in_polygon(&pointset, &Point::new(5, 0)));
    }

    #[test]
    #[should_panic(expected = "Polygon must have at least 3 points")]
    fn test_polygon_is_anticlockwise_less_than_3_points() {
        let coords = [(0, 0), (0, 1)];
        let points: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
        polygon_is_anticlockwise(&points);
    }

    #[test]
    #[should_panic(expected = "Polygon must have at least 3 points")]
    fn test_is_anticlockwise_less_than_3_points() {
        let coords = [(0, 0), (0, 1)];
        let points: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
        let polygon = Polygon::from_pointset(&points);
        polygon.is_anticlockwise();
    }

    #[test]
    fn test_is_convex_more() {
        // Non-convex anti-clockwise polygon
        let non_convex_coords = [(0, 0), (2, 0), (1, 1), (2, 2), (0, 2)];
        let non_convex_points: Vec<Point<i32, i32>> = non_convex_coords
            .iter()
            .map(|(x, y)| Point::new(*x, *y))
            .collect();
        let non_convex_polygon = Polygon::from_pointset(&non_convex_points);
        assert!(!non_convex_polygon.is_convex());

        // Convex anti-clockwise polygon
        let convex_coords = [(0, 0), (2, 0), (2, 2), (0, 2)];
        let convex_points: Vec<Point<i32, i32>> = convex_coords
            .iter()
            .map(|(x, y)| Point::new(*x, *y))
            .collect();
        let convex_polygon = Polygon::from_pointset(&convex_points);
        assert!(convex_polygon.is_convex());
    }

    #[test]
    fn test_point_in_polygon_more() {
        // Create a polygon that will trigger the missed branches
        let coords = [(0, 0), (10, 5), (0, 10)];
        let pointset: Vec<Point<i32, i32>> = coords
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();

        // This should trigger `det > 0`
        assert!(point_in_polygon(&pointset, &Point::new(1, 5)));

        // Create a clockwise polygon to trigger `det < 0`
        let coords_cw = [(0, 0), (0, 10), (10, 5)];
        let pointset_cw: Vec<Point<i32, i32>> = coords_cw
            .iter()
            .map(|(x_coord, y_coord)| Point::new(*x_coord, *y_coord))
            .collect();
        assert!(point_in_polygon(&pointset_cw, &Point::new(1, 5)));
    }

    #[test]
    fn test_is_rectilinear_non_rectilinear_last_edge() {
        // Last edge from last vec to origin is diagonal, not axis-aligned
        let coords = [(0, 0), (4, 0), (4, 4), (1, 3)];
        let points: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
        let poly = Polygon::from_pointset(&points);
        assert!(!poly.is_rectilinear());
    }

    #[test]
    fn test_is_convex_less_than_two_vecs() {
        // Polygon with only 1 vec (2 vertices), is_convex should return false
        let origin = Point::new(0, 0);
        let vecs = vec![Vector2::new(4, 0)];
        let poly = Polygon::from_origin_and_vectors(origin, vecs);
        assert!(!poly.is_convex());
    }

    #[test]
    fn test_bounding_box_branches() {
        // Polygon where y varies both decreasing and increasing to test min/max branches
        let coords = [(3, 5), (8, 2), (10, 7), (6, 9), (1, 4)];
        let points: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
        let poly = Polygon::from_pointset(&points);
        let (min_pt, max_pt) = poly.bounding_box();
        assert_eq!(min_pt, Point::new(1, 2));
        assert_eq!(max_pt, Point::new(10, 9));
    }
}

#[test]
fn test_polygon_signed_area_x2() {
    // Test signed_area_x2 for different polygons
    let coords = [(0, 0), (4, 0), (4, 3), (0, 3)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let poly = Polygon::from_pointset(&pointset);
    assert_eq!(poly.signed_area_x2(), 24); // 2 * (4*3) = 24
}

#[test]
fn test_polygon_vertices() {
    let coords = [(0, 0), (4, 0), (4, 3), (0, 3)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let poly = Polygon::from_pointset(&pointset);
    let vertices = poly.vertices();
    assert_eq!(vertices.len(), 4);
}

#[test]
fn test_polygon_bounding_box() {
    let coords = [(1, 1), (5, 1), (5, 4), (1, 4)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let poly = Polygon::from_pointset(&pointset);
    let (min, max) = poly.bounding_box();
    assert_eq!(min, Point::new(1, 1));
    assert_eq!(max, Point::new(5, 4));
}

#[test]
fn test_polygon_add_assign() {
    let coords = [(0, 0), (4, 0), (4, 3), (0, 3)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let mut poly = Polygon::from_pointset(&pointset);
    poly.add_assign(Vector2::new(1, 2));
    assert_eq!(poly.origin, Point::new(1, 2));
}

#[test]
fn test_polygon_sub_assign() {
    let coords = [(1, 2), (5, 2), (5, 5), (1, 5)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let mut poly = Polygon::from_pointset(&pointset);
    poly.sub_assign(Vector2::new(1, 2));
    assert_eq!(poly.origin, Point::new(0, 0));
}

#[test]
fn test_polygon_partial_eq() {
    let coords = [(0, 0), (4, 0), (4, 3), (0, 3)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let poly1 = Polygon::from_pointset(&pointset);
    let poly2 = Polygon::from_pointset(&pointset);
    assert_eq!(poly1, poly2);

    let coords2 = [(0, 0), (5, 0), (5, 3), (0, 3)];
    let pointset2: Vec<Point<i32, i32>> = coords2.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let poly3 = Polygon::from_pointset(&pointset2);
    assert_ne!(poly1, poly3);
}

#[test]
fn test_polygon_from_origin_and_vectors() {
    let origin = Point::new(0, 0);
    let vecs = vec![Vector2::new(4, 0), Vector2::new(0, 3), Vector2::new(-4, 0)];
    let poly = Polygon::from_origin_and_vectors(origin, vecs);
    assert_eq!(poly.origin, Point::new(0, 0));
    assert_eq!(poly.vecs.len(), 3);
}

#[test]
fn test_polygon_default() {
    let poly: Polygon<i32> = Polygon::default();
    assert_eq!(poly.origin, Point::new(0, 0));
}

#[test]
fn test_polygon_is_monotone_custom() {
    // Test polygon_is_monotone with custom direction
    let coords = [(0, 0), (1, 0), (2, 1), (1, 2), (0, 2)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    // x-monotone
    assert!(polygon_is_monotone(&pointset, |pt| (pt.xcoord, pt.ycoord)));
}

#[test]
fn test_create_mono_polygon_custom() {
    // Test create_mono_polygon with custom function
    let coords = [(0, 0), (2, 1), (1, 2), (3, 2)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let result = create_mono_polygon(&pointset, |pt| (pt.xcoord, pt.ycoord));
    assert!(!result.is_empty());
}

#[test]
fn test_polygon_empty_vecs_is_rectilinear() {
    // Edge case: polygon with no vecs should be rectilinear
    let origin = Point::new(0, 0);
    let poly = Polygon::from_origin_and_vectors(origin, vec![]);
    assert!(poly.is_rectilinear());
}

#[test]
fn test_polygon_signed_area_x2_triangle() {
    // Triangle area calculation
    let coords = [(0, 0), (3, 0), (0, 4)];
    let pointset: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let poly = Polygon::from_pointset(&pointset);
    // Area = 0.5 * |0*(0-4) + 3*(4-0) + 0*(0-0)| = 0.5 * 12 = 6
    // signed_area_x2 = 2 * area = 12
    assert_eq!(poly.signed_area_x2(), 12);
}

#[test]
fn test_polygon_signed_area_x2_single_vec() {
    // Polygon with just 1 vec (2 vertices), signed_area_x2 should return 0 (n < 2)
    let origin = Point::new(0, 0);
    let vecs = vec![Vector2::new(4, 0)];
    let poly = Polygon::from_origin_and_vectors(origin, vecs);
    assert_eq!(poly.signed_area_x2(), 0);
}

#[test]
fn test_polygon_area_multi_vertex() {
    // Pentagon to exercise the area() calculation loop body
    let coords = [(0, 0), (4, 0), (5, 3), (2, 5), (-1, 2)];
    let points: Vec<Point<i32, i32>> = coords.iter().map(|(x, y)| Point::new(*x, *y)).collect();
    let poly = Polygon::from_pointset(&points);
    // area is signed, should be nonzero for a valid polygon
    assert_ne!(poly.area(), 0);
}