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
//! Primitive topological structures.
//!
//! This module provides composable primitives that describe polygonal
//! structures. This includes simple _$n$-gons_ like triangles, _generators_
//! that form polytopes like spheres, and _iterator expressions_ that compose
//! and decompose streams of primitives.
//!
//! Types in this module generally describe [_cycle
//! graphs_](https://en.wikipedia.org/wiki/cycle_graph) and are not strictly
//! geometric. For example, `Polygonal` types may be geometrically degenerate
//! (e.g., collinear, converged, etc.) or used to approximate polygons from
//! $\Reals^2$ embedded into higher-dimensional Euclidean spaces. These types
//! are also used for indexing, in which case their representation and data are
//! both entirely topological.
//!
//! Plexus uses the terms _trigon_ and _tetragon_ for its polygon types, which
//! mean _triangle_ and _quadrilateral_, respectively. This is done for
//! consistency with higher arity polygon names (e.g., _decagon_). In some
//! contexts, the term _triangle_ is still used, such as in functions concerning
//! _triangulation_.
//!
//! # Examples
//!
//! Generating raw buffers with the positional data for a sphere approximation:
//!
//! ```rust
//! # extern crate nalgebra;
//! # extern crate plexus;
//! #
//! use nalgebra::Point3;
//! use plexus::prelude::*;
//! use plexus::primitive::generate::Position;
//! use plexus::primitive::sphere::UvSphere;
//!
//! let sphere = UvSphere::new(16, 16);
//!
//! // Generate the unique set of positional vertices.
//! let positions = sphere
//!     .vertices::<Position<Point3<f64>>>()
//!     .collect::<Vec<_>>();
//!
//! // Generate polygons that index the unique set of positional vertices. The
//! // polygons are decomposed into triangles and then into vertices, where each
//! // vertex is an index into the position data.
//! let indices = sphere
//!     .indexing_polygons::<Position>()
//!     .triangulate()
//!     .vertices()
//!     .collect::<Vec<_>>();
//! ```
//!
//! Generating raw buffers with positional data for a cube using an indexer:
//!
//! ```rust
//! # extern crate decorum;
//! # extern crate nalgebra;
//! # extern crate plexus;
//! #
//! use decorum::N64;
//! use nalgebra::Point3;
//! use plexus::index::{Flat3, HashIndexer};
//! use plexus::prelude::*;
//! use plexus::primitive::cube::Cube;
//! use plexus::primitive::generate::Position;
//!
//! let (indices, positions) = Cube::new()
//!     .polygons::<Position<Point3<N64>>>()
//!     .triangulate()
//!     .index_vertices::<Flat3, _>(HashIndexer::default());
//! ```

pub mod cube;
pub mod decompose;
pub mod generate;
pub mod sphere;

use arrayvec::{Array, ArrayVec};
use decorum::Real;
use itertools::izip;
use itertools::structs::Zip as OuterZip; // Avoid collision with `Zip`.
use num::{Integer, One, Signed, Zero};
use smallvec::{smallvec, SmallVec};
use std::convert::TryInto;
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use theon::adjunct::{Adjunct, Converged, Fold, FromItems, IntoItems, Map, Push, ZipMap};
use theon::ops::Cross;
use theon::query::{Intersection, Line, Plane, Unit};
use theon::space::{EuclideanSpace, FiniteDimensional, Scalar, Vector, VectorSpace};
use theon::{AsPosition, Position};
use typenum::type_operators::Cmp;
use typenum::{Greater, U2, U3};

use crate::primitive::decompose::IntoVertices;
use crate::{DynamicArity, IteratorExt as _, Monomorphic, StaticArity};

