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