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

local GLOBAL=require("./global")

local PAL=nil
local PAL_WHITE=nil
local SCENE=nil
local ACTOR_VEHICLE=nil
local ACTOR_GMAN=nil
local ACTOR_RMAN=nil

return {
    musicPatterns=2,
    bdr=function(y,t,unitT)
        vbank(0)
        local s=R.clamp(10*(unitT-.9),0,1)
        PAL:applyBlend(PAL_WHITE,s)
    end,
    musicTic=function(isFirstRun,t,unitT,donePatterns,tWalk)
        if isFirstRun then
            PAL=R.Palette:new()
            PAL:setRGB(0,R.RGB:new(0,0,0))
            PAL:setRGB(1,GLOBAL.rgbGMan)
            PAL:setRGB(2,GLOBAL.rgbRMan)
            PAL:setRGB(3,R.RGB:new(1,1,1))

            PAL_WHITE=R.Palette:new()
            PAL_WHITE:setAllRGB(R.RGB:new(1,1,1))

            SCENE=R.Scene:new()

            local model=R.Model:new()
            model:load(require("./data/model/green-man-walking"))
            ACTOR_GMAN=R.Actor:new(model)
            ACTOR_GMAN:setDrawFn(R.poly.Draw1Colour(1),0)            

            local model=R.Model:new()
            model:load(require("./data/model/redman"))
            ACTOR_RMAN=R.Actor:new(model)
            ACTOR_RMAN:setDrawFn(R.poly.Draw1Colour(2),0)            

            local model=R.Model:new()
            model:load(require("./data/model/vehicle")())

            ACTOR_VEHICLE=R.Actor:new(model)
            ACTOR_VEHICLE:setDrawFn(R.poly.Draw1Colour(3),0)

            SCENE:registerActor(ACTOR_VEHICLE)
            SCENE:registerActor(ACTOR_RMAN)
            SCENE:registerActor(ACTOR_GMAN)
        end

        vbank(0)
        cls(0)

        GLOBAL.walkAnimWrapper(ACTOR_GMAN,tWalk)

        local y=math.abs(math.sin(unitT*80))*.5
        local mat=R.M44:newTrans(10,y,2)
        ACTOR_RMAN:setMat(mat)

        local z=40-unitT*40
        local mat=R.M44:newTrans(.8,-.2,z)
        ACTOR_VEHICLE:setMat(mat)

        local x,y,z=0,0,0
        if unitT>=.2 and unitT<=.8 then
            local inT=(unitT-.2)/.6
            x=math.sin(inT*math.pi)*10
            y=math.sin(inT*math.pi)*-2
            z=math.sin(inT*math.pi)*-5
        end
        local cam=SCENE:getCam()
        cam:setPos(R.V4:new({x,y,z,1}))
        cam:setAim(R.V4:new({x,0,1,1}))

        SCENE:draw()
    end,
}
