The Expensive Square Root Function

Started by
11 comments, last by iedoc 12 years, 7 months ago
The way I think of the area of a triangle is this:

|x1 y1 1|
|x2 y2 1| * (1/2)
|x3 y3 1|

Similarly, the volume of a tetrahedron is

|x1 y1 z1 1|
|x2 y2 z2 1|
|x3 y3 z3 1| * (1/6)
|x4 y4 z4 1|

You get a sign that has to do with the notion of orientation. You can take the absolute value if you want, but the sign is often helpful (for instance, when computing that area of any polygon, you can simply add up the signed areas of the triangles formed by each side of the polygon and an arbitrary point).

This actually works for R^n, multiplying the determinant by (1/n!). But 2D and 3D are probably the only cases you'll be interested in for game development.
Advertisement

Ok, lets sort this out :)

The area of a triangle is simply half of the 2d cross-product of two of the triangle axis.

http://softsurfer.co...orithm_0101.htm

No need for sqrt() at all.


[source]Area = 1/2 * magnitude( cross(V1-V0, V2-V0) )[/source]

Notice that call to magnitude there? It needs a sqrt....

You get a sign that has to do with the notion of orientation. You can take the absolute value if you want, but the sign is often helpful (for instance, when computing that area of any polygon, you can simply add up the


The sign also tells you if you have the polygon winding order round the wrong way, because it will be negative in that case :)

[color="#1C2837"] (for instance, when computing that area of any polygon, you can simply add up the signed areas of the triangles formed by each side of the polygon and an arbitrary point).
[color="#1C2837"][/quote]
[color="#1C2837"]
[color="#1c2837"]Actually, an interesting property of the area calculation means you can calculate the area of a polygon simply by looping over the vertices and summing the cross-product of sequential vertices like this:

[color="#1c2837"]public function GetArea( ):Number
{
var area:Number = 0;
for ( var i:int = 0; i<m_numPoints; i++ )
{
var P0:Vector2 = m_localSpacePoints;
var P1:Vector2 = m_localSpacePoints[(i+1)%m_numPoints];

area += P0.Cross( P1 );
}

return area/2;
}



[color="#1c2837"]No matter what space those vertices are in, the area returned by this function is the same, which is slightly counter intuitive but makes for a nice tight loop :)

[color="#1c2837"]Cheers, Paul.
I just had to say wildbunny, ^^^ That is a great function! ;)

This topic is closed to new replies.

Advertisement