Calculating integrer x and y coordinates around point by range variable - c++

The problem didn't let me sleep at night.
Given floating point x and y coordinates of infinite 2D space, and the range variable, I need to get all possible intergrer coordinates that are in range.
The green blocks are in range, and the red ones are not.
Now, I have an answer, but I'm not sure if it's the best one.
Make an 2D array with all the values in a square around the point (from -distance, distance to distance, -distance) and then iterate through the entire array, each time checking the distance if it is closer or further than needed, and if so then insert it into another array.

Starting from the center point, go both ways horizontally to the furthest points that are in the range.
For each of these points encountered, calculate the maximum vertical coordinate either way which will still be in the range, and add all the squares along this line.

Related

Access a circle of rays efficiently (find closest obstacle contours)

Have a binary grid (like black and white pixels with black = empty and white = obstacle).
Starting from a given point on black, I want to emit "rays" in all directions. Those rays should either abort when reaching a given length (for example 100) or when hitting a white pixel (in which case the position of this pixel, aka obstacle contour shall be marked).
Those marked pixels result in a view of all obstacle contours that are "visible" from the given point (not obstructed by other obstacles).
What I have thought of so far, is to simply call a sufficient number of bresenham lines. In the case of a radius of 100, that means 100*2*pi = 628 lines to cover all pixels on the outer most circle.
However that results in many many multiple checks of same pixels closer to the center. Now I could split up the check in multiple rings, each of a different density of bresenham lines, but that appears rather inefficient too.
Does someone happen to have a more efficient algorithm idea for this?
Huge thanks in advance!
Unfortunately the hints towards graphics processing techniques while fascinating, are not well applicable in my case because I have no access to shaders or a camera, etc.
For now I have found a sufficiently efficient solution myself. The basic idea is to launch rays from the contours, not from the origin. Furthermore to use a helper grid named "reachable" where all pixels are marked that are successfully visible from the origin. This way only few pixels are read twice, most are read just once and some are written at most once. The code is rather messy yet, thus only pseudocode here:
Have desired origin O.x/O.y
Have obstacle bool grid Obstacle
Define bool grid Reachable[w][h]
Clear Reachable with false
Reachable[O.x][O.y] = true
For each Point C on all obstacle Contours // if not available, compute contours by finding all pixels adjacent to non-obstacle
For all Pixels A on Bresenham line from C to O
If Obstacle[A.x][A.y]
Continue with outer loop on contours // abort this line due to obstacle hit
If Reachable[A.x][A.y]
For all Pixels B on Bresenham line from C to A
Reachable[B.x][B.y] = true // mark all pixels on this line as Reachable
Mark C as a desired result pixel
Continue with outer loop on contours
Let the "square distance" between two points (x1,y1) and (x2,y2) be max(|x1-x2|,|y1-y2|), so that the points at increasing "square distance" around a center for increasingly large squares.
Now, for each square distance d from your center point, in increasing order, keep track of the angles the center point can see through all the obstacles with distance <= d.
You can use a list of angle intervals starting at [(0,360)] for d=0.
For each new distance, you can inspect the list, examine the new pixels within the given angles, and remove angle from the intervals when obstacles are hit. Each obstacle that causes you to modify an interval is visible from the center point, so you can mark it as such.
This method examines pixels only once, and only examines pixels you can see. The way I wrote it above requires trigonometry, however, which is slow. For a practical implementation, instead of actually using angles, use slopes, which require only simple math, and process each octant separately.

The search for a set of points with a minimum sum of lengths to rectangles. What is the algorithm?

