Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Probably the most basic example of using Texture Buffer Objects (TBOs) with openGL
#include "GridDrawer.h"
#include "Grid.h"
GridDrawer::GridDrawer(Grid& grid)
memset(ortho_matrix, 0x00, sizeof(ortho_matrix));
GridDrawer::~GridDrawer() {
void GridDrawer::setup(int w, int h) {
rx_ortho(0, w, h, 0, -1.0, 1.0, ortho_matrix);
grid_prog = rx_create_shader(GD_VS, GD_FS);
glBindAttribLocation(grid_prog, 0, "a_pos");
u_projection_matrix = glGetUniformLocation(grid_prog, "u_projection_matrix");
glUniformMatrix4fv(u_projection_matrix, 1, GL_FALSE, ortho_matrix);
u_tbo_tex = glGetUniformLocation(grid_prog, "u_tbo_tex");
glGenVertexArrays(1, &grid_vao);
glGenBuffers(1, &grid_vbo);
glBindBuffer(GL_ARRAY_BUFFER, grid_vbo);
glBufferData(GL_ARRAY_BUFFER, grid.getNumBytes(), grid.getPtr(), GL_STATIC_DRAW); // gird just returns 2 triangles that form a quad
glEnableVertexAttribArray(0); // position
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GridVertex), (GLvoid*)0);
// TBO
float tbo_data[] = {
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
1.0f, 0.0f, 1.0f
glGenBuffers(1, &tbo);
glBindBuffer(GL_TEXTURE_BUFFER, tbo);
glBufferData(GL_TEXTURE_BUFFER, sizeof(tbo_data), tbo_data, GL_STATIC_DRAW);
glGenTextures(1, &tbo_tex);
glBindBuffer(GL_TEXTURE_BUFFER, 0);
void GridDrawer::draw() {
glBindTexture(GL_TEXTURE_BUFFER, tbo_tex);
glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, tbo);
glUniform1i(u_tbo_tex, 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
#include <roxlu/Roxlu.h>
static const char* GD_VS = GLSL(150,
uniform mat4 u_projection_matrix;
uniform samplerBuffer u_tbo_tex;
in vec4 a_pos;
out float r;
out float g;
out float b;
void main() {
int offset = 6; // 0 = red, 3 = green, 6 = magenta
r = texelFetch(u_tbo_tex, offset + 0).r;
g = texelFetch(u_tbo_tex, offset + 1).r;
b = texelFetch(u_tbo_tex, offset + 2).r;
gl_Position = u_projection_matrix * a_pos;
static const char* GD_FS = GLSL(150,
out vec4 outcol;
in float r;
in float g;
in float b;
void main() {
outcol = vec4(r, g, b, 1.0);
class Grid;
class GridDrawer {
GridDrawer(Grid& grid);
void setup(int w, int h);
void draw();
Grid& grid;
GLint u_projection_matrix;
float ortho_matrix[16];
/* shader */
GLuint grid_prog;
GLuint grid_vao;
GLuint grid_vbo;
/* tbo test */
GLuint tbo;
GLuint tbo_tex;
GLint u_tbo_tex;
Copy link

andybrice commented Aug 4, 2015

This was helpful, thanks. Especially around line 40 of GridDrawer.cpp. It would be good to see the corresponding shaders too though.

Copy link

ghost commented Oct 26, 2015

Copy link

iaomw commented Nov 12, 2015

I am almost dead, there is no glTexBuffer on iOS with GLES2.0, and I don't know what's function of 'tbo_tex'.
How could I do this on iOS? Just want pass a huge array to shaders.

Copy link

phtaylor commented Jan 12, 2016

thanks. this was helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment