Clipper Demo

From GiderosMobile

Available since: Gideros 2015.03.22
Class: Clipper

Description

Full Clipper demo for Gideros.

-- Clipper demo for Gideros (Luau)
-- Boolean operations, offsets, cleaning, simplifying and reversing
-- of polygons, built on top of the Clipper plugin.

local clipperOk = pcall(require, "clipper")
if not clipperOk or not Polygon or not Clipper then
    local t = TextField.new(nil, "Clipper plugin not enabled")
    t:setTextColor(0xff0000)
    t:setPosition(10, 40)
    stage:addChild(t)
    return
end

-------------------------------------------------------------------------------
-- Palette and layout
-------------------------------------------------------------------------------

local C = {
    bg = 0xf4f4f4, card = 0xffffff, line = 0xcccccc,
    subject = 0x2a6fdb, clip = 0xe05252, result = 0x2faa4a,
    bounds = 0xffb000, text = 0x222222, dim = 0x666666,
    accent = 0x2a6fdb, btn = 0xe8e8e8, btnActive = 0xcfe3ff,
}

local DESIGN_W, DESIGN_H = 320, 480
local CANVAS_X, CANVAS_Y = 10, 70
local CANVAS_W, CANVAS_H = 300, 250

local screenW, screenH = application:getContentWidth(), application:getContentHeight()
application:setBackgroundColor(C.bg)

local ui = Sprite.new()
ui:setPosition(math.floor((screenW - DESIGN_W) / 2), math.floor((screenH - DESIGN_H) / 2))
stage:addChild(ui)

-------------------------------------------------------------------------------
-- UI helpers
-------------------------------------------------------------------------------

local function addPanel(parent, x, y, w, h, color)
    local p = Pixel.new(color, 1, w, h)
    p:setPosition(x, y)
    parent:addChild(p)
    return p
end

local function addText(parent, text, x, y, color, scale)
    local t = TextField.new(nil, text)
    t:setTextColor(color)
    t:setPosition(x, y)
    if scale then t:setScale(scale) end
    parent:addChild(t)
    return t
end

local function centerX(t, y)
    t:setPosition(math.floor((DESIGN_W - t:getWidth()) / 2), y)
end

local buttonRegistry = {}

local function makeButton(x, y, w, h, label, onClick)
    local root = Sprite.new()
    root:setPosition(x, y)

    local bg = Pixel.new(C.btn, 1, w, h)
    root:addChild(bg)

    local txt = TextField.new(nil, label)
    txt:setTextColor(C.text)
    txt:setPosition(math.floor((w - txt:getWidth()) / 2),
        math.floor((h - txt:getHeight()) / 2))
    root:addChild(txt)

    local active = false
    local function refresh(down)
        bg:setColor(down and C.btnActive or (active and C.btnActive or C.btn))
    end

    function root:setText(s)
        txt:setText(s)
        txt:setPosition(math.floor((w - txt:getWidth()) / 2),
            math.floor((h - txt:getHeight()) / 2))
    end
    function root:setActive(v)
        active = v
        refresh(false)
    end

    local entry = {root = root, x = x, y = y, w = w, h = h,
        onClick = onClick, refresh = refresh, active = function(v) active = v end}
    table.insert(buttonRegistry, entry)

    ui:addChild(root)
    return root
end

-------------------------------------------------------------------------------
-- Polygon helpers
-------------------------------------------------------------------------------

local function makePolygon(points)
    local p = Polygon.new()
    for _, pt in ipairs(points) do
        p:addPoint(pt[1], pt[2])
    end
    return p
end

local function pointsFromPoly(poly)
    local pts = poly:getPoints()
    local out = {}
    for i = 1, #pts do
        out[i] = { pts[i][1], pts[i][2] }
    end
    return out
end

local function pointsFromPolys(polys)
    local out = {}
    for i = 1, #polys do
        out[i] = pointsFromPoly(polys[i])
    end
    return out
end

local function polyArea(points)
    if #points < 3 then return 0 end
    local p = makePolygon(points)
    return p:getArea()
end

