diff options
Diffstat (limited to 'terrain_cache.cpp')
-rw-r--r-- | terrain_cache.cpp | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/terrain_cache.cpp b/terrain_cache.cpp new file mode 100644 index 0000000..c40a1d6 --- /dev/null +++ b/terrain_cache.cpp @@ -0,0 +1,57 @@ +#include "terrain_cache.h" + +/* TerrainCacheObject */ + +TerrainCacheObject::TerrainCacheObject(TerrainCache *cache, int x, int y, int width, int height) { + this->cache = cache; + this->x = x; + this->y = y; + this->width = width; + this->height = height; + this->heights = cache->tl->get_chunk(x, y, width, height); +} + +TerrainCacheObject::~TerrainCacheObject() { + cache->tl->save_chunk(heights, x, y, width, height); + delete[] heights; +} + +/* TerrainCache */ + +TerrainCache::TerrainCache(int seed, fs::path root, size_t max_size) { + this->max_size = max_size; + tl = new TerrainLoader(seed, root); +} + +TerrainCache::~TerrainCache() { + caches.clear(); + delete tl; +} + +TerrainCacheObject::p TerrainCache::make_object(int x, int y, int width, int height) { + TerrainCacheObject::p ob(new TerrainCacheObject(this, x, y, width, height)); + + if(caches.size() >= max_size) { + for(cache_map::iterator it = caches.begin(); it != caches.end(); it++) { + if(it->second.use_count() == 1) { + caches.erase(it); + break; + } + } + } + + caches.insert(std::pair<intpair, TerrainCacheObject::p>(intpair(x, y), ob)); + return ob; +} + +TerrainCacheObject::p TerrainCache::get_chunk(int x, int y, int width, int height) { + cache_map::iterator it = caches.find(intpair(x, y)); + if(it != caches.end()) + return it->second; + + return make_object(x, y, width, height); +} + +size_t TerrainCache::get_size() { + return caches.size(); +} |