Intersection test with kd-tree - data-structures

My current understanding of a kd-tree is; that on every node we split our points into two equally big groups for one axis.
We iterate through the individual axis until the tree is saturated.
This kind of data-structure is, of course, is interesting for raytracing applications because we don't have to search through every triangle face to test our intersection with the ray, we simply know where it would be likely that a triangle would intersect with our ray.
I have some question on how this is done.
How do we handle weird triangles where we cannot make easy splits(triangles intersecting other triangles or triangles which span the entire?
Do we even split on the triangles or do we split on the vertices?
How exactly do we test for an intersection of a ray that we send out from the camera ?
I see a couple of methods. First, we could build bounding boxes from our scene and the splitting planes and test for intersection with those boxes or we could test for intersection with the splitting planes and see where the intersection is relative to the camera

The short answer is: This all depends on your application. There are several variations of kd-trees.
How do we handle weird triangles where we cannot make easy splits?
I believe you are referring to the choice of the splitting plane for a given set of triangles. This is a pretty hard optimization problem, which is usually solved with a heuristic. E.g., you could sort the centroids of triangles along one axis and choose the median as the splitting plane. Nothing is stopping you from implementing some more intelligent criterion.
If you find that your splitting plane passes through a primitive, you have two options. Either split the primitive or add it to both subtrees. What you should do depends on your application.
Do we even split on the triangles or do we split on the vertices?
That depends on the primitives you want to add to your tree. If you want to use the tree for raycasting, then it makes sense to have the triangles in the tree. kd-trees are a very general concept that works with any kind of primitives, though. E.g., they are also widely used for point clouds.
How exactly do we test for an intersection of a ray that we send out from the camera?
You do this by traversing the tree. So, you start at the root node and check if the ray intersects with the associated bounding box (which is the entire space). Then you check which of the two subtrees are first intersected by the ray and continue to this one. And then you repeat: You test for intersection with the node's AABB (which you build incrementally from the splitting planes). If the ray does not intersect the AABB, then immediately return back to the parent node. If it does, continue to the first child. When you come back from the first child, go to the second child (unless you already found an intersection).
For some more details, I would advice to take a look at application-specific instances of kd-trees.

Related

Drawing no intersected polygon with dragging vertexes

I'm trying to draw a polygon without intersecting.
Below is good example which I want to.
Bad example what I want to prevent.
If I choose red dot one, then what algorithm I can apply to prevent the intersecting sides of the polygon?
Technical answer:
The moving point must belong to the visibility zones of its two neighbors (ignoring the two adjoining edges).
You can construct these two zones and their intersection once for all, then constrain the cursor to remain in the intersection. This can be made efficiently in time O(Log(N)) per query, after some preprocessing. But this is quite complex and not worth the effort.
Practical answer:
Simply check that the two edges from the moving point do not intersect the remaining edges.

Point of intersection between Oriented Boxes (or OBB)

I am trying to write a Rigid body simulator, and during simulation, I am not only interested in finding whether two objects collide or not, but also the point as well as normal of collision. I have found lots of resources which actually says whether two OBB are colliding or not using separating axis theorem. Also I am interested in 3D representation of OBB. Now, if I know the axis with minimum overlap region for two colliding OBB, is there any way to find the point of collision and normal of collision? Also, there are two major cases of collision, first, point-face and second edge-edge.
I tried to google this problem, but almost every solution is only detecting collision with true or false.
Kindly somebody help!
Look at the scene in the direction of the motion (in other terms, apply a change of coordinates such that this direction becomes vertical, and drop the altitude). You get a 2D figure.
Considering the faces of the two boxes that face each other, you will see two hexagons each split in three parallelograms.
Then
Detect the intersections between the edges in 2D. From the section ratios along the edges, you can determine the actual z distances.
For all vertices, determine the face they fall on in the other box; and from the 3D equations, the piercing point of the viewing line into the face plane, hence the distance. (Repeat this for the vertices of A and B.)
Comparing the distances will tell you which collision happens first and give you the coordinates of the first meeting point (in the transformed system, the back to absolute coordinates).
The point-in-face problem is easy to implement as the facesare convex polygons.

Algorithm for finding triangles within a region

I am working on small project that requires me to quickly find which triangles within a set of triangles is either partially or entirely contained within a given rectangular region. I am interested in optimizing for fast searches - I am not memory limited.
This is not an area I am too familiar with, so all I've been able to do thus far is to poke around on Google for standard algorithms for dealing with this problem. The closest I've gotten to so far is to use two interval trees. This is a bit clumsy, since I have to perform a test for interval overlap between the edges of each triangle and the edges of the rectangular region in both directions x and y.
Can someone point me to any resource where the 'correct' way of dealing with this problem is?
Thanks!
Edit: I forgot to mention that the rectangular regions I am currently using are parallel to the coordinate axes x and y. For the time being, I am happy with any solution that exploits this constraint. Generally, though, a solution with completely arbitrary rectangles would be great to know about.
You can use an AABBTree (AABB stands for Axis Aligned Bounding Box tree), the
idea is to enclose each triangle in its axis aligned bounding box, then build a tree that has the initial triangles as leafs, and where upper nodes have a bounding box that is the union of the bounding boxes of its children. Then when searching which triangles have a non-empty intersection with "something", you check whether the "something" has an intersection with the bounding box of a node, and go down the tree to test its children when it's the case (recursive function).
You can find efficient implementations of AABBTrees in:
CGAL: http://doc.cgal.org/latest/AABB_tree/
the GEOGRAM library that I am writing: http://alice.loria.fr/software/geogram/doc/html/classGEO_1_1MeshFacetsAABB.html
OpCode: http://www.codercorner.com/Opcode.htm
Assuming the rectangle is axis aligned, I'd do this:
Compare the bounding box of a triangle to the region. If it is inside, the triangle is inside. If there is no overlap at all, it's not. Use an interval tree for each dimension for this step if you need to check the same set of triangles with different regions.
We have checked the two simple cases in step one, so we know the region and bounding box overlap. Check if any of the points of the triangle is inside the rectangle. If so, the triangle is inside.
Check the four sides of the rectangle with the three sides of the triangle for line segment intersections
If no preprocessing of the set of triangles is allowed, there is nothing better you can do than comparing exhaustively every triangle to the window.
To solve the triangle/rectangle overlap problem easily (or just to reason about it), you can form the Minkowski sum of the two polygons, to turn the problem in a "point-in-convex-polygon" instance.
Of course, an initial axis-aligned bounding box test is welcome.
If your window is a rotated rectangle, you can "unrotate" the whole scene to make the window axis-aligned and revert to the first problem.

How to find if a 3D object fits in another 3D object (the container)?

Given two 3d objects, how can I find if one fits inside the second (and find the location of the object in the container).
The object should be translated and rotated to fit the container - but not modified otherwise.
Additional complications:
The same situation - but look for the best fit solution, even if it's not a proper match (minimize the volume of the object that doesn't fit in the container)
Support for elastic objects - find the best fit while minimizing the "distortion" in the objects
This is a pretty general question - and I don't expect a complete solution.
Any pointers to relevant papers \ articles \ libraries \ tools would be useful
Here is one perhaps less than ideal method.
You could try fixing the position (in 3D space) of 1 shape. Placing the other shape on top of that shape. Then create links that connect one point in shape to a point in the other shape. Then simulate what happens when the links are pulled equally tight. Causing the point that isn't fixed to rotate and translate until it's stable.
If the fit is loose enough, you could use only 3 links (the bare minimum number of links for 3D) and try every possible combination. However, for tighter fit fits, you'll need more links, perhaps enough to place them on every point of the shape with the least number of points. Which means you'll some method to determine how to place the links, which is not trivial.
This seems like quite hard problem. Probable approach is to have some heuristic to suggest transformation and than check is it good one. If transformation moves object only slightly out of interior (e.g. on one part) than make slightly adjust to transformation and test it. If object is 'lot' out (e.g. on same/all axis on both sides) than make new heuristic guess.
Just an general idea for a heuristic. Make a rasterisation of an objects with same pixel size. It can be octree of an object volume. Make connectivity graph between pixels. Check subgraph isomorphism between graphs. If there is a subgraph than that position is for a testing.
This approach also supports 90deg rotation(s).
Some tests can be done even on graphs. If all volume neighbours of a subgraph are in larger graph, than object is in.
In general this is 'refined' boundary box approach.
Another solution is to project equal number of points on both objects and do a least squares best fit on the point sets. The point sets probably will not be ordered the same so iterating between the least squares best fit and a reordering of points so that the points on both objects are close to same order. The equation development for this is a lot of algebra but not conceptually complicated.
Consider one polygon(triangle) in the target object. For this polygon, find the equivalent polygon in the other geometry (source), ie. the length of the sides, angle between the edges, area should all be the same. If there's just one match, find the rigid transform matrix, that alters the vertices that way : X' = M*X. Since X' AND X are known for all the points on the matched polygons, this should be doable with linear algebra.
If you want a one-one mapping between the vertices of the polygon, traverse the edges of the polygons in the same order, and make a lookup table that maps each vertex one one poly to a vertex in another. If you have a half edge data structure of your 3d object that'll simplify this process a great deal.
If you find more than one matching polygon, traverse the source polygon from both the points, and keep matching their neighbouring polygons with the target polygons. Continue until one of them breaks, after which you can do the same steps as the one-match version.
There're more serious solutions that're listed here, but I think the method above will work as well.
What a juicy problem !. As is typical in computational geometry this problem
can be very complicated with a mismatched geometric abstraction. With all kinds of if-else cases etc.
But pick the right abstraction and the solution becomes trivial with few sub-cases.
Compute the Distance Transform of your shapes and VoilĂ ! Your solution is trivial.
Allow me to elaborate.
The distance map of a shape on a grid (pixels) encodes the distance of the closest point on the
shape's border to that pixel. It can be computed in both directions outwards or inwards into the shape.
In this problem, the outward distance map suffices.
Step 1: Compute the distance map of both shapes D_S1, D_S2
Step 2: Subtract the distance maps. Diff = D_S1-D_S2
Step 3: if Diff has only positive values. Then your shapes can be contained in each other(+ve => S1 bigger than S2 -ve => S2 bigger than S1)
If the Diff has both positive and negative values, the shapes intersect.
There you have it. Enjoy !

