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