[
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 Brandon Pelfrey\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "default:\n\tg++ main.cpp -O3 -o octree\nclean:\n\t@rm -f octree \n"
  },
  {
    "path": "Octree.h",
    "content": "#ifndef Octree_H\n#define Octree_H\n\n#include <cstddef>\n#include <vector>\n#include \"OctreePoint.h\"\n\nnamespace brandonpelfrey {\n\n\t/**!\n\t *\n\t */\n\tclass Octree {\n\t\t// Physical position/size. This implicitly defines the bounding \n\t\t// box of this node\n\t\tVec3 origin;         //! The physical center of this node\n\t\tVec3 halfDimension;  //! Half the width/height/depth of this node\n\n\t\t// The tree has up to eight children and can additionally store\n\t\t// a point, though in many applications only, the leaves will store data.\n\t\tOctree *children[8]; //! Pointers to child octants\n\t\tOctreePoint *data;   //! Data point to be stored at a node\n\n\t\t/*\n\t\t\t\tChildren follow a predictable pattern to make accesses simple.\n\t\t\t\tHere, - means less than 'origin' in that dimension, + means greater than.\n\t\t\t\tchild:\t0 1 2 3 4 5 6 7\n\t\t\t\tx:      - - - - + + + +\n\t\t\t\ty:      - - + + - - + +\n\t\t\t\tz:      - + - + - + - +\n\t\t */\n\n\t\tpublic:\n\t\tOctree(const Vec3& origin, const Vec3& halfDimension) \n\t\t\t: origin(origin), halfDimension(halfDimension), data(NULL) {\n\t\t\t\t// Initially, there are no children\n\t\t\t\tfor(int i=0; i<8; ++i) \n\t\t\t\t\tchildren[i] = NULL;\n\t\t\t}\n\n\t\tOctree(const Octree& copy)\n\t\t\t: origin(copy.origin), halfDimension(copy.halfDimension), data(copy.data) {\n\n\t\t\t}\n\n\t\t~Octree() {\n\t\t\t// Recursively destroy octants\n\t\t\tfor(int i=0; i<8; ++i) \n\t\t\t\tdelete children[i];\n\t\t}\n\n\t\t// Determine which octant of the tree would contain 'point'\n\t\tint getOctantContainingPoint(const Vec3& point) const {\n\t\t\tint oct = 0;\n\t\t\tif(point.x >= origin.x) oct |= 4;\n\t\t\tif(point.y >= origin.y) oct |= 2;\n\t\t\tif(point.z >= origin.z) oct |= 1;\n\t\t\treturn oct;\n\t\t}\n\n\t\tbool isLeafNode() const {\n\t\t\t// This is correct, but overkill. See below.\n\t\t\t/*\n\t\t\t\t for(int i=0; i<8; ++i)\n\t\t\t\t if(children[i] != NULL) \n\t\t\t\t return false;\n\t\t\t\t return true;\n\t\t\t */\n\n\t\t\t// We are a leaf iff we have no children. Since we either have none, or \n\t\t\t// all eight, it is sufficient to just check the first.\n\t\t\treturn children[0] == NULL;\n\t\t}\n\n\t\tvoid insert(OctreePoint* point) {\n\t\t\t// If this node doesn't have a data point yet assigned \n\t\t\t// and it is a leaf, then we're done!\n\t\t\tif(isLeafNode()) {\n\t\t\t\tif(data==NULL) {\n\t\t\t\t\tdata = point;\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\t// We're at a leaf, but there's already something here\n\t\t\t\t\t// We will split this node so that it has 8 child octants\n\t\t\t\t\t// and then insert the old data that was here, along with \n\t\t\t\t\t// this new data point\n\n\t\t\t\t\t// Save this data point that was here for a later re-insert\n\t\t\t\t\tOctreePoint *oldPoint = data;\n\t\t\t\t\tdata = NULL;\n\n\t\t\t\t\t// Split the current node and create new empty trees for each\n\t\t\t\t\t// child octant.\n\t\t\t\t\tfor(int i=0; i<8; ++i) {\n\t\t\t\t\t\t// Compute new bounding box for this child\n\t\t\t\t\t\tVec3 newOrigin = origin;\n\t\t\t\t\t\tnewOrigin.x += halfDimension.x * (i&4 ? .5f : -.5f);\n\t\t\t\t\t\tnewOrigin.y += halfDimension.y * (i&2 ? .5f : -.5f);\n\t\t\t\t\t\tnewOrigin.z += halfDimension.z * (i&1 ? .5f : -.5f);\n\t\t\t\t\t\tchildren[i] = new Octree(newOrigin, halfDimension*.5f);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Re-insert the old point, and insert this new point\n\t\t\t\t\t// (We wouldn't need to insert from the root, because we already\n\t\t\t\t\t// know it's guaranteed to be in this section of the tree)\n\t\t\t\t\tchildren[getOctantContainingPoint(oldPoint->getPosition())]->insert(oldPoint);\n\t\t\t\t\tchildren[getOctantContainingPoint(point->getPosition())]->insert(point);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// We are at an interior node. Insert recursively into the \n\t\t\t\t// appropriate child octant\n\t\t\t\tint octant = getOctantContainingPoint(point->getPosition());\n\t\t\t\tchildren[octant]->insert(point);\n\t\t\t}\n\t\t}\n\n\t\t// This is a really simple routine for querying the tree for points\n\t\t// within a bounding box defined by min/max points (bmin, bmax)\n\t\t// All results are pushed into 'results'\n\t\tvoid getPointsInsideBox(const Vec3& bmin, const Vec3& bmax, std::vector<OctreePoint*>& results) {\n\t\t\t// If we're at a leaf node, just see if the current data point is inside\n\t\t\t// the query bounding box\n\t\t\tif(isLeafNode()) {\n\t\t\t\tif(data!=NULL) {\n\t\t\t\t\tconst Vec3& p = data->getPosition();\n\t\t\t\t\tif(p.x>bmax.x || p.y>bmax.y || p.z>bmax.z) return;\n\t\t\t\t\tif(p.x<bmin.x || p.y<bmin.y || p.z<bmin.z) return;\n\t\t\t\t\tresults.push_back(data);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// We're at an interior node of the tree. We will check to see if\n\t\t\t\t// the query bounding box lies outside the octants of this node.\n\t\t\t\tfor(int i=0; i<8; ++i) {\n\t\t\t\t\t// Compute the min/max corners of this child octant\n\t\t\t\t\tVec3 cmax = children[i]->origin + children[i]->halfDimension;\n\t\t\t\t\tVec3 cmin = children[i]->origin - children[i]->halfDimension;\n\n\t\t\t\t\t// If the query rectangle is outside the child's bounding box, \n\t\t\t\t\t// then continue\n\t\t\t\t\tif(cmax.x<bmin.x || cmax.y<bmin.y || cmax.z<bmin.z) continue;\n\t\t\t\t\tif(cmin.x>bmax.x || cmin.y>bmax.y || cmin.z>bmax.z) continue;\n\n\t\t\t\t\t// At this point, we've determined that this child is intersecting \n\t\t\t\t\t// the query bounding box\n\t\t\t\t\tchildren[i]->getPointsInsideBox(bmin,bmax,results);\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\n\t};\n\n}\n#endif\n"
  },
  {
    "path": "OctreePoint.h",
    "content": "#ifndef OctreePoint_H\n#define OctreePoint_H\n\n#include \"Vec3.h\"\n\n// Simple point data type to insert into the tree.\n// Have something with more interesting behavior inherit\n// from this in order to store other attributes in the tree.\nclass OctreePoint {\n\tVec3 position; \npublic:\n\tOctreePoint() { }\n\tOctreePoint(const Vec3& position) : position(position) { }\n\tinline const Vec3& getPosition() const { return position; }\n\tinline void setPosition(const Vec3& p) { position = p; }\n};\n\n#endif\n"
  },
  {
    "path": "README.md",
    "content": "SimpleOctree\n============\n\nA simple octree with good commenting for learning how octrees work. Blog post incoming with description, or read comments in Octree.h\n\nUsage\n============\nmake && ./octree\n"
  },
  {
    "path": "Stopwatch.h",
    "content": "#ifndef _WIN32\r\n#include <sys/time.h>\r\n\r\ndouble stopwatch()\r\n{\r\n\tstruct timeval time;\r\n\tgettimeofday(&time, 0 );\r\n\treturn 1.0 * time.tv_sec + time.tv_usec / (double)1e6;\r\n}\r\n\r\n#else\r\n\r\n#include <windows.h>\r\ndouble stopwatch() \r\n{\r\n\tunsigned long long ticks;\r\n\tunsigned long long ticks_per_sec;\r\n\tQueryPerformanceFrequency( (LARGE_INTEGER *)&ticks_per_sec);\r\n\tQueryPerformanceCounter((LARGE_INTEGER *)&ticks);\r\n\treturn ((float)ticks) / (float)ticks_per_sec;\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "Vec3.h",
    "content": "#ifndef Vec3_h_\n#define Vec3_h_\n\n#include <cmath>\n\nstruct Vec3;\nVec3 operator*(float r, const Vec3& v);\n\nstruct Vec3 {\n\tunion {\n\t\tstruct {\n\t\t\tfloat x,y,z;\n\t\t};\n\t\tfloat D[3];\n\t};\n\n\tVec3() { }\n\tVec3(float _x, float _y, float _z)\n\t\t:x(_x), y(_y), z(_z)\n\t{ }\n\n\tfloat& operator[](unsigned int i) {\n\t\treturn D[i];\n\t}\n\n\tconst float& operator[](unsigned int i) const {\n\t\treturn D[i];\n\t}\n\n\tfloat maxComponent() const {\n\t\tfloat r = x;\n\t\tif(y>r) r = y;\n\t\tif(z>r) r = z;\n\t\treturn r;\n\t}\n\n\tfloat minComponent() const {\n\t\tfloat r = x;\n\t\tif(y<r) r = y;\n\t\tif(z<r) r = z;\n\t\treturn r;\n\t}\n\n\tVec3 operator+(const Vec3& r) const {\n\t\treturn Vec3(x+r.x, y+r.y, z+r.z); \n\t}\n\n\tVec3 operator-(const Vec3& r) const {\n\t\treturn Vec3(x-r.x, y-r.y, z-r.z); \n\t}\n\n\tVec3 cmul(const Vec3& r) const {\n\t\treturn Vec3(x*r.x, y*r.y, z*r.z);\n\t}\n\n\tVec3 cdiv(const Vec3& r) const {\n\t\treturn Vec3(x/r.x, y/r.y, z/r.z);\n\t}\n\n\tVec3 operator*(float r) const {\n\t\treturn Vec3(x*r,y*r,z*r);\n\t}\n\n\n\tVec3 operator/(float r) const {\n\t\treturn Vec3(x/r, y/r, z/r);\n\t}\n\n\tVec3& operator+=(const Vec3& r) {\n\t\tx+=r.x;\n\t\ty+=r.y;\n\t\tz+=r.z;\n\t\treturn *this;\n\t}\n\n\tVec3& operator-=(const Vec3& r) {\n\t\tx-=r.x;\n\t\ty-=r.y;\n\t\tz-=r.z;\n\t\treturn *this;\n\t}\n\n\tVec3& operator*=(float r) {\n\t\tx*=r; y*=r; z*=r;\n\t\treturn *this;\n\t}\n\n\t// Inner/dot product\n\tfloat operator*(const Vec3& r) const {\n\t\treturn x*r.x + y*r.y + z*r.z;\n\t}\n\n\tfloat norm() const {\n\t\treturn sqrtf(x*x+y*y+z*z);\n\t}\n\n\tfloat normSquared() const {\n\t\treturn x*x + y*y + z*z;\n\t}\n\n\t// Cross product\n\tVec3 operator^(const Vec3& r) const {\n\t\treturn Vec3(\n\t\t\t\ty * r.z - z * r.y, \n\t\t\t\tz * r.x - x * r.z, \n\t\t\t\tx * r.y - y * r.x\n\t\t\t\t);\n\t}\n\n\tVec3 normalized() const {\n\t\treturn *this / norm();\n\t}\n};\n\ninline Vec3 operator*(float r, const Vec3& v) {\n\treturn Vec3(v.x*r, v.y*r, v.z*r);\n}\n\n#endif\n"
  },
  {
    "path": "main.cpp",
    "content": "#include <cstdlib>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#include \"Octree.h\"\n#include \"Stopwatch.h\"\n\nusing namespace brandonpelfrey;\n\n// Used for testing\nstd::vector<Vec3> points;\nOctree *octree;\nOctreePoint *octreePoints;\nVec3 qmin, qmax;\n\nfloat rand11() // Random number between [-1,1]\n{ return -1.f + (2.f*rand()) * (1.f / RAND_MAX); }\n\nVec3 randVec3() // Random vector with components in the range [-1,1]\n{ return Vec3(rand11(), rand11(), rand11()); }\n\n// Determine if 'point' is within the bounding box [bmin, bmax]\nbool naivePointInBox(const Vec3& point, const Vec3& bmin, const Vec3& bmax) {\n\treturn \n\t\tpoint.x >= bmin.x &&\n\t\tpoint.y >= bmin.y &&\n\t\tpoint.z >= bmin.z &&\n\t\tpoint.x <= bmax.x &&\n\t\tpoint.y <= bmax.y &&\n\t\tpoint.z <= bmax.z;\n}\n\nvoid init() {\n\t// Create a new Octree centered at the origin\n\t// with physical dimension 2x2x2\n\toctree = new Octree(Vec3(0,0,0), Vec3(1,1,1));\n\n\t// Create a bunch of random points\n\tconst int nPoints = 1 * 1000 * 1000;\n\tfor(int i=0; i<nPoints; ++i) {\n\t\tpoints.push_back(randVec3());\n\t}\n\tprintf(\"Created %ld points\\n\", points.size()); fflush(stdout);\n\n\t// Insert the points into the octree\n\toctreePoints = new OctreePoint[nPoints];\n\tfor(int i=0; i<nPoints; ++i) {\n\t\toctreePoints[i].setPosition(points[i]);\n\t\toctree->insert(octreePoints + i);\n\t}\n\tprintf(\"Inserted points to octree\\n\"); fflush(stdout);\n\n\t// Create a very small query box. The smaller this box is\n\t// the less work the octree will need to do. This may seem\n\t// like it is exagerating the benefits, but often, we only\n\t// need to know very nearby objects.\n\tqmin = Vec3(-.05,-.05,-.05);\n\tqmax = Vec3(.05,.05,.05);\n\n\t// Remember: In the case where the query is relatively close\n\t// to the size of the whole octree space, the octree will\n\t// actually be a good bit slower than brute forcing every point!\n}\n\n// Query using brute-force\nvoid testNaive() {\n\tdouble start = stopwatch();\n\n\tstd::vector<int> results;\n\tfor(int i=0; i<points.size(); ++i) {\n\t\tif(naivePointInBox(points[i], qmin, qmax)) {\n\t\t\tresults.push_back(i);\n\t\t}\n\t}\n\n\tdouble T = stopwatch() - start;\n\tprintf(\"testNaive found %ld points in %.5f sec.\\n\", results.size(), T);\n}\n\n// Query using Octree\nvoid testOctree() {\n\tdouble start = stopwatch();\n\n\tstd::vector<OctreePoint*> results;\n\toctree->getPointsInsideBox(qmin, qmax, results);\n\n\tdouble T = stopwatch() - start;\n\tprintf(\"testOctree found %ld points in %.5f sec.\\n\", results.size(), T);\n}\n\n\nint main(int argc, char **argv) {\n\tinit();\n\ttestNaive();\n\ttestOctree();\n\n\treturn 0;\n}\n"
  }
]