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