109 lines
2.4 KiB
C++
109 lines
2.4 KiB
C++
#include "font.h"
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <assert.h>
|
|
#include <SDL2/SDL_opengl.h>
|
|
#include "texture.h"
|
|
#include "renderer.h"
|
|
|
|
static float colors[16][4] = {
|
|
{0, 0, 0, 1},
|
|
{0.5f, 0, 0, 1},
|
|
{0, 0.5f, 0, 1},
|
|
{0.5f, 0.5f, 0, 1},
|
|
{0, 0, 0.5f, 1},
|
|
{0.5f, 0, 0.5f, 1},
|
|
{0, 0.5f, 0.5f, 1},
|
|
{0.75f, 0.75f, 0.75f, 1},
|
|
{0.5f, 0.5f, 0.5f, 1},
|
|
{1, 0, 0, 1},
|
|
{0, 1, 0, 1},
|
|
{1, 1, 0, 1},
|
|
{0, 0, 1, 1},
|
|
{1, 0, 1, 1},
|
|
{0, 1, 1, 1},
|
|
{1, 1, 1, 1},
|
|
};
|
|
|
|
void Font::Load(const char* filename)
|
|
{
|
|
char name[16]; strcpy(name, filename); strcat(name, ".fnt");
|
|
|
|
FILE* fin = fopen(name, "ra");
|
|
if (fin == NULL) return;
|
|
|
|
char line[256];
|
|
|
|
fgets(line, 255, fin);
|
|
fgets(line, 255, fin);
|
|
int lh, sw, sh;
|
|
assert(sscanf(line, "common lineHeight=%i base=%*i scaleW=%i scaleH=%i", &lh, &sw, &sh) == 3);
|
|
lineHeight = lh;
|
|
bw = sw;
|
|
bh = sh;
|
|
|
|
fgets(line, 255, fin);
|
|
fgets(line, 255, fin);
|
|
int numChars;
|
|
assert(sscanf(line, "chars count=%i", &numChars) == 1);
|
|
|
|
for (int i = 0; i < numChars; i++) {
|
|
fgets(line, 255, fin);
|
|
int id, x, y, w, h, xo, yo, xa;
|
|
assert(sscanf(line, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i", &id, &x, &y, &w, &h, &xo, &yo, &xa) == 8);
|
|
FontChar& c = chars[id-32];
|
|
c.w = w;
|
|
c.h = h;
|
|
c.x1 = float(x)/float(bw);
|
|
c.y1 = float(y)/float(bh);
|
|
c.x2 = c.x1 + float(w)/float(bw);
|
|
c.y2 = c.y1 + float(h)/float(bh);;
|
|
c.xo = xo;
|
|
c.yo = yo;
|
|
c.xa = xa;
|
|
}
|
|
|
|
texture = Texture::Create();
|
|
Texture::Load(texture, filename);
|
|
fclose(fin);
|
|
}
|
|
|
|
void Font::Print(int x, int y, const char* text, char color)
|
|
{
|
|
const unsigned long len = strlen(text);
|
|
|
|
Renderer::SetState(RENDER_FILL | RENDER_BLEND | RENDER_TEXTURE);
|
|
glBindTexture(GL_TEXTURE_2D, texture);
|
|
glBegin(GL_QUADS);
|
|
glColor4fv(colors[color]);
|
|
for (int i = 0; i < len; i++) {
|
|
FontChar& c = chars[text[i]-32];
|
|
glTexCoord2f(c.x1, c.y1);
|
|
glVertex2i(x+c.xo, y+c.yo);
|
|
glTexCoord2f(c.x1, c.y2);
|
|
glVertex2i(x+c.xo, y+c.yo+c.h);
|
|
glTexCoord2f(c.x2, c.y2);
|
|
glVertex2i(x+c.xo+c.w, y+c.yo+c.h);
|
|
glTexCoord2f(c.x2, c.y1);
|
|
glVertex2i(x+c.xo+c.w, y+c.yo);
|
|
x += c.xa;
|
|
}
|
|
glEnd();
|
|
|
|
}
|
|
|
|
Vector2 Font::GetSize(const char* text)
|
|
{
|
|
Vector2 size;
|
|
size.y = lineHeight;
|
|
const unsigned long len = strlen(text);
|
|
for (int i = 0; i < len; i++) {
|
|
//if (i == len-1) {
|
|
// size.x += chars[text[i]-32].w;
|
|
//} else {
|
|
size.x += chars[text[i]-32].xa;
|
|
//}
|
|
}
|
|
return size;
|
|
}
|