#include "Canvas.h"
#include "EngineCore/Game.h"
#include "EngineFrame/Render/RenderManager.h"
Canvas::Canvas(VecSize size)
{
    m_texture = new Texture();
    m_texture->Init(size);
    m_sprite = new Sprite();
    m_sprite->SetTexture(m_texture);

    Actor::Init();

    glGenFramebuffers(1, &m_fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
    // 将目标纹理附加到FBO的颜色附着点
    glFramebufferTexture2D(
        GL_FRAMEBUFFER,       // 帧缓冲类型
        GL_COLOR_ATTACHMENT0, // 颜色附着点（可多个，这里用第一个）
        GL_TEXTURE_2D,        // 纹理类型
        m_texture->getID(),   // 目标纹理ID
        0                     // 多级渐远纹理级别
    );
    glBindFramebuffer(GL_FRAMEBUFFER, 0); // 解绑FBO
}

void Canvas::PreRender()
{
    if (m_dirty)
    {
        glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); // 绑定FBO
        // glViewport(0, 0, m_texture->getSize().width, m_texture->getSize().height);
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // 全透明黑色
        glClear(GL_COLOR_BUFFER_BIT);
        Actor::PreRender();
    }
    else
    {
        m_sprite->PreRender();
    }
}

void Canvas::Render()
{
    if (m_dirty)
    {

        Actor::Render();
        glBindFramebuffer(GL_FRAMEBUFFER, 0); // 解绑FBO
        // glViewport(0, 0, Game::GetInstance().Screen_W, Game::GetInstance().Screen_H);
        m_dirty = false;
    }
    RenderManager *renderer = Game::GetInstance().GetRenderer();
    renderer->SetCurrentShaderProgram("flip_y");
    m_sprite->Render();
    renderer->SetCurrentShaderProgram("normal");
}

void Canvas::AddChild(RefPtr<BaseNode> child)
{
    m_dirty = true;
    Actor::AddChild(child);
}
