#include "stdafx.h"
#include "PostProcBuffer.h"



void PostProcBuffer::RebuildIfResized(int w, int h)
{
	if (m_BufWidth == w && m_BufHeight == h)
		return;

	ReleaseBuf();

	InitializeOnce(w, h);
}

void PostProcBuffer::InitializeOnce(int w, int h)
{
	if (m_IsInitialized)
		return;

	Initialize(w, h);

	m_IsInitialized = true;
}

void PostProcBuffer::Initialize(int w, int h)
{
	m_BufWidth = w;
	m_BufHeight = h;

	InitializeDethBuffer();

	InitializeColorBuffer();

	AssignFBOToFrameBufObjects();
}

void PostProcBuffer::InitializeDethBuffer(void)
{
	m_DepthBuf.GenerateTexture();
	m_DepthBuf.Bind();
	glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR);
	glTexWrapST2D(GL_CLAMP, GL_CLAMP);

	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_DEPTH_COMPONENT,
		m_BufWidth,
		m_BufHeight,
		0,
		GL_DEPTH_COMPONENT,
		GL_FLOAT,
		0);
}

void PostProcBuffer::InitializeColorBuffer(void)
{
	m_ColorBuf.GenerateTexture();
	m_ColorBuf.Bind();
	glTexMinMagFilter2D(GL_LINEAR, GL_LINEAR);
	glTexWrapST2D(GL_CLAMP, GL_CLAMP);

	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_RGBA,
		m_BufWidth,
		m_BufHeight,
		0,
		GL_RGBA,
		GL_FLOAT,
		0);
}

void PostProcBuffer::AssignFBOToFrameBufObjects(void)
{
	m_Fbo.Generate();
	m_Fbo.BeginFBO();

	// for depth texture
	m_Fbo.BindFboTexture(GL_DEPTH_ATTACHMENT_EXT, m_DepthBuf.GetID(), 0);

	// for color color renderbuffer
	m_Fbo.BindFboTexture(GL_COLOR_ATTACHMENT0_EXT, m_ColorBuf.GetID(), 0);

	m_Fbo.EndFBO();
}

void PostProcBuffer::ReleaseBuf(void)
{
	m_IsInitialized = false;

	m_Fbo.Release();
	m_ColorBuf.ReleaseTexture();
	m_DepthBuf.ReleaseTexture();
}


//! フレームバッファオブジェクトのりサイズ
//! 出来るだけバッファ破棄, 再生成が少なくなるようにする
void MultPathRenderBuf::ResizePathCount(size_t num_path)
{
	if (num_path == m_PPAry.size())
		return;

	if (num_path < m_PPAry.size())
	{
		for (size_t i = num_path; i < m_PPAry.size(); ++i)
		{
			m_PPAry[i].ReleaseBuf();
		}
	}

	m_PPAry.resize(num_path);
}
