summaryrefslogtreecommitdiff
path: root/gfx/gl/vertexArrayObject.hpp
blob: 5b9fc60b26e1b54d796efba5117d508c4252713f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#pragma once

#include "collections.hpp"
#include "gl_traits.hpp"
#include <GL/glew.h>
#include <glm/common.hpp>

template<typename Vertex> class VertexArrayObject {
public:
	template<auto Vertex::*... attribs>
	static void
	configure(const GLuint arrayObject, const GLuint arrayBuffer, const GLuint indexBuffer,
			const SequentialCollection<Vertex> auto & vertices, const SequentialCollection<unsigned int> auto & indices)
	{
		glBindVertexArray(arrayObject);

		configure_attribs<attribs...>(arrayBuffer);
		data(vertices, arrayBuffer, GL_ARRAY_BUFFER);
		data(indices, indexBuffer, GL_ELEMENT_ARRAY_BUFFER);

		glBindVertexArray(0);
	}

	template<auto Vertex::*... attribs>
	static void
	configure(const GLuint arrayObject, const GLuint arrayBuffer, const SequentialCollection<Vertex> auto & vertices)
	{
		glBindVertexArray(arrayObject);

		configure_attribs<attribs...>(arrayBuffer);
		data(vertices, arrayBuffer, GL_ARRAY_BUFFER);

		glBindVertexArray(0);
	}

	template<auto Vertex::*... attribs>
	static void
	configure(const GLuint arrayObject, const GLuint arrayBuffer)
	{
		glBindVertexArray(arrayObject);

		configure_attribs<attribs...>(arrayBuffer);
		glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(sizeof(Vertex)), nullptr, GL_DYNAMIC_DRAW);

		glBindVertexArray(0);
	}

private:
	template<typename Data>
	static void
	data(const Data & data, const GLuint arrayBuffer, GLenum target)
	{
		using Value = typename Data::value_type;
		glBindBuffer(target, arrayBuffer);
		glBufferData(target, static_cast<GLsizeiptr>(sizeof(Value) * data.size()), data.data(), GL_STATIC_DRAW);
	}

	template<typename T>
	static void
	set_pointer(const GLuint vertexArrayId, const void * ptr)
	{
		glEnableVertexAttribArray(vertexArrayId);
		using traits = gl_traits<T>;
		traits::vertexAttribFunc(vertexArrayId, traits::size, traits::type, sizeof(Vertex), ptr);
	}

	template<auto Vertex::*attrib>
	static void
	set_pointer(const GLuint vertexArrayId)
	{
		set_pointer<std::decay_t<decltype(std::declval<Vertex>().*attrib)>>(
				vertexArrayId, &(static_cast<const Vertex *>(nullptr)->*attrib));
	}

	template<auto Vertex::*... attribs>
	static void
	configure_attribs(const GLuint arrayBuffer)
	{
		glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
		if constexpr (sizeof...(attribs) == 0) {
			set_pointer<Vertex>(0, nullptr);
		}
		else {
			GLuint vertexArrayId {};
			(set_pointer<attribs>(vertexArrayId++), ...);
		}
	}
};