Box2d源码学习<六>动态树的实现

来源:互联网 发布:螺纹梳刀编程 编辑:程序博客网 时间:2024/05/18 03:23

本系列博客是由扭曲45原创,欢迎转载,转载时注明出处,http://blog.csdn.net/cg0206/article/details/8293049

今天我们将学习碰撞模块(collision)部分,该部分主要有一下内容:

1、 形状,该部分包括的定义、实现。

2、 操作形状方法,该部分包括距离(Distance)、撞击时间(Time of Impact)等。

3、 算法辅助类,包括动态树和broad-phase算法。用来提高系统的碰撞检测的速度。

 

其中前两项均以算法辅助类为基础的,所以我们开始学习这一项,今天我们将学习动态树部分,动态树顾名思义就是“会动的树”,在Bx2d中动态树是由b2DynamicTree类来实现的,它主要是通过用户数据来操作轴对齐包围盒(axis-alignedbounding boxes,AABBs)来完成树的各种操作,并不需要知道形状是什么东东。(如有童鞋像我开始一样,不知道AABB是何物,请记得我们还有维基百科啦)。同时动态树继承自AABB树,树上的每一个节点都有两个孩子。叶节点是一个单独的用户AABB。即便是惰性输入,整个数也可以使用旋转保持平衡。

好了,我们开始上正餐了。先看b2DynameicTree.h文件:

[cpp] view plain copy
  1. //定义空节点  
  2. #define b2_nullNode (-1)  
  3. ///一个动态树的子节点,不于外包直接交换  
  4. struct b2TreeNode  
  5. {  
  6.     //是否是叶子节点  
  7.     bool IsLeaf() const  
  8.     {  
  9.         return child1 == b2_nullNode;  
  10.     }  
  11.   
  12.     /// Enlarged AABB  
  13.     //增大aabb变量  
  14.     b2AABB aabb;  
  15.     //用户数据  
  16.     void* userData;  
  17.     //父节点指针(索引)或孩子节点指针(索引)  
  18.     //因为此动态树是申请一块大的连续的空间,即含有n个元素的动态数组罢了  
  19.     //故用动态数组的索引值来模拟指针。为了统一,我们一下均使用指针  
  20.     union  
  21.     {  
  22.         int32 parent;  
  23.         int32 next;  
  24.     };  
  25.     //左右孩子指针  
  26.     int32 child1;  
  27.     int32 child2;  
  28.     //高度 叶子高度为0,空闲节点高度为-1  
  29.     int32 height;  
  30. };  
  31.   
  32. //动态AABB树broad-phase,灵感来自于Nathanael Presson's btDbvt.  
  33. //一个动态树排列一个二叉树的数据来加速查询像体积查询和光线投射。叶子是若干个代理和轴对齐包围盒  
  34. //在树上我们用b2_fatAABBFactor扩展了aabb代理,这样aabb代理将比客户端对象大。这样允许客户端少量移动  
  35. //而不需更新一个树  
  36. //节点是汇集和浮动的,所以我们使用节点索引而不是指针  
  37. class b2DynamicTree  
  38. {  
  39. public:  
  40.     /************************************************************************** 
  41.     * 功能描述:构造一个树,并初始化节点内存池 
  42.     * 参数说明:(void) 
  43.     * 返 回 值:(void) 
  44.     ***************************************************************************/  
  45.     b2DynamicTree();  
  46.     /************************************************************************** 
  47.     * 功能描述:销毁一个树,并释放节点内存池 
  48.     * 参数说明:(void) 
  49.     * 返 回 值:(void) 
  50.     ***************************************************************************/  
  51.     ~b2DynamicTree();  
  52.     /************************************************************************** 
  53.     * 功能描述:在树上创建一个叶子节点代理 
  54.     * 参数说明:aabb    :aabb变量 
  55.                 user    : 数据 
  56.     * 返 回 值:节点的索引来替代指针,来增长我们的节点池 
  57.     ***************************************************************************/  
  58.     int32 CreateProxy(const b2AABB& aabb, void* userData);  
  59.     /************************************************************************** 
  60.     * 功能描述:销毁一个代理,如果id无效则断言 
  61.     * 参数说明:poxyid :代理id 
  62.     * 返 回 值:节点的索引来替代指针,来增长我们的节点池 
  63.     ***************************************************************************/  
  64.     void DestroyProxy(int32 proxyId);  
  65.     /************************************************************************** 
  66.     * 功能描述:移动一个代理并扫描AABB,如果代理移除了使它充实的AABB盒子 
  67.                 代理将会从树上移除并重新插入。否则,函数将立即返回 
  68.     * 参数说明:proxyId     :叶子代理id 
  69.                 aabb        : aabb变量 
  70.                 displacement:移动坐标向量 
  71.     * 返 回 值: true :移动成功 
  72.                  false:移动失败 
  73.     ***************************************************************************/  
  74.     bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement);  
  75.     /************************************************************************** 
  76.     * 功能描述:获取一个代理的userData 
  77.     * 参数说明:proxyId:叶子代理id 
  78.     * 返 回 值:id有效,则返回代理userData 
  79.                 id无效,则返0 
  80.     ***************************************************************************/  
  81.     void* GetUserData(int32 proxyId) const;  
  82.     /************************************************************************** 
  83.     * 功能描述:获取从代理中宽大的AABB 
  84.     * 参数说明:proxyId:叶子代理id 
  85.     * 返 回 值:aabb对象 
  86.     ***************************************************************************/  
  87.     const b2AABB& GetFatAABB(int32 proxyId) const;  
  88.     /************************************************************************** 
  89.     * 功能描述:查询一个aabb重叠代理,每个重叠提供AABB的代理都将回调回调类 
  90.     * 参数说明:callback :回调对象 
  91.                 aabb     :要查询的aabb 
  92.     * 返 回 值:aabb对象 
  93.     ***************************************************************************/  
  94.     template <typename T>  
  95.     void Query(T* callback, const b2AABB& aabb) const;  
  96.     /************************************************************************** 
  97.     * 功能描述:光线投射到树上的每个代理上。 
  98.                 这依赖于回调去执行一个精确的光线投射到一个包含形状的代理上 
  99.                 这个回调也执行任何碰撞过滤。 
  100.                 性能几乎等于k * log(n),其中k是碰撞的次数,n是树上代理的数量 
  101.     * 参数说明:callback :回调对象类,将会被每一个被光线照到的代理调用 
  102.                 input    :光线投射输入数据,光线从 p1 + maxFraction * (p2 - p1) 
  103.     * 返 回 值:(void) 
  104.     ***************************************************************************/  
  105.     template <typename T>  
  106.     void RayCast(T* callback, const b2RayCastInput& input) const;  
  107.     /************************************************************************** 
  108.     * 功能描述:验证这棵树,用于测试 
  109.     * 参数说明:(void) 
  110.     * 返 回 值:(void) 
  111.     ***************************************************************************/  
  112.     void Validate() const;  
  113.     /************************************************************************** 
  114.     * 功能描述:在O(N)时间上计算二叉树的高度,要不经常调用 
  115.     * 参数说明:(void) 
  116.     * 返 回 值:二叉树的高度 
  117.     ***************************************************************************/  
  118.     int32 GetHeight() const;  
  119.     /************************************************************************** 
  120.     * 功能描述:在树上获得节点之间最大的平衡。平衡是两个孩子节点最大的高度差 
  121.     * 参数说明:(void) 
  122.     * 返 回 值:平衡值 
  123.     ***************************************************************************/  
  124.     int32 GetMaxBalance() const;  
  125.     /************************************************************************** 
  126.     * 功能描述:获得节点总数面积之和根面积的比 
  127.     * 参数说明:(void) 
  128.     * 返 回 值:节点总数面积之和根面积的比 
  129.     ***************************************************************************/  
  130.     float32 GetAreaRatio() const;  
  131.     /************************************************************************** 
  132.     * 功能描述:构建一个最优的树,非常昂贵,用于测试 
  133.     * 参数说明:(void) 
  134.     * 返 回 值:节点总数面积之和根面积的比 
  135.     ***************************************************************************/  
  136.     void RebuildBottomUp();  
  137.   
  138. private:  
  139.     /************************************************************************** 
  140.     * 功能描述:从内存池中申请一个节点.如果必要增大内存池 
  141.     * 参数说明:(void) 
  142.     * 返 回 值:节点指针 
  143.     ***************************************************************************/  
  144.     int32 AllocateNode();  
  145.     /************************************************************************** 
  146.     * 功能描述:释放节点 
  147.     * 参数说明:node :节点指针 
  148.     * 返 回 值:(void) 
  149.     ***************************************************************************/  
  150.     void FreeNode(int32 node);  
  151.     /************************************************************************** 
  152.     * 功能描述:插入叶子节点 
  153.     * 参数说明:node:叶子节点指针 
  154.     * 返 回 值: (void) 
  155.     ***************************************************************************/  
  156.     void InsertLeaf(int32 node);  
  157.     /************************************************************************** 
  158.     * 功能描述:移除叶子 
  159.     * 参数说明:node :叶子节点指针 
  160.     * 返 回 值:(void) 
  161.     ***************************************************************************/  
  162.     void RemoveLeaf(int32 node);  
  163.     /************************************************************************** 
  164.     * 功能描述:如果子树a不平衡,则执行一个向左或向右旋转 
  165.     * 参数说明:iA :子树根节点指针 
  166.     * 返 回 值: 新的子树根指针 
  167.     ***************************************************************************/  
  168.     int32 Balance(int32 index);  
  169.     /************************************************************************** 
  170.     * 功能描述:计算树的高度 
  171.     * 参数说明:(void) 
  172.     * 返 回 值:树的高度 
  173.     ***************************************************************************/  
  174.     int32 ComputeHeight() const;  
  175.     /************************************************************************** 
  176.     * 功能描述:计算子树的高度 
  177.     * 参数说明:nodeid:子树的头指针 
  178.     * 返 回 值:子树的高度 
  179.     ***************************************************************************/  
  180.     int32 ComputeHeight(int32 nodeId) const;  
  181.     /************************************************************************** 
  182.     * 功能描述:验证子树的结构 
  183.     * 参数说明:index:子树的头指针 
  184.     * 返 回 值:(void) 
  185.     ***************************************************************************/  
  186.     void ValidateStructure(int32 index) const;  
  187.     /************************************************************************** 
  188.     * 功能描述:验证子树的度量 
  189.     * 参数说明:index:子树的头指针 
  190.     * 返 回 值:(void) 
  191.     ***************************************************************************/  
  192.     void ValidateMetrics(int32 index) const;  
  193.     //树的根指针(也是索引)  
  194.     int32 m_root;  
  195.     //树的真正的头指针,也是一块连续的内存池的首地址  
  196.     b2TreeNode* m_nodes;  
  197.     //树节点的个数  
  198.     int32 m_nodeCount;  
  199.     //内存池中节点的总个数  
  200.     int32 m_nodeCapacity;  
  201.     //空闲链表指针  
  202.     int32 m_freeList;  
  203.     //  用于增量遍历树的调整  
  204.     uint32 m_path;  
  205.     //记录插入节点总数量  
  206.     int32 m_insertionCount;  
  207. };  

