我试图使用软件渲染绘制一个立方体。所以我用三角形绘制了一个立方体。所以我渲染一个实心三角形。立方体成功渲染,但旋转时闪烁。
这是我的实心三角形填充,有人会注意算法中的问题吗?
void Rasterizer::DrawSolidTriangle(int x0, int y0, int x1, int y1, int x2, int y2, Color&color)
{
// Sort our points into order of y
// 0 top
// 2 middle
// 1 bottom
if (y1 < y0)
{
swap(y1, y0);
swap(x1, x0);
}
if (y2 < y0)
{
swap(y2, y0);
swap(x2, x0);
}
if (y1 < y2)
{
swap(y2, y1);
swap(x2, x1);
}
float xl_edge = (float)x0; // left edge
float xr_edge = (float)x0; // right edge
float dxldy;
float dxrdy;
float dxdy1 = (float)(x2 - x0) / (y2 - y0);
float dxdy2 = (float)(x1 - x0) / (y1 - y0);
if (dxdy1 < dxdy2)
{
dxldy = dxdy1;
dxrdy = dxdy2;
}
else
{
dxldy = dxdy2;
dxrdy = dxdy1;
}
// Top of the triangle
for (int y = y0; y<y2; y++)
{
for (int x = xl_edge; x<xr_edge; x++)
{
SetPixel((unsigned int)x, (unsigned int)y, color);
}//end for loop x
xl_edge = xl_edge + dxldy;
xr_edge = xr_edge + dxrdy;
}// end for loop y
// Bottom half of the triangle
if (dxdy1 < dxdy2)
{
dxldy = (float)(x2 - x1) / (y2 - y1);
}
else
{
dxrdy = (float)(x2 - x1) / (y2 - y1);
}
for (int y = y2; y<y1; y++)
{
for (int x = xl_edge; x<xr_edge; x++)
{
SetPixel((unsigned int)x, (unsigned int)y, color);
}//end for loop x
xl_edge = xl_edge + dxldy;
xr_edge = xr_edge + dxrdy;
}// end for loop y
}
这是问题的截图,当旋转立方体这么慢时它会出现在这里: