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