Blender V4.3
itasc_plugin.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
9#include <algorithm>
10#include <cmath>
11#include <cstdlib>
12#include <cstring>
13#include <vector>
14
15/* iTaSC headers */
16#ifdef WITH_IK_ITASC
17# include "Armature.hpp"
18# include "Cache.hpp"
19# include "CopyPose.hpp"
20# include "Distance.hpp"
21# include "MovingFrame.hpp"
22# include "Scene.hpp"
23# include "WDLSSolver.hpp"
24# include "WSDLSSolver.hpp"
25#endif
26
27#include "MEM_guardedalloc.h"
28
29#include "BIK_api.h"
30#include "BLI_blenlib.h"
31#include "BLI_math_matrix.h"
32#include "BLI_math_rotation.h"
33#include "BLI_math_vector.h"
34#include "BLI_utildefines.h"
35
36#include "BKE_action.hh"
37#include "BKE_armature.hh"
38#include "BKE_constraint.h"
39#include "BKE_global.hh"
40#include "DNA_action_types.h"
41#include "DNA_armature_types.h"
43#include "DNA_object_types.h"
44#include "DNA_scene_types.h"
45
46#include "itasc_plugin.h"
47
48/* default parameters */
50
51/* in case of animation mode, feedback and timestep is fixed */
52// #define ANIM_TIMESTEP 1.0
53#define ANIM_FEEDBACK 0.8
54// #define ANIM_QMAX 0.52
55
56/* Structure pointed by bPose.ikdata
57 * It contains everything needed to simulate the armatures
58 * There can be several simulation islands independent to each other */
59struct IK_Data {
60 struct IK_Scene *first;
61};
62
63using Vector3 = float[3];
64using Vector4 = float[4];
65struct IK_Target;
66using ErrorCallback = void (*)(const iTaSC::ConstraintValues *values,
67 uint nvalues,
68 IK_Target *iktarget);
69
70/* one structure for each target in the scene */
71struct IK_Target {
72 Depsgraph *bldepsgraph;
78 Object *owner; /* for auto IK */
80 std::string targetName;
81 std::string constraintName;
83 short channel; /* index in IK channel array of channel on which this target is defined */
84 short ee; /* end effector number */
85 bool simulation; /* true when simulation mode is used (update feedback) */
86 bool eeBlend; /* end effector affected by enforce blending */
87 float eeRest[4][4]; /* end effector initial pose relative to armature */
88
90 {
91 bldepsgraph = nullptr;
92 blscene = nullptr;
93 target = nullptr;
94 constraint = nullptr;
95 blenderConstraint = nullptr;
96 rootChannel = nullptr;
97 owner = nullptr;
98 controlType = 0;
99 channel = 0;
100 ee = 0;
101 eeBlend = true;
102 simulation = true;
103 targetName.reserve(32);
104 constraintName.reserve(32);
105 }
107 {
108 delete constraint;
109 delete target;
110 }
111};
112
114 bPoseChannel *pchan; /* channel where we must copy matrix back */
115 KDL::Frame frame; /* frame of the bone relative to object base, not armature base */
116 std::string tail; /* segment name of the joint from which we get the bone tail */
117 std::string head; /* segment name of the joint from which we get the bone head */
118 int parent; /* index in this array of the parent channel */
119 short jointType; /* type of joint, combination of IK_SegmentFlag */
120 char ndof; /* number of joint angles for this channel */
121 char jointValid; /* set to 1 when jointValue has been computed */
122 /* for joint constraint */
123 Object *owner; /* for pose and IK param */
124 double jointValue[4]; /* computed joint value */
125
127 {
128 pchan = nullptr;
129 parent = -1;
130 jointType = 0;
131 ndof = 0;
132 jointValid = 0;
133 owner = nullptr;
134 jointValue[0] = 0.0;
135 jointValue[1] = 0.0;
136 jointValue[2] = 0.0;
137 jointValue[3] = 0.0;
138 }
139};
140
141struct IK_Scene {
142 Depsgraph *bldepsgraph;
145 int numchan; /* number of channel in pchan */
146 int numjoint; /* number of joint in jointArray */
147 /* array of bone information, one per channel in the tree */
152 iTaSC::MovingFrame *base; /* armature base object */
153 KDL::Frame baseFrame; /* frame of armature base relative to blArmature */
154 KDL::JntArray jointArray; /* buffer for storing temporary joint array */
157 float blScale; /* scale of the Armature object (assume uniform scaling) */
158 float blInvScale; /* inverse of Armature object scale */
160 std::vector<IK_Target *> targets;
161
163 {
164 bldepsgraph = nullptr;
165 blscene = nullptr;
166 next = nullptr;
167 channels = nullptr;
168 armature = nullptr;
169 cache = nullptr;
170 scene = nullptr;
171 base = nullptr;
172 solver = nullptr;
173 blScale = blInvScale = 1.0f;
174 blArmature = nullptr;
175 numchan = 0;
176 numjoint = 0;
177 polarConstraint = nullptr;
178 }
179
181 {
182 /* delete scene first */
183 delete scene;
184 for (IK_Target *target : targets) {
185 delete target;
186 }
187 targets.clear();
188 delete[] channels;
189 delete solver;
190 delete armature;
191 delete base;
192 /* delete cache last */
193 delete cache;
194 }
195};
196
197/* type of IK joint, can be combined to list the joints corresponding to a bone */
206
215
216static int initialize_chain(Object * /*ob*/, bPoseChannel *pchan_tip, bConstraint *con)
217{
218 bPoseChannel *curchan, *pchan_root = nullptr, *chanlist[256], **oldchan;
219 PoseTree *tree;
220 PoseTarget *target;
222 int a, t, segcount = 0, size, newsize, *oldparent, parent, rootbone, treecount;
223
224 data = (bKinematicConstraint *)con->data;
225
226 /* exclude tip from chain? */
227 if (!(data->flag & CONSTRAINT_IK_TIP)) {
228 pchan_tip = pchan_tip->parent;
229 }
230
231 rootbone = data->rootbone;
232 /* Find the chain's root & count the segments needed */
233 for (curchan = pchan_tip; curchan; curchan = curchan->parent) {
234 pchan_root = curchan;
235
236 if (++segcount > 255) { /* 255 is weak */
237 break;
238 }
239
240 if (segcount == rootbone) {
241 /* reached this end of the chain but if the chain is overlapping with a
242 * previous one, we must go back up to the root of the other chain */
243 if ((curchan->flag & POSE_CHAIN) && BLI_listbase_is_empty(&curchan->iktree)) {
244 rootbone++;
245 continue;
246 }
247 break;
248 }
249
250 if (BLI_listbase_is_empty(&curchan->iktree) == false) {
251 /* Oh, there is already a chain starting from this channel and our chain is longer.
252 * Should handle this by moving the previous chain up to the beginning of our chain
253 * For now we just stop here. */
254 break;
255 }
256 }
257 if (!segcount) {
258 return 0;
259 }
260 /* we reached a limit and still not the end of a previous chain, quit */
261 if ((pchan_root->flag & POSE_CHAIN) && BLI_listbase_is_empty(&pchan_root->iktree)) {
262 return 0;
263 }
264
265 /* now that we know how many segment we have, set the flag */
266 for (rootbone = segcount, segcount = 0, curchan = pchan_tip; segcount < rootbone;
267 segcount++, curchan = curchan->parent)
268 {
269 chanlist[segcount] = curchan;
270 curchan->flag |= POSE_CHAIN;
271 }
272
273 /* setup the chain data */
274 /* create a target */
275 target = MEM_cnew<PoseTarget>("posetarget");
276 target->con = con;
277 /* by construction there can be only one tree per channel
278 * and each channel can be part of at most one tree. */
279 tree = (PoseTree *)pchan_root->iktree.first;
280
281 if (tree == nullptr) {
282 /* make new tree */
283 tree = MEM_cnew<PoseTree>("posetree");
284
285 tree->iterations = data->iterations;
286 tree->totchannel = segcount;
287 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH);
288
289 tree->pchan = (bPoseChannel **)MEM_callocN(segcount * sizeof(void *), "ik tree pchan");
290 tree->parent = (int *)MEM_callocN(segcount * sizeof(int), "ik tree parent");
291 for (a = 0; a < segcount; a++) {
292 tree->pchan[a] = chanlist[segcount - a - 1];
293 tree->parent[a] = a - 1;
294 }
295 target->tip = segcount - 1;
296
297 /* AND! link the tree to the root */
298 BLI_addtail(&pchan_root->iktree, tree);
299 /* new tree */
300 treecount = 1;
301 }
302 else {
303 tree->iterations = std::max<int>(data->iterations, tree->iterations);
304 tree->stretch = tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH);
305
306 /* Skip common pose channels and add remaining. */
307 size = std::min(segcount, tree->totchannel);
308 a = t = 0;
309 while (a < size && t < tree->totchannel) {
310 /* locate first matching channel */
311 for (; t < tree->totchannel && tree->pchan[t] != chanlist[segcount - a - 1]; t++) {
312 /* pass */
313 }
314 if (t >= tree->totchannel) {
315 break;
316 }
317 for (; a < size && t < tree->totchannel && tree->pchan[t] == chanlist[segcount - a - 1];
318 a++, t++)
319 {
320 /* pass */
321 }
322 }
323
324 segcount = segcount - a;
325 target->tip = tree->totchannel + segcount - 1;
326
327 if (segcount > 0) {
328 for (parent = a - 1; parent < tree->totchannel; parent++) {
329 if (tree->pchan[parent] == chanlist[segcount - 1]->parent) {
330 break;
331 }
332 }
333
334 /* shouldn't happen, but could with dependency cycles */
335 if (parent == tree->totchannel) {
336 parent = a - 1;
337 }
338
339 /* resize array */
340 newsize = tree->totchannel + segcount;
341 oldchan = tree->pchan;
342 oldparent = tree->parent;
343
344 tree->pchan = (bPoseChannel **)MEM_callocN(newsize * sizeof(void *), "ik tree pchan");
345 tree->parent = (int *)MEM_callocN(newsize * sizeof(int), "ik tree parent");
346 memcpy(tree->pchan, oldchan, sizeof(void *) * tree->totchannel);
347 memcpy(tree->parent, oldparent, sizeof(int) * tree->totchannel);
348 MEM_freeN(oldchan);
349 MEM_freeN(oldparent);
350
351 /* add new pose channels at the end, in reverse order */
352 for (a = 0; a < segcount; a++) {
353 tree->pchan[tree->totchannel + a] = chanlist[segcount - a - 1];
354 tree->parent[tree->totchannel + a] = tree->totchannel + a - 1;
355 }
356 tree->parent[tree->totchannel] = parent;
357
358 tree->totchannel = newsize;
359 }
360 /* reusing tree */
361 treecount = 0;
362 }
363
364 /* add target to the tree */
365 BLI_addtail(&tree->targets, target);
366 /* mark root channel having an IK tree */
367 pchan_root->flag |= POSE_IKTREE;
368 return treecount;
369}
370
372{
373 // bKinematicConstraint* data=(bKinematicConstraint *)con->data;
374
375 return true;
376}
377
379{
381
382 if (data->flag & CONSTRAINT_IK_AUTO) {
383 return true;
384 }
385 if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) {
386 return false;
387 }
388 if (is_cartesian_constraint(con)) {
389 /* cartesian space constraint */
390 if (data->tar == nullptr) {
391 return false;
392 }
393 if (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0) {
394 return false;
395 }
396 }
397 return true;
398}
399
400static int initialize_scene(Object *ob, bPoseChannel *pchan_tip)
401{
402 /* Find all IK constraints and validate them. */
403 int treecount = 0;
404 LISTBASE_FOREACH (bConstraint *, con, &pchan_tip->constraints) {
405 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
406 if (constraint_valid(con)) {
407 treecount += initialize_chain(ob, pchan_tip, con);
408 }
409 }
410 }
411 return treecount;
412}
413
415{
416 if (pose->ikdata) {
417 return (IK_Data *)pose->ikdata;
418 }
419 pose->ikdata = MEM_callocN(sizeof(IK_Data), "iTaSC ikdata");
420 /* here init ikdata if needed
421 * now that we have scene, make sure the default param are initialized */
422 if (!DefIKParam.iksolver) {
424 }
425
426 return (IK_Data *)pose->ikdata;
427}
428static double EulerAngleFromMatrix(const KDL::Rotation &R, int axis)
429{
430 double t = KDL::sqrt(R(0, 0) * R(0, 0) + R(0, 1) * R(0, 1));
431
432 if (t > 16.0 * KDL::epsilon) {
433 if (axis == 0) {
434 return -KDL::atan2(R(1, 2), R(2, 2));
435 }
436 if (axis == 1) {
437 return KDL::atan2(-R(0, 2), t);
438 }
439
440 return -KDL::atan2(R(0, 1), R(0, 0));
441 }
442
443 if (axis == 0) {
444 return -KDL::atan2(-R(2, 1), R(1, 1));
445 }
446 if (axis == 1) {
447 return KDL::atan2(-R(0, 2), t);
448 }
449
450 return 0.0f;
451}
452
453static double ComputeTwist(const KDL::Rotation &R)
454{
455 /* qy and qw are the y and w components of the quaternion from R */
456 double qy = R(0, 2) - R(2, 0);
457 double qw = R(0, 0) + R(1, 1) + R(2, 2) + 1;
458
459 double tau = 2 * KDL::atan2(qy, qw);
460
461 return tau;
462}
463
464static void RemoveEulerAngleFromMatrix(KDL::Rotation &R, double angle, int axis)
465{
466 /* compute twist parameter */
468 switch (axis) {
469 case 0:
470 T = KDL::Rotation::RotX(-angle);
471 break;
472 case 1:
473 T = KDL::Rotation::RotY(-angle);
474 break;
475 case 2:
476 T = KDL::Rotation::RotZ(-angle);
477 break;
478 default:
479 return;
480 }
481 /* remove angle */
482 R = R * T;
483}
484
485#if 0
486static void GetEulerXZY(const KDL::Rotation &R, double &X, double &Z, double &Y)
487{
488 if (fabs(R(0, 1)) > 1.0 - KDL::epsilon) {
489 X = -KDL::sign(R(0, 1)) * KDL::atan2(R(1, 2), R(1, 0));
490 Z = -KDL::sign(R(0, 1)) * KDL::PI / 2;
491 Y = 0.0;
492 }
493 else {
494 X = KDL::atan2(R(2, 1), R(1, 1));
495 Z = KDL::atan2(-R(0, 1), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 2))));
496 Y = KDL::atan2(R(0, 2), R(0, 0));
497 }
498}
499
500static void GetEulerXYZ(const KDL::Rotation &R, double &X, double &Y, double &Z)
501{
502 if (fabs(R(0, 2)) > 1.0 - KDL::epsilon) {
503 X = KDL::sign(R(0, 2)) * KDL::atan2(-R(1, 0), R(1, 1));
504 Y = KDL::sign(R(0, 2)) * KDL::PI / 2;
505 Z = 0.0;
506 }
507 else {
508 X = KDL::atan2(-R(1, 2), R(2, 2));
509 Y = KDL::atan2(R(0, 2), KDL::sqrt(KDL::sqr(R(0, 0)) + KDL::sqr(R(0, 1))));
510 Z = KDL::atan2(-R(0, 1), R(0, 0));
511 }
512}
513#endif
514
515static void GetJointRotation(KDL::Rotation &boneRot, int type, double *rot)
516{
517 switch (type & ~IK_TRANSY) {
518 default:
519 /* fixed bone, no joint */
520 break;
521 case IK_XDOF:
522 /* RX only, get the X rotation */
523 rot[0] = EulerAngleFromMatrix(boneRot, 0);
524 break;
525 case IK_YDOF:
526 /* RY only, get the Y rotation */
527 rot[0] = ComputeTwist(boneRot);
528 break;
529 case IK_ZDOF:
530 /* RZ only, get the Z rotation */
531 rot[0] = EulerAngleFromMatrix(boneRot, 2);
532 break;
533 case IK_XDOF | IK_YDOF:
534 rot[1] = ComputeTwist(boneRot);
535 RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
536 rot[0] = EulerAngleFromMatrix(boneRot, 0);
537 break;
538 case IK_SWING:
539 /* RX+RZ */
540 boneRot.GetXZRot().GetValue(rot);
541 break;
542 case IK_YDOF | IK_ZDOF:
543 /* RZ+RY */
544 rot[1] = ComputeTwist(boneRot);
545 RemoveEulerAngleFromMatrix(boneRot, rot[1], 1);
546 rot[0] = EulerAngleFromMatrix(boneRot, 2);
547 break;
548 case IK_SWING | IK_YDOF:
549 rot[2] = ComputeTwist(boneRot);
550 RemoveEulerAngleFromMatrix(boneRot, rot[2], 1);
551 boneRot.GetXZRot().GetValue(rot);
552 break;
553 case IK_REVOLUTE:
554 boneRot.GetRot().GetValue(rot);
555 break;
556 }
557}
558
559static bool target_callback(const iTaSC::Timestamp & /*timestamp*/,
560 const iTaSC::Frame & /*current*/,
562 void *param)
563{
564 IK_Target *target = (IK_Target *)param;
565 /* compute next target position
566 * get target matrix from constraint. */
567 bConstraint *constraint = (bConstraint *)target->blenderConstraint;
568 float tarmat[4][4];
569
570 BKE_constraint_target_matrix_get(target->bldepsgraph,
571 target->blscene,
572 constraint,
573 0,
575 target->owner,
576 tarmat,
577 1.0);
578
579 /* rootmat contains the target pose in world coordinate
580 * if enforce is != 1.0, blend the target position with the end effector position
581 * if the armature was in rest position. This information is available in eeRest */
582 if (constraint->enforce != 1.0f && target->eeBlend) {
583 /* eeRest is relative to the reference frame of the IK root
584 * get this frame in world reference */
585 float restmat[4][4];
586 bPoseChannel *pchan = target->rootChannel;
587 if (pchan->parent) {
588 pchan = pchan->parent;
589 float chanmat[4][4];
590 copy_m4_m4(chanmat, pchan->pose_mat);
591 copy_v3_v3(chanmat[3], pchan->pose_tail);
592 mul_m4_series(restmat, target->owner->object_to_world().ptr(), chanmat, target->eeRest);
593 }
594 else {
595 mul_m4_m4m4(restmat, target->owner->object_to_world().ptr(), target->eeRest);
596 }
597 /* blend the target */
598 blend_m4_m4m4(tarmat, restmat, tarmat, constraint->enforce);
599 }
600 next.setValue(&tarmat[0][0]);
601 return true;
602}
603
604static bool base_callback(const iTaSC::Timestamp &timestamp,
605 const iTaSC::Frame & /*current*/,
607 void *param)
608{
609 IK_Scene *ikscene = (IK_Scene *)param;
610 /* compute next armature base pose
611 * algorithm:
612 * ikscene->pchan[0] is the root channel of the tree
613 * if it has a parent, get the pose matrix from it and replace [3] by parent pchan->tail
614 * then multiply by the armature matrix to get ikscene->armature base position */
615 bPoseChannel *pchan = ikscene->channels[0].pchan;
616 float rootmat[4][4];
617 if (pchan->parent) {
618 pchan = pchan->parent;
619 float chanmat[4][4];
620 copy_m4_m4(chanmat, pchan->pose_mat);
621 copy_v3_v3(chanmat[3], pchan->pose_tail);
622 /* save the base as a frame too so that we can compute deformation after simulation */
623 ikscene->baseFrame.setValue(&chanmat[0][0]);
624 /* iTaSC armature is scaled to object scale, scale the base frame too */
625 ikscene->baseFrame.p *= ikscene->blScale;
626 mul_m4_m4m4(rootmat, ikscene->blArmature->object_to_world().ptr(), chanmat);
627 }
628 else {
629 copy_m4_m4(rootmat, ikscene->blArmature->object_to_world().ptr());
630 ikscene->baseFrame = iTaSC::F_identity;
631 }
632 next.setValue(&rootmat[0][0]);
633 /* If there is a polar target (only during solving otherwise we don't have end effector). */
634 if (ikscene->polarConstraint && timestamp.update) {
635 /* compute additional rotation of base frame so that armature follows the polar target */
636 float imat[4][4]; /* IK tree base inverse matrix */
637 float polemat[4][4]; /* polar target in IK tree base frame */
638 float goalmat[4][4]; /* target in IK tree base frame */
639 float mat[4][4]; /* temp matrix */
641
642 invert_m4_m4(imat, rootmat);
643 /* polar constraint imply only one target */
644 IK_Target *iktarget = ikscene->targets[0];
645 /* root channel from which we take the bone initial orientation */
646 IK_Channel &rootchan = ikscene->channels[0];
647
648 /* get polar target matrix in world space */
650 ikscene->blscene,
651 ikscene->polarConstraint,
652 1,
654 ikscene->blArmature,
655 mat,
656 1.0);
657 /* convert to armature space */
658 mul_m4_m4m4(polemat, imat, mat);
659 /* get the target in world space
660 * (was computed before as target object are defined before base object). */
661 iktarget->target->getPose().getValue(mat[0]);
662 /* convert to armature space */
663 mul_m4_m4m4(goalmat, imat, mat);
664 /* take position of target, polar target, end effector, in armature space */
665 KDL::Vector goalpos(goalmat[3]);
666 KDL::Vector polepos(polemat[3]);
667 KDL::Vector endpos = ikscene->armature->getPose(iktarget->ee).p;
668 /* get root bone orientation */
669 KDL::Frame rootframe;
670 ikscene->armature->getRelativeFrame(rootframe, rootchan.tail);
671 KDL::Vector rootx = rootframe.M.UnitX();
672 KDL::Vector rootz = rootframe.M.UnitZ();
673 /* and compute root bone head */
674 double q_rest[3], q[3], length;
675 const KDL::Joint *joint;
676 const KDL::Frame *tip;
677 ikscene->armature->getSegment(rootchan.tail, 3, joint, q_rest[0], q[0], tip);
678 length = (joint->getType() == KDL::Joint::TransY) ? q[0] : tip->p(1);
679 KDL::Vector rootpos = rootframe.p - length * rootframe.M.UnitY();
680
681 /* compute main directions */
682 KDL::Vector dir = KDL::Normalize(endpos - rootpos);
683 KDL::Vector poledir = KDL::Normalize(goalpos - rootpos);
684 /* compute up directions */
685 KDL::Vector poleup = KDL::Normalize(polepos - rootpos);
686 KDL::Vector up = rootx * KDL::cos(poledata->poleangle) + rootz * KDL::sin(poledata->poleangle);
687 /* from which we build rotation matrix */
688 KDL::Rotation endrot, polerot;
689 /* for the armature, using the root bone orientation */
690 KDL::Vector x = KDL::Normalize(dir * up);
691 endrot.UnitX(x);
692 endrot.UnitY(KDL::Normalize(x * dir));
693 endrot.UnitZ(-dir);
694 /* for the polar target */
695 x = KDL::Normalize(poledir * poleup);
696 polerot.UnitX(x);
697 polerot.UnitY(KDL::Normalize(x * poledir));
698 polerot.UnitZ(-poledir);
699 /* the difference between the two is the rotation we want to apply */
700 KDL::Rotation result(polerot * endrot.Inverse());
701 /* apply on base frame as this is an artificial additional rotation */
702 next.M = next.M * result;
703 ikscene->baseFrame.M = ikscene->baseFrame.M * result;
704 }
705 return true;
706}
707
708static bool copypose_callback(const iTaSC::Timestamp & /*timestamp*/,
709 iTaSC::ConstraintValues *const _values,
710 uint /*nvalues*/,
711 void *_param)
712{
713 IK_Target *iktarget = (IK_Target *)_param;
715 iTaSC::ConstraintValues *values = _values;
716 bItasc *ikparam = (bItasc *)iktarget->owner->pose->ikparam;
717
718 /* we need default parameters */
719 if (!ikparam) {
720 ikparam = &DefIKParam;
721 }
722
723 if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
725 values->alpha = 0.0;
726 values->action = iTaSC::ACT_ALPHA;
727 values++;
728 }
730 values->alpha = 0.0;
731 values->action = iTaSC::ACT_ALPHA;
732 values++;
733 }
734 }
735 else {
737 /* update error */
738 values->alpha = condata->weight;
739 values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
740 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
741 values++;
742 }
744 /* update error */
745 values->alpha = condata->orientweight;
746 values->action = iTaSC::ACT_ALPHA | iTaSC::ACT_FEEDBACK;
747 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
748 values++;
749 }
750 }
751 return true;
752}
753
754static void copypose_error(const iTaSC::ConstraintValues *values,
755 uint /*nvalues*/,
756 IK_Target *iktarget)
757{
759 double error;
760 int i;
761
763 /* update error */
764 for (i = 0, error = 0.0, value = values->values; i < values->number; i++, value++) {
765 error += KDL::sqr(value->y - value->yd);
766 }
768 values++;
769 }
771 /* update error */
772 for (i = 0, error = 0.0, value = values->values; i < values->number; i++, value++) {
773 error += KDL::sqr(value->y - value->yd);
774 }
776 values++;
777 }
778}
779
780static bool distance_callback(const iTaSC::Timestamp &timestamp,
781 iTaSC::ConstraintValues *const _values,
782 uint /*nvalues*/,
783 void *_param)
784{
785 IK_Target *iktarget = (IK_Target *)_param;
787 iTaSC::ConstraintValues *values = _values;
788 bItasc *ikparam = (bItasc *)iktarget->owner->pose->ikparam;
789 /* we need default parameters */
790 if (!ikparam) {
791 ikparam = &DefIKParam;
792 }
793
794 /* update weight according to mode */
795 if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) {
796 values->alpha = 0.0;
797 }
798 else {
799 switch (condata->mode) {
800 case LIMITDIST_INSIDE:
801 values->alpha = (values->values[0].y > condata->dist) ? condata->weight : 0.0;
802 break;
804 values->alpha = (values->values[0].y < condata->dist) ? condata->weight : 0.0;
805 break;
806 default:
807 values->alpha = condata->weight;
808 break;
809 }
810 if (!timestamp.substep) {
811 /* only update value on first timestep */
812 switch (condata->mode) {
813 case LIMITDIST_INSIDE:
814 values->values[0].yd = condata->dist * 0.95;
815 break;
817 values->values[0].yd = condata->dist * 1.05;
818 break;
819 default:
820 values->values[0].yd = condata->dist;
821 break;
822 }
823 values->values[0].action = iTaSC::ACT_VALUE | iTaSC::ACT_FEEDBACK;
824 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK;
825 }
826 }
827 values->action |= iTaSC::ACT_ALPHA;
828 return true;
829}
830
831static void distance_error(const iTaSC::ConstraintValues *values,
832 uint /*nvalues*/,
833 IK_Target *iktarget)
834{
835 iktarget->blenderConstraint->lin_error = float(values->values[0].y - values->values[0].yd);
836}
837
838static bool joint_callback(const iTaSC::Timestamp & /*timestamp*/,
839 iTaSC::ConstraintValues *const _values,
840 uint _nvalues,
841 void *_param)
842{
843 IK_Channel *ikchan = (IK_Channel *)_param;
844 bItasc *ikparam = (bItasc *)ikchan->owner->pose->ikparam;
845 bPoseChannel *chan = ikchan->pchan;
846 int dof;
847
848 /* a channel can be split into multiple joints, so we get called multiple
849 * times for one channel (this callback is only for 1 joint in the armature)
850 * the IK_JointTarget structure is shared between multiple joint constraint
851 * and the target joint values is computed only once, remember this in jointValid
852 * Don't forget to reset it before each frame */
853 if (!ikchan->jointValid) {
854 float rmat[3][3];
855
856 if (chan->rotmode > 0) {
857 /* Euler rotations (will cause gimbal lock, but this can be alleviated a bit with rotation
858 * orders) */
859 eulO_to_mat3(rmat, chan->eul, chan->rotmode);
860 }
861 else if (chan->rotmode == ROT_MODE_AXISANGLE) {
862 /* axis-angle - stored in quaternion data,
863 * but not really that great for 3D-changing orientations */
864 axis_angle_to_mat3(rmat, &chan->quat[1], chan->quat[0]);
865 }
866 else {
867 /* Quaternions are normalized before use to eliminate scaling issues. */
868 normalize_qt(chan->quat);
869 quat_to_mat3(rmat, chan->quat);
870 }
871 KDL::Rotation jointRot(rmat[0][0],
872 rmat[1][0],
873 rmat[2][0],
874 rmat[0][1],
875 rmat[1][1],
876 rmat[2][1],
877 rmat[0][2],
878 rmat[1][2],
879 rmat[2][2]);
880 GetJointRotation(jointRot, ikchan->jointType, ikchan->jointValue);
881 ikchan->jointValid = 1;
882 }
883 /* determine which part of jointValue is used for this joint
884 * closely related to the way the joints are defined */
885 switch (ikchan->jointType & ~IK_TRANSY) {
886 case IK_XDOF:
887 case IK_YDOF:
888 case IK_ZDOF:
889 dof = 0;
890 break;
891 case IK_XDOF | IK_YDOF:
892 /* X + Y */
893 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RX) ? 0 : 1;
894 break;
895 case IK_SWING:
896 /* XZ */
897 dof = 0;
898 break;
899 case IK_YDOF | IK_ZDOF:
900 /* Z + Y */
901 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RZ) ? 0 : 1;
902 break;
903 case IK_SWING | IK_YDOF:
904 /* XZ + Y */
905 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RY) ? 2 : 0;
906 break;
907 case IK_REVOLUTE:
908 dof = 0;
909 break;
910 default:
911 dof = -1;
912 break;
913 }
914 if (dof >= 0) {
915 for (uint i = 0; i < _nvalues; i++, dof++) {
916 _values[i].values[0].yd = ikchan->jointValue[dof];
917 _values[i].alpha = chan->ikrotweight;
918 _values[i].feedback = ikparam->feedback;
919 }
920 }
921 return true;
922}
923
924/* build array of joint corresponding to IK chain */
925static int convert_channels(Depsgraph *depsgraph, IK_Scene *ikscene, PoseTree *tree, float ctime)
926{
927 IK_Channel *ikchan;
928 bPoseChannel *pchan;
929 int a, flag, njoint;
930
931 njoint = 0;
932 for (a = 0, ikchan = ikscene->channels; a < ikscene->numchan; a++, ikchan++) {
933 pchan = tree->pchan[a];
934 ikchan->pchan = pchan;
935 ikchan->parent = (a > 0) ? tree->parent[a] : -1;
936 ikchan->owner = ikscene->blArmature;
937
938 /* the constraint and channels must be applied before we build the iTaSC scene,
939 * this is because some of the pose data (e.g. pose head) don't have corresponding
940 * joint angles and can't be applied to the iTaSC armature dynamically */
941 if (!(pchan->flag & POSE_DONE)) {
942 BKE_pose_where_is_bone(depsgraph, ikscene->blscene, ikscene->blArmature, pchan, ctime, true);
943 }
944 /* tell blender that this channel was controlled by IK,
945 * it's cleared on each BKE_pose_where_is() */
946 pchan->flag |= (POSE_DONE | POSE_CHAIN);
947
948 /* set DoF flag */
949 flag = 0;
950 if (!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP) &&
951 (!(pchan->ikflag & BONE_IK_XLIMIT) || pchan->limitmin[0] < 0.0f ||
952 pchan->limitmax[0] > 0.0f))
953 {
954 flag |= IK_XDOF;
955 }
956 if (!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP) &&
957 (!(pchan->ikflag & BONE_IK_YLIMIT) || pchan->limitmin[1] < 0.0f ||
958 pchan->limitmax[1] > 0.0f))
959 {
960 flag |= IK_YDOF;
961 }
962 if (!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP) &&
963 (!(pchan->ikflag & BONE_IK_ZLIMIT) || pchan->limitmin[2] < 0.0f ||
964 pchan->limitmax[2] > 0.0f))
965 {
966 flag |= IK_ZDOF;
967 }
968
969 if (tree->stretch && (pchan->ikstretch > 0.0)) {
970 flag |= IK_TRANSY;
971 }
972 /*
973 * Logic to create the segments:
974 * RX,RY,RZ = rotational joints with no length
975 * RY(tip) = rotational joints with a fixed length arm = (0,length,0)
976 * TY = translational joint on Y axis
977 * F(pos) = fixed joint with an arm at position pos
978 * Conversion rule of the above flags:
979 * - ==> F(tip)
980 * X ==> RX(tip)
981 * Y ==> RY(tip)
982 * Z ==> RZ(tip)
983 * XY ==> RX+RY(tip)
984 * XZ ==> RX+RZ(tip)
985 * YZ ==> RZ+RY(tip)
986 * XYZ ==> full spherical unless there are limits, in which case RX+RZ+RY(tip)
987 * In case of stretch, tip=(0,0,0) and there is an additional TY joint
988 * The frame at last of these joints represents the tail of the bone.
989 * The head is computed by a reverse translation on Y axis of the bone length
990 * or in case of TY joint, by the frame at previous joint.
991 * In case of separation of bones, there is an additional F(head) joint
992 *
993 * Computing rest pose and length is complicated: the solver works in world space
994 * Here is the logic:
995 * rest position is computed only from bone->bone_mat.
996 * bone length is computed from bone->length multiplied by the scaling factor of
997 * the armature. Non-uniform scaling will give bad result!
998 */
999 switch (flag & (IK_XDOF | IK_YDOF | IK_ZDOF)) {
1000 default:
1001 ikchan->jointType = 0;
1002 ikchan->ndof = 0;
1003 break;
1004 case IK_XDOF:
1005 /* RX only, get the X rotation */
1006 ikchan->jointType = IK_XDOF;
1007 ikchan->ndof = 1;
1008 break;
1009 case IK_YDOF:
1010 /* RY only, get the Y rotation */
1011 ikchan->jointType = IK_YDOF;
1012 ikchan->ndof = 1;
1013 break;
1014 case IK_ZDOF:
1015 /* RZ only, get the Zz rotation */
1016 ikchan->jointType = IK_ZDOF;
1017 ikchan->ndof = 1;
1018 break;
1019 case IK_XDOF | IK_YDOF:
1020 ikchan->jointType = IK_XDOF | IK_YDOF;
1021 ikchan->ndof = 2;
1022 break;
1023 case IK_XDOF | IK_ZDOF:
1024 /* RX+RZ */
1025 ikchan->jointType = IK_SWING;
1026 ikchan->ndof = 2;
1027 break;
1028 case IK_YDOF | IK_ZDOF:
1029 /* RZ+RY */
1030 ikchan->jointType = IK_ZDOF | IK_YDOF;
1031 ikchan->ndof = 2;
1032 break;
1033 case IK_XDOF | IK_YDOF | IK_ZDOF:
1034 /* spherical joint */
1036 /* decompose in a Swing+RotY joint */
1037 ikchan->jointType = IK_SWING | IK_YDOF;
1038 }
1039 else {
1040 ikchan->jointType = IK_REVOLUTE;
1041 }
1042 ikchan->ndof = 3;
1043 break;
1044 }
1045 if (flag & IK_TRANSY) {
1046 ikchan->jointType |= IK_TRANSY;
1047 ikchan->ndof++;
1048 }
1049 njoint += ikchan->ndof;
1050 }
1051 /* njoint is the joint coordinate, create the Joint Array */
1052 ikscene->jointArray.resize(njoint);
1053 ikscene->numjoint = njoint;
1054 return njoint;
1055}
1056
1057/* compute array of joint value corresponding to current pose */
1058static void convert_pose(IK_Scene *ikscene)
1059{
1060 KDL::Rotation boneRot;
1061 bPoseChannel *pchan;
1062 IK_Channel *ikchan;
1063 Bone *bone;
1064 float rmat[4][4]; /* rest pose of bone with parent taken into account */
1065 float bmat[4][4]; /* difference */
1066 float scale;
1067 double *rot;
1068 int a, joint;
1069
1070 /* assume uniform scaling and take Y scale as general scale for the armature */
1071 scale = len_v3(ikscene->blArmature->object_to_world().ptr()[1]);
1072 rot = ikscene->jointArray(0);
1073 for (joint = a = 0, ikchan = ikscene->channels;
1074 a < ikscene->numchan && joint < ikscene->numjoint;
1075 a++, ikchan++)
1076 {
1077 pchan = ikchan->pchan;
1078 bone = pchan->bone;
1079
1080 if (pchan->parent) {
1081 unit_m4(bmat);
1082 mul_m4_m4m3(bmat, pchan->parent->pose_mat, bone->bone_mat);
1083 }
1084 else {
1085 copy_m4_m4(bmat, bone->arm_mat);
1086 }
1087 invert_m4_m4(rmat, bmat);
1088 mul_m4_m4m4(bmat, rmat, pchan->pose_mat);
1089 normalize_m4(bmat);
1090 boneRot.setValue(bmat[0]);
1091 GetJointRotation(boneRot, ikchan->jointType, rot);
1092 if (ikchan->jointType & IK_TRANSY) {
1093 /* compute actual length */
1094 rot[ikchan->ndof - 1] = len_v3v3(pchan->pose_tail, pchan->pose_head) * scale;
1095 }
1096 rot += ikchan->ndof;
1097 joint += ikchan->ndof;
1098 }
1099}
1100
1101/* compute array of joint value corresponding to current pose */
1102static void BKE_pose_rest(IK_Scene *ikscene)
1103{
1104 bPoseChannel *pchan;
1105 IK_Channel *ikchan;
1106 Bone *bone;
1107 float scale;
1108 double *rot;
1109 int a, joint;
1110
1111 /* assume uniform scaling and take Y scale as general scale for the armature */
1112 scale = len_v3(ikscene->blArmature->object_to_world().ptr()[1]);
1113 /* rest pose is 0 */
1114 SetToZero(ikscene->jointArray);
1115 /* except for transY joints */
1116 rot = ikscene->jointArray(0);
1117 for (joint = a = 0, ikchan = ikscene->channels;
1118 a < ikscene->numchan && joint < ikscene->numjoint;
1119 a++, ikchan++)
1120 {
1121 pchan = ikchan->pchan;
1122 bone = pchan->bone;
1123
1124 if (ikchan->jointType & IK_TRANSY) {
1125 rot[ikchan->ndof - 1] = bone->length * scale;
1126 }
1127 rot += ikchan->ndof;
1128 joint += ikchan->ndof;
1129 }
1130}
1131
1133 Depsgraph *depsgraph, Scene *blscene, Object *ob, bPoseChannel *pchan, float ctime)
1134{
1135 PoseTree *tree = (PoseTree *)pchan->iktree.first;
1136 PoseTarget *target;
1137 bKinematicConstraint *condata;
1138 bConstraint *polarcon;
1139 bItasc *ikparam;
1140 iTaSC::Armature *arm;
1142 IK_Scene *ikscene;
1143 IK_Channel *ikchan;
1144 KDL::Frame initPose;
1145 Bone *bone;
1146 int a, numtarget;
1147 uint t;
1148 float length;
1149 bool ret = true;
1150 double *rot;
1151 float start[3];
1152
1153 if (tree->totchannel == 0) {
1154 return nullptr;
1155 }
1156
1157 ikscene = new IK_Scene;
1158 ikscene->blscene = blscene;
1159 ikscene->bldepsgraph = depsgraph;
1160 arm = new iTaSC::Armature();
1161 scene = new iTaSC::Scene();
1162 ikscene->channels = new IK_Channel[tree->totchannel];
1163 ikscene->numchan = tree->totchannel;
1164 ikscene->armature = arm;
1165 ikscene->scene = scene;
1166 ikparam = (bItasc *)ob->pose->ikparam;
1167
1168 if (!ikparam) {
1169 /* you must have our own copy */
1170 ikparam = &DefIKParam;
1171 }
1172
1173 if (ikparam->flag & ITASC_SIMULATION) {
1174 /* no cache in animation mode */
1175 ikscene->cache = new iTaSC::Cache();
1176 }
1177
1178 switch (ikparam->solver) {
1179 case ITASC_SOLVER_SDLS:
1180 ikscene->solver = new iTaSC::WSDLSSolver();
1181 break;
1182 case ITASC_SOLVER_DLS:
1183 ikscene->solver = new iTaSC::WDLSSolver();
1184 break;
1185 default:
1186 delete ikscene;
1187 return nullptr;
1188 }
1189 ikscene->blArmature = ob;
1190 /* assume uniform scaling and take Y scale as general scale for the armature */
1191 ikscene->blScale = len_v3(ob->object_to_world().ptr()[1]);
1192 ikscene->blInvScale = (ikscene->blScale < KDL::epsilon) ? 0.0f : 1.0f / ikscene->blScale;
1193
1194 std::string joint;
1195 std::string root("root");
1196 std::string parent;
1197 std::vector<double> weights;
1198 double weight[3];
1199 /* build the array of joints corresponding to the IK chain */
1200 convert_channels(depsgraph, ikscene, tree, ctime);
1201 /* in Blender, the rest pose is always 0 for joints */
1202 BKE_pose_rest(ikscene);
1203 rot = ikscene->jointArray(0);
1204
1205 for (a = 0, ikchan = ikscene->channels; a < tree->totchannel; a++, ikchan++) {
1206 pchan = ikchan->pchan;
1207 bone = pchan->bone;
1208
1210 /* compute the position and rotation of the head from previous segment */
1211 Vector3 *fl = bone->bone_mat;
1212 KDL::Rotation brot(
1213 fl[0][0], fl[1][0], fl[2][0], fl[0][1], fl[1][1], fl[2][1], fl[0][2], fl[1][2], fl[2][2]);
1214 /* if the bone is disconnected, the head is movable in pose mode
1215 * take that into account by using pose matrix instead of bone
1216 * Note that pose is expressed in armature space, convert to previous bone space */
1217 {
1218 float R_parmat[3][3];
1219 float iR_parmat[3][3];
1220 if (pchan->parent) {
1221 copy_m3_m4(R_parmat, pchan->parent->pose_mat);
1222 }
1223 else {
1224 unit_m3(R_parmat);
1225 }
1226 if (pchan->parent) {
1227 sub_v3_v3v3(start, pchan->pose_head, pchan->parent->pose_tail);
1228 }
1229 else if (ikparam->flag & ITASC_TRANSLATE_ROOT_BONES) {
1230 start[0] = start[1] = start[2] = 0.0f;
1231 }
1232 else {
1233 copy_v3_v3(start, pchan->pose_head);
1234 }
1235 invert_m3_m3(iR_parmat, R_parmat);
1236 normalize_m3(iR_parmat);
1237 mul_m3_v3(iR_parmat, start);
1238 }
1239 KDL::Vector bpos(start[0], start[1], start[2]);
1240 bpos *= ikscene->blScale;
1241 KDL::Frame head(brot, bpos);
1242
1243 /* rest pose length of the bone taking scaling into account */
1244 length = bone->length * ikscene->blScale;
1245 parent = (a > 0) ? ikscene->channels[tree->parent[a]].tail : root;
1246 /* first the fixed segment to the bone head */
1247 if (!(ikchan->pchan->bone->flag & BONE_CONNECTED) || head.M.GetRot().Norm() > KDL::epsilon) {
1248 joint = bone->name;
1249 joint += ":H";
1250 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, head);
1251 parent = joint;
1252 }
1253 if (!(ikchan->jointType & IK_TRANSY)) {
1254 /* fixed length, put it in tip */
1255 tip.p[1] = length;
1256 }
1257 joint = bone->name;
1258 weight[0] = (1.0 - pchan->stiffness[0]);
1259 weight[1] = (1.0 - pchan->stiffness[1]);
1260 weight[2] = (1.0 - pchan->stiffness[2]);
1261 switch (ikchan->jointType & ~IK_TRANSY) {
1262 case 0:
1263 /* fixed bone */
1264 joint += ":F";
1265 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, tip);
1266 break;
1267 case IK_XDOF:
1268 /* RX only, get the X rotation */
1269 joint += ":RX";
1270 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0], tip);
1271 weights.push_back(weight[0]);
1272 break;
1273 case IK_YDOF:
1274 /* RY only, get the Y rotation */
1275 joint += ":RY";
1276 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[0], tip);
1277 weights.push_back(weight[1]);
1278 break;
1279 case IK_ZDOF:
1280 /* RZ only, get the Zz rotation */
1281 joint += ":RZ";
1282 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0], tip);
1283 weights.push_back(weight[2]);
1284 break;
1285 case IK_XDOF | IK_YDOF:
1286 joint += ":RX";
1287 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0]);
1288 weights.push_back(weight[0]);
1289 if (ret) {
1290 parent = joint;
1291 joint = bone->name;
1292 joint += ":RY";
1293 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1294 weights.push_back(weight[1]);
1295 }
1296 break;
1297 case IK_SWING:
1298 joint += ":SW";
1299 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0], tip);
1300 weights.push_back(weight[0]);
1301 weights.push_back(weight[2]);
1302 break;
1303 case IK_YDOF | IK_ZDOF:
1304 /* RZ+RY */
1305 joint += ":RZ";
1306 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0]);
1307 weights.push_back(weight[2]);
1308 if (ret) {
1309 parent = joint;
1310 joint = bone->name;
1311 joint += ":RY";
1312 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip);
1313 weights.push_back(weight[1]);
1314 }
1315 break;
1316 case IK_SWING | IK_YDOF:
1317 /* decompose in a Swing+RotY joint */
1318 joint += ":SW";
1319 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0]);
1320 weights.push_back(weight[0]);
1321 weights.push_back(weight[2]);
1322 if (ret) {
1323 parent = joint;
1324 joint = bone->name;
1325 joint += ":RY";
1326 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[2], tip);
1327 weights.push_back(weight[1]);
1328 }
1329 break;
1330 case IK_REVOLUTE:
1331 joint += ":SJ";
1332 ret = arm->addSegment(joint, parent, KDL::Joint::Sphere, rot[0], tip);
1333 weights.push_back(weight[0]);
1334 weights.push_back(weight[1]);
1335 weights.push_back(weight[2]);
1336 break;
1337 }
1338 if (ret && (ikchan->jointType & IK_TRANSY)) {
1339 parent = joint;
1340 joint = bone->name;
1341 joint += ":TY";
1342 ret = arm->addSegment(joint, parent, KDL::Joint::TransY, rot[ikchan->ndof - 1]);
1343 const float ikstretch = pchan->ikstretch * pchan->ikstretch;
1344 /* why invert twice here? */
1345 weight[1] = (1.0 - min_ff(1.0 - ikstretch, 1.0f - 0.001f));
1346 weights.push_back(weight[1]);
1347 }
1348 if (!ret) {
1349 /* error making the armature?? */
1350 break;
1351 }
1352 /* joint points to the segment that correspond to the bone per say */
1353 ikchan->tail = joint;
1354 ikchan->head = parent;
1355 /* in case of error */
1356 ret = false;
1357 if ((ikchan->jointType & IK_XDOF) && (pchan->ikflag & (BONE_IK_XLIMIT | BONE_IK_ROTCTL))) {
1358 joint = bone->name;
1359 joint += ":RX";
1360 if (pchan->ikflag & BONE_IK_XLIMIT) {
1361 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0) {
1362 break;
1363 }
1364 }
1365 if (pchan->ikflag & BONE_IK_ROTCTL) {
1366 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) {
1367 break;
1368 }
1369 }
1370 }
1371 if ((ikchan->jointType & IK_YDOF) && (pchan->ikflag & (BONE_IK_YLIMIT | BONE_IK_ROTCTL))) {
1372 joint = bone->name;
1373 joint += ":RY";
1374 if (pchan->ikflag & BONE_IK_YLIMIT) {
1375 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[1], pchan->limitmax[1]) < 0) {
1376 break;
1377 }
1378 }
1379 if (pchan->ikflag & BONE_IK_ROTCTL) {
1380 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) {
1381 break;
1382 }
1383 }
1384 }
1385 if ((ikchan->jointType & IK_ZDOF) && (pchan->ikflag & (BONE_IK_ZLIMIT | BONE_IK_ROTCTL))) {
1386 joint = bone->name;
1387 joint += ":RZ";
1388 if (pchan->ikflag & BONE_IK_ZLIMIT) {
1389 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[2], pchan->limitmax[2]) < 0) {
1390 break;
1391 }
1392 }
1393 if (pchan->ikflag & BONE_IK_ROTCTL) {
1394 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) {
1395 break;
1396 }
1397 }
1398 }
1399 if ((ikchan->jointType & IK_SWING) &&
1401 {
1402 joint = bone->name;
1403 joint += ":SW";
1404 if (pchan->ikflag & BONE_IK_XLIMIT) {
1405 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0) {
1406 break;
1407 }
1408 }
1409 if (pchan->ikflag & BONE_IK_ZLIMIT) {
1410 if (arm->addLimitConstraint(joint, 1, pchan->limitmin[2], pchan->limitmax[2]) < 0) {
1411 break;
1412 }
1413 }
1414 if (pchan->ikflag & BONE_IK_ROTCTL) {
1415 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) {
1416 break;
1417 }
1418 }
1419 }
1420 if ((ikchan->jointType & IK_REVOLUTE) && (pchan->ikflag & BONE_IK_ROTCTL)) {
1421 joint = bone->name;
1422 joint += ":SJ";
1423 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) {
1424 break;
1425 }
1426 }
1427 /* no error, so restore */
1428 ret = true;
1429 rot += ikchan->ndof;
1430 }
1431 if (!ret) {
1432 delete ikscene;
1433 return nullptr;
1434 }
1435 /* for each target, we need to add an end effector in the armature */
1436 for (numtarget = 0, polarcon = nullptr, ret = true, target = (PoseTarget *)tree->targets.first;
1437 target;
1438 target = (PoseTarget *)target->next)
1439 {
1440 condata = (bKinematicConstraint *)target->con->data;
1441 pchan = tree->pchan[target->tip];
1442
1443 if (is_cartesian_constraint(target->con)) {
1444 /* add the end effector */
1445 IK_Target *iktarget = new IK_Target();
1446 ikscene->targets.push_back(iktarget);
1447 iktarget->ee = arm->addEndEffector(ikscene->channels[target->tip].tail);
1448 if (iktarget->ee == -1) {
1449 ret = false;
1450 break;
1451 }
1452 /* initialize all the fields that we can set at this time */
1453 iktarget->blenderConstraint = target->con;
1454 iktarget->channel = target->tip;
1455 iktarget->simulation = (ikparam->flag & ITASC_SIMULATION);
1456 iktarget->rootChannel = ikscene->channels[0].pchan;
1457 iktarget->owner = ob;
1458 iktarget->targetName = pchan->bone->name;
1459 iktarget->targetName += ":T:";
1460 iktarget->targetName += target->con->name;
1461 iktarget->constraintName = pchan->bone->name;
1462 iktarget->constraintName += ":C:";
1463 iktarget->constraintName += target->con->name;
1464 numtarget++;
1465 if (condata->poletar) {
1466 /* this constraint has a polar target */
1467 polarcon = target->con;
1468 }
1469 }
1470 }
1471 /* deal with polar target if any */
1472 if (numtarget == 1 && polarcon) {
1473 ikscene->polarConstraint = polarcon;
1474 }
1475 /* we can now add the armature
1476 * the armature is based on a moving frame.
1477 * initialize with the correct position in case there is no cache */
1478 base_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, ikscene);
1479 ikscene->base = new iTaSC::MovingFrame(initPose);
1480 ikscene->base->setCallback(base_callback, ikscene);
1481 std::string armname;
1482 armname = ob->id.name;
1483 armname += ":B";
1484 ret = scene->addObject(armname, ikscene->base);
1485 armname = ob->id.name;
1486 armname += ":AR";
1487 if (ret) {
1488 ret = scene->addObject(armname, ikscene->armature, ikscene->base);
1489 }
1490 if (!ret) {
1491 delete ikscene;
1492 return nullptr;
1493 }
1494 /* set the weight */
1495 e_matrix &Wq = arm->getWq();
1496 assert(Wq.cols() == int(weights.size()));
1497 for (int q = 0; q < Wq.cols(); q++) {
1498 Wq(q, q) = weights[q];
1499 }
1500 /* get the inverse rest pose frame of the base to compute relative rest pose of end effectors
1501 * this is needed to handle the enforce parameter
1502 * ikscene->pchan[0] is the root channel of the tree
1503 * if it has no parent, then it's just the identify Frame */
1504 float invBaseFrame[4][4];
1505 pchan = ikscene->channels[0].pchan;
1506 if (pchan->parent) {
1507 /* it has a parent, get the pose matrix from it */
1508 float baseFrame[4][4];
1509 pchan = pchan->parent;
1510 copy_m4_m4(baseFrame, pchan->bone->arm_mat);
1511 /* move to the tail and scale to get rest pose of armature base */
1512 copy_v3_v3(baseFrame[3], pchan->bone->arm_tail);
1513 invert_m4_m4(invBaseFrame, baseFrame);
1514 }
1515 else {
1516 unit_m4(invBaseFrame);
1517 }
1518 /* finally add the constraint */
1519 for (t = 0; t < ikscene->targets.size(); t++) {
1520 IK_Target *iktarget = ikscene->targets[t];
1521 iktarget->blscene = blscene;
1522 iktarget->bldepsgraph = depsgraph;
1523 condata = (bKinematicConstraint *)iktarget->blenderConstraint->data;
1524 pchan = tree->pchan[iktarget->channel];
1525 uint controltype, bone_count;
1526 double bone_length;
1527 float mat[4][4];
1528
1529 /* add the end effector
1530 * estimate the average bone length, used to clamp feedback error */
1531 for (bone_count = 0, bone_length = 0.0f, a = iktarget->channel; a >= 0;
1532 a = tree->parent[a], bone_count++)
1533 {
1534 bone_length += ikscene->blScale * tree->pchan[a]->bone->length;
1535 }
1536 bone_length /= bone_count;
1537
1538 /* store the rest pose of the end effector to compute enforce target */
1539 copy_m4_m4(mat, pchan->bone->arm_mat);
1540 copy_v3_v3(mat[3], pchan->bone->arm_tail);
1541 /* get the rest pose relative to the armature base */
1542 mul_m4_m4m4(iktarget->eeRest, invBaseFrame, mat);
1543 iktarget->eeBlend = (!ikscene->polarConstraint && condata->type == CONSTRAINT_IK_COPYPOSE) ?
1544 true :
1545 false;
1546 /* use target_callback to make sure the initPose includes enforce coefficient */
1547 target_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, iktarget);
1548 iktarget->target = new iTaSC::MovingFrame(initPose);
1549 iktarget->target->setCallback(target_callback, iktarget);
1550 ret = scene->addObject(iktarget->targetName, iktarget->target);
1551 if (!ret) {
1552 break;
1553 }
1554
1555 switch (condata->type) {
1557 controltype = 0;
1558 if (condata->flag & CONSTRAINT_IK_ROT) {
1559 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_X)) {
1560 controltype |= iTaSC::CopyPose::CTL_ROTATIONX;
1561 }
1562 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Y)) {
1563 controltype |= iTaSC::CopyPose::CTL_ROTATIONY;
1564 }
1565 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Z)) {
1566 controltype |= iTaSC::CopyPose::CTL_ROTATIONZ;
1567 }
1568 }
1569 if (condata->flag & CONSTRAINT_IK_POS) {
1570 if (!(condata->flag & CONSTRAINT_IK_NO_POS_X)) {
1571 controltype |= iTaSC::CopyPose::CTL_POSITIONX;
1572 }
1573 if (!(condata->flag & CONSTRAINT_IK_NO_POS_Y)) {
1574 controltype |= iTaSC::CopyPose::CTL_POSITIONY;
1575 }
1576 if (!(condata->flag & CONSTRAINT_IK_NO_POS_Z)) {
1577 controltype |= iTaSC::CopyPose::CTL_POSITIONZ;
1578 }
1579 }
1580 if (controltype) {
1581 iktarget->constraint = new iTaSC::CopyPose(controltype, controltype, bone_length);
1582 /* set the gain */
1583 if (controltype & iTaSC::CopyPose::CTL_POSITION) {
1586 }
1587 if (controltype & iTaSC::CopyPose::CTL_ROTATION) {
1590 }
1591 iktarget->constraint->registerCallback(copypose_callback, iktarget);
1592 iktarget->errorCallback = copypose_error;
1593 iktarget->controlType = controltype;
1594 /* add the constraint */
1595 if (condata->flag & CONSTRAINT_IK_TARGETAXIS) {
1596 ret = scene->addConstraintSet(iktarget->constraintName,
1597 iktarget->constraint,
1598 iktarget->targetName,
1599 armname,
1600 "",
1601 ikscene->channels[iktarget->channel].tail);
1602 }
1603 else {
1604 ret = scene->addConstraintSet(iktarget->constraintName,
1605 iktarget->constraint,
1606 armname,
1607 iktarget->targetName,
1608 ikscene->channels[iktarget->channel].tail);
1609 }
1610 }
1611 break;
1613 iktarget->constraint = new iTaSC::Distance(bone_length);
1616 iktarget->constraint->registerCallback(distance_callback, iktarget);
1617 iktarget->errorCallback = distance_error;
1618 /* we can update the weight on each substep */
1619 iktarget->constraint->substep(true);
1620 /* add the constraint */
1621 ret = scene->addConstraintSet(iktarget->constraintName,
1622 iktarget->constraint,
1623 armname,
1624 iktarget->targetName,
1625 ikscene->channels[iktarget->channel].tail);
1626 break;
1627 }
1628 if (!ret) {
1629 break;
1630 }
1631 }
1632 if (!ret || !scene->addCache(ikscene->cache) || !scene->addSolver(ikscene->solver) ||
1633 !scene->initialize())
1634 {
1635 delete ikscene;
1636 ikscene = nullptr;
1637 }
1638 return ikscene;
1639}
1640
1641static void create_scene(Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime)
1642{
1643 /* create the IK scene */
1644 LISTBASE_FOREACH (bPoseChannel *, pchan, &ob->pose->chanbase) {
1645 /* by construction there is only one tree */
1646 PoseTree *tree = (PoseTree *)pchan->iktree.first;
1647 if (tree) {
1648 IK_Data *ikdata = get_ikdata(ob->pose);
1649 /* convert tree in iTaSC::Scene */
1650 IK_Scene *ikscene = convert_tree(depsgraph, scene, ob, pchan, ctime);
1651 if (ikscene) {
1652 ikscene->next = ikdata->first;
1653 ikdata->first = ikscene;
1654 }
1655 /* delete the trees once we are done */
1656 while (tree) {
1657 BLI_remlink(&pchan->iktree, tree);
1658 BLI_freelistN(&tree->targets);
1659 if (tree->pchan) {
1660 MEM_freeN(tree->pchan);
1661 }
1662 if (tree->parent) {
1663 MEM_freeN(tree->parent);
1664 }
1665 if (tree->basis_change) {
1666 MEM_freeN(tree->basis_change);
1667 }
1668 MEM_freeN(tree);
1669 tree = (PoseTree *)pchan->iktree.first;
1670 }
1671 }
1672 }
1673}
1674
1675/* returns 1 if scaling has changed and tree must be reinitialized */
1676static int init_scene(Object *ob)
1677{
1678 /* check also if scaling has changed */
1679 float scale = len_v3(ob->object_to_world().ptr()[1]);
1680 IK_Scene *scene;
1681
1682 if (ob->pose->ikdata) {
1683 for (scene = ((IK_Data *)ob->pose->ikdata)->first; scene != nullptr; scene = scene->next) {
1684 if (fabs(scene->blScale - scale) > KDL::epsilon) {
1685 return 1;
1686 }
1687 scene->channels[0].pchan->flag |= POSE_IKTREE;
1688 }
1689 }
1690 return 0;
1691}
1692
1693static void execute_scene(Depsgraph *depsgraph,
1694 Scene *blscene,
1695 IK_Scene *ikscene,
1696 bItasc *ikparam,
1697 float ctime,
1698 float frtime)
1699{
1700 int i;
1701 IK_Channel *ikchan;
1702 if (ikparam->flag & ITASC_SIMULATION) {
1703 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ikchan++) {
1704 /* In simulation mode we don't allow external constraint to change our bones,
1705 * mark the channel done also tell Blender that this channel is part of IK tree.
1706 * Cleared on each BKE_pose_where_is() */
1707 ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1708 ikchan->jointValid = 0;
1709 }
1710 }
1711 else {
1712 /* in animation mode, we must get the bone position from action and constraints */
1713 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ikchan++) {
1714 if (!(ikchan->pchan->flag & POSE_DONE)) {
1716 depsgraph, blscene, ikscene->blArmature, ikchan->pchan, ctime, true);
1717 }
1718 /* tell blender that this channel was controlled by IK,
1719 * it's cleared on each BKE_pose_where_is() */
1720 ikchan->pchan->flag |= (POSE_DONE | POSE_CHAIN);
1721 ikchan->jointValid = 0;
1722 }
1723 }
1724 /* only run execute the scene if at least one of our target is enabled */
1725 for (i = ikscene->targets.size(); i > 0; i--) {
1726 IK_Target *iktarget = ikscene->targets[i - 1];
1727 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF)) {
1728 break;
1729 }
1730 }
1731 if (i == 0 && ikscene->armature->getNrOfConstraints() == 0) {
1732 /* all constraint disabled */
1733 return;
1734 }
1735
1736 /* compute timestep */
1737 double timestamp = ctime * frtime + 2147483.648;
1738 double timestep = frtime;
1739 bool reiterate = (ikparam->flag & ITASC_REITERATION) ? true : false;
1740 int numstep = (ikparam->flag & ITASC_AUTO_STEP) ? 0 : ikparam->numstep;
1741 bool simulation = true;
1742
1743 if (ikparam->flag & ITASC_SIMULATION) {
1744 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1745 }
1746 else {
1747 /* in animation mode we start from the pose after action and constraint */
1748 convert_pose(ikscene);
1749 ikscene->armature->setJointArray(ikscene->jointArray);
1750 /* and we don't handle velocity */
1751 reiterate = true;
1752 simulation = false;
1753 /* time is virtual, so take fixed value for velocity parameters (see itasc_update_param)
1754 * and choose 1s timestep to allow having velocity parameters in radiant */
1755 timestep = 1.0;
1756 /* use auto setup to let the solver test the variation of the joints */
1757 numstep = 0;
1758 }
1759
1760 if (ikscene->cache && !reiterate && simulation) {
1761 iTaSC::CacheTS sts, cts;
1762 sts = cts = (iTaSC::CacheTS)std::round(timestamp * 1000.0);
1763 if (ikscene->cache->getPreviousCacheItem(ikscene->armature, 0, &cts) == nullptr || cts == 0) {
1764 /* the cache is empty before this time, reiterate */
1765 if (ikparam->flag & ITASC_INITIAL_REITERATION) {
1766 reiterate = true;
1767 }
1768 }
1769 else {
1770 /* can take the cache as a start point. */
1771 sts -= cts;
1772 timestep = sts / 1000.0;
1773 }
1774 }
1775 /* don't cache if we are reiterating because we don't want to destroy the cache unnecessarily */
1776 ikscene->scene->update(timestamp, timestep, numstep, false, !reiterate, simulation);
1777 if (reiterate) {
1778 /* how many times do we reiterate? */
1779 for (i = 0; i < ikparam->numiter; i++) {
1780 if (ikscene->armature->getMaxJointChange() < ikparam->precision ||
1781 ikscene->armature->getMaxEndEffectorChange() < ikparam->precision)
1782 {
1783 break;
1784 }
1785 ikscene->scene->update(timestamp, timestep, numstep, true, false, simulation);
1786 }
1787 if (simulation) {
1788 /* one more fake iteration to cache */
1789 ikscene->scene->update(timestamp, 0.0, 1, true, true, true);
1790 }
1791 }
1792 /* compute constraint error */
1793 for (i = ikscene->targets.size(); i > 0; i--) {
1794 IK_Target *iktarget = ikscene->targets[i - 1];
1795 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF) && iktarget->constraint) {
1796 uint nvalues;
1797 const iTaSC::ConstraintValues *values;
1798 values = iktarget->constraint->getControlParameters(&nvalues);
1799 iktarget->errorCallback(values, nvalues, iktarget);
1800 }
1801 }
1802 /* Apply result to bone:
1803 * walk the ikscene->channels
1804 * for each, get the Frame of the joint corresponding to the bone relative to its parent
1805 * combine the parent and the joint frame to get the frame relative to armature
1806 * a backward translation of the bone length gives the head
1807 * if TY, compute the scale as the ratio of the joint length with rest pose length */
1808 iTaSC::Armature *arm = ikscene->armature;
1809 KDL::Frame frame;
1810 double q_rest[3], q[3];
1811 const KDL::Joint *joint;
1812 const KDL::Frame *tip;
1813 bPoseChannel *pchan;
1814 float scale;
1815 float length;
1816 float yaxis[3];
1817 for (i = 0, ikchan = ikscene->channels; i < ikscene->numchan; i++, ikchan++) {
1818 if (i == 0) {
1819 if (!arm->getRelativeFrame(frame, ikchan->tail)) {
1820 break;
1821 }
1822 /* this frame is relative to base, make it relative to object */
1823 ikchan->frame = ikscene->baseFrame * frame;
1824 }
1825 else {
1826 if (!arm->getRelativeFrame(frame, ikchan->tail, ikscene->channels[ikchan->parent].tail)) {
1827 break;
1828 }
1829 /* combine with parent frame to get frame relative to object */
1830 ikchan->frame = ikscene->channels[ikchan->parent].frame * frame;
1831 }
1832 /* ikchan->frame is the tail frame relative to object
1833 * get bone length */
1834 if (!arm->getSegment(ikchan->tail, 3, joint, q_rest[0], q[0], tip)) {
1835 break;
1836 }
1837 if (joint->getType() == KDL::Joint::TransY) {
1838 /* stretch bones have a TY joint, compute the scale */
1839 scale = float(q[0] / q_rest[0]);
1840 /* the length is the joint itself */
1841 length = float(q[0]);
1842 }
1843 else {
1844 scale = 1.0f;
1845 /* for fixed bone, the length is in the tip (always along Y axis) */
1846 length = tip->p(1);
1847 }
1848 /* ready to compute the pose mat */
1849 pchan = ikchan->pchan;
1850 /* tail mat */
1851 ikchan->frame.getValue(&pchan->pose_mat[0][0]);
1852 /* the scale of the object was included in the ik scene, take it out now
1853 * because the pose channels are relative to the object */
1854 mul_v3_fl(pchan->pose_mat[3], ikscene->blInvScale);
1855 length *= ikscene->blInvScale;
1856 copy_v3_v3(pchan->pose_tail, pchan->pose_mat[3]);
1857 /* shift to head */
1858 copy_v3_v3(yaxis, pchan->pose_mat[1]);
1859 mul_v3_fl(yaxis, length);
1860 sub_v3_v3v3(pchan->pose_mat[3], pchan->pose_mat[3], yaxis);
1861 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
1862 /* add scale */
1863 mul_v3_fl(pchan->pose_mat[0], scale);
1864 mul_v3_fl(pchan->pose_mat[1], scale);
1865 mul_v3_fl(pchan->pose_mat[2], scale);
1866 }
1867 if (i < ikscene->numchan) {
1868 /* big problem */
1869 }
1870}
1871
1872/* -------------------------------------------------------------------- */
1876void itasc_initialize_tree(Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime)
1877{
1878 int count = 0;
1879
1880 if (ob->pose->ikdata != nullptr && !(ob->pose->flag & POSE_WAS_REBUILT)) {
1881 if (!init_scene(ob)) {
1882 return;
1883 }
1884 }
1885 /* first remove old scene */
1887 /* we should handle all the constraint and mark them all disabled
1888 * for blender but we'll start with the IK constraint alone */
1889 LISTBASE_FOREACH (bPoseChannel *, pchan, &ob->pose->chanbase) {
1890 if (pchan->constflag & PCHAN_HAS_IK) {
1891 count += initialize_scene(ob, pchan);
1892 }
1893 }
1894 /* if at least one tree, create the scenes from the PoseTree stored in the channels
1895 * postpone until execute_tree: this way the pose constraint are included */
1896 if (count) {
1897 create_scene(depsgraph, scene, ob, ctime);
1898 }
1900 /* make sure we don't rebuilt until the user changes something important */
1901 ob->pose->flag &= ~POSE_WAS_REBUILT;
1902}
1903
1905 Depsgraph *depsgraph, Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
1906{
1907 if (ob->pose->ikdata) {
1908 IK_Data *ikdata = (IK_Data *)ob->pose->ikdata;
1909 bItasc *ikparam = (bItasc *)ob->pose->ikparam;
1910 /* we need default parameters */
1911 if (!ikparam) {
1912 ikparam = &DefIKParam;
1913 }
1914
1915 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1916 if (ikscene->channels[0].pchan == pchan_root) {
1917 float timestep = scene->r.frs_sec_base / scene->r.frs_sec;
1918 execute_scene(depsgraph, scene, ikscene, ikparam, ctime, timestep);
1919 break;
1920 }
1921 }
1922 }
1923}
1924
1925void itasc_release_tree(Scene * /*scene*/, Object * /*ob*/, float /*ctime*/)
1926{
1927 /* not used for iTaSC */
1928}
1929
1931{
1932 if (pose->ikdata) {
1933 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1934 for (IK_Scene *scene = ikdata->first; scene; scene = ikdata->first) {
1935 ikdata->first = scene->next;
1936 delete scene;
1937 }
1938 MEM_freeN(ikdata);
1939 pose->ikdata = nullptr;
1940 }
1941}
1942
1944{
1945 if (pose->ikdata) {
1946 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1947 for (IK_Scene *scene = ikdata->first; scene; scene = scene->next) {
1948 if (scene->cache) {
1949 /* clear all cache but leaving the timestamp 0 (=rest pose) */
1950 scene->cache->clearCacheFrom(nullptr, 1);
1951 }
1952 }
1953 }
1954}
1955
1957{
1958 if (pose->ikdata && pose->ikparam) {
1959 IK_Data *ikdata = (IK_Data *)pose->ikdata;
1960 bItasc *ikparam = (bItasc *)pose->ikparam;
1961 for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) {
1962 double armlength = ikscene->armature->getArmLength();
1963 ikscene->solver->setParam(iTaSC::Solver::DLS_LAMBDA_MAX, ikparam->dampmax * armlength);
1964 ikscene->solver->setParam(iTaSC::Solver::DLS_EPSILON, ikparam->dampeps * armlength);
1965 if (ikparam->flag & ITASC_SIMULATION) {
1966 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, ikparam->minstep);
1967 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, ikparam->maxstep);
1968 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel);
1969 ikscene->armature->setControlParameter(
1971 }
1972 else {
1973 /* in animation mode timestep is 1s by convention => qmax becomes radiant and feedback
1974 * becomes fraction of error gap corrected in one iteration. */
1975 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, 1.0);
1976 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, 1.0);
1977 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, 0.52);
1978 ikscene->armature->setControlParameter(
1980 }
1981 }
1982 }
1983}
1984
1986{
1988
1989 /* only for IK constraint */
1990 if (cons->type != CONSTRAINT_TYPE_KINEMATIC || data == nullptr) {
1991 return;
1992 }
1993
1994 switch (data->type) {
1997 /* cartesian space constraint */
1998 break;
1999 }
2000}
2001
Blender kernel action and pose functionality.
void BKE_pose_itasc_init(bItasc *itasc)
void BKE_pose_where_is_bone(Depsgraph *depsgraph, Scene *scene, Object *ob, bPoseChannel *pchan, float ctime, bool do_extra)
Definition armature.cc:2877
void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, struct Scene *scene, struct bConstraint *con, int index, short ownertype, void *ownerdata, float mat[4][4], float ctime)
BLI_INLINE bool BLI_listbase_is_empty(const struct ListBase *lb)
#define LISTBASE_FOREACH(type, var, list)
void void BLI_freelistN(struct ListBase *listbase) ATTR_NONNULL(1)
Definition listbase.cc:496
void BLI_addtail(struct ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:110
void BLI_remlink(struct ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:130
MINLINE float min_ff(float a, float b)
void mul_m3_v3(const float M[3][3], float r[3])
void mul_m4_m4m4(float R[4][4], const float A[4][4], const float B[4][4])
void unit_m3(float m[3][3])
void blend_m4_m4m4(float out[4][4], const float dst[4][4], const float src[4][4], float srcweight)
void copy_m3_m4(float m1[3][3], const float m2[4][4])
void mul_m4_m4m3(float R[4][4], const float A[4][4], const float B[3][3])
bool invert_m3_m3(float inverse[3][3], const float mat[3][3])
void unit_m4(float m[4][4])
Definition rct.c:1127
void normalize_m3(float R[3][3]) ATTR_NONNULL()
#define mul_m4_series(...)
void copy_m4_m4(float m1[4][4], const float m2[4][4])
bool invert_m4_m4(float inverse[4][4], const float mat[4][4])
void normalize_m4(float R[4][4]) ATTR_NONNULL()
void quat_to_mat3(float m[3][3], const float q[4])
float normalize_qt(float q[4])
void eulO_to_mat3(float M[3][3], const float e[3], short order)
void axis_angle_to_mat3(float R[3][3], const float axis[3], float angle)
MINLINE float len_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
MINLINE void mul_v3_fl(float r[3], float f)
MINLINE void copy_v3_v3(float r[3], const float a[3])
MINLINE float len_v3(const float a[3]) ATTR_WARN_UNUSED_RESULT
unsigned short ushort
unsigned int uint
#define CONSTRAINT_ID_ALL
@ ITASC_SOLVER_SDLS
@ ITASC_SOLVER_DLS
@ ROT_MODE_AXISANGLE
@ ITASC_REITERATION
@ ITASC_AUTO_STEP
@ ITASC_TRANSLATE_ROOT_BONES
@ ITASC_SIMULATION
@ ITASC_INITIAL_REITERATION
@ BONE_IK_ZLIMIT
@ BONE_IK_NO_YDOF_TEMP
@ BONE_IK_XLIMIT
@ BONE_IK_NO_XDOF_TEMP
@ BONE_IK_NO_ZDOF
@ BONE_IK_ROTCTL
@ BONE_IK_NO_ZDOF_TEMP
@ BONE_IK_YLIMIT
@ BONE_IK_NO_YDOF
@ BONE_IK_NO_XDOF
@ PCHAN_HAS_IK
@ POSE_DONE
@ POSE_IKTREE
@ POSE_CHAIN
@ POSE_WAS_REBUILT
@ BONE_CONNECTED
@ CONSTRAINT_OFF
@ CONSTRAINT_DISABLE
@ CONSTRAINT_IK_ROT
@ CONSTRAINT_IK_NO_ROT_X
@ CONSTRAINT_IK_TARGETAXIS
@ CONSTRAINT_IK_NO_POS_Z
@ CONSTRAINT_IK_NO_POS_Y
@ CONSTRAINT_IK_NO_ROT_Y
@ CONSTRAINT_IK_POS
@ CONSTRAINT_IK_NO_POS_X
@ CONSTRAINT_IK_NO_ROT_Z
@ CONSTRAINT_IK_AUTO
@ CONSTRAINT_IK_STRETCH
@ CONSTRAINT_IK_TIP
@ CONSTRAINT_TYPE_KINEMATIC
@ CONSTRAINT_OBTYPE_OBJECT
@ LIMITDIST_INSIDE
@ LIMITDIST_OUTSIDE
@ CONSTRAINT_IK_COPYPOSE
@ CONSTRAINT_IK_DISTANCE
Object is a sort of wrapper for general info.
@ OB_ARMATURE
#define X
#define Y
Read Guarded memory(de)allocation.
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
SIMD_FORCE_INLINE btScalar length() const
Return the length of the vector.
Definition btVector3.h:257
represents a frame transformation in 3D space (rotation + translation)
Definition frames.hpp:526
Rotation M
Orientation of the Frame.
Definition frames.hpp:529
void setValue(float *oglmat)
Definition frames.inl:724
void getValue(float *oglmat) const
Definition frames.inl:732
Vector p
origine of the Frame
Definition frames.hpp:528
void resize(unsigned int newSize)
Definition jntarray.cpp:66
This class encapsulates a simple joint, that is with one parameterized degree of freedom and with sca...
Definition joint.hpp:43
const JointType & getType() const
Definition joint.hpp:88
represents rotations in 3 dimensional space.
Definition frames.hpp:299
Vector GetRot() const
Definition frames.cpp:297
Rotation Inverse() const
Gives back the inverse rotation matrix of *this.
Definition frames.inl:641
Vector UnitY() const
Access to the underlying unitvectors of the rotation matrix.
Definition frames.hpp:479
Vector UnitZ() const
Access to the underlying unitvectors of the rotation matrix.
Definition frames.hpp:491
Vector UnitX() const
Access to the underlying unitvectors of the rotation matrix.
Definition frames.hpp:467
static Rotation RotX(double angle)
The Rot... static functions give the value of the appropriate rotation matrix back.
Definition frames.inl:609
Vector2 GetXZRot() const
Definition frames.cpp:330
void setValue(float *oglmat)
Definition frames.inl:656
static Rotation RotY(double angle)
The Rot... static functions give the value of the appropriate rotation matrix back.
Definition frames.inl:614
static Rotation RotZ(double angle)
The Rot... static functions give the value of the appropriate rotation matrix back.
Definition frames.inl:619
void GetValue(double *xy) const
store vector components in array
Definition frames.inl:786
A concrete implementation of a 3 dimensional vector class.
Definition frames.hpp:143
void GetValue(double *xyz) const
store vector components in array
Definition frames.inl:51
double Norm() const
Definition frames.cpp:115
bool addSegment(const std::string &segment_name, const std::string &hook_name, const Joint &joint, const double &q_rest, const Frame &f_tip=F_identity, const Inertia &M=Inertia::Zero())
Definition Armature.cpp:232
int addLimitConstraint(const std::string &segment_name, unsigned int dof, double _min, double _max)
Definition Armature.cpp:336
bool getRelativeFrame(Frame &result, const std::string &segment_name, const std::string &base_name=m_root)
Definition Armature.cpp:662
virtual const Frame & getPose(const unsigned int end_effector)
Definition Armature.cpp:655
int addConstraint(const std::string &segment_name, ConstraintCallback _function, void *_param=NULL, bool _freeParam=false, bool _substep=false)
Definition Armature.cpp:298
virtual int addEndEffector(const std::string &name)
Definition Armature.cpp:355
bool getSegment(const std::string &segment_name, const unsigned int q_size, const Joint *&p_joint, double &q_rest, double &q, const Frame *&p_tip)
Definition Armature.cpp:249
double getMaxEndEffectorChange()
Definition Armature.cpp:279
virtual bool setJointArray(const KDL::JntArray &joints)
Definition Armature.cpp:428
double getMaxJointChange()
Definition Armature.cpp:265
const void * getPreviousCacheItem(const void *device, int channel, CacheTS *timestamp)
Definition Cache.cpp:546
bool setControlParameter(int id, ConstraintAction action, double value, double timestep=0.0)
void substep(bool _substep)
virtual EIGEN_MAKE_ALIGNED_OPERATOR_NEW bool registerCallback(ConstraintCallback _function, void *_param)
virtual const ConstraintValues * getControlParameters(unsigned int *_nvalues)=0
virtual const unsigned int getNrOfConstraints()
virtual e_matrix & getWq()
bool setCallback(MovingFrameCallback _function, void *_param)
virtual const KDL::Frame & getPose(const unsigned int end_effector=0)
Definition Object.hpp:38
bool update(double timestamp, double timestep, unsigned int numsubstep=1, bool reiterate=false, bool cache=true, bool interpolate=true)
Definition Scene.cpp:310
virtual void setParam(SolverParam param, double value)=0
const Depsgraph * depsgraph
KDTree_3d * tree
draw_view in_light_buf[] float
#define rot(x, k)
#define e_matrix
IMETHOD void SetToZero(Vector &v)
Definition frames.inl:1104
int count
void itasc_clear_data(bPose *pose)
static bItasc DefIKParam
static void RemoveEulerAngleFromMatrix(KDL::Rotation &R, double angle, int axis)
static void copypose_error(const iTaSC::ConstraintValues *values, uint, IK_Target *iktarget)
static int init_scene(Object *ob)
static bool copypose_callback(const iTaSC::Timestamp &, iTaSC::ConstraintValues *const _values, uint, void *_param)
float[4] Vector4
#define ANIM_FEEDBACK
void itasc_update_param(bPose *pose)
static void distance_error(const iTaSC::ConstraintValues *values, uint, IK_Target *iktarget)
static void BKE_pose_rest(IK_Scene *ikscene)
static int initialize_chain(Object *, bPoseChannel *pchan_tip, bConstraint *con)
void itasc_initialize_tree(Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime)
static void convert_pose(IK_Scene *ikscene)
static bool distance_callback(const iTaSC::Timestamp &timestamp, iTaSC::ConstraintValues *const _values, uint, void *_param)
static bool joint_callback(const iTaSC::Timestamp &, iTaSC::ConstraintValues *const _values, uint _nvalues, void *_param)
static bool is_cartesian_constraint(bConstraint *)
static int initialize_scene(Object *ob, bPoseChannel *pchan_tip)
IK_SegmentFlag
@ IK_ZDOF
@ IK_REVOLUTE
@ IK_SWING
@ IK_XDOF
@ IK_YDOF
@ IK_TRANSY
static IK_Data * get_ikdata(bPose *pose)
void itasc_clear_cache(bPose *pose)
void itasc_execute_tree(Depsgraph *depsgraph, Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
static bool constraint_valid(bConstraint *con)
void(*)(const iTaSC::ConstraintValues *values, uint nvalues, IK_Target *iktarget) ErrorCallback
static void execute_scene(Depsgraph *depsgraph, Scene *blscene, IK_Scene *ikscene, bItasc *ikparam, float ctime, float frtime)
static bool base_callback(const iTaSC::Timestamp &timestamp, const iTaSC::Frame &, iTaSC::Frame &next, void *param)
static IK_Scene * convert_tree(Depsgraph *depsgraph, Scene *blscene, Object *ob, bPoseChannel *pchan, float ctime)
static void GetJointRotation(KDL::Rotation &boneRot, int type, double *rot)
static double ComputeTwist(const KDL::Rotation &R)
void itasc_test_constraint(Object *, bConstraint *cons)
static void create_scene(Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime)
IK_SegmentAxis
@ IK_X
@ IK_TRANS_X
@ IK_Y
@ IK_TRANS_Y
@ IK_TRANS_Z
@ IK_Z
static bool target_callback(const iTaSC::Timestamp &, const iTaSC::Frame &, iTaSC::Frame &next, void *param)
void itasc_release_tree(Scene *, Object *, float)
static double EulerAngleFromMatrix(const KDL::Rotation &R, int axis)
static int convert_channels(Depsgraph *depsgraph, IK_Scene *ikscene, PoseTree *tree, float ctime)
void MEM_freeN(void *vmemh)
Definition mallocn.cc:105
void *(* MEM_callocN)(size_t len, const char *str)
Definition mallocn.cc:42
ccl_device_inline float2 fabs(const float2 a)
static ulong * next
#define T
#define R
static void error(const char *str)
INLINE Rall1d< T, V, S > sin(const Rall1d< T, V, S > &arg)
Definition rall1d.h:311
INLINE Rall1d< T, V, S > sqrt(const Rall1d< T, V, S > &arg)
Definition rall1d.h:367
double sign(double arg)
Definition utility.h:250
INLINE Rall1d< T, V, S > atan2(const Rall1d< T, V, S > &y, const Rall1d< T, V, S > &x)
Definition rall1d.h:429
INLINE Rall1d< T, V, S > sqr(const Rall1d< T, V, S > &arg)
Definition rall1d.h:351
const double PI
the value of pi
Definition utility.cpp:19
INLINE Rall1d< T, V, S > cos(const Rall1d< T, V, S > &arg)
Definition rall1d.h:319
Vector Normalize(const Vector &, double eps=epsilon)
double epsilon
default precision while comparing with Equal(..,..) functions. Initialized at 0.0000001.
Definition utility.cpp:22
const Frame F_identity
unsigned int CacheTS
Definition Cache.hpp:33
return ret
char name[64]
float arm_tail[3]
float arm_mat[4][4]
float bone_mat[3][3]
char name[66]
Definition DNA_ID.h:425
Object * owner
bPoseChannel * pchan
std::string tail
KDL::Frame frame
std::string head
double jointValue[4]
struct IK_Scene * first
Object * blArmature
KDL::Frame baseFrame
iTaSC::Solver * solver
KDL::JntArray jointArray
Scene * blscene
IK_Scene * next
float blScale
iTaSC::MovingFrame * base
iTaSC::Cache * cache
iTaSC::Armature * armature
std::vector< IK_Target * > targets
iTaSC::Scene * scene
float blInvScale
Depsgraph * bldepsgraph
bConstraint * polarConstraint
IK_Channel * channels
bConstraint * blenderConstraint
std::string targetName
Scene * blscene
std::string constraintName
ushort controlType
iTaSC::ConstraintSet * constraint
bPoseChannel * rootChannel
ErrorCallback errorCallback
iTaSC::MovingFrame * target
short channel
float eeRest[4][4]
bool simulation
Object * owner
Depsgraph * bldepsgraph
void * first
struct bPose * pose
struct bConstraint * next
float precision
struct Bone * bone
struct bPoseChannel * parent
struct ListBase iktree
float pose_mat[4][4]
ListBase chanbase
void * ikdata
void * ikparam
struct ConstraintSingleValue * values
unsigned int substep
Definition Cache.hpp:41
unsigned int update
Definition Cache.hpp:44
uint8_t flag
Definition wm_window.cc:138