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
use crate::idtree;

use blender;

use crate::bones::Skeleton;
use crate::model::Model;
use crate::utils::{self, ObjectId, LibraryId};
use crate::curves;
use crate::lamp;
use crate::scene::{SceneData, BlenderObject};
use crate::empty::Empty;
use crate::shape_keys;

use hashbrown::HashMap;
use std::path:: PathBuf;
use crate::mesh::Mesh;
use crate::trimesh::TriMesh;
use super::packedfile;
use itertools::Itertools;

fn load_libraries(blend: &blender::File) -> Result<(HashMap<LibraryId, blender::File>, LibraryId), blender::Error> {
    let mut libraries = HashMap::new();
    let library_id = if let Some(file_path) = blend.file_path(){
        LibraryId::Path(file_path.to_owned())
    }else{
        LibraryId::Packed(None, "/".to_owned())
    };
    load_libraries_recursively(blend, &library_id, &mut libraries)?;
    libraries.insert(library_id.clone(), blend.clone());
    Ok((libraries, library_id))
}

fn load_actions(blend: &blender::File, scene_data: &mut SceneData, library_id: &LibraryId, libraries: &HashMap<LibraryId, blender::File>){
    scene_data.actions = curves::parse_actions(blend, library_id, libraries);
}


pub fn load(blend: &blender::File) -> Result<SceneData, blender::Error> {
    let path = blend.file_path().map(|p| p.to_owned());
    let mut scene_data = SceneData::new(path);
    let (libraries, library_id) = load_libraries(blend)?;
    load_actions(blend, &mut scene_data, &library_id, &libraries);
    blend_objects_to_scene_data(&mut scene_data, blend, &library_id, None, None, &libraries);

    Ok(scene_data)
}

fn group_objects<'a>(blend: &'a blender::File, group_names: &[&str]) -> Result<Vec<blender::Object<'a>>, blender::Error>{
    let groups = blend.objects("Group");
    let groups = groups
        .filter(|g| group_names.contains(&g.name().unwrap()) )
        .collect::<Vec<_>>();
    if groups.len() == group_names.len() {
        let objects = groups.into_iter()
            .flat_map(|group| group.get_list("gobject").unwrap().iter()
                                .filter_map(|go| go.get_object("ob").ok()))
            .collect();
        Ok(objects)
    }else{
        Err(blender::Error::from(format!("Couldn't find some groups when loading blender file. Asked for {:?} got {:?}",
            group_names,
            groups.iter().map(|g| g.name().unwrap()).collect::<Vec<_>>())))
    }
}

fn collection_objects<'a>(blend: &'a blender::File, group_names: &[&str]) -> Result<Vec<blender::Object<'a>>, blender::Error>{
    let collections = blend.objects("Collection");
    let collections = collections
        .filter(|g| group_names.contains(&g.name().unwrap()))
        .collect::<Vec<_>>();
    if collections.len() == group_names.len() {
        let objects = collections.into_iter()
            .flat_map(|collection| parse_collection(collection))
            .collect();
        Ok(objects)
    }else{
        Err(blender::Error::from(format!("Couldn't find some collections when loading blender file. Asked for {:?} got {:?}",
            group_names,
            collections.iter().map(|c| c.name().unwrap()).collect::<Vec<_>>())))
    }
}

pub fn load_groups(blend: &blender::File, group_names: &[&str]) -> Result<SceneData, blender::Error>{
    let path = blend.file_path().map(|p| p.to_owned());
    let mut scene_data = SceneData::new(path);
    let (libraries, library_id) = load_libraries(blend)?;
    load_actions(blend, &mut scene_data, &library_id, &libraries);
    let version: u32 = blend.header().version_number().parse().unwrap();
    let objects = if version >= 280 {
        collection_objects(blend, group_names)?
    }else{
        group_objects(blend, group_names)?
    };
    blend_objects_to_scene_data(&mut scene_data, blend, &library_id, Some(&objects), None, &libraries);

    Ok(scene_data)
}

fn objects<'a>(blend: &'a blender::File, object_names: &[&str]) -> Vec<blender::Object<'a>>{
    let objects = blend.objects("Object");
    objects
        .filter(|o| object_names.contains(&o.name().unwrap()) )
        .collect()
}

