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
//! Linear representation of meshes.
//!
//! This module provides a `MeshBuffer` that represents a mesh as a linear
//! collection of vertex geometry and an ordered collection of indices into
//! that vertex geometry. These two buffers are called the _vertex buffer_ and
//! _index buffer_, respectively. `MeshBuffer` combines these buffers and
//! exposes them as slices. This layout is well-suited for graphics pipelines.
//!
//! # Vertex Buffers
//!
//! Vertex buffers describe the geometry of a `MeshBuffer`. Only vertex
//! geometry is supported; there is no way to associate geometry with an edge
//! nor face, for example.
//!
//! `MeshBuffer`s use _composite_ vertex buffers. Each element of the vertex
//! buffer completely describes the geometry of that vertex. For example, if
//! each vertex is described by a position and color attribute, then each
//! element in the vertex buffer contains both attributes within a single
//! structure. _Component_ buffers, which store attributes in separate buffers,
//! are not supported.
//!
//! # Index Buffers
//!
//! Index buffers describe the topology of a `MeshBuffer`. Both _structured_
//! and _flat_ index buffers are supported. See the `index` module for more
//! information about index buffer formats.
//!
//! The `MeshBuffer3` and `MeshBufferN` type definitions avoid verbose type
//! parameters and provide the most common index buffer configurations.
//!
//! # Examples
//!
//! Generating a flat `MeshBuffer` from a $uv$-sphere:
//!
//! ```rust
//! # extern crate decorum;
//! # extern crate nalgebra;
//! # extern crate plexus;
//! #
//! use decorum::N32;
//! use nalgebra::Point3;
//! use plexus::buffer::MeshBuffer3;
//! use plexus::prelude::*;
//! use plexus::primitive::generate::Position;
//! use plexus::primitive::sphere::UvSphere;
//!
//! # fn main() {
//! let buffer = UvSphere::new(16, 16)
//!     .polygons::<Position<Point3<N32>>>()
//!     .triangulate()
//!     .collect::<MeshBuffer3<u32, Point3<f32>>>();
//! let indices = buffer.as_index_slice();
//! let positions = buffer.as_vertex_slice();
//! # }
//! ```
//!
//! Converting a `MeshGraph` to a flat `MeshBuffer`:
//!
//! ```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;
//! use plexus::U4;
//!
//! # fn main() {
//! let graph = Cube::new()
//!     .polygons::<Position<Point3<N64>>>()
//!     .collect::<MeshGraph<Point3<N64>>>();
//! let buffer = graph
//!     .to_mesh_buffer_by_vertex::<U4, usize, Point3<N64>>()
//!     .unwrap();
//! # }
//! ```

use itertools::Itertools;
use num::{Integer, NumCast, ToPrimitive, Unsigned};
use std::hash::Hash;
use std::iter::FromIterator;
use theon::ops::Map;
use theon::FromItems;
use thiserror::Error;
use typenum::{self, NonZero, Unsigned as _, U3, U4};

use crate::encoding::{FaceDecoder, FromEncoding, VertexDecoder};
use crate::index::{
    Flat, Flat3, Flat4, FromIndexer, Grouping, HashIndexer, IndexBuffer, IndexVertices, Indexer,
    Push,
};
use crate::primitive::decompose::IntoVertices;
use crate::primitive::{Polygon, Polygonal, Tetragon, Topological, Trigon};
use crate::IntoGeometry;
use crate::{Arity, FromRawBuffers};

#[derive(Debug, Error, PartialEq)]
pub enum BufferError {
    #[error("index into vertex data out of bounds")]
    IndexOutOfBounds,
    #[error("conflicting arity")]
    ArityConflict,
}

/// Alias for a flat and triangular `MeshBuffer`. Prefer this alias.
///
/// For most applications, this alias can be used to avoid more complex and
/// verbose type parameters. Flat and triangular index buffers are most common
/// and should generally be preferred.
pub type MeshBuffer3<N, G> = MeshBuffer<Flat3<N>, G>;
/// Alias for a flat and quadrilateral `MeshBuffer`.
pub type MeshBuffer4<N, G> = MeshBuffer<Flat4<N>, G>;

/// Alias for a structured and polygonal `MeshBuffer`.
pub type MeshBufferN<N, G> = MeshBuffer<Polygon<N>, G>;

pub trait IntoFlatIndex<A, G>
where
    A: NonZero + typenum::Unsigned,
{
    type Item: Copy + Integer + NumCast + Unsigned;

    fn into_flat_index(self) -> MeshBuffer<Flat<A, Self::Item>, G>;
}

pub trait IntoStructuredIndex<G>
where
    <Self::Item as Topological>::Vertex: Copy + Integer + NumCast + Unsigned,
{
    type Item: Polygonal;

    fn into_structured_index(self) -> MeshBuffer<Self::Item, G>;
}

/// Linear representation of a mesh.
///
/// A `MeshBuffer` is a linear representation of a mesh that is composed of two
/// separate buffers: an _index buffer_ and a _vertex buffer_. The index buffer
/// contains ordered indices into the data in the vertex buffer and describes
/// the topology of the mesh. The vertex buffer contains arbitrary geometric
/// data.
///
/// See the module documention for more information.
#[derive(Debug)]
pub struct MeshBuffer<R, G>
where
    R: Grouping,
{
    indices: Vec<R::Item>,
    vertices: Vec<G>,
}

impl<R, G> MeshBuffer<R, G>
where
    R: Grouping,
    Vec<R::Item>: IndexBuffer<R>,
{
    /// Creates an empty `MeshBuffer`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use plexus::buffer::MeshBuffer;
    /// use plexus::index::Flat3;
    ///
    /// let buffer = MeshBuffer::<Flat3<u64>, (f64, f64, f64)>::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    pub fn arity(&self) -> Arity {
        self.indices.arity()
    }
}

impl<R, G> MeshBuffer<R, G>
where
    R: Grouping,
{
    pub fn into_raw_buffers(self) -> (Vec<R::Item>, Vec<G>) {
        let MeshBuffer { indices, vertices } = self;
        (indices, vertices)
    }

    /// Maps over the vertex data in a `MeshBuffer`.
    ///
    /// # Examples
    ///
    /// Translating the position data in a buffer:
    ///
    /// ```rust
    /// # extern crate decorum;
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use decorum::N64;
    /// use nalgebra::{Point3, Vector3};
    /// use plexus::buffer::MeshBuffer3;
    /// use plexus::prelude::*;
    /// use plexus::primitive::generate::Position;
    /// use plexus::primitive::sphere::UvSphere;
    ///
    /// # fn main() {
    /// let buffer = UvSphere::new(16, 8)
    ///     .polygons::<Position<Point3<N64>>>()
    ///     .triangulate()
    ///     .collect::<MeshBuffer3<usize, Point3<f64>>>();
    /// // Translate the positions.
    /// let translation = Vector3::<f64>::x() * 2.0;
    /// let buffer = buffer.map_vertices_into(|position| position + translation);
    /// # }
    /// ```
    pub fn map_vertices_into<H, F>(self, f: F) -> MeshBuffer<R, H>
    where
        F: FnMut(G) -> H,
    {
        let (indices, vertices) = self.into_raw_buffers();
        MeshBuffer {
            indices,
            vertices: vertices.into_iter().map(f).collect::<Vec<_>>(),
        }
    }

    /// Gets a slice of the index data.
    pub fn as_index_slice(&self) -> &[R::Item] {
        self.indices.as_slice()
    }

    /// Gets a slice of the vertex data.
    pub fn as_vertex_slice(&self) -> &[G] {
        self.vertices.as_slice()
    }
}

impl<R, G> Default for MeshBuffer<R, G>
where
    R: Grouping,
    Vec<R::Item>: IndexBuffer<R>,
{
    fn default() -> Self {
        MeshBuffer {
            indices: Default::default(),
            vertices: Default::default(),
        }
    }
}

impl<A, N, G> MeshBuffer<Flat<A, N>, G>
where
    A: NonZero + typenum::Unsigned,
    N: Copy + Integer + NumCast + Unsigned,
{
    /// Appends the contents of a `MeshBuffer` into another `MeshBuffer`. The
    /// source buffer is drained.
    pub fn append<R, H>(&mut self, buffer: &mut MeshBuffer<R, H>)
    where
        R: Grouping,
        R::Item: Into<<Flat<A, N> as Grouping>::Item>,
        H: IntoGeometry<G>,
    {
        let offset = N::from(self.vertices.len()).unwrap();
        self.vertices.extend(
            buffer
                .vertices
                .drain(..)
                .map(|vertex| vertex.into_geometry()),
        );
        self.indices
            .extend(buffer.indices.drain(..).map(|index| index.into() + offset))
    }
}

