Created
May 6, 2018 21:22
-
-
Save kisssko/30deca52ca00534cfddfdaf45b34c126 to your computer and use it in GitHub Desktop.
Speed-optimized Bresenhem algorythm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <conio.h> | |
void plot(int x, int y, int c) | |
{ | |
gotoxy(x+1,y+1); | |
putchar(c); | |
putchar(8); | |
} | |
#define DIR_LRTB 0 // LEFT to RIGHT, TOP to BOTTOM | |
#define DIR_RLTB 1 // RIGHT to LEFT, TOP to BOTTOM | |
#define DIR_LRBT 2 // LEFT to RIGHT, BOTTOM to TOP | |
#define DIR_RLBT 3 // RIGHT to LEFT, BOTTOM to TOP | |
void draw_line(int x0, int y0, int x1, int y1, int c) | |
{ | |
int x,y,dx,dy,s; | |
char d=0; | |
x=x0; y=y0; | |
if(x0>x1)d|=1; | |
if(y0>y1)d|=2; | |
switch(d) | |
{ | |
case DIR_LRTB: | |
dx=x1-x0; | |
dy=y1-y0; | |
if(dy>dx) | |
{ | |
for(s=dx;y<=y1;y++) | |
{ | |
plot(x,y,c); | |
s+=dx; | |
if(s>=dy){x++;s-=dy;} | |
} | |
} else | |
{ | |
for(s=dy;x<=x1;x++) | |
{ | |
plot(x,y,c); | |
s+=dy; | |
if(s>=dx){y++;s-=dx;} | |
} | |
} | |
break; | |
case DIR_RLTB: | |
dx=x0-x1; | |
dy=y1-y0; | |
if(dy>dx) | |
{ | |
for(s=dx;y<=y1;y++) | |
{ | |
plot(x,y,c); | |
s+=dx; | |
if(s>=dy){x--;s-=dy;} | |
} | |
} else | |
{ | |
for(s=dy;x>=x0;x--) | |
{ | |
plot(x,y,c); | |
s+=dy; | |
if(s>=dx){y++;s-=dx;} | |
} | |
} | |
break; | |
case DIR_LRBT: | |
dx=x1-x0; | |
dy=y0-y1; | |
if(dy>dx) | |
{ | |
for(s=dx;y>=y0;y--) | |
{ | |
plot(x,y,c); | |
s+=dx; | |
if(s>=dy){x++;s-=dy;} | |
} | |
} else | |
{ | |
for(s=dy;x<=x1;x++) | |
{ | |
plot(x,y,c); | |
s+=dy; | |
if(s>=dx){y--;s-=dx;} | |
} | |
} | |
break; | |
case DIR_RLBT: | |
dx=x0-x1; | |
dy=y0-y1; | |
if(dy>dx) | |
{ | |
for(s=dx;y>=y0;y--) | |
{ | |
plot(x,y,c); | |
s+=dx; | |
if(s>=dy){x--;s-=dy;} | |
} | |
} else | |
{ | |
for(s=dy;x>=x0;x--) | |
{ | |
plot(x,y,c); | |
s+=dy; | |
if(s>=dx){y--;s-=dx;} | |
} | |
} | |
break; | |
} | |
} | |
void bresenham_line(int x0, int y0, int x1, int y1, int c) | |
{ | |
int x,y,dx,dy,err,derr; | |
dx=abs(x1-x0); | |
dy=abs(y1-y0); | |
err=0; | |
derr=dy; | |
y=y0; | |
for(x=x0;x<=x1;x++) | |
{ | |
plot(x,y,c); | |
err+=derr; | |
if((2*err)>=dx){y--;err-=dx;} | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
bresenham_line(5, 17, 39, 3, '#'); | |
draw_line( 5, 20, 39, 6, '#'); | |
gotoxy(1,1); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment