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