broad_phase_2d_hash_grid.cpp 20 KB

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