Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/servers/rendering/multi_uma_buffer.h
12197 views
1
/**************************************************************************/
2
/* multi_uma_buffer.h */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#pragma once
32
33
#include "servers/rendering/rendering_server.h"
34
35
class MultiUmaBufferBase {
36
protected:
37
LocalVector<RID> buffers;
38
uint32_t curr_idx = UINT32_MAX;
39
uint64_t last_frame_mapped = UINT64_MAX;
40
const uint32_t max_extra_buffers;
41
#ifdef DEBUG_ENABLED
42
const char *debug_name;
43
#endif
44
45
MultiUmaBufferBase(uint32_t p_max_extra_buffers, const char *p_debug_name) :
46
max_extra_buffers(p_max_extra_buffers)
47
#ifdef DEBUG_ENABLED
48
,
49
debug_name(p_debug_name)
50
#endif
51
{
52
}
53
54
#ifdef DEV_ENABLED
55
~MultiUmaBufferBase() {
56
DEV_ASSERT(buffers.is_empty() && "Forgot to call uninit()!");
57
}
58
#endif
59
60
public:
61
void uninit() {
62
if (is_print_verbose_enabled()) {
63
print_line("MultiUmaBuffer '"
64
#ifdef DEBUG_ENABLED
65
+ String(debug_name) +
66
#else
67
"{DEBUG_ENABLED unavailable}"
68
#endif
69
"' used a total of " + itos(buffers.size()) +
70
" buffers. A large number may indicate a waste of VRAM and can be brought down by tweaking MAX_EXTRA_BUFFERS for this buffer.");
71
}
72
73
RenderingDevice *rd = RD::RenderingDevice::get_singleton();
74
75
for (RID buffer : buffers) {
76
if (buffer.is_valid()) {
77
rd->free_rid(buffer);
78
}
79
}
80
81
buffers.clear();
82
}
83
84
void shrink_to_max_extra_buffers() {
85
DEV_ASSERT(curr_idx == 0u && "This function can only be called after reset and before being upload_and_advance again!");
86
87
RenderingDevice *rd = RD::RenderingDevice::get_singleton();
88
89
uint32_t elem_count = buffers.size();
90
91
if (elem_count > max_extra_buffers) {
92
if (is_print_verbose_enabled()) {
93
print_line("MultiUmaBuffer '"
94
#ifdef DEBUG_ENABLED
95
+ String(debug_name) +
96
#else
97
"{DEBUG_ENABLED unavailable}"
98
#endif
99
"' peaked to " + itos(elem_count) + " elements and shrinking it to " + itos(max_extra_buffers) +
100
". If you see this message often, then something is wrong with rendering or MAX_EXTRA_BUFFERS needs to be increased.");
101
}
102
}
103
104
while (elem_count > max_extra_buffers) {
105
--elem_count;
106
if (buffers[elem_count].is_valid()) {
107
rd->free_rid(buffers[elem_count]);
108
}
109
buffers.remove_at(elem_count);
110
}
111
}
112
};
113
114
/// Interface for making it easier to work with UMA.
115
///
116
/// # What is UMA?
117
///
118
/// It stands for Unified Memory Architecture. There are two kinds of UMA:
119
/// 1. HW UMA. This is the case of iGPUs (specially Android, iOS, Apple ARM-based macOS, PS4 & PS5)
120
/// The CPU and GPU share the same die and same memory. So regular RAM and VRAM are internally the
121
/// same thing. There may be some differences between them in practice due to cache synchronization
122
/// behaviors or the regular BW RAM may be purposely throttled (as is the case of PS4 & PS5).
123
/// 2. "Pretended UMA". On PC Desktop GPUs with ReBAR enabled can pretend VRAM behaves like normal
124
/// RAM, while internally the data is moved across the PCIe Bus. This can cause differences
125
/// in execution time of the routines that write to GPU buffers as the region is often uncached
126
/// (i.e. write-combined) and PCIe latency and BW is vastly different from regular RAM.
127
/// Without ReBAR, the amount of UMA memory is limited to 256MB (shared by the entire system).
128
///
129
/// Since often this type of memory is uncached, it is not well-suited for downloading GPU -> CPU,
130
/// but rather for uploading CPU -> GPU.
131
///
132
/// # When to use UMA buffers?
133
///
134
/// UMA buffers have various caveats and improper usage might lead to visual glitches. Therefore they
135
/// should be used sparingly, where it makes a difference. Does all of the following check?:
136
/// 1. Data is uploaded from CPU to GPU every (or almost every) frame.
137
/// 2. Data is always uploaded from scratch. Partial uploads are unsupported.
138
/// 3. If uploading multiple times per frame (e.g. for multiple passes). The amount of times
139
/// per frame is relatively stable (occasional spikes are fine if using MAX_EXTRA_BUFFERS).
140
///
141
/// # Why the caveats?
142
///
143
/// This is due to our inability to detect race conditions. If you write to an UMA buffer, submit
144
/// GPU commands and then write more data to it, we can't guarantee that you won't be writing to a
145
/// region the GPU is currently reading from. Tools like the validation layers cannot detect this
146
/// race condition at all, making it very hard to troubleshoot.
147
///
148
/// Therefore the safest approach is to use an interface that forces users to upload everything at once.
149
/// There is one exception for performance: map_raw_for_upload() will return a pointer, and it is your
150
/// responsibility to make sure you don't use that pointer again after submitting.
151
/// USE THIS API CALL SPARINGLY AND WITH CARE.
152
///
153
/// Since we forbid uploading more data after we've uploaded to it, this Interface will create
154
/// more buffers. This means users will need more UniformSets (i.e. uniform_set_create).
155
///
156
/// # How to use
157
///
158
/// Example code 01:
159
/// MultiUmaBuffer<1> uma_buffer = MultiUmaBuffer<1>("Debug name displayed if run with --verbose");
160
/// uma_buffer.set_size(0, max_size_bytes, false);
161
///
162
/// for(uint32_t i = 0u; i < num_passes; ++i) {
163
/// uma_buffer.prepare_for_upload(); // Creates a new buffer (if none exists already)
164
/// // of max_size_bytes. Must be called.
165
/// uma_buffer.upload(0, src_data, size_bytes);
166
///
167
/// if(!uniform_set[i]) {
168
/// RD::Uniform u;
169
/// u.binding = 1;
170
/// u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC;
171
/// u.append_id(uma_buffer._get(0u));
172
/// uniform_set[i] = rd->uniform_set_create( ... );
173
/// }
174
/// }
175
///
176
/// // On shutdown (or if you need to call set_size again).
177
/// uma_buffer.uninit();
178
///
179
/// Example code 02:
180
///
181
/// uma_buffer.prepare_for_upload();
182
/// RID rid = uma_buffer.get_for_upload(0u);
183
/// rd->buffer_update(rid, 0, sizeof(BakeParameters), &bake_parameters);
184
/// RD::Uniform u; // Skipping full initialization of u. See Example 01.
185
/// u.append_id(rid);
186
///
187
/// Example code 03:
188
///
189
/// void *dst_data = uma_buffer.map_raw_for_upload(0u);
190
/// memcpy(dst_data, src_data, size_bytes);
191
/// rd->buffer_flush(uma_buffer._get(0u));
192
/// RD::Uniform u; // Skipping full initialization of u. See Example 01.
193
/// u.append_id(rid);
194
///
195
/// # Tricks
196
///
197
/// Godot's shadow mapping code calls uma_buffer.uniform_buffers._get(-p_pass_offset) (i.e. a negative value)
198
/// because for various reasons its shadow mapping code was written like this:
199
///
200
/// for( uint32_t i = 0u; i < num_passes; ++i ) {
201
/// uma_buffer.prepare_for_upload();
202
/// uma_buffer.upload(0, src_data, size_bytes);
203
/// }
204
/// for( uint32_t i = 0u; i < num_passes; ++i ) {
205
/// RD::Uniform u;
206
/// u.binding = 1;
207
/// u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER_DYNAMIC;
208
/// u.append_id(uma_buffer._get(-(num_passes - 1u - i)));
209
/// uniform_set[i] = rd->uniform_set_create( ... );
210
/// }
211
///
212
/// Every time prepare_for_upload() is called, uma_buffer._get(-idx) will return a different RID(*).
213
/// Thus with a negative value we can address previous ones. This is fine as long as the value idx
214
/// doesn't exceed the number of times the user called prepare_for_upload() for this frame.
215
///
216
/// (*)This RID will be returned again on the next frame after the same amount of prepare_for_upload()
217
/// calls; unless the number of times it was called exceeded MAX_EXTRA_BUFFERS.
218
///
219
/// # Template parameters
220
///
221
/// ## NUM_BUFFERS
222
///
223
/// How many buffers we should track. e.g. instead of doing this:
224
/// MultiUmaBuffer<1> omni_lights = /*...*/;
225
/// MultiUmaBuffer<1> spot_lights = /*...*/;
226
/// MultiUmaBuffer<1> directional_lights = /*...*/;
227
///
228
/// omni_lights.set_size(0u, omni_size);
229
/// spot_lights.set_size(0u, spot_size);
230
/// directional_lights.set_size(0u, dir_size);
231
///
232
/// omni_lights.prepare_for_upload();
233
/// spot_lights.prepare_for_upload();
234
/// directional_lights.prepare_for_upload();
235
///
236
/// You can do this:
237
///
238
/// MultiUmaBuffer<3> lights = /*...*/;
239
///
240
/// lights.set_size(0u, omni_size);
241
/// lights.set_size(1u, spot_size);
242
/// lights.set_size(2u, dir_size);
243
///
244
/// lights.prepare_for_upload();
245
///
246
/// This approach works as long as all buffers would call prepare_for_upload() at the same time.
247
/// It saves some overhead.
248
///
249
/// ## MAX_EXTRA_BUFFERS
250
///
251
/// Upper limit on the number of buffers per frame.
252
///
253
/// There are times where rendering might spike for exceptional reasons, calling prepare_for_upload()
254
/// too many times, never to do that again. This will cause an increase in memory usage that will
255
/// never be reclaimed until shutdown.
256
///
257
/// MAX_EXTRA_BUFFERS can be used to handle such spikes, by deallocating the extra buffers.
258
/// Example:
259
/// MultiUmaBuffer<1, 6> buffer;
260
///
261
/// // Normal frame (assuming up to 6 passes is considered normal):
262
/// for(uint32_t i = 0u; i < 6u; ++i) {
263
/// buffer.prepare_for_upload();
264
/// ...
265
/// buffer.upload(...);
266
/// }
267
///
268
/// // Exceptional frame:
269
/// for(uint32_t i = 0u; i < 24u; ++i) {
270
/// buffer.prepare_for_upload();
271
/// ...
272
/// buffer.upload(...);
273
/// }
274
///
275
/// After the frame is done, those extra 18 buffers will be deleted.
276
/// Launching godot with --verbose will print diagnostic information.
277
template <uint32_t NUM_BUFFERS, uint32_t MAX_EXTRA_BUFFERS = UINT32_MAX>
278
class MultiUmaBuffer : public MultiUmaBufferBase {
279
uint32_t buffer_sizes[NUM_BUFFERS] = {};
280
#ifdef DEV_ENABLED
281
bool can_upload[NUM_BUFFERS] = {};
282
#endif
283
284
void push() {
285
RenderingDevice *rd = RD::RenderingDevice::get_singleton();
286
for (uint32_t i = 0u; i < NUM_BUFFERS; ++i) {
287
const bool is_storage = buffer_sizes[i] & 0x80000000u;
288
const uint32_t size_bytes = buffer_sizes[i] & ~0x80000000u;
289
RID buffer;
290
if (is_storage) {
291
buffer = rd->storage_buffer_create(size_bytes, Vector<uint8_t>(), 0, RD::BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT);
292
} else {
293
buffer = rd->uniform_buffer_create(size_bytes, Vector<uint8_t>(), RD::BUFFER_CREATION_DYNAMIC_PERSISTENT_BIT);
294
}
295
buffers.push_back(buffer);
296
}
297
}
298
299
public:
300
MultiUmaBuffer(const char *p_debug_name) :
301
MultiUmaBufferBase(MAX_EXTRA_BUFFERS, p_debug_name) {}
302
303
uint32_t get_curr_idx() const { return curr_idx; }
304
305
void set_size(uint32_t p_idx, uint32_t p_size_bytes, bool p_is_storage) {
306
DEV_ASSERT(buffers.is_empty());
307
buffer_sizes[p_idx] = p_size_bytes | (p_is_storage ? 0x80000000u : 0u);
308
curr_idx = UINT32_MAX;
309
last_frame_mapped = UINT64_MAX;
310
}
311
312
uint32_t get_size(uint32_t p_idx) const { return buffer_sizes[p_idx] & ~0x80000000u; }
313
314
// Gets the raw buffer. Use with care.
315
// If you call this function, make sure to have called prepare_for_upload() first.
316
// Do not call _get() then prepare_for_upload().
317
RID _get(uint32_t p_idx) {
318
return buffers[curr_idx * NUM_BUFFERS + p_idx];
319
}
320
321
/**
322
* @param p_append True if you wish to append more data to existing buffer.
323
* @return True if it's possible to append. False if the internal buffer changed.
324
*/
325
bool prepare_for_map(bool p_append) {
326
RenderingDevice *rd = RD::RenderingDevice::get_singleton();
327
const uint64_t frames_drawn = rd->get_frames_drawn();
328
329
if (last_frame_mapped == frames_drawn) {
330
if (!p_append) {
331
++curr_idx;
332
}
333
} else {
334
p_append = false;
335
curr_idx = 0u;
336
if (max_extra_buffers != UINT32_MAX) {
337
shrink_to_max_extra_buffers();
338
}
339
}
340
last_frame_mapped = frames_drawn;
341
if (curr_idx * NUM_BUFFERS >= buffers.size()) {
342
push();
343
}
344
345
#ifdef DEV_ENABLED
346
if (!p_append) {
347
for (size_t i = 0u; i < NUM_BUFFERS; ++i) {
348
can_upload[i] = true;
349
}
350
}
351
#endif
352
return !p_append;
353
}
354
355
void prepare_for_upload() {
356
prepare_for_map(false);
357
}
358
359
void *map_raw_for_upload(uint32_t p_idx) {
360
#ifdef DEV_ENABLED
361
DEV_ASSERT(can_upload[p_idx] && "Forgot to prepare_for_upload first! Or called get_for_upload/upload() twice.");
362
can_upload[p_idx] = false;
363
#endif
364
RenderingDevice *rd = RD::RenderingDevice::get_singleton();
365
return rd->buffer_persistent_map_advance(buffers[curr_idx * NUM_BUFFERS + p_idx]);
366
}
367
368
RID get_for_upload(uint32_t p_idx) {
369
#ifdef DEV_ENABLED
370
DEV_ASSERT(can_upload[p_idx] && "Forgot to prepare_for_upload first! Or called get_for_upload/upload() twice.");
371
can_upload[p_idx] = false;
372
#endif
373
return buffers[curr_idx * NUM_BUFFERS + p_idx];
374
}
375
376
void upload(uint32_t p_idx, const void *p_src_data, uint32_t p_size_bytes) {
377
#ifdef DEV_ENABLED
378
DEV_ASSERT(can_upload[p_idx] && "Forgot to prepare_for_upload first! Or called get_for_upload/upload() twice.");
379
can_upload[p_idx] = false;
380
#endif
381
RenderingDevice *rd = RD::RenderingDevice::get_singleton();
382
rd->buffer_update(buffers[curr_idx * NUM_BUFFERS + p_idx], 0, p_size_bytes, p_src_data, true);
383
}
384
};
385
386