jolt_physics_direct_space_state_3d.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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(logf(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 JoltReadableBody3D other_jolt_body = space->read_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 JoltReadableBody3D other_jolt_body = space->read_body(hit.mBodyID2);
  161. const JoltBody3D *other_body = other_jolt_body.as_body();
  162. ERR_CONTINUE(other_body == nullptr);
  163. combined_priority += other_body->get_collision_priority();
  164. }
  165. const float average_priority = MAX(combined_priority / (float)hit_count, (float)CMP_EPSILON);
  166. recovered = true;
  167. Vector3 recovery;
  168. for (int j = 0; j < hit_count; ++j) {
  169. const JPH::CollideShapeResult &hit = collector.get_hit(j);
  170. const Vector3 penetration_axis = to_godot(hit.mPenetrationAxis.Normalized());
  171. const Vector3 margin_offset = penetration_axis * p_margin;
  172. const Vector3 point_on_1 = base_offset + to_godot(hit.mContactPointOn1) + margin_offset;
  173. const Vector3 point_on_2 = base_offset + to_godot(hit.mContactPointOn2);
  174. const real_t distance_to_1 = penetration_axis.dot(point_on_1 + recovery);
  175. const real_t distance_to_2 = penetration_axis.dot(point_on_2);
  176. const float penetration_depth = float(distance_to_1 - distance_to_2);
  177. if (penetration_depth <= 0.0f) {
  178. continue;
  179. }
  180. const JoltReadableBody3D other_jolt_body = space->read_body(hit.mBodyID2);
  181. const JoltBody3D *other_body = other_jolt_body.as_body();
  182. ERR_CONTINUE(other_body == nullptr);
  183. const float recovery_distance = penetration_depth * JoltProjectSettings::motion_query_recovery_amount;
  184. const float other_priority = other_body->get_collision_priority();
  185. const float other_priority_normalized = other_priority / average_priority;
  186. const float scaled_recovery_distance = recovery_distance * other_priority_normalized;
  187. recovery -= penetration_axis * scaled_recovery_distance;
  188. }
  189. if (recovery == Vector3()) {
  190. break;
  191. }
  192. r_recovery += recovery;
  193. transform_com.origin += recovery;
  194. }
  195. return recovered;
  196. }
  197. 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 {
  198. const Transform3D body_transform = p_transform.scaled_local(p_scale);
  199. const JPH::CollideShapeSettings settings;
  200. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects, p_collide_separation_ray);
  201. bool collided = false;
  202. for (int i = 0; i < p_body.get_shape_count(); ++i) {
  203. if (p_body.is_shape_disabled(i)) {
  204. continue;
  205. }
  206. JoltShape3D *shape = p_body.get_shape(i);
  207. if (!shape->is_convex()) {
  208. continue;
  209. }
  210. const JPH::ShapeRefC jolt_shape = shape->try_build();
  211. if (unlikely(jolt_shape == nullptr)) {
  212. return false;
  213. }
  214. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  215. const Transform3D transform_local = p_body.get_shape_transform_scaled(i);
  216. const Transform3D transform_com_local = transform_local.translated_local(com_scaled);
  217. Transform3D transform_com = body_transform * transform_com_local;
  218. Vector3 scale;
  219. JoltMath::decompose(transform_com, scale);
  220. 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.");
  221. real_t shape_safe_fraction = 1.0;
  222. real_t shape_unsafe_fraction = 1.0;
  223. 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);
  224. r_safe_fraction = MIN(r_safe_fraction, shape_safe_fraction);
  225. r_unsafe_fraction = MIN(r_unsafe_fraction, shape_unsafe_fraction);
  226. }
  227. return collided;
  228. }
  229. 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 {
  230. if (p_max_collisions == 0) {
  231. return false;
  232. }
  233. const JPH::Shape *jolt_shape = p_body.get_jolt_shape();
  234. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  235. const Transform3D transform_com = p_transform.translated_local(com_scaled);
  236. JPH::CollideShapeSettings settings;
  237. settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  238. settings.mMaxSeparationDistance = p_margin;
  239. const Vector3 &base_offset = transform_com.origin;
  240. const JoltMotionFilter3D motion_filter(p_body, p_excluded_bodies, p_excluded_objects);
  241. JoltQueryCollectorClosestMulti<JPH::CollideShapeCollector, 32> collector(p_max_collisions);
  242. _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);
  243. if (!collector.had_hit() || p_result == nullptr) {
  244. return collector.had_hit();
  245. }
  246. int count = 0;
  247. for (int i = 0; i < collector.get_hit_count(); ++i) {
  248. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  249. const float penetration_depth = hit.mPenetrationDepth + p_margin;
  250. if (penetration_depth <= 0.0f) {
  251. continue;
  252. }
  253. const Vector3 normal = to_godot(-hit.mPenetrationAxis.Normalized());
  254. if (p_motion.length_squared() > 0) {
  255. const Vector3 direction = p_motion.normalized();
  256. if (direction.dot(normal) >= -CMP_EPSILON) {
  257. continue;
  258. }
  259. }
  260. JPH::ContactPoints contact_points1;
  261. JPH::ContactPoints contact_points2;
  262. if (p_max_collisions > 1) {
  263. _generate_manifold(hit, contact_points1, contact_points2 JPH_IF_DEBUG_RENDERER(, to_jolt_r(base_offset)));
  264. } else {
  265. contact_points2.push_back(hit.mContactPointOn2);
  266. }
  267. const JoltReadableBody3D collider_jolt_body = space->read_body(hit.mBodyID2);
  268. const JoltShapedObject3D *collider = collider_jolt_body.as_shaped();
  269. ERR_FAIL_NULL_V(collider, false);
  270. const int local_shape = p_body.find_shape_index(hit.mSubShapeID1);
  271. ERR_FAIL_COND_V(local_shape == -1, false);
  272. const int collider_shape = collider->find_shape_index(hit.mSubShapeID2);
  273. ERR_FAIL_COND_V(collider_shape == -1, false);
  274. for (JPH::Vec3 contact_point : contact_points2) {
  275. const Vector3 position = base_offset + to_godot(contact_point);
  276. PhysicsServer3D::MotionCollision &collision = p_result->collisions[count++];
  277. collision.position = position;
  278. collision.normal = normal;
  279. collision.collider_velocity = collider->get_velocity_at_position(position);
  280. collision.collider_angular_velocity = collider->get_angular_velocity();
  281. collision.depth = penetration_depth;
  282. collision.local_shape = local_shape;
  283. collision.collider_id = collider->get_instance_id();
  284. collision.collider = collider->get_rid();
  285. collision.collider_shape = collider_shape;
  286. if (count == p_max_collisions) {
  287. break;
  288. }
  289. }
  290. if (count == p_max_collisions) {
  291. break;
  292. }
  293. }
  294. p_result->collision_count = count;
  295. return count > 0;
  296. }
  297. int JoltPhysicsDirectSpaceState3D::_try_get_face_index(const JPH::Body &p_body, const JPH::SubShapeID &p_sub_shape_id) {
  298. if (!JoltProjectSettings::enable_ray_cast_face_index) {
  299. return -1;
  300. }
  301. const JPH::Shape *root_shape = p_body.GetShape();
  302. JPH::SubShapeID sub_shape_id_remainder;
  303. const JPH::Shape *leaf_shape = root_shape->GetLeafShape(p_sub_shape_id, sub_shape_id_remainder);
  304. if (leaf_shape->GetType() != JPH::EShapeType::Mesh) {
  305. return -1;
  306. }
  307. const JPH::MeshShape *mesh_shape = static_cast<const JPH::MeshShape *>(leaf_shape);
  308. return (int)mesh_shape->GetTriangleUserData(sub_shape_id_remainder);
  309. }
  310. 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 {
  311. const JPH::PhysicsSystem &physics_system = space->get_physics_system();
  312. const JPH::PhysicsSettings &physics_settings = physics_system.GetPhysicsSettings();
  313. const JPH::Vec3 penetration_axis = p_hit.mPenetrationAxis.Normalized();
  314. 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));
  315. if (r_contact_points1.size() > 4) {
  316. JPH::PruneContactPoints(penetration_axis, r_contact_points1, r_contact_points2 JPH_IF_DEBUG_RENDERER(, p_center_of_mass));
  317. }
  318. }
  319. void JoltPhysicsDirectSpaceState3D::_collide_shape_queries(
  320. const JPH::Shape *p_shape,
  321. JPH::Vec3Arg p_scale,
  322. JPH::RMat44Arg p_transform_com,
  323. const JPH::CollideShapeSettings &p_settings,
  324. JPH::RVec3Arg p_base_offset,
  325. JPH::CollideShapeCollector &p_collector,
  326. const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter,
  327. const JPH::ObjectLayerFilter &p_object_layer_filter,
  328. const JPH::BodyFilter &p_body_filter,
  329. const JPH::ShapeFilter &p_shape_filter) const {
  330. if (JoltProjectSettings::use_enhanced_internal_edge_removal_for_queries) {
  331. 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);
  332. } else {
  333. 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);
  334. }
  335. }
  336. void JoltPhysicsDirectSpaceState3D::_collide_shape_kinematics(
  337. const JPH::Shape *p_shape,
  338. JPH::Vec3Arg p_scale,
  339. JPH::RMat44Arg p_transform_com,
  340. const JPH::CollideShapeSettings &p_settings,
  341. JPH::RVec3Arg p_base_offset,
  342. JPH::CollideShapeCollector &p_collector,
  343. const JPH::BroadPhaseLayerFilter &p_broad_phase_layer_filter,
  344. const JPH::ObjectLayerFilter &p_object_layer_filter,
  345. const JPH::BodyFilter &p_body_filter,
  346. const JPH::ShapeFilter &p_shape_filter) const {
  347. if (JoltProjectSettings::use_enhanced_internal_edge_removal_for_motion_queries) {
  348. 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);
  349. } else {
  350. 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);
  351. }
  352. }
  353. JoltPhysicsDirectSpaceState3D::JoltPhysicsDirectSpaceState3D(JoltSpace3D *p_space) :
  354. space(p_space) {
  355. }
  356. bool JoltPhysicsDirectSpaceState3D::intersect_ray(const RayParameters &p_parameters, RayResult &r_result) {
  357. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_ray must not be called while the physics space is being stepped.");
  358. space->try_optimize();
  359. 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);
  360. const JPH::RVec3 from = to_jolt_r(p_parameters.from);
  361. const JPH::RVec3 to = to_jolt_r(p_parameters.to);
  362. const JPH::Vec3 vector = JPH::Vec3(to - from);
  363. const JPH::RRayCast ray(from, vector);
  364. const JPH::EBackFaceMode back_face_mode = p_parameters.hit_back_faces ? JPH::EBackFaceMode::CollideWithBackFaces : JPH::EBackFaceMode::IgnoreBackFaces;
  365. JPH::RayCastSettings settings;
  366. settings.mTreatConvexAsSolid = p_parameters.hit_from_inside;
  367. settings.mBackFaceModeTriangles = back_face_mode;
  368. JoltQueryCollectorClosest<JPH::CastRayCollector> collector;
  369. space->get_narrow_phase_query().CastRay(ray, settings, collector, query_filter, query_filter, query_filter);
  370. if (!collector.had_hit()) {
  371. return false;
  372. }
  373. const JPH::RayCastResult &hit = collector.get_hit();
  374. const JPH::BodyID &body_id = hit.mBodyID;
  375. const JPH::SubShapeID &sub_shape_id = hit.mSubShapeID2;
  376. const JoltReadableBody3D body = space->read_body(body_id);
  377. const JoltObject3D *object = body.as_object();
  378. ERR_FAIL_NULL_V(object, false);
  379. const JPH::RVec3 position = ray.GetPointOnRay(hit.mFraction);
  380. JPH::Vec3 normal = JPH::Vec3::sZero();
  381. if (!p_parameters.hit_from_inside || hit.mFraction > 0.0f) {
  382. normal = body->GetWorldSpaceSurfaceNormal(sub_shape_id, position);
  383. // If we got a back-face normal we need to flip it.
  384. if (normal.Dot(vector) > 0) {
  385. normal = -normal;
  386. }
  387. }
  388. r_result.position = to_godot(position);
  389. r_result.normal = to_godot(normal);
  390. r_result.rid = object->get_rid();
  391. r_result.collider_id = object->get_instance_id();
  392. r_result.collider = object->get_instance();
  393. r_result.shape = 0;
  394. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  395. const int shape_index = shaped_object->find_shape_index(sub_shape_id);
  396. ERR_FAIL_COND_V(shape_index == -1, false);
  397. r_result.shape = shape_index;
  398. r_result.face_index = _try_get_face_index(*body, sub_shape_id);
  399. }
  400. return true;
  401. }
  402. int JoltPhysicsDirectSpaceState3D::intersect_point(const PointParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  403. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_point must not be called while the physics space is being stepped.");
  404. if (p_result_max == 0) {
  405. return 0;
  406. }
  407. space->try_optimize();
  408. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  409. JoltQueryCollectorAnyMulti<JPH::CollidePointCollector, 32> collector(p_result_max);
  410. space->get_narrow_phase_query().CollidePoint(to_jolt_r(p_parameters.position), collector, query_filter, query_filter, query_filter);
  411. const int hit_count = collector.get_hit_count();
  412. for (int i = 0; i < hit_count; ++i) {
  413. const JPH::CollidePointResult &hit = collector.get_hit(i);
  414. const JoltReadableBody3D body = space->read_body(hit.mBodyID);
  415. const JoltObject3D *object = body.as_object();
  416. ERR_FAIL_NULL_V(object, 0);
  417. ShapeResult &result = *r_results++;
  418. result.shape = 0;
  419. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  420. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  421. ERR_FAIL_COND_V(shape_index == -1, 0);
  422. result.shape = shape_index;
  423. }
  424. result.rid = object->get_rid();
  425. result.collider_id = object->get_instance_id();
  426. result.collider = object->get_instance();
  427. }
  428. return hit_count;
  429. }
  430. int JoltPhysicsDirectSpaceState3D::intersect_shape(const ShapeParameters &p_parameters, ShapeResult *r_results, int p_result_max) {
  431. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "intersect_shape must not be called while the physics space is being stepped.");
  432. if (p_result_max == 0) {
  433. return 0;
  434. }
  435. space->try_optimize();
  436. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  437. ERR_FAIL_NULL_V(shape, 0);
  438. const JPH::ShapeRefC jolt_shape = shape->try_build();
  439. ERR_FAIL_NULL_V(jolt_shape, 0);
  440. Transform3D transform = p_parameters.transform;
  441. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "intersect_shape was passed an invalid transform.");
  442. Vector3 scale;
  443. JoltMath::decompose(transform, scale);
  444. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "intersect_shape was passed an invalid transform.");
  445. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  446. const Transform3D transform_com = transform.translated_local(com_scaled);
  447. JPH::CollideShapeSettings settings;
  448. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  449. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  450. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector(p_result_max);
  451. _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);
  452. const int hit_count = collector.get_hit_count();
  453. for (int i = 0; i < hit_count; ++i) {
  454. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  455. const JoltReadableBody3D body = space->read_body(hit.mBodyID2);
  456. const JoltObject3D *object = body.as_object();
  457. ERR_FAIL_NULL_V(object, 0);
  458. ShapeResult &result = *r_results++;
  459. result.shape = 0;
  460. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  461. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  462. ERR_FAIL_COND_V(shape_index == -1, 0);
  463. result.shape = shape_index;
  464. }
  465. result.rid = object->get_rid();
  466. result.collider_id = object->get_instance_id();
  467. result.collider = object->get_instance();
  468. }
  469. return hit_count;
  470. }
  471. bool JoltPhysicsDirectSpaceState3D::cast_motion(const ShapeParameters &p_parameters, real_t &r_closest_safe, real_t &r_closest_unsafe, ShapeRestInfo *r_info) {
  472. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "cast_motion must not be called while the physics space is being stepped.");
  473. ERR_FAIL_COND_V_MSG(r_info != nullptr, false, "Providing rest info as part of cast_motion is not supported when using Jolt Physics.");
  474. space->try_optimize();
  475. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  476. ERR_FAIL_NULL_V(shape, false);
  477. const JPH::ShapeRefC jolt_shape = shape->try_build();
  478. ERR_FAIL_NULL_V(jolt_shape, false);
  479. Transform3D transform = p_parameters.transform;
  480. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "cast_motion (maybe from ShapeCast3D?) was passed an invalid transform.");
  481. Vector3 scale;
  482. JoltMath::decompose(transform, scale);
  483. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "cast_motion (maybe from ShapeCast3D?) was passed an invalid transform.");
  484. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  485. Transform3D transform_com = transform.translated_local(com_scaled);
  486. JPH::CollideShapeSettings settings;
  487. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  488. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  489. _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);
  490. return true;
  491. }
  492. bool JoltPhysicsDirectSpaceState3D::collide_shape(const ShapeParameters &p_parameters, Vector3 *r_results, int p_result_max, int &r_result_count) {
  493. r_result_count = 0;
  494. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "collide_shape must not be called while the physics space is being stepped.");
  495. if (p_result_max == 0) {
  496. return false;
  497. }
  498. space->try_optimize();
  499. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  500. ERR_FAIL_NULL_V(shape, false);
  501. const JPH::ShapeRefC jolt_shape = shape->try_build();
  502. ERR_FAIL_NULL_V(jolt_shape, false);
  503. Transform3D transform = p_parameters.transform;
  504. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "collide_shape was passed an invalid transform.");
  505. Vector3 scale;
  506. JoltMath::decompose(transform, scale);
  507. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "collide_shape was passed an invalid transform.");
  508. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  509. const Transform3D transform_com = transform.translated_local(com_scaled);
  510. JPH::CollideShapeSettings settings;
  511. settings.mCollectFacesMode = JPH::ECollectFacesMode::CollectFaces;
  512. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  513. const Vector3 &base_offset = transform_com.origin;
  514. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  515. JoltQueryCollectorAnyMulti<JPH::CollideShapeCollector, 32> collector(p_result_max);
  516. _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);
  517. if (!collector.had_hit()) {
  518. return false;
  519. }
  520. const int max_points = p_result_max * 2;
  521. int point_count = 0;
  522. for (int i = 0; i < collector.get_hit_count(); ++i) {
  523. const JPH::CollideShapeResult &hit = collector.get_hit(i);
  524. const Vector3 penetration_axis = to_godot(hit.mPenetrationAxis.Normalized());
  525. const Vector3 margin_offset = penetration_axis * (float)p_parameters.margin;
  526. JPH::ContactPoints contact_points1;
  527. JPH::ContactPoints contact_points2;
  528. _generate_manifold(hit, contact_points1, contact_points2 JPH_IF_DEBUG_RENDERER(, to_jolt_r(base_offset)));
  529. for (JPH::uint j = 0; j < contact_points1.size(); ++j) {
  530. r_results[point_count++] = base_offset + to_godot(contact_points1[j]) + margin_offset;
  531. r_results[point_count++] = base_offset + to_godot(contact_points2[j]);
  532. if (point_count >= max_points) {
  533. break;
  534. }
  535. }
  536. if (point_count >= max_points) {
  537. break;
  538. }
  539. }
  540. r_result_count = point_count / 2;
  541. return true;
  542. }
  543. bool JoltPhysicsDirectSpaceState3D::rest_info(const ShapeParameters &p_parameters, ShapeRestInfo *r_info) {
  544. ERR_FAIL_COND_V_MSG(space->is_stepping(), false, "get_rest_info must not be called while the physics space is being stepped.");
  545. space->try_optimize();
  546. JoltShape3D *shape = JoltPhysicsServer3D::get_singleton()->get_shape(p_parameters.shape_rid);
  547. ERR_FAIL_NULL_V(shape, false);
  548. const JPH::ShapeRefC jolt_shape = shape->try_build();
  549. ERR_FAIL_NULL_V(jolt_shape, false);
  550. Transform3D transform = p_parameters.transform;
  551. JOLT_ENSURE_SCALE_NOT_ZERO(transform, "get_rest_info (maybe from ShapeCast3D?) was passed an invalid transform.");
  552. Vector3 scale;
  553. JoltMath::decompose(transform, scale);
  554. JOLT_ENSURE_SCALE_VALID(jolt_shape, scale, "get_rest_info (maybe from ShapeCast3D?) was passed an invalid transform.");
  555. const Vector3 com_scaled = to_godot(jolt_shape->GetCenterOfMass());
  556. const Transform3D transform_com = transform.translated_local(com_scaled);
  557. JPH::CollideShapeSettings settings;
  558. settings.mMaxSeparationDistance = (float)p_parameters.margin;
  559. const Vector3 &base_offset = transform_com.origin;
  560. const JoltQueryFilter3D query_filter(*this, p_parameters.collision_mask, p_parameters.collide_with_bodies, p_parameters.collide_with_areas, p_parameters.exclude);
  561. JoltQueryCollectorClosest<JPH::CollideShapeCollector> collector;
  562. _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);
  563. if (!collector.had_hit()) {
  564. return false;
  565. }
  566. const JPH::CollideShapeResult &hit = collector.get_hit();
  567. const JoltReadableBody3D body = space->read_body(hit.mBodyID2);
  568. const JoltObject3D *object = body.as_object();
  569. ERR_FAIL_NULL_V(object, false);
  570. r_info->shape = 0;
  571. if (const JoltShapedObject3D *shaped_object = object->as_shaped()) {
  572. const int shape_index = shaped_object->find_shape_index(hit.mSubShapeID2);
  573. ERR_FAIL_COND_V(shape_index == -1, false);
  574. r_info->shape = shape_index;
  575. }
  576. const Vector3 hit_point = base_offset + to_godot(hit.mContactPointOn2);
  577. r_info->point = hit_point;
  578. r_info->normal = to_godot(-hit.mPenetrationAxis.Normalized());
  579. r_info->rid = object->get_rid();
  580. r_info->collider_id = object->get_instance_id();
  581. r_info->linear_velocity = object->get_velocity_at_position(hit_point);
  582. return true;
  583. }
  584. Vector3 JoltPhysicsDirectSpaceState3D::get_closest_point_to_object_volume(RID p_object, Vector3 p_point) const {
  585. 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.");
  586. space->try_optimize();
  587. JoltPhysicsServer3D *physics_server = JoltPhysicsServer3D::get_singleton();
  588. JoltObject3D *object = physics_server->get_area(p_object);
  589. if (object == nullptr) {
  590. object = physics_server->get_body(p_object);
  591. }
  592. ERR_FAIL_NULL_V(object, Vector3());
  593. ERR_FAIL_COND_V(object->get_space() != space, Vector3());
  594. const JoltReadableBody3D body = space->read_body(*object);
  595. const JPH::TransformedShape root_shape = body->GetTransformedShape();
  596. JoltQueryCollectorAll<JPH::TransformedShapeCollector, 32> collector;
  597. root_shape.CollectTransformedShapes(body->GetWorldSpaceBounds(), collector);
  598. const JPH::RVec3 point = to_jolt_r(p_point);
  599. float closest_distance_sq = FLT_MAX;
  600. JPH::RVec3 closest_point = JPH::RVec3::sZero();
  601. bool found_point = false;
  602. for (int i = 0; i < collector.get_hit_count(); ++i) {
  603. const JPH::TransformedShape &shape_transformed = collector.get_hit(i);
  604. const JPH::Shape &shape = *shape_transformed.mShape;
  605. if (shape.GetType() != JPH::EShapeType::Convex) {
  606. continue;
  607. }
  608. const JPH::ConvexShape &shape_convex = static_cast<const JPH::ConvexShape &>(shape);
  609. JPH::GJKClosestPoint gjk;
  610. JPH::ConvexShape::SupportBuffer shape_support_buffer;
  611. const JPH::ConvexShape::Support *shape_support = shape_convex.GetSupportFunction(JPH::ConvexShape::ESupportMode::IncludeConvexRadius, shape_support_buffer, shape_transformed.GetShapeScale());
  612. const JPH::Quat &shape_rotation = shape_transformed.mShapeRotation;
  613. const JPH::RVec3 &shape_pos_com = shape_transformed.mShapePositionCOM;
  614. const JPH::RMat44 shape_3x3 = JPH::RMat44::sRotation(shape_rotation);
  615. const JPH::Vec3 shape_com_local = shape.GetCenterOfMass();
  616. const JPH::Vec3 shape_com = shape_3x3.Multiply3x3(shape_com_local);
  617. const JPH::RVec3 shape_pos = shape_pos_com - JPH::RVec3(shape_com);
  618. const JPH::RMat44 shape_4x4 = shape_3x3.PostTranslated(shape_pos);
  619. const JPH::RMat44 shape_4x4_inv = shape_4x4.InversedRotationTranslation();
  620. JPH::PointConvexSupport point_support;
  621. point_support.mPoint = JPH::Vec3(shape_4x4_inv * point);
  622. JPH::Vec3 separating_axis = JPH::Vec3::sAxisX();
  623. JPH::Vec3 point_on_a = JPH::Vec3::sZero();
  624. JPH::Vec3 point_on_b = JPH::Vec3::sZero();
  625. const float distance_sq = gjk.GetClosestPoints(*shape_support, point_support, JPH::cDefaultCollisionTolerance, FLT_MAX, separating_axis, point_on_a, point_on_b);
  626. if (distance_sq == 0.0f) {
  627. closest_point = point;
  628. found_point = true;
  629. break;
  630. }
  631. if (distance_sq < closest_distance_sq) {
  632. closest_distance_sq = distance_sq;
  633. closest_point = shape_4x4 * point_on_a;
  634. found_point = true;
  635. }
  636. }
  637. if (found_point) {
  638. return to_godot(closest_point);
  639. } else {
  640. return to_godot(body->GetPosition());
  641. }
  642. }
  643. bool JoltPhysicsDirectSpaceState3D::body_test_motion(const JoltBody3D &p_body, const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult *r_result) const {
  644. 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.");
  645. const float margin = MAX((float)p_parameters.margin, 0.0001f);
  646. const int max_collisions = MIN(p_parameters.max_collisions, 32);
  647. Transform3D transform = p_parameters.from;
  648. 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()));
  649. Vector3 scale;
  650. JoltMath::decompose(transform, scale);
  651. space->try_optimize();
  652. Vector3 recovery;
  653. const bool recovered = _body_motion_recover(p_body, transform, margin, p_parameters.exclude_bodies, p_parameters.exclude_objects, recovery);
  654. transform.origin += recovery;
  655. real_t safe_fraction = 1.0;
  656. real_t unsafe_fraction = 1.0;
  657. 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);
  658. bool collided = false;
  659. if (hit || (recovered && p_parameters.recovery_as_collision)) {
  660. 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);
  661. }
  662. if (r_result == nullptr) {
  663. return collided;
  664. }
  665. if (collided) {
  666. const PhysicsServer3D::MotionCollision &deepest = r_result->collisions[0];
  667. r_result->travel = recovery + p_parameters.motion * safe_fraction;
  668. r_result->remainder = p_parameters.motion - p_parameters.motion * safe_fraction;
  669. r_result->collision_depth = deepest.depth;
  670. r_result->collision_safe_fraction = safe_fraction;
  671. r_result->collision_unsafe_fraction = unsafe_fraction;
  672. } else {
  673. r_result->travel = recovery + p_parameters.motion;
  674. r_result->remainder = Vector3();
  675. r_result->collision_depth = 0.0f;
  676. r_result->collision_safe_fraction = 1.0f;
  677. r_result->collision_unsafe_fraction = 1.0f;
  678. r_result->collision_count = 0;
  679. }
  680. return collided;
  681. }