67f0694797b12ad01296a51827fbe8bcc543ee3f
[blender.git] / source / blender / ikplugin / intern / iksolver_plugin.c
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/iksolver_plugin.c
30  *  \ingroup ikplugin
31  */
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BIK_api.h"
36 #include "BLI_blenlib.h"
37 #include "BLI_math.h"
38 #include "BLI_utildefines.h"
39
40 #include "BKE_armature.h"
41 #include "BKE_constraint.h"
42
43 #include "DNA_object_types.h"
44 #include "DNA_action_types.h"
45 #include "DNA_constraint_types.h"
46 #include "DNA_armature_types.h"
47
48 #include "IK_solver.h"
49 #include "iksolver_plugin.h"
50
51 #include <string.h> /* memcpy */
52
53 /* ********************** THE IK SOLVER ******************* */
54
55 /* allocates PoseTree, and links that to root bone/channel */
56 /* Note: detecting the IK chain is duplicate code... in drawarmature.c and in transform_conversions.c */
57 static void initialize_posetree(struct Object *UNUSED(ob), bPoseChannel *pchan_tip)
58 {
59         bPoseChannel *curchan, *pchan_root = NULL, *chanlist[256], **oldchan;
60         PoseTree *tree;
61         PoseTarget *target;
62         bConstraint *con;
63         bKinematicConstraint *data;
64         int a, t, segcount = 0, size, newsize, *oldparent, parent;
65
66         /* find IK constraint, and validate it */
67         for (con = pchan_tip->constraints.first; con; con = con->next) {
68                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
69                         data = (bKinematicConstraint *)con->data;
70                         if (data->flag & CONSTRAINT_IK_AUTO) break;
71                         if (data->tar == NULL) continue;
72                         if (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0) continue;
73                         if ((con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) == 0 && (con->enforce != 0.0f)) break;
74                 }
75         }
76         if (con == NULL) return;
77
78         /* exclude tip from chain? */
79         if (!(data->flag & CONSTRAINT_IK_TIP))
80                 pchan_tip = pchan_tip->parent;
81
82         /* Find the chain's root & count the segments needed */
83         for (curchan = pchan_tip; curchan; curchan = curchan->parent) {
84                 pchan_root = curchan;
85
86                 curchan->flag |= POSE_CHAIN;    // don't forget to clear this
87                 chanlist[segcount] = curchan;
88                 segcount++;
89
90                 if (segcount == data->rootbone || segcount > 255) break;  // 255 is weak
91         }
92         if (!segcount) return;
93
94         /* setup the chain data */
95
96         /* we make tree-IK, unless all existing targets are in this chain */
97         for (tree = pchan_root->iktree.first; tree; tree = tree->next) {
98                 for (target = tree->targets.first; target; target = target->next) {
99                         curchan = tree->pchan[target->tip];
100                         if (curchan->flag & POSE_CHAIN)
101                                 curchan->flag &= ~POSE_CHAIN;
102                         else
103                                 break;
104                 }
105                 if (target) break;
106         }
107
108         /* create a target */
109         target = MEM_callocN(sizeof(PoseTarget), "posetarget");
110         target->con = con;
111         pchan_tip->flag &= ~POSE_CHAIN;
112
113         if (tree == NULL) {
114                 /* make new tree */
115                 tree = MEM_callocN(sizeof(PoseTree), "posetree");
116
117                 tree->type = CONSTRAINT_TYPE_KINEMATIC;
118
119                 tree->iterations = data->iterations;
120                 tree->totchannel = segcount;
121                 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH);
122
123                 tree->pchan = MEM_callocN(segcount * sizeof(void *), "ik tree pchan");
124                 tree->parent = MEM_callocN(segcount * sizeof(int), "ik tree parent");
125                 for (a = 0; a < segcount; a++) {
126                         tree->pchan[a] = chanlist[segcount - a - 1];
127                         tree->parent[a] = a - 1;
128                 }
129                 target->tip = segcount - 1;
130
131                 /* AND! link the tree to the root */
132                 BLI_addtail(&pchan_root->iktree, tree);
133         }
134         else {
135                 tree->iterations = MAX2(data->iterations, tree->iterations);
136                 tree->stretch = tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH);
137
138                 /* skip common pose channels and add remaining*/
139                 size = MIN2(segcount, tree->totchannel);
140                 a = t = 0;
141                 while (a < size && t < tree->totchannel) {
142                         /* locate first matching channel */
143                         for (; t < tree->totchannel && tree->pchan[t] != chanlist[segcount - a - 1]; t++) ;
144                         if (t >= tree->totchannel)
145                                 break;
146                         for (; a < size && t < tree->totchannel && tree->pchan[t] == chanlist[segcount - a - 1]; a++, t++) ;
147                 }
148
149                 segcount = segcount - a;
150                 target->tip = tree->totchannel + segcount - 1;
151
152                 if (segcount > 0) {
153                         for (parent = a - 1; parent < tree->totchannel; parent++)
154                                 if (tree->pchan[parent] == chanlist[segcount - 1]->parent)
155                                         break;
156
157                         /* shouldn't happen, but could with dependency cycles */
158                         if (parent == tree->totchannel)
159                                 parent = a - 1;
160
161                         /* resize array */
162                         newsize = tree->totchannel + segcount;
163                         oldchan = tree->pchan;
164                         oldparent = tree->parent;
165
166                         tree->pchan = MEM_callocN(newsize * sizeof(void *), "ik tree pchan");
167                         tree->parent = MEM_callocN(newsize * sizeof(int), "ik tree parent");
168                         memcpy(tree->pchan, oldchan, sizeof(void *) * tree->totchannel);
169                         memcpy(tree->parent, oldparent, sizeof(int) * tree->totchannel);
170                         MEM_freeN(oldchan);
171                         MEM_freeN(oldparent);
172
173                         /* add new pose channels at the end, in reverse order */
174                         for (a = 0; a < segcount; a++) {
175                                 tree->pchan[tree->totchannel + a] = chanlist[segcount - a - 1];
176                                 tree->parent[tree->totchannel + a] = tree->totchannel + a - 1;
177                         }
178                         tree->parent[tree->totchannel] = parent;
179
180                         tree->totchannel = newsize;
181                 }
182
183                 /* move tree to end of list, for correct evaluation order */
184                 BLI_remlink(&pchan_root->iktree, tree);
185                 BLI_addtail(&pchan_root->iktree, tree);
186         }
187
188         /* add target to the tree */
189         BLI_addtail(&tree->targets, target);
190         /* mark root channel having an IK tree */
191         pchan_root->flag |= POSE_IKTREE;
192 }
193
194
195 /* transform from bone(b) to bone(b+1), store in chan_mat */
196 static void make_dmats(bPoseChannel *pchan)
197 {
198         if (pchan->parent) {
199                 float iR_parmat[4][4];
200                 invert_m4_m4(iR_parmat, pchan->parent->pose_mat);
201                 mult_m4_m4m4(pchan->chan_mat, iR_parmat,  pchan->pose_mat); // delta mat
202         }
203         else copy_m4_m4(pchan->chan_mat, pchan->pose_mat);
204 }
205
206 /* applies IK matrix to pchan, IK is done separated */
207 /* formula: pose_mat(b) = pose_mat(b-1) * diffmat(b-1, b) * ik_mat(b) */
208 /* to make this work, the diffmats have to be precalculated! Stored in chan_mat */
209 static void where_is_ik_bone(bPoseChannel *pchan, float ik_mat[3][3])   // nr = to detect if this is first bone
210 {
211         float vec[3], ikmat[4][4];
212
213         copy_m4_m3(ikmat, ik_mat);
214
215         if (pchan->parent)
216                 mul_serie_m4(pchan->pose_mat, pchan->parent->pose_mat, pchan->chan_mat, ikmat, NULL, NULL, NULL, NULL, NULL);
217         else
218                 mult_m4_m4m4(pchan->pose_mat, pchan->chan_mat, ikmat);
219
220         /* calculate head */
221         copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
222         /* calculate tail */
223         copy_v3_v3(vec, pchan->pose_mat[1]);
224         mul_v3_fl(vec, pchan->bone->length);
225         add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
226
227         pchan->flag |= POSE_DONE;
228 }
229
230
231 /* called from within the core BKE_pose_where_is loop, all animsystems and constraints
232  * were executed & assigned. Now as last we do an IK pass */
233 static void execute_posetree(struct Scene *scene, Object *ob, PoseTree *tree)
234 {
235         float R_parmat[3][3], identity[3][3];
236         float iR_parmat[3][3];
237         float R_bonemat[3][3];
238         float goalrot[3][3], goalpos[3];
239         float rootmat[4][4], imat[4][4];
240         float goal[4][4], goalinv[4][4];
241         float irest_basis[3][3], full_basis[3][3];
242         float end_pose[4][4], world_pose[4][4];
243         float length, basis[3][3], rest_basis[3][3], start[3], *ikstretch = NULL;
244         float resultinf = 0.0f;
245         int a, flag, hasstretch = 0, resultblend = 0;
246         bPoseChannel *pchan;
247         IK_Segment *seg, *parent, **iktree, *iktarget;
248         IK_Solver *solver;
249         PoseTarget *target;
250         bKinematicConstraint *data, *poleangledata = NULL;
251         Bone *bone;
252
253         if (tree->totchannel == 0)
254                 return;
255
256         iktree = MEM_mallocN(sizeof(void *) * tree->totchannel, "ik tree");
257
258         for (a = 0; a < tree->totchannel; a++) {
259                 pchan = tree->pchan[a];
260                 bone = pchan->bone;
261
262                 /* set DoF flag */
263                 flag = 0;
264                 if (!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP))
265                         flag |= IK_XDOF;
266                 if (!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP))
267                         flag |= IK_YDOF;
268                 if (!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP))
269                         flag |= IK_ZDOF;
270
271                 if (tree->stretch && (pchan->ikstretch > 0.0f)) {
272                         flag |= IK_TRANS_YDOF;
273                         hasstretch = 1;
274                 }
275
276                 seg = iktree[a] = IK_CreateSegment(flag);
277
278                 /* find parent */
279                 if (a == 0)
280                         parent = NULL;
281                 else
282                         parent = iktree[tree->parent[a]];
283
284                 IK_SetParent(seg, parent);
285
286                 /* get the matrix that transforms from prevbone into this bone */
287                 copy_m3_m4(R_bonemat, pchan->pose_mat);
288
289                 /* gather transformations for this IK segment */
290
291                 if (pchan->parent)
292                         copy_m3_m4(R_parmat, pchan->parent->pose_mat);
293                 else
294                         unit_m3(R_parmat);
295
296                 /* bone offset */
297                 if (pchan->parent && (a > 0))
298                         sub_v3_v3v3(start, pchan->pose_head, pchan->parent->pose_tail);
299                 else
300                         /* only root bone (a = 0) has no parent */
301                         start[0] = start[1] = start[2] = 0.0f;
302
303                 /* change length based on bone size */
304                 length = bone->length * len_v3(R_bonemat[1]);
305
306                 /* compute rest basis and its inverse */
307                 copy_m3_m3(rest_basis, bone->bone_mat);
308                 copy_m3_m3(irest_basis, bone->bone_mat);
309                 transpose_m3(irest_basis);
310
311                 /* compute basis with rest_basis removed */
312                 invert_m3_m3(iR_parmat, R_parmat);
313                 mul_m3_m3m3(full_basis, iR_parmat, R_bonemat);
314                 mul_m3_m3m3(basis, irest_basis, full_basis);
315
316                 /* basis must be pure rotation */
317                 normalize_m3(basis);
318
319                 /* transform offset into local bone space */
320                 normalize_m3(iR_parmat);
321                 mul_m3_v3(iR_parmat, start);
322
323                 IK_SetTransform(seg, start, rest_basis, basis, length);
324
325                 if (pchan->ikflag & BONE_IK_XLIMIT)
326                         IK_SetLimit(seg, IK_X, pchan->limitmin[0], pchan->limitmax[0]);
327                 if (pchan->ikflag & BONE_IK_YLIMIT)
328                         IK_SetLimit(seg, IK_Y, pchan->limitmin[1], pchan->limitmax[1]);
329                 if (pchan->ikflag & BONE_IK_ZLIMIT)
330                         IK_SetLimit(seg, IK_Z, pchan->limitmin[2], pchan->limitmax[2]);
331
332                 IK_SetStiffness(seg, IK_X, pchan->stiffness[0]);
333                 IK_SetStiffness(seg, IK_Y, pchan->stiffness[1]);
334                 IK_SetStiffness(seg, IK_Z, pchan->stiffness[2]);
335
336                 if (tree->stretch && (pchan->ikstretch > 0.0f)) {
337                         const float ikstretch = pchan->ikstretch * pchan->ikstretch;
338                         /* this function does its own clamping */
339                         IK_SetStiffness(seg, IK_TRANS_Y, 1.0f - ikstretch);
340                         IK_SetLimit(seg, IK_TRANS_Y, IK_STRETCH_STIFF_MIN, IK_STRETCH_STIFF_MAX);
341                 }
342         }
343
344         solver = IK_CreateSolver(iktree[0]);
345
346         /* set solver goals */
347
348         /* first set the goal inverse transform, assuming the root of tree was done ok! */
349         pchan = tree->pchan[0];
350         if (pchan->parent) {
351                 /* transform goal by parent mat, so this rotation is not part of the
352                  * segment's basis. otherwise rotation limits do not work on the
353                  * local transform of the segment itself. */
354                 copy_m4_m4(rootmat, pchan->parent->pose_mat);
355                 /* However, we do not want to get (i.e. reverse) parent's scale, as it generates [#31008]
356                  * kind of nasty bugs... */
357                 normalize_m4(rootmat);
358         }
359         else
360                 unit_m4(rootmat);
361         copy_v3_v3(rootmat[3], pchan->pose_head);
362
363         mult_m4_m4m4(imat, ob->obmat, rootmat);
364         invert_m4_m4(goalinv, imat);
365
366         for (target = tree->targets.first; target; target = target->next) {
367                 float polepos[3];
368                 int poleconstrain = 0;
369
370                 data = (bKinematicConstraint *)target->con->data;
371
372                 /* 1.0=ctime, we pass on object for auto-ik (owner-type here is object, even though
373                  * strictly speaking, it is a posechannel)
374                  */
375                 BKE_get_constraint_target_matrix(scene, target->con, 0, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
376
377                 /* and set and transform goal */
378                 mult_m4_m4m4(goal, goalinv, rootmat);
379
380                 copy_v3_v3(goalpos, goal[3]);
381                 copy_m3_m4(goalrot, goal);
382                 normalize_m3(goalrot);
383
384                 /* same for pole vector target */
385                 if (data->poletar) {
386                         BKE_get_constraint_target_matrix(scene, target->con, 1, CONSTRAINT_OBTYPE_OBJECT, ob, rootmat, 1.0);
387
388                         if (data->flag & CONSTRAINT_IK_SETANGLE) {
389                                 /* don't solve IK when we are setting the pole angle */
390                                 break;
391                         }
392                         else {
393                                 mult_m4_m4m4(goal, goalinv, rootmat);
394                                 copy_v3_v3(polepos, goal[3]);
395                                 poleconstrain = 1;
396
397                                 /* for pole targets, we blend the result of the ik solver
398                                  * instead of the target position, otherwise we can't get
399                                  * a smooth transition */
400                                 resultblend = 1;
401                                 resultinf = target->con->enforce;
402
403                                 if (data->flag & CONSTRAINT_IK_GETANGLE) {
404                                         poleangledata = data;
405                                         data->flag &= ~CONSTRAINT_IK_GETANGLE;
406                                 }
407                         }
408                 }
409
410                 /* do we need blending? */
411                 if (!resultblend && target->con->enforce != 1.0f) {
412                         float q1[4], q2[4], q[4];
413                         float fac = target->con->enforce;
414                         float mfac = 1.0f - fac;
415
416                         pchan = tree->pchan[target->tip];
417
418                         /* end effector in world space */
419                         copy_m4_m4(end_pose, pchan->pose_mat);
420                         copy_v3_v3(end_pose[3], pchan->pose_tail);
421                         mul_serie_m4(world_pose, goalinv, ob->obmat, end_pose, NULL, NULL, NULL, NULL, NULL);
422
423                         /* blend position */
424                         goalpos[0] = fac * goalpos[0] + mfac * world_pose[3][0];
425                         goalpos[1] = fac * goalpos[1] + mfac * world_pose[3][1];
426                         goalpos[2] = fac * goalpos[2] + mfac * world_pose[3][2];
427
428                         /* blend rotation */
429                         mat3_to_quat(q1, goalrot);
430                         mat4_to_quat(q2, world_pose);
431                         interp_qt_qtqt(q, q1, q2, mfac);
432                         quat_to_mat3(goalrot, q);
433                 }
434
435                 iktarget = iktree[target->tip];
436
437                 if ((data->flag & CONSTRAINT_IK_POS) && data->weight != 0.0f) {
438                         if (poleconstrain)
439                                 IK_SolverSetPoleVectorConstraint(solver, iktarget, goalpos,
440                                                                  polepos, data->poleangle, (poleangledata == data));
441                         IK_SolverAddGoal(solver, iktarget, goalpos, data->weight);
442                 }
443                 if ((data->flag & CONSTRAINT_IK_ROT) && (data->orientweight != 0.0f))
444                         if ((data->flag & CONSTRAINT_IK_AUTO) == 0)
445                                 IK_SolverAddGoalOrientation(solver, iktarget, goalrot,
446                                                             data->orientweight);
447         }
448
449         /* solve */
450         IK_Solve(solver, 0.0f, tree->iterations);
451
452         if (poleangledata)
453                 poleangledata->poleangle = IK_SolverGetPoleAngle(solver);
454
455         IK_FreeSolver(solver);
456
457         /* gather basis changes */
458         tree->basis_change = MEM_mallocN(sizeof(float[3][3]) * tree->totchannel, "ik basis change");
459         if (hasstretch)
460                 ikstretch = MEM_mallocN(sizeof(float) * tree->totchannel, "ik stretch");
461
462         for (a = 0; a < tree->totchannel; a++) {
463                 IK_GetBasisChange(iktree[a], tree->basis_change[a]);
464
465                 if (hasstretch) {
466                         /* have to compensate for scaling received from parent */
467                         float parentstretch, stretch;
468
469                         pchan = tree->pchan[a];
470                         parentstretch = (tree->parent[a] >= 0) ? ikstretch[tree->parent[a]] : 1.0f;
471
472                         if (tree->stretch && (pchan->ikstretch > 0.0f)) {
473                                 float trans[3], length;
474
475                                 IK_GetTranslationChange(iktree[a], trans);
476                                 length = pchan->bone->length * len_v3(pchan->pose_mat[1]);
477
478                                 ikstretch[a] = (length == 0.0f) ? 1.0f : (trans[1] + length) / length;
479                         }
480                         else
481                                 ikstretch[a] = 1.0;
482
483                         stretch = (parentstretch == 0.0f) ? 1.0f : ikstretch[a] / parentstretch;
484
485                         mul_v3_fl(tree->basis_change[a][0], stretch);
486                         mul_v3_fl(tree->basis_change[a][1], stretch);
487                         mul_v3_fl(tree->basis_change[a][2], stretch);
488                 }
489
490                 if (resultblend && resultinf != 1.0f) {
491                         unit_m3(identity);
492                         blend_m3_m3m3(tree->basis_change[a], identity,
493                                       tree->basis_change[a], resultinf);
494                 }
495
496                 IK_FreeSegment(iktree[a]);
497         }
498
499         MEM_freeN(iktree);
500         if (ikstretch) MEM_freeN(ikstretch);
501 }
502
503 static void free_posetree(PoseTree *tree)
504 {
505         BLI_freelistN(&tree->targets);
506         if (tree->pchan) MEM_freeN(tree->pchan);
507         if (tree->parent) MEM_freeN(tree->parent);
508         if (tree->basis_change) MEM_freeN(tree->basis_change);
509         MEM_freeN(tree);
510 }
511
512 ///----------------------------------------
513 /// Plugin API for legacy iksolver
514
515 void iksolver_initialize_tree(struct Scene *UNUSED(scene), struct Object *ob, float UNUSED(ctime))
516 {
517         bPoseChannel *pchan;
518
519         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
520                 if (pchan->constflag & PCHAN_HAS_IK) // flag is set on editing constraints
521                         initialize_posetree(ob, pchan);  // will attach it to root!
522         }
523         ob->pose->flag &= ~POSE_WAS_REBUILT;
524 }
525
526 void iksolver_execute_tree(struct Scene *scene, struct Object *ob,  struct bPoseChannel *pchan, float ctime)
527 {
528         while (pchan->iktree.first) {
529                 PoseTree *tree = pchan->iktree.first;
530                 int a;
531
532                 /* stop on the first tree that isn't a standard IK chain */
533                 if (tree->type != CONSTRAINT_TYPE_KINEMATIC)
534                         return;
535
536                 /* 4. walk over the tree for regular solving */
537                 for (a = 0; a < tree->totchannel; a++) {
538                         if (!(tree->pchan[a]->flag & POSE_DONE))    // successive trees can set the flag
539                                 BKE_pose_where_is_bone(scene, ob, tree->pchan[a], ctime, 1);
540                         /* tell blender that this channel was controlled by IK, it's cleared on each BKE_pose_where_is() */
541                         tree->pchan[a]->flag |= POSE_CHAIN;
542                 }
543                 /* 5. execute the IK solver */
544                 execute_posetree(scene, ob, tree);
545
546                 /* 6. apply the differences to the channels,
547                  *    we need to calculate the original differences first */
548                 for (a = 0; a < tree->totchannel; a++) {
549                         make_dmats(tree->pchan[a]);
550                 }
551
552                 for (a = 0; a < tree->totchannel; a++) {
553                         /* sets POSE_DONE */
554                         where_is_ik_bone(tree->pchan[a], tree->basis_change[a]);
555                 }
556
557                 /* 7. and free */
558                 BLI_remlink(&pchan->iktree, tree);
559                 free_posetree(tree);
560         }
561 }
562