int shape::intersect(Vec2d* _otherShapePoints, long _otherNumPoints, int _thisCurrentPoint){ // gets passed the third point to start
// new line just being drawn this happens once
Vec2d P0a( this->pointList[_thisCurrentPoint-1].x, this->pointList[_thisCurrentPoint-1].y ); //gets point minus one position
Vec2d P0b( this->pointList[_thisCurrentPoint].x, this->pointList[_thisCurrentPoint].y ); // gets point
float M0 = ( P0b.y - P0a.y ) / ( P0b.x - P0a.x ); //slope of test line the one just being drawn
float X, Y; //equation variables
// check from first line through third last line of every existing line in shape
Vec2d P1a, P1b; // new point
for( int i=0;i<_otherNumPoints-2;i++ ) { // checks from first point to current point
P1a = _otherShapePoints[i]; // for each makes line segment from point P1a to P1b
P1b = _otherShapePoints[i+1];
// check if the intersection is within line segment boundaries of the two segments
float left0 = helpers::min( P0a.x, P0b.x ); // takes first line segment sees which is left boundry
float right0 = helpers::max( P0a.x, P0b.x ); // right
float left1 = helpers::min( P1a.x, P1b.x ); // takes current segment to be checked from for loop starting with first seg of pointarray
float right1 = helpers:: max( P1a.x, P1b.x );// right
float M1 = ( P1b.y - P1a.y ) / ( P1b.x - P1a.x ); //slope of old line segments
if ( M0 != M1 ) {// if slopes are different they must cross somewhere
X = ( P1a.y - P0a.y - P1a.x * M1 + P0a.x * M0 ) / ( M0 - M1 ); //y=mx+b for both they must cross somewhere so y=mx+b = y1=m1x1+b solve for x
Y = P0a.y + ( X - P0a.x) * M0; // plug in x
// if it does intersect
if ( X > left0 && X < right0 && X > left1 && X < right1 ) { // if the intercept point is in between the two segments we are looking at it is crossing
//numPoints = 0; // for debugging
for (int h=0; h< numIntersects; h++){// look at all intercept points
if ((intersects[h].x +1 >= X && X>= intersects[h].x -1) && (intersects[h].y +1 >= Y && Y >= intersects[h].y -1)){ // if already found don't add it give a buffer for no double trouble
return -1;
}
}
//else add put into array
int k = numIntersects;// be sure to give the realloc size
k = k + 1;
intersects = (Vec2d*) realloc( intersects, sizeof(Vec2d)*k );// variable array gets memory space according to size of
intersectPoint = Vec2d ( X,Y ); // store the intersection
intersects[numIntersects] = intersectPoint;
numIntersects++; //increment intersects
//debug
printf( "%f %f point\n",X,Y);
printf( "%d num of inter\n",numIntersects);
return i; // return the intersected line
}
}
}