#include "stdafx.h"
#include "GeometryVBO.h"

#include "Shader/ShaderInterface.h"

#define VBO_BUFFER_OFFSET(bytes) ((GLubyte *)NULL + (bytes))



GeometryVBO::GeometryVBO(void) :
	m_Vertex(GL_ARRAY_BUFFER),
	m_Normal(GL_ARRAY_BUFFER),
	m_Texture(GL_ARRAY_BUFFER),
	m_VCol(GL_ARRAY_BUFFER),
	m_Tangents(GL_ARRAY_BUFFER),
	m_Index(GL_ELEMENT_ARRAY_BUFFER)
{
}

void GeometryVBO::Release(void)
{
	m_Vertex.ReleaseBufferElement();
	m_Normal.ReleaseBufferElement();
	m_Texture.ReleaseBufferElement();
	m_VCol.ReleaseBufferElement();
	m_Tangents.ReleaseBufferElement();
	m_Index.ReleaseBufferElement();

	NumTriangles = 0;
}

void GeometryVBO::DrawVBOAll(GLenum primiType, ShaderInterface* shader, const VertAttrOption& attr)
{
	if (!m_Vertex.HasBuffer())
		return;

	glEnableClientState(GL_VERTEX_ARRAY);
	m_Vertex.Bind();
	glVertexPointer(3, GL_FLOAT, 0, VBO_BUFFER_OFFSET(0));

	if (m_Normal.HasBuffer())
		m_Normal.BindPtrAsNoral();
	
	if (m_Texture.HasBuffer())
		m_Texture.BindPtrAsTexcoord();

	if (attr.vertCol)
	{
		if (m_VCol.HasBuffer())
			m_VCol.BindPtrAsColor();
	}

	GLint tbuf_id = -1;
	if (attr.tangent)
	{
		if (m_Tangents.HasBuffer())
		{
			tbuf_id = shader->GetTangentAttribIndex();
			if (tbuf_id != -1)
				m_Tangents.BindPtrAsAttrib3f(tbuf_id);
		}
	}

	m_Index.Bind();
	glDrawElements(primiType, NumTriangles * 3 * 4, GL_UNSIGNED_INT, VBO_BUFFER_OFFSET(0));

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	if (tbuf_id != -1)
		glDisableVertexAttribArray(tbuf_id);
}
