source: trunk/src/tileset.cpp @ 87

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

Naive font renderer prototype.

  • Property svn:keywords set to Id
File size: 2.2 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 <malloc.h>
17
18#include "tileset.h"
19
20/*
21 * TileSet implementation class
22 */
23
24class TileSetData
25{
26    friend class TileSet;
27
28private:
29    static int Compare(void const *p1, void const *p2)
30    {
31        int const *n1 = (int const *)p1;
32        int const *n2 = (int const *)p2;
33
34        return n1[2] + 32 * n1[3] - (n2[2] + 32 * n2[3]);
35    }
36
37    char *name;
38    int ref;
39    int *tiles;
40    int ntiles;
41
42    SDL_Surface *img;
43    GLuint texture[1];
44};
45
46/*
47 * Public TileSet class
48 */
49
50TileSet::TileSet(char const *path)
51{
52    data = new TileSetData();
53    data->name = strdup(path);
54    data->ref = 0;
55    data->tiles = NULL;
56    data->ntiles = 0;
57    data->img = NULL;
58
59    for (char const *name = path; *name; name++)
60        if ((data->img = IMG_Load(name)))
61            break;
62
63    if (!data->img)
64    {
65        SDL_Quit();
66        exit(1);
67    }
68
69    glGenTextures(1, data->texture);
70    glBindTexture(GL_TEXTURE_2D, data->texture[0]);
71
72    glTexImage2D(GL_TEXTURE_2D, 0, 4, data->img->w, data->img->h, 0,
73                 GL_RGBA, GL_UNSIGNED_BYTE, data->img->pixels);
74
75    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
76    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
77}
78
79TileSet::~TileSet()
80{
81    glDeleteTextures(1, data->texture);
82
83    free(data->tiles);
84    free(data->name);
85    delete data;
86}
87
88void TileSet::Ref()
89{
90    data->ref++;
91}
92
93int TileSet::Unref()
94{
95    return --data->ref;
96}
97
98char const *TileSet::GetName()
99{
100    return data->name;
101}
102
103void TileSet::BlitTile(uint32_t id, int x, int y)
104{
105    float tx = .0625f * (id & 0xf);
106    float ty = .0625f * ((id >> 4) & 0xf);
107
108    glBindTexture(GL_TEXTURE_2D, data->texture[0]);
109    glBegin(GL_QUADS);
110        glTexCoord2f(tx, ty);
111        glVertex2f(x, y);
112        glTexCoord2f(tx + .0625f, ty);
113        glVertex2f(x + 32, y);
114        glTexCoord2f(tx + .0625f, ty + .0625f);
115        glVertex2f(x + 32, y + 32);
116        glTexCoord2f(tx, ty + .0625f);
117        glVertex2f(x, y + 32);
118    glEnd();
119}
120
Note: See TracBrowser for help on using the repository browser.