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
//! Half-edge graph representation of meshes.
//!
//! This module provides a flexible representation of meshes as a [half-edge
//! graph](https://en.wikipedia.org/wiki/doubly_connected_edge_list).
//! _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).
//!
//! Geometry is vertex-based, meaning that geometric operations depend on
//! vertices exposing some notion of positional data. See the `geometry` module
//! and `AsPosition` trait. If geometry does not have this property, then
//! spatial operations will not be available.
//!
//! See the [user guide](https://plexus.rs/user-guide/graphs) for more details
//! and examples.
//!
//! # Representation
//!
//! A `MeshGraph` is conceptually composed of _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 neighbors, 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. A path over vertices $A$, $B$, and $C$ is
//! notated $\overrightarrow{\\{A,B,C\\}}$. This path notation is used to
//! describe rings and faces.
//!
//! Together with vertices and faces, the connectivity of arcs allows for
//! effecient traversals of topology. For example, it becomes trivial to find
//! neighboring topologies, such as the faces that share a given vertex or the
//! neighboring faces of a given face.
//!
//! `MeshGraph`s store topological data using associative collections and mesh
//! data is accessed using keys into this storage. Keys are exposed as strongly
//! typed and opaque values, which can be used to refer to a topological
//! structure.
//!
//! # Topological Views
//!
//! `MeshGraph`s expose _views_ over their topological structures (vertices,
//! arcs, edges, and faces). Views are accessed via keys or iteration and
//! behave similarly to references. They provide the primary API for
//! interacting with a `MeshGraph`'s topology and geometry. There are three
//! types 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_ are similar to mutable views in that they may mutate the
//! geometry of a graph, but they do not have access to the topology of a
//! graph. Because they do not know about other vertices, arcs, etc., an orphan
//! view 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. Iterators over topological structures in a graph sometimes emit
//! orphan views.
//!
//! # 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;
//!
//! # fn main() {
//! 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;
//!
//! # fn main() {
//! let mut graph = UvSphere::new(8, 8)
//!     .polygons::<Position<Point3<N64>>>()
//!     .collect::<MeshGraph<Point3<N64>>>();
//! let key = graph.faces().nth(0).unwrap().key(); // Get the key of the first face.
//! let face = graph.face_mut(key).unwrap().extrude(1.0); // Extrude the face.
//! # }
//! ```
//!
//! 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;
//!
//! # fn main() {
//! 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.neighboring_face_orphans() {
//!     // `face.geometry` is mutable here.
//! }
//! # }
//! ```

mod borrow;
mod core;
mod geometry;
mod mutation;
mod storage;
mod view;

use decorum::N64;
use itertools::{Itertools, MinMaxResult};
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 theon::ops::Map;
use theon::query::Aabb;
use theon::space::{EuclideanSpace, Scalar};
use theon::AsPosition;
use thiserror::Error;
use typenum::{self, NonZero};

use crate::buffer::{BufferError, MeshBuffer};
use crate::encoding::{FaceDecoder, FromEncoding, VertexDecoder};
use crate::graph::core::{Bind, Core, OwnedCore};
use crate::graph::mutation::{Consistent, Mutate, Mutation};
use crate::graph::storage::alias::*;
use crate::graph::storage::key::OpaqueKey;
use crate::graph::storage::{AsStorage, AsStorageMut, StorageProxy};
use crate::graph::view::{IntoView, Orphan};
use crate::index::{Flat, FromIndexer, Grouping, HashIndexer, IndexBuffer, IndexVertices, Indexer};
use crate::primitive::decompose::IntoVertices;
use crate::primitive::Polygonal;
use crate::{Arity, FromRawBuffers, FromRawBuffersWithArity, IntoGeometry, IteratorExt as _};

