Collision test between a triangle and a rectangle (AABB) in 2D - geometry

I've spent a good amount of time getting intersections working correctly between various 2D shapes (circle-circle, circle-tri, circle-rect, rect-rect - a huge thanks to those who've solved such problems from which I drew my solutions from) for a simple project and am now in the process of trying to implement an triangle-AABB intersection test.
I'm a bit stuck however. I've tried searching online and thinking it through however I've been unable to get any ideas. The thing that's given me the biggest issue at the moment is checking whether the edges of triangle (which is an isosceles btw) intersect the rectangle when no vertexes lie within the rectangle.
Any ideas how I could get this working?
EDIT: To give a bit more insight as to stages as I think they should occur:
1 - Check to see if any vertexes lie with in the rectangle (this part is easy). If yes, collision, otherwise continue.
2 - Check to see if any edges are intersecting the rectangle. This is where I'm stuck. I have little idea how to implement this.

I'd calculate a collection of equations which define the 4 lines of the rectangle, and then solve against a collection of equations which define lines of the triangle.
For example, gievn a rectangle with lowest point (x1, y1) and one side having a gradient of g, one of the lines of the rectangle will be y = gx + y1. Find equations to represent the other 3 sides of the rectangle as well.
The lines which form the sides of the triangle will be calculated similarly. The equation for a line given two points is
y - y1 = (x - x1) * (y2 - y1)/(x2 - x1)
If there are any possible x & y values that satisy all 7 equations then you have an intersection.
edit: I realise that although this is a simple algorithm it might be tricky to code; another option is to calculate formulae for the intervals that form each edge (essentially lines with a min and max value) and solve these.

Related

Circle triangulation

I am currently experimenting with openGL, and I'm drawing a lot of circles that I have to break down to triangles (triangulate a circle).
I've been calculating the vertices of the triangles by having an angle that is incremented, and using cos() and sin() to get the x and y values for one vertex.
I searched a bit on the internet about the best and most efficient way of doing this, and even though there's not much information avaliable realized that thin and long triangles (my approach) are not very good. A better approach would be to start with an equilateral triangle and then repeatedly add triangles that cover the larges possible area that's not yet covered.
left - my method; right - new method
I am wondering if this is the most efficient way of doing this, and if yes, how would that be implemented in actual code.
The website where I found the method: link
both triangulations has their pros and cons
The Triangle FAN has equal sized triangles which sometimes looks better with textures (and other interpolated stuff) and the code to generate is simple for loop with parametric circle equation.
The increasing detail mesh has less triangles and can easily support LOD which might be faster. However number of points is not arbitrary (3,6,12,24,48,...). The code is slightly more complicated you could:
start with equilateral triangle remembering circumference edges
so add triangle (p0,p1,p2) to mesh and edges (p0,p1),(p1,p2),(p2,p0) to circumference.
for each edge (p0,p1) of circumference
compute:
p2 = 0.5*(p0+p1); // mid point
p2 = r*p2/|p2|; // normalize it to circle circumference assuming (0,0) is center
add triangle (p0,p1,p2) to mesh and replace p0,p1 edge with (p0,p2),(p2,p1) edges
note that r/|p2| will be the same for all edges in current detail level so no need to compute expensive |p2| over and over again.
goto #2 until you have enough dense triangulation
so 2 for loops and few dynamic lists (points,triangles,circumference_edges,and some temps if not doing this inplace). Also this method does not need goniometrics at all (can be modified to generate the triangle fan too).
Here similar stuff:
sphere triangulation using similar technique

In geometry nodes how can I align instances to both a curve and ground plane?

Given this simple setup:
Node Tree
Viewport Preview
How can I align the planes instances such that the y axis of each plane is parallel to the curve, and the x axis of the planes are parallel to the ground plane (x and Y axis)?
I've tried various combinations with "Align Eular to Vector" node, but as soon as the curve does not face a specific axis the planes get tilted and the alignment to ground plane is lost.
any suggestions?
So after some research I found a solution to my own question. I'm posting it in case anyone else needs to find this out.
Note that I'm not a mathematician and there might be a shorter solution (or specific nodes that I'm not aware of that can perform some of the steps). Also note that this is a solution for instances on a straight line which is what I was aiming for, I didn't test this setup on a curved line but my guess is that it will not work.
For that you'll need to perform step 3 for every point or something like that.
Ok here we go:
Generate instances on a line with the instance on point node.
Auto orient the instances on the z axis with the align Euler to vector node based on the normal of the line.
Calculate a vector between 2 points on the line (which point is not important since the line is straight but the order of the subtraction does!). To calculate the vector from point 1 to point 2 you'll have to subtract point 1 from point 2 (like so: point 2 - point 1).
Calculate the angle between the new vector and the vector of the ground plane [0,0,1]. to do that use this formula:
θ = arccosine ( dot product/ ( length(v1) * length(v2) ) ).
Calculate the complementary angle which is 90 degrees - θ
*** convert 90 to radians of course
rotate the instances on x axis by the result value.
Node Tree
Result
If there is a shorter/easier solution, let me know.

