I came up with some code to check if a point is within a line. The problem with it is that it is going to be too slow as it will be called for each pixel of a rectangular area encompasing a polygon. I'm sure there must be a faster way to go about this. Anyway heres what I got:
Code:
#include <stdio.h>
int PointIsOnLine(int x1, int y1, int x2, int y2, int x3, int y3)
{
if(x1 == x2 && y1 == y2) //Not a line
return -1;
if(x1 == x2) //No gradient
return (y3 == y1)? 1: 0;
if(y1 == y2) //Infinite gradient
return (x3 == x1)? 1: 0;
double gradient = (y2 - y1) / (x2 - x1);
//Line axis intercept
double y01 = y1 - (x1 * gradient);
double x01 = x1 - (y1 / gradient);
//Test point axis intercept
double y02 = y3 - (x3 * gradient);
double x02 = x3 - (y3 / gradient);
//If intercepts are the same then point is on line
int y0 = ((int)(y02+0.5))-((int)(y01+0.5));
int x0 = ((int)(x02+0.5))-((int)(x01+0.5));
return (y0 || x0)? 0: 1;
}
int PointIsWithinLine(int x1, int y1, int x2, int y2, int x3, int y3)
{
int result = PointIsOnLine(x1, y1, x2, y2, x3, y3);
if(! result) return 0;
int lo_x = (x1 < x2)? x1: x2;
int hi_x = (x1 > x2)? x1: x2;
int lo_y = (y1 < y2)? y1: y2;
int hi_y = (y1 > y2)? y1: y2;
if(x3 < lo_x) return 0;
if(x3 > hi_x) return 0;
if(y3 < lo_y) return 0;
if(y3 > hi_y) return 0;
return 1;
}
int main()
{
int result = PointIsWithinLine(20, 60, 00, 00, 2, 6);
if(result == 1)
printf("Point is on line\n");
else if(result == 0)
printf("Point is not on line\n");
else
printf("Not a line\n");
return 0;
}
Any suggestions would be appreciated. Cheers.