jolt_physics_direct_space_state_3d.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. /**************************************************************************/
  2. /* jolt_physics_direct_space_state_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. #include "jolt_physics_direct_space_state_3d.h"
  31. #include "../jolt_physics_server_3d.h"
  32. #include "../jolt_project_settings.h"
  33. #include "../misc/jolt_math_funcs.h"
  34. #include "../misc/jolt_type_conversions.h"
  35. #include "../objects/jolt_area_3d.h"
  36. #include "../objects/jolt_body_3d.h"
  37. #include "../objects/jolt_object_3d.h"
  38. #include "../shapes/jolt_custom_motion_shape.h"
  39. #include "../shapes/jolt_shape_3d.h"
  40. #include "jolt_motion_filter_3d.h"
  41. #include "jolt_query_collectors.h"
  42. #include "jolt_query_filter_3d.h"
  43. #include "jolt_space_3d.h"
  44. #include "Jolt/Geometry/GJKClosestPoint.h"
  45. #include "Jolt/Physics/Body/Body.h"
  46. #include "Jolt/Physics/Body/BodyFilter.h"
  47. #include "Jolt/Physics/Collision/BroadPhase/BroadPhaseQuery.h"
  48. #include "Jolt/Physics/Collision/CastResult.h"
  49. #include "Jolt/Physics/Collision/CollidePointResult.h"
  50. #include "Jolt/Physics/Collision/NarrowPhaseQuery.h"
  51. #include "Jolt/Physics/Collision/RayCast.h"
  52. #include "Jolt/Physics/Collision/Shape/MeshShape.h"
  53. #include "Jolt/Physics/PhysicsSystem.h"
  54. bool JoltPhysicsDirectSpaceState3D::_cast_motion_impl(const JPH::Shape &p_jolt_shape, const Transform3D &p_transform_com, const Vector3 &p_scale, const Vector3 &p_motion, bool p_use_edge_removal, bool p_ignore_overlaps, const JPH::CollideShapeSettings &p_settings, const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter, const JPH::ObjectLayerFilter &p_object_layer_filter, const JPH::BodyFilter &p_body_filter, const JPH::ShapeFilter &p_shape_filter, real_t &r_closest_safe, real_t &r_closest_unsafe) const {
  55. r_closest_safe = 1.0f;
  56. r_closest_unsafe = 1.0f;
  57. ERR_FAIL_COND_V_MSG(p_jolt_shape.GetType() != JPH::EShapeType::Convex, false, "Shape-casting with non-convex shapes is not supported.");
  58. const float motion_length = (float)p_motion.length();
  59. if (p_ignore_overlaps && motion_length == 0.0f) {
  60. return false;
  61. }
  62. const JPH::RMat44 transform_com = to_jolt_r(p_transform_com);
  63. const JPH::Vec3 scale = to_jolt(p_scale);
  64. const JPH::Vec3 motion = to_jolt(p_motion);
  65. const JPH::Vec3 motion_local = transform_com.Multiply3x3Transposed(motion);
  66. JPH::AABox aabb = p_jolt_shape.GetWorldSpaceBounds(transform_com, scale);
  67. JPH::AABox aabb_translated = aabb;
  68. aabb_translated.Translate(motion);
  69. aabb.Encapsulate(aabb_translated);
  70. JoltQueryCollectorAnyMulti<JPH::CollideShapeBodyCollector, 1024> aabb_collector;
  71. space->get_broad_phase_query().CollideAABox(aabb, aabb_collector, p_broad_phase_layer_filter, p_object_layer_filter);
  72. if (!aabb_collector.had_hit()) {
  73. return false;
  74. }
  75. const JPH::RVec3 base_offset = transform_com.GetTranslation();
  76. JoltCustomMotionShape motion_shape(static_cast<const JPH::ConvexShape &>(p_jolt_shape));
  77. auto collides = [&](const JPH::Body &p_other_body, float p_fraction) {
  78. motion_shape.set_motion(motion_local * p_fraction);
  79. const JPH::TransformedShape other_shape = p_other_body.GetTransformedShape();
  80. JoltQueryCollectorAny<JPH::CollideShapeCollector> collector;
  81. if (p_use_edge_removal) {
  82. JPH::CollideShapeSettings eier_settings = p_settings;
  83. eier_settings.mActiveEdgeMode = JPH::EActiveEdgeMode::CollideWithAll;
  84. eier_settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  85. JPH::InternalEdgeRemovingCollector eier_collector(collector);
  86. other_shape.CollideShape(&motion_shape, scale, transform_com, eier_settings, base_offset, eier_collector, p_shape_filter);
  87. eier_collector.Flush();
  88. } else {
  89. other_shape.CollideShape(&motion_shape, scale, transform_com, p_settings, base_offset, collector, p_shape_filter);
  90. }
  91. return collector.had_hit();
  92. };
  93. // Figure out the number of steps we need in our binary search in order to achieve millimeter precision, within reason.
  94. const int step_count = CLAMP(int(std::log(1000.0f * motion_length) / (float)Math::LN2), 4, 16);
  95. bool collided = false;
  96. for (int i = 0; i < aabb_collector.get_hit_count(); ++i) {
  97. const JPH::BodyID other_jolt_id = aabb_collector.get_hit(i);
  98. if (!p_body_filter.ShouldCollide(other_jolt_id)) {
  99. continue;
  100. }
  101. const JPH::Body *other_jolt_body = space->try_get_jolt_body(other_jolt_id);
  102. if (!p_body_filter.ShouldCollideLocked(*other_jolt_body)) {
  103. continue;
  104. }
  105. if (!collides(*other_jolt_body, 1.0f)) {
  106. continue;
  107. }
  108. if (p_ignore_overlaps && collides(*other_jolt_body, 0.0f)) {
  109. continue;
  110. }
  111. float lo = 0.0f;
  112. float hi = 1.0f;
  113. float coeff = 0.5f;
  114. for (int j = 0; j < step_count; ++j) {
  115. const float fraction = lo + (hi - lo) * coeff;
  116. if (collides(*other_jolt_body, fraction)) {
  117. collided = true;
  118. hi = fraction;
  119. if (j == 0 || lo > 0.0f) {
  120. coeff = 0.5f;
  121. } else {
  122. coeff = 0.25f;
  123. }
  124. } else {
  125. lo = fraction;
  126. if (j == 0 || hi < 1.0f) {
  127. coeff = 0.5f;
  128. } else {
  129. coeff = 0.75f;
  130. }
  131. }
  132. }
  133. if (lo < r_closest_safe) {
  134. r_closest_safe = lo;
  135. r_closest_unsafe = hi;
  136. }
  137. }
  138. return collided;
  139. }
  140. bool JoltPhysicsDirectSpaceState3D::_body_motion_recover(const JoltBody3D &p_body, const Transform3D &p_transform, float p_margin, const HashSet<RID> &p_excluded_bodies, const HashSet<ObjectID> &p_excluded_objects, Vector3 &r_recovery) const {
  141. const JPH::Shape *jolt_shape = p_body.get_jolt_shape();
  142. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  143. Transform3D transform_com = p_transform.translated_local(com_scaled);
  144. JPH::CollideShapeSettings settings;
  145. settings.mMaxSeparationDistance = p_margin;
  146. const Vector3 &base_offset = transform_com.origin;
  147. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects);
  148. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector;
  149. bool recovered = false;
  150. for (int i = 0; i < JoltProjectSettings::motion_query_recovery_iterations; ++i) {
  151. collector.reset();
  152. _collide_shape_kinematics(jolt_shape, JPH::Vec3::sOne(), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, motion_filter, motion_filter, motion_filter, motion_filter);
  153. if (!collector.had_hit()) {
  154. break;
  155. }
  156. const int hit_count = collector.get_hit_count();
  157. float combined_priority = 0.0;
  158. for (int j = 0; j < hit_count; j++) {
  159. const JPH::CollideShapeResult &hit = collector.get_hit(j);
  160. const JoltBody3D *other_body = space->try_get_body(hit.mBodyID2);
  161. ERR_CONTINUE(other_body == nullptr);
  162. combined_priority += other_body->get_collision_priority();
  163. }
  164. const float average_priority = MAX(combined_priority / (float)hit_count, (float)CMP_EPSILON);
  165. recovered = true;
  166. Vector3 recovery;
  167. for (int j = 0; j < hit_count; ++j) {
  168. const JPH::CollideShapeResult &hit = collector.get_hit(j);
  169. const Vector3 penetration_axis = to_godot(hit.mPenetrationAxis.Normalized());
  170. const Vector3 margin_offset = penetration_axis * p_margin;
  171. const Vector3 point_on_1 = base_offset + to_godot(hit.mContactPointOn1) + margin_offset;
  172. const Vector3 point_on_2 = base_offset + to_godot(hit.mContactPointOn2);
  173. const real_t distance_to_1 = penetration_axis.dot(point_on_1 + recovery);
  174. const real_t distance_to_2 = penetration_axis.dot(point_on_2);
  175. const float penetration_depth = float(distance_to_1 - distance_to_2);
  176. if (penetration_depth <= 0.0f) {
  177. continue;
  178. }
  179. const JoltBody3D *other_body = space->try_get_body(hit.mBodyID2);
  180. ERR_CONTINUE(other_body == nullptr);
  181. const float recovery_distance = penetration_depth * JoltProjectSettings::motion_query_recovery_amount;
  182. const float other_priority = other_body->get_collision_priority();
  183. const float other_priority_normalized = other_priority / average_priority;
  184. const float scaled_recovery_distance = recovery_distance * other_priority_normalized;
  185. recovery -= penetration_axis * scaled_recovery_distance;
  186. }
  187. if (recovery == Vector3()) {
  188. break;
  189. }
  190. r_recovery += recovery;
  191. transform_com.origin += recovery;
  192. }
  193. return recovered;
  194. }
  195. bool JoltPhysicsDirectSpaceState3D::_body_motion_cast(const JoltBody3D &p_body, const Transform3D &p_transform, const Vector3 &p_scale, const Vector3 &p_motion, bool p_collide_separation_ray, const HashSet<RID> &p_excluded_bodies, const HashSet<ObjectID> &p_excluded_objects, real_t &r_safe_fraction, real_t &r_unsafe_fraction) const {
  196. const Transform3D body_transform = p_transform.scaled_local(p_scale);
  197. const JPH::CollideShapeSettings settings;
  198. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects, p_collide_separation_ray);
  199. bool collided = false;
  200. for (int i = 0; i < p_body.get_shape_count(); ++i) {
  201. if (p_body.is_shape_disabled(i)) {
  202. continue;
  203. }
  204. JoltShape3D *shape = p_body.get_shape(i);
  205. if (!shape->is_convex()) {
  206. continue;
  207. }
  208. const JPH::ShapeRefC jolt_shape = shape->try_build();
  209. if (unlikely(jolt_shape == nullptr)) {
  210. return false;
  211. }
  212. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  213. const Transform3D transform_local = p_body.get_shape_transform_scaled(i);
  214. const Transform3D transform_com_local = transform_local.translated_local(com_scaled);
  215. Transform3D transform_com = body_transform * transform_com_local;
  216. Vector3 scale;
  217. JoltMath::decompose(transform_com, scale);
  218. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "body_test_motion was passed an invalid transform along with body '%s'. This results in invalid scaling for shape at index %d.");
  219. real_t shape_safe_fraction = 1.0;
  220. real_t shape_unsafe_fraction = 1.0;
  221. collided |= _cast_motion_impl(*jolt_shape, transform_com, scale, p_motion, JoltProjectSettings::use_enhanced_internal_edge_removal_for_motion_queries, false, settings, motion_filter, motion_filter, motion_filter, motion_filter, shape_safe_fraction, shape_unsafe_fraction);
  222. r_safe_fraction = MIN(r_safe_fraction, shape_safe_fraction);
  223. r_unsafe_fraction = MIN(r_unsafe_fraction, shape_unsafe_fraction);
  224. }
  225. return collided;
  226. }
  227. bool JoltPhysicsDirectSpaceState3D::_body_motion_collide(const JoltBody3D &p_body, const Transform3D &p_transform, const Vector3 &p_motion, float p_margin, int p_max_collisions, const HashSet<RID> &p_excluded_bodies, const HashSet<ObjectID> &p_excluded_objects, PhysicsServer3D::MotionResult *p_result) const {
  228. if (p_max_collisions == 0) {
  229. return false;
  230. }
  231. const JPH::Shape *jolt_shape = p_body.get_jolt_shape();
  232. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  233. const Transform3D transform_com = p_transform.translated_local(com_scaled);
  234. JPH::CollideShapeSettings settings;
  235. settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  236. settings.mMaxSeparationDistance = p_margin;
  237. const Vector3 &base_offset = transform_com.origin;
  238. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects);
  239. JoltQueryCollectorClosestMulti<JPH::CollideShapeCollector, 32> collector(p_max_collisions);
  240. _collide_shape_kinematics(jolt_shape, JPH::Vec3::sOne(), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, motion_filter, motion_filter, motion_filter, motion_filter);
  241. if (!collector.had_hit() || p_result == nullptr) {
  242. return collector.had_hit();
  243. }
  244. int count = 0;
  245. for (int i = 0; i < collector.get_hit_count(); ++i) {
  246. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  247. const float penetration_depth = hit.mPenetrationDepth + p_margin;
  248. if (penetration_depth <= 0.0f) {
  249. continue;
  250. }
  251. const Vector3 normal = to_godot(-hit.mPenetrationAxis.Normalized());
  252. if (p_motion.length_squared() > 0) {
  253. const Vector3 direction = p_motion.normalized();
  254. if (direction.dot(normal) >= -CMP_EPSILON) {
  255. continue;
  256. }
  257. }
  258. JPH::ContactPoints contact_points1;
  259. JPH::ContactPoints contact_points2;
  260. if (p_max_collisions > 1) {
  261. _generate_manifold(hit, contact_points1, contact_points2 JPH_IF_DEBUG_RENDERER(, to_jolt_r(base_offset)));
  262. } else {
  263. contact_points2.push_back(hit.mContactPointOn2);
  264. }
  265. const JoltShapedObject3D *collider = space->try_get_shaped(hit.mBodyID2);
  266. ERR_FAIL_NULL_V(collider, false);
  267. const int local_shape = p_body.find_shape_index(hit.mSubShapeID1);
  268. ERR_FAIL_COND_V(local_shape == -1, false);
  269. const int collider_shape = collider->find_shape_index(hit.mSubShapeID2);
  270. ERR_FAIL_COND_V(collider_shape == -1, false);
  271. for (JPH::Vec3 contact_point : contact_points2) {
  272. const Vector3 position = base_offset + to_godot(contact_point);
  273. PhysicsServer3D::MotionCollision &collision = p_result->collisions[count++];
  274. collision.position = position;
  275. collision.normal = normal;
  276. collision.collider_velocity = collider->get_velocity_at_position(position);
  277. collision.collider_angular_velocity = collider->get_angular_velocity();
  278. collision.depth = penetration_depth;
  279. collision.local_shape = local_shape;
  280. collision.collider_id = collider->get_instance_id();
  281. collision.collider = collider->get_rid();
  282. collision.collider_shape = collider_shape;
  283. if (count == p_max_collisions) {
  284. break;
  285. }
  286. }
  287. if (count == p_max_collisions) {
  288. break;
  289. }
  290. }
  291. p_result->collision_count = count;
  292. return count > 0;
  293. }
  294. int JoltPhysicsDirectSpaceState3D::_try_get_face_index(const JPH::Body &p_body, const JPH::SubShapeID &p_sub_shape_id) {
  295. if (!JoltProjectSettings::enable_ray_cast_face_index) {
  296. return -1;
  297. }
  298. const JPH::Shape *root_shape = p_body.GetShape();
  299. JPH::SubShapeID sub_shape_id_remainder;
  300. const JPH::Shape *leaf_shape = root_shape->GetLeafShape(p_sub_shape_id, sub_shape_id_remainder);
  301. if (leaf_shape->GetType() != JPH::EShapeType::Mesh) {
  302. return -1;
  303. }
  304. const JPH::MeshShape *mesh_shape = static_cast<const JPH::MeshShape *>(leaf_shape);
  305. return (int)mesh_shape->GetTriangleUserData(sub_shape_id_remainder);
  306. }
  307. void JoltPhysicsDirectSpaceState3D::_generate_manifold(const JPH::CollideShapeResult &p_hit, JPH::ContactPoints &r_contact_points1, JPH::ContactPoints &r_contact_points2 JPH_IF_DEBUG_RENDERER(, JPH::RVec3Arg p_center_of_mass)) const {
  308. const JPH::PhysicsSystem &physics_system = space->get_physics_system();
  309. const JPH::PhysicsSettings &physics_settings = physics_system.GetPhysicsSettings();
  310. const JPH::Vec3 penetration_axis = p_hit.mPenetrationAxis.Normalized();
  311. JPH::ManifoldBetweenTwoFaces(p_hit.mContactPointOn1, p_hit.mContactPointOn2, penetration_axis, physics_settings.mManifoldTolerance, p_hit.mShape1Face, p_hit.mShape2Face, r_contact_points1, r_contact_points2 JPH_IF_DEBUG_RENDERER(, p_center_of_mass));
  312. if (r_contact_points1.size() > 4) {
  313. JPH::PruneContactPoints(penetration_axis, r_contact_points1, r_contact_points2 JPH_IF_DEBUG_RENDERER(, p_center_of_mass));
  314. }
  315. }
  316. void JoltPhysicsDirectSpaceState3D::_collide_shape_queries(
  317. const JPH::Shape *p_shape,
  318. JPH::Vec3Arg p_scale,
  319. JPH::RMat44Arg p_transform_com,
  320. const JPH::CollideShapeSettings &p_settings,
  321. JPH::RVec3Arg p_base_offset,
  322. JPH::CollideShapeCollector &p_collector,
  323. const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter,
  324. const JPH::ObjectLayerFilter &p_object_layer_filter,
  325. const JPH::BodyFilter &p_body_filter,
  326. const JPH::ShapeFilter &p_shape_filter) const {
  327. if (JoltProjectSettings::use_enhanced_internal_edge_removal_for_queries) {
  328. space->get_narrow_phase_query().CollideShapeWithInternalEdgeRemoval(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  329. } else {
  330. space->get_narrow_phase_query().CollideShape(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  331. }
  332. }
  333. void JoltPhysicsDirectSpaceState3D::_collide_shape_kinematics(
  334. const JPH::Shape *p_shape,
  335. JPH::Vec3Arg p_scale,
  336. JPH::RMat44Arg p_transform_com,
  337. const JPH::CollideShapeSettings &p_settings,
  338. JPH::RVec3Arg p_base_offset,
  339. JPH::CollideShapeCollector &p_collector,
  340. const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter,
  341. const JPH::ObjectLayerFilter &p_object_layer_filter,
  342. const JPH::BodyFilter &p_body_filter,
  343. const JPH::ShapeFilter &p_shape_filter) const {
  344. if (JoltProjectSettings::use_enhanced_internal_edge_removal_for_motion_queries) {
  345. space->get_narrow_phase_query().CollideShapeWithInternalEdgeRemoval(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  346. } else {
  347. space->get_narrow_phase_query().CollideShape(p_shape, p_scale, p_transform_com, p_settings, p_base_offset, p_collector, p_broad_phase_layer_filter, p_object_layer_filter, p_body_filter, p_shape_filter);
  348. }
  349. }
  350. JoltPhysicsDirectSpaceState3D::JoltPhysicsDirectSpaceState3D(JoltSpace3D *p_space) :
  351. space(p_space) {
  352. }
  353. bool JoltPhysicsDirectSpaceState3D::intersect_ray(const RayParameters &p_parameters, RayResult &r_result) {
  354. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_ray must not be called while the physics space is being stepped.");
  355. space->flush_pending_objects();
  356. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude, p_parameters.pick_ray);
  357. const JPH::RVec3 from = to_jolt_r(p_parameters.from);
  358. const JPH::RVec3 to = to_jolt_r(p_parameters.to);
  359. const JPH::Vec3 vector = JPH::Vec3(to - from);
  360. const JPH::RRayCast ray(from, vector);
  361. const JPH::EBackFaceMode back_face_mode = p_parameters.hit_back_faces ? JPH::EBackFaceMode::CollideWithBackFaces : JPH::EBackFaceMode::IgnoreBackFaces;
  362. JPH::RayCastSettings settings;
  363. settings.mTreatConvexAsSolid = p_parameters.hit_from_inside;
  364. settings.mBackFaceModeTriangles = back_face_mode;
  365. JoltQueryCollectorClosest<JPH::CastRayCollector> collector;
  366. space->get_narrow_phase_query().CastRay(ray, settings, collector, query_filter, query_filter, query_filter);
  367. if (!collector.had_hit()) {
  368. return false;
  369. }
  370. const JPH::RayCastResult &hit = collector.get_hit();
  371. const JPH::BodyID &body_id = hit.mBodyID;
  372. const JPH::SubShapeID &sub_shape_id = hit.mSubShapeID2;
  373. const JoltObject3D *object = space->try_get_object(body_id);
  374. ERR_FAIL_NULL_V(object, false);
  375. const JPH::RVec3 position = ray.GetPointOnRay(hit.mFraction);
  376. JPH::Vec3 normal = JPH::Vec3::sZero();
  377. if (!p_parameters.hit_from_inside || hit.mFraction > 0.0f) {
  378. normal = object->get_jolt_body()->GetWorldSpaceSurfaceNormal(sub_shape_id, position);
  379. // If we got a back-face normal we need to flip it.
  380. if (normal.Dot(vector) > 0) {
  381. normal = -normal;
  382. }
  383. }
  384. r_result.position = to_godot(position);
  385. r_result.normal = to_godot(normal);
  386. r_result.rid = object->get_rid();
  387. r_result.collider_id = object->get_instance_id();
  388. r_result.collider = object->get_instance();
  389. r_result.shape = 0;
  390. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  391. const int shape_index = shaped_object->find_shape_index(sub_shape_id);
  392. ERR_FAIL_COND_V(shape_index == -1, false);
  393. r_result.shape = shape_index;
  394. r_result.face_index = _try_get_face_index(*object->get_jolt_body(), sub_shape_id);
  395. }
  396. return true;
  397. }
  398. int JoltPhysicsDirectSpaceState3D::intersect_point(const PointParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  399. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_point must not be called while the physics space is being stepped.");
  400. if (p_result_max == 0) {
  401. return 0;
  402. }
  403. space->flush_pending_objects();
  404. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  405. JoltQueryCollectorAnyMulti<JPH::CollidePointCollector, 32> collector(p_result_max);
  406. space->get_narrow_phase_query().CollidePoint(to_jolt_r(p_parameters.position), collector, query_filter, query_filter, query_filter);
  407. const int hit_count = collector.get_hit_count();
  408. for (int i = 0; i < hit_count; ++i) {
  409. const JPH::CollidePointResult &hit = collector.get_hit(i);
  410. const JoltObject3D *object = space->try_get_object(hit.mBodyID);
  411. ERR_FAIL_NULL_V(object, 0);
  412. ShapeResult &result = *r_results++;
  413. result.shape = 0;
  414. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  415. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  416. ERR_FAIL_COND_V(shape_index == -1, 0);
  417. result.shape = shape_index;
  418. }
  419. result.rid = object->get_rid();
  420. result.collider_id = object->get_instance_id();
  421. result.collider = object->get_instance();
  422. }
  423. return hit_count;
  424. }
  425. int JoltPhysicsDirectSpaceState3D::intersect_shape(const ShapeParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  426. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_shape must not be called while the physics space is being stepped.");
  427. if (p_result_max == 0) {
  428. return 0;
  429. }
  430. space->flush_pending_objects();
  431. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  432. ERR_FAIL_NULL_V(shape, 0);
  433. const JPH::ShapeRefC jolt_shape = shape->try_build();
  434. ERR_FAIL_NULL_V(jolt_shape, 0);
  435. Transform3D transform = p_parameters.transform;
  436. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "intersect_shape was passed an invalid transform.");
  437. Vector3 scale;
  438. JoltMath::decompose(transform, scale);
  439. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "intersect_shape was passed an invalid transform.");
  440. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  441. const Transform3D transform_com = transform.translated_local(com_scaled);
  442. JPH::CollideShapeSettings settings;
  443. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  444. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  445. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector(p_result_max);
  446. _collide_shape_queries(jolt_shape, to_jolt(scale), to_jolt_r(transform_com), settings, to_jolt_r(transform_com.origin), collector, query_filter, query_filter, query_filter);
  447. const int hit_count = collector.get_hit_count();
  448. for (int i = 0; i < hit_count; ++i) {
  449. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  450. const JoltObject3D *object = space->try_get_object(hit.mBodyID2);
  451. ERR_FAIL_NULL_V(object, 0);
  452. ShapeResult &result = *r_results++;
  453. result.shape = 0;
  454. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  455. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  456. ERR_FAIL_COND_V(shape_index == -1, 0);
  457. result.shape = shape_index;
  458. }
  459. result.rid = object->get_rid();
  460. result.collider_id = object->get_instance_id();
  461. result.collider = object->get_instance();
  462. }
  463. return hit_count;
  464. }
  465. bool JoltPhysicsDirectSpaceState3D::cast_motion(const ShapeParameters &p_parameters, real_t &r_closest_safe, real_t &r_closest_unsafe, ShapeRestInfo *r_info) {
  466. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "cast_motion must not be called while the physics space is being stepped.");
  467. ERR_FAIL_COND_V_MSG(r_info != nullptr, false, "Providing rest info as part of cast_motion is not supported when using Jolt Physics.");
  468. space->flush_pending_objects();
  469. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  470. ERR_FAIL_NULL_V(shape, false);
  471. const JPH::ShapeRefC jolt_shape = shape->try_build();
  472. ERR_FAIL_NULL_V(jolt_shape, false);
  473. Transform3D transform = p_parameters.transform;
  474. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "cast_motion (maybe from ShapeCast3D?) was passed an invalid transform.");
  475. Vector3 scale;
  476. JoltMath::decompose(transform, scale);
  477. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "cast_motion (maybe from ShapeCast3D?) was passed an invalid transform.");
  478. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  479. Transform3D transform_com = transform.translated_local(com_scaled);
  480. JPH::CollideShapeSettings settings;
  481. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  482. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  483. _cast_motion_impl(*jolt_shape, transform_com, scale, p_parameters.motion, JoltProjectSettings::use_enhanced_internal_edge_removal_for_queries, true, settings, query_filter, query_filter, query_filter, JPH::ShapeFilter(), r_closest_safe, r_closest_unsafe);
  484. return true;
  485. }
  486. bool JoltPhysicsDirectSpaceState3D::collide_shape(const ShapeParameters &p_parameters, Vector3 *r_results, int p_result_max, int &r_result_count) {
  487. r_result_count = 0;
  488. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "collide_shape must not be called while the physics space is being stepped.");
  489. if (p_result_max == 0) {
  490. return false;
  491. }
  492. space->flush_pending_objects();
  493. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  494. ERR_FAIL_NULL_V(shape, false);
  495. const JPH::ShapeRefC jolt_shape = shape->try_build();
  496. ERR_FAIL_NULL_V(jolt_shape, false);
  497. Transform3D transform = p_parameters.transform;
  498. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "collide_shape was passed an invalid transform.");
  499. Vector3 scale;
  500. JoltMath::decompose(transform, scale);
  501. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "collide_shape was passed an invalid transform.");
  502. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  503. const Transform3D transform_com = transform.translated_local(com_scaled);
  504. JPH::CollideShapeSettings settings;
  505. settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  506. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  507. const Vector3 &base_offset = transform_com.origin;
  508. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  509. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector(p_result_max);
  510. _collide_shape_queries(jolt_shape, to_jolt(scale), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, query_filter, query_filter, query_filter);
  511. if (!collector.had_hit()) {
  512. return false;
  513. }
  514. const int max_points = p_result_max * 2;
  515. int point_count = 0;
  516. for (int i = 0; i < collector.get_hit_count(); ++i) {
  517. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  518. const Vector3 penetration_axis = to_godot(hit.mPenetrationAxis.Normalized());
  519. const Vector3 margin_offset = penetration_axis * (float)p_parameters.margin;
  520. JPH::ContactPoints contact_points1;
  521. JPH::ContactPoints contact_points2;
  522. _generate_manifold(hit, contact_points1, contact_points2 JPH_IF_DEBUG_RENDERER(, to_jolt_r(base_offset)));
  523. for (JPH::uint j = 0; j < contact_points1.size(); ++j) {
  524. r_results[point_count++] = base_offset + to_godot(contact_points1[j]) + margin_offset;
  525. r_results[point_count++] = base_offset + to_godot(contact_points2[j]);
  526. if (point_count >= max_points) {
  527. break;
  528. }
  529. }
  530. if (point_count >= max_points) {
  531. break;
  532. }
  533. }
  534. r_result_count = point_count / 2;
  535. return true;
  536. }
  537. bool JoltPhysicsDirectSpaceState3D::rest_info(const ShapeParameters &p_parameters, ShapeRestInfo *r_info) {
  538. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "get_rest_info must not be called while the physics space is being stepped.");
  539. space->flush_pending_objects();
  540. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  541. ERR_FAIL_NULL_V(shape, false);
  542. const JPH::ShapeRefC jolt_shape = shape->try_build();
  543. ERR_FAIL_NULL_V(jolt_shape, false);
  544. Transform3D transform = p_parameters.transform;
  545. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "get_rest_info (maybe from ShapeCast3D?) was passed an invalid transform.");
  546. Vector3 scale;
  547. JoltMath::decompose(transform, scale);
  548. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "get_rest_info (maybe from ShapeCast3D?) was passed an invalid transform.");
  549. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  550. const Transform3D transform_com = transform.translated_local(com_scaled);
  551. JPH::CollideShapeSettings settings;
  552. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  553. const Vector3 &base_offset = transform_com.origin;
  554. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  555. JoltQueryCollectorClosest<JPH::CollideShapeCollector> collector;
  556. _collide_shape_queries(jolt_shape, to_jolt(scale), to_jolt_r(transform_com), settings, to_jolt_r(base_offset), collector, query_filter, query_filter, query_filter);
  557. if (!collector.had_hit()) {
  558. return false;
  559. }
  560. const JPH::CollideShapeResult &hit = collector.get_hit();
  561. const JoltObject3D *object = space->try_get_object(hit.mBodyID2);
  562. ERR_FAIL_NULL_V(object, false);
  563. r_info->shape = 0;
  564. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  565. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  566. ERR_FAIL_COND_V(shape_index == -1, false);
  567. r_info->shape = shape_index;
  568. }
  569. const Vector3 hit_point = base_offset + to_godot(hit.mContactPointOn2);
  570. r_info->point = hit_point;
  571. r_info->normal = to_godot(-hit.mPenetrationAxis.Normalized());
  572. r_info->rid = object->get_rid();
  573. r_info->collider_id = object->get_instance_id();
  574. r_info->linear_velocity = object->get_velocity_at_position(hit_point);
  575. return true;
  576. }
  577. Vector3 JoltPhysicsDirectSpaceState3D::get_closest_point_to_object_volume(RID p_object, Vector3 p_point) const {
  578. ERR_FAIL_COND_V_MSG(space->is_stepping(), Vector3(), "get_closest_point_to_object_volume must not be called while the physics space is being stepped.");
  579. space->flush_pending_objects();
  580. JoltPhysicsServer3D *physics_server = JoltPhysicsServer3D::get_singleton();
  581. JoltObject3D *object = physics_server->get_area(p_object);
  582. if (object == nullptr) {
  583. object = physics_server->get_body(p_object);
  584. }
  585. ERR_FAIL_NULL_V(object, Vector3());
  586. ERR_FAIL_COND_V(object->get_space() != space, Vector3());
  587. JoltQueryCollectorAll<JPH::TransformedShapeCollector, 32> collector;
  588. const JPH::TransformedShape root_shape = object->get_jolt_body()->GetTransformedShape();
  589. root_shape.CollectTransformedShapes(object->get_jolt_body()->GetWorldSpaceBounds(), collector);
  590. const JPH::RVec3 point = to_jolt_r(p_point);
  591. float closest_distance_sq = FLT_MAX;
  592. JPH::RVec3 closest_point = JPH::RVec3::sZero();
  593. bool found_point = false;
  594. for (int i = 0; i < collector.get_hit_count(); ++i) {
  595. const JPH::TransformedShape &shape_transformed = collector.get_hit(i);
  596. const JPH::Shape &shape = *shape_transformed.mShape;
  597. if (shape.GetType() != JPH::EShapeType::Convex) {
  598. continue;
  599. }
  600. const JPH::ConvexShape &shape_convex = static_cast<const JPH::ConvexShape &>(shape);
  601. JPH::GJKClosestPoint gjk;
  602. JPH::ConvexShape::SupportBuffer shape_support_buffer;
  603. const JPH::ConvexShape::Support *shape_support = shape_convex.GetSupportFunction(JPH::ConvexShape::ESupportMode::IncludeConvexRadius, shape_support_buffer, shape_transformed.GetShapeScale());
  604. const JPH::RMat44 shape_rotation = JPH::RMat44::sRotation(shape_transformed.mShapeRotation);
  605. const JPH::Vec3 shape_com = shape_rotation.Multiply3x3(shape.GetCenterOfMass());
  606. const JPH::RVec3 shape_pos = shape_transformed.mShapePositionCOM - JPH::RVec3(shape_com);
  607. const JPH::RMat44 shape_xform = shape_rotation.PostTranslated(shape_pos);
  608. const JPH::RMat44 shape_xform_inv = shape_xform.InversedRotationTranslation();
  609. JPH::PointConvexSupport point_support;
  610. point_support.mPoint = JPH::Vec3(shape_xform_inv * point);
  611. JPH::Vec3 separating_axis = JPH::Vec3::sAxisX();
  612. JPH::Vec3 point_on_a = JPH::Vec3::sZero();
  613. JPH::Vec3 point_on_b = JPH::Vec3::sZero();
  614. const float distance_sq = gjk.GetClosestPoints(*shape_support, point_support, JPH::cDefaultCollisionTolerance, FLT_MAX, separating_axis, point_on_a, point_on_b);
  615. if (distance_sq == 0.0f) {
  616. closest_point = point;
  617. found_point = true;
  618. break;
  619. }
  620. if (distance_sq < closest_distance_sq) {
  621. closest_distance_sq = distance_sq;
  622. closest_point = shape_xform * point_on_a;
  623. found_point = true;
  624. }
  625. }
  626. if (found_point) {
  627. return to_godot(closest_point);
  628. } else {
  629. return to_godot(object->get_jolt_body()->GetPosition());
  630. }
  631. }
  632. bool JoltPhysicsDirectSpaceState3D::body_test_motion(const JoltBody3D &p_body, const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult *r_result) const {
  633. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "body_test_motion (maybe from move_and_slide?) must not be called while the physics space is being stepped.");
  634. space->flush_pending_objects();
  635. const float margin = MAX((float)p_parameters.margin, 0.0001f);
  636. const int max_collisions = MIN(p_parameters.max_collisions, 32);
  637. Transform3D transform = p_parameters.from;
  638. JOLT_ENSURE_SCALE_NOT_ZERO(transform, vformat("body_test_motion (maybe from move_and_slide?) was passed an invalid transform along with body '%s'.", p_body.to_string()));
  639. Vector3 scale;
  640. JoltMath::decompose(transform, scale);
  641. Vector3 recovery;
  642. const bool recovered = _body_motion_recover(p_body, transform, margin, p_parameters.exclude_bodies, p_parameters.exclude_objects, recovery);
  643. transform.origin += recovery;
  644. real_t safe_fraction = 1.0;
  645. real_t unsafe_fraction = 1.0;
  646. const bool hit = _body_motion_cast(p_body, transform, scale, p_parameters.motion, p_parameters.collide_separation_ray, p_parameters.exclude_bodies, p_parameters.exclude_objects, safe_fraction, unsafe_fraction);
  647. bool collided = false;
  648. if (hit || (recovered && p_parameters.recovery_as_collision)) {
  649. collided = _body_motion_collide(p_body, transform.translated(p_parameters.motion * unsafe_fraction), p_parameters.motion, margin, max_collisions, p_parameters.exclude_bodies, p_parameters.exclude_objects, r_result);
  650. }
  651. if (r_result == nullptr) {
  652. return collided;
  653. }
  654. if (collided) {
  655. const PhysicsServer3D::MotionCollision &deepest = r_result->collisions[0];
  656. r_result->travel = recovery + p_parameters.motion * safe_fraction;
  657. r_result->remainder = p_parameters.motion - p_parameters.motion * safe_fraction;
  658. r_result->collision_depth = deepest.depth;
  659. r_result->collision_safe_fraction = safe_fraction;
  660. r_result->collision_unsafe_fraction = unsafe_fraction;
  661. } else {
  662. r_result->travel = recovery + p_parameters.motion;
  663. r_result->remainder = Vector3();
  664. r_result->collision_depth = 0.0f;
  665. r_result->collision_safe_fraction = 1.0f;
  666. r_result->collision_unsafe_fraction = 1.0f;
  667. r_result->collision_count = 0;
  668. }
  669. return collided;
  670. }