Traverse a 2.5D grid - c++

I'm trying to figure out how to traverse a 2.5D grid in an efficient manner. The grid itself is 2D, but each cell in the grid has a float min/max height. The line to traverse is defined by two 3D floating point coordinates. I want to stop traversing the line if the range of z values between entering/exiting a grid cell doesn't overlap with the min/max height for that cell.
I'm currently using the 2D DDA algorithm to traverse through the grid cells in order(see picture), but I'm not sure how to calculate the z value when each grid cell is reached. If I could do that, I could test the z value when entering/leaving the cell against the min/max height for the cell.
Is there a way to modify this algorithm that allows z to be calculated when each grid cell is entered? Or is there a better traversal algorithm that would allow me to do that?
Here's the current code I'm using:
void Grid::TraceGrid(Point3<float>& const start, Point3<float>& const end, GridCallback callback )
{
// calculate and normalize the 2D direction vector
Point2<float> direction=end-start;
float length=direction.getLength( );
direction/=length;
// calculate delta using the grid resolution
Point2<float> delta(m_gridresolution/fabs(direction.x), m_gridresolution/fabs(direction.y));
// calculate the starting/ending points in the grid
Point2<int> startGrid((int)(start.x/m_gridresolution), (int)(start.y/m_gridresolution));
Point2<int> endGrid((int)(end.x/m_gridresolution), (int)(end.y/m_gridresolution));
Point2<int> currentGrid=startGrid;
// calculate the direction step in the grid based on the direction vector
Point2<int> step(direction.x>=0?1:-1, direction.y>=0?1:-1);
// calculate the distance to the next grid cell from the start
Point2<float> currentDistance(((step.x>0?start.x:start.x+1)*m_gridresolution-start.x)/direction.x, ((step.y>0?start.y:start.y+1)*m_gridresolution-start.y)/direction.y);
while(true)
{
// pass currentGrid to the callback
float z = 0.0f; // need to calculate z value somehow
bool bstop=callback(currentGrid, z);
// check if the callback wants to stop or the end grid cell was reached
if(bstop||currentGrid==endGrid) break;
// traverse to the next grid cell
if(currentDistance.x<currentDistance.y) {
currentDistance.x+=delta.x;
currentGrid.x+=step.x;
} else {
currentDistance.y+=delta.y;
currentGrid.y+=step.y;
}
}
}

It seems like a 3D extension of the Bresenham Line Algorithm would work. You would iterate over X and independently track the error for the Y and Z components of your line segment to determine the Y and Z values for each corresponding X value. You just stop when the accumulated error in Z reaches some critical level which would indicate it is outside of your min/max.

For each cell, you know from which cell you came from. This means you know from which side you came from. Calculating z at the intersection of the green line and a given grid line seems trivial.

I figured out a good way to do it. Add to the start of the function:
float fzoffset=end.z-start.z;
Point2<float> deltaZ(fzoffset/fabs(end.x-start.x), fzoffset/fabs(end.y-start.y));
Point2<float> currentOffset((step.x>0?start.x:start.x+1)*m_gridresolution-start.x, (step.y>0?start.y:start.y+1)*m_gridresolution-start.y);
Inside the loop where currentDistance.x/.y are incremented, add:
currentOffset.x+=m_gridresolution; //When stepping in the x axis
currentOffset.y+=m_gridresolution; //When stepping in the y axis
Then to calculate z at each step:
z=currentOffset.x*deltaZ.x+start.z; //When stepping in the x axis
z=currentOffset.y*deltaZ.y+start.z; //When stepping in the y axis

Related

Create continuous matrix of rectangles from set of rectangles

