-- lua script for drawing a Rectangle with Curved Corners

-- allow the user to change the settings.
-- Note the sliders have range is 0 .. 1.0 for reading but have range 1..100 for setting

--@TBCONFIG SLIDER: Width of Frame, 80
--@TBCONFIG SLIDER: Height of Frame, 80
--@TBCONFIG SLIDER: Rounding, 20
--@TBCONFIG SLIDER: X Axis, 50
--@TBCONFIG SLIDER: Y Axis, 50

local wMid = width / 2
local hMid = height / 2
local screen_radius = math.sqrt((wMid * wMid) + (hMid * hMid))
local r2d =  180 / math.pi

local uWidth = sliderVal1 * width / 2
local uHeight = sliderVal2 * height / 2
local uRadius = sliderVal3  * screen_radius / 2
local ucenterX = math.floor((sliderVal4 - 0.5)  * width)
local ucenterY = math.floor((sliderVal5 - 0.5)  * height)

-- Draw a quarter circle at x,y with size r and angle theta
function paint_line_offset(x0,y0,x1,y1)
paint_line(x0 + ucenterX,y0 + ucenterY,x1 + ucenterX,y1 + ucenterY)
end

function DrawQuarterCircle(x, y, r, theta)

local currentx = 1e+10
local currenty = 1e+10
local angle , newx, newy

	for t = 0, 90 , 3 do
		angle = (math.pi * 2) * ((t + theta) / 360)
		newx = math.cos(angle) * r + x
		newy = math.sin(angle) * r + y

		if currentx == 1e+10 then 
			-- ignore first point line
		else
			paint_line_offset(currentx , currenty, newx, newy)
		end

		currentx = newx
		currenty = newy

	end

end

-- the screen coordinates start at (0,0) at the top left corner
-- -------------------------------------------------------------------

paint_open(1)

-- horizontal lines
paint_line_offset(wMid - uWidth + uRadius, hMid - uHeight, wMid + uWidth - uRadius, hMid - uHeight)  -- top
paint_line_offset(wMid - uWidth + uRadius, hMid + uHeight, wMid + uWidth - uRadius, hMid + uHeight)  -- bottom
-- vertical lines
paint_line_offset(wMid - uWidth, hMid - uHeight + uRadius, wMid - uWidth, hMid + uHeight - uRadius)  -- left
paint_line_offset(wMid + uWidth, hMid - uHeight + uRadius, wMid + uWidth, hMid + uHeight - uRadius)  -- right

-- draw the four corners
DrawQuarterCircle(wMid + uWidth - uRadius,hMid + uHeight - uRadius,uRadius, 0) -- br
DrawQuarterCircle(wMid - uWidth + uRadius,hMid + uHeight - uRadius,uRadius, 90) -- bl
DrawQuarterCircle(wMid - uWidth + uRadius,hMid - uHeight + uRadius,uRadius, 180) -- ul
DrawQuarterCircle(wMid + uWidth - uRadius,hMid - uHeight + uRadius,uRadius, 270) -- ur

paint_close()