pub fn load_objects(blend: &blender::File, object_names: &[&str]) -> Result<SceneData, blender::Error> {
    let path = blend.file_path().map(|p| p.to_owned());
    let mut scene_data = SceneData::new(path);
    let (libraries, library_id) = load_libraries(blend)?;
    load_actions(blend, &mut scene_data, &library_id, &libraries);
    let objects = objects(blend, object_names);
    blend_objects_to_scene_data(&mut scene_data, blend, &library_id, Some(&objects), None, &libraries);

    Ok(scene_data)
}

fn load_action(action_id: &ObjectId, scene_data: &mut SceneData, libraries: &HashMap<LibraryId, blender::File>){
    if !scene_data.actions.contains_key(action_id) {
        let library = &libraries[&action_id.source_file];
        let fps = curves::fps_for_file(library);
        let default_action = library.object_by_name(&action_id.name).unwrap();
        let default_action = curves::parse_action(default_action, fps).unwrap();
        scene_data.actions.insert(action_id.clone(), default_action);
    }
}

fn load_blend_meshes(
    scene_data: &mut SceneData,
    library_id: LibraryId,
    blend_mesh: &blender::Object,
    vertex_groups: &[String],
    libraries: &HashMap<LibraryId, blender::File>)
{
    let object_id = library_id.object_id(blend_mesh);
    if scene_data.meshes.contains_key(&object_id){
        return;
    }
    let version = libraries[&object_id.source_file].header().version_number().parse().unwrap();
    let mesh = Mesh::parse(&blend_mesh, version).ok();
    if let Some(mesh) = mesh {
        let trimesh = TriMesh::from(
            &blend_mesh,
            library_id.clone(),
            &mesh,
            libraries,
            scene_data,
        );
        if let Some(key_id) = trimesh.key() {
            if !scene_data.keys.contains_key(&key_id){
                let library = &libraries[&key_id.source_file];
                let key_obj = library.object_by_name(&key_id.name).unwrap();
                let key = shape_keys::parse(&key_obj, key_id.source_file.clone(), libraries, scene_data);
                scene_data.keys.insert(key_id.clone(), key);
            }

            if !scene_data.trimesh_keys.contains_key(&key_id) {
                // TODO: what happens if we try to add a mesh from two models with shapekeys affecting
                // that mesh and vertex groups? the vertex groups could be different since they are
                // set at the model level not the mesh
                let trimeshkey = scene_data.keys[key_id].clone()
                    .to_trimesh(
                        &blend_mesh,
                        library_id.clone(),
                        &mesh,
                        vertex_groups,
                        libraries,
                        scene_data,
                    );
                    scene_data.trimesh_keys.insert(key_id.clone(), trimeshkey);
            }
        }
        scene_data.meshes.insert(object_id.clone(), mesh);
        scene_data.trimeshes.insert(object_id, trimesh);
    }
}

fn load_libraries_recursively(
    blend: &blender::File,
    parent_id: &LibraryId,
    libraries: &mut HashMap<LibraryId, blender::File>) -> Result<(), blender::Error>
{
    for lib in blend.objects("Library") {
        if lib.get_str("name").unwrap().len() > 2 {
            let lib_name = &lib.get_str("name").unwrap()[2..];
            let lib_id;
            let lib = if let Ok(packedfile) = lib.get_object("packedfile"){
                let data = packedfile::data(&packedfile).unwrap();
                lib_id = if let Some(parent_path) = blend.file_path().map(|p| p.to_owned()) {
                    LibraryId::Packed(Some(parent_path), lib_name.to_owned())
                }else{
                    // match parent_id {
                    //     Some(LibraryId::Path(path))
                    //         => LibraryId::Packed(Some(path.clone()), lib_name.to_owned()),
                    //     Some(LibraryId::Packed(path, parent_name))
                    //         => LibraryId::Packed(path.clone(), parent_name.clone() + "/" + lib_name),
                    //     None => LibraryId::Packed(None, lib_name.to_owned()),
                    // }
                     parent_id.join(lib_name)
                };
                blender::File::from_bytes(data)
                    .map_err(|err| blender::Error(format!("Couldn't load linked library from packed file: {}", err)))?
            }else{
                let lib_path = if let Some(parent_path) = blend.file_path().and_then(|p| p.parent()){
                    parent_path.join(lib_name)
                }else{
                    PathBuf::from(lib_name)
                };
                lib_id = LibraryId::Path(lib_path.clone());
                blender::File::load(&lib_path)
                    .map_err(|err| blender::Error(format!("Couldn't load linked library from {}: {}", lib_path.display(), err)))?
            };
            load_libraries_recursively(&lib, &lib_id, libraries)?;
            libraries.insert(lib_id, lib);
        }
    }
    Ok(())
}

