Merging r42648 through r42722 from trunk into soc-2011-tomato
[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                                         {
143                                                 bez.h1 = bez.h2 = HD_AUTO; 
144                                                 bez.ipo = BEZT_IPO_LIN;
145                                         }
146                                         // bez.ipo = U.ipo_new; /* use default interpolation mode here... */
147                                         bez.f1 = bez.f2 = bez.f3 = SELECT;
148
149                                         insert_bezt_fcurve(fcu, &bez, 0);
150                                 }
151
152                                 calchandles_fcurve(fcu);
153
154                                 fcurves.push_back(fcu);
155                         }
156                 }
157                 break;
158         default:
159                 fprintf(stderr, "Output dimension of %d is not yet supported (animation id = %s)\n", (int)dim, curve->getOriginalId().c_str());
160         }
161
162         for (std::vector<FCurve*>::iterator it = fcurves.begin(); it != fcurves.end(); it++)
163                 unused_curves.push_back(*it);
164 }
165
166
167 void AnimationImporter::fcurve_deg_to_rad(FCurve *cu)
168 {
169         for (unsigned int i = 0; i < cu->totvert; i++) {
170                 // TODO convert handles too
171                 cu->bezt[i].vec[1][1] *= DEG2RADF(1.0f);
172                 cu->bezt[i].vec[0][1] *= DEG2RADF(1.0f);
173                 cu->bezt[i].vec[2][1] *= DEG2RADF(1.0f);
174         }
175 }
176
177
178 void AnimationImporter::add_fcurves_to_object(Object *ob, std::vector<FCurve*>& curves, char *rna_path, int array_index, Animation *animated)
179 {
180         bAction *act;
181         
182         if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
183         else act = ob->adt->action;
184         
185         std::vector<FCurve*>::iterator it;
186         int i;
187
188 #if 0
189         char *p = strstr(rna_path, "rotation_euler");
190         bool is_rotation = p && *(p + strlen("rotation_euler")) == '\0';
191
192         // convert degrees to radians for rotation
193         if (is_rotation)
194                 fcurve_deg_to_rad(fcu);
195 #endif
196         
197         for (it = curves.begin(), i = 0; it != curves.end(); it++, i++) {
198                 FCurve *fcu = *it;
199                 fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
200                 
201                 if (array_index == -1) fcu->array_index = i;
202                 else fcu->array_index = array_index;
203         
204                 if (ob->type == OB_ARMATURE) {
205                         bActionGroup *grp = NULL;
206                         const char *bone_name = bc_get_joint_name(animated->node);
207                         
208                         if (bone_name) {
209                                 /* try to find group */
210                                 grp = action_groups_find_named(act, bone_name);
211                                 
212                                 /* no matching groups, so add one */
213                                 if (grp == NULL) {
214                                         /* Add a new group, and make it active */
215                                         grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
216                                         
217                                         grp->flag = AGRP_SELECTED;
218                                         BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
219                                         
220                                         BLI_addtail(&act->groups, grp);
221                                         BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
222                                 }
223                                 
224                                 /* add F-Curve to group */
225                                 action_groups_add_channel(act, grp, fcu);
226                                 
227                         }
228 #if 0
229                         if (is_rotation) {
230                                 fcurves_actionGroup_map[grp].push_back(fcu);
231                         }
232 #endif
233                 }
234                 else {
235                         BLI_addtail(&act->curves, fcu);
236                 }
237
238                 // curve is used, so remove it from unused_curves
239                 unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
240         }
241 }
242
243 AnimationImporter::AnimationImporter(UnitConverter *conv, ArmatureImporter *arm, Scene *scene) :
244                 TransformReader(conv), armature_importer(arm), scene(scene) { }
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                 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 = get_pose_channel(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::find_frames( std::vector<float>* frames , std::vector<FCurve*>* curves)
443 {
444         std::vector<FCurve*>::iterator iter;
445         for (iter = curves->begin(); iter != curves->end(); iter++) {
446                 FCurve *fcu = *iter;
447
448                 for (unsigned int k = 0; k < fcu->totvert; k++) {
449                         //get frame value from bezTriple
450                         float fra = fcu->bezt[k].vec[1][0];
451                         //if frame already not added add frame to frames
452                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
453                                 frames->push_back(fra);
454
455                 }
456         }
457 }
458
459 //creates the rna_paths and array indices of fcurves from animations using transformation and bound animation class of each animation.
460 void AnimationImporter:: Assign_transform_animations(COLLADAFW::Transformation * transform , 
461                                                                                                          const COLLADAFW::AnimationList::AnimationBinding * binding,
462                                                                                                          std::vector<FCurve*>* curves, bool is_joint, char * joint_path)
463 {
464         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
465         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
466         bool is_rotation = tm_type  == COLLADAFW::Transformation::ROTATE;
467
468         //to check if the no of curves are valid
469         bool xyz = ((tm_type == COLLADAFW::Transformation::TRANSLATE ||tm_type  == COLLADAFW::Transformation::SCALE) && binding->animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
470
471
472         if (!((!xyz && curves->size() == 1) || (xyz && curves->size() == 3) || is_matrix)) {
473                 fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves->size());
474                 return;
475         }
476
477         char rna_path[100];
478
479         switch (tm_type) {
480                 case COLLADAFW::Transformation::TRANSLATE:
481                 case COLLADAFW::Transformation::SCALE:
482                         {
483                                 bool loc = tm_type == COLLADAFW::Transformation::TRANSLATE;
484                                 if (is_joint)
485                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
486                                 else
487                                         BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
488
489                                 switch (binding->animationClass) {
490                 case COLLADAFW::AnimationList::POSITION_X:
491                         modify_fcurve(curves, rna_path, 0 );
492                         break;
493                 case COLLADAFW::AnimationList::POSITION_Y:
494                         modify_fcurve(curves, rna_path, 1 );
495                         break;
496                 case COLLADAFW::AnimationList::POSITION_Z:
497                         modify_fcurve(curves, rna_path, 2 );
498                         break;
499                 case COLLADAFW::AnimationList::POSITION_XYZ:
500                         modify_fcurve(curves, rna_path, -1 );
501                         break;
502                 default:
503                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
504                                 binding->animationClass, loc ? "TRANSLATE" : "SCALE");
505                                 }
506                                 break;
507                         }
508
509
510                 case COLLADAFW::Transformation::ROTATE:
511                         {
512                                 if (is_joint)
513                                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
514                                 else
515                                         BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
516                                 std::vector<FCurve*>::iterator iter;
517                                 for (iter = curves->begin(); iter != curves->end(); iter++) {
518                                         FCurve* fcu = *iter;
519
520                                         //if transform is rotation the fcurves values must be turned in to radian.
521                                         if (is_rotation)
522                                                 fcurve_deg_to_rad(fcu);          
523                                 }                                       
524                                 COLLADAFW::Rotate* rot = (COLLADAFW::Rotate*)transform;
525                                 COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
526
527                                 switch (binding->animationClass) {
528                 case COLLADAFW::AnimationList::ANGLE:
529                         if (COLLADABU::Math::Vector3::UNIT_X == axis) {
530                                 modify_fcurve(curves, rna_path, 0 );
531                         }
532                         else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
533                                 modify_fcurve(curves, rna_path, 1 );
534                         }
535                         else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
536                                 modify_fcurve(curves, rna_path, 2 );
537                         }
538                         break;
539                 case COLLADAFW::AnimationList::AXISANGLE:
540                         // TODO convert axis-angle to quat? or XYZ?
541                 default:
542                         fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
543                                 binding->animationClass);
544                                 }
545                                 break;
546                         }
547
548                 case COLLADAFW::Transformation::MATRIX:
549                         /*{
550                         COLLADAFW::Matrix* mat = (COLLADAFW::Matrix*)transform;
551                         COLLADABU::Math::Matrix4 mat4 = mat->getMatrix();
552                         switch (binding->animationClass) {
553                         case COLLADAFW::AnimationList::TRANSFORM:
554
555                         }
556                         }*/
557                         break;
558                 case COLLADAFW::Transformation::SKEW:
559                 case COLLADAFW::Transformation::LOOKAT:
560                         fprintf(stderr, "Animation of SKEW and LOOKAT transformations is not supported yet.\n");
561                         break;
562         }
563
564 }
565
566 //creates the rna_paths and array indices of fcurves from animations using color and bound animation class of each animation.
567 void AnimationImporter:: Assign_color_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves ,const char * anim_type)
568 {
569         char rna_path[100];
570         BLI_strncpy(rna_path,anim_type, sizeof(rna_path));
571
572         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
573         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
574         //all the curves belonging to the current binding
575         std::vector<FCurve*> animcurves;
576         for (unsigned int j = 0; j < bindings.getCount(); j++) {
577                 animcurves = curve_map[bindings[j].animation];
578
579                 switch (bindings[j].animationClass) {
580                 case COLLADAFW::AnimationList::COLOR_R:
581                         modify_fcurve(&animcurves, rna_path, 0 );
582                         break;
583                 case COLLADAFW::AnimationList::COLOR_G:
584                         modify_fcurve(&animcurves, rna_path, 1 );
585                         break;
586                 case COLLADAFW::AnimationList::COLOR_B:
587                         modify_fcurve(&animcurves, rna_path, 2 );
588                         break;
589                 case COLLADAFW::AnimationList::COLOR_RGB:
590                 case COLLADAFW::AnimationList::COLOR_RGBA: // to do-> set intensity
591                         modify_fcurve(&animcurves, rna_path, -1 );
592                         break;
593
594                 default:
595                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
596                                 bindings[j].animationClass, "COLOR" );
597                 }
598
599                 std::vector<FCurve*>::iterator iter;
600                 //Add the curves of the current animation to the object
601                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
602                         FCurve * fcu = *iter;
603                         BLI_addtail(AnimCurves, fcu);   
604                 }
605         }
606
607
608 }
609
610 void AnimationImporter:: Assign_float_animations(const COLLADAFW::UniqueId& listid, ListBase *AnimCurves, const char * anim_type)
611 {
612         char rna_path[100];
613         if (animlist_map.find(listid) == animlist_map.end()) return ;
614         else 
615         {
616                 //anim_type has animations
617                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
618                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
619                 //all the curves belonging to the current binding
620                 std::vector<FCurve*> animcurves;
621                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
622                         animcurves = curve_map[bindings[j].animation];
623
624                         BLI_strncpy(rna_path, anim_type , sizeof(rna_path));
625                         modify_fcurve(&animcurves, rna_path, 0 );
626                         std::vector<FCurve*>::iterator iter;
627                         //Add the curves of the current animation to the object
628                         for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
629                                 FCurve * fcu = *iter;
630                                 BLI_addtail(AnimCurves, fcu);
631                         }
632                 }
633         }
634         
635 }
636
637 void AnimationImporter::apply_matrix_curves( Object * ob, std::vector<FCurve*>& animcurves, COLLADAFW::Node* root ,COLLADAFW::Node* node, 
638                                                                                                         COLLADAFW::Transformation * tm )
639 {
640         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
641         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
642         char joint_path[200];
643         if ( is_joint ) 
644                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
645
646         std::vector<float> frames;
647         find_frames(&frames, &animcurves);
648
649         float irest_dae[4][4];
650         float rest[4][4], irest[4][4];
651
652         if (is_joint) {
653                 get_joint_rest_mat(irest_dae, root, node);
654                 invert_m4(irest_dae);
655
656                 Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
657                 if (!bone) {
658                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
659                         return;
660                 }
661
662                 unit_m4(rest);
663                 copy_m4_m4(rest, bone->arm_mat);
664                 invert_m4_m4(irest, rest);
665         }
666         // new curves to assign matrix transform animation
667         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
668         unsigned int totcu = 10 ;
669         const char *tm_str = NULL;
670         char rna_path[200];
671         for (int i = 0; i < totcu; i++) {
672
673                 int axis = i;
674
675                 if (i < 4) {
676                         tm_str = "rotation_quaternion";
677                         axis = i;
678                 }
679                 else if (i < 7) {
680                         tm_str = "location";
681                         axis = i - 4;
682                 }
683                 else {
684                         tm_str = "scale";
685                         axis = i - 7;
686                 }
687
688
689                 if (is_joint)
690                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
691                 else
692                         BLI_strncpy(rna_path, tm_str, sizeof(rna_path));
693                 newcu[i] = create_fcurve(axis, rna_path);
694                 newcu[i]->totvert = frames.size();
695         }
696
697         if (frames.size() == 0)
698                 return;
699
700         std::sort(frames.begin(), frames.end());
701
702         std::vector<float>::iterator it;
703
704         // sample values at each frame
705         for (it = frames.begin(); it != frames.end(); it++) {
706                 float fra = *it;
707
708                 float mat[4][4];
709                 float matfra[4][4];
710
711                 unit_m4(matfra);
712
713                 // calc object-space mat
714                 evaluate_transform_at_frame(matfra, node, fra);
715
716
717                 // for joints, we need a special matrix
718                 if (is_joint) {
719                         // special matrix: iR * M * iR_dae * R
720                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
721                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
722                         float temp[4][4], par[4][4];
723
724                         // calc M
725                         calc_joint_parent_mat_rest(par, NULL, root, node);
726                         mult_m4_m4m4(temp, par, matfra);
727
728                         // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
729
730                         // calc special matrix
731                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
732                 }
733                 else {
734                         copy_m4_m4(mat, matfra);
735                 }
736
737                 float  rot[4], loc[3], scale[3];
738
739                 mat4_to_quat(rot, mat);
740                 /*for ( int i = 0 ; i < 4  ;  i ++ )
741                 {
742                 rot[i] = RAD2DEGF(rot[i]);
743                 }*/
744                 copy_v3_v3(loc, mat[3]);
745                 mat4_to_size(scale, mat);
746
747                 // add keys
748                 for (int i = 0; i < totcu; i++) {
749                         if (i < 4)
750                                 add_bezt(newcu[i], fra, rot[i]);
751                         else if (i < 7)
752                                 add_bezt(newcu[i], fra, loc[i - 4]);
753                         else
754                                 add_bezt(newcu[i], fra, scale[i - 7]);
755                 }
756         }
757         verify_adt_action((ID*)&ob->id, 1);
758
759         ListBase *curves = &ob->adt->action->curves;
760
761         // add curves
762         for (int i= 0; i < totcu; i++) {
763                 if (is_joint)
764                         add_bone_fcurve(ob, node, newcu[i]);
765                 else
766                         BLI_addtail(curves, newcu[i]);
767         }
768
769         if (is_joint) {
770                 bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
771                 chan->rotmode = ROT_MODE_QUAT;
772         }
773         else {
774                 ob->rotmode = ROT_MODE_QUAT;
775         }
776
777         return;
778
779 }
780
781 void AnimationImporter::translate_Animations ( COLLADAFW::Node * node , 
782                                                                                                    std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
783                                                                                                    std::map<COLLADAFW::UniqueId, Object*>& object_map,
784                                                                                                    std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map)
785 {
786         AnimationImporter::AnimMix* animType = get_animation_type(node, FW_object_map );
787
788         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
789         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
790         Object *ob = is_joint ? armature_importer->get_armature_for_joint(root) : object_map[node->getUniqueId()];
791         if (!ob)
792         {
793                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
794                 return;
795         }
796
797         bAction * act;
798
799         if ( (animType->transform) != 0 )
800         {
801                 const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
802                 char joint_path[200];
803
804                 if ( is_joint ) 
805                         armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
806
807
808                 if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
809                 else act = ob->adt->action;
810
811                 //Get the list of animation curves of the object
812                 ListBase *AnimCurves = &(act->curves);
813
814                 const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
815
816                 //for each transformation in node 
817                 for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
818                         COLLADAFW::Transformation *transform = nodeTransforms[i];
819                         COLLADAFW::Transformation::TransformationType tm_type = transform->getTransformationType();
820
821                         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
822                         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
823
824                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
825
826                         //check if transformation has animations
827                         if (animlist_map.find(listid) == animlist_map.end()) continue ; 
828                         else 
829                         {
830                                 //transformation has animations
831                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
832                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
833                                 //all the curves belonging to the current binding
834                                 std::vector<FCurve*> animcurves;
835                                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
836                                         animcurves = curve_map[bindings[j].animation];
837                                         if ( is_matrix )
838                                                 apply_matrix_curves(ob, animcurves, root , node,  transform  );
839                                         else {                          
840                                                 //calculate rnapaths and array index of fcurves according to transformation and animation class
841                                                 Assign_transform_animations(transform, &bindings[j], &animcurves, is_joint, joint_path ); 
842
843                                                 std::vector<FCurve*>::iterator iter;
844                                                 //Add the curves of the current animation to the object
845                                                 for (iter = animcurves.begin(); iter != animcurves.end(); iter++) {
846                                                         FCurve * fcu = *iter;
847                                                         if ((ob->type == OB_ARMATURE))
848                                                                 add_bone_fcurve( ob, node , fcu );
849                                                         else 
850                                                                 BLI_addtail(AnimCurves, fcu);   
851                                                 }
852                                         }
853                                 }
854                         }
855                         if (is_rotation) {
856                                 if (is_joint) 
857                                 {
858                                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
859                                         chan->rotmode = ROT_MODE_EUL;
860                                 }
861                                 else 
862                                 {
863                                         ob->rotmode = ROT_MODE_EUL;
864                                 }
865                         }
866                 }
867         }
868
869         if ((animType->light) != 0)
870         {
871                 Lamp * lamp  = (Lamp*) ob->data;
872
873                 if (!lamp->adt || !lamp->adt->action) act = verify_adt_action((ID*)&lamp->id, 1);
874                 else act = lamp->adt->action;
875
876                 ListBase *AnimCurves = &(act->curves);
877                 const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
878
879                 for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
880                         const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
881
882                         if ((animType->light & LIGHT_COLOR) != 0)
883                         {
884                                 const COLLADAFW::Color *col =  &(light->getColor());
885                                 const COLLADAFW::UniqueId& listid = col->getAnimationList();
886
887                                 Assign_color_animations(listid, AnimCurves, "color"); 
888                         }
889                         if ((animType->light & LIGHT_FOA) != 0 )
890                         {
891                                 const COLLADAFW::AnimatableFloat *foa =  &(light->getFallOffAngle());
892                                 const COLLADAFW::UniqueId& listid = foa->getAnimationList();
893
894                                 Assign_float_animations( listid ,AnimCurves, "spot_size"); 
895                         }
896                         if ( (animType->light & LIGHT_FOE) != 0 )
897                         {
898                                 const COLLADAFW::AnimatableFloat *foe =  &(light->getFallOffExponent());
899                                 const COLLADAFW::UniqueId& listid = foe->getAnimationList();
900
901                                 Assign_float_animations( listid ,AnimCurves, "spot_blend"); 
902
903                         }
904                 }
905         }
906
907         if ( (animType->camera) != 0) 
908         {
909                 Camera * camera  = (Camera*) ob->data;
910
911                 if (!camera->adt || !camera->adt->action) act = verify_adt_action((ID*)&camera->id, 1);
912                 else act = camera->adt->action;
913
914                 ListBase *AnimCurves = &(act->curves);
915                 const COLLADAFW::InstanceCameraPointerArray& nodeCameras= node->getInstanceCameras();
916
917                 for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
918                         const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
919
920                         if ((animType->camera & CAMERA_XFOV) != 0 )
921                         {
922                                 const COLLADAFW::AnimatableFloat *xfov =  &(camera->getXFov());
923                                 const COLLADAFW::UniqueId& listid = xfov->getAnimationList();
924                                 Assign_float_animations( listid ,AnimCurves, "lens"); 
925                         }
926
927                         else if ((animType->camera & CAMERA_XMAG) != 0 )
928                         {
929                                 const COLLADAFW::AnimatableFloat *xmag =  &(camera->getXMag());
930                                 const COLLADAFW::UniqueId& listid = xmag->getAnimationList();
931                                 Assign_float_animations( listid ,AnimCurves, "ortho_scale"); 
932                         }
933
934                         if ((animType->camera & CAMERA_ZFAR) != 0 )
935                         {
936                                 const COLLADAFW::AnimatableFloat *zfar =  &(camera->getFarClippingPlane());
937                                 const COLLADAFW::UniqueId& listid = zfar->getAnimationList();
938                                 Assign_float_animations( listid ,AnimCurves, "clip_end"); 
939                         }
940
941                         if ((animType->camera & CAMERA_ZNEAR) != 0 )
942                         {
943                                 const COLLADAFW::AnimatableFloat *znear =  &(camera->getNearClippingPlane());
944                                 const COLLADAFW::UniqueId& listid = znear->getAnimationList();
945                                 Assign_float_animations( listid ,AnimCurves, "clip_start"); 
946                         }
947
948                 }
949         }
950         if ( animType->material != 0){
951                 Material *ma = give_current_material(ob, 1);
952                 if (!ma->adt || !ma->adt->action) act = verify_adt_action((ID*)&ma->id, 1);
953                 else act = ma->adt->action;
954
955                 ListBase *AnimCurves = &(act->curves);
956
957                 const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
958                 for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
959                         const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
960                         for (unsigned int j = 0; j < matBinds.getCount(); j++) {
961                                 const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
962                                 const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
963                                 if (ef != NULL) { /* can be NULL [#28909] */
964                                         const COLLADAFW::CommonEffectPointerArray& commonEffects  =  ef->getCommonEffects();
965                                         COLLADAFW::EffectCommon *efc = commonEffects[0];
966                                         if((animType->material & MATERIAL_SHININESS) != 0){
967                                                 const COLLADAFW::FloatOrParam *shin = &(efc->getShininess());
968                                                 const COLLADAFW::UniqueId& listid =  shin->getAnimationList();
969                                                 Assign_float_animations( listid, AnimCurves , "specular_hardness" );
970                                         }
971
972                                         if((animType->material & MATERIAL_IOR) != 0){
973                                                 const COLLADAFW::FloatOrParam *ior = &(efc->getIndexOfRefraction());
974                                                 const COLLADAFW::UniqueId& listid =  ior->getAnimationList();
975                                                 Assign_float_animations( listid, AnimCurves , "raytrace_transparency.ior" );
976                                         }
977
978                                         if((animType->material & MATERIAL_SPEC_COLOR) != 0){
979                                                 const COLLADAFW::ColorOrTexture *cot = &(efc->getSpecular());
980                                                 const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
981                                                 Assign_color_animations( listid, AnimCurves , "specular_color" );
982                                         }
983
984                                         if((animType->material & MATERIAL_DIFF_COLOR) != 0){
985                                                 const COLLADAFW::ColorOrTexture *cot = &(efc->getDiffuse());
986                                                 const COLLADAFW::UniqueId& listid =  cot->getColor().getAnimationList();
987                                                 Assign_color_animations( listid, AnimCurves , "diffuse_color" );
988                                         }
989                                 }
990                         }
991                 }       
992         }
993 }
994
995
996 //Check if object is animated by checking if animlist_map holds the animlist_id of node transforms
997 AnimationImporter::AnimMix* AnimationImporter::get_animation_type ( const COLLADAFW::Node * node , 
998                                                                                         std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map) 
999 {
1000         AnimMix *types = new AnimMix();
1001
1002         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1003
1004         //for each transformation in node 
1005         for (unsigned int i = 0; i < nodeTransforms.getCount(); i++) {
1006                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1007                 const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1008
1009                 //check if transformation has animations
1010                 if (animlist_map.find(listid) == animlist_map.end()) continue ;
1011                 else 
1012                 {
1013                         types->transform = types->transform|NODE_TRANSFORM;
1014                         break;
1015                 }
1016         }
1017         const COLLADAFW::InstanceLightPointerArray& nodeLights = node->getInstanceLights();
1018
1019         for (unsigned int i = 0; i < nodeLights.getCount(); i++) {
1020                 const COLLADAFW::Light *light = (COLLADAFW::Light *) FW_object_map[nodeLights[i]->getInstanciatedObjectId()];
1021                 types->light = setAnimType(&(light->getColor()),(types->light), LIGHT_COLOR);
1022                 types->light = setAnimType(&(light->getFallOffAngle()),(types->light), LIGHT_FOA);
1023                 types->light = setAnimType(&(light->getFallOffExponent()),(types->light), LIGHT_FOE);
1024
1025                 if ( types->light != 0) break;
1026
1027         }
1028
1029         const COLLADAFW::InstanceCameraPointerArray& nodeCameras = node->getInstanceCameras();
1030         for (unsigned int i = 0; i < nodeCameras.getCount(); i++) {
1031                 const COLLADAFW::Camera *camera = (COLLADAFW::Camera *) FW_object_map[nodeCameras[i]->getInstanciatedObjectId()];
1032
1033                 if ( camera->getCameraType() == COLLADAFW::Camera::PERSPECTIVE )
1034                 {
1035                         types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XFOV);
1036                 }
1037                 else
1038                 {
1039                         types->camera = setAnimType(&(camera->getXMag()),(types->camera), CAMERA_XMAG);
1040                 }
1041                 types->camera = setAnimType(&(camera->getFarClippingPlane()),(types->camera), CAMERA_ZFAR);
1042                 types->camera = setAnimType(&(camera->getNearClippingPlane()),(types->camera), CAMERA_ZNEAR);
1043
1044                 if ( types->camera != 0) break;
1045
1046         }
1047
1048         const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
1049         for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
1050                 const COLLADAFW::MaterialBindingArray& matBinds = nodeGeoms[i]->getMaterialBindings();
1051                 for (unsigned int j = 0; j < matBinds.getCount(); j++) {
1052                         const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
1053                         const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
1054                         if (ef != NULL) { /* can be NULL [#28909] */
1055                                 const COLLADAFW::CommonEffectPointerArray& commonEffects = ef->getCommonEffects();
1056                                 if(!commonEffects.empty()) {
1057                                         COLLADAFW::EffectCommon *efc = commonEffects[0];
1058                                         types->material =  setAnimType(&(efc->getShininess()),(types->material), MATERIAL_SHININESS);
1059                                         types->material =  setAnimType(&(efc->getSpecular().getColor()),(types->material), MATERIAL_SPEC_COLOR);
1060                                         types->material =  setAnimType(&(efc->getDiffuse().getColor()),(types->material), MATERIAL_DIFF_COLOR);
1061                                         // types->material =  setAnimType(&(efc->get()),(types->material), MATERIAL_TRANSPARENCY);
1062                                         types->material =  setAnimType(&(efc->getIndexOfRefraction()),(types->material), MATERIAL_IOR);
1063                                 }
1064                         }
1065                 }
1066         }
1067         return types;
1068 }
1069
1070 int AnimationImporter::setAnimType ( const COLLADAFW::Animatable * prop , int types, int addition)
1071 {
1072         const COLLADAFW::UniqueId& listid =  prop->getAnimationList();
1073         if (animlist_map.find(listid) != animlist_map.end())
1074                 return types|addition;
1075         else return types;
1076 }               
1077
1078 // Is not used anymore.
1079 void AnimationImporter::find_frames_old(std::vector<float> * frames, COLLADAFW::Node * node , COLLADAFW::Transformation::TransformationType tm_type)
1080 {
1081         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1082         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1083         // for each <rotate>, <translate>, etc. there is a separate Transformation
1084         const COLLADAFW::TransformationPointerArray& nodeTransforms = node->getTransformations();
1085
1086         unsigned int i;
1087         // find frames at which to sample plus convert all rotation keys to radians
1088         for (i = 0; i < nodeTransforms.getCount(); i++) {
1089                 COLLADAFW::Transformation *transform = nodeTransforms[i];
1090                 COLLADAFW::Transformation::TransformationType nodeTmType = transform->getTransformationType();
1091
1092
1093                 if (nodeTmType == tm_type) {
1094                         //get animation bindings for the current transformation
1095                         const COLLADAFW::UniqueId& listid = transform->getAnimationList();
1096                         //if transform is animated its animlist must exist.
1097                         if (animlist_map.find(listid) != animlist_map.end()) {
1098                                 
1099                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1100                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1101
1102                                 if (bindings.getCount()) {
1103                                         //for each AnimationBinding get the fcurves which animate the transform
1104                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
1105                                                 std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
1106                                                 bool xyz = ((nodeTmType == COLLADAFW::Transformation::TRANSLATE || nodeTmType == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
1107
1108                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
1109                                                         std::vector<FCurve*>::iterator iter;
1110
1111                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
1112                                                                 FCurve *fcu = *iter;
1113
1114                                                                 //if transform is rotation the fcurves values must be turned in to radian.
1115                                                                 if (is_rotation)
1116                                                                         fcurve_deg_to_rad(fcu);
1117
1118                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
1119                                                                         //get frame value from bezTriple
1120                                                                         float fra = fcu->bezt[k].vec[1][0];
1121                                                                         //if frame already not added add frame to frames
1122                                                                         if (std::find(frames->begin(), frames->end(), fra) == frames->end())
1123                                                                                 frames->push_back(fra);
1124                                                                 }
1125                                                         }
1126                                                 }
1127                                                 else {
1128                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
1129                                                 }
1130                                         }
1131                                 }
1132                         }
1133                 }
1134         }
1135 }
1136
1137
1138
1139 // prerequisites:
1140 // animlist_map - map animlist id -> animlist
1141 // curve_map - map anim id -> curve(s)
1142 Object *AnimationImporter::translate_animation_OLD(COLLADAFW::Node *node,
1143                                                         std::map<COLLADAFW::UniqueId, Object*>& object_map,
1144                                                         std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
1145                                                         COLLADAFW::Transformation::TransformationType tm_type,
1146                                                         Object *par_job)
1147 {
1148         
1149         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
1150         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
1151         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
1152         
1153         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
1154         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
1155         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
1156         if (!ob) {
1157                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
1158                 return NULL;
1159         }
1160
1161         // frames at which to sample
1162         std::vector<float> frames;
1163         
1164         find_frames_old(&frames, node , tm_type);
1165         
1166         unsigned int i;
1167         
1168         float irest_dae[4][4];
1169         float rest[4][4], irest[4][4];
1170
1171         if (is_joint) {
1172                 get_joint_rest_mat(irest_dae, root, node);
1173                 invert_m4(irest_dae);
1174
1175                 Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
1176                 if (!bone) {
1177                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
1178                         return NULL;
1179                 }
1180
1181                 unit_m4(rest);
1182                 copy_m4_m4(rest, bone->arm_mat);
1183                 invert_m4_m4(irest, rest);
1184         }
1185
1186         Object *job = NULL;
1187
1188 #ifdef ARMATURE_TEST
1189         FCurve *job_curves[10];
1190         job = get_joint_object(root, node, par_job);
1191 #endif
1192
1193         if (frames.size() == 0)
1194                 return job;
1195
1196         std::sort(frames.begin(), frames.end());
1197
1198         const char *tm_str = NULL;
1199         switch (tm_type) {
1200         case COLLADAFW::Transformation::ROTATE:
1201                 tm_str = "rotation_quaternion";
1202                 break;
1203         case COLLADAFW::Transformation::SCALE:
1204                 tm_str = "scale";
1205                 break;
1206         case COLLADAFW::Transformation::TRANSLATE:
1207                 tm_str = "location";
1208                 break;
1209         case COLLADAFW::Transformation::MATRIX:
1210                 break;
1211         default:
1212                 return job;
1213         }
1214
1215         char rna_path[200];
1216         char joint_path[200];
1217
1218         if (is_joint)
1219                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
1220
1221         // new curves
1222         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
1223         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
1224
1225         for (i = 0; i < totcu; i++) {
1226
1227                 int axis = i;
1228
1229                 if (is_matrix) {
1230                         if (i < 4) {
1231                                 tm_str = "rotation_quaternion";
1232                                 axis = i;
1233                         }
1234                         else if (i < 7) {
1235                                 tm_str = "location";
1236                                 axis = i - 4;
1237                         }
1238                         else {
1239                                 tm_str = "scale";
1240                                 axis = i - 7;
1241                         }
1242                 }
1243
1244                 if (is_joint)
1245                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
1246                 else
1247                         BLI_strncpy(rna_path, tm_str, sizeof(rna_path));
1248                 newcu[i] = create_fcurve(axis, rna_path);
1249
1250 #ifdef ARMATURE_TEST
1251                 if (is_joint)
1252                         job_curves[i] = create_fcurve(axis, tm_str);
1253 #endif
1254         }
1255
1256         std::vector<float>::iterator it;
1257
1258         // sample values at each frame
1259         for (it = frames.begin(); it != frames.end(); it++) {
1260                 float fra = *it;
1261
1262                 float mat[4][4];
1263                 float matfra[4][4];
1264
1265                 unit_m4(matfra);
1266
1267                 // calc object-space mat
1268                 evaluate_transform_at_frame(matfra, node, fra);
1269
1270                 // for joints, we need a special matrix
1271                 if (is_joint) {
1272                         // special matrix: iR * M * iR_dae * R
1273                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
1274                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
1275                         float temp[4][4], par[4][4];
1276
1277                         // calc M
1278                         calc_joint_parent_mat_rest(par, NULL, root, node);
1279                         mult_m4_m4m4(temp, par, matfra);
1280
1281                         // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
1282
1283                         // calc special matrix
1284                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
1285                 }
1286                 else {
1287                         copy_m4_m4(mat, matfra);
1288                 }
1289
1290                 float val[4], rot[4], loc[3], scale[3];
1291
1292                 switch (tm_type) {
1293                 case COLLADAFW::Transformation::ROTATE:
1294                         mat4_to_quat(val, mat);
1295                         break;
1296                 case COLLADAFW::Transformation::SCALE:
1297                         mat4_to_size(val, mat);
1298                         break;
1299                 case COLLADAFW::Transformation::TRANSLATE:
1300                         copy_v3_v3(val, mat[3]);
1301                         break;
1302                 case COLLADAFW::Transformation::MATRIX:
1303                         mat4_to_quat(rot, mat);
1304                         copy_v3_v3(loc, mat[3]);
1305                         mat4_to_size(scale, mat);
1306                         break;
1307                 default:
1308                         break;
1309                 }
1310
1311                 // add keys
1312                 for (i = 0; i < totcu; i++) {
1313                         if (is_matrix) {
1314                                 if (i < 4)
1315                                         add_bezt(newcu[i], fra, rot[i]);
1316                                 else if (i < 7)
1317                                         add_bezt(newcu[i], fra, loc[i - 4]);
1318                                 else
1319                                         add_bezt(newcu[i], fra, scale[i - 7]);
1320                         }
1321                         else {
1322                                 add_bezt(newcu[i], fra, val[i]);
1323                         }
1324                 }
1325
1326 #ifdef ARMATURE_TEST
1327                 if (is_joint) {
1328                         switch (tm_type) {
1329                         case COLLADAFW::Transformation::ROTATE:
1330                                 mat4_to_quat(val, matfra);
1331                                 break;
1332                         case COLLADAFW::Transformation::SCALE:
1333                                 mat4_to_size(val, matfra);
1334                                 break;
1335                         case COLLADAFW::Transformation::TRANSLATE:
1336                                 copy_v3_v3(val, matfra[3]);
1337                                 break;
1338                         case MATRIX:
1339                                 mat4_to_quat(rot, matfra);
1340                                 copy_v3_v3(loc, matfra[3]);
1341                                 mat4_to_size(scale, matfra);
1342                                 break;
1343                         default:
1344                                 break;
1345                         }
1346
1347                         for (i = 0; i < totcu; i++) {
1348                                 if (is_matrix) {
1349                                         if (i < 4)
1350                                                 add_bezt(job_curves[i], fra, rot[i]);
1351                                         else if (i < 7)
1352                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
1353                                         else
1354                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
1355                                 }
1356                                 else {
1357                                         add_bezt(job_curves[i], fra, val[i]);
1358                                 }
1359                         }
1360                 }
1361 #endif
1362         }
1363
1364         verify_adt_action((ID*)&ob->id, 1);
1365
1366         ListBase *curves = &ob->adt->action->curves;
1367
1368         // add curves
1369         for (i = 0; i < totcu; i++) {
1370                 if (is_joint)
1371                         add_bone_fcurve(ob, node, newcu[i]);
1372                 else
1373                         BLI_addtail(curves, newcu[i]);
1374
1375 #ifdef ARMATURE_TEST
1376                 if (is_joint)
1377                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
1378 #endif
1379         }
1380
1381         if (is_rotation || is_matrix) {
1382                 if (is_joint) {
1383                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
1384                         chan->rotmode = ROT_MODE_QUAT;
1385                 }
1386                 else {
1387                         ob->rotmode = ROT_MODE_QUAT;
1388                 }
1389         }
1390
1391         return job;
1392 }
1393
1394 // internal, better make it private
1395 // warning: evaluates only rotation and only assigns matrix transforms now
1396 // prerequisites: animlist_map, curve_map
1397 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
1398 {
1399         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
1400
1401         unit_m4(mat);
1402
1403         for (unsigned int i = 0; i < tms.getCount(); i++) {
1404                 COLLADAFW::Transformation *tm = tms[i];
1405                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1406                 float m[4][4];
1407
1408                 unit_m4(m);
1409                 if ( type != COLLADAFW::Transformation::MATRIX )
1410                         continue;
1411
1412                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
1413                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
1414                         /*switch (type) {
1415                         case COLLADAFW::Transformation::ROTATE:
1416                                 dae_rotate_to_mat4(tm, m);
1417                                 break;
1418                         case COLLADAFW::Transformation::TRANSLATE:
1419                                 dae_translate_to_mat4(tm, m);
1420                                 break;
1421                         case COLLADAFW::Transformation::SCALE:
1422                                 dae_scale_to_mat4(tm, m);
1423                                 break;
1424                         case COLLADAFW::Transformation::MATRIX:
1425                                 dae_matrix_to_mat4(tm, m);
1426                                 break;
1427                         default:
1428                                 fprintf(stderr, "unsupported transformation type %d\n", type);
1429                         }*/
1430                         dae_matrix_to_mat4(tm, m);
1431                         
1432                 }
1433
1434                 float temp[4][4];
1435                 copy_m4_m4(temp, mat);
1436
1437                 mult_m4_m4m4(mat, temp, m);
1438         }
1439 }
1440
1441 // return true to indicate that mat contains a sane value
1442 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
1443 {
1444         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
1445         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
1446
1447         if (type != COLLADAFW::Transformation::ROTATE &&
1448                 type != COLLADAFW::Transformation::SCALE &&
1449                 type != COLLADAFW::Transformation::TRANSLATE &&
1450                 type != COLLADAFW::Transformation::MATRIX) {
1451                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
1452                 return false;
1453         }
1454
1455         if (animlist_map.find(listid) == animlist_map.end())
1456                 return false;
1457
1458         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
1459         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
1460
1461         if (bindings.getCount()) {
1462                 float vec[3];
1463
1464                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
1465                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
1466
1467                 if (is_scale)
1468                         dae_scale_to_v3(tm, vec);
1469                 else if (is_translate)
1470                         dae_translate_to_v3(tm, vec);
1471
1472                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
1473                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
1474                         std::vector<FCurve*>& curves = curve_map[binding.animation];
1475                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
1476                         char path[100];
1477
1478                         switch (type) {
1479                         case COLLADAFW::Transformation::ROTATE:
1480                                 BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
1481                                 break;
1482                         case COLLADAFW::Transformation::SCALE:
1483                                 BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
1484                                 break;
1485                         case COLLADAFW::Transformation::TRANSLATE:
1486                                 BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
1487                                 break;
1488                         case COLLADAFW::Transformation::MATRIX:
1489                                 BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
1490                                 break;
1491                         default:
1492                                 break;
1493                         }
1494
1495                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
1496                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
1497                                 //continue;
1498                         }
1499
1500                         if (type == COLLADAFW::Transformation::ROTATE) {
1501                                 if (curves.size() != 1) {
1502                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
1503                                         return false;
1504                                 }
1505
1506                                 // TODO support other animclasses
1507                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
1508                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1509                                         return false;
1510                                 }
1511
1512                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
1513                                 float ax[3] = {axis[0], axis[1], axis[2]};
1514                                 float angle = evaluate_fcurve(curves[0], fra);
1515                                 axis_angle_to_mat4(mat, ax, angle);
1516
1517                                 return true;
1518                         }
1519                         else if (is_scale || is_translate) {
1520                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
1521
1522                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
1523                                         if (is_xyz)
1524                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
1525                                         else
1526                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
1527                                         return false;
1528                                 }
1529                                 
1530                                 switch (animclass) {
1531                                 case COLLADAFW::AnimationList::POSITION_X:
1532                                         vec[0] = evaluate_fcurve(curves[0], fra);
1533                                         break;
1534                                 case COLLADAFW::AnimationList::POSITION_Y:
1535                                         vec[1] = evaluate_fcurve(curves[0], fra);
1536                                         break;
1537                                 case COLLADAFW::AnimationList::POSITION_Z:
1538                                         vec[2] = evaluate_fcurve(curves[0], fra);
1539                                         break;
1540                                 case COLLADAFW::AnimationList::POSITION_XYZ:
1541                                         vec[0] = evaluate_fcurve(curves[0], fra);
1542                                         vec[1] = evaluate_fcurve(curves[1], fra);
1543                                         vec[2] = evaluate_fcurve(curves[2], fra);
1544                                         break;
1545                                 default:
1546                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
1547                                         break;
1548                                 }
1549                         }
1550                         else if (type == COLLADAFW::Transformation::MATRIX) {
1551                                 // for now, of matrix animation, support only the case when all values are packed into one animation
1552                                 if (curves.size() != 16) {
1553                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
1554                                         return false;
1555                                 }
1556
1557                                 COLLADABU::Math::Matrix4 matrix;
1558                                 int i = 0, j = 0;
1559
1560                                 for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++) {
1561                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
1562                                         j++;
1563                                         if (j == 4) {
1564                                                 i++;
1565                                                 j = 0;
1566                                         }
1567                                         unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), *it), unused_curves.end());
1568                                 }
1569
1570                                 COLLADAFW::Matrix tm(matrix);
1571                                 dae_matrix_to_mat4(&tm, mat);
1572
1573                                 std::vector<FCurve*>::iterator it;
1574
1575                                 return true;
1576                         }
1577                 }
1578
1579                 if (is_scale)
1580                         size_to_mat4(mat, vec);
1581                 else
1582                         copy_v3_v3(mat[3], vec);
1583
1584                 return is_scale || is_translate;
1585         }
1586
1587         return false;
1588 }
1589
1590 // gives a world-space mat of joint at rest position
1591 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1592 {
1593         // if bind mat is not available,
1594         // use "current" node transform, i.e. all those tms listed inside <node>
1595         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1596                 float par[4][4], m[4][4];
1597
1598                 calc_joint_parent_mat_rest(par, NULL, root, node);
1599                 get_node_mat(m, node, NULL, NULL);
1600                 mult_m4_m4m4(mat, par, m);
1601         }
1602 }
1603
1604 // gives a world-space mat, end's mat not included
1605 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1606 {
1607         float m[4][4];
1608
1609         if (node == end) {
1610                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1611                 return true;
1612         }
1613
1614         // use bind matrix if available or calc "current" world mat
1615         if (!armature_importer->get_joint_bind_mat(m, node)) {
1616                 if (par) {
1617                         float temp[4][4];
1618                         get_node_mat(temp, node, NULL, NULL);
1619                         mult_m4_m4m4(m, par, temp);
1620                 }
1621                 else {
1622                         get_node_mat(m, node, NULL, NULL);
1623                 }
1624         }
1625
1626         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1627         for (unsigned int i = 0; i < children.getCount(); i++) {
1628                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1629                         return true;
1630         }
1631
1632         return false;
1633 }
1634
1635 #ifdef ARMATURE_TEST
1636 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1637 {
1638         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1639                 Object *job = add_object(scene, OB_EMPTY);
1640
1641                 rename_id((ID*)&job->id, (char*)get_joint_name(node));
1642
1643                 job->lay = object_in_scene(job, scene)->lay = 2;
1644
1645                 mul_v3_fl(job->size, 0.5f);
1646                 job->recalc |= OB_RECALC_OB;
1647
1648                 verify_adt_action((ID*)&job->id, 1);
1649
1650                 job->rotmode = ROT_MODE_QUAT;
1651
1652                 float mat[4][4];
1653                 get_joint_rest_mat(mat, root, node);
1654
1655                 if (par_job) {
1656                         float temp[4][4], ipar[4][4];
1657                         invert_m4_m4(ipar, par_job->obmat);
1658                         copy_m4_m4(temp, mat);
1659                         mult_m4_m4m4(mat, ipar, temp);
1660                 }
1661
1662                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1663
1664                 if (par_job) {
1665                         job->parent = par_job;
1666
1667                         par_job->recalc |= OB_RECALC_OB;
1668                         job->parsubstr[0] = 0;
1669                 }
1670
1671                 where_is_object(scene, job);
1672
1673                 // after parenting and layer change
1674                 DAG_scene_sort(CTX_data_main(C), scene);
1675
1676                 joint_objects[node->getUniqueId()] = job;
1677         }
1678
1679         return joint_objects[node->getUniqueId()];
1680 }
1681 #endif
1682
1683 #if 0
1684 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1685 // mat must be identity on enter, node must be root
1686 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1687 {
1688         float m[4][4];
1689         if (par) {
1690                 float temp[4][4];
1691                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1692                 mult_m4_m4m4(m, par, temp);
1693         }
1694         else {
1695                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1696         }
1697
1698         if (node == end) {
1699                 copy_m4_m4(mat, m);
1700                 return true;
1701         }
1702         else {
1703                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1704                 for (int i = 0; i < children.getCount(); i++) {
1705                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1706                                 return true;
1707                 }
1708         }
1709
1710         return false;
1711 }
1712 #endif
1713
1714 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1715 {
1716         const char *bone_name = bc_get_joint_name(node);
1717         bAction *act = ob->adt->action;
1718                         
1719         /* try to find group */
1720         bActionGroup *grp = action_groups_find_named(act, bone_name);
1721
1722         /* no matching groups, so add one */
1723         if (grp == NULL) {
1724                 /* Add a new group, and make it active */
1725                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1726                                         
1727                 grp->flag = AGRP_SELECTED;
1728                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1729                                         
1730                 BLI_addtail(&act->groups, grp);
1731                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1732         }
1733                                 
1734         /* add F-Curve to group */
1735         action_groups_add_channel(act, grp, fcu);
1736 }
1737
1738 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1739 {
1740         //float fps = (float)FPS;
1741         BezTriple bez;
1742         memset(&bez, 0, sizeof(BezTriple));
1743         bez.vec[1][0] = fra ;
1744         bez.vec[1][1] = value;
1745         bez.ipo = BEZT_IPO_LIN ;/* use default interpolation mode here... */
1746         bez.f1 = bez.f2 = bez.f3 = SELECT;
1747         bez.h1 = bez.h2 = HD_AUTO;
1748         insert_bezt_fcurve(fcu, &bez, 0);
1749         calchandles_fcurve(fcu);
1750 }
1751