impl<P, G> MeshBuffer<P, G>
where
    P: Grouping + Polygonal,
    P::Vertex: Copy + Integer + NumCast + Unsigned,
{
    /// Converts a structured `MeshBuffer` into an iterator of polygons
    /// containing vertex data.
    ///
    /// # Examples
    ///
    /// Mapping over the polygons described by a buffer:
    ///
    /// ```rust
    /// # extern crate decorum;
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use decorum::R64;
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBufferN;
    /// use plexus::graph::MeshGraph;
    /// use plexus::prelude::*;
    /// use plexus::primitive::generate::Position;
    /// use plexus::primitive::sphere::UvSphere;
    ///
    /// # fn main() {
    /// let buffer = UvSphere::new(8, 8)
    ///     .polygons::<Position<Point3<R64>>>()
    ///     .collect::<MeshBufferN<usize, Point3<R64>>>();
    /// let graph = buffer
    ///     .into_polygons()
    ///     .map_vertices(|position| position * 2.0.into())
    ///     .triangulate()
    ///     .collect::<MeshGraph<Point3<R64>>>();
    /// # }
    /// ```
    pub fn into_polygons(self) -> impl Iterator<Item = <<P as Grouping>::Item as Map<G>>::Output>
    where
        G: Clone,
        <P as Grouping>::Item: Map<G> + Topological,
        <<P as Grouping>::Item as Topological>::Vertex: ToPrimitive,
    {
        let (indices, vertices) = self.into_raw_buffers();
        indices
            .into_iter()
            .map(|polygon| {
                polygon.map(|index| vertices[<usize as NumCast>::from(index).unwrap()].clone())
            })
            .collect::<Vec<_>>()
            .into_iter()
    }

    /// Appends the contents of a `MeshBuffer` into another `MeshBuffer`. The
    /// source buffer is drained.
    pub fn append<R, H>(&mut self, buffer: &mut MeshBuffer<R, H>)
    where
        R: Grouping,
        R::Item: Into<<P as Grouping>::Item>,
        H: IntoGeometry<G>,
        <P as Grouping>::Item:
            Copy + Map<P::Vertex, Output = <P as Grouping>::Item> + Topological<Vertex = P::Vertex>,
    {
        let offset = <P::Vertex as NumCast>::from(self.vertices.len()).unwrap();
        self.vertices.extend(
            buffer
                .vertices
                .drain(..)
                .map(|vertex| vertex.into_geometry()),
        );
        self.indices.extend(
            buffer
                .indices
                .drain(..)
                .map(|topology| topology.into().map(|index| index + offset)),
        )
    }
}

impl<E, G> FromEncoding<E> for MeshBuffer<Polygon<usize>, G>
where
    E: FaceDecoder<Face = (), Index = Polygon<usize>> + VertexDecoder,
    E::Vertex: IntoGeometry<G>,
{
    type Error = BufferError;

    fn from_encoding(
        vertices: <E as VertexDecoder>::Output,
        faces: <E as FaceDecoder>::Output,
    ) -> Result<Self, Self::Error> {
        let indices = faces.into_iter().map(|(index, _)| index);
        let vertices = vertices.into_iter().map(|vertex| vertex.into_geometry());
        MeshBuffer::from_raw_buffers(indices, vertices)
    }
}

impl<R, P, G> FromIndexer<P, P> for MeshBuffer<R, G>
where
    R: Grouping,
    P: Map<<Vec<R::Item> as IndexBuffer<R>>::Index> + Topological,
    P::Output: Topological<Vertex = <Vec<R::Item> as IndexBuffer<R>>::Index>,
    P::Vertex: IntoGeometry<G>,
    Vec<R::Item>: Push<R, P::Output>,
    Self: FromRawBuffers<R::Item, G>,
{
    type Error = <Self as FromRawBuffers<R::Item, G>>::Error;

    fn from_indexer<I, M>(input: I, indexer: M) -> Result<Self, Self::Error>
    where
        I: IntoIterator<Item = P>,
        M: Indexer<P, P::Vertex>,
    {
        let (indices, vertices) = input.into_iter().index_vertices(indexer);
        MeshBuffer::<R, _>::from_raw_buffers(
            indices,
            vertices.into_iter().map(|vertex| vertex.into_geometry()),
        )
    }
}

