Bresenham Line

Rasterization of lines is something that is very important in computer graphics. Line is one of the simplest primitives and we want to specify it by its endpoints. It is up to the computer to fill all the pixels between those endpoints that are visible.

Very efficient and known way of rasterizing lines is called the Bresenham's line algorithm. Idea behind it is that we will consider the slope of the line. Then we will move along one of the coordinates and accumulate the fractions of pixels a line should have moved in the other coordinate. If this fraction accumulates over 0.5, then we move 1 unit in the other coordinate and subtract 1.0 from the accumulator. Wikipedia has a good general explanation of it.

However, for this algorithm to be fast, different optimizations are considered. One of those is avoiding extra calculations like finding the sign inside the rasterization cycle. It might not seem much at first glance, but this algorithm needs to be ran millions of times per second. Even the Wikipedia says that the most optimized version of it only uses integer addition, subtraction and bit shifting.

JavaScript

Take a look at the base code:
https://cglearn.codelight.eu/files/course/2/tasks/BresenhamLineCanvas.zip

In JavaScript there is no actual integer arithmetic. If you divide two integers, you will get a float back. Because of that we will use the division in finding the slope of the line. But do consider all 4 cases separately. There are some differences for steep, non-steep, descending and ascending lines.

You can compare it to canvas's path drawing routine. The final result should look like:

C++

Take a look at the base code:
https://cglearn.codelight.eu/files/course/2/tasks/BresenhamLineAllegro.zip

Here it would be possible to implement this algorithm using only integer math, but to better illustrate the idea, we will use floats. We do consider all 4 cases separately, one case has already been done in the base code.

The final result should look like:

;