dynamic_bvh.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /**************************************************************************/
  2. /* dynamic_bvh.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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. #ifndef DYNAMIC_BVH_H
  31. #define DYNAMIC_BVH_H
  32. #include "core/math/aabb.h"
  33. #include "core/templates/list.h"
  34. #include "core/templates/local_vector.h"
  35. #include "core/templates/paged_allocator.h"
  36. #include "core/typedefs.h"
  37. // Based on bullet Dbvh
  38. /*
  39. Bullet Continuous Collision Detection and Physics Library
  40. Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
  41. This software is provided 'as-is', without any express or implied warranty.
  42. In no event will the authors be held liable for any damages arising from the use of this software.
  43. Permission is granted to anyone to use this software for any purpose,
  44. including commercial applications, and to alter it and redistribute it freely,
  45. subject to the following restrictions:
  46. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  47. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  48. 3. This notice may not be removed or altered from any source distribution.
  49. */
  50. ///DynamicBVH implementation by Nathanael Presson
  51. // The DynamicBVH class implements a fast dynamic bounding volume tree based on axis aligned bounding boxes (aabb tree).
  52. class DynamicBVH {
  53. struct Node;
  54. public:
  55. struct ID {
  56. Node *node = nullptr;
  57. public:
  58. _FORCE_INLINE_ bool is_valid() const { return node != nullptr; }
  59. };
  60. private:
  61. struct Volume {
  62. Vector3 min, max;
  63. _FORCE_INLINE_ Vector3 get_center() const { return ((min + max) / 2); }
  64. _FORCE_INLINE_ Vector3 get_length() const { return (max - min); }
  65. _FORCE_INLINE_ bool contains(const Volume &a) const {
  66. return ((min.x <= a.min.x) &&
  67. (min.y <= a.min.y) &&
  68. (min.z <= a.min.z) &&
  69. (max.x >= a.max.x) &&
  70. (max.y >= a.max.y) &&
  71. (max.z >= a.max.z));
  72. }
  73. _FORCE_INLINE_ Volume merge(const Volume &b) const {
  74. Volume r;
  75. for (int i = 0; i < 3; ++i) {
  76. if (min[i] < b.min[i]) {
  77. r.min[i] = min[i];
  78. } else {
  79. r.min[i] = b.min[i];
  80. }
  81. if (max[i] > b.max[i]) {
  82. r.max[i] = max[i];
  83. } else {
  84. r.max[i] = b.max[i];
  85. }
  86. }
  87. return r;
  88. }
  89. _FORCE_INLINE_ real_t get_size() const {
  90. const Vector3 edges = get_length();
  91. return (edges.x * edges.y * edges.z +
  92. edges.x + edges.y + edges.z);
  93. }
  94. _FORCE_INLINE_ bool is_not_equal_to(const Volume &b) const {
  95. return ((min.x != b.min.x) ||
  96. (min.y != b.min.y) ||
  97. (min.z != b.min.z) ||
  98. (max.x != b.max.x) ||
  99. (max.y != b.max.y) ||
  100. (max.z != b.max.z));
  101. }
  102. _FORCE_INLINE_ real_t get_proximity_to(const Volume &b) const {
  103. const Vector3 d = (min + max) - (b.min + b.max);
  104. return (Math::abs(d.x) + Math::abs(d.y) + Math::abs(d.z));
  105. }
  106. _FORCE_INLINE_ int select_by_proximity(const Volume &a, const Volume &b) const {
  107. return (get_proximity_to(a) < get_proximity_to(b) ? 0 : 1);
  108. }
  109. //
  110. _FORCE_INLINE_ bool intersects(const Volume &b) const {
  111. return ((min.x <= b.max.x) &&
  112. (max.x >= b.min.x) &&
  113. (min.y <= b.max.y) &&
  114. (max.y >= b.min.y) &&
  115. (min.z <= b.max.z) &&
  116. (max.z >= b.min.z));
  117. }
  118. _FORCE_INLINE_ bool intersects_convex(const Plane *p_planes, int p_plane_count, const Vector3 *p_points, int p_point_count) const {
  119. Vector3 half_extents = (max - min) * 0.5;
  120. Vector3 ofs = min + half_extents;
  121. for (int i = 0; i < p_plane_count; i++) {
  122. const Plane &p = p_planes[i];
  123. Vector3 point(
  124. (p.normal.x > 0) ? -half_extents.x : half_extents.x,
  125. (p.normal.y > 0) ? -half_extents.y : half_extents.y,
  126. (p.normal.z > 0) ? -half_extents.z : half_extents.z);
  127. point += ofs;
  128. if (p.is_point_over(point)) {
  129. return false;
  130. }
  131. }
  132. // Make sure all points in the shape aren't fully separated from the AABB on
  133. // each axis.
  134. int bad_point_counts_positive[3] = { 0 };
  135. int bad_point_counts_negative[3] = { 0 };
  136. for (int k = 0; k < 3; k++) {
  137. for (int i = 0; i < p_point_count; i++) {
  138. if (p_points[i].coord[k] > ofs.coord[k] + half_extents.coord[k]) {
  139. bad_point_counts_positive[k]++;
  140. }
  141. if (p_points[i].coord[k] < ofs.coord[k] - half_extents.coord[k]) {
  142. bad_point_counts_negative[k]++;
  143. }
  144. }
  145. if (bad_point_counts_negative[k] == p_point_count) {
  146. return false;
  147. }
  148. if (bad_point_counts_positive[k] == p_point_count) {
  149. return false;
  150. }
  151. }
  152. return true;
  153. }
  154. };
  155. struct Node {
  156. Volume volume;
  157. Node *parent = nullptr;
  158. union {
  159. Node *children[2];
  160. void *data;
  161. };
  162. _FORCE_INLINE_ bool is_leaf() const { return children[1] == nullptr; }
  163. _FORCE_INLINE_ bool is_internal() const { return (!is_leaf()); }
  164. _FORCE_INLINE_ int get_index_in_parent() const {
  165. ERR_FAIL_COND_V(!parent, 0);
  166. return (parent->children[1] == this) ? 1 : 0;
  167. }
  168. void get_max_depth(int depth, int &maxdepth) {
  169. if (is_internal()) {
  170. children[0]->get_max_depth(depth + 1, maxdepth);
  171. children[1]->get_max_depth(depth + 1, maxdepth);
  172. } else {
  173. maxdepth = MAX(maxdepth, depth);
  174. }
  175. }
  176. //
  177. int count_leaves() const {
  178. if (is_internal()) {
  179. return children[0]->count_leaves() + children[1]->count_leaves();
  180. } else {
  181. return (1);
  182. }
  183. }
  184. bool is_left_of_axis(const Vector3 &org, const Vector3 &axis) const {
  185. return axis.dot(volume.get_center() - org) <= 0;
  186. }
  187. Node() {
  188. children[0] = nullptr;
  189. children[1] = nullptr;
  190. }
  191. };
  192. PagedAllocator<Node> node_allocator;
  193. // Fields
  194. Node *bvh_root = nullptr;
  195. int lkhd = -1;
  196. int total_leaves = 0;
  197. uint32_t opath = 0;
  198. uint32_t index = 0;
  199. enum {
  200. ALLOCA_STACK_SIZE = 128
  201. };
  202. _FORCE_INLINE_ void _delete_node(Node *p_node);
  203. void _recurse_delete_node(Node *p_node);
  204. _FORCE_INLINE_ Node *_create_node(Node *p_parent, void *p_data);
  205. _FORCE_INLINE_ DynamicBVH::Node *_create_node_with_volume(Node *p_parent, const Volume &p_volume, void *p_data);
  206. _FORCE_INLINE_ void _insert_leaf(Node *p_root, Node *p_leaf);
  207. _FORCE_INLINE_ Node *_remove_leaf(Node *leaf);
  208. void _fetch_leaves(Node *p_root, LocalVector<Node *> &r_leaves, int p_depth = -1);
  209. static int _split(Node **leaves, int p_count, const Vector3 &p_org, const Vector3 &p_axis);
  210. static Volume _bounds(Node **leaves, int p_count);
  211. void _bottom_up(Node **leaves, int p_count);
  212. Node *_top_down(Node **leaves, int p_count, int p_bu_threshold);
  213. Node *_node_sort(Node *n, Node *&r);
  214. _FORCE_INLINE_ void _update(Node *leaf, int lookahead = -1);
  215. void _extract_leaves(Node *p_node, List<ID> *r_elements);
  216. _FORCE_INLINE_ bool _ray_aabb(const Vector3 &rayFrom, const Vector3 &rayInvDirection, const unsigned int raySign[3], const Vector3 bounds[2], real_t &tmin, real_t lambda_min, real_t lambda_max) {
  217. real_t tmax, tymin, tymax, tzmin, tzmax;
  218. tmin = (bounds[raySign[0]].x - rayFrom.x) * rayInvDirection.x;
  219. tmax = (bounds[1 - raySign[0]].x - rayFrom.x) * rayInvDirection.x;
  220. tymin = (bounds[raySign[1]].y - rayFrom.y) * rayInvDirection.y;
  221. tymax = (bounds[1 - raySign[1]].y - rayFrom.y) * rayInvDirection.y;
  222. if ((tmin > tymax) || (tymin > tmax)) {
  223. return false;
  224. }
  225. if (tymin > tmin) {
  226. tmin = tymin;
  227. }
  228. if (tymax < tmax) {
  229. tmax = tymax;
  230. }
  231. tzmin = (bounds[raySign[2]].z - rayFrom.z) * rayInvDirection.z;
  232. tzmax = (bounds[1 - raySign[2]].z - rayFrom.z) * rayInvDirection.z;
  233. if ((tmin > tzmax) || (tzmin > tmax)) {
  234. return false;
  235. }
  236. if (tzmin > tmin) {
  237. tmin = tzmin;
  238. }
  239. if (tzmax < tmax) {
  240. tmax = tzmax;
  241. }
  242. return ((tmin < lambda_max) && (tmax > lambda_min));
  243. }
  244. public:
  245. // Methods
  246. void clear();
  247. bool is_empty() const { return (nullptr == bvh_root); }
  248. void optimize_bottom_up();
  249. void optimize_top_down(int bu_threshold = 128);
  250. void optimize_incremental(int passes);
  251. ID insert(const AABB &p_box, void *p_userdata);
  252. bool update(const ID &p_id, const AABB &p_box);
  253. void remove(const ID &p_id);
  254. void get_elements(List<ID> *r_elements);
  255. int get_leaf_count() const;
  256. int get_max_depth() const;
  257. /* Discouraged, but works as a reference on how it must be used */
  258. struct DefaultQueryResult {
  259. virtual bool operator()(void *p_data) = 0; //return true whether you want to continue the query
  260. virtual ~DefaultQueryResult() {}
  261. };
  262. template <class QueryResult>
  263. _FORCE_INLINE_ void aabb_query(const AABB &p_aabb, QueryResult &r_result);
  264. template <class QueryResult>
  265. _FORCE_INLINE_ void convex_query(const Plane *p_planes, int p_plane_count, const Vector3 *p_points, int p_point_count, QueryResult &r_result);
  266. template <class QueryResult>
  267. _FORCE_INLINE_ void ray_query(const Vector3 &p_from, const Vector3 &p_to, QueryResult &r_result);
  268. void set_index(uint32_t p_index);
  269. uint32_t get_index() const;
  270. ~DynamicBVH();
  271. };
  272. template <class QueryResult>
  273. void DynamicBVH::aabb_query(const AABB &p_box, QueryResult &r_result) {
  274. if (!bvh_root) {
  275. return;
  276. }
  277. Volume volume;
  278. volume.min = p_box.position;
  279. volume.max = p_box.position + p_box.size;
  280. const Node **stack = (const Node **)alloca(ALLOCA_STACK_SIZE * sizeof(const Node *));
  281. stack[0] = bvh_root;
  282. int32_t depth = 1;
  283. int32_t threshold = ALLOCA_STACK_SIZE - 2;
  284. LocalVector<const Node *> aux_stack; //only used in rare occasions when you run out of alloca memory because tree is too unbalanced. Should correct itself over time.
  285. do {
  286. depth--;
  287. const Node *n = stack[depth];
  288. if (n->volume.intersects(volume)) {
  289. if (n->is_internal()) {
  290. if (depth > threshold) {
  291. if (aux_stack.is_empty()) {
  292. aux_stack.resize(ALLOCA_STACK_SIZE * 2);
  293. memcpy(aux_stack.ptr(), stack, ALLOCA_STACK_SIZE * sizeof(const Node *));
  294. } else {
  295. aux_stack.resize(aux_stack.size() * 2);
  296. }
  297. stack = aux_stack.ptr();
  298. threshold = aux_stack.size() - 2;
  299. }
  300. stack[depth++] = n->children[0];
  301. stack[depth++] = n->children[1];
  302. } else {
  303. if (r_result(n->data)) {
  304. return;
  305. }
  306. }
  307. }
  308. } while (depth > 0);
  309. }
  310. template <class QueryResult>
  311. void DynamicBVH::convex_query(const Plane *p_planes, int p_plane_count, const Vector3 *p_points, int p_point_count, QueryResult &r_result) {
  312. if (!bvh_root) {
  313. return;
  314. }
  315. //generate a volume anyway to improve pre-testing
  316. Volume volume;
  317. for (int i = 0; i < p_point_count; i++) {
  318. if (i == 0) {
  319. volume.min = p_points[0];
  320. volume.max = p_points[0];
  321. } else {
  322. volume.min.x = MIN(volume.min.x, p_points[i].x);
  323. volume.min.y = MIN(volume.min.y, p_points[i].y);
  324. volume.min.z = MIN(volume.min.z, p_points[i].z);
  325. volume.max.x = MAX(volume.max.x, p_points[i].x);
  326. volume.max.y = MAX(volume.max.y, p_points[i].y);
  327. volume.max.z = MAX(volume.max.z, p_points[i].z);
  328. }
  329. }
  330. const Node **stack = (const Node **)alloca(ALLOCA_STACK_SIZE * sizeof(const Node *));
  331. stack[0] = bvh_root;
  332. int32_t depth = 1;
  333. int32_t threshold = ALLOCA_STACK_SIZE - 2;
  334. LocalVector<const Node *> aux_stack; //only used in rare occasions when you run out of alloca memory because tree is too unbalanced. Should correct itself over time.
  335. do {
  336. depth--;
  337. const Node *n = stack[depth];
  338. if (n->volume.intersects(volume) && n->volume.intersects_convex(p_planes, p_plane_count, p_points, p_point_count)) {
  339. if (n->is_internal()) {
  340. if (depth > threshold) {
  341. if (aux_stack.is_empty()) {
  342. aux_stack.resize(ALLOCA_STACK_SIZE * 2);
  343. memcpy(aux_stack.ptr(), stack, ALLOCA_STACK_SIZE * sizeof(const Node *));
  344. } else {
  345. aux_stack.resize(aux_stack.size() * 2);
  346. }
  347. stack = aux_stack.ptr();
  348. threshold = aux_stack.size() - 2;
  349. }
  350. stack[depth++] = n->children[0];
  351. stack[depth++] = n->children[1];
  352. } else {
  353. if (r_result(n->data)) {
  354. return;
  355. }
  356. }
  357. }
  358. } while (depth > 0);
  359. }
  360. template <class QueryResult>
  361. void DynamicBVH::ray_query(const Vector3 &p_from, const Vector3 &p_to, QueryResult &r_result) {
  362. if (!bvh_root) {
  363. return;
  364. }
  365. Vector3 ray_dir = (p_to - p_from);
  366. ray_dir.normalize();
  367. ///what about division by zero? --> just set rayDirection[i] to INF/B3_LARGE_FLOAT
  368. Vector3 inv_dir;
  369. inv_dir[0] = ray_dir[0] == real_t(0.0) ? real_t(1e20) : real_t(1.0) / ray_dir[0];
  370. inv_dir[1] = ray_dir[1] == real_t(0.0) ? real_t(1e20) : real_t(1.0) / ray_dir[1];
  371. inv_dir[2] = ray_dir[2] == real_t(0.0) ? real_t(1e20) : real_t(1.0) / ray_dir[2];
  372. unsigned int signs[3] = { inv_dir[0] < 0.0, inv_dir[1] < 0.0, inv_dir[2] < 0.0 };
  373. real_t lambda_max = ray_dir.dot(p_to - p_from);
  374. Vector3 bounds[2];
  375. const Node **stack = (const Node **)alloca(ALLOCA_STACK_SIZE * sizeof(const Node *));
  376. stack[0] = bvh_root;
  377. int32_t depth = 1;
  378. int32_t threshold = ALLOCA_STACK_SIZE - 2;
  379. LocalVector<const Node *> aux_stack; //only used in rare occasions when you run out of alloca memory because tree is too unbalanced. Should correct itself over time.
  380. do {
  381. depth--;
  382. const Node *node = stack[depth];
  383. bounds[0] = node->volume.min;
  384. bounds[1] = node->volume.max;
  385. real_t tmin = 1.f, lambda_min = 0.f;
  386. unsigned int result1 = false;
  387. result1 = _ray_aabb(p_from, inv_dir, signs, bounds, tmin, lambda_min, lambda_max);
  388. if (result1) {
  389. if (node->is_internal()) {
  390. if (depth > threshold) {
  391. if (aux_stack.is_empty()) {
  392. aux_stack.resize(ALLOCA_STACK_SIZE * 2);
  393. memcpy(aux_stack.ptr(), stack, ALLOCA_STACK_SIZE * sizeof(const Node *));
  394. } else {
  395. aux_stack.resize(aux_stack.size() * 2);
  396. }
  397. stack = aux_stack.ptr();
  398. threshold = aux_stack.size() - 2;
  399. }
  400. stack[depth++] = node->children[0];
  401. stack[depth++] = node->children[1];
  402. } else {
  403. if (r_result(node->data)) {
  404. return;
  405. }
  406. }
  407. }
  408. } while (depth > 0);
  409. }
  410. #endif // DYNAMIC_BVH_H