style cleanup
[blender.git] / source / blender / ikplugin / intern / itasc_plugin.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Original author: Benoit Bolsee
24  * Contributor(s):
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/ikplugin/intern/itasc_plugin.cpp
30  *  \ingroup ikplugin
31  */
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <vector>
36
37 // iTaSC headers
38 #ifdef WITH_IK_ITASC
39 #include "Armature.hpp"
40 #include "MovingFrame.hpp"
41 #include "CopyPose.hpp"
42 #include "WSDLSSolver.hpp"
43 #include "WDLSSolver.hpp"
44 #include "Scene.hpp"
45 #include "Cache.hpp"
46 #include "Distance.hpp"
47 #endif
48
49 #include "MEM_guardedalloc.h"
50
51 extern "C" {
52 #include "BIK_api.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_math.h"
55 #include "BLI_utildefines.h"
56
57 #include "BKE_global.h"
58 #include "BKE_armature.h"
59 #include "BKE_action.h"
60 #include "BKE_constraint.h"
61 #include "DNA_object_types.h"
62 #include "DNA_action_types.h"
63 #include "DNA_constraint_types.h"
64 #include "DNA_armature_types.h"
65 #include "DNA_scene_types.h"
66 };
67
68 #include "itasc_plugin.h"
69
70 // default parameters
71 bItasc DefIKParam;
72
73 // in case of animation mode, feedback and timestep is fixed
74 #define ANIM_TIMESTEP   1.0
75 #define ANIM_FEEDBACK   0.8
76 #define ANIM_QMAX       0.52
77
78
79 // Structure pointed by bPose.ikdata
80 // It contains everything needed to simulate the armatures
81 // There can be several simulation islands independent to each other
82 struct IK_Data {
83         struct IK_Scene *first;
84 };
85
86 typedef float Vector3[3];
87 typedef float Vector4[4];
88 struct IK_Target;
89 typedef void (*ErrorCallback)(const iTaSC::ConstraintValues *values, unsigned int nvalues, IK_Target *iktarget);
90
91 // one structure for each target in the scene
92 struct IK_Target
93 {
94         struct Scene                    *blscene;
95         iTaSC::MovingFrame*             target;
96         iTaSC::ConstraintSet*   constraint;
97         struct bConstraint*             blenderConstraint;
98         struct bPoseChannel*    rootChannel;
99         Object*                                 owner;                  //for auto IK
100         ErrorCallback                   errorCallback;
101         std::string                             targetName;
102         std::string                             constraintName;
103         unsigned short                  controlType;
104         short                                   channel;                //index in IK channel array of channel on which this target is defined
105         short                                   ee;                             //end effector number
106         bool                                    simulation;             //true when simulation mode is used (update feedback)
107         bool                                    eeBlend;                //end effector affected by enforce blending
108         float                                   eeRest[4][4];   //end effector initial pose relative to armature
109
110         IK_Target() {
111                 blscene = NULL;
112                 target = NULL;
113                 constraint = NULL;
114                 blenderConstraint = NULL;
115                 rootChannel = NULL;
116                 owner = NULL;
117                 controlType = 0;
118                 channel = 0;
119                 ee = 0;
120                 eeBlend = true;
121                 simulation = true;
122                 targetName.reserve(32);
123                 constraintName.reserve(32);
124         }
125         ~IK_Target() {
126                 if (constraint)
127                         delete constraint;
128                 if (target)
129                         delete target;
130         }
131 };
132
133 struct IK_Channel {
134         bPoseChannel*   pchan;          // channel where we must copy matrix back
135         KDL::Frame              frame;          // frame of the bone relative to object base, not armature base
136         std::string             tail;           // segment name of the joint from which we get the bone tail
137         std::string     head;           // segment name of the joint from which we get the bone head
138         int                             parent;         // index in this array of the parent channel
139         short                   jointType;      // type of joint, combination of IK_SegmentFlag
140         char                    ndof;           // number of joint angles for this channel
141         char                    jointValid;     // set to 1 when jointValue has been computed
142         // for joint constraint
143         Object*                 owner;                          // for pose and IK param
144         double                  jointValue[4];          // computed joint value
145
146         IK_Channel() {
147                 pchan = NULL;
148                 parent = -1;
149                 jointType = 0;
150                 ndof = 0;
151                 jointValid = 0;
152                 owner = NULL;
153                 jointValue[0] = 0.0;
154                 jointValue[1] = 0.0;
155                 jointValue[2] = 0.0;
156                 jointValue[3] = 0.0;
157         }
158 };
159
160 struct IK_Scene {
161         struct Scene            *blscene;
162         IK_Scene*                       next;
163         int                                     numchan;        // number of channel in pchan
164         int                                     numjoint;       // number of joint in jointArray
165         // array of bone information, one per channel in the tree
166         IK_Channel*                     channels;
167         iTaSC::Armature*        armature;
168         iTaSC::Cache*           cache;
169         iTaSC::Scene*           scene;
170         iTaSC::MovingFrame* base;               // armature base object
171         KDL::Frame                      baseFrame;      // frame of armature base relative to blArmature
172         KDL::JntArray           jointArray;     // buffer for storing temporary joint array
173         iTaSC::Solver*          solver;
174         Object*                         blArmature;
175         float                           blScale;        // scale of the Armature object (assume uniform scaling)
176         float                           blInvScale;     // inverse of Armature object scale
177         struct bConstraint*     polarConstraint;
178         std::vector<IK_Target*>         targets;
179
180         IK_Scene() {
181                 blscene = NULL;
182                 next = NULL;
183                 channels = NULL;
184                 armature = NULL;
185                 cache = NULL;
186                 scene = NULL;
187                 base = NULL;
188                 solver = NULL;
189                 blScale = blInvScale = 1.0f;
190                 blArmature = NULL;
191                 numchan = 0;
192                 numjoint = 0;
193                 polarConstraint = NULL;
194         }
195
196         ~IK_Scene() {
197                 // delete scene first
198                 if (scene)
199                         delete scene;
200                 for (std::vector<IK_Target *>::iterator it = targets.begin(); it != targets.end(); ++it)
201                         delete (*it);
202                 targets.clear();
203                 if (channels)
204                         delete[] channels;
205                 if (solver)
206                         delete solver;
207                 if (armature)
208                         delete armature;
209                 if (base)
210                         delete base;
211                 // delete cache last
212                 if (cache)
213                         delete cache;
214         }
215 };
216
217 // type of IK joint, can be combined to list the joints corresponding to a bone
218 enum IK_SegmentFlag {
219         IK_XDOF = 1,
220         IK_YDOF = 2,
221         IK_ZDOF = 4,
222         IK_SWING = 8,
223         IK_REVOLUTE = 16,
224         IK_TRANSY = 32,
225 };
226
227 enum IK_SegmentAxis {
228         IK_X = 0,
229         IK_Y = 1,
230         IK_Z = 2,
231         IK_TRANS_X = 3,
232         IK_TRANS_Y = 4,
233         IK_TRANS_Z = 5
234 };
235
236 static int initialize_chain(Object *ob, bPoseChannel *pchan_tip, bConstraint *con)
237 {
238         bPoseChannel *curchan, *pchan_root = NULL, *chanlist[256], **oldchan;
239         PoseTree *tree;
240         PoseTarget *target;
241         bKinematicConstraint *data;
242         int a, t, segcount = 0, size, newsize, *oldparent, parent, rootbone, treecount;
243
244         data = (bKinematicConstraint *)con->data;
245
246         /* exclude tip from chain? */
247         if (!(data->flag & CONSTRAINT_IK_TIP))
248                 pchan_tip = pchan_tip->parent;
249
250         rootbone = data->rootbone;
251         /* Find the chain's root & count the segments needed */
252         for (curchan = pchan_tip; curchan; curchan = curchan->parent) {
253                 pchan_root = curchan;
254
255                 if (++segcount > 255)       // 255 is weak
256                         break;
257
258                 if (segcount == rootbone) {
259                         // reached this end of the chain but if the chain is overlapping with a
260                         // previous one, we must go back up to the root of the other chain
261                         if ((curchan->flag & POSE_CHAIN) && curchan->iktree.first == NULL) {
262                                 rootbone++;
263                                 continue;
264                         }
265                         break;
266                 }
267
268                 if (curchan->iktree.first != NULL)
269                         // Oh oh, there is already a chain starting from this channel and our chain is longer...
270                         // Should handle this by moving the previous chain up to the beginning of our chain
271                         // For now we just stop here
272                         break;
273         }
274         if (!segcount) return 0;
275         // we reached a limit and still not the end of a previous chain, quit
276         if ((pchan_root->flag & POSE_CHAIN) && pchan_root->iktree.first == NULL) return 0;
277
278         // now that we know how many segment we have, set the flag
279         for (rootbone = segcount, segcount = 0, curchan = pchan_tip; segcount < rootbone; segcount++, curchan = curchan->parent) {
280                 chanlist[segcount] = curchan;
281                 curchan->flag |= POSE_CHAIN;
282         }
283
284         /* setup the chain data */
285         /* create a target */
286         target = (PoseTarget *)MEM_callocN(sizeof(PoseTarget), "posetarget");
287         target->con = con;
288         // by contruction there can be only one tree per channel and each channel can be part of at most one tree.
289         tree = (PoseTree *)pchan_root->iktree.first;
290
291         if (tree == NULL) {
292                 /* make new tree */
293                 tree = (PoseTree *)MEM_callocN(sizeof(PoseTree), "posetree");
294
295                 tree->iterations = data->iterations;
296                 tree->totchannel = segcount;
297                 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH);
298
299                 tree->pchan = (bPoseChannel **)MEM_callocN(segcount * sizeof(void *), "ik tree pchan");
300                 tree->parent = (int *)MEM_callocN(segcount * sizeof(int), "ik tree parent");
301                 for (a = 0; a < segcount; a++) {
302                         tree->pchan[a] = chanlist[segcount - a - 1];
303                         tree->parent[a] = a - 1;
304                 }
305                 target->tip = segcount - 1;
306
307                 /* AND! link the tree to the root */
308                 BLI_addtail(&pchan_root->iktree, tree);
309                 // new tree
310                 treecount = 1;
311         }
312         else {
313                 tree->iterations = MAX2(data->iterations, tree->iterations);
314                 tree->stretch = tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH);
315
316                 /* skip common pose channels and add remaining*/
317                 size = MIN2(segcount, tree->totchannel);
318                 a = t = 0;
319                 while (a < size && t < tree->totchannel) {
320                         // locate first matching channel
321                         for (; t < tree->totchannel && tree->pchan[t] != chanlist[segcount - a - 1]; t++) ;
322                         if (t >= tree->totchannel)
323                                 break;
324                         for (; a < size && t < tree->totchannel && tree->pchan[t] == chanlist[segcount - a - 1]; a++, t++) ;
325                 }
326
327                 segcount = segcount - a;
328                 target->tip = tree->totchannel + segcount - 1;
329
330                 if (segcount > 0) {
331                         for (parent = a - 1; parent < tree->totchannel; parent++)
332                                 if (tree->pchan[parent] == chanlist[segcount - 1]->parent)
333                                         break;
334
335                         /* shouldn't happen, but could with dependency cycles */
336                         if (parent == tree->totchannel)
337                                 parent = a - 1;
338
339                         /* resize array */
340                         newsize = tree->totchannel + segcount;
341                         oldchan = tree->pchan;
342                         oldparent = tree->parent;
343
344                         tree->pchan = (bPoseChannel **)MEM_callocN(newsize * sizeof(void *), "ik tree pchan");
345                         tree->parent = (int *)MEM_callocN(newsize * sizeof(int), "ik tree parent");
346                         memcpy(tree->pchan, oldchan, sizeof(void *) * tree->totchannel);
347                         memcpy(tree->parent, oldparent, sizeof(int) * tree->totchannel);
348                         MEM_freeN(oldchan);
349                         MEM_freeN(oldparent);
350
351                         /* add new pose channels at the end, in reverse order */
352                         for (a = 0; a < segcount; a++) {
353                                 tree->pchan[tree->totchannel + a] = chanlist[segcount - a - 1];
354                                 tree->parent[tree->totchannel + a] = tree->totchannel + a - 1;
355                         }
356                         tree->parent[tree->totchannel] = parent;
357
358                         tree->totchannel = newsize;
359                 }
360                 // reusing tree
361                 treecount = 0;
362         }
363
364         /* add target to the tree */
365         BLI_addtail(&tree->targets, target);
366         /* mark root channel having an IK tree */
367         pchan_root->flag |= POSE_IKTREE;
368         return treecount;
369 }
370
371 static bool is_cartesian_constraint(bConstraint *con)
372 {
373         //bKinematicConstraint* data=(bKinematicConstraint *)con->data;
374
375         return true;
376 }
377
378 static bool constraint_valid(bConstraint *con)
379 {
380         bKinematicConstraint *data = (bKinematicConstraint *)con->data;
381
382         if (data->flag & CONSTRAINT_IK_AUTO)
383                 return true;
384         if (con->flag & CONSTRAINT_DISABLE)
385                 return false;
386         if (is_cartesian_constraint(con)) {
387                 /* cartesian space constraint */
388                 if (data->tar == NULL)
389                         return false;
390                 if (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)
391                         return false;
392         }
393         return true;
394 }
395
396 static int initialize_scene(Object *ob, bPoseChannel *pchan_tip)
397 {
398         bConstraint *con;
399         int treecount;
400
401         /* find all IK constraints and validate them */
402         treecount = 0;
403         for (con = (bConstraint *)pchan_tip->constraints.first; con; con = (bConstraint *)con->next) {
404                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
405                         if (constraint_valid(con))
406                                 treecount += initialize_chain(ob, pchan_tip, con);
407                 }
408         }
409         return treecount;
410 }
411
412 static IK_Data *get_ikdata(bPose *pose)
413 {
414         if (pose->ikdata)
415                 return (IK_Data *)pose->ikdata;
416         pose->ikdata = MEM_callocN(sizeof(IK_Data), "iTaSC ikdata");
417         // here init ikdata if needed
418         // now that we have scene, make sure the default param are initialized
419         if (!DefIKParam.iksolver)
420                 BKE_pose_itasc_init(&DefIKParam);
421
422         return (IK_Data *)pose->ikdata;
423 }
424 static double EulerAngleFromMatrix(const KDL::Rotation& R, int axis)
425 {
426         double t = KDL::sqrt(R(0, 0) * R(0, 0) + R(0, 1) * R(0, 1));
427
428         if (t > 16.0 * KDL::epsilon) {
429                 if (axis == 0) return -KDL::atan2(R(1, 2), R(2, 2));
430                 else if (axis == 1) return KDL::atan2(-R(0, 2), t);
431                 else return -KDL::atan2(R(0, 1), R(0, 0));
432         }
433         else {
434                 if (axis == 0) return -KDL::atan2(-R(2, 1), R(1, 1));
435                 else if (axis == 1) return KDL::atan2(-R(0, 2), t);
436                 else return 0.0f;
437         }
438 }
439
440 static double ComputeTwist(const KDL::Rotation& R)
441 {
442         // qy and qw are the y and w components of the quaternion from R
443         double qy = R(0, 2) - R(2, 0);
444         double qw = R(0, 0) + R(1, 1) + R(2, 2) + 1;
445
446         double tau = 2 * KDL::atan2(qy, qw);
447
448         return tau;
449 }
450
451 static void RemoveEulerAngleFromMatrix(KDL::Rotation& R, double angle, int axis)
452 {
453         // compute twist parameter
454         KDL::Rotation T;
455         switch (axis) {
456                 case 0:
457                         T = KDL::Rotation::RotX(-angle);
458                         break;
459                 case 1:
460                         T = KDL::Rotation::RotY(-angle);
461                         break;
462                 case 2:
463                         T = KDL::Rotation::RotZ(-angle);
464                         break;
465                 default:
466                         return;
467         }
468         // remove angle
469         R = R * T;
470 }
471
472 #if 0
473 static void GetEulerXZY(const KDL::Rotation& R, double& X, double& Z, double& Y)
474 {
475         if (fabs(R(0, 1)) > 1.0 - KDL::epsilon) {
476                 X = -KDL::sign(R(0, 1)) * KDL::atan2(R(1, 2), R(1, 0));
477                 Z = -KDL::sign(R(0, 1)) * KDL::PI / 2;
478                 Y = 0.0;
479         }
480         else {
481                 X = KDL::atan2(R(2, 1), R(1, 1));
482                 Z = KDL::atan2(-R(0, 1), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 2))));
483                 Y = KDL::atan2(R(0, 2), R(0, 0));
484         }
485 }
486
487 static void GetEulerXYZ(const KDL::Rotation& R, double& X, double& Y, double& Z)
488 {
489         if (fabs(R(0, 2)) > 1.0 - KDL::epsilon) {
490                 X = KDL::sign(R(0, 2)) * KDL::atan2(-R(1, 0), R(1, 1));
491                 Y = KDL::sign(R(0, 2)) * KDL::PI / 2;
492                 Z = 0.0;
493         }
494         else {
495                 X = KDL::atan2(-R(1, 2), R(2, 2));
496                 Y = KDL::atan2(R(0, 2), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 1))));
497                 Z = KDL::atan2(-R(0, 1), R(0, 0));
498         }
499 }
500 #endif
501
502 static void GetJointRotation(KDL::Rotation& boneRot, int type, double *rot)
503 {
504         switch (type & ~IK_TRANSY) {
505                 default:
506                         // fixed bone, no joint
507                         break;
508                 case IK_XDOF:
509                         // RX only, get the X rotation
510                         rot[0] = EulerAngleFromMatrix(boneRot, 0);
511                         break;
512                 case IK_YDOF:
513                         // RY only, get the Y rotation
514                         rot[0] = ComputeTwist(boneRot);
515                         break;
516                 case IK_ZDOF:
517                         // RZ only, get the Z rotation
518                         rot[0] = EulerAngleFromMatrix(boneRot, 2);
519                         break;
520                 case IK_XDOF | IK_YDOF:
521                         rot[1] = ComputeTwist(boneRot);
522                         RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
523                         rot[0] = EulerAngleFromMatrix(boneRot, 0);
524                         break;
525                 case IK_SWING:
526                         // RX+RZ
527                         boneRot.GetXZRot().GetValue(rot);
528                         break;
529                 case IK_YDOF | IK_ZDOF:
530                         // RZ+RY
531                         rot[1] = ComputeTwist(boneRot);
532                         RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
533                         rot[0] = EulerAngleFromMatrix(boneRot, 2);
534                         break;
535                 case IK_SWING | IK_YDOF:
536                         rot[2] = ComputeTwist(boneRot);
537                         RemoveEulerAngleFromMatrix(boneRot, rot[2], 1);
538                         boneRot.GetXZRot().GetValue(rot);
539                         break;
540                 case IK_REVOLUTE:
541                         boneRot.GetRot().GetValue(rot);
542                         break;
543         }
544 }
545
546 static bool target_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param)
547 {
548         IK_Target *target = (IK_Target *)param;
549         // compute next target position
550         // get target matrix from constraint.
551         bConstraint *constraint = (bConstraint *)target->blenderConstraint;
552         float tarmat[4][4];
553
554         BKE_get_constraint_target_matrix(target->blscene, constraint, 0, CONSTRAINT_OBTYPE_OBJECT, target->owner, tarmat, 1.0);
555
556         // rootmat contains the target pose in world coordinate
557         // if enforce is != 1.0, blend the target position with the end effector position
558         // if the armature was in rest position. This information is available in eeRest
559         if (constraint->enforce != 1.0f && target->eeBlend) {
560                 // eeRest is relative to the reference frame of the IK root
561                 // get this frame in world reference
562                 float restmat[4][4];
563                 bPoseChannel *pchan = target->rootChannel;
564                 if (pchan->parent) {
565                         pchan = pchan->parent;
566                         float chanmat[4][4];
567                         copy_m4_m4(chanmat, pchan->pose_mat);
568                         copy_v3_v3(chanmat[3], pchan->pose_tail);
569                         mul_serie_m4(restmat, target->owner->obmat, chanmat, target->eeRest, NULL, NULL, NULL, NULL, NULL);
570                 }
571                 else {
572                         mult_m4_m4m4(restmat, target->owner->obmat, target->eeRest);
573                 }
574                 // blend the target
575                 blend_m4_m4m4(tarmat, restmat, tarmat, constraint->enforce);
576         }
577         next.setValue(&tarmat[0][0]);
578         return true;
579 }
580
581 static bool base_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param)
582 {
583         IK_Scene *ikscene = (IK_Scene *)param;
584         // compute next armature base pose
585         // algorithm:
586         // ikscene->pchan[0] is the root channel of the tree
587         // if it has a parent, get the pose matrix from it and replace [3] by parent pchan->tail
588         // then multiply by the armature matrix to get ikscene->armature base position
589         bPoseChannel *pchan = ikscene->channels[0].pchan;
590         float rootmat[4][4];
591         if (pchan->parent) {
592                 pchan = pchan->parent;
593                 float chanmat[4][4];
594                 copy_m4_m4(chanmat, pchan->pose_mat);
595                 copy_v3_v3(chanmat[3], pchan->pose_tail);
596                 // save the base as a frame too so that we can compute deformation after simulation
597                 ikscene->baseFrame.setValue(&chanmat[0][0]);
598                 // iTaSC armature is scaled to object scale, scale the base frame too
599                 ikscene->baseFrame.p *= ikscene->blScale;
600                 mult_m4_m4m4(rootmat, ikscene->blArmature->obmat, chanmat);
601         }
602         else {
603                 copy_m4_m4(rootmat, ikscene->blArmature->obmat);
604                 ikscene->baseFrame = iTaSC::F_identity;
605         }
606         next.setValue(&rootmat[0][0]);
607         // if there is a polar target (only during solving otherwise we don't have end efffector)
608         if (ikscene->polarConstraint && timestamp.update) {
609                 // compute additional rotation of base frame so that armature follows the polar target
610                 float imat[4][4];       // IK tree base inverse matrix
611                 float polemat[4][4];    // polar target in IK tree base frame
612                 float goalmat[4][4];    // target in IK tree base frame
613                 float mat[4][4];        // temp matrix
614                 bKinematicConstraint *poledata = (bKinematicConstraint *)ikscene->polarConstraint->data;
615
616                 invert_m4_m4(imat, rootmat);
617                 // polar constraint imply only one target
618                 IK_Target *iktarget = ikscene->targets[0];
619                 // root channel from which we take the bone initial orientation
620                 IK_Channel &rootchan = ikscene->channels[0];
621
622                 // get polar target matrix in world space
623                 BKE_get_constraint_target_matrix(ikscene->blscene, ikscene->polarConstraint, 1, CONSTRAINT_OBTYPE_OBJECT, ikscene->blArmature, mat, 1.0);
624                 // convert to armature space
625                 mult_m4_m4m4(polemat, imat, mat);
626                 // get the target in world space (was computed before as target object are defined before base object)
627                 iktarget->target->getPose().getValue(mat[0]);
628                 // convert to armature space
629                 mult_m4_m4m4(goalmat, imat, mat);
630                 // take position of target, polar target, end effector, in armature space
631                 KDL::Vector goalpos(goalmat[3]);
632                 KDL::Vector polepos(polemat[3]);
633                 KDL::Vector endpos = ikscene->armature->getPose(iktarget->ee).p;
634                 // get root bone orientation
635                 KDL::Frame rootframe;
636                 ikscene->armature->getRelativeFrame(rootframe, rootchan.tail);
637                 KDL::Vector rootx = rootframe.M.UnitX();
638                 KDL::Vector rootz = rootframe.M.UnitZ();
639                 // and compute root bone head
640                 double q_rest[3], q[3], length;
641                 const KDL::Joint *joint;
642                 const KDL::Frame *tip;
643                 ikscene->armature->getSegment(rootchan.tail, 3, joint, q_rest[0], q[0], tip);
644                 length = (joint->getType() == KDL::Joint::TransY) ? q[0] : tip->p(1);
645                 KDL::Vector rootpos = rootframe.p - length *rootframe.M.UnitY();
646
647                 // compute main directions
648                 KDL::Vector dir = KDL::Normalize(endpos - rootpos);
649                 KDL::Vector poledir = KDL::Normalize(goalpos - rootpos);
650                 // compute up directions
651                 KDL::Vector poleup = KDL::Normalize(polepos - rootpos);
652                 KDL::Vector up = rootx * KDL::cos(poledata->poleangle) + rootz *KDL::sin(poledata->poleangle);
653                 // from which we build rotation matrix
654                 KDL::Rotation endrot, polerot;
655                 // for the armature, using the root bone orientation
656                 KDL::Vector x = KDL::Normalize(dir * up);
657                 endrot.UnitX(x);
658                 endrot.UnitY(KDL::Normalize(x * dir));
659                 endrot.UnitZ(-dir);
660                 // for the polar target
661                 x = KDL::Normalize(poledir * poleup);
662                 polerot.UnitX(x);
663                 polerot.UnitY(KDL::Normalize(x * poledir));
664                 polerot.UnitZ(-poledir);
665                 // the difference between the two is the rotation we want to apply
666                 KDL::Rotation result(polerot * endrot.Inverse());
667                 // apply on base frame as this is an artificial additional rotation
668                 next.M = next.M * result;
669                 ikscene->baseFrame.M = ikscene->baseFrame.M * result;
670         }
671         return true;
672 }
673
674 static bool copypose_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
675 {
676         IK_Target *iktarget = (IK_Target *)_param;
677         bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
678         iTaSC::ConstraintValues *values = _values;
679         bItasc *ikparam = (bItasc *) iktarget->owner->pose->ikparam;
680
681         // we need default parameters
682         if (!ikparam)
683                 ikparam = &DefIKParam;
684
685         if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
686                 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
687                         values->alpha = 0.0;
688                         values->action = iTaSC::ACT_ALPHA;
689                         values++;
690                 }
691                 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
692                         values->alpha = 0.0;
693                         values->action = iTaSC::ACT_ALPHA;
694                         values++;
695                 }
696         }
697         else {
698                 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
699                         // update error
700                         values->alpha = condata->weight;
701                         values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
702                         values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
703                         values++;
704                 }
705                 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
706                         // update error
707                         values->alpha = condata->orientweight;
708                         values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
709                         values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
710                         values++;
711                 }
712         }
713         return true;
714 }
715
716 static void copypose_error(const iTaSC::ConstraintValues *values, unsigned int nvalues, IK_Target *iktarget)
717 {
718         iTaSC::ConstraintSingleValue *value;
719         double error;
720         int i;
721
722         if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) {
723                 // update error
724                 for (i = 0, error = 0.0, value = values->values; i < values->number; ++i, ++value)
725                         error += KDL::sqr(value->y - value->yd);
726                 iktarget->blenderConstraint->lin_error = (float)KDL::sqrt(error);
727                 values++;
728         }
729         if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) {
730                 // update error
731                 for (i = 0, error = 0.0, value = values->values; i < values->number; ++i, ++value)
732                         error += KDL::sqr(value->y - value->yd);
733                 iktarget->blenderConstraint->rot_error = (float)KDL::sqrt(error);
734                 values++;
735         }
736 }
737
738 static bool distance_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
739 {
740         IK_Target *iktarget = (IK_Target *)_param;
741         bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
742         iTaSC::ConstraintValues *values = _values;
743         bItasc *ikparam = (bItasc *) iktarget->owner->pose->ikparam;
744         // we need default parameters
745         if (!ikparam)
746                 ikparam = &DefIKParam;
747
748         // update weight according to mode
749         if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
750                 values->alpha = 0.0;
751         }
752         else {
753                 switch (condata->mode) {
754                         case LIMITDIST_INSIDE:
755                                 values->alpha = (values->values[0].y > condata->dist) ? condata->weight : 0.0;
756                                 break;
757                         case LIMITDIST_OUTSIDE:
758                                 values->alpha = (values->values[0].y < condata->dist) ? condata->weight : 0.0;
759                                 break;
760                         default:
761                                 values->alpha = condata->weight;
762                                 break;
763                 }
764                 if (!timestamp.substep) {
765                         // only update value on first timestep
766                         switch (condata->mode) {
767                                 case LIMITDIST_INSIDE:
768                                         values->values[0].yd = condata->dist * 0.95;
769                                         break;
770                                 case LIMITDIST_OUTSIDE:
771                                         values->values[0].yd = condata->dist * 1.05;
772                                         break;
773                                 default:
774                                         values->values[0].yd = condata->dist;
775                                         break;
776                         }
777                         values->values[0].action = iTaSC::ACT_VALUE | iTaSC::ACT_FEEDBACK;
778                         values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
779                 }
780         }
781         values->action |= iTaSC::ACT_ALPHA;
782         return true;
783 }
784
785 static void distance_error(const iTaSC::ConstraintValues *values, unsigned int _nvalues, IK_Target *iktarget)
786 {
787         iktarget->blenderConstraint->lin_error = (float)(values->values[0].y - values->values[0].yd);
788 }
789
790 static bool joint_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues *const _values, unsigned int _nvalues, void *_param)
791 {
792         IK_Channel *ikchan = (IK_Channel *)_param;
793         bItasc *ikparam = (bItasc *)ikchan->owner->pose->ikparam;
794         bPoseChannel *chan = ikchan->pchan;
795         int dof;
796
797         // a channel can be splitted into multiple joints, so we get called multiple
798         // times for one channel (this callback is only for 1 joint in the armature)
799         // the IK_JointTarget structure is shared between multiple joint constraint
800         // and the target joint values is computed only once, remember this in jointValid
801         // Don't forget to reset it before each frame
802         if (!ikchan->jointValid) {
803                 float rmat[3][3];
804
805                 if (chan->rotmode > 0) {
806                         /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
807                         eulO_to_mat3(rmat, chan->eul, chan->rotmode);
808                 }
809                 else if (chan->rotmode == ROT_MODE_AXISANGLE) {
810                         /* axis-angle - stored in quaternion data, but not really that great for 3D-changing orientations */
811                         axis_angle_to_mat3(rmat, &chan->quat[1], chan->quat[0]);
812                 }
813                 else {
814                         /* quats are normalized before use to eliminate scaling issues */
815                         normalize_qt(chan->quat);
816                         quat_to_mat3(rmat, chan->quat);
817                 }
818                 KDL::Rotation jointRot(
819                     rmat[0][0], rmat[1][0], rmat[2][0],
820                     rmat[0][1], rmat[1][1], rmat[2][1],
821                     rmat[0][2], rmat[1][2], rmat[2][2]);
822                 GetJointRotation(jointRot, ikchan->jointType, ikchan->jointValue);
823                 ikchan->jointValid = 1;
824         }
825         // determine which part of jointValue is used for this joint
826         // closely related to the way the joints are defined
827         switch (ikchan->jointType & ~IK_TRANSY) {
828                 case IK_XDOF:
829                 case IK_YDOF:
830                 case IK_ZDOF:
831                         dof = 0;
832                         break;
833                 case IK_XDOF | IK_YDOF:
834                         // X + Y
835                         dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RX) ? 0 : 1;
836                         break;
837                 case IK_SWING:
838                         // XZ
839                         dof = 0;
840                         break;
841                 case IK_YDOF | IK_ZDOF:
842                         // Z + Y
843                         dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RZ) ? 0 : 1;
844                         break;
845                 case IK_SWING | IK_YDOF:
846                         // XZ + Y
847                         dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RY) ? 2 : 0;
848                         break;
849                 case IK_REVOLUTE:
850                         dof = 0;
851                         break;
852                 default:
853                         dof = -1;
854                         break;
855         }
856         if (dof >= 0) {
857                 for (unsigned int i = 0; i < _nvalues; i++, dof++) {
858                         _values[i].values[0].yd = ikchan->jointValue[dof];
859                         _values[i].alpha = chan->ikrotweight;
860                         _values[i].feedback = ikparam->feedback;
861                 }
862         }
863         return true;
864 }
865
866 // build array of joint corresponding to IK chain
867 static int convert_channels(IK_Scene *ikscene, PoseTree *tree)
868 {
869         IK_Channel *ikchan;
870         bPoseChannel *pchan;
871         int a, flag, njoint;
872
873         njoint = 0;
874         for (a = 0, ikchan = ikscene->channels; a < ikscene->numchan; ++a, ++ikchan) {
875                 pchan = tree->pchan[a];
876                 ikchan->pchan = pchan;
877                 ikchan->parent = (a > 0) ? tree->parent[a] : -1;
878                 ikchan->owner = ikscene->blArmature;
879
880                 /* set DoF flag */
881                 flag = 0;
882                 if (!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP) &&
883                     (!(pchan->ikflag & BONE_IK_XLIMIT) || pchan->limitmin[0] < 0.f || pchan->limitmax[0] > 0.f))
884                 {
885                         flag |= IK_XDOF;
886                 }
887                 if (!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP) &&
888                     (!(pchan->ikflag & BONE_IK_YLIMIT) || pchan->limitmin[1] < 0.f || pchan->limitmax[1] > 0.f))
889                 {
890                         flag |= IK_YDOF;
891                 }
892                 if (!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP) &&
893                     (!(pchan->ikflag & BONE_IK_ZLIMIT) || pchan->limitmin[2] < 0.f || pchan->limitmax[2] > 0.f))
894                 {
895                         flag |= IK_ZDOF;
896                 }
897
898                 if (tree->stretch && (pchan->ikstretch > 0.0)) {
899                         flag |= IK_TRANSY;
900                 }
901                 /*
902                  * Logic to create the segments:
903                  * RX,RY,RZ = rotational joints with no length
904                  * RY(tip) = rotational joints with a fixed length arm = (0,length,0)
905                  * TY = translational joint on Y axis
906                  * F(pos) = fixed joint with an arm at position pos
907                  * Conversion rule of the above flags:
908                  * -   ==> F(tip)
909                  * X   ==> RX(tip)
910                  * Y   ==> RY(tip)
911                  * Z   ==> RZ(tip)
912                  * XY  ==> RX+RY(tip)
913                  * XZ  ==> RX+RZ(tip)
914                  * YZ  ==> RZ+RY(tip)
915                  * XYZ ==> full spherical unless there are limits, in which case RX+RZ+RY(tip)
916                  * In case of stretch, tip=(0,0,0) and there is an additional TY joint
917                  * The frame at last of these joints represents the tail of the bone.
918                  * The head is computed by a reverse translation on Y axis of the bone length
919                  * or in case of TY joint, by the frame at previous joint.
920                  * In case of separation of bones, there is an additional F(head) joint
921                  *
922                  * Computing rest pose and length is complicated: the solver works in world space
923                  * Here is the logic:
924                  * rest position is computed only from bone->bone_mat.
925                  * bone length is computed from bone->length multiplied by the scaling factor of
926                  * the armature. Non-uniform scaling will give bad result!
927                  */
928                 switch (flag & (IK_XDOF | IK_YDOF | IK_ZDOF)) {
929                         default:
930                                 ikchan->jointType = 0;
931                                 ikchan->ndof = 0;
932                                 break;
933                         case IK_XDOF:
934                                 // RX only, get the X rotation
935                                 ikchan->jointType = IK_XDOF;
936                                 ikchan->ndof = 1;
937                                 break;
938                         case IK_YDOF:
939                                 // RY only, get the Y rotation
940                                 ikchan->jointType = IK_YDOF;
941                                 ikchan->ndof = 1;
942                                 break;
943                         case IK_ZDOF:
944                                 // RZ only, get the Zz rotation
945                                 ikchan->jointType = IK_ZDOF;
946                                 ikchan->ndof = 1;
947                                 break;
948                         case IK_XDOF | IK_YDOF:
949                                 ikchan->jointType = IK_XDOF | IK_YDOF;
950                                 ikchan->ndof = 2;
951                                 break;
952                         case IK_XDOF | IK_ZDOF:
953                                 // RX+RZ
954                                 ikchan->jointType = IK_SWING;
955                                 ikchan->ndof = 2;
956                                 break;
957                         case IK_YDOF | IK_ZDOF:
958                                 // RZ+RY
959                                 ikchan->jointType = IK_ZDOF | IK_YDOF;
960                                 ikchan->ndof = 2;
961                                 break;
962                         case IK_XDOF | IK_YDOF | IK_ZDOF:
963                                 // spherical joint
964                                 if (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_YLIMIT | BONE_IK_ZLIMIT))
965                                         // decompose in a Swing+RotY joint
966                                         ikchan->jointType = IK_SWING | IK_YDOF;
967                                 else
968                                         ikchan->jointType = IK_REVOLUTE;
969                                 ikchan->ndof = 3;
970                                 break;
971                 }
972                 if (flag & IK_TRANSY) {
973                         ikchan->jointType |= IK_TRANSY;
974                         ikchan->ndof++;
975                 }
976                 njoint += ikchan->ndof;
977         }
978         // njoint is the joint coordinate, create the Joint Array
979         ikscene->jointArray.resize(njoint);
980         ikscene->numjoint = njoint;
981         return njoint;
982 }
983
984 // compute array of joint value corresponding to current pose
985 static void convert_pose(IK_Scene *ikscene)
986 {
987         KDL::Rotation boneRot;
988         bPoseChannel *pchan;
989         IK_Channel *ikchan;
990         Bone *bone;
991         float rmat[4][4];   // rest pose of bone with parent taken into account
992         float bmat[4][4];   // difference
993         float scale;
994         double *rot;
995         int a, joint;
996
997         // assume uniform scaling and take Y scale as general scale for the armature
998         scale = len_v3(ikscene->blArmature->obmat[1]);
999         rot = ikscene->jointArray(0);
1000         for (joint = a = 0, ikchan = ikscene->channels; a < ikscene->numchan && joint < ikscene->numjoint; ++a, ++ikchan) {
1001                 pchan = ikchan->pchan;
1002                 bone = pchan->bone;
1003
1004                 if (pchan->parent) {
1005                         unit_m4(bmat);
1006                         mul_m4_m4m3(bmat, pchan->parent->pose_mat, bone->bone_mat);
1007                 }
1008                 else {
1009                         copy_m4_m4(bmat, bone->arm_mat);
1010                 }
1011                 invert_m4_m4(rmat, bmat);
1012                 mult_m4_m4m4(bmat, rmat, pchan->pose_mat);
1013                 normalize_m4(bmat);
1014                 boneRot.setValue(bmat[0]);
1015                 GetJointRotation(boneRot, ikchan->jointType, rot);
1016                 if (ikchan->jointType & IK_TRANSY) {
1017                         // compute actual length
1018                         rot[ikchan->ndof - 1] = len_v3v3(pchan->pose_tail, pchan->pose_head) * scale;
1019                 }
1020                 rot += ikchan->ndof;
1021                 joint += ikchan->ndof;
1022         }
1023 }
1024
1025 // compute array of joint value corresponding to current pose
1026 static void BKE_pose_rest(IK_Scene *ikscene)
1027 {
1028         bPoseChannel *pchan;
1029         IK_Channel *ikchan;
1030         Bone *bone;
1031         float scale;
1032         double *rot;
1033         int a, joint;
1034
1035         // assume uniform scaling and take Y scale as general scale for the armature
1036         scale = len_v3(ikscene->blArmature->obmat[1]);
1037         // rest pose is 0
1038         SetToZero(ikscene->jointArray);
1039         // except for transY joints
1040         rot = ikscene->jointArray(0);
1041         for (joint = a = 0, ikchan = ikscene->channels; a < ikscene->numchan && joint < ikscene->numjoint; ++a, ++ikchan) {
1042                 pchan = ikchan->pchan;
1043                 bone = pchan->bone;
1044
1045                 if (ikchan->jointType & IK_TRANSY)
1046                         rot[ikchan->ndof - 1] = bone->length * scale;
1047                 rot += ikchan->ndof;
1048                 joint += ikchan->ndof;
1049         }
1050 }
1051
1052 static IK_Scene *convert_tree(Scene *blscene, Object *ob, bPoseChannel *pchan)
1053 {
1054         PoseTree *tree = (PoseTree *)pchan->iktree.first;
1055         PoseTarget *target;
1056         bKinematicConstraint *condata;
1057         bConstraint *polarcon;
1058         bItasc *ikparam;
1059         iTaSC::Armature *arm;
1060         iTaSC::Scene *scene;
1061         IK_Scene *ikscene;
1062         IK_Channel *ikchan;
1063         KDL::Frame initPose;
1064         KDL::Rotation boneRot;
1065         Bone *bone;
1066         int a, numtarget;
1067         unsigned int t;
1068         float length;
1069         bool ret = true, ingame;
1070         double *rot;
1071
1072         if (tree->totchannel == 0)
1073                 return NULL;
1074
1075         ikscene = new IK_Scene;
1076         ikscene->blscene = blscene;
1077         arm = new iTaSC::Armature();
1078         scene = new iTaSC::Scene();
1079         ikscene->channels = new IK_Channel[tree->totchannel];
1080         ikscene->numchan = tree->totchannel;
1081         ikscene->armature = arm;
1082         ikscene->scene = scene;
1083         ikparam = (bItasc *)ob->pose->ikparam;
1084         ingame = (ob->pose->flag & POSE_GAME_ENGINE);
1085         if (!ikparam) {
1086                 // you must have our own copy
1087                 ikparam = &DefIKParam;
1088         }
1089         else if (ingame) {
1090                 // tweak the param when in game to have efficient stepping
1091                 // using fixed substep is not effecient since frames in the GE are often
1092                 // shorter than in animation => move to auto step automatically and set
1093                 // the target substep duration via min/max
1094                 if (!(ikparam->flag & ITASC_AUTO_STEP)) {
1095                         float timestep = blscene->r.frs_sec_base / blscene->r.frs_sec;
1096                         if (ikparam->numstep > 0)
1097                                 timestep /= ikparam->numstep;
1098                         // with equal min and max, the algorythm will take this step and the indicative substep most of the time
1099                         ikparam->minstep = ikparam->maxstep = timestep;
1100                         ikparam->flag |= ITASC_AUTO_STEP;
1101                 }
1102         }
1103         if ((ikparam->flag & ITASC_SIMULATION) && !ingame)
1104                 // no cache in animation mode
1105                 ikscene->cache = new iTaSC::Cache();
1106
1107         switch (ikparam->solver) {
1108                 case ITASC_SOLVER_SDLS:
1109                         ikscene->solver = new iTaSC::WSDLSSolver();
1110                         break;
1111                 case ITASC_SOLVER_DLS:
1112                         ikscene->solver = new iTaSC::WDLSSolver();
1113                         break;
1114                 default:
1115                         delete ikscene;
1116                         return NULL;
1117         }
1118         ikscene->blArmature = ob;
1119         // assume uniform scaling and take Y scale as general scale for the armature
1120         ikscene->blScale = len_v3(ob->obmat[1]);
1121         ikscene->blInvScale = (ikscene->blScale < KDL::epsilon) ? 0.0f : 1.0f / ikscene->blScale;
1122
1123         std::string joint;
1124         std::string root("root");
1125         std::string parent;
1126         std::vector<double> weights;
1127         double weight[3];
1128         // build the array of joints corresponding to the IK chain
1129         convert_channels(ikscene, tree);
1130         if (ingame) {
1131                 // in the GE, set the initial joint angle to match the current pose
1132                 // this will update the jointArray in ikscene
1133                 convert_pose(ikscene);
1134         }
1135         else {
1136                 // in Blender, the rest pose is always 0 for joints
1137                 BKE_pose_rest(ikscene);
1138         }
1139         rot = ikscene->jointArray(0);
1140         for (a = 0, ikchan = ikscene->channels; a < tree->totchannel; ++a, ++ikchan) {
1141                 pchan = ikchan->pchan;
1142                 bone = pchan->bone;
1143
1144                 KDL::Frame tip(iTaSC::F_identity);
1145                 Vector3 *fl = bone->bone_mat;
1146                 KDL::Rotation brot(
1147                     fl[0][0], fl[1][0], fl[2][0],
1148                     fl[0][1], fl[1][1], fl[2][1],
1149                     fl[0][2], fl[1][2], fl[2][2]);
1150                 KDL::Vector bpos(bone->head[0], bone->head[1], bone->head[2]);
1151                 bpos *= ikscene->blScale;
1152                 KDL::Frame head(brot, bpos);
1153
1154                 // rest pose length of the bone taking scaling into account
1155                 length = bone->length * ikscene->blScale;
1156                 parent = (a > 0) ? ikscene->channels[tree->parent[a]].tail : root;
1157                 // first the fixed segment to the bone head
1158                 if (head.p.Norm() > KDL::epsilon || head.M.GetRot().Norm() > KDL::epsilon) {
1159                         joint = bone->name;
1160                         joint += ":H";
1161                         ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, head);
1162                         parent = joint;
1163                 }
1164                 if (!(ikchan->jointType & IK_TRANSY)) {
1165                         // fixed length, put it in tip
1166                         tip.p[1] = length;
1167                 }
1168                 joint = bone->name;
1169                 weight[0] = (1.0 - pchan->stiffness[0]);
1170                 weight[1] = (1.0 - pchan->stiffness[1]);
1171                 weight[2] = (1.0 - pchan->stiffness[2]);
1172                 switch (ikchan->jointType & ~IK_TRANSY) {
1173                         case 0:
1174                                 // fixed bone
1175                                 joint += ":F";
1176                                 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, tip);
1177                                 break;
1178                         case IK_XDOF:
1179                                 // RX only, get the X rotation
1180                                 joint += ":RX";
1181                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0], tip);
1182                                 weights.push_back(weight[0]);
1183                                 break;
1184                         case IK_YDOF:
1185                                 // RY only, get the Y rotation
1186                                 joint += ":RY";
1187                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[0], tip);
1188                                 weights.push_back(weight[1]);
1189                                 break;
1190                         case IK_ZDOF:
1191                                 // RZ only, get the Zz rotation
1192                                 joint += ":RZ";
1193                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0], tip);
1194                                 weights.push_back(weight[2]);
1195                                 break;
1196                         case IK_XDOF | IK_YDOF:
1197                                 joint += ":RX";
1198                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0]);
1199                                 weights.push_back(weight[0]);
1200                                 if (ret) {
1201                                         parent = joint;
1202                                         joint = bone->name;
1203                                         joint += ":RY";
1204                                         ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1205                                         weights.push_back(weight[1]);
1206                                 }
1207                                 break;
1208                         case IK_SWING:
1209                                 joint += ":SW";
1210                                 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0], tip);
1211                                 weights.push_back(weight[0]);
1212                                 weights.push_back(weight[2]);
1213                                 break;
1214                         case IK_YDOF | IK_ZDOF:
1215                                 // RZ+RY
1216                                 joint += ":RZ";
1217                                 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0]);
1218                                 weights.push_back(weight[2]);
1219                                 if (ret) {
1220                                         parent = joint;
1221                                         joint = bone->name;
1222                                         joint += ":RY";
1223                                         ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1224                                         weights.push_back(weight[1]);
1225                                 }
1226                                 break;
1227                         case IK_SWING | IK_YDOF:
1228                                 // decompose in a Swing+RotY joint
1229                                 joint += ":SW";
1230                                 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0]);
1231                                 weights.push_back(weight[0]);
1232                                 weights.push_back(weight[2]);
1233                                 if (ret) {
1234                                         parent = joint;
1235                                         joint = bone->name;
1236                                         joint += ":RY";
1237                                         ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[2], tip);
1238                                         weights.push_back(weight[1]);
1239                                 }
1240                                 break;
1241                         case IK_REVOLUTE:
1242                                 joint += ":SJ";
1243                                 ret = arm->addSegment(joint, parent, KDL::Joint::Sphere, rot[0], tip);
1244                                 weights.push_back(weight[0]);
1245                                 weights.push_back(weight[1]);
1246                                 weights.push_back(weight[2]);
1247                                 break;
1248                 }
1249                 if (ret && (ikchan->jointType & IK_TRANSY)) {
1250                         parent = joint;
1251                         joint = bone->name;
1252                         joint += ":TY";
1253                         ret = arm->addSegment(joint, parent, KDL::Joint::TransY, rot[ikchan->ndof - 1]);
1254                         const float ikstretch = pchan->ikstretch * pchan->ikstretch;
1255                         /* why invert twice here? */
1256                         weight[1] = (1.0 - min_ff(1.0 - ikstretch, 1.0f - 0.001f));
1257                         weights.push_back(weight[1]);
1258                 }
1259                 if (!ret)
1260                         // error making the armature??
1261                         break;
1262                 // joint points to the segment that correspond to the bone per say
1263                 ikchan->tail = joint;
1264                 ikchan->head = parent;
1265                 // in case of error
1266                 ret = false;
1267                 if ((ikchan->jointType & IK_XDOF) && (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_ROTCTL))) {
1268                         joint = bone->name;
1269                         joint += ":RX";
1270                         if (pchan->ikflag & BONE_IK_XLIMIT) {
1271                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0)
1272                                         break;
1273                         }
1274                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1275                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1276                                         break;
1277                         }
1278                 }
1279                 if ((ikchan->jointType & IK_YDOF) && (pchan->ikflag & (BONE_IK_YLIMIT | BONE_IK_ROTCTL))) {
1280                         joint = bone->name;
1281                         joint += ":RY";
1282                         if (pchan->ikflag & BONE_IK_YLIMIT) {
1283                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[1], pchan->limitmax[1]) < 0)
1284                                         break;
1285                         }
1286                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1287                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1288                                         break;
1289                         }
1290                 }
1291                 if ((ikchan->jointType & IK_ZDOF) && (pchan->ikflag & (BONE_IK_ZLIMIT | BONE_IK_ROTCTL))) {
1292                         joint = bone->name;
1293                         joint += ":RZ";
1294                         if (pchan->ikflag & BONE_IK_ZLIMIT) {
1295                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[2], pchan->limitmax[2]) < 0)
1296                                         break;
1297                         }
1298                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1299                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1300                                         break;
1301                         }
1302                 }
1303                 if ((ikchan->jointType & IK_SWING) && (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_ZLIMIT | BONE_IK_ROTCTL))) {
1304                         joint = bone->name;
1305                         joint += ":SW";
1306                         if (pchan->ikflag & BONE_IK_XLIMIT) {
1307                                 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0)
1308                                         break;
1309                         }
1310                         if (pchan->ikflag & BONE_IK_ZLIMIT) {
1311                                 if (arm->addLimitConstraint(joint, 1, pchan->limitmin[2], pchan->limitmax[2]) < 0)
1312                                         break;
1313                         }
1314                         if (pchan->ikflag & BONE_IK_ROTCTL) {
1315                                 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1316                                         break;
1317                         }
1318                 }
1319                 if ((ikchan->jointType & IK_REVOLUTE) && (pchan->ikflag & BONE_IK_ROTCTL)) {
1320                         joint = bone->name;
1321                         joint += ":SJ";
1322                         if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0)
1323                                 break;
1324                 }
1325                 //  no error, so restore
1326                 ret = true;
1327                 rot += ikchan->ndof;
1328         }
1329         if (!ret) {
1330                 delete ikscene;
1331                 return NULL;
1332         }
1333         // for each target, we need to add an end effector in the armature
1334         for (numtarget = 0, polarcon = NULL, ret = true, target = (PoseTarget *)tree->targets.first; target; target = (PoseTarget *)target->next) {
1335                 condata = (bKinematicConstraint *)target->con->data;
1336                 pchan = tree->pchan[target->tip];
1337
1338                 if (is_cartesian_constraint(target->con)) {
1339                         // add the end effector
1340                         IK_Target *iktarget = new IK_Target();
1341                         ikscene->targets.push_back(iktarget);
1342                         iktarget->ee = arm->addEndEffector(ikscene->channels[target->tip].tail);
1343                         if (iktarget->ee == -1) {
1344                                 ret = false;
1345                                 break;
1346                         }
1347                         // initialize all the fields that we can set at this time
1348                         iktarget->blenderConstraint = target->con;
1349                         iktarget->channel = target->tip;
1350                         iktarget->simulation = (ikparam->flag & ITASC_SIMULATION);
1351                         iktarget->rootChannel = ikscene->channels[0].pchan;
1352                         iktarget->owner = ob;
1353                         iktarget->targetName = pchan->bone->name;
1354                         iktarget->targetName += ":T:";
1355                         iktarget->targetName += target->con->name;
1356                         iktarget->constraintName = pchan->bone->name;
1357                         iktarget->constraintName += ":C:";
1358                         iktarget->constraintName += target->con->name;
1359                         numtarget++;
1360                         if (condata->poletar)
1361                                 // this constraint has a polar target
1362                                 polarcon = target->con;
1363                 }
1364         }
1365         // deal with polar target if any
1366         if (numtarget == 1 && polarcon) {
1367                 ikscene->polarConstraint = polarcon;
1368         }
1369         // we can now add the armature
1370         // the armature is based on a moving frame.
1371         // initialize with the correct position in case there is no cache
1372         base_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, ikscene);
1373         ikscene->base = new iTaSC::MovingFrame(initPose);
1374         ikscene->base->setCallback(base_callback, ikscene);
1375         std::string armname;
1376         armname = ob->id.name;
1377         armname += ":B";
1378         ret = scene->addObject(armname, ikscene->base);
1379         armname = ob->id.name;
1380         armname += ":AR";
1381         if (ret)
1382                 ret = scene->addObject(armname, ikscene->armature, ikscene->base);
1383         if (!ret) {
1384                 delete ikscene;
1385                 return NULL;
1386         }
1387         // set the weight
1388         e_matrix& Wq = arm->getWq();
1389         assert(Wq.cols() == (int)weights.size());
1390         for (int q = 0; q < Wq.cols(); q++)
1391                 Wq(q, q) = weights[q];
1392         // get the inverse rest pose frame of the base to compute relative rest pose of end effectors
1393         // this is needed to handle the enforce parameter
1394         // ikscene->pchan[0] is the root channel of the tree
1395         // if it has no parent, then it's just the identify Frame
1396         float invBaseFrame[4][4];
1397         pchan = ikscene->channels[0].pchan;
1398         if (pchan->parent) {
1399                 // it has a parent, get the pose matrix from it
1400                 float baseFrame[4][4];
1401                 pchan = pchan->parent;
1402                 copy_m4_m4(baseFrame, pchan->bone->arm_mat);
1403                 // move to the tail and scale to get rest pose of armature base
1404                 copy_v3_v3(baseFrame[3], pchan->bone->arm_tail);
1405                 invert_m4_m4(invBaseFrame, baseFrame);
1406         }
1407         else {
1408                 unit_m4(invBaseFrame);
1409         }
1410         // finally add the constraint
1411         for (t = 0; t < ikscene->targets.size(); t++) {
1412                 IK_Target *iktarget = ikscene->targets[t];
1413                 iktarget->blscene = blscene;
1414                 condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
1415                 pchan = tree->pchan[iktarget->channel];
1416                 unsigned int controltype, bonecnt;
1417                 double bonelen;
1418                 float mat[4][4];
1419
1420                 // add the end effector
1421                 // estimate the average bone length, used to clamp feedback error
1422                 for (bonecnt = 0, bonelen = 0.f, a = iktarget->channel; a >= 0; a = tree->parent[a], bonecnt++)
1423                         bonelen += ikscene->blScale * tree->pchan[a]->bone->length;
1424                 bonelen /= bonecnt;
1425
1426                 // store the rest pose of the end effector to compute enforce target
1427                 copy_m4_m4(mat, pchan->bone->arm_mat);
1428                 copy_v3_v3(mat[3], pchan->bone->arm_tail);
1429                 // get the rest pose relative to the armature base
1430                 mult_m4_m4m4(iktarget->eeRest, invBaseFrame, mat);
1431                 iktarget->eeBlend = (!ikscene->polarConstraint && condata->type == CONSTRAINT_IK_COPYPOSE) ? true : false;
1432                 // use target_callback to make sure the initPose includes enforce coefficient
1433                 target_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, iktarget);
1434                 iktarget->target = new iTaSC::MovingFrame(initPose);
1435                 iktarget->target->setCallback(target_callback, iktarget);
1436                 ret = scene->addObject(iktarget->targetName, iktarget->target);
1437                 if (!ret)
1438                         break;
1439
1440                 switch (condata->type) {
1441                         case CONSTRAINT_IK_COPYPOSE:
1442                                 controltype = 0;
1443                                 if (condata->flag & CONSTRAINT_IK_ROT) {
1444                                         if (!(condata->flag & CONSTRAINT_IK_NO_ROT_X))
1445                                                 controltype |= iTaSC::CopyPose::CTL_ROTATIONX;
1446                                         if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Y))
1447                                                 controltype |= iTaSC::CopyPose::CTL_ROTATIONY;
1448                                         if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Z))
1449                                                 controltype |= iTaSC::CopyPose::CTL_ROTATIONZ;
1450                                 }
1451                                 if (condata->flag & CONSTRAINT_IK_POS) {
1452                                         if (!(condata->flag & CONSTRAINT_IK_NO_POS_X))
1453                                                 controltype |= iTaSC::CopyPose::CTL_POSITIONX;
1454                                         if (!(condata->flag & CONSTRAINT_IK_NO_POS_Y))
1455                                                 controltype |= iTaSC::CopyPose::CTL_POSITIONY;
1456                                         if (!(condata->flag & CONSTRAINT_IK_NO_POS_Z))
1457                                                 controltype |= iTaSC::CopyPose::CTL_POSITIONZ;
1458                                 }
1459                                 if (controltype) {
1460                                         iktarget->constraint = new iTaSC::CopyPose(controltype, controltype, bonelen);
1461                                         // set the gain
1462                                         if (controltype & iTaSC::CopyPose::CTL_POSITION)
1463                                                 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_POSITION, iTaSC::ACT_ALPHA, condata->weight);
1464                                         if (controltype & iTaSC::CopyPose::CTL_ROTATION)
1465                                                 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_ROTATION, iTaSC::ACT_ALPHA, condata->orientweight);
1466                                         iktarget->constraint->registerCallback(copypose_callback, iktarget);
1467                                         iktarget->errorCallback = copypose_error;
1468                                         iktarget->controlType = controltype;
1469                                         // add the constraint
1470                                         if (condata->flag & CONSTRAINT_IK_TARGETAXIS)
1471                                                 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, iktarget->targetName, armname, "", ikscene->channels[iktarget->channel].tail);
1472                                         else
1473                                                 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail);
1474                                 }
1475                                 break;
1476                         case CONSTRAINT_IK_DISTANCE:
1477                                 iktarget->constraint = new iTaSC::Distance(bonelen);
1478                                 iktarget->constraint->setControlParameter(iTaSC::Distance::ID_DISTANCE, iTaSC::ACT_VALUE, condata->dist);
1479                                 iktarget->constraint->registerCallback(distance_callback, iktarget);
1480                                 iktarget->errorCallback = distance_error;
1481                                 // we can update the weight on each substep
1482                                 iktarget->constraint->substep(true);
1483                                 // add the constraint
1484                                 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail);
1485                                 break;
1486                 }
1487                 if (!ret)
1488                         break;
1489         }
1490         if (!ret ||
1491             !scene->addCache(ikscene->cache) ||
1492             !scene->addSolver(ikscene->solver) ||
1493             !scene->initialize()) {
1494                 delete ikscene;
1495                 ikscene = NULL;
1496         }
1497         return ikscene;
1498 }
1499
1500 static void create_scene(Scene *scene, Object *ob)
1501 {
1502         bPoseChannel *pchan;
1503
1504         // create the IK scene
1505         for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = (bPoseChannel *)pchan->next) {
1506                 // by construction there is only one tree
1507                 PoseTree *tree = (PoseTree *)pchan->iktree.first;
1508                 if (tree) {
1509                         IK_Data *ikdata = get_ikdata(ob->pose);
1510                         // convert tree in iTaSC::Scene
1511                         IK_Scene *ikscene = convert_tree(scene, ob, pchan);
1512                         if (ikscene) {
1513                                 ikscene->next = ikdata->first;
1514                                 ikdata->first = ikscene;
1515                         }
1516                         // delete the trees once we are done
1517                         while (tree) {
1518                                 BLI_remlink(&pchan->iktree, tree);
1519                                 BLI_freelistN(&tree->targets);
1520                                 if (tree->pchan) MEM_freeN(tree->pchan);
1521                                 if (tree->parent) MEM_freeN(tree->parent);
1522                                 if (tree->basis_change) MEM_freeN(tree->basis_change);
1523                                 MEM_freeN(tree);
1524                                 tree = (PoseTree *)pchan->iktree.first;
1525                         }
1526                 }
1527         }
1528 }
1529
1530 /* returns 1 if scaling has changed and tree must be reinitialized */
1531 static int init_scene(Object *ob)
1532 {
1533         // check also if scaling has changed
1534         float scale = len_v3(ob->obmat[1]);
1535         IK_Scene *scene;
1536
1537         if (ob->pose->ikdata) {
1538                 for (scene = ((IK_Data *)ob->pose->ikdata)->first;
1539                      scene != NULL;
1540                      scene = scene->next) {
1541                         if (fabs(scene->blScale - scale) > KDL::epsilon)
1542                                 return 1;
1543                         scene->channels[0].pchan->flag |= POSE_IKTREE;
1544                 }
1545         }
1546         return 0;
1547 }
1548
1549 static void execute_scene(Scene *blscene, IK_Scene *ikscene, bItasc *ikparam, float ctime, float frtime)
1550 {
1551         int i;
1552         IK_Channel *ikchan;
1553         if (ikparam->flag & ITASC_SIMULATION) {
1554                 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ++ikchan) {
1555                         // In simulation mode we don't allow external contraint to change our bones, mark the channel done
1556                         // also tell Blender that this channel is part of IK tree (cleared on each BKE_pose_where_is()
1557                         ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1558                         ikchan->jointValid = 0;
1559                 }
1560         }
1561         else {
1562                 // in animation mode, we must get the bone position from action and constraints
1563                 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ++ikchan) {
1564                         if (!(ikchan->pchan->flag & POSE_DONE))
1565                                 BKE_pose_where_is_bone(blscene, ikscene->blArmature, ikchan->pchan, ctime, 1);
1566                         // tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is()
1567                         ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1568                         ikchan->jointValid = 0;
1569                 }
1570         }
1571         // only run execute the scene if at least one of our target is enabled
1572         for (i = ikscene->targets.size(); i > 0; --i) {
1573                 IK_Target *iktarget = ikscene->targets[i - 1];
1574                 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF))
1575                         break;
1576         }
1577         if (i == 0 && ikscene->armature->getNrOfConstraints() == 0)
1578                 // all constraint disabled
1579                 return;
1580
1581         // compute timestep
1582         double timestamp = ctime * frtime + 2147483.648;
1583         double timestep = frtime;
1584         bool reiterate = (ikparam->flag & ITASC_REITERATION) ? true : false;
1585         int numstep = (ikparam->flag & ITASC_AUTO_STEP) ? 0 : ikparam->numstep;
1586         bool simulation = true;
1587
1588         if (ikparam->flag & ITASC_SIMULATION) {
1589                 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1590         }
1591         else {
1592                 // in animation mode we start from the pose after action and constraint
1593                 convert_pose(ikscene);
1594                 ikscene->armature->setJointArray(ikscene->jointArray);
1595                 // and we don't handle velocity
1596                 reiterate = true;
1597                 simulation = false;
1598                 // time is virtual, so take fixed value for velocity parameters (see itasc_update_param)
1599                 // and choose 1s timestep to allow having velocity parameters in radiant
1600                 timestep = 1.0;
1601                 // use auto setup to let the solver test the variation of the joints
1602                 numstep = 0;
1603         }
1604
1605         if (ikscene->cache && !reiterate && simulation) {
1606                 iTaSC::CacheTS sts, cts;
1607                 sts = cts = (iTaSC::CacheTS)(timestamp * 1000.0 + 0.5);
1608                 if (ikscene->cache->getPreviousCacheItem(ikscene->armature, 0, &cts) == NULL || cts == 0) {
1609                         // the cache is empty before this time, reiterate
1610                         if (ikparam->flag & ITASC_INITIAL_REITERATION)
1611                                 reiterate = true;
1612                 }
1613                 else {
1614                         // can take the cache as a start point.
1615                         sts -= cts;
1616                         timestep = sts / 1000.0;
1617                 }
1618         }
1619         // don't cache if we are reiterating because we don't want to destroy the cache unnecessarily
1620         ikscene->scene->update(timestamp, timestep, numstep, false, !reiterate, simulation);
1621         if (reiterate) {
1622                 // how many times do we reiterate?
1623                 for (i = 0; i < ikparam->numiter; i++) {
1624                         if (ikscene->armature->getMaxJointChange() < ikparam->precision ||
1625                             ikscene->armature->getMaxEndEffectorChange() < ikparam->precision)
1626                         {
1627                                 break;
1628                         }
1629                         ikscene->scene->update(timestamp, timestep, numstep, true, false, simulation);
1630                 }
1631                 if (simulation) {
1632                         // one more fake iteration to cache
1633                         ikscene->scene->update(timestamp, 0.0, 1, true, true, true);
1634                 }
1635         }
1636         // compute constraint error
1637         for (i = ikscene->targets.size(); i > 0; --i) {
1638                 IK_Target *iktarget = ikscene->targets[i - 1];
1639                 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF) && iktarget->constraint) {
1640                         unsigned int nvalues;
1641                         const iTaSC::ConstraintValues *values;
1642                         values = iktarget->constraint->getControlParameters(&nvalues);
1643                         iktarget->errorCallback(values, nvalues, iktarget);
1644                 }
1645         }
1646         // Apply result to bone:
1647         // walk the ikscene->channels
1648         // for each, get the Frame of the joint corresponding to the bone relative to its parent
1649         // combine the parent and the joint frame to get the frame relative to armature
1650         // a backward translation of the bone length gives the head
1651         // if TY, compute the scale as the ratio of the joint length with rest pose length
1652         iTaSC::Armature *arm = ikscene->armature;
1653         KDL::Frame frame;
1654         double q_rest[3], q[3];
1655         const KDL::Joint *joint;
1656         const KDL::Frame *tip;
1657         bPoseChannel *pchan;
1658         float scale;
1659         float length;
1660         float yaxis[3];
1661         for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; ++i, ++ikchan) {
1662                 if (i == 0) {
1663                         if (!arm->getRelativeFrame(frame, ikchan->tail))
1664                                 break;
1665                         // this frame is relative to base, make it relative to object
1666                         ikchan->frame = ikscene->baseFrame * frame;
1667                 }
1668                 else {
1669                         if (!arm->getRelativeFrame(frame, ikchan->tail, ikscene->channels[ikchan->parent].tail))
1670                                 break;
1671                         // combine with parent frame to get frame relative to object
1672                         ikchan->frame = ikscene->channels[ikchan->parent].frame * frame;
1673                 }
1674                 // ikchan->frame is the tail frame relative to object
1675                 // get bone length
1676                 if (!arm->getSegment(ikchan->tail, 3, joint, q_rest[0], q[0], tip))
1677                         break;
1678                 if (joint->getType() == KDL::Joint::TransY) {
1679                         // stretch bones have a TY joint, compute the scale
1680                         scale = (float)(q[0] / q_rest[0]);
1681                         // the length is the joint itself
1682                         length = (float)q[0];
1683                 }
1684                 else {
1685                         scale = 1.0f;
1686                         // for fixed bone, the length is in the tip (always along Y axis)
1687                         length = tip->p(1);
1688                 }
1689                 // ready to compute the pose mat
1690                 pchan = ikchan->pchan;
1691                 // tail mat
1692                 ikchan->frame.getValue(&pchan->pose_mat[0][0]);
1693                 // the scale of the object was included in the ik scene, take it out now
1694                 // because the pose channels are relative to the object
1695                 mul_v3_fl(pchan->pose_mat[3], ikscene->blInvScale);
1696                 length *= ikscene->blInvScale;
1697                 copy_v3_v3(pchan->pose_tail, pchan->pose_mat[3]);
1698                 // shift to head
1699                 copy_v3_v3(yaxis, pchan->pose_mat[1]);
1700                 mul_v3_fl(yaxis, length);
1701                 sub_v3_v3v3(pchan->pose_mat[3], pchan->pose_mat[3], yaxis);
1702                 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
1703                 // add scale
1704                 mul_v3_fl(pchan->pose_mat[0], scale);
1705                 mul_v3_fl(pchan->pose_mat[1], scale);
1706                 mul_v3_fl(pchan->pose_mat[2], scale);
1707         }
1708         if (i < ikscene->numchan) {
1709                 // big problem
1710                 ;
1711         }
1712 }
1713
1714 //---------------------------------------------------
1715 // plugin interface
1716 //
1717 void itasc_initialize_tree(struct Scene *scene, Object *ob, float ctime)
1718 {
1719         bPoseChannel *pchan;
1720         int count = 0;
1721
1722         if (ob->pose->ikdata != NULL && !(ob->pose->flag & POSE_WAS_REBUILT)) {
1723                 if (!init_scene(ob))
1724                         return;
1725         }
1726         // first remove old scene
1727         itasc_clear_data(ob->pose);
1728         // we should handle all the constraint and mark them all disabled
1729         // for blender but we'll start with the IK constraint alone
1730         for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = (bPoseChannel *)pchan->next) {
1731                 if (pchan->constflag & PCHAN_HAS_IK)
1732                         count += initialize_scene(ob, pchan);
1733         }
1734         // if at least one tree, create the scenes from the PoseTree stored in the channels
1735         if (count)
1736                 create_scene(scene, ob);
1737         itasc_update_param(ob->pose);
1738         // make sure we don't rebuilt until the user changes something important
1739         ob->pose->flag &= ~POSE_WAS_REBUILT;
1740 }
1741
1742 void itasc_execute_tree(struct Scene *scene, struct Object *ob,  struct bPoseChannel *pchan, float ctime)
1743 {
1744         if (ob->pose->ikdata) {
1745                 IK_Data *ikdata = (IK_Data *)ob->pose->ikdata;
1746                 bItasc *ikparam = (bItasc *) ob->pose->ikparam;
1747                 // we need default parameters
1748                 if (!ikparam) ikparam = &DefIKParam;
1749
1750                 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1751                         if (ikscene->channels[0].pchan == pchan) {
1752                                 float timestep = scene->r.frs_sec_base / scene->r.frs_sec;
1753                                 if (ob->pose->flag & POSE_GAME_ENGINE) {
1754                                         timestep = ob->pose->ctime;
1755                                         // limit the timestep to avoid excessive number of iteration
1756                                         if (timestep > 0.2f)
1757                                                 timestep = 0.2f;
1758                                 }
1759                                 execute_scene(scene, ikscene, ikparam, ctime, timestep);
1760                                 break;
1761                         }
1762                 }
1763         }
1764 }
1765
1766 void itasc_release_tree(struct Scene *scene, struct Object *ob,  float ctime)
1767 {
1768         // not used for iTaSC
1769 }
1770
1771 void itasc_clear_data(struct bPose *pose)
1772 {
1773         if (pose->ikdata) {
1774                 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1775                 for (IK_Scene *scene = ikdata->first; scene; scene = ikdata->first) {
1776                         ikdata->first = scene->next;
1777                         delete scene;
1778                 }
1779                 MEM_freeN(ikdata);
1780                 pose->ikdata = NULL;
1781         }
1782 }
1783
1784 void itasc_clear_cache(struct bPose *pose)
1785 {
1786         if (pose->ikdata) {
1787                 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1788                 for (IK_Scene *scene = ikdata->first; scene; scene = scene->next) {
1789                         if (scene->cache)
1790                                 // clear all cache but leaving the timestamp 0 (=rest pose)
1791                                 scene->cache->clearCacheFrom(NULL, 1);
1792                 }
1793         }
1794 }
1795
1796 void itasc_update_param(struct bPose *pose)
1797 {
1798         if (pose->ikdata && pose->ikparam) {
1799                 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1800                 bItasc *ikparam = (bItasc *)pose->ikparam;
1801                 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1802                         double armlength = ikscene->armature->getArmLength();
1803                         ikscene->solver->setParam(iTaSC::Solver::DLS_LAMBDA_MAX, ikparam->dampmax * armlength);
1804                         ikscene->solver->setParam(iTaSC::Solver::DLS_EPSILON, ikparam->dampeps * armlength);
1805                         if (ikparam->flag & ITASC_SIMULATION) {
1806                                 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, ikparam->minstep);
1807                                 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, ikparam->maxstep);
1808                                 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1809                                 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, ikparam->feedback);
1810                         }
1811                         else {
1812                                 // in animation mode timestep is 1s by convention =>
1813                                 // qmax becomes radiant and feedback becomes fraction of error gap corrected in one iteration
1814                                 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, 1.0);
1815                                 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, 1.0);
1816                                 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, 0.52);
1817                                 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, 0.8);
1818                         }
1819                 }
1820         }
1821 }
1822
1823 void itasc_test_constraint(struct Object *ob, struct bConstraint *cons)
1824 {
1825         struct bKinematicConstraint *data = (struct bKinematicConstraint *)cons->data;
1826
1827         /* only for IK constraint */
1828         if (cons->type != CONSTRAINT_TYPE_KINEMATIC || data == NULL)
1829                 return;
1830
1831         switch (data->type) {
1832                 case CONSTRAINT_IK_COPYPOSE:
1833                 case CONSTRAINT_IK_DISTANCE:
1834                         /* cartesian space constraint */
1835                         break;
1836         }
1837 }
1838