2

I am trying to make triangle rasterization work, and it does not work properly (second link is image). I don't want to use any engines or libraries because I want to practice this a little bit.

This is the page where I got functions from:

The shape on top is the one I get using my functions and the second one is what I get when I use java.awt.Graphics.fillPolygon() method - or what it should look like:

img

I didn't include FillBottomTriangle and FillTopTriangle functions in code because they are copy-pasted from the site (first link). Also, I know code can be optimized, but this was only done to test if it works.

// This is not the entire while-true-loop, only part needed for this question
// This sorts points by their Y value since that's how rasterizing code works
for (int j = 0; j < 2; j++) {
    for (int k = 0; k < 2; k++) {
        if (fpoints[k][1] > fpoints[k + 1][1]) {

            int[] r = fpoints[k];
            fpoints[k] = fpoints[k + 1];
            fpoints[k + 1] = r;

         }
     }
 }

 // DRAW TRIANGLE
 if (fpoints[1][1] == fpoints[2][1]) FillBottomTriangle(g, fpoints[0], fpoints[1], fpoints[2]);
 else if (fpoints[0][1] == fpoints[1][1]) FillTopTriangle(g, fpoints[0], fpoints[1], fpoints[2]);
 else {
     int[] v4 = new int[] {
         (int)(fpoints[0][0] + ((float)(fpoints[1][1] - fpoints[0][1]) / (float)(fpoints[2][1] - fpoints[0][1])) * (fpoints[2][0] - fpoints[0][0])),
                        fpoints[1][1]
                };
     FillBottomTriangle(g, fpoints[0], fpoints[1], v4);
     FillTopTriangle(g, fpoints[1], v4, fpoints[2]);
 }

 Polygon poly = new Polygon();
 for (int j = 0; j < fpoints.length; j++) {
     poly.addPoint(fpoints[j][0], fpoints[j][1] + 128);
 }
 g.fillPolygon(poly);

Thank you.

EDIT: fpoints[n] is the point and fpoints[n][m] is the coordinate, i.e. fpoints[2][0] is X coordinate of point C of triangle.

Spektre
  • 49,595
  • 11
  • 110
  • 380
alant7_
  • 43
  • 6
  • Have you checked if the coordinates for the fourth vertex `v4` are computed correctly? If they are, the error is either in how parameters are passed to `FillTop/BottomTriangle` or in those functions themselves – Joni Jun 27 '20 at 19:41
  • To me it seems that your `FillBottomTriangle` is not modifying `curx2`, changing the right slope into a vertical line. – Thomas Kläger Jun 28 '20 at 06:44
  • weird way of rasterizing... I am using this [Algorithm to fill triangle](https://stackoverflow.com/a/39062479/2521214) in the first link there is the explanation. It works on any convex polygon and uses just integer math. This was the most commonly used algo back in the days of SW rendering. Nowadays massively parallel GPUs are using barycetric interpolation along with pixel inside test instead. – Spektre Jul 04 '20 at 09:16

0 Answers0