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
//! An API for composing **Mesh**s. **Mesh**s may be composed of different sets of channels
//! including position, color, texture-coordinate and normals. Note that this is quite a low-level
//! representation. For a higher-level, graphics-related mesh API, see the `draw` module.

use crate::geom::{self, Point2};
use crate::math::{BaseFloat, BaseNum, EuclideanSpace};
use std::cell::{Ref, RefMut};
use std::cmp;
use std::marker::PhantomData;
use std::ops::{self, Deref, DerefMut};

pub mod channel;
pub mod vertex;

pub use self::channel::{Channel, ChannelMut};

// Type aliases.

/// The fallback scalar type used for texture coordinates if none is specified.
pub type TexCoordScalarDefault = f64;

// Traits describing meshes with access to certain channels.

/// Mesh types that can be indexed to produce a vertex.
pub trait GetVertex {
    /// The vertex type representing all channels of data within the mesh at a single index.
    type Vertex;
    /// Create a vertex containing all channel properties for the given index.
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex>;
}

/// All meshes must contain at least one vertex channel.
pub trait Points {
    /// The scalar value used for the vertex coordinates.
    type Scalar: BaseNum;
    /// The vertex type used to represent the location of a vertex.
    type Point: geom::Vertex<Scalar = Self::Scalar>;
    /// The channel type containing points.
    type Points: Channel<Element = Self::Point>;
    /// Borrow the vertex channel from the mesh.
    fn points(&self) -> &Self::Points;
}

/// Meshes that contain a channel of indices that describe the edges between points.
pub trait Indices {
    /// The channel type containing indices.
    type Indices: Channel<Element = usize>;
    /// Borrow the index channel from the mesh.
    fn indices(&self) -> &Self::Indices;
}

/// Meshes that contain a channel of colors.
pub trait Colors {
    /// The color type stored within the channel.
    type Color;
    /// The channel type containing colors.
    type Colors: Channel<Element = Self::Color>;
    /// Borrow the color channel from the mesh.
    fn colors(&self) -> &Self::Colors;
}

/// Meshes that contain a channel of texture coordinates.
pub trait TexCoords {
    /// The scalar value used for the texture coordinates.
    type TexCoordScalar: BaseFloat;
    /// The channel type containing texture coordinates.
    type TexCoords: Channel<Element = Point2<Self::TexCoordScalar>>;
    /// Borrow the texture coordinate channel from the mesh.
    fn tex_coords(&self) -> &Self::TexCoords;
}

/// Meshes that contain a channel of vertex normals.
pub trait Normals: Points
where
    Self::Point: EuclideanSpace,
{
    /// The channel type containing vertex normals.
    type Normals: Channel<Element = <Self::Point as EuclideanSpace>::Diff>;
    /// Borrow the normal channel from the mesh.
    fn normals(&self) -> &Self::Normals;
}

/// Meshes that can push vertices of type **V** while keeping all non-index channels the same
/// length before and after the push.
pub trait PushVertex<V> {
    /// Push the given vertex onto the mesh.
    ///
    /// Implementation requires that all non-index channels maintain the same length before and
    /// after a call to this method.
    fn push_vertex(&mut self, vertex: V);
}

/// Meshes that contain an **Indices** channel and can push new indices to it.
pub trait PushIndex {
    /// Push a new index onto the indices channel.
    fn push_index(&mut self, index: usize);
    /// Extend the **Mesh**'s **Indices** channel with the given indices.
    fn extend_indices<I>(&mut self, indices: I)
    where
        I: IntoIterator<Item = usize>,
    {
        for i in indices {
            self.push_index(i);
        }
    }
}

/// Meshes whose **Indices** channel can be cleared.
pub trait ClearIndices {
    /// Clear all indices from the mesh.
    fn clear_indices(&mut self);
}

/// Meshes whose vertices channels can be cleared.
pub trait ClearVertices {
    /// Clear all vertices from the mesh.
    fn clear_vertices(&mut self);
}

/// Meshes whose indices and vertices buffers may be cleared for re-use.
pub trait Clear: ClearIndices + ClearVertices {
    fn clear(&mut self) {
        self.clear_indices();
        self.clear_vertices();
    }
}

// Mesh types.

/// The base mesh type with only a single vertex channel.
///
/// Extra channels can be added to the mesh via the `WithIndices`, `WithColors`, `WithTexCoords`
/// and `WithNormals` adaptor types.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct MeshPoints<P> {
    points: P,
}

