I believe I did not write those functions. LOL
Here's a very fast point inside triangle which would work in 3d and 2d (Just set z = 0 for a 2d test):
sub vector_cross (BYVAL v1 as vector3d, BYVAL v2 as vector3d, BYREF vout as vector3d)
vout.x = (v1.y * v2.z) - (v2.y * v1.z)
vout.y = (v1.z * v2.x) - (v2.z * v1.x)
vout.z = (v1.x * v2.y) - (v2.x * v1.y)
end sub
function SameSide(p1 as vector3d,p2 as vector3d, a as vector3d,b as vector3d)
' cp1
' /
' /
' /\ angle(theta)
' / /
' --------- cp2
' angle should be 0<angle<90 to be on the same side
' of the triangle. Because: cos(a<90) = +; cos(a=90) = 0; cos(a>90) = -.
' So we only check for the dot between the 2 vectors as dot/(mag1*mag2)
' = cos(a). No need for divide because we only check for sign. :*)
' Nifty huh? Blackpawn rules!!!
dim cp1 as vector3d, cp2 as vector3d
dim ba as vector3d, p1a as vector3d, p2a as vector3d
ba.x = b.x - a.x
ba.y = b.y - a.y
ba.z = b.z - a.z
p1a.x = p1.x - a.x
p1a.y = p1.y - a.y
p1a.z = p1.z - a.z
p2a.x = p2.x - a.x
p2a.y = p2.y - a.y
p2a.z = p2.z - a.z
vector_cross cp1, ba, p1a
vector_cross cp2, ba, p2a
dim dot as single
dot = vector_dot ( cp1, cp2 )
if dot >=0 then
sameside = TRUE
else
sameside = FALSE
end if
end function
function point_in_triangle(p as vector3d, a as vector3d,b as vector3d,c as vector3d)
if SameSide(p,a, b,c) and SameSide(p,b, a,c) and SameSide(p,c, a,b) then
collide3d_point_in_triangle = TRUE
else
collide3d_point_in_triangle = FALSE
end if
end function
For a straight 2d test you could read up back2basic since I have an inside poly demo there (The zooming demo).
An all integer flat triangle routine in just plain old FB code:
sub Rel_Tri_F( byval x1 as integer, byval y1 as integer,_
byval x2 as integer, byval y2 as integer,_
byval x3 as integer,byval y3 as integer, byval col as integer)
dim dx1 as integer, dy1 as integer
dim dx2 as integer, dy2 as integer
dim dx3 as integer, dy3 as integer
dim delta1 as integer, delta2 as integer, delta3 as integer
dim Lx as integer, Rx as integer
dim p_buffer as integer ptr
IF y2 < y1 THEN
SWAP y1, y2
SWAP x1, x2
END IF
IF y3 < y1 THEN
SWAP y3, y1
SWAP x3, x1
END IF
IF y3 < y2 THEN
SWAP y3, y2
SWAP x3, x2
END IF
dx1 = x2 - x1
dy1 = y2 - y1
IF dy1 <> 0 THEN
delta1 = (dx1 shl 16) \ dy1
ELSE
delta1 = 0
END IF
dx2 = x3 - x2
dy2 = y3 - y2
IF dy2 <> 0 THEN
delta2 = (dx2 shl 16) \ dy2
ELSE
delta2 = 0
END IF
dx3 = x1 - x3
dy3 = y1 - y3
IF dy3 <> 0 THEN
delta3 = (dx3 shl 16) \ dy3
ELSE
delta3 = 0
END IF
'Flat bottom
'Top part of triangle
dim y as integer
dim Lxo as integer, Rxo as integer
Lx = x1 shl 16
Rx = Lx
FOR y = y1 TO y2 - 1
Lxo = Lx shr 16
Rxo = Rx shr 16
line(Lxo, y)-(Rxo,y),col
Lx = Lx + delta1
Rx = Rx + delta3
NEXT y
'Flat top
'Lower part of triangle
Lx = x2 shl 16
FOR y = y2 TO y3
Lxo = Lx shr 16
Rxo = Rx shr 16
line(Lxo, y)-(Rxo,y),col
Lx = Lx + delta2
Rx = Rx + delta3
NEXT y
end sub
Code has the "use" or "abuse" license.