Files
rosetta/tests/codecs/polygon.luau
T

70 lines
2.6 KiB
Luau

-- codecs/model/Polygon tests: convex / concave / holed / nested polygons triangulate to the exact area in
-- counter-clockwise triangles, either input orientation; degenerate loops; a fuzz of random loops never throws.
local T = require("@tests/T")
local Polygon = require("@formats/codecs/model/Polygon")
local t = T.suite("codecs/polygon")
local function area(loops: { { number } }, tris: { number }): (number, boolean)
local a, ccw = 0, true
for k = 1, #tris, 6 do
local p = {}
for c = 0, 2 do
local l = loops[tris[k + c * 2]]
local i = tris[k + c * 2 + 1]
p[c * 2 + 1], p[c * 2 + 2] = l[i * 2 - 1], l[i * 2]
end
local s = ((p[3] - p[1]) * (p[6] - p[2]) - (p[4] - p[2]) * (p[5] - p[1])) / 2
if s <= 0 then
ccw = false
end
a += s
end
return a, ccw
end
local cases = {
{ "square", { { 0, 0, 10, 0, 10, 10, 0, 10 } }, 100 },
{ "clockwise square", { { 0, 0, 0, 10, 10, 10, 10, 0 } }, 100 },
{ "L shape", { { 0, 0, 20, 0, 20, 10, 10, 10, 10, 20, 0, 20 } }, 300 },
{ "comb", { { 0, 0, 50, 0, 50, 10, 40, 10, 40, 2, 30, 2, 30, 10, 20, 10, 20, 2, 10, 2, 10, 10, 0, 10 } }, 50 * 2 + 3 * 10 * 8 },
{ "square with a hole", { { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 2, 4, 4, 4, 4, 2 } }, 96 },
{ "two holes", { { 0, 0, 30, 0, 30, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 }, { 20, 2, 28, 2, 28, 8, 20, 8 } }, 300 - 4 - 48 },
{ "island in a hole", { { 0, 0, 30, 0, 30, 30, 0, 30 }, { 5, 5, 25, 5, 25, 25, 5, 25 }, { 10, 10, 20, 10, 20, 20, 10, 20 } }, 900 - 400 + 100 },
{ "degenerate loops ignored", { { 0, 0, 1, 1 }, { 0, 0, 5, 5, 10, 10 }, { 0, 0, 4, 0, 4, 4, 0, 4 } }, 16 },
}
for _, c in cases do
local tris = Polygon.triangulate(c[2])
local a, ccw = area(c[2], tris)
t:check(math.abs(a - c[3]) < 1e-9, c[1] .. ": area " .. a .. " want " .. c[3])
t:check(ccw, c[1] .. ": counter-clockwise triangles")
end
-- random star polygons with a random hole: area preserved, never throws
local rand = T.rng(3)
local threw = 0
for i = 1, 200 do
local n = 3 + rand(30)
local outer = {}
for k = 0, n - 1 do
local ang = k / n * math.pi * 2
local r = 50 + rand(50)
table.insert(outer, math.floor(math.cos(ang) * r))
table.insert(outer, math.floor(math.sin(ang) * r))
end
local hole = { -5, -5, 5, -5, 5, 5, -5, 5 }
local ok = pcall(Polygon.triangulate, if i % 2 == 0 then { outer, hole } else { outer })
if not ok then
threw += 1
end
local garbage = {}
for _ = 1, rand(40) do
table.insert(garbage, rand(20) - 10)
end
if not pcall(Polygon.triangulate, { garbage, { 0 / 0, 1, 2 } }) then
threw += 1
end
end
t:eq(threw, 0, "random and garbage loops never throw")
t:done()