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
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
//! Half-edge graph representation of meshes.
//!
//! This module provides a flexible representation of meshes as a [half-edge
//! graph][1]. _Half-edges_ and _edges_ are referred to as _arcs_ and _edges_,
//! respectively. Meshes can store arbitrary geometric data associated with any
//! topological structure (vertices, arcs, edges, and faces).
//!
//! Graph APIs expose geometric operations if vertex geometry exposes positional
//! data via the `AsPosition` trait.
//!
//! See the [user guide][2] for more details and examples.
//!
//! # Representation
//!
//! A `MeshGraph` is composed of four primary entities: _vertices_, _arcs_,
//! _edges_, and _faces_. The figure below summarizes the connectivity in a
//! `MeshGraph`.
//!
//! ![Half-Edge Graph Figure](https://plexus.rs/img/heg.svg)
//!
//! Arcs are directed and connect vertices. An arc that is directed toward a
//! vertex $A$ is an _incoming arc_ with respect to $A$. Similarly, an arc
//! directed away from such a vertex is an _outgoing arc_. Every vertex is
//! associated with exactly one _leading arc_, which is always an outgoing arc.
//! The vertex toward which an arc is directed is the arc's _destination vertex_
//! and the other is its _source vertex_.
//!
//! Every arc is paired with an _opposite arc_ with an opposing direction.
//! Given an arc from a vertex $A$ to a vertex $B$, that arc will have an
//! opposite arc from $B$ to $A$. Such arcs are notated $\overrightarrow{AB}$
//! and $\overrightarrow{BA}$. Together, these arcs form an _edge_, which is not
//! directed. An edge and its two arcs are together called a _composite edge_.
//!
//! Arcs are connected to their adjacent arcs, known as _next_ and _previous
//! arcs_. A traversal along a series of arcs is a _path_. The path formed by
//! traversing from an arc to its next arc and so on is a _ring_. When a face is
//! present within an ring, the arcs will refer to that face and the face will
//! refer to exactly one of the arcs in the ring (this is the leading arc of the
//! face). An arc with no associated face is known as a _boundary arc_.  If
//! either of an edge's arcs is a boundary arc, then that edge is a _boundary
//! edge_.
//!
//! A path that terminates is _open_ and a path that forms a loop is _closed_.
//! Rings are always closed. Paths may be notated using _sequence_ or _set
//! notation_ and both forms are used to describe rings and faces.
//!
//! Sequence notation is formed from the ordered sequence of vertices that a
//! path traverses, including the source vertex of the first arc and the
//! destination vertex of the last arc. Set notation is similar, but is
//! implicitly closed and only includes the ordered and unique set of vertices
//! traversed by the path. An open path over vertices $A$, $B$, and $C$ is
//! notated as a sequence $\overrightarrow{(A,B,C)}$. A closed path over
//! vertices $A$, $B$, and $C$ includes the arc $\overrightarrow{CA}$ and is
//! notated as a sequence $\overrightarrow{(A,B,C,A)}$ or a set
//! $\overrightarrow{\\{A,B,C\\}}$.
//!
//! Together with vertices and faces, the connectivity of arcs allows for
//! effecient traversals of topology. For example, it becomes trivial to find
//! adjacent topologies, such as the faces that share a given vertex or the
//! adjacent faces of a given face.
//!
//! `MeshGraph`s store entities using associative storage and keys that are
//! exposed as strongly typed and opaque values. These keys are used to refer to
//! any and all entities in a graph.
//!
//! Note that paths and rings are **not** entities and are not explicitly stored
//! in graphs.
//!
//! # Topological Views
//!
//! `MeshGraph`s expose _views_ over their entities (vertices, arcs, edges, and
//! faces). Views bind a reference to storage with a key into that storage for
//! an entity. They behave similarly to references and expose their underlying
//! entities via `Deref`.
//!
//! Views provide the primary API for interacting with a `MeshGraph`'s topology
//! and geometry. There are three types of views summarized below:
//!
//! | Type      | Traversal | Exclusive | Geometry  | Topology  |
//! |-----------|-----------|-----------|-----------|-----------|
//! | Immutable | Yes       | No        | Immutable | Immutable |
//! | Mutable   | Yes       | Yes       | Mutable   | Mutable   |
//! | Orphan    | No        | No        | Mutable   | N/A       |
//!
//! _Immutable_ and _mutable views_ behave similarly to references: immutable
//! views cannot mutate a graph and are not exclusive while mutable views may
//! mutate both the geometry and topology of a graph but are exclusive.
//!
//! _Orphan views_ (simply referred to as _orphans_ in APIs) are similar to
//! mutable views in that they may mutate the geometry of a graph, but they
//! cannot access storage for other entities (the topology of a graph). Because
//! they cannot access other vertices, arcs, etc., orphan views cannot traverse
//! a graph in any way. These views are most useful for modifying the geometry
//! of a graph and, unlike mutable views, they are not exclusive.
//!
//! Views perform _interior reborrows_, which reborrow the reference to storage
//! to construct other views. Immutable reborrows can be performed explicitly using
//! the conversions described below:
//!
//! | Function   | Receiver    | Borrow | Output    |
//! |------------|-------------|--------|-----------|
//! | `to_ref`   | `&self`     | `&_`   | Immutable |
//! | `into_ref` | `self`      | `&*_`  | Immutable |
//!
//! It is not possible to explicitly perform a mutable interior reborrow. Such a
//! reborrow could invalidate the source view by performing a topological
//! mutation. Mutable reborrows are performed beneath safe APIs, such as those
//! exposing iterators over orphan views.
//!
//! Note that `into_ref` is analogous to an immutable reborrow of a mutable
//! `&mut` Rust reference. Despite the downgraded reference, the mutable source
//! reference remains and so it is not possible to obtain an additional mutable
//! view after using `into_ref` until the originating view is dropped.
//!
//! # Examples
//!
//! Generating a graph from a $uv$-sphere:
//!
//! ```rust
//! # extern crate decorum;
//! # extern crate nalgebra;
//! # extern crate plexus;
//! #
//! use decorum::N64;
//! use nalgebra::Point3;
//! use plexus::graph::MeshGraph;
//! use plexus::prelude::*;
//! use plexus::primitive::generate::Position;
//! use plexus::primitive::sphere::UvSphere;
//!
//! let mut graph = UvSphere::default()
//!     .polygons::<Position<Point3<N64>>>()
//!     .collect::<MeshGraph<Point3<N64>>>();
//! ```
//!
//! Extruding a face in a graph:
//!
//! ```rust
//! # extern crate decorum;
//! # extern crate nalgebra;
//! # extern crate plexus;
//! #
//! use decorum::N64;
//! use nalgebra::Point3;
//! use plexus::graph::MeshGraph;
//! use plexus::prelude::*;
//! use plexus::primitive::generate::Position;
//! use plexus::primitive::sphere::UvSphere;
//!
//! let mut graph = UvSphere::new(8, 8)
//!     .polygons::<Position<Point3<N64>>>()
//!     .collect::<MeshGraph<Point3<N64>>>();
//! // Get the key of the first face and then extrude it.
//! let key = graph.faces().nth(0).unwrap().key();
//! let face = graph.face_mut(key).unwrap().extrude_with_offset(1.0);
//! ```
//!
//! Traversing and circulating over a graph:
//!
//! ```rust
//! # extern crate nalgebra;
//! # extern crate plexus;
//! #
//! use nalgebra::Point2;
//! use plexus::graph::MeshGraph;
//! use plexus::prelude::*;
//! use plexus::primitive::Tetragon;
//!
//! let mut graph = MeshGraph::<Point2<f64>>::from_raw_buffers(
//!     vec![Tetragon::new(0u32, 1, 2, 3)],
//!     vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
//! )
//! .unwrap();
//! graph.triangulate();
//!
//! // Traverse an arc and use a circulator to get the faces of a nearby vertex.
//! let key = graph.arcs().nth(0).unwrap().key();
//! let mut vertex = graph
//!     .arc_mut(key)
//!     .unwrap()
//!     .into_opposite_arc()
//!     .into_next_arc()
//!     .into_destination_vertex();
//! for mut face in vertex.adjacent_face_orphans() {
//!     // `face.geometry` is mutable here.
//! }
//! ```
//!
//! [1]: https://en.wikipedia.org/wiki/doubly_connected_edge_list
//! [2]: https://plexus.rs/user-guide/graphs

