While doing some graphics programming, I was surprised to learn the typical implementation of the Bresenham line plotting algorithm gives different results when the endpoints are reversed. For example, a line drawn with MoveTo(20,50) LineTo(80,122) differs from MoveTo(80,122) LineTo(20,50) twelve times, each mismatch spaced six pixels apart, such as hitting pixel (78,119) when drawing in one direction while drawing in the other direction hits (77,119).
A very simple case is plotting (0,0) to (2,1), which hits (0,0), (1,0), (2,1), while plotting (2,1) to (0,0) hits (2,1), (1,1), (0,0), differing in the middle pixel.
Is there a version of Bresenham that hits all the same pixels regardless of drawing direction between endpoints, and is still fast and efficient? None of my online searches have turned up any discussion of this issue.
The code that ran into this problem was trying to solve the problem where a moving pixel stopped on its way from (X0,Y0) to (X1,Y1). Would another pixel moving in the opposite direction from (X1,Y1) to (X0,Y0) land on the stopped pixel? Using Bresenham to calculate the pixel positions fails for many cases.
The difference in pixels is due to rounding behavior. If you draw a line from low X to high X, then when the "real" Y is 0.5, it will round up. If you draw the line the other way, then it will round down.
The solution (as MrSmith42 mentions in comment) is to always draw the same line in the same direction.
An implementation of Bresenham's must first determine which axis is the major axis, and it will then iterate along the major axis in the loop.
After determining the major axis, you should reverse the line if necessary to ensure that the major axis will be traversed in the positive direction.
This will simplify your code as well as ensuring that you get the same results no matter what order the input points are in.