source: trunk/src/font.cpp @ 87

Last change on this file since 87 was 87, checked in by sam, 10 years ago

Naive font renderer prototype.

  • Property svn:keywords set to Id
File size: 1.8 KB
Line 
1
2#ifdef WIN32
3#   define WIN32_LEAN_AND_MEAN
4#   include <windows.h>
5#endif
6#if defined __APPLE__ && defined __MACH__
7#   include <OpenGL/gl.h>
8#else
9#   define GL_GLEXT_PROTOTYPES
10#   include <GL/gl.h>
11#endif
12
13#include <SDL.h>
14#include <SDL_image.h>
15
16#include "font.h"
17
18/*
19 * Font implementation class
20 */
21
22class FontData
23{
24    friend class Font;
25
26private:
27    SDL_Surface *img;
28    GLuint texture[1];
29};
30
31/*
32 * Public Font class
33 */
34
35Font::Font(char const *path)
36{
37    data = new FontData();
38    data->img = NULL;
39
40    for (char const *name = path; *name; name++)
41        if ((data->img = IMG_Load(name)))
42            break;
43
44    if (!data->img)
45    {
46        SDL_Quit();
47        exit(1);
48    }
49
50    glGenTextures(1, data->texture);
51    glBindTexture(GL_TEXTURE_2D, data->texture[0]);
52
53    glTexImage2D(GL_TEXTURE_2D, 0, 4, data->img->w, data->img->h, 0,
54                 GL_RGBA, GL_UNSIGNED_BYTE, data->img->pixels);
55
56    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
57    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
58}
59
60Font::~Font()
61{
62    glDeleteTextures(1, data->texture);
63    SDL_FreeSurface(data->img);
64
65    delete data;
66}
67
68void Font::Print(int x, int y, char const *str)
69{
70    int w = data->img->w / 16;
71    int h = data->img->h / 16;
72
73    glBindTexture(GL_TEXTURE_2D, data->texture[0]);
74    glBegin(GL_QUADS);
75    while (*str)
76    {
77        uint32_t ch = (uint8_t)*str++;
78        float tx = .0625f * (ch & 0xf);
79        float ty = .0625f * ((ch >> 4) & 0xf);
80
81        glTexCoord2f(tx, ty);
82        glVertex2f(x, y);
83        glTexCoord2f(tx + .0625f, ty);
84        glVertex2f(x + w, y);
85        glTexCoord2f(tx + .0625f, ty + .0625f);
86        glVertex2f(x + w, y + h);
87        glTexCoord2f(tx, ty + .0625f);
88        glVertex2f(x, y + h);
89
90        x += w;
91    }
92    glEnd();
93}
94
Note: See TracBrowser for help on using the repository browser.