1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#define INSIDE_TRIANGLE 0
#define INCREMENT 1
// Scale triangle
void ScaleTriangle(triangle_t *triangle)
{
triangle->scale = 1.0;
triangle->sx1 = triangle->x1 * triangle->scale;
triangle->sx2 = triangle->x2 * triangle->scale;
triangle->sx3 = triangle->x3 * triangle->scale;
triangle->sy1 = triangle->y1 * triangle->scale;
triangle->sy2 = triangle->y2 * triangle->scale;
triangle->sy3 = triangle->y3 * triangle->scale;
}
// Move triangle to its screen position
void TranslateTriangle(triangle_t *triangle)
{
triangle->sx1 += triangle->tx;
triangle->sx2 += triangle->tx;
triangle->sx3 += triangle->tx;
triangle->sy1 += triangle->ty;
triangle->sy2 += triangle->ty;
triangle->sy3 += triangle->ty;
}
// Calculate triangle bounding box
void CalculateTriangleBoundingBox(triangle_t *triangle)
{
triangle->bx = min(triangle->sx1, triangle->sx2, triangle->sx3);
triangle->by = min(triangle->sy1, triangle->sy2, triangle->sy3);
triangle->bw = max(triangle->sx1, triangle->sx2, triangle->sx3);
triangle->bh = max(triangle->sy1, triangle->sy2, triangle->sy3);
}
// Fill triangle with a color
void FillTriangle(SDL_Surface *screen, triangle_t *triangle)
{
int i, j, start, stop, step;
for(i = triangle->bx; i <= triangle->bw; i++){
step = INSIDE_TRIANGLE;
for (j = triangle->by; j <= triangle->bh; j++){
if (GetPixel(screen, i, j) == TRIANGLE_PENCOLOR && step == INSIDE_TRIANGLE){
start = stop = j;
step = INCREMENT;
}
if (GetPixel(screen, i, j) == TRIANGLE_PENCOLOR && step == INCREMENT){
stop = j;
}
}
DrawLine(screen, i, start, i, stop, triangle->fillcolor);
}
}
// Draw triangle on screen
void DrawTriangle(SDL_Surface *screen, triangle_t *triangle)
{
int isOK;
// Scale.
ScaleTriangle(triangle);
// Translate.
triangle->tx = screen->w/2;
triangle->ty = screen->h/2;
TranslateTriangle(triangle);
// Determine bounding box
CalculateTriangleBoundingBox(triangle);
// Sanity check that triangle is within screen boundaries.
isOK = SanityCheckTriangle(screen, triangle);
if (isOK == 0) {
PrintTriangle(triangle, "Triangle outside screen boundaries");
return;
}
//3 DrawLine functions to draw the distinct outline of the triangle in the color Red.
DrawLine(screen, triangle->sx1, triangle->sy1, triangle->sx2, triangle->sy2, TRIANGLE_PENCOLOR);
DrawLine(screen, triangle->sx1, triangle->sy1, triangle->sx3, triangle->sy3, TRIANGLE_PENCOLOR);
DrawLine(screen, triangle->sx2, triangle->sy2, triangle->sx3, triangle->sy3, TRIANGLE_PENCOLOR);
// Fill triangle
FillTriangle(screen, triangle);
// Force screen update.
SDL_UpdateRect(screen, triangle->bx, triangle->by, triangle->bw, triangle->bh);
}
|