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
use std::ops::{Index,IndexMut};
use std::borrow::{Borrow,BorrowMut};
use std::slice;
use std::vec;
use std::iter::{FromIterator, IntoIterator};
use std::io::BufRead;
use super::vertex::*;

use rin_math::{vec3, vec2, zero};
use color::{ToRgba, rgba};
use std::path::Path;
use std::io;
use std::fs::File;
use std::mem;
use std::iter;
#[cfg(feature="serialize")]
use serde_derive::{Serialize, Deserialize};

#[cfg(not(target_os="android"))]
pub type IndexT = u32;
#[cfg(target_os="android")]
pub type IndexT = u16;

/// A Mesh with any vertex type
///
/// Contains vertices that can be of any type although
/// rin define a few of the most commonly used and optionally
/// indices
///
/// Also a primitive type that defines how the vertices / indices
/// should be parsed
#[derive(Debug,Clone)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct Mesh<T>{
    vertices: Vec<T>,
    indices: Vec<IndexT>,
    primitive_type: PrimitiveType,
}

impl<T> Default for Mesh<T>{
    fn default() -> Mesh<T>{
        Mesh{
            vertices: vec![],
            indices: vec![],
            primitive_type: PrimitiveType::Triangles,
        }
    }
}

/// Mesh with no indices from vertices and primitive type
pub fn mesh<T>(vertices: Vec<T>, ty: PrimitiveType) ->Mesh<T>{
    Mesh::from_vertices_and_type(vertices,ty)
}

impl<T> Mesh<T>{
    /// Mesh from vertices, indices and primitive type
    pub fn new(vertices: Vec<T>, indices: Vec<IndexT>, primitive_type: PrimitiveType) -> Mesh<T>{
        Mesh{vertices, indices, primitive_type}
    }

    /// Triangles mesh from vertices with no indices
    pub fn from_vertices(vertices: Vec<T>) -> Mesh<T>{
        Mesh{vertices: vertices, indices: Vec::new(), primitive_type: PrimitiveType::Triangles}
    }

    /// Mesh with no indices from vertices and primitive type
    pub fn from_vertices_and_type(vertices: Vec<T>, ty: PrimitiveType) -> Mesh<T>{
        Mesh{vertices: vertices, indices: Vec::new(), primitive_type: ty}
    }

    /// Mesh with no indices from vertices iterator and primitive type
    pub fn from_iter_and_type<I: Iterator<Item=T>>(vertices: I, ty: PrimitiveType) -> Mesh<T>{
        Mesh{vertices: vertices.collect(), indices: Vec::new(), primitive_type: ty}
    }

    /// Triangles mesh from vertices and indices
    pub fn from_vertices_indices(vertices: Vec<T>, indices: Vec<IndexT>) -> Mesh<T>{
        Mesh{vertices: vertices, indices: indices, primitive_type: PrimitiveType::Triangles}
    }

    /// Empty mesh with the specified primitive type
    pub fn with_type(ty: PrimitiveType) -> Mesh<T>{
         Mesh{vertices: Vec::new(), indices: Vec::new(), primitive_type: ty}
    }

    /// Set the mesh vertices
    pub fn set_vertices(&mut self, vertices: Vec<T>){
        self.vertices = vertices;
    }

    /// Set the mesh vertices
    pub fn set_indices(&mut self, indices: Vec<IndexT>){
        self.indices = indices;
    }

    pub fn indices(&self) -> &Vec<IndexT>{
        &self.indices
    }

    pub fn indices_mut(&mut self) -> &mut Vec<IndexT>{
        &mut self.indices
    }

    pub fn vertices(&self) -> &[T]{
        &self.vertices
    }

    pub fn vertices_mut(&mut self) -> &mut Vec<T>{
        &mut self.vertices
    }

    pub fn vertices_indices_mut(&mut self) -> (&mut Vec<T>, &mut Vec<IndexT>){
        (&mut self.vertices, &mut self.indices)
    }