mod builder;
mod core;
mod edge;
mod face;
mod geometry;
mod mutation;
mod path;
mod trace;
mod vertex;

use decorum::cmp::IntrinsicOrd;
use decorum::N64;
use itertools::Itertools;
use num::{Integer, NumCast, ToPrimitive, Unsigned};
use smallvec::SmallVec;
use std::borrow::Borrow;
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::FromIterator;
use std::vec;
use theon::adjunct::{FromItems, Map};
use theon::query::Aabb;
use theon::space::{EuclideanSpace, Scalar};
use theon::AsPosition;
use thiserror::Error;
use typenum::{self, NonZero};

use crate::buffer::{BufferError, FromRawBuffers, FromRawBuffersWithArity, MeshBuffer};
use crate::builder::{Buildable, FacetBuilder, MeshBuilder, SurfaceBuilder};
use crate::encoding::{FaceDecoder, FromEncoding, VertexDecoder};
use crate::entity::storage::{AsStorage, AsStorageMut, AsStorageOf, Fuse, OpaqueKey, Storage};
use crate::entity::view::{Bind, Orphan, View};
use crate::graph::builder::GraphBuilder;
use crate::graph::core::{Core, OwnedCore};
use crate::graph::geometry::Geometric;
use crate::graph::mutation::face::FaceInsertCache;
use crate::graph::mutation::{Consistent, Mutation};
use crate::index::{Flat, FromIndexer, Grouping, HashIndexer, IndexBuffer, IndexVertices, Indexer};
use crate::primitive::decompose::IntoVertices;
use crate::primitive::{IntoPolygons, Polygonal, UnboundedPolygon};
use crate::transact::Transact;
use crate::{DynamicArity, FromGeometry, IntoGeometry, MeshArity, StaticArity};

pub use crate::entity::dijkstra::Metric;
pub use crate::entity::view::{ClosedView, Rebind};
pub use crate::graph::edge::{
    Arc, ArcKey, ArcOrphan, ArcView, Edge, EdgeKey, EdgeOrphan, EdgeView, ToArc,
};
pub use crate::graph::face::{Face, FaceKey, FaceOrphan, FaceView, Ring, ToRing};
pub use crate::graph::geometry::{
    ArcNormal, EdgeMidpoint, FaceCentroid, FaceNormal, FacePlane, GraphGeometry, VertexCentroid,
    VertexNormal, VertexPosition,
};
pub use crate::graph::path::Path;
pub use crate::graph::vertex::{Vertex, VertexKey, VertexOrphan, VertexView};

pub use Selector::ByIndex;
pub use Selector::ByKey;

#[derive(Debug, Error, PartialEq)]
pub enum GraphError {
    #[error("required topology not found")]
    TopologyNotFound,
    #[error("conflicting topology found")]
    TopologyConflict,
    #[error("topology malformed")]
    TopologyMalformed,
    #[error("arity is non-polygonal")]
    ArityNonPolygonal,
    #[error("conflicting arity; expected {expected}, but got {actual}")]
    ArityConflict { expected: usize, actual: usize },
    #[error("arity is non-uniform")]
    ArityNonUniform,
    #[error("geometric operation failed")]
    Geometry,
    #[error("encoding operation failed")]
    Encoding,
}

// TODO: How should buffer errors be handled? Is this sufficient?
impl From<BufferError> for GraphError {
    fn from(error: BufferError) -> Self {
        match error {
            BufferError::ArityConflict { expected, actual } => {
                GraphError::ArityConflict { expected, actual }
            }
            _ => GraphError::Encoding,
        }
    }
}

trait OptionExt<T> {
    fn expect_consistent(self) -> T;
}

impl<T> OptionExt<T> for Option<T> {
    fn expect_consistent(self) -> T {
        self.expect("internal error: graph consistency violated")
    }
}

trait ResultExt<T, E> {
    fn expect_consistent(self) -> T
    where
        E: Debug;
}

impl<T, E> ResultExt<T, E> for Result<T, E> {
    fn expect_consistent(self) -> T
    where
        E: Debug,
    {
        self.expect("internal error: graph consistency violated")
    }
}

