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