我们可以看到该代码分为节点b2TreeNode定义和b2DynamicTree动态树类的定义,关于b2TreeNode结构体的定义就不多说了,而b2DynamicTree类主要还是先申请一块连续的内存用动态数组去模拟的(如果我们没记错的话,soa也是用动态数组实现的,两个栈的实现也是用的动态数组,好强大的动态数组),所以我们可以用索引模拟指针,直接去访问树上的节点。

 

我们再看看b2DynamicTree类有关内联函数的实现。

[cpp] view plain copy
  1. //根据代理id获取userData  
  2. inline void* b2DynamicTree::GetUserData(int32 proxyId) const  
  3. {  
  4.     //验证代理id的有效性  
  5.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);  
  6.     return m_nodes[proxyId].userData;  
  7. }  
  8. //根据代理id获得宽大的AABB  
  9. inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const  
  10. {  
  11.     //验证代理id的有效性  
  12.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);  
  13.     return m_nodes[proxyId].aabb;  
  14. }  
  15.   
  16. //查询一个aabb重叠代理,每个重叠提供AABB的代理都将回调回调类  
  17. template <typename T>  
  18. inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const  
  19. {  
  20.     //申请临时栈,根节点进栈  
  21.     b2GrowableStack<int32, 256> stack;  
  22.     stack.Push(m_root);  
  23.     //判断栈的个数  
  24.     while (stack.GetCount() > 0)  
  25.     {  
  26.         //获取节点id  
  27.         int32 nodeId = stack.Pop();  
  28.         if (nodeId == b2_nullNode)  
  29.         {  
  30.             //节点内存池中的空闲节点  
  31.             continue;  
  32.         }  
  33.         //获取节点  
  34.         const b2TreeNode* node = m_nodes + nodeId;  
  35.         //测试重叠  
  36.         if (b2TestOverlap(node->aabb, aabb))  
  37.         {  
  38.             //是否是叶子节点  
  39.             if (node->IsLeaf())  
  40.             {  
  41.                 //是否成功  
  42.                 bool proceed = callback->QueryCallback(nodeId);  
  43.                 if (proceed == false)  
  44.                 {  
  45.                     return;  
  46.                 }  
  47.             }  
  48.             else  
  49.             {  
  50.                 //左右孩子节点进栈  
  51.                 stack.Push(node->child1);  
  52.                 stack.Push(node->child2);  
  53.             }  
  54.         }  
  55.     }  
  56. }  
  57. //光线投射  
  58. template <typename T>  
  59. inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const  
  60. {  
  61.     //  
  62.     b2Vec2 p1 = input.p1;  
  63.     b2Vec2 p2 = input.p2;  
  64.     b2Vec2 r = p2 - p1;  
  65.     b2Assert(r.LengthSquared() > 0.0f);  
  66.     r.Normalize();  
  67.     //v垂直于向量r  
  68.     b2Vec2 v = b2Cross(1.0f, r);  
  69.     b2Vec2 abs_v = b2Abs(v);  
  70.     //分离轴 下面的书籍 p80   
  71.     // 《Collision Detection in Interactive 3D Environments》 by Gino van den Bergen  
  72.     // 【从 http://download.csdn.net/detail/cg0206/4875309 下载】  
  73.     // 计算公式:|dot(v, p1 - c)| > dot(|v|, h)  
  74.     float32 maxFraction = input.maxFraction;  
  75.     // 构建一个绑定的盒子用于该线段  
  76.     b2AABB segmentAABB;  
  77.     {  
  78.         b2Vec2 t = p1 + maxFraction * (p2 - p1);  
  79.         segmentAABB.lowerBound = b2Min(p1, t);  
  80.         segmentAABB.upperBound = b2Max(p1, t);  
  81.     }  
  82.     //创建一个临时栈,并将根节点进栈  
  83.     b2GrowableStack<int32, 256> stack;  
  84.     stack.Push(m_root);  
  85.     //栈不为空  
  86.     while (stack.GetCount() > 0)  
  87.     {  
  88.         //出栈  
  89.         int32 nodeId = stack.Pop();  
  90.         if (nodeId == b2_nullNode)  
  91.         {  
  92.             //节点内存池中的空闲节点  
  93.             continue;  
  94.         }  
  95.         //根据节点索引获取节点  
  96.         const b2TreeNode* node = m_nodes + nodeId;  
  97.         //判断AABB  
  98.         if (b2TestOverlap(node->aabb, segmentAABB) == false)  
  99.         {  
  100.             continue;  
  101.         }  
  102.   
  103.         //分离轴  p80   
  104.         // |dot(v, p1 - c)| > dot(|v|, h)  
  105.         b2Vec2 c = node->aabb.GetCenter();  
  106.         b2Vec2 h = node->aabb.GetExtents();  
  107.           
  108.         float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h);  
  109.         if (separation > 0.0f)  
  110.         {  
  111.             continue;  
  112.         }  
  113.         //是否是叶子节点  
  114.         if (node->IsLeaf())  
  115.         {  
  116.             b2RayCastInput subInput;  
  117.             subInput.p1 = input.p1;  
  118.             subInput.p2 = input.p2;  
  119.             subInput.maxFraction = maxFraction;  
  120.   
  121.             float32 value = callback->RayCastCallback(subInput, nodeId);  
  122.   
  123.             if (value == 0.0f)  
  124.             {  
  125.                 //客户端终止了光线投射  
  126.                 return;  
  127.             }  
  128.   
  129.             if (value > 0.0f)  
  130.             {  
  131.                 // 更新线段的盒子边界  
  132.                 maxFraction = value;  
  133.                 b2Vec2 t = p1 + maxFraction * (p2 - p1);  
  134.                 segmentAABB.lowerBound = b2Min(p1, t);  
  135.                 segmentAABB.upperBound = b2Max(p1, t);  
  136.             }  
  137.         }  
  138.         else  
  139.         {  
  140.             //将两个孩子进栈  
  141.             stack.Push(node->child1);  
  142.             stack.Push(node->child2);  
  143.         }  
  144.     }  
  145. }  

