Added gsoc-2012 collada improvements from bratwurst branch
[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
687                                         // NOTE: Needs more testing (As we curretnly have no official test data for this)
688                                         double xfov = (fov_type == CAMERA_YFOV) ? (2.0f * atanf(aspect * tanf(DEG2RADF(input_fov) * 0.5f))) : DEG2RADF(input_fov);
689
690                                         fcu->bezt[i].vec[1][1] = fov_to_focallength(xfov, cam->sensor_x);
691                                 }
692
693                                 BLI_addtail(AnimCurves, fcu);
694                         }
695                 }
696         }
697 }
698
699 void AnimationImporter::apply_matrix_curves(Object *ob, std::vector<FCurve *>& animcurves, COLLADAFW::Node *root, COLLADAFW::Node *node,
700                                             COLLADAFW::Transformation *tm)
701 {
702         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
703         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
704         char joint_path[200];
705         if (is_joint)
706                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
707
708         std::vector<float> frames;
709         find_frames(&frames, &animcurves);
710
711         float irest_dae[4][4];
712         float rest[4][4], irest[4][4];
713
714         if (is_joint) {
715                 get_joint_rest_mat(irest_dae, root, node);
716                 invert_m4(irest_dae);
717
718                 Bone *bone = BKE_armature_find_bone_name((bArmature *)ob->data, bone_name);
719                 if (!bone) {
720                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
721                         return;
722                 }
723
724                 unit_m4(rest);
725                 copy_m4_m4(rest, bone->arm_mat);
726                 invert_m4_m4(irest, rest);
727         }
728         // new curves to assign matrix transform animation
729         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
730         unsigned int totcu = 10;
731         const char *tm_str = NULL;
732         char rna_path[200];
733         for (int i = 0; i < totcu; i++) {
734
735                 int axis = i;
736
737                 if (i < 4) {
738                         tm_str = "rotation_quaternion";
739                         axis = i;
740                 }
741                 else if (i < 7) {
742                         tm_str = "location";
743                         axis = i - 4;
744                 }
745                 else {
746                         tm_str = "scale";
747                         axis = i - 7;
748                 }
749
750
751                 if (is_joint)
752                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
753                 else
754                         BLI_strncpy(rna_path, tm_str, sizeof(rna_path));
755                 newcu[i] = create_fcurve(axis, rna_path);
756                 newcu[i]->totvert = frames.size();
757         }
758
759         if (frames.size() == 0)
760                 return;
761
762         std::sort(frames.begin(), frames.end());
763
764         std::vector<float>::iterator it;
765
766         // sample values at each frame
767         for (it = frames.begin(); it != frames.end(); it++) {
768                 float fra = *it;
769
770                 float mat[4][4];
771                 float matfra[4][4];
772
773                 unit_m4(matfra);
774
775                 // calc object-space mat
776                 evaluate_transform_at_frame(matfra, node, fra);
777
778
779                 // for joints, we need a special matrix
780                 if (is_joint) {
781                         // special matrix: iR * M * iR_dae * R
782                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
783                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
784                         float temp[4][4], par[4][4];
785
786                         // calc M
787                         calc_joint_parent_mat_rest(par, NULL, root, node);
788                         mult_m4_m4m4(temp, par, matfra);
789
790                         // evaluate_joint_world_transform_at_frame(temp, NULL, node, fra);
791
792                         // calc special matrix
793                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
794                 }
795                 else {
796                         copy_m4_m4(mat, matfra);
797                 }
798
799                 float rot[4], loc[3], scale[3];
800
801                 mat4_to_quat(rot, mat);
802                 /*for ( int i = 0 ; i < 4  ;  i ++ )
803                    {
804                    rot[i] = RAD2DEGF(rot[i]);
805                    }*/
806                 copy_v3_v3(loc, mat[3]);
807                 mat4_to_size(scale, mat);
808
809                 // add keys
810                 for (int i = 0; i < totcu; i++) {
811                         if (i < 4)
812                                 add_bezt(newcu[i], fra, rot[i]);
813                         else if (i < 7)
814                                 add_bezt(newcu[i], fra, loc[i - 4]);
815                         else
816                                 add_bezt(newcu[i], fra, scale[i - 7]);
817                 }
818         }
819         verify_adt_action((ID *)&ob->id, 1);
820
821         ListBase *curves = &ob->adt->action->curves;
822
823         // add curves
824         for (int i = 0; i < totcu; i++) {
825                 if (is_joint)
826                         add_bone_fcurve(ob, node, newcu[i]);
827                 else
828                         BLI_addtail(curves, newcu[i]);
829         }
830
831         if (is_joint) {
832                 bPoseChannel *chan = BKE_pose_channel_find_name(ob->pose, bone_name);
833                 chan->rotmode = ROT_MODE_QUAT;
834         }
835         else {
836                 ob->rotmode = ROT_MODE_QUAT;
837         }
838
839         return;
840
841 }
842
843 /*
844  * This function returns the aspet ration from the Collada camera.
845  *
846  * Note:COLLADA allows to specify either XFov, or YFov alone. 
847  * In that case the aspect ratio can be determined from
848  * the viewport aspect ratio (which is 1:1 ?)
849  * XXX: check this: its probably wrong!
850  * If both values are specified, then the aspect ration is simply xfov/yfov
851  * and if aspect ratio is efined, then .. well then its that one.
852  */
853 static const double get_aspect_ratio(const COLLADAFW::Camera *camera)
854 {
855         double aspect =  camera->getAspectRatio().getValue();
856
857         if (aspect == 0) {
858                 const double yfov   =  camera->getYFov().getValue();
859
860                 if (yfov == 0) {
861                         aspect = 1; // assume yfov and xfov are equal
862                 }
863                 else {
864                         const double xfov   =  camera->getXFov().getValue();
865                         if (xfov==0)
866                                 aspect = 1;
867                         else
868                                 aspect = xfov / yfov;
869                 }
870         }
871         return aspect;
872 }
873
874
875 void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
876                                              std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>& root_map,
877                                              std::multimap<COLLADAFW::UniqueId, Object *>& object_map,
878                                              std::map<COLLADAFW::UniqueId, const COLLADAFW::Object *> FW_object_map)
879 {
880         AnimationImporter::AnimMix *animType = get_animation_type(node, FW_object_map);
881
882         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
883         COLLADAFW::UniqueId uid = node->getUniqueId();
884         COLLADAFW::Node *root = root_map.find(uid) == root_map.end() ? node : root_map[uid];
885
886         Object *ob;
887         if (is_joint)
888                 ob = armature_importer->get_armature_for_joint(root);
889         else
890                 ob = object_map.find(uid) == object_map.end() ? NULL : object_map.find(uid)->second;
891
892         if (!ob) {
893                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
894                 return;
895         }
896
897         bAction *act;
898
899         if ( (animType->transform) != 0) {
900                 /* const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL; */ /* UNUSED */
901                 char joint_path[200];
902
903                 if (is_joint)
904                         armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
905
906
907                 if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID *)&ob->id, 1);
908                 else act = ob->adt->action;
909
910                 //Get the list of animation curves of the object
911                 ListBase *AnimCurves = &(act->curves);
912
913                 const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
914
915                 //for each transformation in node 
916                 for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
917                         COLLADAFW::Transformation *transform = nodeTransforms[i];
918                         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
919
920                         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
921                         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
922
923                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
924
925                         //check if transformation has animations
926                         if (animlist_map.find(listid) == animlist_map.end()) {
927                                 continue;
928                         }
929                         else {
930                                 //transformation has animations
931                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
932                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
933                                 //all the curves belonging to the current binding
934                                 std::vector<FCurve *> animcurves;
935                                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
936                                         animcurves = curve_map[bindings[j].animation];
937                                         if (is_matrix) {
938                                                 apply_matrix_curves(ob, animcurves, root, node,  transform);
939                                         }
940                                         else {                          
941
942                                                 if (is_joint) {
943                                                         add_bone_animation_sampled(ob, animcurves, root, node, transform);
944                                                 }
945                                                 else {
946                                                         //calculate rnapaths and array index of fcurves according to transformation and animation class
947                                                         Assign_transform_animations(transform, &bindings[j], &animcurves, is_joint, joint_path);
948
949                                                         std::vector<FCurve *>::iterator iter;
950                                                         //Add the curves of the current animation to the object
951                                                         for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
952                                                                 FCurve *fcu = *iter;
953                                                         
954                                                                 BLI_addtail(AnimCurves, fcu);
955                                                         }
956                                                 }
957                                                 
958                                         }
959                                 }
960                         }
961                         if (is_rotation && !is_joint) {
962                                 ob->rotmode = ROT_MODE_EUL;
963                         }
964                 }
965         }
966
967         if ((animType->light) != 0) {
968                 Lamp *lamp  = (Lamp *) ob->data;
969
970                 if (!lamp->adt || !lamp->adt->action) act = verify_adt_action((ID *)&lamp->id, 1);
971                 else act = lamp->adt->action;
972
973                 ListBase *AnimCurves = &(act->curves);
974                 const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
975
976                 for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
977                         const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
978
979                         if ((animType->light & LIGHT_COLOR) != 0) {
980                                 const COLLADAFW::Color *col =  &(light->getColor());
981                                 const COLLADAFW::UniqueId& listid = col->getAnimationList();
982
983                                 Assign_color_animations(listid, AnimCurves, "color"); 
984                         }
985                         if ((animType->light & LIGHT_FOA) != 0) {
986                                 const COLLADAFW::AnimatableFloat *foa =  &(light->getFallOffAngle());
987                                 const COLLADAFW::UniqueId& listid = foa->getAnimationList();
988
989                                 Assign_float_animations(listid, AnimCurves, "spot_size");
990                         }
991                         if ( (animType->light & LIGHT_FOE) != 0) {
992                                 const COLLADAFW::AnimatableFloat *foe =  &(light->getFallOffExponent());
993                                 const COLLADAFW::UniqueId& listid = foe->getAnimationList();
994
995                                 Assign_float_animations(listid, AnimCurves, "spot_blend");
996
997                         }
998                 }
999         }
1000
1001         if (animType->camera != 0) {
1002                 Camera *cam  = (Camera *) ob->data;
1003                 if (!cam->adt || !cam->adt->action)
1004                         act = verify_adt_action((ID *)&cam->id, 1);
1005                 else
1006                         act = cam->adt->action;
1007
1008                 ListBase *AnimCurves = &(act->curves);
1009                 const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
1010
1011                 for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
1012                         const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
1013
1014                         if ((animType->camera & CAMERA_XFOV) != 0) {
1015                                 const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
1016                                 const COLLADAFW::UniqueId& listid = xfov->getAnimationList();
1017                                 double aspect = get_aspect_ratio(camera); 
1018                                 Assign_lens_animations(listid, AnimCurves, aspect, cam, "lens", CAMERA_XFOV);
1019                         }
1020
1021                         else if ((animType->camera & CAMERA_YFOV) != 0) {
1022                                 const COLLADAFW::AnimatableFloat *yfov =  &(camera->getYFov());
1023                                 const COLLADAFW::UniqueId& listid = yfov->getAnimationList();
1024                                 double aspect = get_aspect_ratio(camera); 
1025                                 Assign_lens_animations(listid, AnimCurves, aspect, cam, "lens", CAMERA_YFOV);
1026                         }
1027
1028                         else if ((animType->camera & CAMERA_XMAG) != 0) {
1029                                 const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
1030                                 const COLLADAFW::UniqueId& listid = xmag->getAnimationList();
1031                                 Assign_float_animations(listid, AnimCurves, "ortho_scale");
1032                         }
1033
1034                         else if ((animType->camera & CAMERA_YMAG) != 0) {
1035                                 const COLLADAFW::AnimatableFloat *ymag =  &(camera->getYMag());
1036                                 const COLLADAFW::UniqueId& listid = ymag->getAnimationList();
1037                                 Assign_float_animations(listid, AnimCurves, "ortho_scale");
1038                         }
1039
1040                         if ((animType->camera & CAMERA_ZFAR) != 0) {
1041                                 const COLLADAFW::AnimatableFloat *zfar =  &(camera->getFarClippingPlane());
1042                                 const COLLADAFW::UniqueId& listid = zfar->getAnimationList();
1043                                 Assign_float_animations(listid, AnimCurves, "clip_end");
1044                         }
1045
1046                         if ((animType->camera & CAMERA_ZNEAR) != 0) {
1047                                 const COLLADAFW::AnimatableFloat *znear =  &(camera->getNearClippingPlane());
1048                                 const COLLADAFW::UniqueId& listid = znear->getAnimationList();
1049                                 Assign_float_animations(listid, AnimCurves, "clip_start");
1050                         }
1051
1052                 }
1053         }
1054         if (animType->material != 0) {
1055                 Material *ma = give_current_material(ob, 1);
1056                 if (!ma->adt || !ma->adt->action) act = verify_adt_action((ID *)&ma->id, 1);
1057                 else act = ma->adt->action;
1058
1059                 ListBase *AnimCurves = &(act->curves);
1060
1061                 const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
1062                 for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
1063                         const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
1064                         for (unsigned int j = 0; j < matBinds.getCount(); j++) {
1065                                 const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
1066                                 const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
1067                                 if (ef != NULL) { /* can be NULL [#28909] */
1068                                         const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
1069                                         COLLADAFW::EffectCommon *efc = commonEffects[0];
1070                                         if ((animType->material & MATERIAL_SHININESS) != 0) {
1071                                                 const COLLADAFW::FloatOrParam *shin = &(efc->getShininess());
1072                                                 const COLLADAFW::UniqueId& listid =  shin->getAnimationList();
1073                                                 Assign_float_animations(listid, AnimCurves, "specular_hardness");
1074                                         }
1075
1076                                         if ((animType->material & MATERIAL_IOR) != 0) {
1077                                                 const COLLADAFW::FloatOrParam *ior = &(efc->getIndexOfRefraction());
1078                                                 const COLLADAFW::UniqueId& listid =  ior->getAnimationList();
1079                                                 Assign_float_animations(listid, AnimCurves, "raytrace_transparency.ior");
1080                                         }
1081
1082                                         if ((animType->material & MATERIAL_SPEC_COLOR) != 0) {
1083                                                 const COLLADAFW::ColorOrTexture *cot = &(efc->getSpecular());
1084                                                 const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
1085                                                 Assign_color_animations(listid, AnimCurves, "specular_color");
1086                                         }
1087
1088                                         if ((animType->material & MATERIAL_DIFF_COLOR) != 0) {
1089                                                 const COLLADAFW::ColorOrTexture *cot = &(efc->getDiffuse());
1090                                                 const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
1091                                                 Assign_color_animations(listid, AnimCurves, "diffuse_color");
1092                                         }
1093                                 }
1094                         }
1095                 }
1096         }
1097 }
1098
1099 void AnimationImporter::add_bone_animation_sampled(Object *ob, std::vector<FCurve *>& animcurves, COLLADAFW::Node *root, COLLADAFW::Node *node, COLLADAFW::Transformation *tm)
1100 {
1101         const char *bone_name = bc_get_joint_name(node);
1102         char joint_path[200];
1103         armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1104
1105         std::vector<float> frames;
1106         find_frames(&frames, &animcurves);
1107
1108         // convert degrees to radians
1109         if (tm->getTransformationType() == COLLADAFW::Transformation::ROTATE) {
1110
1111                 std::vector<FCurve *>::iterator iter;
1112                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
1113                         FCurve *fcu = *iter;
1114
1115                         fcurve_deg_to_rad(fcu);
1116                 }
1117         }
1118
1119
1120         float irest_dae[4][4];
1121         float rest[4][4], irest[4][4];
1122
1123         get_joint_rest_mat(irest_dae, root, node);
1124         invert_m4(irest_dae);
1125
1126         Bone *bone = BKE_armature_find_bone_name((bArmature *)ob->data, bone_name);
1127         if (!bone) {
1128                 fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1129                 return;
1130         }
1131
1132         unit_m4(rest);
1133         copy_m4_m4(rest, bone->arm_mat);
1134         invert_m4_m4(irest, rest);
1135
1136         // new curves to assign matrix transform animation
1137         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1138         unsigned int totcu = 10;
1139         const char *tm_str = NULL;
1140         char rna_path[200];
1141         for (int i = 0; i < totcu; i++) {
1142
1143                 int axis = i;
1144
1145                 if (i < 4) {
1146                         tm_str = "rotation_quaternion";
1147                         axis = i;
1148                 }
1149                 else if (i < 7) {
1150                         tm_str = "location";
1151                         axis = i - 4;
1152                 }
1153                 else {
1154                         tm_str = "scale";
1155                         axis = i - 7;
1156                 }
1157
1158
1159                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1160
1161                 newcu[i] = create_fcurve(axis, rna_path);
1162                 newcu[i]->totvert = frames.size();
1163         }
1164
1165         if (frames.size() == 0)
1166                 return;
1167
1168         std::sort(frames.begin(), frames.end());
1169
1170         std::vector<float>::iterator it;
1171
1172         // sample values at each frame
1173         for (it = frames.begin(); it != frames.end(); it++) {
1174                 float fra = *it;
1175
1176                 float mat[4][4];
1177                 float matfra[4][4];
1178
1179                 unit_m4(matfra);
1180
1181                 // calc object-space mat
1182                 evaluate_transform_at_frame(matfra, node, fra);
1183
1184
1185                 // for joints, we need a special matrix
1186                 // special matrix: iR * M * iR_dae * R
1187                 // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1188                 // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1189                 float temp[4][4], par[4][4];
1190
1191
1192                 // calc M
1193                 calc_joint_parent_mat_rest(par, NULL, root, node);
1194                 mult_m4_m4m4(temp, par, matfra);
1195
1196                 // evaluate_joint_world_transform_at_frame(temp, NULL, node, fra);
1197
1198                 // calc special matrix
1199                 mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
1200
1201                 float rot[4], loc[3], scale[3];
1202
1203                 mat4_to_quat(rot, mat);
1204                 copy_v3_v3(loc, mat[3]);
1205                 mat4_to_size(scale, mat);
1206
1207                 // add keys
1208                 for (int i = 0; i < totcu; i++) {
1209                         if (i < 4)
1210                                 add_bezt(newcu[i], fra, rot[i]);
1211                         else if (i < 7)
1212                                 add_bezt(newcu[i], fra, loc[i - 4]);
1213                         else
1214                                 add_bezt(newcu[i], fra, scale[i - 7]);
1215                 }
1216         }
1217         verify_adt_action((ID *)&ob->id, 1);
1218
1219         // add curves
1220         for (int i = 0; i < totcu; i++) {
1221                 add_bone_fcurve(ob, node, newcu[i]);
1222         }
1223
1224         bPoseChannel *chan = BKE_pose_channel_find_name(ob->pose, bone_name);
1225         chan->rotmode = ROT_MODE_QUAT;
1226
1227 }
1228
1229
1230 //Check if object is animated by checking if animlist_map holds the animlist_id of node transforms
1231 AnimationImporter::AnimMix *AnimationImporter::get_animation_type(const COLLADAFW::Node *node,
1232                                                                   std::map<COLLADAFW::UniqueId, const COLLADAFW::Object *> FW_object_map)
1233 {
1234         AnimMix *types = new AnimMix();
1235
1236         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1237
1238         //for each transformation in node 
1239         for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
1240                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1241                 const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1242
1243                 //check if transformation has animations
1244                 if (animlist_map.find(listid) == animlist_map.end()) {
1245                         continue;
1246                 }
1247                 else {
1248                         types->transform = types->transform | NODE_TRANSFORM;
1249                         break;
1250                 }
1251         }
1252         const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
1253
1254         for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
1255                 const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
1256                 types->light = setAnimType(&(light->getColor()), (types->light), LIGHT_COLOR);
1257                 types->light = setAnimType(&(light->getFallOffAngle()), (types->light), LIGHT_FOA);
1258                 types->light = setAnimType(&(light->getFallOffExponent()), (types->light), LIGHT_FOE);
1259
1260                 if (types->light != 0) break;
1261
1262         }
1263
1264         const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
1265         for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
1266                 const COLLADAFW::Camera *camera  = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
1267                 if ( camera == NULL ) {
1268                         // Can happen if the node refers to an unknown camera.
1269                         continue;
1270                 }
1271
1272                 const bool is_perspective_type   = camera->getCameraType() == COLLADAFW::Camera::PERSPECTIVE;
1273
1274                 int addition;
1275                 const COLLADAFW::Animatable *mag;
1276                 const COLLADAFW::UniqueId listid = camera->getYMag().getAnimationList();
1277                 if (animlist_map.find(listid) != animlist_map.end()) {
1278                         mag = &(camera->getYMag());
1279                         addition = (is_perspective_type) ? CAMERA_YFOV: CAMERA_YMAG;
1280                 }
1281                 else {
1282                         mag = &(camera->getXMag());
1283                         addition = (is_perspective_type) ? CAMERA_XFOV: CAMERA_XMAG;
1284                 }
1285                 types->camera = setAnimType(mag, (types->camera), addition);
1286
1287                 types->camera = setAnimType(&(camera->getFarClippingPlane()), (types->camera), CAMERA_ZFAR);
1288                 types->camera = setAnimType(&(camera->getNearClippingPlane()), (types->camera), CAMERA_ZNEAR);
1289
1290                 if (types->camera != 0) break;
1291
1292         }
1293
1294         const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
1295         for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
1296                 const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
1297                 for (unsigned int j = 0; j < matBinds.getCount(); j++) {
1298                         const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
1299                         const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
1300                         if (ef != NULL) { /* can be NULL [#28909] */
1301                                 const COLLADAFW::CommonEffectPointerArray& commonEffects = ef->getCommonEffects();
1302                                 if (!commonEffects.empty()) {
1303                                         COLLADAFW::EffectCommon *efc = commonEffects[0];
1304                                         types->material =  setAnimType(&(efc->getShininess()), (types->material), MATERIAL_SHININESS);
1305                                         types->material =  setAnimType(&(efc->getSpecular().getColor()), (types->material), MATERIAL_SPEC_COLOR);
1306                                         types->material =  setAnimType(&(efc->getDiffuse().getColor()), (types->material), MATERIAL_DIFF_COLOR);
1307                                         // types->material =  setAnimType(&(efc->get()), (types->material), MATERIAL_TRANSPARENCY);
1308                                         types->material =  setAnimType(&(efc->getIndexOfRefraction()), (types->material), MATERIAL_IOR);
1309                                 }
1310                         }
1311                 }
1312         }
1313         return types;
1314 }
1315
1316 int AnimationImporter::setAnimType(const COLLADAFW::Animatable *prop, int types, int addition)
1317 {
1318         int anim_type;
1319         const COLLADAFW::UniqueId& listid       = prop->getAnimationList();
1320         if (animlist_map.find(listid) != animlist_map.end())
1321                 anim_type =  types | addition;
1322         else
1323                 anim_type = types;
1324
1325         return anim_type;
1326 }               
1327
1328 // Is not used anymore.
1329 void AnimationImporter::find_frames_old(std::vector<float> *frames, COLLADAFW::Node *node, COLLADAFW::Transformation::TransformationType tm_type)
1330 {
1331         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1332         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1333         // for each <rotate>, <translate>, etc. there is a separate Transformation
1334         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1335
1336         unsigned int i;
1337         // find frames at which to sample plus convert all rotation keys to radians
1338         for (i = 0; i < nodeTransforms.getCount(); i++) {
1339                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1340                 COLLADAFW::Transformation::TransformationType nodeTmType = transform->getTransformationType();
1341
1342
1343                 if (nodeTmType == tm_type) {
1344                         //get animation bindings for the current transformation
1345                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1346                         //if transform is animated its animlist must exist.
1347                         if (animlist_map.find(listid) != animlist_map.end()) {
1348                                 
1349                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1350                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1351
1352                                 if (bindings.getCount()) {
1353                                         //for each AnimationBinding get the fcurves which animate the transform
1354                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
1355                                                 std::vector<FCurve *>& curves = curve_map[bindings[j].animation];
1356                                                 bool xyz = ((nodeTmType == COLLADAFW::Transformation::TRANSLATE || nodeTmType == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
1357
1358                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
1359                                                         std::vector<FCurve *>::iterator iter;
1360
1361                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
1362                                                                 FCurve *fcu = *iter;
1363
1364                                                                 //if transform is rotation the fcurves values must be turned in to radian.
1365                                                                 if (is_rotation)
1366                                                                         fcurve_deg_to_rad(fcu);
1367
1368                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
1369                                                                         //get frame value from bezTriple
1370                                                                         float fra = fcu->bezt[k].vec[1][0];
1371                                                                         //if frame already not added add frame to frames
1372                                                                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
1373                                                                                 frames->push_back(fra);
1374                                                                 }
1375                                                         }
1376                                                 }
1377                                                 else {
1378                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
1379                                                 }
1380                                         }
1381                                 }
1382                         }
1383                 }
1384         }
1385 }
1386
1387
1388
1389 // prerequisites:
1390 // animlist_map - map animlist id -> animlist
1391 // curve_map - map anim id -> curve(s)
1392 Object *AnimationImporter::translate_animation_OLD(COLLADAFW::Node *node,
1393                                                    std::map<COLLADAFW::UniqueId, Object *>& object_map,
1394                                                    std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>& root_map,
1395                                                    COLLADAFW::Transformation::TransformationType tm_type,
1396                                                    Object *par_job)
1397 {
1398         
1399         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1400         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1401         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
1402         
1403         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
1404         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
1405         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
1406         if (!ob) {
1407                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
1408                 return NULL;
1409         }
1410
1411         // frames at which to sample
1412         std::vector<float> frames;
1413         
1414         find_frames_old(&frames, node, tm_type);
1415         
1416         unsigned int i;
1417         
1418         float irest_dae[4][4];
1419         float rest[4][4], irest[4][4];
1420
1421         if (is_joint) {
1422                 get_joint_rest_mat(irest_dae, root, node);
1423                 invert_m4(irest_dae);
1424
1425                 Bone *bone = BKE_armature_find_bone_name((bArmature *)ob->data, bone_name);
1426                 if (!bone) {
1427                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1428                         return NULL;
1429                 }
1430
1431                 unit_m4(rest);
1432                 copy_m4_m4(rest, bone->arm_mat);
1433                 invert_m4_m4(irest, rest);
1434         }
1435
1436         Object *job = NULL;
1437
1438 #ifdef ARMATURE_TEST
1439         FCurve *job_curves[10];
1440         job = get_joint_object(root, node, par_job);
1441 #endif
1442
1443         if (frames.size() == 0)
1444                 return job;
1445
1446         std::sort(frames.begin(), frames.end());
1447
1448         const char *tm_str = NULL;
1449         switch (tm_type) {
1450                 case COLLADAFW::Transformation::ROTATE:
1451                         tm_str = "rotation_quaternion";
1452                         break;
1453                 case COLLADAFW::Transformation::SCALE:
1454                         tm_str = "scale";
1455                         break;
1456                 case COLLADAFW::Transformation::TRANSLATE:
1457                         tm_str = "location";
1458                         break;
1459                 case COLLADAFW::Transformation::MATRIX:
1460                         break;
1461                 default:
1462                         return job;
1463         }
1464
1465         char rna_path[200];
1466         char joint_path[200];
1467
1468         if (is_joint)
1469                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1470
1471         // new curves
1472         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1473         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
1474
1475         for (i = 0; i < totcu; i++) {
1476
1477                 int axis = i;
1478
1479                 if (is_matrix) {
1480                         if (i < 4) {
1481                                 tm_str = "rotation_quaternion";
1482                                 axis = i;
1483                         }
1484                         else if (i < 7) {
1485                                 tm_str = "location";
1486                                 axis = i - 4;
1487                         }
1488                         else {
1489                                 tm_str = "scale";
1490                                 axis = i - 7;
1491                         }
1492                 }
1493
1494                 if (is_joint)
1495                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1496                 else
1497                         BLI_strncpy(rna_path, tm_str, sizeof(rna_path));
1498                 newcu[i] = create_fcurve(axis, rna_path);
1499
1500 #ifdef ARMATURE_TEST
1501                 if (is_joint)
1502                         job_curves[i] = create_fcurve(axis, tm_str);
1503 #endif
1504         }
1505
1506         std::vector<float>::iterator it;
1507
1508         // sample values at each frame
1509         for (it = frames.begin(); it != frames.end(); it++) {
1510                 float fra = *it;
1511
1512                 float mat[4][4];
1513                 float matfra[4][4];
1514
1515                 unit_m4(matfra);
1516
1517                 // calc object-space mat
1518                 evaluate_transform_at_frame(matfra, node, fra);
1519
1520                 // for joints, we need a special matrix
1521                 if (is_joint) {
1522                         // special matrix: iR * M * iR_dae * R
1523                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1524                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1525                         float temp[4][4], par[4][4];
1526
1527                         // calc M
1528                         calc_joint_parent_mat_rest(par, NULL, root, node);
1529                         mult_m4_m4m4(temp, par, matfra);
1530
1531                         // evaluate_joint_world_transform_at_frame(temp, NULL, node, fra);
1532
1533                         // calc special matrix
1534                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
1535                 }
1536                 else {
1537                         copy_m4_m4(mat, matfra);
1538                 }
1539
1540                 float val[4], rot[4], loc[3], scale[3];
1541
1542                 switch (tm_type) {
1543                         case COLLADAFW::Transformation::ROTATE:
1544                                 mat4_to_quat(val, mat);
1545                                 break;
1546                         case COLLADAFW::Transformation::SCALE:
1547                                 mat4_to_size(val, mat);
1548                                 break;
1549                         case COLLADAFW::Transformation::TRANSLATE:
1550                                 copy_v3_v3(val, mat[3]);
1551                                 break;
1552                         case COLLADAFW::Transformation::MATRIX:
1553                                 mat4_to_quat(rot, mat);
1554                                 copy_v3_v3(loc, mat[3]);
1555                                 mat4_to_size(scale, mat);
1556                                 break;
1557                         default:
1558                                 break;
1559                 }
1560
1561                 // add keys
1562                 for (i = 0; i < totcu; i++) {
1563                         if (is_matrix) {
1564                                 if (i < 4)
1565                                         add_bezt(newcu[i], fra, rot[i]);
1566                                 else if (i < 7)
1567                                         add_bezt(newcu[i], fra, loc[i - 4]);
1568                                 else
1569                                         add_bezt(newcu[i], fra, scale[i - 7]);
1570                         }
1571                         else {
1572                                 add_bezt(newcu[i], fra, val[i]);
1573                         }
1574                 }
1575
1576 #ifdef ARMATURE_TEST
1577                 if (is_joint) {
1578                         switch (tm_type) {
1579                                 case COLLADAFW::Transformation::ROTATE:
1580                                         mat4_to_quat(val, matfra);
1581                                         break;
1582                                 case COLLADAFW::Transformation::SCALE:
1583                                         mat4_to_size(val, matfra);
1584                                         break;
1585                                 case COLLADAFW::Transformation::TRANSLATE:
1586                                         copy_v3_v3(val, matfra[3]);
1587                                         break;
1588                                 case MATRIX:
1589                                         mat4_to_quat(rot, matfra);
1590                                         copy_v3_v3(loc, matfra[3]);
1591                                         mat4_to_size(scale, matfra);
1592                                         break;
1593                                 default:
1594                                         break;
1595                         }
1596
1597                         for (i = 0; i < totcu; i++) {
1598                                 if (is_matrix) {
1599                                         if (i < 4)
1600                                                 add_bezt(job_curves[i], fra, rot[i]);
1601                                         else if (i < 7)
1602                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
1603                                         else
1604                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
1605                                 }
1606                                 else {
1607                                         add_bezt(job_curves[i], fra, val[i]);
1608                                 }
1609                         }
1610                 }
1611 #endif
1612         }
1613
1614         verify_adt_action((ID *)&ob->id, 1);
1615
1616         ListBase *curves = &ob->adt->action->curves;
1617
1618         // add curves
1619         for (i = 0; i < totcu; i++) {
1620                 if (is_joint)
1621                         add_bone_fcurve(ob, node, newcu[i]);
1622                 else
1623                         BLI_addtail(curves, newcu[i]);
1624
1625 #ifdef ARMATURE_TEST
1626                 if (is_joint)
1627                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
1628 #endif
1629         }
1630
1631         if (is_rotation || is_matrix) {
1632                 if (is_joint) {
1633                         bPoseChannel *chan = BKE_pose_channel_find_name(ob->pose, bone_name);
1634                         chan->rotmode = ROT_MODE_QUAT;
1635                 }
1636                 else {
1637                         ob->rotmode = ROT_MODE_QUAT;
1638                 }
1639         }
1640
1641         return job;
1642 }
1643
1644 // internal, better make it private
1645 // warning: evaluates only rotation and only assigns matrix transforms now
1646 // prerequisites: animlist_map, curve_map
1647 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
1648 {
1649         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
1650
1651         unit_m4(mat);
1652
1653         for (unsigned int i = 0; i < tms.getCount(); i++) {
1654                 COLLADAFW::Transformation *tm = tms[i];
1655                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1656                 float m[4][4];
1657
1658                 unit_m4(m);
1659
1660                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
1661                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
1662                         switch (type) {
1663                                 case COLLADAFW::Transformation::ROTATE:
1664                                         dae_rotate_to_mat4(tm, m);
1665                                         break;
1666                                 case COLLADAFW::Transformation::TRANSLATE:
1667                                         dae_translate_to_mat4(tm, m);
1668                                         break;
1669                                 case COLLADAFW::Transformation::SCALE:
1670                                         dae_scale_to_mat4(tm, m);
1671                                         break;
1672                                 case COLLADAFW::Transformation::MATRIX:
1673                                         dae_matrix_to_mat4(tm, m);
1674                                         break;
1675                                 default:
1676                                         fprintf(stderr, "unsupported transformation type %d\n", type);
1677                         }
1678                 }
1679
1680                 float temp[4][4];
1681                 copy_m4_m4(temp, mat);
1682
1683                 mult_m4_m4m4(mat, temp, m);
1684         }
1685 }
1686
1687 // return true to indicate that mat contains a sane value
1688 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
1689 {
1690         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
1691         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1692
1693         if (type != COLLADAFW::Transformation::ROTATE &&
1694             type != COLLADAFW::Transformation::SCALE &&
1695             type != COLLADAFW::Transformation::TRANSLATE &&
1696             type != COLLADAFW::Transformation::MATRIX) {
1697                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
1698                 return false;
1699         }
1700
1701         if (animlist_map.find(listid) == animlist_map.end())
1702                 return false;
1703
1704         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1705         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1706
1707         if (bindings.getCount()) {
1708                 float vec[3];
1709
1710                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
1711                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
1712
1713                 if (is_scale)
1714                         dae_scale_to_v3(tm, vec);
1715                 else if (is_translate)
1716                         dae_translate_to_v3(tm, vec);
1717
1718                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
1719                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
1720                         std::vector<FCurve *>& curves = curve_map[binding.animation];
1721                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
1722                         char path[100];
1723
1724                         switch (type) {
1725                                 case COLLADAFW::Transformation::ROTATE:
1726                                         BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
1727                                         break;
1728                                 case COLLADAFW::Transformation::SCALE:
1729                                         BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
1730                                         break;
1731                                 case COLLADAFW::Transformation::TRANSLATE:
1732                                         BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
1733                                         break;
1734                                 case COLLADAFW::Transformation::MATRIX:
1735                                         BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
1736                                         break;
1737                                 default:
1738                                         break;
1739                         }
1740
1741                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
1742                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
1743                                 //continue;
1744                         }
1745
1746                         if (type == COLLADAFW::Transformation::ROTATE) {
1747                                 if (curves.size() != 1) {
1748                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
1749                                         return false;
1750                                 }
1751
1752                                 // TODO support other animclasses
1753                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
1754                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1755                                         return false;
1756                                 }
1757
1758                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate *)tm)->getRotationAxis();
1759
1760                                 float ax[3] = {(float)axis[0], (float)axis[1], (float)axis[2]};
1761                                 float angle = evaluate_fcurve(curves[0], fra);
1762                                 axis_angle_to_mat4(mat, ax, angle);
1763
1764                                 return true;
1765                         }
1766                         else if (is_scale || is_translate) {
1767                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
1768
1769                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
1770                                         if (is_xyz)
1771                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
1772                                         else
1773                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
1774                                         return false;
1775                                 }
1776                                 
1777                                 switch (animclass) {
1778                                         case COLLADAFW::AnimationList::POSITION_X:
1779                                                 vec[0] = evaluate_fcurve(curves[0], fra);
1780                                                 break;
1781                                         case COLLADAFW::AnimationList::POSITION_Y:
1782                                                 vec[1] = evaluate_fcurve(curves[0], fra);
1783                                                 break;
1784                                         case COLLADAFW::AnimationList::POSITION_Z:
1785                                                 vec[2] = evaluate_fcurve(curves[0], fra);
1786                                                 break;
1787                                         case COLLADAFW::AnimationList::POSITION_XYZ:
1788                                                 vec[0] = evaluate_fcurve(curves[0], fra);
1789                                                 vec[1] = evaluate_fcurve(curves[1], fra);
1790                                                 vec[2] = evaluate_fcurve(curves[2], fra);
1791                                                 break;
1792                                         default:
1793                                                 fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1794                                                 break;
1795                                 }
1796                         }
1797                         else if (type == COLLADAFW::Transformation::MATRIX) {
1798                                 // for now, of matrix animation, support only the case when all values are packed into one animation
1799                                 if (curves.size() != 16) {
1800                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
1801                                         return false;
1802                                 }
1803
1804                                 COLLADABU::Math::Matrix4 matrix;
1805                                 int i = 0, j = 0;
1806
1807                                 for (std::vector<FCurve *>::iterator it = curves.begin(); it != curves.end(); it++) {
1808                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
1809                                         j++;
1810                                         if (j == 4) {
1811                                                 i++;
1812                                                 j = 0;
1813                                         }
1814                                         unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), *it), unused_curves.end());
1815                                 }
1816
1817                                 COLLADAFW::Matrix tm(matrix);
1818                                 dae_matrix_to_mat4(&tm, mat);
1819
1820                                 std::vector<FCurve *>::iterator it;
1821
1822                                 return true;
1823                         }
1824                 }
1825
1826                 if (is_scale)
1827                         size_to_mat4(mat, vec);
1828                 else
1829                         copy_v3_v3(mat[3], vec);
1830
1831                 return is_scale || is_translate;
1832         }
1833
1834         return false;
1835 }
1836
1837 // gives a world-space mat of joint at rest position
1838 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1839 {
1840         // if bind mat is not available,
1841         // use "current" node transform, i.e. all those tms listed inside <node>
1842         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1843                 float par[4][4], m[4][4];
1844
1845                 calc_joint_parent_mat_rest(par, NULL, root, node);
1846                 get_node_mat(m, node, NULL, NULL);
1847                 mult_m4_m4m4(mat, par, m);
1848         }
1849 }
1850
1851 // gives a world-space mat, end's mat not included
1852 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1853 {
1854         float m[4][4];
1855
1856         if (node == end) {
1857                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1858                 return true;
1859         }
1860
1861         // use bind matrix if available or calc "current" world mat
1862         if (!armature_importer->get_joint_bind_mat(m, node)) {
1863                 if (par) {
1864                         float temp[4][4];
1865                         get_node_mat(temp, node, NULL, NULL);
1866                         mult_m4_m4m4(m, par, temp);
1867                 }
1868                 else {
1869                         get_node_mat(m, node, NULL, NULL);
1870                 }
1871         }
1872
1873         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1874         for (unsigned int i = 0; i < children.getCount(); i++) {
1875                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1876                         return true;
1877         }
1878
1879         return false;
1880 }
1881
1882 #ifdef ARMATURE_TEST
1883 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1884 {
1885         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1886                 Object *job = bc_add_object(scene, OB_EMPTY, (char *)get_joint_name(node));
1887
1888                 job->lay = BKE_scene_base_find(scene, job)->lay = 2;
1889
1890                 mul_v3_fl(job->size, 0.5f);
1891                 job->recalc |= OB_RECALC_OB;
1892
1893                 verify_adt_action((ID *)&job->id, 1);
1894
1895                 job->rotmode = ROT_MODE_QUAT;
1896
1897                 float mat[4][4];
1898                 get_joint_rest_mat(mat, root, node);
1899
1900                 if (par_job) {
1901                         float temp[4][4], ipar[4][4];
1902                         invert_m4_m4(ipar, par_job->obmat);
1903                         copy_m4_m4(temp, mat);
1904                         mult_m4_m4m4(mat, ipar, temp);
1905                 }
1906
1907                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1908
1909                 if (par_job) {
1910                         job->parent = par_job;
1911
1912                         par_job->recalc |= OB_RECALC_OB;
1913                         job->parsubstr[0] = 0;
1914                 }
1915
1916                 BKE_object_where_is_calc(scene, job);
1917
1918                 // after parenting and layer change
1919                 DAG_scene_sort(CTX_data_main(C), scene);
1920
1921                 joint_objects[node->getUniqueId()] = job;
1922         }
1923
1924         return joint_objects[node->getUniqueId()];
1925 }
1926 #endif
1927
1928 #if 0
1929 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1930 // mat must be identity on enter, node must be root
1931 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1932 {
1933         float m[4][4];
1934         if (par) {
1935                 float temp[4][4];
1936                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1937                 mult_m4_m4m4(m, par, temp);
1938         }
1939         else {
1940                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1941         }
1942
1943         if (node == end) {
1944                 copy_m4_m4(mat, m);
1945                 return true;
1946         }
1947         else {
1948                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1949                 for (int i = 0; i < children.getCount(); i++) {
1950                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1951                                 return true;
1952                 }
1953         }
1954
1955         return false;
1956 }
1957 #endif
1958
1959 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1960 {
1961         const char *bone_name = bc_get_joint_name(node);
1962         bAction *act = ob->adt->action;
1963                         
1964         /* try to find group */
1965         bActionGroup *grp = BKE_action_group_find_name(act, bone_name);
1966
1967         /* no matching groups, so add one */
1968         if (grp == NULL) {
1969                 /* Add a new group, and make it active */
1970                 grp = (bActionGroup *)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1971                                         
1972                 grp->flag = AGRP_SELECTED;
1973                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1974                                         
1975                 BLI_addtail(&act->groups, grp);
1976                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1977         }
1978                                 
1979         /* add F-Curve to group */
1980         action_groups_add_channel(act, grp, fcu);
1981 }
1982
1983 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1984 {
1985         //float fps = (float)FPS;
1986         BezTriple bez;
1987         memset(&bez, 0, sizeof(BezTriple));
1988         bez.vec[1][0] = fra;
1989         bez.vec[1][1] = value;
1990         bez.ipo = BEZT_IPO_LIN; /* use default interpolation mode here... */
1991         bez.f1 = bez.f2 = bez.f3 = SELECT;
1992         bez.h1 = bez.h2 = HD_AUTO;
1993         insert_bezt_fcurve(fcu, &bez, 0);
1994         calchandles_fcurve(fcu);
1995 }
1996