    /// Iterator over the mesh vertices in the order they where inserted
    pub fn iter(&self) -> slice::Iter<T>{
        self.vertices.iter()
    }

    /// Mutable iterator over the mesh vertices in the order they where inserted
    pub fn iter_mut(&mut self) -> slice::IterMut< T>{
        self.vertices.iter_mut()
    }

    /// Consume the mesh into an iterator over it's vertices in the order they where inserted
    pub fn into_iter(self) -> vec::IntoIter<T>{
        self.vertices.into_iter()
    }

    /// Pop the last vertex
    pub fn pop(&mut self) -> Option<T>{
        self.vertices.pop()
    }

    /// Push a vertex at the end of the mesh
    pub fn push(&mut self, value: T){
        self.vertices.push(value);
    }

    /// Extend the mesh with an iterator of new vertices
    pub fn extend<I: IntoIterator<Item=T>>(&mut self, other: I){
        self.vertices.extend(other);
    }

    /// Insert a vertex at a certain position
    pub fn insert(&mut self, index: usize, element: T){
        self.vertices.insert(index, element);
    }

    /// Mutably get the vertex at the specified position.
    ///
    /// Will panic if the vertex doesn't exist
    pub fn get_mut(&mut self, index: usize) -> &mut T{
        self.vertices.get_mut(index).unwrap()
    }

    /// Reserve as much capacity for vertices
    pub fn reserve(&mut self, capacity: usize){
        self.vertices.reserve(capacity);
    }

    /// Unsafe operation that sets the len of the vertices
    /// collection
    pub unsafe fn set_len(&mut self, len: usize){
        self.vertices.set_len(len);
    }

    /// Truncate the mesh vertices at the specified len
    pub fn truncate(&mut self, len: usize){
        self.vertices.truncate(len);
    }

    /// Last vertex if there's any
    pub fn last(&self) -> Option<&T>{
        self.vertices.last()
    }

    /// Last vertex mutably if there's any
    pub fn last_mut(&mut self) -> Option<&mut T>{
        self.vertices.last_mut()
    }

    /// Primitive type
    pub fn primitive_type(&self) -> PrimitiveType{
        self.primitive_type
    }

    pub fn set_primitive_type(&mut self, ty: PrimitiveType){
        self.primitive_type = ty;
    }

    /// Add a triangle face (only for Triangles primitive type)
    pub fn add_face(&mut self, i0: IndexT, i1: IndexT, i2: IndexT){
        self.indices.push(i0);
        self.indices.push(i1);
        self.indices.push(i2);
    }

    /// Clear the mesh vertices and indices
    pub fn clear(&mut self){
        self.vertices.clear();
        self.indices.clear();
    }

    /// Clear the vertices
    pub fn clear_vertices(&mut self){
        self.vertices.clear();
    }

    /// Clear the indices
    pub fn clear_indices(&mut self){
        self.indices.clear();
    }

    /// Number of vertices
    pub fn len(&self) -> usize{
        self.vertices.len()
    }

    /// Contains any vertices
    pub fn is_empty(&self) -> bool{
        self.vertices.is_empty()
    }

    pub fn as_slice(&self) -> MeshSlice<T> {
        MeshSlice::new(&self.vertices, &self.indices, self.primitive_type)
    }

