-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageCache.cpp
More file actions
54 lines (49 loc) · 1.39 KB
/
ImageCache.cpp
File metadata and controls
54 lines (49 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "ImageCache.h"
// Filename is input
SDL_Surface *ImageCache::getSurface(std::string file)
{
auto i = surfaceCache.find(file);
if (i == surfaceCache.end())
{
SDL_Surface *surf;
surf = SDL_LoadBMP(file.c_str());
if (surf == NULL) // If file was not found
{
std::cout << "Failed to load \"" << file << "\", using \"" << notFoundImage << "\" instead." << std::endl;
SDL_FreeSurface(surf);
surf = SDL_LoadBMP(notFoundImage);
}
i = surfaceCache.insert(i, make_pair(file, surf));
SDL_SetColorKey(surf, SDL_TRUE, SDL_MapRGB(surf->format, 2, 2, 2)); // This makes the background transparent
}
return i->second;
}
SDL_Texture *ImageCache::getTexture(std::string file, SDL_Renderer *sdlRenderer)
{
auto i = textureCache.find(file);
if (i == textureCache.end())
{
SDL_Texture *texture = SDL_CreateTextureFromSurface(sdlRenderer, getSurface(file));
i = textureCache.insert(i, make_pair(file, texture));
}
return i->second;
}
void ImageCache::flush()
{
std::map<std::string, SDL_Texture *>::iterator j = textureCache.begin();
for (; j != textureCache.end(); ++j)
{
SDL_DestroyTexture(j->second);
}
textureCache.clear();
std::map<std::string, SDL_Surface *>::iterator i = surfaceCache.begin();
for (; i != surfaceCache.end(); ++i)
{
SDL_FreeSurface(i->second);
}
surfaceCache.clear();
}
ImageCache::~ImageCache()
{
flush();
}