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