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