I'm building a game engine and I was wondering: are there any algorithms out there for Collision Detection that have time complexity of O(N^log N)?
I haven't written any coding yet, but I can only think of a O(N^2) algorithm (ie: 2 for-loops looping through a list of object to see if there's collision).
Any advice and help will be appreciated.
Thanks
Spatial partitioning can create O(n log(n)) solutions. Depending on the exact structure and nature of your objects, you'll want a different spatial partitioning algorithm, but the most common are octrees and BSP.
Basically, the idea of spatial partitioning is to group objects by the space they occupy. An object in node Y can never collide with an object in node X (unless X is a subnode of Y or vice versa). Then you partition the objects by which go in which nodes. I implemented an octree myself.
You can minimize the number of checks by sorting the objects into areas of space.
( There is no point in checking for a collision between an object near 0,0 and one near 1000,1000 )
The obvious solution would be to succesively divide your space in half and use a tree (BSP) structure. Although this works best for sparse clouds of objects, otherwise you spend all the time checking if an object near a boundary hits an object just on the other side of the boundary
I assume you have a restricted interaction length, i.e. when two objects are a certain distance, there is no more interaction.
If that is so, you normally would divide your space into domains of appropriate size (e.g. interaction length in each direction). Now, for applying the interaction to a particle, all you need to do is go through its own domain and the nearest neighbor domains, because all other particles are guaranteed further away than the interaction length is. Of course, you must check at particle updates whether any domain boundary is crossed, and adjust the domain membership accordingly. This extra bookkeeping is no problem, considering the enormous performance improvement due to the lowered interacting pair count.
For more tricks I suggest a scientific book about numerical N-Body-Simulation.
Of course each domain has its own list of particles that are in that domain. There's no use having a central list of particles in the simulation and going through all entries to check on each one whether it's in the current or the neighboring domains.
I'm using oct-tree for positions in 3D, which can be quite in-homogeneously distributed. The tree (re-)build is usually quite fast, bot O(N log(N)). Then finding all collisions for a given particle can be done in O(K) with K the number of collisions per particle, in particular there is no factor log(N). So, to find all collisions then need O(K*N), after the tree build.
Related
I am looking for an efficient way to perform nearest neighbor searches within a specified radius in a two-dimensional plane. According to Wikipedia, space-partitioning data structures, such as :
k-d trees,
r-trees,
octrees,
quadtrees,
cover trees,
metric trees,
BBD trees
locality-sensitive hashing,
and bins,
are often used for organizing points in a multi-dimensional space and can provide O(log n) performance for search and insert operations. However, in my case, the points in the two-dimensional plane are moving at each iteration, so I need to update the tree accordingly. Rebuilding the tree from scratch at each iteration seems easier, but I would like to avoid it if possible because the points only move slightly between iterations.
I have read that k-d trees are not naturally balanced, which could be an issue in my case. R-trees, on the other hand, are better suited for storing rectangles. Bin algorithms, on the other hand, are easy to implement and provide near-linear search performance within local bins.
I am working on an autonomous agent simulation where 1,000,000 agents are rendered in the GPU, and the CPU is responsible for computing the next movement of each agent. Each agent is influenced by other agents within its line of sight, or in other words, other agents within a circular sector of angle θ and radius r. So here specific requirements for my use case:
Search space is a 2-d plane,
Each object is a point identified with the x,y coordinate.
All points are frequently updated by a small factor.
Cannot afford any O(n^2) algorithms.
Search within a radius (circular sector)
Search for all candidates within the search surface.
Given these considerations, what would be the best algorithms for my use case?
I think you could potentially solve this by doing a sort of scheduling approach. If you know that no object will move more than d distance in each iteration, and you want to know which objects are within X distance of each other on each iteration, then given the distances between all objects you know that on the next iteration the only potential pairs of objects that would change their neighbor status would be those with a distance between X-d and X+d. The iteration after that it would be X-2d and X+2d and so on.
So I'm thinking that you could do an initial distance calculation between all pairs of objects, and then based on each difference you can create an NxN matrix where the value in each cell is which iteration you will need to re-check their distance. Then when you re-check those during that iteration, you would update their values in this matrix for the next iteration that they need to be checked.
The only problem is whether calculating an initial NxN distance matrix is feasible.
Say you have a list of objects and every object needs to calculate his closest object to shoot. This object has a x and a y value. Also the objects are moving. Will a kd tree still be usefull? I am not sure because if the objects are moving you have to keep creating this kd tree.
What algorithm can i use for the best speed (Preferably with Big O)
The k-d tree is a very, very efficient data structure to determine closest neighbors in a euclidian space with cooordinates.
It would take a really huge number of objects to have issues with a k-d tree generation (it is generated in O(n log²n), so almost linear time, and search of all nearest neighbors takes O(n log n), very cheap too). So you would probably have issues with the rest of the program as well.
From the look of your question, it seems that all you need to keep track of is the closest neighbor of a number of points in a euclidian space. I'd suggest you to start with a vanilla implementation of a k-d tree, and, in the extreme and unlikely case where the generation of the k-d tree would be too costy in terms of time, or of memory, to try and find a way to keep track of several neighbors for each element, and update the list only when needed.
But honestly, I've been working with k-d tree in the past, and I remember that despite the data set being quite big (dozens of millions of points in a 2D space), the generation and search were fast enough to seem negligible w.r.t the other operations.
I'm working on implementing a ModelClass for any 3D model in my DirectX 11/12 pipeline.
My specific problem lies within calculating the min and max for the BoundingBox structure I wish to use as a member of the ModelClass.
I have two approaches to calculating them.
Approach 1.
When each vertex is being read from file, store a current minx,y,z and maxx,y,z and check each vertex as it is loaded in against the current min/max x,y,z.
Approach 2.
After all the vertices have been loaded, sort them by x, then y, then z, finding the lowest and highest value at each point.
Which Approach would you recommend and why?
Approach 1
Time complexity is in O(n) and memory complexity is O(1).
It is simple to implement.
Approach 2
Time complexity is O(nLogn) memory complexity is potentially at least linear (if you make a copy of the arrays or if you use merge sort) or O(1) if you use an in place sorting algorithm like quicksort.
This has to be done 3 times one for each dimension.
All in all Approach 1 is best in all scenarios I can think of.
Sorting generally is not a cheap operation especially as your models are getting larger. Therefore it to me like Approach 1 is more efficient but if unsure I suggest measuring it see which one takes longer.
If you are using a library like Asspimp I believe the library takes care of bounding boxes but this might not be an option if you create the pipeline as a learning opportunity.
I am programming a C++ simulation application in which several mass-spring structures will move and collide and I'm currently struggling with the collision detection and response part. These structures might or might not be closed (it might be a "ball" or just a chain of masses and springs) so it is (I think) impossible to use a "classic" approach where we test for 2 overlapping shapes.
Furthermore, the collisions are a really important part of that simulation and I need them to be as accurate as possible, both in terms of detection and response (real time is not a constraint here). I want to be able to know the forces applied to each Nodes (the masses), as far as possible.
At the moment I am detecting collisions between Nodes and springs at each time step, and the detection seems to work. I can compute the time of collision between one node and a spring, and thus find the exact position of the collision. However, I am not sure if this is the right approach for this problem and after lots of researches I can't quite find a way to make things work properly, mainly on the response aspect of the collisions.
Thus I would really like to hear from any technique, algorithm or library that seems well suited for this kind of collisions problems or any idea you might have to make this work. Really, any kind of help will be greatly appreciated.
If you can meet the following conditions:
0) All collisions are locally binary - that is to say
collisions only occur for pairs of particles, not triples etc,
1) you can predict the future time for a collision between
objects i and j from knowledge of their dynamics (assuming that no other
collision occurs first)
2) you know how to process the physics/dynamicseac of the collision
then you should be able to do the following:
Let Tpq be the predicted time for a collision between particles p and q, and Vp (Vq) be a structure holding the local dynamics of each particle p (q) (i.e its velocity, position, spring-constants, whatever)
For n particles...
Initialise by calculating all Tpq (p,q in 1..n)
Store the n^2 values of Tpq in a Priority Queue (PQ)
repeat
extract first Tpq from the PQ
Advance the time to Tpq
process the collision (i.e. update Vp and Vq according to your dynamics)
remove all Tpi, and Tiq (i in 1..n) from the PQ
// these will be invalid now as the changes in Vp, Vq means the
// previously calculated collision of p and q with any other particle
// i might occur sooner, later or not at all
recalculate new Tpi and Tiq (i in 1..n) and insert in the PQ
until done
There is an o(n^2) initial setup cost, but the repeat loop should be O(nlogn) - the cost of removing and replacing the 2n-1 invalidated collisions. This is fairly efficient for moderate numbers of particles (up to hundreds). It has the benefit that you only need to process things at collision time, rather than for equally spaced time steps. This makes things particularly efficient for a sparsely populated simulation.
I guess an octree approach would do best with your problem. An octree devides the virtual space into several recursive leaves of a tree and lets you compute possible collisions between the most probable nodes.
Here a short introduction: http://www.flipcode.com/archives/Introduction_To_Octrees.shtml :)
I have been looking for a quadtree/quadtree node implementation on the net for ages. There is some basic stuff but nothing that I would be able to really use it a game.
My purpose is to store objects in a game for processing things such as collision detection.
I am not 100% certain that a quadtree is the best data structure to use, but from what I have read it is. I have already coded a Red-Black tree, but I don't really know if the performance would be good enough for my game (which will be an adventure 3rd person game like Ankh).
How would I write a basic but complete quadtree class (or octree) in C++?
How would you use the quad tree for collisions?
Quadtrees are used when you only need to store things that are effectively on a plane. Like units in a classic RTS where they are all on the ground or just a little bit above it. Essentially each node has links to 4 children that divide the node's space up into evenly distributed quarters.
Octrees do the same but in all three dimensions rather than just two, and thus they have 8 child nodes and partition the space up into eights. They should be used when the game entities are distributed more evenly among all three dimensions.
If you are looking for a binary tree - like a red-black tree - then you want to use a data structure called a binary space partitioning tree (BSP tree) or a version of it called the KD Tree. These partition space into halves using a plane, in the KD tree the planes are orthogonal (on the XZ, XY, ZY axes) so sometimes it works better in a 3D scene. BSP trees divide the scene up using planes in any orientation, but they can be quite useful, and they were used as far back as Doom.
Now because you've partitioned the game space you now don't have to test every game entity against every other game entity to see if they collide, which is an O(n^2) algorithm at best. Instead you query the data structure to return the game entities within a sub-region of the game space, and only perform collision detection for those nodes against each other.
This means that collision detection for all game entities should be n O(nlogn) operation (at worst).
A couple of extra things to watch out for:
Make sure you test game entities from adjacent nodes, not just the ones in the current node, since they could still collide.
Rebalance the data structure after the entities have moved since you may have empty nodes in the data structure now, or ones that contain too many entities for good performance (also the degenerate case of all entities being in the same node).
A red-black tree is not a spatial index; it can only sort on a single ordinal key. A quadtree is (for two dimensions) a spatial index that allows fast lookup and elimination of points. An Octree does the same thing for three dimensions.
The reason to use a quadtree is because you can then split on x- and y-coordinates, an octree on x, y and z, making collision detection trivial.
Quadtree: if an element is not in the topleft, it wont collide with one in topright, bottomleft or bottomright.
It is a very basic class, so I don't understand what you are missing in implementations you found.
I would not write such a class, I'd just borrow it from a project with a suitable license.
I warmly suggest you to use a rendering engine, Ogre3D for instance. As far as I know it supports Octrees for scene management. But you can extend the Octree-based class as you wish. I used to code the stuff I needed by myself, but for complex projects, it's just not the right way.
Trees in general are problematic for this in that any item inserted can lie on a boundary, and all the methods of dealing with that situation are fairly unsatisfactory.
You'll most likely want to sort your objects into moveable and static, and check anything that moved on a given frame against the static objects.
BSP Trees are the accepted solution for static geometry (boundary cases handled by splitting the object into two pieces), for dynamic try something like Sort and Sweep (also known as Sweep and Prune).
Right now STANN is the best open source implementation.
http://sites.google.com/a/compgeom.com/stann/