fn blend_objects_to_scene_data(
    scene_data: &mut SceneData,
    blend: &blender::File,
    library_id: &LibraryId,
    objects: Option<&[blender::Object]>,
    parent: Option<idtree::NodeId>,
    libraries: &HashMap<LibraryId, blender::File>)
{
    // parse scene hierarchicaly
    let blender_scene = blend.find_object("Scene").unwrap();
    let scene_eevee = blender_scene.get_object("eevee").ok();
    match blender_scene.get_object("master_collection"){
        Ok(master_collection) => {
            // Has collections: 2.8 file
            let root_objects = parse_collection(master_collection).filter_map(|obj| {
                if obj.get_object("parent").is_err(){
                    Some(obj)
                }else{
                    None
                }
            });

            for obj in root_objects {
                parse_object(
                    &obj,
                    library_id,
                    parent,
                    objects,
                    "",
                    scene_data,
                    libraries,
                    scene_eevee.as_ref()
                )
            }
        }
        Err(_) => {
            // objects in base: 2.7 file
            let root_objects = blender_scene.get_list("base").unwrap().iter().filter_map(|base| {
                let obj = base.get_object("object").unwrap();
                if obj.get_object("parent").is_err(){
                    Some(obj)
                }else{
                    None
                }
            });

            for obj in root_objects {
                parse_object(
                    &obj,
                    library_id,
                    parent,
                    objects,
                    "",
                    scene_data,
                    libraries,
                    scene_eevee.as_ref()
                )
            }
        }
    }
}

fn parse_collection<'a>(collection: blender::Object<'a>) -> impl Iterator<Item = blender::Object<'a>>{
    collection.get_list("children").unwrap().iter().flat_map(|child|{
        let collection = child.get_object("collection").unwrap();
        parse_collection(collection).collect::<Vec<_>>()
    }).chain(collection.get_list("gobject").unwrap().iter().map(|obj| {
        obj.get_object("ob").unwrap()
    })).unique_by(|obj| obj.name().ok())
}


#[allow(dead_code)]
pub enum ObjectRestrict{
	View    = 1 << 0,
	Select  = 1 << 1,
	Render  = 1 << 2,
}

fn parse_empty_linked(
    obj: &blender::Object,
    parent_library_id: &LibraryId,
    scene_data: &mut SceneData,
    libraries: &HashMap<LibraryId, blender::File>,
    parent: idtree::NodeId,
) -> Result<(), blender::Error>
{
    let dup_group = obj.get_object("dup_group")?;
    let group_name = dup_group.name()?;
    let library_id= parent_library_id.linked_library_id(&dup_group)
        .ok_or_else(|| "Can't find linked library".to_owned())?;
    let lib = &libraries[&library_id];
    trace!("Parsing library children for {} from group {} in file {:?}", obj.name().unwrap(), group_name, lib.file_path());
    let version: u32 = lib.header().version_number().parse().unwrap();
    let group_objects = if version >= 280 {
        collection_objects(&lib, &[group_name])?
    }else{
        group_objects(&lib, &[group_name])?
    };
    blend_objects_to_scene_data(
        scene_data,
        &lib,
        &library_id,
        Some(&group_objects),
        Some(parent),
        libraries
    );
    trace!("Done parsing library children for {}", obj.name().unwrap());
    Ok(())
}

fn parse_as_empty(
    obj: &blender::Object,
    library_id: LibraryId,
    scene_data: &mut SceneData,
    parent: Option<idtree::NodeId>,
    libraries: &HashMap<LibraryId, blender::File>,
    parsed_linked: bool) -> Option<idtree::NodeId>
{
    trace!("Parsing empty {}", obj.name().unwrap());
    let transformations = utils::transformations(&obj);
    let name = obj.name().unwrap().to_owned();
    let default_action =
        curves::default_action_name_for(&obj, &library_id, libraries);
    if let Some(default_action_id) = default_action.as_ref() {
        load_action(default_action_id,  scene_data, libraries);
    }
    let trafos = BlenderObject::Empty(Empty{
        name: ObjectId::new(library_id.clone(), &name),
        transformations,
        default_action
    });
    let id = if let Some(parent) = parent{
        parent.append_new(trafos, &mut scene_data.arena).id()
    }else{
        scene_data.arena.new_node(trafos).id()
    };

    if parsed_linked {
        if let Err(_) = parse_empty_linked(obj, &library_id, scene_data, libraries, id){
            trace!("No linked collection for this empty")
        }
    }

    scene_data.empties.insert(ObjectId::new(library_id, &name), id);

    Some(id)
}

