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