Calculate equidistant point with minimal distance from 3 points in N-dimensional space

I'm trying to code the Ritter's bounding sphere algorithm in arbitrary dimensions, and I'm stuck on the part of creating a sphere which would have 3 given points on it's edge, or in other words, a sphere which would be defined by 3 points in N-dimensional space.
That sphere's center would be the minimal-distance equidistant point from the (defining) 3 points.
I know how to solve it in 2-D (circumcenter of a triangle defined by 3 points), and I've seen some vector calculations for 3D, but I don't know what the best method would be for N-D, and if it's even possible.
(I'd also appreciate any other advice about the smallest bounding sphere calculations in ND, in case I'm going in the wrong direction.)
so if I get it right:
Wanted point p is intersection between 3 hyper-spheres of the same radius r where the centers of hyper-spheres are your points p0,p1,p2 and radius r is minimum of all possible solutions. In n-D is arbitrary point defined as (x1,x2,x3,...xn)
so solve following equations:
|p-p0|=r
|p-p1|=r
|p-p2|=r
where p,r are unknowns and p0,p1,p2 are knowns. This lead to 3*n equations and n+1 unknowns. So get all the nonzero r solutions and select the minimal. To compute correctly chose some non trivial equation (0=r) from each sphere to form system of n+1 =equations and n+1 unknowns and solve it.
[notes]
To ease up the processing you can have your equations in this form:
(p.xi-p0.xi)^2=r^2
and use sqrt(r^2) only after solution is found (ignoring negative radius).
there is also another simpler approach possible:
You can compute the plane in which the points p0,p1,p2 lies so just find u,v coordinates of these points inside this plane. Then solve your problem in 2D on (u,v) coordinates and after that convert found solution form (u,v) back to your n-D space.
n=(p1-p0)x(p2-p0); // x is cross product
u=(p1-p0); u/=|u|;
v=u x n; v/=|v|; // x is cross product
if memory of mine serves me well then conversion n-D -> u,v is done like this:
P0=(0,0);
P1=(|p1-p0|,0);
P2=(dot(p2-p0,u),dot(p2-p0,v));
where P0,P1,P2 are 2D points in (u,v) coordinate system of the plane corresponding to points p0,p1,p2 in n-D space.
conversion back is done like this:
p=(P.u*u)+(P.v*v);
My Bounding Sphere algorithm only calculates a near-optimal sphere, in 3 dimensions.
Fischer has an exact, minimal bounding hyper-sphere (N dimensions.) See his paper: http://people.inf.ethz.ch/gaertner/texts/own_work/seb.pdf.
His (C++/Java)code: https://github.com/hbf/miniball.
Jack Ritter
jack#houseofwords.com

How to tell if two rings (circles in 3d) are linked

I have two rings in 3 space each represented by a normal vector, center coordinate, and a radius.
How can I determine if the rings are linked. I.e. a point on one circle lies in the other disk.
This will be implemented in a tight loop so I am concerned about performance. I feel like there should be a closed form solution. So far I've only thought iterative solutions.
Any help?
Outline of the algorithm:
Handle the cases where the planes of the circles are parallel or concurrent.
Find the line of intersection of the planes of the circles.
Find the intersections of the circles with this line.
All the circle intersections with the line are on both planes. We can now do distance checks to see if the circles are linked.
Details:
I'll assume that the circles C1 and C2 are given by a center point (p1, p2), unit normal axis vector (n1, n2) and radii (r1, r2).
If n1 == k n2 for some scalar k, then the planes are parallel or concurrent. If they're concurrent this becomes the trivial 2d problem: check whether dist(p1, p2) < r1+r2.
Otherwise, the planes intersect at a line L. If the circles are linked, then they must both intersect L since linking implies that they mutually pass through each other's plane of definition. This gives you your first trivial rejection test.
L is given by a point q and a vector v. Finding v is easy: It's just the cross product of n1 and n2. q is a little trickier, but we can choose a point of nearest approach of the lines
l1(s) = p1 + s (v X n1)
l2(t) = p2 + t (v X n2)
These lines are perpendicular to v, n1 and n2, and are on the planes of C1 and C2. Their points of nearest approach must be on L.
You can refer to this post to see how to find the points of nearest approach.
Finally, the only way the circles can intersect is if they both have points on L. If they do, then consider the intersection points of C1 and L as they relate to C2. The circles are linked if there are two intersection points q11 and q12 of C1 and L and exactly one of them are inside of C2. Since L is on the plane of C2, this becomes a planar point-in-circle test:
IF dist(p1, q11) < r1 THEN
linked = (dist(p1, q12) > r1)
ELSE
linked = (dist(p1, q11) < r1)
ENDIF
Of course this pseudo-code is a little sloppy about handling the case that the circles actually intersect, but how that should be handled depends on your application.
A straightforward solution that is relatively easy to code: compute the line of intersection of the two planes and rotate and translate everything (in my case the six points defining the two circles) together so that the line becomes the Z axis (x=y=0). Then the planes can be rotated separately around Z so that the first circle, C1, lies on the XZ plane and C2 lies on the YZ plane. Now the centers and radii are easy to find (in my situation I don't initially have them). These rotations do not change the link/no link property and the link or lack of it can be easily determined from the order of the four intersections of the circles with the Z axis. (If either of the circles does not intersect x=y=0, there is no link.) (I may have confused the axes but I think this will work.)
Thank you.
Is this the 3D circle-disk intersection problem? Or, is it the circle-circle intersection problem?
If it's the former, there is a fast, closed form algorithm. First, weed out the circles-too-distant case: dist(CIR1.c, CIR2.c) > CIR1.r + CIR2.r
Handle the edge case: coplanar circles.
Extrude the disk into its plane, then intersect the circle with this plane. If there are 1 or 2 intersection points, test to see if they meet pointInDisk(p, CIR) logic. Report out any surviving intersection points.
A computational geometry textbook might have a good solution!
But I don't have a computation geometry textbook handy at the moment. If I were going to roll my own right now, based on my own (very limited) intuition, I think I'd start with 3d axis-aligned bounding boxes.
e.g., create an "just inside the circle" bounding box, as well as a "just outside the circle" bounding box. I believe it's trivial to figure out if two axis-aligned boxes overlap (section 2.1 of a homework assignment I once did talks about a related problem in the 2D situation --- finding the nearest rectangle to a point: http://juliusdavies.ca/uvic/report.html ).
I suspect the following assertions would hold (but I could be wrong):
If the inner-boxes overlap, then the rings are definitely connected. (I now think this is wrong...)
If the outer-boxes DO NOT overlap, then they are definitely not connected --- I am very confident this assertion holds! :-) :-)
If the outer-boxes overlap, but the inner-boxes do not, then they might be connected.
That's where I'd start, if I were rolling my own.
Conclusion: uhhh, I hope you have better luck with the other answers. :-)

