Sometimes we are required to cover line segments with grids. Here, I will introduce a simple trick to build the grids elegantly. The whole precedure can be divied into two steps as is shown below.
Clip a Line Segment with Boundaries of Grid
Below is the code for clipping a line segment with grids. The idea is pretty straigtfoward. A line can be described by the formula in Fig. 1 parameterized by t. So We can represent a cuting point by t when we cut a line segment with the boundary of grids. The procedure in code consists of three steps. Firstly, we cut a line with the boundaries of grids parallel to x axis and insert the t to a set. And similarly, we cut a line with the boundaries of grids parallel to y axis and also insert the t to a set. Finally, we compute the coordinates of the clipping points according to Fig.1 and put them to a vector.
1 |
set<double> t; |
Put Line Segment to Its Corresponding Grid
After line segment clipping, the endpoints of a line is guaranteed to be lied in the grid. Without loss of generality, we represent a grid with its lower left corner coordinate. Therefore, we could quickly determine which grid the current line is located at by its midpoint.
set<pair<int, int> >grids;
grids.insert(make_pair(int(midpoint_x/GRID_LENGTH) - midpoint_x<0?1:0, int(midpoint_y/GRID_LENGTH) - midpoint_y<0?1:0))
近期评论