/// A mesh type with an added channel containing indices describing the edges between vertices.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct WithIndices<M, I> {
    mesh: M,
    indices: I,
}

/// A `Mesh` type with an added channel containing colors.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct WithColors<M, C> {
    mesh: M,
    colors: C,
}

/// A `Mesh` type with an added channel containing texture coordinates.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct WithTexCoords<M, T, S = TexCoordScalarDefault> {
    mesh: M,
    tex_coords: T,
    _tex_coord_scalar: PhantomData<S>, // Required due to lack of HKT.
}

/// A `Mesh` type with an added channel containing vertex normals.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct WithNormals<M, N> {
    mesh: M,
    normals: N,
}

// **GetVertex** implementations.

impl<'a, M> GetVertex for &'a M
where
    M: GetVertex,
{
    type Vertex = M::Vertex;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        (**self).get_vertex(index)
    }
}

impl<'a, M> GetVertex for &'a mut M
where
    M: GetVertex,
{
    type Vertex = M::Vertex;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        (**self).get_vertex(index)
    }
}

impl<'a, M> GetVertex for Ref<'a, M>
where
    M: GetVertex,
{
    type Vertex = M::Vertex;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        (**self).get_vertex(index)
    }
}

impl<'a, M> GetVertex for RefMut<'a, M>
where
    M: GetVertex,
{
    type Vertex = M::Vertex;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        (**self).get_vertex(index)
    }
}

impl<P> GetVertex for MeshPoints<P>
where
    P: Channel,
    P::Element: geom::Vertex,
{
    type Vertex = P::Element;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        self.points.channel().get(index).map(|&p| p)
    }
}

impl<M, I> GetVertex for WithIndices<M, I>
where
    M: GetVertex,
{
    type Vertex = M::Vertex;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        self.mesh.get_vertex(index)
    }
}

impl<M, C> GetVertex for WithColors<M, C>
where
    M: GetVertex,
    C: Channel,
    C::Element: Clone,
{
    type Vertex = vertex::WithColor<M::Vertex, C::Element>;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        self.mesh.get_vertex(index).and_then(|vertex| {
            self.colors.channel().get(index).map(|color| {
                let color = color.clone();
                vertex::WithColor { vertex, color }
            })
        })
    }
}

impl<M, T, S> GetVertex for WithTexCoords<M, T, S>
where
    M: GetVertex,
    T: Channel,
    T::Element: Clone,
{
    type Vertex = vertex::WithTexCoords<M::Vertex, T::Element>;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        self.mesh.get_vertex(index).and_then(|vertex| {
            self.tex_coords.channel().get(index).map(|tex_coords| {
                let tex_coords = tex_coords.clone();
                vertex::WithTexCoords { vertex, tex_coords }
            })
        })
    }
}

impl<M, N> GetVertex for WithNormals<M, N>
where
    M: GetVertex,
    N: Channel,
    N::Element: Clone,
{
    type Vertex = vertex::WithNormal<M::Vertex, N::Element>;
    fn get_vertex(&self, index: usize) -> Option<Self::Vertex> {
        self.mesh.get_vertex(index).and_then(|vertex| {
            self.normals.channel().get(index).map(|normal| {
                let normal = normal.clone();
                vertex::WithNormal { vertex, normal }
            })
        })
    }
}

// **Points** implementations.

impl<P> Points for MeshPoints<P>
where
    P: Channel,
    P::Element: geom::Vertex,
{
    type Scalar = <P::Element as geom::Vertex>::Scalar;
    type Point = P::Element;
    type Points = P;
    fn points(&self) -> &Self::Points {
        &self.points
    }
}

impl<'a, M> Points for &'a M
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        (**self).points()
    }
}

impl<'a, M> Points for &'a mut M
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        (**self).points()
    }
}

impl<'a, M> Points for Ref<'a, M>
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        (**self).points()
    }
}

impl<'a, M> Points for RefMut<'a, M>
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        (**self).points()
    }
}

impl<M, I> Points for WithIndices<M, I>
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        self.mesh.points()
    }
}

impl<M, C> Points for WithColors<M, C>
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        self.mesh.points()
    }
}

impl<M, T, S> Points for WithTexCoords<M, T, S>
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        self.mesh.points()
    }
}

impl<M, N> Points for WithNormals<M, N>
where
    M: Points,
{
    type Scalar = M::Scalar;
    type Point = M::Point;
    type Points = M::Points;
    fn points(&self) -> &Self::Points {
        self.mesh.points()
    }
}

