diff --git a/src/polygons.jl b/src/polygons.jl index 59f3df5..510035e 100644 --- a/src/polygons.jl +++ b/src/polygons.jl @@ -13,10 +13,11 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =# -function area(contour::AbstractVector{Point{N, T}}) where {N, T} +function area(contour::AbstractVector{Point{2, T}}) where {T} n = length(contour) A = zero(T) - p=n; q=1 + p=lastindex(contour) + q=firstindex(contour) while q <= n A += cross(contour[p], contour[q]) p = q; q +=1 @@ -24,6 +25,15 @@ function area(contour::AbstractVector{Point{N, T}}) where {N, T} return A*T(0.5) end +function area(contour::AbstractVector{Point{3, T}}) where {T} + A = zero(eltype(contour)) + o = contour[1] + for i in (firstindex(contour)+1):(lastindex(contour)-1) + A += cross(contour[i] - o, contour[i+1] - o) + end + return norm(A)*T(0.5) +end + """ InsideTriangle decides if a point P is Inside of the triangle defined by A, B, C. diff --git a/test/polygons.jl b/test/polygons.jl index 34c20be..630d49c 100644 --- a/test/polygons.jl +++ b/test/polygons.jl @@ -24,4 +24,53 @@ @test facetype(mesh) == GLTriangle end + +@testset "area-2d" begin + points = Point2f0[ + (0,0), + (1,0), + (1,1), + (0,1) + ] + @test area(points) ≈ 1f0 + @test area(reverse(points)) ≈ -1f0 +end + +@testset "area-2d-nonconvex" begin + points = Point2f0[ + (0,0), + (1,0), + (0.5,0.5), + (1,1), + (0,1), + (0.5,0.5) + ] + @test area(points) ≈ 0.5f0 + @test area(reverse(points)) ≈ -0.5f0 +end + +@testset "area-3d" begin + points = Point3f0[ + (0,0,0), + (1,0,0), + (1,1,0), + (0,1,0) + ] + @test area(points) ≈ 1f0 + @test area(reverse(points)) ≈ 1f0 +end + +@testset "area-3d-nonconvex" begin + points = Point3f0[ + (0,0,0), + (1,0,0), + (0.5,0.5,0), + (1,1,0), + (0,1,0), + (0.5,0.5,0) + ] + @test area(points) ≈ 0.5f0 + @test area(reverse(points)) ≈ 0.5f0 +end + end