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:
parent
a4af49bc7e
commit
98d0350edb
@ -19,7 +19,7 @@ class SpriteComponent : public Component
|
||||
|
||||
void setTexture(const char* path)
|
||||
{
|
||||
this->texture = TextureManager::loadTexture(path);
|
||||
this->texture = TextureManager::get().loadTexture(path);
|
||||
}
|
||||
|
||||
void init() override
|
||||
@ -43,7 +43,7 @@ class SpriteComponent : public Component
|
||||
|
||||
void draw() override
|
||||
{
|
||||
TextureManager::draw(this->texture, this->srcRect, this->destRect);
|
||||
TextureManager::get().draw(this->texture, this->srcRect, this->destRect);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@ -1,10 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#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
|
||||
{
|
||||
public:
|
||||
static SDL_Texture* loadTexture(const char* fileName);
|
||||
public:
|
||||
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);
|
||||
};
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
GameObject::GameObject(const char* texturesheet, int x, int y)
|
||||
{
|
||||
this->objTexture = TextureManager::loadTexture(texturesheet);
|
||||
this->objTexture = TextureManager::get().loadTexture(texturesheet);
|
||||
this->xPos = x;
|
||||
this->yPos = y;
|
||||
}
|
||||
|
||||
@ -1,8 +1,15 @@
|
||||
#include "TextureManager.h"
|
||||
#include <cstdio>
|
||||
|
||||
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)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user