Function InOrOut(p, q, k, p0, q0) As Integer
'Function to determine the position of point (p0,q0) relative
'to the closed contour defined by the n points with
'coordinates p(i), q(i), i=1, 2, ..., k
'
'Point 1 must be the same as point k
'Returned function values():
' 1: point is inside the contour
' -1: point is outside the contour
' 0: point lies on the contour border
'*********************************************************************
Dim kross As Integer, i As Integer
Dim pp As Single
'Function initialization
InOrOut = 0
'Initialization of kross, a variable which keeps track
'of how many times the horizontal semi-infinite straight
'line starting at (p0,q0) and in the positive (right hand side)
'x axis direction intercepts the contour
'(The contour may have vertices with angles larger than 180 degrees)
kross = 0
'Loop over all contour sides
For i = 1 To k - 1
'If the side between the i and i+1 vertices lies entirely above
'or below the point (p0,q0), skip it (there is no intercept)
If (q(i) > q0 And q(i + 1) > q0) Or (q(i) < q0 And q(i + 1) < q0) Then GoTo NextItem
'If the side is horizontal avoid the calculation of the intercept by interpolation
'as there would be a division by zero
If q(i) = q(i + 1) Then
'It has to be determined if the point (p0,q0) lies on this horizontal segment
If (p(i) > p0 And p(i + 1) > p0) Or (p(i) < p0 And p(i + 1) < p0) Then GoTo NextItem
'If it doesn't, we're done!
Exit Function
End If
'Calculation of pp, the coordinate of the point where the segment connecting the
'sides i and i+1 and the horizontal straight line that goes through (p0,q0) intercept
pp = p(i) + (q0 - q(i)) * ((p(i + 1) - p(i)) / (q(i + 1) - q(i)))
'The sign of pp-p0 determines the position of the intercept relative to (p0,q0)
If pp - p0 > 0 Then
'Intercept to the right: increment counter (but only if the intercept does not lie
'on the first vertex, to avoid counting the same intercept twice!)
If q0 <> q(i) Then kross = kross + 1
ElseIf pp - p0 = 0 Then
Exit Function
End If
'If the intercept lies to the left, take no action and continue on
NextItem:
Next
'If the number of intercepts is even, the point (p0,q0) lies out of the contour
'If it's odd then it lies inside
If kross Mod 2 = 0 Then
InOrOut = -1
Else
InOrOut = 1
End If
End Function