Graphics libraries provide line-drawing routines, sometimes with antialiasing[1] and variable width. On a grid map, line drawing is useful for for visibility, the path of an arrow/bullet, and enemy AI. I sometimes see people adapting the Bresenham line drawing algorithm to draw lines on a grid (especially for roguelike games), but I prefer a much simpler algorithms that runs just as fast. I’ll show the algorithms I use.
This is the code. The first section will explain how it works and the helper functions round_point
and lerp_point
and diagonal_distance
(these are all short), and then the other sections will describe variants of the algorithm.
function line(p0, p1) { let points = []; let N = diagonal_distance(p0, p1); for (let step = 0; step <= N; step++) { let t = N === 0? 0.0 : step / N; points.push(round_point(lerp_point(p0, p1, t))); } return points; }
1 Linear interpolation#
This demo shows what grid locations should be marked if you’re drawing a line between two points. Try moving the endpoints around.
I find the easiest way to find these points is to use linear interpolation. Let’s see how that works.
1.1 Interpolating numbers#
Here’s a simple (Javascript) helper function I’ll use:
function lerp(start, end, t) { return start * (1.0 - t) + end * t; }
Linear interpolation (“lerp”) gives you a number between two other numbers. When t
= 0.0 you get the start point; when t
= 1.0 you get the end point. Try setting t, the third parameter to lerp():
lerp( 0, 1, ) = lerp( 0, 100, ) = lerp( 3, 5, ) = lerp( 5, 3, ) =
1.2 Interpolating points#
We can extend the idea of interpolation to work on points, by interpolating both the x and y coordinates. Try varying t = :
Here’s the code to find point x,y between point p0 = (x0,y0) and point p1 = (x1,y1):
function lerp_point(p0, p1, t) { return new Point(lerp(p0.x, p1.x, t), lerp(p0.y, p1.y, t)); }
Let’s divide the line into equal line segments:
Here’s the code to find those points:
let points = []; for (let step = 0; step <= N; step++) { let t = step / N; points.push(lerp_point(p0, p1, t)); }
Variant: we can start let step = 1, and stop at step < N if we want to exclude the two endpoints. Variant: we can replace step <= N with another condition, such as stopping at a wall or at the edge of the map.
1.3 Snap to grid#
Next we need to figure out which grid squares those points are in. We can round x and y to the nearest integer to find the grid tile:
We also need to decide how many points to include. Too few and the line has holes. Too many and the line has overdraw. How many do we need? The right number is the diagonal distance between the endpoints, which in this case is .
Adjust N = to to see how the line fills in.
That’s it!
- Set N to the diagonal distance between the start and end point.
- Pick N+1 interpolation points, evenly spaced.
- Round those points to the nearest grid tile.
Here’s the final code:
function line(p0, p1) { let points = []; let N = diagonal_distance(p0, p1); for (let step = 0; step <= N; step++) { let t = N === 0? 0.0 : step / N; points.push(round_point(lerp_point(p0, p1, t))); } return points; }
This is the simplest line drawing algorithm I know of. Here are the helper functions, which you may have already implemented:
function diagonal_distance(p0, p1) { let dx = p1.x - p0.x, dy = p1.y - p0.y; return Math.max(Math.abs(dx), Math.abs(dy)); } function round_point(p) { return new Point(Math.round(p.x), Math.round(p.y)); } function lerp_point(p0, p1, t) { return new Point(lerp(p0.x, p1.x, t), lerp(p0.y, p1.y, t)); } function lerp(start, end, t) { return start * (1.0 - t) + t * end; }
1.4 Interpolating other types#
I defined the lerp
function to interpolate between two numbers, and then I defined lerp_point
to work on two points. How about other types T? We need these operations to define interpolation:
- addition
- b = a + d where a: T, b: T, and d: ΔT. For points, b.x = a.x + d.x; b.y = a.y + d.y
- subtraction
- d = a - b where a: T, b: T, and d: ΔT. For points, d.x = a.x - b.x; d.y = a.y - b.y
- multiplication by scalar
- e = k * d where d: ΔT, e: ΔT, and k: number. For points, e.x = k * d.x; e.y = k * d.y
We can do interpolation on any vector space[2]. T can be a number, a 2d point, a 3d point, an angle, a time, a color, or other things too. My guide to hexagonal grids[3] uses interpolation to draw lines on a hex grid. Note that T and ΔT may be the same type, but sometimes they are different. For example, T may be a timestamp and ΔT may be a time difference, or T may be an orientation and ΔT may be a rotation. When T and ΔT are the same type, d = a - b can be implemented as d = a + (-1 * b).
1.5 Aesthetics#
Linear interpolation is calculating a position and then rounding it. What happens when the value is exactly 0.5? Rounding rules vary[4]. That, and floating point precision, make linear interpolation not always choose points in a way that preserves consistency with rotation, reversing, and other symmetry.
I think the thing to do would be to “nudge” the initial points by epsilon. However I haven’t explored this with square grids. I’ve used it with hex grids.
1.6 Code optimization#
You can optimize the regular line drawing algorithm with these steps; it will turn into the DDA algorithm[5]:
- Inlining function calls
- Your compiler will likely do this but you may spot additional optimization opportunities by doing this yourself first.
- Unrolling lerp
- Instead of calculating t each time through the loop, and then x = (b.x-a.x)*t (a subtract and multiply), you can calculate Δx = (b.x-a.x)*Δt outside the loop, and then use x += Δx. Same for y. This will replace the multiplies with adds.
- Unrolling loop
- You can unroll the loop by keeping four x and y pairs, and then using t += 4*Δt. Would this allow the use of SSE instructions? I don’t know.
- Separate cases
- Either Δx or Δy will be ±1. You might want to have a separate versions for each case. For diagonal lines, both will be ±1. For orthogonal lines, one or the other will be 0. If these cases are common, write a separate routine for them.
- Rounding
- Compare the performance of
rint()
,nearestint()
,floor()
, in addition toround()
, as one of these may be faster (but beware of rounding modes, as they may change the result). - Floating point vs fixed point
- If you profile and find Math.round() is expensive, you can switch to fixed point arithmetic, and replace rounding with bit shifting. On x86, consider using the
fist
/fistp
instruction or maybe SSE forcvtsd2si
(I haven’t gone this far in optimization).
Before optimizing, profile and make sure linear interpolation is your bottleneck. In my projects, it rarely is, so I haven’t bothered implementing these optimizations. Here’s an example (in approximate C# syntax, to show the types) of inlining + unrolling lerp, but without applying the other optimizations:
List<Point> line(Point p0, Point p1) { List<Point> = new List<Point>(); int dx = p1.x - p0.x; int dy = p1.y - p0.y; int N = Math.Max(Math.Abs(dx), Math.Abs(dy)); double divN = (N == 0)? 0.0 : 1.0 / N; double xstep = dx * divN; double ystep = dy * divN; double x = p0.x, y = p0.y; for (int step = 0; step <= N; step++, x += xstep, y += ystep) { points.Add(new Point(Math.Round(x), Math.Round(y))); } return points; }
2 Grid walking#
Interpolation is simple and general but doesn’t take into account properties of the grid. Another approach to line drawing is to take one step at a time. This type of movement also allows putting walls on edges so that a wall could block line of sight or movement.
2.1 Orthogonal steps#
In the above lines, we took both orthogonal steps (north, east, south, west) and diagonal steps. Step-by-step algorithms give us more flexibility. What if we only want to take orthogonal steps?
The strategy here is to think about the grid edges being crossed, both vertical and horizontal. At every step we either cross a vertical edge (horizontal step) or cross a horizontal edge (vertical step). The way we can tell which way to go is by looking to see which of (0.5+ix) / nx
and (0.5+iy) / ny
is smaller. The smaller one is where we want to take the next step.
function walk_grid(p0, p1) { let dx = p1.x-p0.x, dy = p1.y-p0.y; let nx = Math.abs(dx), ny = Math.abs(dy); let sign_x = dx > 0? 1 : -1, sign_y = dy > 0? 1 : -1; let p = new Point(p0.x, p0.y); let points = [new Point(p.x, p.y)]; for (let ix = 0, iy = 0; ix < nx || iy < ny;) { if ((0.5+ix) / nx < (0.5+iy) / ny) { // next step is horizontal p.x += sign_x; ix++; } else { // next step is vertical p.y += sign_y; iy++; } points.push(new Point(p.x, p.y)); } return points; }
To avoid the division, including a potential divide by zero, we can rewrite the comparison from (0.5+ix) / nx < (0.5+iy) / ny
to (0.5+ix) * ny < (0.5+iy) * nx
. Then to avoid the floating point we can rewrite that to (1 + 2*ix) * ny < (1 + 2*iy) * nx
.
It’s more work to make it symmetric. Also, sometimes you’ll want more control over whether you pick a horizontal step or a vertical step, especially if the choice is close, and there’s a wall in one direction but not the other.
2.2 Supercover lines#
“Supercover” lines catch all the grid squares that a line passes through. I believe (but am not sure) that it is somewhere in between regular line drawing and grid movement line drawing. Unlike grid movement line drawing, we can take a diagonal step only if the line passes exactly through the corner.
This looks like the grid movement line drawing, except when the line goes through a grid corner.
Let’s modify the grid movement line drawing code for this:
function supercover_line(p0, p1) { let dx = p1.x-p0.x, dy = p1.y-p0.y; let nx = Math.abs(dx), ny = Math.abs(dy); let sign_x = dx > 0? 1 : -1, sign_y = dy > 0? 1 : -1; let p = new Point(p0.x, p0.y); let points = [new Point(p.x, p.y)]; for (let ix = 0, iy = 0; ix < nx || iy < ny;) { let decision = (1 + 2*ix) * ny - (1 + 2*iy) * nx; if (decision === 0) { // next step is diagonal p.x += sign_x; p.y += sign_y; ix++; iy++; } else if (decision < 0) { // next step is horizontal p.x += sign_x; ix++; } else { // next step is vertical p.y += sign_y; iy++; } points.push(new Point(p.x, p.y)); } return points; }
2.3 Line of sight#
If you allow diagonal steps, some algorithms will step through walls:
In this case, you can either take the diagonal step if either the horizontal or vertical step is clear, or you can disallow the diagonal step unless both the horizontal and vertical steps are clear.
3 More reading#
There’s lots written about line drawing but I haven’t researched it extensively. When drawing graphical lines, I use the graphics library. It’s only on grids that I needed to find some other algorithms.
You might have read that Bresenham’s Line Algorithm is the fastest way to draw lines. Please test this yourself. It was the fastest way many decades ago when floating point was slow and branches were fast. Modern CPUs and compilers work quite differently. We have floating point hardware now, and branches can stall CPU pipelines. I’ve tried a few different implementations of Bresenham’s Line Algorithm and it’s not any faster than the code from this page. The code here is much simpler, parallelizes well (SIMD or threads), and generalizes to more than 2D lines.
// For use in benchmark http://www.edepot.com/linebenchmark.html void naive(int x1,int y1,int x2, int y2, UByte clr) { // based on https://www.redblobgames.com/grids/line-drawing/ int dx = abs(x2 - x1); int dy = abs(y2 - y1); int length = dx > dy? dx : dy; // diagonal_distance for (int i = 0; i <= length; ++i) { double t = double(i) / length; int x = x1 + int(t * (x2 - x1)); // lerp int y = y1 + int(t * (y2 - y1)); // lerp pixel(x, y, clr); } }
- The lerp function is called
lerp
[6] in DirectX andmix
[7] in OpenGL andLerpStable
[8] in Unreal. It works for anyt
, includingt
< 0 ort
> 1. In contrast, Unity’s Mathf.Lerp[9], C++’s std::lerp[10] are a clamped lerp, clampingt
to be 0 ≤t
≤ 1. - In terms of math, I prefer to think of lerp as
start + t * (end-start)
, but for code, there are fewer floating point numerical issues[11] by writing it asstart * (1.0 - t) + t * end
. Unreal offers both, withLerp
being the first form andLerpStable
being the second form. Christopher Durham lists the properties we want from lerp[12]: exact, monotonic, consistent, bounded, but neither form provides all four properties. - If you’re interpolating 3d rotations, look at the slerp[13] variant, which works on quaternions.
- If you want non-linear interpolation, take look at smoothstep[14] and others[15], especially for animation.
- Roguebasin has an article various qualities you might want on a grid if calculating field of view or line of sight[16].
- Roguebasin also has an an article about “digital lines”, representing all possible lines[17] between two points.
- A Fast Voxel Traversal Algorithm[18] by Amanatides and Woo gives an extension of the step-by-step line drawing algorithm for 3D coordinates.
- Wu’s algorithm[19] for anti-aliasing might be useful for determining how much of an object is on one grid cell or another; I haven’t tried this.
- This article[20] looks at DDA line drawing with fixed point arithmetic. It’s from 2009 though and CPUs have changed since then. Also look at Extremely Fast Line Algorithm[21].
- I find Bresenham’s algorithm to be much longer than I’d like, but if you’d like to compare, take a look at Michael Abrash’s implementation[22] and explanation[23].
- Boo[24] is another line drawing algorithm which works differently than the usual ones.