/// Primitive topological structure.
///
/// Types implementing `Topological` provide some notion of adjacency between
/// vertices of their `Vertex` type. These types typically represent cycle
/// graphs and polygonal structures, but may also include degenerate forms like
/// monogons.
pub trait Topological:
    Adjunct<Item = <Self as Topological>::Vertex>
    + AsMut<[<Self as Topological>::Vertex]>
    + AsRef<[<Self as Topological>::Vertex]>
    + DynamicArity<Dynamic = usize>
    + IntoIterator<Item = <Self as Topological>::Vertex>
    + Sized
{
    type Vertex;

    fn try_from_slice<T>(vertices: T) -> Option<Self>
    where
        Self::Vertex: Copy,
        T: AsRef<[Self::Vertex]>;

    /// Embeds an $n$-gon from $\Reals^2$ into $\Reals^3$.
    ///
    /// The scalar for the additional basis is normalized to the given value.
    ///
    /// # Examples
    ///
    /// Embedding a triangle into the $xy$-plane at $z=1$:
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate theon;
    /// #
    /// use nalgebra::Point2;
    /// use plexus::primitive::{Topological, Trigon};
    /// use theon::space::EuclideanSpace;
    ///
    /// type E2 = Point2<f64>;
    ///
    /// let trigon = Trigon::embed_into_e3_xy(
    ///     Trigon::from([
    ///         E2::from_xy(-1.0, 0.0),
    ///         E2::from_xy(0.0, 1.0),
    ///         E2::from_xy(1.0, 0.0),
    ///     ]),
    ///     1.0,
    /// );
    /// ```
    fn embed_into_e3_xy<P>(ngon: P, z: Scalar<Self::Vertex>) -> Self
    where
        Self::Vertex: EuclideanSpace + FiniteDimensional<N = U3>,
        P: Map<Self::Vertex, Output = Self> + Topological,
        P::Vertex: EuclideanSpace + FiniteDimensional<N = U2> + Push<Output = Self::Vertex>,
        Vector<P::Vertex>: VectorSpace<Scalar = Scalar<Self::Vertex>>,
    {
        Self::embed_into_e3_xy_with(ngon, z, |position| position)
    }

    fn embed_into_e3_xy_with<P, F>(ngon: P, z: Scalar<Position<Self::Vertex>>, mut f: F) -> Self
    where
        Self::Vertex: AsPosition,
        Position<Self::Vertex>: EuclideanSpace + FiniteDimensional<N = U3>,
        P: Map<Self::Vertex, Output = Self> + Topological,
        P::Vertex:
            EuclideanSpace + FiniteDimensional<N = U2> + Push<Output = Position<Self::Vertex>>,
        Vector<P::Vertex>: VectorSpace<Scalar = Scalar<Position<Self::Vertex>>>,
        F: FnMut(Position<Self::Vertex>) -> Self::Vertex,
    {
        ngon.map(move |position| f(position.push(z)))
    }

    /// Embeds an $n$-gon from $\Reals^2$ into $\Reals^3$.
    ///
    /// The $n$-gon is rotated into the given plane about the origin.
    ///
    /// # Examples
    ///
    /// Embedding a triangle into the $xy$-plane at $z=0$:
    ///
    /// ```rust,no_run
    /// # extern crate nalgebra;
    /// # extern crate theon;
    /// #
    /// use nalgebra::{Point2, Point3};
    /// use plexus::primitive::{Topological, Trigon};
    /// use theon::query::{Plane, Unit};
    /// use theon::space::{Basis, EuclideanSpace};
    ///
    /// type E2 = Point2<f64>;
    /// type E3 = Point3<f64>;
    ///
    /// let trigon = Trigon::embed_into_e3_plane(
    ///     Trigon::from([
    ///         E2::from_xy(-1.0, 0.0),
    ///         E2::from_xy(0.0, 1.0),
    ///         E2::from_xy(1.0, 0.0)
    ///     ]),
    ///     Plane::<E3> {
    ///         origin: EuclideanSpace::origin(),
    ///         normal: Unit::z(),
    ///     },
    /// );
    /// ```
    fn embed_into_e3_plane<P>(ngon: P, plane: Plane<Self::Vertex>) -> Self
    where
        Self::Vertex: EuclideanSpace + FiniteDimensional<N = U3>,
        P: Map<Self::Vertex, Output = Self> + Topological,
        P::Vertex: EuclideanSpace + FiniteDimensional<N = U2> + Push<Output = Self::Vertex>,
        Vector<P::Vertex>: VectorSpace<Scalar = Scalar<Self::Vertex>>,
    {
        Self::embed_into_e3_plane_with(ngon, plane, |position| position)
    }

    fn embed_into_e3_plane_with<P, F>(ngon: P, _: Plane<Position<Self::Vertex>>, f: F) -> Self
    where
        Self::Vertex: AsPosition,
        Position<Self::Vertex>: EuclideanSpace + FiniteDimensional<N = U3>,
        P: Map<Self::Vertex, Output = Self> + Topological,
        P::Vertex:
            EuclideanSpace + FiniteDimensional<N = U2> + Push<Output = Position<Self::Vertex>>,
        Vector<P::Vertex>: VectorSpace<Scalar = Scalar<Position<Self::Vertex>>>,
        F: FnMut(Position<Self::Vertex>) -> Self::Vertex,
    {
        // TODO: Rotate the embedded n-gon into the plane about the origin.
        let _ = Self::embed_into_e3_xy_with(ngon, Zero::zero(), f);
        unimplemented!()
    }

    /// Projects an $n$-gon into a plane.
    ///
    /// The positions in each vertex of the $n$-gon are translated along the
    /// normal of the plane.
    fn project_into_plane(mut self, plane: Plane<Position<Self::Vertex>>) -> Self
    where
        Self::Vertex: AsPosition,
        Position<Self::Vertex>: EuclideanSpace + FiniteDimensional,
        <Position<Self::Vertex> as FiniteDimensional>::N: Cmp<U2, Output = Greater>,
    {
        for vertex in self.as_mut() {
            let line = Line::<Position<Self::Vertex>> {
                origin: *vertex.as_position(),
                direction: plane.normal,
            };
            if let Some(distance) = plane.intersection(&line) {
                let translation = *line.direction.get() * distance;
                vertex.transform(|position| *position + translation);
            }
        }
        self
    }
}