I have a set of objects(each object contains a rectangle and a value assigned to it) which is kept in a vector container.
See picture below:
I need to create a matrix by drawing horizontal and vertical lines at each y/x lower left (LL) / upper right(UR) coordinate like below:
And I need to assign value = 0 to each new empty rectangle, and to other rectangles which are inside of initial rectangles, I need to assign their old values.
I've implemented this with some naive algorithm but it works too slow when I have huge number of rectangles. My algorithm basically does the following:
- Stores all rectangles in a map container. Each element of the map contains set of rectangles with the same LL Y coordinate and they are sorted by LL X coordinate, i.e. key is LL Y coordinate.
- Stores all X/Y coordinates in set containers.
- Iterates over Y/X coordinate containers, and for each new rectangle finds out if it exists in map or not, if exists-assigns existing value to it, otherwise-assigns 0 value. I.e, for each new rectangle it looks for its LL Y coordinate in map, if such Y exists, then searches through the corresponding value(set of rectangles), otherwise-it searches in a whole map.
Is there an effective algorithm to get needed results?
For n rectangles this can be solved easily in O(n^3) time (or just O(n^2) time if at most a bounded number of rectangles intersect) by looking at the problem a different way. This should be adequate for handling up to thousands of rectangles in a few seconds.
Also, unless some other constraints are added to the problem, the latter time bound is optimal: that is, there exist inputs consisting of n non-intersecting rectangles for which O(n^2) smaller grid rectangles will need to be output (which of course requires O(n^2) time). An example such input is n width-1 rectangles, all having equal bottommost y co-ord and having heights 1, 2, ..., n.
Grid size bounds
First of all, notice that there can be at most 2n vertical lines, and at most 2n horizontal lines, since each input rectangle introduces at most 2 of each kind (it may introduce less if one or both vertical lines are also the edge(s) for some already-considered rectangle, and likewise for horizontal lines). So there can be at most (2*n - 1)^2 = O(n^2) cells in the grid defined by these lines.
The grid cell co-ordinate system
We can invent a co-ordinate system for grid cells in which each cell is identified by its lower-left corner, and the co-ordinates of an intersection of two grid lines is given simply by the number of horizontal grid lines below it and the number of vertical grid lines to its left (so that the bottommost, leftmost grid cell has co-ords (0, 0), the cell to its right has co-ords (1, 0), the cell two cells above that cell has co-ords (1, 2), etc.)
The algorithm
For each input rectangle having LL co-ords (x1, y1) and UR co-ords (x2, y2), we determine the horizontal and vertical intervals that it occupies within the new grid co-ordinate system, and then simply iterate through every cell (i, j) belonging to this rectangular region (i.e., every grid cell (i, j) such that toGridX(x1) <= i < toGridX(x2) and toGridY(y1) <= j < toGridY(y2)) with a nested for loop, recording in a hashtable that the ID (colour?) for the cell at (i, j) should be the colour of the current input rectangle. Input rectangles should be processed in decreasing z-order (implicitly at least there seems to be such an order, from your example) so that for any cell covered by more than one input rectangle, the hashtable will wind up recording whatever the "nearest" rectangle's colour is. Finally, iterate through the hash table, converting each grid co-ord pair (i, j) back to the LL and UR co-ords of the input-space rectangle that corresponds to this grid cell, and output this rectangle with the ID given by the value for this hash key.
Preprocessing
In order to accomplish the above, we need two things: a way to map input-space co-ordinates to grid co-ordinates (to determine the horizontal and vertical grid intervals for a given input rectangle), and a way to map grid co-ordinates back to input-space co-ordinates (to generate the output rectangles in the final step). Both operations are easy to do via that old workhorse, sorting.
Given any corner (x, y) of some input rectangle, the grid x co-ordinate corresponding to x, toGridX(x), is simply the rank position of x within the sorted list of all distinct x positions of vertical edges that are present among the input rectangles. Similarly, toGridY(y) is just the rank position of y within the sorted list of all distinct y positions of horizontal edges that are present among the input rectangles. In the other direction, for any grid co-ordinate (i, j), the corresponding input-space x co-ordinate, fromGridX(i), is simply the i-th smallest x co-ord (ignoring duplicates) of any vertical edge among the input rectangles, and similarly for fromGridY(j). These can all be computed as follows (all array indices start at 0, and I show only how to do it for x co-ords; y co-ords are similar):
For each rectangle i in the input having LL co-ords (x1, y1) and (x2, y2):
Append the two-element array [x1, i] to the list-of-arrays VERT.
Append the two-element array [x2, i] to the list-of-arrays VERT.
Sort the list VERT in increasing order by its first item.
Combine elements in VERT having identical x co-ords. Specifically:
Set j = 0.
For i from 1 to n-1:
If VERT[i][0] == VERT[j][0] then append VERT[i][1] to VERT[j] (thereby forming an array of length 3 or more at position j), otherwise set j = j + 1 and overwrite VERT[j] with the two-element array VERT[i].
Delete VERT[j+1] and all later elements from VERT.
By this time, for any i, VERT[i] is an array that contains (in its second and subsequent positions) the IDs of every input rectangle that uses, as either its left or right edge, the ith-leftmost distinct vertical line used by any input rectangle -- or in other words, the rank-i vertical line. We now "invert" this:
For i from 0 to n-1:
For j from 1 to length(VERT[i])-1:
Set toGridX[VERT[i][j]] = i.
For i from 0 to length(VERT)-1:
Set fromGridX[i] = VERT[i][0].
Running time
As previously established, there are at most O(n^2) grid cells. Each of the n input rectangles can occupy at most all of these cells, each of which is visited once per input rectangle, for a time bound of O(n^3). Note that this is an extremely pessimistic time bound, and for example if none (or none but a bounded number) of your rectangles overlap, then it drops to O(n^2) since no grid cell will ever be visited more than once.
I suspect the lookups and iterations are not fast enough. Things like 'otherwise it searches the whole map' point out that you do very heavy computations.
What I think you need is to use a 2d datastructure. A k-d tree or a BSP would work but the easiest to understand and implement would be a quad tree.
In a quad tree each node represents a rectangle in your space. Each node can be split into 4 children by selecting the mid point along the 2 dimensions and having the children represent the 4 resulting rectangles. Each node also holds the value that you want to assign to the area and an extra flag if the value is uniform.
To mark a rectangle with some value, you start from the root and recursively:
If the input rectangle covers the node rectangle you set the value to that node, mark it as uniform and return.
If the input rectangle and the node rectangle don't touch just return.
If the node is marked as uniform, copy the value to it's children and mark the node not uniform.
Recursively call for the 4 children (you might have to create them).
On the way back, check if the 4 children have the same value and are all marked as uniform and if so mark the node as uniform and set the same value as the children.
The main advantage of this approach is that you get to mark large areas of your map quickly. You can also prove that marking a area is O(logN) where N is the size of your map (with a larger constant than the usual tree).
You can find a more detailed explanation and some helpful images on wikipedia.
Assuming you know the top- and bottom-most y and the left- and right-most x, extend the four vectors belonging to each rectangle to the respective max and min x and y points. Keep a set of extended vertical vectors and a set of extended horizontal ones. Whenever an extended vector is added, it will necessarily intersect with each vector in the perpendicular list - the intersections are the cell coordinates of the matrix.
Once the list of cell coordinates is made, iterate over them and assign values appropriately, looking up if they are in or out of an original rectangle. I'm not too versed in data structures for rectangles, but it seems to me that two interval trees, one for horizontal, the other for vertical could find that answer in O(log n) time per query, where n is the number of intervals in the tree.
All together, this method seems to be O(n * log m) time, where n is the number of cell coordinates in the resultant matrix and m is the number of original rectangles.

