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