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