Created
April 22, 2021 09:12
-
-
Save SpineyPete/a649cd27a5c10e320e66054d0032983b to your computer and use it in GitHub Desktop.
Generates a rounded rectangle n-gon, renderable with a triangle fan.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function roundrectpoly(x, y, w, h, r, n) | |
-- required args | |
assert(x ~= nil and type(x) == "number") | |
assert(y ~= nil and type(y) == "number") | |
assert(w ~= nil and type(w) == "number") | |
assert(h ~= nil and type(h) == "number") | |
-- optional args | |
assert(r == nil or type(r) == "number") | |
assert(n == nil or type(n) == "number") | |
r = math.min(r or 10, math.min(w * 0.5, h * 0.5)) | |
n = math.max(n or 5, 2) | |
-- corner sector angle | |
local ang = math.pi / 2 / (n - 1) | |
-- angular starting offsets | |
local br_ang = math.pi * 2.0 - ang | |
local bl_ang = math.pi * 1.5 - ang | |
local tl_ang = math.pi * 1.0 - ang | |
local tr_ang = math.pi * 0.5 - ang | |
-- x and y positions to rotate around | |
local x_lft = x + r | |
local x_rgt = x + w - r | |
local y_top = y + r | |
local y_btm = y + h - r | |
local poly = {} | |
for i = 1, n do | |
local xi = i * 2 - 1 | |
local yi = i * 2 | |
-- bottom-right corner | |
poly[n * 0 + xi] = x_rgt + math.sin(br_ang + ang * i) * r | |
poly[n * 0 + yi] = y_btm + math.cos(br_ang + ang * i) * r | |
-- top-right corner | |
poly[n * 2 + xi] = x_rgt + math.sin(tr_ang + ang * i) * r | |
poly[n * 2 + yi] = y_top + math.cos(tr_ang + ang * i) * r | |
-- top-left corner | |
poly[n * 4 + xi] = x_lft + math.sin(tl_ang + ang * i) * r | |
poly[n * 4 + yi] = y_top + math.cos(tl_ang + ang * i) * r | |
-- bottom-left corner | |
poly[n * 6 + xi] = x_lft + math.sin(bl_ang + ang * i) * r | |
poly[n * 6 + yi] = y_btm + math.cos(bl_ang + ang * i) * r | |
end | |
return poly | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment