R=R or {}
require("./3d/model")(R)
require("./3d/scene")(R)

local GLOBAL=require("./global")

local SCENE=nil
local MODEL_GMAN=nil
local ACTOR_GMAN=nil
local MAT_GMAN=nil

return {
    bdr=function(y,t,unitT)
        vbank(0)
        R.setRGB(0,R.RGB:new(0,0,0))
        R.setRGB(1,GLOBAL.rgbGMan)
    end,
    musicTic=function(isFirstRun,t,unitT)
        if isFirstRun then
            vbank(1)
            cls(0)

            SCENE=R.Scene:new()

            MODEL_GMAN=R.Model:new()
            MODEL_GMAN:load(require("./data/model/green-man-walking"))

            ACTOR_GMAN=R.Actor:new(MODEL_GMAN)
            ACTOR_GMAN:setDrawFn(function(tr)
                local cx,cy=120,68
                -- Get the offset of each point from the centre
                local d1x,d1y=tr.v[1].x-cx,tr.v[1].y-cy
                local d2x,d2y=tr.v[2].x-cx,tr.v[2].y-cy
                local d3x,d3y=tr.v[3].x-cx,tr.v[3].y-cy
                -- Get the centre of this triangle
                local dcx,dcy=(d1x+d2x+d3x)/3,(d1y+d2y+d3y)/3
                local dox,doy=dcx,dcy
                tri(
                    cx+d1x+dox,cy+d1y+doy,
                    cx+d2x+dox,cy+d2y+doy,
                    cx+d3x+dox,cy+d3y+doy,
                    1
                )
            end,0)

            SCENE:registerActor(ACTOR_GMAN)
        end

        vbank(0)
        cls(0)
    --[[
        local mat=R.M44:new(R.M44.ID)
        mat:mulM44(R.M44:newTrans(0,0,unitT*3))
        mat:mulM44(R.M44:newRotZ(-math.pi/4+unitT*math.pi/2))
        ACTOR_GMAN:setMat(mat)
--]]
        local mat=R.M44:new(R.M44.ID)
        mat:mulM44(R.M44:newTrans(.05,.1,2))
        mat:mulM44(R.M44:newRotZ(-math.pi/2+unitT*math.pi*.3))
        ACTOR_GMAN:setMat(mat)

        local cam=SCENE:getCam()
        local camZ=2-unitT*3
        cam:setPos(R.V4:new({0,0,camZ,1}))
        cam:setAim(R.V4:new({0,0,10,1}))

        SCENE:draw()
    end,
}
