#include <stdio.h>
#include <stdlib.h>
typedef struct
{
double x,y;
}Point;
double calc_determinant(Point p1,Point p2);
Point calc_vector(Point p0,Point p1);
// return a number : number < 0 concave, number > 0 convex, number = 0 if num_vertices < 3
int detect_polygon_type(const Point *p,const int num_vertices);
int main(int argc,char **argv)
{
int val;
Point poly1[4];//convex
Point poly2[4];//concave
poly1[0].x = -5.0; poly1[0].y = -5.0;
poly1[1].x = 5.0; poly1[1].y = -5.0;
poly1[2].x = 5.0; poly1[2].y = 5.0;
poly1[3].x = -5.0; poly1[3].y = 5.0;
poly2[0].x = -5.0; poly2[0].y = -5.0;
poly2[1].x = 5.0; poly2[1].y = -5.0;
poly2[2].x = 5.0; poly2[2].y = 5.0;
poly2[3].x = 1.0; poly2[3].y = 0.0;
val = detect_polygon_type(poly1,4);
printf("%i\n",val);
val = detect_polygon_type(poly2,4);
printf("%i\n",val);
return(EXIT_SUCCESS);
}
int detect_polygon_type(const Point *p,const int num_vertices)
{
Point v1,v2;
double det_value;
double cur_det_value;
int i;
if(num_vertices < 3)
{
return(0);
}
v1 = calc_vector(p[0],p[num_vertices-1]);
v2 = calc_vector(p[1],p[0]);
det_value = calc_determinant(v1,v2);
for(i = 1 ; i < num_vertices-1 ; i++)
{
v1 = v2;
v2 = calc_vector(p[i+1],p[i]);
cur_det_value = calc_determinant(v1,v2);
if( (cur_det_value * det_value) < 0.0 )
{
return(-1);
}
}
v1 = v2;
v2 = calc_vector(p[0],p[num_vertices-1]);
cur_det_value = calc_determinant(v1,v2);
if( (cur_det_value * det_value) < 0.0)
{
return(-1);
}
else
{
return(1);
}
}
double calc_determinant(Point p1,Point p2)
{
return (p1.x * p2.y - p1.y * p2.x);
}
Point calc_vector(Point p0,Point p1)
{
Point p;
p.x = p0.x - p1.x;
p.y = p0.y - p1.y;
return(p);
}