/// Primitive polygonal structure.
///
/// `Polygonal` types form _cycle graphs_ and extend `Topological` types with
/// the additional constraint that all vertices have a degree and valence of
/// two. This requires at least three edges and forbids degenerate structures
/// like monogons.
///
/// These types are topological and do not necessarily represent geometric
/// concepts like polygons in the most strict sense. Polygons are only defined
/// in $\Reals^2$ and cannot have converged or collinear vertices, but
/// `Polygonal` types support this kind of data. However, `Polygonal` types are
/// often used as a geometric approximation of polygons. Moreover, `Polygonal`
/// types often contain non-geometric data, especially index data.
pub trait Polygonal: Topological {
    /// Determines if a polygonal structure is convex.
    ///
    /// This function rejects degenerate polygons, such as polygons with
    /// collinear or converged vertices.
    fn is_convex(&self) -> bool
    where
        Self::Vertex: AsPosition,
        Position<Self::Vertex>: EuclideanSpace + FiniteDimensional<N = U2>,
    {
        let pi = <Scalar<Position<Self::Vertex>> as Real>::PI;
        let mut sum = <Scalar<Position<Self::Vertex>> as Zero>::zero();
        for (t1, t2) in angles(self).perimeter() {
            if (t1 * t2) <= Zero::zero() {
                return false;
            }
            sum = sum + t1;
        }
        (sum / (pi + pi)).round().abs() == One::one()
    }
}

pub trait Rotate {
    fn rotate(self, n: isize) -> Self;
}

pub trait Zip {
    type Output: Topological;

    fn zip(self) -> Self::Output;
}

pub trait MapVertices<T, U>: Sized {
    fn map_vertices<F>(self, f: F) -> InteriorMap<Self, U, F>
    where
        F: FnMut(T) -> U;
}

impl<I, T, U> MapVertices<T, U> for I
where
    I: Iterator,
    I::Item: Map<U> + Topological<Vertex = T>,
    <I::Item as Map<U>>::Output: Topological<Vertex = U>,
{
    fn map_vertices<F>(self, f: F) -> InteriorMap<Self, U, F>
    where
        F: FnMut(T) -> U,
    {
        InteriorMap::new(self, f)
    }
}

pub struct InteriorMap<I, T, F> {
    input: I,
    f: F,
    phantom: PhantomData<T>,
}

impl<I, T, F> InteriorMap<I, T, F> {
    fn new(input: I, f: F) -> Self {
        InteriorMap {
            input,
            f,
            phantom: PhantomData,
        }
    }
}

impl<I, T, F> Iterator for InteriorMap<I, T, F>
where
    I: Iterator,
    F: FnMut(<I::Item as Topological>::Vertex) -> T,
    I::Item: Map<T> + Topological,
    <I::Item as Map<T>>::Output: Topological<Vertex = T>,
{
    type Item = <I::Item as Map<T>>::Output;

    fn next(&mut self) -> Option<Self::Item> {
        self.input.next().map(|topology| topology.map(&mut self.f))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.input.size_hint()
    }
}

/// Monomorphic $n$-gon.
///
/// `NGon` represents a polygonal structure as an array. Each array element
/// represents vertex data in order with adjacent elements being connected by
/// an implicit undirected edge. For example, an `NGon` with three vertices
/// (`NGon<[T; 3]>`) would represent a triangle (trigon). Generally these
/// elements are labeled $A$, $B$, $C$, etc.
///
/// `NGon`s with less than three vertices are a degenerate case. An `NGon` with
/// two vertices (`NGon<[T; 2]>`) is considered a _monogon_ despite common
/// definitions specifying a single vertex. Such an `NGon` is not considered a
/// _digon_, as it represents a single undirected edge rather than two distinct
/// (but collapsed) edges. Single-vertex `NGon`s are unsupported. See the `Edge`
/// type definition.
#[derive(Clone, Copy, Debug)]
pub struct NGon<A>(pub A)
where
    A: Array;

impl<A> NGon<A>
where
    A: Array,
{
    pub fn into_array(self) -> A {
        self.0
    }
}