    pub fn faces(&self) -> Box<dyn Iterator<Item = [&T; 3]> + '_>{
        match self.primitive_type() {
            PrimitiveType::Triangles => {
                if self.indices.is_empty(){
                    Box::new(self.vertices.chunks_exact(3).map(|tri| [
                        &tri[0],
                        &tri[1],
                        &tri[2],
                    ]))
                }else{
                    Box::new(self.indices.chunks_exact(3).map(move |tri| [
                        &self.vertices[tri[0] as usize],
                        &self.vertices[tri[1] as usize],
                        &self.vertices[tri[2] as usize],
                    ]))
                }
            }


            PrimitiveType::TriangleStrip => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    Box::new(
                        iter::once([
                            &self.vertices[0],
                            &self.vertices[1],
                            &self.vertices[2],
                        ]).chain(self.vertices[1..].windows(3).map(|v|[
                            &v[1],
                            &v[0],
                            &v[2]
                        ]))
                    )
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    Box::new(
                        iter::once([
                            &self.vertices[self.indices[0] as usize],
                            &self.vertices[self.indices[1] as usize],
                            &self.vertices[self.indices[2] as usize],
                        ]).chain(self.indices[1..].windows(3).map(move |i| [
                            &self.vertices[i[1] as usize],
                            &self.vertices[i[0] as usize],
                            &self.vertices[i[2] as usize],
                        ]))
                    )
                }
            }

            PrimitiveType::TriangleFan => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    Box::new(
                        iter::once([
                            &self.vertices[0],
                            &self.vertices[1],
                            &self.vertices[2],
                        ]).chain(self.vertices.windows(4).map(move |v| [
                            &v[0],
                            &v[2],
                            &v[3]
                        ]))
                    )
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    Box::new(
                        iter::once([
                            &self.vertices[self.indices[0] as usize],
                            &self.vertices[self.indices[1] as usize],
                            &self.vertices[self.indices[2] as usize],
                        ]).chain(self.indices.windows(4).map(move |i| [
                            &self.vertices[i[0] as usize],
                            &self.vertices[i[2] as usize],
                            &self.vertices[i[3] as usize],
                        ]))
                    )
                }
            }

            _ => unimplemented!("Only Triangles, TrianglesStrip and TriangleFan PrimitiveType supported")
        }
    }

    pub fn faces_mut(&mut self) -> Box<dyn Iterator<Item = [&mut T; 3]> + '_>{
        match self.primitive_type() {
            PrimitiveType::Triangles => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    Box::new(self.vertices.chunks_exact_mut(3).map(|tri| [
                        unsafe{ mem::transmute(&mut tri[0]) },
                        unsafe{ mem::transmute(&mut tri[1]) },
                        unsafe{ mem::transmute(&mut tri[2]) },
                    ]))
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let indices = &self.indices;
                    let vertices: &mut Vec<T> = unsafe{ mem::transmute(&mut self.vertices) };
                    Box::new(indices.chunks_exact(3).map(move |tri| [
                        unsafe{ mem::transmute(&mut vertices[tri[0] as usize]) },
                        unsafe{ mem::transmute(&mut vertices[tri[1] as usize]) },
                        unsafe{ mem::transmute(&mut vertices[tri[2] as usize]) },
                    ]))
                }
            }

            PrimitiveType::TriangleStrip => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let vertices: &mut Vec<T> = unsafe{ mem::transmute(&mut self.vertices) };
                    Box::new(
                        iter::once([
                            unsafe{ mem::transmute(&mut vertices[0]) },
                            unsafe{ mem::transmute(&mut vertices[1]) },
                            unsafe{ mem::transmute(&mut vertices[2]) },
                        ]).chain((0..vertices.len()-3).map(move |i| [
                            unsafe{ mem::transmute(&mut vertices[i+2]) },
                            unsafe{ mem::transmute(&mut vertices[i+1]) },
                            unsafe{ mem::transmute(&mut vertices[i+3]) },
                        ]))
                    )
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let indices = &self.indices;
                    let vertices: &mut Vec<T> = unsafe{ mem::transmute(&mut self.vertices) };
                    Box::new(
                        iter::once([
                            unsafe{ mem::transmute(&mut vertices[indices[0] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[indices[1] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[indices[2] as usize]) },
                        ]).chain(indices[1..indices.len()].windows(3).map(move |i| [
                            unsafe{ mem::transmute(&mut vertices[i[1] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[i[0] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[i[2] as usize]) },
                        ]))
                    )
                }
            }

            PrimitiveType::TriangleFan => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let vertices: &mut Vec<T> = unsafe{ mem::transmute(&mut self.vertices) };
                    Box::new(
                        iter::once([
                            unsafe{ mem::transmute(&mut vertices[0]) },
                            unsafe{ mem::transmute(&mut vertices[1]) },
                            unsafe{ mem::transmute(&mut vertices[2]) },
                        ]).chain((0..vertices.len()-3).map(move |i| [
                            unsafe{ mem::transmute(&mut vertices[i]) },
                            unsafe{ mem::transmute(&mut vertices[i+2]) },
                            unsafe{ mem::transmute(&mut vertices[i+3]) },
                        ]))
                    )
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let indices = &self.indices;
                    let vertices: &mut Vec<T> = unsafe{ mem::transmute(&mut self.vertices) };
                    Box::new(
                        iter::once([
                            unsafe{ mem::transmute(&mut vertices[indices[0] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[indices[1] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[indices[2] as usize]) },
                        ]).chain(indices.windows(4).map(move |i| [
                            unsafe{ mem::transmute(&mut vertices[i[0] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[i[2] as usize]) },
                            unsafe{ mem::transmute(&mut vertices[i[3] as usize]) },
                        ]))
                    )
                }
            }

            _ => unimplemented!("Only Triangles, TrianglesStrip and TriangleFan PrimitiveType supported")
        }
    }
}

