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