diff --git a/src/libvgcode/src/SegmentTemplate.cpp b/src/libvgcode/src/SegmentTemplate.cpp index 4e692d5b10..9d9872aa3b 100644 --- a/src/libvgcode/src/SegmentTemplate.cpp +++ b/src/libvgcode/src/SegmentTemplate.cpp @@ -15,7 +15,12 @@ namespace libvgcode { //| 2--0-------5--7 | //| \ | | / | //| 3-------4 | -static constexpr const std::array VERTEX_DATA = { +// The eight corners the vertex shader knows how to place. Each is sent once and +// referenced by INDEX_DATA below, so the post-transform cache can reuse it across +// the triangles that share it: the shader runs 8 times per segment instead of 24. +static constexpr const std::array VERTEX_DATA = { 0, 1, 2, 3, 4, 5, 6, 7 }; + +static constexpr const std::array INDEX_DATA = { 0, 1, 2, // front spike 0, 2, 3, // front spike 0, 3, 4, // right/bottom body @@ -31,7 +36,7 @@ void SegmentTemplate::init() if (m_vao_id != 0) return; - m_size_in_bytes_gpu += VERTEX_DATA.size() * sizeof(uint8_t); + m_size_in_bytes_gpu += (VERTEX_DATA.size() + INDEX_DATA.size()) * sizeof(uint8_t); int curr_vertex_array; glsafe(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curr_vertex_array)); @@ -51,12 +56,22 @@ void SegmentTemplate::init() glsafe(glVertexAttribIPointer(0, 1, GL_UNSIGNED_BYTE, 0, (const void*)0)); #endif // ENABLE_OPENGL_ES + // The element buffer binding is part of the vao state, so it is left bound here + // and restored together with the vao. + glsafe(glGenBuffers(1, &m_ibo_id)); + glsafe(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo_id)); + glsafe(glBufferData(GL_ELEMENT_ARRAY_BUFFER, INDEX_DATA.size() * sizeof(uint8_t), INDEX_DATA.data(), GL_STATIC_DRAW)); + glsafe(glBindBuffer(GL_ARRAY_BUFFER, curr_array_buffer)); glsafe(glBindVertexArray(curr_vertex_array)); } void SegmentTemplate::shutdown() { + if (m_ibo_id != 0) { + glsafe(glDeleteBuffers(1, &m_ibo_id)); + m_ibo_id = 0; + } if (m_vbo_id != 0) { glsafe(glDeleteBuffers(1, &m_vbo_id)); m_vbo_id = 0; @@ -71,14 +86,15 @@ void SegmentTemplate::shutdown() void SegmentTemplate::render(size_t count) { - if (m_vao_id == 0 || m_vbo_id == 0 || count == 0) + if (m_vao_id == 0 || m_vbo_id == 0 || m_ibo_id == 0 || count == 0) return; int curr_vertex_array; glsafe(glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curr_vertex_array)); glsafe(glBindVertexArray(m_vao_id)); - glsafe(glDrawArraysInstanced(GL_TRIANGLES, 0, static_cast(VERTEX_DATA.size()), static_cast(count))); + glsafe(glDrawElementsInstanced(GL_TRIANGLES, static_cast(INDEX_DATA.size()), GL_UNSIGNED_BYTE, + nullptr, static_cast(count))); glsafe(glBindVertexArray(curr_vertex_array)); } diff --git a/src/libvgcode/src/SegmentTemplate.hpp b/src/libvgcode/src/SegmentTemplate.hpp index f104eef5d2..117ed2b678 100644 --- a/src/libvgcode/src/SegmentTemplate.hpp +++ b/src/libvgcode/src/SegmentTemplate.hpp @@ -40,6 +40,7 @@ private: // unsigned int m_vao_id{ 0 }; unsigned int m_vbo_id{ 0 }; + unsigned int m_ibo_id{ 0 }; // // Size of the data sent to gpu, in bytes. //