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