How to find line segments intersecting a 2D viewport - geometry

In an infinite 2D space there are a set of lines, each line having a start and end point, and a time of creation: Line(p0, p1, t).
I want to find the lines that should be rendered in a top-down view of this 2D space (higher values of t show up closer to the viewport, not that it should be relevant.)
The intuitive answer is "check if either point is within the viewport coordinates," but this falls down when the points are further apart than the viewport area covers.
The other idea I had was using something like geohash, this would limit precision i.e. maximum zoom level of the viewport. The idea is enumerating the hashes of the cells intersected and storing them. This way querying is a matter of asking the right question.
Are there any ideal solutions? Has this been solved before?

I think you need to check two conditions: one that the rectangle of viewport overlaps the rectangle with corners (p0,p1) and the second that some corners of viewport rectangle are on the different sides of the whole line which contains line segment (p0,p1).
The task of finding rectangle overlap can be solved very effectively for very large number of rectangles using R-trees (http://en.wikipedia.org/wiki/R-tree).
The second task can be reduced to checking signs of the cross product of (p1-p0) x (corner_coordinate-p0)
(all three quantities taken as 3-d vectors with third coordinate equal to zero, the result will be vector along the perpendicular direction). There should be corners with the opposite sign of this cross product.

Related

Is there a simple algorithm that can find the envelope of several circles?

Given a number of points on a 2d surface and radiuses for these points I can easily paint circles for them. What I need is an algorithm that only paints the envelope (right word for what I am looking for?) or outer bound of these combined circles. Additionally a second set of circles can 'encroach' on these circles, resulting in a kind of 'border'.
Image of what I am looking for
A quick way to draw the outline of the union of the disks is to
fill all disks in yellow, then
fill all disks in white with a smaller radius.
This can be adapted to the "encroached" circles, provided you only fill the remaining portions of the disks. Unfortunately, in a general setting finding the remaining portions can be an uneasy geometric problem.
There is an alternative approach which can work in all cases:
fill an image with zeroes, then for all disks fill every pixel with the value of the distance to the circumference (maximum at the center), but only keep the highest value so far.
while you do this, fill a second image with the color of the disk that achieved that highest value. (Initialize the image with the background color.)
At the end of this process, the first image will represent a "terrain" made of intersecting cones; and for every point of the terrain, you will know the color.
finally, color the pixels that have a height smaller than the desired stroke width, using the color map.
You can do the drawing in two steps.
1) Draw the outline using the following method: For each point, draw a circle using your favorite circle-drawing method, but before drawing a pixel, ensure that it is not contained inside any other circle. Do this for every point and you will get your outline.
2) Draw the borders between different sets using the following method: For each pair of points from different sets, calculate the two intersection points of the circles. If there is an intersection, the border can be drawn as a segment joining these two points. However, you have to make two lines, one for circle A, and another for circle B. To draw the line for circle A, slightly offset the segment towards point A. Then, use your favorite line-drawing method, but before drawing a pixel, ensure that it is closer to point A that any other point of the opposite set. After drawing the line, repeat the process for circle B. Note that both segment are not guaranteed to be the same length since the asymmetry of the points of the different sets. It will, however, always form a closed shape when all outlines and borders are drawn.

Non ordered triangle rasterisation

I'm doing a triangle rasteriser and it all works but now I want to use parallel computing to draw a bunch of triangles.
This means that the triangles can be drawn in any random order each frame, the problem is this disordered drawing is causing artifacts.
As a test case, let's consider two triangles that share two vertices, like so:
If we look at a grid of pixels the vertices will look like this:
The filling convention I'm using is just ceil()
So if we draw the blue triangle it will look like this
The problem that now becomes apparent is that if we now draw the yellow triangle, because they share the two vertices, the yellow triangle will be drawn over the blue one:
This isn't a problem on it's own, the problem is IF we draw them in the reverse order (yellow first, blue second) then the blue one will be drawn over instead:
This causes obvious artifacts because in any frame the order can be random so you will see a flickering line as one triangle is drawn over another and vise versa.
Is there any thing that can be done to ensure that the final image will look identical no matter the order the triangles are drawn in?
Always truncate to integer device pixels, and always do it the same way. This could be floor or ceiling or even rounding (if your sure both triangles get numerically identical inputs then they should round the same).
And define the boundaries of the triangle to include the lowest endpoint but exclude the highest, ie., min(x0,x1) <= x < max(x0,x1) and similarly for the y range.

