这两个设计必须配对,实际上存在一定问题,如果某个函数在中间返回,则可能配不上对,然后造成缓存很快就满了。
这样干脆不free了,到了一定程度自动清理。
代码:
- #define SURFACE_NUM 20
- std::map<int, SDL_Texture*> tmp_Surface;
- int tmp_Surface_count = 0;
- //保存屏幕到临时表面
- int JY_SaveSur(int x, int y, int w, int h)
- {
- int id = tmp_Surface_count;
- int i;
- SDL_Rect r1;
- if (w + x > g_ScreenW) { w = g_ScreenW - x; }
- if (h + y > g_ScreenH) { h = g_ScreenH - h; }
- if (w <= 0 || h <= 0) { return -1; }
- r1.x = x;
- r1.y = y;
- r1.w = w;
- r1.h = h;
- tmp_Surface[id] = SDL_CreateTexture(g_Renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, w, h);
- SDL_SetRenderTarget(g_Renderer, tmp_Surface[id]);
- SDL_RenderCopy(g_Renderer, g_Texture, &r1, NULL);
- tmp_Surface_count++;
- if (tmp_Surface_count % 10 == 0 && tmp_Surface_count > SURFACE_NUM)
- {
- for (auto it = tmp_Surface.begin(); it != tmp_Surface.end();)
- {
- if (it->first < tmp_Surface_count - SURFACE_NUM)
- {
- SDL_DestroyTexture(it->second);
- it = tmp_Surface.erase(it);
- }
- else
- {
- it++;
- }
- }
- }
- JY_Debug("total temp surface: %d, real: %d", tmp_Surface_count, tmp_Surface.size());
- return id;
- }
- int JY_LoadSur(int id, int x, int y)
- {
- if (id < 0 || id >= tmp_Surface_count)
- {
- return 1;
- }
- if (tmp_Surface.count(id) == 0)
- {
- return 1;
- }
- SDL_Rect r1;
- r1.x = (Sint16)x;
- r1.y = (Sint16)y;
- SDL_QueryTexture(tmp_Surface[id], NULL, NULL, &r1.w, &r1.h);
- SDL_SetRenderTarget(g_Renderer, g_Texture);
- SDL_RenderCopy(g_Renderer, tmp_Surface[id], NULL, &r1);
- return 0;
- }
- int JY_FreeSur(int id)
- {
- return 0;
- }
复制代码
|