// **Indices** implementations.

impl<M, I> Indices for WithIndices<M, I>
where
    I: Channel<Element = usize>,
{
    type Indices = I;
    fn indices(&self) -> &Self::Indices {
        &self.indices
    }
}

impl<'a, M> Indices for &'a M
where
    M: Indices,
{
    type Indices = M::Indices;
    fn indices(&self) -> &Self::Indices {
        (**self).indices()
    }
}

impl<'a, M> Indices for &'a mut M
where
    M: Indices,
{
    type Indices = M::Indices;
    fn indices(&self) -> &Self::Indices {
        (**self).indices()
    }
}

impl<'a, M> Indices for Ref<'a, M>
where
    M: Indices,
{
    type Indices = M::Indices;
    fn indices(&self) -> &Self::Indices {
        (**self).indices()
    }
}

impl<'a, M> Indices for RefMut<'a, M>
where
    M: Indices,
{
    type Indices = M::Indices;
    fn indices(&self) -> &Self::Indices {
        (**self).indices()
    }
}

impl<M, C> Indices for WithColors<M, C>
where
    M: Indices,
{
    type Indices = M::Indices;
    fn indices(&self) -> &Self::Indices {
        self.mesh.indices()
    }
}

impl<M, T, S> Indices for WithTexCoords<M, T, S>
where
    M: Indices,
{
    type Indices = M::Indices;
    fn indices(&self) -> &Self::Indices {
        self.mesh.indices()
    }
}

impl<M, N> Indices for WithNormals<M, N>
where
    M: Indices,
{
    type Indices = M::Indices;
    fn indices(&self) -> &Self::Indices {
        self.mesh.indices()
    }
}

// **Colors** implementations.

impl<M, C> Colors for WithColors<M, C>
where
    C: Channel,
{
    type Color = C::Element;
    type Colors = C;
    fn colors(&self) -> &Self::Colors {
        &self.colors
    }
}

impl<'a, M> Colors for &'a M
where
    M: Colors,
{
    type Color = M::Color;
    type Colors = M::Colors;
    fn colors(&self) -> &Self::Colors {
        (**self).colors()
    }
}

impl<'a, M> Colors for &'a mut M
where
    M: Colors,
{
    type Color = M::Color;
    type Colors = M::Colors;
    fn colors(&self) -> &Self::Colors {
        (**self).colors()
    }
}

impl<'a, M> Colors for Ref<'a, M>
where
    M: Colors,
{
    type Color = M::Color;
    type Colors = M::Colors;
    fn colors(&self) -> &Self::Colors {
        (**self).colors()
    }
}

impl<'a, M> Colors for RefMut<'a, M>
where
    M: Colors,
{
    type Color = M::Color;
    type Colors = M::Colors;
    fn colors(&self) -> &Self::Colors {
        (**self).colors()
    }
}

impl<M, I> Colors for WithIndices<M, I>
where
    M: Colors,
{
    type Color = M::Color;
    type Colors = M::Colors;
    fn colors(&self) -> &Self::Colors {
        self.mesh.colors()
    }
}

impl<M, T, S> Colors for WithTexCoords<M, T, S>
where
    M: Colors,
{
    type Color = M::Color;
    type Colors = M::Colors;
    fn colors(&self) -> &Self::Colors {
        self.mesh.colors()
    }
}

impl<M, N> Colors for WithNormals<M, N>
where
    M: Colors,
{
    type Color = M::Color;
    type Colors = M::Colors;
    fn colors(&self) -> &Self::Colors {
        self.mesh.colors()
    }
}

// **TexCoords** implementations.

impl<M, T, S> TexCoords for WithTexCoords<M, T, S>
where
    T: Channel<Element = Point2<S>>,
    S: BaseFloat,
{
    type TexCoordScalar = S;
    type TexCoords = T;
    fn tex_coords(&self) -> &Self::TexCoords {
        &self.tex_coords
    }
}

impl<'a, M> TexCoords for &'a M
where
    M: TexCoords,
{
    type TexCoordScalar = M::TexCoordScalar;
    type TexCoords = M::TexCoords;
    fn tex_coords(&self) -> &Self::TexCoords {
        (**self).tex_coords()
    }
}

impl<'a, M> TexCoords for &'a mut M
where
    M: TexCoords,
{
    type TexCoordScalar = M::TexCoordScalar;
    type TexCoords = M::TexCoords;
    fn tex_coords(&self) -> &Self::TexCoords {
        (**self).tex_coords()
    }
}