获取userData和AABB的,都是根据代理叶子id获取的节点信息。至于Query则是在树上查找每一个与AABB有重叠的叶子节点,并回调,效率比直接使用形状要高很多。

RayCast则用了大量的有关图形碰撞方面的知识和数学方面的计算,《CollisionDetection in Interactive 3D Environments》这本书有提到,本书目前没有找到中文版,对E文有兴趣的朋友可以从这里 下载。偶研究不深,也就不在这里误人子弟了。

 

我们再看看b2DynamicTree.ccp文件。

1、 构造、析构函数

[cpp] view plain copy
  1. /************************************************************************** 
  2. * 功能描述:动态树构造函数,初始化数据 
  3. * 参数说明:(void) 
  4. * 返 回 值:(void) 
  5. ***************************************************************************/  
  6. b2DynamicTree::b2DynamicTree()  
  7. {  
  8.     m_root = b2_nullNode;  
  9.   
  10.     m_nodeCapacity = 16;  
  11.     m_nodeCount = 0;  
  12.     //申请一块内存,创建m_nodeCapacity子节点,并清空内存中的内容  
  13.     m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode));  
  14.     memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode));  
  15.     // 创建一个空闲链表  
  16.     for (int32 i = 0; i < m_nodeCapacity - 1; ++i)  
  17.     {  
  18.         m_nodes[i].next = i + 1;  
  19.         m_nodes[i].height = -1;  
  20.     }  
  21.     //链表的最后一个子节点的孩子指针、高度都置为初始值  
  22.     m_nodes[m_nodeCapacity-1].next = b2_nullNode;  
  23.     m_nodes[m_nodeCapacity-1].height = -1;  
  24.     m_freeList = 0;  
  25.   
  26.     m_path = 0;  
  27.   
  28.     m_insertionCount = 0;  
  29. }  
  30.   
  31. /************************************************************************** 
  32. * 功能描述:析构函数 
  33. * 参数说明:(void) 
  34. * 返 回 值:(void) 
  35. ***************************************************************************/  
  36. b2DynamicTree::~b2DynamicTree()  
  37. {  
  38.     //一次性释放整个内存池  
  39.     b2Free(m_nodes);  
  40. }  

关于构造函数b2DynamicTree 主要是对类的成员初始化,并申请一块连续的内存,注意我们这次不是在自己实现的SOA(小型对象分配器)上面申请的,而是直接在内存中用b2Alloc()申请的。此块内存将作为节点内存池供树的节点使用。同时我们还看到有个for循环将所有的节点都遍历了一遍,又是干嘛呢?创建链表呗,看到注释的童鞋也许会这样回答,对的,那创建链表是干什么用的呢?嘿嘿……主要还是查找方便呗。关于析构函数主要是释放整个内存池。

 

2、对树中节点操作

[cpp] view plain copy
  1. /************************************************************************** 
  2. * 功能描述:从内存池中申请一个节点.如果必要增大内存池 
  3. * 参数说明:(void) 
  4. * 返 回 值:节点指针 
  5. ***************************************************************************/  
  6. int32 b2DynamicTree::AllocateNode()  
  7. {  
  8.     // 如果需要扩大节点内存池  
  9.     if (m_freeList == b2_nullNode)  
  10.     {  
  11.         b2Assert(m_nodeCount == m_nodeCapacity);  
  12.         //空闲链表为空,重新创建一个更大的内存池  
  13.         b2TreeNode* oldNodes = m_nodes;  
  14.         m_nodeCapacity *= 2;  
  15.         m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode));  
  16.         memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode));  
  17.         b2Free(oldNodes);  
  18.         // 创建一个空闲链表。父节点成为下一个指针  
  19.         // 注意:这次是从m_nodeCount开始的  
  20.         for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i)  
  21.         {  
  22.             m_nodes[i].next = i + 1;  
  23.             m_nodes[i].height = -1;  
  24.         }  
  25.   
  26.         m_nodes[m_nodeCapacity-1].next = b2_nullNode;  
  27.         m_nodes[m_nodeCapacity-1].height = -1;  
  28.         m_freeList = m_nodeCount;  
  29.     }  
  30.     //从空闲链表中去下一个节点,初始化该节点,  
  31.     //同时将空闲链表头指针m_freeList指向下一个  
  32.     int32 nodeId = m_freeList;  
  33.     m_freeList = m_nodes[nodeId].next;  
  34.     m_nodes[nodeId].parent = b2_nullNode;  
  35.     m_nodes[nodeId].child1 = b2_nullNode;  
  36.     m_nodes[nodeId].child2 = b2_nullNode;  
  37.     m_nodes[nodeId].height = 0;  
  38.     m_nodes[nodeId].userData = NULL;  
  39.     //增加节点数量  
  40.     ++m_nodeCount;  
  41.     //返回节点id  
  42.     return nodeId;  
  43. }  
  44.   
  45.   
  46. //  
  47. /************************************************************************** 
  48. * 功能描述:从内存池中申请一个节点.根据nodeid将一个节点内存返回到节点池内 
  49. * 参数说明:nodeId:节点指针 
  50. * 返 回 值:(void) 
  51. ***************************************************************************/  
  52. void b2DynamicTree::FreeNode(int32 nodeId)  
  53. {  
  54.     //验证nodeid的有效性  
  55.     b2Assert(0 <= nodeId && nodeId < m_nodeCapacity);  
  56.     //验证是否有节点  
  57.     b2Assert(0 < m_nodeCount);  
  58.     //将当前节点以头插入的方式放到空闲链表中  
  59.     m_nodes[nodeId].next = m_freeList;  
  60.     m_nodes[nodeId].height = -1;  
  61.     m_freeList = nodeId;  
  62.     //将节点个数减1  
  63.     //注意此处并没有释放  
  64.     --m_nodeCount;  
  65. }  

 

