#include <windows.h>
#include "uitexture.h"

// ----------------------------------------------------------------------------------
CUiTexture::CUiTexture(const char* name, CUiLayout* pParent, CUi* pUi)
	: CUiLayout(name, pParent, pUi)
{	
	m_backupAlphaMode	= ALPHA_MODE_BLEND;
	m_alphaMode			= ALPHA_MODE_BLEND;	
	m_texCoords.clear();

	m_animationSpeed	= 0.0f;
	m_animationTime		= 0.0f;
}

// ----------------------------------------------------------------------------------
CUiTexture::~CUiTexture()
{
}

// ----------------------------------------------------------------------------------
void CUiTexture::Update(float elapsedTime)
{
	m_animationTime += elapsedTime;
}

// ----------------------------------------------------------------------------------
void CUiTexture::Render(float alpha)
{
	Render(alpha, m_position.m_x, m_position.m_y, 1.0f, 1.0f);
}

// ----------------------------------------------------------------------------------
void CUiTexture::Render(float alpha, float wScale, float hScale)
{
	Render(alpha, m_position.m_x, m_position.m_y, wScale, hScale);
}

// ----------------------------------------------------------------------------------
void CUiTexture::Render(float alpha, float x, float y, float wScale, float hScale)
{
	if ( !m_isVisible )
		return;

	CRuRectangle tex, dest;
	CUiSize size = GetRealSize();

	// 取得貼圖座標
	if ( !m_texCoords.empty() )
	{
		DWORD texPos = 0;
		if ( m_animationSpeed > 0.0f && m_texCoords.size() > 1 )
			texPos = (DWORD)((m_animationTime + m_animationTime) * m_animationSpeed) % m_texCoords.size();

		tex.m_left		= m_texCoords[texPos].m_left;
		tex.m_top		= m_texCoords[texPos].m_top;
		tex.m_right		= m_texCoords[texPos].m_right * wScale;
		tex.m_bottom	= m_texCoords[texPos].m_bottom * hScale;
	}
	else
		tex.Set( 0.0f, 0.0f, wScale, hScale );

	// 取得目的座標
	dest.m_left		= x;
	dest.m_top		= y;
	dest.m_right	= x + size.m_x * wScale;
	dest.m_bottom	= y + size.m_y * hScale;

	CUiRGBA color;
	color.m_value = m_color.GetColor();
	color.SetAlphaScale(alpha);

	// 繪出圖形
	m_textureImage.Draw(dest, tex, m_alphaMode, color.m_value);
}

// ----------------------------------------------------------------------------------
void CUiTexture::SetTexCoords(int count, CRuRectangle* pRectangle)
{
	m_texCoords.clear();
	for (int i = 0; i < count; i++)
		m_texCoords.push_back(pRectangle[i]);
}

// ----------------------------------------------------------------------------------
void CUiTexture::SetTexture(const CUiTexture* texture)
{
	if (texture)
	{
		m_color				= texture->m_color;
		m_textureImage		= texture->m_textureImage;		
		m_alphaMode			= texture->m_alphaMode;
		m_texCoords			= texture->m_texCoords;
		m_animationSpeed	= texture->m_animationSpeed;
	}
}
