Skip to content
This repository has been archived by the owner on Nov 22, 2023. It is now read-only.

Fix area for higher dimensions #182

Merged
merged 9 commits into from
Oct 18, 2019
14 changes: 12 additions & 2 deletions src/polygons.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,27 @@ 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
end
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.
Expand Down
49 changes: 49 additions & 0 deletions test/polygons.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,53 @@
@test facetype(mesh) == GLTriangle

end

@testset "area-2d" begin
CarpeNecopinum marked this conversation as resolved.
Show resolved Hide resolved
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