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