impl<T: Clone> Mesh<T>{
    pub fn into_faces(self) -> Box<dyn Iterator<Item = [T; 3]>>
    where T: 'static
    {
        match self.primitive_type() {
            PrimitiveType::Triangles => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let vertices = self.vertices;
                    Box::new((0..vertices.len()).step_by(3).map(move |i| [
                        vertices[i+0].clone(),
                        vertices[i+1].clone(),
                        vertices[i+2].clone(),
                    ]))
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let indices = self.indices;
                    let vertices = self.vertices;
                    Box::new((0..indices.len()).step_by(3).map(move |i| [
                        vertices[indices[i+0] as usize].clone(),
                        vertices[indices[i+1] as usize].clone(),
                        vertices[indices[i+2] as usize].clone(),
                    ]))
                }
            }

            PrimitiveType::TriangleStrip => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let vertices = self.vertices;
                    Box::new(
                        iter::once([
                            vertices[0].clone(),
                            vertices[1].clone(),
                            vertices[2].clone(),
                        ]).chain((0..vertices.len()-3).map(move |i| [
                            vertices[i+2].clone(),
                            vertices[i+1].clone(),
                            vertices[i+3].clone(),
                        ]))
                    )
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let indices = self.indices;
                    let vertices = self.vertices;
                    Box::new(
                        iter::once([
                            vertices[indices[0] as usize].clone(),
                            vertices[indices[1] as usize].clone(),
                            vertices[indices[2] as usize].clone(),
                        ]).chain((0..indices.len()-3).map(move |i| [
                            vertices[indices[i+2] as usize].clone(),
                            vertices[indices[i+1] as usize].clone(),
                            vertices[indices[i+3] as usize].clone(),
                        ]))
                    )
                }
            }

            PrimitiveType::TriangleFan => {
                if self.indices.is_empty(){
                    if self.vertices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let vertices = self.vertices;
                    Box::new(
                        iter::once([
                            vertices[0].clone(),
                            vertices[1].clone(),
                            vertices[2].clone(),
                        ]).chain((0..vertices.len()-3).map(move |i| [
                            vertices[i].clone(),
                            vertices[i+2].clone(),
                            vertices[i+3].clone(),
                        ]))
                    )
                }else{
                    if self.indices.len() < 3 {
                        return Box::new(iter::empty())
                    }

                    let indices = self.indices;
                    let vertices = self.vertices;
                    Box::new(
                        iter::once([
                            vertices[indices[0] as usize].clone(),
                            vertices[indices[1] as usize].clone(),
                            vertices[indices[2] as usize].clone(),
                        ]).chain((0..indices.len()-3).map(move |i| [
                            vertices[indices[i] as usize].clone(),
                            vertices[indices[i+2] as usize].clone(),
                            vertices[indices[i+3] as usize].clone(),
                        ]))
                    )
                }
            }

            _ => unimplemented!("Only Triangles, TrianglesStrip and TriangleFan PrimitiveType supported")
        }
    }
}

