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