impl<'a, M> TexCoords for Ref<'a, M>
where
    M: TexCoords,
{
    type TexCoordScalar = M::TexCoordScalar;
    type TexCoords = M::TexCoords;
    fn tex_coords(&self) -> &Self::TexCoords {
        (**self).tex_coords()
    }
}

impl<'a, M> TexCoords for RefMut<'a, M>
where
    M: TexCoords,
{
    type TexCoordScalar = M::TexCoordScalar;
    type TexCoords = M::TexCoords;
    fn tex_coords(&self) -> &Self::TexCoords {
        (**self).tex_coords()
    }
}

impl<M, I> TexCoords for WithIndices<M, I>
where
    M: TexCoords,
{
    type TexCoordScalar = M::TexCoordScalar;
    type TexCoords = M::TexCoords;
    fn tex_coords(&self) -> &Self::TexCoords {
        self.mesh.tex_coords()
    }
}

impl<M, C> TexCoords for WithColors<M, C>
where
    M: TexCoords,
{
    type TexCoordScalar = M::TexCoordScalar;
    type TexCoords = M::TexCoords;
    fn tex_coords(&self) -> &Self::TexCoords {
        self.mesh.tex_coords()
    }
}

impl<M, N> TexCoords for WithNormals<M, N>
where
    M: TexCoords,
{
    type TexCoordScalar = M::TexCoordScalar;
    type TexCoords = M::TexCoords;
    fn tex_coords(&self) -> &Self::TexCoords {
        self.mesh.tex_coords()
    }
}

// **Normals** implementations.

impl<M, N> Normals for WithNormals<M, N>
where
    M: Points,
    M::Point: EuclideanSpace,
    N: Channel<Element = <M::Point as EuclideanSpace>::Diff>,
{
    type Normals = N;
    fn normals(&self) -> &Self::Normals {
        &self.normals
    }
}

impl<'a, M> Normals for &'a M
where
    M: Normals,
    M::Point: EuclideanSpace,
{
    type Normals = M::Normals;
    fn normals(&self) -> &Self::Normals {
        (**self).normals()
    }
}

impl<'a, M> Normals for &'a mut M
where
    M: Normals,
    M::Point: EuclideanSpace,
{
    type Normals = M::Normals;
    fn normals(&self) -> &Self::Normals {
        (**self).normals()
    }
}

impl<'a, M> Normals for Ref<'a, M>
where
    M: Normals,
    M::Point: EuclideanSpace,
{
    type Normals = M::Normals;
    fn normals(&self) -> &Self::Normals {
        (**self).normals()
    }
}

impl<'a, M> Normals for RefMut<'a, M>
where
    M: Normals,
    M::Point: EuclideanSpace,
{
    type Normals = M::Normals;
    fn normals(&self) -> &Self::Normals {
        (**self).normals()
    }
}

impl<M, I> Normals for WithIndices<M, I>
where
    M: Normals,
    M::Point: EuclideanSpace,
{
    type Normals = M::Normals;
    fn normals(&self) -> &Self::Normals {
        self.mesh.normals()
    }
}

impl<M, C> Normals for WithColors<M, C>
where
    M: Normals,
    M::Point: EuclideanSpace,
{
    type Normals = M::Normals;
    fn normals(&self) -> &Self::Normals {
        self.mesh.normals()
    }
}

impl<M, T, S> Normals for WithTexCoords<M, T, S>
where
    M: Normals,
    M::Point: EuclideanSpace,
{
    type Normals = M::Normals;
    fn normals(&self) -> &Self::Normals {
        self.mesh.normals()
    }
}

// PushVertex implementations for each mesh type where the channels are **Vec**s.

impl<'a, M, V> PushVertex<V> for &'a mut M
where
    M: PushVertex<V>,
{
    fn push_vertex(&mut self, v: V) {
        (**self).push_vertex(v)
    }
}

impl<'a, M, V> PushVertex<V> for RefMut<'a, M>
where
    M: PushVertex<V>,
{
    fn push_vertex(&mut self, v: V) {
        (**self).push_vertex(v)
    }
}

impl<V> PushVertex<V> for MeshPoints<Vec<V>> {
    fn push_vertex(&mut self, v: V) {
        self.points.push(v);
    }
}