先看下面的图示:

动态数组m_nodes此时包含两部分,以m_root根的动态树部分用于管理动态树中的用户信息,和以m_freeList为头指针的空闲链表部分,用于管理内存池中未使用的节点。
对于AllocateNode函数,首先从空闲链表中获取其头部指针(索引)并返回,同时调整空闲链表的头指针到下一个节点。注意这里有一种情况,就是当空闲链表没有节点时,我们将重新申请一块是原来2倍内存空间的新的动态数组,并拷贝原来的信息到新的动态数组中,此处我们可以看到无论是m_root还是m_freeList,对其下属保存的都是索引,而非指针。这里拷贝到新的地方仍然有用,而指针则不然,在这里不得不佩服设计者的精妙之处。
对于FreeNode函数,我们将节点置空返回到空闲链表中,也并没有将其真正的释放,这也是很精妙的地方。

 

 

 

3、 对具有aabb代理的节点操作

[cpp] view plain copy
  1. /************************************************************************** 
  2. * 功能描述:在树上创建一个叶子节点代理 
  3. * 参数说明:aabb    :aabb变量 
  4.             user    : 数据 
  5. * 返 回 值:节点的索引来替代指针,来增长我们的节点池 
  6. ***************************************************************************/  
  7. int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData)  
  8. {  
  9.     //申请代理节点id  
  10.     int32 proxyId = AllocateNode();  
  11.   
  12.     // Fatten the aabb.  
  13.     //填充aabb,为节点赋值  
  14.     b2Vec2 r(b2_aabbExtension, b2_aabbExtension);  
  15.     m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r;  
  16.     m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r;  
  17.     m_nodes[proxyId].userData = userData;  
  18.     m_nodes[proxyId].height = 0;  
  19.     //插入叶子节点  
  20.     InsertLeaf(proxyId);  
  21.   
  22.     return proxyId;  
  23. }  
  24.   
  25. /************************************************************************** 
  26. * 功能描述:销毁叶子代理 
  27. * 参数说明:proxyId     :叶子代理id 
  28. * 返 回 值:(void) 
  29. ***************************************************************************/  
  30. void b2DynamicTree::DestroyProxy(int32 proxyId)  
  31. {  
  32.     //验证proxyid的有效性  
  33.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);  
  34.     //验证是否是叶子节点  
  35.     b2Assert(m_nodes[proxyId].IsLeaf());  
  36.     //删除叶子节点  
  37.     RemoveLeaf(proxyId);  
  38.     //是否子节点  
  39.     FreeNode(proxyId);  
  40. }  
  41. /************************************************************************** 
  42. * 功能描述:移动叶子代理 
  43. * 参数说明:proxyId     :叶子代理id 
  44.             aabb        : aabb变量 
  45.             displacement:移动坐标向量 
  46. * 返 回 值: (void) 
  47. ***************************************************************************/  
  48. bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement)  
  49. {  
  50.     //验证proxyid的有效性  
  51.     b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);  
  52.     //验证是否是叶子节点  
  53.     b2Assert(m_nodes[proxyId].IsLeaf());  
  54.     //检验aabb是否互相包含  
  55.     if (m_nodes[proxyId].aabb.Contains(aabb))  
  56.     {  
  57.         return false;  
  58.     }  
  59.     //根据proxyId移除叶子  
  60.     RemoveLeaf(proxyId);  
  61.     //扩大AABB  
  62.     b2AABB b = aabb;  
  63.     b2Vec2 r(b2_aabbExtension, b2_aabbExtension);  
  64.     b.lowerBound = b.lowerBound - r;  
  65.     b.upperBound = b.upperBound + r;  
  66.     //预测aabb的位移  
  67.     b2Vec2 d = b2_aabbMultiplier * displacement;  
  68.     //扩大下限  
  69.     if (d.x < 0.0f)  
  70.     {  
  71.         b.lowerBound.x += d.x;  
  72.     }  
  73.     else  
  74.     {  
  75.         b.upperBound.x += d.x;  
  76.     }  
  77.   
  78.     if (d.y < 0.0f)  
  79.     {  
  80.         b.lowerBound.y += d.y;  
  81.     }  
  82.     else  
  83.     {  
  84.         b.upperBound.y += d.y;  
  85.     }  
  86.     //重新设置aabb  
  87.     m_nodes[proxyId].aabb = b;  
  88.     //插入叶子节点  
  89.     InsertLeaf(proxyId);  
  90.     return true;  
  91. }  
[cpp] view plain copy
  1.   

4、对叶子节点进行操作

