vehicle_body.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. /*************************************************************************/
  2. /* vehicle_body.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
  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. #include "vehicle_body.h"
  31. #define ROLLING_INFLUENCE_FIX
  32. class btVehicleJacobianEntry {
  33. public:
  34. Vector3 m_linearJointAxis;
  35. Vector3 m_aJ;
  36. Vector3 m_bJ;
  37. Vector3 m_0MinvJt;
  38. Vector3 m_1MinvJt;
  39. //Optimization: can be stored in the w/last component of one of the vectors
  40. real_t m_Adiag;
  41. real_t getDiagonal() const { return m_Adiag; }
  42. btVehicleJacobianEntry(){};
  43. //constraint between two different rigidbodies
  44. btVehicleJacobianEntry(
  45. const Basis &world2A,
  46. const Basis &world2B,
  47. const Vector3 &rel_pos1,
  48. const Vector3 &rel_pos2,
  49. const Vector3 &jointAxis,
  50. const Vector3 &inertiaInvA,
  51. const real_t massInvA,
  52. const Vector3 &inertiaInvB,
  53. const real_t massInvB)
  54. : m_linearJointAxis(jointAxis) {
  55. m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis));
  56. m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis));
  57. m_0MinvJt = inertiaInvA * m_aJ;
  58. m_1MinvJt = inertiaInvB * m_bJ;
  59. m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ);
  60. //btAssert(m_Adiag > real_t(0.0));
  61. }
  62. real_t getRelativeVelocity(const Vector3 &linvelA, const Vector3 &angvelA, const Vector3 &linvelB, const Vector3 &angvelB) {
  63. Vector3 linrel = linvelA - linvelB;
  64. Vector3 angvela = angvelA * m_aJ;
  65. Vector3 angvelb = angvelB * m_bJ;
  66. linrel *= m_linearJointAxis;
  67. angvela += angvelb;
  68. angvela += linrel;
  69. real_t rel_vel2 = angvela[0] + angvela[1] + angvela[2];
  70. return rel_vel2 + CMP_EPSILON;
  71. }
  72. };
  73. void VehicleWheel::_notification(int p_what) {
  74. if (p_what == NOTIFICATION_ENTER_TREE) {
  75. VehicleBody *cb = Object::cast_to<VehicleBody>(get_parent());
  76. if (!cb)
  77. return;
  78. body = cb;
  79. local_xform = get_transform();
  80. cb->wheels.push_back(this);
  81. m_chassisConnectionPointCS = get_transform().origin;
  82. m_wheelDirectionCS = -get_transform().basis.get_axis(Vector3::AXIS_Y).normalized();
  83. m_wheelAxleCS = get_transform().basis.get_axis(Vector3::AXIS_X).normalized();
  84. }
  85. if (p_what == NOTIFICATION_EXIT_TREE) {
  86. VehicleBody *cb = Object::cast_to<VehicleBody>(get_parent());
  87. if (!cb)
  88. return;
  89. cb->wheels.erase(this);
  90. body = NULL;
  91. }
  92. }
  93. String VehicleWheel::get_configuration_warning() const {
  94. if (!Object::cast_to<VehicleBody>(get_parent())) {
  95. return TTR("VehicleWheel serves to provide a wheel system to a VehicleBody. Please use it as a child of a VehicleBody.");
  96. }
  97. return String();
  98. }
  99. void VehicleWheel::_update(PhysicsDirectBodyState *s) {
  100. if (m_raycastInfo.m_isInContact)
  101. {
  102. real_t project = m_raycastInfo.m_contactNormalWS.dot(m_raycastInfo.m_wheelDirectionWS);
  103. Vector3 chassis_velocity_at_contactPoint;
  104. Vector3 relpos = m_raycastInfo.m_contactPointWS - s->get_transform().origin;
  105. chassis_velocity_at_contactPoint = s->get_linear_velocity() +
  106. (s->get_angular_velocity()).cross(relpos); // * mPos);
  107. real_t projVel = m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
  108. if (project >= real_t(-0.1)) {
  109. m_suspensionRelativeVelocity = real_t(0.0);
  110. m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
  111. } else {
  112. real_t inv = real_t(-1.) / project;
  113. m_suspensionRelativeVelocity = projVel * inv;
  114. m_clippedInvContactDotSuspension = inv;
  115. }
  116. }
  117. else // Not in contact : position wheel in a nice (rest length) position
  118. {
  119. m_raycastInfo.m_suspensionLength = m_suspensionRestLength;
  120. m_suspensionRelativeVelocity = real_t(0.0);
  121. m_raycastInfo.m_contactNormalWS = -m_raycastInfo.m_wheelDirectionWS;
  122. m_clippedInvContactDotSuspension = real_t(1.0);
  123. }
  124. }
  125. void VehicleWheel::set_radius(float p_radius) {
  126. m_wheelRadius = p_radius;
  127. update_gizmo();
  128. }
  129. float VehicleWheel::get_radius() const {
  130. return m_wheelRadius;
  131. }
  132. void VehicleWheel::set_suspension_rest_length(float p_length) {
  133. m_suspensionRestLength = p_length;
  134. update_gizmo();
  135. }
  136. float VehicleWheel::get_suspension_rest_length() const {
  137. return m_suspensionRestLength;
  138. }
  139. void VehicleWheel::set_suspension_travel(float p_length) {
  140. m_maxSuspensionTravelCm = p_length / 0.01;
  141. }
  142. float VehicleWheel::get_suspension_travel() const {
  143. return m_maxSuspensionTravelCm * 0.01;
  144. }
  145. void VehicleWheel::set_suspension_stiffness(float p_value) {
  146. m_suspensionStiffness = p_value;
  147. }
  148. float VehicleWheel::get_suspension_stiffness() const {
  149. return m_suspensionStiffness;
  150. }
  151. void VehicleWheel::set_suspension_max_force(float p_value) {
  152. m_maxSuspensionForce = p_value;
  153. }
  154. float VehicleWheel::get_suspension_max_force() const {
  155. return m_maxSuspensionForce;
  156. }
  157. void VehicleWheel::set_damping_compression(float p_value) {
  158. m_wheelsDampingCompression = p_value;
  159. }
  160. float VehicleWheel::get_damping_compression() const {
  161. return m_wheelsDampingCompression;
  162. }
  163. void VehicleWheel::set_damping_relaxation(float p_value) {
  164. m_wheelsDampingRelaxation = p_value;
  165. }
  166. float VehicleWheel::get_damping_relaxation() const {
  167. return m_wheelsDampingRelaxation;
  168. }
  169. void VehicleWheel::set_friction_slip(float p_value) {
  170. m_frictionSlip = p_value;
  171. }
  172. float VehicleWheel::get_friction_slip() const {
  173. return m_frictionSlip;
  174. }
  175. void VehicleWheel::set_roll_influence(float p_value) {
  176. m_rollInfluence = p_value;
  177. }
  178. float VehicleWheel::get_roll_influence() const {
  179. return m_rollInfluence;
  180. }
  181. bool VehicleWheel::is_in_contact() const {
  182. return m_raycastInfo.m_isInContact;
  183. }
  184. void VehicleWheel::_bind_methods() {
  185. ClassDB::bind_method(D_METHOD("set_radius", "length"), &VehicleWheel::set_radius);
  186. ClassDB::bind_method(D_METHOD("get_radius"), &VehicleWheel::get_radius);
  187. ClassDB::bind_method(D_METHOD("set_suspension_rest_length", "length"), &VehicleWheel::set_suspension_rest_length);
  188. ClassDB::bind_method(D_METHOD("get_suspension_rest_length"), &VehicleWheel::get_suspension_rest_length);
  189. ClassDB::bind_method(D_METHOD("set_suspension_travel", "length"), &VehicleWheel::set_suspension_travel);
  190. ClassDB::bind_method(D_METHOD("get_suspension_travel"), &VehicleWheel::get_suspension_travel);
  191. ClassDB::bind_method(D_METHOD("set_suspension_stiffness", "length"), &VehicleWheel::set_suspension_stiffness);
  192. ClassDB::bind_method(D_METHOD("get_suspension_stiffness"), &VehicleWheel::get_suspension_stiffness);
  193. ClassDB::bind_method(D_METHOD("set_suspension_max_force", "length"), &VehicleWheel::set_suspension_max_force);
  194. ClassDB::bind_method(D_METHOD("get_suspension_max_force"), &VehicleWheel::get_suspension_max_force);
  195. ClassDB::bind_method(D_METHOD("set_damping_compression", "length"), &VehicleWheel::set_damping_compression);
  196. ClassDB::bind_method(D_METHOD("get_damping_compression"), &VehicleWheel::get_damping_compression);
  197. ClassDB::bind_method(D_METHOD("set_damping_relaxation", "length"), &VehicleWheel::set_damping_relaxation);
  198. ClassDB::bind_method(D_METHOD("get_damping_relaxation"), &VehicleWheel::get_damping_relaxation);
  199. ClassDB::bind_method(D_METHOD("set_use_as_traction", "enable"), &VehicleWheel::set_use_as_traction);
  200. ClassDB::bind_method(D_METHOD("is_used_as_traction"), &VehicleWheel::is_used_as_traction);
  201. ClassDB::bind_method(D_METHOD("set_use_as_steering", "enable"), &VehicleWheel::set_use_as_steering);
  202. ClassDB::bind_method(D_METHOD("is_used_as_steering"), &VehicleWheel::is_used_as_steering);
  203. ClassDB::bind_method(D_METHOD("set_friction_slip", "length"), &VehicleWheel::set_friction_slip);
  204. ClassDB::bind_method(D_METHOD("get_friction_slip"), &VehicleWheel::get_friction_slip);
  205. ClassDB::bind_method(D_METHOD("is_in_contact"), &VehicleWheel::is_in_contact);
  206. ClassDB::bind_method(D_METHOD("set_roll_influence", "roll_influence"), &VehicleWheel::set_roll_influence);
  207. ClassDB::bind_method(D_METHOD("get_roll_influence"), &VehicleWheel::get_roll_influence);
  208. ClassDB::bind_method(D_METHOD("get_skidinfo"), &VehicleWheel::get_skidinfo);
  209. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_traction"), "set_use_as_traction", "is_used_as_traction");
  210. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_steering"), "set_use_as_steering", "is_used_as_steering");
  211. ADD_GROUP("Wheel", "wheel_");
  212. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_roll_influence"), "set_roll_influence", "get_roll_influence");
  213. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_radius"), "set_radius", "get_radius");
  214. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_rest_length"), "set_suspension_rest_length", "get_suspension_rest_length");
  215. ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_friction_slip"), "set_friction_slip", "get_friction_slip");
  216. ADD_GROUP("Suspension", "suspension_");
  217. ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_travel"), "set_suspension_travel", "get_suspension_travel");
  218. ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_stiffness"), "set_suspension_stiffness", "get_suspension_stiffness");
  219. ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_max_force"), "set_suspension_max_force", "get_suspension_max_force");
  220. ADD_GROUP("Damping", "damping_");
  221. ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_compression"), "set_damping_compression", "get_damping_compression");
  222. ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_relaxation"), "set_damping_relaxation", "get_damping_relaxation");
  223. }
  224. void VehicleWheel::set_use_as_traction(bool p_enable) {
  225. engine_traction = p_enable;
  226. }
  227. bool VehicleWheel::is_used_as_traction() const {
  228. return engine_traction;
  229. }
  230. void VehicleWheel::set_use_as_steering(bool p_enabled) {
  231. steers = p_enabled;
  232. }
  233. bool VehicleWheel::is_used_as_steering() const {
  234. return steers;
  235. }
  236. float VehicleWheel::get_skidinfo() const {
  237. return m_skidInfo;
  238. }
  239. VehicleWheel::VehicleWheel() {
  240. steers = false;
  241. engine_traction = false;
  242. m_steering = real_t(0.);
  243. //m_engineForce = real_t(0.);
  244. m_rotation = real_t(0.);
  245. m_deltaRotation = real_t(0.);
  246. m_brake = real_t(0.);
  247. m_rollInfluence = real_t(0.1);
  248. m_suspensionRestLength = 0.15;
  249. m_wheelRadius = 0.5; //0.28;
  250. m_suspensionStiffness = 5.88;
  251. m_wheelsDampingCompression = 0.83;
  252. m_wheelsDampingRelaxation = 0.88;
  253. m_frictionSlip = 10.5;
  254. m_bIsFrontWheel = false;
  255. m_maxSuspensionTravelCm = 500;
  256. m_maxSuspensionForce = 6000;
  257. m_suspensionRelativeVelocity = 0;
  258. m_clippedInvContactDotSuspension = 1.0;
  259. m_raycastInfo.m_isInContact = false;
  260. body = NULL;
  261. }
  262. void VehicleBody::_update_wheel_transform(VehicleWheel &wheel, PhysicsDirectBodyState *s) {
  263. wheel.m_raycastInfo.m_isInContact = false;
  264. Transform chassisTrans = s->get_transform();
  265. /*
  266. if (interpolatedTransform && (getRigidBody()->getMotionState())) {
  267. getRigidBody()->getMotionState()->getWorldTransform(chassisTrans);
  268. }
  269. */
  270. wheel.m_raycastInfo.m_hardPointWS = chassisTrans.xform(wheel.m_chassisConnectionPointCS);
  271. //wheel.m_raycastInfo.m_hardPointWS+=s->get_linear_velocity()*s->get_step();
  272. wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.get_basis().xform(wheel.m_wheelDirectionCS).normalized();
  273. wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.get_basis().xform(wheel.m_wheelAxleCS).normalized();
  274. }
  275. void VehicleBody::_update_wheel(int p_idx, PhysicsDirectBodyState *s) {
  276. VehicleWheel &wheel = *wheels[p_idx];
  277. _update_wheel_transform(wheel, s);
  278. Vector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS;
  279. const Vector3 &right = wheel.m_raycastInfo.m_wheelAxleWS;
  280. Vector3 fwd = up.cross(right);
  281. fwd = fwd.normalized();
  282. //up = right.cross(fwd);
  283. //up.normalize();
  284. //rotate around steering over de wheelAxleWS
  285. real_t steering = wheel.steers ? m_steeringValue : 0.0;
  286. //print_line(itos(p_idx)+": "+rtos(steering));
  287. Basis steeringMat(up, steering);
  288. Basis rotatingMat(right, -wheel.m_rotation);
  289. /*
  290. if (p_idx==1)
  291. print_line("steeringMat " +steeringMat);
  292. */
  293. Basis basis2(
  294. right[0], up[0], fwd[0],
  295. right[1], up[1], fwd[1],
  296. right[2], up[2], fwd[2]);
  297. wheel.m_worldTransform.set_basis(steeringMat * rotatingMat * basis2);
  298. //wheel.m_worldTransform.set_basis(basis2 * (steeringMat * rotatingMat));
  299. wheel.m_worldTransform.set_origin(
  300. wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength);
  301. }
  302. real_t VehicleBody::_ray_cast(int p_idx, PhysicsDirectBodyState *s) {
  303. VehicleWheel &wheel = *wheels[p_idx];
  304. _update_wheel_transform(wheel, s);
  305. real_t depth = -1;
  306. real_t raylen = wheel.m_suspensionRestLength + wheel.m_wheelRadius;
  307. Vector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen);
  308. Vector3 source = wheel.m_raycastInfo.m_hardPointWS;
  309. wheel.m_raycastInfo.m_contactPointWS = source + rayvector;
  310. const Vector3 &target = wheel.m_raycastInfo.m_contactPointWS;
  311. source -= wheel.m_wheelRadius * wheel.m_raycastInfo.m_wheelDirectionWS;
  312. real_t param = real_t(0.);
  313. PhysicsDirectSpaceState::RayResult rr;
  314. PhysicsDirectSpaceState *ss = s->get_space_state();
  315. bool col = ss->intersect_ray(source, target, rr, exclude);
  316. wheel.m_raycastInfo.m_groundObject = 0;
  317. if (col) {
  318. //print_line("WHEEL "+itos(p_idx)+" FROM "+source+" TO: "+target);
  319. //print_line("WHEEL "+itos(p_idx)+" COLLIDE? "+itos(col));
  320. param = source.distance_to(rr.position) / source.distance_to(target);
  321. depth = raylen * param;
  322. wheel.m_raycastInfo.m_contactNormalWS = rr.normal;
  323. wheel.m_raycastInfo.m_isInContact = true;
  324. if (rr.collider)
  325. wheel.m_raycastInfo.m_groundObject = Object::cast_to<PhysicsBody>(rr.collider);
  326. real_t hitDistance = param * raylen;
  327. wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelRadius;
  328. //clamp on max suspension travel
  329. real_t minSuspensionLength = wheel.m_suspensionRestLength - wheel.m_maxSuspensionTravelCm * real_t(0.01);
  330. real_t maxSuspensionLength = wheel.m_suspensionRestLength + wheel.m_maxSuspensionTravelCm * real_t(0.01);
  331. if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) {
  332. wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength;
  333. }
  334. if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) {
  335. wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength;
  336. }
  337. wheel.m_raycastInfo.m_contactPointWS = rr.position;
  338. real_t denominator = wheel.m_raycastInfo.m_contactNormalWS.dot(wheel.m_raycastInfo.m_wheelDirectionWS);
  339. Vector3 chassis_velocity_at_contactPoint;
  340. //Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS-getRigidBody()->getCenterOfMassPosition();
  341. //chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos);
  342. chassis_velocity_at_contactPoint = s->get_linear_velocity() +
  343. (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin); // * mPos);
  344. real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
  345. if (denominator >= real_t(-0.1)) {
  346. wheel.m_suspensionRelativeVelocity = real_t(0.0);
  347. wheel.m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
  348. } else {
  349. real_t inv = real_t(-1.) / denominator;
  350. wheel.m_suspensionRelativeVelocity = projVel * inv;
  351. wheel.m_clippedInvContactDotSuspension = inv;
  352. }
  353. } else {
  354. wheel.m_raycastInfo.m_isInContact = false;
  355. //put wheel info as in rest position
  356. wheel.m_raycastInfo.m_suspensionLength = wheel.m_suspensionRestLength;
  357. wheel.m_suspensionRelativeVelocity = real_t(0.0);
  358. wheel.m_raycastInfo.m_contactNormalWS = -wheel.m_raycastInfo.m_wheelDirectionWS;
  359. wheel.m_clippedInvContactDotSuspension = real_t(1.0);
  360. }
  361. return depth;
  362. }
  363. void VehicleBody::_update_suspension(PhysicsDirectBodyState *s) {
  364. real_t chassisMass = mass;
  365. for (int w_it = 0; w_it < wheels.size(); w_it++) {
  366. VehicleWheel &wheel_info = *wheels[w_it];
  367. if (wheel_info.m_raycastInfo.m_isInContact) {
  368. real_t force;
  369. //Spring
  370. {
  371. real_t susp_length = wheel_info.m_suspensionRestLength;
  372. real_t current_length = wheel_info.m_raycastInfo.m_suspensionLength;
  373. real_t length_diff = (susp_length - current_length);
  374. force = wheel_info.m_suspensionStiffness * length_diff * wheel_info.m_clippedInvContactDotSuspension;
  375. }
  376. // Damper
  377. {
  378. real_t projected_rel_vel = wheel_info.m_suspensionRelativeVelocity;
  379. {
  380. real_t susp_damping;
  381. if (projected_rel_vel < real_t(0.0)) {
  382. susp_damping = wheel_info.m_wheelsDampingCompression;
  383. } else {
  384. susp_damping = wheel_info.m_wheelsDampingRelaxation;
  385. }
  386. force -= susp_damping * projected_rel_vel;
  387. }
  388. }
  389. // RESULT
  390. wheel_info.m_wheelsSuspensionForce = force * chassisMass;
  391. if (wheel_info.m_wheelsSuspensionForce < real_t(0.)) {
  392. wheel_info.m_wheelsSuspensionForce = real_t(0.);
  393. }
  394. } else {
  395. wheel_info.m_wheelsSuspensionForce = real_t(0.0);
  396. }
  397. }
  398. }
  399. //bilateral constraint between two dynamic objects
  400. void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3 &pos1,
  401. PhysicsBody *body2, const Vector3 &pos2, const Vector3 &normal, real_t &impulse) {
  402. real_t normalLenSqr = normal.length_squared();
  403. //ERR_FAIL_COND( normalLenSqr < real_t(1.1));
  404. if (normalLenSqr > real_t(1.1)) {
  405. impulse = real_t(0.);
  406. return;
  407. }
  408. Vector3 rel_pos1 = pos1 - s->get_transform().origin;
  409. Vector3 rel_pos2;
  410. if (body2)
  411. rel_pos2 = pos2 - body2->get_global_transform().origin;
  412. //this jacobian entry could be re-used for all iterations
  413. Vector3 vel1 = s->get_linear_velocity() + (s->get_angular_velocity()).cross(rel_pos1); // * mPos);
  414. Vector3 vel2;
  415. if (body2)
  416. vel2 = body2->get_linear_velocity() + body2->get_angular_velocity().cross(rel_pos2);
  417. Vector3 vel = vel1 - vel2;
  418. Basis b2trans;
  419. float b2invmass = 0;
  420. Vector3 b2lv;
  421. Vector3 b2av;
  422. Vector3 b2invinertia; //todo
  423. if (body2) {
  424. b2trans = body2->get_global_transform().basis.transposed();
  425. b2invmass = body2->get_inverse_mass();
  426. b2lv = body2->get_linear_velocity();
  427. b2av = body2->get_angular_velocity();
  428. }
  429. btVehicleJacobianEntry jac(s->get_transform().basis.transposed(),
  430. b2trans,
  431. rel_pos1,
  432. rel_pos2,
  433. normal,
  434. s->get_inverse_inertia_tensor().get_main_diagonal(),
  435. 1.0 / mass,
  436. b2invinertia,
  437. b2invmass);
  438. // FIXME: rel_vel assignment here is overwritten by the following assignment.
  439. // What seemes to be intented in the next next assignment is: rel_vel = normal.dot(rel_vel);
  440. // Investigate why.
  441. real_t rel_vel = jac.getRelativeVelocity(
  442. s->get_linear_velocity(),
  443. s->get_transform().basis.transposed().xform(s->get_angular_velocity()),
  444. b2lv,
  445. b2trans.xform(b2av));
  446. rel_vel = normal.dot(vel);
  447. //TODO: move this into proper structure
  448. real_t contactDamping = real_t(0.4);
  449. #define ONLY_USE_LINEAR_MASS
  450. #ifdef ONLY_USE_LINEAR_MASS
  451. real_t massTerm = real_t(1.) / ((1.0 / mass) + b2invmass);
  452. impulse = -contactDamping * rel_vel * massTerm;
  453. #else
  454. real_t velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
  455. impulse = velocityImpulse;
  456. #endif
  457. }
  458. VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirectBodyState *s, PhysicsBody *body1, const Vector3 &frictionPosWorld, const Vector3 &frictionDirectionWorld, real_t maxImpulse)
  459. : m_s(s),
  460. m_body1(body1),
  461. m_frictionPositionWorld(frictionPosWorld),
  462. m_frictionDirectionWorld(frictionDirectionWorld),
  463. m_maxImpulse(maxImpulse) {
  464. float denom0 = 0;
  465. float denom1 = 0;
  466. {
  467. Vector3 r0 = frictionPosWorld - s->get_transform().origin;
  468. Vector3 c0 = (r0).cross(frictionDirectionWorld);
  469. Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0);
  470. denom0 = s->get_inverse_mass() + frictionDirectionWorld.dot(vec);
  471. }
  472. /* TODO: Why is this code unused?
  473. if (body1) {
  474. Vector3 r0 = frictionPosWorld - body1->get_global_transform().origin;
  475. Vector3 c0 = (r0).cross(frictionDirectionWorld);
  476. Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0);
  477. //denom1= body1->get_inverse_mass() + frictionDirectionWorld.dot(vec);
  478. }
  479. */
  480. real_t relaxation = 1.f;
  481. m_jacDiagABInv = relaxation / (denom0 + denom1);
  482. }
  483. real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint &contactPoint) {
  484. real_t j1 = 0.f;
  485. const Vector3 &contactPosWorld = contactPoint.m_frictionPositionWorld;
  486. Vector3 rel_pos1 = contactPosWorld - contactPoint.m_s->get_transform().origin;
  487. Vector3 rel_pos2;
  488. if (contactPoint.m_body1)
  489. rel_pos2 = contactPosWorld - contactPoint.m_body1->get_global_transform().origin;
  490. real_t maxImpulse = contactPoint.m_maxImpulse;
  491. Vector3 vel1 = contactPoint.m_s->get_linear_velocity() + (contactPoint.m_s->get_angular_velocity()).cross(rel_pos1); // * mPos);
  492. Vector3 vel2;
  493. if (contactPoint.m_body1) {
  494. vel2 = contactPoint.m_body1->get_linear_velocity() + contactPoint.m_body1->get_angular_velocity().cross(rel_pos2);
  495. }
  496. Vector3 vel = vel1 - vel2;
  497. real_t vrel = contactPoint.m_frictionDirectionWorld.dot(vel);
  498. // calculate j that moves us to zero relative velocity
  499. j1 = -vrel * contactPoint.m_jacDiagABInv;
  500. return CLAMP(j1, -maxImpulse, maxImpulse);
  501. }
  502. static const real_t sideFrictionStiffness2 = real_t(1.0);
  503. void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
  504. //calculate the impulse, so that the wheels don't move sidewards
  505. int numWheel = wheels.size();
  506. if (!numWheel)
  507. return;
  508. m_forwardWS.resize(numWheel);
  509. m_axle.resize(numWheel);
  510. m_forwardImpulse.resize(numWheel);
  511. m_sideImpulse.resize(numWheel);
  512. int numWheelsOnGround = 0;
  513. //collapse all those loops into one!
  514. for (int i = 0; i < wheels.size(); i++) {
  515. VehicleWheel &wheelInfo = *wheels[i];
  516. if (wheelInfo.m_raycastInfo.m_isInContact)
  517. numWheelsOnGround++;
  518. m_sideImpulse[i] = real_t(0.);
  519. m_forwardImpulse[i] = real_t(0.);
  520. }
  521. {
  522. for (int i = 0; i < wheels.size(); i++) {
  523. VehicleWheel &wheelInfo = *wheels[i];
  524. if (wheelInfo.m_raycastInfo.m_isInContact) {
  525. //const btTransform& wheelTrans = getWheelTransformWS( i );
  526. Basis wheelBasis0 = wheelInfo.m_worldTransform.basis; //get_global_transform().basis;
  527. m_axle[i] = wheelBasis0.get_axis(Vector3::AXIS_X);
  528. //m_axle[i] = wheelInfo.m_raycastInfo.m_wheelAxleWS;
  529. const Vector3 &surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS;
  530. real_t proj = m_axle[i].dot(surfNormalWS);
  531. m_axle[i] -= surfNormalWS * proj;
  532. m_axle[i] = m_axle[i].normalized();
  533. m_forwardWS[i] = surfNormalWS.cross(m_axle[i]);
  534. m_forwardWS[i].normalize();
  535. _resolve_single_bilateral(s, wheelInfo.m_raycastInfo.m_contactPointWS,
  536. wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS,
  537. m_axle[i], m_sideImpulse[i]);
  538. m_sideImpulse[i] *= sideFrictionStiffness2;
  539. }
  540. }
  541. }
  542. real_t sideFactor = real_t(1.);
  543. real_t fwdFactor = 0.5;
  544. bool sliding = false;
  545. {
  546. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  547. VehicleWheel &wheelInfo = *wheels[wheel];
  548. //class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject;
  549. real_t rollingFriction = 0.f;
  550. if (wheelInfo.m_raycastInfo.m_isInContact) {
  551. if (engine_force != 0.f) {
  552. rollingFriction = -engine_force * s->get_step();
  553. } else {
  554. real_t defaultRollingFrictionImpulse = 0.f;
  555. float cbrake = MAX(wheelInfo.m_brake, brake);
  556. real_t maxImpulse = cbrake ? cbrake : defaultRollingFrictionImpulse;
  557. btVehicleWheelContactPoint contactPt(s, wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, m_forwardWS[wheel], maxImpulse);
  558. rollingFriction = _calc_rolling_friction(contactPt);
  559. }
  560. }
  561. //switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break)
  562. m_forwardImpulse[wheel] = real_t(0.);
  563. wheelInfo.m_skidInfo = real_t(1.);
  564. if (wheelInfo.m_raycastInfo.m_isInContact) {
  565. wheelInfo.m_skidInfo = real_t(1.);
  566. real_t maximp = wheelInfo.m_wheelsSuspensionForce * s->get_step() * wheelInfo.m_frictionSlip;
  567. real_t maximpSide = maximp;
  568. real_t maximpSquared = maximp * maximpSide;
  569. m_forwardImpulse[wheel] = rollingFriction; //wheelInfo.m_engineForce* timeStep;
  570. real_t x = (m_forwardImpulse[wheel]) * fwdFactor;
  571. real_t y = (m_sideImpulse[wheel]) * sideFactor;
  572. real_t impulseSquared = (x * x + y * y);
  573. if (impulseSquared > maximpSquared) {
  574. sliding = true;
  575. real_t factor = maximp / Math::sqrt(impulseSquared);
  576. wheelInfo.m_skidInfo *= factor;
  577. }
  578. }
  579. }
  580. }
  581. if (sliding) {
  582. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  583. if (m_sideImpulse[wheel] != real_t(0.)) {
  584. if (wheels[wheel]->m_skidInfo < real_t(1.)) {
  585. m_forwardImpulse[wheel] *= wheels[wheel]->m_skidInfo;
  586. m_sideImpulse[wheel] *= wheels[wheel]->m_skidInfo;
  587. }
  588. }
  589. }
  590. }
  591. // apply the impulses
  592. {
  593. for (int wheel = 0; wheel < wheels.size(); wheel++) {
  594. VehicleWheel &wheelInfo = *wheels[wheel];
  595. Vector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS -
  596. s->get_transform().origin;
  597. if (m_forwardImpulse[wheel] != real_t(0.)) {
  598. s->apply_impulse(rel_pos, m_forwardWS[wheel] * (m_forwardImpulse[wheel]));
  599. }
  600. if (m_sideImpulse[wheel] != real_t(0.)) {
  601. PhysicsBody *groundObject = wheelInfo.m_raycastInfo.m_groundObject;
  602. Vector3 rel_pos2;
  603. if (groundObject) {
  604. rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->get_global_transform().origin;
  605. }
  606. Vector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel];
  607. #if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT.
  608. Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1]; //getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis);
  609. rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f - wheelInfo.m_rollInfluence));
  610. #else
  611. rel_pos[1] *= wheelInfo.m_rollInfluence; //?
  612. #endif
  613. s->apply_impulse(rel_pos, sideImp);
  614. //apply friction impulse on the ground
  615. //todo
  616. //groundObject->applyImpulse(-sideImp,rel_pos2);
  617. }
  618. }
  619. }
  620. }
  621. void VehicleBody::_direct_state_changed(Object *p_state) {
  622. PhysicsDirectBodyState *s = Object::cast_to<PhysicsDirectBodyState>(p_state);
  623. set_ignore_transform_notification(true);
  624. set_global_transform(s->get_transform());
  625. set_ignore_transform_notification(false);
  626. float step = s->get_step();
  627. for (int i = 0; i < wheels.size(); i++) {
  628. _update_wheel(i, s);
  629. }
  630. for (int i = 0; i < wheels.size(); i++) {
  631. _ray_cast(i, s);
  632. wheels[i]->set_transform(s->get_transform().inverse() * wheels[i]->m_worldTransform);
  633. }
  634. _update_suspension(s);
  635. for (int i = 0; i < wheels.size(); i++) {
  636. //apply suspension force
  637. VehicleWheel &wheel = *wheels[i];
  638. real_t suspensionForce = wheel.m_wheelsSuspensionForce;
  639. if (suspensionForce > wheel.m_maxSuspensionForce) {
  640. suspensionForce = wheel.m_maxSuspensionForce;
  641. }
  642. Vector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step;
  643. Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin;
  644. s->apply_impulse(relpos, impulse);
  645. //getRigidBody()->applyImpulse(impulse, relpos);
  646. }
  647. _update_friction(s);
  648. for (int i = 0; i < wheels.size(); i++) {
  649. VehicleWheel &wheel = *wheels[i];
  650. Vector3 relpos = wheel.m_raycastInfo.m_hardPointWS - s->get_transform().origin;
  651. Vector3 vel = s->get_linear_velocity() + (s->get_angular_velocity()).cross(relpos); // * mPos);
  652. if (wheel.m_raycastInfo.m_isInContact) {
  653. const Transform &chassisWorldTransform = s->get_transform();
  654. Vector3 fwd(
  655. chassisWorldTransform.basis[0][Vector3::AXIS_Z],
  656. chassisWorldTransform.basis[1][Vector3::AXIS_Z],
  657. chassisWorldTransform.basis[2][Vector3::AXIS_Z]);
  658. real_t proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS);
  659. fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj;
  660. real_t proj2 = fwd.dot(vel);
  661. wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelRadius);
  662. wheel.m_rotation += wheel.m_deltaRotation;
  663. } else {
  664. wheel.m_rotation += wheel.m_deltaRotation;
  665. }
  666. wheel.m_deltaRotation *= real_t(0.99); //damping of rotation when not in contact
  667. }
  668. linear_velocity = s->get_linear_velocity();
  669. }
  670. void VehicleBody::set_mass(real_t p_mass) {
  671. mass = p_mass;
  672. PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_MASS, mass);
  673. }
  674. real_t VehicleBody::get_mass() const {
  675. return mass;
  676. }
  677. void VehicleBody::set_friction(real_t p_friction) {
  678. friction = p_friction;
  679. PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction);
  680. }
  681. real_t VehicleBody::get_friction() const {
  682. return friction;
  683. }
  684. void VehicleBody::set_engine_force(float p_engine_force) {
  685. engine_force = p_engine_force;
  686. }
  687. float VehicleBody::get_engine_force() const {
  688. return engine_force;
  689. }
  690. void VehicleBody::set_brake(float p_brake) {
  691. brake = p_brake;
  692. }
  693. float VehicleBody::get_brake() const {
  694. return brake;
  695. }
  696. void VehicleBody::set_steering(float p_steering) {
  697. m_steeringValue = p_steering;
  698. }
  699. float VehicleBody::get_steering() const {
  700. return m_steeringValue;
  701. }
  702. Vector3 VehicleBody::get_linear_velocity() const {
  703. return linear_velocity;
  704. }
  705. void VehicleBody::_bind_methods() {
  706. ClassDB::bind_method(D_METHOD("set_mass", "mass"), &VehicleBody::set_mass);
  707. ClassDB::bind_method(D_METHOD("get_mass"), &VehicleBody::get_mass);
  708. ClassDB::bind_method(D_METHOD("set_friction", "friction"), &VehicleBody::set_friction);
  709. ClassDB::bind_method(D_METHOD("get_friction"), &VehicleBody::get_friction);
  710. ClassDB::bind_method(D_METHOD("set_engine_force", "engine_force"), &VehicleBody::set_engine_force);
  711. ClassDB::bind_method(D_METHOD("get_engine_force"), &VehicleBody::get_engine_force);
  712. ClassDB::bind_method(D_METHOD("set_brake", "brake"), &VehicleBody::set_brake);
  713. ClassDB::bind_method(D_METHOD("get_brake"), &VehicleBody::get_brake);
  714. ClassDB::bind_method(D_METHOD("set_steering", "steering"), &VehicleBody::set_steering);
  715. ClassDB::bind_method(D_METHOD("get_steering"), &VehicleBody::get_steering);
  716. ClassDB::bind_method(D_METHOD("get_linear_velocity"), &VehicleBody::get_linear_velocity);
  717. ClassDB::bind_method(D_METHOD("_direct_state_changed"), &VehicleBody::_direct_state_changed);
  718. ADD_GROUP("Motion", "");
  719. ADD_PROPERTY(PropertyInfo(Variant::REAL, "engine_force", PROPERTY_HINT_RANGE, "0.00,1024.0,0.01"), "set_engine_force", "get_engine_force");
  720. ADD_PROPERTY(PropertyInfo(Variant::REAL, "brake", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_brake", "get_brake");
  721. ADD_PROPERTY(PropertyInfo(Variant::REAL, "steering", PROPERTY_HINT_RANGE, "-180,180.0,0.01"), "set_steering", "get_steering");
  722. ADD_GROUP("Mass", "");
  723. ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_RANGE, "0.01,65536,0.01"), "set_mass", "get_mass");
  724. ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0.01,1,0.01"), "set_friction", "get_friction");
  725. }
  726. VehicleBody::VehicleBody()
  727. : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) {
  728. m_pitchControl = 0;
  729. m_currentVehicleSpeedKmHour = real_t(0.);
  730. m_steeringValue = real_t(0.);
  731. engine_force = 0;
  732. brake = 0;
  733. friction = 1;
  734. ccd = false;
  735. exclude.insert(get_rid());
  736. PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed");
  737. set_mass(40);
  738. }