pub use crate::graph::geometry::{
    ArcNormal, EdgeMidpoint, FaceCentroid, FaceNormal, FacePlane, GraphGeometry, VertexCentroid,
    VertexNormal, VertexPosition,
};
pub use crate::graph::storage::key::{ArcKey, EdgeKey, FaceKey, VertexKey};
pub use crate::graph::storage::payload::{ArcPayload, EdgePayload, FacePayload, VertexPayload};
pub use crate::graph::view::edge::{ArcOrphan, ArcView, CompositeEdge, EdgeOrphan, EdgeView};
pub use crate::graph::view::face::{FaceOrphan, FaceView, Ring, RingView};
pub use crate::graph::view::path::PathView;
pub use crate::graph::view::vertex::{VertexOrphan, VertexView};
pub use crate::graph::view::PayloadBinding;

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,
}

impl From<BufferError> for GraphError {
    fn from(_: BufferError) -> Self {
        // TODO: How should buffer errors be handled? Is this sufficient?
        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")
    }
}

/// Topology selector.
///
/// Identifies topology by key or index. Keys behave as an absolute selector
/// and uniquely identify a single topological structure. Indices behave as a
/// relative selector and identify topological structures relative to some
/// other structure. `Selector` is used by operations that support both of
/// these selection mechanisms.
///
/// An index is typically used to select a neighbor or contained (and ordered)
/// topological structure, such as a neighboring 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;
///
/// # fn main() {
/// 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 data in the form of 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()
                .bind(StorageProxy::<VertexPayload<G>>::new())
                .bind(StorageProxy::<ArcPayload<G>>::new())
                .bind(StorageProxy::<EdgePayload<G>>::new())
                .bind(StorageProxy::<FacePayload<G>>::new()),
        )
    }

    /// Gets the number of vertices in the graph.
    pub fn vertex_count(&self) -> usize {
        self.as_vertex_storage().len()
    }

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

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

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the vertices in the graph.
    pub fn vertices(&self) -> impl Iterator<Item = VertexView<&Self, G>> {
        self.as_vertex_storage()
            .keys()
            .map(move |key| (key, self).into_view().unwrap())
    }

    /// Gets an iterator of orphan views over the vertices in the graph.
    ///
    /// Because this only yields orphan views, only geometry can be mutated.
    /// For topological mutations, collect the necessary keys and use
    /// `vertex_mut` instead.
    pub fn vertex_orphans(&mut self) -> impl Iterator<Item = VertexOrphan<G>> {
        self.as_vertex_storage_mut()
            .iter_mut()
            .map(|(key, source)| Orphan::from_keyed_source_unchecked((key, source)))
            .map(|view| view.into())
    }

    /// Gets the number of arcs in the graph.
    pub fn arc_count(&self) -> usize {
        self.as_arc_storage().len()
    }

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

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

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the arcs in the graph.
    pub fn arcs(&self) -> impl Iterator<Item = ArcView<&Self, G>> {
        self.as_arc_storage()
            .keys()
            .map(move |key| (key, self).into_view().unwrap())
    }

    /// Gets an iterator of orphan views over the arcs in the graph.
    ///
    /// Because this only yields orphan views, only geometry can be mutated.
    /// For topological mutations, collect the necessary keys and use
    /// `arc_mut` instead.
    pub fn arc_orphans(&mut self) -> impl Iterator<Item = ArcOrphan<G>> {
        self.as_arc_storage_mut()
            .iter_mut()
            .map(|(key, source)| Orphan::from_keyed_source_unchecked((key, source)))
            .map(|view| view.into())
    }

    /// Gets the number of edges in the graph.
    pub fn edge_count(&self) -> usize {
        self.as_edge_storage().len()
    }

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

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

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the edges in the graph.
    pub fn edges(&self) -> impl Iterator<Item = EdgeView<&Self, G>> {
        self.as_edge_storage()
            .keys()
            .map(move |key| (key, self).into_view().unwrap())
    }

    /// Gets an iterator of orphan views over the edges in the graph.
    ///
    /// Because this only yields orphan views, only geometry can be mutated.
    /// For topological mutations, collect the necessary keys and use
    /// `edge_mut` instead.
    pub fn edge_orphans(&mut self) -> impl Iterator<Item = EdgeOrphan<G>> {
        self.as_edge_storage_mut()
            .iter_mut()
            .map(|(key, source)| Orphan::from_keyed_source_unchecked((key, source)))
            .map(|view| view.into())
    }

    /// Gets the number of faces in the graph.
    pub fn face_count(&self) -> usize {
        self.as_face_storage().len()
    }

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

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

    // TODO: Return `Clone + Iterator`.
    /// Gets an iterator of immutable views over the faces in the graph.
    pub fn faces(&self) -> impl Iterator<Item = FaceView<&Self, G>> {
        self.as_face_storage()
            .keys()
            .map(move |key| (key, self).into_view().unwrap())
    }

    /// Gets an iterator of orphan views over the faces in the graph.
    ///
    /// Because this only yields orphan views, only geometry can be mutated.
    /// For topological mutations, collect the necessary keys and use
    /// `face_mut` instead.
    pub fn face_orphans(&mut self) -> impl Iterator<Item = FaceOrphan<G>> {
        self.as_face_storage_mut()
            .iter_mut()
            .map(|(key, source)| Orphan::from_keyed_source_unchecked((key, source)))
            .map(|view| view.into())
    }

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

    pub fn path_mut<I>(&mut self, keys: I) -> Result<PathView<&mut Self, G>, GraphError>
    where
        I: IntoIterator,
        I::Item: Borrow<VertexKey>,
    {
        PathView::try_from_keys(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,
    {
        Aabb::from_points(self.vertices().map(|vertex| *vertex.geometry.as_position()))
    }

    /// Gets the arity of the graph.
    ///
    /// If all faces in the graph have the same arity, then `Arity::Uniform` is
    /// returned with the singular arity of the graph. If the graph contains
    /// faces with differing arity, then `Arity::NonUniform` is returned with
    /// the minimum and maximum arity.
    ///
    /// `Arity::Uniform` is returned with zero if there are no faces in the
    /// graph.
    pub fn arity(&self) -> Arity {
        match self.faces().map(|face| face.arity()).minmax() {
            MinMaxResult::OneElement(arity) => Arity::Uniform(arity),
            MinMaxResult::MinMax(min, max) => Arity::NonUniform(min, max),
            _ => Arity::Uniform(0),
        }
    }

    /// Triangulates the graph, tessellating all faces into triangles.
    pub fn triangulate(&mut self) {
        let faces = self.as_face_storage().keys().collect::<Vec<_>>();
        for face in faces {
            self.face_mut(face).unwrap().triangulate();
        }
    }

    /// 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 neighboring 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();
        }
    }

    // TODO: Because `MeshGraph` supports some non-manifold structures like
    //       singularities and unbounded edges, this operation is complicated.
    //       However, support for these will likely be removed. Once these
    //       structures can be ignored, implement this operation.
    //
    // 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 into two disjoint sub-graphs along a path.
    ///
    /// The given path must either be closed or, if open, must begin and end
    /// within the same ring. Such a path subdivides the graph.
    ///
    /// The sub-graphs are disconnected from each other, copying any vertices,
    /// arcs, and edges at their boundaries.
    #[allow(clippy::type_complexity)]
    pub fn split_at_path(
        path: PathView<&mut Self, G>,
    ) -> Result<(VertexView<&Self, G>, VertexView<&Self, G>), GraphError> {
        if path.is_open() {
            let first = path.vertices().nth(0).unwrap();
            let last = path.vertices().last().unwrap();
            // If the path is open, then the initiating and terminating
            // vertices must be a part of the same ring and that ring must form
            // a boundary (must not be a face).
            first
                .outgoing_arcs()
                .flat_map(|arc| arc.into_boundary_arc())
                .map(|arc| arc.into_ring())
                .nth(0)
                .and_then(|ring| ring.vertices().keys().find(|key| *key == last.key()))
                .ok_or_else(|| GraphError::TopologyMalformed)?;
        }
        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;
    ///
    /// # fn main() {
    /// 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 Iterator<Item = VertexView<&Self, G>> {
        let keys = self.as_vertex_storage().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 = (*key, self).into_view().unwrap();
            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 `MeshBuffer` from the graph.
    ///
    /// The buffer is created using the vertex geometry of each unique vertex.
    ///
    /// # 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_buffer_by_vertex<A, N, H>(&self) -> Result<MeshBuffer<Flat<A, N>, H>, GraphError>
    where
        G::Vertex: IntoGeometry<H>,
        A: NonZero + typenum::Unsigned,
        N: Copy + Integer + NumCast + Unsigned,
    {
        self.to_mesh_buffer_by_vertex_with(|vertex| vertex.geometry.into_geometry())
    }

    /// Creates a `MeshBuffer` from the graph.
    ///
    /// The buffer is created using each unique vertex, which is converted into
    /// the buffer geometry by the given function.
    ///
    /// # 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_buffer_by_vertex_with<A, N, H, F>(
        &self,
        mut f: F,
    ) -> Result<MeshBuffer<Flat<A, N>, H>, GraphError>
    where
        A: NonZero + typenum::Unsigned,
        N: Copy + Integer + NumCast + Unsigned,
        F: FnMut(VertexView<&Self, G>) -> H,
    {
        let (keys, vertices) = {
            let mut keys = HashMap::with_capacity(self.vertex_count());
            let mut vertices = Vec::with_capacity(self.vertex_count());
            for (n, vertex) in self.vertices().enumerate() {
                keys.insert(vertex.key(), n);
                vertices.push(f(vertex));
            }
            (keys, vertices)
        };
        let indices = {
            let arity = A::USIZE;
            let mut indices = Vec::with_capacity(arity * self.face_count());
            for face in self.faces() {
                if face.arity() != arity {
                    return Err(GraphError::ArityConflict {
                        expected: arity,
                        actual: face.arity(),
                    });
                }
                for vertex in face.vertices() {
                    indices.push(N::from(keys[&vertex.key()]).unwrap());
                }
            }
            indices
        };
        MeshBuffer::<Flat<_, _>, _>::from_raw_buffers(indices, vertices)
            .map_err(|error| error.into())
    }

    /// Creates a `MeshBuffer` from the graph.
    ///
    /// The buffer is created using the vertex geometry of each face. Shared
    /// vertices are included for each face to which they belong.
    ///
    /// # 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_buffer_by_face<A, N, H>(&self) -> Result<MeshBuffer<Flat<A, N>, H>, GraphError>
    where
        G::Vertex: IntoGeometry<H>,
        A: NonZero + typenum::Unsigned,
        N: Copy + Integer + NumCast + Unsigned,
    {
        self.to_mesh_buffer_by_face_with(|_, vertex| vertex.geometry.into_geometry())
    }

    /// Creates a `MeshBuffer` from the graph.
    ///
    /// The buffer is created from each face, which is converted into the
    /// buffer geometry by the given function.
    ///
    /// # 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_buffer_by_face_with<A, N, H, F>(
        &self,
        mut f: F,
    ) -> Result<MeshBuffer<Flat<A, N>, H>, GraphError>
    where
        A: NonZero + typenum::Unsigned,
        N: Copy + Integer + NumCast + Unsigned,
        F: FnMut(FaceView<&Self, G>, VertexView<&Self, G>) -> H,
    {
        let vertices = {
            let arity = A::USIZE;
            let mut vertices = Vec::with_capacity(arity * self.face_count());
            for face in self.faces() {
                if face.arity() != arity {
                    return Err(GraphError::ArityConflict {
                        expected: arity,
                        actual: face.arity(),
                    });
                }
                for vertex in face.vertices() {
                    // TODO: Can some sort of dereference be used here?
                    vertices.push(f(face, vertex));
                }
            }
            vertices
        };
        MeshBuffer::<Flat<_, _>, _>::from_raw_buffers(
            // TODO: Cannot use the bound `N: Step`, which is unstable.
            (0..vertices.len()).map(|index| N::from(index).unwrap()),
            vertices,
        )
        .map_err(|error| error.into())
    }
}