[cpp] view plain copy
  1. /************************************************************************** 
  2. * 功能描述:插入叶子节点 
  3. * 参数说明:leaf    :叶子节点指针 
  4. * 返 回 值: (void) 
  5. ***************************************************************************/  
  6. void b2DynamicTree::InsertLeaf(int32 leaf)  
  7. {  
  8.     //插入节点总数量自增  
  9.     ++m_insertionCount;  
  10.     //判断该树是否为空  
  11.     if (m_root == b2_nullNode)  
  12.     {  
  13.         m_root = leaf;  
  14.         m_nodes[m_root].parent = b2_nullNode;  
  15.         return;  
  16.     }  
  17.     //为该节点找到最好的兄弟(姐妹)节点  
  18.     //获取leaf的aabb  
  19.     b2AABB leafAABB = m_nodes[leaf].aabb;  
  20.     //获取根节点  
  21.     int32 index = m_root;  
  22.     //不是叶子节点  
  23.     while (m_nodes[index].IsLeaf() == false)  
  24.     {  
  25.         int32 child1 = m_nodes[index].child1;  
  26.         int32 child2 = m_nodes[index].child2;  
  27.         //获取aabb的周长  
  28.         float32 area = m_nodes[index].aabb.GetPerimeter();  
  29.         //获取  
  30.         b2AABB combinedAABB;  
  31.         combinedAABB.Combine(m_nodes[index].aabb, leafAABB);  
  32.         float32 combinedArea = combinedAABB.GetPerimeter();  
  33.         //为该节点创建一个新的父节点【一个新叶子节点】  
  34.         float32 cost = 2.0f * combinedArea;  
  35.         // 最小cost推动叶子进一步下降的树的下一层  
  36.         float32 inheritanceCost = 2.0f * (combinedArea - area);  
  37.         //降低cost到child1  
  38.         float32 cost1;  
  39.         //左孩子是叶子节点  
  40.         if (m_nodes[child1].IsLeaf())  
  41.         {  
  42.             //获取cost1  
  43.             b2AABB aabb;  
  44.             aabb.Combine(leafAABB, m_nodes[child1].aabb);  
  45.             cost1 = aabb.GetPerimeter() + inheritanceCost;  
  46.         }  
  47.         else  
  48.         {  
  49.             //获取cost1  
  50.             b2AABB aabb;  
  51.             aabb.Combine(leafAABB, m_nodes[child1].aabb);  
  52.             float32 oldArea = m_nodes[child1].aabb.GetPerimeter();  
  53.             float32 newArea = aabb.GetPerimeter();  
  54.             cost1 = (newArea - oldArea) + inheritanceCost;  
  55.         }  
  56.         //降低cost到child2  
  57.         float32 cost2;  
  58.         if (m_nodes[child2].IsLeaf())  
  59.         {  
  60.             //获取cost2  
  61.             b2AABB aabb;  
  62.             aabb.Combine(leafAABB, m_nodes[child2].aabb);  
  63.             cost2 = aabb.GetPerimeter() + inheritanceCost;  
  64.         }  
  65.         else  
  66.         {  
  67.             //获取cost2  
  68.             b2AABB aabb;  
  69.             aabb.Combine(leafAABB, m_nodes[child2].aabb);  
  70.             float32 oldArea = m_nodes[child2].aabb.GetPerimeter();  
  71.             float32 newArea = aabb.GetPerimeter();  
  72.             cost2 = newArea - oldArea + inheritanceCost;  
  73.         }  
  74.         // 获取最小成本  
  75.         if (cost < cost1 && cost < cost2)  
  76.         {  
  77.             break;  
  78.         }  
  79.         //下降到最小cost  
  80.         if (cost1 < cost2)  
  81.         {  
  82.             index = child1;  
  83.         }  
  84.         else  
  85.         {  
  86.             index = child2;  
  87.         }  
  88.     }  
  89.     int32 sibling = index;  
  90.     //创建一个新的父节点  
  91.     //初始化  
  92.     int32 oldParent = m_nodes[sibling].parent;  
  93.     int32 newParent = AllocateNode();  
  94.     m_nodes[newParent].parent = oldParent;  
  95.     m_nodes[newParent].userData = NULL;  
  96.     m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb);  
  97.     m_nodes[newParent].height = m_nodes[sibling].height + 1;  
  98.   
  99.     if (oldParent != b2_nullNode)  
  100.     {  
  101.         // 兄弟节点不是根节点  
  102.         if (m_nodes[oldParent].child1 == sibling)  
  103.         {  
  104.             m_nodes[oldParent].child1 = newParent;  
  105.         }  
  106.         else  
  107.         {  
  108.             m_nodes[oldParent].child2 = newParent;  
  109.         }  
  110.   
  111.         m_nodes[newParent].child1 = sibling;  
  112.         m_nodes[newParent].child2 = leaf;  
  113.         m_nodes[sibling].parent = newParent;  
  114.         m_nodes[leaf].parent = newParent;  
  115.     }  
  116.     else  
  117.     {  
  118.         // 兄弟节点是根节点  
  119.         m_nodes[newParent].child1 = sibling;  
  120.         m_nodes[newParent].child2 = leaf;  
  121.         m_nodes[sibling].parent = newParent;  
  122.         m_nodes[leaf].parent = newParent;  
  123.         m_root = newParent;  
  124.     }  
  125.     // 向后走修复树的高度和aabb  
  126.     index = m_nodes[leaf].parent;  
  127.     while (index != b2_nullNode)  
  128.     {  
  129.         //平衡  
  130.         index = Balance(index);  
  131.         //左右孩子节点  
  132.         int32 child1 = m_nodes[index].child1;  
  133.         int32 child2 = m_nodes[index].child2;  
  134.   
  135.         b2Assert(child1 != b2_nullNode);  
  136.         b2Assert(child2 != b2_nullNode);  
  137.         //获取高度和aabb  
  138.         m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);  
  139.         m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);  
  140.         //获取parent节点  
  141.         index = m_nodes[index].parent;  
  142.     }  
  143.   
  144.     //Validate();  
  145. }  
  146.   
  147. /************************************************************************** 
  148. * 功能描述:删除叶子节点 
  149. * 参数说明:leaf    :叶子节点指针 
  150. * 返 回 值: (void) 
  151. ***************************************************************************/  
  152. void b2DynamicTree::RemoveLeaf(int32 leaf)  
  153. {  
  154.     //只有一个节点  
  155.     if (leaf == m_root)  
  156.     {  
  157.         m_root = b2_nullNode;  
  158.         return;  
  159.     }  
  160.     //获取父节点和祖父节点  
  161.     int32 parent = m_nodes[leaf].parent;  
  162.     int32 grandParent = m_nodes[parent].parent;  
  163.     //选找兄弟节点  
  164.     int32 sibling;  
  165.     if (m_nodes[parent].child1 == leaf)  
  166.     {  
  167.         sibling = m_nodes[parent].child2;  
  168.     }  
  169.     else  
  170.     {  
  171.         sibling = m_nodes[parent].child1;  
  172.     }  
  173.     // 祖父节点不为空,即父节点不是根节点  
  174.     if (grandParent != b2_nullNode)  
  175.     {  
  176.         // Destroy parent and connect sibling to grandParent.  
  177.         // 销毁父节点和将兄弟节点链接到祖父节点中  
  178.         if (m_nodes[grandParent].child1 == parent)  
  179.         {  
  180.             m_nodes[grandParent].child1 = sibling;  
  181.         }  
  182.         else  
  183.         {  
  184.             m_nodes[grandParent].child2 = sibling;  
  185.         }  
  186.         m_nodes[sibling].parent = grandParent;  
  187.         //释放节点到内存池中  
  188.         FreeNode(parent);  
  189.         // 调整祖先界限  
  190.         int32 index = grandParent;  
  191.         while (index != b2_nullNode)  
  192.         {  
  193.             //平衡  
  194.             index = Balance(index);  
  195.             //获取左右孩子  
  196.             int32 child1 = m_nodes[index].child1;  
  197.             int32 child2 = m_nodes[index].child2;  
  198.             //合并aabb  
  199.             //高度  
  200.             m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);  
  201.             m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);  
  202.             //更新index  
  203.             index = m_nodes[index].parent;  
  204.         }  
  205.     }  
  206.     else  
  207.     {  
  208.         //获取根节点  
  209.         m_root = sibling;  
  210.         m_nodes[sibling].parent = b2_nullNode;  
  211.         //释放父节点  
  212.         FreeNode(parent);  
  213.     }  
  214.   
  215.     //Validate();  
  216. }  

