Blender V5.3
gl_texture_pool.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BLI_string.hh"
10
11#include "gl_backend.hh"
12#include "gl_texture_pool.hh"
13
14#include "CLG_log.h"
15
16#include "fmt/format.h"
17
18namespace blender::gpu {
19
20static CLG_LogRef LOG = {"gpu.opengl"};
21
22/* Given a TextureFormat, return an underlying format on which to alias. If the
23 * format does not support aliasing to another format, simply return the input. */
25{
26 /* glTextureView doesn't support aliasing on depth, stencil, or most compressed formats. */
27 GPUTextureFormatFlag format_flag = to_format_flag(format);
28 if (bool(format_flag & GPU_FORMAT_DEPTH_STENCIL)) {
29 return format;
30 }
31 if (bool(format_flag & GPU_FORMAT_COMPRESSED)) {
32 return format;
33 }
34
35 /* Given expected byte size, we use a default format available as write/target format. */
36 switch (to_bytesize(format)) {
37 case 16:
38 return TextureFormat::SFLOAT_32_32_32_32;
39 case 8:
40 return TextureFormat::SFLOAT_32_32;
41 case 4:
42 return TextureFormat::SFLOAT_32;
43 case 2:
44 return TextureFormat::SFLOAT_16;
45 case 1:
46 return TextureFormat::UINT_8;
47 default:
49 }
50}
51
53{
54 for (const TextureHandle &handle : acquired_) {
55 release_texture(wrap(handle.view));
56 }
57 for (AllocationHandle &handle : pool_) {
58 GPU_texture_free(handle.texture);
59 }
60}
61
63 int mip_len,
64 GPUTextureType type,
65 TextureFormat format,
66 eGPUTextureUsage usage,
67 const char *name)
68{
69 /* Determine format of compatible underlying texture. If there is no
70 * compatible format to alias upon, we simply require an exact match
71 * for the underlying texture. */
72 TextureFormat compatible_format = get_compatible_texture_format(format);
73 BLI_assert(compatible_format != TextureFormat::Invalid);
74
75 /* Determine actual mipmap depth. */
76 int mip_len_max = 1 + floorf(log2f(std::max({extent.x, extent.y, extent.z})));
77 mip_len = min_ii(mip_len, mip_len_max);
78
79 /* Search for the first compatible existing texture. */
80 int64_t match_index = -1;
81 for (uint64_t i : pool_.index_range()) {
82 const AllocationHandle &handle = pool_[i];
83 if (handle.texture->format_ != compatible_format) {
84 continue;
85 }
86 if (int3(handle.texture->w_, handle.texture->h_, handle.texture->d_) != extent) {
87 /* TODO(not_mark): sub-view on `texture->d_`. */
88 continue;
89 }
90 if (handle.texture->mip_count() != mip_len) {
91 /* TODO(not_mark): sub-view on mip levels. */
92 continue;
93 }
94 match_index = i;
95 break;
96 }
97
98 /* Return value. */
99 TextureHandle texture_handle;
100
101 /* Acquire the compatible texture, or create a new one as a last resort. */
102 if (match_index != -1) {
103 texture_handle.texture = pool_[match_index].texture;
104 pool_.remove_and_reorder(match_index);
105 /* Override the usage. It doesn't really apply to OpenGL in practice, but `GPU_texture_usage`
106 * callers may still rely on it. */
107 texture_handle.texture->usage_set(usage | GPU_TEXTURE_USAGE_FORMAT_VIEW);
108 }
109 else {
110 /* Debug label attached to allocated texture object. */
111 std::string texture_name_str;
112 if (G.debug & G_DEBUG_GPU) {
113 texture_name_str = fmt::format("TexFromPool_{}", pool_.size());
114 }
115
116 Texture *texture = GPUBackend::get()->texture_alloc(texture_name_str.c_str());
117 texture->usage_set(usage | GPU_TEXTURE_USAGE_FORMAT_VIEW);
118 bool texture_result = false;
119 UNUSED_VARS_NDEBUG(texture_result);
120 switch (type) {
121 case GPU_TEXTURE_1D:
123 texture_result = texture->init_1D(extent.x, extent.y, mip_len, compatible_format);
124 break;
125 case GPU_TEXTURE_2D:
127 texture_result = texture->init_2D(
128 extent.x, extent.y, extent.z, mip_len, compatible_format);
129 break;
130 case GPU_TEXTURE_3D:
131 texture_result = texture->init_3D(
132 extent.x, extent.y, extent.z, mip_len, compatible_format);
133 break;
134 case GPU_TEXTURE_CUBE:
136 texture_result = texture->init_cubemap(extent.x, extent.y, mip_len, compatible_format);
137 break;
138 default:
140 break;
141 }
142 BLI_assert(texture_result);
143
144 texture_handle.texture = unwrap(texture);
145 }
146
147 /* On acquire, issue barriers; backing texture or view may still be in flight somewhere. */
148 GPUBarrier barrier = {};
149 if (usage & GPU_TEXTURE_USAGE_SHADER_READ) {
151 }
152 if (usage & GPU_TEXTURE_USAGE_SHADER_WRITE) {
154 }
155 if (usage & GPU_TEXTURE_USAGE_ATTACHMENT) {
157 }
159
160 /* Debug label attached to view texture object. */
161 std::string view_name_str;
162 if (G.debug & G_DEBUG_GPU) {
163 view_name_str = name ? name : texture_handle.texture->name_;
164 }
165
166 /* Assemble texture view and add to handle. Note, glTextureView with identical formats is
167 * allowed, even if the formats are not listed for aliasing in the Internal Formats table. */
168 Texture *view = GPUBackend::get()->texture_alloc(view_name_str.c_str());
169 bool view_result = false;
170 UNUSED_VARS_NDEBUG(view_result);
171 switch (type) {
172 case GPU_TEXTURE_1D:
173 case GPU_TEXTURE_2D:
174 case GPU_TEXTURE_3D:
175 case GPU_TEXTURE_CUBE:
176 view_result = view->init_view(
177 texture_handle.texture, format, type, 0, mip_len, 0, 1, false, false);
178 break;
180 view_result = view->init_view(
181 texture_handle.texture, format, type, 0, mip_len, 0, extent.y, false, false);
182 break;
185 view_result = view->init_view(
186 texture_handle.texture, format, type, 0, mip_len, 0, extent.z, false, false);
187 break;
188 default:
190 break;
191 }
192 BLI_assert(view_result);
193
194 /* On integer textures, disable filtering by default, as this is not guaranteed to be
195 * consistently supported across backends. */
199 view->sampler_state.set_filtering_flag_from_test(GPU_SAMPLER_FILTERING_ANISOTROPIC_MASK,
200 false);
201 }
202
203 texture_handle.view = unwrap(view);
204
205 if (G.debug & G_DEBUG_GPU) {
206 current_usage_data_.usage_count++;
207 current_usage_data_.usage_count_max = std::max(current_usage_data_.usage_count,
208 current_usage_data_.usage_count_max);
209 }
210
211 acquired_.add(texture_handle);
212 return wrap(texture_handle.view);
213}
214
216{
217 BLI_assert_msg(acquired_.contains({unwrap(tex)}),
218 "Unacquired texture passed to TexturePool::release_texture()");
219 TextureHandle texture_handle = acquired_.lookup_key({unwrap(tex), {}, 1});
220
221 if (G.debug & G_DEBUG_GPU) {
222 current_usage_data_.usage_count--;
223 }
224
225 /* Move allocation back to `pool_`. */
226 AllocationHandle allocation_handle;
227 allocation_handle.texture = texture_handle.texture;
228 pool_.append(allocation_handle);
229
230 /* Destroy view and handle, if a view was created. */
231 GPU_texture_free(texture_handle.view);
232 acquired_.remove(texture_handle);
233}
234
236{
237 BLI_assert_msg(acquired_.contains({unwrap(tex)}),
238 "Unacquired texture passed to TexturePool::offset_users_count()");
239 TextureHandle texture_handle = acquired_.lookup_key({unwrap(tex), {}, 1});
240 texture_handle.users_count += offset;
241 acquired_.add_overwrite(texture_handle);
242}
243
244void GLTexturePool::reset(bool force_free)
245{
246#ifndef NDEBUG
247 /* Iterate acquired textures, and ensure the internal counter equals 0; otherwise
248 * this indicates a missing `::retain()` or `::release()`. */
249 for (const TextureHandle &tex : acquired_) {
250 BLI_assert_msg(tex.users_count == 0,
251 "Missing texture release/retain. Likely TextureFromPool::release(), "
252 "TextureFromPool::retain() or TexturePool::release_texture().");
253 }
254#endif
255
256 /* Reverse iterate unused allocations, to make sure we only reorder known good handles. */
257 for (int i = pool_.size() - 1; i >= 0; i--) {
258 AllocationHandle &handle = pool_[i];
259 if (handle.unused_cycles_count >= max_unused_cycles_ || force_free) {
260 GPU_texture_free(handle.texture);
261 pool_.remove_and_reorder(i);
262 }
263 else {
264 handle.unused_cycles_count++;
265 }
266 }
267
268 if (G.debug & G_DEBUG_GPU) {
269 /* Log debug usage if it differs from the last reset. */
270 if (!(previous_usage_data_ == current_usage_data_)) {
271 log_usage_data();
272 }
273
274 /* Reset usage data to track it for the next reset. */
275 previous_usage_data_ = current_usage_data_;
276 current_usage_data_ = {};
277 current_usage_data_.usage_count = acquired_.size();
278 }
279}
280
281void GLTexturePool::log_usage_data() const
282{
283 int64_t total_texture_count = acquired_.size() + pool_.size();
285 "GLTexturePool uses %ld textures (%ld consecutively)",
286 long(total_texture_count),
287 long(current_usage_data_.usage_count_max));
288}
289} // namespace blender::gpu
#define CLOG_TRACE(clg_ref,...)
Definition CLG_log.h:192
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define BLI_assert_msg(a, msg)
int64_t size() const
Definition BLI_set.hh:606
Texture * acquire_texture_impl(int3 extent, int mip_len, GPUTextureType type, TextureFormat format, eGPUTextureUsage usage=GPU_TEXTURE_USAGE_GENERAL, const char *name=nullptr) override
void offset_users_count(Texture *tex, int offset) override
void release_texture(Texture *tex) override
void reset(bool force_free=false) override
virtual Texture * texture_alloc(const char *name)=0
static GPUBackend * get()
bool init_view(Texture *src, TextureFormat format, GPUTextureType type, int mip_start, int mip_len, int layer_start, int layer_len, bool cube_as_array, bool use_stencil)
void usage_set(eGPUTextureUsage usage_flags)
void barrier()
TEX_TEMPLATE DataVec texture(T, FltCoord, float=0.0f) RET
static TextureFormat get_compatible_texture_format(TextureFormat format)
static CLG_LogRef LOG
BLI_INLINE MTLTexture * unwrap(Texture *tex)
int to_bytesize(const DataFormat format)
BLI_INLINE Texture * wrap(MTLTexture *texture)
GPUTextureFormatFlag to_format_flag(TextureFormat format)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
unsigned __int64 uint64_t
Definition BKE_text.h:91
__int64 int64_t
Definition BKE_text.h:90
bool GPU_texture_has_integer_format(const gpu::Texture *texture)
@ GPU_SAMPLER_FILTERING_LINEAR
@ GPU_SAMPLER_FILTERING_MIPMAP
Global G
Definition blender.cc:57
VecBase< int32_t, 3 > int3
@ GPU_TEXTURE_USAGE_FORMAT_VIEW
@ GPU_TEXTURE_USAGE_SHADER_READ
@ GPU_TEXTURE_USAGE_SHADER_WRITE
@ GPU_TEXTURE_USAGE_ATTACHMENT
void GPU_memory_barrier(GPUBarrier barrier)
Definition gpu_state.cc:305
@ GPU_BARRIER_FRAMEBUFFER
Definition GPU_state.hh:36
@ GPU_BARRIER_TEXTURE_FETCH
Definition GPU_state.hh:40
@ GPU_BARRIER_SHADER_IMAGE_ACCESS
Definition GPU_state.hh:38
void GPU_texture_free(gpu::Texture *texture)
MINLINE int min_ii(int a, int b)
#define floorf
void set_filtering_flag_from_test(GPUSamplerFiltering filtering_flags, bool test)
int size() const
Definition vector.hh:130