C++ 四叉树三角形插入和搜索
我正在尝试用三角形对象实现四叉树数据结构,这样我就可以进行光线三角形相交。但它是在质疑不必要的三角形。我不知道这是否是四叉树的属性 以下是我的四叉树插入代码:C++ 四叉树三角形插入和搜索,c++,data-structures,graphics,quadtree,C++,Data Structures,Graphics,Quadtree,我正在尝试用三角形对象实现四叉树数据结构,这样我就可以进行光线三角形相交。但它是在质疑不必要的三角形。我不知道这是否是四叉树的属性 以下是我的四叉树插入代码: //First check if triangle is inside the node box. If it does, //then subdivide until to insert triangle into the lowest node. //If it doesn't insert into its child, then
//First check if triangle is inside the node box. If it does,
//then subdivide until to insert triangle into the lowest node.
//If it doesn't insert into its child, then insert into the root's
//data.
bool insert(const Triangle& triangle, uint depth = 0) {
if (!triangle.isInside(bound) || depth >= 10) return false;
if (!divided) subdivide();
//insert into root if no nodes can support it
if (!(NW->insert(triangle, depth + 1) || NE->insert(triangle, depth + 1) ||
SW->insert(triangle, depth + 1) || SE->insert(triangle, depth + 1))) {
triangles.push_back(triangle);
}
return true;
}
搜索代码:
void searchTriangles(const QuadTree& tree, const Line& line, vector<Vertex>& vertices, Color color) {
Vector2f hit;
const Boundary* treeBounds = tree.getBound();
//if ray doesn't intersect the box, then exit.
if (!intersect(treeBounds->topLeft, treeBounds->bottomRight, line.p1, line.p2, hit)) return;
//Get all the triangles from this node and childern.
const vector<Triangle>* triangles = tree.getTriangles();
for (const Triangle& t : *triangles) {
vertices.push_back(Vertex(Vector2f(t.getP1()->x, t.getP1()->y), color));
vertices.push_back(Vertex(Vector2f(t.getP2()->x, t.getP2()->y), color));
vertices.push_back(Vertex(Vector2f(t.getP3()->x, t.getP3()->y), color));
}
if (!tree.subdivided()) return;
searchTriangles(*tree.getNW(), line, vertices, color);
searchTriangles(*tree.getNE(), line, vertices, color);
searchTriangles(*tree.getSW(), line, vertices, color);
searchTriangles(*tree.getSE(), line, vertices, color);
}
void searchTriangles(常量四叉树和树、常量直线和直线、向量和顶点、颜色){
向量2f命中;
常量边界*treeBounds=tree.getBound();
//如果光线与长方体不相交,则退出。
如果(!intersect(树根->左上,树根->右下,line.p1,line.p2,hit))返回;
//从该节点和子节点获取所有三角形。
常量向量*三角形=tree.getTriangles();
用于(常量三角形和t:*三角形){
顶点。向后推(顶点(向量2f(t.getP1()->x,t.getP1()->y),颜色);
顶点。向后推(顶点(向量2f(t.getP2()->x,t.getP2()->y),颜色);
顶点。向后推(顶点(向量2f(t.getP3()->x,t.getP3()->y),颜色);
}
如果(!tree.definated())返回;
搜索三角形(*tree.getNW(),直线,顶点,颜色);
搜索三角形(*tree.getNE(),直线,顶点,颜色);
搜索三角形(*tree.getSW(),直线,顶点,颜色);
搜索三角形(*tree.getSE(),直线,顶点,颜色);
}
示例输出:
//如果插入,则不需要检查其他选项--建议--而不是
goto
,如果(NW->insert(triangle,depth+1)| NE->insert(triangle,depth+1)| |……)返回true,则可以执行;else三角形。向后推(三角形);返回false代码>。|
可以作为短路评估器使用。考虑到这一点,你需要发表一篇文章。我想说你的例子效果很好。之所以会看到十字架,是因为如果父对象位于其子对象的边界上,则会在父对象中插入三角形。另一种方法是在与其重叠的所有子对象中插入三角形。对于遍历,您可能需要记住测试过的三角形,以避免重复。