following on from last commit r36263.
[blender.git] / source / blender / blenkernel / intern / armature.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/armature.c
29  *  \ingroup bke
30  */
31
32
33 #include <ctype.h>
34 #include <stdlib.h>
35 #include <math.h>
36 #include <string.h>
37 #include <stdio.h>
38 #include <float.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "BLI_math.h"
43 #include "BLI_blenlib.h"
44 #include "BLI_utildefines.h"
45
46 #include "DNA_anim_types.h"
47 #include "DNA_armature_types.h"
48 #include "DNA_constraint_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_lattice_types.h"
51 #include "DNA_meshdata_types.h"
52 #include "DNA_nla_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_object_types.h"
55
56 #include "BKE_animsys.h"
57 #include "BKE_armature.h"
58 #include "BKE_action.h"
59 #include "BKE_anim.h"
60 #include "BKE_constraint.h"
61 #include "BKE_curve.h"
62 #include "BKE_depsgraph.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_deform.h"
65 #include "BKE_displist.h"
66 #include "BKE_global.h"
67 #include "BKE_idprop.h"
68 #include "BKE_library.h"
69 #include "BKE_lattice.h"
70 #include "BKE_main.h"
71 #include "BKE_object.h"
72
73 #include "BIK_api.h"
74 #include "BKE_sketch.h"
75
76 /*      **************** Generic Functions, data level *************** */
77
78 bArmature *add_armature(const char *name)
79 {
80         bArmature *arm;
81         
82         arm= alloc_libblock (&G.main->armature, ID_AR, name);
83         arm->deformflag = ARM_DEF_VGROUP|ARM_DEF_ENVELOPE;
84         arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
85         arm->layer= 1;
86         return arm;
87 }
88
89 bArmature *get_armature(Object *ob)
90 {
91         if(ob->type==OB_ARMATURE)
92                 return (bArmature *)ob->data;
93         return NULL;
94 }
95
96 void free_bonelist (ListBase *lb)
97 {
98         Bone *bone;
99
100         for(bone=lb->first; bone; bone=bone->next) {
101                 if(bone->prop) {
102                         IDP_FreeProperty(bone->prop);
103                         MEM_freeN(bone->prop);
104                 }
105                 free_bonelist(&bone->childbase);
106         }
107         
108         BLI_freelistN(lb);
109 }
110
111 void free_armature(bArmature *arm)
112 {
113         if (arm) {
114                 free_bonelist(&arm->bonebase);
115                 
116                 /* free editmode data */
117                 if (arm->edbo) {
118                         BLI_freelistN(arm->edbo);
119                         
120                         MEM_freeN(arm->edbo);
121                         arm->edbo= NULL;
122                 }
123
124                 /* free sketch */
125                 if (arm->sketch) {
126                         freeSketch(arm->sketch);
127                         arm->sketch = NULL;
128                 }
129                 
130                 /* free animation data */
131                 if (arm->adt) {
132                         BKE_free_animdata(&arm->id);
133                         arm->adt= NULL;
134                 }
135         }
136 }
137
138 void make_local_armature(bArmature *arm)
139 {
140         int local=0, lib=0;
141         Object *ob;
142         bArmature *newArm;
143         
144         if (arm->id.lib==NULL)
145                 return;
146         if (arm->id.us==1) {
147                 arm->id.lib= NULL;
148                 arm->id.flag= LIB_LOCAL;
149                 new_id(NULL, (ID*)arm, NULL);
150                 return;
151         }
152         
153         if(local && lib==0) {
154                 arm->id.lib= NULL;
155                 arm->id.flag= LIB_LOCAL;
156                 new_id(NULL, (ID *)arm, NULL);
157         }
158         else if(local && lib) {
159                 newArm= copy_armature(arm);
160                 newArm->id.us= 0;
161                 
162                 ob= G.main->object.first;
163                 while(ob) {
164                         if(ob->data==arm) {
165                                 
166                                 if(ob->id.lib==NULL) {
167                                         ob->data= newArm;
168                                         newArm->id.us++;
169                                         arm->id.us--;
170                                 }
171                         }
172                         ob= ob->id.next;
173                 }
174         }
175 }
176
177 static void     copy_bonechildren (Bone* newBone, Bone* oldBone, Bone* actBone, Bone **newActBone)
178 {
179         Bone    *curBone, *newChildBone;
180         
181         if(oldBone == actBone)
182                 *newActBone= newBone;
183
184         if(oldBone->prop)
185                 newBone->prop= IDP_CopyProperty(oldBone->prop);
186
187         /*      Copy this bone's list*/
188         BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
189         
190         /*      For each child in the list, update it's children*/
191         newChildBone=newBone->childbase.first;
192         for (curBone=oldBone->childbase.first;curBone;curBone=curBone->next){
193                 newChildBone->parent=newBone;
194                 copy_bonechildren(newChildBone, curBone, actBone, newActBone);
195                 newChildBone=newChildBone->next;
196         }
197 }
198
199 bArmature *copy_armature(bArmature *arm)
200 {
201         bArmature *newArm;
202         Bone            *oldBone, *newBone;
203         Bone            *newActBone= NULL;
204         
205         newArm= copy_libblock (arm);
206         BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
207         
208         /*      Duplicate the childrens' lists*/
209         newBone=newArm->bonebase.first;
210         for (oldBone=arm->bonebase.first;oldBone;oldBone=oldBone->next){
211                 newBone->parent=NULL;
212                 copy_bonechildren (newBone, oldBone, arm->act_bone, &newActBone);
213                 newBone=newBone->next;
214         };
215         
216         newArm->act_bone= newActBone;
217
218         newArm->edbo= NULL;
219         newArm->act_edbone= NULL;
220         newArm->sketch= NULL;
221
222         return newArm;
223 }
224
225 static Bone *get_named_bone_bonechildren (Bone *bone, const char *name)
226 {
227         Bone *curBone, *rbone;
228         
229         if (!strcmp (bone->name, name))
230                 return bone;
231         
232         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
233                 rbone=get_named_bone_bonechildren (curBone, name);
234                 if (rbone)
235                         return rbone;
236         }
237         
238         return NULL;
239 }
240
241
242 Bone *get_named_bone (bArmature *arm, const char *name)
243 /*
244         Walk the list until the bone is found
245  */
246 {
247         Bone *bone=NULL, *curBone;
248         
249         if (!arm) return NULL;
250         
251         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
252                 bone = get_named_bone_bonechildren (curBone, name);
253                 if (bone)
254                         return bone;
255         }
256         
257         return bone;
258 }
259
260 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for unique names afterwards)
261  *      strip_number: removes number extensions  (TODO: not used)
262  *      axis: the axis to name on
263  *      head/tail: the head/tail co-ordinate of the bone on the specified axis
264  */
265 int bone_autoside_name (char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
266 {
267         unsigned int len;
268         char    basename[MAXBONENAME]= "";
269         char    extension[5]= "";
270
271         len= strlen(name);
272         if (len == 0) return 0;
273         BLI_strncpy(basename, name, sizeof(basename));
274         
275         /* Figure out extension to append: 
276          *      - The extension to append is based upon the axis that we are working on.
277          *      - If head happens to be on 0, then we must consider the tail position as well to decide
278          *        which side the bone is on
279          *              -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
280          *              -> Otherwise, extension is added from perspective of object based on which side tail goes to
281          *      - If head is non-zero, extension is added from perspective of object based on side head is on
282          */
283         if (axis == 2) {
284                 /* z-axis - vertical (top/bottom) */
285                 if (IS_EQ(head, 0)) {
286                         if (tail < 0)
287                                 strcpy(extension, "Bot");
288                         else if (tail > 0)
289                                 strcpy(extension, "Top");
290                 }
291                 else {
292                         if (head < 0)
293                                 strcpy(extension, "Bot");
294                         else
295                                 strcpy(extension, "Top");
296                 }
297         }
298         else if (axis == 1) {
299                 /* y-axis - depth (front/back) */
300                 if (IS_EQ(head, 0)) {
301                         if (tail < 0)
302                                 strcpy(extension, "Fr");
303                         else if (tail > 0)
304                                 strcpy(extension, "Bk");
305                 }
306                 else {
307                         if (head < 0)
308                                 strcpy(extension, "Fr");
309                         else
310                                 strcpy(extension, "Bk");
311                 }
312         }
313         else {
314                 /* x-axis - horizontal (left/right) */
315                 if (IS_EQ(head, 0)) {
316                         if (tail < 0)
317                                 strcpy(extension, "R");
318                         else if (tail > 0)
319                                 strcpy(extension, "L");
320                 }
321                 else {
322                         if (head < 0)
323                                 strcpy(extension, "R");
324                         else if (head > 0)
325                                 strcpy(extension, "L");
326                 }
327         }
328
329         /* Simple name truncation 
330          *      - truncate if there is an extension and it wouldn't be able to fit
331          *      - otherwise, just append to end
332          */
333         if (extension[0]) {
334                 int change = 1;
335                 
336                 while (change) { /* remove extensions */
337                         change = 0;
338                         if (len > 2 && basename[len-2]=='.') {
339                                 if (basename[len-1]=='L' || basename[len-1] == 'R' ) { /* L R */
340                                         basename[len-2] = '\0';
341                                         len-=2;
342                                         change= 1;
343                                 }
344                         } else if (len > 3 && basename[len-3]=='.') {
345                                 if (    (basename[len-2]=='F' && basename[len-1] == 'r') ||     /* Fr */
346                                                 (basename[len-2]=='B' && basename[len-1] == 'k')        /* Bk */
347                                 ) {
348                                         basename[len-3] = '\0';
349                                         len-=3;
350                                         change= 1;
351                                 }
352                         } else if (len > 4 && basename[len-4]=='.') {
353                                 if (    (basename[len-3]=='T' && basename[len-2]=='o' && basename[len-1] == 'p') ||     /* Top */
354                                                 (basename[len-3]=='B' && basename[len-2]=='o' && basename[len-1] == 't')        /* Bot */
355                                 ) {
356                                         basename[len-4] = '\0';
357                                         len-=4;
358                                         change= 1;
359                                 }
360                         }
361                 }
362
363                 if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
364                         strncpy(name, basename, len-strlen(extension));
365                 }
366
367                 BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
368
369                 return 1;
370         }
371
372         else {
373                 return 0;
374         }
375 }
376
377 /* ************* B-Bone support ******************* */
378
379 #define MAX_BBONE_SUBDIV        32
380
381 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
382 static void equalize_bezier(float *data, int desired)
383 {
384         float *fp, totdist, ddist, dist, fac1, fac2;
385         float pdist[MAX_BBONE_SUBDIV+1];
386         float temp[MAX_BBONE_SUBDIV+1][4];
387         int a, nr;
388         
389         pdist[0]= 0.0f;
390         for(a=0, fp= data; a<MAX_BBONE_SUBDIV; a++, fp+=4) {
391                 QUATCOPY(temp[a], fp);
392                 pdist[a+1]= pdist[a]+len_v3v3(fp, fp+4);
393         }
394         /* do last point */
395         QUATCOPY(temp[a], fp);
396         totdist= pdist[a];
397         
398         /* go over distances and calculate new points */
399         ddist= totdist/((float)desired);
400         nr= 1;
401         for(a=1, fp= data+4; a<desired; a++, fp+=4) {
402                 
403                 dist= ((float)a)*ddist;
404                 
405                 /* we're looking for location (distance) 'dist' in the array */
406                 while((dist>= pdist[nr]) && nr<MAX_BBONE_SUBDIV) {
407                         nr++;
408                 }
409                 
410                 fac1= pdist[nr]- pdist[nr-1];
411                 fac2= pdist[nr]-dist;
412                 fac1= fac2/fac1;
413                 fac2= 1.0f-fac1;
414                 
415                 fp[0]= fac1*temp[nr-1][0]+ fac2*temp[nr][0];
416                 fp[1]= fac1*temp[nr-1][1]+ fac2*temp[nr][1];
417                 fp[2]= fac1*temp[nr-1][2]+ fac2*temp[nr][2];
418                 fp[3]= fac1*temp[nr-1][3]+ fac2*temp[nr][3];
419         }
420         /* set last point, needed for orientation calculus */
421         QUATCOPY(fp, temp[MAX_BBONE_SUBDIV]);
422 }
423
424 /* returns pointer to static array, filled with desired amount of bone->segments elements */
425 /* this calculation is done  within unit bone space */
426 Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest)
427 {
428         static Mat4 bbone_array[MAX_BBONE_SUBDIV];
429         static Mat4 bbone_rest_array[MAX_BBONE_SUBDIV];
430         Mat4 *result_array= (rest)? bbone_rest_array: bbone_array;
431         bPoseChannel *next, *prev;
432         Bone *bone= pchan->bone;
433         float h1[3], h2[3], scale[3], length, hlength1, hlength2, roll1=0.0f, roll2;
434         float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
435         float data[MAX_BBONE_SUBDIV+1][4], *fp;
436         int a, doscale= 0;
437
438         length= bone->length;
439
440         if(!rest) {
441                 /* check if we need to take non-uniform bone scaling into account */
442                 scale[0]= len_v3(pchan->pose_mat[0]);
443                 scale[1]= len_v3(pchan->pose_mat[1]);
444                 scale[2]= len_v3(pchan->pose_mat[2]);
445
446                 if(fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
447                         unit_m4(scalemat);
448                         scalemat[0][0]= scale[0];
449                         scalemat[1][1]= scale[1];
450                         scalemat[2][2]= scale[2];
451                         invert_m4_m4(iscalemat, scalemat);
452
453                         length *= scale[1];
454                         doscale = 1;
455                 }
456         }
457         
458         hlength1= bone->ease1*length*0.390464f;         // 0.5*sqrt(2)*kappa, the handle length for near-perfect circles
459         hlength2= bone->ease2*length*0.390464f;
460         
461         /* evaluate next and prev bones */
462         if(bone->flag & BONE_CONNECTED)
463                 prev= pchan->parent;
464         else
465                 prev= NULL;
466         
467         next= pchan->child;
468         
469         /* find the handle points, since this is inside bone space, the 
470                 first point = (0,0,0)
471                 last point =  (0, length, 0) */
472         
473         if(rest) {
474                 invert_m4_m4(imat, pchan->bone->arm_mat);
475         }
476         else if(doscale) {
477                 copy_m4_m4(posemat, pchan->pose_mat);
478                 normalize_m4(posemat);
479                 invert_m4_m4(imat, posemat);
480         }
481         else
482                 invert_m4_m4(imat, pchan->pose_mat);
483         
484         if(prev) {
485                 float difmat[4][4], result[3][3], imat3[3][3];
486
487                 /* transform previous point inside this bone space */
488                 if(rest)
489                         VECCOPY(h1, prev->bone->arm_head)
490                 else
491                         VECCOPY(h1, prev->pose_head)
492                 mul_m4_v3(imat, h1);
493
494                 if(prev->bone->segments>1) {
495                         /* if previous bone is B-bone too, use average handle direction */
496                         h1[1]-= length;
497                         roll1= 0.0f;
498                 }
499
500                 normalize_v3(h1);
501                 mul_v3_fl(h1, -hlength1);
502
503                 if(prev->bone->segments==1) {
504                         /* find the previous roll to interpolate */
505                         if(rest)
506                                 mul_m4_m4m4(difmat, prev->bone->arm_mat, imat);
507                         else
508                                 mul_m4_m4m4(difmat, prev->pose_mat, imat);
509                         copy_m3_m4(result, difmat);                             // the desired rotation at beginning of next bone
510                         
511                         vec_roll_to_mat3(h1, 0.0f, mat3);                       // the result of vec_roll without roll
512                         
513                         invert_m3_m3(imat3, mat3);
514                         mul_m3_m3m3(mat3, result, imat3);                       // the matrix transforming vec_roll to desired roll
515                         
516                         roll1= (float)atan2(mat3[2][0], mat3[2][2]);
517                 }
518         }
519         else {
520                 h1[0]= 0.0f; h1[1]= hlength1; h1[2]= 0.0f;
521                 roll1= 0.0f;
522         }
523         if(next) {
524                 float difmat[4][4], result[3][3], imat3[3][3];
525                 
526                 /* transform next point inside this bone space */
527                 if(rest)
528                         VECCOPY(h2, next->bone->arm_tail)
529                 else
530                         VECCOPY(h2, next->pose_tail)
531                 mul_m4_v3(imat, h2);
532                 /* if next bone is B-bone too, use average handle direction */
533                 if(next->bone->segments>1);
534                 else h2[1]-= length;
535                 normalize_v3(h2);
536                 
537                 /* find the next roll to interpolate as well */
538                 if(rest)
539                         mul_m4_m4m4(difmat, next->bone->arm_mat, imat);
540                 else
541                         mul_m4_m4m4(difmat, next->pose_mat, imat);
542                 copy_m3_m4(result, difmat);                             // the desired rotation at beginning of next bone
543                 
544                 vec_roll_to_mat3(h2, 0.0f, mat3);                       // the result of vec_roll without roll
545                 
546                 invert_m3_m3(imat3, mat3);
547                 mul_m3_m3m3(mat3, imat3, result);                       // the matrix transforming vec_roll to desired roll
548                 
549                 roll2= (float)atan2(mat3[2][0], mat3[2][2]);
550                 
551                 /* and only now negate handle */
552                 mul_v3_fl(h2, -hlength2);
553         }
554         else {
555                 h2[0]= 0.0f; h2[1]= -hlength2; h2[2]= 0.0f;
556                 roll2= 0.0;
557         }
558
559         /* make curve */
560         if(bone->segments > MAX_BBONE_SUBDIV)
561                 bone->segments= MAX_BBONE_SUBDIV;
562         
563         forward_diff_bezier(0.0, h1[0],         h2[0],                  0.0,            data[0],        MAX_BBONE_SUBDIV, 4*sizeof(float));
564         forward_diff_bezier(0.0, h1[1],         length + h2[1], length,         data[0]+1,      MAX_BBONE_SUBDIV, 4*sizeof(float));
565         forward_diff_bezier(0.0, h1[2],         h2[2],                  0.0,            data[0]+2,      MAX_BBONE_SUBDIV, 4*sizeof(float));
566         forward_diff_bezier(roll1, roll1 + 0.390464f*(roll2-roll1), roll2 - 0.390464f*(roll2-roll1),    roll2,  data[0]+3,      MAX_BBONE_SUBDIV, 4*sizeof(float));
567         
568         equalize_bezier(data[0], bone->segments);       // note: does stride 4!
569         
570         /* make transformation matrices for the segments for drawing */
571         for(a=0, fp= data[0]; a<bone->segments; a++, fp+=4) {
572                 sub_v3_v3v3(h1, fp+4, fp);
573                 vec_roll_to_mat3(h1, fp[3], mat3);              // fp[3] is roll
574
575                 copy_m4_m3(result_array[a].mat, mat3);
576                 VECCOPY(result_array[a].mat[3], fp);
577
578                 if(doscale) {
579                         /* correct for scaling when this matrix is used in scaled space */
580                         mul_serie_m4(result_array[a].mat, iscalemat, result_array[a].mat,
581                                 scalemat, NULL, NULL, NULL, NULL, NULL);
582                 }
583         }
584         
585         return result_array;
586 }
587
588 /* ************ Armature Deform ******************* */
589
590 typedef struct bPoseChanDeform {
591         Mat4            *b_bone_mats;   
592         DualQuat        *dual_quat;
593         DualQuat        *b_bone_dual_quats;
594 } bPoseChanDeform;
595
596 static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, int use_quaternion)
597 {
598         Bone *bone= pchan->bone;
599         Mat4 *b_bone= b_bone_spline_setup(pchan, 0);
600         Mat4 *b_bone_rest= b_bone_spline_setup(pchan, 1);
601         Mat4 *b_bone_mats;
602         DualQuat *b_bone_dual_quats= NULL;
603         float tmat[4][4]= MAT4_UNITY;
604         int a;
605         
606         /* allocate b_bone matrices and dual quats */
607         b_bone_mats= MEM_mallocN((1+bone->segments)*sizeof(Mat4), "BBone defmats");
608         pdef_info->b_bone_mats= b_bone_mats;
609
610         if(use_quaternion) {
611                 b_bone_dual_quats= MEM_mallocN((bone->segments)*sizeof(DualQuat), "BBone dqs");
612                 pdef_info->b_bone_dual_quats= b_bone_dual_quats;
613         }
614         
615         /* first matrix is the inverse arm_mat, to bring points in local bone space
616            for finding out which segment it belongs to */
617         invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
618
619         /* then we make the b_bone_mats:
620                 - first transform to local bone space
621                 - translate over the curve to the bbone mat space
622                 - transform with b_bone matrix
623                 - transform back into global space */
624
625         for(a=0; a<bone->segments; a++) {
626                 invert_m4_m4(tmat, b_bone_rest[a].mat);
627
628                 mul_serie_m4(b_bone_mats[a+1].mat, pchan->chan_mat, bone->arm_mat,
629                         b_bone[a].mat, tmat, b_bone_mats[0].mat, NULL, NULL, NULL);
630
631                 if(use_quaternion)
632                         mat4_to_dquat( &b_bone_dual_quats[a],bone->arm_mat, b_bone_mats[a+1].mat);
633         }
634 }
635
636 static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float *co, DualQuat *dq, float defmat[][3])
637 {
638         Mat4 *b_bone= pdef_info->b_bone_mats;
639         float (*mat)[4]= b_bone[0].mat;
640         float segment, y;
641         int a;
642         
643         /* need to transform co back to bonespace, only need y */
644         y= mat[0][1]*co[0] + mat[1][1]*co[1] + mat[2][1]*co[2] + mat[3][1];
645         
646         /* now calculate which of the b_bones are deforming this */
647         segment= bone->length/((float)bone->segments);
648         a= (int)(y/segment);
649         
650         /* note; by clamping it extends deform at endpoints, goes best with
651            straight joints in restpos. */
652         CLAMP(a, 0, bone->segments-1);
653
654         if(dq) {
655                 copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
656         }
657         else {
658                 mul_m4_v3(b_bone[a+1].mat, co);
659
660                 if(defmat)
661                         copy_m3_m4(defmat, b_bone[a+1].mat);
662         }
663 }
664
665 /* using vec with dist to bone b1 - b2 */
666 float distfactor_to_bone (float vec[3], float b1[3], float b2[3], float rad1, float rad2, float rdist)
667 {
668         float dist=0.0f; 
669         float bdelta[3];
670         float pdelta[3];
671         float hsqr, a, l, rad;
672         
673         sub_v3_v3v3(bdelta, b2, b1);
674         l = normalize_v3(bdelta);
675         
676         sub_v3_v3v3(pdelta, vec, b1);
677         
678         a = bdelta[0]*pdelta[0] + bdelta[1]*pdelta[1] + bdelta[2]*pdelta[2];
679         hsqr = ((pdelta[0]*pdelta[0]) + (pdelta[1]*pdelta[1]) + (pdelta[2]*pdelta[2]));
680         
681         if (a < 0.0F){
682                 /* If we're past the end of the bone, do a spherical field attenuation thing */
683                 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])) ;
684                 rad= rad1;
685         }
686         else if (a > l){
687                 /* If we're past the end of the bone, do a spherical field attenuation thing */
688                 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])) ;
689                 rad= rad2;
690         }
691         else {
692                 dist= (hsqr - (a*a));
693                 
694                 if(l!=0.0f) {
695                         rad= a/l;
696                         rad= rad*rad2 + (1.0f-rad)*rad1;
697                 }
698                 else rad= rad1;
699         }
700         
701         a= rad*rad;
702         if(dist < a) 
703                 return 1.0f;
704         else {
705                 l= rad+rdist;
706                 l*= l;
707                 if(rdist==0.0f || dist >= l) 
708                         return 0.0f;
709                 else {
710                         a= (float)sqrt(dist)-rad;
711                         return 1.0f-( a*a )/( rdist*rdist );
712                 }
713         }
714 }
715
716 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[][3], float mat[][3])
717 {
718         float wmat[3][3];
719
720         if(pchan->bone->segments>1)
721                 copy_m3_m3(wmat, bbonemat);
722         else
723                 copy_m3_m4(wmat, pchan->chan_mat);
724
725         mul_m3_fl(wmat, weight);
726         add_m3_m3m3(mat, mat, wmat);
727 }
728
729 static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float *vec, DualQuat *dq, float mat[][3], float *co)
730 {
731         Bone *bone= pchan->bone;
732         float fac, contrib=0.0;
733         float cop[3], bbonemat[3][3];
734         DualQuat bbonedq;
735
736         if(bone==NULL) return 0.0f;
737         
738         VECCOPY (cop, co);
739
740         fac= distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
741         
742         if (fac > 0.0f) {
743                 
744                 fac*=bone->weight;
745                 contrib= fac;
746                 if(contrib > 0.0f) {
747                         if(vec) {
748                                 if(bone->segments>1)
749                                         // applies on cop and bbonemat
750                                         b_bone_deform(pdef_info, bone, cop, NULL, (mat)?bbonemat:NULL);
751                                 else
752                                         mul_m4_v3(pchan->chan_mat, cop);
753
754                                 //      Make this a delta from the base position
755                                 sub_v3_v3(cop, co);
756                                 madd_v3_v3fl(vec, cop, fac);
757
758                                 if(mat)
759                                         pchan_deform_mat_add(pchan, fac, bbonemat, mat);
760                         }
761                         else {
762                                 if(bone->segments>1) {
763                                         b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
764                                         add_weighted_dq_dq(dq, &bbonedq, fac);
765                                 }
766                                 else
767                                         add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
768                         }
769                 }
770         }
771         
772         return contrib;
773 }
774
775 static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float *vec, DualQuat *dq, float mat[][3], float *co, float *contrib)
776 {
777         float cop[3], bbonemat[3][3];
778         DualQuat bbonedq;
779
780         if (!weight)
781                 return;
782
783         VECCOPY(cop, co);
784
785         if(vec) {
786                 if(pchan->bone->segments>1)
787                         // applies on cop and bbonemat
788                         b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat)?bbonemat:NULL);
789                 else
790                         mul_m4_v3(pchan->chan_mat, cop);
791                 
792                 vec[0]+=(cop[0]-co[0])*weight;
793                 vec[1]+=(cop[1]-co[1])*weight;
794                 vec[2]+=(cop[2]-co[2])*weight;
795
796                 if(mat)
797                         pchan_deform_mat_add(pchan, weight, bbonemat, mat);
798         }
799         else {
800                 if(pchan->bone->segments>1) {
801                         b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
802                         add_weighted_dq_dq(dq, &bbonedq, weight);
803                 }
804                 else
805                         add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
806         }
807
808         (*contrib)+=weight;
809 }
810
811 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm,
812                                                    float (*vertexCos)[3], float (*defMats)[3][3],
813                                                    int numVerts, int deformflag, 
814                                                    float (*prevCos)[3], const char *defgrp_name)
815 {
816         bPoseChanDeform *pdef_info_array;
817         bPoseChanDeform *pdef_info= NULL;
818         bArmature *arm= armOb->data;
819         bPoseChannel *pchan, **defnrToPC = NULL;
820         int *defnrToPCIndex= NULL;
821         MDeformVert *dverts = NULL;
822         bDeformGroup *dg;
823         DualQuat *dualquats= NULL;
824         float obinv[4][4], premat[4][4], postmat[4][4];
825         const short use_envelope = deformflag & ARM_DEF_ENVELOPE;
826         const short use_quaternion = deformflag & ARM_DEF_QUATERNION;
827         const short invert_vgroup= deformflag & ARM_DEF_INVERT_VGROUP;
828         int numGroups = 0;              /* safety for vertexgroup index overflow */
829         int i, target_totvert = 0;      /* safety for vertexgroup overflow */
830         int use_dverts = 0;
831         int armature_def_nr;
832         int totchan;
833
834         if(arm->edbo) return;
835         
836         invert_m4_m4(obinv, target->obmat);
837         copy_m4_m4(premat, target->obmat);
838         mul_m4_m4m4(postmat, armOb->obmat, obinv);
839         invert_m4_m4(premat, postmat);
840
841         /* bone defmats are already in the channels, chan_mat */
842         
843         /* initialize B_bone matrices and dual quaternions */
844         totchan= BLI_countlist(&armOb->pose->chanbase);
845
846         if(use_quaternion) {
847                 dualquats= MEM_callocN(sizeof(DualQuat)*totchan, "dualquats");
848         }
849         
850         pdef_info_array= MEM_callocN(sizeof(bPoseChanDeform)*totchan, "bPoseChanDeform");
851
852         totchan= 0;
853         pdef_info= pdef_info_array;
854         for(pchan= armOb->pose->chanbase.first; pchan; pchan= pchan->next, pdef_info++) {
855                 if(!(pchan->bone->flag & BONE_NO_DEFORM)) {
856                         if(pchan->bone->segments > 1)
857                                 pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
858
859                         if(use_quaternion) {
860                                 pdef_info->dual_quat= &dualquats[totchan++];
861                                 mat4_to_dquat( pdef_info->dual_quat,pchan->bone->arm_mat, pchan->chan_mat);
862                         }
863                 }
864         }
865
866         /* get the def_nr for the overall armature vertex group if present */
867         armature_def_nr= defgroup_name_index(target, defgrp_name);
868         
869         if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
870                 numGroups = BLI_countlist(&target->defbase);
871                 
872                 if(target->type==OB_MESH) {
873                         Mesh *me= target->data;
874                         dverts = me->dvert;
875                         if(dverts)
876                                 target_totvert = me->totvert;
877                 }
878                 else {
879                         Lattice *lt= target->data;
880                         dverts = lt->dvert;
881                         if(dverts)
882                                 target_totvert = lt->pntsu*lt->pntsv*lt->pntsw;
883                 }
884         }
885         
886         /* get a vertex-deform-index to posechannel array */
887         if(deformflag & ARM_DEF_VGROUP) {
888                 if(ELEM(target->type, OB_MESH, OB_LATTICE)) {
889                         /* if we have a DerivedMesh, only use dverts if it has them */
890                         if(dm)
891                                 if(dm->getVertData(dm, 0, CD_MDEFORMVERT))
892                                         use_dverts = 1;
893                                 else use_dverts = 0;
894                         else if(dverts) use_dverts = 1;
895
896                         if(use_dverts) {
897                                 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * numGroups, "defnrToBone");
898                                 defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * numGroups, "defnrToIndex");
899                                 for(i = 0, dg = target->defbase.first; dg;
900                                         i++, dg = dg->next) {
901                                         defnrToPC[i] = get_pose_channel(armOb->pose, dg->name);
902                                         /* exclude non-deforming bones */
903                                         if(defnrToPC[i]) {
904                                                 if(defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
905                                                         defnrToPC[i]= NULL;
906                                                 }
907                                                 else {
908                                                         defnrToPCIndex[i]= BLI_findindex(&armOb->pose->chanbase, defnrToPC[i]);
909                                                 }
910                                         }
911                                 }
912                         }
913                 }
914         }
915
916         for(i = 0; i < numVerts; i++) {
917                 MDeformVert *dvert;
918                 DualQuat sumdq, *dq = NULL;
919                 float *co, dco[3];
920                 float sumvec[3], summat[3][3];
921                 float *vec = NULL, (*smat)[3] = NULL;
922                 float contrib = 0.0f;
923                 float armature_weight = 1.0f;   /* default to 1 if no overall def group */
924                 float prevco_weight = 1.0f;             /* weight for optional cached vertexcos */
925                 int       j;
926
927                 if(use_quaternion) {
928                         memset(&sumdq, 0, sizeof(DualQuat));
929                         dq= &sumdq;
930                 }
931                 else {
932                         sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
933                         vec= sumvec;
934
935                         if(defMats) {
936                                 zero_m3(summat);
937                                 smat = summat;
938                         }
939                 }
940
941                 if(use_dverts || armature_def_nr >= 0) {
942                         if(dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
943                         else if(dverts && i < target_totvert) dvert = dverts + i;
944                         else dvert = NULL;
945                 } else
946                         dvert = NULL;
947
948                 if(armature_def_nr >= 0 && dvert) {
949                         armature_weight= defvert_find_weight(dvert, armature_def_nr);
950
951                         if(invert_vgroup) {
952                                 armature_weight= 1.0f-armature_weight;
953                         }
954
955                         /* hackish: the blending factor can be used for blending with prevCos too */
956                         if(prevCos) {
957                                 prevco_weight= armature_weight;
958                                 armature_weight= 1.0f;
959                         }
960                 }
961
962                 /* check if there's any  point in calculating for this vert */
963                 if(armature_weight == 0.0f) continue;
964                 
965                 /* get the coord we work on */
966                 co= prevCos?prevCos[i]:vertexCos[i];
967                 
968                 /* Apply the object's matrix */
969                 mul_m4_v3(premat, co);
970                 
971                 if(use_dverts && dvert && dvert->totweight) { // use weight groups ?
972                         int deformed = 0;
973                         
974                         for(j = 0; j < dvert->totweight; j++){
975                                 int index = dvert->dw[j].def_nr;
976                                 if(index < numGroups && (pchan= defnrToPC[index])) {
977                                         float weight = dvert->dw[j].weight;
978                                         Bone *bone= pchan->bone;
979                                         pdef_info= pdef_info_array + defnrToPCIndex[index];
980
981                                         deformed = 1;
982                                         
983                                         if(bone && bone->flag & BONE_MULT_VG_ENV) {
984                                                 weight *= distfactor_to_bone(co, bone->arm_head,
985                                                                                                          bone->arm_tail,
986                                                                                                          bone->rad_head,
987                                                                                                          bone->rad_tail,
988                                                                                                          bone->dist);
989                                         }
990                                         pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
991                                 }
992                         }
993                         /* if there are vertexgroups but not groups with bones
994                          * (like for softbody groups)
995                          */
996                         if(deformed == 0 && use_envelope) {
997                                 pdef_info= pdef_info_array;
998                                 for(pchan= armOb->pose->chanbase.first; pchan;
999                                         pchan= pchan->next, pdef_info++) {
1000                                         if(!(pchan->bone->flag & BONE_NO_DEFORM))
1001                                                 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1002                                 }
1003                         }
1004                 }
1005                 else if(use_envelope) {
1006                         pdef_info= pdef_info_array;
1007                         for(pchan = armOb->pose->chanbase.first; pchan;
1008                                 pchan = pchan->next, pdef_info++) {
1009                                 if(!(pchan->bone->flag & BONE_NO_DEFORM))
1010                                         contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1011                         }
1012                 }
1013
1014                 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1015                 if(contrib > 0.0001f) {
1016                         if(use_quaternion) {
1017                                 normalize_dq(dq, contrib);
1018
1019                                 if(armature_weight != 1.0f) {
1020                                         VECCOPY(dco, co);
1021                                         mul_v3m3_dq( dco, (defMats)? summat: NULL,dq);
1022                                         sub_v3_v3(dco, co);
1023                                         mul_v3_fl(dco, armature_weight);
1024                                         add_v3_v3(co, dco);
1025                                 }
1026                                 else
1027                                         mul_v3m3_dq( co, (defMats)? summat: NULL,dq);
1028
1029                                 smat = summat;
1030                         }
1031                         else {
1032                                 mul_v3_fl(vec, armature_weight/contrib);
1033                                 add_v3_v3v3(co, vec, co);
1034                         }
1035
1036                         if(defMats) {
1037                                 float pre[3][3], post[3][3], tmpmat[3][3];
1038
1039                                 copy_m3_m4(pre, premat);
1040                                 copy_m3_m4(post, postmat);
1041                                 copy_m3_m3(tmpmat, defMats[i]);
1042
1043                                 if(!use_quaternion) /* quaternion already is scale corrected */
1044                                         mul_m3_fl(smat, armature_weight/contrib);
1045
1046                                 mul_serie_m3(defMats[i], tmpmat, pre, smat, post,
1047                                         NULL, NULL, NULL, NULL);
1048                         }
1049                 }
1050                 
1051                 /* always, check above code */
1052                 mul_m4_v3(postmat, co);
1053                 
1054                 
1055                 /* interpolate with previous modifier position using weight group */
1056                 if(prevCos) {
1057                         float mw= 1.0f - prevco_weight;
1058                         vertexCos[i][0]= prevco_weight*vertexCos[i][0] + mw*co[0];
1059                         vertexCos[i][1]= prevco_weight*vertexCos[i][1] + mw*co[1];
1060                         vertexCos[i][2]= prevco_weight*vertexCos[i][2] + mw*co[2];
1061                 }
1062         }
1063
1064         if(dualquats) MEM_freeN(dualquats);
1065         if(defnrToPC) MEM_freeN(defnrToPC);
1066         if(defnrToPCIndex) MEM_freeN(defnrToPCIndex);
1067
1068         /* free B_bone matrices */
1069         pdef_info= pdef_info_array;
1070         for(pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1071                 if(pdef_info->b_bone_mats) {
1072                         MEM_freeN(pdef_info->b_bone_mats);
1073                 }
1074                 if(pdef_info->b_bone_dual_quats) {
1075                         MEM_freeN(pdef_info->b_bone_dual_quats);
1076                 }
1077         }
1078
1079         MEM_freeN(pdef_info_array);
1080 }
1081
1082 /* ************ END Armature Deform ******************* */
1083
1084 void get_objectspace_bone_matrix (struct Bone* bone, float M_accumulatedMatrix[][4], int UNUSED(root), int UNUSED(posed))
1085 {
1086         copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1087 }
1088
1089 /* **************** Space to Space API ****************** */
1090
1091 /* Convert World-Space Matrix to Pose-Space Matrix */
1092 void armature_mat_world_to_pose(Object *ob, float inmat[][4], float outmat[][4]) 
1093 {
1094         float obmat[4][4];
1095         
1096         /* prevent crashes */
1097         if (ob==NULL) return;
1098         
1099         /* get inverse of (armature) object's matrix  */
1100         invert_m4_m4(obmat, ob->obmat);
1101         
1102         /* multiply given matrix by object's-inverse to find pose-space matrix */
1103         mul_m4_m4m4(outmat, obmat, inmat);
1104 }
1105
1106 /* Convert Wolrd-Space Location to Pose-Space Location
1107  * NOTE: this cannot be used to convert to pose-space location of the supplied
1108  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1109  */
1110 void armature_loc_world_to_pose(Object *ob, float *inloc, float *outloc) 
1111 {
1112         float xLocMat[4][4]= MAT4_UNITY;
1113         float nLocMat[4][4];
1114         
1115         /* build matrix for location */
1116         VECCOPY(xLocMat[3], inloc);
1117
1118         /* get bone-space cursor matrix and extract location */
1119         armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1120         VECCOPY(outloc, nLocMat[3]);
1121 }
1122
1123 /* Convert Pose-Space Matrix to Bone-Space Matrix 
1124  * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1125  *              pose-channel into its local space (i.e. 'visual'-keyframing)
1126  */
1127 void armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[][4], float outmat[][4])
1128 {
1129         float pc_trans[4][4], inv_trans[4][4];
1130         float pc_posemat[4][4], inv_posemat[4][4];
1131         float pose_mat[4][4];
1132
1133         /* paranoia: prevent crashes with no pose-channel supplied */
1134         if (pchan==NULL) return;
1135
1136         /* default flag */
1137         if((pchan->bone->flag & BONE_NO_LOCAL_LOCATION)==0) {
1138                 /* get the inverse matrix of the pchan's transforms */
1139                 switch(pchan->rotmode) {
1140                 case ROT_MODE_QUAT:
1141                         loc_quat_size_to_mat4(pc_trans, pchan->loc, pchan->quat, pchan->size);
1142                         break;
1143                 case ROT_MODE_AXISANGLE:
1144                         loc_axisangle_size_to_mat4(pc_trans, pchan->loc, pchan->rotAxis, pchan->rotAngle, pchan->size);
1145                         break;
1146                 default: /* euler */
1147                         loc_eul_size_to_mat4(pc_trans, pchan->loc, pchan->eul, pchan->size);
1148                 }
1149
1150                 copy_m4_m4(pose_mat, pchan->pose_mat);
1151         }
1152         else {
1153                 /* local location, this is not default, different calculation
1154                  * note: only tested for location with pose bone snapping.
1155                  * If this is not useful in other cases the BONE_NO_LOCAL_LOCATION
1156                  * case may have to be split into its own function. */
1157                 unit_m4(pc_trans);
1158                 copy_v3_v3(pc_trans[3], pchan->loc);
1159
1160                 /* use parents rotation/scale space + own absolute position */
1161                 if(pchan->parent)       copy_m4_m4(pose_mat, pchan->parent->pose_mat);
1162                 else                            unit_m4(pose_mat);
1163
1164                 copy_v3_v3(pose_mat[3], pchan->pose_mat[3]);
1165         }
1166
1167
1168         invert_m4_m4(inv_trans, pc_trans);
1169         
1170         /* Remove the pchan's transforms from it's pose_mat.
1171          * This should leave behind the effects of restpose + 
1172          * parenting + constraints
1173          */
1174         mul_m4_m4m4(pc_posemat, inv_trans, pose_mat);
1175         
1176         /* get the inverse of the leftovers so that we can remove 
1177          * that component from the supplied matrix
1178          */
1179         invert_m4_m4(inv_posemat, pc_posemat);
1180         
1181         /* get the new matrix */
1182         mul_m4_m4m4(outmat, inmat, inv_posemat);
1183 }
1184
1185 /* Convert Pose-Space Location to Bone-Space Location
1186  * NOTE: this cannot be used to convert to pose-space location of the supplied
1187  *              pose-channel into its local space (i.e. 'visual'-keyframing) 
1188  */
1189 void armature_loc_pose_to_bone(bPoseChannel *pchan, float *inloc, float *outloc) 
1190 {
1191         float xLocMat[4][4]= MAT4_UNITY;
1192         float nLocMat[4][4];
1193         
1194         /* build matrix for location */
1195         VECCOPY(xLocMat[3], inloc);
1196
1197         /* get bone-space cursor matrix and extract location */
1198         armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1199         VECCOPY(outloc, nLocMat[3]);
1200 }
1201
1202 /* same as object_mat3_to_rot() */
1203 void pchan_mat3_to_rot(bPoseChannel *pchan, float mat[][3], short use_compat)
1204 {
1205         switch(pchan->rotmode) {
1206         case ROT_MODE_QUAT:
1207                 mat3_to_quat(pchan->quat, mat);
1208                 break;
1209         case ROT_MODE_AXISANGLE:
1210                 mat3_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1211                 break;
1212         default: /* euler */
1213                 if(use_compat)  mat3_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1214                 else                    mat3_to_eulO(pchan->eul, pchan->rotmode, mat);
1215         }
1216 }
1217
1218 /* Apply a 4x4 matrix to the pose bone,
1219  * similar to object_apply_mat4()
1220  */
1221 void pchan_apply_mat4(bPoseChannel *pchan, float mat[][4], short use_compat)
1222 {
1223         float rot[3][3];
1224         mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1225         pchan_mat3_to_rot(pchan, rot, use_compat);
1226 }
1227
1228 /* Remove rest-position effects from pose-transform for obtaining
1229  * 'visual' transformation of pose-channel.
1230  * (used by the Visual-Keyframing stuff)
1231  */
1232 void armature_mat_pose_to_delta(float delta_mat[][4], float pose_mat[][4], float arm_mat[][4])
1233 {
1234         float imat[4][4];
1235         
1236         invert_m4_m4(imat, arm_mat);
1237         mul_m4_m4m4(delta_mat, pose_mat, imat);
1238 }
1239
1240 /* **************** Rotation Mode Conversions ****************************** */
1241 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1242
1243 /* Called from RNA when rotation mode changes 
1244  *      - the result should be that the rotations given in the provided pointers have had conversions 
1245  *        applied (as appropriate), such that the rotation of the element hasn't 'visually' changed 
1246  */
1247 void BKE_rotMode_change_values (float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1248 {
1249         /* check if any change - if so, need to convert data */
1250         if (newMode > 0) { /* to euler */
1251                 if (oldMode == ROT_MODE_AXISANGLE) {
1252                         /* axis-angle to euler */
1253                         axis_angle_to_eulO( eul, newMode,axis, *angle);
1254                 }
1255                 else if (oldMode == ROT_MODE_QUAT) {
1256                         /* quat to euler */
1257                         normalize_qt(quat);
1258                         quat_to_eulO( eul, newMode,quat);
1259                 }
1260                 /* else { no conversion needed } */
1261         }
1262         else if (newMode == ROT_MODE_QUAT) { /* to quat */
1263                 if (oldMode == ROT_MODE_AXISANGLE) {
1264                         /* axis angle to quat */
1265                         axis_angle_to_quat(quat, axis, *angle);
1266                 }
1267                 else if (oldMode > 0) {
1268                         /* euler to quat */
1269                         eulO_to_quat( quat,eul, oldMode);
1270                 }
1271                 /* else { no conversion needed } */
1272         }
1273         else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1274                 if (oldMode > 0) {
1275                         /* euler to axis angle */
1276                         eulO_to_axis_angle( axis, angle,eul, oldMode);
1277                 }
1278                 else if (oldMode == ROT_MODE_QUAT) {
1279                         /* quat to axis angle */
1280                         normalize_qt(quat);
1281                         quat_to_axis_angle( axis, angle,quat);
1282                 }
1283                 
1284                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1285                 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
1286                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1287                         axis[1]= 1.0f;
1288                 }
1289         }
1290 }
1291
1292 /* **************** The new & simple (but OK!) armature evaluation ********* */ 
1293
1294 /*  ****************** And how it works! ****************************************
1295
1296   This is the bone transformation trick; they're hierarchical so each bone(b)
1297   is in the coord system of bone(b-1):
1298
1299   arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) 
1300   
1301   -> yoffs is just the y axis translation in parent's coord system
1302   -> d_root is the translation of the bone root, also in parent's coord system
1303
1304   pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1305
1306   we then - in init deform - store the deform in chan_mat, such that:
1307
1308   pose_mat(b)= arm_mat(b) * chan_mat(b)
1309   
1310   *************************************************************************** */
1311 /*  Computes vector and roll based on a rotation. "mat" must
1312          contain only a rotation, and no scaling. */ 
1313 void mat3_to_vec_roll(float mat[][3], float *vec, float *roll) 
1314 {
1315         if (vec)
1316                 copy_v3_v3(vec, mat[1]);
1317
1318         if (roll) {
1319                 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1320
1321                 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1322                 invert_m3_m3(vecmatinv, vecmat);
1323                 mul_m3_m3m3(rollmat, vecmatinv, mat);
1324
1325                 *roll= (float)atan2(rollmat[2][0], rollmat[2][2]);
1326         }
1327 }
1328
1329 /*      Calculates the rest matrix of a bone based
1330         On its vector and a roll around that vector */
1331 void vec_roll_to_mat3(float *vec, float roll, float mat[][3])
1332 {
1333         float   nor[3], axis[3], target[3]={0,1,0};
1334         float   theta;
1335         float   rMatrix[3][3], bMatrix[3][3];
1336
1337         normalize_v3_v3(nor, vec);
1338         
1339         /*      Find Axis & Amount for bone matrix*/
1340         cross_v3_v3v3(axis,target,nor);
1341
1342         /* was 0.0000000000001, caused bug [#23954], smaller values give unstable
1343          * roll when toggling editmode */
1344         if (dot_v3v3(axis,axis) > 0.00001f) {
1345                 /* if nor is *not* a multiple of target ... */
1346                 normalize_v3(axis);
1347                 
1348                 theta= angle_normalized_v3v3(target, nor);
1349                 
1350                 /*      Make Bone matrix*/
1351                 vec_rot_to_mat3( bMatrix,axis, theta);
1352         }
1353         else {
1354                 /* if nor is a multiple of target ... */
1355                 float updown;
1356                 
1357                 /* point same direction, or opposite? */
1358                 updown = ( dot_v3v3(target,nor) > 0 ) ? 1.0f : -1.0f;
1359                 
1360                 /* I think this should work ... */
1361                 bMatrix[0][0]=updown; bMatrix[0][1]=0.0;    bMatrix[0][2]=0.0;
1362                 bMatrix[1][0]=0.0;    bMatrix[1][1]=updown; bMatrix[1][2]=0.0;
1363                 bMatrix[2][0]=0.0;    bMatrix[2][1]=0.0;    bMatrix[2][2]=1.0;
1364         }
1365         
1366         /*      Make Roll matrix*/
1367         vec_rot_to_mat3( rMatrix,nor, roll);
1368         
1369         /*      Combine and output result*/
1370         mul_m3_m3m3(mat, rMatrix, bMatrix);
1371 }
1372
1373
1374 /* recursive part, calculates restposition of entire tree of children */
1375 /* used by exiting editmode too */
1376 void where_is_armature_bone(Bone *bone, Bone *prevbone)
1377 {
1378         float vec[3];
1379         
1380         /* Bone Space */
1381         sub_v3_v3v3(vec, bone->tail, bone->head);
1382         vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1383
1384         bone->length= len_v3v3(bone->head, bone->tail);
1385         
1386         /* this is called on old file reading too... */
1387         if(bone->xwidth==0.0f) {
1388                 bone->xwidth= 0.1f;
1389                 bone->zwidth= 0.1f;
1390                 bone->segments= 1;
1391         }
1392         
1393         if(prevbone) {
1394                 float offs_bone[4][4];  // yoffs(b-1) + root(b) + bonemat(b)
1395                 
1396                 /* bone transform itself */
1397                 copy_m4_m3(offs_bone, bone->bone_mat);
1398                                 
1399                 /* The bone's root offset (is in the parent's coordinate system) */
1400                 VECCOPY(offs_bone[3], bone->head);
1401
1402                 /* Get the length translation of parent (length along y axis) */
1403                 offs_bone[3][1]+= prevbone->length;
1404                 
1405                 /* Compose the matrix for this bone  */
1406                 mul_m4_m4m4(bone->arm_mat, offs_bone, prevbone->arm_mat);
1407         }
1408         else {
1409                 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1410                 VECCOPY(bone->arm_mat[3], bone->head);
1411         }
1412         
1413         /* and the kiddies */
1414         prevbone= bone;
1415         for(bone= bone->childbase.first; bone; bone= bone->next) {
1416                 where_is_armature_bone(bone, prevbone);
1417         }
1418 }
1419
1420 /* updates vectors and matrices on rest-position level, only needed 
1421    after editing armature itself, now only on reading file */
1422 void where_is_armature (bArmature *arm)
1423 {
1424         Bone *bone;
1425         
1426         /* hierarchical from root to children */
1427         for(bone= arm->bonebase.first; bone; bone= bone->next) {
1428                 where_is_armature_bone(bone, NULL);
1429         }
1430 }
1431
1432 /* if bone layer is protected, copy the data from from->pose
1433  * when used with linked libraries this copies from the linked pose into the local pose */
1434 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1435 {
1436         bPose *pose= ob->pose, *frompose= from->pose;
1437         bPoseChannel *pchan, *pchanp, pchanw;
1438         bConstraint *con;
1439         int error = 0;
1440         
1441         if (frompose==NULL) return;
1442
1443         /* in some cases when rigs change, we cant synchronize
1444          * to avoid crashing check for possible errors here */
1445         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1446                 if (pchan->bone->layer & layer_protected) {
1447                         if(get_pose_channel(frompose, pchan->name) == NULL) {
1448                                 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n", from->id.name, pchan->name);
1449                                 error = 1;
1450                         }
1451                 }
1452         }
1453
1454         if(error)
1455                 return;
1456         
1457         /* clear all transformation values from library */
1458         rest_pose(frompose);
1459         
1460         /* copy over all of the proxy's bone groups */
1461                 /* TODO for later - implement 'local' bone groups as for constraints
1462                  *      Note: this isn't trivial, as bones reference groups by index not by pointer, 
1463                  *               so syncing things correctly needs careful attention
1464                  */
1465         BLI_freelistN(&pose->agroups);
1466         BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1467         pose->active_group= frompose->active_group;
1468         
1469         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
1470                 pchanp= get_pose_channel(frompose, pchan->name);
1471
1472                 if (pchan->bone->layer & layer_protected) {
1473                         ListBase proxylocal_constraints = {NULL, NULL};
1474                         
1475                         /* copy posechannel to temp, but restore important pointers */
1476                         pchanw= *pchanp;
1477                         pchanw.prev= pchan->prev;
1478                         pchanw.next= pchan->next;
1479                         pchanw.parent= pchan->parent;
1480                         pchanw.child= pchan->child;
1481                         pchanw.path= NULL;
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 }