/// Entity selector.
///
/// Identifies an entity by key or index. Keys behave as an absolute selector
/// and uniquely identify a single entity within a graph. Indices behave as a
/// relative selector and identify an entity relative to some other entity.
/// `Selector` is used by operations that support both of these selection
/// mechanisms.
///
/// An index is typically used to select an adjacent entity or contained (and
/// ordered) entity, such as an adjacent face.
///
/// # Examples
///
/// Splitting a face by index (of its contained vertices):
///
/// ```rust
/// # extern crate decorum;
/// # extern crate nalgebra;
/// # extern crate plexus;
/// #
/// use decorum::N64;
/// use nalgebra::Point3;
/// use plexus::graph::MeshGraph;
/// use plexus::prelude::*;
/// use plexus::primitive::cube::Cube;
/// use plexus::primitive::generate::Position;
///
/// let mut graph = Cube::new()
///     .polygons::<Position<Point3<N64>>>()
///     .collect::<MeshGraph<Point3<N64>>>();
/// let key = graph.faces().nth(0).unwrap().key();
/// graph
///     .face_mut(key)
///     .unwrap()
///     .split(ByIndex(0), ByIndex(2))
///     .unwrap();
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Selector<K> {
    ByKey(K),
    ByIndex(usize),
}

impl<K> Selector<K> {
    /// Gets the selector's key or passes its index to a function to resolve
    /// the key.
    pub fn key_or_else<E, F>(self, f: F) -> Result<K, GraphError>
    where
        E: Into<GraphError>,
        F: Fn(usize) -> Result<K, E>,
    {
        match self {
            Selector::ByKey(key) => Ok(key),
            Selector::ByIndex(index) => f(index).map_err(|error| error.into()),
        }
    }

    /// Gets the selector's index or passes its key to a function to resolve
    /// the index.
    pub fn index_or_else<E, F>(self, f: F) -> Result<usize, GraphError>
    where
        E: Into<GraphError>,
        F: Fn(K) -> Result<usize, E>,
    {
        match self {
            Selector::ByKey(key) => f(key).map_err(|error| error.into()),
            Selector::ByIndex(index) => Ok(index),
        }
    }
}

impl<K> From<K> for Selector<K>
where
    K: OpaqueKey,
{
    fn from(key: K) -> Self {
        Selector::ByKey(key)
    }
}

impl<K> From<usize> for Selector<K> {
    fn from(index: usize) -> Self {
        Selector::ByIndex(index)
    }
}

/// Half-edge graph representation of a mesh.
///
/// Provides topological information using four entities: vertices, arcs, edges,
/// and faces.  An arc is directed from one vertex to another, with an opposing
/// arc joining the vertices in the other direction.
///
/// `MeshGraph`s expose topological views, which can be used to traverse and
/// manipulate topology and geometry in the graph.
///
/// See the module documentation for more details.
pub struct MeshGraph<G = (N64, N64, N64)>
where
    G: GraphGeometry,
{
    core: OwnedCore<G>,
}

