2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
23 * ***** END GPL LICENSE BLOCK *****
26 /** \file blender/blenkernel/intern/armature.c
38 #include "MEM_guardedalloc.h"
41 #include "BLI_listbase.h"
42 #include "BLI_string.h"
43 #include "BLI_ghash.h"
45 #include "BLI_utildefines.h"
47 #include "DNA_anim_types.h"
48 #include "DNA_armature_types.h"
49 #include "DNA_constraint_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_lattice_types.h"
52 #include "DNA_listBase.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_object_types.h"
57 #include "BKE_animsys.h"
58 #include "BKE_armature.h"
59 #include "BKE_action.h"
61 #include "BKE_constraint.h"
62 #include "BKE_curve.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_deform.h"
65 #include "BKE_displist.h"
66 #include "BKE_global.h"
67 #include "BKE_idprop.h"
68 #include "BKE_library.h"
69 #include "BKE_library_query.h"
70 #include "BKE_library_remap.h"
71 #include "BKE_lattice.h"
73 #include "BKE_object.h"
74 #include "BKE_scene.h"
77 #include "BKE_sketch.h"
79 /* **************** Generic Functions, data level *************** */
81 bArmature *BKE_armature_add(Main *bmain, const char *name)
85 arm = BKE_libblock_alloc(bmain, ID_AR, name);
86 arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE;
87 arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
93 bArmature *BKE_armature_from_object(Object *ob)
95 if (ob->type == OB_ARMATURE)
96 return (bArmature *)ob->data;
100 int BKE_armature_bonelist_count(ListBase *lb)
103 for (Bone *bone = lb->first; bone; bone = bone->next) {
104 i += 1 + BKE_armature_bonelist_count(&bone->childbase);
110 void BKE_armature_bonelist_free(ListBase *lb)
114 for (bone = lb->first; bone; bone = bone->next) {
116 IDP_FreeProperty(bone->prop);
117 MEM_freeN(bone->prop);
119 BKE_armature_bonelist_free(&bone->childbase);
125 /** Free (or release) any data used by this armature (does not free the armature itself). */
126 void BKE_armature_free(bArmature *arm)
128 BKE_animdata_free(&arm->id, false);
130 BKE_armature_bonelist_free(&arm->bonebase);
132 /* free editmode data */
134 BLI_freelistN(arm->edbo);
136 MEM_freeN(arm->edbo);
142 freeSketch(arm->sketch);
147 void BKE_armature_make_local(Main *bmain, bArmature *arm, const bool lib_local)
149 BKE_id_make_local_generic(bmain, &arm->id, true, lib_local);
152 static void copy_bonechildren(Bone *newBone, Bone *oldBone, Bone *actBone, Bone **newActBone)
154 Bone *curBone, *newChildBone;
156 if (oldBone == actBone)
157 *newActBone = newBone;
160 newBone->prop = IDP_CopyProperty(oldBone->prop);
162 /* Copy this bone's list */
163 BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
165 /* For each child in the list, update it's children */
166 newChildBone = newBone->childbase.first;
167 for (curBone = oldBone->childbase.first; curBone; curBone = curBone->next) {
168 newChildBone->parent = newBone;
169 copy_bonechildren(newChildBone, curBone, actBone, newActBone);
170 newChildBone = newChildBone->next;
174 bArmature *BKE_armature_copy(Main *bmain, bArmature *arm)
177 Bone *oldBone, *newBone;
178 Bone *newActBone = NULL;
180 newArm = BKE_libblock_copy(bmain, &arm->id);
181 BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
183 /* Duplicate the childrens' lists */
184 newBone = newArm->bonebase.first;
185 for (oldBone = arm->bonebase.first; oldBone; oldBone = oldBone->next) {
186 newBone->parent = NULL;
187 copy_bonechildren(newBone, oldBone, arm->act_bone, &newActBone);
188 newBone = newBone->next;
191 newArm->act_bone = newActBone;
194 newArm->act_edbone = NULL;
195 newArm->sketch = NULL;
197 BKE_id_copy_ensure_local(bmain, &arm->id, &newArm->id);
202 static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name)
204 Bone *curBone, *rbone;
206 for (curBone = lb->first; curBone; curBone = curBone->next) {
207 if (STREQ(curBone->name, name))
210 rbone = get_named_bone_bonechildren(&curBone->childbase, name);
220 * Walk the list until the bone is found (slow!),
221 * use #BKE_armature_bone_from_name_map for multiple lookups.
223 Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name)
228 return get_named_bone_bonechildren(&arm->bonebase, name);
231 static void armature_bone_from_name_insert_recursive(GHash *bone_hash, ListBase *lb)
233 for (Bone *bone = lb->first; bone; bone = bone->next) {
234 BLI_ghash_insert(bone_hash, bone->name, bone);
235 armature_bone_from_name_insert_recursive(bone_hash, &bone->childbase);
240 * Create a (name -> bone) map.
242 * \note typically #bPose.chanhash us used via #BKE_pose_channel_find_name
243 * this is for the cases we can't use pose channels.
245 GHash *BKE_armature_bone_from_name_map(bArmature *arm)
247 const int bones_count = BKE_armature_bonelist_count(&arm->bonebase);
248 GHash *bone_hash = BLI_ghash_str_new_ex(__func__, bones_count);
249 armature_bone_from_name_insert_recursive(bone_hash, &arm->bonebase);
253 bool BKE_armature_bone_flag_test_recursive(const Bone *bone, int flag)
255 if (bone->flag & flag) {
258 else if (bone->parent) {
259 return BKE_armature_bone_flag_test_recursive(bone->parent, flag);
266 /* Finds the best possible extension to the name on a particular axis. (For renaming, check for
267 * unique names afterwards) strip_number: removes number extensions (TODO: not used)
268 * axis: the axis to name on
269 * head/tail: the head/tail co-ordinate of the bone on the specified axis */
270 int bone_autoside_name(char name[MAXBONENAME], int UNUSED(strip_number), short axis, float head, float tail)
273 char basename[MAXBONENAME] = "";
274 char extension[5] = "";
279 BLI_strncpy(basename, name, sizeof(basename));
281 /* Figure out extension to append:
282 * - The extension to append is based upon the axis that we are working on.
283 * - If head happens to be on 0, then we must consider the tail position as well to decide
284 * which side the bone is on
285 * -> If tail is 0, then it's bone is considered to be on axis, so no extension should be added
286 * -> Otherwise, extension is added from perspective of object based on which side tail goes to
287 * - If head is non-zero, extension is added from perspective of object based on side head is on
290 /* z-axis - vertical (top/bottom) */
291 if (IS_EQF(head, 0.0f)) {
293 strcpy(extension, "Bot");
295 strcpy(extension, "Top");
299 strcpy(extension, "Bot");
301 strcpy(extension, "Top");
304 else if (axis == 1) {
305 /* y-axis - depth (front/back) */
306 if (IS_EQF(head, 0.0f)) {
308 strcpy(extension, "Fr");
310 strcpy(extension, "Bk");
314 strcpy(extension, "Fr");
316 strcpy(extension, "Bk");
320 /* x-axis - horizontal (left/right) */
321 if (IS_EQF(head, 0.0f)) {
323 strcpy(extension, "R");
325 strcpy(extension, "L");
329 strcpy(extension, "R");
330 /* XXX Shouldn't this be simple else, as for z and y axes? */
332 strcpy(extension, "L");
336 /* Simple name truncation
337 * - truncate if there is an extension and it wouldn't be able to fit
338 * - otherwise, just append to end
343 while (changed) { /* remove extensions */
345 if (len > 2 && basename[len - 2] == '.') {
346 if (basename[len - 1] == 'L' || basename[len - 1] == 'R') { /* L R */
347 basename[len - 2] = '\0';
352 else if (len > 3 && basename[len - 3] == '.') {
353 if ((basename[len - 2] == 'F' && basename[len - 1] == 'r') || /* Fr */
354 (basename[len - 2] == 'B' && basename[len - 1] == 'k')) /* Bk */
356 basename[len - 3] = '\0';
361 else if (len > 4 && basename[len - 4] == '.') {
362 if ((basename[len - 3] == 'T' && basename[len - 2] == 'o' && basename[len - 1] == 'p') || /* Top */
363 (basename[len - 3] == 'B' && basename[len - 2] == 'o' && basename[len - 1] == 't')) /* Bot */
365 basename[len - 4] = '\0';
372 if ((MAXBONENAME - len) < strlen(extension) + 1) { /* add 1 for the '.' */
373 strncpy(name, basename, len - strlen(extension));
376 BLI_snprintf(name, MAXBONENAME, "%s.%s", basename, extension);
385 /* ************* B-Bone support ******************* */
387 /* data has MAX_BBONE_SUBDIV+1 interpolated points, will become desired amount with equal distances */
388 void equalize_bbone_bezier(float *data, int desired)
390 float *fp, totdist, ddist, dist, fac1, fac2;
391 float pdist[MAX_BBONE_SUBDIV + 1];
392 float temp[MAX_BBONE_SUBDIV + 1][4];
396 for (a = 0, fp = data; a < MAX_BBONE_SUBDIV; a++, fp += 4) {
397 copy_qt_qt(temp[a], fp);
398 pdist[a + 1] = pdist[a] + len_v3v3(fp, fp + 4);
401 copy_qt_qt(temp[a], fp);
404 /* go over distances and calculate new points */
405 ddist = totdist / ((float)desired);
407 for (a = 1, fp = data + 4; a < desired; a++, fp += 4) {
408 dist = ((float)a) * ddist;
410 /* we're looking for location (distance) 'dist' in the array */
411 while ((nr < MAX_BBONE_SUBDIV) && (dist >= pdist[nr]))
414 fac1 = pdist[nr] - pdist[nr - 1];
415 fac2 = pdist[nr] - dist;
419 fp[0] = fac1 * temp[nr - 1][0] + fac2 * temp[nr][0];
420 fp[1] = fac1 * temp[nr - 1][1] + fac2 * temp[nr][1];
421 fp[2] = fac1 * temp[nr - 1][2] + fac2 * temp[nr][2];
422 fp[3] = fac1 * temp[nr - 1][3] + fac2 * temp[nr][3];
424 /* set last point, needed for orientation calculus */
425 copy_qt_qt(fp, temp[MAX_BBONE_SUBDIV]);
428 /* returns pointer to static array, filled with desired amount of bone->segments elements */
429 /* this calculation is done within unit bone space */
430 void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BBONE_SUBDIV])
432 bPoseChannel *next, *prev;
433 Bone *bone = pchan->bone;
434 float h1[3], h2[3], scale[3], length, roll1 = 0.0f, roll2;
435 float mat3[3][3], imat[4][4], posemat[4][4], scalemat[4][4], iscalemat[4][4];
436 float data[MAX_BBONE_SUBDIV + 1][4], *fp;
438 bool do_scale = false;
440 length = bone->length;
443 /* check if we need to take non-uniform bone scaling into account */
444 mat4_to_size(scale, pchan->pose_mat);
446 if (fabsf(scale[0] - scale[1]) > 1e-6f || fabsf(scale[1] - scale[2]) > 1e-6f) {
447 size_to_mat4(scalemat, scale);
448 invert_m4_m4(iscalemat, scalemat);
455 /* get "next" and "prev" bones - these are used for handle calculations */
456 if (pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) {
457 /* use the provided bones as the next/prev - leave blank to eliminate this effect altogether */
458 prev = pchan->bbone_prev;
459 next = pchan->bbone_next;
462 /* evaluate next and prev bones */
463 if (bone->flag & BONE_CONNECTED)
464 prev = pchan->parent;
471 /* find the handle points, since this is inside bone space, the
472 * first point = (0, 0, 0)
473 * last point = (0, length, 0) */
475 invert_m4_m4(imat, pchan->bone->arm_mat);
478 copy_m4_m4(posemat, pchan->pose_mat);
479 normalize_m4(posemat);
480 invert_m4_m4(imat, posemat);
483 invert_m4_m4(imat, pchan->pose_mat);
486 float difmat[4][4], result[3][3], imat3[3][3];
488 /* transform previous point inside this bone space */
489 if ((pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) &&
490 (pchan->bboneflag & PCHAN_BBONE_CUSTOM_START_REL))
492 /* Use delta movement (from restpose), and apply this relative to the current bone's head */
494 /* in restpose, arm_head == pose_head */
495 h1[0] = h1[1] = h1[2] = 0.0f;
499 sub_v3_v3v3(delta, prev->pose_head, prev->bone->arm_head);
500 sub_v3_v3v3(h1, pchan->pose_head, delta);
504 /* Use bone head as absolute position */
506 copy_v3_v3(h1, prev->bone->arm_head);
508 copy_v3_v3(h1, prev->pose_head);
512 if (prev->bone->segments > 1) {
513 /* if previous bone is B-bone too, use average handle direction */
521 if (prev->bone->segments == 1) {
522 /* find the previous roll to interpolate */
524 mul_m4_m4m4(difmat, imat, prev->bone->arm_mat);
526 mul_m4_m4m4(difmat, imat, prev->pose_mat);
527 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
529 vec_roll_to_mat3(h1, 0.0f, mat3); /* the result of vec_roll without roll */
531 invert_m3_m3(imat3, mat3);
532 mul_m3_m3m3(mat3, result, imat3); /* the matrix transforming vec_roll to desired roll */
534 roll1 = atan2f(mat3[2][0], mat3[2][2]);
538 h1[0] = 0.0f; h1[1] = 1.0; h1[2] = 0.0f;
542 float difmat[4][4], result[3][3], imat3[3][3];
544 /* transform next point inside this bone space */
545 if ((pchan->bboneflag & PCHAN_BBONE_CUSTOM_HANDLES) &&
546 (pchan->bboneflag & PCHAN_BBONE_CUSTOM_END_REL))
548 /* Use delta movement (from restpose), and apply this relative to the current bone's tail */
550 /* in restpose, arm_tail == pose_tail */
551 h2[0] = h2[1] = h2[2] = 0.0f;
555 sub_v3_v3v3(delta, next->pose_tail, next->bone->arm_tail);
556 add_v3_v3v3(h2, pchan->pose_tail, delta);
560 /* Use bone tail as absolute position */
562 copy_v3_v3(h2, next->bone->arm_tail);
564 copy_v3_v3(h2, next->pose_tail);
568 /* if next bone is B-bone too, use average handle direction */
569 if (next->bone->segments > 1) {
577 /* find the next roll to interpolate as well */
579 mul_m4_m4m4(difmat, imat, next->bone->arm_mat);
581 mul_m4_m4m4(difmat, imat, next->pose_mat);
582 copy_m3_m4(result, difmat); /* the desired rotation at beginning of next bone */
584 vec_roll_to_mat3(h2, 0.0f, mat3); /* the result of vec_roll without roll */
586 invert_m3_m3(imat3, mat3);
587 mul_m3_m3m3(mat3, imat3, result); /* the matrix transforming vec_roll to desired roll */
589 roll2 = atan2f(mat3[2][0], mat3[2][2]);
593 h2[0] = 0.0f; h2[1] = 1.0f; h2[2] = 0.0f;
598 const float circle_factor = length * (cubic_tangent_factor_circle_v3(h1, h2) / 0.75f);
600 const float hlength1 = bone->ease1 * circle_factor;
601 const float hlength2 = bone->ease2 * circle_factor;
603 /* and only now negate h2 */
604 mul_v3_fl(h1, hlength1);
605 mul_v3_fl(h2, -hlength2);
608 /* Add effects from bbone properties over the top
609 * - These properties allow users to hand-animate the
610 * bone curve/shape, without having to resort to using
612 * - The "bone" level offsets are for defining the restpose
613 * shape of the bone (e.g. for curved eyebrows for example).
614 * -> In the viewport, it's needed to define what the rest pose
616 * -> For "rest == 0", we also still need to have it present
617 * so that we can "cancel out" this restpose when it comes
618 * time to deform some geometry, it won't cause double transforms.
619 * - The "pchan" level offsets are the ones that animators actually
623 /* add extra rolls */
624 roll1 += bone->roll1 + (!rest ? pchan->roll1 : 0.0f);
625 roll2 += bone->roll2 + (!rest ? pchan->roll2 : 0.0f);
627 if (bone->flag & BONE_ADD_PARENT_END_ROLL) {
630 roll1 += prev->bone->roll2;
633 roll1 += prev->roll2;
637 /* extra curve x / y */
638 /* NOTE: Scale correction factors here are to compensate for some random floating-point glitches
639 * when scaling up the bone or it's parent by a factor of approximately 8.15/6, which results
640 * in the bone length getting scaled up too (from 1 to 8), causing the curve to flatten out.
642 const float xscale_correction = (do_scale) ? scale[0] : 1.0f;
643 const float yscale_correction = (do_scale) ? scale[2] : 1.0f;
645 h1[0] += (bone->curveInX + (!rest ? pchan->curveInX : 0.0f)) * xscale_correction;
646 h1[2] += (bone->curveInY + (!rest ? pchan->curveInY : 0.0f)) * yscale_correction;
648 h2[0] += (bone->curveOutX + (!rest ? pchan->curveOutX : 0.0f)) * xscale_correction;
649 h2[2] += (bone->curveOutY + (!rest ? pchan->curveOutY : 0.0f)) * yscale_correction;
653 if (bone->segments > MAX_BBONE_SUBDIV)
654 bone->segments = MAX_BBONE_SUBDIV;
656 BKE_curve_forward_diff_bezier(0.0f, h1[0], h2[0], 0.0f, data[0], MAX_BBONE_SUBDIV, 4 * sizeof(float));
657 BKE_curve_forward_diff_bezier(0.0f, h1[1], length + h2[1], length, data[0] + 1, MAX_BBONE_SUBDIV, 4 * sizeof(float));
658 BKE_curve_forward_diff_bezier(0.0f, h1[2], h2[2], 0.0f, data[0] + 2, MAX_BBONE_SUBDIV, 4 * sizeof(float));
659 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));
661 equalize_bbone_bezier(data[0], bone->segments); /* note: does stride 4! */
663 /* make transformation matrices for the segments for drawing */
664 for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) {
665 sub_v3_v3v3(h1, fp + 4, fp);
666 vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */
668 copy_m4_m3(result_array[a].mat, mat3);
669 copy_v3_v3(result_array[a].mat[3], fp);
672 /* correct for scaling when this matrix is used in scaled space */
673 mul_m4_series(result_array[a].mat, iscalemat, result_array[a].mat, scalemat);
678 const int num_segments = bone->segments;
680 const float scaleIn = bone->scaleIn * (!rest ? pchan->scaleIn : 1.0f);
681 const float scaleFactorIn = 1.0f + (scaleIn - 1.0f) * ((float)(num_segments - a) / (float)num_segments);
683 const float scaleOut = bone->scaleOut * (!rest ? pchan->scaleOut : 1.0f);
684 const float scaleFactorOut = 1.0f + (scaleOut - 1.0f) * ((float)(a + 1) / (float)num_segments);
686 const float scalefac = scaleFactorIn * scaleFactorOut;
687 float bscalemat[4][4], bscale[3];
689 bscale[0] = scalefac;
691 bscale[2] = scalefac;
693 size_to_mat4(bscalemat, bscale);
695 /* Note: don't multiply by inverse scale mat here, as it causes problems with scaling shearing and breaking segment chains */
696 /*mul_m4_series(result_array[a].mat, ibscalemat, result_array[a].mat, bscalemat);*/
697 mul_m4_series(result_array[a].mat, result_array[a].mat, bscalemat);
703 /* ************ Armature Deform ******************* */
705 typedef struct bPoseChanDeform {
708 DualQuat *b_bone_dual_quats;
711 static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, const bool use_quaternion)
713 Bone *bone = pchan->bone;
714 Mat4 b_bone[MAX_BBONE_SUBDIV], b_bone_rest[MAX_BBONE_SUBDIV];
716 DualQuat *b_bone_dual_quats = NULL;
719 b_bone_spline_setup(pchan, 0, b_bone);
720 b_bone_spline_setup(pchan, 1, b_bone_rest);
722 /* allocate b_bone matrices and dual quats */
723 b_bone_mats = MEM_mallocN((1 + bone->segments) * sizeof(Mat4), "BBone defmats");
724 pdef_info->b_bone_mats = b_bone_mats;
726 if (use_quaternion) {
727 b_bone_dual_quats = MEM_mallocN((bone->segments) * sizeof(DualQuat), "BBone dqs");
728 pdef_info->b_bone_dual_quats = b_bone_dual_quats;
731 /* first matrix is the inverse arm_mat, to bring points in local bone space
732 * for finding out which segment it belongs to */
733 invert_m4_m4(b_bone_mats[0].mat, bone->arm_mat);
735 /* then we make the b_bone_mats:
736 * - first transform to local bone space
737 * - translate over the curve to the bbone mat space
738 * - transform with b_bone matrix
739 * - transform back into global space */
741 for (a = 0; a < bone->segments; a++) {
744 invert_m4_m4(tmat, b_bone_rest[a].mat);
745 mul_m4_series(b_bone_mats[a + 1].mat, pchan->chan_mat, bone->arm_mat, b_bone[a].mat, tmat, b_bone_mats[0].mat);
748 mat4_to_dquat(&b_bone_dual_quats[a], bone->arm_mat, b_bone_mats[a + 1].mat);
752 static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], DualQuat *dq, float defmat[3][3])
754 Mat4 *b_bone = pdef_info->b_bone_mats;
755 float (*mat)[4] = b_bone[0].mat;
759 /* need to transform co back to bonespace, only need y */
760 y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1];
762 /* now calculate which of the b_bones are deforming this */
763 segment = bone->length / ((float)bone->segments);
764 a = (int)(y / segment);
766 /* note; by clamping it extends deform at endpoints, goes best with
767 * straight joints in restpos. */
768 CLAMP(a, 0, bone->segments - 1);
771 copy_dq_dq(dq, &(pdef_info->b_bone_dual_quats)[a]);
774 mul_m4_v3(b_bone[a + 1].mat, co);
777 copy_m3_m4(defmat, b_bone[a + 1].mat);
782 /* using vec with dist to bone b1 - b2 */
783 float distfactor_to_bone(const float vec[3], const float b1[3], const float b2[3], float rad1, float rad2, float rdist)
788 float hsqr, a, l, rad;
790 sub_v3_v3v3(bdelta, b2, b1);
791 l = normalize_v3(bdelta);
793 sub_v3_v3v3(pdelta, vec, b1);
795 a = dot_v3v3(bdelta, pdelta);
796 hsqr = len_squared_v3(pdelta);
799 /* If we're past the end of the bone, do a spherical field attenuation thing */
800 dist_sq = len_squared_v3v3(b1, vec);
804 /* If we're past the end of the bone, do a spherical field attenuation thing */
805 dist_sq = len_squared_v3v3(b2, vec);
809 dist_sq = (hsqr - (a * a));
813 rad = rad * rad2 + (1.0f - rad) * rad1;
825 if (rdist == 0.0f || dist_sq >= l)
828 a = sqrtf(dist_sq) - rad;
829 return 1.0f - (a * a) / (rdist * rdist);
834 static void pchan_deform_mat_add(bPoseChannel *pchan, float weight, float bbonemat[3][3], float mat[3][3])
838 if (pchan->bone->segments > 1)
839 copy_m3_m3(wmat, bbonemat);
841 copy_m3_m4(wmat, pchan->chan_mat);
843 mul_m3_fl(wmat, weight);
844 add_m3_m3m3(mat, mat, wmat);
847 static float dist_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float vec[3], DualQuat *dq,
848 float mat[3][3], const float co[3])
850 Bone *bone = pchan->bone;
851 float fac, contrib = 0.0;
852 float cop[3], bbonemat[3][3];
860 fac = distfactor_to_bone(cop, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist);
865 if (contrib > 0.0f) {
867 if (bone->segments > 1)
868 /* applies on cop and bbonemat */
869 b_bone_deform(pdef_info, bone, cop, NULL, (mat) ? bbonemat : NULL);
871 mul_m4_v3(pchan->chan_mat, cop);
873 /* Make this a delta from the base position */
875 madd_v3_v3fl(vec, cop, fac);
878 pchan_deform_mat_add(pchan, fac, bbonemat, mat);
881 if (bone->segments > 1) {
882 b_bone_deform(pdef_info, bone, cop, &bbonedq, NULL);
883 add_weighted_dq_dq(dq, &bbonedq, fac);
886 add_weighted_dq_dq(dq, pdef_info->dual_quat, fac);
894 static void pchan_bone_deform(bPoseChannel *pchan, bPoseChanDeform *pdef_info, float weight, float vec[3], DualQuat *dq,
895 float mat[3][3], const float co[3], float *contrib)
897 float cop[3], bbonemat[3][3];
906 if (pchan->bone->segments > 1)
907 /* applies on cop and bbonemat */
908 b_bone_deform(pdef_info, pchan->bone, cop, NULL, (mat) ? bbonemat : NULL);
910 mul_m4_v3(pchan->chan_mat, cop);
912 vec[0] += (cop[0] - co[0]) * weight;
913 vec[1] += (cop[1] - co[1]) * weight;
914 vec[2] += (cop[2] - co[2]) * weight;
917 pchan_deform_mat_add(pchan, weight, bbonemat, mat);
920 if (pchan->bone->segments > 1) {
921 b_bone_deform(pdef_info, pchan->bone, cop, &bbonedq, NULL);
922 add_weighted_dq_dq(dq, &bbonedq, weight);
925 add_weighted_dq_dq(dq, pdef_info->dual_quat, weight);
928 (*contrib) += weight;
931 typedef struct ArmatureBBoneDefmatsData {
932 bPoseChanDeform *pdef_info_array;
935 } ArmatureBBoneDefmatsData;
937 static void armature_bbone_defmats_cb(void *userdata, Link *iter, int index)
939 ArmatureBBoneDefmatsData *data = userdata;
940 bPoseChannel *pchan = (bPoseChannel *)iter;
942 if (!(pchan->bone->flag & BONE_NO_DEFORM)) {
943 bPoseChanDeform *pdef_info = &data->pdef_info_array[index];
944 const bool use_quaternion = data->use_quaternion;
946 if (pchan->bone->segments > 1) {
947 pchan_b_bone_defmats(pchan, pdef_info, use_quaternion);
950 if (use_quaternion) {
951 pdef_info->dual_quat = &data->dualquats[index];
952 mat4_to_dquat(pdef_info->dual_quat, pchan->bone->arm_mat, pchan->chan_mat);
957 void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float (*vertexCos)[3],
958 float (*defMats)[3][3], int numVerts, int deformflag,
959 float (*prevCos)[3], const char *defgrp_name)
961 bPoseChanDeform *pdef_info_array;
962 bPoseChanDeform *pdef_info = NULL;
963 bArmature *arm = armOb->data;
964 bPoseChannel *pchan, **defnrToPC = NULL;
965 int *defnrToPCIndex = NULL;
966 MDeformVert *dverts = NULL;
968 DualQuat *dualquats = NULL;
969 float obinv[4][4], premat[4][4], postmat[4][4];
970 const bool use_envelope = (deformflag & ARM_DEF_ENVELOPE) != 0;
971 const bool use_quaternion = (deformflag & ARM_DEF_QUATERNION) != 0;
972 const bool invert_vgroup = (deformflag & ARM_DEF_INVERT_VGROUP) != 0;
973 int defbase_tot = 0; /* safety for vertexgroup index overflow */
974 int i, target_totvert = 0; /* safety for vertexgroup overflow */
975 bool use_dverts = false;
979 /* in editmode, or not an armature */
980 if (arm->edbo || (armOb->pose == NULL)) {
984 if ((armOb->pose->flag & POSE_RECALC) != 0) {
985 printf("ERROR! Trying to evaluate influence of armature '%s' which needs Pose recalc!", armOb->id.name);
989 invert_m4_m4(obinv, target->obmat);
990 copy_m4_m4(premat, target->obmat);
991 mul_m4_m4m4(postmat, obinv, armOb->obmat);
992 invert_m4_m4(premat, postmat);
994 /* bone defmats are already in the channels, chan_mat */
996 /* initialize B_bone matrices and dual quaternions */
997 totchan = BLI_listbase_count(&armOb->pose->chanbase);
999 if (use_quaternion) {
1000 dualquats = MEM_callocN(sizeof(DualQuat) * totchan, "dualquats");
1003 pdef_info_array = MEM_callocN(sizeof(bPoseChanDeform) * totchan, "bPoseChanDeform");
1005 ArmatureBBoneDefmatsData data = {
1006 .pdef_info_array = pdef_info_array, .dualquats = dualquats, .use_quaternion = use_quaternion
1008 BLI_task_parallel_listbase(&armOb->pose->chanbase, &data, armature_bbone_defmats_cb, totchan > 512);
1010 /* get the def_nr for the overall armature vertex group if present */
1011 armature_def_nr = defgroup_name_index(target, defgrp_name);
1013 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
1014 defbase_tot = BLI_listbase_count(&target->defbase);
1016 if (target->type == OB_MESH) {
1017 Mesh *me = target->data;
1020 target_totvert = me->totvert;
1023 Lattice *lt = target->data;
1026 target_totvert = lt->pntsu * lt->pntsv * lt->pntsw;
1030 /* get a vertex-deform-index to posechannel array */
1031 if (deformflag & ARM_DEF_VGROUP) {
1032 if (ELEM(target->type, OB_MESH, OB_LATTICE)) {
1033 /* if we have a DerivedMesh, only use dverts if it has them */
1035 use_dverts = (dm->getVertDataArray(dm, CD_MDEFORMVERT) != NULL);
1042 defnrToPC = MEM_callocN(sizeof(*defnrToPC) * defbase_tot, "defnrToBone");
1043 defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * defbase_tot, "defnrToIndex");
1044 /* TODO(sergey): Some considerations here:
1046 * - Make it more generic function, maybe even keep together with chanhash.
1047 * - Check whether keeping this consistent across frames gives speedup.
1048 * - Don't use hash for small armatures.
1050 GHash *idx_hash = BLI_ghash_ptr_new("pose channel index by name");
1051 int pchan_index = 0;
1052 for (pchan = armOb->pose->chanbase.first; pchan != NULL; pchan = pchan->next, ++pchan_index) {
1053 BLI_ghash_insert(idx_hash, pchan, SET_INT_IN_POINTER(pchan_index));
1055 for (i = 0, dg = target->defbase.first; dg; i++, dg = dg->next) {
1056 defnrToPC[i] = BKE_pose_channel_find_name(armOb->pose, dg->name);
1057 /* exclude non-deforming bones */
1059 if (defnrToPC[i]->bone->flag & BONE_NO_DEFORM) {
1060 defnrToPC[i] = NULL;
1063 defnrToPCIndex[i] = GET_INT_FROM_POINTER(BLI_ghash_lookup(idx_hash, defnrToPC[i]));
1067 BLI_ghash_free(idx_hash, NULL, NULL);
1072 for (i = 0; i < numVerts; i++) {
1074 DualQuat sumdq, *dq = NULL;
1076 float sumvec[3], summat[3][3];
1077 float *vec = NULL, (*smat)[3] = NULL;
1078 float contrib = 0.0f;
1079 float armature_weight = 1.0f; /* default to 1 if no overall def group */
1080 float prevco_weight = 1.0f; /* weight for optional cached vertexcos */
1082 if (use_quaternion) {
1083 memset(&sumdq, 0, sizeof(DualQuat));
1087 sumvec[0] = sumvec[1] = sumvec[2] = 0.0f;
1096 if (use_dverts || armature_def_nr != -1) {
1098 dvert = dm->getVertData(dm, i, CD_MDEFORMVERT);
1099 else if (dverts && i < target_totvert)
1107 if (armature_def_nr != -1 && dvert) {
1108 armature_weight = defvert_find_weight(dvert, armature_def_nr);
1111 armature_weight = 1.0f - armature_weight;
1113 /* hackish: the blending factor can be used for blending with prevCos too */
1115 prevco_weight = armature_weight;
1116 armature_weight = 1.0f;
1120 /* check if there's any point in calculating for this vert */
1121 if (armature_weight == 0.0f)
1124 /* get the coord we work on */
1125 co = prevCos ? prevCos[i] : vertexCos[i];
1127 /* Apply the object's matrix */
1128 mul_m4_v3(premat, co);
1130 if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */
1131 MDeformWeight *dw = dvert->dw;
1135 for (j = dvert->totweight; j != 0; j--, dw++) {
1136 const int index = dw->def_nr;
1137 if (index >= 0 && index < defbase_tot && (pchan = defnrToPC[index])) {
1138 float weight = dw->weight;
1139 Bone *bone = pchan->bone;
1140 pdef_info = pdef_info_array + defnrToPCIndex[index];
1144 if (bone && bone->flag & BONE_MULT_VG_ENV) {
1145 weight *= distfactor_to_bone(co, bone->arm_head, bone->arm_tail,
1146 bone->rad_head, bone->rad_tail, bone->dist);
1148 pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib);
1151 /* if there are vertexgroups but not groups with bones
1152 * (like for softbody groups) */
1153 if (deformed == 0 && use_envelope) {
1154 pdef_info = pdef_info_array;
1155 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1156 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1157 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1161 else if (use_envelope) {
1162 pdef_info = pdef_info_array;
1163 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1164 if (!(pchan->bone->flag & BONE_NO_DEFORM))
1165 contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co);
1169 /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */
1170 if (contrib > 0.0001f) {
1171 if (use_quaternion) {
1172 normalize_dq(dq, contrib);
1174 if (armature_weight != 1.0f) {
1175 copy_v3_v3(dco, co);
1176 mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq);
1178 mul_v3_fl(dco, armature_weight);
1182 mul_v3m3_dq(co, (defMats) ? summat : NULL, dq);
1187 mul_v3_fl(vec, armature_weight / contrib);
1188 add_v3_v3v3(co, vec, co);
1192 float pre[3][3], post[3][3], tmpmat[3][3];
1194 copy_m3_m4(pre, premat);
1195 copy_m3_m4(post, postmat);
1196 copy_m3_m3(tmpmat, defMats[i]);
1198 if (!use_quaternion) /* quaternion already is scale corrected */
1199 mul_m3_fl(smat, armature_weight / contrib);
1201 mul_m3_series(defMats[i], post, smat, pre, tmpmat);
1205 /* always, check above code */
1206 mul_m4_v3(postmat, co);
1208 /* interpolate with previous modifier position using weight group */
1210 float mw = 1.0f - prevco_weight;
1211 vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0];
1212 vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1];
1213 vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2];
1218 MEM_freeN(dualquats);
1220 MEM_freeN(defnrToPC);
1222 MEM_freeN(defnrToPCIndex);
1224 /* free B_bone matrices */
1225 pdef_info = pdef_info_array;
1226 for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) {
1227 if (pdef_info->b_bone_mats)
1228 MEM_freeN(pdef_info->b_bone_mats);
1229 if (pdef_info->b_bone_dual_quats)
1230 MEM_freeN(pdef_info->b_bone_dual_quats);
1233 MEM_freeN(pdef_info_array);
1236 /* ************ END Armature Deform ******************* */
1238 void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[4][4], int UNUSED(root),
1241 copy_m4_m4(M_accumulatedMatrix, bone->arm_mat);
1244 /* **************** Space to Space API ****************** */
1246 /* Convert World-Space Matrix to Pose-Space Matrix */
1247 void BKE_armature_mat_world_to_pose(Object *ob, float inmat[4][4], float outmat[4][4])
1251 /* prevent crashes */
1255 /* get inverse of (armature) object's matrix */
1256 invert_m4_m4(obmat, ob->obmat);
1258 /* multiply given matrix by object's-inverse to find pose-space matrix */
1259 mul_m4_m4m4(outmat, inmat, obmat);
1262 /* Convert World-Space Location to Pose-Space Location
1263 * NOTE: this cannot be used to convert to pose-space location of the supplied
1264 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1265 void BKE_armature_loc_world_to_pose(Object *ob, const float inloc[3], float outloc[3])
1267 float xLocMat[4][4];
1268 float nLocMat[4][4];
1270 /* build matrix for location */
1272 copy_v3_v3(xLocMat[3], inloc);
1274 /* get bone-space cursor matrix and extract location */
1275 BKE_armature_mat_world_to_pose(ob, xLocMat, nLocMat);
1276 copy_v3_v3(outloc, nLocMat[3]);
1279 /* Simple helper, computes the offset bone matrix.
1280 * offs_bone = yoffs(b-1) + root(b) + bonemat(b).
1281 * Not exported, as it is only used in this file currently... */
1282 static void get_offset_bone_mat(Bone *bone, float offs_bone[4][4])
1284 BLI_assert(bone->parent != NULL);
1286 /* Bone transform itself. */
1287 copy_m4_m3(offs_bone, bone->bone_mat);
1289 /* The bone's root offset (is in the parent's coordinate system). */
1290 copy_v3_v3(offs_bone[3], bone->head);
1292 /* Get the length translation of parent (length along y axis). */
1293 offs_bone[3][1] += bone->parent->length;
1296 /* Construct the matrices (rot/scale and loc) to apply the PoseChannels into the armature (object) space.
1297 * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the
1298 * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1301 * This allows to get the transformations of a bone in its object space, *before* constraints (and IK)
1302 * get applied (used by pose evaluation code).
1303 * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale
1304 * in object space (used by interactive transform, and snapping code).
1306 * Note that, with the HINGE/NO_SCALE/NO_LOCAL_LOCATION options, the location matrix
1307 * will differ from the rotation/scale matrix...
1309 * NOTE: This cannot be used to convert to pose-space transforms of the supplied
1310 * pose-channel into its local space (i.e. 'visual'-keyframing).
1311 * (note: I don't understand that, so I keep it :p --mont29).
1313 void BKE_pchan_to_pose_mat(bPoseChannel *pchan, float rotscale_mat[4][4], float loc_mat[4][4])
1315 Bone *bone, *parbone;
1316 bPoseChannel *parchan;
1318 /* set up variables for quicker access below */
1320 parbone = bone->parent;
1321 parchan = pchan->parent;
1324 float offs_bone[4][4];
1325 /* yoffs(b-1) + root(b) + bonemat(b). */
1326 get_offset_bone_mat(bone, offs_bone);
1328 /* Compose the rotscale matrix for this bone. */
1329 if ((bone->flag & BONE_HINGE) && (bone->flag & BONE_NO_SCALE)) {
1330 /* Parent rest rotation and scale. */
1331 mul_m4_m4m4(rotscale_mat, parbone->arm_mat, offs_bone);
1333 else if (bone->flag & BONE_HINGE) {
1334 /* Parent rest rotation and pose scale. */
1335 float tmat[4][4], tscale[3];
1337 /* Extract the scale of the parent pose matrix. */
1338 mat4_to_size(tscale, parchan->pose_mat);
1339 size_to_mat4(tmat, tscale);
1341 /* Applies the parent pose scale to the rest matrix. */
1342 mul_m4_m4m4(tmat, tmat, parbone->arm_mat);
1344 mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1346 else if (bone->flag & BONE_NO_SCALE) {
1347 /* Parent pose rotation and rest scale (i.e. no scaling). */
1349 copy_m4_m4(tmat, parchan->pose_mat);
1351 mul_m4_m4m4(rotscale_mat, tmat, offs_bone);
1354 mul_m4_m4m4(rotscale_mat, parchan->pose_mat, offs_bone);
1356 /* Compose the loc matrix for this bone. */
1357 /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */
1359 /* In this case, use the object's space *orientation*. */
1360 if (bone->flag & BONE_NO_LOCAL_LOCATION) {
1361 /* XXX I'm sure that code can be simplified! */
1362 float bone_loc[4][4], bone_rotscale[3][3], tmat4[4][4], tmat3[3][3];
1367 mul_v3_m4v3(bone_loc[3], parchan->pose_mat, offs_bone[3]);
1369 unit_m3(bone_rotscale);
1370 copy_m3_m4(tmat3, parchan->pose_mat);
1371 mul_m3_m3m3(bone_rotscale, tmat3, bone_rotscale);
1373 copy_m4_m3(tmat4, bone_rotscale);
1374 mul_m4_m4m4(loc_mat, bone_loc, tmat4);
1376 /* Those flags do not affect position, use plain parent transform space! */
1377 else if (bone->flag & (BONE_HINGE | BONE_NO_SCALE)) {
1378 mul_m4_m4m4(loc_mat, parchan->pose_mat, offs_bone);
1380 /* Else (i.e. default, usual case), just use the same matrix for rotation/scaling, and location. */
1382 copy_m4_m4(loc_mat, rotscale_mat);
1386 /* Rotation/scaling. */
1387 copy_m4_m4(rotscale_mat, pchan->bone->arm_mat);
1389 if (pchan->bone->flag & BONE_NO_LOCAL_LOCATION) {
1390 /* Translation of arm_mat, without the rotation. */
1392 copy_v3_v3(loc_mat[3], pchan->bone->arm_mat[3]);
1395 copy_m4_m4(loc_mat, rotscale_mat);
1399 /* Convert Pose-Space Matrix to Bone-Space Matrix.
1400 * NOTE: this cannot be used to convert to pose-space transforms of the supplied
1401 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1402 void BKE_armature_mat_pose_to_bone(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1404 float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1406 /* Security, this allows to call with inmat == outmat! */
1407 copy_m4_m4(inmat_, inmat);
1409 BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1410 invert_m4(rotscale_mat);
1413 mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1414 mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1417 /* Convert Bone-Space Matrix to Pose-Space Matrix. */
1418 void BKE_armature_mat_bone_to_pose(bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1420 float rotscale_mat[4][4], loc_mat[4][4], inmat_[4][4];
1422 /* Security, this allows to call with inmat == outmat! */
1423 copy_m4_m4(inmat_, inmat);
1425 BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
1427 mul_m4_m4m4(outmat, rotscale_mat, inmat_);
1428 mul_v3_m4v3(outmat[3], loc_mat, inmat_[3]);
1431 /* Convert Pose-Space Location to Bone-Space Location
1432 * NOTE: this cannot be used to convert to pose-space location of the supplied
1433 * pose-channel into its local space (i.e. 'visual'-keyframing) */
1434 void BKE_armature_loc_pose_to_bone(bPoseChannel *pchan, const float inloc[3], float outloc[3])
1436 float xLocMat[4][4];
1437 float nLocMat[4][4];
1439 /* build matrix for location */
1441 copy_v3_v3(xLocMat[3], inloc);
1443 /* get bone-space cursor matrix and extract location */
1444 BKE_armature_mat_pose_to_bone(pchan, xLocMat, nLocMat);
1445 copy_v3_v3(outloc, nLocMat[3]);
1448 void BKE_armature_mat_pose_to_bone_ex(Object *ob, bPoseChannel *pchan, float inmat[4][4], float outmat[4][4])
1450 bPoseChannel work_pchan = *pchan;
1452 /* recalculate pose matrix with only parent transformations,
1453 * bone loc/sca/rot is ignored, scene and frame are not used. */
1454 BKE_pose_where_is_bone(NULL, ob, &work_pchan, 0.0f, false);
1456 /* find the matrix, need to remove the bone transforms first so this is
1457 * calculated as a matrix to set rather then a difference ontop of whats
1460 BKE_pchan_apply_mat4(&work_pchan, outmat, false);
1462 BKE_armature_mat_pose_to_bone(&work_pchan, inmat, outmat);
1465 /* same as BKE_object_mat3_to_rot() */
1466 void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, float mat[3][3], bool use_compat)
1468 BLI_ASSERT_UNIT_M3(mat);
1470 switch (pchan->rotmode) {
1472 mat3_normalized_to_quat(pchan->quat, mat);
1474 case ROT_MODE_AXISANGLE:
1475 mat3_normalized_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat);
1477 default: /* euler */
1479 mat3_normalized_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat);
1481 mat3_normalized_to_eulO(pchan->eul, pchan->rotmode, mat);
1486 /* Apply a 4x4 matrix to the pose bone,
1487 * similar to BKE_object_apply_mat4() */
1488 void BKE_pchan_apply_mat4(bPoseChannel *pchan, float mat[4][4], bool use_compat)
1491 mat4_to_loc_rot_size(pchan->loc, rot, pchan->size, mat);
1492 BKE_pchan_mat3_to_rot(pchan, rot, use_compat);
1495 /* Remove rest-position effects from pose-transform for obtaining
1496 * 'visual' transformation of pose-channel.
1497 * (used by the Visual-Keyframing stuff) */
1498 void BKE_armature_mat_pose_to_delta(float delta_mat[4][4], float pose_mat[4][4], float arm_mat[4][4])
1502 invert_m4_m4(imat, arm_mat);
1503 mul_m4_m4m4(delta_mat, imat, pose_mat);
1506 /* **************** Rotation Mode Conversions ****************************** */
1507 /* Used for Objects and Pose Channels, since both can have multiple rotation representations */
1509 /* Called from RNA when rotation mode changes
1510 * - the result should be that the rotations given in the provided pointers have had conversions
1511 * applied (as appropriate), such that the rotation of the element hasn't 'visually' changed */
1512 void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float *angle, short oldMode, short newMode)
1514 /* check if any change - if so, need to convert data */
1515 if (newMode > 0) { /* to euler */
1516 if (oldMode == ROT_MODE_AXISANGLE) {
1517 /* axis-angle to euler */
1518 axis_angle_to_eulO(eul, newMode, axis, *angle);
1520 else if (oldMode == ROT_MODE_QUAT) {
1523 quat_to_eulO(eul, newMode, quat);
1525 /* else { no conversion needed } */
1527 else if (newMode == ROT_MODE_QUAT) { /* to quat */
1528 if (oldMode == ROT_MODE_AXISANGLE) {
1529 /* axis angle to quat */
1530 axis_angle_to_quat(quat, axis, *angle);
1532 else if (oldMode > 0) {
1534 eulO_to_quat(quat, eul, oldMode);
1536 /* else { no conversion needed } */
1538 else if (newMode == ROT_MODE_AXISANGLE) { /* to axis-angle */
1540 /* euler to axis angle */
1541 eulO_to_axis_angle(axis, angle, eul, oldMode);
1543 else if (oldMode == ROT_MODE_QUAT) {
1544 /* quat to axis angle */
1546 quat_to_axis_angle(axis, angle, quat);
1549 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1550 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
1551 /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1557 /* **************** The new & simple (but OK!) armature evaluation ********* */
1559 /* ****************** And how it works! ****************************************
1561 * This is the bone transformation trick; they're hierarchical so each bone(b)
1562 * is in the coord system of bone(b-1):
1564 * arm_mat(b)= arm_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)
1566 * -> yoffs is just the y axis translation in parent's coord system
1567 * -> d_root is the translation of the bone root, also in parent's coord system
1569 * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b)
1571 * we then - in init deform - store the deform in chan_mat, such that:
1573 * pose_mat(b)= arm_mat(b) * chan_mat(b)
1575 * *************************************************************************** */
1577 /* Computes vector and roll based on a rotation.
1578 * "mat" must contain only a rotation, and no scaling. */
1579 void mat3_to_vec_roll(float mat[3][3], float r_vec[3], float *r_roll)
1582 copy_v3_v3(r_vec, mat[1]);
1586 float vecmat[3][3], vecmatinv[3][3], rollmat[3][3];
1588 vec_roll_to_mat3(mat[1], 0.0f, vecmat);
1589 invert_m3_m3(vecmatinv, vecmat);
1590 mul_m3_m3m3(rollmat, vecmatinv, mat);
1592 *r_roll = atan2f(rollmat[2][0], rollmat[2][2]);
1596 /* Calculates the rest matrix of a bone based on its vector and a roll around that vector. */
1597 /* Given v = (v.x, v.y, v.z) our (normalized) bone vector, we want the rotation matrix M
1598 * from the Y axis (so that M * (0, 1, 0) = v).
1599 * -> The rotation axis a lays on XZ plane, and it is orthonormal to v, hence to the projection of v onto XZ plane.
1600 * -> a = (v.z, 0, -v.x)
1601 * We know a is eigenvector of M (so M * a = a).
1602 * Finally, we have w, such that M * w = (0, 1, 0) (i.e. the vector that will be aligned with Y axis once transformed).
1603 * We know w is symmetric to v by the Y axis.
1604 * -> w = (-v.x, v.y, -v.z)
1606 * Solving this, we get (x, y and z being the components of v):
1607 * ┌ (x^2 * y + z^2) / (x^2 + z^2), x, x * z * (y - 1) / (x^2 + z^2) ┐
1608 * M = │ x * (y^2 - 1) / (x^2 + z^2), y, z * (y^2 - 1) / (x^2 + z^2) │
1609 * └ x * z * (y - 1) / (x^2 + z^2), z, (x^2 + z^2 * y) / (x^2 + z^2) ┘
1611 * This is stable as long as v (the bone) is not too much aligned with +/-Y (i.e. x and z components
1612 * are not too close to 0).
1614 * Since v is normalized, we have x^2 + y^2 + z^2 = 1, hence x^2 + z^2 = 1 - y^2 = (1 - y)(1 + y).
1615 * This allows to simplifies M like this:
1616 * ┌ 1 - x^2 / (1 + y), x, -x * z / (1 + y) ┐
1618 * └ -x * z / (1 + y), z, 1 - z^2 / (1 + y) ┘
1620 * Written this way, we see the case v = +Y is no more a singularity. The only one remaining is the bone being
1623 * Let's handle the asymptotic behavior when bone vector is reaching the limit of y = -1. Each of the four corner
1624 * elements can vary from -1 to 1, depending on the axis a chosen for doing the rotation. And the "rotation" here
1625 * is in fact established by mirroring XZ plane by that given axis, then inversing the Y-axis.
1626 * For sufficiently small x and z, and with y approaching -1, all elements but the four corner ones of M
1627 * will degenerate. So let's now focus on these corner elements.
1629 * We rewrite M so that it only contains its four corner elements, and combine the 1 / (1 + y) factor:
1630 * ┌ 1 + y - x^2, -x * z ┐
1631 * M* = 1 / (1 + y) * │ │
1632 * └ -x * z, 1 + y - z^2 ┘
1634 * When y is close to -1, computing 1 / (1 + y) will cause severe numerical instability, so we ignore it and
1635 * normalize M instead. We know y^2 = 1 - (x^2 + z^2), and y < 0, hence y = -sqrt(1 - (x^2 + z^2)).
1636 * Since x and z are both close to 0, we apply the binomial expansion to the first order:
1637 * y = -sqrt(1 - (x^2 + z^2)) = -1 + (x^2 + z^2) / 2. Which gives:
1638 * ┌ z^2 - x^2, -2 * x * z ┐
1639 * M* = 1 / (x^2 + z^2) * │ │
1640 * └ -2 * x * z, x^2 - z^2 ┘
1642 void vec_roll_to_mat3_normalized(const float nor[3], const float roll, float mat[3][3])
1644 #define THETA_THRESHOLD_NEGY 1.0e-9f
1645 #define THETA_THRESHOLD_NEGY_CLOSE 1.0e-5f
1648 float rMatrix[3][3], bMatrix[3][3];
1650 BLI_ASSERT_UNIT_V3(nor);
1652 theta = 1.0f + nor[1];
1654 /* With old algo, 1.0e-13f caused T23954 and T31333, 1.0e-6f caused T27675 and T30438,
1655 * so using 1.0e-9f as best compromise.
1657 * New algo is supposed much more precise, since less complex computations are performed,
1658 * but it uses two different threshold values...
1660 * Note: When theta is close to zero, we have to check we do have non-null X/Z components as well
1661 * (due to float precision errors, we can have nor = (0.0, 0.99999994, 0.0)...).
1663 if (theta > THETA_THRESHOLD_NEGY_CLOSE || ((nor[0] || nor[2]) && theta > THETA_THRESHOLD_NEGY)) {
1665 * We got these values for free... so be happy with it... ;)
1667 bMatrix[0][1] = -nor[0];
1668 bMatrix[1][0] = nor[0];
1669 bMatrix[1][1] = nor[1];
1670 bMatrix[1][2] = nor[2];
1671 bMatrix[2][1] = -nor[2];
1672 if (theta > THETA_THRESHOLD_NEGY_CLOSE) {
1673 /* If nor is far enough from -Y, apply the general case. */
1674 bMatrix[0][0] = 1 - nor[0] * nor[0] / theta;
1675 bMatrix[2][2] = 1 - nor[2] * nor[2] / theta;
1676 bMatrix[2][0] = bMatrix[0][2] = -nor[0] * nor[2] / theta;
1679 /* If nor is too close to -Y, apply the special case. */
1680 theta = nor[0] * nor[0] + nor[2] * nor[2];
1681 bMatrix[0][0] = (nor[0] + nor[2]) * (nor[0] - nor[2]) / -theta;
1682 bMatrix[2][2] = -bMatrix[0][0];
1683 bMatrix[2][0] = bMatrix[0][2] = 2.0f * nor[0] * nor[2] / theta;
1687 /* If nor is -Y, simple symmetry by Z axis. */
1689 bMatrix[0][0] = bMatrix[1][1] = -1.0;
1692 /* Make Roll matrix */
1693 axis_angle_normalized_to_mat3(rMatrix, nor, roll);
1695 /* Combine and output result */
1696 mul_m3_m3m3(mat, rMatrix, bMatrix);
1698 #undef THETA_THRESHOLD_NEGY
1699 #undef THETA_THRESHOLD_NEGY_CLOSE
1702 void vec_roll_to_mat3(const float vec[3], const float roll, float mat[3][3])
1706 normalize_v3_v3(nor, vec);
1707 vec_roll_to_mat3_normalized(nor, roll, mat);
1710 /* recursive part, calculates restposition of entire tree of children */
1711 /* used by exiting editmode too */
1712 void BKE_armature_where_is_bone(Bone *bone, Bone *prevbone, const bool use_recursion)
1717 sub_v3_v3v3(vec, bone->tail, bone->head);
1718 bone->length = len_v3(vec);
1719 vec_roll_to_mat3(vec, bone->roll, bone->bone_mat);
1721 /* this is called on old file reading too... */
1722 if (bone->xwidth == 0.0f) {
1723 bone->xwidth = 0.1f;
1724 bone->zwidth = 0.1f;
1729 float offs_bone[4][4];
1730 /* yoffs(b-1) + root(b) + bonemat(b) */
1731 get_offset_bone_mat(bone, offs_bone);
1733 /* Compose the matrix for this bone */
1734 mul_m4_m4m4(bone->arm_mat, prevbone->arm_mat, offs_bone);
1737 copy_m4_m3(bone->arm_mat, bone->bone_mat);
1738 copy_v3_v3(bone->arm_mat[3], bone->head);
1741 /* and the kiddies */
1742 if (use_recursion) {
1744 for (bone = bone->childbase.first; bone; bone = bone->next) {
1745 BKE_armature_where_is_bone(bone, prevbone, use_recursion);
1750 /* updates vectors and matrices on rest-position level, only needed
1751 * after editing armature itself, now only on reading file */
1752 void BKE_armature_where_is(bArmature *arm)
1756 /* hierarchical from root to children */
1757 for (bone = arm->bonebase.first; bone; bone = bone->next) {
1758 BKE_armature_where_is_bone(bone, NULL, true);
1762 /* if bone layer is protected, copy the data from from->pose
1763 * when used with linked libraries this copies from the linked pose into the local pose */
1764 static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected)
1766 bPose *pose = ob->pose, *frompose = from->pose;
1767 bPoseChannel *pchan, *pchanp;
1771 if (frompose == NULL)
1774 /* in some cases when rigs change, we cant synchronize
1775 * to avoid crashing check for possible errors here */
1776 for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1777 if (pchan->bone->layer & layer_protected) {
1778 if (BKE_pose_channel_find_name(frompose, pchan->name) == NULL) {
1779 printf("failed to sync proxy armature because '%s' is missing pose channel '%s'\n",
1780 from->id.name, pchan->name);
1789 /* clear all transformation values from library */
1790 BKE_pose_rest(frompose);
1792 /* copy over all of the proxy's bone groups */
1794 * - implement 'local' bone groups as for constraints
1795 * Note: this isn't trivial, as bones reference groups by index not by pointer,
1796 * so syncing things correctly needs careful attention */
1797 BLI_freelistN(&pose->agroups);
1798 BLI_duplicatelist(&pose->agroups, &frompose->agroups);
1799 pose->active_group = frompose->active_group;
1801 for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1802 pchanp = BKE_pose_channel_find_name(frompose, pchan->name);
1804 if (UNLIKELY(pchanp == NULL)) {
1805 /* happens for proxies that become invalid because of a missing link
1806 * for regular cases it shouldn't happen at all */
1808 else if (pchan->bone->layer & layer_protected) {
1809 ListBase proxylocal_constraints = {NULL, NULL};
1810 bPoseChannel pchanw;
1812 /* copy posechannel to temp, but restore important pointers */
1814 pchanw.bone = pchan->bone;
1815 pchanw.prev = pchan->prev;
1816 pchanw.next = pchan->next;
1817 pchanw.parent = pchan->parent;
1818 pchanw.child = pchan->child;
1819 pchanw.custom_tx = pchan->custom_tx;
1821 pchanw.mpath = pchan->mpath;
1822 pchan->mpath = NULL;
1824 /* this is freed so copy a copy, else undo crashes */
1826 pchanw.prop = IDP_CopyProperty(pchanw.prop);
1828 /* use the values from the existing props */
1830 IDP_SyncGroupValues(pchanw.prop, pchan->prop);
1834 /* constraints - proxy constraints are flushed... local ones are added after
1835 * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints
1836 * 2. copy proxy-pchan's constraints on-to new
1837 * 3. add extracted local constraints back on top
1839 * Note for BKE_constraints_copy: when copying constraints, disable 'do_extern' otherwise
1840 * we get the libs direct linked in this blend.
1842 BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints);
1843 BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false);
1844 BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints);
1846 /* constraints - set target ob pointer to own object */
1847 for (con = pchanw.constraints.first; con; con = con->next) {
1848 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1849 ListBase targets = {NULL, NULL};
1850 bConstraintTarget *ct;
1852 if (cti && cti->get_constraint_targets) {
1853 cti->get_constraint_targets(con, &targets);
1855 for (ct = targets.first; ct; ct = ct->next) {
1856 if (ct->tar == from)
1860 if (cti->flush_constraint_targets)
1861 cti->flush_constraint_targets(con, &targets, 0);
1865 /* free stuff from current channel */
1866 BKE_pose_channel_free(pchan);
1868 /* copy data in temp back over to the cleaned-out (but still allocated) original channel */
1870 if (pchan->custom) {
1871 id_us_plus(&pchan->custom->id);
1875 /* always copy custom shape */
1876 pchan->custom = pchanp->custom;
1877 if (pchan->custom) {
1878 id_us_plus(&pchan->custom->id);
1880 if (pchanp->custom_tx)
1881 pchan->custom_tx = BKE_pose_channel_find_name(pose, pchanp->custom_tx->name);
1883 /* ID-Property Syncing */
1885 IDProperty *prop_orig = pchan->prop;
1887 pchan->prop = IDP_CopyProperty(pchanp->prop);
1889 /* copy existing values across when types match */
1890 IDP_SyncGroupValues(pchan->prop, prop_orig);
1897 IDP_FreeProperty(prop_orig);
1898 MEM_freeN(prop_orig);
1905 static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int counter)
1907 bPoseChannel *pchan = BKE_pose_channel_verify(pose, bone->name); /* verify checks and/or adds */
1910 pchan->parent = parchan;
1914 for (bone = bone->childbase.first; bone; bone = bone->next) {
1915 counter = rebuild_pose_bone(pose, bone, pchan, counter);
1916 /* for quick detecting of next bone in chain, only b-bone uses it now */
1917 if (bone->flag & BONE_CONNECTED)
1918 pchan->child = BKE_pose_channel_find_name(pose, bone->name);
1925 * Clear pointers of object's pose (needed in remap case, since we cannot always wait for a complete pose rebuild).
1927 void BKE_pose_clear_pointers(bPose *pose)
1929 for (bPoseChannel *pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
1931 pchan->child = NULL;
1935 /* only after leave editmode, duplicating, validating older files, library syncing */
1936 /* NOTE: pose->flag is set for it */
1937 void BKE_pose_rebuild(Object *ob, bArmature *arm)
1941 bPoseChannel *pchan, *next;
1944 /* only done here */
1945 if (ob->pose == NULL) {
1946 /* create new pose */
1947 ob->pose = MEM_callocN(sizeof(bPose), "new pose");
1949 /* set default settings for animviz */
1950 animviz_settings_init(&ob->pose->avs);
1955 BKE_pose_clear_pointers(pose);
1957 /* first step, check if all channels are there */
1958 for (bone = arm->bonebase.first; bone; bone = bone->next) {
1959 counter = rebuild_pose_bone(pose, bone, NULL, counter);
1962 /* and a check for garbage */
1963 for (pchan = pose->chanbase.first; pchan; pchan = next) {
1965 if (pchan->bone == NULL) {
1966 BKE_pose_channel_free(pchan);
1967 BKE_pose_channels_hash_free(pose);
1968 BLI_freelinkN(&pose->chanbase, pchan);
1971 /* printf("rebuild pose %s, %d bones\n", ob->id.name, counter); */
1973 /* synchronize protected layers with proxy */
1975 BKE_object_copy_proxy_drivers(ob, ob->proxy);
1976 pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected);
1979 BKE_pose_update_constraint_flags(ob->pose); /* for IK detection for example */
1981 ob->pose->flag &= ~POSE_RECALC;
1982 ob->pose->flag |= POSE_WAS_REBUILT;
1984 BKE_pose_channels_hash_make(ob->pose);
1987 /* ********************** THE POSE SOLVER ******************* */
1989 /* loc/rot/size to given mat4 */
1990 void BKE_pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4])
1996 /* get scaling matrix */
1997 size_to_mat3(smat, pchan->size);
1999 /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
2000 if (pchan->rotmode > 0) {
2001 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
2002 eulO_to_mat3(rmat, pchan->eul, pchan->rotmode);
2004 else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
2005 /* axis-angle - not really that great for 3D-changing orientations */
2006 axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle);
2009 /* quats are normalized before use to eliminate scaling issues */
2012 /* NOTE: we now don't normalize the stored values anymore, since this was kindof evil in some cases
2013 * but if this proves to be too problematic, switch back to the old system of operating directly on
2016 normalize_qt_qt(quat, pchan->quat);
2017 quat_to_mat3(rmat, quat);
2020 /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */
2021 mul_m3_m3m3(tmat, rmat, smat);
2022 copy_m4_m3(chan_mat, tmat);
2024 /* prevent action channels breaking chains */
2025 /* need to check for bone here, CONSTRAINT_TYPE_ACTION uses this call */
2026 if ((pchan->bone == NULL) || !(pchan->bone->flag & BONE_CONNECTED)) {
2027 copy_v3_v3(chan_mat[3], pchan->loc);
2031 /* loc/rot/size to mat4 */
2032 /* used in constraint.c too */
2033 void BKE_pchan_calc_mat(bPoseChannel *pchan)
2035 /* this is just a wrapper around the copy of this function which calculates the matrix
2036 * and stores the result in any given channel
2038 BKE_pchan_to_mat4(pchan, pchan->chan_mat);
2041 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2043 /* NLA strip modifiers */
2044 static void do_strip_modifiers(Scene *scene, Object *armob, Bone *bone, bPoseChannel *pchan)
2046 bActionModifier *amod;
2047 bActionStrip *strip, *strip2;
2048 float scene_cfra = BKE_scene_frame_get(scene);
2051 for (strip = armob->nlastrips.first; strip; strip = strip->next) {
2054 if (scene_cfra >= strip->start && scene_cfra <= strip->end)
2057 if ((scene_cfra > strip->end) && (strip->flag & ACTSTRIP_HOLDLASTFRAME)) {
2060 /* if there are any other strips active, ignore modifiers for this strip -
2061 * 'hold' option should only hold action modifiers if there are
2062 * no other active strips */
2063 for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2064 if (strip2 == strip) continue;
2066 if (scene_cfra >= strip2->start && scene_cfra <= strip2->end) {
2067 if (!(strip2->flag & ACTSTRIP_MUTE))
2072 /* if there are any later, activated, strips with 'hold' set, they take precedence,
2073 * so ignore modifiers for this strip */
2074 for (strip2 = strip->next; strip2; strip2 = strip2->next) {
2075 if (scene_cfra < strip2->start) continue;
2076 if ((strip2->flag & ACTSTRIP_HOLDLASTFRAME) && !(strip2->flag & ACTSTRIP_MUTE)) {
2083 /* temporal solution to prevent 2 strips accumulating */
2084 if (scene_cfra == strip->end && strip->next && strip->next->start == scene_cfra)
2087 for (amod = strip->modifiers.first; amod; amod = amod->next) {
2088 switch (amod->type) {
2089 case ACTSTRIP_MOD_DEFORM:
2091 /* validate first */
2092 if (amod->ob && amod->ob->type == OB_CURVE && amod->channel[0]) {
2094 if (STREQ(pchan->name, amod->channel)) {
2095 float mat4[4][4], mat3[3][3];
2097 curve_deform_vector(scene, amod->ob, armob, bone->arm_mat[3], pchan->pose_mat[3], mat3, amod->no_rot_axis);
2098 copy_m4_m4(mat4, pchan->pose_mat);
2099 mul_m4_m3m4(pchan->pose_mat, mat3, mat4);
2105 case ACTSTRIP_MOD_NOISE:
2107 if (STREQ(pchan->name, amod->channel)) {
2108 float nor[3], loc[3], ofs;
2109 float eul[3], size[3], eulo[3], sizeo[3];
2111 /* calculate turbulance */
2112 ofs = amod->turbul / 200.0f;
2114 /* make a copy of starting conditions */
2115 copy_v3_v3(loc, pchan->pose_mat[3]);
2116 mat4_to_eul(eul, pchan->pose_mat);
2117 mat4_to_size(size, pchan->pose_mat);
2118 copy_v3_v3(eulo, eul);
2119 copy_v3_v3(sizeo, size);
2121 /* apply noise to each set of channels */
2122 if (amod->channels & 4) {
2124 nor[0] = BLI_gNoise(amod->noisesize, size[0] + ofs, size[1], size[2], 0, 0) - ofs;
2125 nor[1] = BLI_gNoise(amod->noisesize, size[0], size[1] + ofs, size[2], 0, 0) - ofs;
2126 nor[2] = BLI_gNoise(amod->noisesize, size[0], size[1], size[2] + ofs, 0, 0) - ofs;
2127 add_v3_v3(size, nor);
2130 mul_v3_fl(pchan->pose_mat[0], size[0] / sizeo[0]);
2132 mul_v3_fl(pchan->pose_mat[1], size[1] / sizeo[1]);
2134 mul_v3_fl(pchan->pose_mat[2], size[2] / sizeo[2]);
2136 if (amod->channels & 2) {
2138 nor[0] = BLI_gNoise(amod->noisesize, eul[0] + ofs, eul[1], eul[2], 0, 0) - ofs;
2139 nor[1] = BLI_gNoise(amod->noisesize, eul[0], eul[1] + ofs, eul[2], 0, 0) - ofs;
2140 nor[2] = BLI_gNoise(amod->noisesize, eul[0], eul[1], eul[2] + ofs, 0, 0) - ofs;
2142 compatible_eul(nor, eulo);
2143 add_v3_v3(eul, nor);
2144 compatible_eul(eul, eulo);
2146 loc_eul_size_to_mat4(pchan->pose_mat, loc, eul, size);
2148 if (amod->channels & 1) {
2150 nor[0] = BLI_gNoise(amod->noisesize, loc[0] + ofs, loc[1], loc[2], 0, 0) - ofs;
2151 nor[1] = BLI_gNoise(amod->noisesize, loc[0], loc[1] + ofs, loc[2], 0, 0) - ofs;
2152 nor[2] = BLI_gNoise(amod->noisesize, loc[0], loc[1], loc[2] + ofs, 0, 0) - ofs;
2154 add_v3_v3v3(pchan->pose_mat[3], loc, nor);
2167 /* calculate tail of posechannel */
2168 void BKE_pose_where_is_bone_tail(bPoseChannel *pchan)
2172 copy_v3_v3(vec, pchan->pose_mat[1]);
2173 mul_v3_fl(vec, pchan->bone->length);
2174 add_v3_v3v3(pchan->pose_tail, pchan->pose_head, vec);
2177 /* The main armature solver, does all constraints excluding IK */
2178 /* pchan is validated, as having bone and parent pointer
2179 * 'do_extra': when zero skips loc/size/rot, constraints and strip modifiers.
2181 void BKE_pose_where_is_bone(Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, bool do_extra)
2183 /* This gives a chan_mat with actions (ipos) results. */
2185 BKE_pchan_calc_mat(pchan);
2187 unit_m4(pchan->chan_mat);
2189 /* Construct the posemat based on PoseChannels, that we do before applying constraints. */
2190 /* pose_mat(b) = pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */
2191 BKE_armature_mat_bone_to_pose(pchan, pchan->chan_mat, pchan->pose_mat);
2193 /* Only rootbones get the cyclic offset (unless user doesn't want that). */
2194 /* XXX That could be a problem for snapping and other "reverse transform" features... */
2195 if (!pchan->parent) {
2196 if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0)
2197 add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset);
2201 #if 0 /* XXX OLD ANIMSYS, NLASTRIPS ARE NO LONGER USED */
2202 /* do NLA strip modifiers - i.e. curve follow */
2203 do_strip_modifiers(scene, ob, bone, pchan);
2206 /* Do constraints */
2207 if (pchan->constraints.first) {
2211 /* make a copy of location of PoseChannel for later */
2212 copy_v3_v3(vec, pchan->pose_mat[3]);
2214 /* prepare PoseChannel for Constraint solving
2215 * - makes a copy of matrix, and creates temporary struct to use
2217 cob = BKE_constraints_make_evalob(scene, ob, pchan, CONSTRAINT_OBTYPE_BONE);
2219 /* Solve PoseChannel's Constraints */
2220 BKE_constraints_solve(&pchan->constraints, cob, ctime); /* ctime doesnt alter objects */
2222 /* cleanup after Constraint Solving
2223 * - applies matrix back to pchan, and frees temporary struct used
2225 BKE_constraints_clear_evalob(cob);
2227 /* prevent constraints breaking a chain */
2228 if (pchan->bone->flag & BONE_CONNECTED) {
2229 copy_v3_v3(pchan->pose_mat[3], vec);
2234 /* calculate head */
2235 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
2236 /* calculate tail */
2237 BKE_pose_where_is_bone_tail(pchan);
2240 /* This only reads anim data from channels, and writes to channels */
2241 /* This is the only function adding poses */
2242 void BKE_pose_where_is(Scene *scene, Object *ob)
2246 bPoseChannel *pchan;
2250 if (ob->type != OB_ARMATURE)
2254 if (ELEM(NULL, arm, scene))
2256 if ((ob->pose == NULL) || (ob->pose->flag & POSE_RECALC))
2257 BKE_pose_rebuild(ob, arm);
2259 ctime = BKE_scene_frame_get(scene); /* not accurate... */
2261 /* In editmode or restposition we read the data from the bones */
2262 if (arm->edbo || (arm->flag & ARM_RESTPOS)) {
2263 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2266 copy_m4_m4(pchan->pose_mat, bone->arm_mat);
2267 copy_v3_v3(pchan->pose_head, bone->arm_head);
2268 copy_v3_v3(pchan->pose_tail, bone->arm_tail);
2273 invert_m4_m4(ob->imat, ob->obmat); /* imat is needed */
2275 /* 1. clear flags */
2276 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2277 pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
2280 /* 2a. construct the IK tree (standard IK) */
2281 BIK_initialize_tree(scene, ob, ctime);
2283 /* 2b. construct the Spline IK trees
2284 * - this is not integrated as an IK plugin, since it should be able
2285 * to function in conjunction with standard IK
2287 BKE_pose_splineik_init_tree(scene, ob, ctime);
2289 /* 3. the main loop, channels are already hierarchical sorted from root to children */
2290 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2291 /* 4a. if we find an IK root, we handle it separated */
2292 if (pchan->flag & POSE_IKTREE) {
2293 BIK_execute_tree(scene, ob, pchan, ctime);
2295 /* 4b. if we find a Spline IK root, we handle it separated too */
2296 else if (pchan->flag & POSE_IKSPLINE) {
2297 BKE_splineik_execute_tree(scene, ob, pchan, ctime);
2299 /* 5. otherwise just call the normal solver */
2300 else if (!(pchan->flag & POSE_DONE)) {
2301 BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1);
2304 /* 6. release the IK tree */
2305 BIK_release_tree(scene, ob, ctime);
2308 /* calculating deform matrices */
2309 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2311 invert_m4_m4(imat, pchan->bone->arm_mat);
2312 mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
2317 /************** Bounding box ********************/
2318 static int minmax_armature(Object *ob, float r_min[3], float r_max[3])
2320 bPoseChannel *pchan;
2322 /* For now, we assume BKE_pose_where_is has already been called (hence we have valid data in pachan). */
2323 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2324 minmax_v3v3_v3(r_min, r_max, pchan->pose_head);
2325 minmax_v3v3_v3(r_min, r_max, pchan->pose_tail);
2328 return (BLI_listbase_is_empty(&ob->pose->chanbase) == false);
2331 static void boundbox_armature(Object *ob)
2334 float min[3], max[3];
2336 if (ob->bb == NULL) {
2337 ob->bb = MEM_callocN(sizeof(BoundBox), "Armature boundbox");
2341 INIT_MINMAX(min, max);
2342 if (!minmax_armature(ob, min, max)) {
2343 min[0] = min[1] = min[2] = -1.0f;
2344 max[0] = max[1] = max[2] = 1.0f;
2347 BKE_boundbox_init_from_minmax(bb, min, max);
2349 bb->flag &= ~BOUNDBOX_DIRTY;
2352 BoundBox *BKE_armature_boundbox_get(Object *ob)
2354 boundbox_armature(ob);
2359 bool BKE_pose_minmax(Object *ob, float r_min[3], float r_max[3], bool use_hidden, bool use_select)
2361 bool changed = false;
2364 bArmature *arm = ob->data;
2365 bPoseChannel *pchan;
2367 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2368 /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2369 * (editarmature.c:2592)... Skip in this case too! */
2371 (!((use_hidden == false) && (PBONE_VISIBLE(arm, pchan->bone) == false)) &&
2372 !((use_select == true) && ((pchan->bone->flag & BONE_SELECTED) == 0))))
2374 bPoseChannel *pchan_tx = (pchan->custom && pchan->custom_tx) ? pchan->custom_tx : pchan;
2375 BoundBox *bb_custom = ((pchan->custom) && !(arm->flag & ARM_NO_CUSTOM)) ?
2376 BKE_object_boundbox_get(pchan->custom) : NULL;
2378 float mat[4][4], smat[4][4];
2379 scale_m4_fl(smat, PCHAN_CUSTOM_DRAW_SIZE(pchan));
2380 mul_m4_series(mat, ob->obmat, pchan_tx->pose_mat, smat);
2381 BKE_boundbox_minmax(bb_custom, mat, r_min, r_max);
2385 mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_head);
2386 minmax_v3v3_v3(r_min, r_max, vec);
2387 mul_v3_m4v3(vec, ob->obmat, pchan_tx->pose_tail);
2388 minmax_v3v3_v3(r_min, r_max, vec);
2399 /************** Graph evaluation ********************/
2401 bPoseChannel *BKE_armature_ik_solver_find_root(
2402 bPoseChannel *pchan,
2403 bKinematicConstraint *data)
2405 bPoseChannel *rootchan = pchan;
2406 if (!(data->flag & CONSTRAINT_IK_TIP)) {
2407 /* Exclude tip from chain. */
2408 rootchan = rootchan->parent;
2410 if (rootchan != NULL) {
2412 while (rootchan->parent) {
2413 /* Continue up chain, until we reach target number of items. */
2415 if (segcount == data->rootbone) {
2418 rootchan = rootchan->parent;
2424 bPoseChannel *BKE_armature_splineik_solver_find_root(
2425 bPoseChannel *pchan,
2426 bSplineIKConstraint *data)
2428 bPoseChannel *rootchan = pchan;
2430 BLI_assert(rootchan != NULL);
2431 while (rootchan->parent) {
2432 /* Continue up chain, until we reach target number of items. */
2434 if (segcount == data->chainlen) {
2437 rootchan = rootchan->parent;