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
use crate::mesh::Mesh;
use crate::utils::{ObjectId, LibraryId};
use na::{Vec3, Vec2, Vec4, zero, ToPnt};
use crate::material;
use hashbrown::HashMap;
use crate::scene::SceneData;

use std::mem;
use std::iter;

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Clone,Debug,Copy)]
#[repr(C)]
pub struct Vertex{
    pub position: Vec3,
    pub normal: Vec3,
    pub texcoord: Vec2,
    pub original_idx: u32,
    pub padding: u32,
}

fn vertex(position: Vec3, normal: Vec3, texcoord: Vec2, original_idx: u32) -> Vertex{
    Vertex{
        position: position,
        normal: normal,
        texcoord: texcoord,
        original_idx: original_idx,
        padding: 0,
    }
}

pub trait VertexExt {
    fn position(&self) -> &Vec3;
    fn normal(&self) -> &Vec3;
    fn texcoord(&self) -> &Vec2;
    fn position_mut(&mut self) -> &mut Vec3;
    fn normal_mut(&mut self) -> &mut Vec3;
    fn texcoord_mut(&mut self) -> &mut Vec2;
}

impl VertexExt for Vertex {
    fn position(&self) -> &Vec3 {
        &self.position
    }
    fn normal(&self) -> &Vec3{
        &self.normal
    }
    fn texcoord(&self) -> &Vec2{
        &self.texcoord
    }
    fn position_mut(&mut self) -> &mut Vec3{
        &mut self.position
    }
    fn normal_mut(&mut self) -> &mut Vec3{
        &mut self.normal
    }
    fn texcoord_mut(&mut self) -> &mut Vec2{
        &mut self.texcoord
    }
}

pub trait Vertex4Ext {
    fn position(&self) -> &Vec4;
    fn normal(&self) -> &Vec4;
    fn texcoord(&self) -> &Vec2;
    fn position_mut(&mut self) -> &mut Vec4;
    fn normal_mut(&mut self) -> &mut Vec4;
    fn texcoord_mut(&mut self) -> &mut Vec2;
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct TriMesh{
    flattened_meshes: Vec<Vec<Vertex>>,
    flattened_indices: Option<Vec<Vec<u32>>>,
    original_vertices: Vec<Vertex>,
    original_indices: Vec<u32>,
    materials: Vec<Option<ObjectId>>,
    key: Option<ObjectId>,
}

impl TriMesh{
    pub fn from(
        blend_mesh: &blender::Object,
        library_id: LibraryId,
        mesh: &Mesh,
        libraries: &HashMap<LibraryId, blender::File>,
        scene_data: &mut SceneData) -> TriMesh
    {
        let mut mesh = mesh.clone();
        mesh.triangulate_no_edges();
        mesh.recalculate_normals();
        // --------------------
        // TODO: This can potentially create lots of uneeded triangles by considering as non smooth
        // every triangle in a mesh which will need to replicate a vertex for each face it is in.
        // Same for texcoords
        // We need to replicate only vertices that really need it, for non smooth only vertices
        // that belong to non smooth faces. For texcoords only those that are in the frontier between
        // different materials?
        // --------------------
        let submeshes = parse_uvs_and_submeshes(&mesh);
        let no_texture_and_smooth = submeshes.iter()
            .fold(true, |has_texture_or_flat, submesh|{
                has_texture_or_flat && (submesh.is_all_smooth() && submesh.uvs.is_empty())
            });

        let flattened_meshes;
        let flattened_indices;
        let num_submeshes;

        if no_texture_and_smooth{
            let mesh = mesh.mvert.iter().enumerate().map(|(idx, v)|{
                    vertex(v.position, v.normal, zero(), idx as u32)
                }).collect::<Vec<_>>();
            flattened_meshes = vec![mesh];
            let indices = submeshes.iter()
                .map(|submesh| submesh.indices.to_vec()).collect::<Vec<_>>();
            num_submeshes = indices.len();
            flattened_indices = Some(indices);
        } else {
            flattened_meshes = flatten(&mesh, &submeshes);
            flattened_indices = None;
            num_submeshes = flattened_meshes.len();
        }

        let materials = blend_mesh
            .get_ptr_slice("mat", num_submeshes)
            .map(|mesh_materials| {
                mesh_materials.iter().map(|material_obj| {
                    let mat_id;
                    let material;
                    if let Some(lib_id) = library_id.linked_library_id(material_obj) {
                        mat_id = ObjectId::new(lib_id.clone(), material_obj.name().unwrap());
                        if scene_data.materials.contains_key(&mat_id) {
                            return Some(mat_id)
                        }
                        let library = &libraries[&lib_id];
                        let material_obj = library
                            .object_by_name(material_obj.name().unwrap())
                            .unwrap();
                        material = material::parse_material(
                            material_obj,
                            library_id.clone(),
                            libraries,
                            &mut scene_data.images,
                        );
                    }else{
                        mat_id = ObjectId::new(library_id.clone(), material_obj.name().unwrap());
                        if scene_data.materials.contains_key(&mat_id) {
                            return Some(mat_id)
                        }
                        material = material::parse_material(
                            material_obj.clone(),
                            library_id.clone(),
                            libraries,
                            &mut scene_data.images,
                        );
                    }
                    // TODO: return Result<TriMesh> instead of unwrap material here
                    scene_data.materials.insert(mat_id.clone(), material.unwrap());
                    Some(mat_id)
                }).collect()
            }).unwrap_or(vec![None; num_submeshes]);

        //mesh.recalculate_normals();
        let original_vertices = flattened_meshes.iter()
                .flat_map(|mesh| mesh.iter().cloned())
                .collect::<Vec<_>>();

        let original_indices = flattened_indices.as_ref().map(|flattened_indices| flattened_indices
            .iter()
            .flat_map(|indices| indices).cloned()
            .collect::<Vec<_>>()
        ).unwrap_or(vec![]);

        let key = blend_mesh
            .get_object("key")
            .ok()
            .map(|key| library_id.object_id(&key));

        // if let Some(flattened_indices) = flattened_indices.as_mut(){
        //     for (flattened_mesh, flattened_indices) in flattened_meshes.iter()
        //         .zip(flattened_indices.iter_mut())
        //     {
        //         fix_trimesh_indices_winding(&original_vertices, flattened_indices)
        //     }
        // }else{
        //     // for flattened_mesh in flattened_meshes.iter_mut()
        //     // {
        //         fix_trimesh_winding(&mut original_vertices)
        //     // }
        // }

        TriMesh{
            flattened_meshes,
            flattened_indices,
            original_vertices,
            original_indices,
            materials,
            key,
        }
    }

