How to determine whether a point lies inside a 2D triangle in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

/*
    Simple 2D point structure
*/
typedef struct {
    float x;
    float y;
} Point;

/*
    edge_orientation(p1, p2, p3)
    --------------------------------
    Computes the 2D cross product:

        (p1 - p3) × (p2 - p3)

    The sign of this value tells us whether p1 lies to the left or right
    of the directed edge p3 → p2.

    This is the core of the "same-side" triangle test.
*/
float edge_orientation(Point p1, Point p2, Point p3) {
    return (p1.x - p3.x) * (p2.y - p3.y)
         - (p2.x - p3.x) * (p1.y - p3.y);
}

/*
    point_in_triangle(pt, v1, v2, v3)
    -----------------------------------
    Uses the same-side method:

    A point is inside the triangle if it lies on the same side of all
    three edges. If the signs of the three cross products are all
    non-negative or all non-positive, the point is inside or on the edge.

    If the signs mix (some positive, some negative), the point is outside.
*/
bool point_in_triangle(Point pt, Point v1, Point v2, Point v3) {
    float d1 = edge_orientation(pt, v1, v2);
    float d2 = edge_orientation(pt, v2, v3);
    float d3 = edge_orientation(pt, v3, v1);

    bool has_negative = (d1 < 0.0f) || (d2 < 0.0f) || (d3 < 0.0f);
    bool has_positive = (d1 > 0.0f) || (d2 > 0.0f) || (d3 > 0.0f);

    /* Inside if NOT both negative and positive signs */
    return !(has_negative && has_positive);
}

int main(void) {
    /* Triangle vertices */
    Point A = {0.0f, 0.0f};
    Point B = {5.0f, 0.0f};
    Point C = {2.5f, 5.0f};

    /* Test point */
    Point P = {2.5f, 2.0f};

    bool inside = point_in_triangle(P, A, B, C);

    printf("Point (%.2f, %.2f) is %s the triangle.\n",
           P.x, P.y, inside ? "inside" : "outside");

    return 0;
}


/*
run:

Point (2.50, 2.00) is inside the triangle.

*/

 



answered Jul 31 by avibootz
...