impl<G> AsStorage<VertexPayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &StorageProxy<VertexPayload<G>> {
        self.core.as_vertex_storage()
    }
}

impl<G> AsStorage<ArcPayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &StorageProxy<ArcPayload<G>> {
        self.core.as_arc_storage()
    }
}

impl<G> AsStorage<EdgePayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &StorageProxy<EdgePayload<G>> {
        self.core.as_edge_storage()
    }
}

impl<G> AsStorage<FacePayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage(&self) -> &StorageProxy<FacePayload<G>> {
        self.core.as_face_storage()
    }
}

impl<G> AsStorageMut<VertexPayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut StorageProxy<VertexPayload<G>> {
        self.core.as_vertex_storage_mut()
    }
}

impl<G> AsStorageMut<ArcPayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut StorageProxy<ArcPayload<G>> {
        self.core.as_arc_storage_mut()
    }
}

impl<G> AsStorageMut<EdgePayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut StorageProxy<EdgePayload<G>> {
        self.core.as_edge_storage_mut()
    }
}

impl<G> AsStorageMut<FacePayload<G>> for MeshGraph<G>
where
    G: GraphGeometry,
{
    fn as_storage_mut(&mut self) -> &mut StorageProxy<FacePayload<G>> {
        self.core.as_face_storage_mut()
    }
}

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> 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::mutate(MeshGraph::new());
        let keys = vertices
            .into_iter()
            .map(|geometry| mutation.insert_vertex(geometry.into_geometry()))
            .collect::<Vec<_>>();
        for (perimeter, geometry) in faces {
            let perimeter = perimeter
                .into_iter()
                .map(|index| keys[index])
                .collect::<SmallVec<[_; 4]>>();
            mutation.insert_face(
                perimeter.as_slice(),
                (Default::default(), geometry.into_geometry()),
            )?;
        }
        mutation.commit()
    }
}