impl<M, V> PushVertex<V> for WithIndices<M, Vec<usize>>
where
    M: PushVertex<V>,
{
    fn push_vertex(&mut self, v: V) {
        self.mesh.push_vertex(v);
    }
}

impl<M, V, C> PushVertex<vertex::WithColor<V, C>> for WithColors<M, Vec<C>>
where
    M: PushVertex<V>,
{
    fn push_vertex(&mut self, v: vertex::WithColor<V, C>) {
        let vertex::WithColor { vertex, color } = v;
        self.colors.push(color);
        self.mesh.push_vertex(vertex);
    }
}

impl<M, V, T, S> PushVertex<vertex::WithTexCoords<V, T>> for WithTexCoords<M, Vec<T>, S>
where
    M: PushVertex<V>,
{
    fn push_vertex(&mut self, v: vertex::WithTexCoords<V, T>) {
        let vertex::WithTexCoords { vertex, tex_coords } = v;
        self.tex_coords.push(tex_coords);
        self.mesh.push_vertex(vertex);
    }
}

impl<M, V, N> PushVertex<vertex::WithNormal<V, N>> for WithNormals<M, Vec<N>>
where
    M: PushVertex<V>,
{
    fn push_vertex(&mut self, v: vertex::WithNormal<V, N>) {
        let vertex::WithNormal { vertex, normal } = v;
        self.normals.push(normal);
        self.mesh.push_vertex(vertex);
    }
}

// PushIndex implementations for meshes.

impl<'a, M> PushIndex for &'a mut M
where
    M: PushIndex,
{
    fn push_index(&mut self, index: usize) {
        (**self).push_index(index);
    }
    fn extend_indices<I>(&mut self, indices: I)
    where
        I: IntoIterator<Item = usize>,
    {
        (**self).extend_indices(indices);
    }
}

impl<'a, M> PushIndex for RefMut<'a, M>
where
    M: PushIndex,
{
    fn push_index(&mut self, index: usize) {
        (**self).push_index(index);
    }
    fn extend_indices<I>(&mut self, indices: I)
    where
        I: IntoIterator<Item = usize>,
    {
        (**self).extend_indices(indices);
    }
}

impl<M> PushIndex for WithIndices<M, Vec<usize>> {
    fn push_index(&mut self, index: usize) {
        self.indices.push(index);
    }

    fn extend_indices<I>(&mut self, indices: I)
    where
        I: IntoIterator<Item = usize>,
    {
        self.indices.extend(indices);
    }
}

impl<M, C> PushIndex for WithColors<M, C>
where
    M: PushIndex,
{
    fn push_index(&mut self, index: usize) {
        self.mesh.push_index(index);
    }

    fn extend_indices<I>(&mut self, indices: I)
    where
        I: IntoIterator<Item = usize>,
    {
        self.mesh.extend_indices(indices);
    }
}

impl<M, T, S> PushIndex for WithTexCoords<M, T, S>
where
    M: PushIndex,
{
    fn push_index(&mut self, index: usize) {
        self.mesh.push_index(index);
    }

    fn extend_indices<I>(&mut self, indices: I)
    where
        I: IntoIterator<Item = usize>,
    {
        self.mesh.extend_indices(indices);
    }
}

impl<M, N> PushIndex for WithNormals<M, N>
where
    M: PushIndex,
{
    fn push_index(&mut self, index: usize) {
        self.mesh.push_index(index);
    }

    fn extend_indices<I>(&mut self, indices: I)
    where
        I: IntoIterator<Item = usize>,
    {
        self.mesh.extend_indices(indices);
    }
}

// **ClearIndices** implementations

impl<'a, M> ClearIndices for &'a mut M
where
    M: ClearIndices,
{
    fn clear_indices(&mut self) {
        (**self).clear_indices();
    }
}

impl<'a, M> ClearIndices for RefMut<'a, M>
where
    M: ClearIndices,
{
    fn clear_indices(&mut self) {
        (**self).clear_indices();
    }
}

impl<M> ClearIndices for WithIndices<M, Vec<usize>> {
    fn clear_indices(&mut self) {
        self.indices.clear();
    }
}

impl<M, C> ClearIndices for WithColors<M, C>
where
    M: ClearIndices,
{
    fn clear_indices(&mut self) {
        self.mesh.clear_indices();
    }
}

impl<M, T, S> ClearIndices for WithTexCoords<M, T, S>
where
    M: ClearIndices,
{
    fn clear_indices(&mut self) {
        self.mesh.clear_indices();
    }
}

