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

lampFilter=require('./screenfilters/lamp')

return {
    musicPatterns=2,
    bdr=function(y,t,unitT)
        vbank(0)
        local pal0=R.Palette:new()
        local pal1=R.Palette:new()
        local rgbRMan=GLOBAL.rgbRMan
        pal0:setRGB(0,R.RGB:new(0,0,0))
        pal1:setRGB(0,R.RGB:new(0,0,0))
        for i=1,15 do
            local s1=i/15
            local s0=s1/4
            pal0:setRGB(i,R.RGB:new(rgbRMan.r*s0,rgbRMan.g*s0,rgbRMan.b*s0))
            pal1:setRGB(i,R.RGB:new(rgbRMan.r*s1,rgbRMan.g*s1,rgbRMan.b*s1))
        end
        local blend=1
        if unitT>.5 then
            local t=((unitT-.5)/.5)*math.pi*2*6
            blend=.5+math.cos(t)*.5
        end
        pal0:applyBlend(pal1,blend)

        vbank(1)
        R.setRGB(1,R.RGB:new(0,0,0))
    end,
    musicTic=function(isFirstRun,t,unitT)
        if isFirstRun then
            music(2,-1,-1,false)
            SCENE=R.Scene:new()

            MODEL_GMAN=R.Model:new()
            MODEL_GMAN:load(require("./data/model/redman"))

            ACTOR_GMAN=R.Actor:new(MODEL_GMAN)
            ACTOR_GMAN:setDrawFn(R.poly.Draw1Colour(1),0)

            SCENE:registerActor(ACTOR_GMAN)
        end

        vbank(0)
        cls(0)  
        
        local mat=R.M44:new(R.M44.ID)
        local x,y,z,yr,zr=0,0,0,0,0
        local zBack=3
        if unitT < .4 then
            z=0
        elseif unitT <.7 then
            local inT=(unitT-.4)/.3
            local bounce=math.pi*10
            z=inT*zBack
            y=math.abs(math.sin(inT*bounce))
        elseif unitT <.9 then
            z=zBack
        else
            local inT=(unitT-.9)/.1
            local bounce=math.pi*10
            z=math.max(zBack-inT*(2+zBack),-1.5)
            x=math.sin(inT*bounce)*.5
            y=math.abs(math.sin(inT*bounce))
            zr=math.sin(inT*bounce)*.6
        end
        mat:mulM44(R.M44:newTrans(x*.2,y*-.2,2.2+z))
        mat:mulM44(R.M44:newRotZ(zr*.2))
        ACTOR_GMAN:setMat(mat)

        SCENE:draw()
        lampFilter(120,68,70)
    end,
}
