What I tried:
I was testing some things in order to render text with stb_truetype.h and OpenGL in C.
I took as a reference the example that appears here. Basically, this example, loads a .ttf file and returns the raw information in bytes, that can be used to generate a texture in OpenGL.
I adapted the example, mentioned before, into modern OpenGL, because, the example uses OpenGL deprecated functions, like glVertex2f
. The only thing I get to output on screen was this kind of noise of strange colors:
The code I use:
texture_t fnt_texture;
GLuint fnt_shader;
unsigned char ttf_buffer[1 << 20];
unsigned char temp_bitmap[512 * 512];
stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
#define FONT_VS\
"#version 330 core\n"\
"layout(location = 0) in vec3 m_Position;"\
"layout(location = 1) in vec2 m_TexCoords;"\
"out vec2 TexCoords;\n"\
"void main() {\n"\
"TexCoords = m_TexCoords;\n"\
"gl_Position = vec4(m_Position, 1.0);\n"\
"}\n"\
#define FONT_FS\
"#version 330 core\n"\
"in vec2 TexCoords;\n"\
"uniform sampler2D Texture;\n"\
"void main() {\n"\
"gl_FragColor = texture(Texture, TexCoords);\n"\
"}\n"\
void font_init(void)
{
fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
stbtt_BakeFontBitmap(ttf_buffer, 0, 32.0, temp_bitmap, 512, 512, 32, 96, cdata); // no guarantee this fits!
glGenTextures(1, &fnt_texture[3]); // My texture type, is an array that saves the texture on the 3rd position.
glBindTexture(GL_TEXTURE_2D, fnt_texture[3]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 512, 512, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp_bitmap);
glGenerateMipmap(GL_TEXTURE_2D);
// can free temp_bitmap at this point
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
fnt_shader = shader_init(FONT_VS, FONT_FS);
}
void font_render(model_t model)
{
shader_bind(fnt_shader);
texture_bind(fnt_texture, 0);
model_begin(model);
model_draw(model, GL_TRIANGLES); // The model (vao, vbo, ibo) is rendering the whole buffer, not individual glyphs
model_end();
texture_unbind();
shader_unbind();
}
Can someone tell me what I'm doing wrong, and, how I'm suposed to render correctly text, with modern OpenGL, with textures and buffers, in order to read the .ttf file and create the necessary information with stb_truetype.h and, then, render the text?