impl<T: Clone> Mesh<T>{
    /// Extend the mesh with another mesh
    ///
    /// The vertices and indices will just be inserted at the end
    /// without taking into account the primitive types
    pub fn extend_from_mesh(&mut self, other: &Mesh<T>){
        let offset = self.vertices.len() as u32;
        self.vertices.extend_from_slice(other.vertices());
        self.indices.extend(other.indices().iter().map(|i| i + offset));
    }

    /// Extend the mesh with a slice of new vertices
    pub fn extend_from_slice(&mut self, other: &[T]){
        self.vertices.extend_from_slice(other);
    }
}

impl<T> Index<usize> for Mesh<T>{
	type Output = T;
    fn index(&self, index: usize) -> &T{
        self.vertices.index(index)
    }
}

impl<T> IndexMut<usize> for Mesh<T>{
    fn index_mut(&mut self, index: usize) -> &mut T{
        self.vertices.index_mut(index)
    }
}

impl<T> AsRef<[T]> for Mesh<T>{
    fn as_ref(&self) -> &[T]{
        self.vertices.as_ref()
    }
}

impl<T> AsMut<[T]> for Mesh<T>{
    fn as_mut(&mut self) -> &mut [T]{
        self.vertices.as_mut()
    }
}

impl<T> Into<Vec<T>> for Mesh<T>{
    fn into(self) -> Vec<T>{
        self.vertices
    }
}

impl<T> Into<(Vec<T>, Vec<IndexT>)> for Mesh<T>{
    fn into(self) -> (Vec<T>, Vec<IndexT>){
        (self.vertices, self.indices)
    }
}

impl<T> Borrow<[T]> for Mesh<T>{
    fn borrow(&self) -> &[T]{
        self.vertices.borrow()
    }
}

impl<T> BorrowMut<[T]> for Mesh<T>{
    fn borrow_mut(&mut self) -> &mut [T]{
        self.vertices.borrow_mut()
    }
}

impl<T> FromIterator<T> for Mesh<T>{
    fn from_iter<I>(iter: I) -> Mesh<T> where I: IntoIterator<Item=T>{
        Mesh{
            vertices: iter.into_iter().collect(),
            indices: vec![],
            primitive_type: PrimitiveType::Triangles
        }
    }
}

#[derive(Clone,Copy,Debug,Eq,PartialEq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum PrimitiveType{
    Triangles,
    TriangleStrip,
    TriangleFan,
    Lines,
    LineStrip,
    LineLoop,
    LinesAdjacency,
    LineStripAdjacency,
    Points,
    Patches
}

impl Default for PrimitiveType{
    fn default() -> PrimitiveType {
        PrimitiveType::Triangles
    }
}

