refactor(SpriteFrameCache): 使用 ResourceManager 的 LRU 缓存机制

This commit is contained in:
ChestnutYueyue 2026-02-12 12:26:54 +08:00
parent 85420634aa
commit 1c1f071307
1 changed files with 20 additions and 20 deletions

View File

@ -1,9 +1,9 @@
#pragma once #pragma once
#include <extra2d/animation/sprite_frame.h> #include <extra2d/animation/sprite_frame.h>
#include <extra2d/graphics/opengl/gl_texture.h> #include <extra2d/graphics/texture.h>
#include <extra2d/resource/resource_manager.h>
#include <extra2d/utils/logger.h> #include <extra2d/utils/logger.h>
#include <stb/stb_image.h>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
@ -164,30 +164,30 @@ private:
SpriteFrameCache &operator=(const SpriteFrameCache &) = delete; SpriteFrameCache &operator=(const SpriteFrameCache &) = delete;
/** /**
* @brief * @brief 使 ResourceManager LRU
* @param filepath * @param filepath
* @return nullptr * @return nullptr
*/ */
Ptr<Texture> loadTextureFromFile(const std::string &filepath) { Ptr<Texture> loadTextureFromFile(const std::string &filepath) {
// 使用stb_image加载图像 // 使用 ResourceManager 的纹理缓存机制
stbi_set_flip_vertically_on_load(false); // 这样可以享受 LRU 缓存、自动清理和缓存统计等功能
int width, height, channels; auto &resources = ResourceManager::getInstance();
unsigned char *pixels =
stbi_load(filepath.c_str(), &width, &height, &channels, 4); // 先检查缓存中是否已有该纹理
if (!pixels) { auto texture = resources.getTexture(filepath);
E2D_ERROR("加载纹理失败: {} - {}", filepath, stbi_failure_reason()); if (texture) {
return nullptr; E2D_TRACE("SpriteFrameCache: 使用缓存纹理: {}", filepath);
} return texture;
}
// 创建GLTexture
auto texture = makePtr<GLTexture>(width, height, pixels, 4); // 缓存未命中,通过 ResourceManager 加载
stbi_image_free(pixels); texture = resources.loadTexture(filepath);
if (!texture) {
if (!texture || !texture->isValid()) { E2D_ERROR("SpriteFrameCache: 加载纹理失败: {}", filepath);
E2D_ERROR("创建纹理失败: {}", filepath);
return nullptr; return nullptr;
} }
E2D_TRACE("SpriteFrameCache: 加载新纹理: {}", filepath);
return texture; return texture;
} }