I'm using the below function to draw a line that uses the Bresenham's algorithm copied code from "256-Color VGA Programming in C" tutorial.

My problems are that when plotting a straight line the first pixel isn't plotted and when drawing diagonal lines they aren't straight.

The program is to use a resolution of 640x480x16.

Thank you for your help.

Code:

void line(SDL_Surface *screen, int x1, int y1, int x2, int y2, Uint8 R, Uint8 G, Uint8 B)
{
int i,dx,dy,sdx,sdy,dxabs,dyabs,x,y,px,py;
dx=x2-x1; /* the horizontal distance of the line */
dy=y2-y1; /* the vertical distance of the line */
dxabs=abs(dx);
dyabs=abs(dy);
sdx=sgn(dx);
sdy=sgn(dy);
x=dyabs>>1;
y=dxabs>>1;
px=x1;
py=y1;
// VGA[(py<<8)+(py<<6)+px]=color;
DrawPixel(screen, py<<8, py<<6, R, G, B);
if (dxabs>=dyabs) /* the line is more horizontal than vertical */
{
for(i=0;i<dxabs;i++)
{
y+=dyabs;
if (y>=dxabs)
{
y-=dxabs;
py+=sdy;
}
px+=sdx;
DrawPixel(screen, px, py, R, G, B);
}
}
else /* the line is more vertical than horizontal */
{
for(i=0;i<dyabs;i++)
{
x+=dxabs;
if (x>=dyabs)
{
x-=dyabs;
px+=sdx;
}
py+=sdy;
DrawPixel(screen, px, py, R, G, B);
}
}
}