jolt_soft_body_3d.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. /**************************************************************************/
  2. /* jolt_soft_body_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_soft_body_3d.h"
  31. #include "../jolt_project_settings.h"
  32. #include "../misc/jolt_type_conversions.h"
  33. #include "../spaces/jolt_broad_phase_layer.h"
  34. #include "../spaces/jolt_space_3d.h"
  35. #include "jolt_area_3d.h"
  36. #include "jolt_body_3d.h"
  37. #include "jolt_group_filter.h"
  38. #include "servers/rendering_server.h"
  39. #include "Jolt/Physics/SoftBody/SoftBodyMotionProperties.h"
  40. namespace {
  41. bool is_face_degenerate(const int p_face[3]) {
  42. return p_face[0] == p_face[1] || p_face[0] == p_face[2] || p_face[1] == p_face[2];
  43. }
  44. template <typename TJoltVertex>
  45. void pin_vertices(const JoltSoftBody3D &p_body, const HashSet<int> &p_pinned_vertices, const LocalVector<int> &p_mesh_to_physics, JPH::Array<TJoltVertex> &r_physics_vertices) {
  46. const int mesh_vertex_count = p_mesh_to_physics.size();
  47. const int physics_vertex_count = (int)r_physics_vertices.size();
  48. for (int mesh_index : p_pinned_vertices) {
  49. ERR_CONTINUE_MSG(mesh_index < 0 || mesh_index >= mesh_vertex_count, vformat("Index %d of pinned vertex in soft body '%s' is out of bounds. There are only %d vertices in the current mesh.", mesh_index, p_body.to_string(), mesh_vertex_count));
  50. const int physics_index = p_mesh_to_physics[mesh_index];
  51. ERR_CONTINUE_MSG(physics_index < 0 || physics_index >= physics_vertex_count, vformat("Index %d of pinned vertex in soft body '%s' is out of bounds. There are only %d vertices in the current mesh. This should not happen. Please report this.", physics_index, p_body.to_string(), physics_vertex_count));
  52. r_physics_vertices[physics_index].mInvMass = 0.0f;
  53. }
  54. }
  55. } // namespace
  56. JPH::BroadPhaseLayer JoltSoftBody3D::_get_broad_phase_layer() const {
  57. return JoltBroadPhaseLayer::BODY_DYNAMIC;
  58. }
  59. JPH::ObjectLayer JoltSoftBody3D::_get_object_layer() const {
  60. ERR_FAIL_NULL_V(space, 0);
  61. return space->map_to_object_layer(_get_broad_phase_layer(), collision_layer, collision_mask);
  62. }
  63. void JoltSoftBody3D::_space_changing() {
  64. JoltObject3D::_space_changing();
  65. if (in_space()) {
  66. jolt_settings = new JPH::SoftBodyCreationSettings(jolt_body->GetSoftBodyCreationSettings());
  67. jolt_settings->mSettings = nullptr;
  68. }
  69. _deref_shared_data();
  70. }
  71. void JoltSoftBody3D::_space_changed() {
  72. JoltObject3D::_space_changed();
  73. _update_mass();
  74. _update_pressure();
  75. _update_damping();
  76. _update_simulation_precision();
  77. _update_group_filter();
  78. }
  79. void JoltSoftBody3D::_add_to_space() {
  80. if (unlikely(space == nullptr || !mesh.is_valid())) {
  81. return;
  82. }
  83. const bool has_valid_shared = _ref_shared_data();
  84. ERR_FAIL_COND(!has_valid_shared);
  85. JPH::CollisionGroup::GroupID group_id = 0;
  86. JPH::CollisionGroup::SubGroupID sub_group_id = 0;
  87. JoltGroupFilter::encode_object(this, group_id, sub_group_id);
  88. jolt_settings->mSettings = shared->settings;
  89. jolt_settings->mUserData = reinterpret_cast<JPH::uint64>(this);
  90. jolt_settings->mObjectLayer = _get_object_layer();
  91. jolt_settings->mCollisionGroup = JPH::CollisionGroup(nullptr, group_id, sub_group_id);
  92. jolt_settings->mMaxLinearVelocity = JoltProjectSettings::max_linear_velocity;
  93. JPH::Body *new_jolt_body = space->add_soft_body(*this, *jolt_settings);
  94. if (new_jolt_body == nullptr) {
  95. return;
  96. }
  97. jolt_body = new_jolt_body;
  98. delete jolt_settings;
  99. jolt_settings = nullptr;
  100. }
  101. bool JoltSoftBody3D::_ref_shared_data() {
  102. HashMap<RID, Shared>::Iterator iter_shared_data = mesh_to_shared.find(mesh);
  103. if (iter_shared_data == mesh_to_shared.end()) {
  104. RenderingServer *rendering = RenderingServer::get_singleton();
  105. const Array mesh_data = rendering->mesh_surface_get_arrays(mesh, 0);
  106. ERR_FAIL_COND_V(mesh_data.is_empty(), false);
  107. const PackedInt32Array mesh_indices = mesh_data[RenderingServer::ARRAY_INDEX];
  108. ERR_FAIL_COND_V(mesh_indices.is_empty(), false);
  109. const PackedVector3Array mesh_vertices = mesh_data[RenderingServer::ARRAY_VERTEX];
  110. ERR_FAIL_COND_V(mesh_vertices.is_empty(), false);
  111. iter_shared_data = mesh_to_shared.insert(mesh, Shared());
  112. LocalVector<int> &mesh_to_physics = iter_shared_data->value.mesh_to_physics;
  113. JPH::SoftBodySharedSettings &settings = *iter_shared_data->value.settings;
  114. settings.mVertexRadius = JoltProjectSettings::soft_body_point_radius;
  115. JPH::Array<JPH::SoftBodySharedSettings::Vertex> &physics_vertices = settings.mVertices;
  116. JPH::Array<JPH::SoftBodySharedSettings::Face> &physics_faces = settings.mFaces;
  117. HashMap<Vector3, int> vertex_to_physics;
  118. const int mesh_vertex_count = mesh_vertices.size();
  119. const int mesh_index_count = mesh_indices.size();
  120. mesh_to_physics.resize(mesh_vertex_count);
  121. physics_vertices.reserve(mesh_vertex_count);
  122. vertex_to_physics.reserve(mesh_vertex_count);
  123. int physics_index_count = 0;
  124. for (int i = 0; i < mesh_index_count; i += 3) {
  125. int physics_face[3];
  126. int mesh_face[3];
  127. for (int j = 0; j < 3; ++j) {
  128. const int mesh_index = mesh_indices[i + j];
  129. const Vector3 vertex = mesh_vertices[mesh_index];
  130. HashMap<Vector3, int>::Iterator iter_physics_index = vertex_to_physics.find(vertex);
  131. if (iter_physics_index == vertex_to_physics.end()) {
  132. physics_vertices.emplace_back(JPH::Float3((float)vertex.x, (float)vertex.y, (float)vertex.z), JPH::Float3(0.0f, 0.0f, 0.0f), 1.0f);
  133. iter_physics_index = vertex_to_physics.insert(vertex, physics_index_count++);
  134. }
  135. mesh_face[j] = mesh_index;
  136. physics_face[j] = iter_physics_index->value;
  137. mesh_to_physics[mesh_index] = iter_physics_index->value;
  138. }
  139. ERR_CONTINUE_MSG(is_face_degenerate(physics_face), vformat("Failed to append face to soft body '%s'. Face was found to be degenerate. Face consist of indices %d, %d and %d.", to_string(), mesh_face[0], mesh_face[1], mesh_face[2]));
  140. // Jolt uses a different winding order, so we swap the indices to account for that.
  141. physics_faces.emplace_back((JPH::uint32)physics_face[2], (JPH::uint32)physics_face[1], (JPH::uint32)physics_face[0]);
  142. }
  143. // Pin whatever pinned vertices we have currently. This is used during the `Optimize` call below to order the
  144. // constraints. Note that it's fine if the pinned vertices change later, but that will reduce the effectiveness
  145. // of the constraints a bit.
  146. pin_vertices(*this, pinned_vertices, mesh_to_physics, physics_vertices);
  147. // Since Godot's stiffness is input as a coefficient between 0 and 1, and Jolt uses actual stiffness for its
  148. // edge constraints, we crudely map one to the other with an arbitrary constant.
  149. const float stiffness = MAX(Math::pow(stiffness_coefficient, 3.0f) * 100000.0f, 0.000001f);
  150. const float inverse_stiffness = 1.0f / stiffness;
  151. JPH::SoftBodySharedSettings::VertexAttributes vertex_attrib;
  152. vertex_attrib.mCompliance = vertex_attrib.mShearCompliance = inverse_stiffness;
  153. settings.CreateConstraints(&vertex_attrib, 1, JPH::SoftBodySharedSettings::EBendType::None);
  154. float multiplier = 1.0f - shrinking_factor;
  155. for (JPH::SoftBodySharedSettings::Edge &e : settings.mEdgeConstraints) {
  156. e.mRestLength *= multiplier;
  157. }
  158. settings.Optimize();
  159. } else {
  160. iter_shared_data->value.ref_count++;
  161. }
  162. shared = &iter_shared_data->value;
  163. return true;
  164. }
  165. void JoltSoftBody3D::_deref_shared_data() {
  166. if (unlikely(shared == nullptr)) {
  167. return;
  168. }
  169. HashMap<RID, Shared>::Iterator iter = mesh_to_shared.find(mesh);
  170. if (unlikely(iter == mesh_to_shared.end())) {
  171. return;
  172. }
  173. if (--iter->value.ref_count == 0) {
  174. mesh_to_shared.remove(iter);
  175. }
  176. shared = nullptr;
  177. }
  178. void JoltSoftBody3D::_update_mass() {
  179. if (!in_space()) {
  180. return;
  181. }
  182. JPH::SoftBodyMotionProperties &motion_properties = static_cast<JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  183. JPH::Array<JPH::SoftBodyVertex> &physics_vertices = motion_properties.GetVertices();
  184. const float inverse_vertex_mass = mass == 0.0f ? 1.0f : (float)physics_vertices.size() / mass;
  185. for (JPH::SoftBodyVertex &vertex : physics_vertices) {
  186. vertex.mInvMass = inverse_vertex_mass;
  187. }
  188. pin_vertices(*this, pinned_vertices, shared->mesh_to_physics, physics_vertices);
  189. }
  190. void JoltSoftBody3D::_update_pressure() {
  191. if (!in_space()) {
  192. jolt_settings->mPressure = pressure;
  193. return;
  194. }
  195. JPH::SoftBodyMotionProperties &motion_properties = static_cast<JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  196. motion_properties.SetPressure(pressure);
  197. }
  198. void JoltSoftBody3D::_update_damping() {
  199. if (!in_space()) {
  200. jolt_settings->mLinearDamping = linear_damping;
  201. return;
  202. }
  203. JPH::SoftBodyMotionProperties &motion_properties = static_cast<JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  204. motion_properties.SetLinearDamping(linear_damping);
  205. }
  206. void JoltSoftBody3D::_update_simulation_precision() {
  207. if (!in_space()) {
  208. jolt_settings->mNumIterations = (JPH::uint32)simulation_precision;
  209. return;
  210. }
  211. JPH::SoftBodyMotionProperties &motion_properties = static_cast<JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  212. motion_properties.SetNumIterations((JPH::uint32)simulation_precision);
  213. }
  214. void JoltSoftBody3D::_update_group_filter() {
  215. JPH::GroupFilter *group_filter = !exceptions.is_empty() ? JoltGroupFilter::instance : nullptr;
  216. if (!in_space()) {
  217. jolt_settings->mCollisionGroup.SetGroupFilter(group_filter);
  218. } else {
  219. jolt_body->GetCollisionGroup().SetGroupFilter(group_filter);
  220. }
  221. }
  222. void JoltSoftBody3D::_try_rebuild() {
  223. if (space != nullptr) {
  224. _reset_space();
  225. }
  226. }
  227. void JoltSoftBody3D::_mesh_changed() {
  228. _try_rebuild();
  229. }
  230. void JoltSoftBody3D::_simulation_precision_changed() {
  231. wake_up();
  232. }
  233. void JoltSoftBody3D::_mass_changed() {
  234. wake_up();
  235. }
  236. void JoltSoftBody3D::_pressure_changed() {
  237. _update_pressure();
  238. wake_up();
  239. }
  240. void JoltSoftBody3D::_damping_changed() {
  241. _update_damping();
  242. wake_up();
  243. }
  244. void JoltSoftBody3D::_pins_changed() {
  245. _update_mass();
  246. wake_up();
  247. }
  248. void JoltSoftBody3D::_vertices_changed() {
  249. wake_up();
  250. }
  251. void JoltSoftBody3D::_exceptions_changed() {
  252. _update_group_filter();
  253. }
  254. JoltSoftBody3D::JoltSoftBody3D() :
  255. JoltObject3D(OBJECT_TYPE_SOFT_BODY) {
  256. jolt_settings->mRestitution = 0.0f;
  257. jolt_settings->mFriction = 1.0f;
  258. jolt_settings->mUpdatePosition = false;
  259. jolt_settings->mMakeRotationIdentity = false;
  260. }
  261. JoltSoftBody3D::~JoltSoftBody3D() {
  262. if (jolt_settings != nullptr) {
  263. delete jolt_settings;
  264. jolt_settings = nullptr;
  265. }
  266. }
  267. bool JoltSoftBody3D::in_space() const {
  268. return JoltObject3D::in_space() && shared != nullptr;
  269. }
  270. void JoltSoftBody3D::add_collision_exception(const RID &p_excepted_body) {
  271. exceptions.push_back(p_excepted_body);
  272. _exceptions_changed();
  273. }
  274. void JoltSoftBody3D::remove_collision_exception(const RID &p_excepted_body) {
  275. exceptions.erase(p_excepted_body);
  276. _exceptions_changed();
  277. }
  278. bool JoltSoftBody3D::has_collision_exception(const RID &p_excepted_body) const {
  279. return exceptions.find(p_excepted_body) >= 0;
  280. }
  281. bool JoltSoftBody3D::can_interact_with(const JoltBody3D &p_other) const {
  282. return (can_collide_with(p_other) || p_other.can_collide_with(*this)) && !has_collision_exception(p_other.get_rid()) && !p_other.has_collision_exception(rid);
  283. }
  284. bool JoltSoftBody3D::can_interact_with(const JoltSoftBody3D &p_other) const {
  285. return (can_collide_with(p_other) || p_other.can_collide_with(*this)) && !has_collision_exception(p_other.get_rid()) && !p_other.has_collision_exception(rid);
  286. }
  287. bool JoltSoftBody3D::can_interact_with(const JoltArea3D &p_other) const {
  288. return p_other.can_interact_with(*this);
  289. }
  290. Vector3 JoltSoftBody3D::get_velocity_at_position(const Vector3 &p_position) const {
  291. return Vector3();
  292. }
  293. void JoltSoftBody3D::set_mesh(const RID &p_mesh) {
  294. if (unlikely(mesh == p_mesh)) {
  295. return;
  296. }
  297. _deref_shared_data();
  298. mesh = p_mesh;
  299. _mesh_changed();
  300. }
  301. bool JoltSoftBody3D::is_sleeping() const {
  302. if (!in_space()) {
  303. return false;
  304. } else {
  305. return !jolt_body->IsActive();
  306. }
  307. }
  308. void JoltSoftBody3D::set_is_sleeping(bool p_enabled) {
  309. if (!in_space()) {
  310. return;
  311. }
  312. JPH::BodyInterface &body_iface = space->get_body_iface();
  313. if (p_enabled) {
  314. body_iface.DeactivateBody(jolt_body->GetID());
  315. } else {
  316. body_iface.ActivateBody(jolt_body->GetID());
  317. }
  318. }
  319. bool JoltSoftBody3D::is_sleep_allowed() const {
  320. if (!in_space()) {
  321. return jolt_settings->mAllowSleeping;
  322. } else {
  323. return jolt_body->GetAllowSleeping();
  324. }
  325. }
  326. void JoltSoftBody3D::set_is_sleep_allowed(bool p_enabled) {
  327. if (!in_space()) {
  328. jolt_settings->mAllowSleeping = p_enabled;
  329. } else {
  330. jolt_body->SetAllowSleeping(p_enabled);
  331. }
  332. }
  333. void JoltSoftBody3D::set_simulation_precision(int p_precision) {
  334. if (unlikely(simulation_precision == p_precision)) {
  335. return;
  336. }
  337. simulation_precision = MAX(p_precision, 0);
  338. _simulation_precision_changed();
  339. }
  340. void JoltSoftBody3D::set_mass(float p_mass) {
  341. if (unlikely(mass == p_mass)) {
  342. return;
  343. }
  344. mass = MAX(p_mass, 0.0f);
  345. _mass_changed();
  346. }
  347. float JoltSoftBody3D::get_stiffness_coefficient() const {
  348. return stiffness_coefficient;
  349. }
  350. void JoltSoftBody3D::set_stiffness_coefficient(float p_coefficient) {
  351. stiffness_coefficient = CLAMP(p_coefficient, 0.0f, 1.0f);
  352. }
  353. float JoltSoftBody3D::get_shrinking_factor() const {
  354. return shrinking_factor;
  355. }
  356. void JoltSoftBody3D::set_shrinking_factor(float p_shrinking_factor) {
  357. shrinking_factor = p_shrinking_factor;
  358. }
  359. void JoltSoftBody3D::set_pressure(float p_pressure) {
  360. if (unlikely(pressure == p_pressure)) {
  361. return;
  362. }
  363. pressure = MAX(p_pressure, 0.0f);
  364. _pressure_changed();
  365. }
  366. void JoltSoftBody3D::set_linear_damping(float p_damping) {
  367. if (unlikely(linear_damping == p_damping)) {
  368. return;
  369. }
  370. linear_damping = MAX(p_damping, 0.0f);
  371. _damping_changed();
  372. }
  373. float JoltSoftBody3D::get_drag() const {
  374. // Drag is not a thing in Jolt, and not supported by Godot Physics either.
  375. return 0.0f;
  376. }
  377. void JoltSoftBody3D::set_drag(float p_drag) {
  378. // Drag is not a thing in Jolt, and not supported by Godot Physics either.
  379. }
  380. Variant JoltSoftBody3D::get_state(PhysicsServer3D::BodyState p_state) const {
  381. switch (p_state) {
  382. case PhysicsServer3D::BODY_STATE_TRANSFORM: {
  383. return get_transform();
  384. }
  385. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: {
  386. ERR_FAIL_V_MSG(Variant(), "Linear velocity is not supported for soft bodies.");
  387. }
  388. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: {
  389. ERR_FAIL_V_MSG(Variant(), "Angular velocity is not supported for soft bodies.");
  390. }
  391. case PhysicsServer3D::BODY_STATE_SLEEPING: {
  392. return is_sleeping();
  393. }
  394. case PhysicsServer3D::BODY_STATE_CAN_SLEEP: {
  395. return is_sleep_allowed();
  396. }
  397. default: {
  398. ERR_FAIL_V_MSG(Variant(), vformat("Unhandled body state: '%d'. This should not happen. Please report this.", p_state));
  399. }
  400. }
  401. }
  402. void JoltSoftBody3D::set_state(PhysicsServer3D::BodyState p_state, const Variant &p_value) {
  403. switch (p_state) {
  404. case PhysicsServer3D::BODY_STATE_TRANSFORM: {
  405. set_transform(p_value);
  406. } break;
  407. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: {
  408. ERR_FAIL_MSG("Linear velocity is not supported for soft bodies.");
  409. } break;
  410. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: {
  411. ERR_FAIL_MSG("Angular velocity is not supported for soft bodies.");
  412. } break;
  413. case PhysicsServer3D::BODY_STATE_SLEEPING: {
  414. set_is_sleeping(p_value);
  415. } break;
  416. case PhysicsServer3D::BODY_STATE_CAN_SLEEP: {
  417. set_is_sleep_allowed(p_value);
  418. } break;
  419. default: {
  420. ERR_FAIL_MSG(vformat("Unhandled body state: '%d'. This should not happen. Please report this.", p_state));
  421. } break;
  422. }
  423. }
  424. Transform3D JoltSoftBody3D::get_transform() const {
  425. // Since any transform gets baked into the vertices anyway we can just return identity here.
  426. return Transform3D();
  427. }
  428. void JoltSoftBody3D::set_transform(const Transform3D &p_transform) {
  429. ERR_FAIL_COND_MSG(!in_space(), vformat("Failed to set transform for '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  430. // For whatever reason this has to be interpreted as a relative global-space transform rather than an absolute one,
  431. // because `SoftBody3D` will immediately upon entering the scene tree set itself to be top-level and also set its
  432. // transform to be identity, while still expecting to stay in its original position.
  433. //
  434. // We also discard any scaling, since we have no way of scaling the actual edge lengths.
  435. const JPH::Mat44 relative_transform = to_jolt(p_transform.orthonormalized());
  436. JPH::SoftBodyMotionProperties &motion_properties = static_cast<JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  437. JPH::Array<JPH::SoftBodyVertex> &physics_vertices = motion_properties.GetVertices();
  438. for (JPH::SoftBodyVertex &vertex : physics_vertices) {
  439. vertex.mPosition = vertex.mPreviousPosition = relative_transform * vertex.mPosition;
  440. vertex.mVelocity = JPH::Vec3::sZero();
  441. }
  442. }
  443. AABB JoltSoftBody3D::get_bounds() const {
  444. ERR_FAIL_COND_V_MSG(!in_space(), AABB(), vformat("Failed to retrieve world bounds of '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  445. return to_godot(jolt_body->GetWorldSpaceBounds());
  446. }
  447. void JoltSoftBody3D::update_rendering_server(PhysicsServer3DRenderingServerHandler *p_rendering_server_handler) {
  448. // Ideally we would emit an actual error here, but that would spam the logs to the point where the actual cause will be drowned out.
  449. if (unlikely(!in_space())) {
  450. return;
  451. }
  452. const JPH::SoftBodyMotionProperties &motion_properties = static_cast<const JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  453. typedef JPH::SoftBodyMotionProperties::Vertex SoftBodyVertex;
  454. typedef JPH::SoftBodyMotionProperties::Face SoftBodyFace;
  455. const JPH::Array<SoftBodyVertex> &physics_vertices = motion_properties.GetVertices();
  456. const JPH::Array<SoftBodyFace> &physics_faces = motion_properties.GetFaces();
  457. const int physics_vertex_count = (int)physics_vertices.size();
  458. normals.resize(physics_vertex_count);
  459. for (const SoftBodyFace &physics_face : physics_faces) {
  460. // Jolt uses a different winding order, so we swap the indices to account for that.
  461. const uint32_t i0 = physics_face.mVertex[2];
  462. const uint32_t i1 = physics_face.mVertex[1];
  463. const uint32_t i2 = physics_face.mVertex[0];
  464. const Vector3 v0 = to_godot(physics_vertices[i0].mPosition);
  465. const Vector3 v1 = to_godot(physics_vertices[i1].mPosition);
  466. const Vector3 v2 = to_godot(physics_vertices[i2].mPosition);
  467. const Vector3 normal = (v2 - v0).cross(v1 - v0).normalized();
  468. normals[i0] = normal;
  469. normals[i1] = normal;
  470. normals[i2] = normal;
  471. }
  472. const int mesh_vertex_count = shared->mesh_to_physics.size();
  473. for (int i = 0; i < mesh_vertex_count; ++i) {
  474. const int physics_index = shared->mesh_to_physics[i];
  475. const Vector3 vertex = to_godot(physics_vertices[(size_t)physics_index].mPosition);
  476. const Vector3 normal = normals[(uint32_t)physics_index];
  477. p_rendering_server_handler->set_vertex(i, vertex);
  478. p_rendering_server_handler->set_normal(i, normal);
  479. }
  480. p_rendering_server_handler->set_aabb(get_bounds());
  481. }
  482. Vector3 JoltSoftBody3D::get_vertex_position(int p_index) {
  483. ERR_FAIL_COND_V_MSG(!in_space(), Vector3(), vformat("Failed to retrieve point position for '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  484. ERR_FAIL_NULL_V(shared, Vector3());
  485. ERR_FAIL_INDEX_V(p_index, (int)shared->mesh_to_physics.size(), Vector3());
  486. const size_t physics_index = (size_t)shared->mesh_to_physics[p_index];
  487. const JPH::SoftBodyMotionProperties &motion_properties = static_cast<const JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  488. const JPH::Array<JPH::SoftBodyVertex> &physics_vertices = motion_properties.GetVertices();
  489. const JPH::SoftBodyVertex &physics_vertex = physics_vertices[physics_index];
  490. return to_godot(jolt_body->GetCenterOfMassPosition() + physics_vertex.mPosition);
  491. }
  492. void JoltSoftBody3D::set_vertex_position(int p_index, const Vector3 &p_position) {
  493. ERR_FAIL_COND_MSG(!in_space(), vformat("Failed to set point position for '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  494. ERR_FAIL_NULL(shared);
  495. ERR_FAIL_INDEX(p_index, (int)shared->mesh_to_physics.size());
  496. const size_t physics_index = (size_t)shared->mesh_to_physics[p_index];
  497. JPH::SoftBodyMotionProperties &motion_properties = static_cast<JPH::SoftBodyMotionProperties &>(*jolt_body->GetMotionPropertiesUnchecked());
  498. JPH::Array<JPH::SoftBodyVertex> &physics_vertices = motion_properties.GetVertices();
  499. JPH::SoftBodyVertex &physics_vertex = physics_vertices[physics_index];
  500. const JPH::RVec3 center_of_mass = jolt_body->GetCenterOfMassPosition();
  501. physics_vertex.mPosition = JPH::Vec3(to_jolt_r(p_position) - center_of_mass);
  502. _vertices_changed();
  503. }
  504. void JoltSoftBody3D::pin_vertex(int p_index) {
  505. pinned_vertices.insert(p_index);
  506. _pins_changed();
  507. }
  508. void JoltSoftBody3D::unpin_vertex(int p_index) {
  509. pinned_vertices.erase(p_index);
  510. _pins_changed();
  511. }
  512. void JoltSoftBody3D::unpin_all_vertices() {
  513. pinned_vertices.clear();
  514. _pins_changed();
  515. }
  516. bool JoltSoftBody3D::is_vertex_pinned(int p_index) const {
  517. ERR_FAIL_COND_V_MSG(!in_space(), false, vformat("Failed retrieve pin status of point for '%s'. Doing so without a physics space is not supported when using Jolt Physics. If this relates to a node, try adding the node to a scene tree first.", to_string()));
  518. ERR_FAIL_NULL_V(shared, false);
  519. ERR_FAIL_INDEX_V(p_index, (int)shared->mesh_to_physics.size(), false);
  520. const int physics_index = shared->mesh_to_physics[p_index];
  521. return pinned_vertices.has(physics_index);
  522. }