
function init_event()
    local crate_texture = ag.loadTexture("checker.jpg")
    local ground = ag.createPlane(0, 0, 1, 0)
    ground:setColor(0.2, 1.0, 0.2)
    ground:setTexture(crate_texture)
    ag.setCamera(10, -10, 10, 0, 0, 0)

    if (ag.import("rot_camera") ~= true) then
        ag.println("error importing rot_camera")
        ag.exit()
    end
    ag.setCursorVisible(true)
    pt_x = -1
    pt_y = -1
end

function init_obj(obj)
    obj:setColor(math.random(), math.random(), math.random())
    obj:setPosition((math.random() - 0.5) * 10, (math.random() - 0.5) * 10, 10)
end

-- function update_event()
--     rot_camera()
-- end

function key_down_event(key)
    if     (key == "b") then
        local box = ag.createBox(1, 1, 1)
        init_obj(box)
--    elseif (key == "c") then
--        -- cylinders are buggy in ODE
--        local cyl = ag.createCylinder(0.5, 1)
--        init_obj(cyl)
    elseif (key == "a") then
        local ccyl = ag.createCapsule(0.5, 1)
        init_obj(ccyl)
    elseif (key == "s") then
        local sphere = ag.createSphere(0.8)
        init_obj(sphere)
    elseif (key == "q") then
        ag.exit()
    elseif (key == "r") then
        -- creating a rotating cube
        local spinner = ag.createBox(10, 1, 0.5)
        spinner:setPosition(0, 0, 1)
        spinner:setColor(1, 0.7, 0.7)
        spinner:setGravityMode(false)
        ag.createAMotor(0, spinner,
            { x = 0, y = 0, z = 1, vel = 5, fmax = 50 })
        ag.createHinge(0, spinner, {spinner:getPosition()}, {0, 0, 1})
        -- local box = ag.createBox(1, 1, 1)
        -- init_obj(box)
        -- ag.createAMotor(0, box,
        --     { x = 0, y = 0, z = 1, vel = 0, fmax = 0 })
        -- local x, y, z = box:getPosition()
        -- box:setPosition(x, y, 2)
    elseif (key == "minus") then
        ag.setCursorVisible(not ag.getCursorVisible())
    elseif (key == "d") then
        q = ag.createQuad(0.5, 3, 0, 1, 0, 0, 0, 1, 0)
        q:setColor(0, 0, 1, 0.6)
        q:setOffset(1)
        q:setBlending(true)
    end
end

function mousebutton_down_event(button, x, y)
    if (button == 1) then
        objects = ag.pickObjects(x, y)
        if (objects ~= nil) then
            for id, obj in ipairs(objects) do
                obj:setColor(0, 0, 1)
            end
        end
    elseif (button == 3) then
        pt_x = x
        pt_y = y
    end
end

function update_overlay_event(width, height)
    if (pt_x >= 0 and pt_y >= 0) then
        ag.drawCircle(0, 1, 0, pt_x, pt_y, 5)
    end
    ag.fillArc(1, 1, 0, 50, 50, 30, 30, 330)
    ag.fillCircle(1, 0, 1, width - 50, height - 50, 40)
    ag.drawRect(1, 0.5, 0, width, height, width/2, height/2)
    ag.drawPoint(1, 0, 1, 0, 0, 0)
    ag.drawPoint(1, 0, 1, 0, width-1, height-1)
    ag.drawPoint(1, 0, 1, 1, -1, -1)
    ag.drawPoint(1, 0, 1, 1, width, height)
    msg = "b a s r d - m1 m3"
    tw, th = ag.getTextSize(msg, 14)
    ag.drawText(msg, 1, 1, 1, 14, width / 2 - tw / 2, 10)
end