fast calculation of the intersection area of a triangle and the unit square

In my current project I need to calculate the intersection area of triangles and the unit squares in an infinite grid.
For every triangle (given by three pairs of floating point numbers) I need to know the area (in the interval (0,1]) it has in common with every square it intersects.
Right now I convert both (the triangle and the square) to polygons and use Sutherland-Hodgman polygon clipping to calculate the intersection polygon, which I then use to calculate its area.
This approach now shows to be a performance bottleneck in my application. I guess a more specialized (analytical) algorithm would be much faster. Is there a standard solution for this problem, or do you have any idea? I only need the areas, not the shape of the intersections.
Your polygon are convex. There are some algorithms for convex polygons faster than general ones. I've used O'Rourke algorithm with success (code from his book here, I believe that good description exists). Note that some values may be precomputed for your squares.
If your polygons not always intersect, then you may at first check the fact of intersection with separating axes method.
Another option to try- Liang-Barski algorithm for clipping every triangle edge by square.
Edit: You can quickly find all intersections of triangle edges with grid using algorthm of Amanatides and Woo (example in grid traversal section here)
To process this task with hi performance , i suggest some modifications of
Vatti line sweep clipping.
http://en.wikipedia.org/wiki/Vatti_clipping_algorithm
Stepping from minimal Y vertex of your Triangle make such steps:
sort vertexes by Y coordinate
step Y higher to MIN(nextVertex.Y, nextGridBottom)
Calculate points of intersection of grid with edges.
Collect current trapezoid
repeat from step2 until vertex with highest Y coordinate.
Split trapezoids by X coordinate if required.
here is example of Trapezoidalization in X direction
http://www.personal.kent.edu/~rmuhamma/Compgeometry/MyCG/PolyPart/polyPartition.htm
It illustrate main idea of line sweep algorithm. Good luck.
You are not mentioning what precision you are looking for. In case you are looking for a analytical method, disregard this answer, but if you just want to do antialiasing I suggest a scanline edge-flag algorithm by Kiia Kallio. I have used it a few times and it is quite fast and can be set up for very high precision. I have a java implementation if you are interested.
You can take advantage of the regular pattern of squares.
I'm assuming the reason this is a bottleneck is because you have to wait while your algorithm finds all squares intersecting any of the triangles and computes all the areas of intersection. So we'll compute all the areas, but in batches for each triangle in order to get the most information from the fewest calculations.
First, as explained by others, for each edge of the triangle, you can find the sequence of squares that edge passes through, as well as the points at which it crosses each vertical or horizontal edge of a square.
Do this for all three sides, keeping a list of all the squares you encounter, but keep only one copy of each square. It may be useful to store the squares in multiple lists, so that all squares on a given row are all kept in the same list.
When you've found all squares the triangle's edges pass through, if two of those squares were on the same row, any squares between those two that are not in the list are completely inside the triangle, so 100% of each of those squares is covered.
For the other squares, the calculation of area can depend on how many vertices of the triangle are in the square (0, 1, 2, or 3) and where the edges of the triangle intersect the sides of the square. You can summarize all the cases in a few pencil-and-paper drawings, and come up with calculations for each one. For example, when an edge of triangle crosses two sides of the square, with one corner of the square on the "outside" side of the edge, that corner is one angle of a small triangle "cut off" by that edge of the larger triangle; use the points of intersection on the square's sides to compute the area of the small triangle and deduct it from the area of the square. If two points instead of one are "outside", you have a trapezoid whose two base lengths are found from the points of intersection, and whose height is the width of the square; deduct its area from the square. If three points are outside, deduct the entire area of the square and then add the area of the small triangle.
One vertex of the large triangle inside the square, three corners of the square outside that angle: draw a line from the remaining corner to the triangle's vertex, so you have two small triangles, deduct the entire square and add those triangles' areas. Two corners of the square outside the angle, draw lines to the vertex to get three small triangles, etc.
I'm phrasing this so that you always assume you start with the entire area of the square and reduce the area by some amount depending on how the edge of the triangle intersects the square. That way, in the case where the edges of the triangle intersect the square more than twice--such as one edge cuts across one corner of the square and another edge cuts across a different corner, you can just deduct the area cut off by the first edge, then deduct the area cut off by the second edge.
This will be a considerable number of special cases, though you can take advantage of symmetry; for example, you don't have to write the complete calculation for "cut off a triangle in one corner" four times.
You'll write a lot more code than if you just took someone's convex-polygon library off the shelf, and you will want to test the living daylights out of it to make sure you didn't forget to code any cases, but once you get it working, it shouldn't take much more effort to make it reasonably fast.

