Spline IK: fix continuity issues with influence and curve end rolloff.
[blender.git] / source / blender / blenkernel / intern / armature_update.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2015 Blender Foundation.
17  * All rights reserved.
18  *
19  * Defines and code for core node types
20  */
21
22 /** \file
23  * \ingroup bke
24  */
25
26 #include "MEM_guardedalloc.h"
27
28 #include "BLI_utildefines.h"
29 #include "BLI_listbase.h"
30 #include "BLI_math.h"
31
32 #include "DNA_armature_types.h"
33 #include "DNA_constraint_types.h"
34 #include "DNA_object_types.h"
35 #include "DNA_scene_types.h"
36
37 #include "BKE_action.h"
38 #include "BKE_anim.h"
39 #include "BKE_armature.h"
40 #include "BKE_curve.h"
41 #include "BKE_displist.h"
42 #include "BKE_fcurve.h"
43 #include "BKE_object.h"
44 #include "BKE_scene.h"
45
46 #include "BIK_api.h"
47
48
49 #include "DEG_depsgraph.h"
50
51 /* ********************** SPLINE IK SOLVER ******************* */
52
53 /* Temporary evaluation tree data used for Spline IK */
54 typedef struct tSplineIK_Tree {
55         struct tSplineIK_Tree *next, *prev;
56
57         int type;                    /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
58
59         short chainlen;              /* number of bones in the chain */
60         float totlength;             /* total length of bones in the chain */
61
62         const float *points;         /* parametric positions for the joints along the curve */
63         bPoseChannel **chain;        /* chain of bones to affect using Spline IK (ordered from the tip) */
64
65         bPoseChannel *root;          /* bone that is the root node of the chain */
66
67         bConstraint *con;            /* constraint for this chain */
68         bSplineIKConstraint *ikData; /* constraint settings for this chain */
69 } tSplineIK_Tree;
70
71 /* ----------- */
72
73 /* Tag the bones in the chain formed by the given bone for IK */
74 static void splineik_init_tree_from_pchan(Scene *UNUSED(scene), Object *UNUSED(ob), bPoseChannel *pchan_tip)
75 {
76         bPoseChannel *pchan, *pchanRoot = NULL;
77         bPoseChannel *pchanChain[255];
78         bConstraint *con = NULL;
79         bSplineIKConstraint *ikData = NULL;
80         float boneLengths[255];
81         float totLength = 0.0f;
82         int segcount = 0;
83
84         /* find the SplineIK constraint */
85         for (con = pchan_tip->constraints.first; con; con = con->next) {
86                 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
87                         ikData = con->data;
88
89                         /* target can only be curve */
90                         if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))
91                                 continue;
92                         /* skip if disabled */
93                         if ((con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)))
94                                 continue;
95
96                         /* otherwise, constraint is ok... */
97                         break;
98                 }
99         }
100         if (con == NULL)
101                 return;
102
103         /* find the root bone and the chain of bones from the root to the tip
104          * NOTE: this assumes that the bones are connected, but that may not be true... */
105         for (pchan = pchan_tip; pchan && (segcount < ikData->chainlen); pchan = pchan->parent, segcount++) {
106                 /* store this segment in the chain */
107                 pchanChain[segcount] = pchan;
108
109                 /* if performing rebinding, calculate the length of the bone */
110                 boneLengths[segcount] = pchan->bone->length;
111                 totLength += boneLengths[segcount];
112         }
113
114         if (segcount == 0)
115                 return;
116         else
117                 pchanRoot = pchanChain[segcount - 1];
118
119         /* perform binding step if required */
120         if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
121                 float segmentLen = (1.0f / (float)segcount);
122                 int i;
123
124                 /* setup new empty array for the points list */
125                 if (ikData->points)
126                         MEM_freeN(ikData->points);
127                 ikData->numpoints = ikData->chainlen + 1;
128                 ikData->points = MEM_mallocN(sizeof(float) * ikData->numpoints, "Spline IK Binding");
129
130                 /* bind 'tip' of chain (i.e. first joint = tip of bone with the Spline IK Constraint) */
131                 ikData->points[0] = 1.0f;
132
133                 /* perform binding of the joints to parametric positions along the curve based
134                  * proportion of the total length that each bone occupies
135                  */
136                 for (i = 0; i < segcount; i++) {
137                         /* 'head' joints, traveling towards the root of the chain
138                          * - 2 methods; the one chosen depends on whether we've got usable lengths
139                          */
140                         if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
141                                 /* 1) equi-spaced joints */
142                                 ikData->points[i + 1] = ikData->points[i] - segmentLen;
143                         }
144                         else {
145                                 /* 2) to find this point on the curve, we take a step from the previous joint
146                                  *    a distance given by the proportion that this bone takes
147                                  */
148                                 ikData->points[i + 1] = ikData->points[i] - (boneLengths[i] / totLength);
149                         }
150                 }
151
152                 /* spline has now been bound */
153                 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
154         }
155
156         /* disallow negative values (happens with float precision) */
157         CLAMP_MIN(ikData->points[segcount], 0.0f);
158
159         /* make a new Spline-IK chain, and store it in the IK chains */
160         /* TODO: we should check if there is already an IK chain on this, since that would take precedence... */
161         {
162                 /* make new tree */
163                 tSplineIK_Tree *tree = MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
164                 tree->type = CONSTRAINT_TYPE_SPLINEIK;
165
166                 tree->chainlen = segcount;
167                 tree->totlength = totLength;
168
169                 /* copy over the array of links to bones in the chain (from tip to root) */
170                 tree->chain = MEM_mallocN(sizeof(bPoseChannel *) * segcount, "SplineIK Chain");
171                 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel *) * segcount);
172
173                 /* store reference to joint position array */
174                 tree->points = ikData->points;
175
176                 /* store references to different parts of the chain */
177                 tree->root = pchanRoot;
178                 tree->con = con;
179                 tree->ikData = ikData;
180
181                 /* AND! link the tree to the root */
182                 BLI_addtail(&pchanRoot->siktree, tree);
183         }
184
185         /* mark root channel having an IK tree */
186         pchanRoot->flag |= POSE_IKSPLINE;
187 }
188
189 /* Tag which bones are members of Spline IK chains */
190 static void splineik_init_tree(Scene *scene, Object *ob, float UNUSED(ctime))
191 {
192         bPoseChannel *pchan;
193
194         /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
195         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
196                 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
197                         splineik_init_tree_from_pchan(scene, ob, pchan);
198         }
199 }
200
201 /* ----------- */
202
203 typedef struct tSplineIk_EvalState {
204         float curve_position;        /* Current position along the curve. */
205         float curve_scale;           /* Global scale to apply to curve positions. */
206         float locrot_offset[4][4];   /* Bone rotation and location offset inherited from parent. */
207 } tSplineIk_EvalState;
208
209 /* Prepare data to evaluate spline IK. */
210 static bool splineik_evaluate_init(tSplineIK_Tree *tree, tSplineIk_EvalState *state)
211 {
212         bSplineIKConstraint *ikData = tree->ikData;
213
214         /* Make sure that the constraint targets are ok, to avoid crashes
215          * in case of a depsgraph bug or dependency cycle.
216          */
217         if (ikData->tar == NULL) {
218                 return false;
219         }
220
221         CurveCache *cache = ikData->tar->runtime.curve_cache;
222
223         if (ELEM(NULL, cache, cache->path, cache->path->data)) {
224                 return false;
225         }
226
227         /* Initialize the evaluation state. */
228         state->curve_position = 0.0f;
229         state->curve_scale = 1.0f;
230         unit_m4(state->locrot_offset);
231
232         /* Apply corrections for sensitivity to scaling. */
233         if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (tree->totlength != 0.0f)) {
234                 /* get the current length of the curve */
235                 /* NOTE: this is assumed to be correct even after the curve was resized */
236                 float splineLen = cache->path->totdist;
237
238                 /* calculate the scale factor to multiply all the path values by so that the
239                  * bone chain retains its current length, such that
240                  *     maxScale * splineLen = totLength
241                  */
242                 state->curve_scale = tree->totlength / splineLen;
243         }
244
245         return true;
246 }
247
248 /* Evaluate spline IK for a given bone. */
249 static void splineik_evaluate_bone(tSplineIK_Tree *tree, Object *ob, bPoseChannel *pchan, int index, tSplineIk_EvalState *state)
250 {
251         bSplineIKConstraint *ikData = tree->ikData;
252         float origHead[3], origTail[3], poseHead[3], poseTail[3], basePoseMat[3][3], poseMat[3][3];
253         float splineVec[3], scaleFac, radius = 1.0f;
254         float tailBlendFac = 0.0f;
255
256         mul_v3_m4v3(poseHead, state->locrot_offset, pchan->pose_head);
257         mul_v3_m4v3(poseTail, state->locrot_offset, pchan->pose_tail);
258
259         copy_v3_v3(origHead, poseHead);
260
261         /* first, adjust the point positions on the curve */
262         float curveLen = tree->points[index] - tree->points[index + 1];
263         float pointStart = state->curve_position;
264         float baseScale = 1.0f;
265         float pointEnd = pointStart + curveLen * baseScale * state->curve_scale;
266
267         state->curve_position = pointEnd;
268
269         /* step 1: determine the positions for the endpoints of the bone */
270         if (pointStart < 1.0f) {
271                 float vec[4], dir[3], rad;
272
273                 /* determine if the bone should still be affected by SplineIK */
274                 if (pointEnd >= 1.0f) {
275                         /* blending factor depends on the amount of the bone still left on the chain */
276                         tailBlendFac = (1.0f - pointStart) / (pointEnd - pointStart);
277                 }
278                 else {
279                         tailBlendFac = 1.0f;
280                 }
281
282                 /* tail endpoint */
283                 if (where_on_path(ikData->tar, pointEnd, vec, dir, NULL, &rad, NULL)) {
284                         /* apply curve's object-mode transforms to the position
285                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
286                          */
287                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
288                                 mul_m4_v3(ikData->tar->obmat, vec);
289
290                         /* convert the position to pose-space, then store it */
291                         mul_m4_v3(ob->imat, vec);
292                         copy_v3_v3(poseTail, vec);
293
294                         /* set the new radius */
295                         radius = rad;
296                 }
297
298                 /* head endpoint */
299                 if (where_on_path(ikData->tar, pointStart, vec, dir, NULL, &rad, NULL)) {
300                         /* apply curve's object-mode transforms to the position
301                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
302                          */
303                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
304                                 mul_m4_v3(ikData->tar->obmat, vec);
305
306                         /* store the position, and convert it to pose space */
307                         mul_m4_v3(ob->imat, vec);
308                         copy_v3_v3(poseHead, vec);
309
310                         /* set the new radius (it should be the average value) */
311                         radius = (radius + rad) / 2;
312                 }
313         }
314
315         /* step 2: determine the implied transform from these endpoints
316          *     - splineVec: the vector direction that the spline applies on the bone
317          *     - scaleFac: the factor that the bone length is scaled by to get the desired amount
318          */
319         sub_v3_v3v3(splineVec, poseTail, poseHead);
320         scaleFac = len_v3(splineVec) / pchan->bone->length;
321
322         /* Adjust the scale factor towards the neutral state when rolling off the curve end. */
323         scaleFac = interpf(scaleFac, baseScale, tailBlendFac);
324
325         /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis
326          *      - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
327          */
328         {
329                 float dmat[3][3], rmat[3][3];
330                 float raxis[3], rangle;
331
332                 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
333                  * orientation-relevant axes, and normalizing them
334                  */
335                 mul_m3_m4m4(basePoseMat, state->locrot_offset, pchan->pose_mat);
336                 normalize_m3_m3(rmat, basePoseMat);
337
338                 /* also, normalize the orientation imposed by the bone, now that we've extracted the scale factor */
339                 normalize_v3(splineVec);
340
341                 /* calculate smallest axis-angle rotation necessary for getting from the
342                  * current orientation of the bone, to the spline-imposed direction
343                  */
344                 cross_v3_v3v3(raxis, rmat[1], splineVec);
345
346                 rangle = dot_v3v3(rmat[1], splineVec);
347                 CLAMP(rangle, -1.0f, 1.0f);
348                 rangle = acosf(rangle);
349
350                 /* multiply the magnitude of the angle by the influence of the constraint to
351                  * control the influence of the SplineIK effect
352                  */
353                 rangle *= tree->con->enforce * tailBlendFac;
354
355                 /* construct rotation matrix from the axis-angle rotation found above
356                  * - this call takes care to make sure that the axis provided is a unit vector first
357                  */
358                 axis_angle_to_mat3(dmat, raxis, rangle);
359
360                 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
361                  * while still maintaining roll control from the existing bone animation
362                  */
363                 mul_m3_m3m3(poseMat, dmat, rmat);
364                 normalize_m3(poseMat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
365
366                 mul_m3_m3m3(basePoseMat, dmat, basePoseMat);
367
368                 /* apply rotation to the accumulated parent transform */
369                 mul_m4_m3m4(state->locrot_offset, dmat, state->locrot_offset);
370         }
371
372         /* step 4: set the scaling factors for the axes */
373         {
374                 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
375                 mul_v3_fl(poseMat[1], scaleFac);
376
377                 /* set the scaling factors of the x and z axes from... */
378                 switch (ikData->xzScaleMode) {
379                         case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
380                         {
381                                 /* original scales get used */
382                                 float scale;
383
384                                 /* x-axis scale */
385                                 scale = len_v3(pchan->pose_mat[0]);
386                                 mul_v3_fl(poseMat[0], scale);
387                                 /* z-axis scale */
388                                 scale = len_v3(pchan->pose_mat[2]);
389                                 mul_v3_fl(poseMat[2], scale);
390                                 break;
391                         }
392                         case CONSTRAINT_SPLINEIK_XZS_INVERSE:
393                         {
394                                 /* old 'volume preservation' method using the inverse scale */
395                                 float scale;
396
397                                 /* calculate volume preservation factor which is
398                                  * basically the inverse of the y-scaling factor
399                                  */
400                                 if (fabsf(scaleFac) != 0.0f) {
401                                         scale = 1.0f / fabsf(scaleFac);
402
403                                         /* we need to clamp this within sensible values */
404                                         /* NOTE: these should be fine for now, but should get sanitised in future */
405                                         CLAMP(scale, 0.0001f, 100000.0f);
406                                 }
407                                 else
408                                         scale = 1.0f;
409
410                                 /* apply the scaling */
411                                 mul_v3_fl(poseMat[0], scale);
412                                 mul_v3_fl(poseMat[2], scale);
413                                 break;
414                         }
415                         case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
416                         {
417                                 /* improved volume preservation based on the Stretch To constraint */
418                                 float final_scale;
419
420                                 /* as the basis for volume preservation, we use the inverse scale factor... */
421                                 if (fabsf(scaleFac) != 0.0f) {
422                                         /* NOTE: The method here is taken wholesale from the Stretch To constraint */
423                                         float bulge = powf(1.0f / fabsf(scaleFac), ikData->bulge);
424
425                                         if (bulge > 1.0f) {
426                                                 if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MAX) {
427                                                         float bulge_max = max_ff(ikData->bulge_max, 1.0f);
428                                                         float hard = min_ff(bulge, bulge_max);
429
430                                                         float range = bulge_max - 1.0f;
431                                                         float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
432                                                         float soft = 1.0f + range * atanf((bulge - 1.0f) * scale) / (float)M_PI_2;
433
434                                                         bulge = interpf(soft, hard, ikData->bulge_smooth);
435                                                 }
436                                         }
437                                         if (bulge < 1.0f) {
438                                                 if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MIN) {
439                                                         float bulge_min = CLAMPIS(ikData->bulge_min, 0.0f, 1.0f);
440                                                         float hard = max_ff(bulge, bulge_min);
441
442                                                         float range = 1.0f - bulge_min;
443                                                         float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
444                                                         float soft = 1.0f - range * atanf((1.0f - bulge) * scale) / (float)M_PI_2;
445
446                                                         bulge = interpf(soft, hard, ikData->bulge_smooth);
447                                                 }
448                                         }
449
450                                         /* compute scale factor for xz axes from this value */
451                                         final_scale = sqrtf(bulge);
452                                 }
453                                 else {
454                                         /* no scaling, so scale factor is simple */
455                                         final_scale = 1.0f;
456                                 }
457
458                                 /* apply the scaling (assuming normalised scale) */
459                                 mul_v3_fl(poseMat[0], final_scale);
460                                 mul_v3_fl(poseMat[2], final_scale);
461                                 break;
462                         }
463                 }
464
465                 /* finally, multiply the x and z scaling by the radius of the curve too,
466                  * to allow automatic scales to get tweaked still
467                  */
468                 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
469                         mul_v3_fl(poseMat[0], radius);
470                         mul_v3_fl(poseMat[2], radius);
471                 }
472         }
473
474         /* Blend the scaling of the matrix according to the influence. */
475         sub_m3_m3m3(poseMat, poseMat, basePoseMat);
476         madd_m3_m3m3fl(poseMat, basePoseMat, poseMat, tree->con->enforce * tailBlendFac);
477
478         /* step 5: set the location of the bone in the matrix */
479         if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
480                 /* when the 'no-root' option is affected, the chain can retain
481                  * the shape but be moved elsewhere
482                  */
483                 copy_v3_v3(poseHead, origHead);
484         }
485         else if (tree->con->enforce < 1.0f) {
486                 /* when the influence is too low
487                  * - blend the positions for the 'root' bone
488                  * - stick to the parent for any other
489                  */
490                 if (index < tree->chainlen - 1) {
491                         copy_v3_v3(poseHead, origHead);
492                 }
493                 else {
494                         interp_v3_v3v3(poseHead, origHead, poseHead, tree->con->enforce);
495                 }
496         }
497
498         /* finally, store the new transform */
499         copy_m4_m3(pchan->pose_mat, poseMat);
500         copy_v3_v3(pchan->pose_mat[3], poseHead);
501         copy_v3_v3(pchan->pose_head, poseHead);
502
503         mul_v3_mat3_m4v3(origTail, state->locrot_offset, pchan->pose_tail);
504
505         /* recalculate tail, as it's now outdated after the head gets adjusted above! */
506         BKE_pose_where_is_bone_tail(pchan);
507
508         /* update the offset in the accumulated parent transform */
509         sub_v3_v3v3(state->locrot_offset[3], pchan->pose_tail, origTail);
510
511         /* done! */
512         pchan->flag |= POSE_DONE;
513 }
514
515 /* Evaluate the chain starting from the nominated bone */
516 static void splineik_execute_tree(struct Depsgraph *depsgraph, Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
517 {
518         tSplineIK_Tree *tree;
519
520         /* for each pose-tree, execute it if it is spline, otherwise just free it */
521         while ((tree = pchan_root->siktree.first) != NULL) {
522                 int i;
523
524                 /* Firstly, calculate the bone matrix the standard way, since this is needed for roll control. */
525                 for (i = tree->chainlen - 1; i >= 0; i--) {
526                         BKE_pose_where_is_bone(depsgraph, scene, ob, tree->chain[i], ctime, 1);
527                 }
528
529                 /* After that, evaluate the actual Spline IK, unless there are missing dependencies. */
530                 tSplineIk_EvalState state;
531
532                 if (splineik_evaluate_init(tree, &state)) {
533                         /* Walk over each bone in the chain, calculating the effects of spline IK
534                          *     - the chain is traversed in the opposite order to storage order (i.e. parent to children)
535                          *       so that dependencies are correct
536                          */
537                         for (i = tree->chainlen - 1; i >= 0; i--) {
538                                 bPoseChannel *pchan = tree->chain[i];
539                                 splineik_evaluate_bone(tree, ob, pchan, i, &state);
540                         }
541                 }
542
543                 /* free the tree info specific to SplineIK trees now */
544                 if (tree->chain)
545                         MEM_freeN(tree->chain);
546
547                 /* free this tree */
548                 BLI_freelinkN(&pchan_root->siktree, tree);
549         }
550 }
551
552 void BKE_pose_splineik_init_tree(Scene *scene, Object *ob, float ctime)
553 {
554         splineik_init_tree(scene, ob, ctime);
555 }
556
557 void BKE_splineik_execute_tree(
558         struct Depsgraph *depsgraph, Scene *scene,
559         Object *ob, bPoseChannel *pchan_root, float ctime)
560 {
561         splineik_execute_tree(depsgraph, scene, ob, pchan_root, ctime);
562 }
563
564 /* *************** Depsgraph evaluation callbacks ************ */
565
566 void BKE_pose_pchan_index_rebuild(bPose *pose)
567 {
568         MEM_SAFE_FREE(pose->chan_array);
569         const int num_channels = BLI_listbase_count(&pose->chanbase);
570         pose->chan_array = MEM_malloc_arrayN(
571                 num_channels, sizeof(bPoseChannel *), "pose->chan_array");
572         int pchan_index = 0;
573         for (bPoseChannel *pchan = pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
574                 pose->chan_array[pchan_index++] = pchan;
575         }
576 }
577
578 BLI_INLINE bPoseChannel *pose_pchan_get_indexed(Object *ob, int pchan_index)
579 {
580         bPose *pose = ob->pose;
581         BLI_assert(pose != NULL);
582         BLI_assert(pose->chan_array != NULL);
583         BLI_assert(pchan_index >= 0);
584         BLI_assert(pchan_index < MEM_allocN_len(pose->chan_array) / sizeof(bPoseChannel *));
585         return pose->chan_array[pchan_index];
586 }
587
588 void BKE_pose_eval_init(struct Depsgraph *depsgraph,
589                         Scene *UNUSED(scene),
590                         Object *object)
591 {
592         bPose *pose = object->pose;
593         BLI_assert(pose != NULL);
594
595         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
596
597         BLI_assert(object->type == OB_ARMATURE);
598
599         /* We demand having proper pose. */
600         BLI_assert(object->pose != NULL);
601         BLI_assert((object->pose->flag & POSE_RECALC) == 0);
602
603         /* imat is needed for solvers. */
604         invert_m4_m4(object->imat, object->obmat);
605
606         /* clear flags */
607         for (bPoseChannel *pchan = pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
608                 pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
609
610                 /* Free B-Bone shape data cache if it's not a B-Bone. */
611                 if (pchan->bone == NULL || pchan->bone->segments <= 1) {
612                         BKE_pose_channel_free_bbone_cache(pchan);
613                 }
614         }
615
616         BLI_assert(pose->chan_array != NULL || BLI_listbase_is_empty(&pose->chanbase));
617
618         BKE_armature_cached_bbone_deformation_free_data(object);
619 }
620
621 void BKE_pose_eval_init_ik(struct Depsgraph *depsgraph,
622                            Scene *scene,
623                            Object *object)
624 {
625         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
626         BLI_assert(object->type == OB_ARMATURE);
627         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
628         bArmature *armature = (bArmature *)object->data;
629         if (armature->flag & ARM_RESTPOS) {
630                 return;
631         }
632         /* construct the IK tree (standard IK) */
633         BIK_initialize_tree(depsgraph, scene, object, ctime);
634         /* construct the Spline IK trees
635          * - this is not integrated as an IK plugin, since it should be able
636          *   to function in conjunction with standard IK.  */
637         BKE_pose_splineik_init_tree(scene, object, ctime);
638 }
639
640 void BKE_pose_eval_bone(struct Depsgraph *depsgraph,
641                         Scene *scene,
642                         Object *object,
643                         int pchan_index)
644 {
645         const bArmature *armature = (bArmature *)object->data;
646         if (armature->edbo != NULL) {
647                 return;
648         }
649         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
650         DEG_debug_print_eval_subdata(
651                 depsgraph, __func__, object->id.name, object,
652                 "pchan", pchan->name, pchan);
653         BLI_assert(object->type == OB_ARMATURE);
654         if (armature->flag & ARM_RESTPOS) {
655                 Bone *bone = pchan->bone;
656                 if (bone) {
657                         copy_m4_m4(pchan->pose_mat, bone->arm_mat);
658                         copy_v3_v3(pchan->pose_head, bone->arm_head);
659                         copy_v3_v3(pchan->pose_tail, bone->arm_tail);
660                 }
661         }
662         else {
663                 /* TODO(sergey): Currently if there are constraints full transform is
664                  * being evaluated in BKE_pose_constraints_evaluate. */
665                 if (pchan->constraints.first == NULL) {
666                         if (pchan->flag & POSE_IKTREE || pchan->flag & POSE_IKSPLINE) {
667                                 /* pass */
668                         }
669                         else {
670                                 if ((pchan->flag & POSE_DONE) == 0) {
671                                         /* TODO(sergey): Use time source node for time. */
672                                         float ctime = BKE_scene_frame_get(scene); /* not accurate... */
673                                         BKE_pose_where_is_bone(depsgraph, scene, object, pchan, ctime, 1);
674                                 }
675                         }
676                 }
677         }
678 }
679
680 void BKE_pose_constraints_evaluate(struct Depsgraph *depsgraph,
681                                    Scene *scene,
682                                    Object *object,
683                                    int pchan_index)
684 {
685         const bArmature *armature = (bArmature *)object->data;
686         if (armature->edbo != NULL) {
687                 return;
688         }
689         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
690         DEG_debug_print_eval_subdata(
691                 depsgraph, __func__, object->id.name, object,
692                 "pchan", pchan->name, pchan);
693         if (armature->flag & ARM_RESTPOS) {
694                 return;
695         }
696         else if (pchan->flag & POSE_IKTREE || pchan->flag & POSE_IKSPLINE) {
697                 /* IK are being solved separately/ */
698         }
699         else {
700                 if ((pchan->flag & POSE_DONE) == 0) {
701                         float ctime = BKE_scene_frame_get(scene); /* not accurate... */
702                         BKE_pose_where_is_bone(depsgraph, scene, object, pchan, ctime, 1);
703                 }
704         }
705 }
706
707 void BKE_pose_bone_done(struct Depsgraph *depsgraph,
708                         struct Object *object,
709                         int pchan_index)
710 {
711         const bArmature *armature = (bArmature *)object->data;
712         if (armature->edbo != NULL) {
713                 return;
714         }
715         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
716         float imat[4][4];
717         DEG_debug_print_eval_subdata(
718                 depsgraph, __func__, object->id.name, object,
719                 "pchan", pchan->name, pchan);
720         if (pchan->bone) {
721                 invert_m4_m4(imat, pchan->bone->arm_mat);
722                 mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
723         }
724         if (DEG_is_active(depsgraph) && armature->edbo == NULL) {
725                 bPoseChannel *pchan_orig = pchan->orig_pchan;
726                 copy_m4_m4(pchan_orig->pose_mat, pchan->pose_mat);
727                 copy_m4_m4(pchan_orig->chan_mat, pchan->chan_mat);
728                 copy_v3_v3(pchan_orig->pose_head, pchan->pose_mat[3]);
729                 copy_m4_m4(pchan_orig->constinv, pchan->constinv);
730                 BKE_pose_where_is_bone_tail(pchan_orig);
731                 if (pchan->bone == NULL || pchan->bone->segments <= 1) {
732                         BKE_pose_channel_free_bbone_cache(pchan_orig);
733                 }
734         }
735 }
736
737 void BKE_pose_eval_bbone_segments(struct Depsgraph *depsgraph,
738                                   struct Object *object,
739                                   int pchan_index)
740 {
741         const bArmature *armature = (bArmature *)object->data;
742         if (armature->edbo != NULL) {
743                 return;
744         }
745         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
746         DEG_debug_print_eval_subdata(
747                 depsgraph, __func__, object->id.name, object,
748                 "pchan", pchan->name, pchan);
749         if (pchan->bone != NULL && pchan->bone->segments > 1) {
750                 BKE_pchan_bbone_segments_cache_compute(pchan);
751                 if (DEG_is_active(depsgraph)) {
752                         BKE_pchan_bbone_segments_cache_copy(pchan->orig_pchan, pchan);
753                 }
754         }
755 }
756
757 void BKE_pose_iktree_evaluate(struct Depsgraph *depsgraph,
758                               Scene *scene,
759                               Object *object,
760                               int rootchan_index)
761 {
762         const bArmature *armature = (bArmature *)object->data;
763         if (armature->edbo != NULL) {
764                 return;
765         }
766         bPoseChannel *rootchan = pose_pchan_get_indexed(object, rootchan_index);
767         DEG_debug_print_eval_subdata(
768                 depsgraph, __func__, object->id.name, object,
769                 "rootchan", rootchan->name, rootchan);
770         BLI_assert(object->type == OB_ARMATURE);
771         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
772         if (armature->flag & ARM_RESTPOS) {
773                 return;
774         }
775         BIK_execute_tree(depsgraph, scene, object, rootchan, ctime);
776 }
777
778 void BKE_pose_splineik_evaluate(struct Depsgraph *depsgraph,
779                                 Scene *scene,
780                                 Object *object,
781                                 int rootchan_index)
782
783 {
784         const bArmature *armature = (bArmature *)object->data;
785         if (armature->edbo != NULL) {
786                 return;
787         }
788         bPoseChannel *rootchan = pose_pchan_get_indexed(object, rootchan_index);
789         DEG_debug_print_eval_subdata(
790                 depsgraph, __func__, object->id.name, object,
791                 "rootchan", rootchan->name, rootchan);
792         BLI_assert(object->type == OB_ARMATURE);
793         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
794         if (armature->flag & ARM_RESTPOS) {
795                 return;
796         }
797         BKE_splineik_execute_tree(depsgraph, scene, object, rootchan, ctime);
798 }
799
800 /* Common part for both original and proxy armatrues. */
801 static void pose_eval_done_common(struct Depsgraph *depsgraph, Object *object)
802 {
803         const bArmature *armature = (bArmature *)object->data;
804         if (armature->edbo != NULL) {
805                 return;
806         }
807         bPose *pose = object->pose;
808         UNUSED_VARS_NDEBUG(pose);
809         BLI_assert(pose != NULL);
810         BKE_armature_cached_bbone_deformation_update(object);
811         BKE_object_eval_boundbox(depsgraph, object);
812 }
813 static void pose_eval_cleanup_common(Object *object)
814 {
815         bPose *pose = object->pose;
816         BLI_assert(pose != NULL);
817         BLI_assert(pose->chan_array != NULL || BLI_listbase_is_empty(&pose->chanbase));
818 }
819
820 void BKE_pose_eval_done(struct Depsgraph *depsgraph, Object *object)
821 {
822         bPose *pose = object->pose;
823         BLI_assert(pose != NULL);
824         UNUSED_VARS_NDEBUG(pose);
825         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
826         BLI_assert(object->type == OB_ARMATURE);
827         pose_eval_done_common(depsgraph, object);
828 }
829
830 void BKE_pose_eval_cleanup(struct Depsgraph *depsgraph,
831                            Scene *scene,
832                            Object *object)
833 {
834         bPose *pose = object->pose;
835         BLI_assert(pose != NULL);
836         UNUSED_VARS_NDEBUG(pose);
837         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
838         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
839         BLI_assert(object->type == OB_ARMATURE);
840         /* Release the IK tree. */
841         BIK_release_tree(scene, object, ctime);
842         pose_eval_cleanup_common(object);
843 }
844
845 void BKE_pose_eval_proxy_init(struct Depsgraph *depsgraph, Object *object)
846 {
847         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
848         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
849
850         BLI_assert(object->pose->chan_array != NULL || BLI_listbase_is_empty(&object->pose->chanbase));
851
852         BKE_armature_cached_bbone_deformation_free_data(object);
853 }
854
855 void BKE_pose_eval_proxy_done(struct Depsgraph *depsgraph, Object *object)
856 {
857         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
858         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
859         pose_eval_done_common(depsgraph, object);
860 }
861
862 void BKE_pose_eval_proxy_cleanup(struct Depsgraph *depsgraph, Object *object)
863 {
864         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
865         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
866         pose_eval_cleanup_common(object);
867 }
868
869 void BKE_pose_eval_proxy_copy_bone(
870         struct Depsgraph *depsgraph,
871         Object *object,
872         int pchan_index)
873 {
874         const bArmature *armature = (bArmature *)object->data;
875         if (armature->edbo != NULL) {
876                 return;
877         }
878         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
879         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
880         DEG_debug_print_eval_subdata(
881                 depsgraph, __func__, object->id.name, object,
882                 "pchan", pchan->name, pchan);
883         /* TODO(sergey): Use indexec lookup, once it's guaranteed to be kept
884          * around for the time while proxies are evaluating.
885          */
886 #if 0
887         bPoseChannel *pchan_from = pose_pchan_get_indexed(
888                 object->proxy_from, pchan_index);
889 #else
890         bPoseChannel *pchan_from = BKE_pose_channel_find_name(
891                 object->proxy_from->pose, pchan->name);
892 #endif
893         BLI_assert(pchan != NULL);
894         BLI_assert(pchan_from != NULL);
895         BKE_pose_copyesult_pchan_result(pchan, pchan_from);
896         BKE_pchan_bbone_segments_cache_copy(pchan, pchan_from);
897 }