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