Bresenham’s line drawing algorithm implemetations in Go and C.

Couple of Bresenham’s line drawing implementations in C and Go. They will need hacking to suit your application.

void display_draw_line(int start_x,int start_y,int end_x,int end_y,uint16_t color) {

  // Bresenham's
  int cx = start_x;
  int cy = start_y;

  int dx = end_x - cx;
  int dy = end_y - cy;
  if(dx<0) dx = 0-dx;
  if(dy<0) dy = 0-dy;

  int sx=0; int sy=0;
  if(cx < end_x) sx = 1; else sx = -1;
  if(cy < end_y) sy = 1; else sy = -1;
  int err = dx-dy;

  for(int n=0;n<1000;n++) {
    display_draw_point(cx,cy,color);
    if((cx==end_x) && (cy==end_y)) return;
    int e2 = 2*err;
    if(e2 > (0-dy)) { err = err - dy; cx = cx + sx; }
    if(e2 < dx    ) { err = err + dx; cy = cy + sy; }
  }
}

And golang:

func draw_line(start_x int32,start_y int32,end_x int32,end_y int32,color uint32,screen* sdl.Surface) {

  // Bresenham's
  var cx int32 = start_x;
  var cy int32 = start_y;

  var dx int32 = end_x - cx;
  var dy int32 = end_y - cy;
  if dx<0 { dx = 0-dx; }
  if dy<0 { dy = 0-dy; }

  var sx int32;
  var sy int32;
  if cx < end_x { sx = 1; } else { sx = -1; }
  if cy < end_y { sy = 1; } else { sy = -1; }
  var err int32 = dx-dy;

  var n int32;
  for n=0;n<1000;n++ {
    draw_point(cx,cy,color,screen);
    if((cx==end_x) && (cy==end_y)) {return;}
    var e2 int32 = 2*err;
    if e2 > (0-dy) { err = err - dy; cx = cx + sx; }
    if e2 < dx     { err = err + dx; cy = cy + sy; }
  }
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>