source: trunk/src/tileset.cpp @ 96

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

Implement lazy initialisation of TileSet objects.

  • 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    char *name;
30    int *tiles;
31    int ntiles;
32
33    SDL_Surface *img;
34    GLuint texture;
35};
36
37/*
38 * Public TileSet class
39 */
40
41TileSet::TileSet(char const *path)
42{
43    data = new TileSetData();
44    data->name = strdup(path);
45    data->tiles = NULL;
46    data->ntiles = 0;
47    data->img = NULL;
48    data->texture = 0;
49
50    for (char const *name = path; *name; name++)
51        if ((data->img = IMG_Load(name)))
52            break;
53
54    if (!data->img)
55    {
56        SDL_Quit();
57        exit(1);
58    }
59}
60
61TileSet::~TileSet()
62{
63    free(data->tiles);
64    free(data->name);
65    delete data;
66}
67
68void TileSet::TickRender(float delta_time)
69{
70    Asset::TickRender(delta_time);
71
72    if (data->img)
73    {
74        glGenTextures(1, &data->texture);
75        glBindTexture(GL_TEXTURE_2D, data->texture);
76
77        glTexImage2D(GL_TEXTURE_2D, 0, 4, data->img->w, data->img->h, 0,
78                     GL_RGBA, GL_UNSIGNED_BYTE, data->img->pixels);
79
80        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
81        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
82
83        SDL_FreeSurface(data->img);
84        data->img = NULL;
85    }
86    else if (ref == 0)
87    {
88        glDeleteTextures(1, &data->texture);
89        destroy = 1;
90    }
91}
92
93char const *TileSet::GetName()
94{
95    return data->name;
96}
97
98void TileSet::BlitTile(uint32_t id, int x, int y)
99{
100    float tx = .0625f * (id & 0xf);
101    float ty = .0625f * ((id >> 4) & 0xf);
102
103    if (!data->img)
104    {
105        glBindTexture(GL_TEXTURE_2D, data->texture);
106        glBegin(GL_QUADS);
107            glTexCoord2f(tx, ty);
108            glVertex2f(x, y);
109            glTexCoord2f(tx + .0625f, ty);
110            glVertex2f(x + 32, y);
111            glTexCoord2f(tx + .0625f, ty + .0625f);
112            glVertex2f(x + 32, y + 32);
113            glTexCoord2f(tx, ty + .0625f);
114            glVertex2f(x, y + 32);
115        glEnd();
116    }
117}
118
Note: See TracBrowser for help on using the repository browser.