style cleanup: whitespace, braces
[blender.git] / source / blender / collada / DocumentImporter.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Nathan Letwory.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/collada/DocumentImporter.cpp
24  *  \ingroup collada
25  */
26
27 // TODO:
28 // * name imported objects
29 // * import object rotation as euler
30
31 #include <string>
32 #include <map>
33 #include <algorithm> // sort()
34
35 #include "COLLADAFWRoot.h"
36 #include "COLLADAFWStableHeaders.h"
37 #include "COLLADAFWColorOrTexture.h"
38 #include "COLLADAFWIndexList.h"
39 #include "COLLADAFWMeshPrimitiveWithFaceVertexCount.h"
40 #include "COLLADAFWPolygons.h"
41 #include "COLLADAFWSampler.h"
42 #include "COLLADAFWTypes.h"
43 #include "COLLADAFWVisualScene.h"
44 #include "COLLADAFWArrayPrimitiveType.h"
45 #include "COLLADAFWLibraryNodes.h"
46 #include "COLLADAFWCamera.h"
47 #include "COLLADAFWLight.h"
48
49 #include "COLLADASaxFWLLoader.h"
50 #include "COLLADASaxFWLIExtraDataCallbackHandler.h"
51
52 #include "BLI_listbase.h"
53 #include "BLI_math.h"
54 #include "BLI_string.h"
55 #include "BLI_utildefines.h"
56
57 #include "BKE_camera.h"
58 #include "BKE_main.h"
59 #include "BKE_lamp.h"
60 #include "BKE_library.h"
61 #include "BKE_texture.h"
62 #include "BKE_fcurve.h"
63 #include "BKE_depsgraph.h"
64 #include "BLI_path_util.h"
65 #include "BKE_scene.h"
66 #include "BKE_global.h"
67 #include "BKE_material.h"
68 #include "BKE_utildefines.h"
69 #include "BKE_image.h"
70
71 #include "DNA_camera_types.h"
72 #include "DNA_lamp_types.h"
73
74 #include "RNA_access.h"
75
76 #include "MEM_guardedalloc.h"
77
78 #include "ExtraHandler.h"
79 #include "ErrorHandler.h"
80 #include "DocumentImporter.h"
81 #include "TransformReader.h"
82
83 #include "collada_internal.h"
84 #include "collada_utils.h"
85
86
87 /*
88   COLLADA Importer limitations:
89   - no multiple scene import, all objects are added to active scene
90  */
91
92 // #define COLLADA_DEBUG
93 // creates empties for each imported bone on layer 2, for debugging
94 // #define ARMATURE_TEST
95
96 DocumentImporter::DocumentImporter(bContext *C, const char *filename) :
97         mImportStage(General),
98         mFilename(filename),
99         mContext(C),
100         armature_importer(&unit_converter, &mesh_importer, &anim_importer, CTX_data_scene(C)),
101         mesh_importer(&unit_converter, &armature_importer, CTX_data_scene(C)),
102         anim_importer(&unit_converter, &armature_importer, CTX_data_scene(C))
103 {}
104
105 DocumentImporter::~DocumentImporter()
106 {
107         TagsMap::iterator etit;
108         etit = uid_tags_map.begin();
109         while (etit!=uid_tags_map.end()) {
110                 delete etit->second;
111                 etit++;
112         }
113 }
114
115 bool DocumentImporter::import()
116 {
117         ErrorHandler errorHandler;
118         COLLADASaxFWL::Loader loader(&errorHandler);
119         COLLADAFW::Root root(&loader, this);
120         ExtraHandler *ehandler = new ExtraHandler(this, &(this->anim_importer));
121         
122         loader.registerExtraDataCallbackHandler(ehandler);
123
124         if (!root.loadDocument(mFilename)) {
125                 fprintf(stderr, "COLLADAFW::Root::loadDocument() returned false on 1st pass\n");
126                 return false;
127         }
128         
129         if (errorHandler.hasError())
130                 return false;
131         
132         /** TODO set up scene graph and such here */
133         
134         mImportStage = Controller;
135         
136         COLLADASaxFWL::Loader loader2;
137         COLLADAFW::Root root2(&loader2, this);
138         
139         if (!root2.loadDocument(mFilename)) {
140                 fprintf(stderr, "COLLADAFW::Root::loadDocument() returned false on 2nd pass\n");
141                 return false;
142         }
143         
144         
145         delete ehandler;
146
147         return true;
148 }
149
150 void DocumentImporter::cancel(const COLLADAFW::String& errorMessage)
151 {
152         // TODO: if possible show error info
153         //
154         // Should we get rid of invisible Meshes that were created so far
155         // or maybe create objects at coordinate space origin?
156         //
157         // The latter sounds better.
158 }
159
160 void DocumentImporter::start() {}
161
162 void DocumentImporter::finish()
163 {
164         if (mImportStage!=General)
165                 return;
166                 
167         /** TODO Break up and put into 2-pass parsing of DAE */
168         std::vector<const COLLADAFW::VisualScene*>::iterator it;
169         for (it = vscenes.begin(); it != vscenes.end(); it++) {
170                 PointerRNA sceneptr, unit_settings;
171                 PropertyRNA *system, *scale;
172                 // TODO: create a new scene except the selected <visual_scene> - use current blender scene for it
173                 Scene *sce = CTX_data_scene(mContext);
174                 
175                 // for scene unit settings: system, scale_length
176                 RNA_id_pointer_create(&sce->id, &sceneptr);
177                 unit_settings = RNA_pointer_get(&sceneptr, "unit_settings");
178                 system = RNA_struct_find_property(&unit_settings, "system");
179                 scale = RNA_struct_find_property(&unit_settings, "scale_length");
180                 
181                 switch (unit_converter.isMetricSystem()) {
182                         case UnitConverter::Metric:
183                                 RNA_property_enum_set(&unit_settings, system, USER_UNIT_METRIC);
184                                 break;
185                         case UnitConverter::Imperial:
186                                 RNA_property_enum_set(&unit_settings, system, USER_UNIT_IMPERIAL);
187                                 break;
188                         default:
189                                 RNA_property_enum_set(&unit_settings, system, USER_UNIT_NONE);
190                                 break;
191                 }
192                 RNA_property_float_set(&unit_settings, scale, unit_converter.getLinearMeter());
193                 
194                 const COLLADAFW::NodePointerArray& roots = (*it)->getRootNodes();
195
196                 for (unsigned int i = 0; i < roots.getCount(); i++) {
197                         write_node(roots[i], NULL, sce, NULL, false);
198                 }
199         }
200         armature_importer.set_tags_map(this->uid_tags_map);
201         armature_importer.make_armatures(mContext);
202
203 #if 0
204         armature_importer.fix_animation();
205 #endif
206
207         for (std::vector<const COLLADAFW::VisualScene*>::iterator it = vscenes.begin(); it != vscenes.end(); it++) {
208                 const COLLADAFW::NodePointerArray& roots = (*it)->getRootNodes();
209
210                 for (unsigned int i = 0; i < roots.getCount(); i++)
211                         translate_anim_recursive(roots[i], NULL, NULL);
212         }
213
214         if (libnode_ob.size()) {
215                 Scene *sce = CTX_data_scene(mContext);
216
217                 fprintf(stderr, "got %d library nodes to free\n", (int)libnode_ob.size());
218                 // free all library_nodes
219                 std::vector<Object*>::iterator it;
220                 for (it = libnode_ob.begin(); it != libnode_ob.end(); it++) {
221                         Object *ob = *it;
222
223                         Base *base = object_in_scene(ob, sce);
224                         if (base) {
225                                 BLI_remlink(&sce->base, base);
226                                 free_libblock_us(&G.main->object, base->object);
227                                 if (sce->basact==base)
228                                         sce->basact= NULL;
229                                 MEM_freeN(base);
230                         }
231                 }
232                 libnode_ob.clear();
233
234                 DAG_scene_sort(CTX_data_main(mContext), sce);
235                 DAG_ids_flush_update(CTX_data_main(mContext), 0);
236         }
237 }
238
239
240 void DocumentImporter::translate_anim_recursive(COLLADAFW::Node *node, COLLADAFW::Node *par = NULL, Object *parob = NULL)
241 {
242
243         // The split in #29246, rootmap must point at actual root when
244         // calculating bones in apply_curves_as_matrix.
245         // This has to do with inverse bind poses being world space
246         // (the sources for skinned bones' restposes) and the way
247         // non-skinning nodes have their "restpose" recursively calculated.
248         // XXX TODO: design issue, how to support unrelated joints taking
249         // part in skinning.
250         if (par) { // && par->getType() == COLLADAFW::Node::JOINT) {
251                 // par is root if there's no corresp. key in root_map
252                 if (root_map.find(par->getUniqueId()) == root_map.end())
253                         root_map[node->getUniqueId()] = par;
254                 else
255                         root_map[node->getUniqueId()] = root_map[par->getUniqueId()];
256         }
257
258         /*COLLADAFW::Transformation::TransformationType types[] = {
259                 COLLADAFW::Transformation::ROTATE,
260                 COLLADAFW::Transformation::SCALE,
261                 COLLADAFW::Transformation::TRANSLATE,
262                 COLLADAFW::Transformation::MATRIX
263         };
264
265         Object *ob;*/
266         unsigned int i;
267
268         //for (i = 0; i < 4; i++)
269                 //ob = 
270         anim_importer.translate_Animations(node, root_map, object_map, FW_object_map);
271
272         COLLADAFW::NodePointerArray &children = node->getChildNodes();
273         for (i = 0; i < children.getCount(); i++) {
274                 translate_anim_recursive(children[i], node, NULL);
275         }
276 }
277
278 /** When this method is called, the writer must write the global document asset.
279         \return The writer should return true, if writing succeeded, false otherwise.*/
280 bool DocumentImporter::writeGlobalAsset ( const COLLADAFW::FileInfo* asset ) 
281 {
282         unit_converter.read_asset(asset);
283
284         return true;
285 }
286
287 /** When this method is called, the writer must write the scene.
288         \return The writer should return true, if writing succeeded, false otherwise.*/
289 bool DocumentImporter::writeScene ( const COLLADAFW::Scene* scene ) 
290 {
291         // XXX could store the scene id, but do nothing for now
292         return true;
293 }
294 Object* DocumentImporter::create_camera_object(COLLADAFW::InstanceCamera *camera, Scene *sce)
295 {
296         const COLLADAFW::UniqueId& cam_uid = camera->getInstanciatedObjectId();
297         if (uid_camera_map.find(cam_uid) == uid_camera_map.end()) {     
298                 fprintf(stderr, "Couldn't find camera by UID.\n");
299                 return NULL;
300         }
301         Object *ob = add_object(sce, OB_CAMERA);
302         Camera *cam = uid_camera_map[cam_uid];
303         Camera *old_cam = (Camera*)ob->data;
304         ob->data = cam;
305         old_cam->id.us--;
306         if (old_cam->id.us == 0)
307                 free_libblock(&G.main->camera, old_cam);
308         return ob;
309 }
310
311 Object* DocumentImporter::create_lamp_object(COLLADAFW::InstanceLight *lamp, Scene *sce)
312 {
313         const COLLADAFW::UniqueId& lamp_uid = lamp->getInstanciatedObjectId();
314         if (uid_lamp_map.find(lamp_uid) == uid_lamp_map.end()) {        
315                 fprintf(stderr, "Couldn't find lamp by UID.\n");
316                 return NULL;
317         }
318         Object *ob = add_object(sce, OB_LAMP);
319         Lamp *la = uid_lamp_map[lamp_uid];
320         Lamp *old_lamp = (Lamp*)ob->data;
321         ob->data = la;
322         old_lamp->id.us--;
323         if (old_lamp->id.us == 0)
324                 free_libblock(&G.main->lamp, old_lamp);
325         return ob;
326 }
327
328 Object* DocumentImporter::create_instance_node(Object *source_ob, COLLADAFW::Node *source_node, COLLADAFW::Node *instance_node, Scene *sce, bool is_library_node)
329 {
330         fprintf(stderr, "create <instance_node> under node id=%s from node id=%s\n", instance_node ? instance_node->getOriginalId().c_str() : NULL, source_node ? source_node->getOriginalId().c_str() : NULL);
331
332         Object *obn = copy_object(source_ob);
333         obn->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
334         scene_add_base(sce, obn);
335
336         if (instance_node) {
337                 anim_importer.read_node_transform(instance_node, obn);
338                 // if we also have a source_node (always ;), take its
339                 // transformation matrix and apply it to the newly instantiated
340                 // object to account for node hierarchy transforms in
341                 // .dae
342                 if (source_node) {
343                         COLLADABU::Math::Matrix4 mat4 = source_node->getTransformationMatrix();
344                         COLLADABU::Math::Matrix4 bmat4 = mat4.transpose(); // transpose to get blender row-major order
345                         float mat[4][4];
346                         for (int i = 0; i < 4; i++) {
347                                 for (int j = 0; j < 4; j++) {
348                                         mat[i][j] = bmat4[i][j];
349                                 }
350                         }
351                         // calc new matrix and apply
352                         mult_m4_m4m4(obn->obmat, obn->obmat, mat);
353                         object_apply_mat4(obn, obn->obmat, 0, 0);
354                 }
355         }
356         else {
357                 anim_importer.read_node_transform(source_node, obn);
358         }
359
360         DAG_scene_sort(CTX_data_main(mContext), sce);
361         DAG_ids_flush_update(CTX_data_main(mContext), 0);
362
363         COLLADAFW::NodePointerArray &children = source_node->getChildNodes();
364         if (children.getCount()) {
365                 for (unsigned int i = 0; i < children.getCount(); i++) {
366                         COLLADAFW::Node *child_node = children[i];
367                         const COLLADAFW::UniqueId& child_id = child_node->getUniqueId();
368                         if (object_map.find(child_id) == object_map.end())
369                                 continue;
370                         COLLADAFW::InstanceNodePointerArray &inodes = child_node->getInstanceNodes();
371                         Object *new_child = NULL;
372                         if (inodes.getCount()) { // \todo loop through instance nodes
373                                 const COLLADAFW::UniqueId& id = inodes[0]->getInstanciatedObjectId();
374                                 fprintf(stderr, "Doing %d child nodes\n", node_map.count(id));
375                                 new_child = create_instance_node(object_map.find(id)->second, node_map[id], child_node, sce, is_library_node);
376                         }
377                         else {
378                                 new_child = create_instance_node(object_map.find(child_id)->second, child_node, NULL, sce, is_library_node);
379                         }
380                         bc_set_parent(new_child, obn, mContext, true);
381
382                         if (is_library_node)
383                                 libnode_ob.push_back(new_child);
384                 }
385         }
386
387         return obn;
388 }
389
390 void DocumentImporter::write_node (COLLADAFW::Node *node, COLLADAFW::Node *parent_node, Scene *sce, Object *par, bool is_library_node)
391 {
392         Object *ob = NULL;
393         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
394         bool read_transform = true;
395
396         std::vector<Object*> * objects_done = new std::vector<Object *>();
397
398         if (is_joint) {
399                 if ( par ) {
400                 Object * empty = par;
401                 par = add_object(sce, OB_ARMATURE);
402                 bc_set_parent(par, empty->parent, mContext);
403                 //remove empty : todo
404                 object_map.insert(std::make_pair<COLLADAFW::UniqueId, Object *>(parent_node->getUniqueId(), par));
405                 }
406                 armature_importer.add_joint(node, parent_node == NULL || parent_node->getType() != COLLADAFW::Node::JOINT, par, sce);
407         }
408         else {
409                 COLLADAFW::InstanceGeometryPointerArray &geom = node->getInstanceGeometries();
410                 COLLADAFW::InstanceCameraPointerArray &camera = node->getInstanceCameras();
411                 COLLADAFW::InstanceLightPointerArray &lamp = node->getInstanceLights();
412                 COLLADAFW::InstanceControllerPointerArray &controller = node->getInstanceControllers();
413                 COLLADAFW::InstanceNodePointerArray &inst_node = node->getInstanceNodes();
414                 size_t geom_done = 0;
415                 size_t camera_done = 0;
416                 size_t lamp_done = 0;
417                 size_t controller_done = 0;
418                 size_t inst_done = 0;
419
420                 // XXX linking object with the first <instance_geometry>, though a node may have more of them...
421                 // maybe join multiple <instance_...> meshes into 1, and link object with it? not sure...
422                 // <instance_geometry>
423                 while (geom_done < geom.getCount()) {
424                         ob = mesh_importer.create_mesh_object(node, geom[geom_done], false, uid_material_map,
425                                                                                                   material_texture_mapping_map);
426                         objects_done->push_back(ob);
427                         ++geom_done;
428                 }
429                 while (camera_done < camera.getCount()) {
430                         ob = create_camera_object(camera[camera_done], sce);
431                         objects_done->push_back(ob);
432                         ++camera_done;
433                 }
434                 while (lamp_done < lamp.getCount()) {
435                         ob = create_lamp_object(lamp[lamp_done], sce);
436                         objects_done->push_back(ob);
437                         ++lamp_done;
438                 }
439                 while (controller_done < controller.getCount()) {
440                         COLLADAFW::InstanceGeometry *geom = (COLLADAFW::InstanceGeometry*)controller[controller_done];
441                         ob = mesh_importer.create_mesh_object(node, geom, true, uid_material_map, material_texture_mapping_map);
442                         objects_done->push_back(ob);
443                         ++controller_done;
444                 }
445                 // XXX instance_node is not supported yet
446                 while (inst_done < inst_node.getCount()) {
447                         const COLLADAFW::UniqueId& node_id = inst_node[inst_done]->getInstanciatedObjectId();
448                         if (object_map.find(node_id) == object_map.end()) {
449                                 fprintf(stderr, "Cannot find object for node referenced by <instance_node name=\"%s\">.\n", inst_node[inst_done]->getName().c_str());
450                                 ob = NULL;
451                         }
452                         else {
453                                 std::pair<std::multimap<COLLADAFW::UniqueId, Object *>::iterator, std::multimap<COLLADAFW::UniqueId, Object *>::iterator> pair_iter = object_map.equal_range(node_id);
454                                 for (std::multimap<COLLADAFW::UniqueId, Object *>::iterator it2 = pair_iter.first; it2 != pair_iter.second; it2++) {
455                                         Object *source_ob = (Object *)it2->second;
456                                         COLLADAFW::Node *source_node = node_map[node_id];
457                                         ob = create_instance_node(source_ob, source_node, node, sce, is_library_node);
458                                 }
459                         }
460                         if (ob != NULL) objects_done->push_back(ob);
461                         ++inst_done;
462
463                         read_transform = false;
464                 }
465                 // if node is empty - create empty object
466                 // XXX empty node may not mean it is empty object, not sure about this
467                 if ( (geom_done + camera_done + lamp_done + controller_done + inst_done) < 1) {
468                         ob = add_object(sce, OB_EMPTY);
469                         objects_done->push_back(ob);
470                 }
471                 
472                 // XXX: if there're multiple instances, only one is stored
473
474                 if (!ob) return;
475                 for (std::vector<Object *>::iterator it = objects_done->begin(); it != objects_done->end(); ++it) {
476                         ob = *it;
477                         std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
478                         rename_id(&ob->id, (char*)nodename.c_str());
479                         object_map.insert(std::make_pair<COLLADAFW::UniqueId, Object *>(node->getUniqueId(), ob));
480                         node_map[node->getUniqueId()] = node;
481
482                         if (is_library_node)
483                                 libnode_ob.push_back(ob);
484                 }
485
486         }
487
488         for (std::vector<Object *>::iterator it = objects_done->begin(); it != objects_done->end(); ++it) {
489                 ob =*it;
490
491                 if (read_transform)
492                         anim_importer.read_node_transform(node, ob); // overwrites location set earlier
493
494                 if (!is_joint) {
495                         // if par was given make this object child of the previous
496                         if (par && ob)
497                                 bc_set_parent(ob, par, mContext);
498                 }
499         }
500         // if node has child nodes write them
501         COLLADAFW::NodePointerArray &child_nodes = node->getChildNodes();
502         for (unsigned int i = 0; i < child_nodes.getCount(); i++) {     
503                 write_node(child_nodes[i], node, sce, ob, is_library_node);
504         }
505 }
506
507 /** When this method is called, the writer must write the entire visual scene.
508         \return The writer should return true, if writing succeeded, false otherwise.*/
509 bool DocumentImporter::writeVisualScene ( const COLLADAFW::VisualScene* visualScene ) 
510 {
511         if (mImportStage!=General)
512                 return true;
513                 
514         // this method called on post process after writeGeometry, writeMaterial, etc.
515
516         // for each <node> in <visual_scene>:
517         // create an Object
518         // if Mesh (previously created in writeGeometry) to which <node> corresponds exists, link Object with that mesh
519
520         // update: since we cannot link a Mesh with Object in
521         // writeGeometry because <geometry> does not reference <node>,
522         // we link Objects with Meshes here
523
524         vscenes.push_back(visualScene);
525         
526         return true;
527 }
528
529 /** When this method is called, the writer must handle all nodes contained in the 
530         library nodes.
531         \return The writer should return true, if writing succeeded, false otherwise.*/
532 bool DocumentImporter::writeLibraryNodes ( const COLLADAFW::LibraryNodes* libraryNodes ) 
533 {
534         if (mImportStage!=General)
535                 return true;
536                 
537         Scene *sce = CTX_data_scene(mContext);
538
539         const COLLADAFW::NodePointerArray& nodes = libraryNodes->getNodes();
540
541         for (unsigned int i = 0; i < nodes.getCount(); i++) {
542                 write_node(nodes[i], NULL, sce, NULL, true);
543         }
544
545         return true;
546 }
547
548 /** When this method is called, the writer must write the geometry.
549         \return The writer should return true, if writing succeeded, false otherwise.*/
550 bool DocumentImporter::writeGeometry ( const COLLADAFW::Geometry* geom ) 
551 {
552         if (mImportStage!=General)
553                 return true;
554                 
555         return mesh_importer.write_geometry(geom);
556 }
557
558 /** When this method is called, the writer must write the material.
559         \return The writer should return true, if writing succeeded, false otherwise.*/
560 bool DocumentImporter::writeMaterial( const COLLADAFW::Material* cmat ) 
561 {
562         if (mImportStage!=General)
563                 return true;
564                 
565         const std::string& str_mat_id = cmat->getName().size() ? cmat->getName() : cmat->getOriginalId();
566         Material *ma = add_material((char*)str_mat_id.c_str());
567         
568         this->uid_effect_map[cmat->getInstantiatedEffect()] = ma;
569         this->uid_material_map[cmat->getUniqueId()] = ma;
570         
571         return true;
572 }
573
574 // create mtex, create texture, set texture image
575 MTex* DocumentImporter::create_texture(COLLADAFW::EffectCommon *ef, COLLADAFW::Texture &ctex, Material *ma,
576                                          int i, TexIndexTextureArrayMap &texindex_texarray_map)
577 {
578         COLLADAFW::SamplerPointerArray& samp_array = ef->getSamplerPointerArray();
579         COLLADAFW::Sampler *sampler = samp_array[ctex.getSamplerId()];
580                 
581         const COLLADAFW::UniqueId& ima_uid = sampler->getSourceImage();
582         
583         if (uid_image_map.find(ima_uid) == uid_image_map.end()) {
584                 fprintf(stderr, "Couldn't find an image by UID.\n");
585                 return NULL;
586         }
587         
588         ma->mtex[i] = add_mtex();
589         ma->mtex[i]->texco = TEXCO_UV;
590         ma->mtex[i]->tex = add_texture("Texture");
591         ma->mtex[i]->tex->type = TEX_IMAGE;
592         ma->mtex[i]->tex->imaflag &= ~TEX_USEALPHA;
593         ma->mtex[i]->tex->ima = uid_image_map[ima_uid];
594         
595         texindex_texarray_map[ctex.getTextureMapId()].push_back(ma->mtex[i]);
596         
597         return ma->mtex[i];
598 }
599
600 void DocumentImporter::write_profile_COMMON(COLLADAFW::EffectCommon *ef, Material *ma)
601 {
602         COLLADAFW::EffectCommon::ShaderType shader = ef->getShaderType();
603         
604         // blinn
605         if (shader == COLLADAFW::EffectCommon::SHADER_BLINN) {
606                 ma->spec_shader = MA_SPEC_BLINN;
607                 ma->spec = ef->getShininess().getFloatValue();
608         }
609         // phong
610         else if (shader == COLLADAFW::EffectCommon::SHADER_PHONG) {
611                 ma->spec_shader = MA_SPEC_PHONG;
612                 ma->har = ef->getShininess().getFloatValue();
613         }
614         // lambert
615         else if (shader == COLLADAFW::EffectCommon::SHADER_LAMBERT) {
616                 ma->diff_shader = MA_DIFF_LAMBERT;
617         }
618         // default - lambert
619         else {
620                 ma->diff_shader = MA_DIFF_LAMBERT;
621                 fprintf(stderr, "Current shader type is not supported, default to lambert.\n");
622         }
623         // reflectivity
624         ma->ray_mirror = ef->getReflectivity().getFloatValue();
625         // index of refraction
626         ma->ang = ef->getIndexOfRefraction().getFloatValue();
627         
628         int i = 0;
629         COLLADAFW::Color col;
630         MTex *mtex = NULL;
631         TexIndexTextureArrayMap texindex_texarray_map;
632         
633         // DIFFUSE
634         // color
635         if (ef->getDiffuse().isColor()) {
636                 col = ef->getDiffuse().getColor();
637                 ma->r = col.getRed();
638                 ma->g = col.getGreen();
639                 ma->b = col.getBlue();
640         }
641         // texture
642         else if (ef->getDiffuse().isTexture()) {
643                 COLLADAFW::Texture ctex = ef->getDiffuse().getTexture(); 
644                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
645                 if (mtex != NULL) {
646                         mtex->mapto = MAP_COL;
647                         ma->texact = (int)i;
648                         i++;
649                 }
650         }
651         // AMBIENT
652         // color
653         if (ef->getAmbient().isColor()) {
654                 col = ef->getAmbient().getColor();
655                 ma->ambr = col.getRed();
656                 ma->ambg = col.getGreen();
657                 ma->ambb = col.getBlue();
658         }
659         // texture
660         else if (ef->getAmbient().isTexture()) {
661                 COLLADAFW::Texture ctex = ef->getAmbient().getTexture(); 
662                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
663                 if (mtex != NULL) {
664                         mtex->mapto = MAP_AMB; 
665                         i++;
666                 }
667         }
668         // SPECULAR
669         // color
670         if (ef->getSpecular().isColor()) {
671                 col = ef->getSpecular().getColor();
672                 ma->specr = col.getRed();
673                 ma->specg = col.getGreen();
674                 ma->specb = col.getBlue();
675         }
676         // texture
677         else if (ef->getSpecular().isTexture()) {
678                 COLLADAFW::Texture ctex = ef->getSpecular().getTexture(); 
679                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
680                 if (mtex != NULL) {
681                         mtex->mapto = MAP_SPEC; 
682                         i++;
683                 }
684         }
685         // REFLECTIVE
686         // color
687         if (ef->getReflective().isColor()) {
688                 col = ef->getReflective().getColor();
689                 ma->mirr = col.getRed();
690                 ma->mirg = col.getGreen();
691                 ma->mirb = col.getBlue();
692         }
693         // texture
694         else if (ef->getReflective().isTexture()) {
695                 COLLADAFW::Texture ctex = ef->getReflective().getTexture(); 
696                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
697                 if (mtex != NULL) {
698                         mtex->mapto = MAP_REF; 
699                         i++;
700                 }
701         }
702         // EMISSION
703         // color
704         if (ef->getEmission().isColor()) {
705                 // XXX there is no emission color in blender
706                 // but I am not sure
707         }
708         // texture
709         else if (ef->getEmission().isTexture()) {
710                 COLLADAFW::Texture ctex = ef->getEmission().getTexture(); 
711                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
712                 if (mtex != NULL) {
713                         mtex->mapto = MAP_EMIT; 
714                         i++;
715                 }
716         }
717         
718         if (ef->getOpacity().isTexture()) {
719                 COLLADAFW::Texture ctex = ef->getOpacity().getTexture();
720                 mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
721                 if (mtex != NULL) {
722                         mtex->mapto = MAP_ALPHA;
723                         mtex->tex->imaflag |= TEX_USEALPHA;
724                         i++;
725                         ma->spectra = ma->alpha = 0;
726                         ma->mode |= MA_ZTRANSP|MA_TRANSP;
727                 }
728         }
729         // TRANSPARENT
730         // color
731 //      if (ef->getOpacity().isColor()) {
732 //                      // XXX don't know what to do here
733 //              }
734 //              // texture
735 //              else if (ef->getOpacity().isTexture()) {
736 //                      ctex = ef->getOpacity().getTexture();
737 //                      if (mtex != NULL) mtex->mapto &= MAP_ALPHA;
738 //                      else {
739 //                              mtex = create_texture(ef, ctex, ma, i, texindex_texarray_map);
740 //                              if (mtex != NULL) mtex->mapto = MAP_ALPHA;
741 //                      }
742 //              }
743         material_texture_mapping_map[ma] = texindex_texarray_map;
744 }
745
746 /** When this method is called, the writer must write the effect.
747         \return The writer should return true, if writing succeeded, false otherwise.*/
748
749 bool DocumentImporter::writeEffect( const COLLADAFW::Effect* effect ) 
750 {
751         if (mImportStage!=General)
752                 return true;
753         
754         const COLLADAFW::UniqueId& uid = effect->getUniqueId();
755         
756         if (uid_effect_map.find(uid) == uid_effect_map.end()) {
757                 fprintf(stderr, "Couldn't find a material by UID.\n");
758                 return true;
759         }
760         
761         Material *ma = uid_effect_map[uid];
762         std::map<COLLADAFW::UniqueId, Material*>::iterator  iter;
763         for (iter = uid_material_map.begin(); iter != uid_material_map.end() ; iter++ ) {
764                 if ( iter->second == ma ) {
765                         this->FW_object_map[iter->first] = effect;
766                         break;
767                 }
768         }
769         COLLADAFW::CommonEffectPointerArray common_efs = effect->getCommonEffects();
770         if (common_efs.getCount() < 1) {
771                 fprintf(stderr, "Couldn't find <profile_COMMON>.\n");
772                 return true;
773         }
774         // XXX TODO: Take all <profile_common>s
775         // Currently only first <profile_common> is supported
776         COLLADAFW::EffectCommon *ef = common_efs[0];
777         write_profile_COMMON(ef, ma);
778         this->FW_object_map[effect->getUniqueId()] = effect;
779                 
780         return true;
781 }
782
783
784 /** When this method is called, the writer must write the camera.
785         \return The writer should return true, if writing succeeded, false otherwise.*/
786 bool DocumentImporter::writeCamera( const COLLADAFW::Camera* camera ) 
787 {
788         if (mImportStage!=General)
789                 return true;
790                 
791         Camera *cam = NULL;
792         std::string cam_id, cam_name;
793         
794         cam_id = camera->getOriginalId();
795         cam_name = camera->getName();
796         if (cam_name.size()) cam = (Camera*)add_camera((char*)cam_name.c_str());
797         else cam = (Camera*)add_camera((char*)cam_id.c_str());
798         
799         if (!cam) {
800                 fprintf(stderr, "Cannot create camera.\n");
801                 return true;
802         }
803         cam->clipsta = camera->getNearClippingPlane().getValue();
804         cam->clipend = camera->getFarClippingPlane().getValue();
805         
806         COLLADAFW::Camera::CameraType type = camera->getCameraType();
807         switch (type) {
808         case COLLADAFW::Camera::ORTHOGRAPHIC:
809                 {
810                         cam->type = CAM_ORTHO;
811                 }
812                 break;
813         case COLLADAFW::Camera::PERSPECTIVE:
814                 {
815                         cam->type = CAM_PERSP;
816                 }
817                 break;
818         case COLLADAFW::Camera::UNDEFINED_CAMERATYPE:
819                 {
820                         fprintf(stderr, "Current camera type is not supported.\n");
821                         cam->type = CAM_PERSP;
822                 }
823                 break;
824         }
825         
826         switch (camera->getDescriptionType()) {
827         case COLLADAFW::Camera::ASPECTRATIO_AND_Y:
828                 {
829                         switch (cam->type) {
830                                 case CAM_ORTHO:
831                                         {
832                                                 double ymag = camera->getYMag().getValue();
833                                                 double aspect = camera->getAspectRatio().getValue();
834                                                 double xmag = aspect*ymag;
835                                                 cam->ortho_scale = (float)xmag;
836                                         }
837                                         break;
838                                 case CAM_PERSP:
839                                 default:
840                                         {
841                                                 double yfov = camera->getYFov().getValue();
842                                                 double aspect = camera->getAspectRatio().getValue();
843                                                 double xfov = aspect*yfov;
844                                                 // xfov is in degrees, cam->lens is in millimiters
845                                                 cam->lens = fov_to_focallength(DEG2RADF(xfov), cam->sensor_x);
846                                         }
847                                         break;
848                         }
849                 }
850                 break;
851         /* XXX correct way to do following four is probably to get also render
852            size and determine proper settings from that somehow */
853         case COLLADAFW::Camera::ASPECTRATIO_AND_X:
854         case COLLADAFW::Camera::SINGLE_X:
855         case COLLADAFW::Camera::X_AND_Y:
856                 {
857                         switch (cam->type) {
858                                 case CAM_ORTHO:
859                                         cam->ortho_scale = (float)camera->getXMag().getValue();
860                                         break;
861                                 case CAM_PERSP:
862                                 default:
863                                         {
864                                                 double x = camera->getXFov().getValue();
865                                                 // x is in degrees, cam->lens is in millimiters
866                                                 cam->lens = fov_to_focallength(DEG2RADF(x), cam->sensor_x);
867                                         }
868                                         break;
869                         }
870                 }
871                 break;
872         case COLLADAFW::Camera::SINGLE_Y:
873                 {
874                         switch (cam->type) {
875                                 case CAM_ORTHO:
876                                         cam->ortho_scale = (float)camera->getYMag().getValue();
877                                         break;
878                                 case CAM_PERSP:
879                                 default:
880                                         {
881                                         double yfov = camera->getYFov().getValue();
882                                         // yfov is in degrees, cam->lens is in millimiters
883                                         cam->lens = fov_to_focallength(DEG2RADF(yfov), cam->sensor_x);
884                                         }
885                                         break;
886                         }
887                 }
888                 break;
889         case COLLADAFW::Camera::UNDEFINED:
890                 // read nothing, use blender defaults.
891                 break;
892         }
893         
894         this->uid_camera_map[camera->getUniqueId()] = cam;
895         this->FW_object_map[camera->getUniqueId()] = camera;
896         // XXX import camera options
897         return true;
898 }
899
900 /** When this method is called, the writer must write the image.
901         \return The writer should return true, if writing succeeded, false otherwise.*/
902 bool DocumentImporter::writeImage( const COLLADAFW::Image* image ) 
903 {
904         if (mImportStage!=General)
905                 return true;
906                 
907         // XXX maybe it is necessary to check if the path is absolute or relative
908         const std::string& filepath = image->getImageURI().toNativePath();
909         const char *filename = (const char*)mFilename.c_str();
910         char dir[FILE_MAX];
911         char full_path[FILE_MAX];
912         
913         BLI_split_dir_part(filename, dir, sizeof(dir));
914         BLI_join_dirfile(full_path, sizeof(full_path), dir, filepath.c_str());
915         Image *ima = BKE_add_image_file(full_path);
916         if (!ima) {
917                 fprintf(stderr, "Cannot create image.\n");
918                 return true;
919         }
920         this->uid_image_map[image->getUniqueId()] = ima;
921         
922         return true;
923 }
924
925 /** When this method is called, the writer must write the light.
926         \return The writer should return true, if writing succeeded, false otherwise.*/
927 bool DocumentImporter::writeLight( const COLLADAFW::Light* light ) 
928 {
929         if (mImportStage!=General)
930                 return true;
931
932         Lamp *lamp = NULL;
933         std::string la_id, la_name;
934
935         TagsMap::iterator etit;
936         ExtraTags *et = 0;
937         etit = uid_tags_map.find(light->getUniqueId().toAscii());
938         if (etit != uid_tags_map.end())
939                 et = etit->second;
940
941         la_id = light->getOriginalId();
942         la_name = light->getName();
943         if (la_name.size()) lamp = (Lamp*)add_lamp((char*)la_name.c_str());
944         else lamp = (Lamp*)add_lamp((char*)la_id.c_str());
945
946         if (!lamp) {
947                 fprintf(stderr, "Cannot create lamp.\n");
948                 return true;
949         }
950
951         // if we find an ExtraTags for this, use that instead.
952         if (et && et->isProfile("blender")) {
953                 et->setData("type", &(lamp->type));
954                 et->setData("flag", &(lamp->flag));
955                 et->setData("mode", &(lamp->mode));
956                 et->setData("gamma", &(lamp->k));
957                 et->setData("red", &(lamp->r));
958                 et->setData("green", &(lamp->g));
959                 et->setData("blue", &(lamp->b));
960                 et->setData("shadow_r", &(lamp->shdwr));
961                 et->setData("shadow_g", &(lamp->shdwg));
962                 et->setData("shadow_b", &(lamp->shdwb));
963                 et->setData("energy", &(lamp->energy));
964                 et->setData("dist", &(lamp->dist));
965                 et->setData("spotsize", &(lamp->spotsize));
966                 et->setData("spotblend", &(lamp->spotblend));
967                 et->setData("halo_intensity", &(lamp->haint));
968                 et->setData("att1", &(lamp->att1));
969                 et->setData("att2", &(lamp->att2));
970                 et->setData("falloff_type", &(lamp->falloff_type));
971                 et->setData("clipsta", &(lamp->clipsta));
972                 et->setData("clipend", &(lamp->clipend));
973                 et->setData("shadspotsize", &(lamp->shadspotsize));
974                 et->setData("bias", &(lamp->bias));
975                 et->setData("soft", &(lamp->soft));
976                 et->setData("compressthresh", &(lamp->compressthresh));
977                 et->setData("bufsize", &(lamp->bufsize));
978                 et->setData("samp", &(lamp->samp));
979                 et->setData("buffers", &(lamp->buffers));
980                 et->setData("filtertype", &(lamp->filtertype));
981                 et->setData("bufflag", &(lamp->bufflag));
982                 et->setData("buftype", &(lamp->buftype));
983                 et->setData("ray_samp", &(lamp->ray_samp));
984                 et->setData("ray_sampy", &(lamp->ray_sampy));
985                 et->setData("ray_sampz", &(lamp->ray_sampz));
986                 et->setData("ray_samp_type", &(lamp->ray_samp_type));
987                 et->setData("area_shape", &(lamp->area_shape));
988                 et->setData("area_size", &(lamp->area_size));
989                 et->setData("area_sizey", &(lamp->area_sizey));
990                 et->setData("area_sizez", &(lamp->area_sizez));
991                 et->setData("adapt_thresh", &(lamp->adapt_thresh));
992                 et->setData("ray_samp_method", &(lamp->ray_samp_method));
993                 et->setData("shadhalostep", &(lamp->shadhalostep));
994                 et->setData("sun_effect_type", &(lamp->shadhalostep));
995                 et->setData("skyblendtype", &(lamp->skyblendtype));
996                 et->setData("horizon_brightness", &(lamp->horizon_brightness));
997                 et->setData("spread", &(lamp->spread));
998                 et->setData("sun_brightness", &(lamp->sun_brightness));
999                 et->setData("sun_size", &(lamp->sun_size));
1000                 et->setData("backscattered_light", &(lamp->backscattered_light));
1001                 et->setData("sun_intensity", &(lamp->sun_intensity));
1002                 et->setData("atm_turbidity", &(lamp->atm_turbidity));
1003                 et->setData("atm_extinction_factor", &(lamp->atm_extinction_factor));
1004                 et->setData("atm_distance_factor", &(lamp->atm_distance_factor));
1005                 et->setData("skyblendfac", &(lamp->skyblendfac));
1006                 et->setData("sky_exposure", &(lamp->sky_exposure));
1007                 et->setData("sky_colorspace", &(lamp->sky_colorspace));
1008         }
1009         else {
1010                 float constatt = light->getConstantAttenuation().getValue();
1011                 float linatt = light->getLinearAttenuation().getValue();
1012                 float quadatt = light->getQuadraticAttenuation().getValue();
1013                 float d = 25.0f;
1014                 float att1 = 0.0f;
1015                 float att2 = 0.0f;
1016                 float e = 1.0f;
1017
1018                 if (light->getColor().isValid()) {
1019                         COLLADAFW::Color col = light->getColor();
1020                         lamp->r = col.getRed();
1021                         lamp->g = col.getGreen();
1022                         lamp->b = col.getBlue();
1023                 }
1024
1025                 if (IS_EQ(linatt, 0.0f) && quadatt > 0.0f) {
1026                         att2 = quadatt;
1027                         d = sqrt(1.0f/quadatt);
1028                 }
1029                 // linear light
1030                 else if (IS_EQ(quadatt, 0.0f) && linatt > 0.0f) {
1031                         att1 = linatt;
1032                         d = (1.0f/linatt);
1033                 }
1034                 else if (IS_EQ(constatt, 1.0f)) {
1035                         att1 = 1.0f;
1036                 }
1037                 else {
1038                         // assuming point light (const att = 1.0);
1039                         att1 = 1.0f;
1040                 }
1041                 
1042                 d *= ( 1.0f / unit_converter.getLinearMeter());
1043
1044                 lamp->energy = e;
1045                 lamp->dist = d;
1046
1047                 COLLADAFW::Light::LightType type = light->getLightType();
1048                 switch (type) {
1049                         case COLLADAFW::Light::AMBIENT_LIGHT:
1050                                 {
1051                                         lamp->type = LA_HEMI;
1052                                 }
1053                                 break;
1054                         case COLLADAFW::Light::SPOT_LIGHT:
1055                                 {
1056                                         lamp->type = LA_SPOT;
1057                                         lamp->att1 = att1;
1058                                         lamp->att2 = att2;
1059                                         if (IS_EQ(att1, 0.0f) && att2 > 0)
1060                                                 lamp->falloff_type = LA_FALLOFF_INVSQUARE;
1061                                         if (IS_EQ(att2, 0.0f) && att1 > 0)
1062                                                 lamp->falloff_type = LA_FALLOFF_INVLINEAR;
1063                                         lamp->spotsize = light->getFallOffAngle().getValue();
1064                                         lamp->spotblend = light->getFallOffExponent().getValue();
1065                                 }
1066                                 break;
1067                         case COLLADAFW::Light::DIRECTIONAL_LIGHT:
1068                                 {
1069                                         /* our sun is very strong, so pick a smaller energy level */
1070                                         lamp->type = LA_SUN;
1071                                         lamp->mode |= LA_NO_SPEC;
1072                                 }
1073                                 break;
1074                         case COLLADAFW::Light::POINT_LIGHT:
1075                                 {
1076                                         lamp->type = LA_LOCAL;
1077                                         lamp->att1 = att1;
1078                                         lamp->att2 = att2;
1079                                         if (IS_EQ(att1, 0.0f) && att2 > 0)
1080                                                 lamp->falloff_type = LA_FALLOFF_INVSQUARE;
1081                                         if (IS_EQ(att2, 0.0f) && att1 > 0)
1082                                                 lamp->falloff_type = LA_FALLOFF_INVLINEAR;
1083                                 }
1084                                 break;
1085                         case COLLADAFW::Light::UNDEFINED:
1086                                 {
1087                                         fprintf(stderr, "Current lamp type is not supported.\n");
1088                                         lamp->type = LA_LOCAL;
1089                                 }
1090                                 break;
1091                 }
1092         }
1093
1094         this->uid_lamp_map[light->getUniqueId()] = lamp;
1095         this->FW_object_map[light->getUniqueId()] = light;
1096         return true;
1097 }
1098
1099 // this function is called only for animations that pass COLLADAFW::validate
1100 bool DocumentImporter::writeAnimation( const COLLADAFW::Animation* anim ) 
1101 {
1102         if (mImportStage!=General)
1103                 return true;
1104                 
1105         // return true;
1106         return anim_importer.write_animation(anim);
1107 }
1108
1109 // called on post-process stage after writeVisualScenes
1110 bool DocumentImporter::writeAnimationList( const COLLADAFW::AnimationList* animationList ) 
1111 {
1112         if (mImportStage!=General)
1113                 return true;
1114                 
1115         // return true;
1116         return anim_importer.write_animation_list(animationList);
1117 }
1118
1119 /** When this method is called, the writer must write the skin controller data.
1120         \return The writer should return true, if writing succeeded, false otherwise.*/
1121 bool DocumentImporter::writeSkinControllerData( const COLLADAFW::SkinControllerData* skin ) 
1122 {
1123         return armature_importer.write_skin_controller_data(skin);
1124 }
1125
1126 // this is called on postprocess, before writeVisualScenes
1127 bool DocumentImporter::writeController( const COLLADAFW::Controller* controller ) 
1128 {
1129         if (mImportStage!=General)
1130                 return true;
1131                 
1132         return armature_importer.write_controller(controller);
1133 }
1134
1135 bool DocumentImporter::writeFormulas( const COLLADAFW::Formulas* formulas )
1136 {
1137         return true;
1138 }
1139
1140 bool DocumentImporter::writeKinematicsScene( const COLLADAFW::KinematicsScene* kinematicsScene )
1141 {
1142         return true;
1143 }
1144
1145 ExtraTags* DocumentImporter::getExtraTags(const COLLADAFW::UniqueId &uid)
1146 {
1147         if (uid_tags_map.find(uid.toAscii())==uid_tags_map.end()) {
1148                 return NULL;
1149         }
1150         return uid_tags_map[uid.toAscii()];
1151 }
1152
1153 bool DocumentImporter::addExtraTags( const COLLADAFW::UniqueId &uid, ExtraTags *extra_tags)
1154 {
1155         uid_tags_map[uid.toAscii()] = extra_tags;
1156         return true;
1157 }
1158