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
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::*;
#[cfg(any(feature="gl", feature="gles", feature="webgl"))]
use glin;
#[cfg(any(feature="gl", feature="gles", feature="webgl"))]
use super::primitive_type_to_gl;

use na::*;
use color::ToRgba;
use std::path::Path;
use std::io;
use std::fs::File;
use std::mem;

#[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: Clone>(vertices: Vec<T>, ty: PrimitiveType) ->Mesh<T>{
    Mesh::from_vertices_and_type(vertices,ty)
}

impl<T: Clone> 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 [T]{
        &mut self.vertices
    }

    /// 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 a slice of new vertices
    pub fn extend_from_slice(&mut self, other: &[T]){
        self.vertices.extend_from_slice(other);
    }

    /// 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 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 faces(&self) -> Box<Iterator<Item = [&T; 3]> + '_>{
        if self.indices.is_empty(){
            Box::new(self.vertices.chunks(3).map(|tri| [
                &tri[0],
                &tri[1],
                &tri[2],
            ]))
        }else if self.primitive_type() == PrimitiveType::Triangles{
            Box::new(self.indices.chunks(3).map(move |tri| [
                &self.vertices[tri[0] as usize],
                &self.vertices[tri[1] as usize],
                &self.vertices[tri[2] as usize],
            ]))
        }else{
            unimplemented!()
        }
    }

    pub fn faces_mut(&mut self) -> Box<Iterator<Item = [&mut T; 3]> + '_>{
        if self.primitive_type() == PrimitiveType::Triangles{
            if self.indices.is_empty(){
                Box::new(self.vertices.chunks_mut(3).map(|tri| [
                    unsafe{ mem::transmute(&mut tri[0]) },
                    unsafe{ mem::transmute(&mut tri[1]) },
                    unsafe{ mem::transmute(&mut tri[2]) },
                ]))
            }else{
                let indices = &self.indices;
                let vertices: &mut Vec<T> = unsafe{ mem::transmute(&mut self.vertices) };
                Box::new(indices.chunks(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]) },
                ]))
            }
        }else{
            unimplemented!()
        }
    }
}

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


#[cfg(any(feature="gl", feature="gles", feature="webgl"))]
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: primitive_type_to_gl(self.primitive_type())
        }
    }
}