fn check_children_in_groups(
    parent: &blender::Object,
    parent_library_id: &LibraryId,
    objects: &[blender::Object],
    libraries: &HashMap<LibraryId, blender::File>) -> bool
{
    for child in parent.children() {
        let name = child.name().unwrap().to_owned();
        let obj;
        let library_id;
        if let Some(lib_id) = parent_library_id.linked_library_id(parent){
            let lib = &libraries[&lib_id];
            obj = lib.objects("Object")
                .find(|linked| linked.name().unwrap() == child.name().unwrap())
                .unwrap();
            library_id = lib_id;
        }else{
            obj = child.clone();
            library_id = parent_library_id.clone();
        };
        if objects.iter().find(|obj| obj.name() == Ok(&name)).is_some() {
            return true
        }
        if check_children_in_groups(
            &obj,
            &library_id,
            objects,
            libraries)
        {
            return true
        }
    }

    false
}


fn parse_object(blend_obj: &blender::Object,
                parent_library_id: &LibraryId,
                parent: Option<idtree::NodeId>,
                objects: Option<&[blender::Object]>,
                indent: &str,
                scene_data: &mut SceneData,
                libraries: &HashMap<LibraryId, blender::File>,
                scene_eevee: Option<&blender::Object>,
            )
{
    let obj;
    let library_id;
    if let Some(lib_id) = parent_library_id.linked_library_id(blend_obj){
        trace!("Following link {}", blend_obj.name().unwrap());
        let lib = &libraries[&lib_id];
        obj = lib.objects("Object")
            .find(|linked| linked.name().unwrap() == blend_obj.name().unwrap())
            .unwrap();
        library_id = lib_id;
    }else{
        obj = blend_obj.clone();
        library_id = parent_library_id.clone();
    };

    let ty = *obj.get::<blender::ObjectType>("type").unwrap();
    let restrictflag: u8 = *obj.get("restrictflag").unwrap();
    let hidden = restrictflag & ObjectRestrict::Render as u8 != 0;
    let nodeid = if let Ok(proxied) = obj.get_object("proxy") {
        let proxy_library_id = library_id.linked_library_id(&proxied)
            .unwrap_or_else(|| library_id.clone());
        trace!("Found proxy {} in {} -> {} in {}", obj.name().unwrap(), library_id, proxied.name().unwrap(), proxy_library_id);
        scene_data.proxies.insert(
            ObjectId::new(library_id.clone(), obj.name().unwrap()),
            ObjectId::new(proxy_library_id, proxied.name().unwrap())
        );
        None
    }else{
        if objects.is_none() || objects.unwrap().iter()
            .find(|obj2| obj2.name().unwrap() == obj.name().unwrap())
            .is_some()
        {
            trace!("Found object {:?} type {:?}", obj.name(), ty);
            match ty{
                blender::ObjectType::Armature => {
                    trace!("Parsing armature {}", obj.name().unwrap());
                    let data = obj.get_object("data").unwrap();
                    let skeleton = if let Some(lib_id) = library_id.linked_library_id(&data) {
                        let lib = &libraries[&lib_id];
                        let data_name = data.name().unwrap();
                        let armature_data = lib
                            .objects("bArmature")
                            .find(|armature_data| {
                                armature_data.name() == Ok(data_name)
                            })
                            .unwrap();
                        let name = if let Ok(proxy) = obj.get_object("proxy"){
                            proxy.name().unwrap()
                        }else{
                            obj.name().unwrap()
                        };
                        trace!("From library as {}", name);
                        Skeleton::parse(name, &obj, &lib_id, &armature_data, libraries)
                    }else{
                        Skeleton::parse(obj.name().unwrap(), &obj, &library_id, &data, libraries)
                    };

                    if let Some(default_action) = skeleton.default_action() {
                        load_action(default_action, scene_data, libraries);
                    }

                    let skeleton = BlenderObject::Armature(skeleton);
                    let object_id = skeleton.name().clone();
                    let nodeid = if let Some(parent) = parent{
                        parent.append_new(skeleton, &mut scene_data.arena).id()
                    }else{
                        scene_data.arena.new_node(skeleton).id()
                    };
                    scene_data.skeletons.insert(object_id, nodeid);
                    Some(nodeid)
                }

                blender::ObjectType::Mesh => {
                    trace!("Parsing model {}", obj.name().unwrap());
                    // TODO: we are retrieving this also inside model were it comes from but passing
                    // it as a parameter seems weird since it belongs to the model itself but we
                    // needed before parsing the model to be able to parse the shapekeys from the
                    // mesh
                    let vertex_groups: Vec<String> = obj.get_list("defbase").unwrap().iter()
                        .map(|deformation| {
                            let vertex_group = deformation.name().unwrap().to_string();
                            vertex_group
                        }).collect();
                    let mesh_obj = obj.get_object("data").unwrap();
                    let model = if let Some(lib_id) = library_id.linked_library_id(&mesh_obj) {
                        let lib = &libraries[&lib_id];
                        let mesh_library_id = lib_id;
                        let mesh_name = mesh_obj.name().unwrap();
                        let mesh_data = lib.objects("Mesh")
                            .find(|mesh_data| {
                                mesh_data.name() == Ok(mesh_name)
                            })
                            .unwrap();
                        load_blend_meshes(
                            scene_data,
                            mesh_library_id.clone(),
                            &mesh_data,
                            &vertex_groups,
                            libraries
                        );
                        Model::parse(
                            &obj,
                            mesh_library_id.clone(),
                            &mesh_data,
                            !hidden,
                            scene_data,
                            libraries
                        ).unwrap()
                    }else{
                        load_blend_meshes(
                            scene_data,
                            library_id.clone(),
                            &mesh_obj,
                            &vertex_groups,
                            libraries
                        );
                        Model::parse(
                            &obj,
                            library_id.clone(),
                            &mesh_obj,
                            !hidden,
                            scene_data,
                            libraries
                        ).unwrap()
                    };

                    if let Some(default_action) = model.default_action() {
                        load_action(default_action, scene_data, libraries);
                    }

                    let object_id = model.name().clone();
                    let model = BlenderObject::Model(model);
                    let nodeid = if let Some(parent) = parent{
                        parent.append_new(model, &mut scene_data.arena).id()
                    }else{
                        scene_data.arena.new_node(model).id()
                    };
                    scene_data.models.insert(object_id, nodeid);
                    Some(nodeid)
                }

                blender::ObjectType::Lamp => {
                    // TODO: consider proxies and links
                    trace!("Parsing lamp {}", obj.name().unwrap());
                    lamp::parse(&obj, library_id.clone(), !hidden, scene_eevee).map(|lamp| {
                        let name = lamp.name.name.clone();
                        let lamp = BlenderObject::Light(lamp);
                        let nodeid = if let Some(parent) = parent{
                            parent.append_new(lamp, &mut scene_data.arena).id()
                        }else{
                            scene_data.arena.new_node(lamp).id()
                        };
                        scene_data.lamps.insert(ObjectId::new(library_id.clone(), &name), nodeid);
                        nodeid
                    })
                }

                blender::ObjectType::Empty => {
                    parse_as_empty(&obj, library_id.clone(), scene_data, parent, libraries, true)
                }

                _ => {
                    trace!("Found an unsupported type {:?}, parsing as empty", ty);
                    parse_as_empty(&obj, library_id.clone(), scene_data, parent, libraries, false)
                },
            }
        }else{
            // TODO: should we pass a flag to parse linked as empty instead?
            if check_children_in_groups(
                &obj,
                &library_id,
                objects.as_ref().unwrap(),
                libraries)
            {
                trace!("Found object {:?} not in list of objects, creating as empty and not parsing linked", obj.name());
                parse_as_empty(&obj, library_id.clone(), scene_data, parent, libraries, false)
            }else{
                None
            }
        }
    };

    if let Some(nodeid) = nodeid{
        if parent.is_none(){
            scene_data.roots.push(nodeid);
        }

        for child in obj.children() {
            trace!("Parsing {} child {:?}", obj.name().unwrap(), child.name());
            parse_object(
                &child,
                &library_id,
                Some(nodeid),
                objects,
                &(indent.to_string() + "\t"),
                scene_data,
                libraries,
                scene_eevee)
        }
    }
}