bool splitPolygonEdge( Vertices polygon, Vector2 coordInsideThePolygon, out int vertex1Index, out int vertex2Index )
{
Vector2 slope;
int nearestEdgeVertex1Index = 0;
int nearestEdgeVertex2Index = 0;
bool edgeFound = false;
float shortestDistance = float.MaxValue;
bool edgeCoordFound = false;
Vector2 foundEdgeCoord = Vector2.Zero;
List<float> xCoords = searchCrossingEdges( polygon, (int)coordInsideThePolygon.Y );
vertex1Index = 0;
vertex2Index = 0;
foundEdgeCoord.Y = coordInsideThePolygon.Y;
if( xCoords != null && xCoords.Count > 1 && xCoords.Count % 2 == 0 )
{
float distance;
for( int i = 0; i < xCoords.Count; i++ )
{
if( xCoords[i] < coordInsideThePolygon.X )
{
distance = coordInsideThePolygon.X - xCoords[i];
if( distance < shortestDistance )
{
shortestDistance = distance;
foundEdgeCoord.X = xCoords[i];
edgeCoordFound = true;
}
}
}
if( edgeCoordFound )
{
shortestDistance = float.MaxValue;
int edgeVertex2Index = polygon.Count - 1;
int edgeVertex1Index;
for( edgeVertex1Index = 0; edgeVertex1Index < polygon.Count; edgeVertex1Index++ )
{
Vector2 tempVector1 = polygon[edgeVertex1Index];
Vector2 tempVector2 = polygon[edgeVertex2Index];
distance = LineTools.distanceBetweenPointAndLineSegment( ref foundEdgeCoord,
ref tempVector1, ref tempVector2 );
if( distance < shortestDistance )
{
shortestDistance = distance;
nearestEdgeVertex1Index = edgeVertex1Index;
nearestEdgeVertex2Index = edgeVertex2Index;
edgeFound = true;
}
edgeVertex2Index = edgeVertex1Index;
}
if( edgeFound )
{
slope = polygon[nearestEdgeVertex2Index] - polygon[nearestEdgeVertex1Index];
slope.Normalize();
Vector2 tempVector = polygon[nearestEdgeVertex1Index];
distance = Vector2.Distance( tempVector, foundEdgeCoord );
vertex1Index = nearestEdgeVertex1Index;
vertex2Index = nearestEdgeVertex1Index + 1;
polygon.Insert( nearestEdgeVertex1Index, distance * slope + polygon[vertex1Index] );
polygon.Insert( nearestEdgeVertex1Index, distance * slope + polygon[vertex2Index] );
return true;
}
}
}
return false;
}