/// Load a ply into a Mesh
pub fn load_ply<C: ToRgba, P: AsRef<Path>>(path: P, default_color: C) -> Result<Mesh<Vertex3DTexColor>,String>{
    // let reader = io::file_reader(path).map_err(|err| format!("Couldn't open {}: {:?}", path, err))?;
    let file = File::open(path.as_ref())
        .map_err(|err| format!("Couldn't open {}: {:?}", path.as_ref().display(), err))?;
    let reader = io::BufReader::new(file);
    let mut mesh: Mesh<Vertex3DTexColor> = Mesh::default();
    let mut first_line = true;
    let mut vertex_dim = 0;
    let mut texcoord_dim = 0;
    let mut color_dim = 0;
    let mut state = "init".to_string();
    let mut idx = 0;
    for line in reader.lines() {
        let line = line.unwrap().trim_end_matches([' ','\n'].as_ref()).to_string();
        if first_line && line!="ply"{
            return Err("couldn't read file, ply not found on first line".to_string());
        }
        first_line = false;

        if line.starts_with("format"){
            if line != "format ascii 1.0"{
                return Err(format!("{}, not supported",line));
            }
            continue;
        }

        if line.starts_with("element"){
            let element_ty_len: Vec<&str> = line.split(' ').collect();
            let ty = element_ty_len[1];
            let len = element_ty_len[2];
            if ty == "vertex"{
				unsafe{
					let new_len = len.parse().unwrap();
					mesh.reserve(new_len);
					mesh.set_len(new_len);
				}
            }
            state = ty.to_string();
            println!("state: {}",state);
            continue;
        }

        if line.starts_with("property"){
            //let property_ty_name: ~[&str] = line.split(' ').collect();
            println!("state on property: {}",state);
            match state.as_ref(){
                "vertex" => vertex_dim+=1,
                "texcoord" => texcoord_dim+=1,
                "color" => color_dim+=1,
                _ => {}
            }
            continue;
        }

        if line == "end_header"{
            state = "vertices".to_string();
            continue;
        }

        if state == "vertices"{
            //println!("{} vertex dim",vertex_dim);
            let components: Vec<&str> = line.split(' ').collect();
            let mut next_pos = 0;
            if idx<mesh.vertices.len(){
                if vertex_dim == 2{
                    let pos = vec3(components[next_pos].parse().unwrap(),components[next_pos+1].parse().unwrap(),0.0);
                    mesh[idx].position = pos;
                    next_pos = 3;
                }else if vertex_dim >= 3{
                    let pos = vec3(components[next_pos].parse().unwrap(),components[next_pos+1].parse().unwrap(),components[next_pos+2].parse().unwrap());
                    mesh[idx].position = pos;
                    next_pos = vertex_dim+1;
                }

                if texcoord_dim >= 2{
                    let texcoord = vec2(components[next_pos].parse().unwrap(),components[next_pos+1].parse().unwrap());
                    mesh[idx].texcoord = texcoord;
                    next_pos += texcoord_dim;
                }else{
                    mesh[idx].texcoord = zero();
                }

                if color_dim >= 3{
                    let r = components[next_pos].parse().unwrap();
                    let g = components[next_pos+1].parse().unwrap();
                    let b = components[next_pos+2].parse().unwrap();
                    if color_dim == 3{
                        let color = rgba!(r,g,b,1.0f32);
                        mesh[idx].color = color;
                        //next_pos += color_dim;
                    }else if color_dim >= 4{
                        let a = components[next_pos+3].parse().unwrap();
                        let color = rgba!(r,g,b,a);
                        mesh[idx].color = color;
                        //next_pos += color_dim;
                    }
                }else{
                    mesh[idx].color = default_color.to_rgba().to_standard();
                }
                idx += 1;
            }else{
                state = "faces".to_string();
                idx = 0;
            }
        }

        if state == "faces"{
            let components: Vec<&str> = line.split(' ').collect();
            let num_components: usize = components[0].parse().unwrap();
            if num_components == 3 {
                mesh.add_face(components[1].parse().unwrap(), components[2].parse().unwrap(), components[3].parse().unwrap());
            }else if num_components == 4{
                mesh.add_face(components[1].parse().unwrap(), components[2].parse().unwrap(), components[3].parse().unwrap());
                mesh.add_face(components[3].parse().unwrap(), components[4].parse().unwrap(), components[1].parse().unwrap());
            }
            idx += 1;
        }
    }

    Ok(mesh)
}

use crate::{MeshSlice, projection};
#[cfg(feature="gl")]
use crate::PrimitiveTypeToGl;

#[cfg(feature="gl")]
impl<'a,T: Clone> Into<glin::simple_vao::Data<'a,T>> for &'a Mesh<T>{
    fn into(self) -> glin::simple_vao::Data<'a,T>{
        glin::simple_vao::Data{
            vertices: self,
            indices: self.indices(),
            mode: self.primitive_type().to_gl()
        }
    }
}