impl<A> AsRef<[<A as Array>::Item]> for NGon<A>
where
    A: Array,
{
    fn as_ref(&self) -> &[A::Item] {
        self.0.as_slice()
    }
}

impl<A> AsMut<[<A as Array>::Item]> for NGon<A>
where
    A: Array,
{
    fn as_mut(&mut self) -> &mut [A::Item] {
        self.0.as_mut_slice()
    }
}

impl<A> Adjunct for NGon<A>
where
    A: Array,
{
    type Item = A::Item;
}

impl<A> Fold for NGon<A>
where
    Self: Topological + IntoItems,
    A: Array,
{
    fn fold<U, F>(self, mut seed: U, mut f: F) -> U
    where
        F: FnMut(U, Self::Item) -> U,
    {
        for vertex in self.into_vertices() {
            seed = f(seed, vertex);
        }
        seed
    }
}

impl<A> From<A> for NGon<A>
where
    A: Array,
{
    fn from(array: A) -> Self {
        NGon(array)
    }
}

impl<A> FromItems for NGon<A>
where
    A: Array,
{
    fn from_items<I>(items: I) -> Option<Self>
    where
        I: IntoIterator<Item = Self::Item>,
    {
        items
            .into_iter()
            .collect::<ArrayVec<A>>()
            .into_inner()
            .ok()
            .map(NGon)
    }
}

impl<A> Index<usize> for NGon<A>
where
    A: Array + AsRef<[<A as Array>::Item]>,
{
    type Output = A::Item;

    fn index(&self, index: usize) -> &Self::Output {
        self.0.as_ref().index(index)
    }
}

impl<A> IndexMut<usize> for NGon<A>
where
    A: Array + AsRef<[<A as Array>::Item]> + AsMut<[<A as Array>::Item]>,
{
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.0.as_mut().index_mut(index)
    }
}

impl<A> IntoItems for NGon<A>
where
    A: Array,
{
    type Output = ArrayVec<A>;

    fn into_items(self) -> Self::Output {
        ArrayVec::from(self.into_array())
    }
}

impl<A> IntoIterator for NGon<A>
where
    A: Array,
{
    type Item = <A as Array>::Item;
    type IntoIter = <<Self as IntoItems>::Output as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.into_items().into_iter()
    }
}

