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