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