I actually need to draw horizontal and vertical lines in a game, so I was wondering how to do it the fastest way possible. Here''s the code I''m using for a horizontal line; see if you can work with it:
void HLine(int x1,int x2,int y,int color)
{
// adjust line position to map position
x1 = x1 - world_x;
x2 = x2 - world_x;
y = y - world_y;
// check if line is completely offscreen
if (x2 < 0 // x1 > 639 // y < 0 // y > 479)
return;
// clip to screen if necessary
x1 = ((x1 < 0) ? 0 : x1);
x2 = ((x2 > 639) ? 639 : x2);
// draw the row of pixels
memset((UCHAR *)(back_buffer+(y*back_lpitch)+x1),
(UCHAR)color,x2-x1+1);
} // end HLine
And the vertical line:
void VLine(int y1,int y2,int x,int color)
{
UCHAR *start_offset; // starting memory offset of line
int index; // loop index
// adjust line position to map position
x = x - world_x;
y1 = y1 - world_y;
y2 = y2 - world_y;
// check if line is completely offscreen
if (x < 0 // x > 639 // y2 < 0 // y1 > 479)
return;
// clip to screen if necessary
y1 = ((y1 < 0) ? 0 : y1);
y2 = ((y2 > 479) ? 479 : y2);
// compute starting position
start_offset = back_buffer + (y1*back_lpitch) + x;
// draw line one pixel at a time
for (index=0; index<=y2-y1; index++)
{
// set the pixel
*start_offset = (UCHAR)color;
// advance to next line
start_offset+=back_lpitch;
}
} // end VLine
Of course I have to lock the back buffer before calling these functions, which takes precious time itself. I wish I didn''t have to do that, but oh well, what can you do? Anyway, the slowest parts I can see in my code are the memory copies (and probably the function calls), and this is especially true for the vertical line. Clipping also makes it a tad slower, but I have to use clipping. I''m sure inline assembly would make it faster, but that''s not an option since I don''t know crap about assembly. Maybe someone could me help out? I''d appreciate any suggestions.
Thanks,
Al