space_sw.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. /*************************************************************************/
  2. /* space_sw.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
  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 "space_sw.h"
  31. #include "collision_solver_sw.h"
  32. #include "physics_server_sw.h"
  33. #include "project_settings.h"
  34. _FORCE_INLINE_ static bool _match_object_type_query(CollisionObjectSW *p_object, uint32_t p_collision_mask, uint32_t p_type_mask) {
  35. if ((p_object->get_collision_layer() & p_collision_mask) == 0)
  36. return false;
  37. if (p_object->get_type() == CollisionObjectSW::TYPE_AREA)
  38. return p_type_mask & PhysicsDirectSpaceState::TYPE_MASK_AREA;
  39. BodySW *body = static_cast<BodySW *>(p_object);
  40. return (1 << body->get_mode()) & p_type_mask;
  41. }
  42. int PhysicsDirectSpaceStateSW::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, uint32_t p_object_type_mask) {
  43. ERR_FAIL_COND_V(space->locked, false);
  44. int amount = space->broadphase->cull_point(p_point, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  45. int cc = 0;
  46. //Transform ai = p_xform.affine_inverse();
  47. for (int i = 0; i < amount; i++) {
  48. if (cc >= p_result_max)
  49. break;
  50. if (!_match_object_type_query(space->intersection_query_results[i], p_collision_mask, p_object_type_mask))
  51. continue;
  52. //area can't be picked by ray (default)
  53. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  54. continue;
  55. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  56. int shape_idx = space->intersection_query_subindex_results[i];
  57. Transform inv_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  58. inv_xform.affine_invert();
  59. if (!col_obj->get_shape(shape_idx)->intersect_point(inv_xform.xform(p_point)))
  60. continue;
  61. r_results[cc].collider_id = col_obj->get_instance_id();
  62. if (r_results[cc].collider_id != 0)
  63. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  64. else
  65. r_results[cc].collider = NULL;
  66. r_results[cc].rid = col_obj->get_self();
  67. r_results[cc].shape = shape_idx;
  68. cc++;
  69. }
  70. return cc;
  71. }
  72. bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, uint32_t p_object_type_mask, bool p_pick_ray) {
  73. ERR_FAIL_COND_V(space->locked, false);
  74. Vector3 begin, end;
  75. Vector3 normal;
  76. begin = p_from;
  77. end = p_to;
  78. normal = (end - begin).normalized();
  79. int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  80. //todo, create another array tha references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision
  81. bool collided = false;
  82. Vector3 res_point, res_normal;
  83. int res_shape;
  84. const CollisionObjectSW *res_obj;
  85. real_t min_d = 1e10;
  86. for (int i = 0; i < amount; i++) {
  87. if (!_match_object_type_query(space->intersection_query_results[i], p_collision_mask, p_object_type_mask))
  88. continue;
  89. if (p_pick_ray && !(static_cast<CollisionObjectSW *>(space->intersection_query_results[i])->is_ray_pickable()))
  90. continue;
  91. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  92. continue;
  93. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  94. int shape_idx = space->intersection_query_subindex_results[i];
  95. Transform inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
  96. Vector3 local_from = inv_xform.xform(begin);
  97. Vector3 local_to = inv_xform.xform(end);
  98. const ShapeSW *shape = col_obj->get_shape(shape_idx);
  99. Vector3 shape_point, shape_normal;
  100. if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
  101. Transform xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  102. shape_point = xform.xform(shape_point);
  103. real_t ld = normal.dot(shape_point);
  104. if (ld < min_d) {
  105. min_d = ld;
  106. res_point = shape_point;
  107. res_normal = inv_xform.basis.xform_inv(shape_normal).normalized();
  108. res_shape = shape_idx;
  109. res_obj = col_obj;
  110. collided = true;
  111. }
  112. }
  113. }
  114. if (!collided)
  115. return false;
  116. r_result.collider_id = res_obj->get_instance_id();
  117. if (r_result.collider_id != 0)
  118. r_result.collider = ObjectDB::get_instance(r_result.collider_id);
  119. else
  120. r_result.collider = NULL;
  121. r_result.normal = res_normal;
  122. r_result.position = res_point;
  123. r_result.rid = res_obj->get_self();
  124. r_result.shape = res_shape;
  125. return true;
  126. }
  127. int PhysicsDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, uint32_t p_object_type_mask) {
  128. if (p_result_max <= 0)
  129. return 0;
  130. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  131. ERR_FAIL_COND_V(!shape, 0);
  132. Rect3 aabb = p_xform.xform(shape->get_aabb());
  133. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  134. int cc = 0;
  135. //Transform ai = p_xform.affine_inverse();
  136. for (int i = 0; i < amount; i++) {
  137. if (cc >= p_result_max)
  138. break;
  139. if (!_match_object_type_query(space->intersection_query_results[i], p_collision_mask, p_object_type_mask))
  140. continue;
  141. //area can't be picked by ray (default)
  142. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  143. continue;
  144. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  145. int shape_idx = space->intersection_query_subindex_results[i];
  146. if (!CollisionSolverSW::solve_static(shape, p_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), NULL, NULL, NULL, p_margin, 0))
  147. continue;
  148. if (r_results) {
  149. r_results[cc].collider_id = col_obj->get_instance_id();
  150. if (r_results[cc].collider_id != 0)
  151. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  152. else
  153. r_results[cc].collider = NULL;
  154. r_results[cc].rid = col_obj->get_self();
  155. r_results[cc].shape = shape_idx;
  156. }
  157. cc++;
  158. }
  159. return cc;
  160. }
  161. bool PhysicsDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, uint32_t p_object_type_mask, ShapeRestInfo *r_info) {
  162. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  163. ERR_FAIL_COND_V(!shape, false);
  164. Rect3 aabb = p_xform.xform(shape->get_aabb());
  165. aabb = aabb.merge(Rect3(aabb.position + p_motion, aabb.size)); //motion
  166. aabb = aabb.grow(p_margin);
  167. /*
  168. if (p_motion!=Vector3())
  169. print_line(p_motion);
  170. */
  171. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  172. real_t best_safe = 1;
  173. real_t best_unsafe = 1;
  174. Transform xform_inv = p_xform.affine_inverse();
  175. MotionShapeSW mshape;
  176. mshape.shape = shape;
  177. mshape.motion = xform_inv.basis.xform(p_motion);
  178. bool best_first = true;
  179. Vector3 closest_A, closest_B;
  180. for (int i = 0; i < amount; i++) {
  181. if (!_match_object_type_query(space->intersection_query_results[i], p_collision_mask, p_object_type_mask))
  182. continue;
  183. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  184. continue; //ignore excluded
  185. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  186. int shape_idx = space->intersection_query_subindex_results[i];
  187. Vector3 point_A, point_B;
  188. Vector3 sep_axis = p_motion.normalized();
  189. Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  190. //test initial overlap, does it collide if going all the way?
  191. if (CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
  192. //print_line("failed motion cast (no collision)");
  193. continue;
  194. }
  195. //test initial overlap
  196. sep_axis = p_motion.normalized();
  197. if (!CollisionSolverSW::solve_distance(shape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
  198. //print_line("failed motion cast (no collision)");
  199. return false;
  200. }
  201. //just do kinematic solving
  202. real_t low = 0;
  203. real_t hi = 1;
  204. Vector3 mnormal = p_motion.normalized();
  205. for (int i = 0; i < 8; i++) { //steps should be customizable..
  206. real_t ofs = (low + hi) * 0.5;
  207. Vector3 sep = mnormal; //important optimization for this to work fast enough
  208. mshape.motion = xform_inv.basis.xform(p_motion * ofs);
  209. Vector3 lA, lB;
  210. bool collided = !CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, lA, lB, aabb, &sep);
  211. if (collided) {
  212. //print_line(itos(i)+": "+rtos(ofs));
  213. hi = ofs;
  214. } else {
  215. point_A = lA;
  216. point_B = lB;
  217. low = ofs;
  218. }
  219. }
  220. if (low < best_safe) {
  221. best_first = true; //force reset
  222. best_safe = low;
  223. best_unsafe = hi;
  224. }
  225. if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low <= best_safe))) {
  226. closest_A = point_A;
  227. closest_B = point_B;
  228. r_info->collider_id = col_obj->get_instance_id();
  229. r_info->rid = col_obj->get_self();
  230. r_info->shape = shape_idx;
  231. r_info->point = closest_B;
  232. r_info->normal = (closest_A - closest_B).normalized();
  233. best_first = false;
  234. if (col_obj->get_type() == CollisionObjectSW::TYPE_BODY) {
  235. const BodySW *body = static_cast<const BodySW *>(col_obj);
  236. r_info->linear_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B);
  237. }
  238. }
  239. }
  240. p_closest_safe = best_safe;
  241. p_closest_unsafe = best_unsafe;
  242. return true;
  243. }
  244. bool PhysicsDirectSpaceStateSW::collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, uint32_t p_object_type_mask) {
  245. if (p_result_max <= 0)
  246. return 0;
  247. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  248. ERR_FAIL_COND_V(!shape, 0);
  249. Rect3 aabb = p_shape_xform.xform(shape->get_aabb());
  250. aabb = aabb.grow(p_margin);
  251. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  252. bool collided = false;
  253. r_result_count = 0;
  254. PhysicsServerSW::CollCbkData cbk;
  255. cbk.max = p_result_max;
  256. cbk.amount = 0;
  257. cbk.ptr = r_results;
  258. CollisionSolverSW::CallbackResult cbkres = NULL;
  259. PhysicsServerSW::CollCbkData *cbkptr = NULL;
  260. if (p_result_max > 0) {
  261. cbkptr = &cbk;
  262. cbkres = PhysicsServerSW::_shape_col_cbk;
  263. }
  264. for (int i = 0; i < amount; i++) {
  265. if (!_match_object_type_query(space->intersection_query_results[i], p_collision_mask, p_object_type_mask))
  266. continue;
  267. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  268. int shape_idx = space->intersection_query_subindex_results[i];
  269. if (p_exclude.has(col_obj->get_self())) {
  270. continue;
  271. }
  272. //print_line("AGAINST: "+itos(col_obj->get_self().get_id())+":"+itos(shape_idx));
  273. //print_line("THE ABBB: "+(col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).xform(col_obj->get_shape(shape_idx)->get_aabb()));
  274. if (CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, NULL, p_margin)) {
  275. collided = true;
  276. }
  277. }
  278. r_result_count = cbk.amount;
  279. return collided;
  280. }
  281. struct _RestCallbackData {
  282. const CollisionObjectSW *object;
  283. const CollisionObjectSW *best_object;
  284. int shape;
  285. int best_shape;
  286. Vector3 best_contact;
  287. Vector3 best_normal;
  288. real_t best_len;
  289. };
  290. static void _rest_cbk_result(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) {
  291. _RestCallbackData *rd = (_RestCallbackData *)p_userdata;
  292. Vector3 contact_rel = p_point_B - p_point_A;
  293. real_t len = contact_rel.length();
  294. if (len <= rd->best_len)
  295. return;
  296. rd->best_len = len;
  297. rd->best_contact = p_point_B;
  298. rd->best_normal = contact_rel / len;
  299. rd->best_object = rd->object;
  300. rd->best_shape = rd->shape;
  301. }
  302. bool PhysicsDirectSpaceStateSW::rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, uint32_t p_object_type_mask) {
  303. ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
  304. ERR_FAIL_COND_V(!shape, 0);
  305. Rect3 aabb = p_shape_xform.xform(shape->get_aabb());
  306. aabb = aabb.grow(p_margin);
  307. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  308. _RestCallbackData rcd;
  309. rcd.best_len = 0;
  310. rcd.best_object = NULL;
  311. rcd.best_shape = 0;
  312. for (int i = 0; i < amount; i++) {
  313. if (!_match_object_type_query(space->intersection_query_results[i], p_collision_mask, p_object_type_mask))
  314. continue;
  315. const CollisionObjectSW *col_obj = space->intersection_query_results[i];
  316. int shape_idx = space->intersection_query_subindex_results[i];
  317. if (p_exclude.has(col_obj->get_self()))
  318. continue;
  319. rcd.object = col_obj;
  320. rcd.shape = shape_idx;
  321. bool sc = CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, NULL, p_margin);
  322. if (!sc)
  323. continue;
  324. }
  325. if (rcd.best_len == 0)
  326. return false;
  327. r_info->collider_id = rcd.best_object->get_instance_id();
  328. r_info->shape = rcd.best_shape;
  329. r_info->normal = rcd.best_normal;
  330. r_info->point = rcd.best_contact;
  331. r_info->rid = rcd.best_object->get_self();
  332. if (rcd.best_object->get_type() == CollisionObjectSW::TYPE_BODY) {
  333. const BodySW *body = static_cast<const BodySW *>(rcd.best_object);
  334. r_info->linear_velocity = body->get_linear_velocity() +
  335. (body->get_angular_velocity()).cross(body->get_transform().origin - rcd.best_contact); // * mPos);
  336. } else {
  337. r_info->linear_velocity = Vector3();
  338. }
  339. return true;
  340. }
  341. Vector3 PhysicsDirectSpaceStateSW::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const {
  342. CollisionObjectSW *obj = PhysicsServerSW::singleton->area_owner.getornull(p_object);
  343. if (!obj) {
  344. obj = PhysicsServerSW::singleton->body_owner.getornull(p_object);
  345. }
  346. ERR_FAIL_COND_V(!obj, Vector3());
  347. ERR_FAIL_COND_V(obj->get_space() != space, Vector3());
  348. float min_distance = 1e20;
  349. Vector3 min_point;
  350. bool shapes_found = false;
  351. for (int i = 0; i < obj->get_shape_count(); i++) {
  352. if (obj->is_shape_set_as_disabled(i))
  353. continue;
  354. Transform shape_xform = obj->get_transform() * obj->get_shape_transform(i);
  355. ShapeSW *shape = obj->get_shape(i);
  356. Vector3 point = shape->get_closest_point_to(shape_xform.affine_inverse().xform(p_point));
  357. point = shape_xform.xform(point);
  358. float dist = point.distance_to(p_point);
  359. if (dist < min_distance) {
  360. min_distance = dist;
  361. min_point = point;
  362. }
  363. shapes_found = true;
  364. }
  365. if (!shapes_found) {
  366. return obj->get_transform().origin; //no shapes found, use distance to origin.
  367. } else {
  368. return min_point;
  369. }
  370. }
  371. PhysicsDirectSpaceStateSW::PhysicsDirectSpaceStateSW() {
  372. space = NULL;
  373. }
  374. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  375. int SpaceSW::_cull_aabb_for_body(BodySW *p_body, const Rect3 &p_aabb) {
  376. int amount = broadphase->cull_aabb(p_aabb, intersection_query_results, INTERSECTION_QUERY_MAX, intersection_query_subindex_results);
  377. for (int i = 0; i < amount; i++) {
  378. bool keep = true;
  379. if (intersection_query_results[i] == p_body)
  380. keep = false;
  381. else if (intersection_query_results[i]->get_type() == CollisionObjectSW::TYPE_AREA)
  382. keep = false;
  383. else if ((static_cast<BodySW *>(intersection_query_results[i])->test_collision_mask(p_body)) == 0)
  384. keep = false;
  385. else if (static_cast<BodySW *>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self()))
  386. keep = false;
  387. else if (static_cast<BodySW *>(intersection_query_results[i])->is_shape_set_as_disabled(intersection_query_subindex_results[i]))
  388. keep = false;
  389. if (!keep) {
  390. if (i < amount - 1) {
  391. SWAP(intersection_query_results[i], intersection_query_results[amount - 1]);
  392. SWAP(intersection_query_subindex_results[i], intersection_query_subindex_results[amount - 1]);
  393. }
  394. amount--;
  395. i--;
  396. }
  397. }
  398. return amount;
  399. }
  400. bool SpaceSW::test_body_motion(BodySW *p_body, const Transform &p_from, const Vector3 &p_motion, real_t p_margin, PhysicsServer::MotionResult *r_result) {
  401. //give me back regular physics engine logic
  402. //this is madness
  403. //and most people using this function will think
  404. //what it does is simpler than using physics
  405. //this took about a week to get right..
  406. //but is it right? who knows at this point..
  407. if (r_result) {
  408. r_result->collider_id = 0;
  409. r_result->collider_shape = 0;
  410. }
  411. Rect3 body_aabb;
  412. for (int i = 0; i < p_body->get_shape_count(); i++) {
  413. if (i == 0)
  414. body_aabb = p_body->get_shape_aabb(i);
  415. else
  416. body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
  417. }
  418. // Undo the currently transform the physics server is aware of and apply the provided one
  419. body_aabb = p_from.xform(p_body->get_inv_transform().xform(body_aabb));
  420. body_aabb = body_aabb.grow(p_margin);
  421. Transform body_transform = p_from;
  422. {
  423. //STEP 1, FREE BODY IF STUCK
  424. const int max_results = 32;
  425. int recover_attempts = 4;
  426. Vector3 sr[max_results * 2];
  427. do {
  428. PhysicsServerSW::CollCbkData cbk;
  429. cbk.max = max_results;
  430. cbk.amount = 0;
  431. cbk.ptr = sr;
  432. PhysicsServerSW::CollCbkData *cbkptr = &cbk;
  433. CollisionSolverSW::CallbackResult cbkres = PhysicsServerSW::_shape_col_cbk;
  434. bool collided = false;
  435. int amount = _cull_aabb_for_body(p_body, body_aabb);
  436. for (int j = 0; j < p_body->get_shape_count(); j++) {
  437. if (p_body->is_shape_set_as_disabled(j))
  438. continue;
  439. Transform body_shape_xform = body_transform * p_body->get_shape_transform(j);
  440. ShapeSW *body_shape = p_body->get_shape(j);
  441. for (int i = 0; i < amount; i++) {
  442. const CollisionObjectSW *col_obj = intersection_query_results[i];
  443. int shape_idx = intersection_query_subindex_results[i];
  444. if (CollisionSolverSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, NULL, p_margin)) {
  445. collided = cbk.amount > 0;
  446. }
  447. }
  448. }
  449. if (!collided) {
  450. break;
  451. }
  452. Vector3 recover_motion;
  453. for (int i = 0; i < cbk.amount; i++) {
  454. Vector3 a = sr[i * 2 + 0];
  455. Vector3 b = sr[i * 2 + 1];
  456. recover_motion += (b - a) * 0.4;
  457. }
  458. if (recover_motion == Vector3()) {
  459. collided = false;
  460. break;
  461. }
  462. body_transform.origin += recover_motion;
  463. body_aabb.position += recover_motion;
  464. recover_attempts--;
  465. } while (recover_attempts);
  466. }
  467. real_t safe = 1.0;
  468. real_t unsafe = 1.0;
  469. int best_shape = -1;
  470. {
  471. // STEP 2 ATTEMPT MOTION
  472. Rect3 motion_aabb = body_aabb;
  473. motion_aabb.position += p_motion;
  474. motion_aabb = motion_aabb.merge(body_aabb);
  475. int amount = _cull_aabb_for_body(p_body, motion_aabb);
  476. for (int j = 0; j < p_body->get_shape_count(); j++) {
  477. if (p_body->is_shape_set_as_disabled(j))
  478. continue;
  479. Transform body_shape_xform = body_transform * p_body->get_shape_transform(j);
  480. ShapeSW *body_shape = p_body->get_shape(j);
  481. Transform body_shape_xform_inv = body_shape_xform.affine_inverse();
  482. MotionShapeSW mshape;
  483. mshape.shape = body_shape;
  484. mshape.motion = body_shape_xform_inv.basis.xform(p_motion);
  485. bool stuck = false;
  486. real_t best_safe = 1;
  487. real_t best_unsafe = 1;
  488. for (int i = 0; i < amount; i++) {
  489. const CollisionObjectSW *col_obj = intersection_query_results[i];
  490. int shape_idx = intersection_query_subindex_results[i];
  491. //test initial overlap, does it collide if going all the way?
  492. Vector3 point_A, point_B;
  493. Vector3 sep_axis = p_motion.normalized();
  494. Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  495. //test initial overlap, does it collide if going all the way?
  496. if (CollisionSolverSW::solve_distance(&mshape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, motion_aabb, &sep_axis)) {
  497. //print_line("failed motion cast (no collision)");
  498. continue;
  499. }
  500. sep_axis = p_motion.normalized();
  501. if (!CollisionSolverSW::solve_distance(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, motion_aabb, &sep_axis)) {
  502. //print_line("failed motion cast (no collision)");
  503. stuck = true;
  504. break;
  505. }
  506. //just do kinematic solving
  507. real_t low = 0;
  508. real_t hi = 1;
  509. Vector3 mnormal = p_motion.normalized();
  510. for (int i = 0; i < 8; i++) { //steps should be customizable..
  511. real_t ofs = (low + hi) * 0.5;
  512. Vector3 sep = mnormal; //important optimization for this to work fast enough
  513. mshape.motion = body_shape_xform_inv.basis.xform(p_motion * ofs);
  514. Vector3 lA, lB;
  515. bool collided = !CollisionSolverSW::solve_distance(&mshape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj_xform, lA, lB, motion_aabb, &sep);
  516. if (collided) {
  517. //print_line(itos(i)+": "+rtos(ofs));
  518. hi = ofs;
  519. } else {
  520. point_A = lA;
  521. point_B = lB;
  522. low = ofs;
  523. }
  524. }
  525. if (low < best_safe) {
  526. best_safe = low;
  527. best_unsafe = hi;
  528. }
  529. }
  530. if (stuck) {
  531. safe = 0;
  532. unsafe = 0;
  533. best_shape = j; //sadly it's the best
  534. break;
  535. }
  536. if (best_safe == 1.0) {
  537. continue;
  538. }
  539. if (best_safe < safe) {
  540. safe = best_safe;
  541. unsafe = best_unsafe;
  542. best_shape = j;
  543. }
  544. }
  545. }
  546. bool collided = false;
  547. if (safe >= 1) {
  548. //not collided
  549. collided = false;
  550. if (r_result) {
  551. r_result->motion = p_motion;
  552. r_result->remainder = Vector3();
  553. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  554. }
  555. } else {
  556. //it collided, let's get the rest info in unsafe advance
  557. Transform ugt = body_transform;
  558. ugt.origin += p_motion * unsafe;
  559. _RestCallbackData rcd;
  560. rcd.best_len = 0;
  561. rcd.best_object = NULL;
  562. rcd.best_shape = 0;
  563. Transform body_shape_xform = ugt * p_body->get_shape_transform(best_shape);
  564. ShapeSW *body_shape = p_body->get_shape(best_shape);
  565. body_aabb.position += p_motion * unsafe;
  566. int amount = _cull_aabb_for_body(p_body, body_aabb);
  567. for (int i = 0; i < amount; i++) {
  568. const CollisionObjectSW *col_obj = intersection_query_results[i];
  569. int shape_idx = intersection_query_subindex_results[i];
  570. rcd.object = col_obj;
  571. rcd.shape = shape_idx;
  572. bool sc = CollisionSolverSW::solve_static(body_shape, body_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, NULL, p_margin);
  573. if (!sc)
  574. continue;
  575. }
  576. if (rcd.best_len != 0) {
  577. if (r_result) {
  578. r_result->collider = rcd.best_object->get_self();
  579. r_result->collider_id = rcd.best_object->get_instance_id();
  580. r_result->collider_shape = rcd.best_shape;
  581. r_result->collision_local_shape = best_shape;
  582. r_result->collision_normal = rcd.best_normal;
  583. r_result->collision_point = rcd.best_contact;
  584. //r_result->collider_metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
  585. const BodySW *body = static_cast<const BodySW *>(rcd.best_object);
  586. //Vector3 rel_vec = r_result->collision_point - body->get_transform().get_origin();
  587. // r_result->collider_velocity = Vector3(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  588. r_result->collider_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - rcd.best_contact); // * mPos);
  589. r_result->motion = safe * p_motion;
  590. r_result->remainder = p_motion - safe * p_motion;
  591. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  592. }
  593. collided = true;
  594. } else {
  595. if (r_result) {
  596. r_result->motion = p_motion;
  597. r_result->remainder = Vector3();
  598. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  599. }
  600. collided = false;
  601. }
  602. }
  603. return collided;
  604. }
  605. void *SpaceSW::_broadphase_pair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_self) {
  606. CollisionObjectSW::Type type_A = A->get_type();
  607. CollisionObjectSW::Type type_B = B->get_type();
  608. if (type_A > type_B) {
  609. SWAP(A, B);
  610. SWAP(p_subindex_A, p_subindex_B);
  611. SWAP(type_A, type_B);
  612. }
  613. SpaceSW *self = (SpaceSW *)p_self;
  614. self->collision_pairs++;
  615. if (type_A == CollisionObjectSW::TYPE_AREA) {
  616. AreaSW *area = static_cast<AreaSW *>(A);
  617. if (type_B == CollisionObjectSW::TYPE_AREA) {
  618. AreaSW *area_b = static_cast<AreaSW *>(B);
  619. Area2PairSW *area2_pair = memnew(Area2PairSW(area_b, p_subindex_B, area, p_subindex_A));
  620. return area2_pair;
  621. } else {
  622. BodySW *body = static_cast<BodySW *>(B);
  623. AreaPairSW *area_pair = memnew(AreaPairSW(body, p_subindex_B, area, p_subindex_A));
  624. return area_pair;
  625. }
  626. } else {
  627. BodyPairSW *b = memnew(BodyPairSW((BodySW *)A, p_subindex_A, (BodySW *)B, p_subindex_B));
  628. return b;
  629. }
  630. return NULL;
  631. }
  632. void SpaceSW::_broadphase_unpair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_self) {
  633. SpaceSW *self = (SpaceSW *)p_self;
  634. self->collision_pairs--;
  635. ConstraintSW *c = (ConstraintSW *)p_data;
  636. memdelete(c);
  637. }
  638. const SelfList<BodySW>::List &SpaceSW::get_active_body_list() const {
  639. return active_list;
  640. }
  641. void SpaceSW::body_add_to_active_list(SelfList<BodySW> *p_body) {
  642. active_list.add(p_body);
  643. }
  644. void SpaceSW::body_remove_from_active_list(SelfList<BodySW> *p_body) {
  645. active_list.remove(p_body);
  646. }
  647. void SpaceSW::body_add_to_inertia_update_list(SelfList<BodySW> *p_body) {
  648. inertia_update_list.add(p_body);
  649. }
  650. void SpaceSW::body_remove_from_inertia_update_list(SelfList<BodySW> *p_body) {
  651. inertia_update_list.remove(p_body);
  652. }
  653. BroadPhaseSW *SpaceSW::get_broadphase() {
  654. return broadphase;
  655. }
  656. void SpaceSW::add_object(CollisionObjectSW *p_object) {
  657. ERR_FAIL_COND(objects.has(p_object));
  658. objects.insert(p_object);
  659. }
  660. void SpaceSW::remove_object(CollisionObjectSW *p_object) {
  661. ERR_FAIL_COND(!objects.has(p_object));
  662. objects.erase(p_object);
  663. }
  664. const Set<CollisionObjectSW *> &SpaceSW::get_objects() const {
  665. return objects;
  666. }
  667. void SpaceSW::body_add_to_state_query_list(SelfList<BodySW> *p_body) {
  668. state_query_list.add(p_body);
  669. }
  670. void SpaceSW::body_remove_from_state_query_list(SelfList<BodySW> *p_body) {
  671. state_query_list.remove(p_body);
  672. }
  673. void SpaceSW::area_add_to_monitor_query_list(SelfList<AreaSW> *p_area) {
  674. monitor_query_list.add(p_area);
  675. }
  676. void SpaceSW::area_remove_from_monitor_query_list(SelfList<AreaSW> *p_area) {
  677. monitor_query_list.remove(p_area);
  678. }
  679. void SpaceSW::area_add_to_moved_list(SelfList<AreaSW> *p_area) {
  680. area_moved_list.add(p_area);
  681. }
  682. void SpaceSW::area_remove_from_moved_list(SelfList<AreaSW> *p_area) {
  683. area_moved_list.remove(p_area);
  684. }
  685. const SelfList<AreaSW>::List &SpaceSW::get_moved_area_list() const {
  686. return area_moved_list;
  687. }
  688. void SpaceSW::call_queries() {
  689. while (state_query_list.first()) {
  690. BodySW *b = state_query_list.first()->self();
  691. b->call_queries();
  692. state_query_list.remove(state_query_list.first());
  693. }
  694. while (monitor_query_list.first()) {
  695. AreaSW *a = monitor_query_list.first()->self();
  696. a->call_queries();
  697. monitor_query_list.remove(monitor_query_list.first());
  698. }
  699. }
  700. void SpaceSW::setup() {
  701. contact_debug_count = 0;
  702. while (inertia_update_list.first()) {
  703. inertia_update_list.first()->self()->update_inertias();
  704. inertia_update_list.remove(inertia_update_list.first());
  705. }
  706. }
  707. void SpaceSW::update() {
  708. broadphase->update();
  709. }
  710. void SpaceSW::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
  711. switch (p_param) {
  712. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break;
  713. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break;
  714. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break;
  715. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: body_linear_velocity_sleep_threshold = p_value; break;
  716. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: body_angular_velocity_sleep_threshold = p_value; break;
  717. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break;
  718. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: body_angular_velocity_damp_ratio = p_value; break;
  719. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break;
  720. }
  721. }
  722. real_t SpaceSW::get_param(PhysicsServer::SpaceParameter p_param) const {
  723. switch (p_param) {
  724. case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius;
  725. case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation;
  726. case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: return contact_max_allowed_penetration;
  727. case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: return body_linear_velocity_sleep_threshold;
  728. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: return body_angular_velocity_sleep_threshold;
  729. case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: return body_time_to_sleep;
  730. case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: return body_angular_velocity_damp_ratio;
  731. case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: return constraint_bias;
  732. }
  733. return 0;
  734. }
  735. void SpaceSW::lock() {
  736. locked = true;
  737. }
  738. void SpaceSW::unlock() {
  739. locked = false;
  740. }
  741. bool SpaceSW::is_locked() const {
  742. return locked;
  743. }
  744. PhysicsDirectSpaceStateSW *SpaceSW::get_direct_state() {
  745. return direct_access;
  746. }
  747. SpaceSW::SpaceSW() {
  748. collision_pairs = 0;
  749. active_objects = 0;
  750. island_count = 0;
  751. contact_debug_count = 0;
  752. locked = false;
  753. contact_recycle_radius = 0.01;
  754. contact_max_separation = 0.05;
  755. contact_max_allowed_penetration = 0.01;
  756. constraint_bias = 0.01;
  757. body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_linear", 0.1);
  758. body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI));
  759. body_time_to_sleep = GLOBAL_DEF("physics/3d/time_before_sleep", 0.5);
  760. body_angular_velocity_damp_ratio = 10;
  761. broadphase = BroadPhaseSW::create_func();
  762. broadphase->set_pair_callback(_broadphase_pair, this);
  763. broadphase->set_unpair_callback(_broadphase_unpair, this);
  764. area = NULL;
  765. direct_access = memnew(PhysicsDirectSpaceStateSW);
  766. direct_access->space = this;
  767. for (int i = 0; i < ELAPSED_TIME_MAX; i++)
  768. elapsed_time[i] = 0;
  769. }
  770. SpaceSW::~SpaceSW() {
  771. memdelete(broadphase);
  772. memdelete(direct_access);
  773. }