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