impl<G> MeshGraph<G>
where
    G: GraphGeometry,
{
    /// Creates an empty `MeshGraph`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use plexus::graph::MeshGraph;
    ///
    /// let mut graph = MeshGraph::<()>::new();
    /// ```
    pub fn new() -> Self {
        MeshGraph::from(
            Core::empty()
                .fuse(Storage::<Vertex<G>>::new())
                .fuse(Storage::<Arc<G>>::new())
                .fuse(Storage::<Edge<G>>::new())
                .fuse(Storage::<Face<G>>::new()),
        )
    }

    /// Gets the number of vertices in the graph.
    pub fn vertex_count(&self) -> usize {
        self.as_storage_of::<Vertex<_>>().len()
    }

    /// Gets an immutable view of the vertex with the given key.
    pub fn vertex(&self, key: VertexKey) -> Option<VertexView<&Self>> {
        Bind::bind(self, key)
    }

    /// Gets a mutable view of the vertex with the given key.
    pub fn vertex_mut(&mut self, key: VertexKey) -> Option<VertexView<&mut Self>> {
        Bind::bind(self, key)
    }

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the vertices in the graph.
    pub fn vertices(&self) -> impl ExactSizeIterator<Item = VertexView<&Self>> {
        self.as_storage_of::<Vertex<_>>()
            .keys()
            .map(move |key| View::bind_unchecked(self, key))
            .map(From::from)
    }

    /// Gets an iterator of orphan views over the vertices in the graph.
    pub fn vertex_orphans(&mut self) -> impl ExactSizeIterator<Item = VertexOrphan<G>> {
        self.as_storage_mut_of::<Vertex<_>>()
            .iter_mut()
            .map(|(key, entity)| Orphan::bind_unchecked(entity, key))
            .map(From::from)
    }

    /// Gets the number of arcs in the graph.
    pub fn arc_count(&self) -> usize {
        self.as_storage_of::<Arc<_>>().len()
    }

    /// Gets an immutable view of the arc with the given key.
    pub fn arc(&self, key: ArcKey) -> Option<ArcView<&Self>> {
        Bind::bind(self, key)
    }

    /// Gets a mutable view of the arc with the given key.
    pub fn arc_mut(&mut self, key: ArcKey) -> Option<ArcView<&mut Self>> {
        Bind::bind(self, key)
    }

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the arcs in the graph.
    pub fn arcs(&self) -> impl ExactSizeIterator<Item = ArcView<&Self>> {
        self.as_storage_of::<Arc<_>>()
            .keys()
            .map(move |key| View::bind_unchecked(self, key))
            .map(From::from)
    }

    /// Gets an iterator of orphan views over the arcs in the graph.
    pub fn arc_orphans(&mut self) -> impl ExactSizeIterator<Item = ArcOrphan<G>> {
        self.as_storage_mut_of::<Arc<_>>()
            .iter_mut()
            .map(|(key, entity)| Orphan::bind_unchecked(entity, key))
            .map(From::from)
    }

    /// Gets the number of edges in the graph.
    pub fn edge_count(&self) -> usize {
        self.as_storage_of::<Edge<_>>().len()
    }

    /// Gets an immutable view of the edge with the given key.
    pub fn edge(&self, key: EdgeKey) -> Option<EdgeView<&Self>> {
        Bind::bind(self, key)
    }

    /// Gets a mutable view of the edge with the given key.
    pub fn edge_mut(&mut self, key: EdgeKey) -> Option<EdgeView<&mut Self>> {
        Bind::bind(self, key)
    }

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the edges in the graph.
    pub fn edges(&self) -> impl ExactSizeIterator<Item = EdgeView<&Self>> {
        self.as_storage_of::<Edge<_>>()
            .keys()
            .map(move |key| View::bind_unchecked(self, key))
            .map(From::from)
    }

    /// Gets an iterator of orphan views over the edges in the graph.
    pub fn edge_orphans(&mut self) -> impl ExactSizeIterator<Item = EdgeOrphan<G>> {
        self.as_storage_mut_of::<Edge<_>>()
            .iter_mut()
            .map(|(key, entity)| Orphan::bind_unchecked(entity, key))
            .map(From::from)
    }

    /// Gets the number of faces in the graph.
    pub fn face_count(&self) -> usize {
        self.as_storage_of::<Face<_>>().len()
    }

    /// Gets an immutable view of the face with the given key.
    pub fn face(&self, key: FaceKey) -> Option<FaceView<&Self>> {
        Bind::bind(self, key)
    }

    /// Gets a mutable view of the face with the given key.
    pub fn face_mut(&mut self, key: FaceKey) -> Option<FaceView<&mut Self>> {
        Bind::bind(self, key)
    }

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the faces in the graph.
    pub fn faces(&self) -> impl ExactSizeIterator<Item = FaceView<&Self>> {
        self.as_storage_of::<Face<_>>()
            .keys()
            .map(move |key| View::bind_unchecked(self, key))
            .map(From::from)
    }

    /// Gets an iterator of orphan views over the faces in the graph.
    pub fn face_orphans(&mut self) -> impl ExactSizeIterator<Item = FaceOrphan<G>> {
        self.as_storage_mut_of::<Face<_>>()
            .iter_mut()
            .map(|(key, entity)| Orphan::bind_unchecked(entity, key))
            .map(From::from)
    }

    pub fn path<I>(&self, keys: I) -> Result<Path<&Self>, GraphError>
    where
        I: IntoIterator,
        I::Item: Borrow<VertexKey>,
    {
        Path::bind(self, keys)
    }

    pub fn path_mut<I>(&mut self, keys: I) -> Result<Path<&mut Self>, GraphError>
    where
        I: IntoIterator,
        I::Item: Borrow<VertexKey>,
    {
        Path::bind(self, keys)
    }

    /// Gets an axis-aligned bounding box that encloses the graph.
    pub fn aabb(&self) -> Aabb<VertexPosition<G>>
    where
        G::Vertex: AsPosition,
        VertexPosition<G>: EuclideanSpace,
        Scalar<VertexPosition<G>>: IntrinsicOrd,
    {
        Aabb::from_points(self.vertices().map(|vertex| *vertex.geometry.as_position()))
    }

    // TODO: This triangulation does not consider geometry and exhibits some
    //       bad behavior in certain situations. Triangulation needs to be
    //       reworked and may need to expose a bit more complexity. A geometric
    //       triangulation algorithm would be a useful addition and could
    //       detect concave faces and provide more optimal splits. See comments
    //       on `FaceView::triangulate`.
    /// Triangulates the graph, tessellating all faces into triangles.
    pub fn triangulate(&mut self) {
        // TODO: This implementation is a bit fragile and depends on the
        //       semantics of `TopologyConflict` in this context. It also panics
        //       if no valid split is found given all offsets or if some other
        //       error is encountered while splitting. Can this code assume that
        //       any of these conditions aren't possible? This should work a bit
        //       better than using `FaceView::triangulate` until triangulation
        //       is reworked.
        let keys = self.as_storage_of::<Face<_>>().keys().collect::<Vec<_>>();
        for key in keys {
            let mut face = self.face_mut(key).unwrap();
            let mut offset = 0;
            while face.arity() > 3 {
                match face.split(ByIndex(offset), ByIndex(offset + 2)) {
                    Ok(next) => {
                        face = next.into_face().expect_consistent();
                        offset = 0;
                    }
                    Err(GraphError::TopologyConflict) => {
                        // Retry if the split intersected another face. See
                        // `FaceSplitCache::from_face`.
                        face = self.face_mut(key).unwrap();
                        offset += 1;
                        if offset >= face.arity() {
                            panic!()
                        }
                    }
                    _ => panic!(),
                }
            }
        }
    }

    /// Smooths the positions of vertices in the graph.
    ///
    /// Each position is translated by its offset from its centroid scaled by
    /// the given factor. The centroid of a vertex position is the mean of the
    /// positions of its adjacent vertices. That is, given a factor $k$ and a
    /// vertex with position $P$ and centroid $Q$, its position becomes
    /// $P+k(Q-P)$.
    pub fn smooth<T>(&mut self, factor: T)
    where
        T: Into<Scalar<VertexPosition<G>>>,
        G: VertexCentroid,
        G::Vertex: AsPosition,
        VertexPosition<G>: EuclideanSpace,
    {
        let factor = factor.into();
        let mut positions = HashMap::with_capacity(self.vertex_count());
        for vertex in self.vertices() {
            let position = *vertex.position();
            positions.insert(
                vertex.key(),
                position + ((vertex.centroid() - position) * factor),
            );
        }
        for mut vertex in self.vertex_orphans() {
            *vertex.geometry.as_position_mut() = positions.remove(&vertex.key()).unwrap();
        }
    }

    // This API is a bit unusual, but allows a view-like path to borrow a graph
    // and remain consistent. It also (hopefully) makes it more clear that the
    // _graph_ is split, not the path.
    //
    //   let mut path = graph.arc_mut(...).unwrap().into_path();
    //   path.push(...).unwrap();
    //   ...
    //   let (a, b) = MeshGraph::split_at_path(path).unwrap();
    /// Splits the graph along a path.
    ///
    /// Splitting a graph creates boundaries along the given path and copies any
    /// necessary vertex, arc, and edge geometry.
    ///
    /// If the path bisects the graph, then splitting will result in disjointed
    /// sub-graphs.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point2;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::Trigon;
    ///
    /// type E2 = Point2<f64>;
    ///
    /// // Create a graph from two triangles.
    /// let mut graph = MeshGraph::<E2>::from_raw_buffers(
    ///     vec![Trigon::new(0usize, 1, 2), Trigon::new(2, 1, 3)],
    ///     vec![
    ///         (-1.0, 0.0),
    ///         (0.0, -1.0),
    ///         (0.0, 1.0),
    ///         (1.0, 0.0),
    ///     ],
    /// )
    /// .unwrap();
    ///
    /// // Find the shared edge that bisects the triangles and then construct a path
    /// // along the edge and split the graph.
    /// let key = graph
    ///     .edges()
    ///     .find(|edge| !edge.is_boundary_edge())
    ///     .map(|edge| edge.into_arc().key())
    ///     .unwrap();
    /// let mut path = graph.arc_mut(key).unwrap().into_path();
    /// MeshGraph::split_at_path(path).unwrap();
    /// ```
    pub fn split_at_path(path: Path<&mut Self>) -> Result<(), GraphError> {
        let _ = path;
        unimplemented!()
    }

    /// Gets an iterator over a vertex within each disjoint subgraph.
    ///
    /// Traverses the graph and returns an arbitrary vertex within each
    /// _disjoint subgraph_. A subgraph is _disjoint_ if it cannot be reached
    /// from all other topology in the graph.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point2;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::Trigon;
    ///
    /// type E2 = Point2<f64>;
    ///
    /// // Create a graph from two disjoint triangles.
    /// let graph = MeshGraph::<E2>::from_raw_buffers(
    ///     vec![Trigon::new(0u32, 1, 2), Trigon::new(3, 4, 5)],
    ///     vec![
    ///         (-2.0, 0.0),
    ///         (-1.0, 0.0),
    ///         (-1.0, 1.0),
    ///         (1.0, 0.0),
    ///         (2.0, 0.0),
    ///         (1.0, 1.0),
    ///     ],
    /// )
    /// .unwrap();
    ///
    /// // A vertex from each disjoint triangle is returned.
    /// for vertex in graph.disjoint_subgraph_vertices() {
    ///     // ...
    /// }
    /// ```
    pub fn disjoint_subgraph_vertices(&self) -> impl ExactSizeIterator<Item = VertexView<&Self>> {
        let keys = self
            .as_storage_of::<Vertex<_>>()
            .keys()
            .collect::<HashSet<_>>();
        let mut subkeys = HashSet::with_capacity(self.vertex_count());
        let mut vertices = SmallVec::<[VertexView<_>; 4]>::new();
        while let Some(key) = keys.difference(&subkeys).nth(0) {
            let vertex = VertexView::from(View::bind_unchecked(self, *key));
            vertices.push(vertex);
            subkeys.extend(vertex.traverse_by_depth().map(|vertex| vertex.key()));
        }
        vertices.into_iter()
    }

    /// Moves disjoint sub-graphs into separate graphs.
    pub fn into_disjoint_subgraphs(self) -> Vec<Self> {
        unimplemented!()
    }

    /// Creates a `Buildable` mesh data structure from the graph.
    ///
    /// The output is created from each unique vertex in the graph. No face
    /// geometry is used, and the `Facet` type is always `()`.
    ///
    /// # Examples
    ///
    /// Creating a `MeshBuffer` from a graph used to modify a cube:
    ///
    /// ```rust
    /// # extern crate decorum;
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use decorum::N64;
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBufferN;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    ///
    /// type E3 = Point3<N64>;
    ///
    /// let mut graph = Cube::new()
    ///     .polygons::<Position<E3>>()
    ///     .collect::<MeshGraph<E3>>();
    /// let key = graph.faces().nth(0).unwrap().key();
    /// graph.face_mut(key).unwrap().extrude_with_offset(1.0);
    ///
    /// let buffer = graph.to_mesh_by_vertex::<MeshBufferN<usize, E3>>().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the graph does not have constant arity that is
    /// compatible with the index buffer. Typically, a graph is triangulated
    /// before being converted to a buffer.
    pub fn to_mesh_by_vertex<B>(&self) -> Result<B, B::Error>
    where
        B: Buildable<Facet = ()>,
        B::Vertex: FromGeometry<G::Vertex>,
    {
        self.to_mesh_by_vertex_with(|vertex| vertex.geometry.into_geometry())
    }

    /// Creates a `Buildable` mesh data structure from the graph.
    ///
    /// The output is created from each unique vertex in the graph, which is
    /// converted into the output geometry by the given function. No face
    /// geometry is used, and the `Facet` type is always `()`.
    ///
    /// # Errors
    ///
    /// Returns an error if the vertex geometry cannot be inserted into the
    /// output, there are arity conflicts, or the output does not support
    /// topology found in the graph.
    pub fn to_mesh_by_vertex_with<B, T, F>(&self, mut f: F) -> Result<B, B::Error>
    where
        B: Buildable<Vertex = T, Facet = ()>,
        F: FnMut(VertexView<&Self>) -> T,
    {
        let mut builder = B::builder();
        builder.surface_with(|builder| {
            let mut keys = HashMap::with_capacity(self.vertex_count());
            for vertex in self.vertices() {
                keys.insert(vertex.key(), builder.insert_vertex(f(vertex))?);
            }
            builder.facets_with(|builder| {
                for face in self.faces() {
                    let indices = face
                        .adjacent_vertices()
                        .map(|vertex| keys[&vertex.key()])
                        .collect::<SmallVec<[_; 8]>>();
                    builder.insert_facet(indices.as_slice(), ())?;
                }
                Ok(())
            })
        })?;
        builder.build()
    }

    /// Creates a `Buildable` mesh data structure from the graph.
    ///
    /// The output is created from each face in the graph. For each face, the
    /// face geometry and associated vertex geometry is inserted into the buffer
    /// via `FromGeometry`. This means that a vertex is inserted for each of its
    /// adjacent faces.
    ///
    /// # Errors
    ///
    /// Returns an error if the vertex geometry cannot be inserted into the
    /// output, there are arity conflicts, or the output does not support
    /// topology found in the graph.
    pub fn to_mesh_by_face<B>(&self) -> Result<B, B::Error>
    where
        B: Buildable,
        B::Vertex: FromGeometry<G::Vertex>,
        B::Facet: FromGeometry<G::Face>,
    {
        self.to_mesh_by_face_with(|_, vertex| vertex.geometry.into_geometry())
    }

    /// Creates a `Buildable` mesh data structure from the graph.
    ///
    /// The output is created from each face in the graph. The given function is
    /// called for each vertex of each face and converts the vertex geometry
    /// into the output geometry. This means that a vertex is inserted for each
    /// of its adjacent faces. The face geometry is inserted into the output via
    /// `FromGeometry`.
    ///
    /// # Examples
    ///
    /// Creating a `MeshBuffer` from a graph used to compute normals:
    ///
    /// ```rust
    /// # extern crate decorum;
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// # extern crate theon;
    /// #
    /// use decorum::N64;
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBuffer;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    /// use plexus::primitive::BoundedPolygon;
    /// use theon::space::Vector;
    ///
    /// type E3 = Point3<N64>;
    ///
    /// pub struct Vertex {
    ///     pub position: E3,
    ///     pub normal: Vector<E3>,
    /// }
    ///
    /// let graph = Cube::new()
    ///     .polygons::<Position<E3>>()
    ///     .collect::<MeshGraph<E3>>();
    ///
    /// let buffer: MeshBuffer<BoundedPolygon<usize>, _> = graph
    ///     .to_mesh_by_face_with(|face, vertex| Vertex {
    ///         position: *vertex.position(),
    ///         normal: face.normal().unwrap(),
    ///     })
    ///     .unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the vertex geometry cannot be inserted into the
    /// output, there are arity conflicts, or the output does not support
    /// topology found in the graph.
    pub fn to_mesh_by_face_with<B, T, F>(&self, mut f: F) -> Result<B, B::Error>
    where
        B: Buildable<Vertex = T>,
        B::Facet: FromGeometry<G::Face>,
        F: FnMut(FaceView<&Self>, VertexView<&Self>) -> T,
    {
        let mut builder = B::builder();
        builder.surface_with(|builder| {
            for face in self.faces() {
                let indices = face
                    .adjacent_vertices()
                    .map(|vertex| builder.insert_vertex(f(face, vertex)))
                    .collect::<Result<SmallVec<[_; 8]>, _>>()?;
                builder.facets_with(|builder| {
                    builder.insert_facet(indices.as_slice(), face.geometry)
                })?;
            }
            Ok(())
        })?;
        builder.build()
    }
}