    pub fn original_vertices(&self) -> &[Vertex]{
        &self.original_vertices
    }

    pub fn original_indices(&self) -> &[u32]{
        &self.original_indices
    }

    pub fn submeshes(&self) -> SubMeshIter{
        SubMeshIter{
            trimesh: self,
            next: 0,
        }
    }

    pub fn submeshes_vertices<'s>(&self) -> &[Vec<Vertex>]{
        &self.flattened_meshes
    }

    pub fn submeshes_indices<'s>(&self) -> Option<&Vec<Vec<u32>>>{
        self.flattened_indices.as_ref()
    }

    pub fn materials(&self) -> &[Option<ObjectId>]{
        &self.materials
    }

    pub fn key(&self) -> Option<&ObjectId>{
        self.key.as_ref()
    }
}

pub struct SubMesh<'a>{
    pub material: Option<&'a ObjectId>,
    pub vertices: &'a [Vertex],
    pub indices: Option<&'a [u32]>,
}

pub struct SubMeshIter<'a>{
    trimesh: &'a TriMesh,
    next: usize,
}

impl<'a> Iterator for SubMeshIter<'a>{
    type Item = SubMesh<'a>;
    fn next(&mut self) -> Option<SubMesh<'a>>{
        if self.trimesh.materials.len() == self.next {
            return None;
        }
        let next = self.next;
        self.next += 1;
        let material = self.trimesh.materials[next].as_ref();
        if let Some(ref indices) = self.trimesh.flattened_indices{
            Some(SubMesh{
                material,
                vertices: &self.trimesh.original_vertices,
                indices: Some(&indices[next]),
            })
        }else{
            Some(SubMesh{
                material,
                vertices: &self.trimesh.flattened_meshes[next],
                indices: None,
            })
        }
    }
}


struct UvsIndices{
    indices: Vec<u32>,
    uvs: Vec<Vec2>,
    normals: Vec<Vec3>,
    smooth: Vec<bool>
}

impl UvsIndices{
    fn is_all_smooth(&self) -> bool{
        self.smooth.iter().all(|s| *s)
    }
}

