aboutsummaryrefslogtreecommitdiff
path: root/source/30-game/VertexIndex.cpp
blob: ac68289dc78d96b7c1263616c4775a3793e37ac5 (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
#include "VertexIndex.hpp"

#include <algorithm>

GpuVertexBuffer::GpuVertexBuffer() {
	glGenBuffers(1, &handle);
}

GpuVertexBuffer::~GpuVertexBuffer() {
	glDeleteBuffers(1, &handle);
}

void GpuVertexBuffer::Upload(const std::byte* data, size_t sizeInBytes) {
	glBindBuffer(GL_ARRAY_BUFFER, handle);
	glBufferData(GL_ARRAY_BUFFER, sizeInBytes, data, GL_DYNAMIC_DRAW);
}

GpuIndexBuffer::GpuIndexBuffer() {
	glGenBuffers(1, &handle);
}

GpuIndexBuffer::~GpuIndexBuffer() {
	glDeleteBuffers(1, &handle);
}

void GpuIndexBuffer::Upload(const std::byte* data, Tags::IndexType type, size_t count) {
	this->indexType = type;
	this->count = count;
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * Tags::SizeOf(type), data, GL_DYNAMIC_DRAW);
}

int BufferBindings::GetMaxBindingIndex() const {
	return bindings.size() - 1;
}

GpuVertexBuffer* BufferBindings::GetBinding(int index) const {
	if (index >= 0 && index < bindings.size()) {
		return bindings[index].Get();
	} else {
		return nullptr;
	}
}

void BufferBindings::SetBinding(int index, GpuVertexBuffer* buffer) {
	int maxBindingIndex = GetMaxBindingIndex();
	if (index > maxBindingIndex) {
		int countDelta = index - maxBindingIndex;
		bindings.resize(bindings.size() + countDelta);
	}

	bindings[index].Attach(buffer);
	if (index == maxBindingIndex && buffer == nullptr) {
		bindings.pop_back();
	}
}

void BufferBindings::Clear() {
	bindings.clear();
}

int VertexElementFormat::GetStride() const {
	return Tags::SizeOf(type);
}

void VertexFormat::AddElement(VertexElementFormat element) {
	vertexSize += element.GetStride();

	int lastIdx = (int)elements.size() - 1;
	if (lastIdx >= 0) {
		auto& last = elements[lastIdx];
		element.offset = last.offset + last.GetStride();
	} else {
		element.offset = 0;
	}

	elements.push_back(std::move(element));
}

void VertexFormat::RemoveElement(int index) {
	auto& element = elements[index];
	vertexSize -= element.GetStride();
	elements.erase(elements.begin() + index);
}