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