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