From 6218601074e7070ccd5ded69a79f313d83a17cf6 Mon Sep 17 00:00:00 2001 From: Bad Diode Date: Mon, 29 Aug 2022 07:11:23 +0200 Subject: Add initial working example of instanced text drawing --- src/main.c | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main.c b/src/main.c index 7241409..2a901a3 100644 --- a/src/main.c +++ b/src/main.c @@ -208,6 +208,26 @@ render(Context *ctx) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(f32), (void*)(2 * sizeof(f32))); + // NOTE: This should be a dynamic array of offsets and index into the + // texture atlas. + struct Letter { + f32 x; + f32 y; + f32 idx; + }; + struct Letter letters[] = { + {-0.25, 0.0, 0}, + {0.0, 0.0, 1}, + {0.25, 0.0, 2}, + }; + u32 offset_vbo; + glGenBuffers(1, &offset_vbo); + glBindBuffer(GL_ARRAY_BUFFER, offset_vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(letters), letters, GL_STATIC_DRAW); + glEnableVertexAttribArray(2); + glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(f32), (void*)0); + glVertexAttribDivisor(2, 1); + // Element buffer object setup. u32 ebo; glGenBuffers(1, &ebo); @@ -243,14 +263,14 @@ render(Context *ctx) { "#version 330 core\n" "layout (location = 0) in vec2 position;\n" "layout (location = 1) in vec2 tex_coords;\n" -// TODO: layout (location = 2) in u32 index; +"layout (location = 2) in vec3 offset;\n" "out vec2 tex;\n" "void main() {\n" +" float idx = offset.z;\n" " float N = 3;\n" -" float idx = 2;\n" " float m = 1.0 / N;\n" " float k = m * idx;\n" -" gl_Position = vec4(position.x, position.y, 0.0, 1.0);\n" +" gl_Position = vec4(position / 8 + offset.xy, 0.0, 1.0);\n" " tex = tex_coords * vec2(m, 1.0) + vec2(k, 0.0);\n" "}"; @@ -288,7 +308,9 @@ render(Context *ctx) { // // glBlendEquation(GL_FUNC_ADD); // // glBindTexture(GL_TEXTURE_2D, text_tex); // TODO: Bind the texture atlas. - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); + // TODO: Send the number of instances as a uniform or see if you can query + // it from the GLSL for N. In this case N == 3. + glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, 3); // glDisable(GL_BLEND); glfwSwapBuffers(ctx->window); -- cgit v1.2.1