fn parse_uvs_and_submeshes(blend_mesh: &Mesh) -> Vec<UvsIndices>{
    if blend_mesh.mvert.is_empty() || blend_mesh.mloop.is_empty(){
        return Vec::new();
    }

    let loops = &blend_mesh.mloop;
    let uv_loops = &blend_mesh.mloopuv;
    const SMOOTH: u8 = 1;

    let has_uv = !uv_loops.is_empty();
    let mut submeshes = Vec::new();
    if !blend_mesh.mpoly.is_empty(){
        for poly in blend_mesh.mpoly.iter(){
            let loopstart = poly.loopstart as usize;
            let mat_nr = poly.mat_nr as usize;
            while mat_nr + 1 > submeshes.len() {
                submeshes.push(UvsIndices{ indices: vec![], uvs: vec![], smooth: vec![], normals: vec![]});
            }

            let submesh = &mut submeshes[mat_nr];
            let indices = &mut submesh.indices;
            let uvs = &mut submesh.uvs;
            let normals = &mut submesh.normals;
            let smooth = &mut submesh.smooth;
            //let flag = poly.get::<i8>("flag");
            //let pad = poly.get::<i8>("pad");
            let v0 = loops[loopstart].v;
            let v1 = loops[loopstart+1].v;
            let v2 = loops[loopstart+2].v;
            let pos0 = blend_mesh.mvert[v0 as usize].position.to_pnt();
            let pos1 = blend_mesh.mvert[v1 as usize].position.to_pnt();
            let pos2 = blend_mesh.mvert[v2 as usize].position.to_pnt();
            indices.push(v0);
            indices.push(v1);
            indices.push(v2);
            if has_uv{
                uvs.push(uv_loops[loopstart].uv);
                uvs.push(uv_loops[loopstart + 1].uv);
                uvs.push(uv_loops[loopstart + 2].uv);
            }

            if poly.flag & SMOOTH != 0{
                normals.push(blend_mesh.mvert[v0 as usize].normal);
                normals.push(blend_mesh.mvert[v1 as usize].normal);
                normals.push(blend_mesh.mvert[v2 as usize].normal);
            }else{
                let normal = (pos1 - pos0).cross(&(pos2 - pos0));
                normals.push(normal);
                normals.push(normal);
                normals.push(normal);
            }
            smooth.push(poly.flag & SMOOTH != 0);
        }
    }

    submeshes
}

#[allow(dead_code)]
fn parse_wireframe_indices(blend_mesh: &blender::Object) -> Vec<u32>{
    let mut wireframe_indices = Vec::new();
    let num_edges = *blend_mesh.get::<i32>("totedge").unwrap() as usize;
    if num_edges > 0{
        let edges = blend_mesh.get_ptr_slice("medge", num_edges).unwrap();
        for edge in edges{
            let from = edge.get::<u32>("v1").unwrap();
            let to = edge.get::<u32>("v2").unwrap();
            wireframe_indices.push(*from);
            wireframe_indices.push(*to);
        }
    }
    wireframe_indices
}

fn flatten(blend_mesh: &Mesh, submeshes: &[UvsIndices]) -> Vec<Vec<Vertex>>{
    let zero = [zero(), zero(), zero()];

    submeshes.iter().map(|submesh|{
        let uvs: Box<dyn Iterator<Item=&[Vec2]>> = if submesh.uvs.is_empty(){
            Box::new(iter::repeat(zero.as_ref()))
        }else{
            Box::new(submesh.uvs.chunks(3))
        };
        submesh.indices
            .chunks(3)
            .zip(uvs)
            .zip(submesh.smooth.iter())
            .zip(submesh.normals.chunks(3))
            .flat_map(|(((face, uvs), smooth), normals)|{
                let p1 = blend_mesh.mvert[face[0] as usize].position;
                let p2 = blend_mesh.mvert[face[1] as usize].position;
                let p3 = blend_mesh.mvert[face[2] as usize].position;
                if *smooth {
                    let n1 = blend_mesh.mvert[face[0] as usize].normal;
                    let n2 = blend_mesh.mvert[face[1] as usize].normal;
                    let n3 = blend_mesh.mvert[face[2] as usize].normal;

                    vec![
                        vertex(p1, n1, uvs[0], face[0]),
                        vertex(p2, n2, uvs[1], face[1]),
                        vertex(p3, n3, uvs[2], face[2]),
                    ]
                }else{
                    // let v1 = p2 - p1;
                    // let v2 = p3 - p1;
                    // let normal = vec3(
                    //     v1.y * v2.z - v1.z * v2.y,
                    //     v1.z * v2.x - v1.x * v2.z,
                    //     v1.x * v2.y - v1.y * v2.x,
                    // ).normalize();

                    vec![
                        vertex(p1, normals[0], uvs[0], face[0]),
                        vertex(p2, normals[1], uvs[1], face[1]),
                        vertex(p3, normals[2], uvs[2], face[2]),
                    ]
                }
        }).collect()
    }).collect()
}

// Recalculates correct winding from normals
// fn fix_trimesh_indices_winding(verts: &[Vertex], indices: &mut [u32]){
//     for face in indices.chunks_mut(3){
//         let v0 = &verts[face[0] as usize];
//         let v1 = &verts[face[1] as usize];
//         let v2 = &verts[face[2] as usize];

//         let d0 = v0.position - v2.position;
//         let d1 = v1.position - v2.position;
//         let normal = d0.xyz().cross(&d1.xyz()).normalize();

//         // if normal.component_mul(&v0.normal).dot(&vec3!(1.)) < 0.{
//         //     println!("Fixing");
//         //     face.swap(0, 2)
//         // }

