Code:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#define TRUE 1
#define FALSE 0
struct wcpt3{
float x,y,z;
}nan;
struct plane{
float A,B,C,D;
};
int get_coeff(wcpt3 pt1
,wcpt3 pt2,wcpt3 pt3)
{
plane temp;
temp.A=(pt2.z-pt3.z)*(pt1.y-pt2.y)-(pt1.z-pt2.z)*(pt2.y-pt3.y);
temp.B=(pt2.x-pt3.x)*(pt1.z-pt2.z)-(pt1.x-pt2.x)*(pt2.z-pt3.z);
temp.C=(pt2.y-pt3.y)*(pt1.x-pt2.x)-(pt1.y-pt2.y)*(pt2.x-pt3.x);
temp.D=-pt1.x*(pt2.y*pt3.z-pt2.z*pt3.y)+pt1.y*(pt2.x*pt3.z-pt2.z*pt3.x)-pt1.z*(pt2.x*pt3.y-pt2.y*pt3.x);
return temp;
}
float depth(plane surface, float x, float y)
{
float z=0;
if(surface.C!=0)
z=(-surface.A*x-surface.B*y-surface.D)/surface.C;
return Z;
}
int side_check(wcpt3 ptA, wcpt3 ptB, wcpt3 ptC, float X,float y)
{
float fxyC,fxy;
fxyC=ptC.x*(ptA.y-ptB.y)-ptC.y*(ptA.x-ptB.x)-ptA.x*(ptA.y*ptB.y)+ptA.y*(ptA.x-ptB.x);
fxy=x*(ptA.y-ptB.y)-y*(ptA.x-ptB.x)-ptA.x*(ptA.y-ptB.y)+ptA.y*(ptA.x-ptB.x);
if((fxyC<0)&&(fxy<0))||((fxyC>0)&&(fxy>0)))
return TRUE;
else
return FALSE;
}
int inside_triangle_check(wcpt3 pt1,wcpt3 pt2, wcpt3 pt3,flat x,float y)
{
int check=side_check(pt1,pt2,pt3,x,y)&&side_check(pt2,pt3,pt1,x,y)&&side_check(pt3,pt1,pt2,x,y);
if(check==TRUE)
return TRUE;
else
return FALSE;
}
void main(void)
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"");
wcpt3 ptA,ptB,ptC,ptD;
plane surface[10];
int clr_background=BLACK,clr,numsurf,colorxy[4],surf_clr[10];
float depth_background=0,depthxy[4],x,y,z;
ptA.x=200; ptA.y=200; ptA.z=200;
ptB.x=600; ptB.y=200; ptB.z=200;
ptC.x=400; ptC.y=200; ptC.z=600;
ptD.x=400; ptD.y=400; ptD.z=400;
surface[0]=get_coeff(ptA,ptC,ptD);
surf_clr[0]=BLUE;
surface[1]=get_coeff(ptC,ptB,ptD);
surf_clr[1]=GREEN;
surface[2]=get_coeff(ptB,ptA,ptD);
surf_clr[2]=CYAN;
surface[3]=get_coeff(ptA,ptC,ptB);
surf_clr[3]=RED;
for(x= 0;x<getmaxy();x++)
{
for(numsurf=0; numsurf<4;numsurf++)
{
depth[numsurf]=depth_background;
colorxy[numsurf]=clr_background;
}
if(inside_triangle_check(ptA,ptC,ptD,x,y)==TRUE)
depthxy[0]=depth(surface[0],x,y);
if(inside_triangle_check(ptC,ptB,ptD,x,y)==TRUE)
depthxy[1]=depth(surface[1],x,y);
if(inside_triangle_check(ptA,ptB,ptD,x,y)==TRUE)
depthxy[2]=depth(surface[2],x,y);
if(inside_triangle_check(ptA,ptc,ptB,x,y)==TRUE;
depthxy[3]=depth(surface[3]x,y);
z=depth_background;
clr=clr_background;
for(numsurf=0;numsurf<4;numsurf++)
{
if(deprhxy[numsurf]>z)
{
z=depthxy[numsurf];
clr=surf_clr[numsurf];
}
}
putpixel(x,y,clr);
}
getch();
}
With regards,