Algorithm for Polygon Image Fill

I want an efficient algorithm to fill polygon with an Image, I want to fill an Image into Trapezoid. currently I am doing it in two steps
1) First Perform StretchBlt on Image,
2) Perform Column by Column vertical StretchBlt,
Is there any better method to implement this? Is there any Generic and Fast algorithm which can fill any polygon?
Thanks,
Sunny
I can't help you with the distortion part, but filling polygons is pretty simple, especially if they are convex.
For each Y scan line have a table indexed by Y, containing a minX and maxX.
For each edge, run a DDA line-drawing algorithm, and use it to fill in the table entries.
For each Y line, now you have a minX and maxX, so you can just fill that segment of the scan line.
The hard part is a mental trick - do not think of coordinates as specifying pixels. Think of coordinates as lying between the pixels. In other words, if you have a rectangle going from point 0,0 to point 2,2, it should light up 4 pixels, not 9. Most problems with polygon-filling revolve around this issue.
ADDED: OK, it sounds like what you're really asking is how to stretch the image to a non-rectangular shape (but trapezoidal). I would do it in terms of parameters s and t, going from 0 to 1. In other words, a location in the original rectangle is (x + w0*s, y + h0*t). Then define a function such that s and t also map to positions in the trapezoid, such as ((x+t*a) + w0*s*(t-1) + w1*s*t, y + h1*t). This defines a coordinate mapping between the two shapes. Then just scan x and y, converting to s and t, and mapping points from one to the other. You probably want to have a little smoothing filter rather than a direct copy.
ADDED to try to give a better explanation:
I'm supposing both your rectangle and trapezoid have top and bottom edges parallel with the X axis. The lower-left corner of the rectangle is <x0,y0>, and the lower-left corner of the trapezoid is <x1,y1>. I assume the rectangle's width and height are <w,h>.
For the trapezoid, I assume it has height h1, and that it's lower width is w0, while it's upper width is w1. I assume it's left edge "slants" by a distance a, so that the position of its upper-left corner is <x1+a, y1+h1>. Now suppose you iterate <x,y> over the rectangle. At each point, compute s = (x-x0)/w, and t = (y-y0)/h, which are both in the range 0 to 1. (I'll let you figure out how to do that without using floating point.) Then convert that to a coordinate in the trapezoid, as xt = ((x1 + t*a) + s*(w0*(1-t) + w1*t)), and yt = y1 + h1*t. Then <xt,yt> is the point in the trapezoid corresponding to <x,y> in the rectangle. Now I'll let you figure out how to do the copying :-) Good luck.
P.S. And please don't forget - coordinates fall between pixels, not on them.
Would it be feasible to sidestep the problem and use OpenGL to do this for you? OpenGL can render to memory contexts and if you can take advantage of any hardware acceleration by doing this that'll completely dwarf any code tweaks you can make on the CPU (although on some older cards memory context rendering may not be able to take advantage of the hardware).
If you want to do this completely in software MESA may be an option.

Resources