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