temporary fix for quat rotations
[blender.git] / source / blender / collada / AnimationImporter.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Nathan Letwory.
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/collada/AnimationImporter.cpp
26  *  \ingroup collada
27  */
28
29 #include <stddef.h>
30
31 /* COLLADABU_ASSERT, may be able to remove later */
32 #include "COLLADABUPlatform.h"
33
34 #include "DNA_armature_types.h"
35
36 #include "ED_keyframing.h"
37
38 #include "BLI_listbase.h"
39 #include "BLI_math.h"
40 #include "BLI_path_util.h"
41 #include "BLI_string.h"
42
43 #include "BKE_action.h"
44 #include "BKE_armature.h"
45 #include "BKE_fcurve.h"
46 #include "BKE_object.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "collada_utils.h"
51 #include "AnimationImporter.h"
52 #include "ArmatureImporter.h"
53 #include "MaterialExporter.h"
54
55 #include <algorithm>
56
57 // first try node name, if not available (since is optional), fall back to original id
58 template<class T>
59 static const char *bc_get_joint_name(T *node)
60 {
61         const std::string& id = node->getName();
62         return id.size() ? id.c_str() : node->getOriginalId().c_str();
63 }
64
65 FCurve *AnimationImporter::create_fcurve(int array_index, const char *rna_path)
66 {
67         FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
68         
69         fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
70         fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
71         fcu->array_index = array_index;
72         return fcu;
73 }
74         
75 void AnimationImporter::create_bezt(FCurve *fcu, float frame, float output)
76 {
77         BezTriple bez;
78         memset(&bez, 0, sizeof(BezTriple));
79         bez.vec[1][0] = frame;
80         bez.vec[1][1] = output;
81         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
82         bez.f1 = bez.f2 = bez.f3 = SELECT;
83         bez.h1 = bez.h2 = HD_AUTO;
84         insert_bezt_fcurve(fcu, &bez, 0);
85         calchandles_fcurve(fcu);
86 }
87
88 // create one or several fcurves depending on the number of parameters being animated
89 void AnimationImporter::animation_to_fcurves(COLLADAFW::AnimationCurve *curve)
90 {
91         COLLADAFW::FloatOrDoubleArray& input = curve->getInputValues();
92         COLLADAFW::FloatOrDoubleArray& output = curve->getOutputValues();
93     
94         if( curve->getInterpolationType() == COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER ) {
95         COLLADAFW::FloatOrDoubleArray& intan = curve->getInTangentValues();
96     COLLADAFW::FloatOrDoubleArray& outtan = curve->getOutTangentValues();
97         }
98
99         float fps = (float)FPS;
100         size_t dim = curve->getOutDimension();
101         unsigned int i;
102         
103         std::vector<FCurve*>& fcurves = curve_map[curve->getUniqueId()];
104
105         switch (dim) {
106         case 1: // X, Y, Z or angle
107         case 3: // XYZ
108         case 4:
109         case 16: // matrix
110                 {
111                         for (i = 0; i < dim; i++ ) {
112                                 FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
113                         
114                                 fcu->flag = (FCURVE_VISIBLE|FCURVE_AUTO_HANDLES|FCURVE_SELECTED);
115                                 // fcu->rna_path = BLI_strdupn(path, strlen(path));
116                                 fcu->array_index = 0;
117                                 fcu->totvert = curve->getKeyCount();
118                         
119                                 // create beztriple for each key
120                                 for (unsigned int j = 0; j < curve->getKeyCount(); j++) {
121                                         BezTriple bez;
122                                         memset(&bez, 0, sizeof(BezTriple));
123
124                                         
125                                         // input, output
126                                         bez.vec[1][0] = bc_get_float_value(input, j) * fps; 
127                                         bez.vec[1][1] = bc_get_float_value(output, j * dim + i);
128
129
130                                         if( curve->getInterpolationType() == COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER ) 
131                                         {
132                                                 COLLADAFW::FloatOrDoubleArray& intan = curve->getInTangentValues();
133                         COLLADAFW::FloatOrDoubleArray& outtan = curve->getOutTangentValues();
134
135                                                 // intangent
136                                                  bez.vec[0][0] = bc_get_float_value(intan, (j * 2 * dim ) + (2 * i)) * fps;
137                                                  bez.vec[0][1] = bc_get_float_value(intan, (j * 2 * dim )+ (2 * i) + 1);
138
139                                                  // outtangent
140                                                  bez.vec[2][0] = bc_get_float_value(outtan, (j * 2 * dim ) + (2 * i)) * fps;
141                                                  bez.vec[2][1] = bc_get_float_value(outtan, (j * 2 * dim )+ (2 * i) + 1);
142                                              bez.ipo = BEZT_IPO_BEZ;
143                                                  //bez.h1 = bez.h2 = HD_AUTO;   
144                                         }
145                                         else 
146                                         {
147                                                 bez.h1 = bez.h2 = HD_AUTO; 
148                                                 bez.ipo = BEZT_IPO_LIN;
149                                         }
150                                         // bez.ipo = U.ipo_new; /* use default interpolation mode here... */
151                                         bez.f1 = bez.f2 = bez.f3 = SELECT;
152                                         
153                                         insert_bezt_fcurve(fcu, &bez, 0);
154                                 }
155
156                                 calchandles_fcurve(fcu);
157
158                                 fcurves.push_back(fcu);
159                         }
160                 }
161                 break;
162         default:
163                 fprintf(stderr, "Output dimension of %d is not yet supported (animation id = %s)\n", (int)dim, curve->getOriginalId().c_str());
164         }
165
166         for (std::vector<FCurve*>::iterator it = fcurves.begin(); it != fcurves.end(); it++)
167                 unused_curves.push_back(*it);
168 }
169
170
171 void AnimationImporter::fcurve_deg_to_rad(FCurve *cu)
172 {
173         for (unsigned int i = 0; i < cu->totvert; i++) {
174                 // TODO convert handles too
175                 cu->bezt[i].vec[1][1] *= M_PI / 180.0f;
176                 cu->bezt[i].vec[0][1] *= M_PI / 180.0f;
177                 cu->bezt[i].vec[2][1] *= M_PI / 180.0f;
178                 cu->bezt[i].vec[1][0];
179         }
180 }
181
182 void AnimationImporter::add_fcurves_to_object(Object *ob, std::vector<FCurve*>& curves, char *rna_path, int array_index, Animation *animated)
183 {
184         bAction *act;
185         
186         if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
187         else act = ob->adt->action;
188         
189         std::vector<FCurve*>::iterator it;
190         int i;
191
192 #if 0
193         char *p = strstr(rna_path, "rotation_euler");
194         bool is_rotation = p && *(p + strlen("rotation_euler")) == '\0';
195
196         // convert degrees to radians for rotation
197         if (is_rotation)
198                 fcurve_deg_to_rad(fcu);
199 #endif
200         
201         for (it = curves.begin(), i = 0; it != curves.end(); it++, i++) {
202                 FCurve *fcu = *it;
203                 fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
204                 
205                 if (array_index == -1) fcu->array_index = i;
206                 else fcu->array_index = array_index;
207         
208                 if (ob->type == OB_ARMATURE) {
209                         bActionGroup *grp = NULL;
210                         const char *bone_name = bc_get_joint_name(animated->node);
211                         
212                         if (bone_name) {
213                                 /* try to find group */
214                                 grp = action_groups_find_named(act, bone_name);
215                                 
216                                 /* no matching groups, so add one */
217                                 if (grp == NULL) {
218                                         /* Add a new group, and make it active */
219                                         grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
220                                         
221                                         grp->flag = AGRP_SELECTED;
222                                         BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
223                                         
224                                         BLI_addtail(&act->groups, grp);
225                                         BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
226                                 }
227                                 
228                                 /* add F-Curve to group */
229                                 action_groups_add_channel(act, grp, fcu);
230                                 
231                         }
232 #if 0
233                         if (is_rotation) {
234                                 fcurves_actionGroup_map[grp].push_back(fcu);
235                         }
236 #endif
237                 }
238                 else {
239                         BLI_addtail(&act->curves, fcu);
240                 }
241
242                 // curve is used, so remove it from unused_curves
243                 unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
244         }
245 }
246
247 AnimationImporter::AnimationImporter(UnitConverter *conv, ArmatureImporter *arm, Scene *scene) :
248                 TransformReader(conv), armature_importer(arm), scene(scene) { }
249
250 AnimationImporter::~AnimationImporter()
251 {
252         // free unused FCurves
253         for (std::vector<FCurve*>::iterator it = unused_curves.begin(); it != unused_curves.end(); it++)
254                 free_fcurve(*it);
255
256         if (unused_curves.size())
257                 fprintf(stderr, "removed %d unused curves\n", (int)unused_curves.size());
258 }
259
260 bool AnimationImporter::write_animation(const COLLADAFW::Animation* anim) 
261 {
262         if (anim->getAnimationType() == COLLADAFW::Animation::ANIMATION_CURVE) {
263                 COLLADAFW::AnimationCurve *curve = (COLLADAFW::AnimationCurve*)anim;
264                 
265                 // XXX Don't know if it's necessary
266                 // Should we check outPhysicalDimension?
267                 if (curve->getInPhysicalDimension() != COLLADAFW::PHYSICAL_DIMENSION_TIME) {
268                         fprintf(stderr, "Inputs physical dimension is not time. \n");
269                         return true;
270                 }
271
272                 // a curve can have mixed interpolation type,
273                 // in this case curve->getInterpolationTypes returns a list of interpolation types per key
274                 COLLADAFW::AnimationCurve::InterpolationType interp = curve->getInterpolationType();
275
276                 if (interp != COLLADAFW::AnimationCurve::INTERPOLATION_MIXED) {
277                         switch (interp) {
278                         case COLLADAFW::AnimationCurve::INTERPOLATION_LINEAR:
279                         case COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER:
280                                 animation_to_fcurves(curve);
281                                 break;
282                         default:
283                                 // TODO there're also CARDINAL, HERMITE, BSPLINE and STEP types
284                                 fprintf(stderr, "CARDINAL, HERMITE, BSPLINE and STEP anim interpolation types not supported yet.\n");
285                                 break;
286                         }
287                 }
288                 else {
289                         // not supported yet
290                         fprintf(stderr, "MIXED anim interpolation type is not supported yet.\n");
291                 }
292         }
293         else {
294                 fprintf(stderr, "FORMULA animation type is not supported yet.\n");
295         }
296         
297         return true;
298 }
299         
300 // called on post-process stage after writeVisualScenes
301 bool AnimationImporter::write_animation_list(const COLLADAFW::AnimationList* animlist) 
302 {
303         const COLLADAFW::UniqueId& animlist_id = animlist->getUniqueId();
304     
305         animlist_map[animlist_id] = animlist;
306     
307 #if 0
308
309         // should not happen
310         if (uid_animated_map.find(animlist_id) == uid_animated_map.end()) {
311                 return true;
312         }
313
314         // for bones rna_path is like: pose.bones["bone-name"].rotation
315         
316         // what does this AnimationList animate?
317         Animation& animated = uid_animated_map[animlist_id];
318         Object *ob = animated.ob;
319     
320         char rna_path[100];
321         char joint_path[100];
322         bool is_joint = false;
323
324         // if ob is NULL, it should be a JOINT
325         if (!ob) {
326                 
327                 ob = armature_importer->get_armature_for_joint(animated.node);
328
329                 if (!ob) {
330 //                      fprintf(stderr, "Cannot find armature for node %s\n", get_joint_name(animated.node));
331                         return true;
332                 }
333
334                 armature_importer->get_rna_path_for_joint(animated.node, joint_path, sizeof(joint_path));
335
336                 is_joint = true;
337         }
338         printf("object for animlist: %s found\n", animlist->getUniqueId().toAscii().c_str());
339         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
340
341         switch (animated.tm->getTransformationType()) {
342         case COLLADAFW::Transformation::TRANSLATE:
343         case COLLADAFW::Transformation::SCALE:
344                 {
345                         bool loc = animated.tm->getTransformationType() == COLLADAFW::Transformation::TRANSLATE;
346                         if (is_joint)
347                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
348                         else
349                                 BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
350
351                         for (int i = 0; i < bindings.getCount(); i++) {
352                                 const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
353                                 COLLADAFW::UniqueId anim_uid = binding.animation;
354
355                                 if (curve_map.find(anim_uid) == curve_map.end()) {
356                                         fprintf(stderr, "Cannot find FCurve by animation UID.\n");
357                                         continue;
358                                 }
359
360                                 std::vector<FCurve*>& fcurves = curve_map[anim_uid];
361                                 
362                                 switch (binding.animationClass) {
363                                 case COLLADAFW::AnimationList::POSITION_X:
364                                         add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
365                                         break;
366                                 case COLLADAFW::AnimationList::POSITION_Y:
367                                         add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
368                                         break;
369                                 case COLLADAFW::AnimationList::POSITION_Z:
370                                         add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
371                                         break;
372                                 case COLLADAFW::AnimationList::POSITION_XYZ:
373                                         add_fcurves_to_object(ob, fcurves, rna_path, -1, &animated);
374                                         break;
375                                 default:
376                                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
377                                                         binding.animationClass, loc ? "TRANSLATE" : "SCALE");
378                                 }
379                         }
380                 }
381                 break;
382         case COLLADAFW::Transformation::ROTATE:
383                 {
384                         if (is_joint)
385                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
386                         else
387                                 BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
388
389                         COLLADAFW::Rotate* rot = (COLLADAFW::Rotate*)animated.tm;
390                         COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
391                         
392                         for (int i = 0; i < bindings.getCount(); i++) {
393                                 const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
394                                 COLLADAFW::UniqueId anim_uid = binding.animation;
395
396                                 if (curve_map.find(anim_uid) == curve_map.end()) {
397                                         fprintf(stderr, "Cannot find FCurve by animation UID.\n");
398                                         continue;
399                                 }
400
401                                 std::vector<FCurve*>& fcurves = curve_map[anim_uid];
402
403                                 switch (binding.animationClass) {
404                                 case COLLADAFW::AnimationList::ANGLE:
405                                         if (COLLADABU::Math::Vector3::UNIT_X == axis) {
406                                                 add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
407                                         }
408                                         else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
409                                                 add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
410                                         }
411                                         else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
412                                                 add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
413                                         }
414                                         break;
415                                 case COLLADAFW::AnimationList::AXISANGLE:
416                                         // TODO convert axis-angle to quat? or XYZ?
417                                 default:
418                                         fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
419                                                         binding.animationClass);
420                                 }
421                         }
422                 }
423                 break;
424         case COLLADAFW::Transformation::MATRIX:
425         case COLLADAFW::Transformation::SKEW:
426         case COLLADAFW::Transformation::LOOKAT:
427                 fprintf(stderr, "Animation of MATRIX, SKEW and LOOKAT transformations is not supported yet.\n");
428                 break;
429         }
430 #endif
431         
432         return true;
433 }
434
435 // \todo refactor read_node_transform to not automatically apply anything,
436 // but rather return the transform matrix, so caller can do with it what is
437 // necessary. Same for \ref get_node_mat
438 void AnimationImporter::read_node_transform(COLLADAFW::Node *node, Object *ob)
439 {
440         float mat[4][4];
441         TransformReader::get_node_mat(mat, node, &uid_animated_map, ob);
442         if (ob) {
443                 copy_m4_m4(ob->obmat, mat);
444                 object_apply_mat4(ob, ob->obmat, 0, 0);
445         }
446 }
447
448 #if 0
449 virtual void AnimationImporter::change_eul_to_quat(Object *ob, bAction *act)
450 {
451         bActionGroup *grp;
452         int i;
453         
454         for (grp = (bActionGroup*)act->groups.first; grp; grp = grp->next) {
455
456                 FCurve *eulcu[3] = {NULL, NULL, NULL};
457                 
458                 if (fcurves_actionGroup_map.find(grp) == fcurves_actionGroup_map.end())
459                         continue;
460
461                 std::vector<FCurve*> &rot_fcurves = fcurves_actionGroup_map[grp];
462                 
463                 if (rot_fcurves.size() > 3) continue;
464
465                 for (i = 0; i < rot_fcurves.size(); i++)
466                         eulcu[rot_fcurves[i]->array_index] = rot_fcurves[i];
467
468                 char joint_path[100];
469                 char rna_path[100];
470
471                 BLI_snprintf(joint_path, sizeof(joint_path), "pose.bones[\"%s\"]", grp->name);
472                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_quaternion", joint_path);
473
474                 FCurve *quatcu[4] = {
475                         create_fcurve(0, rna_path),
476                         create_fcurve(1, rna_path),
477                         create_fcurve(2, rna_path),
478                         create_fcurve(3, rna_path)
479                 };
480
481                 bPoseChannel *chan = get_pose_channel(ob->pose, grp->name);
482
483                 float m4[4][4], irest[3][3];
484                 invert_m4_m4(m4, chan->bone->arm_mat);
485                 copy_m3_m4(irest, m4);
486
487                 for (i = 0; i < 3; i++) {
488
489                         FCurve *cu = eulcu[i];
490
491                         if (!cu) continue;
492
493                         for (int j = 0; j < cu->totvert; j++) {
494                                 float frame = cu->bezt[j].vec[1][0];
495
496                                 float eul[3] = {
497                                         eulcu[0] ? evaluate_fcurve(eulcu[0], frame) : 0.0f,
498                                         eulcu[1] ? evaluate_fcurve(eulcu[1], frame) : 0.0f,
499                                         eulcu[2] ? evaluate_fcurve(eulcu[2], frame) : 0.0f
500                                 };
501
502                                 // make eul relative to bone rest pose
503                                 float rot[3][3], rel[3][3], quat[4];
504
505                                 /*eul_to_mat3(rot, eul);
506
507                                 mul_m3_m3m3(rel, irest, rot);
508
509                                 mat3_to_quat(quat, rel);
510                                 */
511
512                                 eul_to_quat(quat, eul);
513
514                                 for (int k = 0; k < 4; k++)
515                                         create_bezt(quatcu[k], frame, quat[k]);
516                         }
517                 }
518
519                 // now replace old Euler curves
520
521                 for (i = 0; i < 3; i++) {
522                         if (!eulcu[i]) continue;
523
524                         action_groups_remove_channel(act, eulcu[i]);
525                         free_fcurve(eulcu[i]);
526                 }
527
528                 chan->rotmode = ROT_MODE_QUAT;
529
530                 for (i = 0; i < 4; i++)
531                         action_groups_add_channel(act, grp, quatcu[i]);
532         }
533
534         bPoseChannel *pchan;
535         for (pchan = (bPoseChannel*)ob->pose->chanbase.first; pchan; pchan = pchan->next) {
536                 pchan->rotmode = ROT_MODE_QUAT;
537         }
538 }
539 #endif
540
541
542 //sets the rna_path and array index to curve
543 void AnimationImporter::modify_fcurve(std::vector<FCurve*>* curves , char* rna_path , int array_index )
544 {   
545         std::vector<FCurve*>::iterator it;
546         int i;
547         for (it = curves->begin(), i = 0; it != curves->end(); it++, i++) {
548                 FCurve *fcu = *it;
549                 fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
550                 
551                 if (array_index == -1) fcu->array_index = i;
552                 else fcu->array_index = array_index;
553
554                 unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
555         }
556 }
557
558 void AnimationImporter::find_frames( std::vector<float>* frames , std::vector<FCurve*>* curves)
559 {
560         std::vector<FCurve*>::iterator iter;
561                 for (iter = curves->begin(); iter != curves->end(); iter++) {
562                         FCurve *fcu = *iter;
563         
564                 for (unsigned int k = 0; k < fcu->totvert; k++) {
565                         //get frame value from bezTriple
566                         float fra = fcu->bezt[k].vec[1][0];
567                         //if frame already not added add frame to frames
568                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
569                                 frames->push_back(fra);
570                                                         
571                 }
572                 }
573 }
574
575 //creates the rna_paths and array indices of fcurves from animations using transformation and bound animation class of each animation.
576 void AnimationImporter:: Assign_transform_animations(COLLADAFW::Transformation * transform , 
577                                                                                                          const COLLADAFW::AnimationList::AnimationBinding * binding,
578                                                                                                          std::vector<FCurve*>* curves, bool is_joint, char * joint_path)
579 {
580         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
581         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
582         bool is_rotation = tm_type  == COLLADAFW::Transformation::ROTATE;
583         
584         //to check if the no of curves are valid
585         bool xyz = ((tm_type == COLLADAFW::Transformation::TRANSLATE ||tm_type  == COLLADAFW::Transformation::SCALE) && binding->animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
586                         
587         
588         if (!((!xyz && curves->size() == 1) || (xyz && curves->size() == 3) || is_matrix)) {
589                 fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves->size());
590                 return;
591         }
592         
593         char rna_path[100];
594                                                         
595         switch (tm_type) {
596                 case COLLADAFW::Transformation::TRANSLATE:
597                 case COLLADAFW::Transformation::SCALE:
598                         {
599                                 bool loc = tm_type == COLLADAFW::Transformation::TRANSLATE;
600                                 if (is_joint)
601                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
602                                 else
603                                         BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
604
605                                 switch (binding->animationClass) {
606                                         case COLLADAFW::AnimationList::POSITION_X:
607                                                 modify_fcurve(curves, rna_path, 0 );
608                                                 break;
609                                         case COLLADAFW::AnimationList::POSITION_Y:
610                                                 modify_fcurve(curves, rna_path, 1 );
611                                                 break;
612                                         case COLLADAFW::AnimationList::POSITION_Z:
613                                                 modify_fcurve(curves, rna_path, 2 );
614                                                 break;
615                                         case COLLADAFW::AnimationList::POSITION_XYZ:
616                                                 modify_fcurve(curves, rna_path, -1 );
617                                                 break;
618                                         default:
619                                                 fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
620                                                                 binding->animationClass, loc ? "TRANSLATE" : "SCALE");
621                                         }
622                 break;
623                         }
624                 
625                 
626                 case COLLADAFW::Transformation::ROTATE:
627                         {
628                                 if (is_joint)
629                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
630                                 else
631                                         BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
632                 std::vector<FCurve*>::iterator iter;
633                                 for (iter = curves->begin(); iter != curves->end(); iter++) {
634                                         FCurve* fcu = *iter;
635                                         
636                                         //if transform is rotation the fcurves values must be turned in to radian.
637                                         if (is_rotation)
638                                                 fcurve_deg_to_rad(fcu);          
639                                 }                                       
640                                 COLLADAFW::Rotate* rot = (COLLADAFW::Rotate*)transform;
641                                 COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
642                         
643                                 switch (binding->animationClass) {
644                                         case COLLADAFW::AnimationList::ANGLE:
645                                                 if (COLLADABU::Math::Vector3::UNIT_X == axis) {
646                                                         modify_fcurve(curves, rna_path, 0 );
647                                                 }
648                                                 else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
649                                                         modify_fcurve(curves, rna_path, 1 );
650                                                 }
651                                                 else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
652                                                         modify_fcurve(curves, rna_path, 2 );
653                                                 }
654                                                 break;
655                                         case COLLADAFW::AnimationList::AXISANGLE:
656                                                 // TODO convert axis-angle to quat? or XYZ?
657                                         default:
658                                                 fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
659                                                                 binding->animationClass);
660                                         }
661                         break;
662                         }
663                         
664                 case COLLADAFW::Transformation::MATRIX:
665                         /*{
666                                 COLLADAFW::Matrix* mat = (COLLADAFW::Matrix*)transform;
667                                 COLLADABU::Math::Matrix4 mat4 = mat->getMatrix();
668                                 switch (binding->animationClass) {
669                                         case COLLADAFW::AnimationList::TRANSFORM:
670
671                                 }
672                         }*/
673                 case COLLADAFW::Transformation::SKEW:
674                 case COLLADAFW::Transformation::LOOKAT:
675                         fprintf(stderr, "Animation of MATRIX, SKEW and LOOKAT transformations is not supported yet.\n");
676                         break;
677                 }
678         
679 }
680
681 void AnimationImporter:: Assign_color_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves ,char * anim_type)
682 {
683         char rna_path[100];
684         BLI_strncpy(rna_path,anim_type, sizeof(rna_path));
685     
686         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
687         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
688                                 //all the curves belonging to the current binding
689         std::vector<FCurve*> animcurves;    
690         for (unsigned int j = 0; j < bindings.getCount(); j++) {
691                  animcurves = curve_map[bindings[j].animation];
692                 //calculate rnapaths and array index of fcurves according to transformation and animation class
693                  //Assign_color_animations( &bindings[j], &animcurves); 
694                 
695             switch (bindings[j].animationClass) {
696                 case COLLADAFW::AnimationList::COLOR_R:
697                         modify_fcurve(&animcurves, rna_path, 0 );
698                         break;
699                 case COLLADAFW::AnimationList::COLOR_G:
700                         modify_fcurve(&animcurves, rna_path, 1 );
701                         break;
702                 case COLLADAFW::AnimationList::COLOR_B:
703                         modify_fcurve(&animcurves, rna_path, 2 );
704                         break;
705                 case COLLADAFW::AnimationList::COLOR_RGB:
706                 case COLLADAFW::AnimationList::COLOR_RGBA:
707                         modify_fcurve(&animcurves, rna_path, -1 );
708                         break;
709                         
710                 default:
711                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
712                                         bindings[j].animationClass, "COLOR" );
713                 }
714
715                  std::vector<FCurve*>::iterator iter;
716                 //Add the curves of the current animation to the object
717                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
718                         FCurve * fcu = *iter;
719                         BLI_addtail(AnimCurves, fcu);   
720                 }                               
721         }
722
723         
724 }
725
726 void AnimationImporter:: Assign_float_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves, char * anim_type)
727 {
728         char rna_path[100];
729         if (animlist_map.find(listid) == animlist_map.end()) return ;
730         else 
731         {
732                 //transformation has animations
733                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
734                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
735                 //all the curves belonging to the current binding
736                 std::vector<FCurve*> animcurves;    
737                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
738                          animcurves = curve_map[bindings[j].animation];
739                         //calculate rnapaths and array index of fcurves according to transformation and animation class
740                          BLI_strncpy(rna_path, anim_type , sizeof(rna_path));
741                          modify_fcurve(&animcurves, rna_path, 0 );
742                          std::vector<FCurve*>::iterator iter;
743                                 //Add the curves of the current animation to the object
744                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
745                                         FCurve * fcu = *iter;
746                                         BLI_addtail(AnimCurves, fcu);   
747                                 }                               
748                 }
749         }
750         
751 }
752
753 void AnimationImporter::translate_Animations_NEW ( COLLADAFW::Node * node , 
754                                                                                                    std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
755                                                                                                    std::map<COLLADAFW::UniqueId, Object*>& object_map,
756                                                                                                    std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map)
757 {
758         AnimationImporter::AnimMix* animType = get_animation_type(node, FW_object_map );
759
760         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
761         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
762         Object *ob = is_joint ? armature_importer->get_armature_for_joint(root) : object_map[node->getUniqueId()];
763         if (!ob)
764         {
765                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
766                 return;
767         }
768
769         bAction * act;
770         bActionGroup *grp = NULL;
771     
772         //if ( (animType & NODE_TRANSFORM) != 0 )
773         if ( (animType->transform) != 0 )
774         {
775         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
776         char joint_path[200];
777
778                 if ( is_joint ) 
779                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
780                 
781         
782                 if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
783                                         else act = ob->adt->action;
784                                         //Get the list of animation curves of the object
785             
786                 ListBase *AnimCurves = &(act->curves);
787
788                 const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
789         
790                 //for each transformation in node 
791                 for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
792                         COLLADAFW::Transformation *transform = nodeTransforms[i];
793                         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
794
795                         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
796                         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
797                                 
798                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
799                 
800                         //check if transformation has animations    
801                         if (animlist_map.find(listid) == animlist_map.end()) continue ; 
802                         else 
803                         {
804                                 //transformation has animations
805                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
806                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
807                                 //all the curves belonging to the current binding
808                                 std::vector<FCurve*> animcurves;    
809                                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
810                                          animcurves = curve_map[bindings[j].animation];
811                                         //calculate rnapaths and array index of fcurves according to transformation and animation class
812                                          Assign_transform_animations(transform, &bindings[j], &animcurves, is_joint, joint_path ); 
813                                         
814                                          std::vector<FCurve*>::iterator iter;
815                                                 //Add the curves of the current animation to the object
816                                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
817                                                         FCurve * fcu = *iter;
818                                                          if (ob->type == OB_ARMATURE) 
819                                                                 add_bone_fcurve( ob, node , fcu );
820                                                          else 
821                                                          BLI_addtail(AnimCurves, fcu);  
822                                                 }                               
823                                 }
824                         }
825                         if (is_rotation || is_matrix) {
826                                 if (is_joint) 
827                                 {
828                                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
829                                         chan->rotmode = ROT_MODE_EUL;
830                                 }
831                                 else 
832                                 {
833                                         ob->rotmode = ROT_MODE_EUL;
834                                 }
835                         }
836                 }
837         }
838
839         if ((animType->light) != 0)
840         {
841                 Lamp * lamp  = (Lamp*) ob->data;
842
843                 if (!lamp->adt || !lamp->adt->action) act = verify_adt_action((ID*)&lamp->id, 1);
844                                         else act = lamp->adt->action;
845
846                 ListBase *AnimCurves = &(act->curves);
847                 const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
848
849                 for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
850                         const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
851
852                         if ((animType->light & LIGHT_COLOR) != 0)
853                         {
854                                 const COLLADAFW::Color *col =  &(light->getColor());
855                                 const COLLADAFW::UniqueId& listid = col->getAnimationList();
856                                 
857                                 Assign_color_animations(listid, AnimCurves, "color"); 
858                         }
859                         if ((animType->light & LIGHT_FOA) != 0 )
860                         {
861                                 const COLLADAFW::AnimatableFloat *foa =  &(light->getFallOffAngle());
862                                 const COLLADAFW::UniqueId& listid = foa->getAnimationList();
863                                 
864                                 Assign_float_animations( listid ,AnimCurves, "spot_size"); 
865                         }
866                         if ( (animType->light & LIGHT_FOE) != 0 )
867                         {
868                                 const COLLADAFW::AnimatableFloat *foe =  &(light->getFallOffExponent());
869                                 const COLLADAFW::UniqueId& listid = foe->getAnimationList();
870                                 
871                                 Assign_float_animations( listid ,AnimCurves, "spot_blend"); 
872                         
873                         }
874                 }
875         }
876
877         if ( (animType->camera) != 0) 
878         {
879                 Camera * camera  = (Camera*) ob->data;
880
881                 if (!camera->adt || !camera->adt->action) act = verify_adt_action((ID*)&camera->id, 1);
882                                         else act = camera->adt->action;
883
884                 ListBase *AnimCurves = &(act->curves);
885                 const COLLADAFW::InstanceCameraPointerArray& nodeCameras= node->getInstanceCameras();
886
887                 for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
888                         const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
889
890                         if ((animType->camera & CAMERA_XFOV) != 0 )
891                         {
892                                 const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
893                                 const COLLADAFW::UniqueId& listid = xfov->getAnimationList();
894                                 Assign_float_animations( listid ,AnimCurves, "lens"); 
895                         }
896
897                         else if ((animType->camera & CAMERA_XMAG) != 0 )
898                         {
899                                 const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
900                                 const COLLADAFW::UniqueId& listid = xmag->getAnimationList();
901                                 Assign_float_animations( listid ,AnimCurves, "ortho_scale"); 
902                         }
903
904                         if ((animType->camera & CAMERA_ZFAR) != 0 )
905                         {
906                                 const COLLADAFW::AnimatableFloat *zfar =  &(camera->getFarClippingPlane());
907                                 const COLLADAFW::UniqueId& listid = zfar->getAnimationList();
908                                 Assign_float_animations( listid ,AnimCurves, "clip_end"); 
909                         }
910
911                         if ((animType->camera & CAMERA_ZNEAR) != 0 )
912                         {
913                                 const COLLADAFW::AnimatableFloat *znear =  &(camera->getNearClippingPlane());
914                                 const COLLADAFW::UniqueId& listid = znear->getAnimationList();
915                                 Assign_float_animations( listid ,AnimCurves, "clip_start"); 
916                         }
917
918                 }
919         }
920         if ( animType->material != 0){
921                  Material *ma = give_current_material(ob, 1);
922                  if (!ma->adt || !ma->adt->action) act = verify_adt_action((ID*)&ma->id, 1);
923                                 else act = ma->adt->action;
924
925                 ListBase *AnimCurves = &(act->curves);
926                 
927                 const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
928                 for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
929                         const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
930                         for (unsigned int j = 0; j < matBinds.getCount(); j++) {
931                                 const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
932                                 const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
933                                 const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
934                                 COLLADAFW::EffectCommon *efc = commonEffects[0];
935                                 if((animType->material & MATERIAL_SHININESS) != 0){
936                                         const COLLADAFW::FloatOrParam *shin = &(efc->getShininess());
937                                         const COLLADAFW::UniqueId& listid =  shin->getAnimationList();
938                                         Assign_float_animations( listid, AnimCurves , "specular_hardness" );
939                                 }
940
941                                 if((animType->material & MATERIAL_IOR) != 0){
942                                         const COLLADAFW::FloatOrParam *ior = &(efc->getIndexOfRefraction());
943                                         const COLLADAFW::UniqueId& listid =  ior->getAnimationList();
944                                         Assign_float_animations( listid, AnimCurves , "raytrace_transparency.ior" );
945                                 }
946
947                                 if((animType->material & MATERIAL_SPEC_COLOR) != 0){
948                                         const COLLADAFW::ColorOrTexture *cot = &(efc->getSpecular());
949                                         const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
950                                         Assign_color_animations( listid, AnimCurves , "specular_color" );
951                                 }
952                                 
953                                 if((animType->material & MATERIAL_DIFF_COLOR) != 0){
954                                         const COLLADAFW::ColorOrTexture *cot = &(efc->getDiffuse());
955                                         const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
956                                         Assign_color_animations( listid, AnimCurves , "diffuse_color" );
957                                 }
958                         }
959                 }       
960         }
961 }
962
963
964 //Check if object is animated by checking if animlist_map holds the animlist_id of node transforms
965 AnimationImporter::AnimMix* AnimationImporter::get_animation_type ( const COLLADAFW::Node * node , 
966                                                                                         std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map) 
967 {
968         AnimMix *types = new AnimMix();
969         
970         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
971         
972         //for each transformation in node 
973         for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
974                 COLLADAFW::Transformation *transform = nodeTransforms[i];
975                 const COLLADAFW::UniqueId& listid = transform->getAnimationList();
976                 
977                 //check if transformation has animations    
978                 if (animlist_map.find(listid) == animlist_map.end()) continue ;
979                 else 
980                 {
981                         types->transform = types->transform|NODE_TRANSFORM;
982                         break;
983                 }
984         }
985         const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
986
987         for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
988                 const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
989                 types->light = setAnimType(&(light->getColor()),(types->light), LIGHT_COLOR);
990                 types->light = setAnimType(&(light->getFallOffAngle()),(types->light), LIGHT_FOA);
991                 types->light = setAnimType(&(light->getFallOffExponent()),(types->light), LIGHT_FOE);
992                 
993                 if ( types->light != 0) break;
994                 
995         }
996
997         const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
998         for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
999                 const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
1000
1001                 if ( camera->getCameraType() == COLLADAFW::Camera::PERSPECTIVE )
1002                 {
1003                     types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XFOV);
1004                 }
1005                 else 
1006                 {
1007                         types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XMAG);
1008                 }
1009                 types->camera = setAnimType(&(camera->getFarClippingPlane()),(types->camera), CAMERA_ZFAR);
1010                 types->camera = setAnimType(&(camera->getNearClippingPlane()),(types->camera), CAMERA_ZNEAR);
1011
1012                 if ( types->camera != 0) break;
1013
1014         }
1015
1016         const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
1017         for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
1018                 const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
1019                 for (unsigned int j = 0; j < matBinds.getCount(); j++) {
1020                         const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
1021                         const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
1022                         const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
1023                         COLLADAFW::EffectCommon *efc = commonEffects[0];
1024                         types->material =  setAnimType(&(efc->getShininess()),(types->material), MATERIAL_SHININESS);
1025                         types->material =  setAnimType(&(efc->getSpecular().getColor()),(types->material), MATERIAL_SPEC_COLOR);
1026                         types->material =  setAnimType(&(efc->getDiffuse().getColor()),(types->material), MATERIAL_DIFF_COLOR);
1027                    // types->material =  setAnimType(&(efc->get()),(types->material), MATERIAL_TRANSPARENCY);
1028                         types->material =  setAnimType(&(efc->getIndexOfRefraction()),(types->material), MATERIAL_IOR);
1029                 }
1030         }
1031         return types;
1032 }
1033
1034 int AnimationImporter::setAnimType ( const COLLADAFW::Animatable * prop , int types, int addition)
1035 {
1036                 const COLLADAFW::UniqueId& listid =  prop->getAnimationList();
1037                 if (animlist_map.find(listid) != animlist_map.end()) 
1038                                 return types|addition;
1039                 else return types;
1040 }               
1041
1042 //XXX Is not used anymore.
1043 void AnimationImporter::find_frames_old(std::vector<float> * frames, COLLADAFW::Node * node , COLLADAFW::Transformation::TransformationType tm_type)
1044 {
1045         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1046         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1047         // for each <rotate>, <translate>, etc. there is a separate Transformation
1048         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1049
1050         unsigned int i;
1051         // find frames at which to sample plus convert all rotation keys to radians
1052         for (i = 0; i < nodeTransforms.getCount(); i++) {
1053                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1054                 COLLADAFW::Transformation::TransformationType nodeTmType = transform->getTransformationType();
1055
1056
1057                 if (nodeTmType == tm_type) {
1058                         //get animation bindings for the current transformation
1059                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1060                         //if transform is animated its animlist must exist.
1061                         if (animlist_map.find(listid) != animlist_map.end()) {
1062                                 
1063                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1064                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1065                 
1066                                 if (bindings.getCount()) {
1067                                         //for each AnimationBinding get the fcurves which animate the transform
1068                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
1069                                                 std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
1070                                                 bool xyz = ((nodeTmType == COLLADAFW::Transformation::TRANSLATE || nodeTmType == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
1071
1072                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
1073                                                         std::vector<FCurve*>::iterator iter;
1074
1075                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
1076                                                                 FCurve *fcu = *iter;
1077                                 
1078                                                                 //if transform is rotation the fcurves values must be turned in to radian.
1079                                                                 if (is_rotation)
1080                                                                         fcurve_deg_to_rad(fcu);
1081
1082                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
1083                                                                         //get frame value from bezTriple
1084                                                                         float fra = fcu->bezt[k].vec[1][0];
1085                                                                         //if frame already not added add frame to frames
1086                                                                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
1087                                                                                 frames->push_back(fra);
1088                                                                 }
1089                                                         }
1090                                                 }
1091                                                 else {
1092                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
1093                                                 }
1094                                         }
1095                                 }
1096                         }
1097                 }
1098         }
1099 }
1100
1101
1102 // prerequisites:
1103 // animlist_map - map animlist id -> animlist
1104 // curve_map - map anim id -> curve(s)
1105 Object *AnimationImporter::translate_animation(COLLADAFW::Node *node,
1106                                                         std::map<COLLADAFW::UniqueId, Object*>& object_map,
1107                                                         std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
1108                                                         COLLADAFW::Transformation::TransformationType tm_type,
1109                                                         Object *par_job)
1110 {
1111         
1112         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1113         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1114         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
1115         
1116         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
1117         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
1118         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
1119         if (!ob) {
1120                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
1121                 return NULL;
1122         }
1123
1124         // frames at which to sample
1125         std::vector<float> frames;
1126         
1127         find_frames_old(&frames, node , tm_type);
1128         
1129         unsigned int i;
1130         
1131         float irest_dae[4][4];
1132         float rest[4][4], irest[4][4];
1133
1134         if (is_joint) {
1135                 get_joint_rest_mat(irest_dae, root, node);
1136                 invert_m4(irest_dae);
1137
1138                 Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
1139                 if (!bone) {
1140                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1141                         return NULL;
1142                 }
1143
1144                 unit_m4(rest);
1145                 copy_m4_m4(rest, bone->arm_mat);
1146                 invert_m4_m4(irest, rest);
1147         }
1148
1149         Object *job = NULL;
1150
1151 #ifdef ARMATURE_TEST
1152         FCurve *job_curves[10];
1153         job = get_joint_object(root, node, par_job);
1154 #endif
1155
1156         if (frames.size() == 0)
1157                 return job;
1158
1159         std::sort(frames.begin(), frames.end());
1160
1161         const char *tm_str = NULL;
1162         switch (tm_type) {
1163         case COLLADAFW::Transformation::ROTATE:
1164                 tm_str = "rotation_quaternion";
1165                 break;
1166         case COLLADAFW::Transformation::SCALE:
1167                 tm_str = "scale";
1168                 break;
1169         case COLLADAFW::Transformation::TRANSLATE:
1170                 tm_str = "location";
1171                 break;
1172         case COLLADAFW::Transformation::MATRIX:
1173                 break;
1174         default:
1175                 return job;
1176         }
1177
1178         char rna_path[200];
1179         char joint_path[200];
1180
1181         if (is_joint)
1182                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1183
1184         // new curves
1185         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1186         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
1187
1188         for (i = 0; i < totcu; i++) {
1189
1190                 int axis = i;
1191
1192                 if (is_matrix) {
1193                         if (i < 4) {
1194                                 tm_str = "rotation_quaternion";
1195                                 axis = i;
1196                         }
1197                         else if (i < 7) {
1198                                 tm_str = "location";
1199                                 axis = i - 4;
1200                         }
1201                         else {
1202                                 tm_str = "scale";
1203                                 axis = i - 7;
1204                         }
1205                 }
1206
1207                 if (is_joint)
1208                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1209                 else
1210                         strcpy(rna_path, tm_str);
1211                 newcu[i] = create_fcurve(axis, rna_path);
1212
1213 #ifdef ARMATURE_TEST
1214                 if (is_joint)
1215                         job_curves[i] = create_fcurve(axis, tm_str);
1216 #endif
1217         }
1218
1219         std::vector<float>::iterator it;
1220
1221         // sample values at each frame
1222         for (it = frames.begin(); it != frames.end(); it++) {
1223                 float fra = *it;
1224
1225                 float mat[4][4];
1226                 float matfra[4][4];
1227
1228                 unit_m4(matfra);
1229
1230                 // calc object-space mat
1231                 evaluate_transform_at_frame(matfra, node, fra);
1232
1233                 // for joints, we need a special matrix
1234                 if (is_joint) {
1235                         // special matrix: iR * M * iR_dae * R
1236                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1237                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1238                         float temp[4][4], par[4][4];
1239
1240                         // calc M
1241                         calc_joint_parent_mat_rest(par, NULL, root, node);
1242                         mul_m4_m4m4(temp, matfra, par);
1243
1244                         // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
1245
1246                         // calc special matrix
1247                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
1248                 }
1249                 else {
1250                         copy_m4_m4(mat, matfra);
1251                 }
1252
1253                 float val[4], rot[4], loc[3], scale[3];
1254
1255                 switch (tm_type) {
1256                 case COLLADAFW::Transformation::ROTATE:
1257                         mat4_to_quat(val, mat);
1258                         break;
1259                 case COLLADAFW::Transformation::SCALE:
1260                         mat4_to_size(val, mat);
1261                         break;
1262                 case COLLADAFW::Transformation::TRANSLATE:
1263                         copy_v3_v3(val, mat[3]);
1264                         break;
1265                 case COLLADAFW::Transformation::MATRIX:
1266                         mat4_to_quat(rot, mat);
1267                         copy_v3_v3(loc, mat[3]);
1268                         mat4_to_size(scale, mat);
1269                         break;
1270                 default:
1271                         break;
1272                 }
1273
1274                 // add keys
1275                 for (i = 0; i < totcu; i++) {
1276                         if (is_matrix) {
1277                                 if (i < 4)
1278                                         add_bezt(newcu[i], fra, rot[i]);
1279                                 else if (i < 7)
1280                                         add_bezt(newcu[i], fra, loc[i - 4]);
1281                                 else
1282                                         add_bezt(newcu[i], fra, scale[i - 7]);
1283                         }
1284                         else {
1285                                 add_bezt(newcu[i], fra, val[i]);
1286                         }
1287                 }
1288
1289 #ifdef ARMATURE_TEST
1290                 if (is_joint) {
1291                         switch (tm_type) {
1292                         case COLLADAFW::Transformation::ROTATE:
1293                                 mat4_to_quat(val, matfra);
1294                                 break;
1295                         case COLLADAFW::Transformation::SCALE:
1296                                 mat4_to_size(val, matfra);
1297                                 break;
1298                         case COLLADAFW::Transformation::TRANSLATE:
1299                                 copy_v3_v3(val, matfra[3]);
1300                                 break;
1301                         case MATRIX:
1302                                 mat4_to_quat(rot, matfra);
1303                                 copy_v3_v3(loc, matfra[3]);
1304                                 mat4_to_size(scale, matfra);
1305                                 break;
1306                         default:
1307                                 break;
1308                         }
1309
1310                         for (i = 0; i < totcu; i++) {
1311                                 if (is_matrix) {
1312                                         if (i < 4)
1313                                                 add_bezt(job_curves[i], fra, rot[i]);
1314                                         else if (i < 7)
1315                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
1316                                         else
1317                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
1318                                 }
1319                                 else {
1320                                         add_bezt(job_curves[i], fra, val[i]);
1321                                 }
1322                         }
1323                 }
1324 #endif
1325         }
1326
1327         verify_adt_action((ID*)&ob->id, 1);
1328
1329         ListBase *curves = &ob->adt->action->curves;
1330
1331         // add curves
1332         for (i = 0; i < totcu; i++) {
1333                 if (is_joint)
1334                         add_bone_fcurve(ob, node, newcu[i]);
1335                 else
1336                         BLI_addtail(curves, newcu[i]);
1337
1338 #ifdef ARMATURE_TEST
1339                 if (is_joint)
1340                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
1341 #endif
1342         }
1343
1344         if (is_rotation || is_matrix) {
1345                 if (is_joint) {
1346                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
1347                         chan->rotmode = ROT_MODE_QUAT;
1348                 }
1349                 else {
1350                         ob->rotmode = ROT_MODE_QUAT;
1351                 }
1352         }
1353
1354         return job;
1355 }
1356
1357 // internal, better make it private
1358 // warning: evaluates only rotation
1359 // prerequisites: animlist_map, curve_map
1360 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
1361 {
1362         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
1363
1364         unit_m4(mat);
1365
1366         for (unsigned int i = 0; i < tms.getCount(); i++) {
1367                 COLLADAFW::Transformation *tm = tms[i];
1368                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1369                 float m[4][4];
1370
1371                 unit_m4(m);
1372
1373                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
1374                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
1375                         switch (type) {
1376                         case COLLADAFW::Transformation::ROTATE:
1377                                 dae_rotate_to_mat4(tm, m);
1378                                 break;
1379                         case COLLADAFW::Transformation::TRANSLATE:
1380                                 dae_translate_to_mat4(tm, m);
1381                                 break;
1382                         case COLLADAFW::Transformation::SCALE:
1383                                 dae_scale_to_mat4(tm, m);
1384                                 break;
1385                         case COLLADAFW::Transformation::MATRIX:
1386                                 dae_matrix_to_mat4(tm, m);
1387                                 break;
1388                         default:
1389                                 fprintf(stderr, "unsupported transformation type %d\n", type);
1390                         }
1391                 }
1392
1393                 float temp[4][4];
1394                 copy_m4_m4(temp, mat);
1395
1396                 mul_m4_m4m4(mat, m, temp);
1397         }
1398 }
1399
1400 // return true to indicate that mat contains a sane value
1401 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
1402 {
1403         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
1404         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1405
1406         if (type != COLLADAFW::Transformation::ROTATE &&
1407             type != COLLADAFW::Transformation::SCALE &&
1408             type != COLLADAFW::Transformation::TRANSLATE &&
1409             type != COLLADAFW::Transformation::MATRIX) {
1410                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
1411                 return false;
1412         }
1413
1414         if (animlist_map.find(listid) == animlist_map.end())
1415                 return false;
1416
1417         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1418         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1419
1420         if (bindings.getCount()) {
1421                 float vec[3];
1422
1423                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
1424                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
1425
1426                 if (type == COLLADAFW::Transformation::SCALE)
1427                         dae_scale_to_v3(tm, vec);
1428                 else if (type == COLLADAFW::Transformation::TRANSLATE)
1429                         dae_translate_to_v3(tm, vec);
1430
1431                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
1432                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
1433                         std::vector<FCurve*>& curves = curve_map[binding.animation];
1434                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
1435                         char path[100];
1436
1437                         switch (type) {
1438                         case COLLADAFW::Transformation::ROTATE:
1439                                 BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
1440                                 break;
1441                         case COLLADAFW::Transformation::SCALE:
1442                                 BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
1443                                 break;
1444                         case COLLADAFW::Transformation::TRANSLATE:
1445                                 BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
1446                                 break;
1447                         case COLLADAFW::Transformation::MATRIX:
1448                                 BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
1449                                 break;
1450                         default:
1451                                 break;
1452                         }
1453
1454                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
1455                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
1456                                 continue;
1457                         }
1458
1459                         if (type == COLLADAFW::Transformation::ROTATE) {
1460                                 if (curves.size() != 1) {
1461                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
1462                                         return false;
1463                                 }
1464
1465                                 // TODO support other animclasses
1466                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
1467                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1468                                         return false;
1469                                 }
1470
1471                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
1472                                 float ax[3] = {axis[0], axis[1], axis[2]};
1473                                 float angle = evaluate_fcurve(curves[0], fra);
1474                                 axis_angle_to_mat4(mat, ax, angle);
1475
1476                                 return true;
1477                         }
1478                         else if (is_scale || is_translate) {
1479                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
1480
1481                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
1482                                         if (is_xyz)
1483                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
1484                                         else
1485                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
1486                                         return false;
1487                                 }
1488                                 
1489                                 switch (animclass) {
1490                                 case COLLADAFW::AnimationList::POSITION_X:
1491                                         vec[0] = evaluate_fcurve(curves[0], fra);
1492                                         break;
1493                                 case COLLADAFW::AnimationList::POSITION_Y:
1494                                         vec[1] = evaluate_fcurve(curves[0], fra);
1495                                         break;
1496                                 case COLLADAFW::AnimationList::POSITION_Z:
1497                                         vec[2] = evaluate_fcurve(curves[0], fra);
1498                                         break;
1499                                 case COLLADAFW::AnimationList::POSITION_XYZ:
1500                                         vec[0] = evaluate_fcurve(curves[0], fra);
1501                                         vec[1] = evaluate_fcurve(curves[1], fra);
1502                                         vec[2] = evaluate_fcurve(curves[2], fra);
1503                                         break;
1504                                 default:
1505                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1506                                         break;
1507                                 }
1508                         }
1509                         else if (type == COLLADAFW::Transformation::MATRIX) {
1510                                 // for now, of matrix animation, support only the case when all values are packed into one animation
1511                                 if (curves.size() != 16) {
1512                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
1513                                         return false;
1514                                 }
1515
1516                                 COLLADABU::Math::Matrix4 matrix;
1517                                 int i = 0, j = 0;
1518
1519                                 for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++) {
1520                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
1521                                         j++;
1522                                         if (j == 4) {
1523                                                 i++;
1524                                                 j = 0;
1525                                         }
1526                                 }
1527
1528                                 COLLADAFW::Matrix tm(matrix);
1529                                 dae_matrix_to_mat4(&tm, mat);
1530
1531                                 return true;
1532                         }
1533                 }
1534
1535                 if (is_scale)
1536                         size_to_mat4(mat, vec);
1537                 else
1538                         copy_v3_v3(mat[3], vec);
1539
1540                 return is_scale || is_translate;
1541         }
1542
1543         return false;
1544 }
1545
1546 // gives a world-space mat of joint at rest position
1547 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1548 {
1549         // if bind mat is not available,
1550         // use "current" node transform, i.e. all those tms listed inside <node>
1551         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1552                 float par[4][4], m[4][4];
1553
1554                 calc_joint_parent_mat_rest(par, NULL, root, node);
1555                 get_node_mat(m, node, NULL, NULL);
1556                 mul_m4_m4m4(mat, m, par);
1557         }
1558 }
1559
1560 // gives a world-space mat, end's mat not included
1561 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1562 {
1563         float m[4][4];
1564
1565         if (node == end) {
1566                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1567                 return true;
1568         }
1569
1570         // use bind matrix if available or calc "current" world mat
1571         if (!armature_importer->get_joint_bind_mat(m, node)) {
1572                 if (par) {
1573                         float temp[4][4];
1574                         get_node_mat(temp, node, NULL, NULL);
1575                         mul_m4_m4m4(m, temp, par);
1576                 }
1577                 else {
1578                         get_node_mat(m, node, NULL, NULL);
1579                 }
1580         }
1581
1582         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1583         for (unsigned int i = 0; i < children.getCount(); i++) {
1584                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1585                         return true;
1586         }
1587
1588         return false;
1589 }
1590
1591 #ifdef ARMATURE_TEST
1592 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1593 {
1594         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1595                 Object *job = add_object(scene, OB_EMPTY);
1596
1597                 rename_id((ID*)&job->id, (char*)get_joint_name(node));
1598
1599                 job->lay = object_in_scene(job, scene)->lay = 2;
1600
1601                 mul_v3_fl(job->size, 0.5f);
1602                 job->recalc |= OB_RECALC_OB;
1603
1604                 verify_adt_action((ID*)&job->id, 1);
1605
1606                 job->rotmode = ROT_MODE_QUAT;
1607
1608                 float mat[4][4];
1609                 get_joint_rest_mat(mat, root, node);
1610
1611                 if (par_job) {
1612                         float temp[4][4], ipar[4][4];
1613                         invert_m4_m4(ipar, par_job->obmat);
1614                         copy_m4_m4(temp, mat);
1615                         mul_m4_m4m4(mat, temp, ipar);
1616                 }
1617
1618                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1619
1620                 if (par_job) {
1621                         job->parent = par_job;
1622
1623                         par_job->recalc |= OB_RECALC_OB;
1624                         job->parsubstr[0] = 0;
1625                 }
1626
1627                 where_is_object(scene, job);
1628
1629                 // after parenting and layer change
1630                 DAG_scene_sort(CTX_data_main(C), scene);
1631
1632                 joint_objects[node->getUniqueId()] = job;
1633         }
1634
1635         return joint_objects[node->getUniqueId()];
1636 }
1637 #endif
1638
1639 #if 0
1640 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1641 // mat must be identity on enter, node must be root
1642 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1643 {
1644         float m[4][4];
1645         if (par) {
1646                 float temp[4][4];
1647                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1648                 mul_m4_m4m4(m, temp, par);
1649         }
1650         else {
1651                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1652         }
1653
1654         if (node == end) {
1655                 copy_m4_m4(mat, m);
1656                 return true;
1657         }
1658         else {
1659                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1660                 for (int i = 0; i < children.getCount(); i++) {
1661                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1662                                 return true;
1663                 }
1664         }
1665
1666         return false;
1667 }
1668 #endif
1669
1670 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1671 {
1672         const char *bone_name = bc_get_joint_name(node);
1673         bAction *act = ob->adt->action;
1674                         
1675         /* try to find group */
1676         bActionGroup *grp = action_groups_find_named(act, bone_name);
1677
1678         /* no matching groups, so add one */
1679         if (grp == NULL) {
1680                 /* Add a new group, and make it active */
1681                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1682                                         
1683                 grp->flag = AGRP_SELECTED;
1684                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1685                                         
1686                 BLI_addtail(&act->groups, grp);
1687                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1688         }
1689                                 
1690         /* add F-Curve to group */
1691         action_groups_add_channel(act, grp, fcu);
1692 }
1693
1694 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1695 {
1696         BezTriple bez;
1697         memset(&bez, 0, sizeof(BezTriple));
1698         bez.vec[1][0] = fra;
1699         bez.vec[1][1] = value;
1700         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1701         bez.f1 = bez.f2 = bez.f3 = SELECT;
1702         bez.h1 = bez.h2 = HD_AUTO;
1703         insert_bezt_fcurve(fcu, &bez, 0);
1704         calchandles_fcurve(fcu);
1705 }