0
0
mirror of https://github.com/Nimac0/SDL_Minigame synced 2026-01-12 13:43:41 +00:00

Implemented texture caching

This commit is contained in:
Benedikt Galbavy 2024-01-11 17:08:35 +01:00
parent a4af49bc7e
commit 98d0350edb
4 changed files with 42 additions and 6 deletions

View File

@ -19,7 +19,7 @@ class SpriteComponent : public Component
void setTexture(const char* path) void setTexture(const char* path)
{ {
this->texture = TextureManager::loadTexture(path); this->texture = TextureManager::get().loadTexture(path);
} }
void init() override void init() override
@ -43,7 +43,7 @@ class SpriteComponent : public Component
void draw() override void draw() override
{ {
TextureManager::draw(this->texture, this->srcRect, this->destRect); TextureManager::get().draw(this->texture, this->srcRect, this->destRect);
} }
private: private:

View File

@ -1,10 +1,39 @@
#pragma once #pragma once
#include "Game.h" #include "Game.h"
#include "SDL_render.h"
#include <map>
struct cmp_str
{
bool operator()(char const *a, char const *b) const {
return strcmp(a, b) < 0;
}
};
class TextureManager class TextureManager
{ {
public: public:
static SDL_Texture* loadTexture(const char* fileName); static TextureManager& get()
{
static TextureManager instance;
return instance;
}
private:
TextureManager() {}
~TextureManager() {
for (auto& it : this->texture_cache) {
SDL_DestroyTexture(it.second);
}
}
public:
TextureManager(TextureManager const&) = delete;
void operator=(TextureManager const&) = delete;
std::map<const char*, SDL_Texture*, cmp_str> texture_cache;
SDL_Texture* loadTexture(const char* fileName);
static void draw(SDL_Texture* texture, SDL_Rect src, SDL_Rect dest); static void draw(SDL_Texture* texture, SDL_Rect src, SDL_Rect dest);
}; };

View File

@ -3,7 +3,7 @@
GameObject::GameObject(const char* texturesheet, int x, int y) GameObject::GameObject(const char* texturesheet, int x, int y)
{ {
this->objTexture = TextureManager::loadTexture(texturesheet); this->objTexture = TextureManager::get().loadTexture(texturesheet);
this->xPos = x; this->xPos = x;
this->yPos = y; this->yPos = y;
} }

View File

@ -1,8 +1,15 @@
#include "TextureManager.h" #include "TextureManager.h"
#include <cstdio>
SDL_Texture* TextureManager::loadTexture(const char* fileName) SDL_Texture* TextureManager::loadTexture(const char* fileName)
{ {
return IMG_LoadTexture(Game::renderer, fileName); auto it = this->texture_cache.find(fileName);
if (it != this->texture_cache.end()) {
return it->second;
}
auto texture = IMG_LoadTexture(Game::renderer, fileName);
this->texture_cache.emplace(fileName, texture);
return texture;
} }
void TextureManager::draw(SDL_Texture* texture, SDL_Rect src, SDL_Rect dest) void TextureManager::draw(SDL_Texture* texture, SDL_Rect src, SDL_Rect dest)