/*
 * GLLoader.cpp
 *
 *  Created on: 4 nov. 2020
 *      Author: simon
 */


#include "client/render/loader/GLLoader.h"
#include "client/render/GL.h"

namespace GL {

VertexArray::~VertexArray() {
	if (m_ID != 0)
		glDeleteVertexArrays(1, &m_ID);
}

VertexArray::VertexArray(unsigned int vertexCount) : m_VertexCount(vertexCount) {
	glGenVertexArrays(1, &m_ID);
}

void VertexArray::Bind() const {
	glBindVertexArray(m_ID);
}

void VertexArray::Unbind() const {
	glBindVertexArray(0);
}

void VertexArray::BindVertexBuffer(VertexBuffer& VertexBuffer) {
	VertexBuffer.Bind();
	VertexBuffer.BindVertexAttribs();
	m_VertexBuffers.push_back(std::move(VertexBuffer));
}

VertexBuffer::~VertexBuffer() {
	if (m_ID != 0)
		glDeleteBuffers(1, &m_ID);
}

VertexBuffer::VertexBuffer(const std::vector<float>& data, unsigned int stride) : m_DataStride(stride) {
	glGenBuffers(1, &m_ID);
	Bind();
	glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(data.size() * sizeof(float)), nullptr, GL_STATIC_DRAW);
	glBufferSubData(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(data.size() * sizeof(float)), data.data());
	Unbind();
}

void VertexBuffer::Bind() const {
	glBindBuffer(GL_ARRAY_BUFFER, m_ID);
}

void VertexBuffer::Unbind() const {
	glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void VertexBuffer::AddVertexAttribPointer(unsigned int index, unsigned int coordinateSize, unsigned int offset) {
	VertexAttribPointer pointer;
	pointer.m_Index = index;
	pointer.m_Size = coordinateSize;
	pointer.m_Offset = offset;
	m_VertexAttribs.push_back(pointer);
}

void VertexBuffer::BindVertexAttribs() const {
	for (const VertexAttribPointer& pointer : m_VertexAttribs) {
		glEnableVertexAttribArray(pointer.m_Index);
		glVertexAttribPointer(pointer.m_Index, static_cast<GLint>(pointer.m_Size), GL_FLOAT, false, m_DataStride * sizeof(float), reinterpret_cast<void*>(pointer.m_Offset));
	}
}
}