local function boundsOf(points)
    if #points == 0 then return 0, 0, 0, 0 end
    local minX, minY = points[1][1], points[1][2]
    local maxX, maxY = minX, minY
    for i = 2, #points do
        local x, y = points[i][1], points[i][2]
        if x < minX then minX = x end
        if y < minY then minY = y end
        if x > maxX then maxX = x end
        if y > maxY then maxY = y end
    end
    return minX, minY, maxX - minX, maxY - minY
end

-------------------------------------------------------------------------------
-- State
-------------------------------------------------------------------------------

local subjectPoints = { {80, 80}, {230, 90}, {220, 230}, {90, 220} }
local clipPoints = { {150, 60}, {270, 170}, {160, 290}, {40, 180} }

local active = "subject"          -- "subject" or "clip"
local currentOp = "intersection"  -- intersection / union / difference / exclusion
local fillRule = Polygon.FILL_EVEN_ODD
local showResult = true

local resultPolys = {}   -- list of point-lists

-------------------------------------------------------------------------------
-- Canvas and shapes
-------------------------------------------------------------------------------

addPanel(ui, CANVAS_X - 2, CANVAS_Y - 2, CANVAS_W + 4, CANVAS_H + 4, C.line)
local canvasBg = addPanel(ui, CANVAS_X, CANVAS_Y, CANVAS_W, CANVAS_H, C.card)

local subjShape = Shape.new()
local clipShape = Shape.new()
local resShape = Shape.new()
local boundsShape = Shape.new()
local lineShape = nil

local canvas = Sprite.new()
canvas:setPosition(CANVAS_X, CANVAS_Y)
ui:addChild(canvas)
canvas:addChild(subjShape)
canvas:addChild(clipShape)
canvas:addChild(resShape)
canvas:addChild(boundsShape)

local function drawPolygon(shape, points, fillColor, fillAlpha, lineColor, lineWidth)
    shape:clear()
    if #points < 2 then return end
    if #points < 3 then
        shape:setLineStyle(lineWidth or 2, lineColor, 1)
        shape:beginPath()
        shape:moveTo(points[1][1], points[1][2])
        for i = 2, #points do
            shape:lineTo(points[i][1], points[i][2])
        end
        shape:endPath()
        return
    end
    shape:setFillStyle(Shape.SOLID, fillColor, fillAlpha or 0.4)
    shape:setLineStyle(lineWidth or 2, lineColor, 1)
    shape:beginPath()
    shape:moveTo(points[1][1], points[1][2])
    for i = 2, #points do
        shape:lineTo(points[i][1], points[i][2])
    end
    shape:closePath()
    shape:endPath()
end

local function drawPolys(shape, polys, fillColor, fillAlpha, lineColor, lineWidth)
    shape:clear()
    for _, pts in ipairs(polys) do
        if #pts >= 3 then
            shape:setFillStyle(Shape.SOLID, fillColor, fillAlpha or 0.4)
            shape:setLineStyle(lineWidth or 2, lineColor, 1)
            shape:beginPath()
            shape:moveTo(pts[1][1], pts[1][2])
            for i = 2, #pts do
                shape:lineTo(pts[i][1], pts[i][2])
            end
            shape:closePath()
            shape:endPath()
        end
    end
end

local infoLabel = addText(ui, "", 10, 322, C.dim)