impl<G> AsStorage<Vertex<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &Storage<Vertex<G>> {
        self.core.as_storage_of::<Vertex<_>>()
    }
}

impl<G> AsStorage<Arc<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &Storage<Arc<G>> {
        self.core.as_storage_of::<Arc<_>>()
    }
}

impl<G> AsStorage<Edge<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &Storage<Edge<G>> {
        self.core.as_storage_of::<Edge<_>>()
    }
}

impl<G> AsStorage<Face<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &Storage<Face<G>> {
        self.core.as_storage_of::<Face<_>>()
    }
}

impl<G> AsStorageMut<Vertex<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut Storage<Vertex<G>> {
        self.core.as_storage_mut_of::<Vertex<_>>()
    }
}

impl<G> AsStorageMut<Arc<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut Storage<Arc<G>> {
        self.core.as_storage_mut_of::<Arc<_>>()
    }
}

impl<G> AsStorageMut<Edge<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut Storage<Edge<G>> {
        self.core.as_storage_mut_of::<Edge<_>>()
    }
}

impl<G> AsStorageMut<Face<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut Storage<Face<G>> {
        self.core.as_storage_mut_of::<Face<_>>()
    }
}

/// Exposes a `MeshBuilder` that can be used to construct a `MeshGraph`
/// incrementally from _surfaces_ and _facets_.
///
/// See the documentation for the `builder` module for more.
///
/// # Examples
///
/// Creating a graph from a triangle:
///
/// ```rust
/// # extern crate nalgebra;
/// # extern crate plexus;
/// #
/// use nalgebra::Point2;
/// use plexus::builder::Buildable;
/// use plexus::graph::MeshGraph;
/// use plexus::prelude::*;
///
/// let mut builder = MeshGraph::<Point2<f64>>::builder();
/// let graph = builder
///     .surface_with(|builder| {
///         let a = builder.insert_vertex((0.0, 0.0))?;
///         let b = builder.insert_vertex((1.0, 0.0))?;
///         let c = builder.insert_vertex((0.0, 1.0))?;
///         builder.facets_with(|builder| builder.insert_facet(&[a, b, c], ()))
///     })
///     .and_then(|_| builder.build())
///     .unwrap();
/// ```
impl<G> Buildable for MeshGraph<G>
where
    G: GraphGeometry,
{
    type Builder = GraphBuilder<G>;
    type Error = GraphError;

    type Vertex = G::Vertex;
    type Facet = G::Face;

    fn builder() -> Self::Builder {
        Default::default()
    }
}