Distance between two cells in a 2D matrix

I have a 2D matrix represented as a vector of values, an index representing the first cell and a pair of coordinate representing the second cell.
vector<double> matrix;
auto index = 10;
auto x1 = index % width;
auto y1 = index / width;
auto x2 = ...
auto y2 = ...
I need to find the distance between these two cells, where the distance is equals to 1 for the first "ring" of the 8 neighbor cells, 2 for the second ring, and so on.
Is there a way faster than the euclidean distance?
What you need is something like a modified Manhattan Distance. I think there may be a specific name for your use case, but I don't know it. Anyway, this is how I'd do it.
Suppose the two points are x rows away and y columns away. Then x+y is the Manhattan Distance. But in your case, diagonal movements are also allowed. So, if you moved diagonally towards the point initially, you'd cover the smaller of x and y, with some amount remaining in the other. You can then move horizontally/vertically to cover the remaining distance. Hence, the distance by your metric would be max(x,y).
Given points (x1,y1) and (x2,y2), the answer would be max(|x1-x2|,|y1-y2|)

How to fill a closed poly-line with equidistant horizontal lines?

I need to write and algorithm that fills closed poly-line with horizontal equidistant lines.
I've done similar things with rectangles and circles, here is a code snippet for the latter:
// circle parameters: center(point(0).x, point(0).y), radius
int offsetX = point(0).x + radius;
int offsetY = point(0).y + radius;
for(int i = -radius; i < radius; i += spacing){
int ry = i;
int rx = sqrt(double(radius*radius - ry*ry));
// the parameters are pair of coordinates of the horizontal line
fl_line(offsetX - rx, offsetY + i,
offsetX + rx, offsetY + i);
}
In the case of closed poly-line the additional degree of difficulty (for me) is that the coordinates of the horizontal lines would not be extracted from a single equation (circle, height of rectangle, etc), but rather from the equations of the lines with the same "y" coordinates, which will not match continuously.
Question:
Could you provide me with some insight on how to proceed with creating an algorithm that fills closed poly-lines with horizontal lines?
This is just a special case of the scan line algorithm (designed for filling polygons): http://www.tutorialspoint.com/computer_graphics/polygon_filling_algorithm.htm
Iterate y from yMin (top of your polygon) to yMax with the desired step (spacing).
For each y, find intersections with the polygon line segments, order them by their x-coordinate, connect every other pair with a line
Create a list of all edges with their lowest endpoint first. Sort the list by increasing ordinate (of the lowest endpoint).
Create an "active list" that will contain all edges that are intersected by the current horizontal.
Initialize the current horizontal position just below the lowest edge and make sure the active list is empty.
Move the horizontal upward in desired increments until the active list empties again.
Upon a move, discard from the active list the edges that will no more intersect it. Also add to it the edges that will start intersecting it (as the edges are sorted, you will search no more than needed).
Beware that an edge can be completely skipped (it can enter the active list and immediately leave it).
When the active list is up-to-date, compute all intersections and join them by an horizontal segment, left-to-right.
Note that it is possible to avoid horizontal sorting before joining the intersections in pairs, by carefully inserting the new edges where necessary. Given that the active list is usually very short, I prefer to systematically apply insertion sort.
Assuming that all active list operations take linear time in the size of the list, the total time is like O(Ne.Lg(Ne) + Ny.L), where Ne is the number of edges, Ny the number of horizontals and L the average number of intersections per horizontal (usually between 2 and 4). This is to be compared to O(Ne.Ny) for the naïve algorithm.