impl<G, P> FromIndexer<P, P> for MeshGraph<G>
where
    G: GraphGeometry,
    P: Map<usize> + Polygonal,
    P::Output: Grouping<Item = 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::mutate(MeshGraph::new());
        let (indices, vertices) = input.into_iter().index_vertices(indexer);
        let vertices = vertices
            .into_iter()
            .map(|vertex| mutation.insert_vertex(vertex.into_geometry()))
            .collect::<Vec<_>>();
        for face in indices {
            let perimeter = face
                .into_vertices()
                .into_iter()
                .map(|index| vertices[index])
                .collect::<SmallVec<[_; 4]>>();
            mutation.insert_face(&perimeter, 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::mutate(MeshGraph::new());
        let vertices = vertices
            .into_iter()
            .map(|vertex| mutation.insert_vertex(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)?,
                );
            }
            mutation.insert_face(&perimeter, 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;
    ///
    /// # fn main() {
    /// 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::mutate(MeshGraph::new());
        let vertices = vertices
            .into_iter()
            .map(|vertex| mutation.insert_vertex(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)?,
                );
            }
            mutation.insert_face(&perimeter, Default::default())?;
        }
        mutation.commit()
    }
}

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

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;
    ///
    /// # fn main() {
    /// 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 = match buffer.arity() {
            Arity::Uniform(arity) => arity,
            _ => panic!("non-uniform flat index 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<Item = 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;
    ///
    /// # fn main() {
    /// 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 typenum::U3;

    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_topology_into_mesh() {
        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_mesh_topology() {
        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<Point3<f64>>>();
        // This conversion will join faces by a single vertex, but ultimately
        // creates a manifold.
        graph
            .to_mesh_buffer_by_face_with::<U3, usize, _, _>(|_, vertex| vertex.geometry)
            .unwrap();
    }

    #[test]
    fn error_on_non_manifold_mesh() {
        // 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);
        }
    }
}