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