#include "dllinterface.h"
#include "DXViewPort.h"
#include "DeviceStateManager.h"
#include "TextureManager.h"

DXViewPort::DXViewPort(DeviceStateManager* const device)
{
	m_pDevice = device;
	ZeroMemory(&m_VPDesc, sizeof(D3DVIEWPORT9));
}

DXViewPort::~DXViewPort(void)
{
	//release all assoziated rendertargets
	//cant use FOREACH because VPRT deletes listelement
	ListElement<ViewPortRenderTexture> *el = m_lRenderTargets.GetHead();

	while(el)
	{
		ListElement<ViewPortRenderTexture> *eldel = el;
		el = el->GetNext();

		eldel->GetInfo()->Release();
	}
}

void DXViewPort::ReleaseRTRef(ViewPortRenderTexture* const rt)
{
	m_lRenderTargets.ReleaseElement((unsigned)rt);
}

void DXViewPort::SetRegion(const unsigned x, const unsigned y, const unsigned width, const unsigned height, const float minz, const float maxz)
{
	bool bNeedRestoreRT = m_VPDesc.Width != width || m_VPDesc.Height != height ? true : false;

	m_VPDesc.X = x;
	m_VPDesc.Y = y;
	m_VPDesc.Width = width;
	m_VPDesc.Height = height;
	m_VPDesc.MinZ = minz;
	m_VPDesc.MaxZ = maxz;

	if(bNeedRestoreRT)
	{
		FOREACH(el, m_lRenderTargets, ViewPortRenderTexture)
		{
			el->GetInfo()->Invalidate();
			el->GetInfo()->Restore();
		}
	}
}

ViewPortRenderTexture* DXViewPort::CreateViewPortRenderTexture(const float scale, const FORMAT fmt)
{
	ViewPortRenderTexture* const rt = m_pDevice->GetTextureManager()->CreateViewPortRenderTexture(this, fmt, scale);
	m_lRenderTargets.AddTail(rt, (unsigned)rt);
	return rt;
}