impl<M, N> ClearIndices for WithNormals<M, N>
where
    M: ClearIndices,
{
    fn clear_indices(&mut self) {
        self.mesh.clear_indices();
    }
}

// **ClearVertices** implementations

impl<'a, M> ClearVertices for &'a mut M
where
    M: ClearVertices,
{
    fn clear_vertices(&mut self) {
        (**self).clear_vertices()
    }
}

impl<'a, M> ClearVertices for RefMut<'a, M>
where
    M: ClearVertices,
{
    fn clear_vertices(&mut self) {
        (**self).clear_vertices()
    }
}

impl<V> ClearVertices for MeshPoints<Vec<V>> {
    fn clear_vertices(&mut self) {
        self.points.clear();
    }
}

impl<M> ClearVertices for WithIndices<M, Vec<usize>>
where
    M: ClearVertices,
{
    fn clear_vertices(&mut self) {
        self.mesh.clear_vertices();
        self.indices.clear();
    }
}

impl<M, C> ClearVertices for WithColors<M, Vec<C>>
where
    M: ClearVertices,
{
    fn clear_vertices(&mut self) {
        self.mesh.clear_vertices();
        self.colors.clear();
    }
}

impl<M, T, S> ClearVertices for WithTexCoords<M, Vec<T>, S>
where
    M: ClearVertices,
{
    fn clear_vertices(&mut self) {
        self.mesh.clear_vertices();
        self.tex_coords.clear();
    }
}

impl<M, N> ClearVertices for WithNormals<M, Vec<N>>
where
    M: ClearVertices,
{
    fn clear_vertices(&mut self) {
        self.mesh.clear_vertices();
        self.normals.clear();
    }
}

// **Clear** implementation for all meshes.

impl<T> Clear for T where T: ClearIndices + ClearVertices {}

// **Default** implementations for all meshes.

impl<P> Default for MeshPoints<P>
where
    P: Default,
{
    fn default() -> Self {
        let points = Default::default();
        MeshPoints { points }
    }
}

impl<M, I> Default for WithIndices<M, I>
where
    M: Default,
    I: Default,
{
    fn default() -> Self {
        let mesh = Default::default();
        let indices = Default::default();
        WithIndices { mesh, indices }
    }
}

impl<M, C> Default for WithColors<M, C>
where
    M: Default,
    C: Default,
{
    fn default() -> Self {
        let mesh = Default::default();
        let colors = Default::default();
        WithColors { mesh, colors }
    }
}

impl<M, T, S> Default for WithTexCoords<M, T, S>
where
    M: Default,
    T: Default,
{
    fn default() -> Self {
        let mesh = Default::default();
        let tex_coords = Default::default();
        let _tex_coord_scalar = PhantomData;
        WithTexCoords {
            mesh,
            tex_coords,
            _tex_coord_scalar,
        }
    }
}

impl<M, N> Default for WithNormals<M, N>
where
    M: Default,
    N: Default,
{
    fn default() -> Self {
        let mesh = Default::default();
        let normals = Default::default();
        WithNormals { mesh, normals }
    }
}

// Deref implementations for the mesh adaptor types to their inner mesh.

impl<M, I> Deref for WithIndices<M, I> {
    type Target = M;
    fn deref(&self) -> &Self::Target {
        &self.mesh
    }
}

impl<M, I> DerefMut for WithIndices<M, I> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.mesh
    }
}

impl<M, C> Deref for WithColors<M, C> {
    type Target = M;
    fn deref(&self) -> &Self::Target {
        &self.mesh
    }
}

impl<M, C> DerefMut for WithColors<M, C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.mesh
    }
}

impl<M, T, S> Deref for WithTexCoords<M, T, S> {
    type Target = M;
    fn deref(&self) -> &Self::Target {
        &self.mesh
    }
}

impl<M, T, S> DerefMut for WithTexCoords<M, T, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.mesh
    }
}

impl<M, N> Deref for WithNormals<M, N> {
    type Target = M;
    fn deref(&self) -> &Self::Target {
        &self.mesh
    }
}

impl<M, N> DerefMut for WithNormals<M, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.mesh
    }
}

// Mesh length functions.

/// Get the number of vertices in the mesh.
pub fn raw_vertex_count<M>(mesh: M) -> usize
where
    M: Points,
{
    mesh.points().channel().len()
}

/// The number of vertices that would be yielded by a **Vertices** iterator for the given mesh.
pub fn vertex_count<M>(mesh: M) -> usize
where
    M: Indices,
{
    mesh.indices().channel().len()
}

