Constraint.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //
  2. // Copyright (c) 2008-2022 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../Physics/Constraint.h"
  28. #include "../Physics/PhysicsUtils.h"
  29. #include "../Physics/PhysicsWorld.h"
  30. #include "../Physics/RigidBody.h"
  31. #include "../Scene/Scene.h"
  32. #include <Bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h>
  33. #include <Bullet/BulletDynamics/ConstraintSolver/btHingeConstraint.h>
  34. #include <Bullet/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h>
  35. #include <Bullet/BulletDynamics/ConstraintSolver/btSliderConstraint.h>
  36. #include <Bullet/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  37. using namespace std;
  38. namespace Urho3D
  39. {
  40. static const char* typeNames[] =
  41. {
  42. "Point",
  43. "Hinge",
  44. "Slider",
  45. "ConeTwist",
  46. nullptr
  47. };
  48. extern const char* PHYSICS_CATEGORY;
  49. Constraint::Constraint(Context* context) :
  50. Component(context),
  51. constraintType_(CONSTRAINT_POINT),
  52. position_(Vector3::ZERO),
  53. rotation_(Quaternion::IDENTITY),
  54. otherPosition_(Vector3::ZERO),
  55. otherRotation_(Quaternion::IDENTITY),
  56. highLimit_(Vector2::ZERO),
  57. lowLimit_(Vector2::ZERO),
  58. erp_(0.0f),
  59. cfm_(0.0f),
  60. otherBodyNodeID_(0),
  61. disableCollision_(false),
  62. recreateConstraint_(true),
  63. framesDirty_(false),
  64. retryCreation_(false)
  65. {
  66. }
  67. Constraint::~Constraint()
  68. {
  69. ReleaseConstraint();
  70. if (physicsWorld_)
  71. physicsWorld_->RemoveConstraint(this);
  72. }
  73. void Constraint::RegisterObject(Context* context)
  74. {
  75. context->RegisterFactory<Constraint>(PHYSICS_CATEGORY);
  76. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  77. URHO3D_ENUM_ATTRIBUTE_EX("Constraint Type", constraintType_, MarkConstraintDirty, typeNames, CONSTRAINT_POINT, AM_DEFAULT);
  78. URHO3D_ATTRIBUTE_EX("Position", Vector3, position_, AdjustOtherBodyPosition, Vector3::ZERO, AM_DEFAULT);
  79. URHO3D_ATTRIBUTE_EX("Rotation", Quaternion, rotation_, MarkFramesDirty, Quaternion::IDENTITY, AM_DEFAULT);
  80. URHO3D_ATTRIBUTE_EX("Other Body Position", Vector3, otherPosition_, MarkFramesDirty, Vector3::ZERO, AM_DEFAULT);
  81. URHO3D_ATTRIBUTE_EX("Other Body Rotation", Quaternion, otherRotation_, MarkFramesDirty, Quaternion::IDENTITY, AM_DEFAULT);
  82. URHO3D_ATTRIBUTE_EX("Other Body NodeID", unsigned, otherBodyNodeID_, MarkConstraintDirty, 0, AM_DEFAULT | AM_NODEID);
  83. URHO3D_ACCESSOR_ATTRIBUTE("High Limit", GetHighLimit, SetHighLimit, Vector2, Vector2::ZERO, AM_DEFAULT);
  84. URHO3D_ACCESSOR_ATTRIBUTE("Low Limit", GetLowLimit, SetLowLimit, Vector2, Vector2::ZERO, AM_DEFAULT);
  85. URHO3D_ACCESSOR_ATTRIBUTE("ERP Parameter", GetERP, SetERP, float, 0.0f, AM_DEFAULT);
  86. URHO3D_ACCESSOR_ATTRIBUTE("CFM Parameter", GetCFM, SetCFM, float, 0.0f, AM_DEFAULT);
  87. URHO3D_ATTRIBUTE_EX("Disable Collision", bool, disableCollision_, MarkConstraintDirty, false, AM_DEFAULT);
  88. }
  89. void Constraint::ApplyAttributes()
  90. {
  91. if (recreateConstraint_)
  92. {
  93. if (otherBody_)
  94. otherBody_->RemoveConstraint(this);
  95. otherBody_.Reset();
  96. Scene* scene = GetScene();
  97. if (scene && otherBodyNodeID_)
  98. {
  99. Node* otherNode = scene->GetNode(otherBodyNodeID_);
  100. if (otherNode)
  101. otherBody_ = otherNode->GetComponent<RigidBody>();
  102. }
  103. CreateConstraint();
  104. }
  105. else if (framesDirty_)
  106. {
  107. ApplyFrames();
  108. framesDirty_ = false;
  109. }
  110. }
  111. void Constraint::OnSetEnabled()
  112. {
  113. if (constraint_)
  114. constraint_->setEnabled(IsEnabledEffective());
  115. }
  116. void Constraint::GetDependencyNodes(PODVector<Node*>& dest)
  117. {
  118. if (otherBody_ && otherBody_->GetNode())
  119. dest.Push(otherBody_->GetNode());
  120. }
  121. void Constraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  122. {
  123. if (debug && physicsWorld_ && constraint_)
  124. {
  125. physicsWorld_->SetDebugRenderer(debug);
  126. physicsWorld_->SetDebugDepthTest(depthTest);
  127. physicsWorld_->GetWorld()->debugDrawConstraint(constraint_.get());
  128. physicsWorld_->SetDebugRenderer(nullptr);
  129. }
  130. }
  131. void Constraint::SetConstraintType(ConstraintType type)
  132. {
  133. if (type != constraintType_ || !constraint_)
  134. {
  135. constraintType_ = type;
  136. CreateConstraint();
  137. MarkNetworkUpdate();
  138. }
  139. }
  140. void Constraint::SetOtherBody(RigidBody* body)
  141. {
  142. if (otherBody_ != body)
  143. {
  144. if (otherBody_)
  145. otherBody_->RemoveConstraint(this);
  146. otherBody_ = body;
  147. // Update the connected body attribute
  148. Node* otherNode = otherBody_ ? otherBody_->GetNode() : nullptr;
  149. otherBodyNodeID_ = otherNode ? otherNode->GetID() : 0;
  150. CreateConstraint();
  151. MarkNetworkUpdate();
  152. }
  153. }
  154. void Constraint::SetPosition(const Vector3& position)
  155. {
  156. if (position != position_)
  157. {
  158. position_ = position;
  159. ApplyFrames();
  160. MarkNetworkUpdate();
  161. }
  162. }
  163. void Constraint::SetRotation(const Quaternion& rotation)
  164. {
  165. if (rotation != rotation_)
  166. {
  167. rotation_ = rotation;
  168. ApplyFrames();
  169. MarkNetworkUpdate();
  170. }
  171. }
  172. void Constraint::SetAxis(const Vector3& axis)
  173. {
  174. switch (constraintType_)
  175. {
  176. case CONSTRAINT_POINT:
  177. case CONSTRAINT_HINGE:
  178. rotation_ = Quaternion(Vector3::FORWARD, axis);
  179. break;
  180. case CONSTRAINT_SLIDER:
  181. case CONSTRAINT_CONETWIST:
  182. rotation_ = Quaternion(Vector3::RIGHT, axis);
  183. break;
  184. default:
  185. break;
  186. }
  187. ApplyFrames();
  188. MarkNetworkUpdate();
  189. }
  190. void Constraint::SetOtherPosition(const Vector3& position)
  191. {
  192. if (position != otherPosition_)
  193. {
  194. otherPosition_ = position;
  195. ApplyFrames();
  196. MarkNetworkUpdate();
  197. }
  198. }
  199. void Constraint::SetOtherRotation(const Quaternion& rotation)
  200. {
  201. if (rotation != otherRotation_)
  202. {
  203. otherRotation_ = rotation;
  204. ApplyFrames();
  205. MarkNetworkUpdate();
  206. }
  207. }
  208. void Constraint::SetOtherAxis(const Vector3& axis)
  209. {
  210. switch (constraintType_)
  211. {
  212. case CONSTRAINT_POINT:
  213. case CONSTRAINT_HINGE:
  214. otherRotation_ = Quaternion(Vector3::FORWARD, axis);
  215. break;
  216. case CONSTRAINT_SLIDER:
  217. case CONSTRAINT_CONETWIST:
  218. otherRotation_ = Quaternion(Vector3::RIGHT, axis);
  219. break;
  220. default:
  221. break;
  222. }
  223. ApplyFrames();
  224. MarkNetworkUpdate();
  225. }
  226. void Constraint::SetWorldPosition(const Vector3& position)
  227. {
  228. if (constraint_)
  229. {
  230. btTransform ownBodyInverse = constraint_->getRigidBodyA().getWorldTransform().inverse();
  231. btTransform otherBodyInverse = constraint_->getRigidBodyB().getWorldTransform().inverse();
  232. btVector3 worldPos = ToBtVector3(position);
  233. position_ = (ToVector3(ownBodyInverse * worldPos) + ownBody_->GetCenterOfMass()) / cachedWorldScale_;
  234. otherPosition_ = ToVector3(otherBodyInverse * worldPos);
  235. if (otherBody_)
  236. {
  237. otherPosition_ += otherBody_->GetCenterOfMass();
  238. otherPosition_ /= otherBody_->GetNode()->GetWorldScale();
  239. }
  240. ApplyFrames();
  241. MarkNetworkUpdate();
  242. }
  243. else
  244. URHO3D_LOGWARNING("Constraint not created, world position could not be stored");
  245. }
  246. void Constraint::SetHighLimit(const Vector2& limit)
  247. {
  248. if (limit != highLimit_)
  249. {
  250. highLimit_ = limit;
  251. ApplyLimits();
  252. MarkNetworkUpdate();
  253. }
  254. }
  255. void Constraint::SetLowLimit(const Vector2& limit)
  256. {
  257. if (limit != lowLimit_)
  258. {
  259. lowLimit_ = limit;
  260. ApplyLimits();
  261. MarkNetworkUpdate();
  262. }
  263. }
  264. void Constraint::SetERP(float erp)
  265. {
  266. erp = Max(erp, 0.0f);
  267. if (erp != erp_)
  268. {
  269. erp_ = erp;
  270. ApplyLimits();
  271. MarkNetworkUpdate();
  272. }
  273. }
  274. void Constraint::SetCFM(float cfm)
  275. {
  276. cfm = Max(cfm, 0.0f);
  277. if (cfm != cfm_)
  278. {
  279. cfm_ = cfm;
  280. ApplyLimits();
  281. MarkNetworkUpdate();
  282. }
  283. }
  284. void Constraint::SetDisableCollision(bool disable)
  285. {
  286. if (disable != disableCollision_)
  287. {
  288. disableCollision_ = disable;
  289. CreateConstraint();
  290. MarkNetworkUpdate();
  291. }
  292. }
  293. Vector3 Constraint::GetWorldPosition() const
  294. {
  295. if (constraint_)
  296. {
  297. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  298. return ToVector3(ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass()));
  299. }
  300. else
  301. return Vector3::ZERO;
  302. }
  303. void Constraint::ReleaseConstraint()
  304. {
  305. if (constraint_)
  306. {
  307. if (ownBody_)
  308. ownBody_->RemoveConstraint(this);
  309. if (otherBody_)
  310. otherBody_->RemoveConstraint(this);
  311. if (physicsWorld_)
  312. physicsWorld_->GetWorld()->removeConstraint(constraint_.get());
  313. constraint_.reset();
  314. }
  315. }
  316. void Constraint::ApplyFrames()
  317. {
  318. if (!constraint_ || !node_ || (otherBody_ && !otherBody_->GetNode()))
  319. return;
  320. cachedWorldScale_ = node_->GetWorldScale();
  321. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  322. Vector3 otherBodyScaledPosition =
  323. otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() - otherBody_->GetCenterOfMass() : otherPosition_;
  324. switch (constraint_->getConstraintType())
  325. {
  326. case POINT2POINT_CONSTRAINT_TYPE:
  327. {
  328. auto* pointConstraint = static_cast<btPoint2PointConstraint*>(constraint_.get());
  329. pointConstraint->setPivotA(ToBtVector3(ownBodyScaledPosition));
  330. pointConstraint->setPivotB(ToBtVector3(otherBodyScaledPosition));
  331. }
  332. break;
  333. case HINGE_CONSTRAINT_TYPE:
  334. {
  335. auto* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.get());
  336. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  337. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  338. hingeConstraint->setFrames(ownFrame, otherFrame);
  339. }
  340. break;
  341. case SLIDER_CONSTRAINT_TYPE:
  342. {
  343. auto* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.get());
  344. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  345. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  346. sliderConstraint->setFrames(ownFrame, otherFrame);
  347. }
  348. break;
  349. case CONETWIST_CONSTRAINT_TYPE:
  350. {
  351. auto* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.get());
  352. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  353. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  354. coneTwistConstraint->setFrames(ownFrame, otherFrame);
  355. }
  356. break;
  357. default:
  358. break;
  359. }
  360. }
  361. void Constraint::OnNodeSet(Node* node)
  362. {
  363. if (node)
  364. {
  365. node->AddListener(this);
  366. cachedWorldScale_ = node->GetWorldScale();
  367. }
  368. }
  369. void Constraint::OnSceneSet(Scene* scene)
  370. {
  371. if (scene)
  372. {
  373. if (scene == node_)
  374. URHO3D_LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  375. physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>();
  376. physicsWorld_->AddConstraint(this);
  377. // Create constraint now if necessary (attributes modified before adding to scene)
  378. if (retryCreation_)
  379. CreateConstraint();
  380. }
  381. else
  382. {
  383. ReleaseConstraint();
  384. if (physicsWorld_)
  385. physicsWorld_->RemoveConstraint(this);
  386. // Recreate when moved to a scene again
  387. retryCreation_ = true;
  388. }
  389. }
  390. void Constraint::OnMarkedDirty(Node* node)
  391. {
  392. /// \todo This does not catch the connected body node's scale changing
  393. if (HasWorldScaleChanged(cachedWorldScale_, node->GetWorldScale()))
  394. ApplyFrames();
  395. }
  396. void Constraint::CreateConstraint()
  397. {
  398. URHO3D_PROFILE(CreateConstraint);
  399. cachedWorldScale_ = node_->GetWorldScale();
  400. ReleaseConstraint();
  401. ownBody_ = GetComponent<RigidBody>();
  402. btRigidBody* ownBody = ownBody_ ? ownBody_->GetBody() : nullptr;
  403. btRigidBody* otherBody = otherBody_ ? otherBody_->GetBody() : nullptr;
  404. // If no physics world available now mark for retry later
  405. if (!physicsWorld_ || !ownBody)
  406. {
  407. retryCreation_ = true;
  408. return;
  409. }
  410. if (!otherBody)
  411. otherBody = &btTypedConstraint::getFixedBody();
  412. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  413. Vector3 otherBodyScaledPosition = otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() -
  414. otherBody_->GetCenterOfMass() : otherPosition_;
  415. switch (constraintType_)
  416. {
  417. case CONSTRAINT_POINT:
  418. {
  419. constraint_ = make_unique<btPoint2PointConstraint>(*ownBody, *otherBody, ToBtVector3(ownBodyScaledPosition),
  420. ToBtVector3(otherBodyScaledPosition));
  421. }
  422. break;
  423. case CONSTRAINT_HINGE:
  424. {
  425. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  426. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  427. constraint_ = make_unique<btHingeConstraint>(*ownBody, *otherBody, ownFrame, otherFrame);
  428. }
  429. break;
  430. case CONSTRAINT_SLIDER:
  431. {
  432. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  433. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  434. constraint_ = make_unique<btSliderConstraint>(*ownBody, *otherBody, ownFrame, otherFrame, false);
  435. }
  436. break;
  437. case CONSTRAINT_CONETWIST:
  438. {
  439. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  440. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  441. constraint_ = make_unique<btConeTwistConstraint>(*ownBody, *otherBody, ownFrame, otherFrame);
  442. }
  443. break;
  444. default:
  445. break;
  446. }
  447. if (constraint_)
  448. {
  449. constraint_->setUserConstraintPtr(this);
  450. constraint_->setEnabled(IsEnabledEffective());
  451. ownBody_->AddConstraint(this);
  452. if (otherBody_)
  453. otherBody_->AddConstraint(this);
  454. ApplyLimits();
  455. physicsWorld_->GetWorld()->addConstraint(constraint_.get(), disableCollision_);
  456. }
  457. recreateConstraint_ = false;
  458. framesDirty_ = false;
  459. retryCreation_ = false;
  460. }
  461. void Constraint::ApplyLimits()
  462. {
  463. if (!constraint_)
  464. return;
  465. switch (constraint_->getConstraintType())
  466. {
  467. case HINGE_CONSTRAINT_TYPE:
  468. {
  469. auto* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.get());
  470. hingeConstraint->setLimit(lowLimit_.x_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  471. }
  472. break;
  473. case SLIDER_CONSTRAINT_TYPE:
  474. {
  475. auto* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.get());
  476. sliderConstraint->setUpperLinLimit(highLimit_.x_);
  477. sliderConstraint->setUpperAngLimit(highLimit_.y_ * M_DEGTORAD);
  478. sliderConstraint->setLowerLinLimit(lowLimit_.x_);
  479. sliderConstraint->setLowerAngLimit(lowLimit_.y_ * M_DEGTORAD);
  480. }
  481. break;
  482. case CONETWIST_CONSTRAINT_TYPE:
  483. {
  484. auto* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.get());
  485. coneTwistConstraint->setLimit(highLimit_.y_ * M_DEGTORAD, highLimit_.y_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  486. }
  487. break;
  488. default:
  489. break;
  490. }
  491. if (erp_ != 0.0f)
  492. constraint_->setParam(BT_CONSTRAINT_STOP_ERP, erp_);
  493. if (cfm_ != 0.0f)
  494. constraint_->setParam(BT_CONSTRAINT_STOP_CFM, cfm_);
  495. }
  496. void Constraint::AdjustOtherBodyPosition()
  497. {
  498. // Convenience for editing static constraints: if not connected to another body, adjust world position to match local
  499. // (when deserializing, the proper other body position will be read after own position, so this calculation is safely
  500. // overridden and does not accumulate constraint error
  501. if (constraint_ && !otherBody_)
  502. {
  503. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  504. btVector3 worldPos = ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass());
  505. otherPosition_ = ToVector3(worldPos);
  506. }
  507. MarkFramesDirty();
  508. }
  509. }