godot_hinge_joint_3d.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /**************************************************************************/
  2. /* godot_hinge_joint_3d.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. /*
  31. Adapted to Godot from the Bullet library.
  32. */
  33. /*
  34. Bullet Continuous Collision Detection and Physics Library
  35. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  36. This software is provided 'as-is', without any express or implied warranty.
  37. In no event will the authors be held liable for any damages arising from the use of this software.
  38. Permission is granted to anyone to use this software for any purpose,
  39. including commercial applications, and to alter it and redistribute it freely,
  40. subject to the following restrictions:
  41. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  42. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  43. 3. This notice may not be removed or altered from any source distribution.
  44. */
  45. #include "godot_hinge_joint_3d.h"
  46. GodotHingeJoint3D::GodotHingeJoint3D(GodotBody3D *rbA, GodotBody3D *rbB, const Transform3D &frameA, const Transform3D &frameB) :
  47. GodotJoint3D(_arr, 2) {
  48. A = rbA;
  49. B = rbB;
  50. m_rbAFrame = frameA;
  51. m_rbBFrame = frameB;
  52. // flip axis
  53. m_rbBFrame.basis[0][2] *= real_t(-1.);
  54. m_rbBFrame.basis[1][2] *= real_t(-1.);
  55. m_rbBFrame.basis[2][2] *= real_t(-1.);
  56. A->add_constraint(this, 0);
  57. B->add_constraint(this, 1);
  58. }
  59. GodotHingeJoint3D::GodotHingeJoint3D(GodotBody3D *rbA, GodotBody3D *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB,
  60. const Vector3 &axisInA, const Vector3 &axisInB) :
  61. GodotJoint3D(_arr, 2) {
  62. A = rbA;
  63. B = rbB;
  64. m_rbAFrame.origin = pivotInA;
  65. // since no frame is given, assume this to be zero angle and just pick rb transform axis
  66. Vector3 rbAxisA1 = rbA->get_transform().basis.get_column(0);
  67. Vector3 rbAxisA2;
  68. real_t projection = axisInA.dot(rbAxisA1);
  69. if (projection >= 1.0f - CMP_EPSILON) {
  70. rbAxisA1 = -rbA->get_transform().basis.get_column(2);
  71. rbAxisA2 = rbA->get_transform().basis.get_column(1);
  72. } else if (projection <= -1.0f + CMP_EPSILON) {
  73. rbAxisA1 = rbA->get_transform().basis.get_column(2);
  74. rbAxisA2 = rbA->get_transform().basis.get_column(1);
  75. } else {
  76. rbAxisA2 = axisInA.cross(rbAxisA1);
  77. rbAxisA1 = rbAxisA2.cross(axisInA);
  78. }
  79. m_rbAFrame.basis = Basis(rbAxisA1.x, rbAxisA2.x, axisInA.x,
  80. rbAxisA1.y, rbAxisA2.y, axisInA.y,
  81. rbAxisA1.z, rbAxisA2.z, axisInA.z);
  82. Quaternion rotationArc = Quaternion(axisInA, axisInB);
  83. Vector3 rbAxisB1 = rotationArc.xform(rbAxisA1);
  84. Vector3 rbAxisB2 = axisInB.cross(rbAxisB1);
  85. m_rbBFrame.origin = pivotInB;
  86. m_rbBFrame.basis = Basis(rbAxisB1.x, rbAxisB2.x, -axisInB.x,
  87. rbAxisB1.y, rbAxisB2.y, -axisInB.y,
  88. rbAxisB1.z, rbAxisB2.z, -axisInB.z);
  89. A->add_constraint(this, 0);
  90. B->add_constraint(this, 1);
  91. }
  92. bool GodotHingeJoint3D::setup(real_t p_step) {
  93. dynamic_A = (A->get_mode() > PhysicsServer3D::BODY_MODE_KINEMATIC);
  94. dynamic_B = (B->get_mode() > PhysicsServer3D::BODY_MODE_KINEMATIC);
  95. if (!dynamic_A && !dynamic_B) {
  96. return false;
  97. }
  98. m_appliedImpulse = real_t(0.);
  99. if (!m_angularOnly) {
  100. Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin);
  101. Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin);
  102. Vector3 relPos = pivotBInW - pivotAInW;
  103. Vector3 normal[3];
  104. if (Math::is_zero_approx(relPos.length_squared())) {
  105. normal[0] = Vector3(real_t(1.0), 0, 0);
  106. } else {
  107. normal[0] = relPos.normalized();
  108. }
  109. plane_space(normal[0], normal[1], normal[2]);
  110. for (int i = 0; i < 3; i++) {
  111. memnew_placement(
  112. &m_jac[i],
  113. GodotJacobianEntry3D(
  114. A->get_principal_inertia_axes().transposed(),
  115. B->get_principal_inertia_axes().transposed(),
  116. pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
  117. pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
  118. normal[i],
  119. A->get_inv_inertia(),
  120. A->get_inv_mass(),
  121. B->get_inv_inertia(),
  122. B->get_inv_mass()));
  123. }
  124. }
  125. //calculate two perpendicular jointAxis, orthogonal to hingeAxis
  126. //these two jointAxis require equal angular velocities for both bodies
  127. //this is unused for now, it's a todo
  128. Vector3 jointAxis0local;
  129. Vector3 jointAxis1local;
  130. plane_space(m_rbAFrame.basis.get_column(2), jointAxis0local, jointAxis1local);
  131. Vector3 jointAxis0 = A->get_transform().basis.xform(jointAxis0local);
  132. Vector3 jointAxis1 = A->get_transform().basis.xform(jointAxis1local);
  133. Vector3 hingeAxisWorld = A->get_transform().basis.xform(m_rbAFrame.basis.get_column(2));
  134. memnew_placement(
  135. &m_jacAng[0],
  136. GodotJacobianEntry3D(
  137. jointAxis0,
  138. A->get_principal_inertia_axes().transposed(),
  139. B->get_principal_inertia_axes().transposed(),
  140. A->get_inv_inertia(),
  141. B->get_inv_inertia()));
  142. memnew_placement(
  143. &m_jacAng[1],
  144. GodotJacobianEntry3D(
  145. jointAxis1,
  146. A->get_principal_inertia_axes().transposed(),
  147. B->get_principal_inertia_axes().transposed(),
  148. A->get_inv_inertia(),
  149. B->get_inv_inertia()));
  150. memnew_placement(
  151. &m_jacAng[2],
  152. GodotJacobianEntry3D(
  153. hingeAxisWorld,
  154. A->get_principal_inertia_axes().transposed(),
  155. B->get_principal_inertia_axes().transposed(),
  156. A->get_inv_inertia(),
  157. B->get_inv_inertia()));
  158. // Compute limit information
  159. real_t hingeAngle = get_hinge_angle();
  160. //set bias, sign, clear accumulator
  161. m_correction = real_t(0.);
  162. m_limitSign = real_t(0.);
  163. m_solveLimit = false;
  164. m_accLimitImpulse = real_t(0.);
  165. if (m_useLimit && m_lowerLimit <= m_upperLimit) {
  166. if (hingeAngle <= m_lowerLimit) {
  167. m_correction = (m_lowerLimit - hingeAngle);
  168. m_limitSign = 1.0f;
  169. m_solveLimit = true;
  170. } else if (hingeAngle >= m_upperLimit) {
  171. m_correction = m_upperLimit - hingeAngle;
  172. m_limitSign = -1.0f;
  173. m_solveLimit = true;
  174. }
  175. }
  176. //Compute K = J*W*J' for hinge axis
  177. Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_column(2));
  178. m_kHinge = 1.0f / (A->compute_angular_impulse_denominator(axisA) + B->compute_angular_impulse_denominator(axisA));
  179. return true;
  180. }
  181. void GodotHingeJoint3D::solve(real_t p_step) {
  182. Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin);
  183. Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin);
  184. //real_t tau = real_t(0.3);
  185. //linear part
  186. if (!m_angularOnly) {
  187. Vector3 rel_pos1 = pivotAInW - A->get_transform().origin;
  188. Vector3 rel_pos2 = pivotBInW - B->get_transform().origin;
  189. Vector3 vel1 = A->get_velocity_in_local_point(rel_pos1);
  190. Vector3 vel2 = B->get_velocity_in_local_point(rel_pos2);
  191. Vector3 vel = vel1 - vel2;
  192. for (int i = 0; i < 3; i++) {
  193. const Vector3 &normal = m_jac[i].m_linearJointAxis;
  194. real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal();
  195. real_t rel_vel;
  196. rel_vel = normal.dot(vel);
  197. //positional error (zeroth order error)
  198. real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
  199. real_t impulse = depth * tau / p_step * jacDiagABInv - rel_vel * jacDiagABInv;
  200. m_appliedImpulse += impulse;
  201. Vector3 impulse_vector = normal * impulse;
  202. if (dynamic_A) {
  203. A->apply_impulse(impulse_vector, pivotAInW - A->get_transform().origin);
  204. }
  205. if (dynamic_B) {
  206. B->apply_impulse(-impulse_vector, pivotBInW - B->get_transform().origin);
  207. }
  208. }
  209. }
  210. {
  211. ///solve angular part
  212. // get axes in world space
  213. Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_column(2));
  214. Vector3 axisB = B->get_transform().basis.xform(m_rbBFrame.basis.get_column(2));
  215. const Vector3 &angVelA = A->get_angular_velocity();
  216. const Vector3 &angVelB = B->get_angular_velocity();
  217. Vector3 angVelAroundHingeAxisA = axisA * axisA.dot(angVelA);
  218. Vector3 angVelAroundHingeAxisB = axisB * axisB.dot(angVelB);
  219. Vector3 angAorthog = angVelA - angVelAroundHingeAxisA;
  220. Vector3 angBorthog = angVelB - angVelAroundHingeAxisB;
  221. Vector3 velrelOrthog = angAorthog - angBorthog;
  222. {
  223. //solve orthogonal angular velocity correction
  224. real_t relaxation = real_t(1.);
  225. real_t len = velrelOrthog.length();
  226. if (len > real_t(0.00001)) {
  227. Vector3 normal = velrelOrthog.normalized();
  228. real_t denom = A->compute_angular_impulse_denominator(normal) +
  229. B->compute_angular_impulse_denominator(normal);
  230. // scale for mass and relaxation
  231. velrelOrthog *= (real_t(1.) / denom) * m_relaxationFactor;
  232. }
  233. //solve angular positional correction
  234. Vector3 angularError = -axisA.cross(axisB) * (real_t(1.) / p_step);
  235. real_t len2 = angularError.length();
  236. if (len2 > real_t(0.00001)) {
  237. Vector3 normal2 = angularError.normalized();
  238. real_t denom2 = A->compute_angular_impulse_denominator(normal2) +
  239. B->compute_angular_impulse_denominator(normal2);
  240. angularError *= (real_t(1.) / denom2) * relaxation;
  241. }
  242. if (dynamic_A) {
  243. A->apply_torque_impulse(-velrelOrthog + angularError);
  244. }
  245. if (dynamic_B) {
  246. B->apply_torque_impulse(velrelOrthog - angularError);
  247. }
  248. // solve limit
  249. if (m_solveLimit) {
  250. real_t amplitude = ((angVelB - angVelA).dot(axisA) * m_relaxationFactor + m_correction * (real_t(1.) / p_step) * m_biasFactor) * m_limitSign;
  251. real_t impulseMag = amplitude * m_kHinge;
  252. // Clamp the accumulated impulse
  253. real_t temp = m_accLimitImpulse;
  254. m_accLimitImpulse = MAX(m_accLimitImpulse + impulseMag, real_t(0));
  255. impulseMag = m_accLimitImpulse - temp;
  256. Vector3 impulse = axisA * impulseMag * m_limitSign;
  257. if (dynamic_A) {
  258. A->apply_torque_impulse(impulse);
  259. }
  260. if (dynamic_B) {
  261. B->apply_torque_impulse(-impulse);
  262. }
  263. }
  264. }
  265. //apply motor
  266. if (m_enableAngularMotor) {
  267. //todo: add limits too
  268. Vector3 angularLimit(0, 0, 0);
  269. Vector3 velrel = angVelAroundHingeAxisA - angVelAroundHingeAxisB;
  270. real_t projRelVel = velrel.dot(axisA);
  271. real_t desiredMotorVel = m_motorTargetVelocity;
  272. real_t motor_relvel = desiredMotorVel - projRelVel;
  273. real_t unclippedMotorImpulse = m_kHinge * motor_relvel;
  274. //todo: should clip against accumulated impulse
  275. real_t clippedMotorImpulse = unclippedMotorImpulse > m_maxMotorImpulse ? m_maxMotorImpulse : unclippedMotorImpulse;
  276. clippedMotorImpulse = clippedMotorImpulse < -m_maxMotorImpulse ? -m_maxMotorImpulse : clippedMotorImpulse;
  277. Vector3 motorImp = clippedMotorImpulse * axisA;
  278. if (dynamic_A) {
  279. A->apply_torque_impulse(motorImp + angularLimit);
  280. }
  281. if (dynamic_B) {
  282. B->apply_torque_impulse(-motorImp - angularLimit);
  283. }
  284. }
  285. }
  286. }
  287. /*
  288. void HingeJointSW::updateRHS(real_t timeStep)
  289. {
  290. (void)timeStep;
  291. }
  292. */
  293. real_t GodotHingeJoint3D::get_hinge_angle() {
  294. const Vector3 refAxis0 = A->get_transform().basis.xform(m_rbAFrame.basis.get_column(0));
  295. const Vector3 refAxis1 = A->get_transform().basis.xform(m_rbAFrame.basis.get_column(1));
  296. const Vector3 swingAxis = B->get_transform().basis.xform(m_rbBFrame.basis.get_column(1));
  297. return atan2fast(swingAxis.dot(refAxis0), swingAxis.dot(refAxis1));
  298. }
  299. void GodotHingeJoint3D::set_param(PhysicsServer3D::HingeJointParam p_param, real_t p_value) {
  300. switch (p_param) {
  301. case PhysicsServer3D::HINGE_JOINT_BIAS:
  302. tau = p_value;
  303. break;
  304. case PhysicsServer3D::HINGE_JOINT_LIMIT_UPPER:
  305. m_upperLimit = p_value;
  306. break;
  307. case PhysicsServer3D::HINGE_JOINT_LIMIT_LOWER:
  308. m_lowerLimit = p_value;
  309. break;
  310. case PhysicsServer3D::HINGE_JOINT_LIMIT_BIAS:
  311. m_biasFactor = p_value;
  312. break;
  313. case PhysicsServer3D::HINGE_JOINT_LIMIT_SOFTNESS:
  314. m_limitSoftness = p_value;
  315. break;
  316. case PhysicsServer3D::HINGE_JOINT_LIMIT_RELAXATION:
  317. m_relaxationFactor = p_value;
  318. break;
  319. case PhysicsServer3D::HINGE_JOINT_MOTOR_TARGET_VELOCITY:
  320. m_motorTargetVelocity = p_value;
  321. break;
  322. case PhysicsServer3D::HINGE_JOINT_MOTOR_MAX_IMPULSE:
  323. m_maxMotorImpulse = p_value;
  324. break;
  325. case PhysicsServer3D::HINGE_JOINT_MAX:
  326. break; // Can't happen, but silences warning
  327. }
  328. }
  329. real_t GodotHingeJoint3D::get_param(PhysicsServer3D::HingeJointParam p_param) const {
  330. switch (p_param) {
  331. case PhysicsServer3D::HINGE_JOINT_BIAS:
  332. return tau;
  333. case PhysicsServer3D::HINGE_JOINT_LIMIT_UPPER:
  334. return m_upperLimit;
  335. case PhysicsServer3D::HINGE_JOINT_LIMIT_LOWER:
  336. return m_lowerLimit;
  337. case PhysicsServer3D::HINGE_JOINT_LIMIT_BIAS:
  338. return m_biasFactor;
  339. case PhysicsServer3D::HINGE_JOINT_LIMIT_SOFTNESS:
  340. return m_limitSoftness;
  341. case PhysicsServer3D::HINGE_JOINT_LIMIT_RELAXATION:
  342. return m_relaxationFactor;
  343. case PhysicsServer3D::HINGE_JOINT_MOTOR_TARGET_VELOCITY:
  344. return m_motorTargetVelocity;
  345. case PhysicsServer3D::HINGE_JOINT_MOTOR_MAX_IMPULSE:
  346. return m_maxMotorImpulse;
  347. case PhysicsServer3D::HINGE_JOINT_MAX:
  348. break; // Can't happen, but silences warning
  349. }
  350. return 0;
  351. }
  352. void GodotHingeJoint3D::set_flag(PhysicsServer3D::HingeJointFlag p_flag, bool p_value) {
  353. switch (p_flag) {
  354. case PhysicsServer3D::HINGE_JOINT_FLAG_USE_LIMIT:
  355. m_useLimit = p_value;
  356. break;
  357. case PhysicsServer3D::HINGE_JOINT_FLAG_ENABLE_MOTOR:
  358. m_enableAngularMotor = p_value;
  359. break;
  360. case PhysicsServer3D::HINGE_JOINT_FLAG_MAX:
  361. break; // Can't happen, but silences warning
  362. }
  363. }
  364. bool GodotHingeJoint3D::get_flag(PhysicsServer3D::HingeJointFlag p_flag) const {
  365. switch (p_flag) {
  366. case PhysicsServer3D::HINGE_JOINT_FLAG_USE_LIMIT:
  367. return m_useLimit;
  368. case PhysicsServer3D::HINGE_JOINT_FLAG_ENABLE_MOTOR:
  369. return m_enableAngularMotor;
  370. case PhysicsServer3D::HINGE_JOINT_FLAG_MAX:
  371. break; // Can't happen, but silences warning
  372. }
  373. return false;
  374. }