Blender V5.3
mtl_texture_pool.mm
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2025 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BLI_string.hh"
10
11#include "BKE_global.hh"
12
13#include "mtl_backend.hh"
14#include "mtl_debug.hh"
15#include "mtl_texture_pool.hh"
16
17#include "fmt/format.h"
18
19namespace blender::gpu {
20
21static CLG_LogRef LOG = {"gpu.metal"};
22
23/* Given if the formats can alias. */
25{
26 /* If the format matches we're good. */
27 if (src_format == dst_format) {
28 return true;
29 }
30
31 /* Metal's newTextureViewWithPixelFormat doesn't support aliasing on depth, stencil,
32 * or compressed formats. */
33 GPUTextureFormatFlag src_format_flag = to_format_flag(src_format);
34 if (bool(src_format_flag & (GPU_FORMAT_DEPTH_STENCIL | GPU_FORMAT_COMPRESSED))) {
35 return false;
36 }
37 GPUTextureFormatFlag dst_format_flag = to_format_flag(dst_format);
38 if (bool(dst_format_flag & (GPU_FORMAT_DEPTH_STENCIL | GPU_FORMAT_COMPRESSED))) {
39 return false;
40 }
41
42 /* Metal docs say: All 8-, 16-, 32-, 64-, and 128-bit color formats are compatible
43 * with other formats with the same bit length. */
44 return to_bytesize(src_format) == to_bytesize(dst_format);
45}
46
48{
49 for (const TextureHandle &handle : acquired_) {
50 release_texture(wrap(handle.view));
51 }
52 for (AllocationHandle &handle : pool_) {
53 GPU_texture_free(handle.texture);
54 }
55}
56
58 int mip_len,
59 GPUTextureType type,
60 TextureFormat format,
61 eGPUTextureUsage usage,
62 const char *name)
63{
65
66 /* Search for the first compatible existing texture. */
67 int64_t match_index = -1;
68 bool exact_format_match = false;
69 for (uint64_t i : pool_.index_range()) {
70 const AllocationHandle &handle = pool_[i];
71 /* Do dimensions match? */
72 if (int3(handle.texture->w_, handle.texture->h_, handle.texture->d_) != extent) {
73 /* TODO(not_mark): sub-view on `texture->d_`. */
74 continue;
75 }
76 if (handle.texture->mip_count() != mip_len) {
77 /* TODO(not_mark): sub-view on mip levels. */
78 continue;
79 }
80 /* Are the formats compatible? */
81 if (!check_texture_format_compatability(format, handle.texture->format_get())) {
82 continue;
83 }
84 /* Metal enforces usage flags at texture creation time, so the pooled texture
85 * must have been created with at least all the usage flags the caller needs. */
86 if ((handle.texture->usage_get() & usage_flag) != usage_flag) {
87 continue;
88 }
89 /* Is the format an exact match? */
90 exact_format_match = (format == handle.texture->format_get());
91
92 /* Do we need a writable texture? */
93 bool writable_texture = usage &
95
96 /* Annoyingly Metal's newTextureViewWithPixelFormat strips MTLTextureUsageRenderTarget
97 * and MTLTextureUsageShaderWrite from cross-format views (of course this is not
98 * documented). If the caller needs either of these, only accept an exact format match
99 * as in that case we don't actually create a view. */
100 if (!exact_format_match && writable_texture) {
101 continue;
102 }
103
104 match_index = i;
105 break;
106 }
107
108 /* Return value. */
109 TextureHandle texture_handle;
110
111 /* Acquire the compatible texture, or create a new one as a last resort. */
112 if (match_index != -1) {
113 texture_handle.texture = pool_[match_index].texture;
114 pool_.remove_and_reorder(match_index);
115 }
116 else {
117 /* Debug label attached to allocated texture object. */
118 std::string texture_name_str;
119 if (G.debug & G_DEBUG_GPU) {
120 texture_name_str = fmt::format("TexFromPool_{}", pool_.size());
121 }
122
123 Texture *texture = GPUBackend::get()->texture_alloc(texture_name_str.c_str());
124 texture->usage_set(usage | GPU_TEXTURE_USAGE_FORMAT_VIEW);
125 bool texture_result = false;
126 UNUSED_VARS_NDEBUG(texture_result);
127 switch (type) {
128 case GPU_TEXTURE_1D:
130 texture_result = texture->init_1D(extent.x, extent.y, mip_len, format);
131 break;
132 case GPU_TEXTURE_2D:
134 texture_result = texture->init_2D(extent.x, extent.y, extent.z, mip_len, format);
135 break;
136 case GPU_TEXTURE_3D:
137 texture_result = texture->init_3D(extent.x, extent.y, extent.z, mip_len, format);
138 break;
139 case GPU_TEXTURE_CUBE:
141 texture_result = texture->init_cubemap(extent.x, extent.y, mip_len, format);
142 break;
143 default:
145 break;
146 }
147 BLI_assert(texture_result);
148
149 texture_handle.texture = unwrap(texture);
150 exact_format_match = true;
151 }
152
153 /* On acquire, issue barriers; backing texture or view may still be in flight somewhere. */
154 GPUBarrier barrier = {};
155 if (usage & GPU_TEXTURE_USAGE_SHADER_READ) {
157 }
158 if (usage & GPU_TEXTURE_USAGE_SHADER_WRITE) {
160 }
161 if (usage & GPU_TEXTURE_USAGE_ATTACHMENT) {
163 }
165
166 /* Only create a view if the format actually differs.
167 * This removes the limitation that the view will strip
168 * any render-target or shader-write usage flags. */
169 if (exact_format_match) {
170 /* No view needed; set view to texture so lookups in release_texture work
171 * (the returned pointer is used as the key in the acquired set). */
172 texture_handle.view = texture_handle.texture;
173 }
174 else {
175 /* Debug label attached to view texture object. */
176 std::string view_name_str;
177 if (G.debug & G_DEBUG_GPU) {
178 view_name_str = name ? name : texture_handle.texture->name_;
179 }
180
181 /* Assemble texture view and add to handle. */
182 Texture *view = GPUBackend::get()->texture_alloc(view_name_str.c_str());
183 bool view_result = false;
184 UNUSED_VARS_NDEBUG(view_result);
185 switch (type) {
186 case GPU_TEXTURE_1D:
187 case GPU_TEXTURE_2D:
188 case GPU_TEXTURE_3D:
189 case GPU_TEXTURE_CUBE:
190 view_result = view->init_view(
191 texture_handle.texture, format, type, 0, mip_len, 0, 1, false, false);
192 break;
194 view_result = view->init_view(
195 texture_handle.texture, format, type, 0, mip_len, 0, extent.y, false, false);
196 break;
199 view_result = view->init_view(
200 texture_handle.texture, format, type, 0, mip_len, 0, extent.z, false, false);
201 break;
202 default:
204 break;
205 }
206 BLI_assert(view_result);
207
208 texture_handle.view = unwrap(view);
209 }
210
211 if (G.debug & G_DEBUG_GPU) {
212 current_usage_data_.usage_count++;
213 current_usage_data_.usage_count_max = std::max(current_usage_data_.usage_count,
214 current_usage_data_.usage_count_max);
215 }
216
217 acquired_.add(texture_handle);
218 return wrap(texture_handle.view);
219}
220
222{
223 BLI_assert_msg(acquired_.contains({unwrap(tex)}),
224 "Unacquired texture passed to TexturePool::release_texture()");
225 TextureHandle texture_handle = acquired_.lookup_key({unwrap(tex), {}, 1});
226
227 if (G.debug & G_DEBUG_GPU) {
228 current_usage_data_.usage_count--;
229 }
230
231 /* Move allocation back to `pool_`. */
232 AllocationHandle allocation_handle;
233 allocation_handle.texture = texture_handle.texture;
234 pool_.append(allocation_handle);
235
236 /* Destroy view if one was created (view equals texture when no aliasing was needed). */
237 if (texture_handle.view && texture_handle.view != texture_handle.texture) {
238 GPU_texture_free(texture_handle.view);
239 }
240 acquired_.remove(texture_handle);
241}
242
244{
245 BLI_assert_msg(acquired_.contains({unwrap(tex)}),
246 "Unacquired texture passed to TexturePool::offset_users_count()");
247 TextureHandle texture_handle = acquired_.lookup_key({unwrap(tex), {}, 1});
248 texture_handle.users_count += offset;
249 acquired_.add_overwrite(texture_handle);
250}
251
252void MTLTexturePool::reset(bool force_free)
253{
254#ifndef NDEBUG
255 /* Iterate acquired textures, and ensure the internal counter equals 0; otherwise
256 * this indicates a missing `::retain()` or `::release()`. */
257 for (const TextureHandle &tex : acquired_) {
258 BLI_assert_msg(tex.users_count == 0,
259 "Missing texture release/retain. Likely TextureFromPool::release(), "
260 "TextureFromPool::retain() or TexturePool::release_texture().");
261 }
262#endif
263
264 /* Reverse iterate unused allocations, to make sure we only reorder known good handles. */
265 for (int i = pool_.size() - 1; i >= 0; i--) {
266 AllocationHandle &handle = pool_[i];
267 if (handle.unused_cycles_count >= max_unused_cycles_ || force_free) {
268 GPU_texture_free(handle.texture);
269 pool_.remove_and_reorder(i);
270 }
271 else {
272 handle.unused_cycles_count++;
273 }
274 }
275
276 if (G.debug & G_DEBUG_GPU) {
277 /* Log debug usage if it differs from the last reset. */
278 if (!(previous_usage_data_ == current_usage_data_)) {
279 log_usage_data();
280 }
281
282 /* Reset usage data to track it for the next reset. */
283 previous_usage_data_ = current_usage_data_;
284 current_usage_data_ = {};
285 current_usage_data_.usage_count = acquired_.size();
286 }
287}
288
289void MTLTexturePool::log_usage_data() const
290{
291 int64_t total_texture_count = acquired_.size() + pool_.size();
293 "MTLTexturePool uses %ld textures (%ld consecutively)",
294 static_cast<long>(total_texture_count),
295 static_cast<long>(current_usage_data_.usage_count_max));
296}
297} // namespace blender::gpu
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define BLI_assert_msg(a, msg)
int64_t size() const
Definition BLI_set.hh:606
virtual Texture * texture_alloc(const char *name)=0
static GPUBackend * get()
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 reset(bool force_free=false) override
void release_texture(Texture *tex) override
eGPUTextureUsage usage_get() const
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)
TextureFormat format_get() const
void barrier()
TEX_TEMPLATE DataVec texture(T, FltCoord, float=0.0f) RET
static CLG_LogRef LOG
BLI_INLINE MTLTexture * unwrap(Texture *tex)
int to_bytesize(const DataFormat format)
static bool check_texture_format_compatability(TextureFormat src_format, TextureFormat dst_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
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)
int size() const
Definition vector.hh:130