#include "BSPTree.h" #include BSPTree::BSPTree(const std::list &triangles) : frontTree(0), backTree(0) { if(triangles.empty()) return; vmml::vec3f center = findCenter(triangles); std::cout << "Center at " << center << std::endl; const Triangle *planeT = findNearestTriangle(triangles, center); plane = Plane(*planeT); std::cout << "The plane normal is " << plane.getNormal() << std::endl; std::list front, back; for(std::list::const_iterator t = triangles.begin(); t != triangles.end(); ++t) { if(plane.contains(*t)) { this->triangles.push_back(*t); continue; } else if(plane.isInFront(*t)) { front.push_back(*t); continue; } else if(plane.isBehind(*t)) { back.push_back(*t); continue; } } std::cout << "All in all: " << triangles.size() << " triangles" << std::endl; std::cout << "Coplanar: " << this->triangles.size() << " triangles" << std::endl; std::cout << "Front: " << front.size() << " triangles" << std::endl; std::cout << "Back: " << back.size() << " triangles" << std::endl; if(!front.empty()) frontTree = new BSPTree(front); if(!back.empty()) backTree = new BSPTree(back); } vmml::vec3f BSPTree::findCenter(const std::list &triangles) { vmml::vec3f v; for(std::list::const_iterator t = triangles.begin(); t != triangles.end(); ++t) { v += t->getCenter(); } return v/triangles.size(); } const Triangle* BSPTree::findNearestTriangle(const std::list &triangles, const vmml::vec3f &v) { if(triangles.empty()) return 0; std::list::const_iterator t = triangles.begin(); const Triangle *current = &*t; float distanceSq = current->getCenter().squared_distance(v); for(++t; t != triangles.end(); ++t) { float d = t->getCenter().squared_distance(v); if(d < distanceSq) { current = &*t; distanceSq = d; } } vmml::vec3f tCenter = current->getCenter(); std::cout << "Nearest triangle center at " << tCenter << std::endl; std::cout << "DistanceSq is " << distanceSq << std::endl; return current; }