Repository: brandonpelfrey/SimpleOctree Branch: master Commit: f334cf2c9116 Files: 8 Total size: 11.3 KB Directory structure: gitextract_u777gmx3/ ├── LICENSE ├── Makefile ├── Octree.h ├── OctreePoint.h ├── README.md ├── Stopwatch.h ├── Vec3.h └── main.cpp ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Brandon Pelfrey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Makefile ================================================ default: g++ main.cpp -O3 -o octree clean: @rm -f octree ================================================ FILE: Octree.h ================================================ #ifndef Octree_H #define Octree_H #include #include #include "OctreePoint.h" namespace brandonpelfrey { /**! * */ class Octree { // Physical position/size. This implicitly defines the bounding // box of this node Vec3 origin; //! The physical center of this node Vec3 halfDimension; //! Half the width/height/depth of this node // The tree has up to eight children and can additionally store // a point, though in many applications only, the leaves will store data. Octree *children[8]; //! Pointers to child octants OctreePoint *data; //! Data point to be stored at a node /* Children follow a predictable pattern to make accesses simple. Here, - means less than 'origin' in that dimension, + means greater than. child: 0 1 2 3 4 5 6 7 x: - - - - + + + + y: - - + + - - + + z: - + - + - + - + */ public: Octree(const Vec3& origin, const Vec3& halfDimension) : origin(origin), halfDimension(halfDimension), data(NULL) { // Initially, there are no children for(int i=0; i<8; ++i) children[i] = NULL; } Octree(const Octree& copy) : origin(copy.origin), halfDimension(copy.halfDimension), data(copy.data) { } ~Octree() { // Recursively destroy octants for(int i=0; i<8; ++i) delete children[i]; } // Determine which octant of the tree would contain 'point' int getOctantContainingPoint(const Vec3& point) const { int oct = 0; if(point.x >= origin.x) oct |= 4; if(point.y >= origin.y) oct |= 2; if(point.z >= origin.z) oct |= 1; return oct; } bool isLeafNode() const { // This is correct, but overkill. See below. /* for(int i=0; i<8; ++i) if(children[i] != NULL) return false; return true; */ // We are a leaf iff we have no children. Since we either have none, or // all eight, it is sufficient to just check the first. return children[0] == NULL; } void insert(OctreePoint* point) { // If this node doesn't have a data point yet assigned // and it is a leaf, then we're done! if(isLeafNode()) { if(data==NULL) { data = point; return; } else { // We're at a leaf, but there's already something here // We will split this node so that it has 8 child octants // and then insert the old data that was here, along with // this new data point // Save this data point that was here for a later re-insert OctreePoint *oldPoint = data; data = NULL; // Split the current node and create new empty trees for each // child octant. for(int i=0; i<8; ++i) { // Compute new bounding box for this child Vec3 newOrigin = origin; newOrigin.x += halfDimension.x * (i&4 ? .5f : -.5f); newOrigin.y += halfDimension.y * (i&2 ? .5f : -.5f); newOrigin.z += halfDimension.z * (i&1 ? .5f : -.5f); children[i] = new Octree(newOrigin, halfDimension*.5f); } // Re-insert the old point, and insert this new point // (We wouldn't need to insert from the root, because we already // know it's guaranteed to be in this section of the tree) children[getOctantContainingPoint(oldPoint->getPosition())]->insert(oldPoint); children[getOctantContainingPoint(point->getPosition())]->insert(point); } } else { // We are at an interior node. Insert recursively into the // appropriate child octant int octant = getOctantContainingPoint(point->getPosition()); children[octant]->insert(point); } } // This is a really simple routine for querying the tree for points // within a bounding box defined by min/max points (bmin, bmax) // All results are pushed into 'results' void getPointsInsideBox(const Vec3& bmin, const Vec3& bmax, std::vector& results) { // If we're at a leaf node, just see if the current data point is inside // the query bounding box if(isLeafNode()) { if(data!=NULL) { const Vec3& p = data->getPosition(); if(p.x>bmax.x || p.y>bmax.y || p.z>bmax.z) return; if(p.xorigin + children[i]->halfDimension; Vec3 cmin = children[i]->origin - children[i]->halfDimension; // If the query rectangle is outside the child's bounding box, // then continue if(cmax.xbmax.x || cmin.y>bmax.y || cmin.z>bmax.z) continue; // At this point, we've determined that this child is intersecting // the query bounding box children[i]->getPointsInsideBox(bmin,bmax,results); } } } }; } #endif ================================================ FILE: OctreePoint.h ================================================ #ifndef OctreePoint_H #define OctreePoint_H #include "Vec3.h" // Simple point data type to insert into the tree. // Have something with more interesting behavior inherit // from this in order to store other attributes in the tree. class OctreePoint { Vec3 position; public: OctreePoint() { } OctreePoint(const Vec3& position) : position(position) { } inline const Vec3& getPosition() const { return position; } inline void setPosition(const Vec3& p) { position = p; } }; #endif ================================================ FILE: README.md ================================================ SimpleOctree ============ A simple octree with good commenting for learning how octrees work. Blog post incoming with description, or read comments in Octree.h Usage ============ make && ./octree ================================================ FILE: Stopwatch.h ================================================ #ifndef _WIN32 #include double stopwatch() { struct timeval time; gettimeofday(&time, 0 ); return 1.0 * time.tv_sec + time.tv_usec / (double)1e6; } #else #include double stopwatch() { unsigned long long ticks; unsigned long long ticks_per_sec; QueryPerformanceFrequency( (LARGE_INTEGER *)&ticks_per_sec); QueryPerformanceCounter((LARGE_INTEGER *)&ticks); return ((float)ticks) / (float)ticks_per_sec; } #endif ================================================ FILE: Vec3.h ================================================ #ifndef Vec3_h_ #define Vec3_h_ #include struct Vec3; Vec3 operator*(float r, const Vec3& v); struct Vec3 { union { struct { float x,y,z; }; float D[3]; }; Vec3() { } Vec3(float _x, float _y, float _z) :x(_x), y(_y), z(_z) { } float& operator[](unsigned int i) { return D[i]; } const float& operator[](unsigned int i) const { return D[i]; } float maxComponent() const { float r = x; if(y>r) r = y; if(z>r) r = z; return r; } float minComponent() const { float r = x; if(y #include #include #include #include "Octree.h" #include "Stopwatch.h" using namespace brandonpelfrey; // Used for testing std::vector points; Octree *octree; OctreePoint *octreePoints; Vec3 qmin, qmax; float rand11() // Random number between [-1,1] { return -1.f + (2.f*rand()) * (1.f / RAND_MAX); } Vec3 randVec3() // Random vector with components in the range [-1,1] { return Vec3(rand11(), rand11(), rand11()); } // Determine if 'point' is within the bounding box [bmin, bmax] bool naivePointInBox(const Vec3& point, const Vec3& bmin, const Vec3& bmax) { return point.x >= bmin.x && point.y >= bmin.y && point.z >= bmin.z && point.x <= bmax.x && point.y <= bmax.y && point.z <= bmax.z; } void init() { // Create a new Octree centered at the origin // with physical dimension 2x2x2 octree = new Octree(Vec3(0,0,0), Vec3(1,1,1)); // Create a bunch of random points const int nPoints = 1 * 1000 * 1000; for(int i=0; iinsert(octreePoints + i); } printf("Inserted points to octree\n"); fflush(stdout); // Create a very small query box. The smaller this box is // the less work the octree will need to do. This may seem // like it is exagerating the benefits, but often, we only // need to know very nearby objects. qmin = Vec3(-.05,-.05,-.05); qmax = Vec3(.05,.05,.05); // Remember: In the case where the query is relatively close // to the size of the whole octree space, the octree will // actually be a good bit slower than brute forcing every point! } // Query using brute-force void testNaive() { double start = stopwatch(); std::vector results; for(int i=0; i results; octree->getPointsInsideBox(qmin, qmax, results); double T = stopwatch() - start; printf("testOctree found %ld points in %.5f sec.\n", results.size(), T); } int main(int argc, char **argv) { init(); testNaive(); testOctree(); return 0; }