/// The number of triangles that would be yielded by a **Triangles** iterator for the given mesh.
pub fn triangle_count<M>(mesh: M) -> usize
where
    M: Indices,
{
    vertex_count(mesh) / geom::tri::NUM_VERTICES as usize
}

// Mesh constructors.

/// Create a simple base mesh from the given channel of vertex points.
pub fn from_points<P>(points: P) -> MeshPoints<P>
where
    P: Channel,
    P::Element: geom::Vertex,
{
    MeshPoints { points }
}

/// Combine the given mesh with the given channel of vertex indices.
pub fn with_indices<M, I>(mesh: M, indices: I) -> WithIndices<M, I>
where
    M: GetVertex,
    I: Channel<Element = usize>,
{
    WithIndices { mesh, indices }
}

/// Combine the given mesh with the given channel of vertex colors.
///
/// **Panics** if the length of the **colors** channel differs from **points**.
pub fn with_colors<M, C>(mesh: M, colors: C) -> WithColors<M, C>
where
    M: Points,
    C: Channel,
{
    assert_eq!(raw_vertex_count(&mesh), colors.channel().len());
    WithColors { mesh, colors }
}

/// Combine the given mesh with the given channel of vertex texture coordinates.
///
/// **Panics** if the length of the **tex_coords** channel differs from **points**.
pub fn with_tex_coords<M, T, S>(mesh: M, tex_coords: T) -> WithTexCoords<M, T, S>
where
    M: Points,
    T: Channel<Element = Point2<S>>,
    S: BaseFloat,
{
    assert_eq!(raw_vertex_count(&mesh), tex_coords.channel().len());
    let _tex_coord_scalar = PhantomData;
    WithTexCoords {
        mesh,
        tex_coords,
        _tex_coord_scalar,
    }
}

/// Combine the given mesh with the given **Normals** channel.
///
/// **Panics** if the length of the **normals** channel differs from **points**.
pub fn with_normals<M, N>(mesh: M, normals: N) -> WithNormals<M, N>
where
    M: Points,
    M::Point: EuclideanSpace,
    N: Channel<Element = <M::Point as EuclideanSpace>::Diff>,
{
    assert_eq!(raw_vertex_count(&mesh), normals.channel().len());
    WithNormals { mesh, normals }
}

// Mesh mutation functions.

/// Push the given vertex to the given `mesh`.
///
/// The lengths of all non-index channels within the mesh should remain equal before and after a
/// call to this function.
pub fn push_vertex<M, V>(mut mesh: M, vertex: V)
where
    M: PushVertex<V>,
{
    mesh.push_vertex(vertex);
}

/// Extend the given **mesh** with the given sequence of **vertices**.
///
/// The lengths of all non-index channels within the mesh should remain equal before and after a
/// call to this function.
pub fn extend_vertices<M, I>(mut mesh: M, vertices: I)
where
    M: PushVertex<I::Item>,
    I: IntoIterator,
{
    for v in vertices {
        push_vertex(&mut mesh, v);
    }
}

/// Push the given index to the given `mesh`.
pub fn push_index<M>(mut mesh: M, index: usize)
where
    M: PushIndex,
{
    mesh.push_index(index);
}

/// Extend the given mesh with the given indices.
pub fn extend_indices<M, I>(mut mesh: M, indices: I)
where
    M: PushIndex,
    I: IntoIterator<Item = usize>,
{
    mesh.extend_indices(indices);
}

/// Clear all vertices from the mesh.
pub fn clear_vertices<M>(mut mesh: M)
where
    M: ClearVertices,
{
    mesh.clear_vertices();
}

/// Clear all indices from the mesh.
pub fn clear_indices<M>(mut mesh: M)
where
    M: ClearIndices,
{
    mesh.clear_indices();
}

/// Clear all vertices and indices from the mesh.
pub fn clear<M>(mut mesh: M)
where
    M: Clear,
{
    mesh.clear();
}

// Mesh iterators.

/// An iterator yielding the raw vertices (with combined channels) of a mesh.
///
/// Requires that the mesh implements **GetVertex**.
///
/// Returns `None` when the inner mesh first returns `None` for a call to **GetVertex::get_vertex**.
#[derive(Clone, Debug)]
pub struct RawVertices<M> {
    range: ops::Range<usize>,
    mesh: M,
}

