eaf6835420e0e50d09e722e029d4db39a608b631
[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 #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::AnimationList::AnimationBinding * binding,
673                                                                                                  std::vector<FCurve*>* curves)
674 {
675         char rna_path[100];
676         BLI_strncpy(rna_path,"color", sizeof(rna_path));
677
678         switch (binding->animationClass) {
679                 case COLLADAFW::AnimationList::COLOR_R:
680                         modify_fcurve(curves, rna_path, 0 );
681                         break;
682                 case COLLADAFW::AnimationList::COLOR_G:
683                         modify_fcurve(curves, rna_path, 1 );
684                         break;
685                 case COLLADAFW::AnimationList::COLOR_B:
686                         modify_fcurve(curves, rna_path, 2 );
687                         break;
688                 case COLLADAFW::AnimationList::COLOR_RGB:
689                 case COLLADAFW::AnimationList::COLOR_RGBA:
690                         modify_fcurve(curves, rna_path, -1 );
691                         break;
692                         
693                 default:
694                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
695                                         binding->animationClass, "COLOR" );
696                 }
697 }
698
699 void AnimationImporter:: Assign_float_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves, char * anim_type)
700 {
701         char rna_path[100];
702         if (animlist_map.find(listid) == animlist_map.end()) return ;
703         else 
704         {
705                 //transformation has animations
706                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
707                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
708                 //all the curves belonging to the current binding
709                 std::vector<FCurve*> animcurves;    
710                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
711                          animcurves = curve_map[bindings[j].animation];
712                         //calculate rnapaths and array index of fcurves according to transformation and animation class
713                          BLI_strncpy(rna_path, anim_type , sizeof(rna_path));
714                          modify_fcurve(&animcurves, rna_path, 0 );
715                          std::vector<FCurve*>::iterator iter;
716                                 //Add the curves of the current animation to the object
717                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
718                                         FCurve * fcu = *iter;
719                                         BLI_addtail(AnimCurves, fcu);   
720                                 }                               
721                 }
722         }
723         
724 }
725
726 void AnimationImporter::translate_Animations_NEW ( COLLADAFW::Node * node , 
727                                                                                                    std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
728                                                                                                    std::map<COLLADAFW::UniqueId, Object*>& object_map,
729                                                                                                    std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map)
730 {
731         AnimationImporter::AnimMix* animType = get_animation_type(node, FW_object_map );
732
733         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
734         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
735         Object *ob = is_joint ? armature_importer->get_armature_for_joint(root) : object_map[node->getUniqueId()];
736         if (!ob)
737         {
738                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
739                 return;
740         }
741
742         bAction * act;
743         bActionGroup *grp = NULL;
744     
745         //if ( (animType & NODE_TRANSFORM) != 0 )
746         if ( (animType->transform) != 0 )
747         {
748         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
749         char joint_path[200];
750
751                 if ( is_joint ) 
752                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
753                 
754         
755                 if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
756                                         else act = ob->adt->action;
757                                         //Get the list of animation curves of the object
758             
759                 ListBase *AnimCurves = &(act->curves);
760
761                 const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
762         
763                 //for each transformation in node 
764                 for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
765                         COLLADAFW::Transformation *transform = nodeTransforms[i];
766                         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
767
768                         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
769                         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
770                                 
771                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
772                 
773                         //check if transformation has animations    
774                         if (animlist_map.find(listid) == animlist_map.end()) continue ; 
775                         else 
776                         {
777                                 //transformation has animations
778                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
779                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
780                                 //all the curves belonging to the current binding
781                                 std::vector<FCurve*> animcurves;    
782                                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
783                                          animcurves = curve_map[bindings[j].animation];
784                                         //calculate rnapaths and array index of fcurves according to transformation and animation class
785                                          Assign_transform_animations(transform, &bindings[j], &animcurves, is_joint, joint_path ); 
786                                         
787                                          std::vector<FCurve*>::iterator iter;
788                                                 //Add the curves of the current animation to the object
789                                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
790                                                         FCurve * fcu = *iter;
791                                                          if (ob->type == OB_ARMATURE) 
792                                                                 add_bone_fcurve( ob, node , fcu );
793                                                          else 
794                                                          BLI_addtail(AnimCurves, fcu);  
795                                                 }                               
796                                 }
797                         }
798                         if (is_rotation || is_matrix) {
799                                 if (is_joint) 
800                                 {
801                                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
802                                         chan->rotmode = ROT_MODE_EUL;
803                                 }
804                                 else 
805                                 {
806                                         ob->rotmode = ROT_MODE_EUL;
807                                 }
808                         }
809                 }
810         }
811
812         //if ( ((animType & LIGHT_COLOR) != 0)|| ((animType & LIGHT_FOA) != 0) || ((animType & LIGHT_FOE) != 0) )
813         if ((animType->light) != 0)
814         {
815                 Lamp * lamp  = (Lamp*) ob->data;
816
817                 if (!lamp->adt || !lamp->adt->action) act = verify_adt_action((ID*)&lamp->id, 1);
818                                         else act = lamp->adt->action;
819
820                 ListBase *AnimCurves = &(act->curves);
821                 const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
822
823                 for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
824                         const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
825
826                         if ((animType->light & LIGHT_COLOR) != 0)
827                         {
828                                 const COLLADAFW::Color *col =  &(light->getColor());
829                                 const COLLADAFW::UniqueId& listid = col->getAnimationList();
830                                 //transformation has animations
831                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
832                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
833                                 //all the curves belonging to the current binding
834                                 std::vector<FCurve*> animcurves;    
835                                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
836                                          animcurves = curve_map[bindings[j].animation];
837                                         //calculate rnapaths and array index of fcurves according to transformation and animation class
838                                          Assign_color_animations( &bindings[j], &animcurves); 
839                                         
840                                          std::vector<FCurve*>::iterator iter;
841                                                 //Add the curves of the current animation to the object
842                                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
843                                                         FCurve * fcu = *iter;
844                                                         BLI_addtail(AnimCurves, fcu);   
845                                                 }                               
846                                 }
847                                 
848                         }
849                         if ((animType->light & LIGHT_FOA) != 0 )
850                         {
851                                 const COLLADAFW::AnimatableFloat *foa =  &(light->getFallOffAngle());
852                                 const COLLADAFW::UniqueId& listid = foa->getAnimationList();
853                                 Assign_float_animations( listid ,AnimCurves, "spot_size"); 
854                         }
855                         if ( (animType->light & LIGHT_FOE) != 0 )
856                         {
857                                 const COLLADAFW::AnimatableFloat *foe =  &(light->getFallOffExponent());
858                                 const COLLADAFW::UniqueId& listid = foe->getAnimationList();
859                                 Assign_float_animations( listid ,AnimCurves, "spot_blend"); 
860                         
861                         }
862                 }
863         }
864
865         //if ( ((animType & CAMERA_XFOV) != 0) || (animType & CAMERA_XMAG) != 0 )
866         if ( (animType->camera) != 0) 
867         {
868                 Camera * camera  = (Camera*) ob->data;
869
870                 if (!camera->adt || !camera->adt->action) act = verify_adt_action((ID*)&camera->id, 1);
871                                         else act = camera->adt->action;
872
873                 ListBase *AnimCurves = &(act->curves);
874                 const COLLADAFW::InstanceCameraPointerArray& nodeCameras= node->getInstanceCameras();
875
876                 for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
877                         const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
878
879                         if ((animType->camera & CAMERA_XFOV) != 0 )
880                         {
881                                 const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
882                                 const COLLADAFW::UniqueId& listid = xfov->getAnimationList();
883                                 Assign_float_animations( listid ,AnimCurves, "lens"); 
884                         }
885
886                         else if ((animType->camera & CAMERA_XMAG) != 0 )
887                         {
888                                 const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
889                                 const COLLADAFW::UniqueId& listid = xmag->getAnimationList();
890                                 Assign_float_animations( listid ,AnimCurves, "ortho_scale"); 
891                         }
892
893                         if ((animType->camera & CAMERA_ZFAR) != 0 )
894                         {
895                                 const COLLADAFW::AnimatableFloat *zfar =  &(camera->getFarClippingPlane());
896                                 const COLLADAFW::UniqueId& listid = zfar->getAnimationList();
897                                 Assign_float_animations( listid ,AnimCurves, "clipend"); 
898                         }
899
900                         if ((animType->camera & CAMERA_ZNEAR) != 0 )
901                         {
902                                 const COLLADAFW::AnimatableFloat *znear =  &(camera->getNearClippingPlane());
903                                 const COLLADAFW::UniqueId& listid = znear->getAnimationList();
904                                 Assign_float_animations( listid ,AnimCurves, "clipsta"); 
905                         }
906
907                 }
908         }
909         if ( animType->material != 0){
910                  Material *ma = give_current_material(ob, 1);
911                  if (!ma->adt || !ma->adt->action) act = verify_adt_action((ID*)&ma->id, 1);
912                                 else act = ma->adt->action;
913
914                 ListBase *AnimCurves = &(act->curves);
915                 
916                 const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
917                 for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
918                         const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
919                         for (unsigned int j = 0; j < matBinds.getCount(); j++) {
920                                 const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
921                                 const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
922                                 const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
923                                 COLLADAFW::EffectCommon *efc = commonEffects[0];
924                                 if((animType->material & MATERIAL_SHININESS) != 0){
925                                         const COLLADAFW::FloatOrParam *shin = &(efc->getShininess());
926                                         const COLLADAFW::UniqueId& listid =  shin->getAnimationList();
927                                         Assign_float_animations( listid, AnimCurves , "specular_hardness" );
928                                 }
929                         }
930                 }       
931         }
932 }
933
934
935 //Check if object is animated by checking if animlist_map holds the animlist_id of node transforms
936 AnimationImporter::AnimMix* AnimationImporter::get_animation_type ( const COLLADAFW::Node * node , 
937                                                                                         std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map) 
938 {
939         AnimMix *types = new AnimMix();
940         
941         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
942         
943         //for each transformation in node 
944         for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
945                 COLLADAFW::Transformation *transform = nodeTransforms[i];
946                 const COLLADAFW::UniqueId& listid = transform->getAnimationList();
947                 
948                 //check if transformation has animations    
949                 if (animlist_map.find(listid) == animlist_map.end()) continue ;
950                 else 
951                 {
952                         types->transform = types->transform|NODE_TRANSFORM;
953                         break;
954                 }
955         }
956         const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
957
958         for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
959                 const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
960                 types->light = setAnimType(&(light->getColor()),(types->light), LIGHT_COLOR);
961                 types->light = setAnimType(&(light->getFallOffAngle()),(types->light), LIGHT_FOA);
962                 types->light = setAnimType(&(light->getFallOffExponent()),(types->light), LIGHT_FOE);
963                 
964                 if ( types->light != 0) break;
965                 
966         }
967
968         const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
969         for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
970                 const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
971         
972
973                 if ( camera->getCameraType() == COLLADAFW::Camera::PERSPECTIVE )
974                 {
975                     types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XFOV);
976                 }
977                 else 
978                 {
979                         types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XMAG);
980                 }
981                         
982                 types->camera = setAnimType(&(camera->getFarClippingPlane()),(types->camera), CAMERA_ZFAR);
983                 types->camera = setAnimType(&(camera->getNearClippingPlane()),(types->camera), CAMERA_ZNEAR);
984
985                 //if ( type != 0) break;
986                 if ( types->camera != 0) break;
987
988         }
989
990         const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
991         for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
992                 const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
993                 for (unsigned int j = 0; j < matBinds.getCount(); j++) {
994                         const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
995                         const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
996                         const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
997                         COLLADAFW::EffectCommon *efc = commonEffects[0];
998                         types->material =  setAnimType(&(efc->getShininess()),(types->material), MATERIAL_SHININESS);
999                 }
1000         }
1001         return types;
1002 }
1003
1004 int AnimationImporter::setAnimType ( const COLLADAFW::Animatable * prop , int types, int addition)
1005 {
1006                 const COLLADAFW::UniqueId& listid =  prop->getAnimationList();
1007                 if (animlist_map.find(listid) != animlist_map.end()) 
1008                                 return types|addition;
1009                 else return types;
1010 }               
1011
1012 //XXX Is not used anymore.
1013 void AnimationImporter::find_frames_old(std::vector<float> * frames, COLLADAFW::Node * node , COLLADAFW::Transformation::TransformationType tm_type)
1014 {
1015         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1016         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1017         // for each <rotate>, <translate>, etc. there is a separate Transformation
1018         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1019
1020         unsigned int i;
1021         // find frames at which to sample plus convert all rotation keys to radians
1022         for (i = 0; i < nodeTransforms.getCount(); i++) {
1023                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1024                 COLLADAFW::Transformation::TransformationType nodeTmType = transform->getTransformationType();
1025
1026
1027                 if (nodeTmType == tm_type) {
1028                         //get animation bindings for the current transformation
1029                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1030                         //if transform is animated its animlist must exist.
1031                         if (animlist_map.find(listid) != animlist_map.end()) {
1032                                 
1033                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1034                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1035                 
1036                                 if (bindings.getCount()) {
1037                                         //for each AnimationBinding get the fcurves which animate the transform
1038                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
1039                                                 std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
1040                                                 bool xyz = ((nodeTmType == COLLADAFW::Transformation::TRANSLATE || nodeTmType == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
1041
1042                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
1043                                                         std::vector<FCurve*>::iterator iter;
1044
1045                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
1046                                                                 FCurve *fcu = *iter;
1047                                 
1048                                                                 //if transform is rotation the fcurves values must be turned in to radian.
1049                                                                 if (is_rotation)
1050                                                                         fcurve_deg_to_rad(fcu);
1051
1052                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
1053                                                                         //get frame value from bezTriple
1054                                                                         float fra = fcu->bezt[k].vec[1][0];
1055                                                                         //if frame already not added add frame to frames
1056                                                                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
1057                                                                                 frames->push_back(fra);
1058                                                                 }
1059                                                         }
1060                                                 }
1061                                                 else {
1062                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
1063                                                 }
1064                                         }
1065                                 }
1066                         }
1067                 }
1068         }
1069 }
1070
1071
1072 // prerequisites:
1073 // animlist_map - map animlist id -> animlist
1074 // curve_map - map anim id -> curve(s)
1075 Object *AnimationImporter::translate_animation(COLLADAFW::Node *node,
1076                                                         std::map<COLLADAFW::UniqueId, Object*>& object_map,
1077                                                         std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
1078                                                         COLLADAFW::Transformation::TransformationType tm_type,
1079                                                         Object *par_job)
1080 {
1081         
1082         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1083         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1084         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
1085         
1086         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
1087         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
1088         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
1089         if (!ob) {
1090                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
1091                 return NULL;
1092         }
1093
1094         // frames at which to sample
1095         std::vector<float> frames;
1096         
1097         find_frames_old(&frames, node , tm_type);
1098         
1099         unsigned int i;
1100         
1101         float irest_dae[4][4];
1102         float rest[4][4], irest[4][4];
1103
1104         if (is_joint) {
1105                 get_joint_rest_mat(irest_dae, root, node);
1106                 invert_m4(irest_dae);
1107
1108                 Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
1109                 if (!bone) {
1110                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1111                         return NULL;
1112                 }
1113
1114                 unit_m4(rest);
1115                 copy_m4_m4(rest, bone->arm_mat);
1116                 invert_m4_m4(irest, rest);
1117         }
1118
1119         Object *job = NULL;
1120
1121 #ifdef ARMATURE_TEST
1122         FCurve *job_curves[10];
1123         job = get_joint_object(root, node, par_job);
1124 #endif
1125
1126         if (frames.size() == 0)
1127                 return job;
1128
1129         std::sort(frames.begin(), frames.end());
1130
1131         const char *tm_str = NULL;
1132         switch (tm_type) {
1133         case COLLADAFW::Transformation::ROTATE:
1134                 tm_str = "rotation_quaternion";
1135                 break;
1136         case COLLADAFW::Transformation::SCALE:
1137                 tm_str = "scale";
1138                 break;
1139         case COLLADAFW::Transformation::TRANSLATE:
1140                 tm_str = "location";
1141                 break;
1142         case COLLADAFW::Transformation::MATRIX:
1143                 break;
1144         default:
1145                 return job;
1146         }
1147
1148         char rna_path[200];
1149         char joint_path[200];
1150
1151         if (is_joint)
1152                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1153
1154         // new curves
1155         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1156         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
1157
1158         for (i = 0; i < totcu; i++) {
1159
1160                 int axis = i;
1161
1162                 if (is_matrix) {
1163                         if (i < 4) {
1164                                 tm_str = "rotation_quaternion";
1165                                 axis = i;
1166                         }
1167                         else if (i < 7) {
1168                                 tm_str = "location";
1169                                 axis = i - 4;
1170                         }
1171                         else {
1172                                 tm_str = "scale";
1173                                 axis = i - 7;
1174                         }
1175                 }
1176
1177                 if (is_joint)
1178                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1179                 else
1180                         strcpy(rna_path, tm_str);
1181                 newcu[i] = create_fcurve(axis, rna_path);
1182
1183 #ifdef ARMATURE_TEST
1184                 if (is_joint)
1185                         job_curves[i] = create_fcurve(axis, tm_str);
1186 #endif
1187         }
1188
1189         std::vector<float>::iterator it;
1190
1191         // sample values at each frame
1192         for (it = frames.begin(); it != frames.end(); it++) {
1193                 float fra = *it;
1194
1195                 float mat[4][4];
1196                 float matfra[4][4];
1197
1198                 unit_m4(matfra);
1199
1200                 // calc object-space mat
1201                 evaluate_transform_at_frame(matfra, node, fra);
1202
1203                 // for joints, we need a special matrix
1204                 if (is_joint) {
1205                         // special matrix: iR * M * iR_dae * R
1206                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1207                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1208                         float temp[4][4], par[4][4];
1209
1210                         // calc M
1211                         calc_joint_parent_mat_rest(par, NULL, root, node);
1212                         mul_m4_m4m4(temp, matfra, par);
1213
1214                         // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
1215
1216                         // calc special matrix
1217                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
1218                 }
1219                 else {
1220                         copy_m4_m4(mat, matfra);
1221                 }
1222
1223                 float val[4], rot[4], loc[3], scale[3];
1224
1225                 switch (tm_type) {
1226                 case COLLADAFW::Transformation::ROTATE:
1227                         mat4_to_quat(val, mat);
1228                         break;
1229                 case COLLADAFW::Transformation::SCALE:
1230                         mat4_to_size(val, mat);
1231                         break;
1232                 case COLLADAFW::Transformation::TRANSLATE:
1233                         copy_v3_v3(val, mat[3]);
1234                         break;
1235                 case COLLADAFW::Transformation::MATRIX:
1236                         mat4_to_quat(rot, mat);
1237                         copy_v3_v3(loc, mat[3]);
1238                         mat4_to_size(scale, mat);
1239                         break;
1240                 default:
1241                         break;
1242                 }
1243
1244                 // add keys
1245                 for (i = 0; i < totcu; i++) {
1246                         if (is_matrix) {
1247                                 if (i < 4)
1248                                         add_bezt(newcu[i], fra, rot[i]);
1249                                 else if (i < 7)
1250                                         add_bezt(newcu[i], fra, loc[i - 4]);
1251                                 else
1252                                         add_bezt(newcu[i], fra, scale[i - 7]);
1253                         }
1254                         else {
1255                                 add_bezt(newcu[i], fra, val[i]);
1256                         }
1257                 }
1258
1259 #ifdef ARMATURE_TEST
1260                 if (is_joint) {
1261                         switch (tm_type) {
1262                         case COLLADAFW::Transformation::ROTATE:
1263                                 mat4_to_quat(val, matfra);
1264                                 break;
1265                         case COLLADAFW::Transformation::SCALE:
1266                                 mat4_to_size(val, matfra);
1267                                 break;
1268                         case COLLADAFW::Transformation::TRANSLATE:
1269                                 copy_v3_v3(val, matfra[3]);
1270                                 break;
1271                         case MATRIX:
1272                                 mat4_to_quat(rot, matfra);
1273                                 copy_v3_v3(loc, matfra[3]);
1274                                 mat4_to_size(scale, matfra);
1275                                 break;
1276                         default:
1277                                 break;
1278                         }
1279
1280                         for (i = 0; i < totcu; i++) {
1281                                 if (is_matrix) {
1282                                         if (i < 4)
1283                                                 add_bezt(job_curves[i], fra, rot[i]);
1284                                         else if (i < 7)
1285                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
1286                                         else
1287                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
1288                                 }
1289                                 else {
1290                                         add_bezt(job_curves[i], fra, val[i]);
1291                                 }
1292                         }
1293                 }
1294 #endif
1295         }
1296
1297         verify_adt_action((ID*)&ob->id, 1);
1298
1299         ListBase *curves = &ob->adt->action->curves;
1300
1301         // add curves
1302         for (i = 0; i < totcu; i++) {
1303                 if (is_joint)
1304                         add_bone_fcurve(ob, node, newcu[i]);
1305                 else
1306                         BLI_addtail(curves, newcu[i]);
1307
1308 #ifdef ARMATURE_TEST
1309                 if (is_joint)
1310                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
1311 #endif
1312         }
1313
1314         if (is_rotation || is_matrix) {
1315                 if (is_joint) {
1316                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
1317                         chan->rotmode = ROT_MODE_QUAT;
1318                 }
1319                 else {
1320                         ob->rotmode = ROT_MODE_QUAT;
1321                 }
1322         }
1323
1324         return job;
1325 }
1326
1327 // internal, better make it private
1328 // warning: evaluates only rotation
1329 // prerequisites: animlist_map, curve_map
1330 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
1331 {
1332         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
1333
1334         unit_m4(mat);
1335
1336         for (unsigned int i = 0; i < tms.getCount(); i++) {
1337                 COLLADAFW::Transformation *tm = tms[i];
1338                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1339                 float m[4][4];
1340
1341                 unit_m4(m);
1342
1343                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
1344                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
1345                         switch (type) {
1346                         case COLLADAFW::Transformation::ROTATE:
1347                                 dae_rotate_to_mat4(tm, m);
1348                                 break;
1349                         case COLLADAFW::Transformation::TRANSLATE:
1350                                 dae_translate_to_mat4(tm, m);
1351                                 break;
1352                         case COLLADAFW::Transformation::SCALE:
1353                                 dae_scale_to_mat4(tm, m);
1354                                 break;
1355                         case COLLADAFW::Transformation::MATRIX:
1356                                 dae_matrix_to_mat4(tm, m);
1357                                 break;
1358                         default:
1359                                 fprintf(stderr, "unsupported transformation type %d\n", type);
1360                         }
1361                 }
1362
1363                 float temp[4][4];
1364                 copy_m4_m4(temp, mat);
1365
1366                 mul_m4_m4m4(mat, m, temp);
1367         }
1368 }
1369
1370 // return true to indicate that mat contains a sane value
1371 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
1372 {
1373         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
1374         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1375
1376         if (type != COLLADAFW::Transformation::ROTATE &&
1377             type != COLLADAFW::Transformation::SCALE &&
1378             type != COLLADAFW::Transformation::TRANSLATE &&
1379             type != COLLADAFW::Transformation::MATRIX) {
1380                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
1381                 return false;
1382         }
1383
1384         if (animlist_map.find(listid) == animlist_map.end())
1385                 return false;
1386
1387         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1388         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1389
1390         if (bindings.getCount()) {
1391                 float vec[3];
1392
1393                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
1394                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
1395
1396                 if (type == COLLADAFW::Transformation::SCALE)
1397                         dae_scale_to_v3(tm, vec);
1398                 else if (type == COLLADAFW::Transformation::TRANSLATE)
1399                         dae_translate_to_v3(tm, vec);
1400
1401                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
1402                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
1403                         std::vector<FCurve*>& curves = curve_map[binding.animation];
1404                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
1405                         char path[100];
1406
1407                         switch (type) {
1408                         case COLLADAFW::Transformation::ROTATE:
1409                                 BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
1410                                 break;
1411                         case COLLADAFW::Transformation::SCALE:
1412                                 BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
1413                                 break;
1414                         case COLLADAFW::Transformation::TRANSLATE:
1415                                 BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
1416                                 break;
1417                         case COLLADAFW::Transformation::MATRIX:
1418                                 BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
1419                                 break;
1420                         default:
1421                                 break;
1422                         }
1423
1424                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
1425                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
1426                                 continue;
1427                         }
1428
1429                         if (type == COLLADAFW::Transformation::ROTATE) {
1430                                 if (curves.size() != 1) {
1431                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
1432                                         return false;
1433                                 }
1434
1435                                 // TODO support other animclasses
1436                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
1437                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1438                                         return false;
1439                                 }
1440
1441                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
1442                                 float ax[3] = {axis[0], axis[1], axis[2]};
1443                                 float angle = evaluate_fcurve(curves[0], fra);
1444                                 axis_angle_to_mat4(mat, ax, angle);
1445
1446                                 return true;
1447                         }
1448                         else if (is_scale || is_translate) {
1449                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
1450
1451                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
1452                                         if (is_xyz)
1453                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
1454                                         else
1455                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
1456                                         return false;
1457                                 }
1458                                 
1459                                 switch (animclass) {
1460                                 case COLLADAFW::AnimationList::POSITION_X:
1461                                         vec[0] = evaluate_fcurve(curves[0], fra);
1462                                         break;
1463                                 case COLLADAFW::AnimationList::POSITION_Y:
1464                                         vec[1] = evaluate_fcurve(curves[0], fra);
1465                                         break;
1466                                 case COLLADAFW::AnimationList::POSITION_Z:
1467                                         vec[2] = evaluate_fcurve(curves[0], fra);
1468                                         break;
1469                                 case COLLADAFW::AnimationList::POSITION_XYZ:
1470                                         vec[0] = evaluate_fcurve(curves[0], fra);
1471                                         vec[1] = evaluate_fcurve(curves[1], fra);
1472                                         vec[2] = evaluate_fcurve(curves[2], fra);
1473                                         break;
1474                                 default:
1475                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1476                                         break;
1477                                 }
1478                         }
1479                         else if (type == COLLADAFW::Transformation::MATRIX) {
1480                                 // for now, of matrix animation, support only the case when all values are packed into one animation
1481                                 if (curves.size() != 16) {
1482                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
1483                                         return false;
1484                                 }
1485
1486                                 COLLADABU::Math::Matrix4 matrix;
1487                                 int i = 0, j = 0;
1488
1489                                 for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++) {
1490                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
1491                                         j++;
1492                                         if (j == 4) {
1493                                                 i++;
1494                                                 j = 0;
1495                                         }
1496                                 }
1497
1498                                 COLLADAFW::Matrix tm(matrix);
1499                                 dae_matrix_to_mat4(&tm, mat);
1500
1501                                 return true;
1502                         }
1503                 }
1504
1505                 if (is_scale)
1506                         size_to_mat4(mat, vec);
1507                 else
1508                         copy_v3_v3(mat[3], vec);
1509
1510                 return is_scale || is_translate;
1511         }
1512
1513         return false;
1514 }
1515
1516 // gives a world-space mat of joint at rest position
1517 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1518 {
1519         // if bind mat is not available,
1520         // use "current" node transform, i.e. all those tms listed inside <node>
1521         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1522                 float par[4][4], m[4][4];
1523
1524                 calc_joint_parent_mat_rest(par, NULL, root, node);
1525                 get_node_mat(m, node, NULL, NULL);
1526                 mul_m4_m4m4(mat, m, par);
1527         }
1528 }
1529
1530 // gives a world-space mat, end's mat not included
1531 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1532 {
1533         float m[4][4];
1534
1535         if (node == end) {
1536                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1537                 return true;
1538         }
1539
1540         // use bind matrix if available or calc "current" world mat
1541         if (!armature_importer->get_joint_bind_mat(m, node)) {
1542                 if (par) {
1543                         float temp[4][4];
1544                         get_node_mat(temp, node, NULL, NULL);
1545                         mul_m4_m4m4(m, temp, par);
1546                 }
1547                 else {
1548                         get_node_mat(m, node, NULL, NULL);
1549                 }
1550         }
1551
1552         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1553         for (unsigned int i = 0; i < children.getCount(); i++) {
1554                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1555                         return true;
1556         }
1557
1558         return false;
1559 }
1560
1561 #ifdef ARMATURE_TEST
1562 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1563 {
1564         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1565                 Object *job = add_object(scene, OB_EMPTY);
1566
1567                 rename_id((ID*)&job->id, (char*)get_joint_name(node));
1568
1569                 job->lay = object_in_scene(job, scene)->lay = 2;
1570
1571                 mul_v3_fl(job->size, 0.5f);
1572                 job->recalc |= OB_RECALC_OB;
1573
1574                 verify_adt_action((ID*)&job->id, 1);
1575
1576                 job->rotmode = ROT_MODE_QUAT;
1577
1578                 float mat[4][4];
1579                 get_joint_rest_mat(mat, root, node);
1580
1581                 if (par_job) {
1582                         float temp[4][4], ipar[4][4];
1583                         invert_m4_m4(ipar, par_job->obmat);
1584                         copy_m4_m4(temp, mat);
1585                         mul_m4_m4m4(mat, temp, ipar);
1586                 }
1587
1588                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1589
1590                 if (par_job) {
1591                         job->parent = par_job;
1592
1593                         par_job->recalc |= OB_RECALC_OB;
1594                         job->parsubstr[0] = 0;
1595                 }
1596
1597                 where_is_object(scene, job);
1598
1599                 // after parenting and layer change
1600                 DAG_scene_sort(CTX_data_main(C), scene);
1601
1602                 joint_objects[node->getUniqueId()] = job;
1603         }
1604
1605         return joint_objects[node->getUniqueId()];
1606 }
1607 #endif
1608
1609 #if 0
1610 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1611 // mat must be identity on enter, node must be root
1612 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1613 {
1614         float m[4][4];
1615         if (par) {
1616                 float temp[4][4];
1617                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1618                 mul_m4_m4m4(m, temp, par);
1619         }
1620         else {
1621                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1622         }
1623
1624         if (node == end) {
1625                 copy_m4_m4(mat, m);
1626                 return true;
1627         }
1628         else {
1629                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1630                 for (int i = 0; i < children.getCount(); i++) {
1631                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1632                                 return true;
1633                 }
1634         }
1635
1636         return false;
1637 }
1638 #endif
1639
1640 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1641 {
1642         const char *bone_name = bc_get_joint_name(node);
1643         bAction *act = ob->adt->action;
1644                         
1645         /* try to find group */
1646         bActionGroup *grp = action_groups_find_named(act, bone_name);
1647
1648         /* no matching groups, so add one */
1649         if (grp == NULL) {
1650                 /* Add a new group, and make it active */
1651                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1652                                         
1653                 grp->flag = AGRP_SELECTED;
1654                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1655                                         
1656                 BLI_addtail(&act->groups, grp);
1657                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1658         }
1659                                 
1660         /* add F-Curve to group */
1661         action_groups_add_channel(act, grp, fcu);
1662 }
1663
1664 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1665 {
1666         BezTriple bez;
1667         memset(&bez, 0, sizeof(BezTriple));
1668         bez.vec[1][0] = fra;
1669         bez.vec[1][1] = value;
1670         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1671         bez.f1 = bez.f2 = bez.f3 = SELECT;
1672         bez.h1 = bez.h2 = HD_AUTO;
1673         insert_bezt_fcurve(fcu, &bez, 0);
1674         calchandles_fcurve(fcu);
1675 }