Locating Bounding 2D Entities

Given a point and a set of arbitrary 2D entities (circles, polygons, lines, polylines, arcs, etc.), does anyone know of existing strategies to:
Determine if the point is enclosed (bounded) by any combination of entities? I know that it is easy enough to do an 'inside' test on the closed shapes, but this won't always give me what I want - particularly with nested or intersecting shapes.
Find the smallest (closest?) set of lines / entities that form a closed polygon around my point? (think of a flood-fill, but without relying on colour)
I've addressed this problem in a commercial product in the past. You've asked about analytic curves, but I'll address it more generally for curves that are at least twice differentiable. Handle polygons as a set of separate line segments. There is no need to segment the curves, but if you want to you can and adapt the algorithm slightly.
Also, you might want to see my paper Matrix-Based Ellipse Geometry in Graphics Gems V to find the intersections between your ellipses.
Basic idea:
Consider a ray from your test point in the +x direction.
Now consider an ant walking along your ray from the test point.
When the ant hits the first intersection with one of the curves, it makes the sharpest left it can, and leaves an arrow at that intersection indicating the direction it's chosen. (If there is no intersection, then obviously the point isn't bounded.)
If it comes to the end of a curve, it doubles back on itself.
If there are multiple curves intersecting at that point, it chooses the curve that is most to the left.
If one or more of the curves is in fact tangent to the ray at the intersection, higher derivatives can be used decide which curve and direction to choose. (This ant knows calculus.)
Now as the ant strolls along the curves, it always makes the biggest left turn it can as above. If there is tangency between curves at the intersection, use higher derivatives to decide the one that is "most to the left". (Details are left to the ant).
In its travels, the ant may come to the starting intersection with the ray multiple times. But as soon as it finds itself proceeding in the direction of the arrow (the one it left in step 3), it's travels are done and it has traversed a "contour". The problem is reduced to deciding if the point is in that contour.
A "contour" is a topological entity. It's closed ring of "segments" connected at "vertices".
A "segment" is a piece of a curve used by the contour in a particular direction.
A "vertex" is a connection between segments. A vertex is associated with a (x, y) position on the plane, but there may be multiple vertices at the same position, one for each pair of segments in the contour that meet at that point. There is a vertex for each curve endpoint (a spur vertex), or curve-curve intersection encountered by the ant.
A contour (in this context) is not a geometric entity! Don't think of it as a simple closed path on the plane. The ant might go along a segment, get to the end, and go back the way it came--this is called a "spur" and includes two contour segments, one for either direction. Or it might go along one direction of a curve segment, wander around a bit along other curves, and return along the other direction of the segment.
So even if your set of curves has only one line in it from A to B (I'm assuming you don't have infinite lines) and your ray hits it at P, you still have the contour V0(P)-V1(A)-V2(P)-V3(B)-V0 with 4 segments V0-V1, V1-V2, V2-V3, V3-V0. Note that V0 and V2 are distinct vertices, both positioned at P.
Now to test if your point is in the contour.
Find the intersections of your ray (any ray originating at your test point will do) with the contour. We only really want the parity (even or odd) of the number of intersections with the contour. If the parity is odd, the point is bounded by the curves, if it's even it's not.
Because doubly traversed segments contribute nothing to the parity, we can ignore them. This is because there are always an even number of intersections on doubly traversed segments, since they're in the contour twice.
Examples:
Consider this curve set. I use lines so I don't work too hard:
Case 1 - The point is not bounded. The contour's use of the curve segments is indicated by the dotted arrows. The number of ray-contour intersection parity is even.
Case 2 - The point is bounded. The ray-contour intersection parity is odd.
Here's what can go wrong:
You can't find a contour for various numerical reasons. For example, you might miss intersections, e.g. two curves are almost tangent at a curve. You might see it as a single intersection, but when you do the ray intersection parity test you see a single crossing so that the parity flips when it shouldn't.
You might not be able to compute enough derivatives to make the correct turn decisions. In the case of analytic geometry this should never be the case.
Your ray hits a vertex (connections between segments) of your contour. (Note that there can be multiple vertices at a single (x, y) point. Each of these has to be handled separately.)
In this case, you have to decide if the incoming and outgoing segments of the vertex are on the same side of the ray at the vertex. If they're on the same side, the parity is not affected. Otherwise the parity flips. If one of the curves is tangent to the ray at the vertex, you may have to use higher derivatives to decide this.
A line segment is collinear with your test ray. This is actually a special case of 2, but easy to handle: Ignore it.
There are lots of details, but you should be able to handle them. Be sure to use spatial trees to avoid computing unnecessary intersections.
The answer to your second question comes from removing from the contour any doubly traversed segments. This may yield multiple sub-contours. One of them will contain your point.

Resources