broad_phase_2d_hash_grid.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. /*************************************************************************/
  2. /* broad_phase_2d_hash_grid.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "broad_phase_2d_hash_grid.h"
  31. #include "collision_object_2d_sw.h"
  32. #include "core/config/project_settings.h"
  33. #define LARGE_ELEMENT_FI 1.01239812
  34. void BroadPhase2DHashGrid::_pair_attempt(Element *p_elem, Element *p_with) {
  35. Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with);
  36. ERR_FAIL_COND(p_elem->_static && p_with->_static);
  37. if (!E) {
  38. PairData *pd = memnew(PairData);
  39. p_elem->paired[p_with] = pd;
  40. p_with->paired[p_elem] = pd;
  41. } else {
  42. E->get()->rc++;
  43. }
  44. }
  45. void BroadPhase2DHashGrid::_unpair_attempt(Element *p_elem, Element *p_with) {
  46. Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with);
  47. ERR_FAIL_COND(!E); //this should really be paired..
  48. E->get()->rc--;
  49. if (E->get()->rc == 0) {
  50. if (E->get()->colliding) {
  51. //uncollide
  52. if (unpair_callback) {
  53. unpair_callback(p_elem->owner, p_elem->subindex, p_with->owner, p_with->subindex, E->get()->ud, unpair_userdata);
  54. }
  55. }
  56. memdelete(E->get());
  57. p_elem->paired.erase(E);
  58. p_with->paired.erase(p_elem);
  59. }
  60. }
  61. void BroadPhase2DHashGrid::_check_motion(Element *p_elem) {
  62. for (Map<Element *, PairData *>::Element *E = p_elem->paired.front(); E; E = E->next()) {
  63. bool physical_collision = p_elem->aabb.intersects(E->key()->aabb);
  64. bool logical_collision = p_elem->owner->test_collision_mask(E->key()->owner);
  65. if (physical_collision) {
  66. if (!E->get()->colliding || (logical_collision && !E->get()->ud && pair_callback)) {
  67. E->get()->ud = pair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, pair_userdata);
  68. } else if (E->get()->colliding && !logical_collision && E->get()->ud && unpair_callback) {
  69. unpair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, E->get()->ud, unpair_userdata);
  70. E->get()->ud = nullptr;
  71. }
  72. E->get()->colliding = true;
  73. } else { // No physcial_collision
  74. if (E->get()->colliding && unpair_callback) {
  75. unpair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, E->get()->ud, unpair_userdata);
  76. }
  77. E->get()->colliding = false;
  78. }
  79. }
  80. }
  81. void BroadPhase2DHashGrid::_enter_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) {
  82. Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI); //use magic number to avoid floating point issues
  83. if (sz.width * sz.height > large_object_min_surface) {
  84. //large object, do not use grid, must check against all elements
  85. for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) {
  86. if (E->key() == p_elem->self) {
  87. continue; // do not pair against itself
  88. }
  89. if (E->get().owner == p_elem->owner) {
  90. continue;
  91. }
  92. if (E->get()._static && p_static) {
  93. continue;
  94. }
  95. _pair_attempt(p_elem, &E->get());
  96. }
  97. large_elements[p_elem].inc();
  98. return;
  99. }
  100. Point2i from = (p_rect.position / cell_size).floor();
  101. Point2i to = ((p_rect.position + p_rect.size) / cell_size).floor();
  102. for (int i = from.x; i <= to.x; i++) {
  103. for (int j = from.y; j <= to.y; j++) {
  104. PosKey pk;
  105. pk.x = i;
  106. pk.y = j;
  107. uint32_t idx = pk.hash() % hash_table_size;
  108. PosBin *pb = hash_table[idx];
  109. while (pb) {
  110. if (pb->key == pk) {
  111. break;
  112. }
  113. pb = pb->next;
  114. }
  115. bool entered = false;
  116. if (!pb) {
  117. //does not exist, create!
  118. pb = memnew(PosBin);
  119. pb->key = pk;
  120. pb->next = hash_table[idx];
  121. hash_table[idx] = pb;
  122. }
  123. if (p_static) {
  124. if (pb->static_object_set[p_elem].inc() == 1) {
  125. entered = true;
  126. }
  127. } else {
  128. if (pb->object_set[p_elem].inc() == 1) {
  129. entered = true;
  130. }
  131. }
  132. if (entered) {
  133. for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
  134. if (E->key()->owner == p_elem->owner) {
  135. continue;
  136. }
  137. _pair_attempt(p_elem, E->key());
  138. }
  139. if (!p_static) {
  140. for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
  141. if (E->key()->owner == p_elem->owner) {
  142. continue;
  143. }
  144. _pair_attempt(p_elem, E->key());
  145. }
  146. }
  147. }
  148. }
  149. }
  150. //pair separatedly with large elements
  151. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  152. if (E->key() == p_elem) {
  153. continue; // do not pair against itself
  154. }
  155. if (E->key()->owner == p_elem->owner) {
  156. continue;
  157. }
  158. if (E->key()->_static && p_static) {
  159. continue;
  160. }
  161. _pair_attempt(E->key(), p_elem);
  162. }
  163. }
  164. void BroadPhase2DHashGrid::_exit_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) {
  165. Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI);
  166. if (sz.width * sz.height > large_object_min_surface) {
  167. //unpair all elements, instead of checking all, just check what is already paired, so we at least save from checking static vs static
  168. Map<Element *, PairData *>::Element *E = p_elem->paired.front();
  169. while (E) {
  170. Map<Element *, PairData *>::Element *next = E->next();
  171. _unpair_attempt(p_elem, E->key());
  172. E = next;
  173. }
  174. if (large_elements[p_elem].dec() == 0) {
  175. large_elements.erase(p_elem);
  176. }
  177. return;
  178. }
  179. Point2i from = (p_rect.position / cell_size).floor();
  180. Point2i to = ((p_rect.position + p_rect.size) / cell_size).floor();
  181. for (int i = from.x; i <= to.x; i++) {
  182. for (int j = from.y; j <= to.y; j++) {
  183. PosKey pk;
  184. pk.x = i;
  185. pk.y = j;
  186. uint32_t idx = pk.hash() % hash_table_size;
  187. PosBin *pb = hash_table[idx];
  188. while (pb) {
  189. if (pb->key == pk) {
  190. break;
  191. }
  192. pb = pb->next;
  193. }
  194. ERR_CONTINUE(!pb); //should exist!!
  195. bool exited = false;
  196. if (p_static) {
  197. if (pb->static_object_set[p_elem].dec() == 0) {
  198. pb->static_object_set.erase(p_elem);
  199. exited = true;
  200. }
  201. } else {
  202. if (pb->object_set[p_elem].dec() == 0) {
  203. pb->object_set.erase(p_elem);
  204. exited = true;
  205. }
  206. }
  207. if (exited) {
  208. for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
  209. if (E->key()->owner == p_elem->owner) {
  210. continue;
  211. }
  212. _unpair_attempt(p_elem, E->key());
  213. }
  214. if (!p_static) {
  215. for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
  216. if (E->key()->owner == p_elem->owner) {
  217. continue;
  218. }
  219. _unpair_attempt(p_elem, E->key());
  220. }
  221. }
  222. }
  223. if (pb->object_set.is_empty() && pb->static_object_set.is_empty()) {
  224. if (hash_table[idx] == pb) {
  225. hash_table[idx] = pb->next;
  226. } else {
  227. PosBin *px = hash_table[idx];
  228. while (px) {
  229. if (px->next == pb) {
  230. px->next = pb->next;
  231. break;
  232. }
  233. px = px->next;
  234. }
  235. ERR_CONTINUE(!px);
  236. }
  237. memdelete(pb);
  238. }
  239. }
  240. }
  241. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  242. if (E->key() == p_elem) {
  243. continue; // do not pair against itself
  244. }
  245. if (E->key()->owner == p_elem->owner) {
  246. continue;
  247. }
  248. if (E->key()->_static && p_static) {
  249. continue;
  250. }
  251. //unpair from large elements
  252. _unpair_attempt(p_elem, E->key());
  253. }
  254. }
  255. BroadPhase2DHashGrid::ID BroadPhase2DHashGrid::create(CollisionObject2DSW *p_object, int p_subindex) {
  256. current++;
  257. Element e;
  258. e.owner = p_object;
  259. e._static = false;
  260. e.subindex = p_subindex;
  261. e.self = current;
  262. e.pass = 0;
  263. element_map[current] = e;
  264. return current;
  265. }
  266. void BroadPhase2DHashGrid::move(ID p_id, const Rect2 &p_aabb) {
  267. Map<ID, Element>::Element *E = element_map.find(p_id);
  268. ERR_FAIL_COND(!E);
  269. Element &e = E->get();
  270. if (p_aabb != e.aabb) {
  271. if (p_aabb != Rect2()) {
  272. _enter_grid(&e, p_aabb, e._static);
  273. }
  274. if (e.aabb != Rect2()) {
  275. _exit_grid(&e, e.aabb, e._static);
  276. }
  277. e.aabb = p_aabb;
  278. }
  279. _check_motion(&e);
  280. }
  281. void BroadPhase2DHashGrid::set_static(ID p_id, bool p_static) {
  282. Map<ID, Element>::Element *E = element_map.find(p_id);
  283. ERR_FAIL_COND(!E);
  284. Element &e = E->get();
  285. if (e._static == p_static) {
  286. return;
  287. }
  288. if (e.aabb != Rect2()) {
  289. _exit_grid(&e, e.aabb, e._static);
  290. }
  291. e._static = p_static;
  292. if (e.aabb != Rect2()) {
  293. _enter_grid(&e, e.aabb, e._static);
  294. _check_motion(&e);
  295. }
  296. }
  297. void BroadPhase2DHashGrid::remove(ID p_id) {
  298. Map<ID, Element>::Element *E = element_map.find(p_id);
  299. ERR_FAIL_COND(!E);
  300. Element &e = E->get();
  301. if (e.aabb != Rect2()) {
  302. _exit_grid(&e, e.aabb, e._static);
  303. }
  304. element_map.erase(p_id);
  305. }
  306. CollisionObject2DSW *BroadPhase2DHashGrid::get_object(ID p_id) const {
  307. const Map<ID, Element>::Element *E = element_map.find(p_id);
  308. ERR_FAIL_COND_V(!E, nullptr);
  309. return E->get().owner;
  310. }
  311. bool BroadPhase2DHashGrid::is_static(ID p_id) const {
  312. const Map<ID, Element>::Element *E = element_map.find(p_id);
  313. ERR_FAIL_COND_V(!E, false);
  314. return E->get()._static;
  315. }
  316. int BroadPhase2DHashGrid::get_subindex(ID p_id) const {
  317. const Map<ID, Element>::Element *E = element_map.find(p_id);
  318. ERR_FAIL_COND_V(!E, -1);
  319. return E->get().subindex;
  320. }
  321. template <bool use_aabb, bool use_segment>
  322. 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) {
  323. PosKey pk;
  324. pk.x = p_cell.x;
  325. pk.y = p_cell.y;
  326. uint32_t idx = pk.hash() % hash_table_size;
  327. PosBin *pb = hash_table[idx];
  328. while (pb) {
  329. if (pb->key == pk) {
  330. break;
  331. }
  332. pb = pb->next;
  333. }
  334. if (!pb) {
  335. return;
  336. }
  337. for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
  338. if (index >= p_max_results) {
  339. break;
  340. }
  341. if (E->key()->pass == pass) {
  342. continue;
  343. }
  344. E->key()->pass = pass;
  345. if (use_aabb && !p_aabb.intersects(E->key()->aabb)) {
  346. continue;
  347. }
  348. if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to)) {
  349. continue;
  350. }
  351. p_results[index] = E->key()->owner;
  352. p_result_indices[index] = E->key()->subindex;
  353. index++;
  354. }
  355. for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
  356. if (index >= p_max_results) {
  357. break;
  358. }
  359. if (E->key()->pass == pass) {
  360. continue;
  361. }
  362. if (use_aabb && !p_aabb.intersects(E->key()->aabb)) {
  363. continue;
  364. }
  365. if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to)) {
  366. continue;
  367. }
  368. E->key()->pass = pass;
  369. p_results[index] = E->key()->owner;
  370. p_result_indices[index] = E->key()->subindex;
  371. index++;
  372. }
  373. }
  374. int BroadPhase2DHashGrid::cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
  375. pass++;
  376. Vector2 dir = (p_to - p_from);
  377. if (dir == Vector2()) {
  378. return 0;
  379. }
  380. //avoid divisions by zero
  381. dir.normalize();
  382. if (dir.x == 0.0) {
  383. dir.x = 0.000001;
  384. }
  385. if (dir.y == 0.0) {
  386. dir.y = 0.000001;
  387. }
  388. Vector2 delta = dir.abs();
  389. delta.x = cell_size / delta.x;
  390. delta.y = cell_size / delta.y;
  391. Point2i pos = (p_from / cell_size).floor();
  392. Point2i end = (p_to / cell_size).floor();
  393. Point2i step = Vector2(SGN(dir.x), SGN(dir.y));
  394. Vector2 max;
  395. if (dir.x < 0) {
  396. max.x = (Math::floor((double)pos.x) * cell_size - p_from.x) / dir.x;
  397. } else {
  398. max.x = (Math::floor((double)pos.x + 1) * cell_size - p_from.x) / dir.x;
  399. }
  400. if (dir.y < 0) {
  401. max.y = (Math::floor((double)pos.y) * cell_size - p_from.y) / dir.y;
  402. } else {
  403. max.y = (Math::floor((double)pos.y + 1) * cell_size - p_from.y) / dir.y;
  404. }
  405. int cullcount = 0;
  406. _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount);
  407. bool reached_x = false;
  408. bool reached_y = false;
  409. while (true) {
  410. if (max.x < max.y) {
  411. max.x += delta.x;
  412. pos.x += step.x;
  413. } else {
  414. max.y += delta.y;
  415. pos.y += step.y;
  416. }
  417. if (step.x > 0) {
  418. if (pos.x >= end.x) {
  419. reached_x = true;
  420. }
  421. } else if (pos.x <= end.x) {
  422. reached_x = true;
  423. }
  424. if (step.y > 0) {
  425. if (pos.y >= end.y) {
  426. reached_y = true;
  427. }
  428. } else if (pos.y <= end.y) {
  429. reached_y = true;
  430. }
  431. _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount);
  432. if (reached_x && reached_y) {
  433. break;
  434. }
  435. }
  436. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  437. if (cullcount >= p_max_results) {
  438. break;
  439. }
  440. if (E->key()->pass == pass) {
  441. continue;
  442. }
  443. E->key()->pass = pass;
  444. /*
  445. if (use_aabb && !p_aabb.intersects(E->key()->aabb))
  446. continue;
  447. */
  448. if (!E->key()->aabb.intersects_segment(p_from, p_to)) {
  449. continue;
  450. }
  451. p_results[cullcount] = E->key()->owner;
  452. p_result_indices[cullcount] = E->key()->subindex;
  453. cullcount++;
  454. }
  455. return cullcount;
  456. }
  457. int BroadPhase2DHashGrid::cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
  458. pass++;
  459. Point2i from = (p_aabb.position / cell_size).floor();
  460. Point2i to = ((p_aabb.position + p_aabb.size) / cell_size).floor();
  461. int cullcount = 0;
  462. for (int i = from.x; i <= to.x; i++) {
  463. for (int j = from.y; j <= to.y; j++) {
  464. _cull<true, false>(Point2i(i, j), p_aabb, Point2(), Point2(), p_results, p_max_results, p_result_indices, cullcount);
  465. }
  466. }
  467. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  468. if (cullcount >= p_max_results) {
  469. break;
  470. }
  471. if (E->key()->pass == pass) {
  472. continue;
  473. }
  474. E->key()->pass = pass;
  475. if (!p_aabb.intersects(E->key()->aabb)) {
  476. continue;
  477. }
  478. /*
  479. if (!E->key()->aabb.intersects_segment(p_from,p_to))
  480. continue;
  481. */
  482. p_results[cullcount] = E->key()->owner;
  483. p_result_indices[cullcount] = E->key()->subindex;
  484. cullcount++;
  485. }
  486. return cullcount;
  487. }
  488. void BroadPhase2DHashGrid::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) {
  489. pair_callback = p_pair_callback;
  490. pair_userdata = p_userdata;
  491. }
  492. void BroadPhase2DHashGrid::set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) {
  493. unpair_callback = p_unpair_callback;
  494. unpair_userdata = p_userdata;
  495. }
  496. void BroadPhase2DHashGrid::update() {
  497. }
  498. BroadPhase2DSW *BroadPhase2DHashGrid::_create() {
  499. return memnew(BroadPhase2DHashGrid);
  500. }
  501. BroadPhase2DHashGrid::BroadPhase2DHashGrid() {
  502. hash_table_size = GLOBAL_DEF("physics/2d/bp_hash_table_size", 4096);
  503. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/bp_hash_table_size", PropertyInfo(Variant::INT, "physics/2d/bp_hash_table_size", PROPERTY_HINT_RANGE, "0,8192,1,or_greater"));
  504. hash_table_size = Math::larger_prime(hash_table_size);
  505. hash_table = memnew_arr(PosBin *, hash_table_size);
  506. cell_size = GLOBAL_DEF("physics/2d/cell_size", 128);
  507. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/cell_size", PropertyInfo(Variant::INT, "physics/2d/cell_size", PROPERTY_HINT_RANGE, "0,512,1,or_greater"));
  508. large_object_min_surface = GLOBAL_DEF("physics/2d/large_object_surface_threshold_in_cells", 512);
  509. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/large_object_surface_threshold_in_cells", PropertyInfo(Variant::INT, "physics/2d/large_object_surface_threshold_in_cells", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"));
  510. for (uint32_t i = 0; i < hash_table_size; i++) {
  511. hash_table[i] = nullptr;
  512. }
  513. pass = 1;
  514. current = 0;
  515. }
  516. BroadPhase2DHashGrid::~BroadPhase2DHashGrid() {
  517. for (uint32_t i = 0; i < hash_table_size; i++) {
  518. while (hash_table[i]) {
  519. PosBin *pb = hash_table[i];
  520. hash_table[i] = pb->next;
  521. memdelete(pb);
  522. }
  523. }
  524. memdelete_arr(hash_table);
  525. }
  526. /* 3D version of voxel traversal:
  527. public IEnumerable<Point3D> GetCellsOnRay(Ray ray, int maxDepth)
  528. {
  529. // Implementation is based on:
  530. // "A Fast Voxel Traversal Algorithm for Ray Tracing"
  531. // John Amanatides, Andrew Woo
  532. // http://www.cse.yorku.ca/~amana/research/grid.pdf
  533. // https://web.archive.org/web/20100616193049/http://www.devmaster.net/articles/raytracing_series/A%20faster%20voxel%20traversal%20algorithm%20for%20ray%20tracing.pdf
  534. // NOTES:
  535. // * This code assumes that the ray's position and direction are in 'cell coordinates', which means
  536. // that one unit equals one cell in all directions.
  537. // * When the ray doesn't start within the voxel grid, calculate the first position at which the
  538. // ray could enter the grid. If it never enters the grid, there is nothing more to do here.
  539. // * Also, it is important to test when the ray exits the voxel grid when the grid isn't infinite.
  540. // * The Point3D structure is a simple structure having three integer fields (X, Y and Z).
  541. // The cell in which the ray starts.
  542. Point3D start = GetCellAt(ray.Position); // Rounds the position's X, Y and Z down to the nearest integer values.
  543. int x = start.X;
  544. int y = start.Y;
  545. int z = start.Z;
  546. // Determine which way we go.
  547. int stepX = Math.Sign(ray.Direction.X);
  548. int stepY = Math.Sign(ray.Direction.Y);
  549. int stepZ = Math.Sign(ray.Direction.Z);
  550. // Calculate cell boundaries. When the step (i.e. direction sign) is positive,
  551. // the next boundary is AFTER our current position, meaning that we have to add 1.
  552. // Otherwise, it is BEFORE our current position, in which case we add nothing.
  553. Point3D cellBoundary = new Point3D(
  554. x + (stepX > 0 ? 1 : 0),
  555. y + (stepY > 0 ? 1 : 0),
  556. z + (stepZ > 0 ? 1 : 0));
  557. // NOTE: For the following calculations, the result will be Single.PositiveInfinity
  558. // when ray.Direction.X, Y or Z equals zero, which is OK. However, when the left-hand
  559. // value of the division also equals zero, the result is Single.NaN, which is not OK.
  560. // Determine how far we can travel along the ray before we hit a voxel boundary.
  561. Vector3 tMax = new Vector3(
  562. (cellBoundary.X - ray.Position.X) / ray.Direction.X, // Boundary is a plane on the YZ axis.
  563. (cellBoundary.Y - ray.Position.Y) / ray.Direction.Y, // Boundary is a plane on the XZ axis.
  564. (cellBoundary.Z - ray.Position.Z) / ray.Direction.Z); // Boundary is a plane on the XY axis.
  565. if (Single.IsNaN(tMax.X)) tMax.X = Single.PositiveInfinity;
  566. if (Single.IsNaN(tMax.Y)) tMax.Y = Single.PositiveInfinity;
  567. if (Single.IsNaN(tMax.Z)) tMax.Z = Single.PositiveInfinity;
  568. // Determine how far we must travel along the ray before we have crossed a gridcell.
  569. Vector3 tDelta = new Vector3(
  570. stepX / ray.Direction.X, // Crossing the width of a cell.
  571. stepY / ray.Direction.Y, // Crossing the height of a cell.
  572. stepZ / ray.Direction.Z); // Crossing the depth of a cell.
  573. if (Single.IsNaN(tDelta.X)) tDelta.X = Single.PositiveInfinity;
  574. if (Single.IsNaN(tDelta.Y)) tDelta.Y = Single.PositiveInfinity;
  575. if (Single.IsNaN(tDelta.Z)) tDelta.Z = Single.PositiveInfinity;
  576. // For each step, determine which distance to the next voxel boundary is lowest (i.e.
  577. // which voxel boundary is nearest) and walk that way.
  578. for (int i = 0; i < maxDepth; i++)
  579. {
  580. // Return it.
  581. yield return new Point3D(x, y, z);
  582. // Do the next step.
  583. if (tMax.X < tMax.Y && tMax.X < tMax.Z)
  584. {
  585. // tMax.X is the lowest, an YZ cell boundary plane is nearest.
  586. x += stepX;
  587. tMax.X += tDelta.X;
  588. }
  589. else if (tMax.Y < tMax.Z)
  590. {
  591. // tMax.Y is the lowest, an XZ cell boundary plane is nearest.
  592. y += stepY;
  593. tMax.Y += tDelta.Y;
  594. }
  595. else
  596. {
  597. // tMax.Z is the lowest, an XY cell boundary plane is nearest.
  598. z += stepZ;
  599. tMax.Z += tDelta.Z;
  600. }
  601. }
  602. */