local function rebuild()
    local subjPts = subjectPoints
    local clipPts = clipPoints

    drawPolygon(subjShape, subjPts, C.subject, 0.25, C.subject, 2)
    drawPolygon(clipShape, clipPts, C.clip, 0.20, C.clip, 2)

    -- clear the transient line-offset shape
    if lineShape then
        lineShape:removeFromParent()
        lineShape = nil
    end

    -- run the boolean operation
    resultPolys = {}
    if #subjPts >= 3 and #clipPts >= 3 then
        local c = Clipper.new()
        c:addSubjectPolygon(makePolygon(subjPts))
        c:addClipPolygon(makePolygon(clipPts))
        local raw
        if currentOp == "intersection" then
            raw = c:getIntersection(fillRule, fillRule)
        elseif currentOp == "union" then
            raw = c:getUnion(fillRule, fillRule)
        elseif currentOp == "difference" then
            raw = c:getDifference(fillRule, fillRule)
        else
            raw = c:getExclusion(fillRule, fillRule)
        end
        resultPolys = pointsFromPolys(raw)
    end

    if showResult then
        drawPolys(resShape, resultPolys, C.result, 0.45, 0x1f7a33, 2)
    else
        resShape:clear()
    end

    -- bounds of the active polygon
    boundsShape:clear()
    local activePts = (active == "subject") and subjPts or clipPts
    local bx, by, bw, bh = boundsOf(activePts)
    if bw > 0 and bh > 0 then
        boundsShape:setLineStyle(2, C.bounds, 1)
        boundsShape:beginPath()
        boundsShape:moveTo(bx, by)
        boundsShape:lineTo(bx + bw, by)
        boundsShape:lineTo(bx + bw, by + bh)
        boundsShape:lineTo(bx, by + bh)
        boundsShape:closePath()
        boundsShape:endPath()
    end

    -- info text
    local subjArea = polyArea(subjPts)
    local clipArea = polyArea(clipPts)
    local resArea = 0
    for _, rp in ipairs(resultPolys) do
        resArea = resArea + polyArea(rp)
    end
    infoLabel:setText(string.format(
        "subj %d pts  %.0f px2   clip %d pts  %.0f px2   result %d poly  %.0f px2",
        #subjPts, subjArea, #clipPts, clipArea, #resultPolys, resArea))
end

-------------------------------------------------------------------------------
-- Touch: add points to the active polygon
-------------------------------------------------------------------------------

-- canvas touches are handled by the single dispatcher below

-------------------------------------------------------------------------------
-- Controls
-------------------------------------------------------------------------------

-- Header
addPanel(ui, 16, 12, 4, 24, C.accent)
addText(ui, "Clipper", 28, 10, C.text, 2)
addText(ui, "polygon boolean operations and offsets", 16, 40, C.dim)
addPanel(ui, 16, 58, 288, 1, C.line)

local activeBtn
activeBtn = makeButton(10, 332, 92, 30, "EDIT: SUBJECT", function()
    active = (active == "subject") and "clip" or "subject"
    activeBtn:setText("EDIT: " .. active:upper())
    rebuild()
end)

local undoBtn = makeButton(108, 332, 62, 30, "UNDO", function()
    local pts = (active == "subject") and subjectPoints or clipPoints
    if #pts > 0 then pts[#pts] = nil end
    rebuild()
end)

local clearBtn = makeButton(176, 332, 62, 30, "CLEAR", function()
    if active == "subject" then subjectPoints = {} else clipPoints = {} end
    rebuild()
end)

local fillBtn
fillBtn = makeButton(244, 332, 66, 30, "FILL EO", function()
    if fillRule == Polygon.FILL_EVEN_ODD then
        fillRule = Polygon.FILL_NON_ZERO
        fillBtn:setText("FILL NZ")
    else
        fillRule = Polygon.FILL_EVEN_ODD
        fillBtn:setText("FILL EO")
    end
    rebuild()
end)

-- Operation buttons
local function opButton(label, opName, x)
    return makeButton(x, 368, 72, 30, label, function()
        currentOp = opName
        rebuild()
    end)
end
opButton("INTERSECT", "intersection", 10)
opButton("UNION", "union", 88)
opButton("DIFFERENCE", "difference", 166)
opButton("XOR", "exclusion", 244)

-- Offset / clean / reverse / simplify
local function offsetActive(delta)
    local pts = (active == "subject") and subjectPoints or clipPoints
    if #pts < 3 then return end
    local poly = makePolygon(pts)
    local res = poly:getPolygonOffset(delta, Polygon.JOINT_ROUND, 2, true)
    if res and #res > 0 then
        local newPts = pointsFromPoly(res[1])
        if #newPts >= 3 then
            if active == "subject" then subjectPoints = newPts
            else clipPoints = newPts end
        end
    end
    rebuild()
end

makeButton(10, 404, 58, 30, "OFF+", function() offsetActive(8) end)
makeButton(74, 404, 58, 30, "OFF-", function() offsetActive(-8) end)

makeButton(138, 404, 58, 30, "CLEAN", function()
    local pts = (active == "subject") and subjectPoints or clipPoints
    if #pts < 3 then return end
    local poly = makePolygon(pts)
    poly:clean(1.415)
    local newPts = pointsFromPoly(poly)
    if active == "subject" then subjectPoints = newPts
    else clipPoints = newPts end
    rebuild()
end)

makeButton(202, 404, 58, 30, "REVERSE", function()
    local pts = (active == "subject") and subjectPoints or clipPoints
    if #pts < 3 then return end
    local poly = makePolygon(pts)
    poly:reverse()
    local newPts = pointsFromPoly(poly)
    if active == "subject" then subjectPoints = newPts
    else clipPoints = newPts end
    rebuild()
end)

makeButton(266, 404, 44, 30, "SIMPL", function()
    local pts = (active == "subject") and subjectPoints or clipPoints
    if #pts < 3 then return end
    local poly = makePolygon(pts)
    local res = poly:simplify(fillRule)
    if res and #res > 0 then
        local newPts = pointsFromPoly(res[1])
        if #newPts >= 3 then
            if active == "subject" then subjectPoints = newPts
            else clipPoints = newPts end
        end
    end
    rebuild()
end)

-- Show / hide result
local showBtn
showBtn = makeButton(10, 440, 96, 30, "RESULT: ON", function()
    showResult = not showResult
    showBtn:setText(showResult and "RESULT: ON" or "RESULT: OFF")
    rebuild()
end)

-- Line offset demo: offsets the active polygon as a polyline (open shape)
makeButton(112, 440, 96, 30, "LINE OFF", function()
    local pts = (active == "subject") and subjectPoints or clipPoints
    if #pts < 2 then return end
    local poly = makePolygon(pts)
    local res = poly:getLineOffset(6, Polygon.JOINT_ROUND, Polygon.END_ROUND, 2)
    if lineShape then lineShape:removeFromParent() end
    lineShape = Shape.new()
    lineShape:setLineStyle(2, 0xffb000, 1)
    for _, lp in ipairs(pointsFromPolys(res)) do
        if #lp >= 2 then
            lineShape:beginPath()
            lineShape:moveTo(lp[1][1], lp[1][2])
            for i = 2, #lp do
                lineShape:lineTo(lp[i][1], lp[i][2])
            end
            lineShape:endPath()
        end
    end
    canvas:addChild(lineShape)
end)

local legend = addText(ui, "blue = subject   red = clip   green = result   yellow = bounds", 10, 474, C.dim)
legend:setScale(0.85)

-- Single touch dispatcher: avoids Gideros delivering one touch to several sprites.
local pressedButton = nil

local function findButtonAt(px, py)
    for i = #buttonRegistry, 1, -1 do
        local b = buttonRegistry[i]
        if px >= b.x and px <= b.x + b.w and py >= b.y and py <= b.y + b.h then
            return b
        end
    end
    return nil
end

ui:addEventListener(Event.TOUCHES_BEGIN, function(e)
    local ux, uy = ui:globalToLocal(e.touch.x, e.touch.y)
    local b = findButtonAt(ux, uy)
    if b then
        pressedButton = b
        b.refresh(true)
    else
        pressedButton = nil
        -- canvas tap: add a point to the active polygon
        local cx, cy = canvas:globalToLocal(e.touch.x, e.touch.y)
        if cx >= 0 and cy >= 0 and cx <= CANVAS_W and cy <= CANVAS_H then
            local pts = (active == "subject") and subjectPoints or clipPoints
            pts[#pts + 1] = { math.floor(cx), math.floor(cy) }
            rebuild()
        end
    end
    return true
end)

ui:addEventListener(Event.TOUCHES_END, function(e)
    if pressedButton then
        pressedButton.refresh(false)
        if pressedButton.onClick then pressedButton.onClick() end
        pressedButton = nil
    end
    return true
end)

ui:addEventListener(Event.TOUCHES_CANCEL, function(e)
    if pressedButton then
        pressedButton.refresh(false)
        pressedButton = nil
    end
    return true
end)

rebuild()