我们首先来说说InsertLeaf函数

它有以下几种情况,如图:

以上就是动态树节点插入的几种情况,主要做法就是:

a)、通过遍历树上的节点,对比aabb找到代价最小的节点A

b)、将A作为兄弟节点,先建一个父节点N,将A的父节点的孩子指针指向N,同时N将A和要插入的叶子节点L作为左右孩子节点连接起来

c)、如果出现树不平衡,旋转动态树,使它成为新的平衡二叉树。大家可以看到,目前上图倒数第一和第二幅图上的都还不是平衡树,这部分等到说的平衡树的函数的时候再弄。

另外关于box2d中的动态树,我们来思考一些问题,就是我们插入的节点会始终是树的叶子节点吗?如果不是的那些节点又到哪去了呢?如果是的怎么做到的呢?

关于这个问题先卖个关子,我们再看看删除叶子函数RemoveLeaf,还是先看图:

关于删除函数,主要步骤是:

a)、根据索引找到父节点、祖父节点、和兄弟节点

b)、将祖父节点的原本指向父节点的孩子指针指向兄弟节点,并释放父亲节点

c)、如果出现树不平衡,旋转动态树,使它成为新的平衡二叉树。

还要注意一点的就是我们插入的有用的信息都是叶子节点,剩下的节点全部都是辅助节点。等我们看到重新构建一棵新的二叉树的时候会对这方面有新的认识。

 

相信大家对节点操作有一定的认识了吧,现在知道上面问题的答案了吗?其实,不管插入还是删除还是我们下面要说的使树平衡的函数,叶子节点还是叶子节点,丝毫没有变成其他节点,我们插入的有用的信息都是叶子节点,剩下的节点全部都是辅助节点,插入的时候添加父节点,删除的时候同时也删除了父节点。等我们看到重新构建一棵新的二叉树的时候会对这方面有新的认识。

5、 对树的操作