impl<R, P, G> FromIterator<P> for MeshBuffer<R, G>
where
    R: Grouping,
    P: Topological,
    P::Vertex: Copy + Eq + Hash + IntoGeometry<G>,
    Vec<R::Item>: IndexBuffer<R>,
    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<A, N, M, G> FromRawBuffers<M, G> for MeshBuffer<Flat<A, N>, G>
where
    A: NonZero + typenum::Unsigned,
    N: Copy + Integer + NumCast + Unsigned,
    M: Copy + Integer + NumCast + Unsigned,
    <Flat<A, N> as Grouping>::Item: ToPrimitive,
{
    type Error = BufferError;

    /// Creates a flat `MeshBuffer` from raw index and vertex buffers.
    ///
    /// # Errors
    ///
    /// Returns an error if the index data is out of bounds within the vertex
    /// buffer or if the number of indices disagrees with the arity of the
    /// index buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate decorum;
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use decorum::N64;
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBuffer3;
    /// use plexus::index::{Flat3, HashIndexer};
    /// use plexus::prelude::*;
    /// use plexus::primitive;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::{Normal, Position};
    ///
    /// # fn main() {
    /// type E3 = Point3<N64>;
    ///
    /// let cube = Cube::new();
    /// let (indices, vertices) = primitive::zip_vertices((
    ///     cube.polygons::<Position<E3>>(),
    ///     cube.polygons::<Normal<E3>>()
    ///         .map_vertices(|normal| normal.into_inner()),
    /// ))
    /// .triangulate()
    /// .index_vertices::<Flat3, _>(HashIndexer::default());
    /// let buffer = MeshBuffer3::<usize, _>::from_raw_buffers(indices, vertices).unwrap();
    /// # }
    /// ```
    fn from_raw_buffers<I, J>(indices: I, vertices: J) -> Result<Self, BufferError>
    where
        I: IntoIterator<Item = M>,
        J: IntoIterator<Item = G>,
    {
        let indices = indices
            .into_iter()
            .map(|index| <<Flat<A, N> as Grouping>::Item as NumCast>::from(index).unwrap())
            .collect::<Vec<_>>();
        if indices.len() % A::USIZE != 0 {
            Err(BufferError::ArityConflict)
        }
        else {
            let vertices = vertices.into_iter().collect::<Vec<_>>();
            let len = N::from(vertices.len()).unwrap();
            if indices.iter().any(|index| *index >= len) {
                Err(BufferError::IndexOutOfBounds)
            }
            else {
                Ok(MeshBuffer { indices, vertices })
            }
        }
    }
}

impl<P, Q, G> FromRawBuffers<Q, G> for MeshBuffer<P, G>
where
    P: Grouping + Polygonal,
    P::Vertex: Copy + Integer + NumCast + Unsigned,
    Q: Into<<P as Grouping>::Item>,
    <P as Grouping>::Item: Copy + IntoVertices + Topological<Vertex = P::Vertex>,
{
    type Error = BufferError;

    /// Creates a structured `MeshBuffer` from raw index and vertex buffers.
    ///
    /// # Errors
    ///
    /// Returns an error if the index data is out of bounds within the vertex
    /// buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBufferN;
    /// use plexus::prelude::*;
    /// use plexus::primitive::generate::Position;
    /// use plexus::primitive::sphere::UvSphere;
    ///
    /// # fn main() {
    /// let sphere = UvSphere::new(8, 8);
    /// let buffer = MeshBufferN::<usize, _>::from_raw_buffers(
    ///     sphere.indexing_polygons::<Position>(),
    ///     sphere.vertices::<Position<Point3<f64>>>(),
    /// )
    /// .unwrap();
    /// # }
    /// ```
    fn from_raw_buffers<I, J>(indices: I, vertices: J) -> Result<Self, BufferError>
    where
        I: IntoIterator<Item = Q>,
        J: IntoIterator<Item = G>,
    {
        let indices = indices
            .into_iter()
            .map(|topology| topology.into())
            .collect::<Vec<_>>();
        let vertices = vertices
            .into_iter()
            .map(|geometry| geometry)
            .collect::<Vec<_>>();
        let is_out_of_bounds = {
            let len = <P::Vertex as NumCast>::from(vertices.len()).unwrap();
            indices.iter().any(|polygon| {
                polygon
                    .into_vertices()
                    .into_iter()
                    .any(|index| index >= len)
            })
        };
        if is_out_of_bounds {
            Err(BufferError::IndexOutOfBounds)
        }
        else {
            Ok(MeshBuffer { indices, vertices })
        }
    }
}

impl<A, N, G> IntoFlatIndex<A, G> for MeshBuffer<Flat<A, N>, G>
where
    A: NonZero + typenum::Unsigned,
    N: Copy + Integer + NumCast + Unsigned,
{
    type Item = N;

    fn into_flat_index(self) -> MeshBuffer<Flat<A, Self::Item>, G> {
        self
    }
}

impl<N, G> IntoFlatIndex<U3, G> for MeshBuffer<Trigon<N>, G>
where
    N: Copy + Integer + NumCast + Unsigned,
{
    type Item = N;

    /// Converts a structured index buffer into a flat index buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBuffer;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    /// use plexus::primitive::Trigon;
    ///
    /// # fn main() {
    /// let cube = Cube::new();
    /// let buffer = MeshBuffer::<Trigon<usize>, _>::from_raw_buffers(
    ///     cube.indexing_polygons::<Position>().triangulate(),
    ///     cube.vertices::<Position<Point3<f32>>>(),
    /// )
    /// .unwrap();
    /// let buffer = buffer.into_flat_index();
    /// for index in buffer.as_index_slice() {
    ///     // ...
    /// }
    /// # }
    /// ```
    fn into_flat_index(self) -> MeshBuffer<Flat<U3, Self::Item>, G> {
        let MeshBuffer { indices, vertices } = self;
        MeshBuffer {
            indices: indices
                .into_iter()
                .flat_map(|trigon| trigon.into_vertices())
                .collect(),
            vertices,
        }
    }
}

impl<N, G> IntoFlatIndex<U4, G> for MeshBuffer<Tetragon<N>, G>
where
    N: Copy + Integer + NumCast + Unsigned,
{
    type Item = N;

    /// Converts a structured index buffer into a flat index buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBuffer;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    /// use plexus::primitive::Tetragon;
    ///
    /// # fn main() {
    /// let cube = Cube::new();
    /// let buffer = MeshBuffer::<Tetragon<usize>, _>::from_raw_buffers(
    ///     cube.indexing_polygons::<Position>(),
    ///     cube.vertices::<Position<Point3<f64>>>(),
    /// )
    /// .unwrap();
    /// let buffer = buffer.into_flat_index();
    /// for index in buffer.as_index_slice() {
    ///     // ...
    /// }
    /// # }
    /// ```
    fn into_flat_index(self) -> MeshBuffer<Flat<U4, Self::Item>, G> {
        let MeshBuffer { indices, vertices } = self;
        MeshBuffer {
            indices: indices
                .into_iter()
                .flat_map(|tetragon| tetragon.into_vertices())
                .collect(),
            vertices,
        }
    }
}

impl<P, G> IntoStructuredIndex<G> for MeshBuffer<P, G>
where
    P: Grouping + Polygonal,
    P::Vertex: Copy + Integer + NumCast + Unsigned,
{
    type Item = P;

    fn into_structured_index(self) -> MeshBuffer<Self::Item, G> {
        self
    }
}

