PageRenderTime 30ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/blender/source/blender/blenkernel/intern/armature.c

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