a166324bde793451c2d9b3d7c4f3593da79cea5a
[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 // use this for retrieving bone names, since these must be unique
57 template<class T>
58 static const char *bc_get_joint_name(T *node)
59 {
60         const std::string& id = node->getOriginalId();
61         return id.size() ? id.c_str() : node->getName().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                 if (!evaluate_animation(tm, m, fra, node->getOriginalId().c_str())) {
831                         switch (type) {
832                         case COLLADAFW::Transformation::ROTATE:
833                                 dae_rotate_to_mat4(tm, m);
834                                 break;
835                         case COLLADAFW::Transformation::TRANSLATE:
836                                 dae_translate_to_mat4(tm, m);
837                                 break;
838                         case COLLADAFW::Transformation::SCALE:
839                                 dae_scale_to_mat4(tm, m);
840                                 break;
841                         case COLLADAFW::Transformation::MATRIX:
842                                 dae_matrix_to_mat4(tm, m);
843                                 break;
844                         default:
845                                 fprintf(stderr, "unsupported transformation type %d\n", type);
846                         }
847                 }
848
849                 float temp[4][4];
850                 copy_m4_m4(temp, mat);
851
852                 mul_m4_m4m4(mat, m, temp);
853         }
854 }
855
856 // return true to indicate that mat contains a sane value
857 bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float mat[4][4], float fra, const char *node_id)
858 {
859         const COLLADAFW::UniqueId& listid = tm->getAnimationList();
860         COLLADAFW::Transformation::TransformationType type = tm->getTransformationType();
861
862         if (type != COLLADAFW::Transformation::ROTATE &&
863             type != COLLADAFW::Transformation::SCALE &&
864             type != COLLADAFW::Transformation::TRANSLATE &&
865             type != COLLADAFW::Transformation::MATRIX) {
866                 fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
867                 return false;
868         }
869
870         if (animlist_map.find(listid) == animlist_map.end())
871                 return false;
872
873         const COLLADAFW::AnimationList *animlist = animlist_map[listid];
874         const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
875
876         if (bindings.getCount()) {
877                 float vec[3];
878
879                 bool is_scale = (type == COLLADAFW::Transformation::SCALE);
880                 bool is_translate = (type == COLLADAFW::Transformation::TRANSLATE);
881
882                 if (type == COLLADAFW::Transformation::SCALE)
883                         dae_scale_to_v3(tm, vec);
884                 else if (type == COLLADAFW::Transformation::TRANSLATE)
885                         dae_translate_to_v3(tm, vec);
886
887                 for (unsigned int j = 0; j < bindings.getCount(); j++) {
888                         const COLLADAFW::AnimationList::AnimationBinding& binding = bindings[j];
889                         std::vector<FCurve*>& curves = curve_map[binding.animation];
890                         COLLADAFW::AnimationList::AnimationClass animclass = binding.animationClass;
891                         char path[100];
892
893                         switch (type) {
894                         case COLLADAFW::Transformation::ROTATE:
895                                 BLI_snprintf(path, sizeof(path), "%s.rotate (binding %u)", node_id, j);
896                                 break;
897                         case COLLADAFW::Transformation::SCALE:
898                                 BLI_snprintf(path, sizeof(path), "%s.scale (binding %u)", node_id, j);
899                                 break;
900                         case COLLADAFW::Transformation::TRANSLATE:
901                                 BLI_snprintf(path, sizeof(path), "%s.translate (binding %u)", node_id, j);
902                                 break;
903                         case COLLADAFW::Transformation::MATRIX:
904                                 BLI_snprintf(path, sizeof(path), "%s.matrix (binding %u)", node_id, j);
905                                 break;
906                         default:
907                                 break;
908                         }
909
910                         if (animclass == COLLADAFW::AnimationList::UNKNOWN_CLASS) {
911                                 fprintf(stderr, "%s: UNKNOWN animation class\n", path);
912                                 continue;
913                         }
914
915                         if (type == COLLADAFW::Transformation::ROTATE) {
916                                 if (curves.size() != 1) {
917                                         fprintf(stderr, "expected 1 curve, got %d\n", (int)curves.size());
918                                         return false;
919                                 }
920
921                                 // TODO support other animclasses
922                                 if (animclass != COLLADAFW::AnimationList::ANGLE) {
923                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
924                                         return false;
925                                 }
926
927                                 COLLADABU::Math::Vector3& axis = ((COLLADAFW::Rotate*)tm)->getRotationAxis();
928                                 float ax[3] = {axis[0], axis[1], axis[2]};
929                                 float angle = evaluate_fcurve(curves[0], fra);
930                                 axis_angle_to_mat4(mat, ax, angle);
931
932                                 return true;
933                         }
934                         else if (is_scale || is_translate) {
935                                 bool is_xyz = animclass == COLLADAFW::AnimationList::POSITION_XYZ;
936
937                                 if ((!is_xyz && curves.size() != 1) || (is_xyz && curves.size() != 3)) {
938                                         if (is_xyz)
939                                                 fprintf(stderr, "%s: expected 3 curves, got %d\n", path, (int)curves.size());
940                                         else
941                                                 fprintf(stderr, "%s: expected 1 curve, got %d\n", path, (int)curves.size());
942                                         return false;
943                                 }
944                                 
945                                 switch (animclass) {
946                                 case COLLADAFW::AnimationList::POSITION_X:
947                                         vec[0] = evaluate_fcurve(curves[0], fra);
948                                         break;
949                                 case COLLADAFW::AnimationList::POSITION_Y:
950                                         vec[1] = evaluate_fcurve(curves[0], fra);
951                                         break;
952                                 case COLLADAFW::AnimationList::POSITION_Z:
953                                         vec[2] = evaluate_fcurve(curves[0], fra);
954                                         break;
955                                 case COLLADAFW::AnimationList::POSITION_XYZ:
956                                         vec[0] = evaluate_fcurve(curves[0], fra);
957                                         vec[1] = evaluate_fcurve(curves[1], fra);
958                                         vec[2] = evaluate_fcurve(curves[2], fra);
959                                         break;
960                                 default:
961                                         fprintf(stderr, "%s: animation class %d is not supported yet\n", path, animclass);
962                                         break;
963                                 }
964                         }
965                         else if (type == COLLADAFW::Transformation::MATRIX) {
966                                 // for now, of matrix animation, support only the case when all values are packed into one animation
967                                 if (curves.size() != 16) {
968                                         fprintf(stderr, "%s: expected 16 curves, got %d\n", path, (int)curves.size());
969                                         return false;
970                                 }
971
972                                 COLLADABU::Math::Matrix4 matrix;
973                                 int i = 0, j = 0;
974
975                                 for (std::vector<FCurve*>::iterator it = curves.begin(); it != curves.end(); it++) {
976                                         matrix.setElement(i, j, evaluate_fcurve(*it, fra));
977                                         j++;
978                                         if (j == 4) {
979                                                 i++;
980                                                 j = 0;
981                                         }
982                                 }
983
984                                 COLLADAFW::Matrix tm(matrix);
985                                 dae_matrix_to_mat4(&tm, mat);
986
987                                 return true;
988                         }
989                 }
990
991                 if (is_scale)
992                         size_to_mat4(mat, vec);
993                 else
994                         copy_v3_v3(mat[3], vec);
995
996                 return is_scale || is_translate;
997         }
998
999         return false;
1000 }
1001
1002 // gives a world-space mat of joint at rest position
1003 void AnimationImporter::get_joint_rest_mat(float mat[4][4], COLLADAFW::Node *root, COLLADAFW::Node *node)
1004 {
1005         // if bind mat is not available,
1006         // use "current" node transform, i.e. all those tms listed inside <node>
1007         if (!armature_importer->get_joint_bind_mat(mat, node)) {
1008                 float par[4][4], m[4][4];
1009
1010                 calc_joint_parent_mat_rest(par, NULL, root, node);
1011                 get_node_mat(m, node, NULL, NULL);
1012                 mul_m4_m4m4(mat, m, par);
1013         }
1014 }
1015
1016 // gives a world-space mat, end's mat not included
1017 bool AnimationImporter::calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end)
1018 {
1019         float m[4][4];
1020
1021         if (node == end) {
1022                 par ? copy_m4_m4(mat, par) : unit_m4(mat);
1023                 return true;
1024         }
1025
1026         // use bind matrix if available or calc "current" world mat
1027         if (!armature_importer->get_joint_bind_mat(m, node)) {
1028                 if (par) {
1029                         float temp[4][4];
1030                         get_node_mat(temp, node, NULL, NULL);
1031                         mul_m4_m4m4(m, temp, par);
1032                 }
1033                 else {
1034                         get_node_mat(m, node, NULL, NULL);
1035                 }
1036         }
1037
1038         COLLADAFW::NodePointerArray& children = node->getChildNodes();
1039         for (unsigned int i = 0; i < children.getCount(); i++) {
1040                 if (calc_joint_parent_mat_rest(mat, m, children[i], end))
1041                         return true;
1042         }
1043
1044         return false;
1045 }
1046
1047 #ifdef ARMATURE_TEST
1048 Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job)
1049 {
1050         if (joint_objects.find(node->getUniqueId()) == joint_objects.end()) {
1051                 Object *job = add_object(scene, OB_EMPTY);
1052
1053                 rename_id((ID*)&job->id, (char*)get_joint_name(node));
1054
1055                 job->lay = object_in_scene(job, scene)->lay = 2;
1056
1057                 mul_v3_fl(job->size, 0.5f);
1058                 job->recalc |= OB_RECALC_OB;
1059
1060                 verify_adt_action((ID*)&job->id, 1);
1061
1062                 job->rotmode = ROT_MODE_QUAT;
1063
1064                 float mat[4][4];
1065                 get_joint_rest_mat(mat, root, node);
1066
1067                 if (par_job) {
1068                         float temp[4][4], ipar[4][4];
1069                         invert_m4_m4(ipar, par_job->obmat);
1070                         copy_m4_m4(temp, mat);
1071                         mul_m4_m4m4(mat, temp, ipar);
1072                 }
1073
1074                 TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
1075
1076                 if (par_job) {
1077                         job->parent = par_job;
1078
1079                         par_job->recalc |= OB_RECALC_OB;
1080                         job->parsubstr[0] = 0;
1081                 }
1082
1083                 where_is_object(scene, job);
1084
1085                 // after parenting and layer change
1086                 DAG_scene_sort(CTX_data_main(C), scene);
1087
1088                 joint_objects[node->getUniqueId()] = job;
1089         }
1090
1091         return joint_objects[node->getUniqueId()];
1092 }
1093 #endif
1094
1095 #if 0
1096 // recursively evaluates joint tree until end is found, mat then is world-space matrix of end
1097 // mat must be identity on enter, node must be root
1098 bool AnimationImporter::evaluate_joint_world_transform_at_frame(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end, float fra)
1099 {
1100         float m[4][4];
1101         if (par) {
1102                 float temp[4][4];
1103                 evaluate_transform_at_frame(temp, node, node == end ? fra : 0.0f);
1104                 mul_m4_m4m4(m, temp, par);
1105         }
1106         else {
1107                 evaluate_transform_at_frame(m, node, node == end ? fra : 0.0f);
1108         }
1109
1110         if (node == end) {
1111                 copy_m4_m4(mat, m);
1112                 return true;
1113         }
1114         else {
1115                 COLLADAFW::NodePointerArray& children = node->getChildNodes();
1116                 for (int i = 0; i < children.getCount(); i++) {
1117                         if (evaluate_joint_world_transform_at_frame(mat, m, children[i], end, fra))
1118                                 return true;
1119                 }
1120         }
1121
1122         return false;
1123 }
1124 #endif
1125
1126 void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu)
1127 {
1128         const char *bone_name = bc_get_joint_name(node);
1129         bAction *act = ob->adt->action;
1130                         
1131         /* try to find group */
1132         bActionGroup *grp = action_groups_find_named(act, bone_name);
1133
1134         /* no matching groups, so add one */
1135         if (grp == NULL) {
1136                 /* Add a new group, and make it active */
1137                 grp = (bActionGroup*)MEM_callocN(sizeof(bActionGroup), "bActionGroup");
1138                                         
1139                 grp->flag = AGRP_SELECTED;
1140                 BLI_strncpy(grp->name, bone_name, sizeof(grp->name));
1141                                         
1142                 BLI_addtail(&act->groups, grp);
1143                 BLI_uniquename(&act->groups, grp, "Group", '.', offsetof(bActionGroup, name), 64);
1144         }
1145                                 
1146         /* add F-Curve to group */
1147         action_groups_add_channel(act, grp, fcu);
1148 }
1149
1150 void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
1151 {
1152         BezTriple bez;
1153         memset(&bez, 0, sizeof(BezTriple));
1154         bez.vec[1][0] = fra;
1155         bez.vec[1][1] = value;
1156         bez.ipo = U.ipo_new; /* use default interpolation mode here... */
1157         bez.f1 = bez.f2 = bez.f3 = SELECT;
1158         bez.h1 = bez.h2 = HD_AUTO;
1159         insert_bezt_fcurve(fcu, &bez, 0);
1160         calchandles_fcurve(fcu);
1161 }