Check if the line goes through wall on 2D map

I have 2d map and I want to check if line collides with any element. I need a function that can tell me if the line intersect any object on its way.
Take a look:
Red lines are not correct (function should return false), and green are (return true).
My collision map is map of boolean with 1 for wall and 0 for empty space.
How to this? I've read that I need to check if the line intersect any wall, but i have completely no idea how to do this on 2d map.
Thanx for any replies.
It depends on how your walls are represented.
If they are rectangle, then look for the line/segment intersection between your line and the 4 segments representing the rectangle.
If they are pixels, you can use the bresenham line algorithm to see if the pixels on the line are on these blocks.
If your walls are represented as line-segments you could test for intersection of line-segments as Paul Bourke describes: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/
If your walls are represented as polygons you could clip your test line against the wall polygon and see if the clipping result is non-empty as Paul Bourke describes: http://local.wasp.uwa.edu.au/~pbourke/geometry/cliplinetopoly/
So, I imagined that your cells are squares... let say they're unit squares. So, if I have any coordinate, for a point like , which are floats or doubles, they are in cell .
you need to know in which cells are the endpoints of the line
walk straight from one endpoint to the other and for each cell, test if it's a wall or not
return false when a wall is found, true otherwise.
To walk from one endpoint to the other, you need to compute the delta of each axis (call delta_x and delta_y, those values are 'int' because we're talking cells here), i.e. the number of cells it goes on the vertical and on the horizontal. You take the largest of the two. You will use that largest value for your loop. Let say it's this value is D = max(delta_x, delta_y) and XX and YY are the coordinate of the cell of one endpoint.
float step = 1.0f / D;
float current_location = 0.0;
for (int i = 0; i <= D; ++i, current_location += step)
{
int cur_x = XX + current_location * delta_x;
int cur_y = YY + current_location * delta_y;
if (intersect_wall(cur_x, cur_y))
return false;
}
return true;
That's it... adapt this to your functions.

Working out positions with array indexes

I have an array that represents a grid
For the sake of this example we will start the array at 1 rather that 0 because I realized after doing the picture, and can't be bothered to edit it
In this example blue would have an index of 5, green an index of 23 and red 38
Each color represents an object and the array index represents where the object is. I have implemented very simple gravity, whereby if the grid underneath is empty x + (WIDTH * (y + 1)) then the grid below is occupied by this object, and the grid that the object was in becomes empty.
This all works well in its current form, but what I want to do is make it so that red is the gravity point, so that in this example, blue will move to array index 16 and then 27.
This is not too bad, but how would the object be able to work out dynamically where to move, as in the example of the green grid? How can I get it to move to the correct index?
Also, what would be the best way to iterate through the array to 'find' the location of red? I should also note that red won't always be at 38
Any questions please ask, also thank you for your help.
This sounds very similar to line rasterization. Just imagine the grid to be a grid of pixels. Now when you draw a line from the green point to the red point, the pixels/cells that the line will pass are the cells that the green point should travel along, which should indeed be the shortest path from the green point to the red point along the discrete grid cells. You then just stop once you encounter a non-empty grid cell.
Look for Bresenham's algorithm as THE school book algorithm for line rasterization.
And for searching the red point, just iterate over the array linearly until you have it and then keep track of its grid position, like William already suggested in his answer.
x = x position
y = y position
cols = number of columns across in your grid
(y * cols) + x = index in array absolute value for any x, y
you could generalize this in a function:
int get_index(int x, int y, int gridcols)
{
return (gridcols * y) + x;
}
It should be noted that this works for ZERO BASED INDICES.
This is assuming I am understanding what you're talking about at all...
As for the second question, for any colored element you have, you should keep a value in memory (possibly stored in a structure) that keeps track of its position so you don't have to search for it at all.
struct _THING {
int xpos;
int ypos;
};
Using the get_index() function, you could find the index of the grid cell below it by calling like this:
index_below = get_index(thing.x, thing.y + 1, gridcols);
thing.y++; // increment the thing's y now since it has moved down
simple...
IF YOU WANT TO DO IT IN REVERSE, as in finding the x,y position by the array index, you can use the modulus operator and division.
ypos = array_index / total_cols; // division without remainder
xpos = array_index % total_cols; // gives the remainder
You could generalize this in a function like this:
// x and y parameters are references, and return values using these references
void get_positions_from_index(int array_index, int total_columns, int& x, int& y)
{
y = array_index / total_columns;
x = array_index % total_columns;
}
Whenever you're referring to an array index, it must be zero-based. However, when you are referring to the number of columns, that value will be 1-based for the calculations. x and y positions will also be zero based.
Probably easiest would be to work entirely in a system of (x,y) coordinates to calculate gravity and switch to the array coordinates when you finally need to lookup and store objects.
In your example, consider (2, 4) (red) to be the center of gravity; (5, 1) (blue) needs to move in the direction (2-5, 4-1) == (-3, 3) by the distance _n_. You get decide how simple you want n to be -- it could be that you move your objects to an adjoining element, including diagonals, so move (blue) to (5-1, 1+1) == (4, 2). Or perhaps you could move objects by some scalar multiple of the unit vector that describes the direction you need to move. (Say, heavier objects move further because the attraction of gravity is stronger. Or, lighter objects move further because they have less inertia to overcome. Or objects move further the closer they are to the gravity well, because gravity is an inverse square law).
Once you've sorted out the virtual coordinates of your universe, then convert your numbers (4, 2) via some simple linear formulas: 4*columns + 2 -- or just use multidimensional arrays and truncate your floating-point results to get your array indexes.