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