//
// Asura_GX_DisplayList.cpp
//
// Created by AS - 12 July 2007
//
// Copyright (C) 2007 Rebellion, All Rights Reserved.
//

#include "Core/Asura.h"

// This file's header
#include "Asura_GX_DisplayList.h"

// Asura
#include "ChunkSystem/Asura_Chunk_Stream.h"
#include "Debugging/Asura_Assert.h"
#include "FileAccess/Asura_FileAccess.h"

// Asura Wii
#include "Core/Asura_Wii_Mem2.h"


void Asura_GX_DisplayList::Iterator::ReadFromFile(Asura_Handle fileHandle, u_int uSize)
{
	if(uSize)
	{
		Asura_FileAccess::ReadData(fileHandle, m_pu8DisplayListMem, uSize);
		m_pu8DisplayListMem += uSize;
	}
}

void Asura_GX_DisplayList::Iterator::ReadFromStream(Asura_Chunk_Stream& xStream, u_int uSize)
{
	if(uSize)
	{
		xStream.Read(uSize, m_pu8DisplayListMem);
		m_pu8DisplayListMem += uSize;
	}
}

void Asura_GX_DisplayList::Iterator::Finalize(Asura_GX_DisplayList &xDisplayList, bool bPad)
{
	if (bPad)
	{
		unsigned int uPad = 32 - (((m_pu8DisplayListMem - (u_char*)xDisplayList.m_pvMem) & 31));
		Asura_Mem::Set(m_pu8DisplayListMem, 0, uPad); // GX_NOP
		m_pu8DisplayListMem += uPad; 
	} else {
		Asura_Assert(((m_pu8DisplayListMem - (u_char*)xDisplayList.m_pvMem) & 31) == 0, "Display list size not aligned");
	}
	Asura_Assertf(m_pu8DisplayListMem - xDisplayList.GetSize() == ((u_char*)xDisplayList.m_pvMem) , ("Display list mis-calculation, allocated %d but used %d", xDisplayList.GetSize(), m_pu8DisplayListMem -((u_char*)xDisplayList.m_pvMem) ));
	DCFlushRange(xDisplayList.m_pvMem, xDisplayList.GetSize());
}

void Asura_GX_DisplayListBlock::Initialise(unsigned int uSize, bool bPad)
{
	Release();
	u_int uAlignedSize = uSize + (bPad ? 32 - (uSize & 31) : 0);
	m_xDisplayList.Initialise(ASURA_WII_MEM2_ALLOC(uAlignedSize), uAlignedSize);
}


void Asura_GX_DisplayListBlock::Release()
{
	if (m_xDisplayList.m_pvMem)
	{
		Asura_Wii_MEM2::Free(m_xDisplayList.m_pvMem);
		m_xDisplayList.Initialise(NULL, 0);
	}
}

void Asura_GX_DisplayListBlock::Iterator::Finalize(Asura_GX_DisplayListBlock &xDisplayListBlock)
{
	Asura_Assert(((m_pu8DisplayListMem - (u_char*)xDisplayListBlock.GetMem()) & 31) == 0, "Display list size not aligned");
	Asura_Assert(m_pu8DisplayListMem == ((u_char*)xDisplayListBlock.GetMem()) + xDisplayListBlock.GetSize(), "Display list mis-calculation");
}


