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