largest empty sphere or rectangle

In N (~ 500) dimensions, I wish to find out the largest sphere or rectangle such that the sphere/rectangle does not contain already existing points. The entire set of points is bounded in an axis-aligned rectangular box (lower and upper bounds on the values).
Is there any known polynomial time method/code that I can use to solve my problem?
The two well known algorithms: i) the largest empty rectangle within a rectangle (http://www.cs.princeton.edu/~chazelle/pubs/ComputLargestEmptyRectangle.pdf) and, ii) finding largest empty circle within location constraints (http://www.cs.dartmouth.edu/reports/TR86-130.pdf) do not work.
Although the complexity of above algorithms is N log N or N^2 log N, where N is the number of already existing points, the complexity is also a linear function of the number of vertices of the convex hull or the bounding polygon. A rectangle in 500 dimensions will have 2^500 corners which makes the above techniques infeasible.
Ideally, I am looking for a method (it does not have to be exact) that can determine the largest cirle/rectangle in polynomial time in N (number of points) and D (the dimension).
Thank you.
One possible heuristic solution is to restrict the large rectangle so that it's axis-aligned. In this case, a rectangle can be bounded by at most 2 * d points, where each point represents a bounding min or max to one or more dimensions. It can be then be determined if a point is inside that rectangle in only O(d).
A heuristic method to make use of this is to pick 2 points, and use those to form an initial bounding box, then randomly add points. If the point is inside the box, shrink or split the box. If the point is outside of the box, try to make the box bigger. A single pass should take O(d * N) if the box is shrunk instead of split.
The quality perhaps can be improved a bit by ensuring that no point is within the bounding box formed by the two points. It might be ideal to find all pairs of points such that no point is within the bounding box, as when converted to a graph, they should help with expanding the solution in a less random way. Dynamic programming likely leads to an algorithm that is better than O(d*N^3) perhaps O(d*N^2) or better.

Gaps Between Rectangles Connected at the Center

I'm experimenting with a vector based graphics style with objects represented as series of line segments with a given width(it would probably be easier to think of these as rectangles). The problem is that these segments are connected at the center and leave a gap (shown below). I've determined that the most efficient way to cover this gap is simply to cover it with a triangle, and since I'm working in OpenGL, all I need are the points of the two points that don't overlap with the other rectangle, the third point being the center point where the two line segments(rectangles) are connected. How can I determine which points I need to use for the triangle, given that I have all of the points from both rectangles?
EDIT: I will also accept alternative solutions, as long as they cover up that gap.
EDIT 2: Nevermind, I solved it. I'll post code once I have better Internet connection.
Maybe I'm misunderstanding the question... but if you zoom in on the top corner of your red pentagon, you get something like this, am I right?
where A and B are nodes on the rectangle for edge1 and C and D are nodes on the rectangle for edge2. You say you already know these coordinates. And from what you say, the edges meet at the centre, which is halfway between A and B, and also halfway between C and D. So call this point X, and you can calculate its coordinates easily I guess.
So all you need to do is draw the missing triangle AXC, right? So one way would be to determine that A and C are on the "outside" of the polygon (and therefore need filling) and B and D are on the "inside" and therefore don't. But it's probably easier to just draw both, as it doesn't hurt. So if you fill AXC and BXD, you'd get this:
The solution I found assumes that there are 3 basic cases:
First, the three unique center points for the two rectangle proceed upward (positive y direction) so the gap is either on the left or right of the connection. In my code, I had the corner points of the rectangle organized by their orientation to the left or right of the center point, so if the bottom rectangle's left point is below the top rectangle's left point, then the gap is between the left points of the two rectangles, otherwise the gap is between the right points.
Second, the three unique center points have a maximum at the center most of the center points, so the gap is on the top. The gap is then between the two points with the maximum y values.
Third, the three unique center points have a minimum at the center most of the center points, so the gap is on the bottom. The gap is then between the two points with the minimum y values.
[I'll post pictures of the example cases if it is requested]

Resources