bvh_tree.h 13 KB

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