/**************************************************************************/1/* bvh_tree.h */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#pragma once3132// BVH Tree33// 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 object35// 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 different37// to a simpler tree.38// Note that MAX_CHILDREN should be fixed at 2 for now.3940#include "core/math/aabb.h"41#include "core/math/bvh_abb.h"42#include "core/math/vector3.h"43#include "core/templates/local_vector.h"44#include "core/templates/pooled_list.h"4546#include <climits>4748#define BVHABB_CLASS BVH_ABB<BOUNDS, POINT>4950// not sure if this is better yet so making optional51#define BVH_EXPAND_LEAF_AABBS5253// never do these checks in release54#ifdef DEV_ENABLED55//#define BVH_VERBOSE56//#define BVH_VERBOSE_TREE57//#define BVH_VERBOSE_PAIRING58//#define BVH_VERBOSE_MOVES5960//#define BVH_VERBOSE_FRAME61//#define BVH_CHECKS62//#define BVH_INTEGRITY_CHECKS63#endif6465// debug only assert66#ifdef BVH_CHECKS67#define BVH_ASSERT(a) CRASH_COND((a) == false)68#else69#define BVH_ASSERT(a)70#endif7172#ifdef BVH_VERBOSE73#define VERBOSE_PRINT print_line74#else75#define VERBOSE_PRINT(a)76#endif7778// really just a namespace79struct BVHCommon {80// these could possibly also be the same constant,81// although this may be useful for debugging.82// or use zero for invalid and +1 based indices.83static const uint32_t INVALID = (0xffffffff);84static const uint32_t INACTIVE = (0xfffffffe);85};8687// really a handle, can be anything88// note that zero is a valid reference for the BVH .. this may involve using89// a plus one based ID for clients that expect 0 to be invalid.90struct BVHHandle {91// conversion operator92operator uint32_t() const { return _data; }93void set(uint32_t p_value) { _data = p_value; }9495uint32_t _data;9697void set_invalid() { _data = BVHCommon::INVALID; }98bool is_invalid() const { return _data == BVHCommon::INVALID; }99uint32_t id() const { return _data; }100void set_id(uint32_t p_id) { _data = p_id; }101102bool operator==(const BVHHandle &p_h) const { return _data == p_h._data; }103bool operator!=(const BVHHandle &p_h) const { return (*this == p_h) == false; }104};105106// helper class to make iterative versions of recursive functions107template <typename T>108class BVH_IterativeInfo {109public:110constexpr static const size_t ALLOCA_STACK_SIZE = 128;111112int32_t depth = 1;113int32_t threshold = ALLOCA_STACK_SIZE - 2;114T *stack;115//only used in rare occasions when you run out of alloca memory116// because tree is too unbalanced.117LocalVector<T> aux_stack;118int32_t get_alloca_stacksize() const { return ALLOCA_STACK_SIZE * sizeof(T); }119120T *get_first() const {121return &stack[0];122}123124// pop the last member of the stack, or return false125bool pop(T &r_value) {126if (!depth) {127return false;128}129130depth--;131r_value = stack[depth];132return true;133}134135// request new addition to stack136T *request() {137if (depth > threshold) {138if (aux_stack.is_empty()) {139aux_stack.resize(ALLOCA_STACK_SIZE * 2);140memcpy(aux_stack.ptr(), stack, get_alloca_stacksize());141} else {142aux_stack.resize(aux_stack.size() * 2);143}144stack = aux_stack.ptr();145threshold = aux_stack.size() - 2;146}147return &stack[depth++];148}149};150151template <typename T>152class BVH_DummyPairTestFunction {153public:154static bool user_collision_check(T *p_a, T *p_b) {155// return false if no collision, decided by masks etc156return true;157}158};159160template <typename T>161class BVH_DummyCullTestFunction {162public:163static bool user_cull_check(T *p_a, T *p_b) {164// return false if no collision165return true;166}167};168169template <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>170class BVH_Tree {171friend class BVH;172173#include "bvh_pair.inc"174#include "bvh_structs.inc"175176public:177BVH_Tree() {178for (int n = 0; n < NUM_TREES; n++) {179_root_node_id[n] = BVHCommon::INVALID;180}181182// disallow zero leaf ids183// (as these ids are stored as negative numbers in the node)184uint32_t dummy_leaf_id;185_leaves.request(dummy_leaf_id);186187// In many cases you may want to change this default in the client code,188// or expose this value to the user.189// This default may make sense for a typically scaled 3d game, but maybe not for 2d on a pixel scale.190params_set_pairing_expansion(0.1);191}192193private:194bool node_add_child(uint32_t p_node_id, uint32_t p_child_node_id) {195TNode &tnode = _nodes[p_node_id];196if (tnode.is_full_of_children()) {197return false;198}199200tnode.children[tnode.num_children] = p_child_node_id;201tnode.num_children += 1;202203// back link in the child to the parent204TNode &tnode_child = _nodes[p_child_node_id];205tnode_child.parent_id = p_node_id;206207return true;208}209210void node_replace_child(uint32_t p_parent_id, uint32_t p_old_child_id, uint32_t p_new_child_id) {211TNode &parent = _nodes[p_parent_id];212BVH_ASSERT(!parent.is_leaf());213214int child_num = parent.find_child(p_old_child_id);215BVH_ASSERT(child_num != -1);216parent.children[child_num] = p_new_child_id;217218TNode &new_child = _nodes[p_new_child_id];219new_child.parent_id = p_parent_id;220}221222void node_remove_child(uint32_t p_parent_id, uint32_t p_child_id, uint32_t p_tree_id, bool p_prevent_sibling = false) {223TNode &parent = _nodes[p_parent_id];224BVH_ASSERT(!parent.is_leaf());225226int child_num = parent.find_child(p_child_id);227BVH_ASSERT(child_num != -1);228229parent.remove_child_internal(child_num);230231// no need to keep back references for children at the moment232233uint32_t sibling_id = 0; // always a node id, as tnode is never a leaf234bool sibling_present = false;235236// if there are more children, or this is the root node, don't try and delete237if (parent.num_children > 1) {238return;239}240241// if there is 1 sibling, it can be moved to be a child of the242if (parent.num_children == 1) {243// else there is now a redundant node with one child, which can be removed244sibling_id = parent.children[0];245sibling_present = true;246}247248// now there may be no children in this node .. in which case it can be deleted249// remove node if empty250// remove link from parent251uint32_t grandparent_id = parent.parent_id;252253// special case for root node254if (grandparent_id == BVHCommon::INVALID) {255if (sibling_present) {256// change the root node257change_root_node(sibling_id, p_tree_id);258259// delete the old root node as no longer needed260node_free_node_and_leaf(p_parent_id);261}262263return;264}265266if (sibling_present) {267node_replace_child(grandparent_id, p_parent_id, sibling_id);268} else {269node_remove_child(grandparent_id, p_parent_id, p_tree_id, true);270}271272// put the node on the free list to recycle273node_free_node_and_leaf(p_parent_id);274}275276// A node can either be a node, or a node AND a leaf combo.277// Both must be deleted to prevent a leak.278void node_free_node_and_leaf(uint32_t p_node_id) {279TNode &node = _nodes[p_node_id];280if (node.is_leaf()) {281int leaf_id = node.get_leaf_id();282_leaves.free(leaf_id);283}284285_nodes.free(p_node_id);286}287288void change_root_node(uint32_t p_new_root_id, uint32_t p_tree_id) {289_root_node_id[p_tree_id] = p_new_root_id;290TNode &root = _nodes[p_new_root_id];291292// mark no parent293root.parent_id = BVHCommon::INVALID;294}295296void node_make_leaf(uint32_t p_node_id) {297uint32_t child_leaf_id;298TLeaf *child_leaf = _leaves.request(child_leaf_id);299child_leaf->clear();300301// zero is reserved at startup, to prevent this id being used302// (as they are stored as negative values in the node, and zero is already taken)303BVH_ASSERT(child_leaf_id != 0);304305TNode &node = _nodes[p_node_id];306node.neg_leaf_id = -(int)child_leaf_id;307}308309void node_remove_item(uint32_t p_ref_id, uint32_t p_tree_id, BVHABB_CLASS *r_old_aabb = nullptr) {310// get the reference311ItemRef &ref = _refs[p_ref_id];312uint32_t owner_node_id = ref.tnode_id;313314// debug draw special315// This may not be needed316if (owner_node_id == BVHCommon::INVALID) {317return;318}319320TNode &tnode = _nodes[owner_node_id];321CRASH_COND(!tnode.is_leaf());322323TLeaf &leaf = _node_get_leaf(tnode);324325// if the aabb is not determining the corner size, then there is no need to refit!326// (optimization, as merging AABBs takes a lot of time)327const BVHABB_CLASS &old_aabb = leaf.get_aabb(ref.item_id);328329// shrink a little to prevent using corner aabbs330// in order to miss the corners first we shrink by node_expansion331// (which is added to the overall bound of the leaf), then we also332// shrink by an epsilon, in order to miss out the very corner aabbs333// which are important in determining the bound. Any other aabb334// within this can be removed and not affect the overall bound.335BVHABB_CLASS node_bound = tnode.aabb;336node_bound.expand(-_node_expansion - 0.001f);337bool refit = true;338339if (node_bound.is_other_within(old_aabb)) {340refit = false;341}342343// record the old aabb if required (for incremental remove_and_reinsert)344if (r_old_aabb) {345*r_old_aabb = old_aabb;346}347348leaf.remove_item_unordered(ref.item_id);349350if (leaf.num_items) {351// the swapped item has to have its reference changed to, to point to the new item id352uint32_t swapped_ref_id = leaf.get_item_ref_id(ref.item_id);353354ItemRef &swapped_ref = _refs[swapped_ref_id];355356swapped_ref.item_id = ref.item_id;357358// only have to refit if it is an edge item359// This is a VERY EXPENSIVE STEP360// we defer the refit updates until the update function is called once per frame361if (refit) {362leaf.set_dirty(true);363}364} else {365// remove node if empty366// remove link from parent367if (tnode.parent_id != BVHCommon::INVALID) {368// DANGER .. this can potentially end up with root node with 1 child ...369// we don't want this and must check for it370371uint32_t parent_id = tnode.parent_id;372373node_remove_child(parent_id, owner_node_id, p_tree_id);374refit_upward(parent_id);375376// put the node on the free list to recycle377node_free_node_and_leaf(owner_node_id);378}379380// else if no parent, it is the root node. Do not delete381}382383ref.tnode_id = BVHCommon::INVALID;384ref.item_id = BVHCommon::INVALID; // unset385}386387// returns true if needs refit of PARENT tree only, the node itself AABB is calculated388// within this routine389bool _node_add_item(uint32_t p_node_id, uint32_t p_ref_id, const BVHABB_CLASS &p_aabb) {390ItemRef &ref = _refs[p_ref_id];391ref.tnode_id = p_node_id;392393TNode &node = _nodes[p_node_id];394BVH_ASSERT(node.is_leaf());395TLeaf &leaf = _node_get_leaf(node);396397// optimization - we only need to do a refit398// if the added item is changing the AABB of the node.399// in most cases it won't.400bool needs_refit = true;401402// expand bound now403BVHABB_CLASS expanded = p_aabb;404expanded.expand(_node_expansion);405406// the bound will only be valid if there is an item in there already407if (leaf.num_items) {408if (node.aabb.is_other_within(expanded)) {409// no change to node AABBs410needs_refit = false;411} else {412node.aabb.merge(expanded);413}414} else {415// bound of the node = the new aabb416node.aabb = expanded;417}418419ref.item_id = leaf.request_item();420BVH_ASSERT(ref.item_id != BVHCommon::INVALID);421422// set the aabb of the new item423leaf.get_aabb(ref.item_id) = p_aabb;424425// back reference on the item back to the item reference426leaf.get_item_ref_id(ref.item_id) = p_ref_id;427428return needs_refit;429}430431uint32_t _node_create_another_child(uint32_t p_node_id, const BVHABB_CLASS &p_aabb) {432uint32_t child_node_id;433TNode *child_node = _nodes.request(child_node_id);434child_node->clear();435436// may not be necessary437child_node->aabb = p_aabb;438439node_add_child(p_node_id, child_node_id);440441return child_node_id;442}443444#include "bvh_cull.inc"445#include "bvh_debug.inc"446#include "bvh_integrity.inc"447#include "bvh_logic.inc"448#include "bvh_misc.inc"449#include "bvh_public.inc"450#include "bvh_refit.inc"451#include "bvh_split.inc"452};453454#undef VERBOSE_PRINT455456457