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