Finding time and position of intersection of two moving, rotating bounding boxes - algorithm

With an emphasis on finding the time (when the intersection starts), although the position is also important. The bounding boxes (not axis aligned) have a position, rotation, velocity, and angular velocity (rate of rotation). NO accelerations, which should really simplify things... And I could probably remove the angular velocity component as well if necessary. Either a continuous or iterative function would work, but unless the iterative function actively converges toward a solution (or lack thereof), it probably would be too slow.
I looked at the SAT, but it doesn't seem to be built to find the actual time of collision of moving objects. It seems to only work with non-moving snapshots and is designed to work with more complicated objects than rectangles, so it actually seems ill-suited to this problem.
I've considered possibly drawing the trajectory out of each of the 8 points then somehow having a function for if a point is in or out of the other shape and getting a time range of that occurring, but I'm pretty lost on how to go about that. One nice feature would be that it operates entirely with time and ignores the idea of discrete "steps", but it also strikes me as an inefficient approach.
No worries about broad phase (determining if it's worth seeing if these two bounding boxes may overlap), I already have that tackled.

Finding an exact collision time is essentially a nonlinear root-finding problem. This means that you will ultimately need an iterative approach to determine the final collision time -- but the clever bit in designing a collision solver is to avoid the root-solving when it isn't actually necessary...
The SAT is a theorem, not an algorithm: it can be used to guide the design of a collision solver, but it is not one itself. Briefly, it says that, if you can demonstrate a separating axis exists, the objects have not collided. Conversely, if you can show that there is no such axis, then the objects currently do overlap. As you point out, you can use this principle more-or-less directly, to design a binary "yes/no" query as to whether two objects in given positions overlap or not.
The difference with a collision solver is that the problem is animated, or kinetic: object position is a function of time. One way to solve this problem is to start with a valid "yes/no" collision test, treat all the inequalities as functions of time, and use root-finding methods to look for the actual collision times on that basis.
There is a variety of existing methods in published academic literature. I recommend some library research: the best option probably depends on the details of your application.

First of all, instead of thinking of two rectangles moving with speed (x1, y1) and (x2, y2) respectively, you may fix one of them (set its speed to (0, 0) ) and think of another one moving with speed (x2 - x1, y2 - y1).
This way, the situation looks like one rectangle is immovable, and another one is passing by, possibly hitting the first.
Assuming you don't have any angular velocity
Not hard to see, that you can then intersect 4 trajectories of a second rectangle (they are rays starting from different corners of a bounding box in (x2 - x1, y2 - y1) direction) with 4 sides of the first rectangle, standing still. Then you'll have to do the same vice versa - find the intersection of a first rectangle moving in reverse direction - (-(x2 - x1), -(y2 - y1)) with 4 sides of a second rectangle. Choose the minimum distance between the all intersection points you've found (there might be 0-8 of them) and you're done.
Don't forget to consider many special cases - when the sides of both rectangles are parallel, when there's no intersection at all etc.
Note, this all is done in O(1) time, though the calculations are quite complex - 32 intersections of a ray and a segment.
If you really wish your rectangles to rotate with some speed, I would suggest considering what #comingstorm has said: this is a problem of finding roots of a non-linear equation, however, even in such case, if you have a limited angular speed of your rectangles, you may split the task into a series of ternary search subtasks, though I suppose this is just one of possible methods of solving non-linear problems.

Related

How to calculate the normals of a box?

I am trying to create an algorithm that calculate the normals of a model/ mesh. People have been telling me to use the cross products between the two vectors which at first seem like a good idea until I discovered that it might not always work. For instance just imagine a box with its front face sitting at the origin and its back face down the Z axis. Here is an image:
I do apologize for bad hand writing but that shouldn't be of any significance. As you can see,I cross v and u to get the normal pointing toward the positive z axis. However, If I use that same calculation to calculate the normal for the back face then obviously the normal will then be a vector directing inside the shape. The result is that I have inaccurate normals to calculate the brightness of a light. I want the normal to be facing away from the model at all time.
I know there gotta be a better way to calculate the normal but I don't know what it is. Can anyone suggests to me another algorithm to calculate the normal that would get rid of this problem? If not then there has to be a way to check whether or not a normal is facing inside the object / model. If so then can you suggests it in the answer and where I would find an explanation about it because I would love to have an intuition on how these methodologies work.
Most software packages obey a configurable cyclic ordering for triangle indices - clockwise or anti-clockwise. Thus all meshes they export have self-consistent ordering, and as long as your program uses the same convention, you should have nothing to worry about.
Having said that, I imagine you want to know what to do in the hypothetical (?) situation where the index ordering is inconsistent.
One method we could use is ray-intersection. The important theorem is that a ray with its source outside the mesh will only intersect the mesh an even number of times, and if inside, odd.
To do this, we can do the following:
Calculate the "normal" using the cross product as above (and normalize it) => N
Take any point on the triangle (preferably the midpoint)
Increment this point along the normal by some small epsilon value (depends on your floating point format and size of model - I'd say 1e-4 for single and 1e-8 for double precision) => P
Intersect this ray [dir = N, src = P] with all triangles in the mesh (a good algorithm for this would be Möller–Trumbore)
If the number of intersections is even, then the ray started from outside of the mesh; this means that the normal points outwards from the mesh (because you incremented its source from a point on the surface). - and of course, vice versa.
Minor (-ish ?) digression: a naive approach to the above, of looping through all triangles in the mesh, would be O(n) - and hence the whole procedure would have quadratic time complexity. This is perfectly fine for very small meshes of ~20 triangles (e.g. a box), but not ideal for any larger!
You can use spatial sub-division techniques to lower the cost of this intersection step:
K-D trees / Octrees: These require O(n log n) (for the best algorithm, that is - see Ingo Wald's paper) to construct, but intersections are guaranteed to be O(log n) if done properly. The overall complexity would then be O(n log n), which is pretty much the best you can get
Grid: This simply partitions the search space and triangles into smaller boxes. Construction is O(n) and much more memory-efficient. Intersection time is still O(n), but the constant factor is much smaller than that of the naive approach.
Cross products are not commutative so v x u is not the same as u x v. In fact, they will be the exact opposite.
For the front face, you want to take u x v (assuming you're in a right-hand coordinate system), and the back face you want to cross v x u.
See right-hand rule for more info on how crossing vectors works.

What "boundary conditions" can make a rectangle "look" like a circle?

I am solving a fourth order non-linear partial differential equation in time and space (t, x) on a square domain with periodic or free boundary conditions with MATHEMATICA.
WITHOUT using conformal mapping, what boundary conditions at the edge or corner could I use to make the square domain "seem" like a circular domain for my non-linear partial differential equation which is cartesian?
The options I would NOT like to use are:
Conformal mapping
changing my equation to polar/cylindrical coordinates?
This is something I am pursuing purely out of interest just in case someone screams bloody murder if misconstrued as a homework problem! :P
That question was asked on the time people found out that the world was spherical. They wanted to make rectangular maps of the surface of the world...
It is not possible.
The reason why is not possible is because the sphere has an intrinsic curvature, while the cube/parallelepiped has not. It can be shown that for two elements with different intrinsic curvatures, their surfaces cannot be mapped while either keeping constant infinitesimal distances, either the distance between two points is given by the euclidean distance.
The easiest way to understand this problem is to pick some rectangular piece of paper and try to make a sphere of it without locally stretch it or compress it (you can fold). You can't. On the other hand, you can make a cylinder surface, because the cylinder has also no intrinsic curvature.
In maps, normally people use one of the two options:
approximate the local surface of the sphere by a tangent plane and make a rectangle out of it. (a local map of some region)
make world maps but implement some curved lines everywhere identifying that the measuring distances must be made according to those lines.
This is also the main reason why when traveling from Europe to North America the airplanes seems to make a curve always trying to pass near canada. If we measured the distance from the rectangular map, we see that they should go on a strait line to minimize the distance. However, because we are mapping two different intrinsic curvatures, the real distance must be measured in a different way (and not via a strait line).
For 2D (in fact for nD) the same reasoning applies.

Continuous Physics Engine's Collision Detection Techniques

I'm working on a purely continuous physics engine, and I need to choose algorithms for broad and narrow phase collision detection. "Purely continuous" means I never do intersection tests, but instead want to find ways to catch every collision before it happens, and put each into "planned collisions" stack that is ordered by TOI.
Broad Phase
The only continuous broad-phase method I can think of is encasing each body in a circle and testing if each circle will ever overlap another. This seems horribly inefficient however, and lacks any culling.
I have no idea what continuous analogs might exist for today's discrete collision culling methods such as quad-trees either. How might I go about preventing inappropriate and pointless broad test's such as a discrete engine does?
Narrow Phase
I've managed to adapt the narrow SAT to a continuous check rather than discrete, but I'm sure there's other better algorithms out there in papers or sites you guys might have come across.
What various fast or accurate algorithm's do you suggest I use and what are the advantages / disatvantages of each?
Final Note:
I say techniques and not algorithms because I have not yet decided on how I will store different polygons which might be concave, convex, round, or even have holes. I plan to make a decision on this based on what the algorithm requires (for instance if I choose an algorithm that breaks down a polygon into triangles or convex shapes I will simply store the polygon data in this form).
You said circles, so I'm assuming you have 2D objects. You could extend your 2D object (or their bounding shapes) into 3D by adding a time dimension, and then you can use the normal techniques for checking for static collisions among a set of 3D objects.
For example, if you have a circle in (x, y) moving to the right (+x) with constant velocity, then, when you extend that with a time dimension, you have a diagonal cylinder in (x, y, t). By doing intersections between these 3D objects (just treat time as z), you can see if two objects will ever intersect. If point P is a point of intersection, then you know the time of that intersection simply by looking at P.t.
This generalizes into higher dimensions, too, though the math gets hard (for me anyway).
The collision detection might be tricky if objects have complex paths. For example, if your circle is influenced by gravity, then the extruded space-time object is a parabolic sphere sweep rather than a simple cylinder. You could pad the bounding objects a bit and use linear approximations over shorter periods of time and iterate, but I'm not sure if that violates what you mean by continuous.
I am going to assume you want things like gravity or other conservative forces in your simulation. If that's the case the trajectories of your objects are most likely not going to be lines, in which case, just like Adrian pointed out, the math will be somewhat harder. I can't think of a way to avoid checking all possible combinations of curves for collisions, but you can calculate the minimum distance between two curves rather easily, as long as both are solutions to linear systems (or, in general, if you have a closed form solution for the curves). If you know that x1(t) = f(t) and x2(t) = g(t) then what you'll want to
do is calculate the distance ||x1(t) - x2(t)|| and set its derivative to zero. This should be an expression that depends on f(t), g(t) and their derivatives and will give you a time tmin (or maybe a few possible ones) at which you then evaluate the distance and check to see if it is greater or smaller than r1+r2 --- the sum of the radii of the two bounding circles. If it is smaller, then you have a potential collision at that time so you run the narrow phase algorithm.

Detect when 2 moving objects in 2d plane are close

Imagine we have a 2D sky (10000x10000 coordinates). Anywhere on this sky we can have an aircraft, identified by its position (x, y). Any aircraft can start moving to another coordinates (in straight line).
There is a single component that manages all this positioning and movement. When a aircraft wants to move, it send it a message in the form of (start_pos, speed, end_pos). How can I tell in the component, when one aircraft will move in the line of sight of another (each aircraft has this as a property as radius of sight) in order to notify it. Note that many aircrafts can be moving at the same time. Also, this algorithm is good to be effective sa it can handle ~1000 planes.
If there is some constraint, that is limiting your solution - it can probably be removed. The problem is not fixed.
Use a line to represent the flight path.
Convert each line to a rectangle embracing it. The width of the rectangle is determined by your definition of "close" (The bigger the safety distance is, the wider the rectangle should be).
For each new flight plan:
Check if the new rectangle intersects with another rectangle.
If so, calculate when will each plane reach the collision point. If the time difference is too small (and you should define too small according to the scenario), refuse the new flight plan.
If you want to deal with the temporal aspect (i.e. dealing with the fact that the aircraft move), then I think a potentially simplification is lifting the problem by the time dimension (adding one more dimension - hence, the original problem, being 2D, becomes a 3D problem).
Then, the problem becomes a matter of finding the point where a line intersects a (tilted) cylinder. Finding all possible intersections would then be n^2; not too sure if that is efficient enough.
See Wikipedia:Quadtree for a data structure that will make it easy to find which airplanes are close to a given airplane. It will save you from doing O(N^2) tests for closeness.
You have good answers, I'll comment only on one aspect and probably not correctly
you say that you aircrafts move in form (start_pos, speed, end_pos)
if all aircrafts have such, let's call them, flightplans then you should be able to calculate directly when and where they will be within certain distance from each other, or when will they be at closest point from each other or if the will collide/get too near
So, if they indeed move according to the flightplans and do not deviate from them your problem is deterministic - it boils down to solving a set of equations, which for ~1000 planes is not such a big task.
If you do need to solve these equations faster you can employ the techniques described in other answers
using efficient structures that can speedup calculating distances (quadtree, octree, kd-trees),
splitting the problem to solve the equations only for some relevant future timeslice
prioritize solving equations for pairs for which the distance changes most rapidly
Of course converting time to a third dimension turns the aircrafts from points into lines and you end up searching for the closest points between two 3d lines (here's some math)
I actually found an answer to this question.
It is in the book Real-Time Collision Detection, p. 223. It's better named, as well: Intersecting Moving Sphere Against Sphere, where a 2D sphere is a circle. It's not so simple (and I may also violate some rights) to explain it here, but the basic idea is to fix one of the circles as a point, adding its radius to the radius of the moving one. The new direction for the moving one is the sum of the two original vectors.

How do I distribute 5 points evenly onto an irregular shape?

Here is a problem I am trying to solve:
I have an irregular shape. How would I go about evenly distributing 5 points on this shape so that the distance between each point is equal to each other?
David says this is impossible, but in fact there is an answer out of left field: just put all your points on top of each other! They'll all have the same distance to all the other points: zero.
In fact, that's the only algorithm that has a solution (i.e. all pairwise distances are the same) regardless of the input shape.
I know the question asks to put the points "evenly", but since that's not formally defined, I expect that was just an attempt to explain "all pairwise distances are the same", in which case my answer is "even".
this is mathematically impossible. It will only work for a small subset of base shapes.
There are however some solutions you might try:
Analytic approach. Start with a point P0, create a sphere around P0 and intersect it with the base shape, giving you a set of curves C0. Then create another point P1 somewhere on C0. Again, create a sphere around P1 and intersect it with C0, giving you a set of points C1, your third point P2 will be one of the points in C1. And so on and so forth. This approach guarantees distance constraints, but it also heavily depends on initial conditions.
Iterative approach. Essentially form-finding. You create some points on the object and you also create springs between the ones that share a distance constraint. Then you solve the spring forces and move your points accordingly. This will most likely push them away from the base shape, so you need to pull them back onto the base shape. Repeat until your points are no longer moving or until the distance constraint has been satisfied within tolerance.
Sampling approach. Convert your base geometry into a voxel space, and start scooping out all the voxels that are too close to a newly inserted point. This makes sure you never get two points too close together, but it also suffers from tolerance (and probably performance) issues.
If you can supply more information regarding the nature of your geometry and your constraints, a more specific answer becomes possible.
For folks stumbling across here in the future, check out Lloyd's algorithm.
The only way to position 5 points equally distant from one another (other than the trivial solution of putting them through the origin) is in the 4+ dimensional space. It is mathematically impossible to have 5 equally distanced object in 3D.
Four is the most you can have in 3D and that shape is a tetrahedron.

Resources