[cpp] view plain copy
  1. /************************************************************************** 
  2. * 功能描述:如果子树A不平衡,则执行一个向左或向右旋转 
  3. * 参数说明:iA   :子树A 
  4. * 返 回 值: (void) 
  5. ***************************************************************************/  
  6. int32 b2DynamicTree::Balance(int32 iA)  
  7. {  
  8.     //iA不是根节点  
  9.     b2Assert(iA != b2_nullNode);  
  10.     //获取子树A  
  11.     b2TreeNode* A = m_nodes + iA;  
  12.     //已是平衡树,不需要调整  
  13.     if (A->IsLeaf() || A->height < 2)  
  14.     {  
  15.         return iA;  
  16.     }  
  17.     // 获取A的左右孩子  
  18.     int32 iB = A->child1;  
  19.     int32 iC = A->child2;  
  20.     // iB、iC是否有效  
  21.     b2Assert(0 <= iB && iB < m_nodeCapacity);  
  22.     b2Assert(0 <= iC && iC < m_nodeCapacity);  
  23.     // 获取子树B、C   
  24.     b2TreeNode* B = m_nodes + iB;  
  25.     b2TreeNode* C = m_nodes + iC;  
  26.     // 获得平衡值  
  27.     int32 balance = C->height - B->height;  
  28.   
  29.     // 上旋C  
  30.     if (balance > 1)  
  31.     {  
  32.         //获取C的左右孩子iF、iG和子树F、G  
  33.         int32 iF = C->child1;  
  34.         int32 iG = C->child2;  
  35.         b2TreeNode* F = m_nodes + iF;  
  36.         b2TreeNode* G = m_nodes + iG;  
  37.         // 验证iF、iG是否有效  
  38.         b2Assert(0 <= iF && iF < m_nodeCapacity);  
  39.         b2Assert(0 <= iG && iG < m_nodeCapacity);  
  40.         // 交换A和C  
  41.         C->child1 = iA;  
  42.         C->parent = A->parent;  
  43.         A->parent = iC;  
  44.         // A的父指针应该指向c  
  45.         // A不是头节点  
  46.         if (C->parent != b2_nullNode)  
  47.         {  
  48.             if (m_nodes[C->parent].child1 == iA)  
  49.             {  
  50.                 m_nodes[C->parent].child1 = iC;  
  51.             }  
  52.             else  
  53.             {  
  54.                 b2Assert(m_nodes[C->parent].child2 == iA);  
  55.                 m_nodes[C->parent].child2 = iC;  
  56.             }  
  57.         }  
  58.         else  
  59.         {  
  60.             //A是头节点  
  61.             m_root = iC;  
  62.         }  
  63.         // 旋转  
  64.         // 如果f的高度大,则旋转F  
  65.         if (F->height > G->height)  
  66.         {  
  67.             C->child2 = iF;  
  68.             A->child2 = iG;  
  69.             G->parent = iA;  
  70.             A->aabb.Combine(B->aabb, G->aabb);  
  71.             C->aabb.Combine(A->aabb, F->aabb);  
  72.   
  73.             A->height = 1 + b2Max(B->height, G->height);  
  74.             C->height = 1 + b2Max(A->height, F->height);  
  75.         }  
  76.         else  
  77.         {  
  78.             // 旋转G  
  79.             C->child2 = iG;  
  80.             A->child2 = iF;  
  81.             F->parent = iA;  
  82.             A->aabb.Combine(B->aabb, F->aabb);  
  83.             C->aabb.Combine(A->aabb, G->aabb);  
  84.   
  85.             A->height = 1 + b2Max(B->height, F->height);  
  86.             C->height = 1 + b2Max(A->height, G->height);  
  87.         }  
  88.   
  89.         return iC;  
  90.     }  
  91.       
  92.     // 上旋B  
  93.     if (balance < -1)  
  94.     {  
  95.         int32 iD = B->child1;  
  96.         int32 iE = B->child2;  
  97.         b2TreeNode* D = m_nodes + iD;  
  98.         b2TreeNode* E = m_nodes + iE;  
  99.         b2Assert(0 <= iD && iD < m_nodeCapacity);  
  100.         b2Assert(0 <= iE && iE < m_nodeCapacity);  
  101.   
  102.         //交换A和B  
  103.         B->child1 = iA;  
  104.         B->parent = A->parent;  
  105.         A->parent = iB;  
  106.         // A的旧父指针指向B  
  107.         if (B->parent != b2_nullNode)  
  108.         {  
  109.             if (m_nodes[B->parent].child1 == iA)  
  110.             {  
  111.                 m_nodes[B->parent].child1 = iB;  
  112.             }  
  113.             else  
  114.             {  
  115.                 b2Assert(m_nodes[B->parent].child2 == iA);  
  116.                 m_nodes[B->parent].child2 = iB;  
  117.             }  
  118.         }  
  119.         else  
  120.         {  
  121.             m_root = iB;  
  122.         }  
  123.   
  124.         //旋转  
  125.         if (D->height > E->height)  
  126.         {  
  127.             // 旋转D  
  128.             B->child2 = iD;  
  129.             A->child1 = iE;  
  130.             E->parent = iA;  
  131.             A->aabb.Combine(C->aabb, E->aabb);  
  132.             B->aabb.Combine(A->aabb, D->aabb);  
  133.   
  134.             A->height = 1 + b2Max(C->height, E->height);  
  135.             B->height = 1 + b2Max(A->height, D->height);  
  136.         }  
  137.         else  
  138.         {  
  139.             // 旋转E  
  140.             B->child2 = iE;  
  141.             A->child1 = iD;  
  142.             D->parent = iA;  
  143.             A->aabb.Combine(C->aabb, D->aabb);  
  144.             B->aabb.Combine(A->aabb, E->aabb);  
  145.   
  146.             A->height = 1 + b2Max(C->height, D->height);  
  147.             B->height = 1 + b2Max(A->height, E->height);  
  148.         }  
  149.   
  150.         return iB;  
  151.     }  
  152.   
  153.     return iA;  
  154. }  
  155. /************************************************************************** 
  156. * 功能描述:获得树的高度 
  157. * 参数说明:(void) 
  158. * 返 回 值:树的高度 
  159. ***************************************************************************/  
  160. int32 b2DynamicTree::GetHeight() const  
  161. {  
  162.     if (m_root == b2_nullNode)  
  163.     {  
  164.         return 0;  
  165.     }  
  166.   
  167.     return m_nodes[m_root].height;  
  168. }  
  169.   
  170. /************************************************************************** 
  171. * 功能描述:获得节点总数“面积”之和根“面积”的比 
  172. * 参数说明:(void) 
  173. * 返 回 值:树的高度 
  174. ***************************************************************************/  
  175. float32 b2DynamicTree::GetAreaRatio() const  
  176. {  
  177.     //空树  
  178.     if (m_root == b2_nullNode)  
  179.     {  
  180.         return 0.0f;  
  181.     }  
  182.     //获取根子树  
  183.     const b2TreeNode* root = m_nodes + m_root;  
  184.     float32 rootArea = root->aabb.GetPerimeter();  
  185.     //获取所有节点的总“面积”,其实是周长  
  186.     float32 totalArea = 0.0f;  
  187.     for (int32 i = 0; i < m_nodeCapacity; ++i)  
  188.     {  
  189.         const b2TreeNode* node = m_nodes + i;  
  190.         if (node->height < 0)  
  191.         {  
  192.             //内存池内的空闲节点  
  193.             continue;  
  194.         }  
  195.   
  196.         totalArea += node->aabb.GetPerimeter();  
  197.     }  
  198.     //获取比率  
  199.     return totalArea / rootArea;  
  200. }  
  201. /************************************************************************** 
  202. * 功能描述:计算子树的高度 
  203. * 参数说明:nodeid:子树的头指针索引 
  204. * 返 回 值:子树的高度 
  205. ***************************************************************************/  
  206. int32 b2DynamicTree::ComputeHeight(int32 nodeId) const  
  207. {  
  208.     //验证子树的头指针索引  
  209.     b2Assert(0 <= nodeId && nodeId < m_nodeCapacity);  
  210.     //获取子树头节点  
  211.     b2TreeNode* node = m_nodes + nodeId;  
  212.     // 是否是叶子  
  213.     if (node->IsLeaf())  
  214.     {  
  215.         return 0;  
  216.     }  
  217.     //递给调用,返回高度  
  218.     int32 height1 = ComputeHeight(node->child1);  
  219.     int32 height2 = ComputeHeight(node->child2);  
  220.     return 1 + b2Max(height1, height2);  
  221. }/************************************************************************** 
  222. * 功能描述:计算树的高度 
  223. * 参数说明:(void) 
  224. * 返 回 值:树的高度 
  225. ***************************************************************************/  
  226. int32 b2DynamicTree::ComputeHeight() const  
  227. {  
  228.     int32 height = ComputeHeight(m_root);  
  229.     return height;  
  230. }  
  231. /************************************************************************** 
  232. * 功能描述:验证子树的结构 
  233. * 参数说明:index:子树的索引值 
  234. * 返 回 值:(void) 
  235. ***************************************************************************/  
  236. void b2DynamicTree::ValidateStructure(int32 index) const  
  237. {  
  238.     //空树  
  239.     if (index == b2_nullNode)  
  240.     {  
  241.         return;  
  242.     }  
  243.     //子树是整个树  
  244.     if (index == m_root)  
  245.     {  
  246.         //验证有效性  
  247.         b2Assert(m_nodes[index].parent == b2_nullNode);  
  248.     }  
  249.     //获取子树的头指针  
  250.     const b2TreeNode* node = m_nodes + index;  
  251.     //获取左右孩子  
  252.     int32 child1 = node->child1;  
  253.     int32 child2 = node->child2;  
  254.     //node是否是叶子节点  
  255.     if (node->IsLeaf())  
  256.     {  
  257.         //验证左右孩子和高度  
  258.         b2Assert(child1 == b2_nullNode);  
  259.         b2Assert(child2 == b2_nullNode);  
  260.         b2Assert(node->height == 0);  
  261.         return;  
  262.     }  
  263.     //验证左右孩子  
  264.     b2Assert(0 <= child1 && child1 < m_nodeCapacity);  
  265.     b2Assert(0 <= child2 && child2 < m_nodeCapacity);  
  266.     //验证左右孩子的父节点  
  267.     b2Assert(m_nodes[child1].parent == index);  
  268.     b2Assert(m_nodes[child2].parent == index);  
  269.     //递归验证左右孩子的结构  
  270.     ValidateStructure(child1);  
  271.     ValidateStructure(child2);  
  272. }  
  273. /************************************************************************** 
  274. * 功能描述:验证子树的度量值 
  275. * 参数说明:index:子树的索引值 
  276. * 返 回 值:(void) 
  277. ***************************************************************************/  
  278. void b2DynamicTree::ValidateMetrics(int32 index) const  
  279. {  
  280.     //空子树  
  281.     if (index == b2_nullNode)  
  282.     {  
  283.         return;  
  284.     }  
  285.     //子树的头指针  
  286.     const b2TreeNode* node = m_nodes + index;  
  287.     //获取左右孩子  
  288.     int32 child1 = node->child1;  
  289.     int32 child2 = node->child2;  
  290.     //子树是否是叶子节点  
  291.     if (node->IsLeaf())  
  292.     {  
  293.         //验证左右孩子和高度  
  294.         b2Assert(child1 == b2_nullNode);  
  295.         b2Assert(child2 == b2_nullNode);  
  296.         b2Assert(node->height == 0);  
  297.         return;  
  298.     }  
  299.     //验证左右孩子  
  300.     b2Assert(0 <= child1 && child1 < m_nodeCapacity);  
  301.     b2Assert(0 <= child2 && child2 < m_nodeCapacity);  
  302.     //验证高度  
  303.     int32 height1 = m_nodes[child1].height;  
  304.     int32 height2 = m_nodes[child2].height;  
  305.     int32 height;  
  306.     height = 1 + b2Max(height1, height2);  
  307.     b2Assert(node->height == height);  
  308.     //验证aabb  
  309.     b2AABB aabb;  
  310.     aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);  
  311.   
  312.     b2Assert(aabb.lowerBound == node->aabb.lowerBound);  
  313.     b2Assert(aabb.upperBound == node->aabb.upperBound);  
  314.     //递归验证左右孩子子树  
  315.     ValidateMetrics(child1);  
  316.     ValidateMetrics(child2);  
  317. }  
  318.   
  319. /************************************************************************** 
  320. * 功能描述:验证这棵树,用于测试 
  321. * 参数说明:(void) 
  322. * 返 回 值:(void) 
  323. ***************************************************************************/  
  324. void b2DynamicTree::Validate() const  
  325. {  
  326.     //验证这棵树的结构和度量  
  327.     ValidateStructure(m_root);  
  328.     ValidateMetrics(m_root);  
  329.     //遍历空闲链表,计算空闲节点的个数  
  330.     int32 freeCount = 0;  
  331.     int32 freeIndex = m_freeList;  
  332.     while (freeIndex != b2_nullNode)  
  333.     {  
  334.         b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity);  
  335.         freeIndex = m_nodes[freeIndex].next;  
  336.         ++freeCount;  
  337.     }  
  338.     //验证高度  
  339.     b2Assert(GetHeight() == ComputeHeight());  
  340.     //验证内存池中的节点总容量  
  341.     b2Assert(m_nodeCount + freeCount == m_nodeCapacity);  
  342. }  
  343. /************************************************************************** 
  344. * 功能描述:获取平衡值 
  345. * 参数说明:获取最大的平衡值 
  346. * 返 回 值:(void) 
  347. ***************************************************************************/  
  348. int32 b2DynamicTree::GetMaxBalance() const  
  349. {  
  350.     //  
  351.     int32 maxBalance = 0;  
  352.     for (int32 i = 0; i < m_nodeCapacity; ++i)  
  353.     {  
  354.         const b2TreeNode* node = m_nodes + i;  
  355.         // 内存池中的空闲节点  
  356.         if (node->height <= 1)  
  357.         {  
  358.             continue;  
  359.         }  
  360.   
  361.         b2Assert(node->IsLeaf() == false);  
  362.         //获取最大平衡值  
  363.         int32 child1 = node->child1;  
  364.         int32 child2 = node->child2;  
  365.         int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height);  
  366.         maxBalance = b2Max(maxBalance, balance);  
  367.     }  
  368.   
  369.     return maxBalance;  
  370. }  
  371. /************************************************************************** 
  372. * 功能描述:构建一个最优的树,非常昂贵,用于测试 
  373. * 参数说明:(void) 
  374. * 返 回 值:(void) 
  375. ***************************************************************************/  
  376. void b2DynamicTree::RebuildBottomUp()  
  377. {  
  378.     //从系统堆中申请一段内存  
  379.     int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32));  
  380.     int32 count = 0;  
  381.     //创建空闲的叶子数组。其余是空闲的  
  382.     for (int32 i = 0; i < m_nodeCapacity; ++i)  
  383.     {  
  384.         if (m_nodes[i].height < 0)  
  385.         {  
  386.             // 内存池中空闲的节点  
  387.             continue;  
  388.         }  
  389.         // 是否是叶子节点  
  390.         if (m_nodes[i].IsLeaf())  
  391.         {  
  392.               
  393.             m_nodes[i].parent = b2_nullNode;  
  394.             nodes[count] = i;  
  395.             ++count;  
  396.         }  
  397.         else  
  398.         {  
  399.             // 不是则释放到内存池中  
  400.             FreeNode(i);  
  401.         }  
  402.     }  
  403.     // 叶子节点的个数  
  404.     while (count > 1)  
  405.     {  
  406.         //最小cost  
  407.         float32 minCost = b2_maxFloat;  
  408.         int32 iMin = -1, jMin = -1;  
  409.         //获取最小(j)和第二小(i)的cost  
  410.         for (int32 i = 0; i < count; ++i)  
  411.         {  
  412.             b2AABB aabbi = m_nodes[nodes[i]].aabb;  
  413.             for (int32 j = i + 1; j < count; ++j)  
  414.             {  
  415.                 b2AABB aabbj = m_nodes[nodes[j]].aabb;  
  416.                 b2AABB b;  
  417.                 b.Combine(aabbi, aabbj);  
  418.                 float32 cost = b.GetPerimeter();  
  419.                 //获取最小的cost  
  420.                 if (cost < minCost)  
  421.                 {  
  422.                     iMin = i;  
  423.                     jMin = j;  
  424.                     minCost = cost;  
  425.                 }  
  426.             }  
  427.         }  
  428.         //获取左右孩子节点和左右子树  
  429.         int32 index1 = nodes[iMin];  
  430.         int32 index2 = nodes[jMin];  
  431.         b2TreeNode* child1 = m_nodes + index1;  
  432.         b2TreeNode* child2 = m_nodes + index2;  
  433.         //申请父子树索引  
  434.         int32 parentIndex = AllocateNode();  
  435.         //获取父子树节点  
  436.         b2TreeNode* parent = m_nodes + parentIndex;  
  437.         parent->child1 = index1;  
  438.         parent->child2 = index2;  
  439.         parent->height = 1 + b2Max(child1->height, child2->height);  
  440.         parent->aabb.Combine(child1->aabb, child2->aabb);  
  441.         parent->parent = b2_nullNode;  
  442.         //  
  443.         child1->parent = parentIndex;  
  444.         child2->parent = parentIndex;  
  445.         //覆盖最小aabb节点  
  446.         nodes[jMin] = nodes[count-1];  
  447.         //将第二小aabb节点用父节点覆盖  
  448.         nodes[iMin] = parentIndex;  
  449.         --count;  
  450.     }  
  451.     //获取跟节点  
  452.     m_root = nodes[0];  
  453.     //释放节点  
  454.     b2Free(nodes);  
  455.     //验证这棵树,用于测试  
  456.     Validate();  
  457. }  