/// An iterator yielding vertices in the order specified via the mesh's **Indices** channel.
///
/// Requires that the mesh implements **Indices** and **GetVertex**.
///
/// Returns `None` when a vertex has been yielded for every index in the **Indices** channel.
///
/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
/// vertices.
#[derive(Clone, Debug)]
pub struct Vertices<M> {
    index_range: ops::Range<usize>,
    mesh: M,
}

/// An iterator yielding triangles in the order specified via the mesh's **Indices** channel.
///
/// Requires that the mesh implements **Indices** and **GetVertex**.
///
/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
pub type Triangles<M> = geom::tri::IterFromVertices<Vertices<M>>;

/// An iterator yielding the raw vertices (with combined channels) of a mesh.
///
/// Requires that the inner mesh implements **GetVertex**.
///
/// Returns `None` when the inner mesh first returns `None` for a call to **GetVertex::get_vertex**.
pub fn raw_vertices<M>(mesh: M) -> RawVertices<M>
where
    M: Points + GetVertex,
{
    let range = 0..raw_vertex_count(&mesh);
    RawVertices { range, mesh }
}

/// Produce an iterator yielding vertices in the order specified via the mesh's **Indices**
/// channel.
///
/// Requires that the mesh implements **Indices** and **GetVertex**.
///
/// Returns `None` when a vertex has been yielded for every index in the **Indices** channel.
///
/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
/// vertices.
pub fn vertices<M>(mesh: M) -> Vertices<M>
where
    M: Indices + GetVertex,
{
    let index_range = 0..mesh.indices().channel().len();
    Vertices { index_range, mesh }
}

/// Produce an iterator yielding triangles for every three vertices yielded in the order specified
/// via the mesh's **Indices** channel.
///
/// Requires that the mesh implements **Indices** and **GetVertex**.
///
/// Returns `None` when there are no longer enough vertex indices to produce a triangle.
///
/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
/// vertices.
pub fn triangles<M>(mesh: M) -> Triangles<M>
where
    M: Indices + GetVertex,
{
    geom::tri::iter_from_vertices(vertices(mesh))
}

// The error message produced when the `Vertices` iterator panics due to an out of bound index.
const NO_VERTEX_FOR_INDEX: &'static str =
    "no vertex for the index produced by the mesh's indices channel";

impl<M> RawVertices<M> {
    /// Specify a range of raw vertices to yield.
    pub fn range(mut self, range: ops::Range<usize>) -> Self {
        self.range = range;
        self
    }
}

impl<M> Vertices<M> {
    /// Specify the range of vertex indices to yield vertices from.
    pub fn index_range(mut self, range: ops::Range<usize>) -> Self {
        self.index_range = range;
        self
    }

    /// Convert this iterator yielding vertices into an iterator yielding triangles for every three
    /// vertices yielded.
    pub fn triangles(self) -> Triangles<M>
    where
        M: GetVertex + Indices,
    {
        geom::tri::iter_from_vertices(self)
    }
}

impl<M> Iterator for RawVertices<M>
where
    M: GetVertex,
{
    type Item = M::Vertex;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(vertex) = self.range.next().and_then(|i| self.mesh.get_vertex(i)) {
            return Some(vertex);
        }
        None
    }
}

impl<M> Iterator for Vertices<M>
where
    M: Indices + GetVertex,
{
    type Item = M::Vertex;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(i) = self.index_range.next() {
            if let Some(&index) = self.mesh.indices().channel().get(i) {
                let vertex = self.mesh.get_vertex(index).expect(NO_VERTEX_FOR_INDEX);
                return Some(vertex);
            }
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}

impl<M> ExactSizeIterator for RawVertices<M>
where
    M: GetVertex,
{
    fn len(&self) -> usize {
        self.range.len()
    }
}

impl<M> DoubleEndedIterator for Vertices<M>
where
    M: Indices + GetVertex,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        if let Some(i) = self.index_range.next_back() {
            if let Some(&index) = self.mesh.indices().channel().get(i) {
                let vertex = self.mesh.get_vertex(index).expect(NO_VERTEX_FOR_INDEX);
                return Some(vertex);
            }
        }
        None
    }
}

impl<M> ExactSizeIterator for Vertices<M>
where
    M: Indices + GetVertex,
{
    fn len(&self) -> usize {
        let indices_len = self.mesh.indices().channel().len();
        let remaining_indices = indices_len - self.index_range.start;
        let range_len = self.index_range.len();
        cmp::min(remaining_indices, range_len)
    }
}