#include "StdAfx.h"
#include "ShadowMap.h"

#include <LibTest/DebugStream.h>

#include "../ShaderUtil.h"



ShadowMap::ShadowMap(ShaderContext* context) :
	ShaderInterface(context)
{
}

bool ShadowMap::Initialize(const std::string& shader_libdir)
{
	if( !InitializeShader(shader_libdir) )
		return false;

	return true;
}

bool ShadowMap::InitializeShader(const std::string& shader_libdir)
{
	std::string vert_filename = shader_libdir + "shadowmap.vert";
	std::string frag_filename = shader_libdir + "shadowmap.frag";

	return ShaderUtil::InitShaderStd(m_Shader, frag_filename, vert_filename);
}


void ShadowMap::BeginShader(void)
{
	m_Shader.BeginShader();

	SceneMain* scene = m_Context->m_Scene;
	ShadowBuffer& shadow = m_Context->m_ShadowBuf;

	GLint mat_loc = m_Shader.GetUniformLocation("shadow_mat");
	glUniformMatrix4fv(mat_loc, 1, GL_FALSE, shadow.m_ShadowMatrix.v());

	glActiveTexture(GL_TEXTURE1);
	shadow.m_ShadowBuffer.Bind();

	glActiveTexture(GL_TEXTURE0);

	glUniform1i(m_Shader.GetUniformLocation("tex_color"), 0);
	glUniform1i(m_Shader.GetUniformLocation("shadow_buffer"), 1);

	glUniform1i(m_Shader.GetUniformLocation("enable_shadow"), scene->m_ShadowConfig.m_EnableShadow);
	glUniform1i(m_Shader.GetUniformLocation("enable_softshadow"), scene->m_ShadowConfig.m_EnableSoftShadow);

	glUniform1f(m_Shader.GetUniformLocation("color_shadow_ratio"), scene->m_ShadowConfig.m_ShadowDarkness);
}

void ShadowMap::EndShader(void)
{
	m_Shader.EndShader();
}


void ShadowMap::SetTextureEnabled(bool enabled)
{
	glUniform1i( m_Shader.GetUniformLocation( "enable_texture" ) , enabled ? 1 : 0 );
}

void ShadowMap::SetDublesideEnabled(bool enabled)
{
	glUniform1i( m_Shader.GetUniformLocation( "enable_doubleside" ) , enabled ? 1 : 0 );
}

void ShadowMap::SetLightingEnabled(bool enabled)
{
	glUniform1i( m_Shader.GetUniformLocation( "enable_lighting" ) , enabled ? 1 : 0 );
}