这部分,我们主要来看一看Blance函数和RebuildBottomUp函数,Blance函数主要是调节树的平衡,使之成为平衡二叉树。主要步骤是:

a)、获取当前节点的两个孩子节点,比对孩子子树B、C的高度,求的高度差b

b)、若b不在[-1,1]之间,则上旋孩子子树较高的(这里假设是B),将父节点作为子树B的一个孩子,同时树的根节点指针m_root指向B节点。

c)、然后在B子树上进行a、b操作,直到叶子节点。同时返回新的根节点

我们就用上图中插入时形成的动态树但还没有进行平衡处理的树进行调整,如图:

哈哈,一棵平衡树就这样就成了,当然这个步骤不复杂,但是原理是一样的,就不介绍了。注意,我们可以看到,平衡操作后,叶子节点依然是叶子节点,我们所需要的信息还是在那里面。

下面我们说说RebuildBottomUp这个函数,它主要重新构建一棵树。

主要步骤是:

a)、获取所有叶子节点放入动态数组中,其他释放到叶子节点内存池中

b)、获取所有叶子节点中aabb最小的两个,申请一个节点,作为它们的父节点,形成一个新的子树

c)、用动态数组最后一个节点覆盖最小aabb的节点,用父节点放入动态数组aabb第二小的位置上。同时将动态数组中的节点个数减少一个。

d)、重复a、b、c步骤,直到动态数组中的节点个数为1个。

e)、获取头指针。

 

今天的动态树部分就说到这了,如有本人理解不妥或错误之处,望大家多多指正,同时也希望和大家多多交流。

0 0