[2.0.x] Fix Bresenham rounding errors#10871
[2.0.x] Fix Bresenham rounding errors#10871thinkyhead merged 1 commit intoMarlinFirmware:bugfix-2.0.xfrom ejtagle:bugfix-2.0.x
Conversation
|
@thinkyhead : Be careful, as the quoted article is missing the last piece of the puzzle, the one that explains the rounding needed to get it right. And that was the problem of the previous implementation!! |
|
As they say, the devil is in the details. Grbl implementation is not exactly this one, but is also properly handling rounding |
|
I appreciate the effort to document the code, but quoting an entire article is serious overkill in the middle of our If we very much want to document the operational theory that goes into making Marlin work and we're concerned that the pages we're linking to might go away, then we should add a new section to marlinfw.org for that purpose and link to that instead. |
|
@thinkyhead : That would be great, or at least, add a new folder to the solution (called docs/) and place all those comments there. |
|
Was the previous code deduced to produce an error of one step sometimes? I'd be curious to see an example where initializing to one less (with the rounding) and using I could experiment with that, as I have a handy C file already set up for testing Bresnham variants. |
|
Hmm, I see that the simple count[0] = -((inDividend + 1) >> 1);
. . .
const bool over = (count >= 0); |
|
Well, so far in my testing, rounding down and using count[0] = -(inDividend >> 1);
. . .
const bool over = (count > 0);Can you come up with any ratio where a step would be missed using this over the former? |
|
It depends on how long the line is, and it has to be "nearly exact" multiple of the lenght. Then, at the end a step will be lost (it is just a rounding error) |
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
class Bresenham {
public:
long divisor, dividend, count, ticker, invocations;
public:
Bresenham() { Bresenham(1, 1, 0); }
Bresenham(const long &inDividend, const long &inDivisor, const long &inTicker=0) {
cout << "Bresenham(" << inDividend << ", " << inDivisor << ")" << endl;
invocations = 0;
divisor = inDivisor;
dividend = inDividend;
count = -((inDividend + 1) >> 1);
ticker = inTicker;
}
bool tick() {
invocations++;
count += dividend;
const bool over = (count >= 0);
if (over) {
ticker++;
count -= divisor;
}
report();
return over;
}
long operator++() {
tick();
return ticker;
}
void report() {
static long lastTicker = 0;
rj(invocations, 3);
cout << ": " << "count: ";
rj(count[0], 3);
cout << ", ticker: ";
rj(ticker, 3);
if (ticker != lastTicker) {
cout << " *";
lastTicker = ticker;
}
cout << endl;
}
};
Bresenham bres(13, 14);
int main(int argc, char const *argv[]) {
do { bres.tick(); } while (bres.invocations < bres.divisor);
return 0;
} |
|
I do a agree, it is a rare situation 👍 -- But math does not lie here 🥇 |
I think we're already guaranteed to get the right number of ticks. Rounding closer to 0 (on the negative side of the number line) at the start, like we currently do, simply means we can use |
|
Ok, I´ll send a test program... 👍 |
|
Surely you can see all you've done is shifted the count values one to the left, |
|
I realized that with positive counts there may be a difference. Here's an example where it differs. A tick at iteration 9 instead of iteration 10. |
|
The problem , as was stated in the report, is that > is not the same as >= due to the error rounding. At least, that causes 1isr pulse jitter (depending if dx is even or odd) ... |
|
(and there is also something you don´t know: It is much cheaper to test for >= than to test for >. Reason is that the first one only needs to read the sign bit, and the other one need to read the whole value... ;) |
Ah, this is true! |
|
So, as long as we're counting cycles, which of these is faster? |
|
Is nearly the same. Maybe the first one, as there is one less operation 👍 -- Yes, the first one. One addition, then one shift. |
|
Yep, the first one does less, compiles 14 bytes smaller, and uses 4 fewer registers. Excelsior! |
Fix Bresenham algorithm (rounding errors), add theory of operation and deduction of the employed algorithm.
On the Bresenham algorithm as implemented by Marlin:
(Taken from https://www.cs.helsinki.fi/group/goa/mallinnus/lines/bresenh.html)
The basic Bresenham algorithm:
Consider drawing a line on a raster grid where we restrict the allowable slopes of the line to the range 0 <= m <= 1
If we further restrict the line-drawing routine so that it always increments x as it plots, it becomes clear that, having plotted a point at (x,y), the routine has a severely limited range of options as to where it may put the next point on the line:
-It may plot the point (x+1,y), or:
-It may plot the point (x+1,y+1).
So, working in the first positive octant of the plane, line drawing becomes a matter of deciding between two possibilities at each step. We can draw a diagram of the situation which the plotting program finds itself in having plotted (x,y).
In plotting (x,y) the line drawing routine will, in general, be making a compromise between what it would like to draw and what the resolution of the stepper motors actually allows it to draw. Usually the plotted point (x,y) will be in error, the actual, mathematical point on the line will not be addressable on the pixel grid. So we associate an error, ε , with each y ordinate, the real value of y should be y+ε . This error will range from -0.5 to just under +0.5.
In moving from x to x+1 we increase the value of the true (mathematical) y-ordinate by an amount equal to the slope of the line, m. We will choose to plot (x+1,y) if the difference between this new value and y is less than 0.5
Otherwise we will plot (x+1,y+1). It should be clear that by so doing we minimise the total error between the mathematical line segment and what actually gets drawn on the display.
The error resulting from this new point can now be written back into ε, this will allow us to repeat the whole process for the next point along the line, at x+2.
The new value of error can adopt one of two possible values, depending on what new point is plotted. If (x+1,y) is chosen, the new value of error is given by:
Otherwise, it is:
This gives an algorithm for a DDA which avoids rounding operations, instead using the error variable ε to control plotting:
This still employs floating point values. Consider, however, what happens if we multiply across both sides of the plotting test by Δx and then by 2:
All quantities in this inequality are now integral.
Substitute ε' for ε.Δx . The test becomes:
This gives an integer-only test for deciding which point to plot.
The update rules for the error on each step may also be cast into ε' form:
Consider the floating-point versions of the update rules:
Multiplying through by Δx yields:
Which is in ε' form:
Using this new "error" value, ε' with the new test and update equations gives Bresenham's integer-only line drawing algorithm:
It is an Integer-only algorithm - hence efficient (fast). And the Multiplication by 2 can be implemented by left-shift. 0 <= m <= 1
A possible implementation in C:
We can optimize it a bit, by noting that
Is equivalent to:
Even if it would seem that right shifting dx would lose the least significant bit, we can handle it by proper rounding: eps is an integer variable, so only has integer values. dx is also an integer value, so after dividing by 2, either the value was an integer, or we missed by 0.5 less than true value.
1] If, after the division, the value was exactly an integer, then the following holds true:
2] If, after the division, the result was truncation of the last bit of dx, then
But, as eps is an integer, we can rewrite the expression as:
Now, the algorithm can be rewritten as:
The last thing we can do to improve the algorithm, is instead of initializing eps to 0, we can initialize it to -((dx>>1) + (dx&1)) , so the algorithm becomes:
And this is exactly the algorithm implemented by Marlin