#include "Mix/Private/Graphics/DX11/ShaderConstant.h"
#include "Mix/Private/Graphics/DX11/Device.h"

namespace Mix{ namespace Graphics{ namespace DX11{

////////////////////////////////////////////////////////////////////////////////////////////////////
// Mix::Graphics::DX11::ShaderConstant
////////////////////////////////////////////////////////////////////////////////////////////////////

ShaderConstant* ShaderConstant::CreateInstance( Mix::Graphics::DX11::Device* pDevice, UInt32 size, Boolean bDynamic, ID3D11Buffer* pBuffer )
{
	return MIX_LIB_NEW_T( Mix::Memory::SECTION_GRAPHICS, ShaderConstant, pDevice, size, bDynamic, pBuffer );
}

ShaderConstant::ShaderConstant( Mix::Graphics::DX11::Device* pDevice, UInt32 size, Boolean bDynamic, ID3D11Buffer* pBuffer ) :
DeviceObject( pDevice ),
m_pDevice( pDevice ),
m_Size( size ),
m_bDynamic( bDynamic ),
m_pBuffer( pBuffer ),
m_bLock( False )
{
	MIX_ADD_REF( m_pDevice );
}

ShaderConstant::~ShaderConstant( void )
{
	MIX_RELEASE( m_pBuffer );
	MIX_RELEASE( m_pDevice );
}

ID3D11Buffer* ShaderConstant::GetInterface( void )
{
	return m_pBuffer;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Mix::Graphics::IShaderConstant
////////////////////////////////////////////////////////////////////////////////////////////////////

Boolean ShaderConstant::Lock( void )
{
	if( m_bDynamic == False )
	{
		return False;
	}

	if( m_pDevice->Map( m_pBuffer, m_bDynamic, m_Mapped ) != S_OK )
	{
		return False;
	}

	m_bLock = True;

	return True;
}

void ShaderConstant::Unlock( void )
{
	if( m_bLock == False )
	{
		return;
	}

	m_pDevice->Unmap( m_pBuffer );
	m_bLock = False;
}

Boolean ShaderConstant::Write( const void* pData, UInt32 dataSize )
{
	if( ( m_bLock == False ) || ( m_Size < dataSize ) )
	{
		return False;
	}

	Mix::Memory::Copy( m_Mapped.pData, pData, dataSize );

	return True;
}

UInt32 ShaderConstant::GetSize( void ) const
{
	return m_Size;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Mix::Graphics::IDeviceObject
////////////////////////////////////////////////////////////////////////////////////////////////////

Mix::Graphics::IDeviceObject::TYPE ShaderConstant::GetType( void ) const
{
	return Mix::Graphics::IDeviceObject::SHADER_CONSTANT;
}

}}}
