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