Skip to content

Instantly share code, notes, and snippets.

@henrikno
Created May 26, 2013 22:47
Show Gist options
  • Save henrikno/5654312 to your computer and use it in GitHub Desktop.
Save henrikno/5654312 to your computer and use it in GitHub Desktop.
#include "Font.h"
#include <GL/glew.h>
#include <cstdio>
#include <cassert>
#include <cstdlib>
void Font::SetHeight(float h) {
m_height = h;
}
bool Font::LoadFromFile(const std::string &filename) {
FILE *fd = fopen(filename.c_str(), "rb");
char *ttf_buffer = new char[1<<20];
assert(fd != 0);
int rc = fread(ttf_buffer, 1, 1<<20, fd);
assert(rc > 0);
int texture_width = 512;
int texture_height = 512;
fclose(fd);
stbtt_BakeFontBitmap((const unsigned char*)ttf_buffer, 0, m_height, temp_bitmap, texture_width, texture_height, 32, 96, cdata); // no guarantee this fits!
free(ttf_buffer);
glGenTextures(1, &ftex);
glBindTexture(GL_TEXTURE_2D, ftex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texture_width, texture_height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
// can free temp_bitmap at this point
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
return true;
}
void Font::Draw(float x, float y, std::string text) {
// assume orthographic projection with units = screen pixels, origin at top left
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ftex);
glPushMatrix();
glBegin(GL_TRIANGLES);
for (size_t i = 0; i < text.size(); ++i) {
char c = text[i];
if (c >= 32) {
stbtt_aligned_quad q;
stbtt_GetBakedQuad(cdata, 512, 512, c-32, &x,&y,&q,1);
glTexCoord2f(q.s0, q.t0); glVertex2f(q.x0, q.y0);
glTexCoord2f(q.s1, q.t1); glVertex2f(q.x1, q.y1);
glTexCoord2f(q.s1, q.t0); glVertex2f(q.x1, q.y0);
glTexCoord2f(q.s0, q.t0); glVertex2f(q.x0, q.y0);
glTexCoord2f(q.s0, q.t1); glVertex2f(q.x0, q.y1);
glTexCoord2f(q.s1, q.t1); glVertex2f(q.x1, q.y1);
}
}
glEnd();
glPopMatrix();
}
#pragma once
#include "Resource.h"
#include "stb_truetype.h"
class Font : public Resource {
public:
Font() {
m_height = 16.0;
ftex = 0;
}
bool LoadFromFile(const std::string &filename);
void Draw(float x, float y, std::string text);
void SetHeight(float h);
float GetHeight() { return m_height; }
private:
unsigned char temp_bitmap[512*512];
stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
unsigned int ftex;
float m_height;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment