broad_phase_2d_hash_grid.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. /*************************************************************************/
  2. /* broad_phase_2d_hash_grid.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "broad_phase_2d_hash_grid.h"
  30. #include "globals.h"
  31. void BroadPhase2DHashGrid::_pair_attempt(Element *p_elem, Element* p_with) {
  32. Map<Element*,PairData*>::Element *E=p_elem->paired.find(p_with);
  33. ERR_FAIL_COND(p_elem->_static && p_with->_static);
  34. if (!E) {
  35. PairData *pd = memnew( PairData );
  36. p_elem->paired[p_with]=pd;
  37. p_with->paired[p_elem]=pd;
  38. } else {
  39. E->get()->rc++;
  40. }
  41. }
  42. void BroadPhase2DHashGrid::_unpair_attempt(Element *p_elem, Element* p_with) {
  43. Map<Element*,PairData*>::Element *E=p_elem->paired.find(p_with);
  44. ERR_FAIL_COND(!E); //this should really be paired..
  45. E->get()->rc--;
  46. if (E->get()->rc==0) {
  47. if (E->get()->colliding) {
  48. //uncollide
  49. if (unpair_callback) {
  50. unpair_callback(p_elem->owner,p_elem->subindex,p_with->owner,p_with->subindex,E->get()->ud,unpair_userdata);
  51. }
  52. }
  53. memdelete(E->get());
  54. p_elem->paired.erase(E);
  55. p_with->paired.erase(p_elem);
  56. }
  57. }
  58. void BroadPhase2DHashGrid::_check_motion(Element *p_elem) {
  59. for (Map<Element*,PairData*>::Element *E=p_elem->paired.front();E;E=E->next()) {
  60. bool pairing = p_elem->aabb.intersects( E->key()->aabb );
  61. if (pairing!=E->get()->colliding) {
  62. if (pairing) {
  63. if (pair_callback) {
  64. E->get()->ud=pair_callback(p_elem->owner,p_elem->subindex,E->key()->owner,E->key()->subindex,pair_userdata);
  65. }
  66. } else {
  67. if (unpair_callback) {
  68. unpair_callback(p_elem->owner,p_elem->subindex,E->key()->owner,E->key()->subindex,E->get()->ud,unpair_userdata);
  69. }
  70. }
  71. E->get()->colliding=pairing;
  72. }
  73. }
  74. }
  75. void BroadPhase2DHashGrid::_enter_grid( Element* p_elem, const Rect2& p_rect,bool p_static) {
  76. Point2i from = (p_rect.pos/cell_size).floor();
  77. Point2i to = ((p_rect.pos+p_rect.size)/cell_size).floor();
  78. for(int i=from.x;i<=to.x;i++) {
  79. for(int j=from.y;j<=to.y;j++) {
  80. PosKey pk;
  81. pk.x=i;
  82. pk.y=j;
  83. uint32_t idx = pk.hash() % hash_table_size;
  84. PosBin *pb = hash_table[idx];
  85. while (pb) {
  86. if (pb->key == pk) {
  87. break;
  88. }
  89. pb=pb->next;
  90. }
  91. bool entered=false;
  92. if (!pb) {
  93. //does not exist, create!
  94. pb = memnew( PosBin );
  95. pb->key=pk;
  96. pb->next=hash_table[idx];
  97. hash_table[idx]=pb;
  98. }
  99. if (p_static) {
  100. if (pb->static_object_set[p_elem].inc()==1) {
  101. entered=true;
  102. }
  103. } else {
  104. if (pb->object_set[p_elem].inc()==1) {
  105. entered=true;
  106. }
  107. }
  108. if (entered) {
  109. for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) {
  110. if (E->key()->owner==p_elem->owner)
  111. continue;
  112. _pair_attempt(p_elem,E->key());
  113. }
  114. if (!p_static) {
  115. for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) {
  116. if (E->key()->owner==p_elem->owner)
  117. continue;
  118. _pair_attempt(p_elem,E->key());
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. void BroadPhase2DHashGrid::_exit_grid( Element* p_elem, const Rect2& p_rect,bool p_static) {
  126. Point2i from = (p_rect.pos/cell_size).floor();
  127. Point2i to = ((p_rect.pos+p_rect.size)/cell_size).floor();
  128. for(int i=from.x;i<=to.x;i++) {
  129. for(int j=from.y;j<=to.y;j++) {
  130. PosKey pk;
  131. pk.x=i;
  132. pk.y=j;
  133. uint32_t idx = pk.hash() % hash_table_size;
  134. PosBin *pb = hash_table[idx];
  135. while (pb) {
  136. if (pb->key == pk) {
  137. break;
  138. }
  139. pb=pb->next;
  140. }
  141. ERR_CONTINUE(!pb); //should exist!!
  142. bool exited=false;
  143. if (p_static) {
  144. if (pb->static_object_set[p_elem].dec()==0) {
  145. pb->static_object_set.erase(p_elem);
  146. exited=true;
  147. }
  148. } else {
  149. if (pb->object_set[p_elem].dec()==0) {
  150. pb->object_set.erase(p_elem);
  151. exited=true;
  152. }
  153. }
  154. if (exited) {
  155. for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) {
  156. if (E->key()->owner==p_elem->owner)
  157. continue;
  158. _unpair_attempt(p_elem,E->key());
  159. }
  160. if (!p_static) {
  161. for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) {
  162. if (E->key()->owner==p_elem->owner)
  163. continue;
  164. _unpair_attempt(p_elem,E->key());
  165. }
  166. }
  167. }
  168. if (pb->object_set.empty() && pb->static_object_set.empty()) {
  169. if (hash_table[idx]==pb) {
  170. hash_table[idx]=pb->next;
  171. } else {
  172. PosBin *px = hash_table[idx];
  173. while (px) {
  174. if (px->next==pb) {
  175. px->next=pb->next;
  176. break;
  177. }
  178. px=px->next;
  179. }
  180. ERR_CONTINUE(!px);
  181. }
  182. memdelete(pb);
  183. }
  184. }
  185. }
  186. }
  187. BroadPhase2DHashGrid::ID BroadPhase2DHashGrid::create(CollisionObject2DSW *p_object, int p_subindex) {
  188. current++;
  189. Element e;
  190. e.owner=p_object;
  191. e._static=false;
  192. e.subindex=p_subindex;
  193. e.self=current;
  194. e.pass=0;
  195. element_map[current]=e;
  196. return current;
  197. }
  198. void BroadPhase2DHashGrid::move(ID p_id, const Rect2& p_aabb) {
  199. Map<ID,Element>::Element *E=element_map.find(p_id);
  200. ERR_FAIL_COND(!E);
  201. Element &e=E->get();
  202. if (p_aabb==e.aabb)
  203. return;
  204. if (p_aabb!=Rect2()) {
  205. _enter_grid(&e,p_aabb,e._static);
  206. }
  207. if (e.aabb!=Rect2()) {
  208. _exit_grid(&e,e.aabb,e._static);
  209. }
  210. e.aabb=p_aabb;
  211. _check_motion(&e);
  212. e.aabb=p_aabb;
  213. }
  214. void BroadPhase2DHashGrid::set_static(ID p_id, bool p_static) {
  215. Map<ID,Element>::Element *E=element_map.find(p_id);
  216. ERR_FAIL_COND(!E);
  217. Element &e=E->get();
  218. if (e._static==p_static)
  219. return;
  220. if (e.aabb!=Rect2())
  221. _exit_grid(&e,e.aabb,e._static);
  222. e._static=p_static;
  223. if (e.aabb!=Rect2()) {
  224. _enter_grid(&e,e.aabb,e._static);
  225. _check_motion(&e);
  226. }
  227. }
  228. void BroadPhase2DHashGrid::remove(ID p_id) {
  229. Map<ID,Element>::Element *E=element_map.find(p_id);
  230. ERR_FAIL_COND(!E);
  231. Element &e=E->get();
  232. if (e.aabb!=Rect2())
  233. _exit_grid(&e,e.aabb,e._static);
  234. element_map.erase(p_id);
  235. }
  236. CollisionObject2DSW *BroadPhase2DHashGrid::get_object(ID p_id) const {
  237. const Map<ID,Element>::Element *E=element_map.find(p_id);
  238. ERR_FAIL_COND_V(!E,NULL);
  239. return E->get().owner;
  240. }
  241. bool BroadPhase2DHashGrid::is_static(ID p_id) const {
  242. const Map<ID,Element>::Element *E=element_map.find(p_id);
  243. ERR_FAIL_COND_V(!E,false);
  244. return E->get()._static;
  245. }
  246. int BroadPhase2DHashGrid::get_subindex(ID p_id) const {
  247. const Map<ID,Element>::Element *E=element_map.find(p_id);
  248. ERR_FAIL_COND_V(!E,-1);
  249. return E->get().subindex;
  250. }
  251. template<bool use_aabb,bool use_segment>
  252. void BroadPhase2DHashGrid::_cull(const Point2i p_cell,const Rect2& p_aabb,const Point2& p_from, const Point2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices,int &index) {
  253. PosKey pk;
  254. pk.x=p_cell.x;
  255. pk.y=p_cell.y;
  256. uint32_t idx = pk.hash() % hash_table_size;
  257. PosBin *pb = hash_table[idx];
  258. while (pb) {
  259. if (pb->key == pk) {
  260. break;
  261. }
  262. pb=pb->next;
  263. }
  264. if (!pb)
  265. return;
  266. for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) {
  267. if (index>=p_max_results)
  268. break;
  269. if (E->key()->pass==pass)
  270. continue;
  271. E->key()->pass=pass;
  272. if (use_aabb && !p_aabb.intersects(E->key()->aabb))
  273. continue;
  274. if (use_segment && !E->key()->aabb.intersects_segment(p_from,p_to))
  275. continue;
  276. p_results[index]=E->key()->owner;
  277. p_result_indices[index]=E->key()->subindex;
  278. index++;
  279. }
  280. for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) {
  281. if (index>=p_max_results)
  282. break;
  283. if (E->key()->pass==pass)
  284. continue;
  285. if (use_aabb && !p_aabb.intersects(E->key()->aabb)) {
  286. continue;
  287. }
  288. if (use_segment && !E->key()->aabb.intersects_segment(p_from,p_to))
  289. continue;
  290. E->key()->pass=pass;
  291. p_results[index]=E->key()->owner;
  292. p_result_indices[index]=E->key()->subindex;
  293. index++;
  294. }
  295. }
  296. int BroadPhase2DHashGrid::cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) {
  297. pass++;
  298. Vector2 dir = (p_to-p_from);
  299. if (dir==Vector2())
  300. return 0;
  301. //avoid divisions by zero
  302. dir.normalize();
  303. if (dir.x==0.0)
  304. dir.x=0.000001;
  305. if (dir.y==0.0)
  306. dir.y=0.000001;
  307. Vector2 delta = dir.abs();
  308. delta.x=cell_size/delta.x;
  309. delta.y=cell_size/delta.y;
  310. Point2i pos = (p_from/cell_size).floor();
  311. Point2i end = (p_to/cell_size).floor();
  312. Point2i step = Vector2( SGN(dir.x), SGN(dir.y) );
  313. Vector2 max;
  314. if (dir.x<0)
  315. max.x= (Math::floor(pos.x)*cell_size - p_from.x) / dir.x;
  316. else
  317. max.x= (Math::floor(pos.x + 1)*cell_size - p_from.x) / dir.x;
  318. if (dir.y<0)
  319. max.y= (Math::floor(pos.y)*cell_size - p_from.y) / dir.y;
  320. else
  321. max.y= (Math::floor(pos.y + 1)*cell_size - p_from.y) / dir.y;
  322. int cullcount=0;
  323. _cull<false,true>(pos,Rect2(),p_from,p_to,p_results,p_max_results,p_result_indices,cullcount);
  324. bool reached_x=false;
  325. bool reached_y=false;
  326. while(true) {
  327. if (max.x < max.y) {
  328. max.x+=delta.x;
  329. pos.x+=step.x;
  330. } else {
  331. max.y+=delta.y;
  332. pos.y+=step.y;
  333. }
  334. if (step.x>0) {
  335. if (pos.x>=end.x)
  336. reached_x=true;
  337. } else if (pos.x<=end.x) {
  338. reached_x=true;
  339. }
  340. if (step.y>0) {
  341. if (pos.y>=end.y)
  342. reached_y=true;
  343. } else if (pos.y<=end.y) {
  344. reached_y=true;
  345. }
  346. _cull<false,true>(pos,Rect2(),p_from,p_to,p_results,p_max_results,p_result_indices,cullcount);
  347. if (reached_x && reached_y)
  348. break;
  349. }
  350. return cullcount;
  351. }
  352. int BroadPhase2DHashGrid::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) {
  353. pass++;
  354. Point2i from = (p_aabb.pos/cell_size).floor();
  355. Point2i to = ((p_aabb.pos+p_aabb.size)/cell_size).floor();
  356. int cullcount=0;
  357. for(int i=from.x;i<=to.x;i++) {
  358. for(int j=from.y;j<=to.y;j++) {
  359. _cull<true,false>(Point2i(i,j),p_aabb,Point2(),Point2(),p_results,p_max_results,p_result_indices,cullcount);
  360. }
  361. }
  362. return cullcount;
  363. }
  364. void BroadPhase2DHashGrid::set_pair_callback(PairCallback p_pair_callback,void *p_userdata) {
  365. pair_callback=p_pair_callback;
  366. pair_userdata=p_userdata;
  367. }
  368. void BroadPhase2DHashGrid::set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata) {
  369. unpair_callback=p_unpair_callback;
  370. unpair_userdata=p_userdata;
  371. }
  372. void BroadPhase2DHashGrid::update() {
  373. }
  374. BroadPhase2DSW *BroadPhase2DHashGrid::_create() {
  375. return memnew( BroadPhase2DHashGrid );
  376. }
  377. BroadPhase2DHashGrid::BroadPhase2DHashGrid() {
  378. hash_table_size = GLOBAL_DEF("physics_2d/bp_hash_table_size",4096);
  379. hash_table_size = Math::larger_prime(hash_table_size);
  380. hash_table = memnew_arr( PosBin*, hash_table_size);
  381. cell_size = GLOBAL_DEF("physics_2d/cell_size",128);
  382. for(int i=0;i<hash_table_size;i++)
  383. hash_table[i]=NULL;
  384. pass=1;
  385. current=0;
  386. }
  387. BroadPhase2DHashGrid::~BroadPhase2DHashGrid() {
  388. for(int i=0;i<hash_table_size;i++) {
  389. while(hash_table[i]) {
  390. PosBin *pb=hash_table[i];
  391. hash_table[i]=pb->next;
  392. memdelete(pb);
  393. }
  394. }
  395. memdelete_arr( hash_table );
  396. }
  397. /* 3D version of voxel traversal:
  398. public IEnumerable<Point3D> GetCellsOnRay(Ray ray, int maxDepth)
  399. {
  400. // Implementation is based on:
  401. // "A Fast Voxel Traversal Algorithm for Ray Tracing"
  402. // John Amanatides, Andrew Woo
  403. // http://www.cse.yorku.ca/~amana/research/grid.pdf
  404. // http://www.devmaster.net/articles/raytracing_series/A%20faster%20voxel%20traversal%20algorithm%20for%20ray%20tracing.pdf
  405. // NOTES:
  406. // * This code assumes that the ray's position and direction are in 'cell coordinates', which means
  407. // that one unit equals one cell in all directions.
  408. // * When the ray doesn't start within the voxel grid, calculate the first position at which the
  409. // ray could enter the grid. If it never enters the grid, there is nothing more to do here.
  410. // * Also, it is important to test when the ray exits the voxel grid when the grid isn't infinite.
  411. // * The Point3D structure is a simple structure having three integer fields (X, Y and Z).
  412. // The cell in which the ray starts.
  413. Point3D start = GetCellAt(ray.Position); // Rounds the position's X, Y and Z down to the nearest integer values.
  414. int x = start.X;
  415. int y = start.Y;
  416. int z = start.Z;
  417. // Determine which way we go.
  418. int stepX = Math.Sign(ray.Direction.X);
  419. int stepY = Math.Sign(ray.Direction.Y);
  420. int stepZ = Math.Sign(ray.Direction.Z);
  421. // Calculate cell boundaries. When the step (i.e. direction sign) is positive,
  422. // the next boundary is AFTER our current position, meaning that we have to add 1.
  423. // Otherwise, it is BEFORE our current position, in which case we add nothing.
  424. Point3D cellBoundary = new Point3D(
  425. x + (stepX > 0 ? 1 : 0),
  426. y + (stepY > 0 ? 1 : 0),
  427. z + (stepZ > 0 ? 1 : 0));
  428. // NOTE: For the following calculations, the result will be Single.PositiveInfinity
  429. // when ray.Direction.X, Y or Z equals zero, which is OK. However, when the left-hand
  430. // value of the division also equals zero, the result is Single.NaN, which is not OK.
  431. // Determine how far we can travel along the ray before we hit a voxel boundary.
  432. Vector3 tMax = new Vector3(
  433. (cellBoundary.X - ray.Position.X) / ray.Direction.X, // Boundary is a plane on the YZ axis.
  434. (cellBoundary.Y - ray.Position.Y) / ray.Direction.Y, // Boundary is a plane on the XZ axis.
  435. (cellBoundary.Z - ray.Position.Z) / ray.Direction.Z); // Boundary is a plane on the XY axis.
  436. if (Single.IsNaN(tMax.X)) tMax.X = Single.PositiveInfinity;
  437. if (Single.IsNaN(tMax.Y)) tMax.Y = Single.PositiveInfinity;
  438. if (Single.IsNaN(tMax.Z)) tMax.Z = Single.PositiveInfinity;
  439. // Determine how far we must travel along the ray before we have crossed a gridcell.
  440. Vector3 tDelta = new Vector3(
  441. stepX / ray.Direction.X, // Crossing the width of a cell.
  442. stepY / ray.Direction.Y, // Crossing the height of a cell.
  443. stepZ / ray.Direction.Z); // Crossing the depth of a cell.
  444. if (Single.IsNaN(tDelta.X)) tDelta.X = Single.PositiveInfinity;
  445. if (Single.IsNaN(tDelta.Y)) tDelta.Y = Single.PositiveInfinity;
  446. if (Single.IsNaN(tDelta.Z)) tDelta.Z = Single.PositiveInfinity;
  447. // For each step, determine which distance to the next voxel boundary is lowest (i.e.
  448. // which voxel boundary is nearest) and walk that way.
  449. for (int i = 0; i < maxDepth; i++)
  450. {
  451. // Return it.
  452. yield return new Point3D(x, y, z);
  453. // Do the next step.
  454. if (tMax.X < tMax.Y && tMax.X < tMax.Z)
  455. {
  456. // tMax.X is the lowest, an YZ cell boundary plane is nearest.
  457. x += stepX;
  458. tMax.X += tDelta.X;
  459. }
  460. else if (tMax.Y < tMax.Z)
  461. {
  462. // tMax.Y is the lowest, an XZ cell boundary plane is nearest.
  463. y += stepY;
  464. tMax.Y += tDelta.Y;
  465. }
  466. else
  467. {
  468. // tMax.Z is the lowest, an XY cell boundary plane is nearest.
  469. z += stepZ;
  470. tMax.Z += tDelta.Z;
  471. }
  472. }
  473. */