I'm looking for an algorithm that can compute all grid cells occupied by an arbitrary rectangle in 2d space in a defined area. The rectangle is defined by it's 4 corner coordinates. In the picture below I marked two of them as red, the coordinates of the grid cells are in black. I'm looking for a generic case that also covers unaligned grids (center of grid != center of underlying coodinate system), but converting between Cell coordinates <=> Coordinate system is trivial and already implemented. All cells are squares.
The calculation is done thousands in very short amounts of time and needs to be as fast as possible.
What I'm doing right now:
Right now I'm calculating the edges of the rectangle (AB, BC, CD, DA) and sample them at sampleRate = cellWidth / 4
intervals. To find the middle cells I construct new lines from AB + sampleRate * x
to CD + sampleRate * x
and sample those lines again at sampleRate
. I put all cells that I find at each sampled point into a HashSet to remove duplicates. But I feel this is increadibly inefficient.
I also thought about grabbing all cells in my relevant area into a buffer and generate a range tree or index tree. Then I could queue the bounds of the rectangle and get all contained cells at O(log n+m), but I'm not sure how to implement that and I can't even find any C# range tree implementations.
My knowledge in computer graphics is very rusty, but shouldn't there be an easy geometrical approach that works without sampling?