Merge from trunk -r 24758:25003.
[blender-staging.git] / source / blender / collada / DocumentImporter.cpp
1 // TODO:
2 // * name imported objects
3 // * import object rotation as euler
4
5 #include "COLLADAFWRoot.h"
6 #include "COLLADAFWIWriter.h"
7 #include "COLLADAFWStableHeaders.h"
8 #include "COLLADAFWAnimationCurve.h"
9 #include "COLLADAFWAnimationList.h"
10 #include "COLLADAFWCamera.h"
11 #include "COLLADAFWColorOrTexture.h"
12 #include "COLLADAFWEffect.h"
13 #include "COLLADAFWFloatOrDoubleArray.h"
14 #include "COLLADAFWGeometry.h"
15 #include "COLLADAFWImage.h"
16 #include "COLLADAFWIndexList.h"
17 #include "COLLADAFWInstanceGeometry.h"
18 #include "COLLADAFWLight.h"
19 #include "COLLADAFWMaterial.h"
20 #include "COLLADAFWMesh.h"
21 #include "COLLADAFWMeshPrimitiveWithFaceVertexCount.h"
22 #include "COLLADAFWNode.h"
23 #include "COLLADAFWPolygons.h"
24 #include "COLLADAFWSampler.h"
25 #include "COLLADAFWSkinController.h"
26 #include "COLLADAFWSkinControllerData.h"
27 #include "COLLADAFWTransformation.h"
28 #include "COLLADAFWTranslate.h"
29 #include "COLLADAFWRotate.h"
30 #include "COLLADAFWScale.h"
31 #include "COLLADAFWMatrix.h"
32 #include "COLLADAFWTypes.h"
33 #include "COLLADAFWVisualScene.h"
34 #include "COLLADAFWFileInfo.h"
35 #include "COLLADAFWArrayPrimitiveType.h"
36
37 #include "COLLADASaxFWLLoader.h"
38
39 // TODO move "extern C" into header files
40 extern "C" 
41 {
42 #include "ED_keyframing.h"
43 #include "ED_armature.h"
44 #include "ED_mesh.h" // ED_vgroup_vert_add, ...
45 #include "ED_anim_api.h"
46 #include "WM_types.h"
47 #include "WM_api.h"
48
49 #include "BKE_main.h"
50 #include "BKE_customdata.h"
51 #include "BKE_library.h"
52 #include "BKE_texture.h"
53 #include "BKE_fcurve.h"
54 #include "BKE_depsgraph.h"
55 #include "BLI_util.h"
56 #include "BKE_displist.h"
57 #include "BLI_math.h"
58 #include "BKE_scene.h"
59 }
60 #include "BKE_armature.h"
61 #include "BKE_mesh.h"
62 #include "BKE_global.h"
63 #include "BKE_context.h"
64 #include "BKE_object.h"
65 #include "BKE_image.h"
66 #include "BKE_material.h"
67 #include "BKE_utildefines.h"
68 #include "BKE_action.h"
69
70 #include "BLI_math.h"
71 #include "BLI_listbase.h"
72 #include "BLI_string.h"
73
74 #include "DNA_lamp_types.h"
75 #include "DNA_armature_types.h"
76 #include "DNA_anim_types.h"
77 #include "DNA_curve_types.h"
78 #include "DNA_texture_types.h"
79 #include "DNA_camera_types.h"
80 #include "DNA_object_types.h"
81 #include "DNA_meshdata_types.h"
82 #include "DNA_mesh_types.h"
83 #include "DNA_material_types.h"
84 #include "DNA_scene_types.h"
85
86 #include "MEM_guardedalloc.h"
87
88 #include "DocumentImporter.h"
89 #include "collada_internal.h"
90
91 #include <string>
92 #include <map>
93 #include <algorithm> // sort()
94
95 #include <math.h>
96 #include <float.h>
97
98 // #define COLLADA_DEBUG
99 #define ARMATURE_TEST
100
101 char *CustomData_get_layer_name(const struct CustomData *data, int type, int n);
102
103 const char *primTypeToStr(COLLADAFW::MeshPrimitive::PrimitiveType type)
104 {
105         using namespace COLLADAFW;
106         
107         switch (type) {
108         case MeshPrimitive::LINES:
109                 return "LINES";
110         case MeshPrimitive::LINE_STRIPS:
111                 return "LINESTRIPS";
112         case MeshPrimitive::POLYGONS:
113                 return "POLYGONS";
114         case MeshPrimitive::POLYLIST:
115                 return "POLYLIST";
116         case MeshPrimitive::TRIANGLES:
117                 return "TRIANGLES";
118         case MeshPrimitive::TRIANGLE_FANS:
119                 return "TRIANGLE_FANS";
120         case MeshPrimitive::TRIANGLE_STRIPS:
121                 return "TRIANGLE_FANS";
122         case MeshPrimitive::POINTS:
123                 return "POINTS";
124         case MeshPrimitive::UNDEFINED_PRIMITIVE_TYPE:
125                 return "UNDEFINED_PRIMITIVE_TYPE";
126         }
127         return "UNKNOWN";
128 }
129 const char *geomTypeToStr(COLLADAFW::Geometry::GeometryType type)
130 {
131         switch (type) {
132         case COLLADAFW::Geometry::GEO_TYPE_MESH:
133                 return "MESH";
134         case COLLADAFW::Geometry::GEO_TYPE_SPLINE:
135                 return "SPLINE";
136         case COLLADAFW::Geometry::GEO_TYPE_CONVEX_MESH:
137                 return "CONVEX_MESH";
138         case COLLADAFW::Geometry::GEO_TYPE_UNKNOWN:
139         default:
140                 return "UNKNOWN";
141         }
142 }
143
144 // works for COLLADAFW::Node, COLLADAFW::Geometry
145 template<class T>
146 const char *get_dae_name(T *node)
147 {
148         const std::string& name = node->getName();
149         return name.size() ? name.c_str() : node->getOriginalId().c_str();
150 }
151
152 // use this for retrieving bone names, since these must be unique
153 template<class T>
154 const char *get_joint_name(T *node)
155 {
156         const std::string& id = node->getOriginalId();
157         return id.size() ? id.c_str() : node->getName().c_str();
158 }
159
160 float get_float_value(const COLLADAFW::FloatOrDoubleArray& array, int index)
161 {
162         if (index >= array.getValuesCount())
163                 return 0.0f;
164
165         if (array.getType() == COLLADAFW::MeshVertexData::DATA_TYPE_FLOAT)
166                 return array.getFloatValues()->getData()[index];
167         else 
168                 return array.getDoubleValues()->getData()[index];
169 }
170
171 typedef std::map<COLLADAFW::TextureMapId, std::vector<MTex*> > TexIndexTextureArrayMap;
172
173 class TransformReader : public TransformBase
174 {
175 protected:
176
177         UnitConverter *unit_converter;
178
179         struct Animation {
180                 Object *ob;
181                 COLLADAFW::Node *node;
182                 COLLADAFW::Transformation *tm; // which transform is animated by an AnimationList->id
183         };
184
185 public:
186
187         TransformReader(UnitConverter* conv) : unit_converter(conv) {}
188
189         void get_node_mat(float mat[][4], COLLADAFW::Node *node, std::map<COLLADAFW::UniqueId, Animation> *animation_map,
190                                           Object *ob)
191         {
192                 float cur[4][4];
193                 float copy[4][4];
194
195                 unit_m4(mat);
196                 
197                 for (int i = 0; i < node->getTransformations().getCount(); i++) {
198
199                         COLLADAFW::Transformation *tm = node->getTransformations()[i];
200                         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
201
202                         switch(type) {
203                         case COLLADAFW::Transformation::TRANSLATE:
204                                 dae_translate_to_mat4(tm, cur);
205                                 break;
206                         case COLLADAFW::Transformation::ROTATE:
207                                 dae_rotate_to_mat4(tm, cur);
208                                 break;
209                         case COLLADAFW::Transformation::SCALE:
210                                 dae_scale_to_mat4(tm, cur);
211                                 break;
212                         case COLLADAFW::Transformation::MATRIX:
213                                 dae_matrix_to_mat4(tm, cur);
214                                 break;
215                         case COLLADAFW::Transformation::LOOKAT:
216                         case COLLADAFW::Transformation::SKEW:
217                                 fprintf(stderr, "LOOKAT and SKEW transformations are not supported yet.\n");
218                                 break;
219                         }
220
221                         copy_m4_m4(copy, mat);
222                         mul_m4_m4m4(mat, cur, copy);
223
224                         if (animation_map) {
225                                 // AnimationList that drives this Transformation
226                                 const COLLADAFW::UniqueId& anim_list_id = tm->getAnimationList();
227                         
228                                 // store this so later we can link animation data with ob
229                                 Animation anim = {ob, node, tm};
230                                 (*animation_map)[anim_list_id] = anim;
231                         }
232                 }
233         }
234
235         void dae_rotate_to_mat4(COLLADAFW::Transformation *tm, float m[][4])
236         {
237                 COLLADAFW::Rotate *ro = (COLLADAFW::Rotate*)tm;
238                 COLLADABU::Math::Vector3& axis = ro->getRotationAxis();
239                 float angle = (float)(ro->getRotationAngle() * M_PI / 180.0f);
240                 float ax[] = {axis[0], axis[1], axis[2]};
241                 // float quat[4];
242                 // axis_angle_to_quat(quat, axis, angle);
243                 // quat_to_mat4(m, quat);
244                 axis_angle_to_mat4(m, ax, angle);
245         }
246
247         void dae_translate_to_mat4(COLLADAFW::Transformation *tm, float m[][4])
248         {
249                 COLLADAFW::Translate *tra = (COLLADAFW::Translate*)tm;
250                 COLLADABU::Math::Vector3& t = tra->getTranslation();
251
252                 unit_m4(m);
253
254                 m[3][0] = (float)t[0];
255                 m[3][1] = (float)t[1];
256                 m[3][2] = (float)t[2];
257         }
258
259         void dae_scale_to_mat4(COLLADAFW::Transformation *tm, float m[][4])
260         {
261                 COLLADABU::Math::Vector3& s = ((COLLADAFW::Scale*)tm)->getScale();
262                 float size[3] = {(float)s[0], (float)s[1], (float)s[2]};
263                 size_to_mat4(m, size);
264         }
265
266         void dae_matrix_to_mat4(COLLADAFW::Transformation *tm, float m[][4])
267         {
268                 unit_converter->dae_matrix_to_mat4(m, ((COLLADAFW::Matrix*)tm)->getMatrix());
269         }
270 };
271
272 // only for ArmatureImporter to "see" MeshImporter::get_object_by_geom_uid
273 class MeshImporterBase
274 {
275 public:
276         virtual Object *get_object_by_geom_uid(const COLLADAFW::UniqueId& geom_uid) = 0;
277 };
278
279 // ditto as above
280 class AnimationImporterBase
281 {
282 public:
283         // virtual void change_eul_to_quat(Object *ob, bAction *act) = 0;
284 };
285
286 class ArmatureImporter : private TransformReader
287 {
288 private:
289         Scene *scene;
290         UnitConverter *unit_converter;
291
292         // std::map<int, JointData> joint_index_to_joint_info_map;
293         // std::map<COLLADAFW::UniqueId, int> joint_id_to_joint_index_map;
294
295         struct LeafBone {
296                 // COLLADAFW::Node *node;
297                 EditBone *bone;
298                 char name[32];
299                 float mat[4][4]; // bone matrix, derived from inv_bind_mat
300         };
301         std::vector<LeafBone> leaf_bones;
302         // int bone_direction_row; // XXX not used
303         float leaf_bone_length;
304         int totbone;
305         // XXX not used
306         // float min_angle; // minimum angle between bone head-tail and a row of bone matrix
307
308 #if 0
309         struct ArmatureJoints {
310                 Object *ob_arm;
311                 std::vector<COLLADAFW::Node*> root_joints;
312         };
313         std::vector<ArmatureJoints> armature_joints;
314 #endif
315
316         Object *empty; // empty for leaf bones
317
318         std::map<COLLADAFW::UniqueId, COLLADAFW::UniqueId> geom_uid_by_controller_uid;
319         std::map<COLLADAFW::UniqueId, COLLADAFW::Node*> joint_by_uid; // contains all joints
320         std::vector<COLLADAFW::Node*> root_joints;
321
322         std::vector<Object*> armature_objects;
323
324         MeshImporterBase *mesh_importer;
325         AnimationImporterBase *anim_importer;
326
327         // This is used to store data passed in write_controller_data.
328         // Arrays from COLLADAFW::SkinControllerData lose ownership, so do this class members
329         // so that arrays don't get freed until we free them explicitly.
330         class SkinInfo
331         {
332         private:
333                 // to build armature bones from inverse bind matrices
334                 struct JointData {
335                         float inv_bind_mat[4][4]; // joint inverse bind matrix
336                         COLLADAFW::UniqueId joint_uid; // joint node UID
337                         // Object *ob_arm;                        // armature object
338                 };
339
340                 float bind_shape_matrix[4][4];
341
342                 // data from COLLADAFW::SkinControllerData, each array should be freed
343                 COLLADAFW::UIntValuesArray joints_per_vertex;
344                 COLLADAFW::UIntValuesArray weight_indices;
345                 COLLADAFW::IntValuesArray joint_indices;
346                 // COLLADAFW::FloatOrDoubleArray weights;
347                 std::vector<float> weights;
348
349                 std::vector<JointData> joint_data; // index to this vector is joint index
350
351                 UnitConverter *unit_converter;
352
353                 Object *ob_arm;
354                 COLLADAFW::UniqueId controller_uid;
355
356         public:
357
358                 SkinInfo() {}
359
360                 SkinInfo(const SkinInfo& skin) : weights(skin.weights),
361                                                                                  joint_data(skin.joint_data),
362                                                                                  unit_converter(skin.unit_converter),
363                                                                                  ob_arm(skin.ob_arm),
364                                                                                  controller_uid(skin.controller_uid)
365                 {
366                         copy_m4_m4(bind_shape_matrix, (float (*)[4])skin.bind_shape_matrix);
367
368                         transfer_uint_array_data_const(skin.joints_per_vertex, joints_per_vertex);
369                         transfer_uint_array_data_const(skin.weight_indices, weight_indices);
370                         transfer_int_array_data_const(skin.joint_indices, joint_indices);
371                 }
372
373                 SkinInfo(UnitConverter *conv) : unit_converter(conv), ob_arm(NULL) {}
374
375                 // nobody owns the data after this, so it should be freed manually with releaseMemory
376                 template <class T>
377                 void transfer_array_data(T& src, T& dest)
378                 {
379                         dest.setData(src.getData(), src.getCount());
380                         src.yieldOwnerShip();
381                         dest.yieldOwnerShip();
382                 }
383
384                 // when src is const we cannot src.yieldOwnerShip, this is used by copy constructor
385                 void transfer_int_array_data_const(const COLLADAFW::IntValuesArray& src, COLLADAFW::IntValuesArray& dest)
386                 {
387                         dest.setData((int*)src.getData(), src.getCount());
388                         dest.yieldOwnerShip();
389                 }
390
391                 void transfer_uint_array_data_const(const COLLADAFW::UIntValuesArray& src, COLLADAFW::UIntValuesArray& dest)
392                 {
393                         dest.setData((unsigned int*)src.getData(), src.getCount());
394                         dest.yieldOwnerShip();
395                 }
396
397                 void borrow_skin_controller_data(const COLLADAFW::SkinControllerData* skin)
398                 {
399                         transfer_array_data((COLLADAFW::UIntValuesArray&)skin->getJointsPerVertex(), joints_per_vertex);
400                         transfer_array_data((COLLADAFW::UIntValuesArray&)skin->getWeightIndices(), weight_indices);
401                         transfer_array_data((COLLADAFW::IntValuesArray&)skin->getJointIndices(), joint_indices);
402                         // transfer_array_data(skin->getWeights(), weights);
403
404                         // cannot transfer data for FloatOrDoubleArray, copy values manually
405                         const COLLADAFW::FloatOrDoubleArray& weight = skin->getWeights();
406                         for (int i = 0; i < weight.getValuesCount(); i++)
407                                 weights.push_back(get_float_value(weight, i));
408
409                         unit_converter->dae_matrix_to_mat4(bind_shape_matrix, skin->getBindShapeMatrix());
410                 }
411                         
412                 void free()
413                 {
414                         joints_per_vertex.releaseMemory();
415                         weight_indices.releaseMemory();
416                         joint_indices.releaseMemory();
417                         // weights.releaseMemory();
418                 }
419
420                 // using inverse bind matrices to construct armature
421                 // it is safe to invert them to get the original matrices
422                 // because if they are inverse matrices, they can be inverted
423                 void add_joint(const COLLADABU::Math::Matrix4& matrix)
424                 {
425                         JointData jd;
426                         unit_converter->dae_matrix_to_mat4(jd.inv_bind_mat, matrix);
427                         joint_data.push_back(jd);
428                 }
429
430                 // called from write_controller
431                 Object *create_armature(const COLLADAFW::SkinController* co, Scene *scene)
432                 {
433                         ob_arm = add_object(scene, OB_ARMATURE);
434
435                         controller_uid = co->getUniqueId();
436
437                         const COLLADAFW::UniqueIdArray& joint_uids = co->getJoints();
438                         for (int i = 0; i < joint_uids.getCount(); i++) {
439                                 joint_data[i].joint_uid = joint_uids[i];
440
441                                 // // store armature pointer
442                                 // JointData& jd = joint_index_to_joint_info_map[i];
443                                 // jd.ob_arm = ob_arm;
444
445                                 // now we'll be able to get inv bind matrix from joint id
446                                 // joint_id_to_joint_index_map[joint_ids[i]] = i;
447                         }
448
449                         return ob_arm;
450                 }
451
452                 bool get_joint_inv_bind_matrix(float inv_bind_mat[][4], COLLADAFW::Node *node)
453                 {
454                         const COLLADAFW::UniqueId& uid = node->getUniqueId();
455                         std::vector<JointData>::iterator it;
456                         for (it = joint_data.begin(); it != joint_data.end(); it++) {
457                                 if ((*it).joint_uid == uid) {
458                                         copy_m4_m4(inv_bind_mat, (*it).inv_bind_mat);
459                                         return true;
460                                 }
461                         }
462
463                         return false;
464                 }
465
466                 Object *get_armature()
467                 {
468                         return ob_arm;
469                 }
470
471                 const COLLADAFW::UniqueId& get_controller_uid()
472                 {
473                         return controller_uid;
474                 }
475
476                 // some nodes may not be referenced by SkinController,
477                 // in this case to determine if the node belongs to this armature,
478                 // we need to search down the tree
479                 bool uses_joint(COLLADAFW::Node *node)
480                 {
481                         const COLLADAFW::UniqueId& uid = node->getUniqueId();
482                         std::vector<JointData>::iterator it;
483                         for (it = joint_data.begin(); it != joint_data.end(); it++) {
484                                 if ((*it).joint_uid == uid)
485                                         return true;
486                         }
487
488                         COLLADAFW::NodePointerArray& children = node->getChildNodes();
489                         for (int i = 0; i < children.getCount(); i++) {
490                                 if (this->uses_joint(children[i]))
491                                         return true;
492                         }
493
494                         return false;
495                 }
496
497                 void link_armature(bContext *C, Object *ob, std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& joint_by_uid,
498                                                    TransformReader *tm)
499                 {
500                         tm->decompose(bind_shape_matrix, ob->loc, ob->rot, NULL, ob->size);
501
502                         ob->parent = ob_arm;
503                         ob->partype = PARSKEL;
504                         ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA;
505
506                         ((bArmature*)ob_arm->data)->deformflag = ARM_DEF_VGROUP;
507
508                         // we need armature matrix here... where do we get it from I wonder...
509                         // root node/joint? or node with <instance_controller>?
510                         float parmat[4][4];
511                         unit_m4(parmat);
512                         invert_m4_m4(ob->parentinv, parmat);
513
514                         // create all vertex groups
515                         std::vector<JointData>::iterator it;
516                         int joint_index;
517                         for (it = joint_data.begin(), joint_index = 0; it != joint_data.end(); it++, joint_index++) {
518                                 const char *name = "Group";
519
520                                 // name group by joint node name
521                                 if (joint_by_uid.find((*it).joint_uid) != joint_by_uid.end()) {
522                                         name = get_joint_name(joint_by_uid[(*it).joint_uid]);
523                                 }
524
525                                 ED_vgroup_add_name(ob, (char*)name);
526                         }
527
528                         // <vcount> - number of joints per vertex - joints_per_vertex
529                         // <v> - [[bone index, weight index] * joints per vertex] * vertices - weight indices
530                         // ^ bone index can be -1 meaning weight toward bind shape, how to express this in Blender?
531
532                         // for each vertex in weight indices
533                         //   for each bone index in vertex
534                         //     add vertex to group at group index
535                         //     treat group index -1 specially
536
537                         // get def group by index with BLI_findlink
538
539                         for (int vertex = 0, weight = 0; vertex < joints_per_vertex.getCount(); vertex++) {
540
541                                 int limit = weight + joints_per_vertex[vertex];
542                                 for ( ; weight < limit; weight++) {
543                                         int joint = joint_indices[weight], joint_weight = weight_indices[weight];
544
545                                         // -1 means "weight towards the bind shape", we just don't assign it to any group
546                                         if (joint != -1) {
547                                                 bDeformGroup *def = (bDeformGroup*)BLI_findlink(&ob->defbase, joint);
548
549                                                 ED_vgroup_vert_add(ob, def, vertex, weights[joint_weight], WEIGHT_REPLACE);
550                                         }
551                                 }
552                         }
553
554                         DAG_scene_sort(CTX_data_scene(C));
555                         DAG_ids_flush_update(0);
556                         WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, NULL);
557                 }
558
559                 bPoseChannel *get_pose_channel_from_node(COLLADAFW::Node *node)
560                 {
561                         return get_pose_channel(ob_arm->pose, get_joint_name(node));
562                 }
563         };
564
565         std::map<COLLADAFW::UniqueId, SkinInfo> skin_by_data_uid; // data UID = skin controller data UID
566 #if 0
567         JointData *get_joint_data(COLLADAFW::Node *node)
568         {
569                 const COLLADAFW::UniqueId& joint_id = node->getUniqueId();
570
571                 if (joint_id_to_joint_index_map.find(joint_id) == joint_id_to_joint_index_map.end()) {
572                         fprintf(stderr, "Cannot find a joint index by joint id for %s.\n",
573                                         node->getOriginalId().c_str());
574                         return NULL;
575                 }
576
577                 int joint_index = joint_id_to_joint_index_map[joint_id];
578
579                 return &joint_index_to_joint_info_map[joint_index];
580         }
581 #endif
582
583         void create_bone(SkinInfo& skin, COLLADAFW::Node *node, EditBone *parent, int totchild,
584                                          float parent_mat[][4], bArmature *arm)
585         {
586                 float joint_inv_bind_mat[4][4];
587
588                 // JointData* jd = get_joint_data(node);
589
590                 float mat[4][4];
591
592                 if (skin.get_joint_inv_bind_matrix(joint_inv_bind_mat, node)) {
593                         // get original world-space matrix
594                         invert_m4_m4(mat, joint_inv_bind_mat);
595                 }
596                 // create a bone even if there's no joint data for it (i.e. it has no influence)
597                 else {
598                         float obmat[4][4];
599
600                         // object-space
601                         get_node_mat(obmat, node, NULL, NULL);
602
603                         // get world-space
604                         if (parent)
605                                 mul_m4_m4m4(mat, obmat, parent_mat);
606                         else
607                                 copy_m4_m4(mat, obmat);
608                 }
609
610                 // TODO rename from Node "name" attrs later
611                 EditBone *bone = ED_armature_edit_bone_add(arm, (char*)get_joint_name(node));
612                 totbone++;
613
614                 if (parent) bone->parent = parent;
615
616                 // set head
617                 copy_v3_v3(bone->head, mat[3]);
618
619                 // set tail, don't set it to head because 0-length bones are not allowed
620                 float vec[3] = {0.0f, 0.5f, 0.0f};
621                 add_v3_v3v3(bone->tail, bone->head, vec);
622
623                 // set parent tail
624                 if (parent && totchild == 1) {
625                         copy_v3_v3(parent->tail, bone->head);
626
627                         // XXX increase this to prevent "very" small bones?
628                         const float epsilon = 0.000001f;
629
630                         // derive leaf bone length
631                         float length = len_v3v3(parent->head, parent->tail);
632                         if ((length < leaf_bone_length || totbone == 0) && length > epsilon) {
633                                 leaf_bone_length = length;
634                         }
635
636                         // treat zero-sized bone like a leaf bone
637                         if (length <= epsilon) {
638                                 add_leaf_bone(parent_mat, parent);
639                         }
640
641                         /*
642 #if 0
643                         // and which row in mat is bone direction
644                         float vec[3];
645                         sub_v3_v3v3(vec, parent->tail, parent->head);
646 #ifdef COLLADA_DEBUG
647                         print_v3("tail - head", vec);
648                         print_m4("matrix", parent_mat);
649 #endif
650                         for (int i = 0; i < 3; i++) {
651 #ifdef COLLADA_DEBUG
652                                 char *axis_names[] = {"X", "Y", "Z"};
653                                 printf("%s-axis length is %f\n", axis_names[i], len_v3(parent_mat[i]));
654 #endif
655                                 float angle = angle_v2v2(vec, parent_mat[i]);
656                                 if (angle < min_angle) {
657 #ifdef COLLADA_DEBUG
658                                         print_v3("picking", parent_mat[i]);
659                                         printf("^ %s axis of %s's matrix\n", axis_names[i], get_dae_name(node));
660 #endif
661                                         bone_direction_row = i;
662                                         min_angle = angle;
663                                 }
664                         }
665 #endif
666                         */
667                 }
668
669                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
670                 for (int i = 0; i < children.getCount(); i++) {
671                         create_bone(skin, children[i], bone, children.getCount(), mat, arm);
672                 }
673
674                 // in second case it's not a leaf bone, but we handle it the same way
675                 if (!children.getCount() || children.getCount() > 1) {
676                         add_leaf_bone(mat, bone);
677                 }
678         }
679
680         void add_leaf_bone(float mat[][4], EditBone *bone)
681         {
682                 LeafBone leaf;
683
684                 leaf.bone = bone;
685                 copy_m4_m4(leaf.mat, mat);
686                 BLI_strncpy(leaf.name, bone->name, sizeof(leaf.name));
687
688                 leaf_bones.push_back(leaf);
689         }
690
691         void fix_leaf_bones()
692         {
693                 // just setting tail for leaf bones here
694
695                 std::vector<LeafBone>::iterator it;
696                 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
697                         LeafBone& leaf = *it;
698
699                         // pointing up
700                         float vec[3] = {0.0f, 0.0f, 1.0f};
701
702                         mul_v3_fl(vec, leaf_bone_length);
703
704                         copy_v3_v3(leaf.bone->tail, leaf.bone->head);
705                         add_v3_v3v3(leaf.bone->tail, leaf.bone->head, vec);
706                 }
707         }
708
709         void set_leaf_bone_shapes(Object *ob_arm)
710         {
711                 bPose *pose = ob_arm->pose;
712
713                 std::vector<LeafBone>::iterator it;
714                 for (it = leaf_bones.begin(); it != leaf_bones.end(); it++) {
715                         LeafBone& leaf = *it;
716
717                         bPoseChannel *pchan = get_pose_channel(pose, leaf.name);
718                         if (pchan) {
719                                 pchan->custom = get_empty_for_leaves();
720                         }
721                         else {
722                                 fprintf(stderr, "Cannot find a pose channel for leaf bone %s\n", leaf.name);
723                         }
724                 }
725         }
726
727 #if 0
728         void set_euler_rotmode()
729         {
730                 // just set rotmode = ROT_MODE_EUL on pose channel for each joint
731
732                 std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>::iterator it;
733
734                 for (it = joint_by_uid.begin(); it != joint_by_uid.end(); it++) {
735
736                         COLLADAFW::Node *joint = it->second;
737
738                         std::map<COLLADAFW::UniqueId, SkinInfo>::iterator sit;
739                         
740                         for (sit = skin_by_data_uid.begin(); sit != skin_by_data_uid.end(); sit++) {
741                                 SkinInfo& skin = sit->second;
742
743                                 if (skin.uses_joint(joint)) {
744                                         bPoseChannel *pchan = skin.get_pose_channel_from_node(joint);
745
746                                         if (pchan) {
747                                                 pchan->rotmode = ROT_MODE_EUL;
748                                         }
749                                         else {
750                                                 fprintf(stderr, "Cannot find pose channel for %s.\n", get_joint_name(joint));
751                                         }
752
753                                         break;
754                                 }
755                         }
756                 }
757         }
758 #endif
759
760         Object *get_empty_for_leaves()
761         {
762                 if (empty) return empty;
763                 
764                 empty = add_object(scene, OB_EMPTY);
765                 empty->empty_drawtype = OB_EMPTY_SPHERE;
766
767                 return empty;
768         }
769
770 #if 0
771         Object *find_armature(COLLADAFW::Node *node)
772         {
773                 JointData* jd = get_joint_data(node);
774                 if (jd) return jd->ob_arm;
775
776                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
777                 for (int i = 0; i < children.getCount(); i++) {
778                         Object *ob_arm = find_armature(children[i]);
779                         if (ob_arm) return ob_arm;
780                 }
781
782                 return NULL;
783         }
784
785         ArmatureJoints& get_armature_joints(Object *ob_arm)
786         {
787                 // try finding it
788                 std::vector<ArmatureJoints>::iterator it;
789                 for (it = armature_joints.begin(); it != armature_joints.end(); it++) {
790                         if ((*it).ob_arm == ob_arm) return *it;
791                 }
792
793                 // not found, create one
794                 ArmatureJoints aj;
795                 aj.ob_arm = ob_arm;
796                 armature_joints.push_back(aj);
797
798                 return armature_joints.back();
799         }
800 #endif
801
802         void create_armature_bones(SkinInfo& skin)
803         {
804                 // just do like so:
805                 // - get armature
806                 // - enter editmode
807                 // - add edit bones and head/tail properties using matrices and parent-child info
808                 // - exit edit mode
809                 // - set a sphere shape to leaf bones
810
811                 Object *ob_arm = skin.get_armature();
812
813                 // enter armature edit mode
814                 ED_armature_to_edit(ob_arm);
815
816                 leaf_bones.clear();
817                 totbone = 0;
818                 // bone_direction_row = 1; // TODO: don't default to Y but use asset and based on it decide on default row
819                 leaf_bone_length = 0.1f;
820                 // min_angle = 360.0f;          // minimum angle between bone head-tail and a row of bone matrix
821
822                 // create bones
823
824                 std::vector<COLLADAFW::Node*>::iterator it;
825                 for (it = root_joints.begin(); it != root_joints.end(); it++) {
826                         // since root_joints may contain joints for multiple controllers, we need to filter
827                         if (skin.uses_joint(*it)) {
828                                 create_bone(skin, *it, NULL, (*it)->getChildNodes().getCount(), NULL, (bArmature*)ob_arm->data);
829                         }
830                 }
831
832                 fix_leaf_bones();
833
834                 // exit armature edit mode
835                 ED_armature_from_edit(ob_arm);
836                 ED_armature_edit_free(ob_arm);
837                 DAG_id_flush_update(&ob_arm->id, OB_RECALC_OB|OB_RECALC_DATA);
838
839                 set_leaf_bone_shapes(ob_arm);
840
841                 // set_euler_rotmode();
842         }
843         
844
845 public:
846
847         ArmatureImporter(UnitConverter *conv, MeshImporterBase *mesh, AnimationImporterBase *anim, Scene *sce) :
848                 TransformReader(conv), scene(sce), empty(NULL), mesh_importer(mesh), anim_importer(anim) {}
849
850         ~ArmatureImporter()
851         {
852                 // free skin controller data if we forget to do this earlier
853                 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
854                 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
855                         it->second.free();
856                 }
857         }
858
859         // root - if this joint is the top joint in hierarchy, if a joint
860         // is a child of a node (not joint), root should be true since
861         // this is where we build armature bones from
862         void add_joint(COLLADAFW::Node *node, bool root)
863         {
864                 joint_by_uid[node->getUniqueId()] = node;
865                 if (root) root_joints.push_back(node);
866         }
867
868 #if 0
869         void add_root_joint(COLLADAFW::Node *node)
870         {
871                 // root_joints.push_back(node);
872                 Object *ob_arm = find_armature(node);
873                 if (ob_arm)     {
874                         get_armature_joints(ob_arm).root_joints.push_back(node);
875                 }
876 #ifdef COLLADA_DEBUG
877                 else {
878                         fprintf(stderr, "%s cannot be added to armature.\n", get_joint_name(node));
879                 }
880 #endif
881         }
882 #endif
883
884         // here we add bones to armatures, having armatures previously created in write_controller
885         void make_armatures(bContext *C)
886         {
887                 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
888                 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
889
890                         SkinInfo& skin = it->second;
891
892                         create_armature_bones(skin);
893
894                         // link armature with an object
895                         Object *ob = mesh_importer->get_object_by_geom_uid(*get_geometry_uid(skin.get_controller_uid()));
896                         if (ob) {
897                                 skin.link_armature(C, ob, joint_by_uid, this);
898                         }
899                         else {
900                                 fprintf(stderr, "Cannot find object to link armature with.\n");
901                         }
902
903                         // free memory stolen from SkinControllerData
904                         skin.free();
905                 }
906         }
907
908 #if 0
909         // link with meshes, create vertex groups, assign weights
910         void link_armature(Object *ob_arm, const COLLADAFW::UniqueId& geom_id, const COLLADAFW::UniqueId& controller_data_id)
911         {
912                 Object *ob = mesh_importer->get_object_by_geom_uid(geom_id);
913
914                 if (!ob) {
915                         fprintf(stderr, "Cannot find object by geometry UID.\n");
916                         return;
917                 }
918
919                 if (skin_by_data_uid.find(controller_data_id) == skin_by_data_uid.end()) {
920                         fprintf(stderr, "Cannot find skin info by controller data UID.\n");
921                         return;
922                 }
923
924                 SkinInfo& skin = skin_by_data_uid[conroller_data_id];
925
926                 // create vertex groups
927         }
928 #endif
929
930         bool write_skin_controller_data(const COLLADAFW::SkinControllerData* data)
931         {
932                 // at this stage we get vertex influence info that should go into me->verts and ob->defbase
933                 // there's no info to which object this should be long so we associate it with skin controller data UID
934
935                 // don't forget to call unique_vertexgroup_name before we copy
936
937                 // controller data uid -> [armature] -> joint data, 
938                 // [mesh object]
939                 // 
940
941                 SkinInfo skin(unit_converter);
942                 skin.borrow_skin_controller_data(data);
943
944                 // store join inv bind matrix to use it later in armature construction
945                 const COLLADAFW::Matrix4Array& inv_bind_mats = data->getInverseBindMatrices();
946                 for (int i = 0; i < data->getJointsCount(); i++) {
947                         skin.add_joint(inv_bind_mats[i]);
948                 }
949
950                 skin_by_data_uid[data->getUniqueId()] = skin;
951
952                 return true;
953         }
954
955         bool write_controller(const COLLADAFW::Controller* controller)
956         {
957                 // - create and store armature object
958
959                 const COLLADAFW::UniqueId& skin_id = controller->getUniqueId();
960
961                 if (controller->getControllerType() == COLLADAFW::Controller::CONTROLLER_TYPE_SKIN) {
962
963                         COLLADAFW::SkinController *co = (COLLADAFW::SkinController*)controller;
964
965                         // to find geom id by controller id
966                         geom_uid_by_controller_uid[skin_id] = co->getSource();
967
968                         const COLLADAFW::UniqueId& data_uid = co->getSkinControllerData();
969                         if (skin_by_data_uid.find(data_uid) == skin_by_data_uid.end()) {
970                                 fprintf(stderr, "Cannot find skin by controller data UID.\n");
971                                 return true;
972                         }
973
974                         Object *ob_arm = skin_by_data_uid[data_uid].create_armature(co, scene);
975
976                         armature_objects.push_back(ob_arm);
977                 }
978                 // morph controller
979                 else {
980                         // shape keys? :)
981                         fprintf(stderr, "Morph controller is not supported yet.\n");
982                 }
983
984                 return true;
985         }
986
987         COLLADAFW::UniqueId *get_geometry_uid(const COLLADAFW::UniqueId& controller_uid)
988         {
989                 if (geom_uid_by_controller_uid.find(controller_uid) == geom_uid_by_controller_uid.end())
990                         return NULL;
991
992                 return &geom_uid_by_controller_uid[controller_uid];
993         }
994
995         Object *get_armature_for_joint(COLLADAFW::Node *node)
996         {
997                 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
998                 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
999                         SkinInfo& skin = it->second;
1000
1001                         if (skin.uses_joint(node))
1002                                 return skin.get_armature();
1003                 }
1004
1005                 return NULL;
1006         }
1007
1008         void get_rna_path_for_joint(COLLADAFW::Node *node, char *joint_path, size_t count)
1009         {
1010                 BLI_snprintf(joint_path, count, "pose.bones[\"%s\"]", get_joint_name(node));
1011         }
1012         
1013 #if 0
1014         void fix_animation()
1015         {
1016                 /* Change Euler rotation to Quaternion for bone animation */
1017                 std::vector<Object*>::iterator it;
1018                 for (it = armature_objects.begin(); it != armature_objects.end(); it++) {
1019                         Object *ob = *it;
1020                         if (!ob || !ob->adt || !ob->adt->action) continue;
1021                         anim_importer->change_eul_to_quat(ob, ob->adt->action);
1022                 }
1023         }
1024 #endif
1025
1026         // gives a world-space mat
1027         bool get_joint_bind_mat(float m[][4], COLLADAFW::Node *joint)
1028         {
1029                 std::map<COLLADAFW::UniqueId, SkinInfo>::iterator it;
1030                 bool found = false;
1031                 for (it = skin_by_data_uid.begin(); it != skin_by_data_uid.end(); it++) {
1032                         SkinInfo& skin = it->second;
1033                         if ((found = skin.get_joint_inv_bind_matrix(m, joint))) {
1034                                 invert_m4(m);
1035                                 break;
1036                         }
1037                 }
1038
1039                 return found;
1040         }
1041 };
1042
1043 class MeshImporter : public MeshImporterBase
1044 {
1045 private:
1046
1047         Scene *scene;
1048         ArmatureImporter *armature_importer;
1049
1050         std::map<COLLADAFW::UniqueId, Mesh*> uid_mesh_map; // geometry unique id-to-mesh map
1051         std::map<COLLADAFW::UniqueId, Object*> uid_object_map; // geom uid-to-object
1052         // this structure is used to assign material indices to faces
1053         // it holds a portion of Mesh faces and corresponds to a DAE primitive list (<triangles>, <polylist>, etc.)
1054         struct Primitive {
1055                 MFace *mface;
1056                 unsigned int totface;
1057         };
1058         typedef std::map<COLLADAFW::MaterialId, std::vector<Primitive> > MaterialIdPrimitiveArrayMap;
1059         std::map<COLLADAFW::UniqueId, MaterialIdPrimitiveArrayMap> geom_uid_mat_mapping_map; // crazy name!
1060         
1061         class UVDataWrapper
1062         {
1063                 COLLADAFW::MeshVertexData *mVData;
1064         public:
1065                 UVDataWrapper(COLLADAFW::MeshVertexData& vdata) : mVData(&vdata)
1066                 {}
1067
1068 #ifdef COLLADA_DEBUG
1069                 void print()
1070                 {
1071                         fprintf(stderr, "UVs:\n");
1072                         switch(mVData->getType()) {
1073                         case COLLADAFW::MeshVertexData::DATA_TYPE_FLOAT:
1074                                 {
1075                                         COLLADAFW::ArrayPrimitiveType<float>* values = mVData->getFloatValues();
1076                                         if (values->getCount()) {
1077                                                 for (int i = 0; i < values->getCount(); i += 2) {
1078                                                         fprintf(stderr, "%.1f, %.1f\n", (*values)[i], (*values)[i+1]);
1079                                                 }
1080                                         }
1081                                 }
1082                                 break;
1083                         case COLLADAFW::MeshVertexData::DATA_TYPE_DOUBLE:
1084                                 {
1085                                         COLLADAFW::ArrayPrimitiveType<double>* values = mVData->getDoubleValues();
1086                                         if (values->getCount()) {
1087                                                 for (int i = 0; i < values->getCount(); i += 2) {
1088                                                         fprintf(stderr, "%.1f, %.1f\n", (float)(*values)[i], (float)(*values)[i+1]);
1089                                                 }
1090                                         }
1091                                 }
1092                                 break;
1093                         }
1094                         fprintf(stderr, "\n");
1095                 }
1096 #endif
1097
1098                 void getUV(int uv_set_index, int uv_index[2], float *uv)
1099                 {
1100                         switch(mVData->getType()) {
1101                         case COLLADAFW::MeshVertexData::DATA_TYPE_FLOAT:
1102                                 {
1103                                         COLLADAFW::ArrayPrimitiveType<float>* values = mVData->getFloatValues();
1104                                         if (values->empty()) return;
1105                                         uv[0] = (*values)[uv_index[0]];
1106                                         uv[1] = (*values)[uv_index[1]];
1107                                         
1108                                 }
1109                                 break;
1110                         case COLLADAFW::MeshVertexData::DATA_TYPE_DOUBLE:
1111                                 {
1112                                         COLLADAFW::ArrayPrimitiveType<double>* values = mVData->getDoubleValues();
1113                                         if (values->empty()) return;
1114                                         uv[0] = (float)(*values)[uv_index[0]];
1115                                         uv[1] = (float)(*values)[uv_index[1]];
1116                                         
1117                                 }
1118                                 break;
1119                         case COLLADAFW::MeshVertexData::DATA_TYPE_UNKNOWN:      
1120                         default:
1121                                 fprintf(stderr, "MeshImporter.getUV(): unknown data type\n");
1122                         }
1123                 }
1124         };
1125
1126         void set_face_indices(MFace *mface, unsigned int *indices, bool quad)
1127         {
1128                 mface->v1 = indices[0];
1129                 mface->v2 = indices[1];
1130                 mface->v3 = indices[2];
1131                 if (quad) mface->v4 = indices[3];
1132                 else mface->v4 = 0;
1133 #ifdef COLLADA_DEBUG
1134                 // fprintf(stderr, "%u, %u, %u \n", indices[0], indices[1], indices[2]);
1135 #endif
1136         }
1137
1138         // not used anymore, test_index_face from blenkernel is better
1139 #if 0
1140         // change face indices order so that v4 is not 0
1141         void rotate_face_indices(MFace *mface) {
1142                 mface->v4 = mface->v1;
1143                 mface->v1 = mface->v2;
1144                 mface->v2 = mface->v3;
1145                 mface->v3 = 0;
1146         }
1147 #endif
1148         
1149         void set_face_uv(MTFace *mtface, UVDataWrapper &uvs, int uv_set_index,
1150                                          COLLADAFW::IndexList& index_list, unsigned int *tris_indices)
1151         {
1152                 int uv_indices[4][2];
1153
1154                 // per face vertex indices, this means for quad we have 4 indices, not 8
1155                 COLLADAFW::UIntValuesArray& indices = index_list.getIndices();
1156
1157                 // make indices into FloatOrDoubleArray
1158                 for (int i = 0; i < 3; i++) {
1159                         int uv_index = indices[tris_indices[i]];
1160                         uv_indices[i][0] = uv_index * 2;
1161                         uv_indices[i][1] = uv_index * 2 + 1;
1162                 }
1163
1164                 uvs.getUV(uv_set_index, uv_indices[0], mtface->uv[0]);
1165                 uvs.getUV(uv_set_index, uv_indices[1], mtface->uv[1]);
1166                 uvs.getUV(uv_set_index, uv_indices[2], mtface->uv[2]);
1167         }
1168
1169         void set_face_uv(MTFace *mtface, UVDataWrapper &uvs, int uv_set_index,
1170                                         COLLADAFW::IndexList& index_list, int index, bool quad)
1171         {
1172                 int uv_indices[4][2];
1173
1174                 // per face vertex indices, this means for quad we have 4 indices, not 8
1175                 COLLADAFW::UIntValuesArray& indices = index_list.getIndices();
1176
1177                 // make indices into FloatOrDoubleArray
1178                 for (int i = 0; i < (quad ? 4 : 3); i++) {
1179                         int uv_index = indices[index + i];
1180                         uv_indices[i][0] = uv_index * 2;
1181                         uv_indices[i][1] = uv_index * 2 + 1;
1182                 }
1183
1184                 uvs.getUV(uv_set_index, uv_indices[0], mtface->uv[0]);
1185                 uvs.getUV(uv_set_index, uv_indices[1], mtface->uv[1]);
1186                 uvs.getUV(uv_set_index, uv_indices[2], mtface->uv[2]);
1187
1188                 if (quad) uvs.getUV(uv_set_index, uv_indices[3], mtface->uv[3]);
1189
1190 #ifdef COLLADA_DEBUG
1191                 /*if (quad) {
1192                         fprintf(stderr, "face uv:\n"
1193                                         "((%d, %d), (%d, %d), (%d, %d), (%d, %d))\n"
1194                                         "((%.1f, %.1f), (%.1f, %.1f), (%.1f, %.1f), (%.1f, %.1f))\n",
1195
1196                                         uv_indices[0][0], uv_indices[0][1],
1197                                         uv_indices[1][0], uv_indices[1][1],
1198                                         uv_indices[2][0], uv_indices[2][1],
1199                                         uv_indices[3][0], uv_indices[3][1],
1200
1201                                         mtface->uv[0][0], mtface->uv[0][1],
1202                                         mtface->uv[1][0], mtface->uv[1][1],
1203                                         mtface->uv[2][0], mtface->uv[2][1],
1204                                         mtface->uv[3][0], mtface->uv[3][1]);
1205                 }
1206                 else {
1207                         fprintf(stderr, "face uv:\n"
1208                                         "((%d, %d), (%d, %d), (%d, %d))\n"
1209                                         "((%.1f, %.1f), (%.1f, %.1f), (%.1f, %.1f))\n",
1210
1211                                         uv_indices[0][0], uv_indices[0][1],
1212                                         uv_indices[1][0], uv_indices[1][1],
1213                                         uv_indices[2][0], uv_indices[2][1],
1214
1215                                         mtface->uv[0][0], mtface->uv[0][1],
1216                                         mtface->uv[1][0], mtface->uv[1][1],
1217                                         mtface->uv[2][0], mtface->uv[2][1]);
1218                 }*/
1219 #endif
1220         }
1221
1222 #ifdef COLLADA_DEBUG
1223         void print_index_list(COLLADAFW::IndexList& index_list)
1224         {
1225                 fprintf(stderr, "Index list for \"%s\":\n", index_list.getName().c_str());
1226                 for (int i = 0; i < index_list.getIndicesCount(); i += 2) {
1227                         fprintf(stderr, "%u, %u\n", index_list.getIndex(i), index_list.getIndex(i + 1));
1228                 }
1229                 fprintf(stderr, "\n");
1230         }
1231 #endif
1232
1233         bool is_nice_mesh(COLLADAFW::Mesh *mesh)
1234         {
1235                 COLLADAFW::MeshPrimitiveArray& prim_arr = mesh->getMeshPrimitives();
1236                 int i;
1237
1238                 const char *name = get_dae_name(mesh);
1239                 
1240                 for (i = 0; i < prim_arr.getCount(); i++) {
1241                         
1242                         COLLADAFW::MeshPrimitive *mp = prim_arr[i];
1243                         COLLADAFW::MeshPrimitive::PrimitiveType type = mp->getPrimitiveType();
1244
1245                         const char *type_str = primTypeToStr(type);
1246                         
1247                         // OpenCollada passes POLYGONS type for <polylist>
1248                         if (type == COLLADAFW::MeshPrimitive::POLYLIST || type == COLLADAFW::MeshPrimitive::POLYGONS) {
1249
1250                                 COLLADAFW::Polygons *mpvc = (COLLADAFW::Polygons*)mp;
1251                                 COLLADAFW::Polygons::VertexCountArray& vca = mpvc->getGroupedVerticesVertexCountArray();
1252                                 
1253                                 for(int j = 0; j < vca.getCount(); j++){
1254                                         int count = vca[j];
1255                                         if (count < 3) {
1256                                                 fprintf(stderr, "Primitive %s in %s has at least one face with vertex count < 3\n",
1257                                                                 type_str, name);
1258                                                 return false;
1259                                         }
1260                                 }
1261                                         
1262                         }
1263                         else if(type != COLLADAFW::MeshPrimitive::TRIANGLES) {
1264                                 fprintf(stderr, "Primitive type %s is not supported.\n", type_str);
1265                                 return false;
1266                         }
1267                 }
1268                 
1269                 if (mesh->getPositions().empty()) {
1270                         fprintf(stderr, "Mesh %s has no vertices.\n", name);
1271                         return false;
1272                 }
1273
1274                 return true;
1275         }
1276
1277         void read_vertices(COLLADAFW::Mesh *mesh, Mesh *me)
1278         {
1279                 // vertices     
1280                 me->totvert = mesh->getPositions().getFloatValues()->getCount() / 3;
1281                 me->mvert = (MVert*)CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, me->totvert);
1282
1283                 const COLLADAFW::MeshVertexData& pos = mesh->getPositions();
1284                 MVert *mvert;
1285                 int i, j;
1286
1287                 for (i = 0, mvert = me->mvert; i < me->totvert; i++, mvert++) {
1288                         j = i * 3;
1289
1290                         if (pos.getType() == COLLADAFW::MeshVertexData::DATA_TYPE_FLOAT) {
1291                                 const float *array = pos.getFloatValues()->getData();
1292                                 mvert->co[0] = array[j];
1293                                 mvert->co[1] = array[j + 1];
1294                                 mvert->co[2] = array[j + 2];
1295                         }
1296                         else if (pos.getType() == COLLADAFW::MeshVertexData::DATA_TYPE_DOUBLE){
1297                                 const double *array = pos.getDoubleValues()->getData();
1298                                 mvert->co[0] = (float)array[j];
1299                                 mvert->co[1] = (float)array[j + 1];
1300                                 mvert->co[2] = (float)array[j + 2];
1301                         }
1302                         else {
1303                                 fprintf(stderr, "Cannot read vertex positions: unknown data type.\n");
1304                                 break;
1305                         }
1306                 }
1307         }
1308         
1309         int triangulate_poly(unsigned int *indices, int totvert, MVert *verts, std::vector<unsigned int>& tri)
1310         {
1311                 ListBase dispbase;
1312                 DispList *dl;
1313                 float *vert;
1314                 int i = 0;
1315                 
1316                 dispbase.first = dispbase.last = NULL;
1317                 
1318                 dl = (DispList*)MEM_callocN(sizeof(DispList), "poly disp");
1319                 dl->nr = totvert;
1320                 dl->type = DL_POLY;
1321                 dl->parts = 1;
1322                 dl->verts = vert = (float*)MEM_callocN(totvert * 3 * sizeof(float), "poly verts");
1323                 dl->index = (int*)MEM_callocN(sizeof(int) * 3 * totvert, "dl index");
1324
1325                 BLI_addtail(&dispbase, dl);
1326                 
1327                 for (i = 0; i < totvert; i++) {
1328                         copy_v3_v3(vert, verts[indices[i]].co);
1329                         vert += 3;
1330                 }
1331                 
1332                 filldisplist(&dispbase, &dispbase);
1333
1334                 int tottri = 0;
1335                 dl= (DispList*)dispbase.first;
1336
1337                 if (dl->type == DL_INDEX3) {
1338                         tottri = dl->parts;
1339
1340                         int *index = dl->index;
1341                         for (i= 0; i < tottri; i++) {
1342                                 int t[3]= {*index, *(index + 1), *(index + 2)};
1343
1344                                 std::sort(t, t + 3);
1345
1346                                 tri.push_back(t[0]);
1347                                 tri.push_back(t[1]);
1348                                 tri.push_back(t[2]);
1349
1350                                 index += 3;
1351                         }
1352                 }
1353
1354                 freedisplist(&dispbase);
1355
1356                 return tottri;
1357         }
1358         
1359         int count_new_tris(COLLADAFW::Mesh *mesh, Mesh *me)
1360         {
1361                 COLLADAFW::MeshPrimitiveArray& prim_arr = mesh->getMeshPrimitives();
1362                 int i, j;
1363                 int tottri = 0;
1364                 
1365                 for (i = 0; i < prim_arr.getCount(); i++) {
1366                         
1367                         COLLADAFW::MeshPrimitive *mp = prim_arr[i];
1368                         int type = mp->getPrimitiveType();
1369                         size_t prim_totface = mp->getFaceCount();
1370                         unsigned int *indices = mp->getPositionIndices().getData();
1371                         
1372                         if (type == COLLADAFW::MeshPrimitive::POLYLIST ||
1373                                 type == COLLADAFW::MeshPrimitive::POLYGONS) {
1374                                 
1375                                 COLLADAFW::Polygons *mpvc =     (COLLADAFW::Polygons*)mp;
1376                                 COLLADAFW::Polygons::VertexCountArray& vcounta = mpvc->getGroupedVerticesVertexCountArray();
1377                                 
1378                                 for (j = 0; j < prim_totface; j++) {
1379                                         int vcount = vcounta[j];
1380                                         
1381                                         if (vcount > 4) {
1382                                                 std::vector<unsigned int> tri;
1383                                                 
1384                                                 // tottri += triangulate_poly(indices, vcount, me->mvert, tri) - 1; // XXX why - 1?!
1385                                                 tottri += triangulate_poly(indices, vcount, me->mvert, tri);
1386                                         }
1387
1388                                         indices += vcount;
1389                                 }
1390                         }
1391                 }
1392                 return tottri;
1393         }
1394         
1395         // TODO: import uv set names
1396         void read_faces(COLLADAFW::Mesh *mesh, Mesh *me, int new_tris)
1397         {
1398                 int i;
1399                 
1400                 // allocate faces
1401                 me->totface = mesh->getFacesCount() + new_tris;
1402                 me->mface = (MFace*)CustomData_add_layer(&me->fdata, CD_MFACE, CD_CALLOC, NULL, me->totface);
1403                 
1404                 // allocate UV layers
1405                 int totuvset = mesh->getUVCoords().getInputInfosArray().getCount();
1406
1407                 for (i = 0; i < totuvset; i++) {
1408                         CustomData_add_layer(&me->fdata, CD_MTFACE, CD_CALLOC, NULL, me->totface);
1409                         //this->set_layername_map[i] = CustomData_get_layer_name(&me->fdata, CD_MTFACE, i);
1410                 }
1411
1412                 // activate the first uv layer
1413                 if (totuvset) me->mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, 0);
1414
1415                 UVDataWrapper uvs(mesh->getUVCoords());
1416
1417 #ifdef COLLADA_DEBUG
1418                 // uvs.print();
1419 #endif
1420
1421                 MFace *mface = me->mface;
1422
1423                 MaterialIdPrimitiveArrayMap mat_prim_map;
1424
1425                 int face_index = 0;
1426
1427                 COLLADAFW::MeshPrimitiveArray& prim_arr = mesh->getMeshPrimitives();
1428
1429                 for (i = 0; i < prim_arr.getCount(); i++) {
1430                         
1431                         COLLADAFW::MeshPrimitive *mp = prim_arr[i];
1432
1433                         // faces
1434                         size_t prim_totface = mp->getFaceCount();
1435                         unsigned int *indices = mp->getPositionIndices().getData();
1436                         int j, k;
1437                         int type = mp->getPrimitiveType();
1438                         int index = 0;
1439                         
1440                         // since we cannot set mface->mat_nr here, we store a portion of me->mface in Primitive
1441                         Primitive prim = {mface, 0};
1442                         COLLADAFW::IndexListArray& index_list_array = mp->getUVCoordIndicesArray();
1443
1444 #ifdef COLLADA_DEBUG
1445                         /*
1446                         fprintf(stderr, "Primitive %d:\n", i);
1447                         for (int j = 0; j < totuvset; j++) {
1448                                 print_index_list(*index_list_array[j]);
1449                         }
1450                         */
1451 #endif
1452                         
1453                         if (type == COLLADAFW::MeshPrimitive::TRIANGLES) {
1454                                 for (j = 0; j < prim_totface; j++){
1455                                         
1456                                         set_face_indices(mface, indices, false);
1457                                         indices += 3;
1458
1459                                         for (k = 0; k < totuvset; k++) {
1460                                                 // get mtface by face index and uv set index
1461                                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, k);
1462                                                 set_face_uv(&mtface[face_index], uvs, k, *index_list_array[k], index, false);
1463                                         }
1464
1465                                         test_index_face(mface, &me->fdata, face_index, 3);
1466                                         
1467                                         index += 3;
1468                                         mface++;
1469                                         face_index++;
1470                                         prim.totface++;
1471                                 }
1472                         }
1473                         else if (type == COLLADAFW::MeshPrimitive::POLYLIST || type == COLLADAFW::MeshPrimitive::POLYGONS) {
1474                                 COLLADAFW::Polygons *mpvc =     (COLLADAFW::Polygons*)mp;
1475                                 COLLADAFW::Polygons::VertexCountArray& vcounta = mpvc->getGroupedVerticesVertexCountArray();
1476                                 
1477                                 for (j = 0; j < prim_totface; j++) {
1478                                         
1479                                         // face
1480                                         int vcount = vcounta[j];
1481                                         if (vcount == 3 || vcount == 4) {
1482                                                 
1483                                                 set_face_indices(mface, indices, vcount == 4);
1484                                                 
1485                                                 // set mtface for each uv set
1486                                                 // it is assumed that all primitives have equal number of UV sets
1487                                                 
1488                                                 for (k = 0; k < totuvset; k++) {
1489                                                         // get mtface by face index and uv set index
1490                                                         MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, k);
1491                                                         set_face_uv(&mtface[face_index], uvs, k, *index_list_array[k], index, mface->v4 != 0);
1492                                                 }
1493
1494                                                 test_index_face(mface, &me->fdata, face_index, vcount);
1495                                                 
1496                                                 mface++;
1497                                                 face_index++;
1498                                                 prim.totface++;
1499                                                 
1500                                         }
1501                                         else {
1502                                                 std::vector<unsigned int> tri;
1503                                                 
1504                                                 triangulate_poly(indices, vcount, me->mvert, tri);
1505                                                 
1506                                                 for (k = 0; k < tri.size() / 3; k++) {
1507                                                         int v = k * 3;
1508                                                         unsigned int uv_indices[3] = {
1509                                                                 index + tri[v],
1510                                                                 index + tri[v + 1],
1511                                                                 index + tri[v + 2]
1512                                                         };
1513                                                         unsigned int tri_indices[3] = {
1514                                                                 indices[tri[v]],
1515                                                                 indices[tri[v + 1]],
1516                                                                 indices[tri[v + 2]]
1517                                                         };
1518
1519                                                         set_face_indices(mface, tri_indices, false);
1520                                                         
1521                                                         for (int l = 0; l < totuvset; l++) {
1522                                                                 // get mtface by face index and uv set index
1523                                                                 MTFace *mtface = (MTFace*)CustomData_get_layer_n(&me->fdata, CD_MTFACE, l);
1524                                                                 set_face_uv(&mtface[face_index], uvs, l, *index_list_array[l], uv_indices);
1525                                                         }
1526
1527                                                         test_index_face(mface, &me->fdata, face_index, 3);
1528                                                         
1529                                                         mface++;
1530                                                         face_index++;
1531                                                         prim.totface++;
1532                                                 }
1533                                         }
1534
1535                                         index += vcount;
1536                                         indices += vcount;
1537                                 }
1538                         }
1539                         
1540                         mat_prim_map[mp->getMaterialId()].push_back(prim);
1541                 }
1542
1543                 geom_uid_mat_mapping_map[mesh->getUniqueId()] = mat_prim_map;
1544         }
1545
1546 public:
1547
1548         MeshImporter(ArmatureImporter *arm, Scene *sce) : scene(sce), armature_importer(arm) {}
1549
1550         virtual Object *get_object_by_geom_uid(const COLLADAFW::UniqueId& geom_uid)
1551         {
1552                 if (uid_object_map.find(geom_uid) != uid_object_map.end())
1553                         return uid_object_map[geom_uid];
1554                 return NULL;
1555         }
1556         
1557         MTex *assign_textures_to_uvlayer(COLLADAFW::InstanceGeometry::TextureCoordinateBinding &ctexture,
1558                                                                          Mesh *me, TexIndexTextureArrayMap& texindex_texarray_map,
1559                                                                          MTex *color_texture)
1560         {
1561                 
1562                 COLLADAFW::TextureMapId texture_index = ctexture.textureMapId;
1563                 
1564                 char *uvname = CustomData_get_layer_name(&me->fdata, CD_MTFACE, ctexture.setIndex);
1565                 
1566                 if (texindex_texarray_map.find(texture_index) == texindex_texarray_map.end()) {
1567                         
1568                         fprintf(stderr, "Cannot find texture array by texture index.\n");
1569                         return color_texture;
1570                 }
1571                 
1572                 std::vector<MTex*> textures = texindex_texarray_map[texture_index];
1573                 
1574                 std::vector<MTex*>::iterator it;
1575                 
1576                 for (it = textures.begin(); it != textures.end(); it++) {
1577                         
1578                         MTex *texture = *it;
1579                         
1580                         if (texture) {
1581                                 strcpy(texture->uvname, uvname);
1582                                 if (texture->mapto == MAP_COL) color_texture = texture;
1583                         }
1584                 }
1585                 return color_texture;
1586         }
1587         
1588         MTFace *assign_material_to_geom(COLLADAFW::InstanceGeometry::MaterialBinding cmaterial,
1589                                                                         std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
1590                                                                         Object *ob, const COLLADAFW::UniqueId *geom_uid, 
1591                                                                         MTex **color_texture, char *layername, MTFace *texture_face,
1592                                                                         std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map, int mat_index)
1593         {
1594                 Mesh *me = (Mesh*)ob->data;
1595                 const COLLADAFW::UniqueId& ma_uid = cmaterial.getReferencedMaterial();
1596                 
1597                 // do we know this material?
1598                 if (uid_material_map.find(ma_uid) == uid_material_map.end()) {
1599                         
1600                         fprintf(stderr, "Cannot find material by UID.\n");
1601                         return NULL;
1602                 }
1603                 
1604                 Material *ma = uid_material_map[ma_uid];
1605                 assign_material(ob, ma, ob->totcol + 1);
1606                 
1607                 COLLADAFW::InstanceGeometry::TextureCoordinateBindingArray& tex_array = 
1608                         cmaterial.getTextureCoordinateBindingArray();
1609                 TexIndexTextureArrayMap texindex_texarray_map = material_texture_mapping_map[ma];
1610                 unsigned int i;
1611                 // loop through <bind_vertex_inputs>
1612                 for (i = 0; i < tex_array.getCount(); i++) {
1613                         
1614                         *color_texture = assign_textures_to_uvlayer(tex_array[i], me, texindex_texarray_map,
1615                                                                                                                 *color_texture);
1616                 }
1617                 
1618                 // set texture face
1619                 if (*color_texture &&
1620                         strlen((*color_texture)->uvname) &&
1621                         strcmp(layername, (*color_texture)->uvname) != 0) {
1622                         
1623                         texture_face = (MTFace*)CustomData_get_layer_named(&me->fdata, CD_MTFACE,
1624                                                                                                                            (*color_texture)->uvname);
1625                         strcpy(layername, (*color_texture)->uvname);
1626                 }
1627                 
1628                 MaterialIdPrimitiveArrayMap& mat_prim_map = geom_uid_mat_mapping_map[*geom_uid];
1629                 COLLADAFW::MaterialId mat_id = cmaterial.getMaterialId();
1630                 
1631                 // assign material indices to mesh faces
1632                 if (mat_prim_map.find(mat_id) != mat_prim_map.end()) {
1633                         
1634                         std::vector<Primitive>& prims = mat_prim_map[mat_id];
1635                         
1636                         std::vector<Primitive>::iterator it;
1637                         
1638                         for (it = prims.begin(); it != prims.end(); it++) {
1639                                 Primitive& prim = *it;
1640                                 i = 0;
1641                                 while (i++ < prim.totface) {
1642                                         prim.mface->mat_nr = mat_index;
1643                                         prim.mface++;
1644                                         // bind texture images to faces
1645                                         if (texture_face && (*color_texture)) {
1646                                                 texture_face->mode = TF_TEX;
1647                                                 texture_face->tpage = (Image*)(*color_texture)->tex->ima;
1648                                                 texture_face++;
1649                                         }
1650                                 }
1651                         }
1652                 }
1653                 
1654                 return texture_face;
1655         }
1656         
1657         
1658         Object *create_mesh_object(COLLADAFW::Node *node, COLLADAFW::InstanceGeometry *geom,
1659                                                            bool isController,
1660                                                            std::map<COLLADAFW::UniqueId, Material*>& uid_material_map,
1661                                                            std::map<Material*, TexIndexTextureArrayMap>& material_texture_mapping_map)
1662         {
1663                 const COLLADAFW::UniqueId *geom_uid = &geom->getInstanciatedObjectId();
1664                 
1665                 // check if node instanciates controller or geometry
1666                 if (isController) {
1667                         
1668                         geom_uid = armature_importer->get_geometry_uid(*geom_uid);
1669                         
1670                         if (!geom_uid) {
1671                                 fprintf(stderr, "Couldn't find a mesh UID by controller's UID.\n");
1672                                 return NULL;
1673                         }
1674                 }
1675                 else {
1676                         
1677                         if (uid_mesh_map.find(*geom_uid) == uid_mesh_map.end()) {
1678                                 // this could happen if a mesh was not created
1679                                 // (e.g. if it contains unsupported geometry)
1680                                 fprintf(stderr, "Couldn't find a mesh by UID.\n");
1681                                 return NULL;
1682                         }
1683                 }
1684                 if (!uid_mesh_map[*geom_uid]) return NULL;
1685                 
1686                 Object *ob = add_object(scene, OB_MESH);
1687
1688                 // store object pointer for ArmatureImporter
1689                 uid_object_map[*geom_uid] = ob;
1690                 
1691                 // name Object
1692                 const std::string& id = node->getOriginalId();
1693                 if (id.length())
1694                         rename_id(&ob->id, (char*)id.c_str());
1695                 
1696                 // replace ob->data freeing the old one
1697                 Mesh *old_mesh = (Mesh*)ob->data;
1698
1699                 set_mesh(ob, uid_mesh_map[*geom_uid]);
1700                 
1701                 if (old_mesh->id.us == 0) free_libblock(&G.main->mesh, old_mesh);
1702                 
1703                 char layername[100];
1704                 MTFace *texture_face = NULL;
1705                 MTex *color_texture = NULL;
1706                 
1707                 COLLADAFW::InstanceGeometry::MaterialBindingArray& mat_array = 
1708                         geom->getMaterialBindings();
1709                 
1710                 // loop through geom's materials
1711                 for (unsigned int i = 0; i < mat_array.getCount(); i++) {
1712                         
1713                         texture_face = assign_material_to_geom(mat_array[i], uid_material_map, ob, geom_uid,
1714                                                                                                    &color_texture, layername, texture_face,
1715                                                                                                    material_texture_mapping_map, i);
1716                 }
1717                         
1718                 return ob;
1719         }
1720
1721         // create a mesh storing a pointer in a map so it can be retrieved later by geometry UID
1722         bool write_geometry(const COLLADAFW::Geometry* geom) 
1723         {
1724                 // TODO: import also uvs, normals
1725                 // XXX what to do with normal indices?
1726                 // XXX num_normals may be != num verts, then what to do?
1727
1728                 // check geometry->getType() first
1729                 if (geom->getType() != COLLADAFW::Geometry::GEO_TYPE_MESH) {
1730                         // TODO: report warning
1731                         fprintf(stderr, "Mesh type %s is not supported\n", geomTypeToStr(geom->getType()));
1732                         return true;
1733                 }
1734                 
1735                 COLLADAFW::Mesh *mesh = (COLLADAFW::Mesh*)geom;
1736                 
1737                 if (!is_nice_mesh(mesh)) {
1738                         fprintf(stderr, "Ignoring mesh %s\n", get_dae_name(mesh));
1739                         return true;
1740                 }
1741                 
1742                 const std::string& str_geom_id = mesh->getOriginalId();
1743                 Mesh *me = add_mesh((char*)str_geom_id.c_str());
1744
1745                 // store the Mesh pointer to link it later with an Object
1746                 this->uid_mesh_map[mesh->getUniqueId()] = me;
1747                 
1748                 int new_tris = 0;
1749                 
1750                 read_vertices(mesh, me);
1751
1752                 new_tris = count_new_tris(mesh, me);
1753                 
1754                 read_faces(mesh, me, new_tris);
1755
1756                 make_edges(me, 0);
1757                 
1758                 mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
1759
1760                 return true;
1761         }
1762
1763 };
1764
1765 class AnimationImporter : private TransformReader, public AnimationImporterBase
1766 {
1767 private:
1768
1769         ArmatureImporter *armature_importer;
1770         Scene *scene;
1771
1772         std::map<COLLADAFW::UniqueId, std::vector<FCurve*> > curve_map;
1773         std::map<COLLADAFW::UniqueId, TransformReader::Animation> uid_animated_map;
1774         // std::map<bActionGroup*, std::vector<FCurve*> > fcurves_actionGroup_map;
1775         std::map<COLLADAFW::UniqueId, const COLLADAFW::AnimationList*> animlist_map;
1776         std::vector<FCurve*> unused_curves;
1777         std::map<COLLADAFW::UniqueId, Object*> joint_objects;
1778         
1779         FCurve *create_fcurve(int array_index, const char *rna_path)
1780         {
1781                 FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
1782                 
1783                 fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
1784                 fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
1785                 fcu->array_index = array_index;
1786                 return fcu;
1787         }
1788         
1789         void create_bezt(FCurve *fcu, float frame, float output)
1790         {
1791                 BezTriple bez;
1792                 memset(&bez, 0, sizeof(BezTriple));
1793                 bez.vec[1][0] = frame;
1794                 bez.vec[1][1] = output;
1795                 bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1796                 bez.f1 = bez.f2 = bez.f3 = SELECT;
1797                 bez.h1 = bez.h2 = HD_AUTO;
1798                 insert_bezt_fcurve(fcu, &bez, 0);
1799                 calchandles_fcurve(fcu);
1800         }
1801
1802         // create one or several fcurves depending on the number of parameters being animated
1803         void animation_to_fcurves(COLLADAFW::AnimationCurve *curve)
1804         {
1805                 COLLADAFW::FloatOrDoubleArray& input = curve->getInputValues();
1806                 COLLADAFW::FloatOrDoubleArray& output = curve->getOutputValues();
1807                 // COLLADAFW::FloatOrDoubleArray& intan = curve->getInTangentValues();
1808                 // COLLADAFW::FloatOrDoubleArray& outtan = curve->getOutTangentValues();
1809                 float fps = (float)FPS;
1810                 size_t dim = curve->getOutDimension();
1811                 int i;
1812
1813                 std::vector<FCurve*>& fcurves = curve_map[curve->getUniqueId()];
1814
1815                 if (dim == 1) {
1816                         FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
1817
1818                         fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
1819                         // fcu->rna_path = BLI_strdupn(path, strlen(path));
1820                         fcu->array_index = 0;
1821                         //fcu->totvert = curve->getKeyCount();
1822                         
1823                         // create beztriple for each key
1824                         for (i = 0; i < curve->getKeyCount(); i++) {
1825                                 BezTriple bez;
1826                                 memset(&bez, 0, sizeof(BezTriple));
1827
1828                                 // intangent
1829                                 // bez.vec[0][0] = get_float_value(intan, i + i) * fps;
1830                                 // bez.vec[0][1] = get_float_value(intan, i + i + 1);
1831
1832                                 // input, output
1833                                 bez.vec[1][0] = get_float_value(input, i) * fps;
1834                                 bez.vec[1][1] = get_float_value(output, i);
1835
1836                                 // outtangent
1837                                 // bez.vec[2][0] = get_float_value(outtan, i + i) * fps;
1838                                 // bez.vec[2][1] = get_float_value(outtan, i + i + 1);
1839                                 
1840                                 bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1841                                 bez.f1 = bez.f2 = bez.f3 = SELECT;
1842                                 bez.h1 = bez.h2 = HD_AUTO;
1843                                 insert_bezt_fcurve(fcu, &bez, 0);
1844                         }
1845
1846                         calchandles_fcurve(fcu);
1847
1848                         fcurves.push_back(fcu);
1849                 }
1850                 else if(dim == 3) {
1851                         for (i = 0; i < dim; i++ ) {
1852                                 FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
1853                                 
1854                                 fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
1855                                 // fcu->rna_path = BLI_strdupn(path, strlen(path));
1856                                 fcu->array_index = 0;
1857                                 //fcu->totvert = curve->getKeyCount();
1858                                 
1859                                 // create beztriple for each key
1860                                 for (int j = 0; j < curve->getKeyCount(); j++) {
1861                                         BezTriple bez;
1862                                         memset(&bez, 0, sizeof(BezTriple));
1863
1864                                         // intangent
1865                                         // bez.vec[0][0] = get_float_value(intan, j * 6 + i + i) * fps;
1866                                         // bez.vec[0][1] = get_float_value(intan, j * 6 + i + i + 1);
1867
1868                                         // input, output
1869                                         bez.vec[1][0] = get_float_value(input, j) * fps; 
1870                                         bez.vec[1][1] = get_float_value(output, j * 3 + i);
1871
1872                                         // outtangent
1873                                         // bez.vec[2][0] = get_float_value(outtan, j * 6 + i + i) * fps;
1874                                         // bez.vec[2][1] = get_float_value(outtan, j * 6 + i + i + 1);
1875
1876                                         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1877                                         bez.f1 = bez.f2 = bez.f3 = SELECT;
1878                                         bez.h1 = bez.h2 = HD_AUTO;
1879                                         insert_bezt_fcurve(fcu, &bez, 0);
1880                                 }
1881
1882                                 calchandles_fcurve(fcu);
1883
1884                                 fcurves.push_back(fcu);
1885                         }
1886                 }
1887
1888                 for (std::vector<FCurve*>::iterator it = fcurves.begin(); it != fcurves.end(); it++)
1889                         unused_curves.push_back(*it);
1890         }
1891
1892         void fcurve_deg_to_rad(FCurve *cu)
1893         {
1894                 for (int i = 0; i < cu->totvert; i++) {
1895                         // TODO convert handles too
1896                         cu->bezt[i].vec[1][1] *= M_PI / 180.0f;
1897                 }
1898         }
1899
1900 #if 0
1901         void make_fcurves_from_animation(COLLADAFW::AnimationCurve *curve,
1902                                                                          COLLADAFW::FloatOrDoubleArray& input,
1903                                                                          COLLADAFW::FloatOrDoubleArray& output,
1904                                                                          COLLADAFW::FloatOrDoubleArray& intan,
1905                                                                          COLLADAFW::FloatOrDoubleArray& outtan, size_t dim, float fps)
1906         {
1907                 int i;
1908                 // char *path = "location";
1909                 std::vector<FCurve*>& fcurves = curve_map[curve->getUniqueId()];
1910
1911                 if (dim == 1) {
1912                         // create fcurve
1913                         FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
1914
1915                         fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
1916                         // fcu->rna_path = BLI_strdupn(path, strlen(path));
1917                         fcu->array_index = 0;
1918                         //fcu->totvert = curve->getKeyCount();
1919                         
1920                         // create beztriple for each key
1921                         for (i = 0; i < curve->getKeyCount(); i++) {
1922                                 BezTriple bez;
1923                                 memset(&bez, 0, sizeof(BezTriple));
1924                                 // intangent
1925                                 bez.vec[0][0] = get_float_value(intan, i + i) * fps;
1926                                 bez.vec[0][1] = get_float_value(intan, i + i + 1);
1927                                 // input, output
1928                                 bez.vec[1][0] = get_float_value(input, i) * fps;
1929                                 bez.vec[1][1] = get_float_value(output, i);
1930                                 // outtangent
1931                                 bez.vec[2][0] = get_float_value(outtan, i + i) * fps;
1932                                 bez.vec[2][1] = get_float_value(outtan, i + i + 1);
1933                                 
1934                                 bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1935                                 bez.f1 = bez.f2 = bez.f3 = SELECT;
1936                                 bez.h1 = bez.h2 = HD_AUTO;
1937                                 insert_bezt_fcurve(fcu, &bez, 0);
1938                                 calchandles_fcurve(fcu);
1939                         }
1940
1941                         fcurves.push_back(fcu);
1942                 }
1943                 else if(dim == 3) {
1944                         for (i = 0; i < dim; i++ ) {
1945                                 // create fcurve
1946                                 FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
1947                                 
1948                                 fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
1949                                 // fcu->rna_path = BLI_strdupn(path, strlen(path));
1950                                 fcu->array_index = 0;
1951                                 //fcu->totvert = curve->getKeyCount();
1952                                 
1953                                 // create beztriple for each key
1954                                 for (int j = 0; j < curve->getKeyCount(); j++) {
1955                                         BezTriple bez;
1956                                         memset(&bez, 0, sizeof(BezTriple));
1957                                         // intangent
1958                                         bez.vec[0][0] = get_float_value(intan, j * 6 + i + i) * fps;
1959                                         bez.vec[0][1] = get_float_value(intan, j * 6 + i + i + 1);
1960                                         // input, output
1961                                         bez.vec[1][0] = get_float_value(input, j) * fps; 
1962                                         bez.vec[1][1] = get_float_value(output, j * 3 + i);
1963                                         // outtangent
1964                                         bez.vec[2][0] = get_float_value(outtan, j * 6 + i + i) * fps;
1965                                         bez.vec[2][1] = get_float_value(outtan, j * 6 + i + i + 1);
1966
1967                                         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1968                                         bez.f1 = bez.f2 = bez.f3 = SELECT;
1969                                         bez.h1 = bez.h2 = HD_AUTO;
1970                                         insert_bezt_fcurve(fcu, &bez, 0);
1971                                         calchandles_fcurve(fcu);
1972                                 }
1973
1974                                 fcurves.push_back(fcu);
1975                         }
1976                 }
1977         }
1978 #endif
1979         
1980         void add_fcurves_to_object(Object *ob, std::vector<FCurve*>& curves, char *rna_path, int array_index, Animation *animated)
1981         {
1982                 bAction *act;
1983                 
1984                 if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
1985                 else act = ob->adt->action;
1986                 
1987                 std::vector<FCurve*>::iterator it;
1988                 int i;
1989
1990 #if 0
1991                 char *p = strstr(rna_path, "rotation_euler");
1992                 bool is_rotation = p && *(p + strlen("rotation_euler")) == '\0';
1993
1994                 // convert degrees to radians for rotation
1995                 if (is_rotation)
1996                         fcurve_deg_to_rad(fcu);
1997 #endif
1998                 
1999                 for (it = curves.begin(), i = 0; it != curves.end(); it++, i++) {
2000                         FCurve *fcu = *it;
2001                         fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
2002                         
2003                         if (array_index == -1) fcu->array_index = i;
2004                         else fcu->array_index = array_index;
2005                 
2006                         if (ob->type == OB_ARMATURE) {
2007                                 bActionGroup *grp = NULL;
2008                                 const char *bone_name = get_joint_name(animated->node);
2009                                 
2010                                 if (bone_name) {
2011                                         /* try to find group */
2012                                         grp = action_groups_find_named(act, bone_name);
2013                                         
2014                                         /* no matching groups, so add one */
2015                                         if (grp == NULL) {
2016                                                 /* Add a new group, and make it active */
2017                                                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
2018                                                 
2019                                                 grp->flag = AGRP_SELECTED;
2020                                                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
2021                                                 
2022                                                 BLI_addtail(&act->groups, grp);
2023                                                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
2024                                         }
2025                                         
2026                                         /* add F-Curve to group */
2027                                         action_groups_add_channel(act, grp, fcu);
2028                                         
2029                                 }
2030 #if 0
2031                                 if (is_rotation) {
2032                                         fcurves_actionGroup_map[grp].push_back(fcu);
2033                                 }
2034 #endif
2035                         }
2036                         else {
2037                                 BLI_addtail(&act->curves, fcu);
2038                         }
2039
2040                         // curve is used, so remove it from unused_curves
2041                         unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
2042                 }
2043         }
2044 public:
2045
2046         AnimationImporter(UnitConverter *conv, ArmatureImporter *arm, Scene *scene) :
2047                 TransformReader(conv), armature_importer(arm), scene(scene) { }
2048
2049         ~AnimationImporter()
2050         {
2051                 // free unused FCurves
2052                 for (std::vector<FCurve*>::iterator it = unused_curves.begin(); it != unused_curves.end(); it++)
2053                         free_fcurve(*it);
2054
2055                 if (unused_curves.size())
2056                         fprintf(stderr, "removed %u unused curves\n", unused_curves.size());
2057         }
2058
2059         bool write_animation(const COLLADAFW::Animation* anim) 
2060         {
2061                 if (anim->getAnimationType() == COLLADAFW::Animation::ANIMATION_CURVE) {
2062                         COLLADAFW::AnimationCurve *curve = (COLLADAFW::AnimationCurve*)anim;
2063                         
2064                         // XXX Don't know if it's necessary
2065                         // Should we check outPhysicalDimension?
2066                         if (curve->getInPhysicalDimension() != COLLADAFW::PHYSICAL_DIMENSION_TIME) {
2067                                 fprintf(stderr, "Inputs physical dimension is not time. \n");
2068                                 return true;
2069                         }
2070
2071                         // a curve can have mixed interpolation type,
2072                         // in this case curve->getInterpolationTypes returns a list of interpolation types per key
2073                         COLLADAFW::AnimationCurve::InterpolationType interp = curve->getInterpolationType();
2074
2075                         if (interp != COLLADAFW::AnimationCurve::INTERPOLATION_MIXED) {
2076                                 switch (interp) {
2077                                 case COLLADAFW::AnimationCurve::INTERPOLATION_LINEAR:
2078                                 case COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER:
2079                                         animation_to_fcurves(curve);
2080                                         break;
2081                                 default:
2082                                         // TODO there're also CARDINAL, HERMITE, BSPLINE and STEP types
2083                                         fprintf(stderr, "CARDINAL, HERMITE, BSPLINE and STEP anim interpolation types not supported yet.\n");
2084                                         break;
2085                                 }
2086                         }
2087                         else {
2088                                 // not supported yet
2089                                 fprintf(stderr, "MIXED anim interpolation type is not supported yet.\n");
2090                         }
2091                 }
2092                 else {
2093                         fprintf(stderr, "FORMULA animation type is not supported yet.\n");
2094                 }
2095                 
2096                 return true;
2097         }
2098         
2099         // called on post-process stage after writeVisualScenes
2100         bool write_animation_list(const COLLADAFW::AnimationList* animlist) 
2101         {
2102                 const COLLADAFW::UniqueId& animlist_id = animlist->getUniqueId();
2103
2104                 animlist_map[animlist_id] = animlist;
2105
2106 #if 0
2107                 // should not happen
2108                 if (uid_animated_map.find(animlist_id) == uid_animated_map.end()) {
2109                         return true;
2110                 }
2111
2112                 // for bones rna_path is like: pose.bones["bone-name"].rotation
2113                 
2114                 // what does this AnimationList animate?
2115                 Animation& animated = uid_animated_map[animlist_id];
2116                 Object *ob = animated.ob;
2117
2118                 char rna_path[100];
2119                 char joint_path[100];
2120                 bool is_joint = false;
2121
2122                 // if ob is NULL, it should be a JOINT
2123                 if (!ob) {
2124                         ob = armature_importer->get_armature_for_joint(animated.node);
2125
2126                         if (!ob) {
2127                                 fprintf(stderr, "Cannot find armature for node %s\n", get_joint_name(animated.node));
2128                                 return true;
2129                         }
2130
2131                         armature_importer->get_rna_path_for_joint(animated.node, joint_path, sizeof(joint_path));
2132
2133                         is_joint = true;
2134                 }
2135                 
2136                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
2137
2138                 switch (animated.tm->getTransformationType()) {
2139                 case COLLADAFW::Transformation::TRANSLATE:
2140                 case COLLADAFW::Transformation::SCALE:
2141                         {
2142                                 bool loc = animated.tm->getTransformationType() == COLLADAFW::Transformation::TRANSLATE;
2143                                 if (is_joint)
2144                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
2145                                 else
2146                                         BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
2147
2148                                 for (int i = 0; i < bindings.getCount(); i++) {
2149                                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
2150                                         COLLADAFW::UniqueId anim_uid = binding.animation;
2151
2152                                         if (curve_map.find(anim_uid) == curve_map.end()) {
2153                                                 fprintf(stderr, "Cannot find FCurve by animation UID.\n");
2154                                                 continue;
2155                                         }
2156
2157                                         std::vector<FCurve*>& fcurves = curve_map[anim_uid];
2158                                         
2159                                         switch (binding.animationClass) {
2160                                         case COLLADAFW::AnimationList::POSITION_X:
2161                                                 add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
2162                                                 break;
2163                                         case COLLADAFW::AnimationList::POSITION_Y:
2164                                                 add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
2165                                                 break;
2166                                         case COLLADAFW::AnimationList::POSITION_Z:
2167                                                 add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
2168                                                 break;
2169                                         case COLLADAFW::AnimationList::POSITION_XYZ:
2170                                                 add_fcurves_to_object(ob, fcurves, rna_path, -1, &animated);
2171                                                 break;
2172                                         default:
2173                                                 fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
2174                                                                 binding.animationClass, loc ? "TRANSLATE" : "SCALE");
2175                                         }
2176                                 }
2177                         }
2178                         break;
2179                 case COLLADAFW::Transformation::ROTATE:
2180                         {
2181                                 if (is_joint)
2182                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
2183                                 else
2184                                         BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
2185
2186                                 COLLADAFW::Rotate* rot = (COLLADAFW::Rotate*)animated.tm;
2187                                 COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
2188                                 
2189                                 for (int i = 0; i < bindings.getCount(); i++) {
2190                                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
2191                                         COLLADAFW::UniqueId anim_uid = binding.animation;
2192
2193                                         if (curve_map.find(anim_uid) == curve_map.end()) {
2194                                                 fprintf(stderr, "Cannot find FCurve by animation UID.\n");
2195                                                 continue;
2196                                         }
2197
2198                                         std::vector<FCurve*>& fcurves = curve_map[anim_uid];
2199
2200                                         switch (binding.animationClass) {
2201                                         case COLLADAFW::AnimationList::ANGLE:
2202                                                 if (COLLADABU::Math::Vector3::UNIT_X == axis) {
2203                                                         add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
2204                                                 }
2205                                                 else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
2206                                                         add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
2207                                                 }
2208                                                 else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
2209                                                         add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
2210                                                 }
2211                                                 break;
2212                                         case COLLADAFW::AnimationList::AXISANGLE:
2213                                                 // TODO convert axis-angle to quat? or XYZ?
2214                                         default:
2215                                                 fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
2216                                                                 binding.animationClass);
2217                                         }
2218                                 }
2219                         }
2220                         break;
2221                 case COLLADAFW::Transformation::MATRIX:
2222                 case COLLADAFW::Transformation::SKEW:
2223                 case COLLADAFW::Transformation::LOOKAT:
2224                         fprintf(stderr, "Animation of MATRIX, SKEW and LOOKAT transformations is not supported yet.\n");
2225                         break;
2226                 }
2227 #endif
2228                 
2229                 return true;
2230         }
2231
2232         void read_node_transform(COLLADAFW::Node *node, Object *ob)
2233         {
2234                 float mat[4][4];
2235                 TransformReader::get_node_mat(mat, node, &uid_animated_map, ob);
2236                 if (ob)
2237                         TransformReader::decompose(mat, ob->loc, ob->rot, NULL, ob->size);
2238         }
2239         
2240 #if 0
2241         virtual void change_eul_to_quat(Object *ob, bAction *act)
2242         {
2243                 bActionGroup *grp;
2244                 int i;
2245                 
2246                 for (grp = (bActionGroup*)act->groups.first; grp; grp = grp->next) {
2247
2248                         FCurve *eulcu[3] = {NULL, NULL, NULL};
2249                         
2250                         if (fcurves_actionGroup_map.find(grp) == fcurves_actionGroup_map.end())
2251                                 continue;
2252
2253                         std::vector<FCurve*> &rot_fcurves = fcurves_actionGroup_map[grp];
2254                         
2255                         if (rot_fcurves.size() > 3) continue;
2256
2257                         for (i = 0; i < rot_fcurves.size(); i++)
2258                                 eulcu[rot_fcurves[i]->array_index] = rot_fcurves[i];
2259
2260                         char joint_path[100];
2261                         char rna_path[100];
2262
2263                         BLI_snprintf(joint_path, sizeof(joint_path), "pose.bones[\"%s\"]", grp->name);
2264                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_quaternion", joint_path);
2265
2266                         FCurve *quatcu[4] = {
2267                                 create_fcurve(0, rna_path),
2268                                 create_fcurve(1, rna_path),
2269                                 create_fcurve(2, rna_path),
2270                                 create_fcurve(3, rna_path)
2271                         };
2272
2273                         bPoseChannel *chan = get_pose_channel(ob->pose, grp->name);
2274
2275                         float m4[4][4], irest[3][3];
2276                         invert_m4_m4(m4, chan->bone->arm_mat);
2277                         copy_m3_m4(irest, m4);
2278
2279                         for (i = 0; i < 3; i++) {
2280
2281                                 FCurve *cu = eulcu[i];
2282
2283                                 if (!cu) continue;
2284
2285                                 for (int j = 0; j < cu->totvert; j++) {
2286                                         float frame = cu->bezt[j].vec[1][0];
2287
2288                                         float eul[3] = {
2289                                                 eulcu[0] ? evaluate_fcurve(eulcu[0], frame) : 0.0f,
2290                                                 eulcu[1] ? evaluate_fcurve(eulcu[1], frame) : 0.0f,
2291                                                 eulcu[2] ? evaluate_fcurve(eulcu[2], frame) : 0.0f
2292                                         };
2293
2294                                         // make eul relative to bone rest pose
2295                                         float rot[3][3], rel[3][3], quat[4];
2296
2297                                         /*eul_to_mat3(rot, eul);
2298
2299                                         mul_m3_m3m3(rel, irest, rot);
2300
2301                                         mat3_to_quat(quat, rel);
2302                                         */
2303
2304                                         eul_to_quat(quat, eul);
2305
2306                                         for (int k = 0; k < 4; k++)
2307                                                 create_bezt(quatcu[k], frame, quat[k]);
2308                                 }
2309                         }
2310
2311                         // now replace old Euler curves
2312
2313                         for (i = 0; i < 3; i++) {
2314                                 if (!eulcu[i]) continue;
2315
2316                                 action_groups_remove_channel(act, eulcu[i]);
2317                                 free_fcurve(eulcu[i]);
2318                         }
2319
2320                         chan->rotmode = ROT_MODE_QUAT;
2321
2322                         for (i = 0; i < 4; i++)
2323                                 action_groups_add_channel(act, grp, quatcu[i]);
2324                 }
2325
2326                 bPoseChannel *pchan;
2327                 for (pchan = (bPoseChannel*)ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2328                         pchan->rotmode = ROT_MODE_QUAT;
2329                 }
2330         }
2331 #endif
2332
2333         // prerequisites:
2334         // animlist_map - map animlist id -> animlist
2335         // curve_map - map anim id -> curve(s)
2336 #ifdef ARMATURE_TEST
2337         Object *translate_animation(COLLADAFW::Node *node,
2338                                                                 std::map<COLLADAFW::UniqueId, Object*>& object_map,
2339                                                                 std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
2340                                                                 COLLADAFW::Transformation::TransformationType tm_type,
2341                                                                 Object *par_job = NULL)
2342 #else
2343         void translate_animation(COLLADAFW::Node *node,
2344                                                          std::map<COLLADAFW::UniqueId, Object*>& object_map,
2345                                                          std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
2346                                                          COLLADAFW::Transformation::TransformationType tm_type)
2347 #endif
2348         {
2349                 bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
2350                 bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
2351                 COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
2352                 Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
2353                 const char *bone_name = is_joint ? get_joint_name(node) : NULL;
2354
2355                 if (!ob) {
2356                         fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
2357 #ifdef ARMATURE_TEST
2358                         return NULL;
2359 #else
2360                         return;
2361 #endif
2362                 }
2363
2364                 // frames at which to sample
2365                 std::vector<float> frames;
2366
2367                 // for each <rotate>, <translate>, etc. there is a separate Transformation
2368                 const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
2369
2370                 std::vector<FCurve*> old_curves;
2371
2372                 int i;
2373
2374                 // find frames at which to sample plus convert all keys to radians
2375                 for (i = 0; i < tms.getCount(); i++) {
2376                         COLLADAFW::Transformation *tm = tms[i];
2377                         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
2378
2379                         if (type == tm_type) {
2380                                 const COLLADAFW::UniqueId& listid = tm->getAnimationList();
2381
2382                                 if (animlist_map.find(listid) != animlist_map.end()) {
2383                                         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
2384                                         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
2385
2386                                         if (bindings.getCount()) {
2387                                                 for (int j = 0; j < bindings.getCount(); j++) {
2388                                                         std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
2389                                                         bool xyz = ((type == COLLADAFW::Transformation::TRANSLATE || type == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
2390
2391                                                         if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3)) {
2392                                                                 std::vector<FCurve*>::iterator iter;
2393
2394                                                                 for (iter = curves.begin(); iter != curves.end(); iter++) {
2395                                                                         FCurve *fcu = *iter;
2396
2397                                                                         if (is_rotation)
2398                                                                                 fcurve_deg_to_rad(fcu);
2399
2400                                                                         for (int k = 0; k < fcu->totvert; k++) {
2401                                                                                 float fra = fcu->bezt[k].vec[1][0];
2402                                                                                 if (std::find(frames.begin(), frames.end(), fra) == frames.end())
2403                                                                                         frames.push_back(fra);
2404                                                                         }
2405                                                                 }
2406                                                         }
2407                                                         else {
2408                                                                 fprintf(stderr, "expected 1 or 3 curves, got %u\n", curves.size());
2409                                                         }
2410
2411                                                         for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++)
2412                                                                 old_curves.push_back(*it);
2413                                                 }
2414                                         }
2415                                 }
2416                         }
2417                 }
2418
2419                 sort(frames.begin(), frames.end());
2420
2421                 float irest_dae[4][4];
2422                 float rest[4][4], irest[4][4];
2423
2424                 if (is_joint) {
2425                         if (is_joint)
2426                                 get_joint_rest_mat(irest_dae, root, node);
2427                         else
2428                                 evaluate_transform_at_frame(irest_dae, node, 0.0f);
2429                         invert_m4(irest_dae);
2430
2431                         Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
2432                         if (!bone) {
2433                                 fprintf(stderr, "cannot find bone \"%s\"", bone_name);
2434 #ifdef ARMATURE_TEST
2435                                 return NULL;
2436 #else
2437                                 return;
2438 #endif
2439                         }
2440
2441                         unit_m4(rest);
2442                         copy_m4_m4(rest, bone->arm_mat);
2443                         invert_m4_m4(irest, rest);
2444                 }
2445
2446                 char rna_path[200];
2447
2448 #ifdef ARMATURE_TEST
2449                 Object *job = get_joint_object(root, node, par_job);
2450                 FCurve *job_curves[4];
2451 #endif
2452
2453                 if (frames.size() == 0) {
2454 #ifdef ARMATURE_TEST
2455                         return job;
2456 #else
2457                         return;
2458 #endif
2459                 }
2460
2461                 const char *tm_str = NULL;
2462                 switch (tm_type) {
2463                 case COLLADAFW::Transformation::ROTATE:
2464                         tm_str = "rotation_quaternion";
2465                         break;
2466                 case COLLADAFW::Transformation::SCALE:
2467                         tm_str = "scale";
2468                         break;
2469                 case COLLADAFW::Transformation::TRANSLATE:
2470                         tm_str = "location";
2471                         break;
2472                 default:
2473 #ifdef ARMATURE_TEST
2474                         return job;
2475 #else
2476                         return;
2477 #endif
2478                 }
2479
2480                 if (is_joint) {
2481                         char joint_path[200];
2482                         armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
2483                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
2484                 }
2485                 else {
2486                         strcpy(rna_path, tm_str);
2487                 }
2488
2489                 // new curves
2490                 FCurve *newcu[4];
2491                 int totcu = is_rotation ? 4 : 3;
2492
2493                 for (i = 0; i < totcu; i++) {
2494                         newcu[i] = create_fcurve(i, rna_path);
2495 #ifdef ARMATURE_TEST
2496                         job_curves[i] = create_fcurve(i, tm_str);
2497 #endif
2498                 }
2499
2500                 std::vector<float>::iterator it;
2501
2502                 // sample values at each frame
2503                 for (it = frames.begin(); it != frames.end(); it++) {
2504                         float fra = *it;
2505
2506                         float mat[4][4];
2507
2508                         unit_m4(mat);
2509
2510                         // calc object-space mat
2511                         evaluate_transform_at_frame(mat, node, fra);
2512
2513                         // for joints, we need a special matrix
2514                         if (is_joint) {
2515                                 // special matrix: iR * M * iR_dae * R
2516                                 // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
2517                                 // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
2518                                 float temp[4][4], par[4][4];
2519
2520                                 // calc M
2521                                 calc_joint_parent_mat_rest(par, NULL, root, node);
2522                                 mul_m4_m4m4(temp, mat, par);
2523
2524                                 // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
2525
2526                                 // calc special matrix
2527                                 mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
2528                         }
2529
2530                         float val[4];
2531
2532                         switch (tm_type) {
2533                         case COLLADAFW::Transformation::ROTATE:
2534                                 mat4_to_quat(val, mat);
2535                                 break;
2536                         case COLLADAFW::Transformation::SCALE:
2537                                 mat4_to_size(val, mat);
2538                                 break;
2539                         case COLLADAFW::Transformation::TRANSLATE:
2540                                 copy_v3_v3(val, mat[3]);
2541                                 break;
2542                         default:
2543                                 break;
2544                         }
2545
2546                         // add 4 or 3 keys
2547                         for (i = 0; i < totcu; i++) {
2548                                 add_bezt(newcu[i], fra, val[i]);
2549                         }
2550
2551 #ifdef ARMATURE_TEST
2552                         if (is_joint) {
2553                                 evaluate_transform_at_frame(mat, node, fra);
2554
2555                                 switch (tm_type) {
2556                                 case COLLADAFW::Transformation::ROTATE:
2557                                         mat4_to_quat(val, mat);
2558                                         break;
2559                                 case COLLADAFW::Transformation::SCALE:
2560                                         mat4_to_size(val, mat);
2561                                         break;
2562                                 case COLLADAFW::Transformation::TRANSLATE:
2563                                         copy_v3_v3(val, mat[3]);
2564                                         break;
2565                                 default:
2566                                         break;
2567                                 }
2568
2569                                 for (i = 0; i < totcu; i++)
2570                                         add_bezt(job_curves[i], fra, val[i]);
2571                         }
2572 #endif
2573                 }
2574
2575                 verify_adt_action((ID*)&ob->id, 1);
2576
2577                 ListBase *curves = &ob->adt->action->curves;
2578                 // no longer needed
2579 #if 0
2580                 // remove old curves
2581                 for (std::vector<FCurve*>::iterator it = old_curves.begin(); it != old_curves.end(); it++) {
2582                         if (is_joint)
2583                                 action_groups_remove_channel(ob->adt->action, *it);
2584                         else
2585                                 BLI_remlink(curves, *it);
2586
2587                         // std::remove(unused_curves.begin(), unused_curves.end(), *it);
2588                         // free_fcurve(*it);
2589                 }
2590 #endif
2591
2592                 // add curves
2593                 for (i = 0; i < totcu; i++) {
2594                         if (is_joint)
2595                                 add_bone_fcurve(ob, node, newcu[i]);
2596                         else
2597                                 BLI_addtail(curves, newcu[i]);
2598
2599 #ifdef ARMATURE_TEST
2600                         if (is_joint)
2601                                 BLI_addtail(&job->adt->action->curves, job_curves[i]);
2602 #endif
2603                 }
2604
2605                 if (is_rotation) {
2606                         if (is_joint) {
2607                                 bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
2608                                 chan->rotmode = ROT_MODE_QUAT;
2609                         }
2610                         else {
2611                                 ob->rotmode = ROT_MODE_QUAT;
2612                         }
2613                 }
2614
2615 #ifdef ARMATURE_TEST
2616                 return job;
2617 #endif
2618         }
2619
2620         // internal, better make it private
2621         // warning: evaluates only rotation
2622         // prerequisites: animlist_map, curve_map
2623         void evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
2624         {
2625                 const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
2626
2627                 unit_m4(mat);
2628
2629                 for (int i = 0; i < tms.getCount(); i++) {
2630                         COLLADAFW::Transformation *tm = tms[i];
2631                         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
2632                         float m[4][4];
2633
2634                         unit_m4(m);
2635
2636                         if (!evaluate_animation(tm, m, fra)) {
2637                                 switch (type) {
2638                                 case COLLADAFW::Transformation::ROTATE:
2639                                         dae_rotate_to_mat4(tm, m);
2640                                         break;
2641                                 case COLLADAFW::Transformation::TRANSLATE:
2642                                         dae_translate_to_mat4(tm, m);
2643                                         break;
2644                                 case COLLADAFW::Transformation::SCALE:
2645                                         dae_scale_to_mat4(tm, m);
2646                                         break;
2647                                 case COLLADAFW::Transformation::MATRIX:
2648                                         dae_matrix_to_mat4(tm, m);
2649                                         break;
2650                                 default:
2651                                         fprintf(stderr, "unsupported transformation type %d\n", type);
2652                                 }
2653                         }
2654
2655                         float temp[4][4];
2656                         copy_m4_m4(temp, mat);
2657
2658                         mul_m4_m4m4(mat, m, temp);
2659                 }
2660         }
2661
2662         bool evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra)
2663         {
2664                 const COLLADAFW::UniqueId& listid = tm->getAnimationList();
2665
2666                 if (animlist_map.find(listid) != animlist_map.end()) {
2667                         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
2668                         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
2669
2670                         if (bindings.getCount()) {
2671                                 for (int j = 0; j < bindings.getCount(); j++) {
2672                                         std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
2673                                         COLLADAFW::AnimationList::AnimationClass animclass = bindings[j].animationClass;
2674                                         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
2675                                         bool xyz = ((type == COLLADAFW::Transformation::TRANSLATE || type == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
2676
2677                                         if (type == COLLADAFW::Transformation::ROTATE) {
2678                                                 if (curves.size() != 1) {
2679                                                         fprintf(stderr, "expected 1 curve, got %u\n", curves.size());
2680                                                 }
2681                                                 else {
2682                                                         if (animclass == COLLADAFW::AnimationList::ANGLE) {
2683                                                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
2684                                                                 float ax[3] = {axis[0], axis[1], axis[2]};
2685                                                                 float angle = evaluate_fcurve(curves[0], fra);
2686                                                                 axis_angle_to_mat4(mat, ax, angle);
2687
2688                                                                 return true;
2689                                                         }
2690                                                         else {
2691                                                                 // TODO support other animclasses
2692                                                                 fprintf(stderr, "<rotate> animclass %d is not supported yet\n", bindings[j].animationClass);
2693                                                         }
2694                                                 }
2695                                         }
2696                                         else if (type == COLLADAFW::Transformation::SCALE || type == COLLADAFW::Transformation::TRANSLATE) {
2697                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3)) {
2698                                                         bool animated = true;
2699                                                         bool scale = (type == COLLADAFW::Transformation::SCALE);
2700
2701                                                         float vec[3] = {0.0f, 0.0f, 0.0f};
2702                                                         if (scale)
2703                                                                 vec[0] = vec[1] = vec[2] = 1.0f;
2704
2705                                                         switch (animclass) {
2706                                                         case COLLADAFW::AnimationList::POSITION_X:
2707                                                                 vec[0] = evaluate_fcurve(curves[0], fra);
2708                                                                 break;
2709                                                         case COLLADAFW::AnimationList::POSITION_Y:
2710                                                                 vec[1] = evaluate_fcurve(curves[0], fra);
2711                                                                 break;
2712                                                         case COLLADAFW::AnimationList::POSITION_Z:
2713                                                                 vec[2] = evaluate_fcurve(curves[0], fra);
2714                                                                 break;
2715                                                         case COLLADAFW::AnimationList::POSITION_XYZ:
2716                                                                 vec[0] = evaluate_fcurve(curves[0], fra);
2717                                                                 vec[1] = evaluate_fcurve(curves[1], fra);
2718                                                                 vec[2] = evaluate_fcurve(curves[2], fra);
2719                                                                 break;
2720                                                         default:
2721                                                                 fprintf(stderr, "<%s> animclass %d is not supported yet\n", scale ? "scale" : "translate", animclass);
2722                                                                 animated = false;
2723                                                                 break;
2724                                                         }
2725
2726                                                         if (animated) {
2727                                                                 if (scale)
2728                                                                         size_to_mat4(mat, vec);
2729                                                                 else
2730                                                                         copy_v3_v3(mat[3], vec);
2731