Fixed Camera Ortho scale animation import
[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         if ( ((animType & CAMERA_XFOV) != 0) || (animType & CAMERA_XMAG) != 0 )
860         {
861                 Camera * camera  = (Camera*) ob->data;
862
863                 if (!camera->adt || !camera->adt->action) act = verify_adt_action((ID*)&camera->id, 1);
864                                         else act = camera->adt->action;
865
866                 ListBase *AnimCurves = &(act->curves);
867                 const COLLADAFW::InstanceCameraPointerArray& nodeCameras= node->getInstanceCameras();
868
869                 for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
870                         const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
871
872                         if ((animType & CAMERA_XFOV) != 0 )
873                         {
874                                 const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
875                                 const COLLADAFW::UniqueId& listid = xfov->getAnimationList();
876                                 Assign_float_animations( listid ,AnimCurves, "lens"); 
877                         }
878
879                         else if ((animType & CAMERA_XMAG) != 0 )
880                         {
881                                 const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
882                                 const COLLADAFW::UniqueId& listid = xmag->getAnimationList();
883                                 Assign_float_animations( listid ,AnimCurves, "ortho_scale"); 
884                         }
885                 }
886         }
887 }
888
889 //Check if object is animated by checking if animlist_map holds the animlist_id of node transforms
890 int AnimationImporter::get_animation_type ( const COLLADAFW::Node * node , 
891                                                                                         std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map) 
892 {
893         int type = INANIMATE ;
894         //bool exists = false;
895         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
896         
897         //for each transformation in node 
898         for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
899                 COLLADAFW::Transformation *transform = nodeTransforms[i];
900                 const COLLADAFW::UniqueId& listid = transform->getAnimationList();
901                 
902                 //check if transformation has animations    
903                 if (animlist_map.find(listid) == animlist_map.end()) continue ;
904                 else 
905                 {
906                         type = type|NODE_TRANSFORM;
907                         break;
908                 }
909         }
910         const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
911
912         for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
913                 const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
914                 
915                 const COLLADAFW::Color *col =  &(light->getColor());
916                 const COLLADAFW::UniqueId& col_listid = col->getAnimationList();
917
918                 //check if color has animations    
919                 if (animlist_map.find(col_listid) != animlist_map.end())  
920                         type = type|LIGHT_COLOR;
921                 
922                 const COLLADAFW::AnimatableFloat *fallOffAngle =  &(light->getFallOffAngle());
923             const COLLADAFW::UniqueId& foa_listid = fallOffAngle ->getAnimationList();
924
925                 if (animlist_map.find(foa_listid) != animlist_map.end()) 
926                                 type = type|LIGHT_FOA;
927                 
928                 const COLLADAFW::AnimatableFloat *fallOffExpo =  &(light->getFallOffExponent());
929             const COLLADAFW::UniqueId& foe_listid = fallOffExpo ->getAnimationList();
930
931                 if (animlist_map.find(foe_listid) != animlist_map.end()) 
932                                 type = type|LIGHT_FOE;
933                 
934                 if ( type != 0) break;
935
936         }
937
938         const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
939         for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
940                 const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
941                 
942                 if ( camera->getCameraType() == COLLADAFW::Camera::PERSPECTIVE )
943                 {
944                         const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
945                         const COLLADAFW::UniqueId& xfov_listid = xfov ->getAnimationList();
946                         if (animlist_map.find(xfov_listid) != animlist_map.end()) 
947                                 type = type|CAMERA_XFOV;
948                 }
949                 else 
950                 {
951                         const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
952                         const COLLADAFW::UniqueId& xmag_listid = xmag ->getAnimationList();
953                         if (animlist_map.find(xmag_listid) != animlist_map.end()) 
954                                         type = type|CAMERA_XMAG;
955                 }       
956                 if ( type != 0) break;
957
958         }
959         return type;
960 }
961
962 //XXX Is not used anymore.
963 void AnimationImporter::find_frames_old(std::vector<float> * frames, COLLADAFW::Node * node , COLLADAFW::Transformation::TransformationType tm_type)
964 {
965         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
966         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
967         // for each <rotate>, <translate>, etc. there is a separate Transformation
968         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
969
970         unsigned int i;
971         // find frames at which to sample plus convert all rotation keys to radians
972         for (i = 0; i < nodeTransforms.getCount(); i++) {
973                 COLLADAFW::Transformation *transform = nodeTransforms[i];
974                 COLLADAFW::Transformation::TransformationType nodeTmType = transform->getTransformationType();
975
976
977                 if (nodeTmType == tm_type) {
978                         //get animation bindings for the current transformation
979                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
980                         //if transform is animated its animlist must exist.
981                         if (animlist_map.find(listid) != animlist_map.end()) {
982                                 
983                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
984                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
985                 
986                                 if (bindings.getCount()) {
987                                         //for each AnimationBinding get the fcurves which animate the transform
988                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
989                                                 std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
990                                                 bool xyz = ((nodeTmType == COLLADAFW::Transformation::TRANSLATE || nodeTmType == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
991
992                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
993                                                         std::vector<FCurve*>::iterator iter;
994
995                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
996                                                                 FCurve *fcu = *iter;
997                                 
998                                                                 //if transform is rotation the fcurves values must be turned in to radian.
999                                                                 if (is_rotation)
1000                                                                         fcurve_deg_to_rad(fcu);
1001
1002                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
1003                                                                         //get frame value from bezTriple
1004                                                                         float fra = fcu->bezt[k].vec[1][0];
1005                                                                         //if frame already not added add frame to frames
1006                                                                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
1007                                                                                 frames->push_back(fra);
1008                                                                 }
1009                                                         }
1010                                                 }
1011                                                 else {
1012                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
1013                                                 }
1014                                         }
1015                                 }
1016                         }
1017                 }
1018         }
1019 }
1020
1021
1022 // prerequisites:
1023 // animlist_map - map animlist id -> animlist
1024 // curve_map - map anim id -> curve(s)
1025 Object *AnimationImporter::translate_animation(COLLADAFW::Node *node,
1026                                                         std::map<COLLADAFW::UniqueId, Object*>& object_map,
1027                                                         std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
1028                                                         COLLADAFW::Transformation::TransformationType tm_type,
1029                                                         Object *par_job)
1030 {
1031         
1032         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1033         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1034         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
1035         
1036         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
1037         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
1038         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
1039         if (!ob) {
1040                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
1041                 return NULL;
1042         }
1043
1044         // frames at which to sample
1045         std::vector<float> frames;
1046         
1047         find_frames_old(&frames, node , tm_type);
1048         
1049         unsigned int i;
1050         
1051         float irest_dae[4][4];
1052         float rest[4][4], irest[4][4];
1053
1054         if (is_joint) {
1055                 get_joint_rest_mat(irest_dae, root, node);
1056                 invert_m4(irest_dae);
1057
1058                 Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
1059                 if (!bone) {
1060                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1061                         return NULL;
1062                 }
1063
1064                 unit_m4(rest);
1065                 copy_m4_m4(rest, bone->arm_mat);
1066                 invert_m4_m4(irest, rest);
1067         }
1068
1069         Object *job = NULL;
1070
1071 #ifdef ARMATURE_TEST
1072         FCurve *job_curves[10];
1073         job = get_joint_object(root, node, par_job);
1074 #endif
1075
1076         if (frames.size() == 0)
1077                 return job;
1078
1079         std::sort(frames.begin(), frames.end());
1080
1081         const char *tm_str = NULL;
1082         switch (tm_type) {
1083         case COLLADAFW::Transformation::ROTATE:
1084                 tm_str = "rotation_quaternion";
1085                 break;
1086         case COLLADAFW::Transformation::SCALE:
1087                 tm_str = "scale";
1088                 break;
1089         case COLLADAFW::Transformation::TRANSLATE:
1090                 tm_str = "location";
1091                 break;
1092         case COLLADAFW::Transformation::MATRIX:
1093                 break;
1094         default:
1095                 return job;
1096         }
1097
1098         char rna_path[200];
1099         char joint_path[200];
1100
1101         if (is_joint)
1102                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1103
1104         // new curves
1105         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1106         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
1107
1108         for (i = 0; i < totcu; i++) {
1109
1110                 int axis = i;
1111
1112                 if (is_matrix) {
1113                         if (i < 4) {
1114                                 tm_str = "rotation_quaternion";
1115                                 axis = i;
1116                         }
1117                         else if (i < 7) {
1118                                 tm_str = "location";
1119                                 axis = i - 4;
1120                         }
1121                         else {
1122                                 tm_str = "scale";
1123                                 axis = i - 7;
1124                         }
1125                 }
1126
1127                 if (is_joint)
1128                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1129                 else
1130                         strcpy(rna_path, tm_str);
1131                 newcu[i] = create_fcurve(axis, rna_path);
1132
1133 #ifdef ARMATURE_TEST
1134                 if (is_joint)
1135                         job_curves[i] = create_fcurve(axis, tm_str);
1136 #endif
1137         }
1138
1139         std::vector<float>::iterator it;
1140
1141         // sample values at each frame
1142         for (it = frames.begin(); it != frames.end(); it++) {
1143                 float fra = *it;
1144
1145                 float mat[4][4];
1146                 float matfra[4][4];
1147
1148                 unit_m4(matfra);
1149
1150                 // calc object-space mat
1151                 evaluate_transform_at_frame(matfra, node, fra);
1152
1153                 // for joints, we need a special matrix
1154                 if (is_joint) {
1155                         // special matrix: iR * M * iR_dae * R
1156                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1157                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1158                         float temp[4][4], par[4][4];
1159
1160                         // calc M
1161                         calc_joint_parent_mat_rest(par, NULL, root, node);
1162                         mul_m4_m4m4(temp, matfra, par);
1163
1164                         // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
1165
1166                         // calc special matrix
1167                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
1168                 }
1169                 else {
1170                         copy_m4_m4(mat, matfra);
1171                 }
1172
1173                 float val[4], rot[4], loc[3], scale[3];
1174
1175                 switch (tm_type) {
1176                 case COLLADAFW::Transformation::ROTATE:
1177                         mat4_to_quat(val, mat);
1178                         break;
1179                 case COLLADAFW::Transformation::SCALE:
1180                         mat4_to_size(val, mat);
1181                         break;
1182                 case COLLADAFW::Transformation::TRANSLATE:
1183                         copy_v3_v3(val, mat[3]);
1184                         break;
1185                 case COLLADAFW::Transformation::MATRIX:
1186                         mat4_to_quat(rot, mat);
1187                         copy_v3_v3(loc, mat[3]);
1188                         mat4_to_size(scale, mat);
1189                         break;
1190                 default:
1191                         break;
1192                 }
1193
1194                 // add keys
1195                 for (i = 0; i < totcu; i++) {
1196                         if (is_matrix) {
1197                                 if (i < 4)
1198                                         add_bezt(newcu[i], fra, rot[i]);
1199                                 else if (i < 7)
1200                                         add_bezt(newcu[i], fra, loc[i - 4]);
1201                                 else
1202                                         add_bezt(newcu[i], fra, scale[i - 7]);
1203                         }
1204                         else {
1205                                 add_bezt(newcu[i], fra, val[i]);
1206                         }
1207                 }
1208
1209 #ifdef ARMATURE_TEST
1210                 if (is_joint) {
1211                         switch (tm_type) {
1212                         case COLLADAFW::Transformation::ROTATE:
1213                                 mat4_to_quat(val, matfra);
1214                                 break;
1215                         case COLLADAFW::Transformation::SCALE:
1216                                 mat4_to_size(val, matfra);
1217                                 break;
1218                         case COLLADAFW::Transformation::TRANSLATE:
1219                                 copy_v3_v3(val, matfra[3]);
1220                                 break;
1221                         case MATRIX:
1222                                 mat4_to_quat(rot, matfra);
1223                                 copy_v3_v3(loc, matfra[3]);
1224                                 mat4_to_size(scale, matfra);
1225                                 break;
1226                         default:
1227                                 break;
1228                         }
1229
1230                         for (i = 0; i < totcu; i++) {
1231                                 if (is_matrix) {
1232                                         if (i < 4)
1233                                                 add_bezt(job_curves[i], fra, rot[i]);
1234                                         else if (i < 7)
1235                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
1236                                         else
1237                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
1238                                 }
1239                                 else {
1240                                         add_bezt(job_curves[i], fra, val[i]);
1241                                 }
1242                         }
1243                 }
1244 #endif
1245         }
1246
1247         verify_adt_action((ID*)&ob->id, 1);
1248
1249         ListBase *curves = &ob->adt->action->curves;
1250
1251         // add curves
1252         for (i = 0; i < totcu; i++) {
1253                 if (is_joint)
1254                         add_bone_fcurve(ob, node, newcu[i]);
1255                 else
1256                         BLI_addtail(curves, newcu[i]);
1257
1258 #ifdef ARMATURE_TEST
1259                 if (is_joint)
1260                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
1261 #endif
1262         }
1263
1264         if (is_rotation || is_matrix) {
1265                 if (is_joint) {
1266                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
1267                         chan->rotmode = ROT_MODE_QUAT;
1268                 }
1269                 else {
1270                         ob->rotmode = ROT_MODE_QUAT;
1271                 }
1272         }
1273
1274         return job;
1275 }
1276
1277 // internal, better make it private
1278 // warning: evaluates only rotation
1279 // prerequisites: animlist_map, curve_map
1280 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
1281 {
1282         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
1283
1284         unit_m4(mat);
1285
1286         for (unsigned int i = 0; i < tms.getCount(); i++) {
1287                 COLLADAFW::Transformation *tm = tms[i];
1288                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1289                 float m[4][4];
1290
1291                 unit_m4(m);
1292
1293                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
1294                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
1295                         switch (type) {
1296                         case COLLADAFW::Transformation::ROTATE:
1297                                 dae_rotate_to_mat4(tm, m);
1298                                 break;
1299                         case COLLADAFW::Transformation::TRANSLATE:
1300                                 dae_translate_to_mat4(tm, m);
1301                                 break;
1302                         case COLLADAFW::Transformation::SCALE:
1303                                 dae_scale_to_mat4(tm, m);
1304                                 break;
1305                         case COLLADAFW::Transformation::MATRIX:
1306                                 dae_matrix_to_mat4(tm, m);
1307                                 break;
1308                         default:
1309                                 fprintf(stderr, "unsupported transformation type %d\n", type);
1310                         }
1311                 }
1312
1313                 float temp[4][4];
1314                 copy_m4_m4(temp, mat);
1315
1316                 mul_m4_m4m4(mat, m, temp);
1317         }
1318 }
1319
1320 // return true to indicate that mat contains a sane value
1321 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
1322 {
1323         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
1324         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1325
1326         if (type != COLLADAFW::Transformation::ROTATE &&
1327             type != COLLADAFW::Transformation::SCALE &&
1328             type != COLLADAFW::Transformation::TRANSLATE &&
1329             type != COLLADAFW::Transformation::MATRIX) {
1330                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
1331                 return false;
1332         }
1333
1334         if (animlist_map.find(listid) == animlist_map.end())
1335                 return false;
1336
1337         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1338         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1339
1340         if (bindings.getCount()) {
1341                 float vec[3];
1342
1343                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
1344                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
1345
1346                 if (type == COLLADAFW::Transformation::SCALE)
1347                         dae_scale_to_v3(tm, vec);
1348                 else if (type == COLLADAFW::Transformation::TRANSLATE)
1349                         dae_translate_to_v3(tm, vec);
1350
1351                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
1352                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
1353                         std::vector<FCurve*>& curves = curve_map[binding.animation];
1354                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
1355                         char path[100];
1356
1357                         switch (type) {
1358                         case COLLADAFW::Transformation::ROTATE:
1359                                 BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
1360                                 break;
1361                         case COLLADAFW::Transformation::SCALE:
1362                                 BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
1363                                 break;
1364                         case COLLADAFW::Transformation::TRANSLATE:
1365                                 BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
1366                                 break;
1367                         case COLLADAFW::Transformation::MATRIX:
1368                                 BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
1369                                 break;
1370                         default:
1371                                 break;
1372                         }
1373
1374                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
1375                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
1376                                 continue;
1377                         }
1378
1379                         if (type == COLLADAFW::Transformation::ROTATE) {
1380                                 if (curves.size() != 1) {
1381                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
1382                                         return false;
1383                                 }
1384
1385                                 // TODO support other animclasses
1386                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
1387                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1388                                         return false;
1389                                 }
1390
1391                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
1392                                 float ax[3] = {axis[0], axis[1], axis[2]};
1393                                 float angle = evaluate_fcurve(curves[0], fra);
1394                                 axis_angle_to_mat4(mat, ax, angle);
1395
1396                                 return true;
1397                         }
1398                         else if (is_scale || is_translate) {
1399                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
1400
1401                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
1402                                         if (is_xyz)
1403                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
1404                                         else
1405                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
1406                                         return false;
1407                                 }
1408                                 
1409                                 switch (animclass) {
1410                                 case COLLADAFW::AnimationList::POSITION_X:
1411                                         vec[0] = evaluate_fcurve(curves[0], fra);
1412                                         break;
1413                                 case COLLADAFW::AnimationList::POSITION_Y:
1414                                         vec[1] = evaluate_fcurve(curves[0], fra);
1415                                         break;
1416                                 case COLLADAFW::AnimationList::POSITION_Z:
1417                                         vec[2] = evaluate_fcurve(curves[0], fra);
1418                                         break;
1419                                 case COLLADAFW::AnimationList::POSITION_XYZ:
1420                                         vec[0] = evaluate_fcurve(curves[0], fra);
1421                                         vec[1] = evaluate_fcurve(curves[1], fra);
1422                                         vec[2] = evaluate_fcurve(curves[2], fra);
1423                                         break;
1424                                 default:
1425                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1426                                         break;
1427                                 }
1428                         }
1429                         else if (type == COLLADAFW::Transformation::MATRIX) {
1430                                 // for now, of matrix animation, support only the case when all values are packed into one animation
1431                                 if (curves.size() != 16) {
1432                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
1433                                         return false;
1434                                 }
1435
1436                                 COLLADABU::Math::Matrix4 matrix;
1437                                 int i = 0, j = 0;
1438
1439                                 for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++) {
1440                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
1441                                         j++;
1442                                         if (j == 4) {
1443                                                 i++;
1444                                                 j = 0;
1445                                         }
1446                                 }
1447
1448                                 COLLADAFW::Matrix tm(matrix);
1449                                 dae_matrix_to_mat4(&tm, mat);
1450
1451                                 return true;
1452                         }
1453                 }
1454
1455                 if (is_scale)
1456                         size_to_mat4(mat, vec);
1457                 else
1458                         copy_v3_v3(mat[3], vec);
1459
1460                 return is_scale || is_translate;
1461         }
1462
1463         return false;
1464 }
1465
1466 // gives a world-space mat of joint at rest position
1467 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1468 {
1469         // if bind mat is not available,
1470         // use "current" node transform, i.e. all those tms listed inside <node>
1471         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1472                 float par[4][4], m[4][4];
1473
1474                 calc_joint_parent_mat_rest(par, NULL, root, node);
1475                 get_node_mat(m, node, NULL, NULL);
1476                 mul_m4_m4m4(mat, m, par);
1477         }
1478 }
1479
1480 // gives a world-space mat, end's mat not included
1481 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1482 {
1483         float m[4][4];
1484
1485         if (node == end) {
1486                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1487                 return true;
1488         }
1489
1490         // use bind matrix if available or calc "current" world mat
1491         if (!armature_importer->get_joint_bind_mat(m, node)) {
1492                 if (par) {
1493                         float temp[4][4];
1494                         get_node_mat(temp, node, NULL, NULL);
1495                         mul_m4_m4m4(m, temp, par);
1496                 }
1497                 else {
1498                         get_node_mat(m, node, NULL, NULL);
1499                 }
1500         }
1501
1502         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1503         for (unsigned int i = 0; i < children.getCount(); i++) {
1504                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1505                         return true;
1506         }
1507
1508         return false;
1509 }
1510
1511 #ifdef ARMATURE_TEST
1512 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1513 {
1514         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1515                 Object *job = add_object(scene, OB_EMPTY);
1516
1517                 rename_id((ID*)&job->id, (char*)get_joint_name(node));
1518
1519                 job->lay = object_in_scene(job, scene)->lay = 2;
1520
1521                 mul_v3_fl(job->size, 0.5f);
1522                 job->recalc |= OB_RECALC_OB;
1523
1524                 verify_adt_action((ID*)&job->id, 1);
1525
1526                 job->rotmode = ROT_MODE_QUAT;
1527
1528                 float mat[4][4];
1529                 get_joint_rest_mat(mat, root, node);
1530
1531                 if (par_job) {
1532                         float temp[4][4], ipar[4][4];
1533                         invert_m4_m4(ipar, par_job->obmat);
1534                         copy_m4_m4(temp, mat);
1535                         mul_m4_m4m4(mat, temp, ipar);
1536                 }
1537
1538                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1539
1540                 if (par_job) {
1541                         job->parent = par_job;
1542
1543                         par_job->recalc |= OB_RECALC_OB;
1544                         job->parsubstr[0] = 0;
1545                 }
1546
1547                 where_is_object(scene, job);
1548
1549                 // after parenting and layer change
1550                 DAG_scene_sort(CTX_data_main(C), scene);
1551
1552                 joint_objects[node->getUniqueId()] = job;
1553         }
1554
1555         return joint_objects[node->getUniqueId()];
1556 }
1557 #endif
1558
1559 #if 0
1560 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1561 // mat must be identity on enter, node must be root
1562 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1563 {
1564         float m[4][4];
1565         if (par) {
1566                 float temp[4][4];
1567                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1568                 mul_m4_m4m4(m, temp, par);
1569         }
1570         else {
1571                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1572         }
1573
1574         if (node == end) {
1575                 copy_m4_m4(mat, m);
1576                 return true;
1577         }
1578         else {
1579                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1580                 for (int i = 0; i < children.getCount(); i++) {
1581                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1582                                 return true;
1583                 }
1584         }
1585
1586         return false;
1587 }
1588 #endif
1589
1590 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1591 {
1592         const char *bone_name = bc_get_joint_name(node);
1593         bAction *act = ob->adt->action;
1594                         
1595         /* try to find group */
1596         bActionGroup *grp = action_groups_find_named(act, bone_name);
1597
1598         /* no matching groups, so add one */
1599         if (grp == NULL) {
1600                 /* Add a new group, and make it active */
1601                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1602                                         
1603                 grp->flag = AGRP_SELECTED;
1604                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1605                                         
1606                 BLI_addtail(&act->groups, grp);
1607                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1608         }
1609                                 
1610         /* add F-Curve to group */
1611         action_groups_add_channel(act, grp, fcu);
1612 }
1613
1614 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1615 {
1616         BezTriple bez;
1617         memset(&bez, 0, sizeof(BezTriple));
1618         bez.vec[1][0] = fra;
1619         bez.vec[1][1] = value;
1620         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1621         bez.f1 = bez.f2 = bez.f3 = SELECT;
1622         bez.h1 = bez.h2 = HD_AUTO;
1623         insert_bezt_fcurve(fcu, &bez, 0);
1624         calchandles_fcurve(fcu);
1625 }