Search code examples
algorithmmathgeometry2dcomputational-geometry

Getting a list of locations within a triangle in the form of x,y positions


Let's say I have a triangle given by the three integer vertices (x1,y1), (x2,y2) and (x3,y3). What sort of algorithm can I use to return a comprehensive list of ALL (x,y) integer pairs that lie inside the triangle.


Solution

  • The following algorithm should be appropriate:

    1. Sort the triangle vertices by x coordinate in increasing order. Now we have two segments (1-2 and 2-3) on the one side (top or bottom), and one segment from the other one (1-3).

    2. Compute coefficients of equations of lines (which contain the segments):

      A * x + B * y + C = 0
      A = y2 - y1
      B = x1 - x2
      C = x2 * y1 - x1 * y2
      

      There (x1, y1) and (x2, y2) are two points of the line.

    3. For each of ranges [x1, x2), (x2, x3], and x2 (special case) iterate over integer points in ranges and do the following for every x:

      1. Find top bound as y_top = (- A1 * x - C1) div B1.
      2. Find bottom bound as y_bottom = (- A2 * y - C2 - 1) div B2 + 1.
      3. Add all points between (x, y_bottom) and (x, y_top) to the result.

    This algorithm is for not strictly internal vertices. For strictly internal vertices items 3.1 and 3.2 slightly differ.