nannou_mesh/
lib.rs

1//! An API for composing **Mesh**s. **Mesh**s may be composed of different sets of channels
2//! including position, color, texture-coordinate and normals. Note that this is quite a low-level
3//! representation. For a higher-level, graphics-related mesh API, see the `draw` module.
4
5use core::cell::{Ref, RefMut};
6use core::cmp;
7use core::convert::{TryFrom, TryInto};
8use core::ops::{self, Deref, DerefMut};
9use nannou_core::geom;
10
11pub mod channel;
12pub mod vertex;
13
14pub use self::channel::{Channel, ChannelMut};
15
16// Traits describing meshes with access to certain channels.
17
18/// Mesh types that can be indexed to produce a vertex.
19pub trait GetVertex<I> {
20    /// The vertex type representing all channels of data within the mesh at a single index.
21    type Vertex;
22    /// Create a vertex containing all channel properties for the given index.
23    fn get_vertex(&self, index: I) -> Option<Self::Vertex>;
24}
25
26/// All meshes must contain at least one vertex channel.
27pub trait Points {
28    /// The vertex type used to represent the location of a vertex.
29    type Point;
30    /// The channel type containing points.
31    type Points: Channel<Element = Self::Point>;
32    /// Borrow the vertex channel from the mesh.
33    fn points(&self) -> &Self::Points;
34}
35
36/// Meshes that contain a channel of indices that describe the edges between points.
37pub trait Indices {
38    /// The type used to index into the vertex buffer.
39    type Index;
40    /// The channel type containing indices.
41    type Indices: Channel<Element = Self::Index>;
42    /// Borrow the index channel from the mesh.
43    fn indices(&self) -> &Self::Indices;
44}
45
46/// Meshes that contain a channel of colors.
47pub trait Colors {
48    /// The color type stored within the channel.
49    type Color;
50    /// The channel type containing colors.
51    type Colors: Channel<Element = Self::Color>;
52    /// Borrow the color channel from the mesh.
53    fn colors(&self) -> &Self::Colors;
54}
55
56/// Meshes that contain a channel of texture coordinates.
57pub trait TexCoords {
58    /// The point type used to represent texture coordinates.
59    type TexCoord;
60    /// The channel type containing texture coordinates.
61    type TexCoords: Channel<Element = Self::TexCoord>;
62    /// Borrow the texture coordinate channel from the mesh.
63    fn tex_coords(&self) -> &Self::TexCoords;
64}
65
66/// Meshes that contain a channel of vertex normals.
67pub trait Normals {
68    /// The vector type used to represent the normal.
69    type Normal;
70    /// The channel type containing vertex normals.
71    type Normals: Channel<Element = Self::Normal>;
72    /// Borrow the normal channel from the mesh.
73    fn normals(&self) -> &Self::Normals;
74}
75
76/// Meshes that can push vertices of type **V** while keeping all non-index channels the same
77/// length before and after the push.
78pub trait PushVertex<V> {
79    /// Push the given vertex onto the mesh.
80    ///
81    /// Implementation requires that all non-index channels maintain the same length before and
82    /// after a call to this method.
83    fn push_vertex(&mut self, vertex: V);
84}
85
86/// Meshes that contain an **Indices** channel and can push new indices to it.
87pub trait PushIndex {
88    /// The inner index type.
89    type Index;
90    /// Push a new index onto the indices channel.
91    fn push_index(&mut self, index: Self::Index);
92    /// Extend the **Mesh**'s **Indices** channel with the given indices.
93    fn extend_indices<I>(&mut self, indices: I)
94    where
95        I: IntoIterator<Item = Self::Index>,
96    {
97        for i in indices {
98            self.push_index(i);
99        }
100    }
101}
102
103/// Meshes whose **Indices** channel can be cleared.
104pub trait ClearIndices {
105    /// Clear all indices from the mesh.
106    fn clear_indices(&mut self);
107}
108
109/// Meshes whose vertices channels can be cleared.
110pub trait ClearVertices {
111    /// Clear all vertices from the mesh.
112    fn clear_vertices(&mut self);
113}
114
115/// Meshes whose indices and vertices buffers may be cleared for re-use.
116pub trait Clear: ClearIndices + ClearVertices {
117    fn clear(&mut self) {
118        self.clear_indices();
119        self.clear_vertices();
120    }
121}
122
123/// Meshes that may be extended from a slice of data.
124pub trait ExtendFromSlice<'a> {
125    /// The slice type expected via the mesh.
126    ///
127    /// Note: This may be multiple combined slices if the mesh contains multiple channels of data.
128    type Slice: 'a;
129    /// Extend the mesh.
130    fn extend_from_slice(&mut self, slice: Self::Slice);
131}
132
133// Mesh types.
134
135/// The base mesh type with only a single vertex channel.
136///
137/// Extra channels can be added to the mesh via the `WithIndices`, `WithColors`, `WithTexCoords`
138/// and `WithNormals` adaptor types.
139#[derive(Copy, Clone, Debug, PartialEq)]
140pub struct MeshPoints<P> {
141    points: P,
142}
143
144/// A mesh type with an added channel containing indices describing the edges between vertices.
145#[derive(Copy, Clone, Debug, PartialEq)]
146pub struct WithIndices<M, I> {
147    mesh: M,
148    indices: I,
149}
150
151/// A `Mesh` type with an added channel containing colors.
152#[derive(Copy, Clone, Debug, PartialEq)]
153pub struct WithColors<M, C> {
154    mesh: M,
155    colors: C,
156}
157
158/// A `Mesh` type with an added channel containing texture coordinates.
159#[derive(Copy, Clone, Debug, PartialEq)]
160pub struct WithTexCoords<M, T> {
161    mesh: M,
162    tex_coords: T,
163}
164
165/// A `Mesh` type with an added channel containing vertex normals.
166#[derive(Copy, Clone, Debug, PartialEq)]
167pub struct WithNormals<M, N> {
168    mesh: M,
169    normals: N,
170}
171
172// **GetVertex** implementations.
173
174impl<'a, M, I> GetVertex<I> for &'a M
175where
176    M: GetVertex<I>,
177{
178    type Vertex = M::Vertex;
179    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
180        (**self).get_vertex(index)
181    }
182}
183
184impl<'a, M, I> GetVertex<I> for &'a mut M
185where
186    M: GetVertex<I>,
187{
188    type Vertex = M::Vertex;
189    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
190        (**self).get_vertex(index)
191    }
192}
193
194impl<'a, M, I> GetVertex<I> for Ref<'a, M>
195where
196    M: GetVertex<I>,
197{
198    type Vertex = M::Vertex;
199    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
200        (**self).get_vertex(index)
201    }
202}
203
204impl<'a, M, I> GetVertex<I> for RefMut<'a, M>
205where
206    M: GetVertex<I>,
207{
208    type Vertex = M::Vertex;
209    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
210        (**self).get_vertex(index)
211    }
212}
213
214impl<P, I> GetVertex<I> for MeshPoints<P>
215where
216    P: Channel,
217    P::Element: Clone,
218    I: TryInto<usize>,
219{
220    type Vertex = P::Element;
221    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
222        let index = index
223            .try_into()
224            .unwrap_or_else(|_err| panic!("index out of range of valid `usize` values"));
225        self.points.channel().get(index).map(|p| p.clone())
226    }
227}
228
229impl<M, I, Ix> GetVertex<Ix> for WithIndices<M, I>
230where
231    M: GetVertex<Ix>,
232{
233    type Vertex = M::Vertex;
234    fn get_vertex(&self, index: Ix) -> Option<Self::Vertex> {
235        self.mesh.get_vertex(index)
236    }
237}
238
239impl<M, C, I> GetVertex<I> for WithColors<M, C>
240where
241    M: GetVertex<I>,
242    C: Channel,
243    C::Element: Clone,
244    I: Copy + TryInto<usize>,
245{
246    type Vertex = vertex::WithColor<M::Vertex, C::Element>;
247    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
248        self.mesh.get_vertex(index).and_then(|vertex| {
249            let index: usize = index
250                .try_into()
251                .unwrap_or_else(|_err| panic!("index out of range of valid usize values"));
252            self.colors.channel().get(index).map(|color: &C::Element| {
253                let color = color.clone();
254                vertex::WithColor { vertex, color }
255            })
256        })
257    }
258}
259
260impl<M, T, I> GetVertex<I> for WithTexCoords<M, T>
261where
262    M: GetVertex<I>,
263    T: Channel,
264    T::Element: Clone,
265    I: Copy + TryInto<usize>,
266{
267    type Vertex = vertex::WithTexCoords<M::Vertex, T::Element>;
268    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
269        self.mesh.get_vertex(index).and_then(|vertex| {
270            let index: usize = index
271                .try_into()
272                .unwrap_or_else(|_err| panic!("index out of range of valid usize values"));
273            self.tex_coords.channel().get(index).map(|tex_coords| {
274                let tex_coords = tex_coords.clone();
275                vertex::WithTexCoords { vertex, tex_coords }
276            })
277        })
278    }
279}
280
281impl<M, N, I> GetVertex<I> for WithNormals<M, N>
282where
283    M: GetVertex<I>,
284    N: Channel,
285    N::Element: Clone,
286    I: Copy + TryInto<usize>,
287{
288    type Vertex = vertex::WithNormal<M::Vertex, N::Element>;
289    fn get_vertex(&self, index: I) -> Option<Self::Vertex> {
290        self.mesh.get_vertex(index).and_then(|vertex| {
291            let index: usize = index
292                .try_into()
293                .unwrap_or_else(|_err| panic!("index out of range of valid usize values"));
294            self.normals.channel().get(index).map(|normal| {
295                let normal = normal.clone();
296                vertex::WithNormal { vertex, normal }
297            })
298        })
299    }
300}
301
302// **Points** implementations.
303
304impl<P> Points for MeshPoints<P>
305where
306    P: Channel,
307{
308    type Point = P::Element;
309    type Points = P;
310    fn points(&self) -> &Self::Points {
311        &self.points
312    }
313}
314
315impl<'a, M> Points for &'a M
316where
317    M: Points,
318{
319    type Point = M::Point;
320    type Points = M::Points;
321    fn points(&self) -> &Self::Points {
322        (**self).points()
323    }
324}
325
326impl<'a, M> Points for &'a mut M
327where
328    M: Points,
329{
330    type Point = M::Point;
331    type Points = M::Points;
332    fn points(&self) -> &Self::Points {
333        (**self).points()
334    }
335}
336
337impl<'a, M> Points for Ref<'a, M>
338where
339    M: Points,
340{
341    type Point = M::Point;
342    type Points = M::Points;
343    fn points(&self) -> &Self::Points {
344        (**self).points()
345    }
346}
347
348impl<'a, M> Points for RefMut<'a, M>
349where
350    M: Points,
351{
352    type Point = M::Point;
353    type Points = M::Points;
354    fn points(&self) -> &Self::Points {
355        (**self).points()
356    }
357}
358
359impl<M, I> Points for WithIndices<M, I>
360where
361    M: Points,
362{
363    type Point = M::Point;
364    type Points = M::Points;
365    fn points(&self) -> &Self::Points {
366        self.mesh.points()
367    }
368}
369
370impl<M, C> Points for WithColors<M, C>
371where
372    M: Points,
373{
374    type Point = M::Point;
375    type Points = M::Points;
376    fn points(&self) -> &Self::Points {
377        self.mesh.points()
378    }
379}
380
381impl<M, T> Points for WithTexCoords<M, T>
382where
383    M: Points,
384{
385    type Point = M::Point;
386    type Points = M::Points;
387    fn points(&self) -> &Self::Points {
388        self.mesh.points()
389    }
390}
391
392impl<M, N> Points for WithNormals<M, N>
393where
394    M: Points,
395{
396    type Point = M::Point;
397    type Points = M::Points;
398    fn points(&self) -> &Self::Points {
399        self.mesh.points()
400    }
401}
402
403// **Indices** implementations.
404
405impl<M, I> Indices for WithIndices<M, I>
406where
407    I: Channel,
408{
409    type Index = I::Element;
410    type Indices = I;
411    fn indices(&self) -> &Self::Indices {
412        &self.indices
413    }
414}
415
416impl<'a, M> Indices for &'a M
417where
418    M: Indices,
419{
420    type Index = M::Index;
421    type Indices = M::Indices;
422    fn indices(&self) -> &Self::Indices {
423        (**self).indices()
424    }
425}
426
427impl<'a, M> Indices for &'a mut M
428where
429    M: Indices,
430{
431    type Index = M::Index;
432    type Indices = M::Indices;
433    fn indices(&self) -> &Self::Indices {
434        (**self).indices()
435    }
436}
437
438impl<'a, M> Indices for Ref<'a, M>
439where
440    M: Indices,
441{
442    type Index = M::Index;
443    type Indices = M::Indices;
444    fn indices(&self) -> &Self::Indices {
445        (**self).indices()
446    }
447}
448
449impl<'a, M> Indices for RefMut<'a, M>
450where
451    M: Indices,
452{
453    type Index = M::Index;
454    type Indices = M::Indices;
455    fn indices(&self) -> &Self::Indices {
456        (**self).indices()
457    }
458}
459
460impl<M, C> Indices for WithColors<M, C>
461where
462    M: Indices,
463{
464    type Index = M::Index;
465    type Indices = M::Indices;
466    fn indices(&self) -> &Self::Indices {
467        self.mesh.indices()
468    }
469}
470
471impl<M, T> Indices for WithTexCoords<M, T>
472where
473    M: Indices,
474{
475    type Index = M::Index;
476    type Indices = M::Indices;
477    fn indices(&self) -> &Self::Indices {
478        self.mesh.indices()
479    }
480}
481
482impl<M, N> Indices for WithNormals<M, N>
483where
484    M: Indices,
485{
486    type Index = M::Index;
487    type Indices = M::Indices;
488    fn indices(&self) -> &Self::Indices {
489        self.mesh.indices()
490    }
491}
492
493// **Colors** implementations.
494
495impl<M, C> Colors for WithColors<M, C>
496where
497    C: Channel,
498{
499    type Color = C::Element;
500    type Colors = C;
501    fn colors(&self) -> &Self::Colors {
502        &self.colors
503    }
504}
505
506impl<'a, M> Colors for &'a M
507where
508    M: Colors,
509{
510    type Color = M::Color;
511    type Colors = M::Colors;
512    fn colors(&self) -> &Self::Colors {
513        (**self).colors()
514    }
515}
516
517impl<'a, M> Colors for &'a mut M
518where
519    M: Colors,
520{
521    type Color = M::Color;
522    type Colors = M::Colors;
523    fn colors(&self) -> &Self::Colors {
524        (**self).colors()
525    }
526}
527
528impl<'a, M> Colors for Ref<'a, M>
529where
530    M: Colors,
531{
532    type Color = M::Color;
533    type Colors = M::Colors;
534    fn colors(&self) -> &Self::Colors {
535        (**self).colors()
536    }
537}
538
539impl<'a, M> Colors for RefMut<'a, M>
540where
541    M: Colors,
542{
543    type Color = M::Color;
544    type Colors = M::Colors;
545    fn colors(&self) -> &Self::Colors {
546        (**self).colors()
547    }
548}
549
550impl<M, I> Colors for WithIndices<M, I>
551where
552    M: Colors,
553{
554    type Color = M::Color;
555    type Colors = M::Colors;
556    fn colors(&self) -> &Self::Colors {
557        self.mesh.colors()
558    }
559}
560
561impl<M, T> Colors for WithTexCoords<M, T>
562where
563    M: Colors,
564{
565    type Color = M::Color;
566    type Colors = M::Colors;
567    fn colors(&self) -> &Self::Colors {
568        self.mesh.colors()
569    }
570}
571
572impl<M, N> Colors for WithNormals<M, N>
573where
574    M: Colors,
575{
576    type Color = M::Color;
577    type Colors = M::Colors;
578    fn colors(&self) -> &Self::Colors {
579        self.mesh.colors()
580    }
581}
582
583// **TexCoords** implementations.
584
585impl<M, T> TexCoords for WithTexCoords<M, T>
586where
587    T: Channel,
588{
589    type TexCoord = T::Element;
590    type TexCoords = T;
591    fn tex_coords(&self) -> &Self::TexCoords {
592        &self.tex_coords
593    }
594}
595
596impl<'a, M> TexCoords for &'a M
597where
598    M: TexCoords,
599{
600    type TexCoord = M::TexCoord;
601    type TexCoords = M::TexCoords;
602    fn tex_coords(&self) -> &Self::TexCoords {
603        (**self).tex_coords()
604    }
605}
606
607impl<'a, M> TexCoords for &'a mut M
608where
609    M: TexCoords,
610{
611    type TexCoord = M::TexCoord;
612    type TexCoords = M::TexCoords;
613    fn tex_coords(&self) -> &Self::TexCoords {
614        (**self).tex_coords()
615    }
616}
617
618impl<'a, M> TexCoords for Ref<'a, M>
619where
620    M: TexCoords,
621{
622    type TexCoord = M::TexCoord;
623    type TexCoords = M::TexCoords;
624    fn tex_coords(&self) -> &Self::TexCoords {
625        (**self).tex_coords()
626    }
627}
628
629impl<'a, M> TexCoords for RefMut<'a, M>
630where
631    M: TexCoords,
632{
633    type TexCoord = M::TexCoord;
634    type TexCoords = M::TexCoords;
635    fn tex_coords(&self) -> &Self::TexCoords {
636        (**self).tex_coords()
637    }
638}
639
640impl<M, I> TexCoords for WithIndices<M, I>
641where
642    M: TexCoords,
643{
644    type TexCoord = M::TexCoord;
645    type TexCoords = M::TexCoords;
646    fn tex_coords(&self) -> &Self::TexCoords {
647        self.mesh.tex_coords()
648    }
649}
650
651impl<M, C> TexCoords for WithColors<M, C>
652where
653    M: TexCoords,
654{
655    type TexCoord = M::TexCoord;
656    type TexCoords = M::TexCoords;
657    fn tex_coords(&self) -> &Self::TexCoords {
658        self.mesh.tex_coords()
659    }
660}
661
662impl<M, N> TexCoords for WithNormals<M, N>
663where
664    M: TexCoords,
665{
666    type TexCoord = M::TexCoord;
667    type TexCoords = M::TexCoords;
668    fn tex_coords(&self) -> &Self::TexCoords {
669        self.mesh.tex_coords()
670    }
671}
672
673// **Normals** implementations.
674
675impl<M, N> Normals for WithNormals<M, N>
676where
677    M: Points,
678    N: Channel,
679{
680    type Normal = N::Element;
681    type Normals = N;
682    fn normals(&self) -> &Self::Normals {
683        &self.normals
684    }
685}
686
687impl<'a, M> Normals for &'a M
688where
689    M: Normals,
690{
691    type Normal = M::Normal;
692    type Normals = M::Normals;
693    fn normals(&self) -> &Self::Normals {
694        (**self).normals()
695    }
696}
697
698impl<'a, M> Normals for &'a mut M
699where
700    M: Normals,
701{
702    type Normal = M::Normal;
703    type Normals = M::Normals;
704    fn normals(&self) -> &Self::Normals {
705        (**self).normals()
706    }
707}
708
709impl<'a, M> Normals for Ref<'a, M>
710where
711    M: Normals,
712{
713    type Normal = M::Normal;
714    type Normals = M::Normals;
715    fn normals(&self) -> &Self::Normals {
716        (**self).normals()
717    }
718}
719
720impl<'a, M> Normals for RefMut<'a, M>
721where
722    M: Normals,
723{
724    type Normal = M::Normal;
725    type Normals = M::Normals;
726    fn normals(&self) -> &Self::Normals {
727        (**self).normals()
728    }
729}
730
731impl<M, I> Normals for WithIndices<M, I>
732where
733    M: Normals,
734{
735    type Normal = M::Normal;
736    type Normals = M::Normals;
737    fn normals(&self) -> &Self::Normals {
738        self.mesh.normals()
739    }
740}
741
742impl<M, C> Normals for WithColors<M, C>
743where
744    M: Normals,
745{
746    type Normal = M::Normal;
747    type Normals = M::Normals;
748    fn normals(&self) -> &Self::Normals {
749        self.mesh.normals()
750    }
751}
752
753impl<M, T> Normals for WithTexCoords<M, T>
754where
755    M: Normals,
756{
757    type Normal = M::Normal;
758    type Normals = M::Normals;
759    fn normals(&self) -> &Self::Normals {
760        self.mesh.normals()
761    }
762}
763
764// PushVertex implementations for each mesh type where the channels are **Vec**s.
765
766impl<'a, M, V> PushVertex<V> for &'a mut M
767where
768    M: PushVertex<V>,
769{
770    fn push_vertex(&mut self, v: V) {
771        (**self).push_vertex(v)
772    }
773}
774
775impl<'a, M, V> PushVertex<V> for RefMut<'a, M>
776where
777    M: PushVertex<V>,
778{
779    fn push_vertex(&mut self, v: V) {
780        (**self).push_vertex(v)
781    }
782}
783
784impl<V> PushVertex<V> for MeshPoints<Vec<V>> {
785    fn push_vertex(&mut self, v: V) {
786        self.points.push(v);
787    }
788}
789
790impl<M, I, V> PushVertex<V> for WithIndices<M, Vec<I>>
791where
792    M: PushVertex<V>,
793{
794    fn push_vertex(&mut self, v: V) {
795        self.mesh.push_vertex(v);
796    }
797}
798
799impl<M, V, C> PushVertex<vertex::WithColor<V, C>> for WithColors<M, Vec<C>>
800where
801    M: PushVertex<V>,
802{
803    fn push_vertex(&mut self, v: vertex::WithColor<V, C>) {
804        let vertex::WithColor { vertex, color } = v;
805        self.colors.push(color);
806        self.mesh.push_vertex(vertex);
807    }
808}
809
810impl<M, V, T> PushVertex<vertex::WithTexCoords<V, T>> for WithTexCoords<M, Vec<T>>
811where
812    M: PushVertex<V>,
813{
814    fn push_vertex(&mut self, v: vertex::WithTexCoords<V, T>) {
815        let vertex::WithTexCoords { vertex, tex_coords } = v;
816        self.tex_coords.push(tex_coords);
817        self.mesh.push_vertex(vertex);
818    }
819}
820
821impl<M, V, N> PushVertex<vertex::WithNormal<V, N>> for WithNormals<M, Vec<N>>
822where
823    M: PushVertex<V>,
824{
825    fn push_vertex(&mut self, v: vertex::WithNormal<V, N>) {
826        let vertex::WithNormal { vertex, normal } = v;
827        self.normals.push(normal);
828        self.mesh.push_vertex(vertex);
829    }
830}
831
832// PushIndex implementations for meshes.
833
834impl<'a, M> PushIndex for &'a mut M
835where
836    M: PushIndex,
837{
838    type Index = M::Index;
839    fn push_index(&mut self, index: Self::Index) {
840        (**self).push_index(index);
841    }
842    fn extend_indices<I>(&mut self, indices: I)
843    where
844        I: IntoIterator<Item = Self::Index>,
845    {
846        (**self).extend_indices(indices);
847    }
848}
849
850impl<'a, M> PushIndex for RefMut<'a, M>
851where
852    M: PushIndex,
853{
854    type Index = M::Index;
855    fn push_index(&mut self, index: Self::Index) {
856        (**self).push_index(index);
857    }
858    fn extend_indices<I>(&mut self, indices: I)
859    where
860        I: IntoIterator<Item = Self::Index>,
861    {
862        (**self).extend_indices(indices);
863    }
864}
865
866impl<M, I> PushIndex for WithIndices<M, Vec<I>> {
867    type Index = I;
868
869    fn push_index(&mut self, index: Self::Index) {
870        self.indices.push(index);
871    }
872
873    fn extend_indices<It>(&mut self, indices: It)
874    where
875        It: IntoIterator<Item = Self::Index>,
876    {
877        self.indices.extend(indices);
878    }
879}
880
881impl<M, C> PushIndex for WithColors<M, C>
882where
883    M: PushIndex,
884{
885    type Index = M::Index;
886
887    fn push_index(&mut self, index: Self::Index) {
888        self.mesh.push_index(index);
889    }
890
891    fn extend_indices<I>(&mut self, indices: I)
892    where
893        I: IntoIterator<Item = Self::Index>,
894    {
895        self.mesh.extend_indices(indices);
896    }
897}
898
899impl<M, T> PushIndex for WithTexCoords<M, T>
900where
901    M: PushIndex,
902{
903    type Index = M::Index;
904
905    fn push_index(&mut self, index: Self::Index) {
906        self.mesh.push_index(index);
907    }
908
909    fn extend_indices<I>(&mut self, indices: I)
910    where
911        I: IntoIterator<Item = Self::Index>,
912    {
913        self.mesh.extend_indices(indices);
914    }
915}
916
917impl<M, N> PushIndex for WithNormals<M, N>
918where
919    M: PushIndex,
920{
921    type Index = M::Index;
922
923    fn push_index(&mut self, index: M::Index) {
924        self.mesh.push_index(index);
925    }
926
927    fn extend_indices<I>(&mut self, indices: I)
928    where
929        I: IntoIterator<Item = M::Index>,
930    {
931        self.mesh.extend_indices(indices);
932    }
933}
934
935// **ClearIndices** implementations
936
937impl<'a, M> ClearIndices for &'a mut M
938where
939    M: ClearIndices,
940{
941    fn clear_indices(&mut self) {
942        (**self).clear_indices();
943    }
944}
945
946impl<'a, M> ClearIndices for RefMut<'a, M>
947where
948    M: ClearIndices,
949{
950    fn clear_indices(&mut self) {
951        (**self).clear_indices();
952    }
953}
954
955impl<M, I> ClearIndices for WithIndices<M, Vec<I>> {
956    fn clear_indices(&mut self) {
957        self.indices.clear();
958    }
959}
960
961impl<M, C> ClearIndices for WithColors<M, C>
962where
963    M: ClearIndices,
964{
965    fn clear_indices(&mut self) {
966        self.mesh.clear_indices();
967    }
968}
969
970impl<M, T> ClearIndices for WithTexCoords<M, T>
971where
972    M: ClearIndices,
973{
974    fn clear_indices(&mut self) {
975        self.mesh.clear_indices();
976    }
977}
978
979impl<M, N> ClearIndices for WithNormals<M, N>
980where
981    M: ClearIndices,
982{
983    fn clear_indices(&mut self) {
984        self.mesh.clear_indices();
985    }
986}
987
988// **ClearVertices** implementations
989
990impl<'a, M> ClearVertices for &'a mut M
991where
992    M: ClearVertices,
993{
994    fn clear_vertices(&mut self) {
995        (**self).clear_vertices()
996    }
997}
998
999impl<'a, M> ClearVertices for RefMut<'a, M>
1000where
1001    M: ClearVertices,
1002{
1003    fn clear_vertices(&mut self) {
1004        (**self).clear_vertices()
1005    }
1006}
1007
1008impl<V> ClearVertices for MeshPoints<Vec<V>> {
1009    fn clear_vertices(&mut self) {
1010        self.points.clear();
1011    }
1012}
1013
1014impl<M, I> ClearVertices for WithIndices<M, Vec<I>>
1015where
1016    M: ClearVertices,
1017{
1018    fn clear_vertices(&mut self) {
1019        self.mesh.clear_vertices();
1020        self.indices.clear();
1021    }
1022}
1023
1024impl<M, C> ClearVertices for WithColors<M, Vec<C>>
1025where
1026    M: ClearVertices,
1027{
1028    fn clear_vertices(&mut self) {
1029        self.mesh.clear_vertices();
1030        self.colors.clear();
1031    }
1032}
1033
1034impl<M, T> ClearVertices for WithTexCoords<M, Vec<T>>
1035where
1036    M: ClearVertices,
1037{
1038    fn clear_vertices(&mut self) {
1039        self.mesh.clear_vertices();
1040        self.tex_coords.clear();
1041    }
1042}
1043
1044impl<M, N> ClearVertices for WithNormals<M, Vec<N>>
1045where
1046    M: ClearVertices,
1047{
1048    fn clear_vertices(&mut self) {
1049        self.mesh.clear_vertices();
1050        self.normals.clear();
1051    }
1052}
1053
1054// **ExtendFromSlice** implementations
1055
1056impl<'a, P> ExtendFromSlice<'a> for MeshPoints<Vec<P>>
1057where
1058    P: 'a + Clone,
1059{
1060    type Slice = &'a [P];
1061    fn extend_from_slice(&mut self, slice: Self::Slice) {
1062        self.points.extend_from_slice(slice);
1063    }
1064}
1065
1066impl<'a, M, I> ExtendFromSlice<'a> for WithIndices<M, Vec<I>>
1067where
1068    M: ExtendFromSlice<'a>,
1069    I: 'a + Clone,
1070{
1071    type Slice = (&'a [I], M::Slice);
1072    fn extend_from_slice(&mut self, slice: Self::Slice) {
1073        let (slice, inner) = slice;
1074        self.mesh.extend_from_slice(inner);
1075        self.indices.extend_from_slice(slice);
1076    }
1077}
1078
1079impl<'a, M, C> ExtendFromSlice<'a> for WithColors<M, Vec<C>>
1080where
1081    M: ExtendFromSlice<'a>,
1082    C: 'a + Clone,
1083{
1084    type Slice = (&'a [C], M::Slice);
1085    fn extend_from_slice(&mut self, slice: Self::Slice) {
1086        let (slice, inner) = slice;
1087        self.mesh.extend_from_slice(inner);
1088        self.colors.extend_from_slice(slice);
1089    }
1090}
1091
1092impl<'a, M, T> ExtendFromSlice<'a> for WithTexCoords<M, Vec<T>>
1093where
1094    M: ExtendFromSlice<'a>,
1095    T: 'a + Clone,
1096{
1097    type Slice = (&'a [T], M::Slice);
1098    fn extend_from_slice(&mut self, slice: Self::Slice) {
1099        let (slice, inner) = slice;
1100        self.mesh.extend_from_slice(inner);
1101        self.tex_coords.extend_from_slice(slice);
1102    }
1103}
1104
1105impl<'a, M, N> ExtendFromSlice<'a> for WithNormals<M, Vec<N>>
1106where
1107    M: ExtendFromSlice<'a>,
1108    N: 'a + Clone,
1109{
1110    type Slice = (&'a [N], M::Slice);
1111    fn extend_from_slice(&mut self, slice: Self::Slice) {
1112        let (slice, inner) = slice;
1113        self.mesh.extend_from_slice(inner);
1114        self.normals.extend_from_slice(slice);
1115    }
1116}
1117
1118// **Clear** implementation for all meshes.
1119
1120impl<T> Clear for T where T: ClearIndices + ClearVertices {}
1121
1122// **Default** implementations for all meshes.
1123
1124impl<P> Default for MeshPoints<P>
1125where
1126    P: Default,
1127{
1128    fn default() -> Self {
1129        let points = Default::default();
1130        MeshPoints { points }
1131    }
1132}
1133
1134impl<M, I> Default for WithIndices<M, I>
1135where
1136    M: Default,
1137    I: Default,
1138{
1139    fn default() -> Self {
1140        let mesh = Default::default();
1141        let indices = Default::default();
1142        WithIndices { mesh, indices }
1143    }
1144}
1145
1146impl<M, C> Default for WithColors<M, C>
1147where
1148    M: Default,
1149    C: Default,
1150{
1151    fn default() -> Self {
1152        let mesh = Default::default();
1153        let colors = Default::default();
1154        WithColors { mesh, colors }
1155    }
1156}
1157
1158impl<M, T> Default for WithTexCoords<M, T>
1159where
1160    M: Default,
1161    T: Default,
1162{
1163    fn default() -> Self {
1164        let mesh = Default::default();
1165        let tex_coords = Default::default();
1166        WithTexCoords { mesh, tex_coords }
1167    }
1168}
1169
1170impl<M, N> Default for WithNormals<M, N>
1171where
1172    M: Default,
1173    N: Default,
1174{
1175    fn default() -> Self {
1176        let mesh = Default::default();
1177        let normals = Default::default();
1178        WithNormals { mesh, normals }
1179    }
1180}
1181
1182// Deref implementations for the mesh adaptor types to their inner mesh.
1183
1184impl<M, I> Deref for WithIndices<M, I> {
1185    type Target = M;
1186    fn deref(&self) -> &Self::Target {
1187        &self.mesh
1188    }
1189}
1190
1191impl<M, I> DerefMut for WithIndices<M, I> {
1192    fn deref_mut(&mut self) -> &mut Self::Target {
1193        &mut self.mesh
1194    }
1195}
1196
1197impl<M, C> Deref for WithColors<M, C> {
1198    type Target = M;
1199    fn deref(&self) -> &Self::Target {
1200        &self.mesh
1201    }
1202}
1203
1204impl<M, C> DerefMut for WithColors<M, C> {
1205    fn deref_mut(&mut self) -> &mut Self::Target {
1206        &mut self.mesh
1207    }
1208}
1209
1210impl<M, T> Deref for WithTexCoords<M, T> {
1211    type Target = M;
1212    fn deref(&self) -> &Self::Target {
1213        &self.mesh
1214    }
1215}
1216
1217impl<M, T> DerefMut for WithTexCoords<M, T> {
1218    fn deref_mut(&mut self) -> &mut Self::Target {
1219        &mut self.mesh
1220    }
1221}
1222
1223impl<M, N> Deref for WithNormals<M, N> {
1224    type Target = M;
1225    fn deref(&self) -> &Self::Target {
1226        &self.mesh
1227    }
1228}
1229
1230impl<M, N> DerefMut for WithNormals<M, N> {
1231    fn deref_mut(&mut self) -> &mut Self::Target {
1232        &mut self.mesh
1233    }
1234}
1235
1236// Mesh length functions.
1237
1238/// Get the number of vertices in the mesh.
1239pub fn raw_vertex_count<M>(mesh: M) -> usize
1240where
1241    M: Points,
1242{
1243    mesh.points().channel().len()
1244}
1245
1246/// The number of vertices that would be yielded by a **Vertices** iterator for the given mesh.
1247pub fn vertex_count<M>(mesh: M) -> usize
1248where
1249    M: Indices,
1250{
1251    mesh.indices().channel().len()
1252}
1253
1254/// The number of triangles that would be yielded by a **Triangles** iterator for the given mesh.
1255pub fn triangle_count<M>(mesh: M) -> usize
1256where
1257    M: Indices,
1258{
1259    vertex_count(mesh) / geom::tri::NUM_VERTICES as usize
1260}
1261
1262// Mesh constructors.
1263
1264/// Create a simple base mesh from the given channel of vertex points.
1265pub fn from_points<P>(points: P) -> MeshPoints<P>
1266where
1267    P: Channel,
1268{
1269    MeshPoints { points }
1270}
1271
1272/// Combine the given mesh with the given channel of vertex indices.
1273pub fn with_indices<M, I, Ix>(mesh: M, indices: I) -> WithIndices<M, I>
1274where
1275    M: GetVertex<Ix>,
1276    I: Channel<Element = Ix>,
1277{
1278    WithIndices { mesh, indices }
1279}
1280
1281/// Combine the given mesh with the given channel of vertex colors.
1282///
1283/// **Panics** if the length of the **colors** channel differs from **points**.
1284pub fn with_colors<M, C>(mesh: M, colors: C) -> WithColors<M, C>
1285where
1286    M: Points,
1287    C: Channel,
1288{
1289    assert_eq!(raw_vertex_count(&mesh), colors.channel().len());
1290    WithColors { mesh, colors }
1291}
1292
1293/// Combine the given mesh with the given channel of vertex texture coordinates.
1294///
1295/// **Panics** if the length of the **tex_coords** channel differs from **points**.
1296pub fn with_tex_coords<M, T>(mesh: M, tex_coords: T) -> WithTexCoords<M, T>
1297where
1298    M: Points,
1299    T: Channel,
1300{
1301    assert_eq!(raw_vertex_count(&mesh), tex_coords.channel().len());
1302    WithTexCoords { mesh, tex_coords }
1303}
1304
1305/// Combine the given mesh with the given **Normals** channel.
1306///
1307/// **Panics** if the length of the **normals** channel differs from **points**.
1308pub fn with_normals<M, N>(mesh: M, normals: N) -> WithNormals<M, N>
1309where
1310    M: Points,
1311    N: Channel,
1312{
1313    assert_eq!(raw_vertex_count(&mesh), normals.channel().len());
1314    WithNormals { mesh, normals }
1315}
1316
1317// Mesh mutation functions.
1318
1319/// Push the given vertex to the given `mesh`.
1320///
1321/// The lengths of all non-index channels within the mesh should remain equal before and after a
1322/// call to this function.
1323pub fn push_vertex<M, V>(mut mesh: M, vertex: V)
1324where
1325    M: PushVertex<V>,
1326{
1327    mesh.push_vertex(vertex);
1328}
1329
1330/// Extend the given **mesh** with the given sequence of **vertices**.
1331///
1332/// The lengths of all non-index channels within the mesh should remain equal before and after a
1333/// call to this function.
1334pub fn extend_vertices<M, I>(mut mesh: M, vertices: I)
1335where
1336    M: PushVertex<I::Item>,
1337    I: IntoIterator,
1338{
1339    for v in vertices {
1340        push_vertex(&mut mesh, v);
1341    }
1342}
1343
1344/// Push the given index to the given `mesh`.
1345pub fn push_index<M>(mut mesh: M, index: M::Index)
1346where
1347    M: PushIndex,
1348{
1349    mesh.push_index(index);
1350}
1351
1352/// Extend the given mesh with the given indices.
1353pub fn extend_indices<M, I>(mut mesh: M, indices: I)
1354where
1355    M: PushIndex,
1356    I: IntoIterator<Item = M::Index>,
1357{
1358    mesh.extend_indices(indices);
1359}
1360
1361/// Clear all vertices from the mesh.
1362pub fn clear_vertices<M>(mut mesh: M)
1363where
1364    M: ClearVertices,
1365{
1366    mesh.clear_vertices();
1367}
1368
1369/// Clear all indices from the mesh.
1370pub fn clear_indices<M>(mut mesh: M)
1371where
1372    M: ClearIndices,
1373{
1374    mesh.clear_indices();
1375}
1376
1377/// Clear all vertices and indices from the mesh.
1378pub fn clear<M>(mut mesh: M)
1379where
1380    M: Clear,
1381{
1382    mesh.clear();
1383}
1384
1385// Mesh iterators.
1386
1387/// An iterator yielding the raw vertices (with combined channels) of a mesh.
1388///
1389/// Requires that the mesh implements **GetVertex**.
1390///
1391/// Returns `None` when the inner mesh first returns `None` for a call to **GetVertex::get_vertex**.
1392#[derive(Clone, Debug)]
1393pub struct RawVertices<M> {
1394    range: ops::Range<usize>,
1395    mesh: M,
1396}
1397
1398/// An iterator yielding vertices in the order specified via the mesh's **Indices** channel.
1399///
1400/// Requires that the mesh implements **Indices** and **GetVertex**.
1401///
1402/// Returns `None` when a vertex has been yielded for every index in the **Indices** channel.
1403///
1404/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
1405/// vertices.
1406#[derive(Clone, Debug)]
1407pub struct Vertices<M> {
1408    index_range: ops::Range<usize>,
1409    mesh: M,
1410}
1411
1412/// An iterator yielding triangles in the order specified via the mesh's **Indices** channel.
1413///
1414/// Requires that the mesh implements **Indices** and **GetVertex**.
1415///
1416/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
1417pub type Triangles<M> = geom::tri::IterFromVertices<Vertices<M>>;
1418
1419/// An iterator yielding the raw vertices (with combined channels) of a mesh.
1420///
1421/// Requires that the inner mesh implements **GetVertex**.
1422///
1423/// Returns `None` when the inner mesh first returns `None` for a call to **GetVertex::get_vertex**.
1424pub fn raw_vertices<M>(mesh: M) -> RawVertices<M>
1425where
1426    M: Points,
1427{
1428    let len = raw_vertex_count(&mesh);
1429    let range = 0..len;
1430    RawVertices { range, mesh }
1431}
1432
1433/// Produce an iterator yielding vertices in the order specified via the mesh's **Indices**
1434/// channel.
1435///
1436/// Requires that the mesh implements **Indices** and **GetVertex**.
1437///
1438/// Returns `None` when a vertex has been yielded for every index in the **Indices** channel.
1439///
1440/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
1441/// vertices.
1442pub fn vertices<M, I>(mesh: M) -> Vertices<M>
1443where
1444    M: Indices<Index = I> + GetVertex<I>,
1445    I: TryFrom<usize>,
1446{
1447    let len = mesh.indices().channel().len();
1448    let index_range = 0..len;
1449    Vertices { index_range, mesh }
1450}
1451
1452/// Produce an iterator yielding triangles for every three vertices yielded in the order specified
1453/// via the mesh's **Indices** channel.
1454///
1455/// Requires that the mesh implements **Indices** and **GetVertex**.
1456///
1457/// Returns `None` when there are no longer enough vertex indices to produce a triangle.
1458///
1459/// **Panics** if the **Indices** channel produces an index that is out of bounds of the mesh's
1460/// vertices.
1461pub fn triangles<M, I>(mesh: M) -> Triangles<M>
1462where
1463    M: Indices<Index = I> + GetVertex<I>,
1464    I: Copy + TryFrom<usize>,
1465{
1466    geom::tri::iter_from_vertices(vertices(mesh))
1467}
1468
1469// The error message produced when the `Vertices` iterator panics due to an out of bound index.
1470const NO_VERTEX_FOR_INDEX: &'static str =
1471    "no vertex for the index produced by the mesh's indices channel";
1472
1473impl<M> RawVertices<M> {
1474    /// Specify a range of raw vertices to yield.
1475    pub fn range(mut self, range: ops::Range<usize>) -> Self {
1476        self.range = range;
1477        self
1478    }
1479}
1480
1481impl<M> Vertices<M>
1482where
1483    M: Indices,
1484{
1485    /// Specify the range of vertex indices to yield vertices from.
1486    pub fn index_range(mut self, range: ops::Range<usize>) -> Self {
1487        self.index_range = range;
1488        self
1489    }
1490
1491    /// Convert this iterator yielding vertices into an iterator yielding triangles for every three
1492    /// vertices yielded.
1493    pub fn triangles<I>(self) -> Triangles<M>
1494    where
1495        M: Indices<Index = I> + GetVertex<I>,
1496        I: Copy,
1497    {
1498        geom::tri::iter_from_vertices(self)
1499    }
1500}
1501
1502impl<M> Iterator for RawVertices<M>
1503where
1504    M: GetVertex<usize>,
1505{
1506    type Item = M::Vertex;
1507    fn next(&mut self) -> Option<Self::Item> {
1508        if let Some(vertex) = self.range.next().and_then(|i| self.mesh.get_vertex(i)) {
1509            return Some(vertex);
1510        }
1511        None
1512    }
1513}
1514
1515impl<M, I> Iterator for Vertices<M>
1516where
1517    M: Indices<Index = I> + GetVertex<I>,
1518    I: Copy,
1519{
1520    type Item = M::Vertex;
1521    fn next(&mut self) -> Option<Self::Item> {
1522        if let Some(i) = self.index_range.next() {
1523            if let Some(&index) = self.mesh.indices().channel().get(i) {
1524                let vertex = self.mesh.get_vertex(index).expect(NO_VERTEX_FOR_INDEX);
1525                return Some(vertex);
1526            }
1527        }
1528        None
1529    }
1530
1531    fn size_hint(&self) -> (usize, Option<usize>) {
1532        let len = self.len();
1533        (len, Some(len))
1534    }
1535}
1536
1537impl<M> ExactSizeIterator for RawVertices<M>
1538where
1539    M: GetVertex<usize>,
1540{
1541    fn len(&self) -> usize {
1542        self.range.len()
1543    }
1544}
1545
1546impl<M, I> DoubleEndedIterator for Vertices<M>
1547where
1548    M: Indices<Index = I> + GetVertex<I>,
1549    I: Copy,
1550{
1551    fn next_back(&mut self) -> Option<Self::Item> {
1552        if let Some(i) = self.index_range.next_back() {
1553            if let Some(&index) = self.mesh.indices().channel().get(i) {
1554                let vertex = self.mesh.get_vertex(index).expect(NO_VERTEX_FOR_INDEX);
1555                return Some(vertex);
1556            }
1557        }
1558        None
1559    }
1560}
1561
1562impl<M, I> ExactSizeIterator for Vertices<M>
1563where
1564    M: Indices<Index = I> + GetVertex<I>,
1565    I: Copy,
1566{
1567    fn len(&self) -> usize {
1568        let indices_len = self.mesh.indices().channel().len();
1569        let remaining_indices = indices_len - self.index_range.start;
1570        let range_len = self.index_range.len();
1571        cmp::min(remaining_indices, range_len)
1572    }
1573}