Good day.
I have the task of finding the set of points in 2D space for which the sum of the distances to the rectangles is minimal. For example, for two rectangles, the result will be the next area (picture). Any point in this area has the minimum sum of lengths to A and B rectangles.
Which algorithm is suitable for finding a region, all points of which have the minimum sum of lengths? The number of rectangles can be different, they are randomly located. They can even overlap each other. The sides of the rectangles are parallel to the coordinate axes and cannot be rotated. The region must be either a rectangle or a line or a point.
Hint:
The distance map of a rectangle (function that maps any point (x,y) to the closest distance to the rectangle) is made of four slanted planes (slope 45°), four quarter of cones and the rectangle itself, which is at ground level, forming a continuous surface.
To obtain the global distance map, it "suffices" to sum the distance maps of the individual rectangles. A pretty complex surface will result. Depending on the geometries, the minimum might be achieved on a single vertex, a whole edge or a whole face.
The construction of the global map seems more difficult than that of a line arrangement, due to the conic patches. A very difficult problem in the general case, though the axis-aligned constraint might ease it.
Add on Yves's answer.
As Yves described, each rectangle 'divide' plane into 9 parts and adds different distance method in to the sum. Middle part (rectangle) add distance 0, side parts add coordinate distance to that side, corner parts add point distance to that corner. With that approach plan has to be divided into 9^n parts, and distance sum is calculated by adding appropriate rectangle distance functions. That is feasible if number of rectangles is not too large.
Probably it is not needed to calculate all parts since it is easy to calculate some bound on part min value and check is it needed to calculate part at all.
I am not sure, but it seems to me that global distance map is convex function. If that is the case than it can be solved iteratively by similar idea as in linear programming.

Function to approach a number asymptotically

I have a map that I can zoom in and out of. Gridlines display the latitude and longitude.
Right now I zoom in by shrinking the borders by a specific amount.
Say top edge is lat 30n, bot edge is lat 28n, left edge is lon -40w, right edge is lon -38w.
So for one zoom in, the new edges are 29.5n, 28.5n, -39.5w,-38.5 respectively.
Zooming in enough times would eventually make the opposite edges equal each other and then flip.
So next zoom in for top and bot edge would be 29n, 29n and then next 28.5n,29.5n which flips the orientation.
I'm looking for a function or a way that I can continuously zoom in, but never have the edges equal each other or flip. In others words something where I can get the edges to continuously get closer and closer to each other, but never touch.
So I have an idea that I'll need some function like
lim x-> infinity of x/(x+1) - 1 + midpoint of the two edges
which basically means, as I zoom in I will approach the midpoint.
If this is valid, I don't know how to implement limits in C++.
This is only one equation too. I have two edges on each axis and so I'd need two equations to approach the midpoint from both sides at an equal rate.

Sustaining value in specified range

Lets say i have a point with its position on 2d plane.
This point is going to change it position randomly, but thats not the point, so lets assume that it has its own velocity and its moving on plane with restricted width and height;
So after a while of movement this point is going to reach plane boundary.
But its not allowed to leave plane.
So now i can check point position each frame to see is it reached bound or not.
if(point.x>bound.xMax)point.x=bound.xMax
if i want point to teleport itself to second side of plane i can simply :
point.x = point.x%bound.xMax;
but then i need to store point position in integers.
For 10 milion values on my corei7 1.6 both solutions
have similar timings. 41ms vs 47 on second,
so there is no sense in using modulo function in that case, its faster to just check value.
But, is there any kind of trick to make it faster?
Multiple threads for iterating array approach is not a solution.
Maybe i can scale my bound value to some wierd value and for example discard a part of binary interpretation of position value.
And if there is some trick to do it i think that somebody did it before me :)
Do you know any kind of solution that could help me?
If there is some way you can add information around the plane coordinates you could very well make a "border" around the plane which contains a value that is identified as "out of boundaries". For example if you have a 10x10 board, make it 12x12 and use the 2 extra rows and columns to insert that information.
Now you can do (pseudo-code):
IF point IN board IS "out of boundaries value" THEN
do your thing
END IF
Note that this method is only an optimization if your point has both x and y values (my assumption on your case).

