Created
August 14, 2017 08:59
-
-
Save msmshazan/2348155d4a62e01850da631a08f497d7 to your computer and use it in GitHub Desktop.
Triangle Raster Function
This file contains hidden or 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
void DrawTriangleTextured(SDL_Surface *Buffer,SDL_Surface *Texture,float * Zbuffer, vec3 *Points,vec2 *UV,float* Intensity) { | |
Uint32 Rshift = 16, Gshift =8, Bshift = 0, Ashift=24; | |
vec2 BBoxmin = {}; | |
vec2 BBoxmax = {}; | |
// Compute triangle bounding box | |
BBoxmin.X = MIN(MIN(Points[0].X, Points[1].X), Points[2].X); | |
BBoxmin.Y = MIN(MIN(Points[0].Y, Points[1].Y), Points[2].Y); | |
BBoxmax.X = MAX(MAX(Points[0].X, Points[1].X), Points[2].X); | |
BBoxmax.Y = MAX(MAX(Points[0].Y, Points[1].Y), Points[2].Y); | |
// Clip against screen bounds | |
BBoxmin.X = MAX(BBoxmin.X, 0); | |
BBoxmin.Y = MAX(BBoxmin.Y, 0); | |
BBoxmax.X = MIN(BBoxmax.X, Buffer->w - 1); | |
BBoxmax.Y = MIN(BBoxmax.Y, Buffer->h - 1); | |
vec3 P= {}; | |
for (P.X=BBoxmin.X; P.X<=BBoxmax.X; P.X++) { | |
for (P.Y=BBoxmin.Y; P.Y<=BBoxmax.Y; P.Y++) { | |
vec3 BarycentricPos = GetBarycentric(Points[0],Points[1],Points[2], P); | |
if (BarycentricPos.X<0 || BarycentricPos.Y<0 || BarycentricPos.Z<0) continue; | |
P.Z = 0; | |
for (int i=0; i<3; i++){ | |
P.Z += Points[i].Elements[2]*BarycentricPos.Elements[i]; | |
} | |
//Interpolating UV to get color | |
vec2 UVP = {}; | |
UVP.X = BarycentricPos.X * UV[0].X + BarycentricPos.Y * UV[1].X + BarycentricPos.Z * UV[2].X; | |
UVP.Y = BarycentricPos.X * UV[0].Y + BarycentricPos.Y * UV[1].Y + BarycentricPos.Z * UV[2].Y; | |
//Interpolating Intensity to get light | |
float iP = BarycentricPos.X * Intensity[0] + BarycentricPos.Y * Intensity[1] + BarycentricPos.Z * Intensity[2]; | |
if(Zbuffer[int(P.X+P.Y*Buffer->w)]<P.Z){ | |
Zbuffer[int(P.X+P.Y*Buffer->w)] = P.Z; | |
Uint8 *Pix = (Uint8 *) Texture->pixels + (int)((UVP.Y)*Texture->h) * Texture->pitch + | |
((int)((1-UVP.X)*Texture->w) )* 4; | |
// Write to Pixel in buffer | |
Uint32 Pixel = *(Uint32 *)Pix; | |
float r = (float)((Pixel & 0x00FF0000) >> Rshift) / 255; | |
float g = (float)((Pixel & 0x0000FF00) >> Gshift) / 255; | |
float b = (float)((Pixel & 0x000000FF) >> Bshift) / 255; | |
float a = (float)((Pixel & 0xFF000000) >> Ashift) / 255; | |
DrawPixel(Buffer,P.X, P.Y, r*iP,g*iP,b*iP); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment