bvh_tree.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /**************************************************************************/
  2. /* bvh_tree.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 BVH_TREE_H
  31. #define BVH_TREE_H
  32. // BVH Tree
  33. // This is an implementation of a dynamic BVH with templated leaf size.
  34. // This differs from most dynamic BVH in that it can handle more than 1 object
  35. // in leaf nodes. This can make it far more efficient in certain circumstances.
  36. // It also means that the splitting logic etc have to be completely different
  37. // to a simpler tree.
  38. // Note that MAX_CHILDREN should be fixed at 2 for now.
  39. #include "core/math/aabb.h"
  40. #include "core/math/bvh_abb.h"
  41. #include "core/math/geometry_3d.h"
  42. #include "core/math/vector3.h"
  43. #include "core/templates/local_vector.h"
  44. #include "core/templates/pooled_list.h"
  45. #include <limits.h>
  46. #define BVHABB_CLASS BVH_ABB<BOUNDS, POINT>
  47. // not sure if this is better yet so making optional
  48. #define BVH_EXPAND_LEAF_AABBS
  49. // never do these checks in release
  50. #ifdef DEV_ENABLED
  51. //#define BVH_VERBOSE
  52. //#define BVH_VERBOSE_TREE
  53. //#define BVH_VERBOSE_PAIRING
  54. //#define BVH_VERBOSE_MOVES
  55. //#define BVH_VERBOSE_FRAME
  56. //#define BVH_CHECKS
  57. //#define BVH_INTEGRITY_CHECKS
  58. #endif
  59. // debug only assert
  60. #ifdef BVH_CHECKS
  61. #define BVH_ASSERT(a) CRASH_COND((a) == false)
  62. #else
  63. #define BVH_ASSERT(a)
  64. #endif
  65. #ifdef BVH_VERBOSE
  66. #define VERBOSE_PRINT print_line
  67. #else
  68. #define VERBOSE_PRINT(a)
  69. #endif
  70. // really just a namespace
  71. struct BVHCommon {
  72. // these could possibly also be the same constant,
  73. // although this may be useful for debugging.
  74. // or use zero for invalid and +1 based indices.
  75. static const uint32_t INVALID = (0xffffffff);
  76. static const uint32_t INACTIVE = (0xfffffffe);
  77. };
  78. // really a handle, can be anything
  79. // note that zero is a valid reference for the BVH .. this may involve using
  80. // a plus one based ID for clients that expect 0 to be invalid.
  81. struct BVHHandle {
  82. // conversion operator
  83. operator uint32_t() const { return _data; }
  84. void set(uint32_t p_value) { _data = p_value; }
  85. uint32_t _data;
  86. void set_invalid() { _data = BVHCommon::INVALID; }
  87. bool is_invalid() const { return _data == BVHCommon::INVALID; }
  88. uint32_t id() const { return _data; }
  89. void set_id(uint32_t p_id) { _data = p_id; }
  90. bool operator==(const BVHHandle &p_h) const { return _data == p_h._data; }
  91. bool operator!=(const BVHHandle &p_h) const { return (*this == p_h) == false; }
  92. };
  93. // helper class to make iterative versions of recursive functions
  94. template <typename T>
  95. class BVH_IterativeInfo {
  96. public:
  97. constexpr static const size_t ALLOCA_STACK_SIZE = 128;
  98. int32_t depth = 1;
  99. int32_t threshold = ALLOCA_STACK_SIZE - 2;
  100. T *stack;
  101. //only used in rare occasions when you run out of alloca memory
  102. // because tree is too unbalanced.
  103. LocalVector<T> aux_stack;
  104. int32_t get_alloca_stacksize() const { return ALLOCA_STACK_SIZE * sizeof(T); }
  105. T *get_first() const {
  106. return &stack[0];
  107. }
  108. // pop the last member of the stack, or return false
  109. bool pop(T &r_value) {
  110. if (!depth) {
  111. return false;
  112. }
  113. depth--;
  114. r_value = stack[depth];
  115. return true;
  116. }
  117. // request new addition to stack
  118. T *request() {
  119. if (depth > threshold) {
  120. if (aux_stack.is_empty()) {
  121. aux_stack.resize(ALLOCA_STACK_SIZE * 2);
  122. memcpy(aux_stack.ptr(), stack, get_alloca_stacksize());
  123. } else {
  124. aux_stack.resize(aux_stack.size() * 2);
  125. }
  126. stack = aux_stack.ptr();
  127. threshold = aux_stack.size() - 2;
  128. }
  129. return &stack[depth++];
  130. }
  131. };
  132. template <typename T>
  133. class BVH_DummyPairTestFunction {
  134. public:
  135. static bool user_collision_check(T *p_a, T *p_b) {
  136. // return false if no collision, decided by masks etc
  137. return true;
  138. }
  139. };
  140. template <typename T>
  141. class BVH_DummyCullTestFunction {
  142. public:
  143. static bool user_cull_check(T *p_a, T *p_b) {
  144. // return false if no collision
  145. return true;
  146. }
  147. };
  148. template <typename T, int NUM_TREES, int MAX_CHILDREN, int MAX_ITEMS, typename USER_PAIR_TEST_FUNCTION = BVH_DummyPairTestFunction<T>, typename USER_CULL_TEST_FUNCTION = BVH_DummyCullTestFunction<T>, bool USE_PAIRS = false, typename BOUNDS = AABB, typename POINT = Vector3>
  149. class BVH_Tree {
  150. friend class BVH;
  151. #include "bvh_pair.inc"
  152. #include "bvh_structs.inc"
  153. public:
  154. BVH_Tree() {
  155. for (int n = 0; n < NUM_TREES; n++) {
  156. _root_node_id[n] = BVHCommon::INVALID;
  157. }
  158. // disallow zero leaf ids
  159. // (as these ids are stored as negative numbers in the node)
  160. uint32_t dummy_leaf_id;
  161. _leaves.request(dummy_leaf_id);
  162. // In many cases you may want to change this default in the client code,
  163. // or expose this value to the user.
  164. // This default may make sense for a typically scaled 3d game, but maybe not for 2d on a pixel scale.
  165. params_set_pairing_expansion(0.1);
  166. }
  167. private:
  168. bool node_add_child(uint32_t p_node_id, uint32_t p_child_node_id) {
  169. TNode &tnode = _nodes[p_node_id];
  170. if (tnode.is_full_of_children()) {
  171. return false;
  172. }
  173. tnode.children[tnode.num_children] = p_child_node_id;
  174. tnode.num_children += 1;
  175. // back link in the child to the parent
  176. TNode &tnode_child = _nodes[p_child_node_id];
  177. tnode_child.parent_id = p_node_id;
  178. return true;
  179. }
  180. void node_replace_child(uint32_t p_parent_id, uint32_t p_old_child_id, uint32_t p_new_child_id) {
  181. TNode &parent = _nodes[p_parent_id];
  182. BVH_ASSERT(!parent.is_leaf());
  183. int child_num = parent.find_child(p_old_child_id);
  184. BVH_ASSERT(child_num != -1);
  185. parent.children[child_num] = p_new_child_id;
  186. TNode &new_child = _nodes[p_new_child_id];
  187. new_child.parent_id = p_parent_id;
  188. }
  189. void node_remove_child(uint32_t p_parent_id, uint32_t p_child_id, uint32_t p_tree_id, bool p_prevent_sibling = false) {
  190. TNode &parent = _nodes[p_parent_id];
  191. BVH_ASSERT(!parent.is_leaf());
  192. int child_num = parent.find_child(p_child_id);
  193. BVH_ASSERT(child_num != -1);
  194. parent.remove_child_internal(child_num);
  195. // no need to keep back references for children at the moment
  196. uint32_t sibling_id = 0; // always a node id, as tnode is never a leaf
  197. bool sibling_present = false;
  198. // if there are more children, or this is the root node, don't try and delete
  199. if (parent.num_children > 1) {
  200. return;
  201. }
  202. // if there is 1 sibling, it can be moved to be a child of the
  203. if (parent.num_children == 1) {
  204. // else there is now a redundant node with one child, which can be removed
  205. sibling_id = parent.children[0];
  206. sibling_present = true;
  207. }
  208. // now there may be no children in this node .. in which case it can be deleted
  209. // remove node if empty
  210. // remove link from parent
  211. uint32_t grandparent_id = parent.parent_id;
  212. // special case for root node
  213. if (grandparent_id == BVHCommon::INVALID) {
  214. if (sibling_present) {
  215. // change the root node
  216. change_root_node(sibling_id, p_tree_id);
  217. // delete the old root node as no longer needed
  218. node_free_node_and_leaf(p_parent_id);
  219. }
  220. return;
  221. }
  222. if (sibling_present) {
  223. node_replace_child(grandparent_id, p_parent_id, sibling_id);
  224. } else {
  225. node_remove_child(grandparent_id, p_parent_id, p_tree_id, true);
  226. }
  227. // put the node on the free list to recycle
  228. node_free_node_and_leaf(p_parent_id);
  229. }
  230. // A node can either be a node, or a node AND a leaf combo.
  231. // Both must be deleted to prevent a leak.
  232. void node_free_node_and_leaf(uint32_t p_node_id) {
  233. TNode &node = _nodes[p_node_id];
  234. if (node.is_leaf()) {
  235. int leaf_id = node.get_leaf_id();
  236. _leaves.free(leaf_id);
  237. }
  238. _nodes.free(p_node_id);
  239. }
  240. void change_root_node(uint32_t p_new_root_id, uint32_t p_tree_id) {
  241. _root_node_id[p_tree_id] = p_new_root_id;
  242. TNode &root = _nodes[p_new_root_id];
  243. // mark no parent
  244. root.parent_id = BVHCommon::INVALID;
  245. }
  246. void node_make_leaf(uint32_t p_node_id) {
  247. uint32_t child_leaf_id;
  248. TLeaf *child_leaf = _leaves.request(child_leaf_id);
  249. child_leaf->clear();
  250. // zero is reserved at startup, to prevent this id being used
  251. // (as they are stored as negative values in the node, and zero is already taken)
  252. BVH_ASSERT(child_leaf_id != 0);
  253. TNode &node = _nodes[p_node_id];
  254. node.neg_leaf_id = -(int)child_leaf_id;
  255. }
  256. void node_remove_item(uint32_t p_ref_id, uint32_t p_tree_id, BVHABB_CLASS *r_old_aabb = nullptr) {
  257. // get the reference
  258. ItemRef &ref = _refs[p_ref_id];
  259. uint32_t owner_node_id = ref.tnode_id;
  260. // debug draw special
  261. // This may not be needed
  262. if (owner_node_id == BVHCommon::INVALID) {
  263. return;
  264. }
  265. TNode &tnode = _nodes[owner_node_id];
  266. CRASH_COND(!tnode.is_leaf());
  267. TLeaf &leaf = _node_get_leaf(tnode);
  268. // if the aabb is not determining the corner size, then there is no need to refit!
  269. // (optimization, as merging AABBs takes a lot of time)
  270. const BVHABB_CLASS &old_aabb = leaf.get_aabb(ref.item_id);
  271. // shrink a little to prevent using corner aabbs
  272. // in order to miss the corners first we shrink by node_expansion
  273. // (which is added to the overall bound of the leaf), then we also
  274. // shrink by an epsilon, in order to miss out the very corner aabbs
  275. // which are important in determining the bound. Any other aabb
  276. // within this can be removed and not affect the overall bound.
  277. BVHABB_CLASS node_bound = tnode.aabb;
  278. node_bound.expand(-_node_expansion - 0.001f);
  279. bool refit = true;
  280. if (node_bound.is_other_within(old_aabb)) {
  281. refit = false;
  282. }
  283. // record the old aabb if required (for incremental remove_and_reinsert)
  284. if (r_old_aabb) {
  285. *r_old_aabb = old_aabb;
  286. }
  287. leaf.remove_item_unordered(ref.item_id);
  288. if (leaf.num_items) {
  289. // the swapped item has to have its reference changed to, to point to the new item id
  290. uint32_t swapped_ref_id = leaf.get_item_ref_id(ref.item_id);
  291. ItemRef &swapped_ref = _refs[swapped_ref_id];
  292. swapped_ref.item_id = ref.item_id;
  293. // only have to refit if it is an edge item
  294. // This is a VERY EXPENSIVE STEP
  295. // we defer the refit updates until the update function is called once per frame
  296. if (refit) {
  297. leaf.set_dirty(true);
  298. }
  299. } else {
  300. // remove node if empty
  301. // remove link from parent
  302. if (tnode.parent_id != BVHCommon::INVALID) {
  303. // DANGER .. this can potentially end up with root node with 1 child ...
  304. // we don't want this and must check for it
  305. uint32_t parent_id = tnode.parent_id;
  306. node_remove_child(parent_id, owner_node_id, p_tree_id);
  307. refit_upward(parent_id);
  308. // put the node on the free list to recycle
  309. node_free_node_and_leaf(owner_node_id);
  310. }
  311. // else if no parent, it is the root node. Do not delete
  312. }
  313. ref.tnode_id = BVHCommon::INVALID;
  314. ref.item_id = BVHCommon::INVALID; // unset
  315. }
  316. // returns true if needs refit of PARENT tree only, the node itself AABB is calculated
  317. // within this routine
  318. bool _node_add_item(uint32_t p_node_id, uint32_t p_ref_id, const BVHABB_CLASS &p_aabb) {
  319. ItemRef &ref = _refs[p_ref_id];
  320. ref.tnode_id = p_node_id;
  321. TNode &node = _nodes[p_node_id];
  322. BVH_ASSERT(node.is_leaf());
  323. TLeaf &leaf = _node_get_leaf(node);
  324. // optimization - we only need to do a refit
  325. // if the added item is changing the AABB of the node.
  326. // in most cases it won't.
  327. bool needs_refit = true;
  328. // expand bound now
  329. BVHABB_CLASS expanded = p_aabb;
  330. expanded.expand(_node_expansion);
  331. // the bound will only be valid if there is an item in there already
  332. if (leaf.num_items) {
  333. if (node.aabb.is_other_within(expanded)) {
  334. // no change to node AABBs
  335. needs_refit = false;
  336. } else {
  337. node.aabb.merge(expanded);
  338. }
  339. } else {
  340. // bound of the node = the new aabb
  341. node.aabb = expanded;
  342. }
  343. ref.item_id = leaf.request_item();
  344. BVH_ASSERT(ref.item_id != BVHCommon::INVALID);
  345. // set the aabb of the new item
  346. leaf.get_aabb(ref.item_id) = p_aabb;
  347. // back reference on the item back to the item reference
  348. leaf.get_item_ref_id(ref.item_id) = p_ref_id;
  349. return needs_refit;
  350. }
  351. uint32_t _node_create_another_child(uint32_t p_node_id, const BVHABB_CLASS &p_aabb) {
  352. uint32_t child_node_id;
  353. TNode *child_node = _nodes.request(child_node_id);
  354. child_node->clear();
  355. // may not be necessary
  356. child_node->aabb = p_aabb;
  357. node_add_child(p_node_id, child_node_id);
  358. return child_node_id;
  359. }
  360. #include "bvh_cull.inc"
  361. #include "bvh_debug.inc"
  362. #include "bvh_integrity.inc"
  363. #include "bvh_logic.inc"
  364. #include "bvh_misc.inc"
  365. #include "bvh_public.inc"
  366. #include "bvh_refit.inc"
  367. #include "bvh_split.inc"
  368. };
  369. #undef VERBOSE_PRINT
  370. #endif // BVH_TREE_H