<p>I do work in theoretical chemistry on a high performance cluster, often involving molecular dynamics simulations.  One of the problems my work addresses involves a static field of N-dimensional (typically N = 2-5) hyper-spheres, that a test particle may collide with.  I'm looking to optimize (read: overhaul) the the data structure I use for representing the field of spheres so I can do rapid collision detection.  Currently I use a dead simple array of pointers to an N-membered struct (doubles for each coordinate of the center) and a nearest-neighbor list.  I've heard of oct- and quad- trees but haven't found a clear explanation of how they work, how to efficiently implement one, or how to then do fast collision detection with one.  Given the size of my simulations, memory is (almost) no object, but cycles are.</p>

[{'answer_id': 78104, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 0, 'selected': False, 'text': '<p>A Quad tree is a 2 dimensional tree, in which at each level a node has 4 children, each of which covers 1/4 of the area of the parent node.</p>\n\n<p>An Oct tree is a 3 dimensional tree, in which at each level a node has 8 children, each of which contains 1/8th of the volume of the parent node.  Here is picture to help you visualize it: <a href="http://en.wikipedia.org/wiki/Octree" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Octree</a></p>\n\n<p>If you\'re doing N dimensional intersection tests, you could generalize this to an N tree.</p>\n\n<p>Intersection algorithms work by starting at the top of the tree and recursively traversing into any child nodes that intersect the object being tested, at some point you get to leaf nodes, which contain the actual objects.</p>\n'}, {'answer_id': 78117, 'author': 'Marcel Levy', 'author_id': 676, 'author_profile': 'https://Stackoverflow.com/users/676', 'pm_score': 1, 'selected': False, 'text': '<p>It sounds like you\'d want to implement a <a href="http://en.wikipedia.org/wiki/Kd-tree" rel="nofollow noreferrer">kd-tree,</a> which would allow you to more quickly search the N-dimensional space. There\'s some more information and links to implementations at <a href="http://www.cs.sunysb.edu/~algorith/files/kd-trees.shtml" rel="nofollow noreferrer">the Stony Brook Algorithm Repository.</a></p>\n'}, {'answer_id': 78139, 'author': 'user14273', 'author_id': 14273, 'author_profile': 'https://Stackoverflow.com/users/14273', 'pm_score': 1, 'selected': False, 'text': '<p>Since your field is static (by which I\'m assuming you mean that the hyper spheres don\'t move), then the fastest solution I know of is a Kdtree.<br>\nYou can either make your own, or use someone else\'s, like this one:\n<a href="http://libkdtree.alioth.debian.org/" rel="nofollow noreferrer">http://libkdtree.alioth.debian.org/</a></p>\n'}, {'answer_id': 81455, 'author': 'danio', 'author_id': 12663, 'author_profile': 'https://Stackoverflow.com/users/12663', 'pm_score': 2, 'selected': False, 'text': '<p>How best to approach this for your problem depends on several factors that you have not described:\n- Will the same hypersphere arrangement be used for many particle collision calculations?\n- Are the hyperspheres uniform size?\n- What is the movement of the particle (e.g. straight line/curve) and is that movement affected by the spheres?\n- Do you consider the particle to have zero volume?</p>\n\n<p>I assume that the particle does not have simple straight line movement as that would be the relatively fast calculation of finding the closest point between a line and a point, which is likely going to be about the same speed as finding which of the boxes the line intersects with (to determine where in the n-tree to examine).</p>\n\n<p>If your hypersphere positions are fixed for a lot of particle collisions then computing a <a href="http://en.wikipedia.org/wiki/Voronoi_diagram" rel="nofollow noreferrer">voronoi decomposition/Dirichlet tessellation</a> would give you a fast way of later finding exactly which sphere is closest to your particle for any given point in the space.</p>\n\n<p>However to answer your original question about octrees/quadtrees/2^n-trees, in n dimensions you start with a (hyper)-cube that contains the area of space that you are interested in.  This will be subdivided into 2^n hypercubes if you deem the contents to be too complicated.  This continues recursively until you have only simple elements (e.g. one hypersphere centroid) in the leaf nodes.\nNow that the n-tree is built you use it for collision detection by taking the path of your particle and intersecting it with the outer hypercube. The intersection position will tell you which hypercube in the next level down of the tree to visit next, and you determine the position of intersection with all 2^n hypercubes at that level, following downwards until you reach a leaf node.  Once you reach the leaf you can examine interactions between your particle path and the hypersphere stored at that leaf.  If you have collision you have finished, otherwise you have to find the exit point of the particle path from the current hypercube leaf and determine which hypercube it moves to next.  Continue until you find a collision or entirely leave the overall bounding hypercube.</p>\n\n<p>Efficiently finding the neighbouring hypercube when exiting a hypercube is one of the most challenging parts of this approach.  For 2^n trees Samet\'s approaches {1, 2} can be adapted.  For kd-trees (binary trees) an approach is suggested in {3} section 4.3.3.</p>\n\n<p>Efficient implementation can be as simple as storing a list of 8 pointers from each hypercube to its children hypercubes, and marking the hypercube in a special way if it is a leaf (e.g. make all pointers NULL).</p>\n\n<p>A description of dividing space to create a quadtree (which you can generalise to n-tree) can be found in Klinger &amp; Dyer {4}</p>\n\n<p>As others have mentioned kd-trees may be more suited than 2^n-trees as extension to an arbitrary number of dimensions is more straightforward, however they will result in a deeper tree.  It is also easier to adapt the split positions to match the geometry of your \nhyperspheres with a kd-tree.  The description above of collision detection in a 2^n tree is equally applicable to a kd-tree.</p>\n\n<p>{1} <a href="http://portal.acm.org/citation.cfm?id=322267&amp;dl=ACM&amp;coll=ACM" rel="nofollow noreferrer">Connected Component Labeling, Hanan Samet,  Using Quadtrees Journal of the ACM  Volume 28 ,  Issue 3  (July 1981)</a></p>\n\n<p>{2} <a href="http://portal.acm.org/citation.cfm?id=65329" rel="nofollow noreferrer">Neighbor finding in images represented by octrees, Hanan Samet, Computer Vision, Graphics, and Image Processing  Volume 46 ,  Issue 3  (June 1989)</a></p>\n\n<p>{3} <a href="http://people.bath.ac.uk/ensab/G_mod/Distances/" rel="nofollow noreferrer">Convex hull generation, connected component labelling, and minimum distance\ncalculation for set-theoretically defined models, Dan Pidcock, 2000</a></p>\n\n<p>{4} Experiments in picture representation using regular decomposition, Klinger, A., and Dyer, C.R. E, Comptr. Graphics and Image Processing 5 (1976), 68-105.</p>\n'}, {'answer_id': 81527, 'author': 'ConcernedOfTunbridgeWells', 'author_id': 15401, 'author_profile': 'https://Stackoverflow.com/users/15401', 'pm_score': 0, 'selected': False, 'text': '<p>An octree will work as long as you can specify the spheres by their centres - it hierarchically bins points into cubic regions with eight children.  Working out neighbours in an octree data structure will require you to do sphere-intersecting-cube calculations (to some extent easier than they look) to work out which cubic regions in an octree are within the sphere.</p>\n\n<p>Finding the nearest neighbours means walking back up the tree until you get a node with more than one populated child and all surrounding nodes included (this ensures the query gets all sides).</p>\n\n<p>From memory, this is the (somewhat naive) basic algorithm for sphere-cube intersection:</p>\n\n<p>i. Is the centre within the cube (this gets the eponymous situation)</p>\n\n<p>ii. Are any of the corners of the cube within radius r of the centre (corners within the sphere)</p>\n\n<p>iii. For each surface of the cube (you can eliminate some of the surfaces by working out which side of the surface the centre lies on) work out (this is all first-year vector arithmetic):</p>\n\n<p>a. A normal of the surface that goes to the centre of the sphere</p>\n\n<p>b. The distance from the centre of the sphere to the intersection of the normal with the plane of the surface (chord intersets plane the surface of the cube)</p>\n\n<p>c. Intersection of the plane lies within the side of the cube (one condition of chord intersection to the cube)</p>\n\n<p>iv. Calculate the size of the chord (Sin of Cos^-1 of ratio of normal length to radius of sphere)</p>\n\n<p>v. If the nearest point on the line is less than the distance of the chord and the point lies between the ends of the line the chord intersects one of the edges of the cube (chord intersects cube surface somewhere along one of the edges).</p>\n\n<p>Slightly dimly remembered but this is something I did for a situation involving spherical regions using an octee data structure (many years ago).  You may also wish to check out KD-trees as some of the other posters suggest but your initial question sounds very similar to what I did.</p>\n'}]
['https://Stackoverflow.com/questions/78045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']