how to determine whether a point lies inside a rectangle? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Finding whether a point lies inside a rectangle or not
There is an interview question that is, "How to determine whether a point lies inside a rectangle"
Note that the rectangle could be rotated as well. So the simple solution of checking point inside the rectangle doesn't stands valid here...
Please share your thoughts on this question..
I found a link on internet, and was trying to understand it, but failed.... Please if any body out here can give complete solution with bit of computer graphics logic, because i have forgotten all the basics....
How to determine if a point is inside rectangle.
Pick a point that's definitely outside the rectangle. Then create a segment from that point to the point in question. Solve the linear equations for intersections between that segment and the segments that make up the rectangle. If you get exactly one intersection, the point is inside the rectangle. Otherwise (0 or 2 intersections), it's outside.
This is trivial to extend to essentially any polygon -- an odd number of intersections means the point is inside the polygon, and an even number means it's outside.
Edit: It may not be immediately obvious, so I'll emphasize that the point we pick outside the rectangle (polygon) is entirely arbitrary. We can pick whatever point we want as long as we're sure it's outside the polygon. To keep our computations easy, what we'll typically do is pick (Px, infinity) (where Px is the x coordinate of the point P that we're testing) -- that is, what we're creating is essentially a vertical ray. That simplifies testing a bit, because we only have to test against one end-point to find an intersection. It also simplifies solving the linear equations to the point that it's barely recognizable as solving linear equations anymore. We really just need to compute the Y coordinate for the line at the Px, and see if it's greater than Py. As such, solving the linear equation breaks down to:
checking whether that X value is within the range of X values for the segment
if it is, plugging the X value into the equation of the line
testing whether the resulting Y value is greater than Py
If those pass, we have an intersection. Also note that the tests can be carried out in parallel (handy if we're doing this on parallel hardware like a GPU).
Simple solution that works in N dimensions for convex polyhedra, of which a 2-dimensional rectangle is a special case:
Represent the polyhedron as the intersection of half-spaces, each defined by a unit normal vector and the distance of the surface hyperplane from the origin along the normal.
For each of these half-spaces, take the dot product of point in question with the defining normal vector. The point is in the half-space if and only if the dot product is less than [or equal to] the defining distance.
The point is inside the polyhedron if and only if it's in every one of the half-spaces.
For a rectangle defined as a counter-clockwise sequence of edges, step 1 amounts to rotating the edges each by 90 degrees clockwise to get the normals, then intersecting the normal line with the line containing the edge to find the distance to the origin.
Assuming step 1 is complete, testing a point takes at most 8 multiplications, 4 additions, and 4 comparisons.
If you want to, you can optimize the process a bit since you have rectangles (and thus opposite sides have opposite normals). Now you're only looking at 2 normals rather than 4, and a range of dot product values which indicate points that lie between the opposite sides. So now you're down to 4 multiplications, 2 additions, and 4 comparisons.
You can also get lucky if the first test you make shows that the point is outside the rectangle, in which case it's just 2 multiplications, 1 addition, and 1-2 comparisons.
This is far from the best solution... But if you have the points in consecutive order, call them a, b, c, and d with an x and a y field, you can use the cross product of the vectors between your point p and each of the consecutive pairs.
If you always get the same sign for the result (i.e., all are positive or all are negative) then you're inside the rectangle; otherwise, you're outside.
Define a new coordinate system with two rectangle sides as unit vectors and transform the coordinate of the point into the new coordinate system. If both coordinates are between 0 and 1, it's inside.
In equations (assuming A,B,C,D are corners of the rectangle, P is the point, _x and _y are the x and y components):
P_x = A_x + x * (B_x - A_x) + y * (D_x - A_x)
P_y = A_y + x * (B_y - A_y) + y * (D_y - A_y)
Solve for x and y and check if they are between 0 and 1
Written as linear equation system (A,B,C,D,P are vectors of length 2):
[ | ] [x] [ ]
[B-A | D-A] * [ ] = [P-A]
[ | ] [y] [ ]
Solving is easy as it has only two dimensions and you can be sure that you are not singular.
You can rotate and move your reference system so it matches position and rotation of the rectangle. Now it is just a matter of simple comparisons between coordinates. This is more a mathematical way, so not the fastest (bellieve #Platinum Azure's one is)
Since the rectangle could be rotated, you might want to consider an algorithm that is used to determine whether a point is interior to a convex polygon.
You could also compute the rotation angle of the rectangle, then transform both the rectangle and the point to axially align the rectangle. Then check to see if the transformed point is inside the axially aligned rectangle.
Finding whether a point lies within a bounded region like rectangle is part of the classic clipping algorithms. Refer to the wikipedia articles on Clipping and Line Clipping to know more about it.
Following the spirit of #Jerry Coffin: create segments from rectangle corners to the point in question. Solve the linear equations. Slope is tan(a). Sum up all seq arctangents diff, if it is 2*PI and each diff < PI - point is inside the rectangle.
Edit Probably enough just check for each sequential difference < Pi...