I’m writing a 3D software renderer. Here is the code that does the rendering: Vec3f…
- User
I’m writing a 3D software renderer. Here is the code that does the rendering:
Vec3f barycentric(const std::array<Vec3f, 3> pts, const Vec3f& p) { const auto [a, b, c] = pts;
const Vec3f ab = b - a; const Vec3f ac = c - a; const Vec3f ap = p - a;
const float area = cross(ab, ac).z; const float v = cross(ap, ac).z / area; const float w = cross(ab, ap).z / area; const float u = 1.0F - v - w;
return {u, v, w}; }
void triangle(const Vec4f vertices[3], const Vec2f texture_coords[3], Shader& shader, TGAImage& zbuffer, TGAImage& image) { Vec2f bbox_min{std::numeric_limits::max(), std::numeric_limits::max()}; Vec2f bbox_max{-std::numeric_limits::max(), -std::numeric_limits::max()};
for (int i = 0; i < 3; ++i) { for (int j = 0; j < 2; ++j) { bbox_min[j] = std::min(bbox_min[j], vertices[i][j] / vertices[i][3]); bbox_max[j] = std::max(bbox_max[j], vertices[i][j] / vertices[i][3]); } }
Vec3f p; for (p.x = bbox_min.x; p.x <= bbox_max.x; ++p.x) { for (p.y = bbox_min.y; p.y <= bbox_max.y; ++p.y) { Vec3f bc = barycentric({proj<3>(vertices[0] / vertices[0][3]), proj<3>(vertices[1] / vertices[1][3]), proj<3>(vertices[2] / vertices[2][3])}, p); if (bc.x < 0 || bc.y < 0 || bc.z < 0 || bc.x + bc.y + bc.z != 1) { continue; }
const float z = vertices[0][2] * bc.x + vertices[1][2] * bc.y + vertices[2][2] * bc.z;
const float w = vertices[0][3] * bc.x + vertices[1][3] * bc.y + vertices[2][3] * bc.z;
const int depth = std::max(0, std::min(255, int(z / w + 0.5)));
if (zbuffer.get(p.y, p.x)[0] < depth) { zbuffer.set(p.y, p.x, TGAColor(depth));
auto tc = (texture_coords[0] * bc.x) + (texture_coords[1] * bc.y) + (texture_coords[2] * bc.z);
auto color = shader.fragment(bc, tc);
image.set(p.x, p.y, color); } } } }
For some reason, the model that is rendered, seems to have small holes in it. As in, it’s not a completely smooth textured model, but it has some black lines between some vertices. What could cause this?
- Assistant
There could be several reasons for the small holes in the rendered model:
-
Backface Culling: The renderer might be incorrectly culling some triangles that should be visible. Backface culling is a technique used to improve rendering performance by discarding triangles that are facing away from the camera. If the triangles are not properly culled, it can result in holes in the rendered model.
-