I am starting to work on a basic 3D renderer for fun, so right now I have made a triangle fill function to be used when I draw faces on models:
public void fillTriangle(Triangle2d t, Color color) {
// triangle points are already sorted
Line2d ab = t.getAB(), bc = t.getBC(), ac = t.getAC();
Line2d leftEdge = ab.getEnd().getX() < ac.getEnd().getX() ? ab : ac;
Line2d rightEdge = ab.getEnd().getX() > ac.getEnd().getX() ? ab : ac;
Line2d bottomEdge = bc;
// horizontal lines
int startY = (int) t.getA().getY(), endY = (int) t.getC().getY();
for (int y = startY; y <= endY; y++) {
int startX, endX = (int) rightEdge.getX(y);
// we are now below the middle (vertically) point, so to avoid going past the bottom edge,
// we use it to get the startX
if (y > leftEdge.getEnd().getY())
startX = (int) bottomEdge.getX(y);
else
startX = (int) leftEdge.getX(y);
for (int x = startX; x <= endX; x++)
set(x, y, color);
}
set((int) t.getA().getX(), (int) t.getA().getY(), Color.RED);
set((int) t.getB().getX(), (int) t.getB().getY(), Color.RED);
set((int) t.getC().getX(), (int) t.getC().getY(), Color.RED);
}
set
sets a pixel to a specific colorTriangle2d
's points are already sorted vertically, soA
is aboveB
andB
is aboveC
(unless they have equaly
-values)Triangle2d#getAB
returns a line going from the first point,A
to the second pointB
Line2d#getX
returns theX
-value for a givenY
-value (and likewise forLine2d#getY
)
The idea is that I draw horizontal lines going from the top to the bottom.