macro_rules! impl_monomorphic_ngon {
    (length => $n:expr) => (
        impl<T> Monomorphic for NGon<[T; $n]> {}

        impl<T> StaticArity for NGon<[T; $n]> {
            type Static = usize;

            const ARITY: Self::Static = $n;
        }

        impl<T> Polygonal for NGon<[T; $n]> {}
    );
    (lengths => $($n:expr),*$(,)?) => (
        impl<T> Monomorphic for NGon<[T; 2]> {}

        impl<T> StaticArity for NGon<[T; 2]> {
            type Static = usize;

            const ARITY: Self::Static = 1;
        }

        $(impl_monomorphic_ngon!(length => $n);)*
    );
}
impl_monomorphic_ngon!(lengths => 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

macro_rules! impl_zip_ngon {
    (composite => $c:ident, length => $n:expr) => (
        impl_zip_ngon!(composite => $c, length => $n, items => (A, B));
        impl_zip_ngon!(composite => $c, length => $n, items => (A, B, C));
        impl_zip_ngon!(composite => $c, length => $n, items => (A, B, C, D));
        impl_zip_ngon!(composite => $c, length => $n, items => (A, B, C, D, E));
        impl_zip_ngon!(composite => $c, length => $n, items => (A, B, C, D, E, F));
    );
    (composite => $c:ident, length => $n:expr, items => ($($i:ident),*)) => (
        #[allow(non_snake_case)]
        impl<$($i),*> Zip for ($($c<[$i; $n]>),*) {
            type Output = $c<[($($i),*); $n]>;

            fn zip(self) -> Self::Output {
                let ($($i,)*) = self;
                FromItems::from_items(izip!($($i.into_items()),*)).unwrap()
            }
        }
    );
}

// TODO: Some inherent functions are not documented to avoid bloat.
macro_rules! impl_ngon {
    (length => $n:expr) => (
        impl<T> NGon<[T; $n]> {
            #[doc(hidden)]
            pub fn positions(&self) -> NGon<[&Position<T>; $n]>
            where
                T: AsPosition,
            {
                if let Ok(array) = self
                    .as_ref()
                    .iter()
                    .map(|vertex| vertex.as_position())
                    .collect::<ArrayVec<[_; $n]>>()
                    .into_inner()
                {
                    array.into()
                }
                else {
                    panic!()
                }
            }
        }

        impl<'a, T> NGon<[&'a T; $n]> {
            #[doc(hidden)]
            pub fn cloned(self) -> NGon<[T; $n]>
            where
                T: Clone,
            {
                self.map(|vertex| vertex.clone())
            }
        }

        impl<T> Converged for NGon<[T; $n]>
        where
            T: Copy,
        {
            fn converged(item: T) -> Self {
                NGon([item; $n])
            }
        }

        impl<T> DynamicArity for NGon<[T; $n]> {
            type Dynamic = usize;

            fn arity(&self) -> Self::Dynamic {
                <Self as StaticArity>::ARITY
            }
        }

        impl<T, U> Map<U> for NGon<[T; $n]> {
            type Output = NGon<[U; $n]>;

            fn map<F>(self, f: F) -> Self::Output
            where
                F: FnMut(Self::Item) -> U,
            {
                FromItems::from_items(self.into_iter().map(f)).unwrap()
            }
        }

        impl<T> Topological for NGon<[T; $n]> {
            type Vertex = T;

            fn try_from_slice<U>(vertices: U) -> Option<Self>
            where
                Self::Vertex: Copy,
                U: AsRef<[Self::Vertex]>,
            {
                vertices.as_ref().try_into().map(NGon).ok()
            }
        }

        impl_zip_ngon!(composite => NGon, length => $n);

        impl<T, U> ZipMap<U> for NGon<[T; $n]> {
            type Output = NGon<[U; $n]>;

            fn zip_map<F>(self, other: Self, mut f: F) -> Self::Output
            where
                F: FnMut(Self::Item, Self::Item) -> U,
            {
                FromItems::from_items(self.into_iter().zip(other).map(|(a, b)| f(a, b))).unwrap()
            }
        }
    );
    (lengths => $($n:expr),*$(,)?) => (
        $(impl_ngon!(length => $n);)*
    );
}
impl_ngon!(lengths => 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

pub type Edge<T> = NGon<[T; 2]>;

impl<T> Edge<T> {
    pub fn new(a: T, b: T) -> Self {
        NGon([a, b])
    }
}

impl<T> Rotate for Edge<T> {
    fn rotate(self, n: isize) -> Self {
        if n % 2 != 0 {
            let [a, b] = self.into_array();
            Edge::new(b, a)
        }
        else {
            self
        }
    }
}

/// Triangle.
pub type Trigon<T> = NGon<[T; 3]>;

impl<T> Trigon<T> {
    pub fn new(a: T, b: T, c: T) -> Self {
        NGon([a, b, c])
    }

    #[allow(clippy::many_single_char_names)]
    pub fn plane(&self) -> Option<Plane<Position<T>>>
    where
        T: AsPosition,
        Position<T>: EuclideanSpace + FiniteDimensional<N = U3>,
        Vector<Position<T>>: Cross<Output = Vector<Position<T>>>,
    {
        let [a, b, c] = self.positions().cloned().into_array();
        let v = a - b;
        let u = a - c;
        Unit::try_from_inner(v.cross(u))
            .map(move |normal| Plane::<Position<T>> { origin: a, normal })
    }
}

impl<T> Rotate for Trigon<T> {
    fn rotate(self, n: isize) -> Self {
        let n = umod(n, Self::ARITY as isize);
        if n == 1 {
            let [a, b, c] = self.into_array();
            Trigon::new(b, c, a)
        }
        else if n == 2 {
            let [a, b, c] = self.into_array();
            Trigon::new(c, a, b)
        }
        else {
            self
        }
    }
}

/// Quadrilateral.
pub type Tetragon<T> = NGon<[T; 4]>;

impl<T> Tetragon<T> {
    pub fn new(a: T, b: T, c: T, d: T) -> Self {
        NGon([a, b, c, d])
    }
}

impl<T> Rotate for Tetragon<T> {
    #[allow(clippy::many_single_char_names)]
    fn rotate(self, n: isize) -> Self {
        let n = umod(n, Self::ARITY as isize);
        if n == 1 {
            let [a, b, c, d] = self.into_array();
            Tetragon::new(b, c, d, a)
        }
        else if n == 2 {
            let [a, b, c, d] = self.into_array();
            Tetragon::new(c, d, a, b)
        }
        else if n == 3 {
            let [a, b, c, d] = self.into_array();
            Tetragon::new(d, a, b, c)
        }
        else {
            self
        }
    }
}

/// Bounded polymorphic $n$-gon.
///
/// `BoundedPolygon` represents an $n$-gon with at least three edges by
/// enumerating `NGon`s. As such, $n$ is bounded, because the enumeration only
/// supports a limited set of polygons. Only common arities used by generators
/// are provided.
#[derive(Clone, Copy, Debug)]
pub enum BoundedPolygon<T> {
    N3(Trigon<T>),
    N4(Tetragon<T>),
}

impl<T> AsRef<[T]> for BoundedPolygon<T> {
    fn as_ref(&self) -> &[T] {
        match *self {
            BoundedPolygon::N3(ref trigon) => trigon.as_ref(),
            BoundedPolygon::N4(ref tetragon) => tetragon.as_ref(),
        }
    }
}

impl<T> AsMut<[T]> for BoundedPolygon<T> {
    fn as_mut(&mut self) -> &mut [T] {
        match *self {
            BoundedPolygon::N3(ref mut trigon) => trigon.as_mut(),
            BoundedPolygon::N4(ref mut tetragon) => tetragon.as_mut(),
        }
    }
}

impl<T> Adjunct for BoundedPolygon<T> {
    type Item = T;
}

impl<T> DynamicArity for BoundedPolygon<T> {
    type Dynamic = usize;

    fn arity(&self) -> Self::Dynamic {
        match *self {
            BoundedPolygon::N3(..) => Trigon::<T>::ARITY,
            BoundedPolygon::N4(..) => Tetragon::<T>::ARITY,
        }
    }
}

impl<T> Fold for BoundedPolygon<T> {
    fn fold<U, F>(self, mut seed: U, mut f: F) -> U
    where
        F: FnMut(U, Self::Item) -> U,
    {
        for vertex in self.into_vertices() {
            seed = f(seed, vertex);
        }
        seed
    }
}

impl<T> From<[T; 3]> for BoundedPolygon<T> {
    fn from(array: [T; 3]) -> Self {
        BoundedPolygon::N3(array.into())
    }
}

impl<T> From<[T; 4]> for BoundedPolygon<T> {
    fn from(array: [T; 4]) -> Self {
        BoundedPolygon::N4(array.into())
    }
}

impl<T> From<Trigon<T>> for BoundedPolygon<T> {
    fn from(trigon: Trigon<T>) -> Self {
        BoundedPolygon::N3(trigon)
    }
}

impl<T> From<Tetragon<T>> for BoundedPolygon<T> {
    fn from(tetragon: Tetragon<T>) -> Self {
        BoundedPolygon::N4(tetragon)
    }
}

impl<T> Index<usize> for BoundedPolygon<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        match *self {
            BoundedPolygon::N3(ref trigon) => trigon.index(index),
            BoundedPolygon::N4(ref tetragon) => tetragon.index(index),
        }
    }
}

impl<T> IndexMut<usize> for BoundedPolygon<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        match *self {
            BoundedPolygon::N3(ref mut trigon) => trigon.index_mut(index),
            BoundedPolygon::N4(ref mut tetragon) => tetragon.index_mut(index),
        }
    }
}

impl<T> IntoItems for BoundedPolygon<T> {
    type Output = SmallVec<[T; 4]>;

    fn into_items(self) -> Self::Output {
        match self {
            BoundedPolygon::N3(trigon) => trigon.into_items().into_iter().collect(),
            BoundedPolygon::N4(tetragon) => tetragon.into_items().into_iter().collect(),
        }
    }
}

impl<T> IntoIterator for BoundedPolygon<T> {
    type Item = T;
    type IntoIter = <<Self as IntoItems>::Output as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.into_items().into_iter()
    }
}

impl<T, U> Map<U> for BoundedPolygon<T> {
    type Output = BoundedPolygon<U>;

    fn map<F>(self, f: F) -> Self::Output
    where
        F: FnMut(Self::Item) -> U,
    {
        match self {
            BoundedPolygon::N3(trigon) => BoundedPolygon::N3(trigon.map(f)),
            BoundedPolygon::N4(tetragon) => BoundedPolygon::N4(tetragon.map(f)),
        }
    }
}

impl<T> Polygonal for BoundedPolygon<T> {}

impl<T> Rotate for BoundedPolygon<T> {
    fn rotate(self, n: isize) -> Self {
        match self {
            BoundedPolygon::N3(trigon) => BoundedPolygon::N3(trigon.rotate(n)),
            BoundedPolygon::N4(tetragon) => BoundedPolygon::N4(tetragon.rotate(n)),
        }
    }
}

impl<T> StaticArity for BoundedPolygon<T> {
    type Static = (usize, usize);

    const ARITY: Self::Static = (3, 4);
}

impl<T> Topological for BoundedPolygon<T> {
    type Vertex = T;

    fn try_from_slice<U>(vertices: U) -> Option<Self>
    where
        Self::Vertex: Copy,
        U: AsRef<[Self::Vertex]>,
    {
        let vertices = vertices.as_ref();
        match vertices.len() {
            3 => Some(BoundedPolygon::N3(NGon(vertices.try_into().unwrap()))),
            4 => Some(BoundedPolygon::N4(NGon(vertices.try_into().unwrap()))),
            _ => None,
        }
    }
}

/// Unbounded polymorphic $n$-gon.
///
/// `UnboundedPolygon` represents an $n$-gon with three or more edges. Unlike
/// `BoundedPolygon`, there is no limit to the arity of polygons that
/// `UnboundedPolygon` may represent.
///
/// It is not possible to trivially convert an `UnboundedPolygon` into another
/// well-formed topological type such as `NGon`.
#[derive(Clone, Debug)]
pub struct UnboundedPolygon<T>(SmallVec<[T; 4]>);

impl<T> UnboundedPolygon<T> {
    pub fn trigon(a: T, b: T, c: T) -> Self {
        UnboundedPolygon(smallvec![a, b, c])
    }

    pub fn tetragon(a: T, b: T, c: T, d: T) -> Self {
        UnboundedPolygon(smallvec![a, b, c, d])
    }

    pub fn positions(&self) -> UnboundedPolygon<&Position<T>>
    where
        T: AsPosition,
    {
        UnboundedPolygon(self.0.iter().map(|vertex| vertex.as_position()).collect())
    }
}

impl<'a, T> UnboundedPolygon<&'a T>
where
    T: Clone,
{
    pub fn cloned(self) -> UnboundedPolygon<T> {
        self.map(|vertex| vertex.clone())
    }
}

impl<T> Adjunct for UnboundedPolygon<T> {
    type Item = T;
}

impl<T> AsRef<[T]> for UnboundedPolygon<T> {
    fn as_ref(&self) -> &[T] {
        self.0.as_ref()
    }
}

impl<T> AsMut<[T]> for UnboundedPolygon<T> {
    fn as_mut(&mut self) -> &mut [T] {
        self.0.as_mut()
    }
}

impl<T> DynamicArity for UnboundedPolygon<T> {
    type Dynamic = usize;

    fn arity(&self) -> Self::Dynamic {
        self.0.len()
    }
}

impl<T> From<BoundedPolygon<T>> for UnboundedPolygon<T>
where
    T: Clone,
{
    fn from(polygon: BoundedPolygon<T>) -> Self {
        UnboundedPolygon(SmallVec::from(polygon.as_ref()))
    }
}

impl<T> Index<usize> for UnboundedPolygon<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        self.0.index(index)
    }
}

impl<T> IndexMut<usize> for UnboundedPolygon<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.0.index_mut(index)
    }
}

impl<T> IntoItems for UnboundedPolygon<T> {
    type Output = SmallVec<[T; 4]>;

    fn into_items(self) -> Self::Output {
        self.0
    }
}

impl<T> IntoIterator for UnboundedPolygon<T> {
    type IntoIter = <SmallVec<[T; 4]> as IntoIterator>::IntoIter;
    type Item = T;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<T, U> Map<U> for UnboundedPolygon<T> {
    type Output = UnboundedPolygon<U>;

    fn map<F>(self, f: F) -> Self::Output
    where
        F: FnMut(Self::Item) -> U,
    {
        UnboundedPolygon(self.0.into_iter().map(f).collect())
    }
}

impl<T> Polygonal for UnboundedPolygon<T> {}

impl<T> StaticArity for UnboundedPolygon<T> {
    type Static = (usize, Option<usize>);

    const ARITY: Self::Static = (3, None);
}

impl<T> Topological for UnboundedPolygon<T> {
    type Vertex = T;

