Blender V2.61 - r43446
|
00001 /* 00002 * ***** BEGIN GPL LICENSE BLOCK ***** 00003 * 00004 * This program is free software; you can redistribute it and/or 00005 * modify it under the terms of the GNU General Public License 00006 * as published by the Free Software Foundation; either version 2 00007 * of the License, or (at your option) any later version. 00008 * 00009 * This program is distributed in the hope that it will be useful, 00010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00012 * GNU General Public License for more details. 00013 * 00014 * You should have received a copy of the GNU General Public License 00015 * along with this program; if not, write to the Free Software Foundation, 00016 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 00017 * 00018 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. 00019 * All rights reserved. 00020 * 00021 * The Original Code is: all of this file. 00022 * 00023 * Original author: Benoit Bolsee 00024 * Contributor(s): 00025 * 00026 * ***** END GPL LICENSE BLOCK ***** 00027 */ 00028 00034 #include <stdlib.h> 00035 #include <string.h> 00036 #include <vector> 00037 00038 // iTaSC headers 00039 #ifdef WITH_IK_ITASC 00040 #include "Armature.hpp" 00041 #include "MovingFrame.hpp" 00042 #include "CopyPose.hpp" 00043 #include "WSDLSSolver.hpp" 00044 #include "WDLSSolver.hpp" 00045 #include "Scene.hpp" 00046 #include "Cache.hpp" 00047 #include "Distance.hpp" 00048 #endif 00049 00050 #include "MEM_guardedalloc.h" 00051 00052 extern "C" { 00053 #include "BIK_api.h" 00054 #include "BLI_blenlib.h" 00055 #include "BLI_math.h" 00056 #include "BLI_utildefines.h" 00057 00058 #include "BKE_global.h" 00059 #include "BKE_armature.h" 00060 #include "BKE_action.h" 00061 #include "BKE_utildefines.h" 00062 #include "BKE_constraint.h" 00063 #include "DNA_object_types.h" 00064 #include "DNA_action_types.h" 00065 #include "DNA_constraint_types.h" 00066 #include "DNA_armature_types.h" 00067 #include "DNA_scene_types.h" 00068 }; 00069 00070 #include "itasc_plugin.h" 00071 00072 // default parameters 00073 bItasc DefIKParam; 00074 00075 // in case of animation mode, feedback and timestep is fixed 00076 #define ANIM_TIMESTEP 1.0 00077 #define ANIM_FEEDBACK 0.8 00078 #define ANIM_QMAX 0.52 00079 00080 00081 // Structure pointed by bPose.ikdata 00082 // It contains everything needed to simulate the armatures 00083 // There can be several simulation islands independent to each other 00084 struct IK_Data 00085 { 00086 struct IK_Scene* first; 00087 }; 00088 00089 typedef float Vector3[3]; 00090 typedef float Vector4[4]; 00091 struct IK_Target; 00092 typedef void (*ErrorCallback)(const iTaSC::ConstraintValues* values, unsigned int nvalues, IK_Target* iktarget); 00093 // For some reason, gcc doesn't find the declaration of this function in linux 00094 void KDL::SetToZero(JntArray& array); 00095 00096 // one structure for each target in the scene 00097 struct IK_Target 00098 { 00099 struct Scene *blscene; 00100 iTaSC::MovingFrame* target; 00101 iTaSC::ConstraintSet* constraint; 00102 struct bConstraint* blenderConstraint; 00103 struct bPoseChannel* rootChannel; 00104 Object* owner; //for auto IK 00105 ErrorCallback errorCallback; 00106 std::string targetName; 00107 std::string constraintName; 00108 unsigned short controlType; 00109 short channel; //index in IK channel array of channel on which this target is defined 00110 short ee; //end effector number 00111 bool simulation; //true when simulation mode is used (update feedback) 00112 bool eeBlend; //end effector affected by enforce blending 00113 float eeRest[4][4]; //end effector initial pose relative to armature 00114 00115 IK_Target() { 00116 blscene = NULL; 00117 target = NULL; 00118 constraint = NULL; 00119 blenderConstraint = NULL; 00120 rootChannel = NULL; 00121 owner = NULL; 00122 controlType = 0; 00123 channel = 0; 00124 ee = 0; 00125 eeBlend = true; 00126 simulation = true; 00127 targetName.reserve(32); 00128 constraintName.reserve(32); 00129 } 00130 ~IK_Target() { 00131 if (constraint) 00132 delete constraint; 00133 if (target) 00134 delete target; 00135 } 00136 }; 00137 00138 struct IK_Channel { 00139 bPoseChannel* pchan; // channel where we must copy matrix back 00140 KDL::Frame frame; // frame of the bone relative to object base, not armature base 00141 std::string tail; // segment name of the joint from which we get the bone tail 00142 std::string head; // segment name of the joint from which we get the bone head 00143 int parent; // index in this array of the parent channel 00144 short jointType; // type of joint, combination of IK_SegmentFlag 00145 char ndof; // number of joint angles for this channel 00146 char jointValid; // set to 1 when jointValue has been computed 00147 // for joint constraint 00148 Object* owner; // for pose and IK param 00149 double jointValue[4]; // computed joint value 00150 00151 IK_Channel() { 00152 pchan = NULL; 00153 parent = -1; 00154 jointType = 0; 00155 ndof = 0; 00156 jointValid = 0; 00157 owner = NULL; 00158 jointValue[0] = 0.0; 00159 jointValue[1] = 0.0; 00160 jointValue[2] = 0.0; 00161 jointValue[3] = 0.0; 00162 } 00163 }; 00164 00165 struct IK_Scene 00166 { 00167 struct Scene *blscene; 00168 IK_Scene* next; 00169 int numchan; // number of channel in pchan 00170 int numjoint; // number of joint in jointArray 00171 // array of bone information, one per channel in the tree 00172 IK_Channel* channels; 00173 iTaSC::Armature* armature; 00174 iTaSC::Cache* cache; 00175 iTaSC::Scene* scene; 00176 iTaSC::MovingFrame* base; // armature base object 00177 KDL::Frame baseFrame; // frame of armature base relative to blArmature 00178 KDL::JntArray jointArray; // buffer for storing temporary joint array 00179 iTaSC::Solver* solver; 00180 Object* blArmature; 00181 struct bConstraint* polarConstraint; 00182 std::vector<IK_Target*> targets; 00183 00184 IK_Scene() { 00185 blscene = NULL; 00186 next = NULL; 00187 channels = NULL; 00188 armature = NULL; 00189 cache = NULL; 00190 scene = NULL; 00191 base = NULL; 00192 solver = NULL; 00193 blArmature = NULL; 00194 numchan = 0; 00195 numjoint = 0; 00196 polarConstraint = NULL; 00197 } 00198 00199 ~IK_Scene() { 00200 // delete scene first 00201 if (scene) 00202 delete scene; 00203 for(std::vector<IK_Target*>::iterator it = targets.begin(); it != targets.end(); ++it) 00204 delete (*it); 00205 targets.clear(); 00206 if (channels) 00207 delete [] channels; 00208 if (solver) 00209 delete solver; 00210 if (armature) 00211 delete armature; 00212 if (base) 00213 delete base; 00214 // delete cache last 00215 if (cache) 00216 delete cache; 00217 } 00218 }; 00219 00220 // type of IK joint, can be combined to list the joints corresponding to a bone 00221 enum IK_SegmentFlag { 00222 IK_XDOF = 1, 00223 IK_YDOF = 2, 00224 IK_ZDOF = 4, 00225 IK_SWING = 8, 00226 IK_REVOLUTE = 16, 00227 IK_TRANSY = 32, 00228 }; 00229 00230 enum IK_SegmentAxis { 00231 IK_X = 0, 00232 IK_Y = 1, 00233 IK_Z = 2, 00234 IK_TRANS_X = 3, 00235 IK_TRANS_Y = 4, 00236 IK_TRANS_Z = 5 00237 }; 00238 00239 static int initialize_chain(Object *ob, bPoseChannel *pchan_tip, bConstraint *con) 00240 { 00241 bPoseChannel *curchan, *pchan_root=NULL, *chanlist[256], **oldchan; 00242 PoseTree *tree; 00243 PoseTarget *target; 00244 bKinematicConstraint *data; 00245 int a, t, segcount= 0, size, newsize, *oldparent, parent, rootbone, treecount; 00246 00247 data=(bKinematicConstraint*)con->data; 00248 00249 /* exclude tip from chain? */ 00250 if(!(data->flag & CONSTRAINT_IK_TIP)) 00251 pchan_tip= pchan_tip->parent; 00252 00253 rootbone = data->rootbone; 00254 /* Find the chain's root & count the segments needed */ 00255 for (curchan = pchan_tip; curchan; curchan=curchan->parent){ 00256 pchan_root = curchan; 00257 00258 if (++segcount > 255) // 255 is weak 00259 break; 00260 00261 if(segcount==rootbone){ 00262 // reached this end of the chain but if the chain is overlapping with a 00263 // previous one, we must go back up to the root of the other chain 00264 if ((curchan->flag & POSE_CHAIN) && curchan->iktree.first == NULL){ 00265 rootbone++; 00266 continue; 00267 } 00268 break; 00269 } 00270 00271 if (curchan->iktree.first != NULL) 00272 // Oh oh, there is already a chain starting from this channel and our chain is longer... 00273 // Should handle this by moving the previous chain up to the begining of our chain 00274 // For now we just stop here 00275 break; 00276 } 00277 if (!segcount) return 0; 00278 // we reached a limit and still not the end of a previous chain, quit 00279 if ((pchan_root->flag & POSE_CHAIN) && pchan_root->iktree.first == NULL) return 0; 00280 00281 // now that we know how many segment we have, set the flag 00282 for (rootbone = segcount, segcount = 0, curchan = pchan_tip; segcount < rootbone; segcount++, curchan=curchan->parent) { 00283 chanlist[segcount]=curchan; 00284 curchan->flag |= POSE_CHAIN; 00285 } 00286 00287 /* setup the chain data */ 00288 /* create a target */ 00289 target= (PoseTarget*)MEM_callocN(sizeof(PoseTarget), "posetarget"); 00290 target->con= con; 00291 // by contruction there can be only one tree per channel and each channel can be part of at most one tree. 00292 tree = (PoseTree*)pchan_root->iktree.first; 00293 00294 if(tree==NULL) { 00295 /* make new tree */ 00296 tree= (PoseTree*)MEM_callocN(sizeof(PoseTree), "posetree"); 00297 00298 tree->iterations= data->iterations; 00299 tree->totchannel= segcount; 00300 tree->stretch = (data->flag & CONSTRAINT_IK_STRETCH); 00301 00302 tree->pchan= (bPoseChannel**)MEM_callocN(segcount*sizeof(void*), "ik tree pchan"); 00303 tree->parent= (int*)MEM_callocN(segcount*sizeof(int), "ik tree parent"); 00304 for(a=0; a<segcount; a++) { 00305 tree->pchan[a]= chanlist[segcount-a-1]; 00306 tree->parent[a]= a-1; 00307 } 00308 target->tip= segcount-1; 00309 00310 /* AND! link the tree to the root */ 00311 BLI_addtail(&pchan_root->iktree, tree); 00312 // new tree 00313 treecount = 1; 00314 } 00315 else { 00316 tree->iterations= MAX2(data->iterations, tree->iterations); 00317 tree->stretch= tree->stretch && !(data->flag & CONSTRAINT_IK_STRETCH); 00318 00319 /* skip common pose channels and add remaining*/ 00320 size= MIN2(segcount, tree->totchannel); 00321 a = t = 0; 00322 while (a<size && t<tree->totchannel) { 00323 // locate first matching channel 00324 for (;t<tree->totchannel && tree->pchan[t]!=chanlist[segcount-a-1];t++); 00325 if (t>=tree->totchannel) 00326 break; 00327 for(; a<size && t<tree->totchannel && tree->pchan[t]==chanlist[segcount-a-1]; a++, t++); 00328 } 00329 00330 segcount= segcount-a; 00331 target->tip= tree->totchannel + segcount - 1; 00332 00333 if (segcount > 0) { 00334 for(parent = a - 1; parent < tree->totchannel; parent++) 00335 if(tree->pchan[parent] == chanlist[segcount-1]->parent) 00336 break; 00337 00338 /* shouldn't happen, but could with dependency cycles */ 00339 if(parent == tree->totchannel) 00340 parent = a - 1; 00341 00342 /* resize array */ 00343 newsize= tree->totchannel + segcount; 00344 oldchan= tree->pchan; 00345 oldparent= tree->parent; 00346 00347 tree->pchan= (bPoseChannel**)MEM_callocN(newsize*sizeof(void*), "ik tree pchan"); 00348 tree->parent= (int*)MEM_callocN(newsize*sizeof(int), "ik tree parent"); 00349 memcpy(tree->pchan, oldchan, sizeof(void*)*tree->totchannel); 00350 memcpy(tree->parent, oldparent, sizeof(int)*tree->totchannel); 00351 MEM_freeN(oldchan); 00352 MEM_freeN(oldparent); 00353 00354 /* add new pose channels at the end, in reverse order */ 00355 for(a=0; a<segcount; a++) { 00356 tree->pchan[tree->totchannel+a]= chanlist[segcount-a-1]; 00357 tree->parent[tree->totchannel+a]= tree->totchannel+a-1; 00358 } 00359 tree->parent[tree->totchannel]= parent; 00360 00361 tree->totchannel= newsize; 00362 } 00363 // reusing tree 00364 treecount = 0; 00365 } 00366 00367 /* add target to the tree */ 00368 BLI_addtail(&tree->targets, target); 00369 /* mark root channel having an IK tree */ 00370 pchan_root->flag |= POSE_IKTREE; 00371 return treecount; 00372 } 00373 00374 static bool is_cartesian_constraint(bConstraint *con) 00375 { 00376 //bKinematicConstraint* data=(bKinematicConstraint*)con->data; 00377 00378 return true; 00379 } 00380 00381 static bool constraint_valid(bConstraint *con) 00382 { 00383 bKinematicConstraint* data=(bKinematicConstraint*)con->data; 00384 00385 if (data->flag & CONSTRAINT_IK_AUTO) 00386 return true; 00387 if (con->flag & CONSTRAINT_DISABLE) 00388 return false; 00389 if (is_cartesian_constraint(con)) { 00390 /* cartesian space constraint */ 00391 if (data->tar==NULL) 00392 return false; 00393 if (data->tar->type==OB_ARMATURE && data->subtarget[0]==0) 00394 return false; 00395 } 00396 return true; 00397 } 00398 00399 int initialize_scene(Object *ob, bPoseChannel *pchan_tip) 00400 { 00401 bConstraint *con; 00402 int treecount; 00403 00404 /* find all IK constraints and validate them */ 00405 treecount = 0; 00406 for(con= (bConstraint *)pchan_tip->constraints.first; con; con= (bConstraint *)con->next) { 00407 if(con->type==CONSTRAINT_TYPE_KINEMATIC) { 00408 if (constraint_valid(con)) 00409 treecount += initialize_chain(ob, pchan_tip, con); 00410 } 00411 } 00412 return treecount; 00413 } 00414 00415 static IK_Data* get_ikdata(bPose *pose) 00416 { 00417 if (pose->ikdata) 00418 return (IK_Data*)pose->ikdata; 00419 pose->ikdata = MEM_callocN(sizeof(IK_Data), "iTaSC ikdata"); 00420 // here init ikdata if needed 00421 // now that we have scene, make sure the default param are initialized 00422 if (!DefIKParam.iksolver) 00423 init_pose_itasc(&DefIKParam); 00424 00425 return (IK_Data*)pose->ikdata; 00426 } 00427 static double EulerAngleFromMatrix(const KDL::Rotation& R, int axis) 00428 { 00429 double t = KDL::sqrt(R(0,0)*R(0,0) + R(0,1)*R(0,1)); 00430 00431 if (t > 16.0*KDL::epsilon) { 00432 if (axis == 0) return -KDL::atan2(R(1,2), R(2,2)); 00433 else if(axis == 1) return KDL::atan2(-R(0,2), t); 00434 else return -KDL::atan2(R(0,1), R(0,0)); 00435 } else { 00436 if (axis == 0) return -KDL::atan2(-R(2,1), R(1,1)); 00437 else if(axis == 1) return KDL::atan2(-R(0,2), t); 00438 else return 0.0f; 00439 } 00440 } 00441 00442 static double ComputeTwist(const KDL::Rotation& R) 00443 { 00444 // qy and qw are the y and w components of the quaternion from R 00445 double qy = R(0,2) - R(2,0); 00446 double qw = R(0,0) + R(1,1) + R(2,2) + 1; 00447 00448 double tau = 2*KDL::atan2(qy, qw); 00449 00450 return tau; 00451 } 00452 00453 static void RemoveEulerAngleFromMatrix(KDL::Rotation& R, double angle, int axis) 00454 { 00455 // compute twist parameter 00456 KDL::Rotation T; 00457 switch (axis) { 00458 case 0: 00459 T = KDL::Rotation::RotX(-angle); 00460 break; 00461 case 1: 00462 T = KDL::Rotation::RotY(-angle); 00463 break; 00464 case 2: 00465 T = KDL::Rotation::RotZ(-angle); 00466 break; 00467 default: 00468 return; 00469 } 00470 // remove angle 00471 R = R*T; 00472 } 00473 00474 #if 0 00475 static void GetEulerXZY(const KDL::Rotation& R, double& X,double& Z,double& Y) 00476 { 00477 if (fabs(R(0,1)) > 1.0 - KDL::epsilon ) { 00478 X = -KDL::sign(R(0,1)) * KDL::atan2(R(1,2), R(1,0)); 00479 Z = -KDL::sign(R(0,1)) * KDL::PI / 2; 00480 Y = 0.0 ; 00481 } else { 00482 X = KDL::atan2(R(2,1), R(1,1)); 00483 Z = KDL::atan2(-R(0,1), KDL::sqrt( KDL::sqr(R(0,0)) + KDL::sqr(R(0,2)))); 00484 Y = KDL::atan2(R(0,2), R(0,0)); 00485 } 00486 } 00487 00488 static void GetEulerXYZ(const KDL::Rotation& R, double& X,double& Y,double& Z) 00489 { 00490 if (fabs(R(0,2)) > 1.0 - KDL::epsilon ) { 00491 X = KDL::sign(R(0,2)) * KDL::atan2(-R(1,0), R(1,1)); 00492 Y = KDL::sign(R(0,2)) * KDL::PI / 2; 00493 Z = 0.0 ; 00494 } else { 00495 X = KDL::atan2(-R(1,2), R(2,2)); 00496 Y = KDL::atan2(R(0,2), KDL::sqrt( KDL::sqr(R(0,0)) + KDL::sqr(R(0,1)))); 00497 Z = KDL::atan2(-R(0,1), R(0,0)); 00498 } 00499 } 00500 #endif 00501 00502 static void GetJointRotation(KDL::Rotation& boneRot, int type, double* rot) 00503 { 00504 switch (type & ~IK_TRANSY) 00505 { 00506 default: 00507 // fixed bone, no joint 00508 break; 00509 case IK_XDOF: 00510 // RX only, get the X rotation 00511 rot[0] = EulerAngleFromMatrix(boneRot, 0); 00512 break; 00513 case IK_YDOF: 00514 // RY only, get the Y rotation 00515 rot[0] = ComputeTwist(boneRot); 00516 break; 00517 case IK_ZDOF: 00518 // RZ only, get the Z rotation 00519 rot[0] = EulerAngleFromMatrix(boneRot, 2); 00520 break; 00521 case IK_XDOF|IK_YDOF: 00522 rot[1] = ComputeTwist(boneRot); 00523 RemoveEulerAngleFromMatrix(boneRot, rot[1], 1); 00524 rot[0] = EulerAngleFromMatrix(boneRot, 0); 00525 break; 00526 case IK_SWING: 00527 // RX+RZ 00528 boneRot.GetXZRot().GetValue(rot); 00529 break; 00530 case IK_YDOF|IK_ZDOF: 00531 // RZ+RY 00532 rot[1] = ComputeTwist(boneRot); 00533 RemoveEulerAngleFromMatrix(boneRot, rot[1], 1); 00534 rot[0] = EulerAngleFromMatrix(boneRot, 2); 00535 break; 00536 case IK_SWING|IK_YDOF: 00537 rot[2] = ComputeTwist(boneRot); 00538 RemoveEulerAngleFromMatrix(boneRot, rot[2], 1); 00539 boneRot.GetXZRot().GetValue(rot); 00540 break; 00541 case IK_REVOLUTE: 00542 boneRot.GetRot().GetValue(rot); 00543 break; 00544 } 00545 } 00546 00547 static bool target_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param) 00548 { 00549 IK_Target* target = (IK_Target*)param; 00550 // compute next target position 00551 // get target matrix from constraint. 00552 bConstraint* constraint = (bConstraint*)target->blenderConstraint; 00553 float tarmat[4][4]; 00554 00555 get_constraint_target_matrix(target->blscene, constraint, 0, CONSTRAINT_OBTYPE_OBJECT, target->owner, tarmat, 1.0); 00556 00557 // rootmat contains the target pose in world coordinate 00558 // if enforce is != 1.0, blend the target position with the end effector position 00559 // if the armature was in rest position. This information is available in eeRest 00560 if (constraint->enforce != 1.0f && target->eeBlend) { 00561 // eeRest is relative to the reference frame of the IK root 00562 // get this frame in world reference 00563 float restmat[4][4]; 00564 bPoseChannel* pchan = target->rootChannel; 00565 if (pchan->parent) { 00566 pchan = pchan->parent; 00567 float chanmat[4][4]; 00568 copy_m4_m4(chanmat, pchan->pose_mat); 00569 copy_v3_v3(chanmat[3], pchan->pose_tail); 00570 mul_serie_m4(restmat, target->owner->obmat, chanmat, target->eeRest, NULL, NULL, NULL, NULL, NULL); 00571 } 00572 else { 00573 mult_m4_m4m4(restmat, target->owner->obmat, target->eeRest); 00574 } 00575 // blend the target 00576 blend_m4_m4m4(tarmat, restmat, tarmat, constraint->enforce); 00577 } 00578 next.setValue(&tarmat[0][0]); 00579 return true; 00580 } 00581 00582 static bool base_callback(const iTaSC::Timestamp& timestamp, const iTaSC::Frame& current, iTaSC::Frame& next, void *param) 00583 { 00584 IK_Scene* ikscene = (IK_Scene*)param; 00585 // compute next armature base pose 00586 // algorithm: 00587 // ikscene->pchan[0] is the root channel of the tree 00588 // if it has a parent, get the pose matrix from it and replace [3] by parent pchan->tail 00589 // then multiply by the armature matrix to get ikscene->armature base position 00590 bPoseChannel* pchan = ikscene->channels[0].pchan; 00591 float rootmat[4][4]; 00592 if (pchan->parent) { 00593 pchan = pchan->parent; 00594 float chanmat[4][4]; 00595 copy_m4_m4(chanmat, pchan->pose_mat); 00596 copy_v3_v3(chanmat[3], pchan->pose_tail); 00597 // save the base as a frame too so that we can compute deformation 00598 // after simulation 00599 ikscene->baseFrame.setValue(&chanmat[0][0]); 00600 mult_m4_m4m4(rootmat, ikscene->blArmature->obmat, chanmat); 00601 } 00602 else { 00603 copy_m4_m4(rootmat, ikscene->blArmature->obmat); 00604 ikscene->baseFrame = iTaSC::F_identity; 00605 } 00606 next.setValue(&rootmat[0][0]); 00607 // if there is a polar target (only during solving otherwise we don't have end efffector) 00608 if (ikscene->polarConstraint && timestamp.update) { 00609 // compute additional rotation of base frame so that armature follows the polar target 00610 float imat[4][4]; // IK tree base inverse matrix 00611 float polemat[4][4]; // polar target in IK tree base frame 00612 float goalmat[4][4]; // target in IK tree base frame 00613 float mat[4][4]; // temp matrix 00614 bKinematicConstraint* poledata = (bKinematicConstraint*)ikscene->polarConstraint->data; 00615 00616 invert_m4_m4(imat, rootmat); 00617 // polar constraint imply only one target 00618 IK_Target *iktarget = ikscene->targets[0]; 00619 // root channel from which we take the bone initial orientation 00620 IK_Channel &rootchan = ikscene->channels[0]; 00621 00622 // get polar target matrix in world space 00623 get_constraint_target_matrix(ikscene->blscene, ikscene->polarConstraint, 1, CONSTRAINT_OBTYPE_OBJECT, ikscene->blArmature, mat, 1.0); 00624 // convert to armature space 00625 mult_m4_m4m4(polemat, imat, mat); 00626 // get the target in world space (was computed before as target object are defined before base object) 00627 iktarget->target->getPose().getValue(mat[0]); 00628 // convert to armature space 00629 mult_m4_m4m4(goalmat, imat, mat); 00630 // take position of target, polar target, end effector, in armature space 00631 KDL::Vector goalpos(goalmat[3]); 00632 KDL::Vector polepos(polemat[3]); 00633 KDL::Vector endpos = ikscene->armature->getPose(iktarget->ee).p; 00634 // get root bone orientation 00635 KDL::Frame rootframe; 00636 ikscene->armature->getRelativeFrame(rootframe, rootchan.tail); 00637 KDL::Vector rootx = rootframe.M.UnitX(); 00638 KDL::Vector rootz = rootframe.M.UnitZ(); 00639 // and compute root bone head 00640 double q_rest[3], q[3], length; 00641 const KDL::Joint* joint; 00642 const KDL::Frame* tip; 00643 ikscene->armature->getSegment(rootchan.tail, 3, joint, q_rest[0], q[0], tip); 00644 length = (joint->getType() == KDL::Joint::TransY) ? q[0] : tip->p(1); 00645 KDL::Vector rootpos = rootframe.p - length*rootframe.M.UnitY(); 00646 00647 // compute main directions 00648 KDL::Vector dir = KDL::Normalize(endpos - rootpos); 00649 KDL::Vector poledir = KDL::Normalize(goalpos-rootpos); 00650 // compute up directions 00651 KDL::Vector poleup = KDL::Normalize(polepos-rootpos); 00652 KDL::Vector up = rootx*KDL::cos(poledata->poleangle) + rootz*KDL::sin(poledata->poleangle); 00653 // from which we build rotation matrix 00654 KDL::Rotation endrot, polerot; 00655 // for the armature, using the root bone orientation 00656 KDL::Vector x = KDL::Normalize(dir*up); 00657 endrot.UnitX(x); 00658 endrot.UnitY(KDL::Normalize(x*dir)); 00659 endrot.UnitZ(-dir); 00660 // for the polar target 00661 x = KDL::Normalize(poledir*poleup); 00662 polerot.UnitX(x); 00663 polerot.UnitY(KDL::Normalize(x*poledir)); 00664 polerot.UnitZ(-poledir); 00665 // the difference between the two is the rotation we want to apply 00666 KDL::Rotation result(polerot*endrot.Inverse()); 00667 // apply on base frame as this is an artificial additional rotation 00668 next.M = next.M*result; 00669 ikscene->baseFrame.M = ikscene->baseFrame.M*result; 00670 } 00671 return true; 00672 } 00673 00674 static bool copypose_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues* const _values, unsigned int _nvalues, void* _param) 00675 { 00676 IK_Target* iktarget =(IK_Target*)_param; 00677 bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data; 00678 iTaSC::ConstraintValues* values = _values; 00679 bItasc* ikparam = (bItasc*) iktarget->owner->pose->ikparam; 00680 00681 // we need default parameters 00682 if (!ikparam) 00683 ikparam = &DefIKParam; 00684 00685 if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) { 00686 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) { 00687 values->alpha = 0.0; 00688 values->action = iTaSC::ACT_ALPHA; 00689 values++; 00690 } 00691 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) { 00692 values->alpha = 0.0; 00693 values->action = iTaSC::ACT_ALPHA; 00694 values++; 00695 } 00696 } else { 00697 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) { 00698 // update error 00699 values->alpha = condata->weight; 00700 values->action = iTaSC::ACT_ALPHA|iTaSC::ACT_FEEDBACK; 00701 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK; 00702 values++; 00703 } 00704 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) { 00705 // update error 00706 values->alpha = condata->orientweight; 00707 values->action = iTaSC::ACT_ALPHA|iTaSC::ACT_FEEDBACK; 00708 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK; 00709 values++; 00710 } 00711 } 00712 return true; 00713 } 00714 00715 static void copypose_error(const iTaSC::ConstraintValues* values, unsigned int nvalues, IK_Target* iktarget) 00716 { 00717 iTaSC::ConstraintSingleValue* value; 00718 double error; 00719 int i; 00720 00721 if (iktarget->controlType & iTaSC::CopyPose::CTL_POSITION) { 00722 // update error 00723 for (i=0, error=0.0, value=values->values; i<values->number; ++i, ++value) 00724 error += KDL::sqr(value->y - value->yd); 00725 iktarget->blenderConstraint->lin_error = (float)KDL::sqrt(error); 00726 values++; 00727 } 00728 if (iktarget->controlType & iTaSC::CopyPose::CTL_ROTATION) { 00729 // update error 00730 for (i=0, error=0.0, value=values->values; i<values->number; ++i, ++value) 00731 error += KDL::sqr(value->y - value->yd); 00732 iktarget->blenderConstraint->rot_error = (float)KDL::sqrt(error); 00733 values++; 00734 } 00735 } 00736 00737 static bool distance_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues* const _values, unsigned int _nvalues, void* _param) 00738 { 00739 IK_Target* iktarget =(IK_Target*)_param; 00740 bKinematicConstraint *condata = (bKinematicConstraint *)iktarget->blenderConstraint->data; 00741 iTaSC::ConstraintValues* values = _values; 00742 bItasc* ikparam = (bItasc*) iktarget->owner->pose->ikparam; 00743 // we need default parameters 00744 if (!ikparam) 00745 ikparam = &DefIKParam; 00746 00747 // update weight according to mode 00748 if (iktarget->blenderConstraint->flag & CONSTRAINT_OFF) { 00749 values->alpha = 0.0; 00750 } else { 00751 switch (condata->mode) { 00752 case LIMITDIST_INSIDE: 00753 values->alpha = (values->values[0].y > condata->dist) ? condata->weight : 0.0; 00754 break; 00755 case LIMITDIST_OUTSIDE: 00756 values->alpha = (values->values[0].y < condata->dist) ? condata->weight : 0.0; 00757 break; 00758 default: 00759 values->alpha = condata->weight; 00760 break; 00761 } 00762 if (!timestamp.substep) { 00763 // only update value on first timestep 00764 switch (condata->mode) { 00765 case LIMITDIST_INSIDE: 00766 values->values[0].yd = condata->dist*0.95; 00767 break; 00768 case LIMITDIST_OUTSIDE: 00769 values->values[0].yd = condata->dist*1.05; 00770 break; 00771 default: 00772 values->values[0].yd = condata->dist; 00773 break; 00774 } 00775 values->values[0].action = iTaSC::ACT_VALUE|iTaSC::ACT_FEEDBACK; 00776 values->feedback = (iktarget->simulation) ? ikparam->feedback : ANIM_FEEDBACK; 00777 } 00778 } 00779 values->action |= iTaSC::ACT_ALPHA; 00780 return true; 00781 } 00782 00783 static void distance_error(const iTaSC::ConstraintValues* values, unsigned int _nvalues, IK_Target* iktarget) 00784 { 00785 iktarget->blenderConstraint->lin_error = (float)(values->values[0].y - values->values[0].yd); 00786 } 00787 00788 static bool joint_callback(const iTaSC::Timestamp& timestamp, iTaSC::ConstraintValues* const _values, unsigned int _nvalues, void* _param) 00789 { 00790 IK_Channel* ikchan = (IK_Channel*)_param; 00791 bItasc* ikparam = (bItasc*)ikchan->owner->pose->ikparam; 00792 bPoseChannel* chan = ikchan->pchan; 00793 int dof; 00794 00795 // a channel can be splitted into multiple joints, so we get called multiple 00796 // times for one channel (this callback is only for 1 joint in the armature) 00797 // the IK_JointTarget structure is shared between multiple joint constraint 00798 // and the target joint values is computed only once, remember this in jointValid 00799 // Don't forget to reset it before each frame 00800 if (!ikchan->jointValid) { 00801 float rmat[3][3]; 00802 00803 if (chan->rotmode > 0) { 00804 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */ 00805 eulO_to_mat3( rmat,chan->eul, chan->rotmode); 00806 } 00807 else if (chan->rotmode == ROT_MODE_AXISANGLE) { 00808 /* axis-angle - stored in quaternion data, but not really that great for 3D-changing orientations */ 00809 axis_angle_to_mat3( rmat,&chan->quat[1], chan->quat[0]); 00810 } 00811 else { 00812 /* quats are normalised before use to eliminate scaling issues */ 00813 normalize_qt(chan->quat); 00814 quat_to_mat3( rmat,chan->quat); 00815 } 00816 KDL::Rotation jointRot( 00817 rmat[0][0], rmat[1][0], rmat[2][0], 00818 rmat[0][1], rmat[1][1], rmat[2][1], 00819 rmat[0][2], rmat[1][2], rmat[2][2]); 00820 GetJointRotation(jointRot, ikchan->jointType, ikchan->jointValue); 00821 ikchan->jointValid = 1; 00822 } 00823 // determine which part of jointValue is used for this joint 00824 // closely related to the way the joints are defined 00825 switch (ikchan->jointType & ~IK_TRANSY) 00826 { 00827 case IK_XDOF: 00828 case IK_YDOF: 00829 case IK_ZDOF: 00830 dof = 0; 00831 break; 00832 case IK_XDOF|IK_YDOF: 00833 // X + Y 00834 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RX) ? 0 : 1; 00835 break; 00836 case IK_SWING: 00837 // XZ 00838 dof = 0; 00839 break; 00840 case IK_YDOF|IK_ZDOF: 00841 // Z + Y 00842 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RZ) ? 0 : 1; 00843 break; 00844 case IK_SWING|IK_YDOF: 00845 // XZ + Y 00846 dof = (_values[0].id == iTaSC::Armature::ID_JOINT_RY) ? 2 : 0; 00847 break; 00848 case IK_REVOLUTE: 00849 dof = 0; 00850 break; 00851 default: 00852 dof = -1; 00853 break; 00854 } 00855 if (dof >= 0) { 00856 for (unsigned int i=0; i<_nvalues; i++, dof++) { 00857 _values[i].values[0].yd = ikchan->jointValue[dof]; 00858 _values[i].alpha = chan->ikrotweight; 00859 _values[i].feedback = ikparam->feedback; 00860 } 00861 } 00862 return true; 00863 } 00864 00865 // build array of joint corresponding to IK chain 00866 static int convert_channels(IK_Scene *ikscene, PoseTree *tree) 00867 { 00868 IK_Channel *ikchan; 00869 bPoseChannel *pchan; 00870 int a, flag, njoint; 00871 00872 njoint = 0; 00873 for(a=0, ikchan = ikscene->channels; a<ikscene->numchan; ++a, ++ikchan) { 00874 pchan= tree->pchan[a]; 00875 ikchan->pchan = pchan; 00876 ikchan->parent = (a>0) ? tree->parent[a] : -1; 00877 ikchan->owner = ikscene->blArmature; 00878 00879 /* set DoF flag */ 00880 flag = 0; 00881 if(!(pchan->ikflag & BONE_IK_NO_XDOF) && !(pchan->ikflag & BONE_IK_NO_XDOF_TEMP) && 00882 (!(pchan->ikflag & BONE_IK_XLIMIT) || pchan->limitmin[0]<0.f || pchan->limitmax[0]>0.f)) 00883 flag |= IK_XDOF; 00884 if(!(pchan->ikflag & BONE_IK_NO_YDOF) && !(pchan->ikflag & BONE_IK_NO_YDOF_TEMP) && 00885 (!(pchan->ikflag & BONE_IK_YLIMIT) || pchan->limitmin[1]<0.f || pchan->limitmax[1]>0.f)) 00886 flag |= IK_YDOF; 00887 if(!(pchan->ikflag & BONE_IK_NO_ZDOF) && !(pchan->ikflag & BONE_IK_NO_ZDOF_TEMP) && 00888 (!(pchan->ikflag & BONE_IK_ZLIMIT) || pchan->limitmin[2]<0.f || pchan->limitmax[2]>0.f)) 00889 flag |= IK_ZDOF; 00890 00891 if(tree->stretch && (pchan->ikstretch > 0.0)) { 00892 flag |= IK_TRANSY; 00893 } 00894 /* 00895 Logic to create the segments: 00896 RX,RY,RZ = rotational joints with no length 00897 RY(tip) = rotational joints with a fixed length arm = (0,length,0) 00898 TY = translational joint on Y axis 00899 F(pos) = fixed joint with an arm at position pos 00900 Conversion rule of the above flags: 00901 - ==> F(tip) 00902 X ==> RX(tip) 00903 Y ==> RY(tip) 00904 Z ==> RZ(tip) 00905 XY ==> RX+RY(tip) 00906 XZ ==> RX+RZ(tip) 00907 YZ ==> RZ+RY(tip) 00908 XYZ ==> full spherical unless there are limits, in which case RX+RZ+RY(tip) 00909 In case of stretch, tip=(0,0,0) and there is an additional TY joint 00910 The frame at last of these joints represents the tail of the bone. 00911 The head is computed by a reverse translation on Y axis of the bone length 00912 or in case of TY joint, by the frame at previous joint. 00913 In case of separation of bones, there is an additional F(head) joint 00914 00915 Computing rest pose and length is complicated: the solver works in world space 00916 Here is the logic: 00917 rest position is computed only from bone->bone_mat. 00918 bone length is computed from bone->length multiplied by the scaling factor of 00919 the armature. Non-uniform scaling will give bad result! 00920 00921 */ 00922 switch (flag & (IK_XDOF|IK_YDOF|IK_ZDOF)) 00923 { 00924 default: 00925 ikchan->jointType = 0; 00926 ikchan->ndof = 0; 00927 break; 00928 case IK_XDOF: 00929 // RX only, get the X rotation 00930 ikchan->jointType = IK_XDOF; 00931 ikchan->ndof = 1; 00932 break; 00933 case IK_YDOF: 00934 // RY only, get the Y rotation 00935 ikchan->jointType = IK_YDOF; 00936 ikchan->ndof = 1; 00937 break; 00938 case IK_ZDOF: 00939 // RZ only, get the Zz rotation 00940 ikchan->jointType = IK_ZDOF; 00941 ikchan->ndof = 1; 00942 break; 00943 case IK_XDOF|IK_YDOF: 00944 ikchan->jointType = IK_XDOF|IK_YDOF; 00945 ikchan->ndof = 2; 00946 break; 00947 case IK_XDOF|IK_ZDOF: 00948 // RX+RZ 00949 ikchan->jointType = IK_SWING; 00950 ikchan->ndof = 2; 00951 break; 00952 case IK_YDOF|IK_ZDOF: 00953 // RZ+RY 00954 ikchan->jointType = IK_ZDOF|IK_YDOF; 00955 ikchan->ndof = 2; 00956 break; 00957 case IK_XDOF|IK_YDOF|IK_ZDOF: 00958 // spherical joint 00959 if (pchan->ikflag & (BONE_IK_XLIMIT|BONE_IK_YLIMIT|BONE_IK_ZLIMIT)) 00960 // decompose in a Swing+RotY joint 00961 ikchan->jointType = IK_SWING|IK_YDOF; 00962 else 00963 ikchan->jointType = IK_REVOLUTE; 00964 ikchan->ndof = 3; 00965 break; 00966 } 00967 if (flag & IK_TRANSY) { 00968 ikchan->jointType |= IK_TRANSY; 00969 ikchan->ndof++; 00970 } 00971 njoint += ikchan->ndof; 00972 } 00973 // njoint is the joint coordinate, create the Joint Array 00974 ikscene->jointArray.resize(njoint); 00975 ikscene->numjoint = njoint; 00976 return njoint; 00977 } 00978 00979 // compute array of joint value corresponding to current pose 00980 static void convert_pose(IK_Scene *ikscene) 00981 { 00982 KDL::Rotation boneRot; 00983 bPoseChannel *pchan; 00984 IK_Channel *ikchan; 00985 Bone *bone; 00986 float rmat[4][4]; // rest pose of bone with parent taken into account 00987 float bmat[4][4]; // difference 00988 float scale; 00989 double *rot; 00990 int a, joint; 00991 00992 // assume uniform scaling and take Y scale as general scale for the armature 00993 scale = len_v3(ikscene->blArmature->obmat[1]); 00994 rot = &ikscene->jointArray(0); 00995 for(joint=a=0, ikchan = ikscene->channels; a<ikscene->numchan && joint<ikscene->numjoint; ++a, ++ikchan) { 00996 pchan= ikchan->pchan; 00997 bone= pchan->bone; 00998 00999 if (pchan->parent) { 01000 unit_m4(bmat); 01001 mul_m4_m4m3(bmat, pchan->parent->pose_mat, bone->bone_mat); 01002 } else { 01003 copy_m4_m4(bmat, bone->arm_mat); 01004 } 01005 invert_m4_m4(rmat, bmat); 01006 mult_m4_m4m4(bmat, rmat, pchan->pose_mat); 01007 normalize_m4(bmat); 01008 boneRot.setValue(bmat[0]); 01009 GetJointRotation(boneRot, ikchan->jointType, rot); 01010 if (ikchan->jointType & IK_TRANSY) { 01011 // compute actual length 01012 rot[ikchan->ndof-1] = len_v3v3(pchan->pose_tail, pchan->pose_head) * scale; 01013 } 01014 rot += ikchan->ndof; 01015 joint += ikchan->ndof; 01016 } 01017 } 01018 01019 // compute array of joint value corresponding to current pose 01020 static void rest_pose(IK_Scene *ikscene) 01021 { 01022 bPoseChannel *pchan; 01023 IK_Channel *ikchan; 01024 Bone *bone; 01025 float scale; 01026 double *rot; 01027 int a, joint; 01028 01029 // assume uniform scaling and take Y scale as general scale for the armature 01030 scale = len_v3(ikscene->blArmature->obmat[1]); 01031 // rest pose is 0 01032 KDL::SetToZero(ikscene->jointArray); 01033 // except for transY joints 01034 rot = &ikscene->jointArray(0); 01035 for(joint=a=0, ikchan = ikscene->channels; a<ikscene->numchan && joint<ikscene->numjoint; ++a, ++ikchan) { 01036 pchan= ikchan->pchan; 01037 bone= pchan->bone; 01038 01039 if (ikchan->jointType & IK_TRANSY) 01040 rot[ikchan->ndof-1] = bone->length*scale; 01041 rot += ikchan->ndof; 01042 joint += ikchan->ndof; 01043 } 01044 } 01045 01046 static IK_Scene* convert_tree(Scene *blscene, Object *ob, bPoseChannel *pchan) 01047 { 01048 PoseTree *tree = (PoseTree*)pchan->iktree.first; 01049 PoseTarget *target; 01050 bKinematicConstraint *condata; 01051 bConstraint *polarcon; 01052 bItasc *ikparam; 01053 iTaSC::Armature* arm; 01054 iTaSC::Scene* scene; 01055 IK_Scene* ikscene; 01056 IK_Channel* ikchan; 01057 KDL::Frame initPose; 01058 KDL::Rotation boneRot; 01059 Bone *bone; 01060 int a, numtarget; 01061 unsigned int t; 01062 float length; 01063 bool ret = true, ingame; 01064 double *rot; 01065 01066 if (tree->totchannel == 0) 01067 return NULL; 01068 01069 ikscene = new IK_Scene; 01070 ikscene->blscene = blscene; 01071 arm = new iTaSC::Armature(); 01072 scene = new iTaSC::Scene(); 01073 ikscene->channels = new IK_Channel[tree->totchannel]; 01074 ikscene->numchan = tree->totchannel; 01075 ikscene->armature = arm; 01076 ikscene->scene = scene; 01077 ikparam = (bItasc*)ob->pose->ikparam; 01078 ingame = (ob->pose->flag & POSE_GAME_ENGINE); 01079 if (!ikparam) { 01080 // you must have our own copy 01081 ikparam = &DefIKParam; 01082 } else if (ingame) { 01083 // tweak the param when in game to have efficient stepping 01084 // using fixed substep is not effecient since frames in the GE are often 01085 // shorter than in animation => move to auto step automatically and set 01086 // the target substep duration via min/max 01087 if (!(ikparam->flag & ITASC_AUTO_STEP)) { 01088 float timestep = blscene->r.frs_sec_base/blscene->r.frs_sec; 01089 if (ikparam->numstep > 0) 01090 timestep /= ikparam->numstep; 01091 // with equal min and max, the algorythm will take this step and the indicative substep most of the time 01092 ikparam->minstep = ikparam->maxstep = timestep; 01093 ikparam->flag |= ITASC_AUTO_STEP; 01094 } 01095 } 01096 if ((ikparam->flag & ITASC_SIMULATION) && !ingame) 01097 // no cache in animation mode 01098 ikscene->cache = new iTaSC::Cache(); 01099 01100 switch (ikparam->solver) { 01101 case ITASC_SOLVER_SDLS: 01102 ikscene->solver = new iTaSC::WSDLSSolver(); 01103 break; 01104 case ITASC_SOLVER_DLS: 01105 ikscene->solver = new iTaSC::WDLSSolver(); 01106 break; 01107 default: 01108 delete ikscene; 01109 return NULL; 01110 } 01111 ikscene->blArmature = ob; 01112 01113 std::string joint; 01114 std::string root("root"); 01115 std::string parent; 01116 std::vector<double> weights; 01117 double weight[3]; 01118 // assume uniform scaling and take Y scale as general scale for the armature 01119 float scale = len_v3(ob->obmat[1]); 01120 // build the array of joints corresponding to the IK chain 01121 convert_channels(ikscene, tree); 01122 if (ingame) { 01123 // in the GE, set the initial joint angle to match the current pose 01124 // this will update the jointArray in ikscene 01125 convert_pose(ikscene); 01126 } else { 01127 // in Blender, the rest pose is always 0 for joints 01128 rest_pose(ikscene); 01129 } 01130 rot = &ikscene->jointArray(0); 01131 for(a=0, ikchan = ikscene->channels; a<tree->totchannel; ++a, ++ikchan) { 01132 pchan= ikchan->pchan; 01133 bone= pchan->bone; 01134 01135 KDL::Frame tip(iTaSC::F_identity); 01136 Vector3 *fl = bone->bone_mat; 01137 KDL::Rotation brot( 01138 fl[0][0], fl[1][0], fl[2][0], 01139 fl[0][1], fl[1][1], fl[2][1], 01140 fl[0][2], fl[1][2], fl[2][2]); 01141 KDL::Vector bpos(bone->head[0], bone->head[1], bone->head[2]); 01142 bpos = bpos*scale; 01143 KDL::Frame head(brot, bpos); 01144 01145 // rest pose length of the bone taking scaling into account 01146 length= bone->length*scale; 01147 parent = (a > 0) ? ikscene->channels[tree->parent[a]].tail : root; 01148 // first the fixed segment to the bone head 01149 if (head.p.Norm() > KDL::epsilon || head.M.GetRot().Norm() > KDL::epsilon) { 01150 joint = bone->name; 01151 joint += ":H"; 01152 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, head); 01153 parent = joint; 01154 } 01155 if (!(ikchan->jointType & IK_TRANSY)) { 01156 // fixed length, put it in tip 01157 tip.p[1] = length; 01158 } 01159 joint = bone->name; 01160 weight[0] = (1.0-pchan->stiffness[0]); 01161 weight[1] = (1.0-pchan->stiffness[1]); 01162 weight[2] = (1.0-pchan->stiffness[2]); 01163 switch (ikchan->jointType & ~IK_TRANSY) 01164 { 01165 case 0: 01166 // fixed bone 01167 if (!(ikchan->jointType & IK_TRANSY)) { 01168 joint += ":F"; 01169 ret = arm->addSegment(joint, parent, KDL::Joint::None, 0.0, tip); 01170 } 01171 break; 01172 case IK_XDOF: 01173 // RX only, get the X rotation 01174 joint += ":RX"; 01175 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0], tip); 01176 weights.push_back(weight[0]); 01177 break; 01178 case IK_YDOF: 01179 // RY only, get the Y rotation 01180 joint += ":RY"; 01181 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[0], tip); 01182 weights.push_back(weight[1]); 01183 break; 01184 case IK_ZDOF: 01185 // RZ only, get the Zz rotation 01186 joint += ":RZ"; 01187 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0], tip); 01188 weights.push_back(weight[2]); 01189 break; 01190 case IK_XDOF|IK_YDOF: 01191 joint += ":RX"; 01192 ret = arm->addSegment(joint, parent, KDL::Joint::RotX, rot[0]); 01193 weights.push_back(weight[0]); 01194 if (ret) { 01195 parent = joint; 01196 joint = bone->name; 01197 joint += ":RY"; 01198 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip); 01199 weights.push_back(weight[1]); 01200 } 01201 break; 01202 case IK_SWING: 01203 joint += ":SW"; 01204 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0], tip); 01205 weights.push_back(weight[0]); 01206 weights.push_back(weight[2]); 01207 break; 01208 case IK_YDOF|IK_ZDOF: 01209 // RZ+RY 01210 joint += ":RZ"; 01211 ret = arm->addSegment(joint, parent, KDL::Joint::RotZ, rot[0]); 01212 weights.push_back(weight[2]); 01213 if (ret) { 01214 parent = joint; 01215 joint = bone->name; 01216 joint += ":RY"; 01217 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[1], tip); 01218 weights.push_back(weight[1]); 01219 } 01220 break; 01221 case IK_SWING|IK_YDOF: 01222 // decompose in a Swing+RotY joint 01223 joint += ":SW"; 01224 ret = arm->addSegment(joint, parent, KDL::Joint::Swing, rot[0]); 01225 weights.push_back(weight[0]); 01226 weights.push_back(weight[2]); 01227 if (ret) { 01228 parent = joint; 01229 joint = bone->name; 01230 joint += ":RY"; 01231 ret = arm->addSegment(joint, parent, KDL::Joint::RotY, rot[2], tip); 01232 weights.push_back(weight[1]); 01233 } 01234 break; 01235 case IK_REVOLUTE: 01236 joint += ":SJ"; 01237 ret = arm->addSegment(joint, parent, KDL::Joint::Sphere, rot[0], tip); 01238 weights.push_back(weight[0]); 01239 weights.push_back(weight[1]); 01240 weights.push_back(weight[2]); 01241 break; 01242 } 01243 if (ret && (ikchan->jointType & IK_TRANSY)) { 01244 parent = joint; 01245 joint = bone->name; 01246 joint += ":TY"; 01247 ret = arm->addSegment(joint, parent, KDL::Joint::TransY, rot[ikchan->ndof-1]); 01248 float ikstretch = pchan->ikstretch*pchan->ikstretch; 01249 weight[1] = (1.0-MIN2(1.0-ikstretch, 0.99)); 01250 weights.push_back(weight[1]); 01251 } 01252 if (!ret) 01253 // error making the armature?? 01254 break; 01255 // joint points to the segment that correspond to the bone per say 01256 ikchan->tail = joint; 01257 ikchan->head = parent; 01258 // in case of error 01259 ret = false; 01260 if ((ikchan->jointType & IK_XDOF) && (pchan->ikflag & (BONE_IK_XLIMIT|BONE_IK_ROTCTL))) { 01261 joint = bone->name; 01262 joint += ":RX"; 01263 if (pchan->ikflag & BONE_IK_XLIMIT) { 01264 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0) 01265 break; 01266 } 01267 if (pchan->ikflag & BONE_IK_ROTCTL) { 01268 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) 01269 break; 01270 } 01271 } 01272 if ((ikchan->jointType & IK_YDOF) && (pchan->ikflag & (BONE_IK_YLIMIT|BONE_IK_ROTCTL))) { 01273 joint = bone->name; 01274 joint += ":RY"; 01275 if (pchan->ikflag & BONE_IK_YLIMIT) { 01276 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[1], pchan->limitmax[1]) < 0) 01277 break; 01278 } 01279 if (pchan->ikflag & BONE_IK_ROTCTL) { 01280 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) 01281 break; 01282 } 01283 } 01284 if ((ikchan->jointType & IK_ZDOF) && (pchan->ikflag & (BONE_IK_ZLIMIT|BONE_IK_ROTCTL))) { 01285 joint = bone->name; 01286 joint += ":RZ"; 01287 if (pchan->ikflag & BONE_IK_ZLIMIT) { 01288 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[2], pchan->limitmax[2]) < 0) 01289 break; 01290 } 01291 if (pchan->ikflag & BONE_IK_ROTCTL) { 01292 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) 01293 break; 01294 } 01295 } 01296 if ((ikchan->jointType & IK_SWING) && (pchan->ikflag & (BONE_IK_XLIMIT|BONE_IK_ZLIMIT|BONE_IK_ROTCTL))) { 01297 joint = bone->name; 01298 joint += ":SW"; 01299 if (pchan->ikflag & BONE_IK_XLIMIT) { 01300 if (arm->addLimitConstraint(joint, 0, pchan->limitmin[0], pchan->limitmax[0]) < 0) 01301 break; 01302 } 01303 if (pchan->ikflag & BONE_IK_ZLIMIT) { 01304 if (arm->addLimitConstraint(joint, 1, pchan->limitmin[2], pchan->limitmax[2]) < 0) 01305 break; 01306 } 01307 if (pchan->ikflag & BONE_IK_ROTCTL) { 01308 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) 01309 break; 01310 } 01311 } 01312 if ((ikchan->jointType & IK_REVOLUTE) && (pchan->ikflag & BONE_IK_ROTCTL)) { 01313 joint = bone->name; 01314 joint += ":SJ"; 01315 if (arm->addConstraint(joint, joint_callback, ikchan, false, false) < 0) 01316 break; 01317 } 01318 // no error, so restore 01319 ret = true; 01320 rot += ikchan->ndof; 01321 } 01322 if (!ret) { 01323 delete ikscene; 01324 return NULL; 01325 } 01326 // for each target, we need to add an end effector in the armature 01327 for (numtarget=0, polarcon=NULL, ret = true, target=(PoseTarget*)tree->targets.first; target; target=(PoseTarget*)target->next) { 01328 condata= (bKinematicConstraint*)target->con->data; 01329 pchan = tree->pchan[target->tip]; 01330 01331 if (is_cartesian_constraint(target->con)) { 01332 // add the end effector 01333 IK_Target* iktarget = new IK_Target(); 01334 ikscene->targets.push_back(iktarget); 01335 iktarget->ee = arm->addEndEffector(ikscene->channels[target->tip].tail); 01336 if (iktarget->ee == -1) { 01337 ret = false; 01338 break; 01339 } 01340 // initialize all the fields that we can set at this time 01341 iktarget->blenderConstraint = target->con; 01342 iktarget->channel = target->tip; 01343 iktarget->simulation = (ikparam->flag & ITASC_SIMULATION); 01344 iktarget->rootChannel = ikscene->channels[0].pchan; 01345 iktarget->owner = ob; 01346 iktarget->targetName = pchan->bone->name; 01347 iktarget->targetName += ":T:"; 01348 iktarget->targetName += target->con->name; 01349 iktarget->constraintName = pchan->bone->name; 01350 iktarget->constraintName += ":C:"; 01351 iktarget->constraintName += target->con->name; 01352 numtarget++; 01353 if (condata->poletar) 01354 // this constraint has a polar target 01355 polarcon = target->con; 01356 } 01357 } 01358 // deal with polar target if any 01359 if (numtarget == 1 && polarcon) { 01360 ikscene->polarConstraint = polarcon; 01361 } 01362 // we can now add the armature 01363 // the armature is based on a moving frame. 01364 // initialize with the correct position in case there is no cache 01365 base_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, ikscene); 01366 ikscene->base = new iTaSC::MovingFrame(initPose); 01367 ikscene->base->setCallback(base_callback, ikscene); 01368 std::string armname; 01369 armname = ob->id.name; 01370 armname += ":B"; 01371 ret = scene->addObject(armname, ikscene->base); 01372 armname = ob->id.name; 01373 armname += ":AR"; 01374 if (ret) 01375 ret = scene->addObject(armname, ikscene->armature, ikscene->base); 01376 if (!ret) { 01377 delete ikscene; 01378 return NULL; 01379 } 01380 // set the weight 01381 e_matrix& Wq = arm->getWq(); 01382 assert(Wq.cols() == (int)weights.size()); 01383 for (int q=0; q<Wq.cols(); q++) 01384 Wq(q,q)=weights[q]; 01385 // get the inverse rest pose frame of the base to compute relative rest pose of end effectors 01386 // this is needed to handle the enforce parameter 01387 // ikscene->pchan[0] is the root channel of the tree 01388 // if it has no parent, then it's just the identify Frame 01389 float invBaseFrame[4][4]; 01390 pchan = ikscene->channels[0].pchan; 01391 if (pchan->parent) { 01392 // it has a parent, get the pose matrix from it 01393 float baseFrame[4][4]; 01394 pchan = pchan->parent; 01395 copy_m4_m4(baseFrame, pchan->bone->arm_mat); 01396 // move to the tail and scale to get rest pose of armature base 01397 copy_v3_v3(baseFrame[3], pchan->bone->arm_tail); 01398 invert_m4_m4(invBaseFrame, baseFrame); 01399 } else { 01400 unit_m4(invBaseFrame); 01401 } 01402 // finally add the constraint 01403 for (t=0; t<ikscene->targets.size(); t++) { 01404 IK_Target* iktarget = ikscene->targets[t]; 01405 iktarget->blscene = blscene; 01406 condata= (bKinematicConstraint*)iktarget->blenderConstraint->data; 01407 pchan = tree->pchan[iktarget->channel]; 01408 unsigned int controltype, bonecnt; 01409 double bonelen; 01410 float mat[4][4]; 01411 01412 // add the end effector 01413 // estimate the average bone length, used to clamp feedback error 01414 for (bonecnt=0, bonelen=0.f, a=iktarget->channel; a>=0; a=tree->parent[a], bonecnt++) 01415 bonelen += scale*tree->pchan[a]->bone->length; 01416 bonelen /= bonecnt; 01417 01418 // store the rest pose of the end effector to compute enforce target 01419 copy_m4_m4(mat, pchan->bone->arm_mat); 01420 copy_v3_v3(mat[3], pchan->bone->arm_tail); 01421 // get the rest pose relative to the armature base 01422 mult_m4_m4m4(iktarget->eeRest, invBaseFrame, mat); 01423 iktarget->eeBlend = (!ikscene->polarConstraint && condata->type==CONSTRAINT_IK_COPYPOSE) ? true : false; 01424 // use target_callback to make sure the initPose includes enforce coefficient 01425 target_callback(iTaSC::Timestamp(), iTaSC::F_identity, initPose, iktarget); 01426 iktarget->target = new iTaSC::MovingFrame(initPose); 01427 iktarget->target->setCallback(target_callback, iktarget); 01428 ret = scene->addObject(iktarget->targetName, iktarget->target); 01429 if (!ret) 01430 break; 01431 01432 switch (condata->type) { 01433 case CONSTRAINT_IK_COPYPOSE: 01434 controltype = 0; 01435 if (condata->flag & CONSTRAINT_IK_ROT) { 01436 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_X)) 01437 controltype |= iTaSC::CopyPose::CTL_ROTATIONX; 01438 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Y)) 01439 controltype |= iTaSC::CopyPose::CTL_ROTATIONY; 01440 if (!(condata->flag & CONSTRAINT_IK_NO_ROT_Z)) 01441 controltype |= iTaSC::CopyPose::CTL_ROTATIONZ; 01442 } 01443 if (condata->flag & CONSTRAINT_IK_POS) { 01444 if (!(condata->flag & CONSTRAINT_IK_NO_POS_X)) 01445 controltype |= iTaSC::CopyPose::CTL_POSITIONX; 01446 if (!(condata->flag & CONSTRAINT_IK_NO_POS_Y)) 01447 controltype |= iTaSC::CopyPose::CTL_POSITIONY; 01448 if (!(condata->flag & CONSTRAINT_IK_NO_POS_Z)) 01449 controltype |= iTaSC::CopyPose::CTL_POSITIONZ; 01450 } 01451 if (controltype) { 01452 iktarget->constraint = new iTaSC::CopyPose(controltype, controltype, bonelen); 01453 // set the gain 01454 if (controltype & iTaSC::CopyPose::CTL_POSITION) 01455 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_POSITION, iTaSC::ACT_ALPHA, condata->weight); 01456 if (controltype & iTaSC::CopyPose::CTL_ROTATION) 01457 iktarget->constraint->setControlParameter(iTaSC::CopyPose::ID_ROTATION, iTaSC::ACT_ALPHA, condata->orientweight); 01458 iktarget->constraint->registerCallback(copypose_callback, iktarget); 01459 iktarget->errorCallback = copypose_error; 01460 iktarget->controlType = controltype; 01461 // add the constraint 01462 if (condata->flag & CONSTRAINT_IK_TARGETAXIS) 01463 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, iktarget->targetName, armname, "", ikscene->channels[iktarget->channel].tail); 01464 else 01465 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail); 01466 } 01467 break; 01468 case CONSTRAINT_IK_DISTANCE: 01469 iktarget->constraint = new iTaSC::Distance(bonelen); 01470 iktarget->constraint->setControlParameter(iTaSC::Distance::ID_DISTANCE, iTaSC::ACT_VALUE, condata->dist); 01471 iktarget->constraint->registerCallback(distance_callback, iktarget); 01472 iktarget->errorCallback = distance_error; 01473 // we can update the weight on each substep 01474 iktarget->constraint->substep(true); 01475 // add the constraint 01476 ret = scene->addConstraintSet(iktarget->constraintName, iktarget->constraint, armname, iktarget->targetName, ikscene->channels[iktarget->channel].tail); 01477 break; 01478 } 01479 if (!ret) 01480 break; 01481 } 01482 if (!ret || 01483 !scene->addCache(ikscene->cache) || 01484 !scene->addSolver(ikscene->solver) || 01485 !scene->initialize()) { 01486 delete ikscene; 01487 ikscene = NULL; 01488 } 01489 return ikscene; 01490 } 01491 01492 static void create_scene(Scene *scene, Object *ob) 01493 { 01494 bPoseChannel *pchan; 01495 01496 // create the IK scene 01497 for(pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= (bPoseChannel *)pchan->next) { 01498 // by construction there is only one tree 01499 PoseTree *tree = (PoseTree*)pchan->iktree.first; 01500 if (tree) { 01501 IK_Data* ikdata = get_ikdata(ob->pose); 01502 // convert tree in iTaSC::Scene 01503 IK_Scene* ikscene = convert_tree(scene, ob, pchan); 01504 if (ikscene) { 01505 ikscene->next = ikdata->first; 01506 ikdata->first = ikscene; 01507 } 01508 // delete the trees once we are done 01509 while(tree) { 01510 BLI_remlink(&pchan->iktree, tree); 01511 BLI_freelistN(&tree->targets); 01512 if(tree->pchan) MEM_freeN(tree->pchan); 01513 if(tree->parent) MEM_freeN(tree->parent); 01514 if(tree->basis_change) MEM_freeN(tree->basis_change); 01515 MEM_freeN(tree); 01516 tree = (PoseTree*)pchan->iktree.first; 01517 } 01518 } 01519 } 01520 } 01521 01522 static void init_scene(Object *ob) 01523 { 01524 if (ob->pose->ikdata) { 01525 for(IK_Scene* scene = ((IK_Data*)ob->pose->ikdata)->first; 01526 scene != NULL; 01527 scene = scene->next) { 01528 scene->channels[0].pchan->flag |= POSE_IKTREE; 01529 } 01530 } 01531 } 01532 01533 static void execute_scene(Scene* blscene, IK_Scene* ikscene, bItasc* ikparam, float ctime, float frtime) 01534 { 01535 int i; 01536 IK_Channel* ikchan; 01537 if (ikparam->flag & ITASC_SIMULATION) { 01538 for (i=0, ikchan=ikscene->channels; i<ikscene->numchan; i++, ++ikchan) { 01539 // In simulation mode we don't allow external contraint to change our bones, mark the channel done 01540 // also tell Blender that this channel is part of IK tree (cleared on each where_is_pose() 01541 ikchan->pchan->flag |= (POSE_DONE|POSE_CHAIN); 01542 ikchan->jointValid = 0; 01543 } 01544 } else { 01545 // in animation mode, we must get the bone position from action and constraints 01546 for(i=0, ikchan=ikscene->channels; i<ikscene->numchan; i++, ++ikchan) { 01547 if (!(ikchan->pchan->flag & POSE_DONE)) 01548 where_is_pose_bone(blscene, ikscene->blArmature, ikchan->pchan, ctime, 1); 01549 // tell blender that this channel was controlled by IK, it's cleared on each where_is_pose() 01550 ikchan->pchan->flag |= (POSE_DONE|POSE_CHAIN); 01551 ikchan->jointValid = 0; 01552 } 01553 } 01554 // only run execute the scene if at least one of our target is enabled 01555 for (i=ikscene->targets.size(); i > 0; --i) { 01556 IK_Target* iktarget = ikscene->targets[i-1]; 01557 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF)) 01558 break; 01559 } 01560 if (i == 0 && ikscene->armature->getNrOfConstraints() == 0) 01561 // all constraint disabled 01562 return; 01563 01564 // compute timestep 01565 double timestamp = ctime * frtime + 2147483.648; 01566 double timestep = frtime; 01567 bool reiterate = (ikparam->flag & ITASC_REITERATION) ? true : false; 01568 int numstep = (ikparam->flag & ITASC_AUTO_STEP) ? 0 : ikparam->numstep; 01569 bool simulation = true; 01570 01571 if (ikparam->flag & ITASC_SIMULATION) { 01572 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel); 01573 } 01574 else { 01575 // in animation mode we start from the pose after action and constraint 01576 convert_pose(ikscene); 01577 ikscene->armature->setJointArray(ikscene->jointArray); 01578 // and we don't handle velocity 01579 reiterate = true; 01580 simulation = false; 01581 // time is virtual, so take fixed value for velocity parameters (see itasc_update_param) 01582 // and choose 1s timestep to allow having velocity parameters in radiant 01583 timestep = 1.0; 01584 // use auto setup to let the solver test the variation of the joints 01585 numstep = 0; 01586 } 01587 01588 if (ikscene->cache && !reiterate && simulation) { 01589 iTaSC::CacheTS sts, cts; 01590 sts = cts = (iTaSC::CacheTS)(timestamp*1000.0+0.5); 01591 if (ikscene->cache->getPreviousCacheItem(ikscene->armature, 0, &cts) == NULL || cts == 0) { 01592 // the cache is empty before this time, reiterate 01593 if (ikparam->flag & ITASC_INITIAL_REITERATION) 01594 reiterate = true; 01595 } else { 01596 // can take the cache as a start point. 01597 sts -= cts; 01598 timestep = sts/1000.0; 01599 } 01600 } 01601 // don't cache if we are reiterating because we don't want to distroy the cache unnecessarily 01602 ikscene->scene->update(timestamp, timestep, numstep, false, !reiterate, simulation); 01603 if (reiterate) { 01604 // how many times do we reiterate? 01605 for (i=0; i<ikparam->numiter; i++) { 01606 if (ikscene->armature->getMaxJointChange() < ikparam->precision || 01607 ikscene->armature->getMaxEndEffectorChange() < ikparam->precision) 01608 break; 01609 ikscene->scene->update(timestamp, timestep, numstep, true, false, simulation); 01610 } 01611 if (simulation) { 01612 // one more fake iteration to cache 01613 ikscene->scene->update(timestamp, 0.0, 1, true, true, true); 01614 } 01615 } 01616 // compute constraint error 01617 for (i=ikscene->targets.size(); i > 0; --i) { 01618 IK_Target* iktarget = ikscene->targets[i-1]; 01619 if (!(iktarget->blenderConstraint->flag & CONSTRAINT_OFF)) { 01620 unsigned int nvalues; 01621 const iTaSC::ConstraintValues* values; 01622 values = iktarget->constraint->getControlParameters(&nvalues); 01623 iktarget->errorCallback(values, nvalues, iktarget); 01624 } 01625 } 01626 // Apply result to bone: 01627 // walk the ikscene->channels 01628 // for each, get the Frame of the joint corresponding to the bone relative to its parent 01629 // combine the parent and the joint frame to get the frame relative to armature 01630 // a backward translation of the bone length gives the head 01631 // if TY, compute the scale as the ratio of the joint length with rest pose length 01632 iTaSC::Armature* arm = ikscene->armature; 01633 KDL::Frame frame; 01634 double q_rest[3], q[3]; 01635 const KDL::Joint* joint; 01636 const KDL::Frame* tip; 01637 bPoseChannel* pchan; 01638 float scale; 01639 float length; 01640 float yaxis[3]; 01641 for (i=0, ikchan=ikscene->channels; i<ikscene->numchan; ++i, ++ikchan) { 01642 if (i == 0) { 01643 if (!arm->getRelativeFrame(frame, ikchan->tail)) 01644 break; 01645 // this frame is relative to base, make it relative to object 01646 ikchan->frame = ikscene->baseFrame * frame; 01647 } 01648 else { 01649 if (!arm->getRelativeFrame(frame, ikchan->tail, ikscene->channels[ikchan->parent].tail)) 01650 break; 01651 // combine with parent frame to get frame relative to object 01652 ikchan->frame = ikscene->channels[ikchan->parent].frame * frame; 01653 } 01654 // ikchan->frame is the tail frame relative to object 01655 // get bone length 01656 if (!arm->getSegment(ikchan->tail, 3, joint, q_rest[0], q[0], tip)) 01657 break; 01658 if (joint->getType() == KDL::Joint::TransY) { 01659 // stretch bones have a TY joint, compute the scale 01660 scale = (float)(q[0]/q_rest[0]); 01661 // the length is the joint itself 01662 length = (float)q[0]; 01663 } 01664 else { 01665 scale = 1.0f; 01666 // for fixed bone, the length is in the tip (always along Y axis) 01667 length = tip->p(1); 01668 } 01669 // ready to compute the pose mat 01670 pchan = ikchan->pchan; 01671 // tail mat 01672 ikchan->frame.getValue(&pchan->pose_mat[0][0]); 01673 copy_v3_v3(pchan->pose_tail, pchan->pose_mat[3]); 01674 // shift to head 01675 copy_v3_v3(yaxis, pchan->pose_mat[1]); 01676 mul_v3_fl(yaxis, length); 01677 sub_v3_v3v3(pchan->pose_mat[3], pchan->pose_mat[3], yaxis); 01678 copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]); 01679 // add scale 01680 mul_v3_fl(pchan->pose_mat[0], scale); 01681 mul_v3_fl(pchan->pose_mat[1], scale); 01682 mul_v3_fl(pchan->pose_mat[2], scale); 01683 } 01684 if (i<ikscene->numchan) { 01685 // big problem 01686 ; 01687 } 01688 } 01689 01690 //--------------------------------------------------- 01691 // plugin interface 01692 // 01693 void itasc_initialize_tree(struct Scene *scene, Object *ob, float ctime) 01694 { 01695 bPoseChannel *pchan; 01696 int count = 0; 01697 01698 if (ob->pose->ikdata != NULL && !(ob->pose->flag & POSE_WAS_REBUILT)) { 01699 init_scene(ob); 01700 return; 01701 } 01702 // first remove old scene 01703 itasc_clear_data(ob->pose); 01704 // we should handle all the constraint and mark them all disabled 01705 // for blender but we'll start with the IK constraint alone 01706 for(pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= (bPoseChannel *)pchan->next) { 01707 if(pchan->constflag & PCHAN_HAS_IK) 01708 count += initialize_scene(ob, pchan); 01709 } 01710 // if at least one tree, create the scenes from the PoseTree stored in the channels 01711 if (count) 01712 create_scene(scene, ob); 01713 itasc_update_param(ob->pose); 01714 // make sure we don't rebuilt until the user changes something important 01715 ob->pose->flag &= ~POSE_WAS_REBUILT; 01716 } 01717 01718 void itasc_execute_tree(struct Scene *scene, struct Object *ob, struct bPoseChannel *pchan, float ctime) 01719 { 01720 if (ob->pose->ikdata) { 01721 IK_Data* ikdata = (IK_Data*)ob->pose->ikdata; 01722 bItasc* ikparam = (bItasc*) ob->pose->ikparam; 01723 // we need default parameters 01724 if (!ikparam) ikparam = &DefIKParam; 01725 01726 for (IK_Scene* ikscene = ikdata->first; ikscene; ikscene = ikscene->next) { 01727 if (ikscene->channels[0].pchan == pchan) { 01728 float timestep = scene->r.frs_sec_base/scene->r.frs_sec; 01729 if (ob->pose->flag & POSE_GAME_ENGINE) { 01730 timestep = ob->pose->ctime; 01731 // limit the timestep to avoid excessive number of iteration 01732 if (timestep > 0.2f) 01733 timestep = 0.2f; 01734 } 01735 execute_scene(scene, ikscene, ikparam, ctime, timestep); 01736 break; 01737 } 01738 } 01739 } 01740 } 01741 01742 void itasc_release_tree(struct Scene *scene, struct Object *ob, float ctime) 01743 { 01744 // not used for iTaSC 01745 } 01746 01747 void itasc_clear_data(struct bPose *pose) 01748 { 01749 if (pose->ikdata) { 01750 IK_Data* ikdata = (IK_Data*)pose->ikdata; 01751 for (IK_Scene* scene = ikdata->first; scene; scene = ikdata->first) { 01752 ikdata->first = scene->next; 01753 delete scene; 01754 } 01755 MEM_freeN(ikdata); 01756 pose->ikdata = NULL; 01757 } 01758 } 01759 01760 void itasc_clear_cache(struct bPose *pose) 01761 { 01762 if (pose->ikdata) { 01763 IK_Data* ikdata = (IK_Data*)pose->ikdata; 01764 for (IK_Scene* scene = ikdata->first; scene; scene = scene->next) { 01765 if (scene->cache) 01766 // clear all cache but leaving the timestamp 0 (=rest pose) 01767 scene->cache->clearCacheFrom(NULL, 1); 01768 } 01769 } 01770 } 01771 01772 void itasc_update_param(struct bPose *pose) 01773 { 01774 if (pose->ikdata && pose->ikparam) { 01775 IK_Data* ikdata = (IK_Data*)pose->ikdata; 01776 bItasc* ikparam = (bItasc*)pose->ikparam; 01777 for (IK_Scene* ikscene = ikdata->first; ikscene; ikscene = ikscene->next) { 01778 double armlength = ikscene->armature->getArmLength(); 01779 ikscene->solver->setParam(iTaSC::Solver::DLS_LAMBDA_MAX, ikparam->dampmax*armlength); 01780 ikscene->solver->setParam(iTaSC::Solver::DLS_EPSILON, ikparam->dampeps*armlength); 01781 if (ikparam->flag & ITASC_SIMULATION) { 01782 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, ikparam->minstep); 01783 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, ikparam->maxstep); 01784 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, ikparam->maxvel); 01785 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, ikparam->feedback); 01786 } else { 01787 // in animation mode timestep is 1s by convention => 01788 // qmax becomes radiant and feedback becomes fraction of error gap corrected in one iteration 01789 ikscene->scene->setParam(iTaSC::Scene::MIN_TIMESTEP, 1.0); 01790 ikscene->scene->setParam(iTaSC::Scene::MAX_TIMESTEP, 1.0); 01791 ikscene->solver->setParam(iTaSC::Solver::DLS_QMAX, 0.52); 01792 ikscene->armature->setControlParameter(CONSTRAINT_ID_ALL, iTaSC::Armature::ID_JOINT, iTaSC::ACT_FEEDBACK, 0.8); 01793 } 01794 } 01795 } 01796 } 01797 01798 void itasc_test_constraint(struct Object *ob, struct bConstraint *cons) 01799 { 01800 struct bKinematicConstraint *data = (struct bKinematicConstraint *)cons->data; 01801 01802 /* only for IK constraint */ 01803 if (cons->type != CONSTRAINT_TYPE_KINEMATIC || data == NULL) 01804 return; 01805 01806 switch (data->type) { 01807 case CONSTRAINT_IK_COPYPOSE: 01808 case CONSTRAINT_IK_DISTANCE: 01809 /* cartesian space constraint */ 01810 break; 01811 } 01812 } 01813