llik.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. /**
  2. * @file llik.h
  3. * @brief Implementation of LLIK::Solver class and related helpers.
  4. *
  5. * $LicenseInfo:firstyear=2021&license=viewergpl$
  6. *
  7. * Copyright (c) 2021, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #ifndef LL_LLIK_H
  33. #define LL_LLIK_H
  34. #include <map>
  35. #include <memory>
  36. #include <set>
  37. #include <string>
  38. #include <vector>
  39. #include "hbfastmap.h"
  40. #include "llmath.h"
  41. #include "llsingleton.h"
  42. #include "llvector3.h"
  43. // EXPERIMENTAL: disabled since we hit the constraint during the swing; perhaps
  44. // some twist can get us closer
  45. #define LLIK_EXPERIMENTAL 0
  46. // Inverse Kinematics (IK) for humanoid character.
  47. //
  48. // The Solver uses Forward and Backward Reaching Inverse Kinematics (FABRIK)
  49. // algorightm to iterate toward a solution:
  50. //
  51. // http://andreasaristidou.com/FABRIK.html
  52. //
  53. // The Joints can have Constraints which limite their parent-local orientations.
  54. class LLJoint;
  55. namespace LLIK
  56. {
  57. class Solver;
  58. class Joint;
  59. constexpr F32 IK_DEFAULT_ACCEPTABLE_ERROR = 5.0e-4f; // Half a millimeter
  60. // Local flags:
  61. constexpr U8 CONFIG_FLAG_LOCAL_POS = 1 << 0;
  62. constexpr U8 CONFIG_FLAG_LOCAL_ROT = 1 << 1;
  63. constexpr U8 CONFIG_FLAG_LOCAL_SCALE = 1 << 2;
  64. constexpr U8 CONFIG_FLAG_DISABLE_CONSTRAINT = 1 << 3;
  65. // Config flags:
  66. constexpr U8 CONFIG_FLAG_TARGET_POS = 1 << 4;
  67. constexpr U8 CONFIG_FLAG_TARGET_ROT = 1 << 5;
  68. #if LLIK_EXPERIMENTAL
  69. constexpr U8 CONFIG_FLAG_HAS_DELEGATED = 1 << 6;
  70. #endif
  71. constexpr U8 CONFIG_FLAG_ENABLE_REPORTING = 1 << 7;
  72. constexpr U8 MASK_POS = CONFIG_FLAG_TARGET_POS | CONFIG_FLAG_LOCAL_POS;
  73. constexpr U8 MASK_ROT = CONFIG_FLAG_TARGET_ROT | CONFIG_FLAG_LOCAL_ROT;
  74. constexpr U8 MASK_TRANSFORM = MASK_POS | MASK_ROT;
  75. constexpr U8 MASK_LOCAL = CONFIG_FLAG_LOCAL_POS | CONFIG_FLAG_LOCAL_ROT |
  76. CONFIG_FLAG_DISABLE_CONSTRAINT;
  77. constexpr U8 MASK_TARGET = CONFIG_FLAG_TARGET_POS | CONFIG_FLAG_TARGET_ROT;
  78. // This mask relates to LLJointState::Usage enum
  79. constexpr U8 MASK_JOINT_STATE_USAGE = CONFIG_FLAG_LOCAL_POS |
  80. CONFIG_FLAG_LOCAL_ROT |
  81. CONFIG_FLAG_LOCAL_SCALE;
  82. // IK has adjusted local_rot
  83. constexpr U8 IK_FLAG_LOCAL_ROT = 1 << 1;
  84. constexpr U8 IK_FLAG_ACTIVE = 1 << 5;
  85. // local_rot is locked during IK
  86. constexpr U8 IK_FLAG_LOCAL_ROT_LOCKED = 1 << 7;
  87. // A Constraint exists at the tip of Joint and limits the range of
  88. // Joint.mLocalRot.
  89. class Constraint
  90. {
  91. public:
  92. typedef std::shared_ptr<Constraint> ptr_t;
  93. enum ConstraintType
  94. {
  95. NULL_CONSTRAINT,
  96. UNKNOWN_CONSTRAINT,
  97. SIMPLE_CONE_CONSTRAINT,
  98. TWIST_LIMITED_CONE_CONSTRAINT,
  99. ELBOW_CONSTRAINT,
  100. KNEE_CONSTRAINT,
  101. ACUTE_ELLIPSOIDAL_CONE_CONSTRAINT,
  102. DOUBLE_LIMITED_HINGE_CONSTRAINT
  103. };
  104. LL_INLINE Constraint()
  105. : mType(NULL_CONSTRAINT)
  106. {
  107. }
  108. Constraint(ConstraintType type, const LLSD& parameters);
  109. virtual ~Constraint() = default;
  110. virtual LLSD asLLSD() const;
  111. virtual U64 getHash() const;
  112. LL_INLINE ConstraintType getType() const { return mType; }
  113. const std::string& typeToName() const;
  114. bool enforce(Joint& joint) const;
  115. virtual LLQuaternion computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const = 0;
  116. virtual LLQuaternion minimizeTwist(const LLQuaternion& j_loc_rot) const;
  117. // All Constraints have a forward axis
  118. LL_INLINE const LLVector3& getForwardAxis() const
  119. {
  120. return mForward;
  121. }
  122. LL_INLINE virtual bool allowsTwist() const { return true; }
  123. protected:
  124. LLVector3 mForward;
  125. ConstraintType mType;
  126. };
  127. // SimpleCone Constrainte can twist arbitrarily about its 'forward' axis
  128. // but has a uniform bend limit for orientations perpendicular to 'forward'.
  129. class SimpleCone : public Constraint
  130. {
  131. // Constrains forward axis inside cone.
  132. //
  133. // / max_angle
  134. // /
  135. // ---@--------> forward
  136. // `
  137. // ` max_angle
  138. //
  139. public:
  140. SimpleCone(const LLVector3& forward_axis, F32 max_angle);
  141. SimpleCone(const LLSD& parameters);
  142. LLSD asLLSD() const override;
  143. U64 getHash() const override;
  144. LLQuaternion computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const override;
  145. private:
  146. F32 mMaxAngle;
  147. F32 mCosConeAngle;
  148. F32 mSinConeAngle;
  149. };
  150. // TwistLimitedCone Constrainte can has limited twist about its 'forward' axis
  151. // but has a uniform bend limit for orientations perpendicular to 'forward'.
  152. class TwistLimitedCone : public Constraint
  153. {
  154. // A constraint for the shoulder. Like SimpleCone but with limited twist
  155. //
  156. // View from side: View with foward out of page:
  157. // max_twist
  158. // / cone_angle | /
  159. // / |/
  160. // ---@--------> forward_axis ----(o)----> perp_axis
  161. // ` /|
  162. // ` cone_angle / |
  163. // min_twist
  164. //
  165. //
  166. public:
  167. TwistLimitedCone(const LLVector3& forward_axis, F32 cone_angle,
  168. F32 min_twist, F32 max_twist);
  169. TwistLimitedCone(const LLSD& parameters);
  170. LLSD asLLSD() const override;
  171. U64 getHash() const override;
  172. LLQuaternion computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const override;
  173. LLQuaternion minimizeTwist(const LLQuaternion& j_loc_rot) const override;
  174. private:
  175. F32 mConeAngle;
  176. F32 mCosConeAngle;
  177. F32 mSinConeAngle;
  178. F32 mMinTwist;
  179. F32 mMaxTwist;
  180. };
  181. // ElbowConstraint can only bend (with limits) about its 'pivot' axis
  182. // and allows limited twist about its 'forward' axis.
  183. class ElbowConstraint : public Constraint
  184. {
  185. // A Constraint for Elbow: limited hinge with limited twist about forward
  186. // (forearm) axis.
  187. //
  188. // View from the side, View with foreward axis out of page:
  189. // with pivot axis out of page:
  190. // up max_twist
  191. // / max_bend | /
  192. // / |/
  193. // ---(o)--------+ forward ----(o)----> left
  194. // ` /|
  195. // ` min_bend / |
  196. // min_twist
  197. //
  198. public:
  199. ElbowConstraint(const LLVector3& forward_axis, const LLVector3& pivot_axis,
  200. F32 min_bend, F32 max_bend, F32 min_twist, F32 max_twist);
  201. ElbowConstraint(const LLSD& parameters);
  202. LLSD asLLSD() const override;
  203. U64 getHash() const override;
  204. LLQuaternion computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const override;
  205. LLQuaternion minimizeTwist(const LLQuaternion& j_loc_rot) const override;
  206. private:
  207. LLVector3 mPivotAxis;
  208. LLVector3 mLeft;
  209. F32 mMinBend;
  210. F32 mMaxBend;
  211. F32 mMinTwist;
  212. F32 mMaxTwist;
  213. };
  214. // KneeConstraint only allows bend (limited) about its 'pivot' axis but does
  215. // not allow any twist about its 'forward' axis.
  216. class KneeConstraint : public Constraint
  217. {
  218. // A Constraint for knee, or finger. Like ElbowConstraint but
  219. // no twist allowed, min/max limits on angle about pivot.
  220. //
  221. // View from the side, with pivot axis out of page:
  222. //
  223. // / max_bend
  224. // /
  225. // ---(o)--------+
  226. // `
  227. // ` min_bend
  228. //
  229. public:
  230. KneeConstraint(const LLVector3& forward_axis, const LLVector3& pivot_axis,
  231. F32 min_bend, F32 max_bend);
  232. KneeConstraint(const LLSD& parameters);
  233. LLSD asLLSD() const override;
  234. U64 getHash() const override;
  235. LLQuaternion computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const override;
  236. LL_INLINE bool allowsTwist() const override { return false; }
  237. LLQuaternion minimizeTwist(const LLQuaternion& j_loc_rot) const override;
  238. private:
  239. LLVector3 mPivotAxis;
  240. LLVector3 mLeft;
  241. F32 mMinBend;
  242. F32 mMaxBend;
  243. };
  244. // AcuteEllipsoidalCone is like SimpleCone but with asymmetric radiuses in the
  245. // up, left, down, right directions. In other words: it has non-symmetric bend
  246. // limits for axes perpendicular to its 'forward' axix. It was implemented
  247. // mostly as an exercise, since it is similar to the Constraint described in
  248. // the original FABRIK papter. The geometry of the ellipsoidal boundary are
  249. // described by defining the forward offset of the "cross" of radiuses. Each
  250. // quadrant of the cross in the left-up plane is bound by an elliptical curve
  251. // that depends on its bounding radiuses.
  252. //
  253. // up left |
  254. // | / | /
  255. // |/ |/
  256. // ---@------------------+
  257. // forward /|
  258. //
  259. class AcuteEllipsoidalCone : public Constraint
  260. {
  261. public:
  262. AcuteEllipsoidalCone(const LLVector3& forw_axis, const LLVector3& up_axis,
  263. F32 forward, F32 up, F32 left, F32 down, F32 right);
  264. AcuteEllipsoidalCone(const LLSD& parameters);
  265. LLSD asLLSD() const override;
  266. U64 getHash() const override;
  267. LLQuaternion computeAdjustedLocalRot(const LLQuaternion& j_loc_rot) const override;
  268. private:
  269. LLVector3 mUp;
  270. LLVector3 mLeft;
  271. F32 mXForward;
  272. F32 mXUp;
  273. F32 mXDown;
  274. F32 mXLeft;
  275. F32 mXRight;
  276. // for each quadrant we cache these parameters to help
  277. // us project onto each partial ellipse.
  278. F32 mQuadrantScales[4];
  279. F32 mQuadrantCosAngles[4];
  280. F32 mQuadrantCotAngles[4];
  281. };
  282. // The DoubleLimitedHinge constraint is intended for uses on Joints like
  283. // the wrist, or first finger Joints. It allows for yaw and pitch bends
  284. // but zero twist.
  285. class DoubleLimitedHinge : public Constraint
  286. {
  287. // A Constraint for first finger bones.
  288. // No twist allowed, min/max limits on yaw, then pitch.
  289. //
  290. // View from above View from right
  291. // with UP out of page (remember to use right-hand-rule)
  292. //
  293. // left_axis up_axis
  294. // | |
  295. // | / max_yaw_angle | / min_pitch_angle
  296. // |/ |/
  297. // ---(o)--------> forward_axis ---(x)--------> forward_axis
  298. // up ` left `
  299. // ` min_yaw_angle ` max_pitch_angle
  300. //
  301. public:
  302. DoubleLimitedHinge(const LLVector3& forward_axis, const LLVector3& up_axis,
  303. F32 min_yaw, F32 max_yaw, F32 min_pitch, F32 max_pitch);
  304. DoubleLimitedHinge(const LLSD& parameters);
  305. LLSD asLLSD() const override;
  306. U64 getHash() const override;
  307. LLQuaternion computeAdjustedLocalRot(const LLQuaternion& joint_loc_rot) const override;
  308. LLQuaternion minimizeTwist(const LLQuaternion& joint_loc_rot) const override;
  309. private:
  310. LLVector3 mUp;
  311. LLVector3 mLeft; // mUp X mForward
  312. F32 mMinYaw;
  313. F32 mMaxYaw;
  314. F32 mMinPitch;
  315. F32 mMaxPitch;
  316. };
  317. // Joint represents a constrained bone in the skeleton heirarchy. It typically
  318. // has a parent Joint, a fixed mLocalPos position in its parent's local-frame,
  319. // and a fixed mBone to its 'end' position in its own local-frame. A summary of
  320. // its important data members is as follows:
  321. //
  322. // mLocalPos = tip position in parent's local-frame
  323. // mLocalRot = orientation of Joint's tip relative to parent's local-frame
  324. // mBone = invarient end position in local-frame
  325. // mPos = tip position in world-frame (we call it 'world-frame'
  326. // but really it is the 'root-frame' of the Skeleton hierarchy).
  327. // mRot = orientation of Joint in world-frame.
  328. //
  329. // Some important formula to keep in mind:
  330. //
  331. // mPos = mParent->mPos + mLocalPos * mParent->mRot
  332. // mRot = mLocalRot * mParent->mRot
  333. //
  334. // The world-frame 'end' position of the Joint can be calculated:
  335. //
  336. // world_end_pos = mPos + mBone * mRot
  337. class Joint
  338. {
  339. protected:
  340. LOG_CLASS(LLIK::Joint);
  341. public:
  342. class Config
  343. {
  344. public:
  345. LL_INLINE Config()
  346. : mFlags(0)
  347. {
  348. }
  349. LL_INLINE bool hasLocalPos() const
  350. {
  351. return mFlags & CONFIG_FLAG_LOCAL_POS;
  352. }
  353. LL_INLINE void setLocalPos(const LLVector3& pos)
  354. {
  355. mLocalPos = pos;
  356. mFlags |= CONFIG_FLAG_LOCAL_POS;
  357. }
  358. LL_INLINE bool hasLocalRot() const
  359. {
  360. return mFlags & CONFIG_FLAG_LOCAL_ROT;
  361. }
  362. LL_INLINE bool hasLocalScale() const
  363. {
  364. return mFlags & CONFIG_FLAG_LOCAL_SCALE;
  365. }
  366. LL_INLINE void setLocalRot(const LLQuaternion& rot)
  367. {
  368. mLocalRot = rot;
  369. mLocalRot.normalize();
  370. mFlags |= CONFIG_FLAG_LOCAL_ROT;
  371. }
  372. LL_INLINE bool constraintIsDisabled() const
  373. {
  374. return mFlags & CONFIG_FLAG_DISABLE_CONSTRAINT;
  375. }
  376. LL_INLINE void disableConstraint()
  377. {
  378. mFlags |= CONFIG_FLAG_DISABLE_CONSTRAINT;
  379. }
  380. LL_INLINE const LLVector3& getLocalPos() const
  381. {
  382. return mLocalPos;
  383. }
  384. LL_INLINE const LLQuaternion& getLocalRot() const
  385. {
  386. return mLocalRot;
  387. }
  388. LL_INLINE bool hasTargetPos() const
  389. {
  390. return mFlags & CONFIG_FLAG_TARGET_POS;
  391. }
  392. LL_INLINE void setTargetPos(const LLVector3& pos)
  393. {
  394. mTargetPos = pos;
  395. mFlags |= CONFIG_FLAG_TARGET_POS;
  396. }
  397. LL_INLINE const LLVector3& getTargetPos() const
  398. {
  399. return mTargetPos;
  400. }
  401. LL_INLINE bool hasTargetRot() const
  402. {
  403. return mFlags & CONFIG_FLAG_TARGET_ROT;
  404. }
  405. LL_INLINE void setTargetRot(const LLQuaternion& rot)
  406. {
  407. mTargetRot = rot;
  408. mTargetRot.normalize();
  409. mFlags |= CONFIG_FLAG_TARGET_ROT;
  410. }
  411. LL_INLINE const LLQuaternion& getTargetRot() const
  412. {
  413. return mTargetRot;
  414. }
  415. LL_INLINE void setLocalScale(const LLVector3& scale)
  416. {
  417. mLocalScale = scale;
  418. mFlags |= CONFIG_FLAG_LOCAL_SCALE;
  419. }
  420. LL_INLINE const LLVector3& getLocalScale() const
  421. {
  422. return mLocalScale;
  423. }
  424. LL_INLINE void enableReporting(S32 reqid)
  425. {
  426. mFlags |= CONFIG_FLAG_ENABLE_REPORTING;
  427. }
  428. #if LLIK_EXPERIMENTAL
  429. LL_INLINE void delegate()
  430. {
  431. mFlags |= CONFIG_FLAG_HAS_DELEGATED;
  432. }
  433. LL_INLINE bool hasDelegated() const
  434. {
  435. return mFlags & CONFIG_FLAG_HAS_DELEGATED;
  436. }
  437. #endif
  438. LL_INLINE U8 getFlags() const { return mFlags; }
  439. void updateFrom(const Config& other_config);
  440. private:
  441. LLVector3 mLocalScale;
  442. LLVector3 mLocalPos;
  443. LLVector3 mTargetPos;
  444. LLQuaternion mLocalRot;
  445. LLQuaternion mTargetRot;
  446. U8 mFlags; // Per-feature bits
  447. };
  448. typedef std::shared_ptr<Joint> ptr_t;
  449. typedef std::vector<ptr_t> child_vec_t;
  450. Joint(LLJoint* info);
  451. void resetFromInfo();
  452. void addChild(const ptr_t& child);
  453. void setParent(const ptr_t& parent);
  454. void resetRecursively();
  455. void relaxRotationsRecursively(F32 blend_factor);
  456. F32 recursiveComputeLongestChainLength(F32 length) const;
  457. void updateGeometry(const LLVector3& local_pos, const LLVector3& bone);
  458. LLVector3 computeEndTargetPos() const;
  459. LLVector3 computeWorldTipOffset() const;
  460. void updateEndInward();
  461. void updateEndOutward();
  462. void updateBranchRoot();
  463. void updateInward(const ptr_t& child);
  464. void updatePosAndRotFromParent();
  465. void updateOutward();
  466. void applyLocalRot();
  467. void updateLocalRot();
  468. LLQuaternion computeParentRot() const;
  469. void updateChildLocalRots() const;
  470. LL_INLINE LLVector3 computePosFromParent() const
  471. {
  472. return mParent->mPos + mLocalPos * mParent->mRot;
  473. }
  474. LL_INLINE const LLVector3& getWorldTipPos() const
  475. {
  476. return mPos;
  477. }
  478. LL_INLINE const LLQuaternion& getWorldRot() const
  479. {
  480. return mRot;
  481. }
  482. LL_INLINE LLVector3 computeWorldEndPos() const
  483. {
  484. return mPos + mBone * mRot;
  485. }
  486. // Only call this if you know what you are doing: this should only be
  487. // called once before starting IK algorithm iterations.
  488. LL_INLINE void setLocalPos(const LLVector3& pos)
  489. {
  490. mLocalPos = pos.scaledVec(mLocalScale);
  491. mLocalPosLength = mLocalPos.length();
  492. if (!mParent)
  493. {
  494. mPos = mLocalPos;
  495. }
  496. }
  497. void setLocalScale(const LLVector3& scale);
  498. // Returns local_pos with any non-uniform scale from the "info" removed.
  499. LLVector3 getPreScaledLocalPos() const;
  500. void setLocalRot(const LLQuaternion& new_local_rot);
  501. LL_INLINE void setWorldPos(const LLVector3& p) { mPos = p; }
  502. LL_INLINE void setWorldRot(const LLQuaternion& rot)
  503. {
  504. mRot = rot;
  505. }
  506. void adjustWorldRot(const LLQuaternion& adjustment);
  507. LL_INLINE void shiftPos(const LLVector3& shift) { mPos += shift; }
  508. LL_INLINE void setConfig(const Config& config)
  509. {
  510. // We only remember the config here; it gets applied later when we
  511. // build the chains.
  512. mConfig = &config;
  513. mConfigFlags = config.getFlags();
  514. }
  515. void setTargetPos(const LLVector3& pos);
  516. LL_INLINE LLVector3 getTargetPos()
  517. {
  518. return mConfig->getTargetPos();
  519. }
  520. LL_INLINE const Config* getConfig() const { return mConfig; }
  521. LL_INLINE bool hasPosTarget() const
  522. {
  523. return mConfigFlags & CONFIG_FLAG_TARGET_POS;
  524. }
  525. LL_INLINE bool hasRotTarget() const
  526. {
  527. return mConfigFlags & CONFIG_FLAG_TARGET_ROT;
  528. }
  529. LL_INLINE U8 getConfigFlags() const { return mConfigFlags; }
  530. LL_INLINE U8 getHarvestFlags() const
  531. {
  532. return (mConfigFlags | mIkFlags) & MASK_LOCAL;
  533. }
  534. LL_INLINE void resetFlags()
  535. {
  536. mConfig = NULL;
  537. mConfigFlags = 0;
  538. // Root Joint always has IK_FLAG_LOCAL_ROT_LOCKED set
  539. mIkFlags = mParent ? 0 : IK_FLAG_LOCAL_ROT_LOCKED;
  540. }
  541. void lockLocalRot(const LLQuaternion& local_rot);
  542. LL_INLINE void setConstraint(std::shared_ptr<Constraint> constraint)
  543. {
  544. mConstraint = constraint;
  545. }
  546. bool enforceConstraint();
  547. void updateWorldTransformsRecursively();
  548. LL_INLINE const LLQuaternion& getLocalRot() const
  549. {
  550. return mLocalRot;
  551. }
  552. LL_INLINE S16 getID() const { return mID; }
  553. LL_INLINE const LLVector3& getBone() const { return mBone; }
  554. LL_INLINE const LLVector3& getLocalPos() const { return mLocalPos; }
  555. LL_INLINE const LLVector3& getLocalScale() const
  556. {
  557. return mLocalScale;
  558. }
  559. LL_INLINE F32 getBoneLength() const { return mBone.length(); }
  560. LL_INLINE F32 getLocalPosLength() const { return mLocalPosLength; }
  561. LL_INLINE ptr_t getParent() { return mParent; }
  562. LL_INLINE void activate()
  563. {
  564. mIkFlags |= IK_FLAG_ACTIVE;
  565. }
  566. LL_INLINE bool isActive() const
  567. {
  568. return mIkFlags & IK_FLAG_ACTIVE;
  569. }
  570. LL_INLINE bool hasDisabledConstraint() const
  571. {
  572. return mConfigFlags & CONFIG_FLAG_DISABLE_CONSTRAINT;
  573. }
  574. // Joint::mLocalRot is considered "locked" when its mConfigFlag's
  575. // CONFIG_FLAG_LOCAL_ROT bit is set
  576. LL_INLINE bool localRotLocked() const
  577. {
  578. return mIkFlags & IK_FLAG_LOCAL_ROT_LOCKED;
  579. }
  580. LL_INLINE size_t getNumChildren() const
  581. {
  582. return mChildren.size();
  583. }
  584. ptr_t getSingleActiveChild();
  585. void transformTargetsToParentLocal(std::vector<LLVector3>& ltargets) const;
  586. bool swingTowardTargets(const std::vector<LLVector3>& local_targets,
  587. const std::vector<LLVector3>& world_targets);
  588. #if LLIK_EXPERIMENTAL
  589. void twistTowardTargets(const std::vector<LLVector3>& local_targets,
  590. const std::vector<LLVector3>& world_targets);
  591. #endif
  592. void untwist();
  593. // We call flagForHarvest() when we expect the joint to be updated by IK so
  594. // we know to harvest its mLocalRot later.
  595. LL_INLINE void flagForHarvest()
  596. {
  597. mIkFlags |= IK_FLAG_LOCAL_ROT;
  598. }
  599. void collectTargetPositions(std::vector<LLVector3>& local_targets,
  600. std::vector<LLVector3>& world_targets) const;
  601. protected:
  602. void reset();
  603. void relaxRot(F32 blend_factor);
  604. protected:
  605. ptr_t mParent;
  606. Constraint::ptr_t mConstraint;
  607. // Pointer into Solver::mJointConfigs
  608. const Config* mConfig;
  609. const LLJoint* mInfoPtr;
  610. // List of joint_ids attached to this one.
  611. typedef std::vector<ptr_t> child_list_t;
  612. child_list_t mChildren;
  613. LLVector3 mLocalScale;
  614. LLVector3 mLocalPos; // Current pos in parent-frame
  615. LLVector3 mPos; // Pos in world-frame
  616. // The fundamental position formula is:
  617. // mPos = mParent->mPos + mLocalPos * mParent->mRot;
  618. // Note: there is no mDefaultLocalRot because it is identity
  619. LLQuaternion mLocalRot; // Orientations in parent-frame
  620. LLQuaternion mRot;
  621. // The fundamental orientations formula is:
  622. // mRot = mLocalRot * mParent->mRot
  623. LLVector3 mBone;
  624. // There is another fundamental formula:
  625. // world_end_pos = mPos + mBone * mRot
  626. F32 mLocalPosLength; // Cached copy of mLocalPos.length()
  627. S16 mID;
  628. U8 mConfigFlags; // Cache of mConfig->mFlags
  629. U8 mIkFlags; // Flags for IK calculations
  630. };
  631. // The Solver maintains a skeleton of connected Joints and computes the
  632. // parent-relative orientations to allow end-effectors to reach their targets.
  633. class Solver
  634. {
  635. protected:
  636. LOG_CLASS(LLIK::Solver);
  637. public:
  638. typedef std::map<S16, Joint::ptr_t> joint_map_t;
  639. typedef std::vector<S16> S16_vec_t;
  640. typedef std::map<S16, Joint::Config> joint_config_map_t;
  641. typedef std::vector<Joint::ptr_t> joint_list_t;
  642. typedef std::map<S16, joint_list_t> chain_map_t;
  643. LL_INLINE Solver()
  644. : mRootID(-1),
  645. mAcceptableError(IK_DEFAULT_ACCEPTABLE_ERROR),
  646. mLastError(0.f)
  647. {
  648. }
  649. // Puts skeleton back into default orientation (e.g. T-Pose for a humanoid
  650. // character)
  651. void resetSkeleton();
  652. // Computes the offset from the "tip" of from_id to the "end" of to_id or
  653. // the negative when from_id > to_id
  654. LLVector3 computeReach(S16 to_id, S16 from_id) const;
  655. // Adds a Joint to the skeleton.
  656. void addJoint(S16 joint_id, S16 parent_id, LLJoint* info_ptr,
  657. const Constraint::ptr_t& constraint);
  658. // Apply configs and return 'true' if something changed
  659. bool updateJointConfigs(const joint_config_map_t& configs);
  660. // Solves the IK problem for the given list of joint configurations
  661. F32 solve();
  662. // Specifies a joint as a 'wrist'. Will be used to help 'drop the elbow' of
  663. // the arm to achieve a more realistic solution.
  664. void addWristID(S16 wrist_id);
  665. LL_INLINE void setRootID(S16 root_id) { mRootID = root_id; }
  666. LL_INLINE S16 getRootID() const { return mRootID; }
  667. LL_INLINE const joint_list_t getActiveJoints() const
  668. {
  669. return mActiveJoints;
  670. }
  671. // Specifies the list of joint Ids that should be considered as sub-bases
  672. // e.g. joints that are known to have multipe child chains, like the chest
  673. // (chains on left and right collar children) or wrists (chain for each
  674. // fingers).
  675. LL_INLINE void setSubBaseIds(const std::set<S16>& ids)
  676. {
  677. mSubBaseIds = ids;
  678. }
  679. // Set list of joint ids that should be considered sub-roots where the IK
  680. // chains stop. This HACK was used to remove the spine from the solver
  681. // before spine constraints were working.
  682. LL_INLINE void setSubRootIds(const std::set<S16>& ids)
  683. {
  684. mSubRootIds = ids;
  685. }
  686. // Per-Joint property accessors from outside Solver
  687. LLQuaternion getJointLocalRot(S16 joint_id) const;
  688. LLVector3 getJointLocalPos(S16 joint_id) const;
  689. bool getJointLocalTransform(S16 joint_id, LLVector3& pos,
  690. LLQuaternion& rot) const;
  691. LLVector3 getJointWorldEndPos(S16 joint_id) const;
  692. LLQuaternion getJointWorldRot(S16 joint_id) const;
  693. void resetJointGeometry(S16 joint_id, const Constraint::ptr_t& constraint);
  694. LL_INLINE void setAcceptableError(F32 slop) { mAcceptableError = slop; }
  695. private:
  696. // Sometimes we cannot rely on the skeleton topology to determine whether a
  697. // Joint is a sub-base or not. So so we offer this workaround: outside
  698. // logic can supply a whitelist of sub-base ids.
  699. LL_INLINE bool isSubBase(S16 joint_id) const
  700. {
  701. return mSubBaseIds.count(joint_id);
  702. }
  703. LL_INLINE bool isSubRoot(S16 joint_id) const
  704. {
  705. return mSubRootIds.count(joint_id);
  706. }
  707. void dropElbow(const Joint::ptr_t& wrist_joint);
  708. void rebuildAllChains();
  709. void buildChain(Joint::ptr_t joint, joint_list_t& chain,
  710. std::set<S16>& sub_bases);
  711. void executeFabrikInward(const joint_list_t& chain);
  712. void executeFabrikOutward(const joint_list_t& chain);
  713. void shiftChainToBase(const joint_list_t& chain);
  714. void executeFabrikPass();
  715. void enforceConstraintsOutward();
  716. void untwistChain(const joint_list_t& chain);
  717. F32 measureMaxError();
  718. F32 solveOnce();
  719. void executeFabrik(bool constrain = false, bool drop_elbow = false,
  720. bool untwist = false);
  721. #if LLIK_EXPERIMENTAL
  722. void executeCcdPass(bool constrain);
  723. void executeCcd(bool constrain = false, bool drop_elbow = false,
  724. bool untwist = false);
  725. void executeCcdInward(const joint_list_t& chain, bool constrain);
  726. void adjustTargets(joint_config_map_t& targets);
  727. #endif
  728. private:
  729. joint_map_t mSkeleton;
  730. joint_config_map_t mJointConfigs;
  731. chain_map_t mChainMap;
  732. std::set<S16> mSubBaseIds; // HACK: whitelist of sub-bases
  733. std::set<S16> mSubRootIds; // HACK: whitelist of sub-roots
  734. std::set<Joint::ptr_t> mActiveRoots;
  735. // Joints with non-default local-pos
  736. std::vector<Joint::ptr_t> mActiveJoints;
  737. joint_list_t mWristJoints;
  738. F32 mAcceptableError;
  739. F32 mLastError;
  740. // ID number of the root joint for this skeleton
  741. S16 mRootID;
  742. };
  743. } // namespace LLIK
  744. // Constraints are 'stateless' configurations so we use a Factory pattern to
  745. // allocate them, which allows multiple Joints with identical constraint
  746. // configs to use a single Constraint instance.
  747. class LLIKConstraintFactory : public LLSingleton<LLIKConstraintFactory>
  748. {
  749. friend class LLSingleton<LLIKConstraintFactory>;
  750. protected:
  751. LOG_CLASS(LLIKConstraintFactory);
  752. public:
  753. LLIK::Constraint::ptr_t getConstrForJoint(const std::string& jname) const;
  754. private:
  755. void initSingleton() override;
  756. LLIK::Constraint::ptr_t getConstraint(const LLSD& data);
  757. static LLIK::Constraint::ptr_t create(const LLSD& info);
  758. private:
  759. typedef flat_hmap<U64, LLIK::Constraint::ptr_t> cache_map_t;
  760. cache_map_t mConstraints;
  761. typedef flat_hmap<std::string, LLIK::Constraint::ptr_t> joint_map_t;
  762. joint_map_t mJointMapping;
  763. };
  764. // std::hash implementation for Constraint
  765. namespace std
  766. {
  767. template<> struct hash<LLIK::Constraint>
  768. {
  769. LL_INLINE size_t operator()(const LLIK::Constraint& s) const noexcept
  770. {
  771. return s.getHash();
  772. }
  773. };
  774. }
  775. // For use with boost::unordered_map and boost::unordered_set
  776. LL_INLINE size_t hash_value(const LLIK::Constraint& s) noexcept
  777. {
  778. return s.getHash();
  779. }
  780. #endif // LL_LLIK_H