impl<G> Consistent for MeshGraph<G> where G: GraphGeometry {}

impl<G> Default for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn default() -> Self {
        MeshGraph::new()
    }
}

impl<G> DynamicArity for MeshGraph<G>
where
    G: GraphGeometry,
{
    type Dynamic = MeshArity;

    fn arity(&self) -> Self::Dynamic {
        MeshArity::from_components(self.faces())
    }
}

impl<P, G> From<P> for MeshGraph<G>
where
    P: Polygonal,
    G: GraphGeometry,
    G::Vertex: FromGeometry<P::Vertex>,
{
    fn from(polygon: P) -> Self {
        let arity = polygon.arity();
        MeshGraph::from_raw_buffers_with_arity(0..arity, polygon, arity)
            .expect("inconsistent polygon")
    }
}

impl<G> From<OwnedCore<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn from(core: OwnedCore<G>) -> Self {
        MeshGraph { core }
    }
}

impl<E, G> FromEncoding<E> for MeshGraph<G>
where
    G: GraphGeometry,
    E: FaceDecoder + VertexDecoder,
    E::Face: IntoGeometry<G::Face>,
    E::Vertex: IntoGeometry<G::Vertex>,
{
    type Error = GraphError;

    fn from_encoding(
        vertices: <E as VertexDecoder>::Output,
        faces: <E as FaceDecoder>::Output,
    ) -> Result<Self, Self::Error> {
        let mut mutation = Mutation::from(MeshGraph::new());
        let keys = vertices
            .into_iter()
            .map(|geometry| mutation::vertex::insert(&mut mutation, geometry.into_geometry()))
            .collect::<Vec<_>>();
        for (perimeter, geometry) in faces {
            let perimeter = perimeter
                .into_iter()
                .map(|index| keys[index])
                .collect::<SmallVec<[_; 4]>>();
            let cache = FaceInsertCache::from_storage(&mutation, perimeter.as_slice())?;
            let geometry = geometry.into_geometry();
            mutation::face::insert_with(&mut mutation, cache, || (Default::default(), geometry))?;
        }
        mutation.commit()
    }
}

impl<G, P> FromIndexer<P, P> for MeshGraph<G>
where
    G: GraphGeometry,
    P: Map<usize> + Polygonal,
    P::Output: Grouping<Group = P::Output> + IntoVertices + Polygonal<Vertex = usize>,
    P::Vertex: IntoGeometry<G::Vertex>,
    Vec<P::Output>: IndexBuffer<P::Output, Index = usize>,
{
    type Error = GraphError;

    fn from_indexer<I, N>(input: I, indexer: N) -> Result<Self, Self::Error>
    where
        I: IntoIterator<Item = P>,
        N: Indexer<P, P::Vertex>,
    {
        let mut mutation = Mutation::from(MeshGraph::new());
        let (indices, vertices) = input.into_iter().index_vertices(indexer);
        let vertices = vertices
            .into_iter()
            .map(|vertex| mutation::vertex::insert(&mut mutation, vertex.into_geometry()))
            .collect::<Vec<_>>();
        for face in indices {
            let perimeter = face
                .into_vertices()
                .into_iter()
                .map(|index| vertices[index])
                .collect::<SmallVec<[_; 4]>>();
            let cache = FaceInsertCache::from_storage(&mutation, &perimeter)?;
            mutation::face::insert_with(&mut mutation, cache, Default::default)?;
        }
        mutation.commit()
    }
}

