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