godot_soft_body_3d.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. /**************************************************************************/
  2. /* godot_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 "godot_soft_body_3d.h"
  31. #include "godot_space_3d.h"
  32. #include "core/math/geometry_3d.h"
  33. #include "core/templates/rb_map.h"
  34. #include "servers/rendering_server.h"
  35. // Based on Bullet soft body.
  36. /*
  37. Bullet Continuous Collision Detection and Physics Library
  38. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  39. This software is provided 'as-is', without any express or implied warranty.
  40. In no event will the authors be held liable for any damages arising from the use of this software.
  41. Permission is granted to anyone to use this software for any purpose,
  42. including commercial applications, and to alter it and redistribute it freely,
  43. subject to the following restrictions:
  44. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  45. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  46. 3. This notice may not be removed or altered from any source distribution.
  47. */
  48. ///btSoftBody implementation by Nathanael Presson
  49. GodotSoftBody3D::GodotSoftBody3D() :
  50. GodotCollisionObject3D(TYPE_SOFT_BODY),
  51. active_list(this) {
  52. _set_static(false);
  53. }
  54. void GodotSoftBody3D::_shapes_changed() {
  55. }
  56. void GodotSoftBody3D::set_state(PhysicsServer3D::BodyState p_state, const Variant &p_variant) {
  57. switch (p_state) {
  58. case PhysicsServer3D::BODY_STATE_TRANSFORM: {
  59. _set_transform(p_variant);
  60. _set_inv_transform(get_transform().inverse());
  61. apply_nodes_transform(get_transform());
  62. } break;
  63. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: {
  64. // Not supported.
  65. ERR_FAIL_MSG("Linear velocity is not supported for Soft bodies.");
  66. } break;
  67. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: {
  68. ERR_FAIL_MSG("Angular velocity is not supported for Soft bodies.");
  69. } break;
  70. case PhysicsServer3D::BODY_STATE_SLEEPING: {
  71. ERR_FAIL_MSG("Sleeping state is not supported for Soft bodies.");
  72. } break;
  73. case PhysicsServer3D::BODY_STATE_CAN_SLEEP: {
  74. ERR_FAIL_MSG("Sleeping state is not supported for Soft bodies.");
  75. } break;
  76. }
  77. }
  78. Variant GodotSoftBody3D::get_state(PhysicsServer3D::BodyState p_state) const {
  79. switch (p_state) {
  80. case PhysicsServer3D::BODY_STATE_TRANSFORM: {
  81. return get_transform();
  82. } break;
  83. case PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY: {
  84. ERR_FAIL_V_MSG(Vector3(), "Linear velocity is not supported for Soft bodies.");
  85. } break;
  86. case PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY: {
  87. ERR_FAIL_V_MSG(Vector3(), "Angular velocity is not supported for Soft bodies.");
  88. } break;
  89. case PhysicsServer3D::BODY_STATE_SLEEPING: {
  90. ERR_FAIL_V_MSG(false, "Sleeping state is not supported for Soft bodies.");
  91. } break;
  92. case PhysicsServer3D::BODY_STATE_CAN_SLEEP: {
  93. ERR_FAIL_V_MSG(false, "Sleeping state is not supported for Soft bodies.");
  94. } break;
  95. }
  96. return Variant();
  97. }
  98. void GodotSoftBody3D::set_space(GodotSpace3D *p_space) {
  99. if (get_space()) {
  100. get_space()->soft_body_remove_from_active_list(&active_list);
  101. deinitialize_shape();
  102. }
  103. _set_space(p_space);
  104. if (get_space()) {
  105. get_space()->soft_body_add_to_active_list(&active_list);
  106. if (bounds != AABB()) {
  107. initialize_shape(true);
  108. }
  109. }
  110. }
  111. void GodotSoftBody3D::set_mesh(RID p_mesh) {
  112. destroy();
  113. soft_mesh = p_mesh;
  114. if (soft_mesh.is_null()) {
  115. return;
  116. }
  117. Array arrays = RenderingServer::get_singleton()->mesh_surface_get_arrays(soft_mesh, 0);
  118. ERR_FAIL_COND(arrays.is_empty());
  119. bool success = create_from_trimesh(arrays[RenderingServer::ARRAY_INDEX], arrays[RenderingServer::ARRAY_VERTEX]);
  120. if (!success) {
  121. destroy();
  122. }
  123. }
  124. void GodotSoftBody3D::update_rendering_server(PhysicsServer3DRenderingServerHandler *p_rendering_server_handler) {
  125. if (soft_mesh.is_null()) {
  126. return;
  127. }
  128. const uint32_t vertex_count = map_visual_to_physics.size();
  129. for (uint32_t i = 0; i < vertex_count; ++i) {
  130. const uint32_t node_index = map_visual_to_physics[i];
  131. const Node &node = nodes[node_index];
  132. p_rendering_server_handler->set_vertex(i, node.x);
  133. p_rendering_server_handler->set_normal(i, node.n);
  134. }
  135. p_rendering_server_handler->set_aabb(bounds);
  136. }
  137. void GodotSoftBody3D::update_normals_and_centroids() {
  138. for (Node &node : nodes) {
  139. node.n = Vector3();
  140. }
  141. for (Face &face : faces) {
  142. const Vector3 n = vec3_cross(face.n[0]->x - face.n[2]->x, face.n[0]->x - face.n[1]->x);
  143. face.n[0]->n += n;
  144. face.n[1]->n += n;
  145. face.n[2]->n += n;
  146. face.normal = n;
  147. face.normal.normalize();
  148. face.centroid = 0.33333333333 * (face.n[0]->x + face.n[1]->x + face.n[2]->x);
  149. }
  150. for (Node &node : nodes) {
  151. real_t len = node.n.length();
  152. if (len > CMP_EPSILON) {
  153. node.n /= len;
  154. }
  155. }
  156. }
  157. void GodotSoftBody3D::update_bounds() {
  158. AABB prev_bounds = bounds;
  159. prev_bounds.grow_by(collision_margin);
  160. bounds = AABB();
  161. const uint32_t nodes_count = nodes.size();
  162. if (nodes_count == 0) {
  163. deinitialize_shape();
  164. return;
  165. }
  166. bool first = true;
  167. bool moved = false;
  168. for (uint32_t node_index = 0; node_index < nodes_count; ++node_index) {
  169. const Node &node = nodes[node_index];
  170. if (!prev_bounds.has_point(node.x)) {
  171. moved = true;
  172. }
  173. if (first) {
  174. bounds.position = node.x;
  175. first = false;
  176. } else {
  177. bounds.expand_to(node.x);
  178. }
  179. }
  180. if (get_space()) {
  181. initialize_shape(moved);
  182. }
  183. }
  184. void GodotSoftBody3D::update_constants() {
  185. reset_link_rest_lengths();
  186. update_link_constants();
  187. update_area();
  188. }
  189. void GodotSoftBody3D::update_area() {
  190. int i, ni;
  191. // Face area.
  192. for (Face &face : faces) {
  193. const Vector3 &x0 = face.n[0]->x;
  194. const Vector3 &x1 = face.n[1]->x;
  195. const Vector3 &x2 = face.n[2]->x;
  196. const Vector3 a = x1 - x0;
  197. const Vector3 b = x2 - x0;
  198. const Vector3 cr = vec3_cross(a, b);
  199. face.ra = cr.length() * 0.5;
  200. }
  201. // Node area.
  202. LocalVector<int> counts;
  203. if (nodes.size() > 0) {
  204. counts.resize(nodes.size());
  205. memset(counts.ptr(), 0, counts.size() * sizeof(int));
  206. }
  207. for (Node &node : nodes) {
  208. node.area = 0.0;
  209. }
  210. for (const Face &face : faces) {
  211. for (int j = 0; j < 3; ++j) {
  212. const int index = (int)(face.n[j] - &nodes[0]);
  213. counts[index]++;
  214. face.n[j]->area += Math::abs(face.ra);
  215. }
  216. }
  217. for (i = 0, ni = nodes.size(); i < ni; ++i) {
  218. if (counts[i] > 0) {
  219. nodes[i].area /= (real_t)counts[i];
  220. } else {
  221. nodes[i].area = 0.0;
  222. }
  223. }
  224. }
  225. void GodotSoftBody3D::reset_link_rest_lengths() {
  226. for (Link &link : links) {
  227. link.rl = (link.n[0]->x - link.n[1]->x).length();
  228. link.c1 = link.rl * link.rl;
  229. }
  230. }
  231. void GodotSoftBody3D::update_link_constants() {
  232. real_t inv_linear_stiffness = 1.0 / linear_stiffness;
  233. for (Link &link : links) {
  234. link.c0 = (link.n[0]->im + link.n[1]->im) * inv_linear_stiffness;
  235. }
  236. }
  237. void GodotSoftBody3D::apply_nodes_transform(const Transform3D &p_transform) {
  238. if (soft_mesh.is_null()) {
  239. return;
  240. }
  241. uint32_t node_count = nodes.size();
  242. Vector3 leaf_size = Vector3(collision_margin, collision_margin, collision_margin) * 2.0;
  243. for (uint32_t node_index = 0; node_index < node_count; ++node_index) {
  244. Node &node = nodes[node_index];
  245. node.x = p_transform.xform(node.x);
  246. node.q = node.x;
  247. node.v = Vector3();
  248. node.bv = Vector3();
  249. AABB node_aabb(node.x, leaf_size);
  250. node_tree.update(node.leaf, node_aabb);
  251. }
  252. face_tree.clear();
  253. update_normals_and_centroids();
  254. update_bounds();
  255. update_constants();
  256. }
  257. Vector3 GodotSoftBody3D::get_vertex_position(int p_index) const {
  258. ERR_FAIL_COND_V(p_index < 0, Vector3());
  259. if (soft_mesh.is_null()) {
  260. return Vector3();
  261. }
  262. ERR_FAIL_COND_V(p_index >= (int)map_visual_to_physics.size(), Vector3());
  263. uint32_t node_index = map_visual_to_physics[p_index];
  264. ERR_FAIL_COND_V(node_index >= nodes.size(), Vector3());
  265. return nodes[node_index].x;
  266. }
  267. void GodotSoftBody3D::set_vertex_position(int p_index, const Vector3 &p_position) {
  268. ERR_FAIL_COND(p_index < 0);
  269. if (soft_mesh.is_null()) {
  270. return;
  271. }
  272. ERR_FAIL_COND(p_index >= (int)map_visual_to_physics.size());
  273. uint32_t node_index = map_visual_to_physics[p_index];
  274. ERR_FAIL_COND(node_index >= nodes.size());
  275. Node &node = nodes[node_index];
  276. node.q = node.x;
  277. node.x = p_position;
  278. }
  279. void GodotSoftBody3D::pin_vertex(int p_index) {
  280. ERR_FAIL_COND(p_index < 0);
  281. if (is_vertex_pinned(p_index)) {
  282. return;
  283. }
  284. pinned_vertices.push_back(p_index);
  285. if (!soft_mesh.is_null()) {
  286. ERR_FAIL_COND(p_index >= (int)map_visual_to_physics.size());
  287. uint32_t node_index = map_visual_to_physics[p_index];
  288. ERR_FAIL_COND(node_index >= nodes.size());
  289. Node &node = nodes[node_index];
  290. node.im = 0.0;
  291. }
  292. }
  293. void GodotSoftBody3D::unpin_vertex(int p_index) {
  294. ERR_FAIL_COND(p_index < 0);
  295. uint32_t pinned_count = pinned_vertices.size();
  296. for (uint32_t i = 0; i < pinned_count; ++i) {
  297. if (p_index == pinned_vertices[i]) {
  298. pinned_vertices.remove_at(i);
  299. if (!soft_mesh.is_null()) {
  300. ERR_FAIL_COND(p_index >= (int)map_visual_to_physics.size());
  301. uint32_t node_index = map_visual_to_physics[p_index];
  302. ERR_FAIL_COND(node_index >= nodes.size());
  303. real_t inv_node_mass = nodes.size() * inv_total_mass;
  304. Node &node = nodes[node_index];
  305. node.im = inv_node_mass;
  306. }
  307. return;
  308. }
  309. }
  310. }
  311. void GodotSoftBody3D::unpin_all_vertices() {
  312. if (!soft_mesh.is_null()) {
  313. real_t inv_node_mass = nodes.size() * inv_total_mass;
  314. uint32_t pinned_count = pinned_vertices.size();
  315. for (uint32_t i = 0; i < pinned_count; ++i) {
  316. int pinned_vertex = pinned_vertices[i];
  317. ERR_CONTINUE(pinned_vertex >= (int)map_visual_to_physics.size());
  318. uint32_t node_index = map_visual_to_physics[pinned_vertex];
  319. ERR_CONTINUE(node_index >= nodes.size());
  320. Node &node = nodes[node_index];
  321. node.im = inv_node_mass;
  322. }
  323. }
  324. pinned_vertices.clear();
  325. }
  326. bool GodotSoftBody3D::is_vertex_pinned(int p_index) const {
  327. ERR_FAIL_COND_V(p_index < 0, false);
  328. uint32_t pinned_count = pinned_vertices.size();
  329. for (uint32_t i = 0; i < pinned_count; ++i) {
  330. if (p_index == pinned_vertices[i]) {
  331. return true;
  332. }
  333. }
  334. return false;
  335. }
  336. uint32_t GodotSoftBody3D::get_node_count() const {
  337. return nodes.size();
  338. }
  339. real_t GodotSoftBody3D::get_node_inv_mass(uint32_t p_node_index) const {
  340. ERR_FAIL_UNSIGNED_INDEX_V(p_node_index, nodes.size(), 0.0);
  341. return nodes[p_node_index].im;
  342. }
  343. Vector3 GodotSoftBody3D::get_node_position(uint32_t p_node_index) const {
  344. ERR_FAIL_UNSIGNED_INDEX_V(p_node_index, nodes.size(), Vector3());
  345. return nodes[p_node_index].x;
  346. }
  347. Vector3 GodotSoftBody3D::get_node_velocity(uint32_t p_node_index) const {
  348. ERR_FAIL_UNSIGNED_INDEX_V(p_node_index, nodes.size(), Vector3());
  349. return nodes[p_node_index].v;
  350. }
  351. Vector3 GodotSoftBody3D::get_node_biased_velocity(uint32_t p_node_index) const {
  352. ERR_FAIL_UNSIGNED_INDEX_V(p_node_index, nodes.size(), Vector3());
  353. return nodes[p_node_index].bv;
  354. }
  355. void GodotSoftBody3D::apply_node_impulse(uint32_t p_node_index, const Vector3 &p_impulse) {
  356. ERR_FAIL_UNSIGNED_INDEX(p_node_index, nodes.size());
  357. Node &node = nodes[p_node_index];
  358. node.v += p_impulse * node.im;
  359. }
  360. void GodotSoftBody3D::apply_node_bias_impulse(uint32_t p_node_index, const Vector3 &p_impulse) {
  361. ERR_FAIL_UNSIGNED_INDEX(p_node_index, nodes.size());
  362. Node &node = nodes[p_node_index];
  363. node.bv += p_impulse * node.im;
  364. }
  365. uint32_t GodotSoftBody3D::get_face_count() const {
  366. return faces.size();
  367. }
  368. void GodotSoftBody3D::get_face_points(uint32_t p_face_index, Vector3 &r_point_1, Vector3 &r_point_2, Vector3 &r_point_3) const {
  369. ERR_FAIL_UNSIGNED_INDEX(p_face_index, faces.size());
  370. const Face &face = faces[p_face_index];
  371. r_point_1 = face.n[0]->x;
  372. r_point_2 = face.n[1]->x;
  373. r_point_3 = face.n[2]->x;
  374. }
  375. Vector3 GodotSoftBody3D::get_face_normal(uint32_t p_face_index) const {
  376. ERR_FAIL_UNSIGNED_INDEX_V(p_face_index, faces.size(), Vector3());
  377. return faces[p_face_index].normal;
  378. }
  379. bool GodotSoftBody3D::create_from_trimesh(const Vector<int> &p_indices, const Vector<Vector3> &p_vertices) {
  380. ERR_FAIL_COND_V(p_indices.is_empty(), false);
  381. ERR_FAIL_COND_V(p_vertices.is_empty(), false);
  382. uint32_t node_count = 0;
  383. LocalVector<Vector3> vertices;
  384. const int visual_vertex_count(p_vertices.size());
  385. LocalVector<int> triangles;
  386. const uint32_t triangle_count(p_indices.size() / 3);
  387. triangles.resize(triangle_count * 3);
  388. // Merge all overlapping vertices and create a map of physical vertices to visual vertices.
  389. {
  390. // Process vertices.
  391. {
  392. uint32_t vertex_count = 0;
  393. HashMap<Vector3, uint32_t> unique_vertices;
  394. vertices.resize(visual_vertex_count);
  395. map_visual_to_physics.resize(visual_vertex_count);
  396. for (int visual_vertex_index = 0; visual_vertex_index < visual_vertex_count; ++visual_vertex_index) {
  397. const Vector3 &vertex = p_vertices[visual_vertex_index];
  398. HashMap<Vector3, uint32_t>::Iterator e = unique_vertices.find(vertex);
  399. uint32_t vertex_id;
  400. if (e) {
  401. // Already existing.
  402. vertex_id = e->value;
  403. } else {
  404. // Create new one.
  405. vertex_id = vertex_count++;
  406. unique_vertices[vertex] = vertex_id;
  407. vertices[vertex_id] = vertex;
  408. }
  409. map_visual_to_physics[visual_vertex_index] = vertex_id;
  410. }
  411. vertices.resize(vertex_count);
  412. }
  413. // Process triangles.
  414. {
  415. for (uint32_t triangle_index = 0; triangle_index < triangle_count; ++triangle_index) {
  416. for (int i = 0; i < 3; ++i) {
  417. int visual_index = 3 * triangle_index + i;
  418. int physics_index = map_visual_to_physics[p_indices[visual_index]];
  419. triangles[visual_index] = physics_index;
  420. node_count = MAX((int)node_count, physics_index);
  421. }
  422. }
  423. }
  424. }
  425. ++node_count;
  426. // Create nodes from vertices.
  427. nodes.resize(node_count);
  428. real_t inv_node_mass = node_count * inv_total_mass;
  429. Vector3 leaf_size = Vector3(collision_margin, collision_margin, collision_margin) * 2.0;
  430. for (uint32_t i = 0; i < node_count; ++i) {
  431. Node &node = nodes[i];
  432. node.s = vertices[i];
  433. node.x = node.s;
  434. node.q = node.s;
  435. node.im = inv_node_mass;
  436. AABB node_aabb(node.x, leaf_size);
  437. node.leaf = node_tree.insert(node_aabb, &node);
  438. node.index = i;
  439. }
  440. // Create links and faces from triangles.
  441. LocalVector<bool> chks;
  442. chks.resize(node_count * node_count);
  443. memset(chks.ptr(), 0, chks.size() * sizeof(bool));
  444. for (uint32_t i = 0; i < triangle_count * 3; i += 3) {
  445. const int idx[] = { triangles[i], triangles[i + 1], triangles[i + 2] };
  446. for (int j = 2, k = 0; k < 3; j = k++) {
  447. int chk = idx[k] * node_count + idx[j];
  448. if (!chks[chk]) {
  449. chks[chk] = true;
  450. int inv_chk = idx[j] * node_count + idx[k];
  451. chks[inv_chk] = true;
  452. append_link(idx[j], idx[k]);
  453. }
  454. }
  455. append_face(idx[0], idx[1], idx[2]);
  456. }
  457. // Set pinned nodes.
  458. uint32_t pinned_count = pinned_vertices.size();
  459. for (uint32_t i = 0; i < pinned_count; ++i) {
  460. int pinned_vertex = pinned_vertices[i];
  461. ERR_CONTINUE(pinned_vertex >= visual_vertex_count);
  462. uint32_t node_index = map_visual_to_physics[pinned_vertex];
  463. ERR_CONTINUE(node_index >= node_count);
  464. Node &node = nodes[node_index];
  465. node.im = 0.0;
  466. }
  467. generate_bending_constraints(2);
  468. reoptimize_link_order();
  469. update_constants();
  470. update_normals_and_centroids();
  471. update_bounds();
  472. return true;
  473. }
  474. void GodotSoftBody3D::generate_bending_constraints(int p_distance) {
  475. uint32_t i, j;
  476. if (p_distance > 1) {
  477. // Build graph.
  478. const uint32_t n = nodes.size();
  479. const unsigned inf = (~(unsigned)0) >> 1;
  480. const uint32_t adj_size = n * n;
  481. unsigned *adj = memnew_arr(unsigned, adj_size);
  482. #define IDX(_x_, _y_) ((_y_)*n + (_x_))
  483. for (j = 0; j < n; ++j) {
  484. for (i = 0; i < n; ++i) {
  485. int idx_ij = j * n + i;
  486. int idx_ji = i * n + j;
  487. if (i != j) {
  488. adj[idx_ij] = adj[idx_ji] = inf;
  489. } else {
  490. adj[idx_ij] = adj[idx_ji] = 0;
  491. }
  492. }
  493. }
  494. for (Link &link : links) {
  495. const int ia = (int)(link.n[0] - &nodes[0]);
  496. const int ib = (int)(link.n[1] - &nodes[0]);
  497. int idx = ib * n + ia;
  498. int idx_inv = ia * n + ib;
  499. adj[idx] = 1;
  500. adj[idx_inv] = 1;
  501. }
  502. // Special optimized case for distance == 2.
  503. if (p_distance == 2) {
  504. LocalVector<LocalVector<int>> node_links;
  505. // Build node links.
  506. node_links.resize(nodes.size());
  507. for (Link &link : links) {
  508. const int ia = (int)(link.n[0] - &nodes[0]);
  509. const int ib = (int)(link.n[1] - &nodes[0]);
  510. if (node_links[ia].find(ib) == -1) {
  511. node_links[ia].push_back(ib);
  512. }
  513. if (node_links[ib].find(ia) == -1) {
  514. node_links[ib].push_back(ia);
  515. }
  516. }
  517. for (uint32_t ii = 0; ii < node_links.size(); ii++) {
  518. for (uint32_t jj = 0; jj < node_links[ii].size(); jj++) {
  519. int k = node_links[ii][jj];
  520. for (const int &l : node_links[k]) {
  521. if ((int)ii != l) {
  522. int idx_ik = k * n + ii;
  523. int idx_kj = l * n + k;
  524. const unsigned sum = adj[idx_ik] + adj[idx_kj];
  525. ERR_FAIL_COND(sum != 2);
  526. int idx_ij = l * n + ii;
  527. if (adj[idx_ij] > sum) {
  528. int idx_ji = l * n + ii;
  529. adj[idx_ij] = adj[idx_ji] = sum;
  530. }
  531. }
  532. }
  533. }
  534. }
  535. } else {
  536. // Generic Floyd's algorithm.
  537. for (uint32_t k = 0; k < n; ++k) {
  538. for (j = 0; j < n; ++j) {
  539. for (i = j + 1; i < n; ++i) {
  540. int idx_ik = k * n + i;
  541. int idx_kj = j * n + k;
  542. const unsigned sum = adj[idx_ik] + adj[idx_kj];
  543. int idx_ij = j * n + i;
  544. if (adj[idx_ij] > sum) {
  545. int idx_ji = j * n + i;
  546. adj[idx_ij] = adj[idx_ji] = sum;
  547. }
  548. }
  549. }
  550. }
  551. }
  552. // Build links.
  553. for (j = 0; j < n; ++j) {
  554. for (i = j + 1; i < n; ++i) {
  555. int idx_ij = j * n + i;
  556. if (adj[idx_ij] == (unsigned)p_distance) {
  557. append_link(i, j);
  558. }
  559. }
  560. }
  561. memdelete_arr(adj);
  562. }
  563. }
  564. //===================================================================
  565. //
  566. //
  567. // This function takes in a list of interdependent Links and tries
  568. // to maximize the distance between calculation
  569. // of dependent links. This increases the amount of parallelism that can
  570. // be exploited by out-of-order instruction processors with large but
  571. // (inevitably) finite instruction windows.
  572. //
  573. //===================================================================
  574. // A small structure to track lists of dependent link calculations.
  575. class LinkDeps {
  576. public:
  577. // A link calculation that is dependent on this one.
  578. // Positive values = "input A" while negative values = "input B".
  579. int value;
  580. // Next dependence in the list.
  581. LinkDeps *next;
  582. };
  583. typedef LinkDeps *LinkDepsPtr;
  584. void GodotSoftBody3D::reoptimize_link_order() {
  585. const int reop_not_dependent = -1;
  586. const int reop_node_complete = -2;
  587. uint32_t link_count = links.size();
  588. uint32_t node_count = nodes.size();
  589. if (link_count < 1 || node_count < 2) {
  590. return;
  591. }
  592. uint32_t i;
  593. Link *lr;
  594. int ar, br;
  595. Node *node0 = &(nodes[0]);
  596. Node *node1 = &(nodes[1]);
  597. LinkDepsPtr link_dep;
  598. int ready_list_head, ready_list_tail, link_num, link_dep_frees, dep_link;
  599. // Allocate temporary buffers.
  600. int *node_written_at = memnew_arr(int, node_count + 1); // What link calculation produced this node's current values?
  601. int *link_dep_A = memnew_arr(int, link_count); // Link calculation input is dependent upon prior calculation #N
  602. int *link_dep_B = memnew_arr(int, link_count);
  603. int *ready_list = memnew_arr(int, link_count); // List of ready-to-process link calculations (# of links, maximum)
  604. LinkDeps *link_dep_free_list = memnew_arr(LinkDeps, 2 * link_count); // Dependent-on-me list elements (2x# of links, maximum)
  605. LinkDepsPtr *link_dep_list_starts = memnew_arr(LinkDepsPtr, link_count); // Start nodes of dependent-on-me lists, one for each link
  606. // Copy the original, unsorted links to a side buffer.
  607. Link *link_buffer = memnew_arr(Link, link_count);
  608. memcpy(link_buffer, &(links[0]), sizeof(Link) * link_count);
  609. // Clear out the node setup and ready list.
  610. for (i = 0; i < node_count + 1; i++) {
  611. node_written_at[i] = reop_not_dependent;
  612. }
  613. for (i = 0; i < link_count; i++) {
  614. link_dep_list_starts[i] = nullptr;
  615. }
  616. ready_list_head = ready_list_tail = link_dep_frees = 0;
  617. // Initial link analysis to set up data structures.
  618. for (i = 0; i < link_count; i++) {
  619. // Note which prior link calculations we are dependent upon & build up dependence lists.
  620. lr = &(links[i]);
  621. ar = (lr->n[0] - node0) / (node1 - node0);
  622. br = (lr->n[1] - node0) / (node1 - node0);
  623. if (node_written_at[ar] > reop_not_dependent) {
  624. link_dep_A[i] = node_written_at[ar];
  625. link_dep = &link_dep_free_list[link_dep_frees++];
  626. link_dep->value = i;
  627. link_dep->next = link_dep_list_starts[node_written_at[ar]];
  628. link_dep_list_starts[node_written_at[ar]] = link_dep;
  629. } else {
  630. link_dep_A[i] = reop_not_dependent;
  631. }
  632. if (node_written_at[br] > reop_not_dependent) {
  633. link_dep_B[i] = node_written_at[br];
  634. link_dep = &link_dep_free_list[link_dep_frees++];
  635. link_dep->value = -(int)(i + 1);
  636. link_dep->next = link_dep_list_starts[node_written_at[br]];
  637. link_dep_list_starts[node_written_at[br]] = link_dep;
  638. } else {
  639. link_dep_B[i] = reop_not_dependent;
  640. }
  641. // Add this link to the initial ready list, if it is not dependent on any other links.
  642. if ((link_dep_A[i] == reop_not_dependent) && (link_dep_B[i] == reop_not_dependent)) {
  643. ready_list[ready_list_tail++] = i;
  644. link_dep_A[i] = link_dep_B[i] = reop_node_complete; // Probably not needed now.
  645. }
  646. // Update the nodes to mark which ones are calculated by this link.
  647. node_written_at[ar] = node_written_at[br] = i;
  648. }
  649. // Process the ready list and create the sorted list of links:
  650. // -- By treating the ready list as a queue, we maximize the distance between any
  651. // inter-dependent node calculations.
  652. // -- All other (non-related) nodes in the ready list will automatically be inserted
  653. // in between each set of inter-dependent link calculations by this loop.
  654. i = 0;
  655. while (ready_list_head != ready_list_tail) {
  656. // Use ready list to select the next link to process.
  657. link_num = ready_list[ready_list_head++];
  658. // Copy the next-to-calculate link back into the original link array.
  659. links[i++] = link_buffer[link_num];
  660. // Free up any link inputs that are dependent on this one.
  661. link_dep = link_dep_list_starts[link_num];
  662. while (link_dep) {
  663. dep_link = link_dep->value;
  664. if (dep_link >= 0) {
  665. link_dep_A[dep_link] = reop_not_dependent;
  666. } else {
  667. dep_link = -dep_link - 1;
  668. link_dep_B[dep_link] = reop_not_dependent;
  669. }
  670. // Add this dependent link calculation to the ready list if *both* inputs are clear.
  671. if ((link_dep_A[dep_link] == reop_not_dependent) && (link_dep_B[dep_link] == reop_not_dependent)) {
  672. ready_list[ready_list_tail++] = dep_link;
  673. link_dep_A[dep_link] = link_dep_B[dep_link] = reop_node_complete; // Probably not needed now.
  674. }
  675. link_dep = link_dep->next;
  676. }
  677. }
  678. // Delete the temporary buffers.
  679. memdelete_arr(node_written_at);
  680. memdelete_arr(link_dep_A);
  681. memdelete_arr(link_dep_B);
  682. memdelete_arr(ready_list);
  683. memdelete_arr(link_dep_free_list);
  684. memdelete_arr(link_dep_list_starts);
  685. memdelete_arr(link_buffer);
  686. }
  687. void GodotSoftBody3D::append_link(uint32_t p_node1, uint32_t p_node2) {
  688. if (p_node1 == p_node2) {
  689. return;
  690. }
  691. Node *node1 = &nodes[p_node1];
  692. Node *node2 = &nodes[p_node2];
  693. Link link;
  694. link.n[0] = node1;
  695. link.n[1] = node2;
  696. link.rl = (node1->x - node2->x).length();
  697. links.push_back(link);
  698. }
  699. void GodotSoftBody3D::append_face(uint32_t p_node1, uint32_t p_node2, uint32_t p_node3) {
  700. if (p_node1 == p_node2) {
  701. return;
  702. }
  703. if (p_node1 == p_node3) {
  704. return;
  705. }
  706. if (p_node2 == p_node3) {
  707. return;
  708. }
  709. Node *node1 = &nodes[p_node1];
  710. Node *node2 = &nodes[p_node2];
  711. Node *node3 = &nodes[p_node3];
  712. Face face;
  713. face.n[0] = node1;
  714. face.n[1] = node2;
  715. face.n[2] = node3;
  716. face.index = faces.size();
  717. faces.push_back(face);
  718. }
  719. void GodotSoftBody3D::set_iteration_count(int p_val) {
  720. iteration_count = p_val;
  721. }
  722. void GodotSoftBody3D::set_total_mass(real_t p_val) {
  723. ERR_FAIL_COND(p_val < 0.0);
  724. inv_total_mass = 1.0 / p_val;
  725. real_t mass_factor = total_mass * inv_total_mass;
  726. total_mass = p_val;
  727. uint32_t node_count = nodes.size();
  728. for (uint32_t node_index = 0; node_index < node_count; ++node_index) {
  729. Node &node = nodes[node_index];
  730. node.im *= mass_factor;
  731. }
  732. update_constants();
  733. }
  734. void GodotSoftBody3D::set_collision_margin(real_t p_val) {
  735. collision_margin = p_val;
  736. }
  737. void GodotSoftBody3D::set_linear_stiffness(real_t p_val) {
  738. linear_stiffness = p_val;
  739. }
  740. void GodotSoftBody3D::set_pressure_coefficient(real_t p_val) {
  741. pressure_coefficient = p_val;
  742. }
  743. void GodotSoftBody3D::set_damping_coefficient(real_t p_val) {
  744. damping_coefficient = p_val;
  745. }
  746. void GodotSoftBody3D::set_drag_coefficient(real_t p_val) {
  747. drag_coefficient = p_val;
  748. }
  749. void GodotSoftBody3D::add_velocity(const Vector3 &p_velocity) {
  750. for (Node &node : nodes) {
  751. if (node.im > 0) {
  752. node.v += p_velocity;
  753. }
  754. }
  755. }
  756. void GodotSoftBody3D::apply_forces(const LocalVector<GodotArea3D *> &p_wind_areas) {
  757. if (nodes.is_empty()) {
  758. return;
  759. }
  760. int32_t j;
  761. real_t volume = 0.0;
  762. const Vector3 &org = nodes[0].x;
  763. // Iterate over faces (try not to iterate elsewhere if possible).
  764. for (const Face &face : faces) {
  765. Vector3 wind_force(0, 0, 0);
  766. // Compute volume.
  767. volume += vec3_dot(face.n[0]->x - org, vec3_cross(face.n[1]->x - org, face.n[2]->x - org));
  768. // Compute nodal forces from area winds.
  769. if (!p_wind_areas.is_empty()) {
  770. for (const GodotArea3D *area : p_wind_areas) {
  771. wind_force += _compute_area_windforce(area, &face);
  772. }
  773. for (j = 0; j < 3; j++) {
  774. Node *current_node = face.n[j];
  775. current_node->f += wind_force;
  776. }
  777. }
  778. }
  779. volume /= 6.0;
  780. // Apply nodal pressure forces.
  781. if (pressure_coefficient > CMP_EPSILON) {
  782. real_t ivolumetp = 1.0 / Math::abs(volume) * pressure_coefficient;
  783. for (Node &node : nodes) {
  784. if (node.im > 0) {
  785. node.f += node.n * (node.area * ivolumetp);
  786. }
  787. }
  788. }
  789. }
  790. Vector3 GodotSoftBody3D::_compute_area_windforce(const GodotArea3D *p_area, const Face *p_face) {
  791. real_t wfm = p_area->get_wind_force_magnitude();
  792. real_t waf = p_area->get_wind_attenuation_factor();
  793. const Vector3 &wd = p_area->get_wind_direction();
  794. const Vector3 &ws = p_area->get_wind_source();
  795. real_t projection_on_tri_normal = vec3_dot(p_face->normal, wd);
  796. real_t projection_toward_centroid = vec3_dot(p_face->centroid - ws, wd);
  797. real_t attenuation_over_distance = pow(projection_toward_centroid, -waf);
  798. real_t nodal_force_magnitude = wfm * 0.33333333333 * p_face->ra * projection_on_tri_normal * attenuation_over_distance;
  799. return nodal_force_magnitude * p_face->normal;
  800. }
  801. void GodotSoftBody3D::predict_motion(real_t p_delta) {
  802. const real_t inv_delta = 1.0 / p_delta;
  803. ERR_FAIL_NULL(get_space());
  804. bool gravity_done = false;
  805. Vector3 gravity;
  806. LocalVector<GodotArea3D *> wind_areas;
  807. int ac = areas.size();
  808. if (ac) {
  809. areas.sort();
  810. const AreaCMP *aa = &areas[0];
  811. for (int i = ac - 1; i >= 0; i--) {
  812. if (!gravity_done) {
  813. PhysicsServer3D::AreaSpaceOverrideMode area_gravity_mode = (PhysicsServer3D::AreaSpaceOverrideMode)(int)aa[i].area->get_param(PhysicsServer3D::AREA_PARAM_GRAVITY_OVERRIDE_MODE);
  814. if (area_gravity_mode != PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED) {
  815. Vector3 area_gravity;
  816. aa[i].area->compute_gravity(get_transform().get_origin(), area_gravity);
  817. switch (area_gravity_mode) {
  818. case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE:
  819. case PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: {
  820. gravity += area_gravity;
  821. gravity_done = area_gravity_mode == PhysicsServer3D::AREA_SPACE_OVERRIDE_COMBINE_REPLACE;
  822. } break;
  823. case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE:
  824. case PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: {
  825. gravity = area_gravity;
  826. gravity_done = area_gravity_mode == PhysicsServer3D::AREA_SPACE_OVERRIDE_REPLACE;
  827. } break;
  828. default: {
  829. }
  830. }
  831. }
  832. }
  833. if (aa[i].area->get_wind_force_magnitude() > CMP_EPSILON) {
  834. wind_areas.push_back(aa[i].area);
  835. }
  836. }
  837. }
  838. // Add default gravity and damping from space area.
  839. if (!gravity_done) {
  840. GodotArea3D *default_area = get_space()->get_default_area();
  841. ERR_FAIL_NULL(default_area);
  842. Vector3 default_gravity;
  843. default_area->compute_gravity(get_transform().get_origin(), default_gravity);
  844. gravity += default_gravity;
  845. }
  846. // Apply forces.
  847. add_velocity(gravity * p_delta);
  848. if (pressure_coefficient > CMP_EPSILON || !wind_areas.is_empty()) {
  849. apply_forces(wind_areas);
  850. }
  851. // Avoid soft body from 'exploding' so use some upper threshold of maximum motion
  852. // that a node can travel per frame.
  853. const real_t max_displacement = 1000.0;
  854. real_t clamp_delta_v = max_displacement * inv_delta;
  855. // Integrate.
  856. for (Node &node : nodes) {
  857. node.q = node.x;
  858. Vector3 delta_v = node.f * node.im * p_delta;
  859. for (int c = 0; c < 3; c++) {
  860. delta_v[c] = CLAMP(delta_v[c], -clamp_delta_v, clamp_delta_v);
  861. }
  862. node.v += delta_v;
  863. node.x += node.v * p_delta;
  864. node.f = Vector3();
  865. }
  866. // Bounds and tree update.
  867. update_bounds();
  868. // Node tree update.
  869. for (const Node &node : nodes) {
  870. AABB node_aabb(node.x, Vector3());
  871. node_aabb.expand_to(node.x + node.v * p_delta);
  872. node_aabb.grow_by(collision_margin);
  873. node_tree.update(node.leaf, node_aabb);
  874. }
  875. // Face tree update.
  876. if (!face_tree.is_empty()) {
  877. update_face_tree(p_delta);
  878. }
  879. // Optimize node tree.
  880. node_tree.optimize_incremental(1);
  881. face_tree.optimize_incremental(1);
  882. }
  883. void GodotSoftBody3D::solve_constraints(real_t p_delta) {
  884. const real_t inv_delta = 1.0 / p_delta;
  885. for (Link &link : links) {
  886. link.c3 = link.n[1]->q - link.n[0]->q;
  887. link.c2 = 1 / (link.c3.length_squared() * link.c0);
  888. }
  889. // Solve velocities.
  890. for (Node &node : nodes) {
  891. node.x = node.q + node.v * p_delta;
  892. }
  893. // Solve positions.
  894. for (int isolve = 0; isolve < iteration_count; ++isolve) {
  895. const real_t ti = isolve / (real_t)iteration_count;
  896. solve_links(1.0, ti);
  897. }
  898. const real_t vc = (1.0 - damping_coefficient) * inv_delta;
  899. for (Node &node : nodes) {
  900. node.x += node.bv * p_delta;
  901. node.bv = Vector3();
  902. node.v = (node.x - node.q) * vc;
  903. node.q = node.x;
  904. }
  905. update_normals_and_centroids();
  906. }
  907. void GodotSoftBody3D::solve_links(real_t kst, real_t ti) {
  908. for (Link &link : links) {
  909. if (link.c0 > 0) {
  910. Node &node_a = *link.n[0];
  911. Node &node_b = *link.n[1];
  912. const Vector3 del = node_b.x - node_a.x;
  913. const real_t len = del.length_squared();
  914. if (link.c1 + len > CMP_EPSILON) {
  915. const real_t k = ((link.c1 - len) / (link.c0 * (link.c1 + len))) * kst;
  916. node_a.x -= del * (k * node_a.im);
  917. node_b.x += del * (k * node_b.im);
  918. }
  919. }
  920. }
  921. }
  922. struct AABBQueryResult {
  923. const GodotSoftBody3D *soft_body = nullptr;
  924. void *userdata = nullptr;
  925. GodotSoftBody3D::QueryResultCallback result_callback = nullptr;
  926. _FORCE_INLINE_ bool operator()(void *p_data) {
  927. return result_callback(soft_body->get_node_index(p_data), userdata);
  928. };
  929. };
  930. void GodotSoftBody3D::query_aabb(const AABB &p_aabb, GodotSoftBody3D::QueryResultCallback p_result_callback, void *p_userdata) {
  931. AABBQueryResult query_result;
  932. query_result.soft_body = this;
  933. query_result.result_callback = p_result_callback;
  934. query_result.userdata = p_userdata;
  935. node_tree.aabb_query(p_aabb, query_result);
  936. }
  937. struct RayQueryResult {
  938. const GodotSoftBody3D *soft_body = nullptr;
  939. void *userdata = nullptr;
  940. GodotSoftBody3D::QueryResultCallback result_callback = nullptr;
  941. _FORCE_INLINE_ bool operator()(void *p_data) {
  942. return result_callback(soft_body->get_face_index(p_data), userdata);
  943. };
  944. };
  945. void GodotSoftBody3D::query_ray(const Vector3 &p_from, const Vector3 &p_to, GodotSoftBody3D::QueryResultCallback p_result_callback, void *p_userdata) {
  946. if (face_tree.is_empty()) {
  947. initialize_face_tree();
  948. }
  949. RayQueryResult query_result;
  950. query_result.soft_body = this;
  951. query_result.result_callback = p_result_callback;
  952. query_result.userdata = p_userdata;
  953. face_tree.ray_query(p_from, p_to, query_result);
  954. }
  955. void GodotSoftBody3D::initialize_face_tree() {
  956. face_tree.clear();
  957. for (Face &face : faces) {
  958. AABB face_aabb;
  959. face_aabb.position = face.n[0]->x;
  960. face_aabb.expand_to(face.n[1]->x);
  961. face_aabb.expand_to(face.n[2]->x);
  962. face_aabb.grow_by(collision_margin);
  963. face.leaf = face_tree.insert(face_aabb, &face);
  964. }
  965. }
  966. void GodotSoftBody3D::update_face_tree(real_t p_delta) {
  967. for (const Face &face : faces) {
  968. AABB face_aabb;
  969. const Node *node0 = face.n[0];
  970. face_aabb.position = node0->x;
  971. face_aabb.expand_to(node0->x + node0->v * p_delta);
  972. const Node *node1 = face.n[1];
  973. face_aabb.expand_to(node1->x);
  974. face_aabb.expand_to(node1->x + node1->v * p_delta);
  975. const Node *node2 = face.n[2];
  976. face_aabb.expand_to(node2->x);
  977. face_aabb.expand_to(node2->x + node2->v * p_delta);
  978. face_aabb.grow_by(collision_margin);
  979. face_tree.update(face.leaf, face_aabb);
  980. }
  981. }
  982. void GodotSoftBody3D::initialize_shape(bool p_force_move) {
  983. if (get_shape_count() == 0) {
  984. GodotSoftBodyShape3D *soft_body_shape = memnew(GodotSoftBodyShape3D(this));
  985. add_shape(soft_body_shape);
  986. } else if (p_force_move) {
  987. GodotSoftBodyShape3D *soft_body_shape = static_cast<GodotSoftBodyShape3D *>(get_shape(0));
  988. soft_body_shape->update_bounds();
  989. }
  990. }
  991. void GodotSoftBody3D::deinitialize_shape() {
  992. if (get_shape_count() > 0) {
  993. GodotShape3D *shape = get_shape(0);
  994. remove_shape(shape);
  995. memdelete(shape);
  996. }
  997. }
  998. void GodotSoftBody3D::destroy() {
  999. soft_mesh = RID();
  1000. map_visual_to_physics.clear();
  1001. node_tree.clear();
  1002. face_tree.clear();
  1003. nodes.clear();
  1004. links.clear();
  1005. faces.clear();
  1006. bounds = AABB();
  1007. deinitialize_shape();
  1008. }
  1009. void GodotSoftBodyShape3D::update_bounds() {
  1010. ERR_FAIL_NULL(soft_body);
  1011. AABB collision_aabb = soft_body->get_bounds();
  1012. collision_aabb.grow_by(soft_body->get_collision_margin());
  1013. configure(collision_aabb);
  1014. }
  1015. GodotSoftBodyShape3D::GodotSoftBodyShape3D(GodotSoftBody3D *p_soft_body) {
  1016. soft_body = p_soft_body;
  1017. update_bounds();
  1018. }
  1019. struct _SoftBodyIntersectSegmentInfo {
  1020. const GodotSoftBody3D *soft_body = nullptr;
  1021. Vector3 from;
  1022. Vector3 dir;
  1023. Vector3 hit_position;
  1024. uint32_t hit_face_index = -1;
  1025. real_t hit_dist_sq = INFINITY;
  1026. static bool process_hit(uint32_t p_face_index, void *p_userdata) {
  1027. _SoftBodyIntersectSegmentInfo &query_info = *(static_cast<_SoftBodyIntersectSegmentInfo *>(p_userdata));
  1028. Vector3 points[3];
  1029. query_info.soft_body->get_face_points(p_face_index, points[0], points[1], points[2]);
  1030. Vector3 result;
  1031. if (Geometry3D::ray_intersects_triangle(query_info.from, query_info.dir, points[0], points[1], points[2], &result)) {
  1032. real_t dist_sq = query_info.from.distance_squared_to(result);
  1033. if (dist_sq < query_info.hit_dist_sq) {
  1034. query_info.hit_dist_sq = dist_sq;
  1035. query_info.hit_position = result;
  1036. query_info.hit_face_index = p_face_index;
  1037. }
  1038. }
  1039. // Continue with the query.
  1040. return false;
  1041. }
  1042. };
  1043. bool GodotSoftBodyShape3D::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal, int &r_face_index, bool p_hit_back_faces) const {
  1044. _SoftBodyIntersectSegmentInfo query_info;
  1045. query_info.soft_body = soft_body;
  1046. query_info.from = p_begin;
  1047. query_info.dir = (p_end - p_begin).normalized();
  1048. soft_body->query_ray(p_begin, p_end, _SoftBodyIntersectSegmentInfo::process_hit, &query_info);
  1049. if (query_info.hit_dist_sq != INFINITY) {
  1050. r_result = query_info.hit_position;
  1051. r_normal = soft_body->get_face_normal(query_info.hit_face_index);
  1052. return true;
  1053. }
  1054. return false;
  1055. }
  1056. bool GodotSoftBodyShape3D::intersect_point(const Vector3 &p_point) const {
  1057. return false;
  1058. }
  1059. Vector3 GodotSoftBodyShape3D::get_closest_point_to(const Vector3 &p_point) const {
  1060. ERR_FAIL_V_MSG(Vector3(), "Get closest point is not supported for soft bodies.");
  1061. }