Depsgraph: remove EvaluationContext, pass Depsgraph instead.
[blender.git] / source / blender / blenkernel / intern / armature.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/armature.c
27  *  \ingroup bke
28  */
29
30
31 #include <ctype.h>
32 #include <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_math.h"
41 #include "BLI_listbase.h"
42 #include "BLI_string.h"
43 #include "BLI_ghash.h"
44 #include "BLI_task.h"
45 #include "BLI_utildefines.h"
46
47 #include "DNA_anim_types.h"
48 #include "DNA_armature_types.h"
49 #include "DNA_constraint_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_lattice_types.h"
52 #include "DNA_listBase.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_object_types.h"
56
57 #include "BKE_animsys.h"
58 #include "BKE_armature.h"
59 #include "BKE_action.h"
60 #include "BKE_anim.h"
61 #include "BKE_constraint.h"
62 #include "BKE_curve.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_deform.h"
65 #include "BKE_displist.h"
66 #include "BKE_idprop.h"
67 #include "BKE_library.h"
68 #include "BKE_library_query.h"
69 #include "BKE_library_remap.h"
70 #include "BKE_lattice.h"
71 #include "BKE_main.h"
72 #include "BKE_object.h"
73 #include "BKE_scene.h"
74
75 #include "BIK_api.h"
76 #include "BKE_sketch.h"
77
78 /* **************** Generic Functions, data level *************** */
79
80 bArmature *BKE_armature_add(Main *bmain, const char *name)
81 {
82         bArmature *arm;
83
84         arm = BKE_libblock_alloc(bmain, ID_AR, name, 0);
85         arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE;
86         arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
87         arm->layer = 1;
88         arm->ghostsize = 1;
89         return arm;
90 }
91
92 bArmature *BKE_armature_from_object(Object *ob)
93 {
94         if (ob->type == OB_ARMATURE)
95                 return (bArmature *)ob->data;
96         return NULL;
97 }
98
99 int BKE_armature_bonelist_count(ListBase *lb)
100 {
101         int i = 0;
102         for (Bone *bone = lb->first; bone; bone = bone->next) {
103                 i += 1 + BKE_armature_bonelist_count(&bone->childbase);
104         }
105
106         return i;
107 }
108
109 void BKE_armature_bonelist_free(ListBase *lb)
110 {
111         Bone *bone;
112
113         for (bone = lb->first; bone; bone = bone->next) {
114                 if (bone->prop) {
115                         IDP_FreeProperty(bone->prop);
116                         MEM_freeN(bone->prop);
117                 }
118                 BKE_armature_bonelist_free(&bone->childbase);
119         }
120
121         BLI_freelistN(lb);
122 }
123
124 /** Free (or release) any data used by this armature (does not free the armature itself). */
125 void BKE_armature_free(bArmature *arm)
126 {
127         BKE_animdata_free(&arm->id, false);
128
129         BKE_armature_bonelist_free(&arm->bonebase);
130
131         /* free editmode data */
132         if (arm->edbo) {
133                 BLI_freelistN(arm->edbo);
134
135                 MEM_freeN(arm->edbo);
136                 arm->edbo = NULL;
137         }
138
139         /* free sketch */
140         if (arm->sketch) {
141                 freeSketch(arm->sketch);
142                 arm->sketch = NULL;
143         }
144 }
145
146 void BKE_armature_make_local(Main *bmain, bArmature *arm, const bool lib_local)
147 {
148         BKE_id_make_local_generic(bmain, &arm->id, true, lib_local);
149 }
150
151 static void copy_bonechildren(
152         Bone *bone_dst, const Bone *bone_src, const Bone *bone_src_act, Bone **r_bone_dst_act, const int flag)
153 {
154         Bone *bone_src_child, *bone_dst_child;
155
156         if (bone_src == bone_src_act) {
157                 *r_bone_dst_act = bone_dst;
158         }
159
160         if (bone_src->prop) {
161                 bone_dst->prop = IDP_CopyProperty_ex(bone_src->prop, flag);
162         }
163
164         /* Copy this bone's list */
165         BLI_duplicatelist(&bone_dst->childbase, &bone_src->childbase);
166
167         /* For each child in the list, update it's children */
168         for (bone_src_child = bone_src->childbase.first, bone_dst_child = bone_dst->childbase.first;
169              bone_src_child;
170              bone_src_child = bone_src_child->next, bone_dst_child = bone_dst_child->next)
171         {
172                 bone_dst_child->parent = bone_dst;
173                 copy_bonechildren(bone_dst_child, bone_src_child, bone_src_act, r_bone_dst_act, flag);
174         }
175 }
176
177 /**
178  * Only copy internal data of Armature ID from source to already allocated/initialized destination.
179  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
180  *
181  * WARNING! This function will not handle ID user count!
182  *
183  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
184  */
185 void BKE_armature_copy_data(Main *UNUSED(bmain), bArmature *arm_dst, const bArmature *arm_src, const int flag)
186 {
187         Bone *bone_src, *bone_dst;
188         Bone *bone_dst_act = NULL;
189
190         /* We never handle usercount here for own data. */
191         const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
192
193         BLI_duplicatelist(&arm_dst->bonebase, &arm_src->bonebase);
194
195         /* Duplicate the childrens' lists */
196         bone_dst = arm_dst->bonebase.first;
197         for (bone_src = arm_src->bonebase.first; bone_src; bone_src = bone_src->next) {
198                 bone_dst->parent = NULL;
199                 copy_bonechildren(bone_dst, bone_src, arm_src->act_bone, &bone_dst_act, flag_subdata);
200                 bone_dst = bone_dst->next;
201         }
202
203         arm_dst->act_bone = bone_dst_act;
204
205         arm_dst->edbo = NULL;
206         arm_dst->act_edbone = NULL;
207         arm_dst->sketch = NULL;
208 }
209
210 bArmature *BKE_armature_copy(Main *bmain, const bArmature *arm)
211 {
212         bArmature *arm_copy;
213         BKE_id_copy_ex(bmain, &arm->id, (ID **)&arm_copy, 0, false);
214         return arm_copy;
215 }
216
217 static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name)
218 {
219         Bone *curBone, *rbone;
220
221         for (curBone = lb->first; curBone; curBone = curBone->next) {
222                 if (STREQ(curBone->name, name))
223                         return curBone;
224
225                 rbone = get_named_bone_bonechildren(&curBone->childbase, name);
226                 if (rbone)
227                         return rbone;
228         }
229
230         return NULL;
231 }
232
233
234 /**
235  * Walk the list until the bone is found (slow!),
236  * use #BKE_armature_bone_from_name_map for multiple lookups.
237  */
238 Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name)
239 {
240         if (!arm)
241                 return NULL;
242
243         return get_named_bone_bonechildren(&arm->bonebase, name);
244 }
245
246 static void armature_bone_from_name_insert_recursive(GHash *bone_hash, ListBase *lb)
247 {
248         for (Bone *bone = lb->first; bone; bone = bone->next) {
249                 BLI_ghash_insert(bone_hash, bone->name, bone);
250                 armature_bone_from_name_insert_recursive(bone_hash, &bone->childbase);
251         }
252 }
253
254 /**
255  * Create a (name -> bone) map.
256  *
257  * \note typically #bPose.chanhash us used via #BKE_pose_channel_find_name
258  * this is for the cases we can't use pose channels.
259  */
260 GHash *BKE_armature_bone_from_name_map(bArmature *arm)
261 {
262         const int bones_count = BKE_armature_bonelist_count(&arm->bonebase);
263         GHash *bone_hash = BLI_ghash_str_new_ex(__func__, bones_count);
264         armature_bone_from_name_insert_recursive(bone_hash, &arm->bonebase);
265         return bone_hash;
266 }
267
268 bool BKE_armature_bone_flag_test_recursive(const Bone *bone, int flag)
269 {
270         if (bone->flag & flag) {
271                 return true;
272         }
273         else if (bone->parent) {
274                 return BKE_armature_bone_flag_test_recursive(bone->parent, flag);
275         }
276         else {
277                 return false;
278         }
279 }
280
281 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for
282  * unique names afterwards) strip_number: removes number extensions  (TODO: not used)
283  * axis: the axis to name on
284  * head/tail: the head/tail co-ordinate of the bone on the specified axis */
285 int bone_autoside_name(char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
286 {
287         unsigned int len;
288         char basename[MAXBONENAME] = "";
289         char extension[5] = "";
290
291         len = strlen(name);
292         if (len == 0)
293                 return 0;
294         BLI_strncpy(basename, name, sizeof(basename));
295
296         /* Figure out extension to append:
297          *      - The extension to append is based upon the axis that we are working on.
298          *      - If head happens to be on 0, then we must consider the tail position as well to decide
299          *        which side the bone is on
300          *              -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
301          *              -> Otherwise, extension is added from perspective of object based on which side tail goes to
302          *      - If head is non-zero, extension is added from perspective of object based on side head is on
303          */
304         if (axis == 2) {
305                 /* z-axis - vertical (top/bottom) */
306                 if (IS_EQF(head, 0.0f)) {
307                         if (tail < 0)
308                                 strcpy(extension, "Bot");
309                         else if (tail > 0)
310                                 strcpy(extension, "Top");
311                 }
312                 else {
313                         if (head < 0)
314                                 strcpy(extension, "Bot");
315                         else
316                                 strcpy(extension, "Top");
317                 }
318         }
319         else if (axis == 1) {
320                 /* y-axis - depth (front/back) */
321                 if (IS_EQF(head, 0.0f)) {
322                         if (tail < 0)
323                                 strcpy(extension, "Fr");
324                         else if (tail > 0)
325                                 strcpy(extension, "Bk");
326                 }
327                 else {
328                         if (head < 0)
329                                 strcpy(extension, "Fr");
330                         else
331                                 strcpy(extension, "Bk");
332                 }
333         }
334         else {
335                 /* x-axis - horizontal (left/right) */
336                 if (IS_EQF(head, 0.0f)) {
337                         if (tail < 0)
338                                 strcpy(extension, "R");
339                         else if (tail > 0)
340                                 strcpy(extension, "L");
341                 }
342                 else {
343                         if (head < 0)
344                                 strcpy(extension, "R");
345                         /* XXX Shouldn't this be simple else, as for z and y axes? */
346                         else if (head > 0)
347                                 strcpy(extension, "L");
348                 }
349         }
350
351         /* Simple name truncation
352          *      - truncate if there is an extension and it wouldn't be able to fit
353          *      - otherwise, just append to end
354          */
355         if (extension[0]) {
356                 bool changed = true;
357
358                 while (changed) { /* remove extensions */
359                         changed = false;
360                         if (len > 2 && basename[len - 2] == '.') {
361                                 if (basename[len - 1] == 'L' || basename[len - 1] == 'R') { /* L R */
362                                         basename[len - 2] = '\0';
363                                         len -= 2;
364                                         changed = true;
365                                 }
366                         }
367                         else if (len > 3 && basename[len - 3] == '.') {
368                                 if ((basename[len - 2] == 'F' && basename[len - 1] == 'r') || /* Fr */
369                                     (basename[len - 2] == 'B' && basename[len - 1] == 'k')) /* Bk */
370                                 {
371                                         basename[len - 3] = '\0';
372                                         len -= 3;
373                                         changed = true;
374                                 }
375                         }
376                         else if (len > 4 && basename[len - 4] == '.') {
377                                 if ((basename[len - 3] == 'T' && basename[len - 2] == 'o' && basename[len - 1] == 'p') || /* Top */
378                                     (basename[len - 3] == 'B' && basename[len - 2] == 'o' && basename[len - 1] == 't')) /* Bot */
379                                 {
380                                         basename[len - 4] = '\0';
381                                         len -= 4;
382                                         changed = true;
383                                 }
384                         }
385                 }
386
387                 if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
388                         strncpy(name, basename, len - strlen(extension));
389                 }
390
391                 BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
392
393                 return 1;
394         }
395
396         else
397                 return 0;
398 }
399
400 /* ************* B-Bone support ******************* */
401
402 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
403 void equalize_bbone_bezier(float *data, int desired)
404 {
405         float *fp, totdist, ddist, dist, fac1, fac2;
406         float pdist[MAX_BBONE_SUBDIV + 1];
407         float temp[MAX_BBONE_SUBDIV + 1][4];
408         int a, nr;
409
410         pdist[0] = 0.0f;
411         for (a = 0, fp = data; a < MAX_BBONE_SUBDIV; a++, fp += 4) {
412                 copy_qt_qt(temp[a], fp);
413                 pdist[a + 1] = pdist[a] + len_v3v3(fp, fp + 4);
414         }
415         /* do last point */
416         copy_qt_qt(temp[a], fp);
417         totdist = pdist[a];
418
419         /* go over distances and calculate new points */
420         ddist = totdist / ((float)desired);
421         nr = 1;
422         for (a = 1, fp = data + 4; a < desired; a++, fp += 4) {
423                 dist = ((float)a) * ddist;
424
425                 /* we're looking for location (distance) 'dist' in the array */
426                 while ((nr < MAX_BBONE_SUBDIV) && (dist >= pdist[nr]))
427                         nr++;
428
429                 fac1 = pdist[nr] - pdist[nr - 1];
430                 fac2 = pdist[nr] - dist;
431                 fac1 = fac2 / fac1;
432                 fac2 = 1.0f - fac1;
433
434                 fp[0] = fac1 * temp[nr - 1][0] + fac2 * temp[nr][0];
435                 fp[1] = fac1 * temp[nr - 1][1] + fac2 * temp[nr][1];
436                 fp[2] = fac1 * temp[nr - 1][2] + fac2 * temp[nr][2];
437                 fp[3] = fac1 * temp[nr - 1][3] + fac2 * temp[nr][3];
438         }
439         /* set last point, needed for orientation calculus */
440         copy_qt_qt(fp, temp[MAX_BBONE_SUBDIV]);
441 }
442
443 /* returns pointer to static array, filled with desired amount of bone->segments elements */
444 /* this calculation is done  within unit bone space */
445 void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BBONE_SUBDIV])
446 {
447         bPoseChannel *next, *prev;
448         Bone *bone = pchan->bone;
449         float h1[3], h2[3], scale[3], length, roll1 = 0.0f, roll2;
450         float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
451         float data[MAX_BBONE_SUBDIV + 1][4], *fp;
452         int a;
453         bool do_scale = false;
454
455         length = bone->length;
456
457         if (!rest) {
458                 /* check if we need to take non-uniform bone scaling into account */
459                 mat4_to_size(scale, pchan->pose_mat);
460
461                 if (fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
462                         size_to_mat4(scalemat, scale);
463                         invert_m4_m4(iscalemat, scalemat);
464
465                         length *= scale[1];
466                         do_scale = 1;
467                 }
468         }
469
470         /* get "next" and "prev" bones - these are used for handle calculations */
471         if (pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) {
472                 /* use the provided bones as the next/prev - leave blank to eliminate this effect altogether */
473                 prev = pchan->bbone_prev;
474                 next = pchan->bbone_next;
475         }
476         else {
477                 /* evaluate next and prev bones */
478                 if (bone->flag & BONE_CONNECTED)
479                         prev = pchan->parent;
480                 else
481                         prev = NULL;
482
483                 next = pchan->child;
484         }
485
486         /* find the handle points, since this is inside bone space, the
487          * first point = (0, 0, 0)
488          * last point =  (0, length, 0) */
489         if (rest) {
490                 invert_m4_m4(imat, pchan->bone->arm_mat);
491         }
492         else if (do_scale) {
493                 copy_m4_m4(posemat, pchan->pose_mat);
494                 normalize_m4(posemat);
495                 invert_m4_m4(imat, posemat);
496         }
497         else
498                 invert_m4_m4(imat, pchan->pose_mat);
499
500         if (prev) {
501                 float difmat[4][4], result[3][3], imat3[3][3];
502
503                 /* transform previous point inside this bone space */
504                 if ((pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) &&
505                     (pchan->bboneflag & PCHAN_BBONE_CUSTOM_START_REL))
506                 {
507                         /* Use delta movement (from restpose), and apply this relative to the current bone's head */
508                         if (rest) {
509                                 /* in restpose, arm_head == pose_head */
510                                 h1[0] = h1[1] = h1[2] = 0.0f;
511                         }
512                         else {
513                                 float delta[3];
514                                 sub_v3_v3v3(delta, prev->pose_head, prev->bone->arm_head);
515                                 sub_v3_v3v3(h1, pchan->pose_head, delta);
516                         }
517                 }
518                 else {
519                         /* Use bone head as absolute position */
520                         if (rest)
521                                 copy_v3_v3(h1, prev->bone->arm_head);
522                         else
523                                 copy_v3_v3(h1, prev->pose_head);
524                 }
525                 mul_m4_v3(imat, h1);
526
527                 if (prev->bone->segments > 1) {
528                         /* if previous bone is B-bone too, use average handle direction */
529                         h1[1] -= length;
530                         roll1 = 0.0f;
531                 }
532
533                 normalize_v3(h1);
534                 negate_v3(h1);
535
536                 if (prev->bone->segments == 1) {
537                         /* find the previous roll to interpolate */
538                         if (rest)
539                                 mul_m4_m4m4(difmat, imat, prev->bone->arm_mat);
540                         else
541                                 mul_m4_m4m4(difmat, imat, prev->pose_mat);
542                         copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
543
544                         vec_roll_to_mat3(h1, 0.0f, mat3); /* the result of vec_roll without roll */
545
546                         invert_m3_m3(imat3, mat3);
547                         mul_m3_m3m3(mat3, result, imat3); /* the matrix transforming vec_roll to desired roll */
548
549                         roll1 = atan2f(mat3[2][0], mat3[2][2]);
550                 }
551         }
552         else {
553                 h1[0] = 0.0f; h1[1] = 1.0; h1[2] = 0.0f;
554                 roll1 = 0.0f;
555         }
556         if (next) {
557                 float difmat[4][4], result[3][3], imat3[3][3];
558
559                 /* transform next point inside this bone space */
560                 if ((pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) &&
561                     (pchan->bboneflag & PCHAN_BBONE_CUSTOM_END_REL))
562                 {
563                         /* Use delta movement (from restpose), and apply this relative to the current bone's tail */
564                         if (rest) {
565                                 /* in restpose, arm_tail == pose_tail */
566                                 h2[0] = h2[1] = h2[2] = 0.0f;
567                         }
568                         else {
569                                 float delta[3];
570                                 sub_v3_v3v3(delta, next->pose_tail, next->bone->arm_tail);
571                                 add_v3_v3v3(h2, pchan->pose_tail, delta);
572                         }
573                 }
574                 else {
575                         /* Use bone tail as absolute position */
576                         if (rest)
577                                 copy_v3_v3(h2, next->bone->arm_tail);
578                         else
579                                 copy_v3_v3(h2, next->pose_tail);
580                 }
581                 mul_m4_v3(imat, h2);
582
583                 /* if next bone is B-bone too, use average handle direction */
584                 if (next->bone->segments > 1) {
585                         /* pass */
586                 }
587                 else {
588                         h2[1] -= length;
589                 }
590                 normalize_v3(h2);
591
592                 /* find the next roll to interpolate as well */
593                 if (rest)
594                         mul_m4_m4m4(difmat, imat, next->bone->arm_mat);
595                 else
596                         mul_m4_m4m4(difmat, imat, next->pose_mat);
597                 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
598
599                 vec_roll_to_mat3(h2, 0.0f, mat3); /* the result of vec_roll without roll */
600
601                 invert_m3_m3(imat3, mat3);
602                 mul_m3_m3m3(mat3, imat3, result); /* the matrix transforming vec_roll to desired roll */
603
604                 roll2 = atan2f(mat3[2][0], mat3[2][2]);
605
606         }
607         else {
608                 h2[0] = 0.0f; h2[1] = 1.0f; h2[2] = 0.0f;
609                 roll2 = 0.0;
610         }
611
612         {
613                 const float circle_factor = length * (cubic_tangent_factor_circle_v3(h1, h2) / 0.75f);
614
615                 const float combined_ease1 = bone->ease1 + (!rest ? pchan->ease1 : 0.0f);
616                 const float combined_ease2 = bone->ease2 + (!rest ? pchan->ease2 : 0.0f);
617                 const float hlength1 = combined_ease1 * circle_factor;
618                 const float hlength2 = combined_ease2 * circle_factor;
619
620                 /* and only now negate h2 */
621                 mul_v3_fl(h1,  hlength1);
622                 mul_v3_fl(h2, -hlength2);
623         }
624
625         /* Add effects from bbone properties over the top
626          * - These properties allow users to hand-animate the
627          *   bone curve/shape, without having to resort to using
628          *   extra bones
629          * - The "bone" level offsets are for defining the restpose
630          *   shape of the bone (e.g. for curved eyebrows for example).
631          *   -> In the viewport, it's needed to define what the rest pose
632          *      looks like
633          *   -> For "rest == 0", we also still need to have it present
634          *      so that we can "cancel out" this restpose when it comes
635          *      time to deform some geometry, it won't cause double transforms.
636          * - The "pchan" level offsets are the ones that animators actually
637          *   end up animating
638          */
639         {
640                 /* add extra rolls */
641                 roll1 += bone->roll1 + (!rest ? pchan->roll1 : 0.0f);
642                 roll2 += bone->roll2 + (!rest ? pchan->roll2 : 0.0f);
643                 
644                 if (bone->flag & BONE_ADD_PARENT_END_ROLL) {
645                         if (prev) {
646                                 if (prev->bone)
647                                         roll1 += prev->bone->roll2;
648                                 
649                                 if (!rest)
650                                         roll1 += prev->roll2;
651                         }
652                 }
653                 
654                 /* extra curve x / y */
655                 /* NOTE: Scale correction factors here are to compensate for some random floating-point glitches
656                  *       when scaling up the bone or it's parent by a factor of approximately 8.15/6, which results
657                  *       in the bone length getting scaled up too (from 1 to 8), causing the curve to flatten out.
658                  */
659                 const float xscale_correction = (do_scale) ? scale[0] : 1.0f;
660                 const float yscale_correction = (do_scale) ? scale[2] : 1.0f;
661                 
662                 h1[0] += (bone->curveInX + (!rest ? pchan->curveInX : 0.0f)) * xscale_correction;
663                 h1[2] += (bone->curveInY + (!rest ? pchan->curveInY : 0.0f)) * yscale_correction;
664                 
665                 h2[0] += (bone->curveOutX + (!rest ? pchan->curveOutX : 0.0f)) * xscale_correction;
666                 h2[2] += (bone->curveOutY + (!rest ? pchan->curveOutY : 0.0f)) * yscale_correction;
667         }
668         
669         /* make curve */
670         if (bone->segments > MAX_BBONE_SUBDIV)
671                 bone->segments = MAX_BBONE_SUBDIV;
672
673         BKE_curve_forward_diff_bezier(0.0f,  h1[0],                               h2[0],                               0.0f,   data[0],     MAX_BBONE_SUBDIV, 4 * sizeof(float));
674         BKE_curve_forward_diff_bezier(0.0f,  h1[1],                               length + h2[1],                      length, data[0] + 1, MAX_BBONE_SUBDIV, 4 * sizeof(float));
675         BKE_curve_forward_diff_bezier(0.0f,  h1[2],                               h2[2],                               0.0f,   data[0] + 2, MAX_BBONE_SUBDIV, 4 * sizeof(float));
676         BKE_curve_forward_diff_bezier(roll1, roll1 + 0.390464f * (roll2 - roll1), roll2 - 0.390464f * (roll2 - roll1), roll2,  data[0] + 3, MAX_BBONE_SUBDIV, 4 * sizeof(float));
677
678         equalize_bbone_bezier(data[0], bone->segments); /* note: does stride 4! */
679
680         /* make transformation matrices for the segments for drawing */
681         for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) {
682                 sub_v3_v3v3(h1, fp + 4, fp);
683                 vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */
684                 
685                 copy_m4_m3(result_array[a].mat, mat3);
686                 copy_v3_v3(result_array[a].mat[3], fp);
687                 
688                 if (do_scale) {
689                         /* correct for scaling when this matrix is used in scaled space */
690                         mul_m4_series(result_array[a].mat, iscalemat, result_array[a].mat, scalemat);
691                 }
692                 
693                 /* BBone scale... */
694                 {
695                         const int num_segments = bone->segments;
696                         
697                         const float scaleIn = bone->scaleIn * (!rest ? pchan->scaleIn : 1.0f);
698                         const float scaleFactorIn  = 1.0f + (scaleIn  - 1.0f) * ((float)(num_segments - a) / (float)num_segments);
699                         
700                         const float scaleOut = bone->scaleOut * (!rest ? pchan->scaleOut : 1.0f);
701                         const float scaleFactorOut = 1.0f + (scaleOut - 1.0f) * ((float)(a + 1)            / (float)num_segments);
702                         
703                         const float scalefac = scaleFactorIn * scaleFactorOut;
704                         float bscalemat[4][4], bscale[3];
705                         
706                         bscale[0] = scalefac;
707                         bscale[1] = 1.0f;
708                         bscale[2] = scalefac;
709                         
710                         size_to_mat4(bscalemat, bscale);
711                         
712                         /* Note: don't multiply by inverse scale mat here, as it causes problems with scaling shearing and breaking segment chains */
713                         /*mul_m4_series(result_array[a].mat, ibscalemat, result_array[a].mat, bscalemat);*/
714                         mul_m4_series(result_array[a].mat, result_array[a].mat, bscalemat);
715                 }
716                 
717         }
718 }
719
720 /* ************ Armature Deform ******************* */
721
722 typedef struct bPoseChanDeform {
723         Mat4     *b_bone_mats;
724         DualQuat *dual_quat;
725         DualQuat *b_bone_dual_quats;
726 } bPoseChanDeform;
727
728 static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, const bool use_quaternion)
729 {
730         Bone *bone = pchan->bone;
731         Mat4 b_bone[MAX_BBONE_SUBDIV], b_bone_rest[MAX_BBONE_SUBDIV];
732         Mat4 *b_bone_mats;
733         DualQuat *b_bone_dual_quats = NULL;
734         int a;
735
736         b_bone_spline_setup(pchan, 0, b_bone);
737         b_bone_spline_setup(pchan, 1, b_bone_rest);
738
739         /* allocate b_bone matrices and dual quats */
740         b_bone_mats = MEM_mallocN((1 + bone->segments) * sizeof(Mat4), "BBone defmats");
741         pdef_info->b_bone_mats = b_bone_mats;
742
743         if (use_quaternion) {
744                 b_bone_dual_quats = MEM_mallocN((bone->segments) * sizeof(DualQuat), "BBone dqs");
745                 pdef_info->b_bone_dual_quats = b_bone_dual_quats;
746         }
747
748         /* first matrix is the inverse arm_mat, to bring points in local bone space
749          * for finding out which segment it belongs to */
750         invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
751
752         /* then we make the b_bone_mats:
753          * - first transform to local bone space
754          * - translate over the curve to the bbone mat space
755          * - transform with b_bone matrix
756          * - transform back into global space */
757
758         for (a = 0; a < bone->segments; a++) {
759                 float tmat[4][4];
760
761                 invert_m4_m4(tmat, b_bone_rest[a].mat);
762                 mul_m4_series(b_bone_mats[a + 1].mat, pchan->chan_mat, bone->arm_mat, b_bone[a].mat, tmat, b_bone_mats[0].mat);
763
764                 if (use_quaternion)
765                         mat4_to_dquat(&b_bone_dual_quats[a], bone->arm_mat, b_bone_mats[a + 1].mat);
766         }
767 }
768
769 static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], DualQuat *dq, float defmat[3][3])
770 {
771         Mat4 *b_bone = pdef_info->b_bone_mats;
772         float (*mat)[4] = b_bone[0].mat;
773         float segment, y;
774         int a;
775         
776         /* need to transform co back to bonespace, only need y */
777         y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1];
778         
779         /* now calculate which of the b_bones are deforming this */
780         segment = bone->length / ((float)bone->segments);
781         a = (int)(y / segment);
782
783         /* note; by clamping it extends deform at endpoints, goes best with
784          * straight joints in restpos. */
785         CLAMP(a, 0, bone->segments - 1);
786
787         if (dq) {
788                 copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
789         }
790         else {
791                 mul_m4_v3(b_bone[a + 1].mat, co);
792
793                 if (defmat) {
794                         copy_m3_m4(defmat, b_bone[a + 1].mat);
795                 }
796         }
797 }
798
799 /* using vec with dist to bone b1 - b2 */
800 float distfactor_to_bone(const float vec[3], const float b1[3], const float b2[3], float rad1, float rad2, float rdist)
801 {
802         float dist_sq;
803         float bdelta[3];
804         float pdelta[3];
805         float hsqr, a, l, rad;
806
807         sub_v3_v3v3(bdelta, b2, b1);
808         l = normalize_v3(bdelta);
809
810         sub_v3_v3v3(pdelta, vec, b1);
811
812         a = dot_v3v3(bdelta, pdelta);
813         hsqr = len_squared_v3(pdelta);
814
815         if (a < 0.0f) {
816                 /* If we're past the end of the bone, do a spherical field attenuation thing */
817                 dist_sq = len_squared_v3v3(b1, vec);
818                 rad = rad1;
819         }
820         else if (a > l) {
821                 /* If we're past the end of the bone, do a spherical field attenuation thing */
822                 dist_sq = len_squared_v3v3(b2, vec);
823                 rad = rad2;
824         }
825         else {
826                 dist_sq = (hsqr - (a * a));
827
828                 if (l != 0.0f) {
829                         rad = a / l;
830                         rad = rad * rad2 + (1.0f - rad) * rad1;
831                 }
832                 else
833                         rad = rad1;
834         }
835
836         a = rad * rad;
837         if (dist_sq < a)
838                 return 1.0f;
839         else {
840                 l = rad + rdist;
841                 l *= l;
842                 if (rdist == 0.0f || dist_sq >= l)
843                         return 0.0f;
844                 else {
845                         a = sqrtf(dist_sq) - rad;
846                         return 1.0f - (a * a) / (rdist * rdist);
847                 }
848         }
849 }
850
851 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[3][3], float mat[3][3])
852 {
853         float wmat[3][3];
854
855         if (pchan->bone->segments > 1)
856                 copy_m3_m3(wmat, bbonemat);
857         else
858                 copy_m3_m4(wmat, pchan->chan_mat);
859
860         mul_m3_fl(wmat, weight);
861         add_m3_m3m3(mat, mat, wmat);
862 }
863
864 static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float vec[3], DualQuat *dq,
865                               float mat[3][3], const float co[3])
866 {
867         Bone *bone = pchan->bone;
868         float fac, contrib = 0.0;
869         float cop[3], bbonemat[3][3];
870         DualQuat bbonedq;
871
872         if (bone == NULL)
873                 return 0.0f;
874
875         copy_v3_v3(cop, co);
876
877         fac = distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
878
879         if (fac > 0.0f) {
880                 fac *= bone->weight;
881                 contrib = fac;
882                 if (contrib > 0.0f) {
883                         if (vec) {
884                                 if (bone->segments > 1)
885                                         /* applies on cop and bbonemat */
886                                         b_bone_deform(pdef_info, bone, cop, NULL, (mat) ? bbonemat : NULL);
887                                 else
888                                         mul_m4_v3(pchan->chan_mat, cop);
889
890                                 /* Make this a delta from the base position */
891                                 sub_v3_v3(cop, co);
892                                 madd_v3_v3fl(vec, cop, fac);
893
894                                 if (mat)
895                                         pchan_deform_mat_add(pchan, fac, bbonemat, mat);
896                         }
897                         else {
898                                 if (bone->segments > 1) {
899                                         b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
900                                         add_weighted_dq_dq(dq, &bbonedq, fac);
901                                 }
902                                 else
903                                         add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
904                         }
905                 }
906         }
907
908         return contrib;
909 }
910
911 static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float vec[3], DualQuat *dq,
912                               float mat[3][3], const float co[3], float *contrib)
913 {
914         float cop[3], bbonemat[3][3];
915         DualQuat bbonedq;
916
917         if (!weight)
918                 return;
919
920         copy_v3_v3(cop, co);
921
922         if (vec) {
923                 if (pchan->bone->segments > 1)
924                         /* applies on cop and bbonemat */
925                         b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat) ? bbonemat : NULL);
926                 else
927                         mul_m4_v3(pchan->chan_mat, cop);
928
929                 vec[0] += (cop[0] - co[0]) * weight;
930                 vec[1] += (cop[1] - co[1]) * weight;
931                 vec[2] += (cop[2] - co[2]) * weight;
932
933                 if (mat)
934                         pchan_deform_mat_add(pchan, weight, bbonemat, mat);
935         }
936         else {
937                 if (pchan->bone->segments > 1) {
938                         b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
939                         add_weighted_dq_dq(dq, &bbonedq, weight);
940                 }
941                 else
942                         add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
943         }
944
945         (*contrib) += weight;
946 }
947
948 typedef struct ArmatureBBoneDefmatsData {
949         bPoseChanDeform *pdef_info_array;
950         DualQuat *dualquats;
951         bool use_quaternion;
952 } ArmatureBBoneDefmatsData;
953
954 static void armature_bbone_defmats_cb(void *userdata, Link *iter, int index)
955 {
956         ArmatureBBoneDefmatsData *data = userdata;
957         bPoseChannel *pchan = (bPoseChannel *)iter;
958
959         if (!(pchan->bone->flag & BONE_NO_DEFORM)) {
960                 bPoseChanDeform *pdef_info = &data->pdef_info_array[index];
961                 const bool use_quaternion = data->use_quaternion;
962
963                 if (pchan->bone->segments > 1) {
964                         pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
965                 }
966
967                 if (use_quaternion) {
968                         pdef_info->dual_quat = &data->dualquats[index];
969                         mat4_to_dquat(pdef_info->dual_quat, pchan->bone->arm_mat, pchan->chan_mat);
970                 }
971         }
972 }
973
974 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3],
975                            float (*defMats)[3][3], int numVerts, int deformflag,
976                            float (*prevCos)[3], const char *defgrp_name)
977 {
978         bPoseChanDeform *pdef_info_array;
979         bPoseChanDeform *pdef_info = NULL;
980         bArmature *arm = armOb->data;
981         bPoseChannel *pchan, **defnrToPC = NULL;
982         int *defnrToPCIndex = NULL;
983         MDeformVert *dverts = NULL;
984         bDeformGroup *dg;
985         DualQuat *dualquats = NULL;
986         float obinv[4][4], premat[4][4], postmat[4][4];
987         const bool use_envelope   = (deformflag & ARM_DEF_ENVELOPE) != 0;
988         const bool use_quaternion = (deformflag & ARM_DEF_QUATERNION) != 0;
989         const bool invert_vgroup  = (deformflag & ARM_DEF_INVERT_VGROUP) != 0;
990         int defbase_tot = 0;       /* safety for vertexgroup index overflow */
991         int i, target_totvert = 0; /* safety for vertexgroup overflow */
992         bool use_dverts = false;
993         int armature_def_nr;
994         int totchan;
995
996         /* in editmode, or not an armature */
997         if (arm->edbo || (armOb->pose == NULL)) {
998                 return;
999         }
1000
1001         if ((armOb->pose->flag & POSE_RECALC) != 0) {
1002                 printf("ERROR! Trying to evaluate influence of armature '%s' which needs Pose recalc!", armOb->id.name);
1003                 BLI_assert(0);
1004         }
1005
1006         invert_m4_m4(obinv, target->obmat);
1007         copy_m4_m4(premat, target->obmat);
1008         mul_m4_m4m4(postmat, obinv, armOb->obmat);
1009         invert_m4_m4(premat, postmat);
1010
1011         /* bone defmats are already in the channels, chan_mat */
1012
1013         /* initialize B_bone matrices and dual quaternions */
1014         totchan = BLI_listbase_count(&armOb->pose->chanbase);
1015
1016         if (use_quaternion) {
1017                 dualquats = MEM_callocN(sizeof(DualQuat) * totchan, "dualquats");
1018         }
1019
1020         pdef_info_array = MEM_callocN(sizeof(bPoseChanDeform) * totchan, "bPoseChanDeform");
1021
1022         ArmatureBBoneDefmatsData data = {
1023             .pdef_info_array = pdef_info_array, .dualquats = dualquats, .use_quaternion = use_quaternion
1024         };
1025         BLI_task_parallel_listbase(&armOb->pose->chanbase, &data, armature_bbone_defmats_cb, totchan > 512);
1026
1027         /* get the def_nr for the overall armature vertex group if present */
1028         armature_def_nr = defgroup_name_index(target, defgrp_name);
1029
1030         if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
1031                 defbase_tot = BLI_listbase_count(&target->defbase);
1032
1033                 if (target->type == OB_MESH) {
1034                         Mesh *me = target->data;
1035                         dverts = me->dvert;
1036                         if (dverts)
1037                                 target_totvert = me->totvert;
1038                 }
1039                 else {
1040                         Lattice *lt = target->data;
1041                         dverts = lt->dvert;
1042                         if (dverts)
1043                                 target_totvert = lt->pntsu * lt->pntsv * lt->pntsw;
1044                 }
1045         }
1046
1047         /* get a vertex-deform-index to posechannel array */
1048         if (deformflag & ARM_DEF_VGROUP) {
1049                 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
1050                         /* if we have a DerivedMesh, only use dverts if it has them */
1051                         if (dm) {
1052                                 use_dverts = (dm->getVertDataArray(dm, CD_MDEFORMVERT) != NULL);
1053                         }
1054                         else if (dverts) {
1055                                 use_dverts = true;
1056                         }
1057
1058                         if (use_dverts) {
1059                                 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * defbase_tot, "defnrToBone");
1060                                 defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * defbase_tot, "defnrToIndex");
1061                                 /* TODO(sergey): Some considerations here:
1062                                  *
1063                                  * - Make it more generic function, maybe even keep together with chanhash.
1064                                  * - Check whether keeping this consistent across frames gives speedup.
1065                                  * - Don't use hash for small armatures.
1066                                  */
1067                                 GHash *idx_hash = BLI_ghash_ptr_new("pose channel index by name");
1068                                 int pchan_index = 0;
1069                                 for (pchan = armOb->pose->chanbase.first; pchan != NULL; pchan = pchan->next, ++pchan_index) {
1070                                         BLI_ghash_insert(idx_hash, pchan, SET_INT_IN_POINTER(pchan_index));
1071                                 }
1072                                 for (i = 0, dg = target->defbase.first; dg; i++, dg = dg->next) {
1073                                         defnrToPC[i] = BKE_pose_channel_find_name(armOb->pose, dg->name);
1074                                         /* exclude non-deforming bones */
1075                                         if (defnrToPC[i]) {
1076                                                 if (defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
1077                                                         defnrToPC[i] = NULL;
1078                                                 }
1079                                                 else {
1080                                                         defnrToPCIndex[i] = GET_INT_FROM_POINTER(BLI_ghash_lookup(idx_hash, defnrToPC[i]));
1081                                                 }
1082                                         }
1083                                 }
1084                                 BLI_ghash_free(idx_hash, NULL, NULL);
1085                         }
1086                 }
1087         }
1088
1089         for (i = 0; i < numVerts; i++) {
1090                 MDeformVert *dvert;
1091                 DualQuat sumdq, *dq = NULL;
1092                 float *co, dco[3];
1093                 float sumvec[3], summat[3][3];
1094                 float *vec = NULL, (*smat)[3] = NULL;
1095                 float contrib = 0.0f;
1096                 float armature_weight = 1.0f; /* default to 1 if no overall def group */
1097                 float prevco_weight = 1.0f;   /* weight for optional cached vertexcos */
1098
1099                 if (use_quaternion) {
1100                         memset(&sumdq, 0, sizeof(DualQuat));
1101                         dq = &sumdq;
1102                 }
1103                 else {
1104                         sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
1105                         vec = sumvec;
1106
1107                         if (defMats) {
1108                                 zero_m3(summat);
1109                                 smat = summat;
1110                         }
1111                 }
1112
1113                 if (use_dverts || armature_def_nr != -1) {
1114                         if (dm)
1115                                 dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
1116                         else if (dverts && i < target_totvert)
1117                                 dvert = dverts + i;
1118                         else
1119                                 dvert = NULL;
1120                 }
1121                 else
1122                         dvert = NULL;
1123
1124                 if (armature_def_nr != -1 && dvert) {
1125                         armature_weight = defvert_find_weight(dvert, armature_def_nr);
1126
1127                         if (invert_vgroup)
1128                                 armature_weight = 1.0f - armature_weight;
1129
1130                         /* hackish: the blending factor can be used for blending with prevCos too */
1131                         if (prevCos) {
1132                                 prevco_weight = armature_weight;
1133                                 armature_weight = 1.0f;
1134                         }
1135                 }
1136
1137                 /* check if there's any  point in calculating for this vert */
1138                 if (armature_weight == 0.0f)
1139                         continue;
1140
1141                 /* get the coord we work on */
1142                 co = prevCos ? prevCos[i] : vertexCos[i];
1143
1144                 /* Apply the object's matrix */
1145                 mul_m4_v3(premat, co);
1146
1147                 if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */
1148                         MDeformWeight *dw = dvert->dw;
1149                         int deformed = 0;
1150                         unsigned int j;
1151
1152                         for (j = dvert->totweight; j != 0; j--, dw++) {
1153                                 const int index = dw->def_nr;
1154                                 if (index >= 0 && index < defbase_tot && (pchan = defnrToPC[index])) {
1155                                         float weight = dw->weight;
1156                                         Bone *bone = pchan->bone;
1157                                         pdef_info = pdef_info_array + defnrToPCIndex[index];
1158
1159                                         deformed = 1;
1160
1161                                         if (bone && bone->flag & BONE_MULT_VG_ENV) {
1162                                                 weight *= distfactor_to_bone(co, bone->arm_head, bone->arm_tail,
1163                                                                              bone->rad_head, bone->rad_tail, bone->dist);
1164                                         }
1165                                         pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
1166                                 }
1167                         }
1168                         /* if there are vertexgroups but not groups with bones
1169                          * (like for softbody groups) */
1170                         if (deformed == 0 && use_envelope) {
1171                                 pdef_info = pdef_info_array;
1172                                 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1173                                         if (!(pchan->bone->flag & BONE_NO_DEFORM))
1174                                                 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1175                                 }
1176                         }
1177                 }
1178                 else if (use_envelope) {
1179                         pdef_info = pdef_info_array;
1180                         for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1181                                 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1182                                         contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1183                         }
1184                 }
1185
1186                 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1187                 if (contrib > 0.0001f) {
1188                         if (use_quaternion) {
1189                                 normalize_dq(dq, contrib);
1190
1191                                 if (armature_weight != 1.0f) {
1192                                         copy_v3_v3(dco, co);
1193                                         mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq);
1194                                         sub_v3_v3(dco, co);
1195                                         mul_v3_fl(dco, armature_weight);
1196                                         add_v3_v3(co, dco);
1197                                 }
1198                                 else
1199                                         mul_v3m3_dq(co, (defMats) ? summat : NULL, dq);
1200
1201                                 smat = summat;
1202                         }
1203                         else {
1204                                 mul_v3_fl(vec, armature_weight / contrib);
1205                                 add_v3_v3v3(co, vec, co);
1206                         }
1207
1208                         if (defMats) {
1209                                 float pre[3][3], post[3][3], tmpmat[3][3];
1210
1211                                 copy_m3_m4(pre, premat);
1212                                 copy_m3_m4(post, postmat);
1213                                 copy_m3_m3(tmpmat, defMats[i]);
1214
1215                                 if (!use_quaternion) /* quaternion already is scale corrected */
1216                                         mul_m3_fl(smat, armature_weight / contrib);
1217
1218                                 mul_m3_series(defMats[i], post, smat, pre, tmpmat);
1219                         }
1220                 }
1221
1222                 /* always, check above code */
1223                 mul_m4_v3(postmat, co);
1224
1225                 /* interpolate with previous modifier position using weight group */
1226                 if (prevCos) {
1227                         float mw = 1.0f - prevco_weight;
1228                         vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0];
1229                         vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1];
1230                         vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2];
1231                 }
1232         }
1233
1234         if (dualquats)
1235                 MEM_freeN(dualquats);
1236         if (defnrToPC)
1237                 MEM_freeN(defnrToPC);
1238         if (defnrToPCIndex)
1239                 MEM_freeN(defnrToPCIndex);
1240
1241         /* free B_bone matrices */
1242         pdef_info = pdef_info_array;
1243         for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1244                 if (pdef_info->b_bone_mats)
1245                         MEM_freeN(pdef_info->b_bone_mats);
1246                 if (pdef_info->b_bone_dual_quats)
1247                         MEM_freeN(pdef_info->b_bone_dual_quats);
1248         }
1249
1250         MEM_freeN(pdef_info_array);
1251 }
1252
1253 /* ************ END Armature Deform ******************* */
1254
1255 void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[4][4], int UNUSED(root),
1256                                  int UNUSED(posed))
1257 {
1258         copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1259 }
1260
1261 /* **************** Space to Space API ****************** */
1262
1263 /* Convert World-Space Matrix to Pose-Space Matrix */
1264 void BKE_armature_mat_world_to_pose(Object *ob, float inmat[4][4], float outmat[4][4])
1265 {
1266         float obmat[4][4];
1267
1268         /* prevent crashes */
1269         if (ob == NULL)
1270                 return;
1271
1272         /* get inverse of (armature) object's matrix  */
1273         invert_m4_m4(obmat, ob->obmat);
1274
1275         /* multiply given matrix by object's-inverse to find pose-space matrix */
1276         mul_m4_m4m4(outmat, inmat, obmat);
1277 }
1278
1279 /* Convert World-Space Location to Pose-Space Location
1280  * NOTE: this cannot be used to convert to pose-space location of the supplied
1281  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
1282 void BKE_armature_loc_world_to_pose(Object *ob, const float inloc[3], float outloc[3])
1283 {
1284         float xLocMat[4][4];
1285         float nLocMat[4][4];
1286
1287         /* build matrix for location */
1288         unit_m4(xLocMat);
1289         copy_v3_v3(xLocMat[3], inloc);
1290
1291         /* get bone-space cursor matrix and extract location */
1292         BKE_armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1293         copy_v3_v3(outloc, nLocMat[3]);
1294 }
1295
1296 /* Simple helper, computes the offset bone matrix.
1297  *     offs_bone = yoffs(b-1) + root(b) + bonemat(b).
1298  * Not exported, as it is only used in this file currently... */
1299 static void get_offset_bone_mat(Bone *bone, float offs_bone[4][4])
1300 {
1301         BLI_assert(bone->parent != NULL);
1302
1303         /* Bone transform itself. */
1304         copy_m4_m3(offs_bone, bone->bone_mat);
1305
1306         /* The bone's root offset (is in the parent's coordinate system). */
1307         copy_v3_v3(offs_bone[3], bone->head);
1308
1309         /* Get the length translation of parent (length along y axis). */
1310         offs_bone[3][1] += bone->parent->length;
1311 }
1312
1313 /* Construct the matrices (rot/scale and loc) to apply the PoseChannels into the armature (object) space.
1314  * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the
1315  *     pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1316  * ...function.
1317  *
1318  * This allows to get the transformations of a bone in its object space, *before* constraints (and IK)
1319  * get applied (used by pose evaluation code).
1320  * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale
1321  * in object space (used by interactive transform, and snapping code).
1322  *
1323  * Note that, with the HINGE/NO_SCALE/NO_LOCAL_LOCATION options, the location matrix
1324  * will differ from the rotation/scale matrix...
1325  *
1326  * NOTE: This cannot be used to convert to pose-space transforms of the supplied
1327  *       pose-channel into its local space (i.e. 'visual'-keyframing).
1328  *       (note: I don't understand that, so I keep it :p --mont29).
1329  */
1330 void BKE_pchan_to_pose_mat(bPoseChannel *pchan, float rotscale_mat[4][4], float loc_mat[4][4])
1331 {
1332         Bone *bone, *parbone;
1333         bPoseChannel *parchan;
1334
1335         /* set up variables for quicker access below */
1336         bone = pchan->bone;
1337         parbone = bone->parent;
1338         parchan = pchan->parent;
1339
1340         if (parchan) {
1341                 float offs_bone[4][4];
1342                 /* yoffs(b-1) + root(b) + bonemat(b). */
1343                 get_offset_bone_mat(bone, offs_bone);
1344
1345                 /* Compose the rotscale matrix for this bone. */
1346                 if ((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) {
1347                         /* Parent rest rotation and scale. */
1348                         mul_m4_m4m4(rotscale_mat, parbone->arm_mat, offs_bone);
1349                 }
1350                 else if (bone->flag & BONE_HINGE) {
1351                         /* Parent rest rotation and pose scale. */
1352                         float tmat[4][4], tscale[3];
1353
1354                         /* Extract the scale of the parent pose matrix. */
1355                         mat4_to_size(tscale, parchan->pose_mat);
1356                         size_to_mat4(tmat, tscale);
1357
1358                         /* Applies the parent pose scale to the rest matrix. */
1359                         mul_m4_m4m4(tmat, tmat, parbone->arm_mat);
1360
1361                         mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1362                 }
1363                 else if (bone->flag & BONE_NO_SCALE) {
1364                         /* Parent pose rotation and rest scale (i.e. no scaling). */
1365                         float tmat[4][4];
1366                         copy_m4_m4(tmat, parchan->pose_mat);
1367                         normalize_m4(tmat);
1368                         mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1369                 }
1370                 else
1371                         mul_m4_m4m4(rotscale_mat, parchan->pose_mat, offs_bone);
1372
1373                 /* Compose the loc matrix for this bone. */
1374                 /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */
1375
1376                 /* In this case, use the object's space *orientation*. */
1377                 if (bone->flag & BONE_NO_LOCAL_LOCATION) {
1378                         /* XXX I'm sure that code can be simplified! */
1379                         float bone_loc[4][4], bone_rotscale[3][3], tmat4[4][4], tmat3[3][3];
1380                         unit_m4(bone_loc);
1381                         unit_m4(loc_mat);
1382                         unit_m4(tmat4);
1383
1384                         mul_v3_m4v3(bone_loc[3], parchan->pose_mat, offs_bone[3]);
1385
1386                         unit_m3(bone_rotscale);
1387                         copy_m3_m4(tmat3, parchan->pose_mat);
1388                         mul_m3_m3m3(bone_rotscale, tmat3, bone_rotscale);
1389
1390                         copy_m4_m3(tmat4, bone_rotscale);
1391                         mul_m4_m4m4(loc_mat, bone_loc, tmat4);
1392                 }
1393                 /* Those flags do not affect position, use plain parent transform space! */
1394                 else if (bone->flag & (BONE_HINGE | BONE_NO_SCALE)) {
1395                         mul_m4_m4m4(loc_mat, parchan->pose_mat, offs_bone);
1396                 }
1397                 /* Else (i.e. default, usual case), just use the same matrix for rotation/scaling, and location. */
1398                 else
1399                         copy_m4_m4(loc_mat, rotscale_mat);
1400         }
1401         /* Root bones. */
1402         else {
1403                 /* Rotation/scaling. */
1404                 copy_m4_m4(rotscale_mat, pchan->bone->arm_mat);
1405                 /* Translation. */
1406                 if (pchan->bone->flag & BONE_NO_LOCAL_LOCATION) {
1407                         /* Translation of arm_mat, without the rotation. */
1408                         unit_m4(loc_mat);
1409                         copy_v3_v3(loc_mat[3], pchan->bone->arm_mat[3]);
1410                 }
1411                 else
1412                         copy_m4_m4(loc_mat, rotscale_mat);
1413         }
1414 }
1415
1416 /* Convert Pose-Space Matrix to Bone-Space Matrix.
1417  * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1418  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
1419 void BKE_armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1420 {
1421         float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1422
1423         /* Security, this allows to call with inmat == outmat! */
1424         copy_m4_m4(inmat_, inmat);
1425
1426         BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1427         invert_m4(rotscale_mat);
1428         invert_m4(loc_mat);
1429
1430         mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1431         mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1432 }
1433
1434 /* Convert Bone-Space Matrix to Pose-Space Matrix. */
1435 void BKE_armature_mat_bone_to_pose(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1436 {
1437         float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1438
1439         /* Security, this allows to call with inmat == outmat! */
1440         copy_m4_m4(inmat_, inmat);
1441
1442         BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1443
1444         mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1445         mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1446 }
1447
1448 /* Convert Pose-Space Location to Bone-Space Location
1449  * NOTE: this cannot be used to convert to pose-space location of the supplied
1450  *       pose-channel into its local space (i.e. 'visual'-keyframing) */
1451 void BKE_armature_loc_pose_to_bone(bPoseChannel *pchan, const float inloc[3], float outloc[3])
1452 {
1453         float xLocMat[4][4];
1454         float nLocMat[4][4];
1455
1456         /* build matrix for location */
1457         unit_m4(xLocMat);
1458         copy_v3_v3(xLocMat[3], inloc);
1459
1460         /* get bone-space cursor matrix and extract location */
1461         BKE_armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1462         copy_v3_v3(outloc, nLocMat[3]);
1463 }
1464
1465 void BKE_armature_mat_pose_to_bone_ex(struct Depsgraph *depsgraph, Object *ob, bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1466 {
1467         bPoseChannel work_pchan = *pchan;
1468
1469         /* recalculate pose matrix with only parent transformations,
1470          * bone loc/sca/rot is ignored, scene and frame are not used. */
1471         BKE_pose_where_is_bone(depsgraph, NULL, ob, &work_pchan, 0.0f, false);
1472
1473         /* find the matrix, need to remove the bone transforms first so this is
1474          * calculated as a matrix to set rather then a difference ontop of whats
1475          * already there. */
1476         unit_m4(outmat);
1477         BKE_pchan_apply_mat4(&work_pchan, outmat, false);
1478
1479         BKE_armature_mat_pose_to_bone(&work_pchan, inmat, outmat);
1480 }
1481
1482 /* same as BKE_object_mat3_to_rot() */
1483 void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, float mat[3][3], bool use_compat)
1484 {
1485         BLI_ASSERT_UNIT_M3(mat);
1486
1487         switch (pchan->rotmode) {
1488                 case ROT_MODE_QUAT:
1489                         mat3_normalized_to_quat(pchan->quat, mat);
1490                         break;
1491                 case ROT_MODE_AXISANGLE:
1492                         mat3_normalized_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1493                         break;
1494                 default: /* euler */
1495                         if (use_compat)
1496                                 mat3_normalized_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1497                         else
1498                                 mat3_normalized_to_eulO(pchan->eul, pchan->rotmode, mat);
1499                         break;
1500         }
1501 }
1502
1503 /* Apply a 4x4 matrix to the pose bone,
1504  * similar to BKE_object_apply_mat4() */
1505 void BKE_pchan_apply_mat4(bPoseChannel *pchan, float mat[4][4], bool use_compat)
1506 {
1507         float rot[3][3];
1508         mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1509         BKE_pchan_mat3_to_rot(pchan, rot, use_compat);
1510 }
1511
1512 /* Remove rest-position effects from pose-transform for obtaining
1513  * 'visual' transformation of pose-channel.
1514  * (used by the Visual-Keyframing stuff) */
1515 void BKE_armature_mat_pose_to_delta(float delta_mat[4][4], float pose_mat[4][4], float arm_mat[4][4])
1516 {
1517         float imat[4][4];
1518
1519         invert_m4_m4(imat, arm_mat);
1520         mul_m4_m4m4(delta_mat, imat, pose_mat);
1521 }
1522
1523 /* **************** Rotation Mode Conversions ****************************** */
1524 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1525
1526 /* Called from RNA when rotation mode changes
1527  * - the result should be that the rotations given in the provided pointers have had conversions
1528  *   applied (as appropriate), such that the rotation of the element hasn't 'visually' changed  */
1529 void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1530 {
1531         /* check if any change - if so, need to convert data */
1532         if (newMode > 0) { /* to euler */
1533                 if (oldMode == ROT_MODE_AXISANGLE) {
1534                         /* axis-angle to euler */
1535                         axis_angle_to_eulO(eul, newMode, axis, *angle);
1536                 }
1537                 else if (oldMode == ROT_MODE_QUAT) {
1538                         /* quat to euler */
1539                         normalize_qt(quat);
1540                         quat_to_eulO(eul, newMode, quat);
1541                 }
1542                 /* else { no conversion needed } */
1543         }
1544         else if (newMode == ROT_MODE_QUAT) { /* to quat */
1545                 if (oldMode == ROT_MODE_AXISANGLE) {
1546                         /* axis angle to quat */
1547                         axis_angle_to_quat(quat, axis, *angle);
1548                 }
1549                 else if (oldMode > 0) {
1550                         /* euler to quat */
1551                         eulO_to_quat(quat, eul, oldMode);
1552                 }
1553                 /* else { no conversion needed } */
1554         }
1555         else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1556                 if (oldMode > 0) {
1557                         /* euler to axis angle */
1558                         eulO_to_axis_angle(axis, angle, eul, oldMode);
1559                 }
1560                 else if (oldMode == ROT_MODE_QUAT) {
1561                         /* quat to axis angle */
1562                         normalize_qt(quat);
1563                         quat_to_axis_angle(axis, angle, quat);
1564                 }
1565
1566                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1567                 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
1568                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1569                         axis[1] = 1.0f;
1570                 }
1571         }
1572 }
1573
1574 /* **************** The new & simple (but OK!) armature evaluation ********* */
1575
1576 /* ****************** And how it works! ****************************************
1577  *
1578  * This is the bone transformation trick; they're hierarchical so each bone(b)
1579  * is in the coord system of bone(b-1):
1580  *
1581  * arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
1582  *
1583  * -> yoffs is just the y axis translation in parent's coord system
1584  * -> d_root is the translation of the bone root, also in parent's coord system
1585  *
1586  * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1587  *
1588  * we then - in init deform - store the deform in chan_mat, such that:
1589  *
1590  * pose_mat(b)= arm_mat(b) * chan_mat(b)
1591  *
1592  * *************************************************************************** */
1593
1594 /* Computes vector and roll based on a rotation.
1595  * "mat" must contain only a rotation, and no scaling. */
1596 void mat3_to_vec_roll(float mat[3][3], float r_vec[3], float *r_roll)
1597 {
1598         if (r_vec) {
1599                 copy_v3_v3(r_vec, mat[1]);
1600         }
1601
1602         if (r_roll) {
1603                 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1604
1605                 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1606                 invert_m3_m3(vecmatinv, vecmat);
1607                 mul_m3_m3m3(rollmat, vecmatinv, mat);
1608
1609                 *r_roll = atan2f(rollmat[2][0], rollmat[2][2]);
1610         }
1611 }
1612
1613 /* Calculates the rest matrix of a bone based on its vector and a roll around that vector. */
1614 /* Given v = (v.x, v.y, v.z) our (normalized) bone vector, we want the rotation matrix M
1615  * from the Y axis (so that M * (0, 1, 0) = v).
1616  *   -> The rotation axis a lays on XZ plane, and it is orthonormal to v, hence to the projection of v onto XZ plane.
1617  *   -> a = (v.z, 0, -v.x)
1618  * We know a is eigenvector of M (so M * a = a).
1619  * Finally, we have w, such that M * w = (0, 1, 0) (i.e. the vector that will be aligned with Y axis once transformed).
1620  * We know w is symmetric to v by the Y axis.
1621  *   -> w = (-v.x, v.y, -v.z)
1622  *
1623  * Solving this, we get (x, y and z being the components of v):
1624  *     ┌ (x^2 * y + z^2) / (x^2 + z^2),   x,   x * z * (y - 1) / (x^2 + z^2) ┐
1625  * M = │  x * (y^2 - 1)  / (x^2 + z^2),   y,    z * (y^2 - 1)  / (x^2 + z^2) │
1626  *     └ x * z * (y - 1) / (x^2 + z^2),   z,   (x^2 + z^2 * y) / (x^2 + z^2) ┘
1627  *
1628  * This is stable as long as v (the bone) is not too much aligned with +/-Y (i.e. x and z components
1629  * are not too close to 0).
1630  *
1631  * Since v is normalized, we have x^2 + y^2 + z^2 = 1, hence x^2 + z^2 = 1 - y^2 = (1 - y)(1 + y).
1632  * This allows to simplifies M like this:
1633  *     ┌ 1 - x^2 / (1 + y),   x,     -x * z / (1 + y) ┐
1634  * M = │                -x,   y,                   -z │
1635  *     └  -x * z / (1 + y),   z,    1 - z^2 / (1 + y) ┘
1636  *
1637  * Written this way, we see the case v = +Y is no more a singularity. The only one remaining is the bone being
1638  * aligned with -Y.
1639  *
1640  * Let's handle the asymptotic behavior when bone vector is reaching the limit of y = -1. Each of the four corner
1641  * elements can vary from -1 to 1, depending on the axis a chosen for doing the rotation. And the "rotation" here
1642  * is in fact established by mirroring XZ plane by that given axis, then inversing the Y-axis.
1643  * For sufficiently small x and z, and with y approaching -1, all elements but the four corner ones of M
1644  * will degenerate. So let's now focus on these corner elements.
1645  *
1646  * We rewrite M so that it only contains its four corner elements, and combine the 1 / (1 + y) factor:
1647  *                    ┌ 1 + y - x^2,        -x * z ┐
1648  * M* = 1 / (1 + y) * │                            │
1649  *                    └      -x * z,   1 + y - z^2 ┘
1650  *
1651  * When y is close to -1, computing 1 / (1 + y) will cause severe numerical instability, so we ignore it and
1652  * normalize M instead. We know y^2 = 1 - (x^2 + z^2), and y < 0, hence y = -sqrt(1 - (x^2 + z^2)).
1653  * Since x and z are both close to 0, we apply the binomial expansion to the first order:
1654  * y = -sqrt(1 - (x^2 + z^2)) = -1 + (x^2 + z^2) / 2. Which gives:
1655  *                        ┌  z^2 - x^2,  -2 * x * z ┐
1656  * M* = 1 / (x^2 + z^2) * │                         │
1657  *                        └ -2 * x * z,   x^2 - z^2 ┘
1658  */
1659 void vec_roll_to_mat3_normalized(const float nor[3], const float roll, float mat[3][3])
1660 {
1661 #define THETA_THRESHOLD_NEGY 1.0e-9f
1662 #define THETA_THRESHOLD_NEGY_CLOSE 1.0e-5f
1663
1664         float theta;
1665         float rMatrix[3][3], bMatrix[3][3];
1666
1667         BLI_ASSERT_UNIT_V3(nor);
1668
1669         theta = 1.0f + nor[1];
1670
1671         /* With old algo, 1.0e-13f caused T23954 and T31333, 1.0e-6f caused T27675 and T30438,
1672          * so using 1.0e-9f as best compromise.
1673          *
1674          * New algo is supposed much more precise, since less complex computations are performed,
1675          * but it uses two different threshold values...
1676          *
1677          * Note: When theta is close to zero, we have to check we do have non-null X/Z components as well
1678          *       (due to float precision errors, we can have nor = (0.0, 0.99999994, 0.0)...).
1679          */
1680         if (theta > THETA_THRESHOLD_NEGY_CLOSE || ((nor[0] || nor[2]) && theta > THETA_THRESHOLD_NEGY)) {
1681                 /* nor is *not* -Y.
1682                  * We got these values for free... so be happy with it... ;)
1683                  */
1684                 bMatrix[0][1] = -nor[0];
1685                 bMatrix[1][0] = nor[0];
1686                 bMatrix[1][1] = nor[1];
1687                 bMatrix[1][2] = nor[2];
1688                 bMatrix[2][1] = -nor[2];
1689                 if (theta > THETA_THRESHOLD_NEGY_CLOSE) {
1690                         /* If nor is far enough from -Y, apply the general case. */
1691                         bMatrix[0][0] = 1 - nor[0] * nor[0] / theta;
1692                         bMatrix[2][2] = 1 - nor[2] * nor[2] / theta;
1693                         bMatrix[2][0] = bMatrix[0][2] = -nor[0] * nor[2] / theta;
1694                 }
1695                 else {
1696                         /* If nor is too close to -Y, apply the special case. */
1697                         theta = nor[0] * nor[0] + nor[2] * nor[2];
1698                         bMatrix[0][0] = (nor[0] + nor[2]) * (nor[0] - nor[2]) / -theta;
1699                         bMatrix[2][2] = -bMatrix[0][0];
1700                         bMatrix[2][0] = bMatrix[0][2] = 2.0f * nor[0] * nor[2] / theta;
1701                 }
1702         }
1703         else {
1704                 /* If nor is -Y, simple symmetry by Z axis. */
1705                 unit_m3(bMatrix);
1706                 bMatrix[0][0] = bMatrix[1][1] = -1.0;
1707         }
1708
1709         /* Make Roll matrix */
1710         axis_angle_normalized_to_mat3(rMatrix, nor, roll);
1711
1712         /* Combine and output result */
1713         mul_m3_m3m3(mat, rMatrix, bMatrix);
1714
1715 #undef THETA_THRESHOLD_NEGY
1716 #undef THETA_THRESHOLD_NEGY_CLOSE
1717 }
1718
1719 void vec_roll_to_mat3(const float vec[3], const float roll, float mat[3][3])
1720 {
1721         float nor[3];
1722
1723         normalize_v3_v3(nor, vec);
1724         vec_roll_to_mat3_normalized(nor, roll, mat);
1725 }
1726
1727 /* recursive part, calculates restposition of entire tree of children */
1728 /* used by exiting editmode too */
1729 void BKE_armature_where_is_bone(Bone *bone, Bone *prevbone, const bool use_recursion)
1730 {
1731         float vec[3];
1732
1733         /* Bone Space */
1734         sub_v3_v3v3(vec, bone->tail, bone->head);
1735         bone->length = len_v3(vec);
1736         vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1737
1738         /* this is called on old file reading too... */
1739         if (bone->xwidth == 0.0f) {
1740                 bone->xwidth = 0.1f;
1741                 bone->zwidth = 0.1f;
1742                 bone->segments = 1;
1743         }
1744
1745         if (prevbone) {
1746                 float offs_bone[4][4];
1747                 /* yoffs(b-1) + root(b) + bonemat(b) */
1748                 get_offset_bone_mat(bone, offs_bone);
1749
1750                 /* Compose the matrix for this bone  */
1751                 mul_m4_m4m4(bone->arm_mat, prevbone->arm_mat, offs_bone);
1752         }
1753         else {
1754                 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1755                 copy_v3_v3(bone->arm_mat[3], bone->head);
1756         }
1757
1758         /* and the kiddies */
1759         if (use_recursion) {
1760                 prevbone = bone;
1761                 for (bone = bone->childbase.first; bone; bone = bone->next) {
1762                         BKE_armature_where_is_bone(bone, prevbone, use_recursion);
1763                 }
1764         }
1765 }
1766
1767 /* updates vectors and matrices on rest-position level, only needed
1768  * after editing armature itself, now only on reading file */
1769 void BKE_armature_where_is(bArmature *arm)
1770 {
1771         Bone *bone;
1772
1773         /* hierarchical from root to children */
1774         for (bone = arm->bonebase.first; bone; bone = bone->next) {
1775                 BKE_armature_where_is_bone(bone, NULL, true);
1776         }
1777 }
1778
1779 /* if bone layer is protected, copy the data from from->pose
1780  * when used with linked libraries this copies from the linked pose into the local pose */
1781 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1782 {
1783         bPose *pose = ob->pose, *frompose = from->pose;
1784         bPoseChannel *pchan, *pchanp;
1785         bConstraint *con;
1786         int error = 0;
1787
1788         if (frompose == NULL)
1789                 return;
1790
1791         /* in some cases when rigs change, we cant synchronize
1792          * to avoid crashing check for possible errors here */
1793         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1794                 if (pchan->bone->layer & layer_protected) {
1795                         if (BKE_pose_channel_find_name(frompose, pchan->name) == NULL) {
1796                                 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n",
1797                                        from->id.name, pchan->name);
1798                                 error = 1;
1799                         }
1800                 }
1801         }
1802
1803         if (error)
1804                 return;
1805
1806         /* clear all transformation values from library */
1807         BKE_pose_rest(frompose);
1808
1809         /* copy over all of the proxy's bone groups */
1810         /* TODO for later
1811          * - implement 'local' bone groups as for constraints
1812          * Note: this isn't trivial, as bones reference groups by index not by pointer,
1813          *       so syncing things correctly needs careful attention */
1814         BLI_freelistN(&pose->agroups);
1815         BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1816         pose->active_group = frompose->active_group;
1817
1818         for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1819                 pchanp = BKE_pose_channel_find_name(frompose, pchan->name);
1820                 
1821                 if (UNLIKELY(pchanp == NULL)) {
1822                         /* happens for proxies that become invalid because of a missing link
1823                          * for regular cases it shouldn't happen at all */
1824                 }
1825                 else if (pchan->bone->layer & layer_protected) {
1826                         ListBase proxylocal_constraints = {NULL, NULL};
1827                         bPoseChannel pchanw;
1828                         
1829                         /* copy posechannel to temp, but restore important pointers */
1830                         pchanw = *pchanp;
1831                         pchanw.bone = pchan->bone;
1832                         pchanw.prev = pchan->prev;
1833                         pchanw.next = pchan->next;
1834                         pchanw.parent = pchan->parent;
1835                         pchanw.child = pchan->child;
1836                         pchanw.custom_tx = pchan->custom_tx;
1837
1838                         pchanw.mpath = pchan->mpath;
1839                         pchan->mpath = NULL;
1840
1841                         /* this is freed so copy a copy, else undo crashes */
1842                         if (pchanw.prop) {
1843                                 pchanw.prop = IDP_CopyProperty(pchanw.prop);
1844                                 
1845                                 /* use the values from the existing props */
1846                                 if (pchan->prop) {
1847                                         IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1848                                 }
1849                         }
1850                         
1851                         /* constraints - proxy constraints are flushed... local ones are added after
1852                          *     1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1853                          *     2. copy proxy-pchan's constraints on-to new
1854                          *     3. add extracted local constraints back on top
1855                          *
1856                          * Note for BKE_constraints_copy: when copying constraints, disable 'do_extern' otherwise
1857                          *                                we get the libs direct linked in this blend.
1858                          */
1859                         BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints);
1860                         BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false);
1861                         BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
1862                         
1863                         /* constraints - set target ob pointer to own object */
1864                         for (con = pchanw.constraints.first; con; con = con->next) {
1865                                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1866                                 ListBase targets = {NULL, NULL};
1867                                 bConstraintTarget *ct;
1868                                 
1869                                 if (cti && cti->get_constraint_targets) {
1870                                         cti->get_constraint_targets(con, &targets);
1871                                         
1872                                         for (ct = targets.first; ct; ct = ct->next) {
1873                                                 if (ct->tar == from)
1874                                                         ct->tar = ob;
1875                                         }
1876                                         
1877                                         if (cti->flush_constraint_targets)
1878                                                 cti->flush_constraint_targets(con, &targets, 0);
1879                                 }
1880                         }
1881                         
1882                         /* free stuff from current channel */
1883                         BKE_pose_channel_free(pchan);
1884                         
1885                         /* copy data in temp back over to the cleaned-out (but still allocated) original channel */
1886                         *pchan = pchanw;
1887                         if (pchan->custom) {
1888                                 id_us_plus(&pchan->custom->id);
1889                         }
1890                 }
1891                 else {
1892                         /* always copy custom shape */
1893                         pchan->custom = pchanp->custom;
1894                         if (pchan->custom) {
1895                                 id_us_plus(&pchan->custom->id);
1896                         }
1897                         if (pchanp->custom_tx)
1898                                 pchan->custom_tx = BKE_pose_channel_find_name(pose, pchanp->custom_tx->name);
1899
1900                         /* ID-Property Syncing */
1901                         {
1902                                 IDProperty *prop_orig = pchan->prop;
1903                                 if (pchanp->prop) {
1904                                         pchan->prop = IDP_CopyProperty(pchanp->prop);
1905                                         if (prop_orig) {
1906                                                 /* copy existing values across when types match */
1907                                                 IDP_SyncGroupValues(pchan->prop, prop_orig);
1908                                         }
1909                                 }
1910                                 else {
1911                                         pchan->prop = NULL;
1912                                 }
1913                                 if (prop_orig) {
1914                                         IDP_FreeProperty(prop_orig);
1915                                         MEM_freeN(prop_orig);
1916                                 }
1917                         }
1918                 }
1919         }
1920 }
1921
1922 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1923 {
1924         bPoseChannel *pchan = BKE_pose_channel_verify(pose, bone->name); /* verify checks and/or adds */
1925
1926         pchan->bone = bone;
1927         pchan->parent = parchan;
1928
1929         counter++;
1930
1931         for (bone = bone->childbase.first; bone; bone = bone->next) {
1932                 counter = rebuild_pose_bone(pose, bone, pchan, counter);
1933                 /* for quick detecting of next bone in chain, only b-bone uses it now */
1934                 if (bone->flag & BONE_CONNECTED)
1935                         pchan->child = BKE_pose_channel_find_name(pose, bone->name);
1936         }
1937
1938         return counter;
1939 }
1940
1941 /**
1942  * Clear pointers of object's pose (needed in remap case, since we cannot always wait for a complete pose rebuild).
1943  */
1944 void BKE_pose_clear_pointers(bPose *pose)
1945 {
1946         for (bPoseChannel *pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1947                 pchan->bone = NULL;
1948                 pchan->child = NULL;
1949         }
1950 }
1951
1952 /* only after leave editmode, duplicating, validating older files, library syncing */
1953 /* NOTE: pose->flag is set for it */
1954 void BKE_pose_rebuild(Object *ob, bArmature *arm)
1955 {
1956         Bone *bone;
1957         bPose *pose;
1958         bPoseChannel *pchan, *next;
1959         int counter = 0;
1960
1961         /* only done here */
1962         if (ob->pose == NULL) {
1963                 /* create new pose */
1964                 ob->pose = MEM_callocN(sizeof(bPose), "new pose");
1965
1966                 /* set default settings for animviz */
1967                 animviz_settings_init(&ob->pose->avs);
1968         }
1969         pose = ob->pose;
1970
1971         /* clear */
1972         BKE_pose_clear_pointers(pose);
1973
1974         /* first step, check if all channels are there */
1975         for (bone = arm->bonebase.first; bone; bone = bone->next) {
1976                 counter = rebuild_pose_bone(pose, bone, NULL, counter);
1977         }
1978
1979         /* and a check for garbage */
1980         for (pchan = pose->chanbase.first; pchan; pchan = next) {
1981                 next = pchan->next;
1982                 if (pchan->bone == NULL) {
1983                         BKE_pose_channel_free(pchan);
1984                         BKE_pose_channels_hash_free(pose);
1985                         BLI_freelinkN(&pose->chanbase, pchan);
1986                 }
1987         }
1988         /* printf("rebuild pose %s, %d bones\n", ob->id.name, counter); */
1989
1990         /* synchronize protected layers with proxy */
1991         if (ob->proxy) {
1992                 BKE_object_copy_proxy_drivers(ob, ob->proxy);
1993                 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1994         }
1995
1996         BKE_pose_update_constraint_flags(ob->pose); /* for IK detection for example */
1997
1998         ob->pose->flag &= ~POSE_RECALC;
1999         ob->pose->flag |= POSE_WAS_REBUILT;
2000
2001         BKE_pose_channels_hash_make(ob->pose);
2002 }
2003
2004 /* ********************** THE POSE SOLVER ******************* */
2005
2006 /* loc/rot/size to given mat4 */
2007 void BKE_pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
2008 {
2009         float smat[3][3];
2010         float rmat[3][3];
2011         float tmat[3][3];
2012
2013         /* get scaling matrix */
2014         size_to_mat3(smat, pchan->size);
2015
2016         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2017         if (pchan->rotmode > 0) {
2018                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2019                 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2020         }
2021         else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2022                 /* axis-angle - not really that great for 3D-changing orientations */
2023                 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2024         }
2025         else {
2026                 /* quats are normalized before use to eliminate scaling issues */
2027                 float quat[4];
2028
2029                 /* NOTE: we now don't normalize the stored values anymore, since this was kindof evil in some cases
2030                  * but if this proves to be too problematic, switch back to the old system of operating directly on
2031                  * the stored copy
2032                  */
2033                 normalize_qt_qt(quat, pchan->quat);
2034                 quat_to_mat3(rmat, quat);
2035         }
2036
2037         /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2038         mul_m3_m3m3(tmat, rmat, smat);
2039         copy_m4_m3(chan_mat, tmat);
2040
2041         /* prevent action channels breaking chains */
2042         /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2043         if ((pchan->bone == NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2044                 copy_v3_v3(chan_mat[3], pchan->loc);
2045         }
2046 }
2047
2048 /* loc/rot/size to mat4 */
2049 /* used in constraint.c too */
2050 void BKE_pchan_calc_mat(bPoseChannel *pchan)
2051 {
2052         /* this is just a wrapper around the copy of this function which calculates the matrix
2053          * and stores the result in any given channel
2054          */
2055         BKE_pchan_to_mat4(pchan, pchan->chan_mat);
2056 }
2057
2058 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2059
2060 /* NLA strip modifiers */
2061 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2062 {
2063         bActionModifier *amod;
2064         bActionStrip *strip, *strip2;
2065         float scene_cfra = BKE_scene_frame_get(scene);
2066         int do_modif;
2067
2068         for (strip = armob->nlastrips.first; strip; strip = strip->next) {
2069                 do_modif = false;
2070
2071                 if (scene_cfra >= strip->start && scene_cfra <= strip->end)
2072                         do_modif = true;
2073
2074                 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2075                         do_modif = true;
2076
2077                         /* if there are any other strips active, ignore modifiers for this strip -
2078                          * 'hold' option should only hold action modifiers if there are
2079                          * no other active strips */
2080                         for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2081                                 if (strip2 == strip) continue;
2082
2083                                 if (scene_cfra >= strip2->start && scene_cfra <= strip2->end) {
2084                                         if (!(strip2->flag & ACTSTRIP_MUTE))
2085                                                 do_modif = false;
2086                                 }
2087                         }
2088
2089                         /* if there are any later, activated, strips with 'hold' set, they take precedence,
2090                          * so ignore modifiers for this strip */
2091                         for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2092                                 if (scene_cfra < strip2->start) continue;
2093                                 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2094                                         do_modif = false;
2095                                 }
2096                         }
2097                 }
2098
2099                 if (do_modif) {
2100                         /* temporal solution to prevent 2 strips accumulating */
2101                         if (scene_cfra == strip->end && strip->next && strip->next->start == scene_cfra)
2102                                 continue;
2103
2104                         for (amod = strip->modifiers.first; amod; amod = amod->next) {
2105                                 switch (amod->type) {
2106                                         case ACTSTRIP_MOD_DEFORM:
2107                                         {
2108                                                 /* validate first */
2109                                                 if (amod->ob && amod->ob->type == OB_CURVE && amod->channel[0]) {
2110
2111                                                         if (STREQ(pchan->name, amod->channel)) {
2112                                                                 float mat4[4][4], mat3[3][3];
2113
2114                                                                 curve_deform_vector(amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2115                                                                 copy_m4_m4(mat4, pchan->pose_mat);
2116                                                                 mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2117
2118                                                         }
2119                                                 }
2120                                         }
2121                                         break;
2122                                         case ACTSTRIP_MOD_NOISE:
2123                                         {
2124                                                 if (STREQ(pchan->name, amod->channel)) {
2125                                                         float nor[3], loc[3], ofs;
2126                                                         float eul[3], size[3], eulo[3], sizeo[3];
2127
2128                                                         /* calculate turbulance */
2129                                                         ofs = amod->turbul / 200.0f;
2130
2131                                                         /* make a copy of starting conditions */
2132                                                         copy_v3_v3(loc, pchan->pose_mat[3]);
2133                                                         mat4_to_eul(eul, pchan->pose_mat);
2134                                                         mat4_to_size(size, pchan->pose_mat);
2135                                                         copy_v3_v3(eulo, eul);
2136                                                         copy_v3_v3(sizeo, size);
2137
2138                                                         /* apply noise to each set of channels */
2139                                                         if (amod->channels & 4) {
2140                                                                 /* for scaling */
2141                                                                 nor[0] = BLI_gNoise(amod->noisesize, size[0] + ofs, size[1], size[2], 0, 0) - ofs;
2142                                                                 nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1] + ofs, size[2], 0, 0) - ofs;
2143                                                                 nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2] + ofs, 0, 0) - ofs;
2144                                                                 add_v3_v3(size, nor);
2145
2146                                                                 if (sizeo[0] != 0)
2147                                                                         mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2148                                                                 if (sizeo[1] != 0)
2149                                                                         mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2150                                                                 if (sizeo[2] != 0)
2151                                                                         mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2152                                                         }
2153                                                         if (amod->channels & 2) {
2154                                                                 /* for rotation */
2155                                                                 nor[0] = BLI_gNoise(amod->noisesize, eul[0] + ofs, eul[1], eul[2], 0, 0) - ofs;
2156                                                                 nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1] + ofs, eul[2], 0, 0) - ofs;
2157                                                                 nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2] + ofs, 0, 0) - ofs;
2158
2159                                                                 compatible_eul(nor, eulo);
2160                                                                 add_v3_v3(eul, nor);
2161                                                                 compatible_eul(eul, eulo);
2162
2163                                                                 loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2164                                                         }
2165                                                         if (amod->channels & 1) {
2166                                                                 /* for location */
2167                                                                 nor[0] = BLI_gNoise(amod->noisesize, loc[0] + ofs, loc[1], loc[2], 0, 0) - ofs;
2168                                                                 nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1] + ofs, loc[2], 0, 0) - ofs;
2169                                                                 nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2] + ofs, 0, 0) - ofs;
2170
2171                                                                 add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2172                                                         }
2173                                                 }
2174                                         }
2175                                         break;
2176                                 }
2177                         }
2178                 }
2179         }
2180 }
2181
2182 #endif
2183
2184 /* calculate tail of posechannel */
2185 void BKE_pose_where_is_bone_tail(bPoseChannel *pchan)
2186 {
2187         float vec[3];
2188
2189         copy_v3_v3(vec, pchan->pose_mat[1]);
2190         mul_v3_fl(vec, pchan->bone->length);
2191         add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2192 }
2193
2194 /* The main armature solver, does all constraints excluding IK */
2195 /* pchan is validated, as having bone and parent pointer
2196  * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2197  */
2198 void BKE_pose_where_is_bone(
2199         struct Depsgraph *depsgraph, Scene *scene,
2200         Object *ob, bPoseChannel *pchan, float ctime, bool do_extra)
2201 {
2202         /* This gives a chan_mat with actions (ipos) results. */
2203         if (do_extra)
2204                 BKE_pchan_calc_mat(pchan);
2205         else
2206                 unit_m4(pchan->chan_mat);
2207
2208         /* Construct the posemat based on PoseChannels, that we do before applying constraints. */
2209         /* pose_mat(b) = pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2210         BKE_armature_mat_bone_to_pose(pchan, pchan->chan_mat, pchan->pose_mat);
2211
2212         /* Only rootbones get the cyclic offset (unless user doesn't want that). */
2213         /* XXX That could be a problem for snapping and other "reverse transform" features... */
2214         if (!pchan->parent) {
2215                 if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2216                         add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2217         }
2218
2219         if (do_extra) {
2220 #if 0   /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2221                 /* do NLA strip modifiers - i.e. curve follow */
2222                 do_strip_modifiers(scene, ob, bone, pchan);
2223 #endif
2224
2225                 /* Do constraints */
2226                 if (pchan->constraints.first) {
2227                         bConstraintOb *cob;
2228                         float vec[3];
2229
2230                         /* make a copy of location of PoseChannel for later */
2231                         copy_v3_v3(vec, pchan->pose_mat[3]);
2232
2233                         /* prepare PoseChannel for Constraint solving
2234                          * - makes a copy of matrix, and creates temporary struct to use
2235                          */
2236                         cob = BKE_constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2237
2238                         /* Solve PoseChannel's Constraints */
2239                         BKE_constraints_solve(depsgraph, &pchan->constraints, cob, ctime); /* ctime doesnt alter objects */
2240
2241                         /* cleanup after Constraint Solving
2242                          * - applies matrix back to pchan, and frees temporary struct used
2243                          */
2244                         BKE_constraints_clear_evalob(cob);
2245
2246                         /* prevent constraints breaking a chain */
2247                         if (pchan->bone->flag & BONE_CONNECTED) {
2248                                 copy_v3_v3(pchan->pose_mat[3], vec);
2249                         }
2250                 }
2251         }
2252
2253         /* calculate head */
2254         copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
2255         /* calculate tail */
2256         BKE_pose_where_is_bone_tail(pchan);
2257 }
2258
2259 /* This only reads anim data from channels, and writes to channels */
2260 /* This is the only function adding poses */
2261 void BKE_pose_where_is(struct Depsgraph *depsgraph, Scene *scene, Object *ob)
2262 {
2263         bArmature *arm;
2264         Bone *bone;
2265         bPoseChannel *pchan;
2266         float imat[4][4];
2267         float ctime;
2268
2269         if (ob->type != OB_ARMATURE)
2270                 return;
2271         arm = ob->data;
2272
2273         if (ELEM(NULL, arm, scene))
2274                 return;
2275         if ((ob->pose == NULL) || (ob->pose->flag & POSE_RECALC))
2276                 BKE_pose_rebuild(ob, arm);
2277
2278         ctime = BKE_scene_frame_get(scene); /* not accurate... */
2279
2280         /* In editmode or restposition we read the data from the bones */
2281         if (arm->edbo || (arm->flag & ARM_RESTPOS)) {
2282                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2283                         bone = pchan->bone;
2284                         if (bone) {
2285                                 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2286                                 copy_v3_v3(pchan->pose_head, bone->arm_head);
2287                                 copy_v3_v3(pchan->pose_tail, bone->arm_tail);
2288                         }
2289                 }
2290         }
2291         else {
2292                 invert_m4_m4(ob->imat, ob->obmat); /* imat is needed */
2293
2294                 /* 1. clear flags */
2295                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2296                         pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
2297                 }
2298
2299                 /* 2a. construct the IK tree (standard IK) */
2300                 BIK_initialize_tree(depsgraph, scene, ob, ctime);
2301
2302                 /* 2b. construct the Spline IK trees
2303                  *  - this is not integrated as an IK plugin, since it should be able
2304                  *        to function in conjunction with standard IK
2305                  */
2306                 BKE_pose_splineik_init_tree(scene, ob, ctime);
2307
2308                 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2309                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2310                         /* 4a. if we find an IK root, we handle it separated */
2311                         if (pchan->flag & POSE_IKTREE) {
2312                                 BIK_execute_tree(depsgraph, scene, ob, pchan, ctime);
2313                         }
2314                         /* 4b. if we find a Spline IK root, we handle it separated too */
2315                         else if (pchan->flag & POSE_IKSPLINE) {
2316                                 BKE_splineik_execute_tree(depsgraph, scene, ob, pchan, ctime);
2317                         }
2318                         /* 5. otherwise just call the normal solver */
2319                         else if (!(pchan->flag & POSE_DONE)) {
2320                                 BKE_pose_where_is_bone(depsgraph, scene, ob, pchan, ctime, 1);
2321                         }
2322                 }
2323                 /* 6. release the IK tree */
2324                 BIK_release_tree(scene, ob, ctime);
2325         }
2326
2327         /* calculating deform matrices */
2328         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2329                 if (pchan->bone) {
2330                         invert_m4_m4(imat, pchan->bone->arm_mat);
2331                         mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
2332                 }
2333         }
2334 }
2335
2336 /************** Bounding box ********************/
2337 static int minmax_armature(Object *ob, float r_min[3], float r_max[3])
2338 {
2339         bPoseChannel *pchan;
2340
2341         /* For now, we assume BKE_pose_where_is has already been called (hence we have valid data in pachan). */
2342         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2343                 minmax_v3v3_v3(r_min, r_max, pchan->pose_head);
2344                 minmax_v3v3_v3(r_min, r_max, pchan->pose_tail);
2345         }
2346
2347         return (BLI_listbase_is_empty(&ob->pose->chanbase) == false);
2348 }
2349
2350 static void boundbox_armature(Object *ob)
2351 {
2352         BoundBox *bb;
2353         float min[3], max[3];
2354
2355         if (ob->bb == NULL) {
2356                 ob->bb = MEM_callocN(sizeof(BoundBox), "Armature boundbox");
2357         }
2358         bb = ob->bb;
2359
2360         INIT_MINMAX(min, max);
2361         if (!minmax_armature(ob, min, max)) {
2362                 min[0] = min[1] = min[2] = -1.0f;
2363                 max[0] = max[1] = max[2] = 1.0f;
2364         }
2365
2366         BKE_boundbox_init_from_minmax(bb, min, max);
2367
2368         bb->flag &= ~BOUNDBOX_DIRTY;
2369 }
2370
2371 BoundBox *BKE_armature_boundbox_get(Object *ob)
2372 {
2373         boundbox_armature(ob);
2374
2375         return ob->bb;
2376 }
2377
2378 bool BKE_pose_minmax(Object *ob, float r_min[3], float r_max[3], bool use_hidden, bool use_select)
2379 {
2380         bool changed = false;
2381
2382         if (ob->pose) {
2383                 bArmature *arm = ob->data;
2384                 bPoseChannel *pchan;
2385
2386                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2387                         /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2388                          *     (editarmature.c:2592)... Skip in this case too! */
2389                         if (pchan->bone &&
2390                             (!((use_hidden == false) && (PBONE_VISIBLE(arm, pchan->bone) == false)) &&
2391                              !((use_select == true)  && ((pchan->bone->flag & BONE_SELECTED) == 0))))
2392                         {
2393                                 bPoseChannel *pchan_tx = (pchan->custom && pchan->custom_tx) ? pchan->custom_tx : pchan;
2394                                 BoundBox *bb_custom = ((pchan->custom) && !(arm->flag & ARM_NO_CUSTOM)) ?
2395                                                       BKE_object_boundbox_get(pchan->custom) : NULL;
2396                                 if (bb_custom) {
2397                                         float mat[4][4], smat[4][4];
2398                                         scale_m4_fl(smat, PCHAN_CUSTOM_DRAW_SIZE(pchan));
2399                                         mul_m4_series(mat, ob->obmat, pchan_tx->pose_mat, smat);
2400                                         BKE_boundbox_minmax(bb_custom, mat, r_min, r_max);
2401                                 }
2402                                 else {
2403                                         float vec[3];
2404                                         mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_head);
2405                                         minmax_v3v3_v3(r_min, r_max, vec);
2406                                         mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_tail);
2407                                         minmax_v3v3_v3(r_min, r_max, vec);
2408                                 }
2409
2410                                 changed = true;
2411                         }
2412                 }
2413         }
2414
2415         return changed;
2416 }
2417
2418 /************** Graph evaluation ********************/
2419
2420 bPoseChannel *BKE_armature_ik_solver_find_root(
2421         bPoseChannel *pchan,
2422         bKinematicConstraint *data)
2423 {
2424         bPoseChannel *rootchan = pchan;
2425         if (!(data->flag & CONSTRAINT_IK_TIP)) {
2426                 /* Exclude tip from chain. */
2427                 rootchan = rootchan->parent;
2428         }
2429         if (rootchan != NULL) {
2430                 int segcount = 0;
2431                 while (rootchan->parent) {
2432                         /* Continue up chain, until we reach target number of items. */
2433                         segcount++;
2434                         if (segcount == data->rootbone) {
2435                                 break;
2436                         }
2437                         rootchan = rootchan->parent;
2438                 }
2439         }
2440         return rootchan;
2441 }
2442
2443 bPoseChannel *BKE_armature_splineik_solver_find_root(
2444         bPoseChannel *pchan,
2445         bSplineIKConstraint *data)
2446 {
2447         bPoseChannel *rootchan = pchan;
2448         int segcount = 0;
2449         BLI_assert(rootchan != NULL);
2450         while (rootchan->parent) {
2451                 /* Continue up chain, until we reach target number of items. */
2452                 segcount++;
2453                 if (segcount == data->chainlen) {
2454                         break;
2455                 }
2456                 rootchan = rootchan->parent;
2457         }
2458         return rootchan;
2459 }