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

local function drawBuf(buf,w,h,dx0,dy0,dp,pixR)
    for oy=0,h do
        for ox=0,w do
            local dx,dy=dx0+ox,dy0+oy
--            local sp=pix(dx,dy)
            local bp=buf[oy*w+ox]
            if bp>0 then
                if math.random()<pixR then
                    pix(dx,dy,dp)
                end
--                pix(dx,dy,sp+1)
            end
        end    
    end
end

return {
    bdr=function(y,t,unitT)
        vbank(0)
        local rgbMen={GLOBAL.rgbGMan,R.RGB:new(.85,.85,0),R.RGB:new(0,.85,.85),R.RGB:new(1,.2,.2),R.RGB:new(.2,.2,1)}
        local tBlend=0.5+math.sin(unitT*math.pi)*.5
        for i=1,#rgbMen do
            R.setRGB(i,rgbMen[1]:getBlendTo(rgbMen[i],tBlend))
        end

        local s=math.sin(unitT*math.pi)
        R.setRGB(0,R.RGB:new(s,s,s))
    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(R.poly.Draw1Colour(10),0)
            
            SCENE:registerActor(ACTOR_GMAN)
        end

        GLOBAL.walkAnimWrapper(ACTOR_GMAN,unitT)
        local manX,manY,manW,manH=80,10,80,120

        vbank(1)
        cls(0)
        SCENE:draw()
        local buf={}
        for oy=0,manH do
            for ox=0,manW do
                local x,y=manX+ox,manY+oy
                buf[oy*manW+ox]=pix(x,y)
            end    
        end

        vbank(0)
        cls(0)
        local xc=manX
        local xd=math.sin(unitT*math.pi)*85
        local yd=math.sin(math.sin(unitT*math.pi)*5)*10
        local pixR=.6+(.5+math.cos(unitT*math.pi*2)*.5)*.4
        drawBuf(buf,manW,manH,xc-xd,manY-yd,4,pixR)
        drawBuf(buf,manW,manH,xc+xd,manY+yd,5,pixR)
        drawBuf(buf,manW,manH,xc-xd/2,manY-yd/2,2,pixR)
        drawBuf(buf,manW,manH,xc+xd/2,manY+yd/2,3,pixR)
        drawBuf(buf,manW,manH,xc,manY,1,pixR)

        vbank(1)
        cls(0)
    end,
}
