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