vehicle_body.cpp 33 KB

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