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