merge from trunk #37722
[blender-staging.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.
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
54 #include <algorithm>
55
56 // first try node name, if not available (since is optional), fall back to original id
57 template<class T>
58 static const char *bc_get_joint_name(T *node)
59 {
60         const std::string& id = node->getName();
61         return id.size() ? id.c_str() : node->getOriginalId().c_str();
62 }
63
64 FCurve *AnimationImporter::create_fcurve(int array_index, const char *rna_path)
65 {
66         FCurve *fcu = (FCurve*)MEM_callocN(sizeof(FCurve), "FCurve");
67         
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         // COLLADAFW::FloatOrDoubleArray& intan = curve->getInTangentValues();
93         // COLLADAFW::FloatOrDoubleArray& outtan = curve->getOutTangentValues();
94         float fps = (float)FPS;
95         size_t dim = curve->getOutDimension();
96         unsigned int i;
97
98         std::vector<FCurve*>& fcurves = curve_map[curve->getUniqueId()];
99
100         switch (dim) {
101         case 1: // X, Y, Z or angle
102         case 3: // XYZ
103         case 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                                         // intangent
119                                         // bez.vec[0][0] = get_float_value(intan, j * 6 + i + i) * fps;
120                                         // bez.vec[0][1] = get_float_value(intan, j * 6 + i + i + 1);
121
122                                         // input, output
123                                         bez.vec[1][0] = bc_get_float_value(input, j) * fps; 
124                                         bez.vec[1][1] = bc_get_float_value(output, j * dim + i);
125
126                                         // outtangent
127                                         // bez.vec[2][0] = get_float_value(outtan, j * 6 + i + i) * fps;
128                                         // bez.vec[2][1] = get_float_value(outtan, j * 6 + i + i + 1);
129
130                                         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
131                                         bez.f1 = bez.f2 = bez.f3 = SELECT;
132                                         bez.h1 = bez.h2 = HD_AUTO;
133                                         insert_bezt_fcurve(fcu, &bez, 0);
134                                 }
135
136                                 calchandles_fcurve(fcu);
137
138                                 fcurves.push_back(fcu);
139                         }
140                 }
141                 break;
142         default:
143                 fprintf(stderr, "Output dimension of %d is not yet supported (animation id = %s)\n", (int)dim, curve->getOriginalId().c_str());
144         }
145
146         for (std::vector<FCurve*>::iterator it = fcurves.begin(); it != fcurves.end(); it++)
147                 unused_curves.push_back(*it);
148 }
149
150 void AnimationImporter::fcurve_deg_to_rad(FCurve *cu)
151 {
152         for (unsigned int i = 0; i < cu->totvert; i++) {
153                 // TODO convert handles too
154                 cu->bezt[i].vec[1][1] *= M_PI / 180.0f;
155         }
156 }
157
158 void AnimationImporter::add_fcurves_to_object(Object *ob, std::vector<FCurve*>& curves, char *rna_path, int array_index, Animation *animated)
159 {
160         bAction *act;
161         
162         if (!ob->adt || !ob->adt->action) act = verify_adt_action((ID*)&ob->id, 1);
163         else act = ob->adt->action;
164         
165         std::vector<FCurve*>::iterator it;
166         int i;
167
168 #if 0
169         char *p = strstr(rna_path, "rotation_euler");
170         bool is_rotation = p && *(p + strlen("rotation_euler")) == '\0';
171
172         // convert degrees to radians for rotation
173         if (is_rotation)
174                 fcurve_deg_to_rad(fcu);
175 #endif
176         
177         for (it = curves.begin(), i = 0; it != curves.end(); it++, i++) {
178                 FCurve *fcu = *it;
179                 fcu->rna_path = BLI_strdupn(rna_path, strlen(rna_path));
180                 
181                 if (array_index == -1) fcu->array_index = i;
182                 else fcu->array_index = array_index;
183         
184                 if (ob->type == OB_ARMATURE) {
185                         bActionGroup *grp = NULL;
186                         const char *bone_name = bc_get_joint_name(animated->node);
187                         
188                         if (bone_name) {
189                                 /* try to find group */
190                                 grp = action_groups_find_named(act, bone_name);
191                                 
192                                 /* no matching groups, so add one */
193                                 if (grp == NULL) {
194                                         /* Add a new group, and make it active */
195                                         grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
196                                         
197                                         grp->flag = AGRP_SELECTED;
198                                         BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
199                                         
200                                         BLI_addtail(&act->groups, grp);
201                                         BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
202                                 }
203                                 
204                                 /* add F-Curve to group */
205                                 action_groups_add_channel(act, grp, fcu);
206                                 
207                         }
208 #if 0
209                         if (is_rotation) {
210                                 fcurves_actionGroup_map[grp].push_back(fcu);
211                         }
212 #endif
213                 }
214                 else {
215                         BLI_addtail(&act->curves, fcu);
216                 }
217
218                 // curve is used, so remove it from unused_curves
219                 unused_curves.erase(std::remove(unused_curves.begin(), unused_curves.end(), fcu), unused_curves.end());
220         }
221 }
222
223 AnimationImporter::AnimationImporter(UnitConverter *conv, ArmatureImporter *arm, Scene *scene) :
224                 TransformReader(conv), armature_importer(arm), scene(scene) { }
225
226 AnimationImporter::~AnimationImporter()
227 {
228         // free unused FCurves
229         for (std::vector<FCurve*>::iterator it = unused_curves.begin(); it != unused_curves.end(); it++)
230                 free_fcurve(*it);
231
232         if (unused_curves.size())
233                 fprintf(stderr, "removed %d unused curves\n", (int)unused_curves.size());
234 }
235
236 bool AnimationImporter::write_animation(const COLLADAFW::Animation* anim) 
237 {
238         if (anim->getAnimationType() == COLLADAFW::Animation::ANIMATION_CURVE) {
239                 COLLADAFW::AnimationCurve *curve = (COLLADAFW::AnimationCurve*)anim;
240                 
241                 // XXX Don't know if it's necessary
242                 // Should we check outPhysicalDimension?
243                 if (curve->getInPhysicalDimension() != COLLADAFW::PHYSICAL_DIMENSION_TIME) {
244                         fprintf(stderr, "Inputs physical dimension is not time. \n");
245                         return true;
246                 }
247
248                 // a curve can have mixed interpolation type,
249                 // in this case curve->getInterpolationTypes returns a list of interpolation types per key
250                 COLLADAFW::AnimationCurve::InterpolationType interp = curve->getInterpolationType();
251
252                 if (interp != COLLADAFW::AnimationCurve::INTERPOLATION_MIXED) {
253                         switch (interp) {
254                         case COLLADAFW::AnimationCurve::INTERPOLATION_LINEAR:
255                         case COLLADAFW::AnimationCurve::INTERPOLATION_BEZIER:
256                                 animation_to_fcurves(curve);
257                                 break;
258                         default:
259                                 // TODO there're also CARDINAL, HERMITE, BSPLINE and STEP types
260                                 fprintf(stderr, "CARDINAL, HERMITE, BSPLINE and STEP anim interpolation types not supported yet.\n");
261                                 break;
262                         }
263                 }
264                 else {
265                         // not supported yet
266                         fprintf(stderr, "MIXED anim interpolation type is not supported yet.\n");
267                 }
268         }
269         else {
270                 fprintf(stderr, "FORMULA animation type is not supported yet.\n");
271         }
272         
273         return true;
274 }
275         
276 // called on post-process stage after writeVisualScenes
277 bool AnimationImporter::write_animation_list(const COLLADAFW::AnimationList* animlist) 
278 {
279         const COLLADAFW::UniqueId& animlist_id = animlist->getUniqueId();
280
281         animlist_map[animlist_id] = animlist;
282
283 #if 0
284         // should not happen
285         if (uid_animated_map.find(animlist_id) == uid_animated_map.end()) {
286                 return true;
287         }
288
289         // for bones rna_path is like: pose.bones["bone-name"].rotation
290         
291         // what does this AnimationList animate?
292         Animation& animated = uid_animated_map[animlist_id];
293         Object *ob = animated.ob;
294
295         char rna_path[100];
296         char joint_path[100];
297         bool is_joint = false;
298
299         // if ob is NULL, it should be a JOINT
300         if (!ob) {
301                 ob = armature_importer->get_armature_for_joint(animated.node);
302
303                 if (!ob) {
304                         fprintf(stderr, "Cannot find armature for node %s\n", get_joint_name(animated.node));
305                         return true;
306                 }
307
308                 armature_importer->get_rna_path_for_joint(animated.node, joint_path, sizeof(joint_path));
309
310                 is_joint = true;
311         }
312         
313         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
314
315         switch (animated.tm->getTransformationType()) {
316         case COLLADAFW::Transformation::TRANSLATE:
317         case COLLADAFW::Transformation::SCALE:
318                 {
319                         bool loc = animated.tm->getTransformationType() == COLLADAFW::Transformation::TRANSLATE;
320                         if (is_joint)
321                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, loc ? "location" : "scale");
322                         else
323                                 BLI_strncpy(rna_path, loc ? "location" : "scale", sizeof(rna_path));
324
325                         for (int i = 0; i < bindings.getCount(); i++) {
326                                 const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
327                                 COLLADAFW::UniqueId anim_uid = binding.animation;
328
329                                 if (curve_map.find(anim_uid) == curve_map.end()) {
330                                         fprintf(stderr, "Cannot find FCurve by animation UID.\n");
331                                         continue;
332                                 }
333
334                                 std::vector<FCurve*>& fcurves = curve_map[anim_uid];
335                                 
336                                 switch (binding.animationClass) {
337                                 case COLLADAFW::AnimationList::POSITION_X:
338                                         add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
339                                         break;
340                                 case COLLADAFW::AnimationList::POSITION_Y:
341                                         add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
342                                         break;
343                                 case COLLADAFW::AnimationList::POSITION_Z:
344                                         add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
345                                         break;
346                                 case COLLADAFW::AnimationList::POSITION_XYZ:
347                                         add_fcurves_to_object(ob, fcurves, rna_path, -1, &animated);
348                                         break;
349                                 default:
350                                         fprintf(stderr, "AnimationClass %d is not supported for %s.\n",
351                                                         binding.animationClass, loc ? "TRANSLATE" : "SCALE");
352                                 }
353                         }
354                 }
355                 break;
356         case COLLADAFW::Transformation::ROTATE:
357                 {
358                         if (is_joint)
359                                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_euler", joint_path);
360                         else
361                                 BLI_strncpy(rna_path, "rotation_euler", sizeof(rna_path));
362
363                         COLLADAFW::Rotate* rot = (COLLADAFW::Rotate*)animated.tm;
364                         COLLADABU::Math::Vector3& axis = rot->getRotationAxis();
365                         
366                         for (int i = 0; i < bindings.getCount(); i++) {
367                                 const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[i];
368                                 COLLADAFW::UniqueId anim_uid = binding.animation;
369
370                                 if (curve_map.find(anim_uid) == curve_map.end()) {
371                                         fprintf(stderr, "Cannot find FCurve by animation UID.\n");
372                                         continue;
373                                 }
374
375                                 std::vector<FCurve*>& fcurves = curve_map[anim_uid];
376
377                                 switch (binding.animationClass) {
378                                 case COLLADAFW::AnimationList::ANGLE:
379                                         if (COLLADABU::Math::Vector3::UNIT_X == axis) {
380                                                 add_fcurves_to_object(ob, fcurves, rna_path, 0, &animated);
381                                         }
382                                         else if (COLLADABU::Math::Vector3::UNIT_Y == axis) {
383                                                 add_fcurves_to_object(ob, fcurves, rna_path, 1, &animated);
384                                         }
385                                         else if (COLLADABU::Math::Vector3::UNIT_Z == axis) {
386                                                 add_fcurves_to_object(ob, fcurves, rna_path, 2, &animated);
387                                         }
388                                         break;
389                                 case COLLADAFW::AnimationList::AXISANGLE:
390                                         // TODO convert axis-angle to quat? or XYZ?
391                                 default:
392                                         fprintf(stderr, "AnimationClass %d is not supported for ROTATE transformation.\n",
393                                                         binding.animationClass);
394                                 }
395                         }
396                 }
397                 break;
398         case COLLADAFW::Transformation::MATRIX:
399         case COLLADAFW::Transformation::SKEW:
400         case COLLADAFW::Transformation::LOOKAT:
401                 fprintf(stderr, "Animation of MATRIX, SKEW and LOOKAT transformations is not supported yet.\n");
402                 break;
403         }
404 #endif
405         
406         return true;
407 }
408
409 // \todo refactor read_node_transform to not automatically apply anything,
410 // but rather return the transform matrix, so caller can do with it what is
411 // necessary. Same for \ref get_node_mat
412 void AnimationImporter::read_node_transform(COLLADAFW::Node *node, Object *ob)
413 {
414         float mat[4][4];
415         TransformReader::get_node_mat(mat, node, &uid_animated_map, ob);
416         if (ob) {
417                 copy_m4_m4(ob->obmat, mat);
418                 object_apply_mat4(ob, ob->obmat, 0, 0);
419         }
420 }
421
422 #if 0
423 virtual void AnimationImporter::change_eul_to_quat(Object *ob, bAction *act)
424 {
425         bActionGroup *grp;
426         int i;
427         
428         for (grp = (bActionGroup*)act->groups.first; grp; grp = grp->next) {
429
430                 FCurve *eulcu[3] = {NULL, NULL, NULL};
431                 
432                 if (fcurves_actionGroup_map.find(grp) == fcurves_actionGroup_map.end())
433                         continue;
434
435                 std::vector<FCurve*> &rot_fcurves = fcurves_actionGroup_map[grp];
436                 
437                 if (rot_fcurves.size() > 3) continue;
438
439                 for (i = 0; i < rot_fcurves.size(); i++)
440                         eulcu[rot_fcurves[i]->array_index] = rot_fcurves[i];
441
442                 char joint_path[100];
443                 char rna_path[100];
444
445                 BLI_snprintf(joint_path, sizeof(joint_path), "pose.bones[\"%s\"]", grp->name);
446                 BLI_snprintf(rna_path, sizeof(rna_path), "%s.rotation_quaternion", joint_path);
447
448                 FCurve *quatcu[4] = {
449                         create_fcurve(0, rna_path),
450                         create_fcurve(1, rna_path),
451                         create_fcurve(2, rna_path),
452                         create_fcurve(3, rna_path)
453                 };
454
455                 bPoseChannel *chan = get_pose_channel(ob->pose, grp->name);
456
457                 float m4[4][4], irest[3][3];
458                 invert_m4_m4(m4, chan->bone->arm_mat);
459                 copy_m3_m4(irest, m4);
460
461                 for (i = 0; i < 3; i++) {
462
463                         FCurve *cu = eulcu[i];
464
465                         if (!cu) continue;
466
467                         for (int j = 0; j < cu->totvert; j++) {
468                                 float frame = cu->bezt[j].vec[1][0];
469
470                                 float eul[3] = {
471                                         eulcu[0] ? evaluate_fcurve(eulcu[0], frame) : 0.0f,
472                                         eulcu[1] ? evaluate_fcurve(eulcu[1], frame) : 0.0f,
473                                         eulcu[2] ? evaluate_fcurve(eulcu[2], frame) : 0.0f
474                                 };
475
476                                 // make eul relative to bone rest pose
477                                 float rot[3][3], rel[3][3], quat[4];
478
479                                 /*eul_to_mat3(rot, eul);
480
481                                 mul_m3_m3m3(rel, irest, rot);
482
483                                 mat3_to_quat(quat, rel);
484                                 */
485
486                                 eul_to_quat(quat, eul);
487
488                                 for (int k = 0; k < 4; k++)
489                                         create_bezt(quatcu[k], frame, quat[k]);
490                         }
491                 }
492
493                 // now replace old Euler curves
494
495                 for (i = 0; i < 3; i++) {
496                         if (!eulcu[i]) continue;
497
498                         action_groups_remove_channel(act, eulcu[i]);
499                         free_fcurve(eulcu[i]);
500                 }
501
502                 chan->rotmode = ROT_MODE_QUAT;
503
504                 for (i = 0; i < 4; i++)
505                         action_groups_add_channel(act, grp, quatcu[i]);
506         }
507
508         bPoseChannel *pchan;
509         for (pchan = (bPoseChannel*)ob->pose->chanbase.first; pchan; pchan = pchan->next) {
510                 pchan->rotmode = ROT_MODE_QUAT;
511         }
512 }
513 #endif
514
515 // prerequisites:
516 // animlist_map - map animlist id -> animlist
517 // curve_map - map anim id -> curve(s)
518 Object *AnimationImporter::translate_animation(COLLADAFW::Node *node,
519                                                         std::map<COLLADAFW::UniqueId, Object*>& object_map,
520                                                         std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
521                                                         COLLADAFW::Transformation::TransformationType tm_type,
522                                                         Object *par_job)
523 {
524         bool is_rotation = tm_type == COLLADAFW::Transformation::ROTATE;
525         bool is_matrix = tm_type == COLLADAFW::Transformation::MATRIX;
526         bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
527
528         COLLADAFW::Node *root = root_map.find(node->getUniqueId()) == root_map.end() ? node : root_map[node->getUniqueId()];
529         Object *ob = is_joint ? armature_importer->get_armature_for_joint(node) : object_map[node->getUniqueId()];
530         const char *bone_name = is_joint ? bc_get_joint_name(node) : NULL;
531
532         if (!ob) {
533                 fprintf(stderr, "cannot find Object for Node with id=\"%s\"\n", node->getOriginalId().c_str());
534                 return NULL;
535         }
536
537         // frames at which to sample
538         std::vector<float> frames;
539
540         // for each <rotate>, <translate>, etc. there is a separate Transformation
541         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
542
543         unsigned int i;
544
545         // find frames at which to sample plus convert all rotation keys to radians
546         for (i = 0; i < tms.getCount(); i++) {
547                 COLLADAFW::Transformation *tm = tms[i];
548                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
549
550                 if (type == tm_type) {
551                         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
552
553                         if (animlist_map.find(listid) != animlist_map.end()) {
554                                 const COLLADAFW::AnimationList *animlist = animlist_map[listid];
555                                 const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
556
557                                 if (bindings.getCount()) {
558                                         for (unsigned int j = 0; j < bindings.getCount(); j++) {
559                                                 std::vector<FCurve*>& curves = curve_map[bindings[j].animation];
560                                                 bool xyz = ((type == COLLADAFW::Transformation::TRANSLATE || type == COLLADAFW::Transformation::SCALE) && bindings[j].animationClass == COLLADAFW::AnimationList::POSITION_XYZ);
561
562                                                 if ((!xyz && curves.size() == 1) || (xyz && curves.size() == 3) || is_matrix) {
563                                                         std::vector<FCurve*>::iterator iter;
564
565                                                         for (iter = curves.begin(); iter != curves.end(); iter++) {
566                                                                 FCurve *fcu = *iter;
567
568                                                                 if (is_rotation)
569                                                                         fcurve_deg_to_rad(fcu);
570
571                                                                 for (unsigned int k = 0; k < fcu->totvert; k++) {
572                                                                         float fra = fcu->bezt[k].vec[1][0];
573                                                                         if (std::find(frames.begin(), frames.end(), fra) == frames.end())
574                                                                                 frames.push_back(fra);
575                                                                 }
576                                                         }
577                                                 }
578                                                 else {
579                                                         fprintf(stderr, "expected %d curves, got %d\n", xyz ? 3 : 1, (int)curves.size());
580                                                 }
581                                         }
582                                 }
583                         }
584                 }
585         }
586
587         float irest_dae[4][4];
588         float rest[4][4], irest[4][4];
589
590         if (is_joint) {
591                 get_joint_rest_mat(irest_dae, root, node);
592                 invert_m4(irest_dae);
593
594                 Bone *bone = get_named_bone((bArmature*)ob->data, bone_name);
595                 if (!bone) {
596                         fprintf(stderr, "cannot find bone \"%s\"\n", bone_name);
597                         return NULL;
598                 }
599
600                 unit_m4(rest);
601                 copy_m4_m4(rest, bone->arm_mat);
602                 invert_m4_m4(irest, rest);
603         }
604
605         Object *job = NULL;
606
607 #ifdef ARMATURE_TEST
608         FCurve *job_curves[10];
609         job = get_joint_object(root, node, par_job);
610 #endif
611
612         if (frames.size() == 0)
613                 return job;
614
615         std::sort(frames.begin(), frames.end());
616
617         const char *tm_str = NULL;
618         switch (tm_type) {
619         case COLLADAFW::Transformation::ROTATE:
620                 tm_str = "rotation_quaternion";
621                 break;
622         case COLLADAFW::Transformation::SCALE:
623                 tm_str = "scale";
624                 break;
625         case COLLADAFW::Transformation::TRANSLATE:
626                 tm_str = "location";
627                 break;
628         case COLLADAFW::Transformation::MATRIX:
629                 break;
630         default:
631                 return job;
632         }
633
634         char rna_path[200];
635         char joint_path[200];
636
637         if (is_joint)
638                 armature_importer->get_rna_path_for_joint(node, joint_path, sizeof(joint_path));
639
640         // new curves
641         FCurve *newcu[10]; // if tm_type is matrix, then create 10 curves: 4 rot, 3 loc, 3 scale
642         unsigned int totcu = is_matrix ? 10 : (is_rotation ? 4 : 3);
643
644         for (i = 0; i < totcu; i++) {
645
646                 int axis = i;
647
648                 if (is_matrix) {
649                         if (i < 4) {
650                                 tm_str = "rotation_quaternion";
651                                 axis = i;
652                         }
653                         else if (i < 7) {
654                                 tm_str = "location";
655                                 axis = i - 4;
656                         }
657                         else {
658                                 tm_str = "scale";
659                                 axis = i - 7;
660                         }
661                 }
662
663                 if (is_joint)
664                         BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
665                 else
666                         strcpy(rna_path, tm_str);
667
668                 newcu[i] = create_fcurve(axis, rna_path);
669
670 #ifdef ARMATURE_TEST
671                 if (is_joint)
672                         job_curves[i] = create_fcurve(axis, tm_str);
673 #endif
674         }
675
676         std::vector<float>::iterator it;
677
678         // sample values at each frame
679         for (it = frames.begin(); it != frames.end(); it++) {
680                 float fra = *it;
681
682                 float mat[4][4];
683                 float matfra[4][4];
684
685                 unit_m4(matfra);
686
687                 // calc object-space mat
688                 evaluate_transform_at_frame(matfra, node, fra);
689
690                 // for joints, we need a special matrix
691                 if (is_joint) {
692                         // special matrix: iR * M * iR_dae * R
693                         // where R, iR are bone rest and inverse rest mats in world space (Blender bones),
694                         // iR_dae is joint inverse rest matrix (DAE) and M is an evaluated joint world-space matrix (DAE)
695                         float temp[4][4], par[4][4];
696
697                         // calc M
698                         calc_joint_parent_mat_rest(par, NULL, root, node);
699                         mul_m4_m4m4(temp, matfra, par);
700
701                         // evaluate_joint_world_transform_at_frame(temp, NULL, , node, fra);
702
703                         // calc special matrix
704                         mul_serie_m4(mat, irest, temp, irest_dae, rest, NULL, NULL, NULL, NULL);
705                 }
706                 else {
707                         copy_m4_m4(mat, matfra);
708                 }
709
710                 float val[4], rot[4], loc[3], scale[3];
711
712                 switch (tm_type) {
713                 case COLLADAFW::Transformation::ROTATE:
714                         mat4_to_quat(val, mat);
715                         break;
716                 case COLLADAFW::Transformation::SCALE:
717                         mat4_to_size(val, mat);
718                         break;
719                 case COLLADAFW::Transformation::TRANSLATE:
720                         copy_v3_v3(val, mat[3]);
721                         break;
722                 case COLLADAFW::Transformation::MATRIX:
723                         mat4_to_quat(rot, mat);
724                         copy_v3_v3(loc, mat[3]);
725                         mat4_to_size(scale, mat);
726                         break;
727                 default:
728                         break;
729                 }
730
731                 // add keys
732                 for (i = 0; i < totcu; i++) {
733                         if (is_matrix) {
734                                 if (i < 4)
735                                         add_bezt(newcu[i], fra, rot[i]);
736                                 else if (i < 7)
737                                         add_bezt(newcu[i], fra, loc[i - 4]);
738                                 else
739                                         add_bezt(newcu[i], fra, scale[i - 7]);
740                         }
741                         else {
742                                 add_bezt(newcu[i], fra, val[i]);
743                         }
744                 }
745
746 #ifdef ARMATURE_TEST
747                 if (is_joint) {
748                         switch (tm_type) {
749                         case COLLADAFW::Transformation::ROTATE:
750                                 mat4_to_quat(val, matfra);
751                                 break;
752                         case COLLADAFW::Transformation::SCALE:
753                                 mat4_to_size(val, matfra);
754                                 break;
755                         case COLLADAFW::Transformation::TRANSLATE:
756                                 copy_v3_v3(val, matfra[3]);
757                                 break;
758                         case MATRIX:
759                                 mat4_to_quat(rot, matfra);
760                                 copy_v3_v3(loc, matfra[3]);
761                                 mat4_to_size(scale, matfra);
762                                 break;
763                         default:
764                                 break;
765                         }
766
767                         for (i = 0; i < totcu; i++) {
768                                 if (is_matrix) {
769                                         if (i < 4)
770                                                 add_bezt(job_curves[i], fra, rot[i]);
771                                         else if (i < 7)
772                                                 add_bezt(job_curves[i], fra, loc[i - 4]);
773                                         else
774                                                 add_bezt(job_curves[i], fra, scale[i - 7]);
775                                 }
776                                 else {
777                                         add_bezt(job_curves[i], fra, val[i]);
778                                 }
779                         }
780                 }
781 #endif
782         }
783
784         verify_adt_action((ID*)&ob->id, 1);
785
786         ListBase *curves = &ob->adt->action->curves;
787
788         // add curves
789         for (i = 0; i < totcu; i++) {
790                 if (is_joint)
791                         add_bone_fcurve(ob, node, newcu[i]);
792                 else
793                         BLI_addtail(curves, newcu[i]);
794
795 #ifdef ARMATURE_TEST
796                 if (is_joint)
797                         BLI_addtail(&job->adt->action->curves, job_curves[i]);
798 #endif
799         }
800
801         if (is_rotation || is_matrix) {
802                 if (is_joint) {
803                         bPoseChannel *chan = get_pose_channel(ob->pose, bone_name);
804                         chan->rotmode = ROT_MODE_QUAT;
805                 }
806                 else {
807                         ob->rotmode = ROT_MODE_QUAT;
808                 }
809         }
810
811         return job;
812 }
813
814 // internal, better make it private
815 // warning: evaluates only rotation
816 // prerequisites: animlist_map, curve_map
817 void AnimationImporter::evaluate_transform_at_frame(float mat[4][4], COLLADAFW::Node *node, float fra)
818 {
819         const COLLADAFW::TransformationPointerArray& tms = node->getTransformations();
820
821         unit_m4(mat);
822
823         for (unsigned int i = 0; i < tms.getCount(); i++) {
824                 COLLADAFW::Transformation *tm = tms[i];
825                 COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
826                 float m[4][4];
827
828                 unit_m4(m);
829
830                 std::string nodename = node->getName().size() ? node->getName() : node->getOriginalId();
831                 if (!evaluate_animation(tm, m, fra, nodename.c_str())) {
832                         switch (type) {
833                         case COLLADAFW::Transformation::ROTATE:
834                                 dae_rotate_to_mat4(tm, m);
835                                 break;
836                         case COLLADAFW::Transformation::TRANSLATE:
837                                 dae_translate_to_mat4(tm, m);
838                                 break;
839                         case COLLADAFW::Transformation::SCALE:
840                                 dae_scale_to_mat4(tm, m);
841                                 break;
842                         case COLLADAFW::Transformation::MATRIX:
843                                 dae_matrix_to_mat4(tm, m);
844                                 break;
845                         default:
846                                 fprintf(stderr, "unsupported transformation type %d\n", type);
847                         }
848                 }
849
850                 float temp[4][4];
851                 copy_m4_m4(temp, mat);
852
853                 mul_m4_m4m4(mat, m, temp);
854         }
855 }
856
857 // return true to indicate that mat contains a sane value
858 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
859 {
860         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
861         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
862
863         if (type != COLLADAFW::Transformation::ROTATE &&
864             type != COLLADAFW::Transformation::SCALE &&
865             type != COLLADAFW::Transformation::TRANSLATE &&
866             type != COLLADAFW::Transformation::MATRIX) {
867                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
868                 return false;
869         }
870
871         if (animlist_map.find(listid) == animlist_map.end())
872                 return false;
873
874         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
875         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
876
877         if (bindings.getCount()) {
878                 float vec[3];
879
880                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
881                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
882
883                 if (type == COLLADAFW::Transformation::SCALE)
884                         dae_scale_to_v3(tm, vec);
885                 else if (type == COLLADAFW::Transformation::TRANSLATE)
886                         dae_translate_to_v3(tm, vec);
887
888                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
889                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
890                         std::vector<FCurve*>& curves = curve_map[binding.animation];
891                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
892                         char path[100];
893
894                         switch (type) {
895                         case COLLADAFW::Transformation::ROTATE:
896                                 BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
897                                 break;
898                         case COLLADAFW::Transformation::SCALE:
899                                 BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
900                                 break;
901                         case COLLADAFW::Transformation::TRANSLATE:
902                                 BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
903                                 break;
904                         case COLLADAFW::Transformation::MATRIX:
905                                 BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
906                                 break;
907                         default:
908                                 break;
909                         }
910
911                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
912                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
913                                 continue;
914                         }
915
916                         if (type == COLLADAFW::Transformation::ROTATE) {
917                                 if (curves.size() != 1) {
918                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
919                                         return false;
920                                 }
921
922                                 // TODO support other animclasses
923                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
924                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
925                                         return false;
926                                 }
927
928                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
929                                 float ax[3] = {axis[0], axis[1], axis[2]};
930                                 float angle = evaluate_fcurve(curves[0], fra);
931                                 axis_angle_to_mat4(mat, ax, angle);
932
933                                 return true;
934                         }
935                         else if (is_scale || is_translate) {
936                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
937
938                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
939                                         if (is_xyz)
940                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
941                                         else
942                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
943                                         return false;
944                                 }
945                                 
946                                 switch (animclass) {
947                                 case COLLADAFW::AnimationList::POSITION_X:
948                                         vec[0] = evaluate_fcurve(curves[0], fra);
949                                         break;
950                                 case COLLADAFW::AnimationList::POSITION_Y:
951                                         vec[1] = evaluate_fcurve(curves[0], fra);
952                                         break;
953                                 case COLLADAFW::AnimationList::POSITION_Z:
954                                         vec[2] = evaluate_fcurve(curves[0], fra);
955                                         break;
956                                 case COLLADAFW::AnimationList::POSITION_XYZ:
957                                         vec[0] = evaluate_fcurve(curves[0], fra);
958                                         vec[1] = evaluate_fcurve(curves[1], fra);
959                                         vec[2] = evaluate_fcurve(curves[2], fra);
960                                         break;
961                                 default:
962                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
963                                         break;
964                                 }
965                         }
966                         else if (type == COLLADAFW::Transformation::MATRIX) {
967                                 // for now, of matrix animation, support only the case when all values are packed into one animation
968                                 if (curves.size() != 16) {
969                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
970                                         return false;
971                                 }
972
973                                 COLLADABU::Math::Matrix4 matrix;
974                                 int i = 0, j = 0;
975
976                                 for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++) {
977                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
978                                         j++;
979                                         if (j == 4) {
980                                                 i++;
981                                                 j = 0;
982                                         }
983                                 }
984
985                                 COLLADAFW::Matrix tm(matrix);
986                                 dae_matrix_to_mat4(&tm, mat);
987
988                                 return true;
989                         }
990                 }
991
992                 if (is_scale)
993                         size_to_mat4(mat, vec);
994                 else
995                         copy_v3_v3(mat[3], vec);
996
997                 return is_scale || is_translate;
998         }
999
1000         return false;
1001 }
1002
1003 // gives a world-space mat of joint at rest position
1004 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1005 {
1006         // if bind mat is not available,
1007         // use "current" node transform, i.e. all those tms listed inside <node>
1008         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1009                 float par[4][4], m[4][4];
1010
1011                 calc_joint_parent_mat_rest(par, NULL, root, node);
1012                 get_node_mat(m, node, NULL, NULL);
1013                 mul_m4_m4m4(mat, m, par);
1014         }
1015 }
1016
1017 // gives a world-space mat, end's mat not included
1018 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1019 {
1020         float m[4][4];
1021
1022         if (node == end) {
1023                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1024                 return true;
1025         }
1026
1027         // use bind matrix if available or calc "current" world mat
1028         if (!armature_importer->get_joint_bind_mat(m, node)) {
1029                 if (par) {
1030                         float temp[4][4];
1031                         get_node_mat(temp, node, NULL, NULL);
1032                         mul_m4_m4m4(m, temp, par);
1033                 }
1034                 else {
1035                         get_node_mat(m, node, NULL, NULL);
1036                 }
1037         }
1038
1039         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1040         for (unsigned int i = 0; i < children.getCount(); i++) {
1041                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1042                         return true;
1043         }
1044
1045         return false;
1046 }
1047
1048 #ifdef ARMATURE_TEST
1049 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1050 {
1051         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1052                 Object *job = add_object(scene, OB_EMPTY);
1053
1054                 rename_id((ID*)&job->id, (char*)get_joint_name(node));
1055
1056                 job->lay = object_in_scene(job, scene)->lay = 2;
1057
1058                 mul_v3_fl(job->size, 0.5f);
1059                 job->recalc |= OB_RECALC_OB;
1060
1061                 verify_adt_action((ID*)&job->id, 1);
1062
1063                 job->rotmode = ROT_MODE_QUAT;
1064
1065                 float mat[4][4];
1066                 get_joint_rest_mat(mat, root, node);
1067
1068                 if (par_job) {
1069                         float temp[4][4], ipar[4][4];
1070                         invert_m4_m4(ipar, par_job->obmat);
1071                         copy_m4_m4(temp, mat);
1072                         mul_m4_m4m4(mat, temp, ipar);
1073                 }
1074
1075                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1076
1077                 if (par_job) {
1078                         job->parent = par_job;
1079
1080                         par_job->recalc |= OB_RECALC_OB;
1081                         job->parsubstr[0] = 0;
1082                 }
1083
1084                 where_is_object(scene, job);
1085
1086                 // after parenting and layer change
1087                 DAG_scene_sort(CTX_data_main(C), scene);
1088
1089                 joint_objects[node->getUniqueId()] = job;
1090         }
1091
1092         return joint_objects[node->getUniqueId()];
1093 }
1094 #endif
1095
1096 #if 0
1097 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1098 // mat must be identity on enter, node must be root
1099 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1100 {
1101         float m[4][4];
1102         if (par) {
1103                 float temp[4][4];
1104                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1105                 mul_m4_m4m4(m, temp, par);
1106         }
1107         else {
1108                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1109         }
1110
1111         if (node == end) {
1112                 copy_m4_m4(mat, m);
1113                 return true;
1114         }
1115         else {
1116                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1117                 for (int i = 0; i < children.getCount(); i++) {
1118                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1119                                 return true;
1120                 }
1121         }
1122
1123         return false;
1124 }
1125 #endif
1126
1127 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1128 {
1129         const char *bone_name = bc_get_joint_name(node);
1130         bAction *act = ob->adt->action;
1131                         
1132         /* try to find group */
1133         bActionGroup *grp = action_groups_find_named(act, bone_name);
1134
1135         /* no matching groups, so add one */
1136         if (grp == NULL) {
1137                 /* Add a new group, and make it active */
1138                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1139                                         
1140                 grp->flag = AGRP_SELECTED;
1141                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1142                                         
1143                 BLI_addtail(&act->groups, grp);
1144                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1145         }
1146                                 
1147         /* add F-Curve to group */
1148         action_groups_add_channel(act, grp, fcu);
1149 }
1150
1151 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1152 {
1153         BezTriple bez;
1154         memset(&bez, 0, sizeof(BezTriple));
1155         bez.vec[1][0] = fra;
1156         bez.vec[1][1] = value;
1157         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1158         bez.f1 = bez.f2 = bez.f3 = SELECT;
1159         bez.h1 = bez.h2 = HD_AUTO;
1160         insert_bezt_fcurve(fcu, &bez, 0);
1161         calchandles_fcurve(fcu);
1162 }