    fn try_from_slice<U>(vertices: U) -> Option<Self>
    where
        Self::Vertex: Copy,
        U: AsRef<[Self::Vertex]>,
    {
        let vertices = vertices.as_ref();
        if vertices.len() > 2 {
            Some(UnboundedPolygon(SmallVec::from(vertices)))
        }
        else {
            None
        }
    }
}

macro_rules! impl_unbounded_polygon {
    (length => $n:expr) => (
        impl<T> From<NGon<[T; $n]>> for UnboundedPolygon<T>
        where
            T: Clone,
        {
            fn from(ngon: NGon<[T; $n]>) -> Self {
                UnboundedPolygon(SmallVec::from(ngon.as_ref()))
            }
        }
    );
    (lengths => $($n:expr),*$(,)?) => (
        $(impl_unbounded_polygon!(length => $n);)*
    );
}
impl_unbounded_polygon!(lengths => 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

/// Zips the vertices and topologies from multiple iterators into a single
/// iterator.
///
/// This is useful for zipping different attributes of a primitive generator.
/// For example, it can be used to combine position, plane, and normal data data
/// of a cube into a single topology stream.
///
/// # Examples
///
/// Zip position, normal, and plane data for a cube:
///
/// ```rust
/// # extern crate decorum;
/// # extern crate nalgebra;
/// # extern crate num;
/// # extern crate plexus;
/// # extern crate theon;
/// #
/// use decorum::N64;
/// use nalgebra::Point3;
/// use plexus::prelude::*;
/// use plexus::primitive;
/// use plexus::primitive::cube::{Cube, Plane};
/// use plexus::primitive::generate::{Normal, Position};
///
/// type E3 = Point3<N64>;
///
/// let cube = Cube::new();
/// // Zip positions and texture coordinates into each vertex.
/// let polygons = primitive::zip_vertices((
///     cube.polygons::<Position<E3>>(),
///     cube.polygons::<Normal<E3>>(),
///     cube.polygons::<Plane>(),
/// ))
/// .triangulate()
/// .collect::<Vec<_>>();
/// ```
pub fn zip_vertices<T, U>(
    tuple: U,
) -> impl Iterator<Item = <<OuterZip<T> as Iterator>::Item as Zip>::Output>
where
    OuterZip<T>: From<U> + Iterator,
    <OuterZip<T> as Iterator>::Item: Zip,
{
    OuterZip::from(tuple).map(|item| item.zip())
}

/// Gets the relative angles between adjacent line segments in a `Polygonal`
/// with positional data in $\Reals^2$.
///
/// Computes the angle between line segments at each vertex in order. The angles
/// are wrapped into the interval $(-\pi,\pi]$. The sign of each angle specifies
/// the orientation of adjacent line segments. Given a square, exactly four
/// angles of $\plusmn\frac{\pi}{2}$ will be returned, with the sign depending
/// on the winding of the square.
///
/// Adjacent vertices with the same position are ignored, as there is no
/// meaningful line segment between such vertices. Because of this, it is
/// possible that the number of angles returned by this function disagrees with
/// the arity of the polygon.
fn angles<'a, P>(polygon: &'a P) -> impl 'a + Clone + Iterator<Item = Scalar<Position<P::Vertex>>>
where
    P: Polygonal,
    P::Vertex: AsPosition,
    Position<P::Vertex>: EuclideanSpace + FiniteDimensional<N = U2>,
{
    polygon
        .as_ref()
        .iter()
        .map(|vertex| vertex.as_position())
        .perimeter()
        .map(|(a, b)| *b - *a)
        .filter(|vector| !vector.is_zero()) // Reject like positions.
        .map(|vector| vector.into_xy())
        .map(|(x, y)| Real::atan2(x, y)) // Absolute angle.
        .perimeter()
        .map(|(t1, t2)| t2 - t1) // Relative angle (between segments).
        .map(|t| {
            // Wrap the angle into the interval `(-pi, pi]`.
            let pi = <Scalar<Position<P::Vertex>> as Real>::PI;
            if t <= -pi {
                t + (pi + pi)
            }
            else if t > pi {
                t - (pi + pi)
            }
            else {
                t
            }
        })
}

fn umod<T>(n: T, m: T) -> T
where
    T: Copy + Integer,
{
    ((n % m) + m) % m
}

#[cfg(test)]
mod tests {
    use nalgebra::Point2;
    use theon::adjunct::Converged;
    use theon::space::EuclideanSpace;

    use crate::primitive::{NGon, Polygonal, Tetragon, Trigon};

    type E2 = Point2<f64>;

    #[test]
    fn convexity() {
        // Convex triangle.
        let trigon = Trigon::new(
            E2::from_xy(0.0, 1.0),
            E2::from_xy(1.0, 0.0),
            E2::from_xy(-1.0, 0.0),
        );
        assert!(trigon.is_convex());

        // Convex quadrilateral.
        let tetragon = Tetragon::new(
            E2::from_xy(1.0, 1.0),
            E2::from_xy(1.0, -1.0),
            E2::from_xy(-1.0, -1.0),
            E2::from_xy(-1.0, 1.0),
        );
        assert!(tetragon.is_convex());

        // Degenerate (collinear) triangle. Not convex.
        let trigon = Trigon::new(
            E2::from_xy(0.0, 0.0),
            E2::from_xy(0.0, 1.0),
            E2::from_xy(0.0, 2.0),
        );
        assert!(!trigon.is_convex());

        // Degenerate (converged) triangle. Not convex.
        let trigon = Trigon::converged(E2::origin());
        assert!(!trigon.is_convex());

        // Self-intersecting pentagon. Not convex.
        let pentagon = NGon::from([
            E2::from_xy(1.0, 1.0),
            E2::from_xy(1.0, -1.0),
            E2::from_xy(-1.0, -1.0),
            E2::from_xy(-1.0, 1.0),
            E2::from_xy(0.0, -2.0), // Self-intersecting vertex.
        ]);
        assert!(!pentagon.is_convex());
    }
}