I'm getting started with graphics and I'm having trouble implementing the Bresenham's algorithm. Now, I know that my implementation is incomplente, but I can't see why it doesn't make horizontal lines(same height(y) values, different width(x values). I get a floating point exception. Here's the algo:

int draw_line(void *mlx_ptr, void*win_ptr, t_2dpoint *initial_p, t_2dpoint *final_p)
{
 53     int delta_x;

 53     int delta_x;
 54     int y;
 55     int delta_y;
 56
 57     delta_x = final_p->x - initial_p->x;
 58     delta_y = final_p->y - initial_p->y;
 59
 60     x = initial_p->x;
 61     y = initial_p->y;
 62     e = (float)(delta_x / delta_y) - 1.0;
 63
 64     while(x < final_p->x - 1)
 65     {
 66         mlx_pixel_put(mlx_ptr, win_ptr, x, y, 0XFF00FF);
 67         if ( e >= 0)
 68         {
 69             y += 1;
 70             e -= 1.0;
 71         }
 72         x += 1;
 73         e += (float)delta_x / delta_y;
 74     }
 75     mlx_pixel_put(mlx_ptr, win_ptr, x, y, 0XFF00FF);
 76 }
e = (float)(delta_x / delta_y) - 1.0;

e += (float)delta_x / delta_y;

Either of these lines will cause a divide-by-zero error when delta_y is zero, which is when the line is horizontal (or zero-length). You need to check for this condition and have some special-case code.

As an aside, I don't know why people still teach Bresenham's algorithm to new CG students. It's a good example of an algorithm but it's not very useful knowledge in itself: you're unlikely to need to know it unless it's for a job interview.

  • The underlying principle of Bresenham (the error value getting accumulated and moved back to 0 as events happen) is nice but no-one seems to teach it – ratchet freak Aug 7 at 14:58
  • Yep, that fixes the floating point exception, now I just need to find the math logic. What algorithm you'd recommend? – koperandus Aug 8 at 16:38
  • 2
    Well, if you want to draw lines one pixel at a time, Bresenham's algorithm is the right one. But why do you want to draw lines one pixel at a time? Any OpenGL implementation will draw them all at once for you. – Dan Hulme Aug 8 at 17:04
  • @DanHulme Sometimes it's useful to know a little history.... even if it's only to give you a greater appreciation of the present ;-) – Simon F Sep 7 at 8:20

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.