#include "..\inc\mystar.h"
#include "myDirect3D.h"

myStar::myStar(void)
{
	m_vFormat	= 0;
	m_vCount	= 0;
	m_vBuffer	= NULL;
	m_iCount	= 0;
	m_iBuffer	= NULL;
}

myStar::~myStar(void)
{
	clean();
}

bool myStar::init()
{
	// Setting up the Vertex Buffer
	myVertex verticies[] = {
		{150, 50,0.5,1,		0xffffffff},
		{ 50,100,0.5,1,		0xffffffff},
		{120,100,0.5,1,		0xffffffff},
		{180,100,0.5,1,		0xffffffff},
		{250,100,0.5,1,		0xffffffff},
		{ 30,250,0.5,1,		0xffffffff},
		{270,250,0.5,1,		0xffffffff},
	};
	m_vFormat = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
	m_vCount = 7;
	
	HRESULT hr;
	hr = myDirect3D::getDevice()->CreateVertexBuffer(
		sizeof(myVertex)*m_vCount,
		0,
		m_vFormat,
		D3DPOOL_DEFAULT,
		&m_vBuffer,
		NULL);
	if(FAILED(hr)) return false;

	void* data;
	hr = m_vBuffer->Lock(0,0,&data,0);
	if(FAILED(hr)) return false;
		memcpy(data,verticies,sizeof(myVertex)*m_vCount);	
	m_vBuffer->Unlock();

	// Setting up the Index Buffer
	WORD indicies[] = {
		2,4,5,  // blue triangle
		1,3,6,  // black triangle
		0,3,2	// red triangle
	};
	m_iCount = 9;

	hr = myDirect3D::getDevice()->CreateIndexBuffer(
		sizeof(WORD)*m_iCount,
		0,
		D3DFMT_INDEX16,
		D3DPOOL_DEFAULT,
		&m_iBuffer,
		NULL);
	if(FAILED(hr)) return false;

	data = NULL;
	hr = m_iBuffer->Lock(0,0,&data,0);
	if(FAILED(hr)) return false;
		memcpy(data,indicies,sizeof(WORD)*m_iCount);
	m_iBuffer->Unlock();

	myDirect3D::getD3D()->registerModel(this);
	return true;
}

void myStar::draw()
{
	myDirect3D::getDevice()->SetStreamSource(0,m_vBuffer,0,sizeof(myVertex));
	myDirect3D::getDevice()->SetIndices(m_iBuffer);
	myDirect3D::getDevice()->SetFVF(m_vFormat);
	myDirect3D::getDevice()->DrawIndexedPrimitive(
		D3DPT_TRIANGLELIST,0,0,m_vCount,0,3);
}

void myStar::clean()
{
	myDirect3D::getD3D()->unregisterModel(this);
	if(m_vBuffer == NULL)
	{
		m_vBuffer->Release();	
		m_vBuffer = NULL;
	}
	if(m_iBuffer == NULL)
	{
		m_iBuffer->Release();
		m_iBuffer = NULL;
	}
	m_vFormat	= 0;
	m_vCount	= 0;
	m_iCount	= 0;
}