impl<N, G> IntoStructuredIndex<G> for MeshBuffer<Flat3<N>, G>
where
    N: Copy + Integer + NumCast + Unsigned,
    Trigon<N>: Grouping<Item = Trigon<N>>,
{
    type Item = Trigon<N>;

    /// Converts a flat index buffer into a structured index buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBuffer3;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    ///
    /// # fn main() {
    /// let cube = Cube::new();
    /// let buffer = MeshBuffer3::<usize, _>::from_raw_buffers(
    ///     cube.indexing_polygons::<Position>()
    ///         .triangulate()
    ///         .vertices(),
    ///     cube.vertices::<Position<Point3<f32>>>(),
    /// )
    /// .unwrap();
    /// let buffer = buffer.into_structured_index();
    /// for trigon in buffer.as_index_slice() {
    ///     // ...
    /// }
    /// # }
    /// ```
    fn into_structured_index(self) -> MeshBuffer<Self::Item, G> {
        let MeshBuffer { indices, vertices } = self;
        let indices = indices
            .into_iter()
            .chunks(U3::USIZE)
            .into_iter()
            .map(<Self::Item as Grouping>::Item::from_items)
            .collect::<Option<Vec<_>>>()
            .expect("inconsistent index buffer");
        MeshBuffer { indices, vertices }
    }
}

impl<N, G> IntoStructuredIndex<G> for MeshBuffer<Flat4<N>, G>
where
    N: Copy + Integer + NumCast + Unsigned,
    Tetragon<N>: Grouping<Item = Tetragon<N>>,
{
    type Item = Tetragon<N>;

    /// Converts a flat index buffer into a structured index buffer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate nalgebra;
    /// # extern crate plexus;
    /// #
    /// use nalgebra::Point3;
    /// use plexus::buffer::MeshBuffer4;
    /// use plexus::prelude::*;
    /// use plexus::primitive::cube::Cube;
    /// use plexus::primitive::generate::Position;
    ///
    /// # fn main() {
    /// let cube = Cube::new();
    /// let buffer = MeshBuffer4::<usize, _>::from_raw_buffers(
    ///     cube.indexing_polygons::<Position>().vertices(),
    ///     cube.vertices::<Position<Point3<f64>>>(),
    /// )
    /// .unwrap();
    /// let buffer = buffer.into_structured_index();
    /// for tetragon in buffer.as_index_slice() {
    ///     // ...
    /// }
    /// # }
    /// ```
    fn into_structured_index(self) -> MeshBuffer<Self::Item, G> {
        let MeshBuffer { indices, vertices } = self;
        let indices = indices
            .into_iter()
            .chunks(U4::USIZE)
            .into_iter()
            .map(<Self::Item as Grouping>::Item::from_items)
            .collect::<Option<Vec<_>>>()
            .expect("inconsistent index buffer");
        MeshBuffer { indices, vertices }
    }
}

#[cfg(test)]
mod tests {
    use decorum::N64;
    use nalgebra::Point3;
    use typenum::U3;

    use crate::buffer::{MeshBuffer, MeshBuffer3, MeshBufferN};
    use crate::graph::MeshGraph;
    use crate::prelude::*;
    use crate::primitive::cube::Cube;
    use crate::primitive::generate::Position;
    use crate::primitive::sphere::UvSphere;
    use crate::primitive::{Polygon, Tetragon};

    type E3 = Point3<N64>;

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

        assert_eq!(18, buffer.as_index_slice().len());
        assert_eq!(5, buffer.as_vertex_slice().len());
    }

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

        assert_eq!(6, buffer.as_index_slice().len());
        assert_eq!(5, buffer.as_vertex_slice().len());
    }

    #[test]
    fn append_structured_buffers() {
        let mut buffer = UvSphere::new(3, 2)
            .polygons::<Position<E3>>() // 6 triangles, 18 vertices.
            .collect::<MeshBuffer<Polygon<u32>, Point3<f64>>>();
        buffer.append(
            &mut Cube::new()
                .polygons::<Position<E3>>() // 6 quadrilaterals, 24 vertices.
                .collect::<MeshBuffer<Tetragon<u32>, Point3<f64>>>(),
        );

        assert_eq!(12, buffer.as_index_slice().len());
        assert_eq!(13, buffer.as_vertex_slice().len());
    }

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

        assert_eq!(18, buffer.as_index_slice().len());
        assert_eq!(5, buffer.as_vertex_slice().len());
    }

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

        assert_eq!(18, buffer.as_index_slice().len());
        assert_eq!(18, buffer.as_vertex_slice().len());
    }
}