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