impl<G, P> FromIterator<P> for MeshGraph<G>
where
    G: GraphGeometry,
    P: Polygonal,
    P::Vertex: Clone + Eq + Hash + IntoGeometry<G::Vertex>,
    Self: FromIndexer<P, P>,
{
    fn from_iter<I>(input: I) -> Self
    where
        I: IntoIterator<Item = P>,
    {
        Self::from_indexer(input, HashIndexer::default()).unwrap_or_else(|_| Self::default())
    }
}

impl<P, G, H> FromRawBuffers<P, H> for MeshGraph<G>
where
    P: IntoVertices + Polygonal,
    P::Vertex: Integer + ToPrimitive + Unsigned,
    G: GraphGeometry,
    H: IntoGeometry<G::Vertex>,
{
    type Error = GraphError;

    fn from_raw_buffers<I, J>(indices: I, vertices: J) -> Result<Self, Self::Error>
    where
        I: IntoIterator<Item = P>,
        J: IntoIterator<Item = H>,
    {
        let mut mutation = Mutation::from(MeshGraph::new());
        let vertices = vertices
            .into_iter()
            .map(|vertex| mutation::vertex::insert(&mut mutation, vertex.into_geometry()))
            .collect::<Vec<_>>();
        for face in indices {
            let mut perimeter = SmallVec::<[_; 4]>::with_capacity(face.arity());
            for index in face.into_vertices() {
                let index = <usize as NumCast>::from(index).unwrap();
                perimeter.push(
                    *vertices
                        .get(index)
                        .ok_or_else(|| GraphError::TopologyNotFound)?,
                );
            }
            let cache = FaceInsertCache::from_storage(&mutation, &perimeter)?;
            mutation::face::insert_with(&mut mutation, cache, Default::default)?;
        }
        mutation.commit()
    }
}

impl<N, G, H> FromRawBuffersWithArity<N, H> for MeshGraph<G>
where
    N: Integer + ToPrimitive + Unsigned,
    G: GraphGeometry,
    H: IntoGeometry<G::Vertex>,
{
    type Error = GraphError;

    /// Creates a `MeshGraph` from raw index and vertex buffers. The arity of
    /// the polygons in the index buffer must be known and constant.
    ///
    /// # Errors
    ///
    /// Returns an error if the arity of the index buffer is not constant, any
    /// index is out of bounds, or there is an error inserting topology into the
    /// graph.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point3;
    /// use plexus::graph::MeshGraph;
    /// use plexus::index::{Flat3, LruIndexer};
    /// use plexus::prelude::*;
    /// use plexus::primitive::generate::Position;
    /// use plexus::primitive::sphere::UvSphere;
    ///
    /// let (indices, positions) = UvSphere::new(16, 16)
    ///     .polygons::<Position<Point3<f64>>>()
    ///     .triangulate()
    ///     .index_vertices::<Flat3, _>(LruIndexer::with_capacity(256));
    /// let mut graph =
    ///     MeshGraph::<Point3<f64>>::from_raw_buffers_with_arity(indices, positions, 3).unwrap();
    /// ```
    fn from_raw_buffers_with_arity<I, J>(
        indices: I,
        vertices: J,
        arity: usize,
    ) -> Result<Self, Self::Error>
    where
        I: IntoIterator<Item = N>,
        J: IntoIterator<Item = H>,
    {
        if arity < 3 {
            return Err(GraphError::ArityNonPolygonal);
        }
        let mut mutation = Mutation::from(MeshGraph::new());
        let vertices = vertices
            .into_iter()
            .map(|vertex| mutation::vertex::insert(&mut mutation, vertex.into_geometry()))
            .collect::<Vec<_>>();
        for face in &indices
            .into_iter()
            .map(|index| <usize as NumCast>::from(index).unwrap())
            .chunks(arity)
        {
            let face = face.collect::<Vec<_>>();
            if face.len() != arity {
                // Index buffer length is not a multiple of arity.
                return Err(GraphError::ArityConflict {
                    expected: arity,
                    actual: face.len(),
                });
            }
            let mut perimeter = SmallVec::<[_; 4]>::with_capacity(arity);
            for index in face {
                perimeter.push(
                    *vertices
                        .get(index)
                        .ok_or_else(|| GraphError::TopologyNotFound)?,
                );
            }
            let cache = FaceInsertCache::from_storage(&mutation, &perimeter)?;
            mutation::face::insert_with(&mut mutation, cache, Default::default)?;
        }
        mutation.commit()
    }
}

impl<G> Geometric for MeshGraph<G>
where
    G: GraphGeometry,
{
    type Geometry = G;
}

impl<G> Into<OwnedCore<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn into(self) -> OwnedCore<G> {
        let MeshGraph { core, .. } = self;
        core
    }
}

impl<G> IntoPolygons for MeshGraph<G>
where
    G: GraphGeometry,
{
    type Output = vec::IntoIter<Self::Polygon>;
    type Polygon = UnboundedPolygon<G::Vertex>;

    fn into_polygons(self) -> Self::Output {
        self.faces()
            .map(|face| {
                // The arity of a face in a graph must be polygonal (three or
                // higher) so this should never fail.
                let vertices = face.adjacent_vertices().map(|vertex| vertex.geometry);
                UnboundedPolygon::from_items(vertices).expect_consistent()
            })
            .collect::<Vec<_>>()
            .into_iter()
    }
}

