xcal
基于 C++23 的现代图形渲染引擎
载入中...
搜索中...
未找到
resourcedistributor.hpp
浏览该文件的文档.
1#include <memory>
2#include <unordered_map>
3static constexpr size_t CLEAR_THRESHOLD = 100;
4
6template <typename T, typename Catgory = void, size_t Id = 0>
8 static std::shared_ptr<T> allocate();
9};
10template <typename T, typename Catgory, size_t Id>
12 return std::make_shared<T>();
13}
14template <typename T, typename Catgory = void, size_t Id = 0>
16 static std::weak_ptr<T> resource_;
17
18 public:
19 static std::shared_ptr<T> instance() {
20 auto resource = resource_.lock();
21 if (!resource) {
23 resource_ = resource;
24 }
25 return resource;
26 }
27};
28template <typename T, typename Catgory, size_t Id>
29std::weak_ptr<T> StaticResourceDistributor<T, Catgory, Id>::resource_;
30
31template <typename T, typename Catgory = void, size_t Id = 0>
33 static std::unordered_map<size_t, std::weak_ptr<T>> resources_;
34 static size_t last_size_;
35
36 public:
37 static std::shared_ptr<T> instance(size_t id = 0) {
38 auto resource = resources_[id].lock();
39 if (!resource) {
41 resources_[id] = resource;
42 }
43 if (resources_.size() > last_size_ + CLEAR_THRESHOLD) {
44 std::vector<size_t> to_erase;
45 for (auto& pair : resources_) {
46 if (pair.second.expired()) {
47 to_erase.push_back(pair.first);
48 }
49 }
50 for (auto id : to_erase) {
51 resources_.erase(id);
52 }
53
54 last_size_ = resources_.size();
55 }
56 return resource;
57 }
58};
59template <typename T, typename Catgory, size_t Id>
60std::unordered_map<size_t, std::weak_ptr<T>>
61 DynamicResourceDistributor<T, Catgory, Id>::resources_;
62template <typename T, typename Catgory, size_t Id>
63size_t DynamicResourceDistributor<T, Catgory, Id>::last_size_ = 0;
64} // namespace xcal::render::opengl::utils