Constraint.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  24. #include "DebugRenderer.h"
  25. #include "Constraint.h"
  26. #include "Log.h"
  27. #include "PhysicsUtils.h"
  28. #include "PhysicsWorld.h"
  29. #include "Profiler.h"
  30. #include "RigidBody.h"
  31. #include "Scene.h"
  32. #include <BulletDynamics/ConstraintSolver/btConeTwistConstraint.h>
  33. #include <BulletDynamics/ConstraintSolver/btHingeConstraint.h>
  34. #include <BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h>
  35. #include <BulletDynamics/ConstraintSolver/btSliderConstraint.h>
  36. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  37. #include "DebugNew.h"
  38. namespace Urho3D
  39. {
  40. static const char* typeNames[] =
  41. {
  42. "Point",
  43. "Hinge",
  44. "Slider",
  45. "ConeTwist",
  46. 0
  47. };
  48. extern const char* PHYSICS_CATEGORY;
  49. OBJECTTYPESTATIC(Constraint);
  50. Constraint::Constraint(Context* context) :
  51. Component(context),
  52. constraint_(0),
  53. constraintType_(CONSTRAINT_POINT),
  54. position_(Vector3::ZERO),
  55. rotation_(Quaternion::IDENTITY),
  56. otherPosition_(Vector3::ZERO),
  57. otherRotation_(Quaternion::IDENTITY),
  58. highLimit_(Vector2::ZERO),
  59. lowLimit_(Vector2::ZERO),
  60. erp_(0.0f),
  61. cfm_(0.0f),
  62. otherBodyNodeID_(0),
  63. disableCollision_(false),
  64. recreateConstraint_(true),
  65. framesDirty_(false)
  66. {
  67. }
  68. Constraint::~Constraint()
  69. {
  70. ReleaseConstraint();
  71. if (physicsWorld_)
  72. physicsWorld_->RemoveConstraint(this);
  73. }
  74. void Constraint::RegisterObject(Context* context)
  75. {
  76. context->RegisterFactory<Constraint>(PHYSICS_CATEGORY);
  77. ACCESSOR_ATTRIBUTE(Constraint, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  78. ENUM_ATTRIBUTE(Constraint, "Constraint Type", constraintType_, typeNames, CONSTRAINT_POINT, AM_DEFAULT);
  79. ATTRIBUTE(Constraint, VAR_VECTOR3, "Position", position_, Vector3::ZERO, AM_DEFAULT);
  80. ATTRIBUTE(Constraint, VAR_QUATERNION, "Rotation", rotation_, Quaternion::IDENTITY, AM_DEFAULT);
  81. ATTRIBUTE(Constraint, VAR_VECTOR3, "Other Body Position", otherPosition_, Vector3::ZERO, AM_DEFAULT);
  82. ATTRIBUTE(Constraint, VAR_QUATERNION, "Other Body Rotation", otherRotation_, Quaternion::IDENTITY, AM_DEFAULT);
  83. ATTRIBUTE(Constraint, VAR_INT, "Other Body NodeID", otherBodyNodeID_, 0, AM_DEFAULT | AM_NODEID);
  84. REF_ACCESSOR_ATTRIBUTE(Constraint, VAR_VECTOR2, "High Limit", GetHighLimit, SetHighLimit, Vector2, Vector2::ZERO, AM_DEFAULT);
  85. REF_ACCESSOR_ATTRIBUTE(Constraint, VAR_VECTOR2, "Low Limit", GetLowLimit, SetLowLimit, Vector2, Vector2::ZERO, AM_DEFAULT);
  86. ACCESSOR_ATTRIBUTE(Constraint, VAR_FLOAT, "ERP Parameter", GetERP, SetERP, float, 0.0f, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE(Constraint, VAR_FLOAT, "CFM Parameter", GetCFM, SetCFM, float, 0.0f, AM_DEFAULT);
  88. ATTRIBUTE(Constraint, VAR_BOOL, "Disable Collision", disableCollision_, false, AM_DEFAULT);
  89. }
  90. void Constraint::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  91. {
  92. Component::OnSetAttribute(attr, src);
  93. if (!attr.accessor_)
  94. {
  95. // Convenience for editing static constraints: if not connected to another body, adjust world position to match local
  96. // (when deserializing, the proper other body position will be read after own position, so this calculation is safely
  97. // overridden and does not accumulate constraint error
  98. if (attr.offset_ == offsetof(Constraint, position_) && constraint_ && !otherBody_)
  99. {
  100. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  101. btVector3 worldPos = ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass());
  102. otherPosition_ = ToVector3(worldPos);
  103. }
  104. // Certain attribute changes require recreation of the constraint
  105. if (attr.offset_ == offsetof(Constraint, constraintType_) || attr.offset_ == offsetof(Constraint, otherBodyNodeID_) ||
  106. attr.offset_ == offsetof(Constraint, disableCollision_))
  107. recreateConstraint_ = true;
  108. else
  109. framesDirty_ = true;
  110. }
  111. }
  112. void Constraint::ApplyAttributes()
  113. {
  114. if (recreateConstraint_)
  115. {
  116. if (otherBody_)
  117. otherBody_->RemoveConstraint(this);
  118. otherBody_.Reset();
  119. Scene* scene = GetScene();
  120. if (scene && otherBodyNodeID_)
  121. {
  122. Node* otherNode = scene->GetNode(otherBodyNodeID_);
  123. if (otherNode)
  124. otherBody_ = otherNode->GetComponent<RigidBody>();
  125. }
  126. CreateConstraint();
  127. }
  128. else if (framesDirty_)
  129. {
  130. ApplyFrames();
  131. framesDirty_ = false;
  132. }
  133. }
  134. void Constraint::OnSetEnabled()
  135. {
  136. if (constraint_)
  137. constraint_->setEnabled(IsEnabledEffective());
  138. }
  139. void Constraint::GetDependencyNodes(PODVector<Node*>& dest)
  140. {
  141. if (otherBody_ && otherBody_->GetNode())
  142. dest.Push(otherBody_->GetNode());
  143. }
  144. void Constraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  145. {
  146. if (debug && physicsWorld_ && constraint_ && IsEnabledEffective())
  147. {
  148. physicsWorld_->SetDebugRenderer(debug);
  149. physicsWorld_->SetDebugDepthTest(depthTest);
  150. physicsWorld_->GetWorld()->debugDrawConstraint(constraint_);
  151. physicsWorld_->SetDebugRenderer(0);
  152. }
  153. }
  154. void Constraint::SetConstraintType(ConstraintType type)
  155. {
  156. if (type != constraintType_)
  157. {
  158. constraintType_ = type;
  159. CreateConstraint();
  160. MarkNetworkUpdate();
  161. }
  162. }
  163. void Constraint::SetOtherBody(RigidBody* body)
  164. {
  165. if (otherBody_ != body)
  166. {
  167. if (otherBody_)
  168. otherBody_->RemoveConstraint(this);
  169. otherBody_ = body;
  170. // Update the connected body attribute
  171. Node* otherNode = otherBody_ ? otherBody_->GetNode() : 0;
  172. otherBodyNodeID_ = otherNode ? otherNode->GetID() : 0;
  173. CreateConstraint();
  174. MarkNetworkUpdate();
  175. }
  176. }
  177. void Constraint::SetPosition(const Vector3& position)
  178. {
  179. if (position != position_)
  180. {
  181. position_ = position;
  182. ApplyFrames();
  183. MarkNetworkUpdate();
  184. }
  185. }
  186. void Constraint::SetRotation(const Quaternion& rotation)
  187. {
  188. if (rotation != rotation_)
  189. {
  190. rotation_ = rotation;
  191. ApplyFrames();
  192. MarkNetworkUpdate();
  193. }
  194. }
  195. void Constraint::SetAxis(const Vector3& axis)
  196. {
  197. switch (constraintType_)
  198. {
  199. case CONSTRAINT_POINT:
  200. case CONSTRAINT_HINGE:
  201. rotation_ = Quaternion(Vector3::FORWARD, axis);
  202. break;
  203. case CONSTRAINT_SLIDER:
  204. case CONSTRAINT_CONETWIST:
  205. rotation_ = Quaternion(Vector3::RIGHT, axis);
  206. break;
  207. default:
  208. break;
  209. }
  210. ApplyFrames();
  211. MarkNetworkUpdate();
  212. }
  213. void Constraint::SetOtherPosition(const Vector3& position)
  214. {
  215. if (position != otherPosition_)
  216. {
  217. otherPosition_ = position;
  218. ApplyFrames();
  219. MarkNetworkUpdate();
  220. }
  221. }
  222. void Constraint::SetOtherRotation(const Quaternion& rotation)
  223. {
  224. if (rotation != otherRotation_)
  225. {
  226. otherRotation_ = rotation;
  227. ApplyFrames();
  228. MarkNetworkUpdate();
  229. }
  230. }
  231. void Constraint::SetOtherAxis(const Vector3& axis)
  232. {
  233. switch (constraintType_)
  234. {
  235. case CONSTRAINT_POINT:
  236. case CONSTRAINT_HINGE:
  237. otherRotation_ = Quaternion(Vector3::FORWARD, axis);
  238. break;
  239. case CONSTRAINT_SLIDER:
  240. case CONSTRAINT_CONETWIST:
  241. otherRotation_ = Quaternion(Vector3::RIGHT, axis);
  242. break;
  243. default:
  244. break;
  245. }
  246. ApplyFrames();
  247. MarkNetworkUpdate();
  248. }
  249. void Constraint::SetWorldPosition(const Vector3& position)
  250. {
  251. if (constraint_)
  252. {
  253. btTransform ownBodyInverse = constraint_->getRigidBodyA().getWorldTransform().inverse();
  254. btTransform otherBodyInverse = constraint_->getRigidBodyB().getWorldTransform().inverse();
  255. btVector3 worldPos = ToBtVector3(position);
  256. position_ = (ToVector3(ownBodyInverse * worldPos) + ownBody_->GetCenterOfMass()) / cachedWorldScale_;
  257. otherPosition_ = ToVector3(otherBodyInverse * worldPos);
  258. if (otherBody_)
  259. {
  260. otherPosition_ += otherBody_->GetCenterOfMass();
  261. otherPosition_ /= otherBody_->GetNode()->GetWorldScale();
  262. }
  263. ApplyFrames();
  264. MarkNetworkUpdate();
  265. }
  266. else
  267. LOGWARNING("Constraint not created, world position could not be stored");
  268. }
  269. void Constraint::SetHighLimit(const Vector2& limit)
  270. {
  271. if (limit != highLimit_)
  272. {
  273. highLimit_ = limit;
  274. ApplyLimits();
  275. MarkNetworkUpdate();
  276. }
  277. }
  278. void Constraint::SetLowLimit(const Vector2& limit)
  279. {
  280. if (limit != lowLimit_)
  281. {
  282. lowLimit_ = limit;
  283. ApplyLimits();
  284. MarkNetworkUpdate();
  285. }
  286. }
  287. void Constraint::SetERP(float erp)
  288. {
  289. erp = Max(erp, 0.0f);
  290. if (erp != erp_)
  291. {
  292. erp_ = erp;
  293. ApplyLimits();
  294. MarkNetworkUpdate();
  295. }
  296. }
  297. void Constraint::SetCFM(float cfm)
  298. {
  299. cfm = Max(cfm, 0.0f);
  300. if (cfm != cfm_)
  301. {
  302. cfm_ = cfm;
  303. ApplyLimits();
  304. MarkNetworkUpdate();
  305. }
  306. }
  307. void Constraint::SetDisableCollision(bool disable)
  308. {
  309. if (disable != disableCollision_)
  310. {
  311. disableCollision_ = disable;
  312. CreateConstraint();
  313. MarkNetworkUpdate();
  314. }
  315. }
  316. Vector3 Constraint::GetWorldPosition() const
  317. {
  318. if (constraint_)
  319. {
  320. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  321. return ToVector3(ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass()));
  322. }
  323. else
  324. return Vector3::ZERO;
  325. }
  326. void Constraint::ReleaseConstraint()
  327. {
  328. if (constraint_)
  329. {
  330. if (ownBody_)
  331. ownBody_->RemoveConstraint(this);
  332. if (otherBody_)
  333. otherBody_->RemoveConstraint(this);
  334. if (physicsWorld_)
  335. physicsWorld_->GetWorld()->removeConstraint(constraint_);
  336. delete constraint_;
  337. constraint_ = 0;
  338. }
  339. }
  340. void Constraint::ApplyFrames()
  341. {
  342. if (!constraint_)
  343. return;
  344. if (node_)
  345. cachedWorldScale_ = node_->GetWorldScale();
  346. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  347. Vector3 otherBodyScaledPosition = otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() -
  348. otherBody_->GetCenterOfMass() : otherPosition_;
  349. switch (constraint_->getConstraintType())
  350. {
  351. case POINT2POINT_CONSTRAINT_TYPE:
  352. {
  353. btPoint2PointConstraint* pointConstraint = static_cast<btPoint2PointConstraint*>(constraint_);
  354. pointConstraint->setPivotA(ToBtVector3(ownBodyScaledPosition));
  355. pointConstraint->setPivotB(ToBtVector3(otherBodyScaledPosition));
  356. }
  357. break;
  358. case HINGE_CONSTRAINT_TYPE:
  359. {
  360. btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_);
  361. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  362. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  363. hingeConstraint->setFrames(ownFrame, otherFrame);
  364. }
  365. break;
  366. case SLIDER_CONSTRAINT_TYPE:
  367. {
  368. btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_);
  369. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  370. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  371. sliderConstraint->setFrames(ownFrame, otherFrame);
  372. }
  373. break;
  374. case CONETWIST_CONSTRAINT_TYPE:
  375. {
  376. btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_);
  377. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  378. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  379. coneTwistConstraint->setFrames(ownFrame, otherFrame);
  380. }
  381. break;
  382. default:
  383. break;
  384. }
  385. }
  386. void Constraint::OnNodeSet(Node* node)
  387. {
  388. if (node)
  389. {
  390. Scene* scene = GetScene();
  391. if (scene)
  392. {
  393. if (scene == node)
  394. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  395. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  396. if (physicsWorld_)
  397. physicsWorld_->AddConstraint(this);
  398. else
  399. LOGERROR("No physics world component in scene, can not create constraint");
  400. }
  401. else
  402. LOGERROR("Node is detached from scene, can not create constraint");
  403. node->AddListener(this);
  404. cachedWorldScale_ = node->GetWorldScale();
  405. }
  406. }
  407. void Constraint::OnMarkedDirty(Node* node)
  408. {
  409. /// \todo This does not catch the connected body node's scale changing
  410. if (HasWorldScaleChanged(cachedWorldScale_, node->GetWorldScale()))
  411. ApplyFrames();
  412. }
  413. void Constraint::CreateConstraint()
  414. {
  415. PROFILE(CreateConstraint);
  416. cachedWorldScale_ = node_->GetWorldScale();
  417. ReleaseConstraint();
  418. ownBody_ = GetComponent<RigidBody>();
  419. btRigidBody* ownBody = ownBody_ ? ownBody_->GetBody() : 0;
  420. btRigidBody* otherBody = otherBody_ ? otherBody_->GetBody() : 0;
  421. if (!physicsWorld_ || !ownBody)
  422. return;
  423. if (!otherBody)
  424. otherBody = &btTypedConstraint::getFixedBody();
  425. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  426. Vector3 otherBodyScaledPosition = otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() -
  427. otherBody_->GetCenterOfMass() : otherPosition_;
  428. switch (constraintType_)
  429. {
  430. case CONSTRAINT_POINT:
  431. {
  432. constraint_ = new btPoint2PointConstraint(*ownBody, *otherBody, ToBtVector3(ownBodyScaledPosition),
  433. ToBtVector3(otherBodyScaledPosition));
  434. }
  435. break;
  436. case CONSTRAINT_HINGE:
  437. {
  438. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  439. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  440. constraint_ = new btHingeConstraint(*ownBody, *otherBody, ownFrame, otherFrame);
  441. }
  442. break;
  443. case CONSTRAINT_SLIDER:
  444. {
  445. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  446. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  447. constraint_ = new btSliderConstraint(*ownBody, *otherBody, ownFrame, otherFrame, false);
  448. }
  449. break;
  450. case CONSTRAINT_CONETWIST:
  451. {
  452. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  453. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  454. constraint_ = new btConeTwistConstraint(*ownBody, *otherBody, ownFrame, otherFrame);
  455. }
  456. break;
  457. default:
  458. break;
  459. }
  460. if (constraint_)
  461. {
  462. constraint_->setUserConstraintPtr(this);
  463. constraint_->setEnabled(IsEnabledEffective());
  464. ownBody_->AddConstraint(this);
  465. if (otherBody_)
  466. otherBody_->AddConstraint(this);
  467. ApplyLimits();
  468. physicsWorld_->GetWorld()->addConstraint(constraint_, disableCollision_);
  469. }
  470. recreateConstraint_ = false;
  471. framesDirty_ = false;
  472. }
  473. void Constraint::ApplyLimits()
  474. {
  475. if (!constraint_)
  476. return;
  477. switch (constraint_->getConstraintType())
  478. {
  479. case HINGE_CONSTRAINT_TYPE:
  480. {
  481. btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_);
  482. hingeConstraint->setLimit(lowLimit_.x_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  483. }
  484. break;
  485. case SLIDER_CONSTRAINT_TYPE:
  486. {
  487. btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_);
  488. sliderConstraint->setUpperLinLimit(highLimit_.x_);
  489. sliderConstraint->setUpperAngLimit(highLimit_.y_ * M_DEGTORAD);
  490. sliderConstraint->setLowerLinLimit(lowLimit_.x_);
  491. sliderConstraint->setLowerAngLimit(lowLimit_.y_ * M_DEGTORAD);
  492. }
  493. break;
  494. case CONETWIST_CONSTRAINT_TYPE:
  495. {
  496. btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_);
  497. coneTwistConstraint->setLimit(highLimit_.y_ * M_DEGTORAD, highLimit_.y_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  498. }
  499. break;
  500. default:
  501. break;
  502. }
  503. if (erp_ != 0.0f)
  504. constraint_->setParam(BT_CONSTRAINT_STOP_ERP, erp_);
  505. if (cfm_ != 0.0f)
  506. constraint_->setParam(BT_CONSTRAINT_STOP_CFM, cfm_);
  507. }
  508. }