space_2d_sw.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. /*************************************************************************/
  2. /* space_2d_sw.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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_2d_sw.h"
  31. #include "collision_solver_2d_sw.h"
  32. #include "core/os/os.h"
  33. #include "core/pair.h"
  34. #include "physics_2d_server_sw.h"
  35. _FORCE_INLINE_ static bool _can_collide_with(CollisionObject2DSW *p_object, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  36. if (!(p_object->get_collision_layer() & p_collision_mask)) {
  37. return false;
  38. }
  39. if (p_object->get_type() == CollisionObject2DSW::TYPE_AREA && !p_collide_with_areas)
  40. return false;
  41. if (p_object->get_type() == CollisionObject2DSW::TYPE_BODY && !p_collide_with_bodies)
  42. return false;
  43. return true;
  44. }
  45. int Physics2DDirectSpaceStateSW::_intersect_point_impl(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_point, bool p_filter_by_canvas, ObjectID p_canvas_instance_id) {
  46. if (p_result_max <= 0)
  47. return 0;
  48. Rect2 aabb;
  49. aabb.position = p_point - Vector2(0.00001, 0.00001);
  50. aabb.size = Vector2(0.00002, 0.00002);
  51. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  52. int cc = 0;
  53. for (int i = 0; i < amount; i++) {
  54. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas))
  55. continue;
  56. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  57. continue;
  58. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  59. if (p_pick_point && !col_obj->is_pickable())
  60. continue;
  61. if (p_filter_by_canvas && col_obj->get_canvas_instance_id() != p_canvas_instance_id)
  62. continue;
  63. int shape_idx = space->intersection_query_subindex_results[i];
  64. Shape2DSW *shape = col_obj->get_shape(shape_idx);
  65. Vector2 local_point = (col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).affine_inverse().xform(p_point);
  66. if (!shape->contains_point(local_point))
  67. continue;
  68. if (cc >= p_result_max)
  69. continue;
  70. r_results[cc].collider_id = col_obj->get_instance_id();
  71. if (r_results[cc].collider_id != 0)
  72. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  73. r_results[cc].rid = col_obj->get_self();
  74. r_results[cc].shape = shape_idx;
  75. r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx);
  76. cc++;
  77. }
  78. return cc;
  79. }
  80. int Physics2DDirectSpaceStateSW::intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_point) {
  81. return _intersect_point_impl(p_point, r_results, p_result_max, p_exclude, p_collision_mask, p_collide_with_bodies, p_collide_with_areas, p_pick_point);
  82. }
  83. int Physics2DDirectSpaceStateSW::intersect_point_on_canvas(const Vector2 &p_point, ObjectID p_canvas_instance_id, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_point) {
  84. return _intersect_point_impl(p_point, r_results, p_result_max, p_exclude, p_collision_mask, p_collide_with_bodies, p_collide_with_areas, p_pick_point, true, p_canvas_instance_id);
  85. }
  86. bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  87. ERR_FAIL_COND_V(space->locked, false);
  88. Vector2 begin, end;
  89. Vector2 normal;
  90. begin = p_from;
  91. end = p_to;
  92. normal = (end - begin).normalized();
  93. int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  94. //todo, create another array that references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision
  95. bool collided = false;
  96. Vector2 res_point, res_normal;
  97. int res_shape;
  98. const CollisionObject2DSW *res_obj;
  99. real_t min_d = 1e10;
  100. for (int i = 0; i < amount; i++) {
  101. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas))
  102. continue;
  103. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  104. continue;
  105. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  106. int shape_idx = space->intersection_query_subindex_results[i];
  107. Transform2D inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
  108. Vector2 local_from = inv_xform.xform(begin);
  109. Vector2 local_to = inv_xform.xform(end);
  110. /*local_from = col_obj->get_inv_transform().xform(begin);
  111. local_from = col_obj->get_shape_inv_transform(shape_idx).xform(local_from);
  112. local_to = col_obj->get_inv_transform().xform(end);
  113. local_to = col_obj->get_shape_inv_transform(shape_idx).xform(local_to);*/
  114. const Shape2DSW *shape = col_obj->get_shape(shape_idx);
  115. Vector2 shape_point, shape_normal;
  116. if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
  117. Transform2D xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  118. shape_point = xform.xform(shape_point);
  119. real_t ld = normal.dot(shape_point);
  120. if (ld < min_d) {
  121. min_d = ld;
  122. res_point = shape_point;
  123. res_normal = inv_xform.basis_xform_inv(shape_normal).normalized();
  124. res_shape = shape_idx;
  125. res_obj = col_obj;
  126. collided = true;
  127. }
  128. }
  129. }
  130. if (!collided)
  131. return false;
  132. r_result.collider_id = res_obj->get_instance_id();
  133. if (r_result.collider_id != 0)
  134. r_result.collider = ObjectDB::get_instance(r_result.collider_id);
  135. r_result.normal = res_normal;
  136. r_result.metadata = res_obj->get_shape_metadata(res_shape);
  137. r_result.position = res_point;
  138. r_result.rid = res_obj->get_self();
  139. r_result.shape = res_shape;
  140. return true;
  141. }
  142. int Physics2DDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  143. if (p_result_max <= 0)
  144. return 0;
  145. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  146. ERR_FAIL_COND_V(!shape, 0);
  147. Rect2 aabb = p_xform.xform(shape->get_aabb());
  148. aabb = aabb.grow(p_margin);
  149. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  150. int cc = 0;
  151. for (int i = 0; i < amount; i++) {
  152. if (cc >= p_result_max)
  153. break;
  154. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas))
  155. continue;
  156. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  157. continue;
  158. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  159. int shape_idx = space->intersection_query_subindex_results[i];
  160. if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), NULL, NULL, NULL, p_margin))
  161. continue;
  162. r_results[cc].collider_id = col_obj->get_instance_id();
  163. if (r_results[cc].collider_id != 0)
  164. r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
  165. r_results[cc].rid = col_obj->get_self();
  166. r_results[cc].shape = shape_idx;
  167. r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx);
  168. cc++;
  169. }
  170. return cc;
  171. }
  172. bool Physics2DDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &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, bool p_collide_with_bodies, bool p_collide_with_areas) {
  173. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  174. ERR_FAIL_COND_V(!shape, false);
  175. Rect2 aabb = p_xform.xform(shape->get_aabb());
  176. aabb = aabb.merge(Rect2(aabb.position + p_motion, aabb.size)); //motion
  177. aabb = aabb.grow(p_margin);
  178. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  179. real_t best_safe = 1;
  180. real_t best_unsafe = 1;
  181. for (int i = 0; i < amount; i++) {
  182. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas))
  183. continue;
  184. if (p_exclude.has(space->intersection_query_results[i]->get_self()))
  185. continue; //ignore excluded
  186. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  187. int shape_idx = space->intersection_query_subindex_results[i];
  188. Transform2D col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  189. //test initial overlap, does it collide if going all the way?
  190. if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, p_margin)) {
  191. continue;
  192. }
  193. //test initial overlap
  194. if (CollisionSolver2DSW::solve(shape, p_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, p_margin)) {
  195. return false;
  196. }
  197. //just do kinematic solving
  198. real_t low = 0;
  199. real_t hi = 1;
  200. Vector2 mnormal = p_motion.normalized();
  201. for (int j = 0; j < 8; j++) { //steps should be customizable..
  202. real_t ofs = (low + hi) * 0.5;
  203. Vector2 sep = mnormal; //important optimization for this to work fast enough
  204. bool collided = CollisionSolver2DSW::solve(shape, p_xform, p_motion * ofs, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, &sep, p_margin);
  205. if (collided) {
  206. hi = ofs;
  207. } else {
  208. low = ofs;
  209. }
  210. }
  211. if (low < best_safe) {
  212. best_safe = low;
  213. best_unsafe = hi;
  214. }
  215. }
  216. p_closest_safe = best_safe;
  217. p_closest_unsafe = best_unsafe;
  218. return true;
  219. }
  220. bool Physics2DDirectSpaceStateSW::collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  221. if (p_result_max <= 0)
  222. return 0;
  223. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  224. ERR_FAIL_COND_V(!shape, 0);
  225. Rect2 aabb = p_shape_xform.xform(shape->get_aabb());
  226. aabb = aabb.merge(Rect2(aabb.position + p_motion, aabb.size)); //motion
  227. aabb = aabb.grow(p_margin);
  228. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  229. bool collided = false;
  230. r_result_count = 0;
  231. Physics2DServerSW::CollCbkData cbk;
  232. cbk.max = p_result_max;
  233. cbk.amount = 0;
  234. cbk.passed = 0;
  235. cbk.ptr = r_results;
  236. CollisionSolver2DSW::CallbackResult cbkres = NULL;
  237. Physics2DServerSW::CollCbkData *cbkptr = NULL;
  238. if (p_result_max > 0) {
  239. cbkptr = &cbk;
  240. cbkres = Physics2DServerSW::_shape_col_cbk;
  241. }
  242. for (int i = 0; i < amount; i++) {
  243. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas))
  244. continue;
  245. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  246. int shape_idx = space->intersection_query_subindex_results[i];
  247. if (p_exclude.has(col_obj->get_self()))
  248. continue;
  249. cbk.valid_dir = Vector2();
  250. cbk.valid_depth = 0;
  251. if (CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), cbkres, cbkptr, NULL, p_margin)) {
  252. collided = p_result_max == 0 || cbk.amount > 0;
  253. }
  254. }
  255. r_result_count = cbk.amount;
  256. return collided;
  257. }
  258. struct _RestCallbackData2D {
  259. const CollisionObject2DSW *object;
  260. const CollisionObject2DSW *best_object;
  261. int local_shape;
  262. int best_local_shape;
  263. int shape;
  264. int best_shape;
  265. Vector2 best_contact;
  266. Vector2 best_normal;
  267. real_t best_len;
  268. Vector2 valid_dir;
  269. real_t valid_depth;
  270. real_t min_allowed_depth;
  271. };
  272. static void _rest_cbk_result(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) {
  273. _RestCallbackData2D *rd = (_RestCallbackData2D *)p_userdata;
  274. if (rd->valid_dir != Vector2()) {
  275. if (p_point_A.distance_squared_to(p_point_B) > rd->valid_depth * rd->valid_depth)
  276. return;
  277. if (rd->valid_dir.dot((p_point_A - p_point_B).normalized()) < Math_PI * 0.25)
  278. return;
  279. }
  280. Vector2 contact_rel = p_point_B - p_point_A;
  281. real_t len = contact_rel.length();
  282. if (len < rd->min_allowed_depth)
  283. return;
  284. if (len <= rd->best_len)
  285. return;
  286. rd->best_len = len;
  287. rd->best_contact = p_point_B;
  288. rd->best_normal = contact_rel / len;
  289. rd->best_object = rd->object;
  290. rd->best_shape = rd->shape;
  291. rd->best_local_shape = rd->local_shape;
  292. }
  293. bool Physics2DDirectSpaceStateSW::rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
  294. Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
  295. ERR_FAIL_COND_V(!shape, 0);
  296. Rect2 aabb = p_shape_xform.xform(shape->get_aabb());
  297. aabb = aabb.merge(Rect2(aabb.position + p_motion, aabb.size)); //motion
  298. aabb = aabb.grow(p_margin);
  299. int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
  300. _RestCallbackData2D rcd;
  301. rcd.best_len = 0;
  302. rcd.best_object = NULL;
  303. rcd.best_shape = 0;
  304. rcd.min_allowed_depth = space->test_motion_min_contact_depth;
  305. for (int i = 0; i < amount; i++) {
  306. if (!_can_collide_with(space->intersection_query_results[i], p_collision_mask, p_collide_with_bodies, p_collide_with_areas))
  307. continue;
  308. const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
  309. int shape_idx = space->intersection_query_subindex_results[i];
  310. if (p_exclude.has(col_obj->get_self()))
  311. continue;
  312. rcd.valid_dir = Vector2();
  313. rcd.valid_depth = 0;
  314. rcd.object = col_obj;
  315. rcd.shape = shape_idx;
  316. rcd.local_shape = 0;
  317. bool sc = CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), _rest_cbk_result, &rcd, NULL, p_margin);
  318. if (!sc)
  319. continue;
  320. }
  321. if (rcd.best_len == 0)
  322. return false;
  323. r_info->collider_id = rcd.best_object->get_instance_id();
  324. r_info->shape = rcd.best_shape;
  325. r_info->normal = rcd.best_normal;
  326. r_info->point = rcd.best_contact;
  327. r_info->rid = rcd.best_object->get_self();
  328. r_info->metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
  329. if (rcd.best_object->get_type() == CollisionObject2DSW::TYPE_BODY) {
  330. const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object);
  331. Vector2 rel_vec = r_info->point - body->get_transform().get_origin();
  332. r_info->linear_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  333. } else {
  334. r_info->linear_velocity = Vector2();
  335. }
  336. return true;
  337. }
  338. Physics2DDirectSpaceStateSW::Physics2DDirectSpaceStateSW() {
  339. space = NULL;
  340. }
  341. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  342. int Space2DSW::_cull_aabb_for_body(Body2DSW *p_body, const Rect2 &p_aabb) {
  343. int amount = broadphase->cull_aabb(p_aabb, intersection_query_results, INTERSECTION_QUERY_MAX, intersection_query_subindex_results);
  344. for (int i = 0; i < amount; i++) {
  345. bool keep = true;
  346. if (intersection_query_results[i] == p_body)
  347. keep = false;
  348. else if (intersection_query_results[i]->get_type() == CollisionObject2DSW::TYPE_AREA)
  349. keep = false;
  350. else if ((static_cast<Body2DSW *>(intersection_query_results[i])->test_collision_mask(p_body)) == 0)
  351. keep = false;
  352. else if (static_cast<Body2DSW *>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self()))
  353. keep = false;
  354. else if (static_cast<Body2DSW *>(intersection_query_results[i])->is_shape_set_as_disabled(intersection_query_subindex_results[i]))
  355. keep = false;
  356. if (!keep) {
  357. if (i < amount - 1) {
  358. SWAP(intersection_query_results[i], intersection_query_results[amount - 1]);
  359. SWAP(intersection_query_subindex_results[i], intersection_query_subindex_results[amount - 1]);
  360. }
  361. amount--;
  362. i--;
  363. }
  364. }
  365. return amount;
  366. }
  367. int Space2DSW::test_body_ray_separation(Body2DSW *p_body, const Transform2D &p_transform, bool p_infinite_inertia, Vector2 &r_recover_motion, Physics2DServer::SeparationResult *r_results, int p_result_max, real_t p_margin) {
  368. Rect2 body_aabb;
  369. bool shapes_found = false;
  370. for (int i = 0; i < p_body->get_shape_count(); i++) {
  371. if (p_body->is_shape_set_as_disabled(i))
  372. continue;
  373. if (p_body->get_shape(i)->get_type() != Physics2DServer::SHAPE_RAY)
  374. continue;
  375. if (!shapes_found) {
  376. body_aabb = p_body->get_shape_aabb(i);
  377. shapes_found = true;
  378. } else {
  379. body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
  380. }
  381. }
  382. if (!shapes_found) {
  383. return 0;
  384. }
  385. // Undo the currently transform the physics server is aware of and apply the provided one
  386. body_aabb = p_transform.xform(p_body->get_inv_transform().xform(body_aabb));
  387. body_aabb = body_aabb.grow(p_margin);
  388. Transform2D body_transform = p_transform;
  389. for (int i = 0; i < p_result_max; i++) {
  390. //reset results
  391. r_results[i].collision_depth = 0;
  392. }
  393. int rays_found = 0;
  394. {
  395. // raycast AND separate
  396. const int max_results = 32;
  397. int recover_attempts = 4;
  398. Vector2 sr[max_results * 2];
  399. Physics2DServerSW::CollCbkData cbk;
  400. cbk.max = max_results;
  401. Physics2DServerSW::CollCbkData *cbkptr = &cbk;
  402. CollisionSolver2DSW::CallbackResult cbkres = Physics2DServerSW::_shape_col_cbk;
  403. do {
  404. Vector2 recover_motion;
  405. bool collided = false;
  406. int amount = _cull_aabb_for_body(p_body, body_aabb);
  407. for (int j = 0; j < p_body->get_shape_count(); j++) {
  408. if (p_body->is_shape_set_as_disabled(j))
  409. continue;
  410. Shape2DSW *body_shape = p_body->get_shape(j);
  411. if (body_shape->get_type() != Physics2DServer::SHAPE_RAY)
  412. continue;
  413. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j);
  414. for (int i = 0; i < amount; i++) {
  415. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  416. int shape_idx = intersection_query_subindex_results[i];
  417. cbk.amount = 0;
  418. cbk.passed = 0;
  419. cbk.ptr = sr;
  420. cbk.invalid_by_dir = 0;
  421. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  422. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  423. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  424. continue;
  425. }
  426. }
  427. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  428. /*
  429. * There is no point in supporting one way collisions with ray shapes, as they will always collide in the desired
  430. * direction. Use a short ray shape if you want to achieve a similar effect.
  431. *
  432. if (col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  433. cbk.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  434. cbk.valid_depth = p_margin; //only valid depth is the collision margin
  435. cbk.invalid_by_dir = 0;
  436. } else {
  437. */
  438. cbk.valid_dir = Vector2();
  439. cbk.valid_depth = 0;
  440. cbk.invalid_by_dir = 0;
  441. /*
  442. }
  443. */
  444. Shape2DSW *against_shape = col_obj->get_shape(shape_idx);
  445. if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, NULL, p_margin)) {
  446. if (cbk.amount > 0) {
  447. collided = true;
  448. }
  449. int ray_index = -1; //reuse shape
  450. for (int k = 0; k < rays_found; k++) {
  451. if (r_results[ray_index].collision_local_shape == j) {
  452. ray_index = k;
  453. }
  454. }
  455. if (ray_index == -1 && rays_found < p_result_max) {
  456. ray_index = rays_found;
  457. rays_found++;
  458. }
  459. if (ray_index != -1) {
  460. Physics2DServer::SeparationResult &result = r_results[ray_index];
  461. for (int k = 0; k < cbk.amount; k++) {
  462. Vector2 a = sr[k * 2 + 0];
  463. Vector2 b = sr[k * 2 + 1];
  464. recover_motion += (b - a) * 0.4;
  465. float depth = a.distance_to(b);
  466. if (depth > result.collision_depth) {
  467. result.collision_depth = depth;
  468. result.collision_point = b;
  469. result.collision_normal = (b - a).normalized();
  470. result.collision_local_shape = j;
  471. result.collider_shape = shape_idx;
  472. result.collider = col_obj->get_self();
  473. result.collider_id = col_obj->get_instance_id();
  474. result.collider_metadata = col_obj->get_shape_metadata(shape_idx);
  475. if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
  476. Body2DSW *body = (Body2DSW *)col_obj;
  477. Vector2 rel_vec = b - body->get_transform().get_origin();
  478. result.collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  479. }
  480. }
  481. }
  482. }
  483. }
  484. }
  485. }
  486. if (!collided || recover_motion == Vector2()) {
  487. break;
  488. }
  489. body_transform.elements[2] += recover_motion;
  490. body_aabb.position += recover_motion;
  491. recover_attempts--;
  492. } while (recover_attempts);
  493. }
  494. //optimize results (remove non colliding)
  495. for (int i = 0; i < rays_found; i++) {
  496. if (r_results[i].collision_depth == 0) {
  497. rays_found--;
  498. SWAP(r_results[i], r_results[rays_found]);
  499. }
  500. }
  501. r_recover_motion = body_transform.elements[2] - p_transform.elements[2];
  502. return rays_found;
  503. }
  504. bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, bool p_infinite_inertia, real_t p_margin, Physics2DServer::MotionResult *r_result, bool p_exclude_raycast_shapes) {
  505. //give me back regular physics engine logic
  506. //this is madness
  507. //and most people using this function will think
  508. //what it does is simpler than using physics
  509. //this took about a week to get right..
  510. //but is it right? who knows at this point..
  511. if (r_result) {
  512. r_result->collider_id = 0;
  513. r_result->collider_shape = 0;
  514. }
  515. Rect2 body_aabb;
  516. bool shapes_found = false;
  517. for (int i = 0; i < p_body->get_shape_count(); i++) {
  518. if (p_body->is_shape_set_as_disabled(i))
  519. continue;
  520. if (p_exclude_raycast_shapes && p_body->get_shape(i)->get_type() == Physics2DServer::SHAPE_RAY)
  521. continue;
  522. if (!shapes_found) {
  523. body_aabb = p_body->get_shape_aabb(i);
  524. shapes_found = true;
  525. } else {
  526. body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
  527. }
  528. }
  529. if (!shapes_found) {
  530. if (r_result) {
  531. *r_result = Physics2DServer::MotionResult();
  532. r_result->motion = p_motion;
  533. }
  534. return false;
  535. }
  536. // Undo the currently transform the physics server is aware of and apply the provided one
  537. body_aabb = p_from.xform(p_body->get_inv_transform().xform(body_aabb));
  538. body_aabb = body_aabb.grow(p_margin);
  539. static const int max_excluded_shape_pairs = 32;
  540. ExcludedShapeSW excluded_shape_pairs[max_excluded_shape_pairs];
  541. int excluded_shape_pair_count = 0;
  542. float separation_margin = MIN(p_margin, MAX(0.0, p_motion.length() - CMP_EPSILON)); //don't separate by more than the intended motion
  543. Transform2D body_transform = p_from;
  544. {
  545. //STEP 1, FREE BODY IF STUCK
  546. const int max_results = 32;
  547. int recover_attempts = 4;
  548. Vector2 sr[max_results * 2];
  549. do {
  550. Physics2DServerSW::CollCbkData cbk;
  551. cbk.max = max_results;
  552. cbk.amount = 0;
  553. cbk.passed = 0;
  554. cbk.ptr = sr;
  555. cbk.invalid_by_dir = 0;
  556. excluded_shape_pair_count = 0; //last step is the one valid
  557. Physics2DServerSW::CollCbkData *cbkptr = &cbk;
  558. CollisionSolver2DSW::CallbackResult cbkres = Physics2DServerSW::_shape_col_cbk;
  559. bool collided = false;
  560. int amount = _cull_aabb_for_body(p_body, body_aabb);
  561. for (int j = 0; j < p_body->get_shape_count(); j++) {
  562. if (p_body->is_shape_set_as_disabled(j))
  563. continue;
  564. Shape2DSW *body_shape = p_body->get_shape(j);
  565. if (p_exclude_raycast_shapes && body_shape->get_type() == Physics2DServer::SHAPE_RAY) {
  566. continue;
  567. }
  568. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j);
  569. for (int i = 0; i < amount; i++) {
  570. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  571. int shape_idx = intersection_query_subindex_results[i];
  572. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  573. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  574. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  575. continue;
  576. }
  577. }
  578. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  579. if (col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  580. cbk.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  581. float owc_margin = col_obj->get_shape_one_way_collision_margin(shape_idx);
  582. cbk.valid_depth = MAX(owc_margin, p_margin); //user specified, but never less than actual margin or it wont work
  583. cbk.invalid_by_dir = 0;
  584. if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
  585. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  586. if (b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC || b->get_mode() == Physics2DServer::BODY_MODE_RIGID) {
  587. //fix for moving platforms (kinematic and dynamic), margin is increased by how much it moved in the given direction
  588. Vector2 lv = b->get_linear_velocity();
  589. //compute displacement from linear velocity
  590. Vector2 motion = lv * Physics2DDirectBodyStateSW::singleton->step;
  591. float motion_len = motion.length();
  592. motion.normalize();
  593. cbk.valid_depth += motion_len * MAX(motion.dot(-cbk.valid_dir), 0.0);
  594. }
  595. }
  596. } else {
  597. cbk.valid_dir = Vector2();
  598. cbk.valid_depth = 0;
  599. cbk.invalid_by_dir = 0;
  600. }
  601. int current_passed = cbk.passed; //save how many points passed collision
  602. bool did_collide = false;
  603. Shape2DSW *against_shape = col_obj->get_shape(shape_idx);
  604. if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), cbkres, cbkptr, NULL, separation_margin)) {
  605. did_collide = cbk.passed > current_passed; //more passed, so collision actually existed
  606. }
  607. if (!did_collide && cbk.invalid_by_dir > 0) {
  608. //this shape must be excluded
  609. if (excluded_shape_pair_count < max_excluded_shape_pairs) {
  610. ExcludedShapeSW esp;
  611. esp.local_shape = body_shape;
  612. esp.against_object = col_obj;
  613. esp.against_shape_index = shape_idx;
  614. excluded_shape_pairs[excluded_shape_pair_count++] = esp;
  615. }
  616. }
  617. if (did_collide) {
  618. collided = true;
  619. }
  620. }
  621. }
  622. if (!collided) {
  623. break;
  624. }
  625. Vector2 recover_motion;
  626. for (int i = 0; i < cbk.amount; i++) {
  627. Vector2 a = sr[i * 2 + 0];
  628. Vector2 b = sr[i * 2 + 1];
  629. recover_motion += (b - a) * 0.4;
  630. }
  631. if (recover_motion == Vector2()) {
  632. collided = false;
  633. break;
  634. }
  635. body_transform.elements[2] += recover_motion;
  636. body_aabb.position += recover_motion;
  637. recover_attempts--;
  638. } while (recover_attempts);
  639. }
  640. real_t safe = 1.0;
  641. real_t unsafe = 1.0;
  642. int best_shape = -1;
  643. {
  644. // STEP 2 ATTEMPT MOTION
  645. Rect2 motion_aabb = body_aabb;
  646. motion_aabb.position += p_motion;
  647. motion_aabb = motion_aabb.merge(body_aabb);
  648. int amount = _cull_aabb_for_body(p_body, motion_aabb);
  649. for (int body_shape_idx = 0; body_shape_idx < p_body->get_shape_count(); body_shape_idx++) {
  650. if (p_body->is_shape_set_as_disabled(body_shape_idx))
  651. continue;
  652. Shape2DSW *body_shape = p_body->get_shape(body_shape_idx);
  653. if (p_exclude_raycast_shapes && body_shape->get_type() == Physics2DServer::SHAPE_RAY) {
  654. continue;
  655. }
  656. Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(body_shape_idx);
  657. bool stuck = false;
  658. real_t best_safe = 1;
  659. real_t best_unsafe = 1;
  660. for (int i = 0; i < amount; i++) {
  661. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  662. int col_shape_idx = intersection_query_subindex_results[i];
  663. Shape2DSW *against_shape = col_obj->get_shape(col_shape_idx);
  664. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  665. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  666. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  667. continue;
  668. }
  669. }
  670. bool excluded = false;
  671. for (int k = 0; k < excluded_shape_pair_count; k++) {
  672. if (excluded_shape_pairs[k].local_shape == body_shape && excluded_shape_pairs[k].against_object == col_obj && excluded_shape_pairs[k].against_shape_index == col_shape_idx) {
  673. excluded = true;
  674. break;
  675. }
  676. }
  677. if (excluded) {
  678. continue;
  679. }
  680. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(col_shape_idx);
  681. //test initial overlap, does it collide if going all the way?
  682. if (!CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion, against_shape, col_obj_shape_xform, Vector2(), NULL, NULL, NULL, 0)) {
  683. continue;
  684. }
  685. //test initial overlap
  686. if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), NULL, NULL, NULL, 0)) {
  687. if (col_obj->is_shape_set_as_one_way_collision(col_shape_idx)) {
  688. continue;
  689. }
  690. stuck = true;
  691. break;
  692. }
  693. //just do kinematic solving
  694. real_t low = 0;
  695. real_t hi = 1;
  696. Vector2 mnormal = p_motion.normalized();
  697. for (int k = 0; k < 8; k++) { //steps should be customizable..
  698. real_t ofs = (low + hi) * 0.5;
  699. Vector2 sep = mnormal; //important optimization for this to work fast enough
  700. bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * ofs, against_shape, col_obj_shape_xform, Vector2(), NULL, NULL, &sep, 0);
  701. if (collided) {
  702. hi = ofs;
  703. } else {
  704. low = ofs;
  705. }
  706. }
  707. if (col_obj->is_shape_set_as_one_way_collision(col_shape_idx)) {
  708. Vector2 cd[2];
  709. Physics2DServerSW::CollCbkData cbk;
  710. cbk.max = 1;
  711. cbk.amount = 0;
  712. cbk.passed = 0;
  713. cbk.ptr = cd;
  714. cbk.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  715. cbk.valid_depth = 10e20;
  716. Vector2 sep = mnormal; //important optimization for this to work fast enough
  717. bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * (hi + contact_max_allowed_penetration), col_obj->get_shape(col_shape_idx), col_obj_shape_xform, Vector2(), Physics2DServerSW::_shape_col_cbk, &cbk, &sep, 0);
  718. if (!collided || cbk.amount == 0) {
  719. continue;
  720. }
  721. }
  722. if (low < best_safe) {
  723. best_safe = low;
  724. best_unsafe = hi;
  725. }
  726. }
  727. if (stuck) {
  728. safe = 0;
  729. unsafe = 0;
  730. best_shape = body_shape_idx; //sadly it's the best
  731. break;
  732. }
  733. if (best_safe == 1.0) {
  734. continue;
  735. }
  736. if (best_safe < safe) {
  737. safe = best_safe;
  738. unsafe = best_unsafe;
  739. best_shape = body_shape_idx;
  740. }
  741. }
  742. }
  743. bool collided = false;
  744. if (safe >= 1) {
  745. best_shape = -1; //no best shape with cast, reset to -1
  746. }
  747. {
  748. //it collided, let's get the rest info in unsafe advance
  749. Transform2D ugt = body_transform;
  750. ugt.elements[2] += p_motion * unsafe;
  751. _RestCallbackData2D rcd;
  752. rcd.best_len = 0;
  753. rcd.best_object = NULL;
  754. rcd.best_shape = 0;
  755. rcd.min_allowed_depth = test_motion_min_contact_depth;
  756. //optimization
  757. int from_shape = best_shape != -1 ? best_shape : 0;
  758. int to_shape = best_shape != -1 ? best_shape + 1 : p_body->get_shape_count();
  759. for (int j = from_shape; j < to_shape; j++) {
  760. if (p_body->is_shape_set_as_disabled(j))
  761. continue;
  762. Transform2D body_shape_xform = ugt * p_body->get_shape_transform(j);
  763. Shape2DSW *body_shape = p_body->get_shape(j);
  764. if (p_exclude_raycast_shapes && body_shape->get_type() == Physics2DServer::SHAPE_RAY) {
  765. continue;
  766. }
  767. body_aabb.position += p_motion * unsafe;
  768. int amount = _cull_aabb_for_body(p_body, body_aabb);
  769. for (int i = 0; i < amount; i++) {
  770. const CollisionObject2DSW *col_obj = intersection_query_results[i];
  771. int shape_idx = intersection_query_subindex_results[i];
  772. if (CollisionObject2DSW::TYPE_BODY == col_obj->get_type()) {
  773. const Body2DSW *b = static_cast<const Body2DSW *>(col_obj);
  774. if (p_infinite_inertia && Physics2DServer::BODY_MODE_STATIC != b->get_mode() && Physics2DServer::BODY_MODE_KINEMATIC != b->get_mode()) {
  775. continue;
  776. }
  777. }
  778. Shape2DSW *against_shape = col_obj->get_shape(shape_idx);
  779. bool excluded = false;
  780. for (int k = 0; k < excluded_shape_pair_count; k++) {
  781. if (excluded_shape_pairs[k].local_shape == body_shape && excluded_shape_pairs[k].against_object == col_obj && excluded_shape_pairs[k].against_shape_index == shape_idx) {
  782. excluded = true;
  783. break;
  784. }
  785. }
  786. if (excluded)
  787. continue;
  788. Transform2D col_obj_shape_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
  789. if (col_obj->is_shape_set_as_one_way_collision(shape_idx)) {
  790. rcd.valid_dir = col_obj_shape_xform.get_axis(1).normalized();
  791. rcd.valid_depth = 10e20;
  792. } else {
  793. rcd.valid_dir = Vector2();
  794. rcd.valid_depth = 0;
  795. }
  796. rcd.object = col_obj;
  797. rcd.shape = shape_idx;
  798. rcd.local_shape = j;
  799. bool sc = CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), against_shape, col_obj_shape_xform, Vector2(), _rest_cbk_result, &rcd, NULL, p_margin);
  800. if (!sc)
  801. continue;
  802. }
  803. }
  804. if (rcd.best_len != 0) {
  805. if (r_result) {
  806. r_result->collider = rcd.best_object->get_self();
  807. r_result->collider_id = rcd.best_object->get_instance_id();
  808. r_result->collider_shape = rcd.best_shape;
  809. r_result->collision_local_shape = rcd.best_local_shape;
  810. r_result->collision_normal = rcd.best_normal;
  811. r_result->collision_point = rcd.best_contact;
  812. r_result->collider_metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
  813. const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object);
  814. Vector2 rel_vec = r_result->collision_point - body->get_transform().get_origin();
  815. r_result->collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
  816. r_result->motion = safe * p_motion;
  817. r_result->remainder = p_motion - safe * p_motion;
  818. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  819. }
  820. collided = true;
  821. }
  822. }
  823. if (!collided && r_result) {
  824. r_result->motion = p_motion;
  825. r_result->remainder = Vector2();
  826. r_result->motion += (body_transform.get_origin() - p_from.get_origin());
  827. }
  828. return collided;
  829. }
  830. void *Space2DSW::_broadphase_pair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_self) {
  831. CollisionObject2DSW::Type type_A = A->get_type();
  832. CollisionObject2DSW::Type type_B = B->get_type();
  833. if (type_A > type_B) {
  834. SWAP(A, B);
  835. SWAP(p_subindex_A, p_subindex_B);
  836. SWAP(type_A, type_B);
  837. }
  838. Space2DSW *self = (Space2DSW *)p_self;
  839. self->collision_pairs++;
  840. if (type_A == CollisionObject2DSW::TYPE_AREA) {
  841. Area2DSW *area = static_cast<Area2DSW *>(A);
  842. if (type_B == CollisionObject2DSW::TYPE_AREA) {
  843. Area2DSW *area_b = static_cast<Area2DSW *>(B);
  844. Area2Pair2DSW *area2_pair = memnew(Area2Pair2DSW(area_b, p_subindex_B, area, p_subindex_A));
  845. return area2_pair;
  846. } else {
  847. Body2DSW *body = static_cast<Body2DSW *>(B);
  848. AreaPair2DSW *area_pair = memnew(AreaPair2DSW(body, p_subindex_B, area, p_subindex_A));
  849. return area_pair;
  850. }
  851. } else {
  852. BodyPair2DSW *b = memnew(BodyPair2DSW((Body2DSW *)A, p_subindex_A, (Body2DSW *)B, p_subindex_B));
  853. return b;
  854. }
  855. return NULL;
  856. }
  857. void Space2DSW::_broadphase_unpair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_data, void *p_self) {
  858. Space2DSW *self = (Space2DSW *)p_self;
  859. self->collision_pairs--;
  860. Constraint2DSW *c = (Constraint2DSW *)p_data;
  861. memdelete(c);
  862. }
  863. const SelfList<Body2DSW>::List &Space2DSW::get_active_body_list() const {
  864. return active_list;
  865. }
  866. void Space2DSW::body_add_to_active_list(SelfList<Body2DSW> *p_body) {
  867. active_list.add(p_body);
  868. }
  869. void Space2DSW::body_remove_from_active_list(SelfList<Body2DSW> *p_body) {
  870. active_list.remove(p_body);
  871. }
  872. void Space2DSW::body_add_to_inertia_update_list(SelfList<Body2DSW> *p_body) {
  873. inertia_update_list.add(p_body);
  874. }
  875. void Space2DSW::body_remove_from_inertia_update_list(SelfList<Body2DSW> *p_body) {
  876. inertia_update_list.remove(p_body);
  877. }
  878. BroadPhase2DSW *Space2DSW::get_broadphase() {
  879. return broadphase;
  880. }
  881. void Space2DSW::add_object(CollisionObject2DSW *p_object) {
  882. ERR_FAIL_COND(objects.has(p_object));
  883. objects.insert(p_object);
  884. }
  885. void Space2DSW::remove_object(CollisionObject2DSW *p_object) {
  886. ERR_FAIL_COND(!objects.has(p_object));
  887. objects.erase(p_object);
  888. }
  889. const Set<CollisionObject2DSW *> &Space2DSW::get_objects() const {
  890. return objects;
  891. }
  892. void Space2DSW::body_add_to_state_query_list(SelfList<Body2DSW> *p_body) {
  893. state_query_list.add(p_body);
  894. }
  895. void Space2DSW::body_remove_from_state_query_list(SelfList<Body2DSW> *p_body) {
  896. state_query_list.remove(p_body);
  897. }
  898. void Space2DSW::area_add_to_monitor_query_list(SelfList<Area2DSW> *p_area) {
  899. monitor_query_list.add(p_area);
  900. }
  901. void Space2DSW::area_remove_from_monitor_query_list(SelfList<Area2DSW> *p_area) {
  902. monitor_query_list.remove(p_area);
  903. }
  904. void Space2DSW::area_add_to_moved_list(SelfList<Area2DSW> *p_area) {
  905. area_moved_list.add(p_area);
  906. }
  907. void Space2DSW::area_remove_from_moved_list(SelfList<Area2DSW> *p_area) {
  908. area_moved_list.remove(p_area);
  909. }
  910. const SelfList<Area2DSW>::List &Space2DSW::get_moved_area_list() const {
  911. return area_moved_list;
  912. }
  913. void Space2DSW::call_queries() {
  914. while (state_query_list.first()) {
  915. Body2DSW *b = state_query_list.first()->self();
  916. state_query_list.remove(state_query_list.first());
  917. b->call_queries();
  918. }
  919. while (monitor_query_list.first()) {
  920. Area2DSW *a = monitor_query_list.first()->self();
  921. monitor_query_list.remove(monitor_query_list.first());
  922. a->call_queries();
  923. }
  924. }
  925. void Space2DSW::setup() {
  926. contact_debug_count = 0;
  927. while (inertia_update_list.first()) {
  928. inertia_update_list.first()->self()->update_inertias();
  929. inertia_update_list.remove(inertia_update_list.first());
  930. }
  931. }
  932. void Space2DSW::update() {
  933. broadphase->update();
  934. }
  935. void Space2DSW::set_param(Physics2DServer::SpaceParameter p_param, real_t p_value) {
  936. switch (p_param) {
  937. case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break;
  938. case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break;
  939. case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break;
  940. case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: body_linear_velocity_sleep_threshold = p_value; break;
  941. case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: body_angular_velocity_sleep_threshold = p_value; break;
  942. case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break;
  943. case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break;
  944. case Physics2DServer::SPACE_PARAM_TEST_MOTION_MIN_CONTACT_DEPTH: test_motion_min_contact_depth = p_value; break;
  945. }
  946. }
  947. real_t Space2DSW::get_param(Physics2DServer::SpaceParameter p_param) const {
  948. switch (p_param) {
  949. case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius;
  950. case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation;
  951. case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: return contact_max_allowed_penetration;
  952. case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_THRESHOLD: return body_linear_velocity_sleep_threshold;
  953. case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_THRESHOLD: return body_angular_velocity_sleep_threshold;
  954. case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: return body_time_to_sleep;
  955. case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: return constraint_bias;
  956. case Physics2DServer::SPACE_PARAM_TEST_MOTION_MIN_CONTACT_DEPTH: return test_motion_min_contact_depth;
  957. }
  958. return 0;
  959. }
  960. void Space2DSW::lock() {
  961. locked = true;
  962. }
  963. void Space2DSW::unlock() {
  964. locked = false;
  965. }
  966. bool Space2DSW::is_locked() const {
  967. return locked;
  968. }
  969. Physics2DDirectSpaceStateSW *Space2DSW::get_direct_state() {
  970. return direct_access;
  971. }
  972. Space2DSW::Space2DSW() {
  973. collision_pairs = 0;
  974. active_objects = 0;
  975. island_count = 0;
  976. contact_debug_count = 0;
  977. locked = false;
  978. contact_recycle_radius = 1.0;
  979. contact_max_separation = 1.5;
  980. contact_max_allowed_penetration = 0.3;
  981. test_motion_min_contact_depth = 0.005;
  982. constraint_bias = 0.2;
  983. body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_linear", 2.0);
  984. body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/2d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI));
  985. body_time_to_sleep = GLOBAL_DEF("physics/2d/time_before_sleep", 0.5);
  986. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/time_before_sleep", PropertyInfo(Variant::REAL, "physics/2d/time_before_sleep", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater"));
  987. broadphase = BroadPhase2DSW::create_func();
  988. broadphase->set_pair_callback(_broadphase_pair, this);
  989. broadphase->set_unpair_callback(_broadphase_unpair, this);
  990. area = NULL;
  991. direct_access = memnew(Physics2DDirectSpaceStateSW);
  992. direct_access->space = this;
  993. for (int i = 0; i < ELAPSED_TIME_MAX; i++)
  994. elapsed_time[i] = 0;
  995. }
  996. Space2DSW::~Space2DSW() {
  997. memdelete(broadphase);
  998. memdelete(direct_access);
  999. }