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