//         if normal.dot(&v0.normal) < 0.
//             && normal.dot(&v1.normal) < 0.
//             && normal.dot(&v2.normal) < 0.
//         {
//             face.swap(0, 2)
//         }

//         // let center = (v0.position + v1.position + v2.position) / 3.;

//         // let v3 = center + v0.normal;
//         // let mat0 = Mat4::new(
//         //     v0.position.x, v0.position.y, v0.position.z, 1.,
//         //     v1.position.x, v1.position.y, v1.position.z, 1.,
//         //     v2.position.x, v2.position.y, v2.position.z, 1.,
//         //     v3.x, v3.y, v3.z, 1.,
//         // ).transpose();

//         // let v3 = center + v1.normal;
//         // let mat1 = Mat4::new(
//         //     v0.position.x, v0.position.y, v0.position.z, 1.,
//         //     v1.position.x, v1.position.y, v1.position.z, 1.,
//         //     v2.position.x, v2.position.y, v2.position.z, 1.,
//         //     v3.x, v3.y, v3.z, 1.,
//         // ).transpose();

//         // let v3 = center + v2.normal;
//         // let mat2 = Mat4::new(
//         //     v0.position.x, v0.position.y, v0.position.z, 1.,
//         //     v1.position.x, v1.position.y, v1.position.z, 1.,
//         //     v2.position.x, v2.position.y, v2.position.z, 1.,
//         //     v3.x, v3.y, v3.z, 1.,
//         // ).transpose();

//         // if mat0.determinant() < 0. && mat1.determinant() < 0. && mat2.determinant() < 0.{
//         //     face.swap(0, 2)
//         // }
//     }
// }

// Recalculates correct winding from normals
// fn fix_trimesh_winding(verts: &mut [Vertex]){
//     for face in verts.chunks_mut(3){
//         let v0 = &face[0];
//         let v1 = &face[1];
//         let v2 = &face[2];

//         let d0 = v0.position - v2.position;
//         let d1 = v1.position - v2.position;
//         let normal = d0.xyz().cross(&d1.xyz()).normalize();

//         // if normal.component_mul(&v0.normal).dot(&vec3!(1.)) < 0.{
//         //     println!("Fixing");
//         //     face.swap(0, 2)
//         // }

//         if normal.dot(&v0.normal) < 0.
//             && normal.dot(&v1.normal) < 0.
//             && normal.dot(&v2.normal) < 0.
//         {
//             face.swap(0, 2)
//         }

//         // let center = (v0.position + v1.position + v2.position) / 3.;

//         // let v3 = center + v0.normal;
//         // let mat0 = Mat4::new(
//         //     v0.position.x, v0.position.y, v0.position.z, 1.,
//         //     v1.position.x, v1.position.y, v1.position.z, 1.,
//         //     v2.position.x, v2.position.y, v2.position.z, 1.,
//         //     v3.x, v3.y, v3.z, 1.,
//         // ).transpose();

//         // let v3 = center + v1.normal;
//         // let mat1 = Mat4::new(
//         //     v0.position.x, v0.position.y, v0.position.z, 1.,
//         //     v1.position.x, v1.position.y, v1.position.z, 1.,
//         //     v2.position.x, v2.position.y, v2.position.z, 1.,
//         //     v3.x, v3.y, v3.z, 1.,
//         // ).transpose();

//         // let v3 = center + v2.normal;
//         // let mat2 = Mat4::new(
//         //     v0.position.x, v0.position.y, v0.position.z, 1.,
//         //     v1.position.x, v1.position.y, v1.position.z, 1.,
//         //     v2.position.x, v2.position.y, v2.position.z, 1.,
//         //     v3.x, v3.y, v3.z, 1.,
//         // ).transpose();

//         // if mat0.determinant() < 0. && mat1.determinant() < 0. && mat2.determinant() < 0.{
//         //     face.swap(0, 2)
//         // }
//     }
// }

//
// fn parse_materials<'a>(blend_mesh: &'a blender::Object, num_materials: usize, materials: &HashMap<String, ::Material>) -> blender::Result<Vec<&'a str>>{
//     blend_mesh.get_ptr_slice("mat", num_materials).map(|materials| {
//         materials.iter().map(|material| {
//             let mat_name = material.name().unwrap();
//             mat_name
//         }).collect()
//     })
// }

#[allow(dead_code)]
fn parse_faces(blend_mesh: &blender::Object) -> Vec<Vec<u32>>{
    let num_faces = *blend_mesh.get::<i32>("totface").unwrap() as usize;
    if num_faces > 0{
        // TODO: should go thorugh faces and create indices
        //let faces = blend_mesh.get_ptr_slice("mface", num_faces).unwrap();
    }else{
    }
    Vec::new()
}