impl<G> StaticArity for MeshGraph<G>
where
    G: GraphGeometry,
{
    type Static = (usize, Option<usize>);

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

impl<A, N, H, G> TryFrom<MeshBuffer<Flat<A, N>, H>> for MeshGraph<G>
where
    A: NonZero + typenum::Unsigned,
    N: Copy + Integer + NumCast + Unsigned,
    H: Clone + IntoGeometry<G::Vertex>,
    G: GraphGeometry,
{
    type Error = GraphError;

    /// Creates a `MeshGraph` from a flat `MeshBuffer`. The arity of the
    /// polygons in the index buffer must be known and constant.
    ///
    /// # Errors
    ///
    /// Returns an error if a `MeshGraph` cannot represent the topology in the
    /// `MeshBuffer`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point2;
    /// use plexus::buffer::MeshBuffer;
    /// use plexus::graph::MeshGraph;
    /// use plexus::index::Flat4;
    /// use plexus::prelude::*;
    /// use std::convert::TryFrom;
    ///
    /// let buffer = MeshBuffer::<Flat4, _>::from_raw_buffers(
    ///     vec![0u64, 1, 2, 3],
    ///     vec![(0.0f64, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
    /// )
    /// .unwrap();
    /// let mut graph = MeshGraph::<Point2<f64>>::try_from(buffer).unwrap();
    /// ```
    fn try_from(buffer: MeshBuffer<Flat<A, N>, H>) -> Result<Self, Self::Error> {
        let arity = buffer.arity();
        let (indices, vertices) = buffer.into_raw_buffers();
        MeshGraph::from_raw_buffers_with_arity(indices, vertices, arity)
    }
}

impl<P, H, G> TryFrom<MeshBuffer<P, H>> for MeshGraph<G>
where
    P: Grouping<Group = P> + IntoVertices + Polygonal,
    P::Vertex: Copy + Integer + NumCast + Unsigned,
    H: Clone + IntoGeometry<G::Vertex>,
    G: GraphGeometry,
{
    type Error = GraphError;

    /// Creates a `MeshGraph` from a structured `MeshBuffer`.
    ///
    /// # Errors
    ///
    /// Returns an error if a `MeshGraph` cannot represent the topology in the
    /// `MeshBuffer`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point2;
    /// use plexus::buffer::MeshBuffer;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::Tetragon;
    /// use std::convert::TryFrom;
    ///
    /// let buffer = MeshBuffer::<Tetragon<u64>, _>::from_raw_buffers(
    ///     vec![Tetragon::new(0u64, 1, 2, 3)],
    ///     vec![(0.0f64, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
    /// )
    /// .unwrap();
    /// let mut graph = MeshGraph::<Point2<f64>>::try_from(buffer).unwrap();
    /// ```
    fn try_from(buffer: MeshBuffer<P, H>) -> Result<Self, Self::Error> {
        let (indices, vertices) = buffer.into_raw_buffers();
        MeshGraph::from_raw_buffers(indices, vertices)
    }
}

#[cfg(test)]
mod tests {
    use decorum::N64;
    use nalgebra::{Point2, Point3, Vector3};
    use num::Zero;

    use crate::buffer::MeshBuffer3;
    use crate::graph::{GraphError, GraphGeometry, MeshGraph};
    use crate::prelude::*;
    use crate::primitive::generate::Position;
    use crate::primitive::sphere::UvSphere;
    use crate::primitive::NGon;

    type E2 = Point2<N64>;
    type E3 = Point3<N64>;

    #[test]
    fn collect() {
        let graph = UvSphere::new(3, 2)
            .polygons::<Position<E3>>() // 6 triangles, 18 vertices.
            .collect::<MeshGraph<Point3<f64>>>();

        assert_eq!(5, graph.vertex_count());
        assert_eq!(18, graph.arc_count());
        assert_eq!(6, graph.face_count());
    }

    #[test]
    fn iterate() {
        let mut graph = UvSphere::new(4, 2)
            .polygons::<Position<E3>>() // 8 triangles, 24 vertices.
            .collect::<MeshGraph<Point3<f64>>>();

        assert_eq!(6, graph.vertices().count());
        assert_eq!(24, graph.arcs().count());
        assert_eq!(8, graph.faces().count());
        for vertex in graph.vertices() {
            // Every vertex is connected to 4 triangles with 4 (incoming) arcs.
            // Traversal of topology should be possible.
            assert_eq!(4, vertex.incoming_arcs().count());
        }
        for mut vertex in graph.vertex_orphans() {
            // Geometry should be mutable.
            vertex.geometry += Vector3::zero();
        }
    }

    #[test]
    fn isolate_disjoint_subgraphs() {
        // Construct a graph from a quadrilateral.
        let graph = MeshGraph::<E2>::from_raw_buffers(
            vec![NGon([0u32, 1, 2, 3])],
            vec![(1.0, 0.0), (2.0, 0.0), (2.0, 1.0), (1.0, 1.0)],
        )
        .unwrap();

        assert_eq!(1, graph.disjoint_subgraph_vertices().count());

        // Construct a graph with two disjoint quadrilaterals.
        let graph = MeshGraph::<E2>::from_raw_buffers(
            vec![NGon([0u32, 1, 2, 3]), NGon([4, 5, 6, 7])],
            vec![
                (-2.0, 0.0),
                (-1.0, 0.0),
                (-1.0, 1.0),
                (-2.0, 1.0),
                (1.0, 0.0),
                (2.0, 0.0),
                (2.0, 1.0),
                (1.0, 1.0),
            ],
        )
        .unwrap();

        assert_eq!(2, graph.disjoint_subgraph_vertices().count());
    }

    #[test]
    fn non_manifold_error_deferred() {
        let graph = UvSphere::new(32, 32)
            .polygons::<Position<E3>>()
            .triangulate()
            .collect::<MeshGraph<E3>>();
        // This conversion will join faces by a single vertex, but ultimately
        // creates a manifold.
        let _: MeshBuffer3<usize, E3> = graph.to_mesh_by_face().unwrap();
    }

    #[test]
    fn error_on_non_manifold() {
        // Construct a graph with a "fan" of three triangles sharing the same
        // arc along the Z-axis. The edge would have three associated faces,
        // which should not be possible.
        let graph = MeshGraph::<Point3<i32>>::from_raw_buffers(
            vec![NGon([0u32, 1, 2]), NGon([0, 1, 3]), NGon([0, 1, 4])],
            vec![(0, 0, 1), (0, 0, -1), (1, 0, 0), (0, 1, 0), (1, 1, 0)],
        );

        assert_eq!(graph.err().unwrap(), GraphError::TopologyConflict);
    }

    // This test is a sanity check for graph iterators, topological views, and
    // the unsafe transmutations used to coerce lifetimes.
    #[test]
    fn read_write_geometry_ref() {
        struct ValueGeometry;

        impl GraphGeometry for ValueGeometry {
            type Vertex = Point3<f64>;
            type Arc = ();
            type Edge = ();
            type Face = u64;
        }

        // Create a graph with a floating point value associated with each face.
        // Use a mutable iterator to write to the geometry of each face.
        let mut graph = UvSphere::new(4, 4)
            .polygons::<Position<E3>>()
            .collect::<MeshGraph<ValueGeometry>>();
        let value = 123_456_789;
        for mut face in graph.face_orphans() {
            face.geometry = value;
        }

        // Read the geometry of each face using an immutable iterator to ensure
        // it is what we expect.
        for face in graph.faces() {
            assert_eq!(value, face.geometry);
        }
    }
}