//1// Copyright (c) 2019-2022 Advanced Micro Devices, Inc. All rights reserved.2//3// Permission is hereby granted, free of charge, to any person obtaining a copy4// of this software and associated documentation files (the "Software"), to deal5// in the Software without restriction, including without limitation the rights6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7// copies of the Software, and to permit persons to whom the Software is8// furnished to do so, subject to the following conditions:9//10// The above copyright notice and this permission notice shall be included in11// all copies or substantial portions of the Software.12//13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19// THE SOFTWARE.20//2122#pragma once2324/** \mainpage D3D12 Memory Allocator2526<b>Version 2.1.0-development</b> (2022-12-15)2728Copyright (c) 2019-2022 Advanced Micro Devices, Inc. All rights reserved. \n29License: MIT3031Documentation of all members: D3D12MemAlloc.h3233\section main_table_of_contents Table of contents3435- \subpage quick_start36- [Project setup](@ref quick_start_project_setup)37- [Creating resources](@ref quick_start_creating_resources)38- [Resource reference counting](@ref quick_start_resource_reference_counting)39- [Mapping memory](@ref quick_start_mapping_memory)40- \subpage custom_pools41- \subpage defragmentation42- \subpage statistics43- \subpage resource_aliasing44- \subpage linear_algorithm45- \subpage virtual_allocator46- \subpage configuration47- [Custom CPU memory allocator](@ref custom_memory_allocator)48- [Debug margins](@ref debug_margins)49- \subpage general_considerations50- [Thread safety](@ref general_considerations_thread_safety)51- [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility)52- [Features not supported](@ref general_considerations_features_not_supported)5354\section main_see_also See also5556- [Product page on GPUOpen](https://gpuopen.com/gaming-product/d3d12-memory-allocator/)57- [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator)58*/5960// If using this library on a platform different than Windows PC or want to use different version of DXGI,61// you should include D3D12-compatible headers before this library on your own and define this macro.62#ifndef D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED63#include <d3d12.h>64#include <dxgi1_4.h>65#endif6667// Define this macro to 0 to disable usage of DXGI 1.4 (needed for IDXGIAdapter3 and query for memory budget).68#ifndef D3D12MA_DXGI_1_469#ifdef __IDXGIAdapter3_INTERFACE_DEFINED__70#define D3D12MA_DXGI_1_4 171#else72#define D3D12MA_DXGI_1_4 073#endif74#endif7576/*77When defined to value other than 0, the library will try to use78D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT or D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT79for created textures when possible, which can save memory because some small textures80may get their alignment 4K and their size a multiply of 4K instead of 64K.8182#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 083Disables small texture alignment.84#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 185Enables conservative algorithm that will use small alignment only for some textures86that are surely known to support it.87#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 288Enables query for small alignment to D3D12 (based on Microsoft sample) which will89enable small alignment for more textures, but will also generate D3D Debug Layer90error #721 on call to ID3D12Device::GetResourceAllocationInfo, which you should just91ignore.92*/93#ifndef D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT94#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 195#endif9697/// \cond INTERNAL9899#define D3D12MA_CLASS_NO_COPY(className) \100private: \101className(const className&) = delete; \102className(className&&) = delete; \103className& operator=(const className&) = delete; \104className& operator=(className&&) = delete;105106// To be used with MAKE_HRESULT to define custom error codes.107#define FACILITY_D3D12MA 3542108109/*110If providing your own implementation, you need to implement a subset of std::atomic.111*/112#if !defined(D3D12MA_ATOMIC_UINT32) || !defined(D3D12MA_ATOMIC_UINT64)113#include <atomic>114#endif115116#ifndef D3D12MA_ATOMIC_UINT32117#define D3D12MA_ATOMIC_UINT32 std::atomic<UINT>118#endif119120#ifndef D3D12MA_ATOMIC_UINT64121#define D3D12MA_ATOMIC_UINT64 std::atomic<UINT64>122#endif123124#ifdef D3D12MA_EXPORTS125#define D3D12MA_API __declspec(dllexport)126#elif defined(D3D12MA_IMPORTS)127#define D3D12MA_API __declspec(dllimport)128#else129#define D3D12MA_API130#endif131132// Forward declaration if ID3D12ProtectedResourceSession is not defined inside the headers (older SDK, pre ID3D12Device4)133struct ID3D12ProtectedResourceSession;134135// Define this enum even if SDK doesn't provide it, to simplify the API.136#ifndef __ID3D12Device1_INTERFACE_DEFINED__137typedef enum D3D12_RESIDENCY_PRIORITY138{139D3D12_RESIDENCY_PRIORITY_MINIMUM = 0x28000000,140D3D12_RESIDENCY_PRIORITY_LOW = 0x50000000,141D3D12_RESIDENCY_PRIORITY_NORMAL = 0x78000000,142D3D12_RESIDENCY_PRIORITY_HIGH = 0xa0010000,143D3D12_RESIDENCY_PRIORITY_MAXIMUM = 0xc8000000144} D3D12_RESIDENCY_PRIORITY;145#endif146147namespace D3D12MA148{149class D3D12MA_API IUnknownImpl : public IUnknown150{151public:152virtual ~IUnknownImpl() = default;153virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject);154virtual ULONG STDMETHODCALLTYPE AddRef();155virtual ULONG STDMETHODCALLTYPE Release();156protected:157virtual void ReleaseThis() { delete this; }158private:159D3D12MA_ATOMIC_UINT32 m_RefCount = {1};160};161} // namespace D3D12MA162163/// \endcond164165namespace D3D12MA166{167168/// \cond INTERNAL169class DefragmentationContextPimpl;170class AllocatorPimpl;171class PoolPimpl;172class NormalBlock;173class BlockVector;174class CommittedAllocationList;175class JsonWriter;176class VirtualBlockPimpl;177/// \endcond178179class Pool;180class Allocator;181struct Statistics;182struct DetailedStatistics;183struct TotalStatistics;184185/// \brief Unique identifier of single allocation done inside the memory heap.186typedef UINT64 AllocHandle;187188/// Pointer to custom callback function that allocates CPU memory.189using ALLOCATE_FUNC_PTR = void* (*)(size_t Size, size_t Alignment, void* pPrivateData);190/**191\brief Pointer to custom callback function that deallocates CPU memory.192193`pMemory = null` should be accepted and ignored.194*/195using FREE_FUNC_PTR = void (*)(void* pMemory, void* pPrivateData);196197/// Custom callbacks to CPU memory allocation functions.198struct ALLOCATION_CALLBACKS199{200/// %Allocation function.201ALLOCATE_FUNC_PTR pAllocate;202/// Dellocation function.203FREE_FUNC_PTR pFree;204/// Custom data that will be passed to allocation and deallocation functions as `pUserData` parameter.205void* pPrivateData;206};207208209/// \brief Bit flags to be used with ALLOCATION_DESC::Flags.210enum ALLOCATION_FLAGS211{212/// Zero213ALLOCATION_FLAG_NONE = 0,214215/**216Set this flag if the allocation should have its own dedicated memory allocation (committed resource with implicit heap).217218Use it for special, big resources, like fullscreen textures used as render targets.219220- When used with functions like D3D12MA::Allocator::CreateResource, it will use `ID3D12Device::CreateCommittedResource`,221so the created allocation will contain a resource (D3D12MA::Allocation::GetResource() `!= NULL`) but will not have222a heap (D3D12MA::Allocation::GetHeap() `== NULL`), as the heap is implicit.223- When used with raw memory allocation like D3D12MA::Allocator::AllocateMemory, it will use `ID3D12Device::CreateHeap`,224so the created allocation will contain a heap (D3D12MA::Allocation::GetHeap() `!= NULL`) and its offset will always be 0.225*/226ALLOCATION_FLAG_COMMITTED = 0x1,227228/**229Set this flag to only try to allocate from existing memory heaps and never create new such heap.230231If new allocation cannot be placed in any of the existing heaps, allocation232fails with `E_OUTOFMEMORY` error.233234You should not use D3D12MA::ALLOCATION_FLAG_COMMITTED and235D3D12MA::ALLOCATION_FLAG_NEVER_ALLOCATE at the same time. It makes no sense.236*/237ALLOCATION_FLAG_NEVER_ALLOCATE = 0x2,238239/** Create allocation only if additional memory required for it, if any, won't exceed240memory budget. Otherwise return `E_OUTOFMEMORY`.241*/242ALLOCATION_FLAG_WITHIN_BUDGET = 0x4,243244/** Allocation will be created from upper stack in a double stack pool.245246This flag is only allowed for custom pools created with #POOL_FLAG_ALGORITHM_LINEAR flag.247*/248ALLOCATION_FLAG_UPPER_ADDRESS = 0x8,249250/** Set this flag if the allocated memory will have aliasing resources.251252Use this when calling D3D12MA::Allocator::CreateResource() and similar to253guarantee creation of explicit heap for desired allocation and prevent it from using `CreateCommittedResource`,254so that new allocation object will always have `allocation->GetHeap() != NULL`.255*/256ALLOCATION_FLAG_CAN_ALIAS = 0x10,257258/** Allocation strategy that chooses smallest possible free range for the allocation259to minimize memory usage and fragmentation, possibly at the expense of allocation time.260*/261ALLOCATION_FLAG_STRATEGY_MIN_MEMORY = 0x00010000,262263/** Allocation strategy that chooses first suitable free range for the allocation -264not necessarily in terms of the smallest offset but the one that is easiest and fastest to find265to minimize allocation time, possibly at the expense of allocation quality.266*/267ALLOCATION_FLAG_STRATEGY_MIN_TIME = 0x00020000,268269/** Allocation strategy that chooses always the lowest offset in available space.270This is not the most efficient strategy but achieves highly packed data.271Used internally by defragmentation, not recomended in typical usage.272*/273ALLOCATION_FLAG_STRATEGY_MIN_OFFSET = 0x0004000,274275/// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_MEMORY.276ALLOCATION_FLAG_STRATEGY_BEST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_MEMORY,277/// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_TIME.278ALLOCATION_FLAG_STRATEGY_FIRST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_TIME,279280/// A bit mask to extract only `STRATEGY` bits from entire set of flags.281ALLOCATION_FLAG_STRATEGY_MASK =282ALLOCATION_FLAG_STRATEGY_MIN_MEMORY |283ALLOCATION_FLAG_STRATEGY_MIN_TIME |284ALLOCATION_FLAG_STRATEGY_MIN_OFFSET,285};286287/// \brief Parameters of created D3D12MA::Allocation object. To be used with Allocator::CreateResource.288struct ALLOCATION_DESC289{290/// Flags.291ALLOCATION_FLAGS Flags;292/** \brief The type of memory heap where the new allocation should be placed.293294It must be one of: `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`.295296When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.297*/298D3D12_HEAP_TYPE HeapType;299/** \brief Additional heap flags to be used when allocating memory.300301In most cases it can be 0.302303- If you use D3D12MA::Allocator::CreateResource(), you don't need to care.304Necessary flag `D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`, `D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,305or `D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES` is added automatically.306- If you use D3D12MA::Allocator::AllocateMemory(), you should specify one of those `ALLOW_ONLY` flags.307Except when you validate that D3D12MA::Allocator::GetD3D12Options()`.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1` -308then you can leave it 0.309- You can specify additional flags if needed. Then the memory will always be allocated as310separate block using `D3D12Device::CreateCommittedResource` or `CreateHeap`, not as part of an existing larget block.311312When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.313*/314D3D12_HEAP_FLAGS ExtraHeapFlags;315/** \brief Custom pool to place the new resource in. Optional.316317When not NULL, the resource will be created inside specified custom pool.318*/319Pool* CustomPool;320/// Custom general-purpose pointer that will be stored in D3D12MA::Allocation.321void* pPrivateData;322};323324/** \brief Calculated statistics of memory usage e.g. in a specific memory heap type,325memory segment group, custom pool, or total.326327These are fast to calculate.328See functions: D3D12MA::Allocator::GetBudget(), D3D12MA::Pool::GetStatistics().329*/330struct Statistics331{332/** \brief Number of D3D12 memory blocks allocated - `ID3D12Heap` objects and committed resources.333*/334UINT BlockCount;335/** \brief Number of D3D12MA::Allocation objects allocated.336337Committed allocations have their own blocks, so each one adds 1 to `AllocationCount` as well as `BlockCount`.338*/339UINT AllocationCount;340/** \brief Number of bytes allocated in memory blocks.341*/342UINT64 BlockBytes;343/** \brief Total number of bytes occupied by all D3D12MA::Allocation objects.344345Always less or equal than `BlockBytes`.346Difference `(BlockBytes - AllocationBytes)` is the amount of memory allocated from D3D12347but unused by any D3D12MA::Allocation.348*/349UINT64 AllocationBytes;350};351352/** \brief More detailed statistics than D3D12MA::Statistics.353354These are slower to calculate. Use for debugging purposes.355See functions: D3D12MA::Allocator::CalculateStatistics(), D3D12MA::Pool::CalculateStatistics().356357Averages are not provided because they can be easily calculated as:358359\code360UINT64 AllocationSizeAvg = DetailedStats.Statistics.AllocationBytes / detailedStats.Statistics.AllocationCount;361UINT64 UnusedBytes = DetailedStats.Statistics.BlockBytes - DetailedStats.Statistics.AllocationBytes;362UINT64 UnusedRangeSizeAvg = UnusedBytes / DetailedStats.UnusedRangeCount;363\endcode364*/365struct DetailedStatistics366{367/// Basic statistics.368Statistics Stats;369/// Number of free ranges of memory between allocations.370UINT UnusedRangeCount;371/// Smallest allocation size. `UINT64_MAX` if there are 0 allocations.372UINT64 AllocationSizeMin;373/// Largest allocation size. 0 if there are 0 allocations.374UINT64 AllocationSizeMax;375/// Smallest empty range size. `UINT64_MAX` if there are 0 empty ranges.376UINT64 UnusedRangeSizeMin;377/// Largest empty range size. 0 if there are 0 empty ranges.378UINT64 UnusedRangeSizeMax;379};380381/** \brief General statistics from current state of the allocator -382total memory usage across all memory heaps and segments.383384These are slower to calculate. Use for debugging purposes.385See function D3D12MA::Allocator::CalculateStatistics().386*/387struct TotalStatistics388{389/** \brief One element for each type of heap located at the following indices:390391- 0 = `D3D12_HEAP_TYPE_DEFAULT`392- 1 = `D3D12_HEAP_TYPE_UPLOAD`393- 2 = `D3D12_HEAP_TYPE_READBACK`394- 3 = `D3D12_HEAP_TYPE_CUSTOM`395*/396DetailedStatistics HeapType[4];397/** \brief One element for each memory segment group located at the following indices:398399- 0 = `DXGI_MEMORY_SEGMENT_GROUP_LOCAL`400- 1 = `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL`401402Meaning of these segment groups is:403404- When `IsUMA() == FALSE` (discrete graphics card):405- `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` (index 0) represents GPU memory406(resources allocated in `D3D12_HEAP_TYPE_DEFAULT` or `D3D12_MEMORY_POOL_L1`).407- `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` (index 1) represents system memory408(resources allocated in `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`, or `D3D12_MEMORY_POOL_L0`).409- When `IsUMA() == TRUE` (integrated graphics chip):410- `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` = (index 0) represents memory shared for all the resources.411- `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` = (index 1) is unused and always 0.412*/413DetailedStatistics MemorySegmentGroup[2];414/// Total statistics from all memory allocated from D3D12.415DetailedStatistics Total;416};417418/** \brief %Statistics of current memory usage and available budget for a specific memory segment group.419420These are fast to calculate. See function D3D12MA::Allocator::GetBudget().421*/422struct Budget423{424/** \brief %Statistics fetched from the library.425*/426Statistics Stats;427/** \brief Estimated current memory usage of the program.428429Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.430431It might be different than `BlockBytes` (usually higher) due to additional implicit objects432also occupying the memory, like swapchain, pipeline state objects, descriptor heaps, command lists, or433heaps and resources allocated outside of this library, if any.434*/435UINT64 UsageBytes;436/** \brief Estimated amount of memory available to the program.437438Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.439440It might be different (most probably smaller) than memory capacity returned441by D3D12MA::Allocator::GetMemoryCapacity() due to factors442external to the program, decided by the operating system.443Difference `BudgetBytes - UsageBytes` is the amount of additional memory that can probably444be allocated without problems. Exceeding the budget may result in various problems.445*/446UINT64 BudgetBytes;447};448449450/// \brief Represents single memory allocation done inside VirtualBlock.451struct D3D12MA_API VirtualAllocation452{453/// \brief Unique idenitfier of current allocation. 0 means null/invalid.454AllocHandle AllocHandle;455};456457/** \brief Represents single memory allocation.458459It may be either implicit memory heap dedicated to a single resource or a460specific region of a bigger heap plus unique offset.461462To create such object, fill structure D3D12MA::ALLOCATION_DESC and call function463Allocator::CreateResource.464465The object remembers size and some other information.466To retrieve this information, use methods of this class.467468The object also remembers `ID3D12Resource` and "owns" a reference to it,469so it calls `%Release()` on the resource when destroyed.470*/471class D3D12MA_API Allocation : public IUnknownImpl472{473public:474/** \brief Returns offset in bytes from the start of memory heap.475476You usually don't need to use this offset. If you create a buffer or a texture together with the allocation using function477D3D12MA::Allocator::CreateResource, functions that operate on that resource refer to the beginning of the resource,478not entire memory heap.479480If the Allocation represents committed resource with implicit heap, returns 0.481*/482UINT64 GetOffset() const;483484/// Returns alignment that resource was created with.485UINT64 GetAlignment() const { return m_Alignment; }486487/** \brief Returns size in bytes of the allocation.488489- If you created a buffer or a texture together with the allocation using function D3D12MA::Allocator::CreateResource,490this is the size of the resource returned by `ID3D12Device::GetResourceAllocationInfo`.491- For allocations made out of bigger memory blocks, this also is the size of the memory region assigned exclusively to this allocation.492- For resources created as committed, this value may not be accurate. DirectX implementation may optimize memory usage internally493so that you may even observe regions of `ID3D12Resource::GetGPUVirtualAddress()` + Allocation::GetSize() to overlap in memory and still work correctly.494*/495UINT64 GetSize() const { return m_Size; }496497/** \brief Returns D3D12 resource associated with this object.498499Calling this method doesn't increment resource's reference counter.500*/501ID3D12Resource* GetResource() const { return m_Resource; }502503/// Releases the resource currently pointed by the allocation (if any), sets it to new one, incrementing its reference counter (if not null).504void SetResource(ID3D12Resource* pResource);505506/** \brief Returns memory heap that the resource is created in.507508If the Allocation represents committed resource with implicit heap, returns NULL.509*/510ID3D12Heap* GetHeap() const;511512/// Changes custom pointer for an allocation to a new value.513void SetPrivateData(void* pPrivateData) { m_pPrivateData = pPrivateData; }514515/// Get custom pointer associated with the allocation.516void* GetPrivateData() const { return m_pPrivateData; }517518/** \brief Associates a name with the allocation object. This name is for use in debug diagnostics and tools.519520Internal copy of the string is made, so the memory pointed by the argument can be521changed of freed immediately after this call.522523`Name` can be null.524*/525void SetName(LPCWSTR Name);526527/** \brief Returns the name associated with the allocation object.528529Returned string points to an internal copy.530531If no name was associated with the allocation, returns null.532*/533LPCWSTR GetName() const { return m_Name; }534535/** \brief Returns `TRUE` if the memory of the allocation was filled with zeros when the allocation was created.536537Returns `TRUE` only if the allocator is sure that the entire memory where the538allocation was created was filled with zeros at the moment the allocation was made.539540Returns `FALSE` if the memory could potentially contain garbage data.541If it's a render-target or depth-stencil texture, it then needs proper542initialization with `ClearRenderTargetView`, `ClearDepthStencilView`, `DiscardResource`,543or a copy operation, as described on page544"ID3D12Device::CreatePlacedResource method - Notes on the required resource initialization" in Microsoft documentation.545Please note that rendering a fullscreen triangle or quad to the texture as546a render target is not a proper way of initialization!547548See also articles:549550- "Coming to DirectX 12: More control over memory allocation" on DirectX Developer Blog551- ["Initializing DX12 Textures After Allocation and Aliasing"](https://asawicki.info/news_1724_initializing_dx12_textures_after_allocation_and_aliasing).552*/553BOOL WasZeroInitialized() const { return m_PackedData.WasZeroInitialized(); }554555protected:556void ReleaseThis() override;557558private:559friend class AllocatorPimpl;560friend class BlockVector;561friend class CommittedAllocationList;562friend class JsonWriter;563friend class BlockMetadata_Linear;564friend class DefragmentationContextPimpl;565friend struct CommittedAllocationListItemTraits;566template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);567template<typename T> friend class PoolAllocator;568569enum Type570{571TYPE_COMMITTED,572TYPE_PLACED,573TYPE_HEAP,574TYPE_COUNT575};576577AllocatorPimpl* m_Allocator;578UINT64 m_Size;579UINT64 m_Alignment;580ID3D12Resource* m_Resource;581void* m_pPrivateData;582wchar_t* m_Name;583584union585{586struct587{588CommittedAllocationList* list;589Allocation* prev;590Allocation* next;591} m_Committed;592593struct594{595AllocHandle allocHandle;596NormalBlock* block;597} m_Placed;598599struct600{601// Beginning must be compatible with m_Committed.602CommittedAllocationList* list;603Allocation* prev;604Allocation* next;605ID3D12Heap* heap;606} m_Heap;607};608609struct PackedData610{611public:612PackedData() :613m_Type(0), m_ResourceDimension(0), m_ResourceFlags(0), m_TextureLayout(0), m_WasZeroInitialized(0) { }614615Type GetType() const { return (Type)m_Type; }616D3D12_RESOURCE_DIMENSION GetResourceDimension() const { return (D3D12_RESOURCE_DIMENSION)m_ResourceDimension; }617D3D12_RESOURCE_FLAGS GetResourceFlags() const { return (D3D12_RESOURCE_FLAGS)m_ResourceFlags; }618D3D12_TEXTURE_LAYOUT GetTextureLayout() const { return (D3D12_TEXTURE_LAYOUT)m_TextureLayout; }619BOOL WasZeroInitialized() const { return (BOOL)m_WasZeroInitialized; }620621void SetType(Type type);622void SetResourceDimension(D3D12_RESOURCE_DIMENSION resourceDimension);623void SetResourceFlags(D3D12_RESOURCE_FLAGS resourceFlags);624void SetTextureLayout(D3D12_TEXTURE_LAYOUT textureLayout);625void SetWasZeroInitialized(BOOL wasZeroInitialized) { m_WasZeroInitialized = wasZeroInitialized ? 1 : 0; }626627private:628UINT m_Type : 2; // enum Type629UINT m_ResourceDimension : 3; // enum D3D12_RESOURCE_DIMENSION630UINT m_ResourceFlags : 24; // flags D3D12_RESOURCE_FLAGS631UINT m_TextureLayout : 9; // enum D3D12_TEXTURE_LAYOUT632UINT m_WasZeroInitialized : 1; // BOOL633} m_PackedData;634635Allocation(AllocatorPimpl* allocator, UINT64 size, UINT64 alignment, BOOL wasZeroInitialized);636// Nothing here, everything already done in Release.637virtual ~Allocation() = default;638639void InitCommitted(CommittedAllocationList* list);640void InitPlaced(AllocHandle allocHandle, NormalBlock* block);641void InitHeap(CommittedAllocationList* list, ID3D12Heap* heap);642void SwapBlockAllocation(Allocation* allocation);643// If the Allocation represents committed resource with implicit heap, returns UINT64_MAX.644AllocHandle GetAllocHandle() const;645NormalBlock* GetBlock();646template<typename D3D12_RESOURCE_DESC_T>647void SetResourcePointer(ID3D12Resource* resource, const D3D12_RESOURCE_DESC_T* pResourceDesc);648void FreeName();649650D3D12MA_CLASS_NO_COPY(Allocation)651};652653654/// Flags to be passed as DEFRAGMENTATION_DESC::Flags.655enum DEFRAGMENTATION_FLAGS656{657/** Use simple but fast algorithm for defragmentation.658May not achieve best results but will require least time to compute and least allocations to copy.659*/660DEFRAGMENTATION_FLAG_ALGORITHM_FAST = 0x1,661/** Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified.662Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved.663*/664DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED = 0x2,665/** Perform full defragmentation of memory.666Can result in notably more time to compute and allocations to copy, but will achieve best memory packing.667*/668DEFRAGMENTATION_FLAG_ALGORITHM_FULL = 0x4,669670/// A bit mask to extract only `ALGORITHM` bits from entire set of flags.671DEFRAGMENTATION_FLAG_ALGORITHM_MASK =672DEFRAGMENTATION_FLAG_ALGORITHM_FAST |673DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED |674DEFRAGMENTATION_FLAG_ALGORITHM_FULL675};676677/** \brief Parameters for defragmentation.678679To be used with functions Allocator::BeginDefragmentation() and Pool::BeginDefragmentation().680*/681struct DEFRAGMENTATION_DESC682{683/// Flags.684DEFRAGMENTATION_FLAGS Flags;685/** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places.6866870 means no limit.688*/689UINT64 MaxBytesPerPass;690/** \brief Maximum number of allocations that can be moved during single pass to a different place.6916920 means no limit.693*/694UINT32 MaxAllocationsPerPass;695};696697/// Operation performed on single defragmentation move.698enum DEFRAGMENTATION_MOVE_OPERATION699{700/** Resource has been recreated at `pDstTmpAllocation`, data has been copied, old resource has been destroyed.701`pSrcAllocation` will be changed to point to the new place. This is the default value set by DefragmentationContext::BeginPass().702*/703DEFRAGMENTATION_MOVE_OPERATION_COPY = 0,704/// Set this value if you cannot move the allocation. New place reserved at `pDstTmpAllocation` will be freed. `pSrcAllocation` will remain unchanged.705DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1,706/// Set this value if you decide to abandon the allocation and you destroyed the resource. New place reserved `pDstTmpAllocation` will be freed, along with `pSrcAllocation`.707DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2,708};709710/// Single move of an allocation to be done for defragmentation.711struct DEFRAGMENTATION_MOVE712{713/** \brief Operation to be performed on the allocation by DefragmentationContext::EndPass().714Default value is #DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it.715*/716DEFRAGMENTATION_MOVE_OPERATION Operation;717/// %Allocation that should be moved.718Allocation* pSrcAllocation;719/** \brief Temporary allocation pointing to destination memory that will replace `pSrcAllocation`.720721Use it to retrieve new `ID3D12Heap` and offset to create new `ID3D12Resource` and then store it here via Allocation::SetResource().722723\warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass,724to be used for storing newly created resource. DefragmentationContext::EndPass() will destroy it and make `pSrcAllocation` point to this memory.725*/726Allocation* pDstTmpAllocation;727};728729/** \brief Parameters for incremental defragmentation steps.730731To be used with function DefragmentationContext::BeginPass().732*/733struct DEFRAGMENTATION_PASS_MOVE_INFO734{735/// Number of elements in the `pMoves` array.736UINT32 MoveCount;737/** \brief Array of moves to be performed by the user in the current defragmentation pass.738739Pointer to an array of `MoveCount` elements, owned by %D3D12MA, created in DefragmentationContext::BeginPass(), destroyed in DefragmentationContext::EndPass().740741For each element, you should:7427431. Create a new resource in the place pointed by `pMoves[i].pDstTmpAllocation->GetHeap()` + `pMoves[i].pDstTmpAllocation->GetOffset()`.7442. Store new resource in `pMoves[i].pDstTmpAllocation` by using Allocation::SetResource(). It will later replace old resource from `pMoves[i].pSrcAllocation`.7453. Copy data from the `pMoves[i].pSrcAllocation` e.g. using `D3D12GraphicsCommandList::CopyResource`.7464. Make sure these commands finished executing on the GPU.747748Only then you can finish defragmentation pass by calling DefragmentationContext::EndPass().749After this call, the allocation will point to the new place in memory.750751Alternatively, if you cannot move specific allocation,752you can set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.753754Alternatively, if you decide you want to completely remove the allocation,755set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY.756Then, after DefragmentationContext::EndPass() the allocation will be released.757*/758DEFRAGMENTATION_MOVE* pMoves;759};760761/// %Statistics returned for defragmentation process by function DefragmentationContext::GetStats().762struct DEFRAGMENTATION_STATS763{764/// Total number of bytes that have been copied while moving allocations to different places.765UINT64 BytesMoved;766/// Total number of bytes that have been released to the system by freeing empty heaps.767UINT64 BytesFreed;768/// Number of allocations that have been moved to different places.769UINT32 AllocationsMoved;770/// Number of empty `ID3D12Heap` objects that have been released to the system.771UINT32 HeapsFreed;772};773774/** \brief Represents defragmentation process in progress.775776You can create this object using Allocator::BeginDefragmentation (for default pools) or777Pool::BeginDefragmentation (for a custom pool).778*/779class D3D12MA_API DefragmentationContext : public IUnknownImpl780{781public:782/** \brief Starts single defragmentation pass.783784\param[out] pPassInfo Computed informations for current pass.785\returns786- `S_OK` if no more moves are possible. Then you can omit call to DefragmentationContext::EndPass() and simply end whole defragmentation.787- `S_FALSE` if there are pending moves returned in `pPassInfo`. You need to perform them, call DefragmentationContext::EndPass(),788and then preferably try another pass with DefragmentationContext::BeginPass().789*/790HRESULT BeginPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);791/** \brief Ends single defragmentation pass.792793\param pPassInfo Computed informations for current pass filled by DefragmentationContext::BeginPass() and possibly modified by you.794\return Returns `S_OK` if no more moves are possible or `S_FALSE` if more defragmentations are possible.795796Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`.797After this call:798799- %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].Operation ==` #DEFRAGMENTATION_MOVE_OPERATION_COPY800(which is the default) will be pointing to the new destination place.801- %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].operation ==` #DEFRAGMENTATION_MOVE_OPERATION_DESTROY802will be released.803804If no more moves are possible you can end whole defragmentation.805*/806HRESULT EndPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);807/** \brief Returns statistics of the defragmentation performed so far.808*/809void GetStats(DEFRAGMENTATION_STATS* pStats);810811protected:812void ReleaseThis() override;813814private:815friend class Pool;816friend class Allocator;817template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);818819DefragmentationContextPimpl* m_Pimpl;820821DefragmentationContext(AllocatorPimpl* allocator,822const DEFRAGMENTATION_DESC& desc,823BlockVector* poolVector);824~DefragmentationContext();825826D3D12MA_CLASS_NO_COPY(DefragmentationContext)827};828829/// \brief Bit flags to be used with POOL_DESC::Flags.830enum POOL_FLAGS831{832/// Zero833POOL_FLAG_NONE = 0,834835/** \brief Enables alternative, linear allocation algorithm in this pool.836837Specify this flag to enable linear allocation algorithm, which always creates838new allocations after last one and doesn't reuse space from allocations freed in839between. It trades memory consumption for simplified algorithm and data840structure, which has better performance and uses less memory for metadata.841842By using this flag, you can achieve behavior of free-at-once, stack,843ring buffer, and double stack.844For details, see documentation chapter \ref linear_algorithm.845*/846POOL_FLAG_ALGORITHM_LINEAR = 0x1,847848/** \brief Optimization, allocate MSAA textures as committed resources always.849850Specify this flag to create MSAA textures with implicit heaps, as if they were created851with flag D3D12MA::ALLOCATION_FLAG_COMMITTED. Usage of this flags enables pool to create its heaps852on smaller alignment not suitable for MSAA textures.853*/854POOL_FLAG_MSAA_TEXTURES_ALWAYS_COMMITTED = 0x2,855856// Bit mask to extract only `ALGORITHM` bits from entire set of flags.857POOL_FLAG_ALGORITHM_MASK = POOL_FLAG_ALGORITHM_LINEAR858};859860/// \brief Parameters of created D3D12MA::Pool object. To be used with D3D12MA::Allocator::CreatePool.861struct POOL_DESC862{863/// Flags.864POOL_FLAGS Flags;865/** \brief The parameters of memory heap where allocations of this pool should be placed.866867In the simplest case, just fill it with zeros and set `Type` to one of: `D3D12_HEAP_TYPE_DEFAULT`,868`D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`. Additional parameters can be used e.g. to utilize UMA.869*/870D3D12_HEAP_PROPERTIES HeapProperties;871/** \brief Heap flags to be used when allocating heaps of this pool.872873It should contain one of these values, depending on type of resources you are going to create in this heap:874`D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,875`D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,876`D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.877Except if ResourceHeapTier = 2, then it may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.878879You can specify additional flags if needed.880*/881D3D12_HEAP_FLAGS HeapFlags;882/** \brief Size of a single heap (memory block) to be allocated as part of this pool, in bytes. Optional.883884Specify nonzero to set explicit, constant size of memory blocks used by this pool.885Leave 0 to use default and let the library manage block sizes automatically.886Then sizes of particular blocks may vary.887*/888UINT64 BlockSize;889/** \brief Minimum number of heaps (memory blocks) to be always allocated in this pool, even if they stay empty. Optional.890891Set to 0 to have no preallocated blocks and allow the pool be completely empty.892*/893UINT MinBlockCount;894/** \brief Maximum number of heaps (memory blocks) that can be allocated in this pool. Optional.895896Set to 0 to use default, which is `UINT64_MAX`, which means no limit.897898Set to same value as D3D12MA::POOL_DESC::MinBlockCount to have fixed amount of memory allocated899throughout whole lifetime of this pool.900*/901UINT MaxBlockCount;902/** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.903904Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.905*/906UINT64 MinAllocationAlignment;907/** \brief Additional parameter allowing pool to create resources with passed protected session.908909If not null then all the heaps and committed resources will be created with this parameter.910Valid only if ID3D12Device4 interface is present in current Windows SDK!911*/912ID3D12ProtectedResourceSession* pProtectedSession;913/** \brief Residency priority to be set for all allocations made in this pool. Optional.914915Set this parameter to one of the possible enum values e.g. `D3D12_RESIDENCY_PRIORITY_HIGH`916to apply specific residency priority to all allocations made in this pool:917`ID3D12Heap` memory blocks used to sub-allocate for placed resources, as well as918committed resources or heaps created when D3D12MA::ALLOCATION_FLAG_COMMITTED is used.919This can increase/decrease chance that the memory will be pushed out from VRAM920to system RAM when the system runs out of memory, which is invisible to the developer921using D3D12 API while it can degrade performance.922923Priority is set using function `ID3D12Device1::SetResidencyPriority`.924It is performed only when `ID3D12Device1` interface is defined and successfully obtained.925Otherwise, this parameter is ignored.926927This parameter is optional. If you set it to `D3D12_RESIDENCY_PRIORITY(0)`,928residency priority will not be set for allocations made in this pool.929930There is no equivalent parameter for allocations made in default pools.931If you want to set residency priority for such allocation, you need to do it manually:932allocate with D3D12MA::ALLOCATION_FLAG_COMMITTED and call933`ID3D12Device1::SetResidencyPriority`, passing `allocation->GetResource()`.934*/935D3D12_RESIDENCY_PRIORITY ResidencyPriority;936};937938/** \brief Custom memory pool939940Represents a separate set of heaps (memory blocks) that can be used to create941D3D12MA::Allocation-s and resources in it. Usually there is no need to create custom942pools - creating resources in default pool is sufficient.943944To create custom pool, fill D3D12MA::POOL_DESC and call D3D12MA::Allocator::CreatePool.945*/946class D3D12MA_API Pool : public IUnknownImpl947{948public:949/** \brief Returns copy of parameters of the pool.950951These are the same parameters as passed to D3D12MA::Allocator::CreatePool.952*/953POOL_DESC GetDesc() const;954955/** \brief Retrieves basic statistics of the custom pool that are fast to calculate.956957\param[out] pStats %Statistics of the current pool.958*/959void GetStatistics(Statistics* pStats);960961/** \brief Retrieves detailed statistics of the custom pool that are slower to calculate.962963\param[out] pStats %Statistics of the current pool.964*/965void CalculateStatistics(DetailedStatistics* pStats);966967/** \brief Associates a name with the pool. This name is for use in debug diagnostics and tools.968969Internal copy of the string is made, so the memory pointed by the argument can be970changed of freed immediately after this call.971972`Name` can be NULL.973*/974void SetName(LPCWSTR Name);975976/** \brief Returns the name associated with the pool object.977978Returned string points to an internal copy.979980If no name was associated with the allocation, returns NULL.981*/982LPCWSTR GetName() const;983984/** \brief Begins defragmentation process of the current pool.985986\param pDesc Structure filled with parameters of defragmentation.987\param[out] ppContext Context object that will manage defragmentation.988\returns989- `S_OK` if defragmentation can begin.990- `E_NOINTERFACE` if defragmentation is not supported.991992For more information about defragmentation, see documentation chapter:993[Defragmentation](@ref defragmentation).994*/995HRESULT BeginDefragmentation(const DEFRAGMENTATION_DESC* pDesc, DefragmentationContext** ppContext);996997protected:998void ReleaseThis() override;9991000private:1001friend class Allocator;1002friend class AllocatorPimpl;1003template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);10041005PoolPimpl* m_Pimpl;10061007Pool(Allocator* allocator, const POOL_DESC &desc);1008~Pool();10091010D3D12MA_CLASS_NO_COPY(Pool)1011};101210131014/// \brief Bit flags to be used with ALLOCATOR_DESC::Flags.1015enum ALLOCATOR_FLAGS1016{1017/// Zero1018ALLOCATOR_FLAG_NONE = 0,10191020/**1021Allocator and all objects created from it will not be synchronized internally,1022so you must guarantee they are used from only one thread at a time or1023synchronized by you.10241025Using this flag may increase performance because internal mutexes are not used.1026*/1027ALLOCATOR_FLAG_SINGLETHREADED = 0x1,10281029/**1030Every allocation will have its own memory block.1031To be used for debugging purposes.1032*/1033ALLOCATOR_FLAG_ALWAYS_COMMITTED = 0x2,10341035/**1036Heaps created for the default pools will be created with flag `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`,1037allowing for their memory to be not zeroed by the system if possible,1038which can speed up allocation.10391040Only affects default pools.1041To use the flag with @ref custom_pools, you need to add it manually:10421043\code1044poolDesc.heapFlags |= D3D12_HEAP_FLAG_CREATE_NOT_ZEROED;1045\endcode10461047Only avaiable if `ID3D12Device8` is present. Otherwise, the flag is ignored.1048*/1049ALLOCATOR_FLAG_DEFAULT_POOLS_NOT_ZEROED = 0x4,10501051/** \brief Optimization, allocate MSAA textures as committed resources always.10521053Specify this flag to create MSAA textures with implicit heaps, as if they were created1054with flag D3D12MA::ALLOCATION_FLAG_COMMITTED. Usage of this flags enables all default pools1055to create its heaps on smaller alignment not suitable for MSAA textures.1056*/1057ALLOCATOR_FLAG_MSAA_TEXTURES_ALWAYS_COMMITTED = 0x8,1058};10591060/// \brief Parameters of created Allocator object. To be used with CreateAllocator().1061struct ALLOCATOR_DESC1062{1063/// Flags.1064ALLOCATOR_FLAGS Flags;10651066/** Direct3D device object that the allocator should be attached to.10671068Allocator is doing `AddRef`/`Release` on this object.1069*/1070ID3D12Device* pDevice;10711072/** \brief Preferred size of a single `ID3D12Heap` block to be allocated.10731074Set to 0 to use default, which is currently 64 MiB.1075*/1076UINT64 PreferredBlockSize;10771078/** \brief Custom CPU memory allocation callbacks. Optional.10791080Optional, can be null. When specified, will be used for all CPU-side memory allocations.1081*/1082const ALLOCATION_CALLBACKS* pAllocationCallbacks;10831084/** DXGI Adapter object that you use for D3D12 and this allocator.10851086Allocator is doing `AddRef`/`Release` on this object.1087*/1088IDXGIAdapter* pAdapter;1089};10901091/**1092\brief Represents main object of this library initialized for particular `ID3D12Device`.10931094Fill structure D3D12MA::ALLOCATOR_DESC and call function CreateAllocator() to create it.1095Call method `Release()` to destroy it.10961097It is recommended to create just one object of this type per `ID3D12Device` object,1098right after Direct3D 12 is initialized and keep it alive until before Direct3D device is destroyed.1099*/1100class D3D12MA_API Allocator : public IUnknownImpl1101{1102public:1103/// Returns cached options retrieved from D3D12 device.1104const D3D12_FEATURE_DATA_D3D12_OPTIONS& GetD3D12Options() const;1105/** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::UMA` was found to be true.11061107For more information about how to use it, see articles in Microsoft Docs articles:11081109- "UMA Optimizations: CPU Accessible Textures and Standard Swizzle"1110- "D3D12_FEATURE_DATA_ARCHITECTURE structure (d3d12.h)"1111- "ID3D12Device::GetCustomHeapProperties method (d3d12.h)"1112*/1113BOOL IsUMA() const;1114/** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::CacheCoherentUMA` was found to be true.11151116For more information about how to use it, see articles in Microsoft Docs articles:11171118- "UMA Optimizations: CPU Accessible Textures and Standard Swizzle"1119- "D3D12_FEATURE_DATA_ARCHITECTURE structure (d3d12.h)"1120- "ID3D12Device::GetCustomHeapProperties method (d3d12.h)"1121*/1122BOOL IsCacheCoherentUMA() const;1123/** \brief Returns total amount of memory of specific segment group, in bytes.11241125\param memorySegmentGroup use `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` or DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL`.11261127This information is taken from `DXGI_ADAPTER_DESC`.1128It is not recommended to use this number.1129You should preferably call GetBudget() and limit memory usage to D3D12MA::Budget::BudgetBytes instead.11301131- When IsUMA() `== FALSE` (discrete graphics card):1132- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)` returns the size of the video memory.1133- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)` returns the size of the system memory available for D3D12 resources.1134- When IsUMA() `== TRUE` (integrated graphics chip):1135- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)` returns the size of the shared memory available for all D3D12 resources.1136All memory is considered "local".1137- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)` is not applicable and returns 0.1138*/1139UINT64 GetMemoryCapacity(UINT memorySegmentGroup) const;11401141/** \brief Allocates memory and creates a D3D12 resource (buffer or texture). This is the main allocation function.11421143The function is similar to `ID3D12Device::CreateCommittedResource`, but it may1144really call `ID3D12Device::CreatePlacedResource` to assign part of a larger,1145existing memory heap to the new resource, which is the main purpose of this1146whole library.11471148If `ppvResource` is null, you receive only `ppAllocation` object from this function.1149It holds pointer to `ID3D12Resource` that can be queried using function D3D12MA::Allocation::GetResource().1150Reference count of the resource object is 1.1151It is automatically destroyed when you destroy the allocation object.11521153If `ppvResource` is not null, you receive pointer to the resource next to allocation object.1154Reference count of the resource object is then increased by calling `QueryInterface`, so you need to manually `Release` it1155along with the allocation.11561157\param pAllocDesc Parameters of the allocation.1158\param pResourceDesc Description of created resource.1159\param InitialResourceState Initial resource state.1160\param pOptimizedClearValue Optional. Either null or optimized clear value.1161\param[out] ppAllocation Filled with pointer to new allocation object created.1162\param riidResource IID of a resource to be returned via `ppvResource`.1163\param[out] ppvResource Optional. If not null, filled with pointer to new resouce created.11641165\note This function creates a new resource. Sub-allocation of parts of one large buffer,1166although recommended as a good practice, is out of scope of this library and could be implemented1167by the user as a higher-level logic on top of it, e.g. using the \ref virtual_allocator feature.1168*/1169HRESULT CreateResource(1170const ALLOCATION_DESC* pAllocDesc,1171const D3D12_RESOURCE_DESC* pResourceDesc,1172D3D12_RESOURCE_STATES InitialResourceState,1173const D3D12_CLEAR_VALUE *pOptimizedClearValue,1174Allocation** ppAllocation,1175REFIID riidResource,1176void** ppvResource);11771178#ifdef __ID3D12Device8_INTERFACE_DEFINED__1179/** \brief Similar to Allocator::CreateResource, but supports new structure `D3D12_RESOURCE_DESC1`.11801181It internally uses `ID3D12Device8::CreateCommittedResource2` or `ID3D12Device8::CreatePlacedResource1`.11821183To work correctly, `ID3D12Device8` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1184*/1185HRESULT CreateResource2(1186const ALLOCATION_DESC* pAllocDesc,1187const D3D12_RESOURCE_DESC1* pResourceDesc,1188D3D12_RESOURCE_STATES InitialResourceState,1189const D3D12_CLEAR_VALUE *pOptimizedClearValue,1190Allocation** ppAllocation,1191REFIID riidResource,1192void** ppvResource);1193#endif // #ifdef __ID3D12Device8_INTERFACE_DEFINED__11941195#ifdef __ID3D12Device10_INTERFACE_DEFINED__1196/** \brief Similar to Allocator::CreateResource2, but there are initial layout instead of state and1197castable formats list11981199It internally uses `ID3D12Device10::CreateCommittedResource3` or `ID3D12Device10::CreatePlacedResource2`.12001201To work correctly, `ID3D12Device10` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1202*/1203HRESULT CreateResource3(const ALLOCATION_DESC* pAllocDesc,1204const D3D12_RESOURCE_DESC1* pResourceDesc,1205D3D12_BARRIER_LAYOUT InitialLayout,1206const D3D12_CLEAR_VALUE* pOptimizedClearValue,1207UINT32 NumCastableFormats,1208DXGI_FORMAT* pCastableFormats,1209Allocation** ppAllocation,1210REFIID riidResource,1211void** ppvResource);1212#endif // #ifdef __ID3D12Device10_INTERFACE_DEFINED__12131214/** \brief Allocates memory without creating any resource placed in it.12151216This function is similar to `ID3D12Device::CreateHeap`, but it may really assign1217part of a larger, existing heap to the allocation.12181219`pAllocDesc->heapFlags` should contain one of these values, depending on type of resources you are going to create in this memory:1220`D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,1221`D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,1222`D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.1223Except if you validate that ResourceHeapTier = 2 - then `heapFlags`1224may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.1225Additional flags in `heapFlags` are allowed as well.12261227`pAllocInfo->SizeInBytes` must be multiply of 64KB.1228`pAllocInfo->Alignment` must be one of the legal values as described in documentation of `D3D12_HEAP_DESC`.12291230If you use D3D12MA::ALLOCATION_FLAG_COMMITTED you will get a separate memory block -1231a heap that always has offset 0.1232*/1233HRESULT AllocateMemory(1234const ALLOCATION_DESC* pAllocDesc,1235const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,1236Allocation** ppAllocation);12371238/** \brief Creates a new resource in place of an existing allocation. This is useful for memory aliasing.12391240\param pAllocation Existing allocation indicating the memory where the new resource should be created.1241It can be created using D3D12MA::Allocator::CreateResource and already have a resource bound to it,1242or can be a raw memory allocated with D3D12MA::Allocator::AllocateMemory.1243It must not be created as committed so that `ID3D12Heap` is available and not implicit.1244\param AllocationLocalOffset Additional offset in bytes to be applied when allocating the resource.1245Local from the start of `pAllocation`, not the beginning of the whole `ID3D12Heap`!1246If the new resource should start from the beginning of the `pAllocation` it should be 0.1247\param pResourceDesc Description of the new resource to be created.1248\param InitialResourceState1249\param pOptimizedClearValue1250\param riidResource1251\param[out] ppvResource Returns pointer to the new resource.1252The resource is not bound with `pAllocation`.1253This pointer must not be null - you must get the resource pointer and `Release` it when no longer needed.12541255Memory requirements of the new resource are checked for validation.1256If its size exceeds the end of `pAllocation` or required alignment is not fulfilled1257considering `pAllocation->GetOffset() + AllocationLocalOffset`, the function1258returns `E_INVALIDARG`.1259*/1260HRESULT CreateAliasingResource(1261Allocation* pAllocation,1262UINT64 AllocationLocalOffset,1263const D3D12_RESOURCE_DESC* pResourceDesc,1264D3D12_RESOURCE_STATES InitialResourceState,1265const D3D12_CLEAR_VALUE *pOptimizedClearValue,1266REFIID riidResource,1267void** ppvResource);12681269#ifdef __ID3D12Device8_INTERFACE_DEFINED__1270/** \brief Similar to Allocator::CreateAliasingResource, but supports new structure `D3D12_RESOURCE_DESC1`.12711272It internally uses `ID3D12Device8::CreatePlacedResource1`.12731274To work correctly, `ID3D12Device8` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1275*/1276HRESULT CreateAliasingResource1(Allocation* pAllocation,1277UINT64 AllocationLocalOffset,1278const D3D12_RESOURCE_DESC1* pResourceDesc,1279D3D12_RESOURCE_STATES InitialResourceState,1280const D3D12_CLEAR_VALUE* pOptimizedClearValue,1281REFIID riidResource,1282void** ppvResource);1283#endif // #ifdef __ID3D12Device8_INTERFACE_DEFINED__12841285#ifdef __ID3D12Device10_INTERFACE_DEFINED__1286/** \brief Similar to Allocator::CreateAliasingResource1, but there are initial layout instead of state and1287castable formats list12881289It internally uses `ID3D12Device10::CreatePlacedResource2`.12901291To work correctly, `ID3D12Device10` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1292*/1293HRESULT CreateAliasingResource2(Allocation* pAllocation,1294UINT64 AllocationLocalOffset,1295const D3D12_RESOURCE_DESC1* pResourceDesc,1296D3D12_BARRIER_LAYOUT InitialLayout,1297const D3D12_CLEAR_VALUE* pOptimizedClearValue,1298UINT32 NumCastableFormats,1299DXGI_FORMAT* pCastableFormats,1300REFIID riidResource,1301void** ppvResource);1302#endif // #ifdef __ID3D12Device10_INTERFACE_DEFINED__13031304/** \brief Creates custom pool.1305*/1306HRESULT CreatePool(1307const POOL_DESC* pPoolDesc,1308Pool** ppPool);13091310/** \brief Sets the index of the current frame.13111312This function is used to set the frame index in the allocator when a new game frame begins.1313*/1314void SetCurrentFrameIndex(UINT frameIndex);13151316/** \brief Retrieves information about current memory usage and budget.13171318\param[out] pLocalBudget Optional, can be null.1319\param[out] pNonLocalBudget Optional, can be null.13201321- When IsUMA() `== FALSE` (discrete graphics card):1322- `pLocalBudget` returns the budget of the video memory.1323- `pNonLocalBudget` returns the budget of the system memory available for D3D12 resources.1324- When IsUMA() `== TRUE` (integrated graphics chip):1325- `pLocalBudget` returns the budget of the shared memory available for all D3D12 resources.1326All memory is considered "local".1327- `pNonLocalBudget` is not applicable and returns zeros.13281329This function is called "get" not "calculate" because it is very fast, suitable to be called1330every frame or every allocation. For more detailed statistics use CalculateStatistics().13311332Note that when using allocator from multiple threads, returned information may immediately1333become outdated.1334*/1335void GetBudget(Budget* pLocalBudget, Budget* pNonLocalBudget);13361337/** \brief Retrieves statistics from current state of the allocator.13381339This function is called "calculate" not "get" because it has to traverse all1340internal data structures, so it may be quite slow. Use it for debugging purposes.1341For faster but more brief statistics suitable to be called every frame or every allocation,1342use GetBudget().13431344Note that when using allocator from multiple threads, returned information may immediately1345become outdated.1346*/1347void CalculateStatistics(TotalStatistics* pStats);13481349/** \brief Builds and returns statistics as a string in JSON format.1350*1351@param[out] ppStatsString Must be freed using Allocator::FreeStatsString.1352@param DetailedMap `TRUE` to include full list of allocations (can make the string quite long), `FALSE` to only return statistics.1353*/1354void BuildStatsString(WCHAR** ppStatsString, BOOL DetailedMap) const;13551356/// Frees memory of a string returned from Allocator::BuildStatsString.1357void FreeStatsString(WCHAR* pStatsString) const;13581359/** \brief Begins defragmentation process of the default pools.13601361\param pDesc Structure filled with parameters of defragmentation.1362\param[out] ppContext Context object that will manage defragmentation.13631364For more information about defragmentation, see documentation chapter:1365[Defragmentation](@ref defragmentation).1366*/1367void BeginDefragmentation(const DEFRAGMENTATION_DESC* pDesc, DefragmentationContext** ppContext);13681369protected:1370void ReleaseThis() override;13711372private:1373friend D3D12MA_API HRESULT CreateAllocator(const ALLOCATOR_DESC*, Allocator**);1374template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);1375friend class DefragmentationContext;1376friend class Pool;13771378Allocator(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc);1379~Allocator();13801381AllocatorPimpl* m_Pimpl;13821383D3D12MA_CLASS_NO_COPY(Allocator)1384};138513861387/// \brief Bit flags to be used with VIRTUAL_BLOCK_DESC::Flags.1388enum VIRTUAL_BLOCK_FLAGS1389{1390/// Zero1391VIRTUAL_BLOCK_FLAG_NONE = 0,13921393/** \brief Enables alternative, linear allocation algorithm in this virtual block.13941395Specify this flag to enable linear allocation algorithm, which always creates1396new allocations after last one and doesn't reuse space from allocations freed in1397between. It trades memory consumption for simplified algorithm and data1398structure, which has better performance and uses less memory for metadata.13991400By using this flag, you can achieve behavior of free-at-once, stack,1401ring buffer, and double stack.1402For details, see documentation chapter \ref linear_algorithm.1403*/1404VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR = POOL_FLAG_ALGORITHM_LINEAR,14051406// Bit mask to extract only `ALGORITHM` bits from entire set of flags.1407VIRTUAL_BLOCK_FLAG_ALGORITHM_MASK = POOL_FLAG_ALGORITHM_MASK1408};14091410/// Parameters of created D3D12MA::VirtualBlock object to be passed to CreateVirtualBlock().1411struct VIRTUAL_BLOCK_DESC1412{1413/// Flags.1414VIRTUAL_BLOCK_FLAGS Flags;1415/** \brief Total size of the block.14161417Sizes can be expressed in bytes or any units you want as long as you are consistent in using them.1418For example, if you allocate from some array of structures, 1 can mean single instance of entire structure.1419*/1420UINT64 Size;1421/** \brief Custom CPU memory allocation callbacks. Optional.14221423Optional, can be null. When specified, will be used for all CPU-side memory allocations.1424*/1425const ALLOCATION_CALLBACKS* pAllocationCallbacks;1426};14271428/// \brief Bit flags to be used with VIRTUAL_ALLOCATION_DESC::Flags.1429enum VIRTUAL_ALLOCATION_FLAGS1430{1431/// Zero1432VIRTUAL_ALLOCATION_FLAG_NONE = 0,14331434/** \brief Allocation will be created from upper stack in a double stack pool.14351436This flag is only allowed for virtual blocks created with #VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR flag.1437*/1438VIRTUAL_ALLOCATION_FLAG_UPPER_ADDRESS = ALLOCATION_FLAG_UPPER_ADDRESS,14391440/// Allocation strategy that tries to minimize memory usage.1441VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_MEMORY = ALLOCATION_FLAG_STRATEGY_MIN_MEMORY,1442/// Allocation strategy that tries to minimize allocation time.1443VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_TIME = ALLOCATION_FLAG_STRATEGY_MIN_TIME,1444/** \brief Allocation strategy that chooses always the lowest offset in available space.1445This is not the most efficient strategy but achieves highly packed data.1446*/1447VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_OFFSET = ALLOCATION_FLAG_STRATEGY_MIN_OFFSET,1448/** \brief A bit mask to extract only `STRATEGY` bits from entire set of flags.14491450These strategy flags are binary compatible with equivalent flags in #ALLOCATION_FLAGS.1451*/1452VIRTUAL_ALLOCATION_FLAG_STRATEGY_MASK = ALLOCATION_FLAG_STRATEGY_MASK,1453};14541455/// Parameters of created virtual allocation to be passed to VirtualBlock::Allocate().1456struct VIRTUAL_ALLOCATION_DESC1457{1458/// Flags.1459VIRTUAL_ALLOCATION_FLAGS Flags;1460/** \brief Size of the allocation.14611462Cannot be zero.1463*/1464UINT64 Size;1465/** \brief Required alignment of the allocation.14661467Must be power of two. Special value 0 has the same meaning as 1 - means no special alignment is required, so allocation can start at any offset.1468*/1469UINT64 Alignment;1470/** \brief Custom pointer to be associated with the allocation.14711472It can be fetched or changed later.1473*/1474void* pPrivateData;1475};14761477/// Parameters of an existing virtual allocation, returned by VirtualBlock::GetAllocationInfo().1478struct VIRTUAL_ALLOCATION_INFO1479{1480/// \brief Offset of the allocation.1481UINT64 Offset;1482/** \brief Size of the allocation.14831484Same value as passed in VIRTUAL_ALLOCATION_DESC::Size.1485*/1486UINT64 Size;1487/** \brief Custom pointer associated with the allocation.14881489Same value as passed in VIRTUAL_ALLOCATION_DESC::pPrivateData or VirtualBlock::SetAllocationPrivateData().1490*/1491void* pPrivateData;1492};14931494/** \brief Represents pure allocation algorithm and a data structure with allocations in some memory block, without actually allocating any GPU memory.14951496This class allows to use the core algorithm of the library custom allocations e.g. CPU memory or1497sub-allocation regions inside a single GPU buffer.14981499To create this object, fill in D3D12MA::VIRTUAL_BLOCK_DESC and call CreateVirtualBlock().1500To destroy it, call its method `VirtualBlock::Release()`.1501You need to free all the allocations within this block or call Clear() before destroying it.15021503This object is not thread-safe - should not be used from multiple threads simultaneously, must be synchronized externally.1504*/1505class D3D12MA_API VirtualBlock : public IUnknownImpl1506{1507public:1508/** \brief Returns true if the block is empty - contains 0 allocations.1509*/1510BOOL IsEmpty() const;1511/** \brief Returns information about an allocation - its offset, size and custom pointer.1512*/1513void GetAllocationInfo(VirtualAllocation allocation, VIRTUAL_ALLOCATION_INFO* pInfo) const;15141515/** \brief Creates new allocation.1516\param pDesc1517\param[out] pAllocation Unique indentifier of the new allocation within single block.1518\param[out] pOffset Returned offset of the new allocation. Optional, can be null.1519\return `S_OK` if allocation succeeded, `E_OUTOFMEMORY` if it failed.15201521If the allocation failed, `pAllocation->AllocHandle` is set to 0 and `pOffset`, if not null, is set to `UINT64_MAX`.1522*/1523HRESULT Allocate(const VIRTUAL_ALLOCATION_DESC* pDesc, VirtualAllocation* pAllocation, UINT64* pOffset);1524/** \brief Frees the allocation.15251526Calling this function with `allocation.AllocHandle == 0` is correct and does nothing.1527*/1528void FreeAllocation(VirtualAllocation allocation);1529/** \brief Frees all the allocations.1530*/1531void Clear();1532/** \brief Changes custom pointer for an allocation to a new value.1533*/1534void SetAllocationPrivateData(VirtualAllocation allocation, void* pPrivateData);1535/** \brief Retrieves basic statistics of the virtual block that are fast to calculate.15361537\param[out] pStats %Statistics of the virtual block.1538*/1539void GetStatistics(Statistics* pStats) const;1540/** \brief Retrieves detailed statistics of the virtual block that are slower to calculate.15411542\param[out] pStats %Statistics of the virtual block.1543*/1544void CalculateStatistics(DetailedStatistics* pStats) const;15451546/** \brief Builds and returns statistics as a string in JSON format, including the list of allocations with their parameters.1547@param[out] ppStatsString Must be freed using VirtualBlock::FreeStatsString.1548*/1549void BuildStatsString(WCHAR** ppStatsString) const;15501551/** \brief Frees memory of a string returned from VirtualBlock::BuildStatsString.1552*/1553void FreeStatsString(WCHAR* pStatsString) const;15541555protected:1556void ReleaseThis() override;15571558private:1559friend D3D12MA_API HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC*, VirtualBlock**);1560template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);15611562VirtualBlockPimpl* m_Pimpl;15631564VirtualBlock(const ALLOCATION_CALLBACKS& allocationCallbacks, const VIRTUAL_BLOCK_DESC& desc);1565~VirtualBlock();15661567D3D12MA_CLASS_NO_COPY(VirtualBlock)1568};156915701571/** \brief Creates new main D3D12MA::Allocator object and returns it through `ppAllocator`.15721573You normally only need to call it once and keep a single Allocator object for your `ID3D12Device`.1574*/1575D3D12MA_API HRESULT CreateAllocator(const ALLOCATOR_DESC* pDesc, Allocator** ppAllocator);15761577/** \brief Creates new D3D12MA::VirtualBlock object and returns it through `ppVirtualBlock`.15781579Note you don't need to create D3D12MA::Allocator to use virtual blocks.1580*/1581D3D12MA_API HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC* pDesc, VirtualBlock** ppVirtualBlock);15821583} // namespace D3D12MA15841585/// \cond INTERNAL1586DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATION_FLAGS);1587DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::DEFRAGMENTATION_FLAGS);1588DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATOR_FLAGS);1589DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::POOL_FLAGS);1590DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::VIRTUAL_BLOCK_FLAGS);1591DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::VIRTUAL_ALLOCATION_FLAGS);1592/// \endcond15931594/**1595\page quick_start Quick start15961597\section quick_start_project_setup Project setup and initialization15981599This is a small, standalone C++ library. It consists of a pair of 2 files:1600"D3D12MemAlloc.h" header file with public interface and "D3D12MemAlloc.cpp" with1601internal implementation. The only external dependencies are WinAPI, Direct3D 12,1602and parts of C/C++ standard library (but STL containers, exceptions, or RTTI are1603not used).16041605The library is developed and tested using Microsoft Visual Studio 2019, but it1606should work with other compilers as well. It is designed for 64-bit code.16071608To use the library in your project:16091610(1.) Copy files `D3D12MemAlloc.cpp`, `%D3D12MemAlloc.h` to your project.16111612(2.) Make `D3D12MemAlloc.cpp` compiling as part of the project, as C++ code.16131614(3.) Include library header in each CPP file that needs to use the library.16151616\code1617#include "D3D12MemAlloc.h"1618\endcode16191620(4.) Right after you created `ID3D12Device`, fill D3D12MA::ALLOCATOR_DESC1621structure and call function D3D12MA::CreateAllocator to create the main1622D3D12MA::Allocator object.16231624Please note that all symbols of the library are declared inside #D3D12MA namespace.16251626\code1627IDXGIAdapter* adapter = (...)1628ID3D12Device* device = (...)16291630D3D12MA::ALLOCATOR_DESC allocatorDesc = {};1631allocatorDesc.pDevice = device;1632allocatorDesc.pAdapter = adapter;16331634D3D12MA::Allocator* allocator;1635HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);1636\endcode16371638(5.) Right before destroying the D3D12 device, destroy the allocator object.16391640Objects of this library must be destroyed by calling `Release` method.1641They are somewhat compatible with COM: they implement `IUnknown` interface with its virtual methods: `AddRef`, `Release`, `QueryInterface`,1642and they are reference-counted internally.1643You can use smart pointers designed for COM with objects of this library - e.g. `CComPtr` or `Microsoft::WRL::ComPtr`.1644The reference counter is thread-safe.1645`QueryInterface` method supports only `IUnknown`, as classes of this library don't define their own GUIDs.16461647\code1648allocator->Release();1649\endcode165016511652\section quick_start_creating_resources Creating resources16531654To use the library for creating resources (textures and buffers), call method1655D3D12MA::Allocator::CreateResource in the place where you would previously call1656`ID3D12Device::CreateCommittedResource`.16571658The function has similar syntax, but it expects structure D3D12MA::ALLOCATION_DESC1659to be passed along with `D3D12_RESOURCE_DESC` and other parameters for created1660resource. This structure describes parameters of the desired memory allocation,1661including choice of `D3D12_HEAP_TYPE`.16621663The function returns a new object of type D3D12MA::Allocation.1664It represents allocated memory and can be queried for size, offset, `ID3D12Heap`.1665It also holds a reference to the `ID3D12Resource`, which can be accessed by calling D3D12MA::Allocation::GetResource().16661667\code1668D3D12_RESOURCE_DESC resourceDesc = {};1669resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;1670resourceDesc.Alignment = 0;1671resourceDesc.Width = 1024;1672resourceDesc.Height = 1024;1673resourceDesc.DepthOrArraySize = 1;1674resourceDesc.MipLevels = 1;1675resourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;1676resourceDesc.SampleDesc.Count = 1;1677resourceDesc.SampleDesc.Quality = 0;1678resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;1679resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;16801681D3D12MA::ALLOCATION_DESC allocationDesc = {};1682allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;16831684D3D12MA::Allocation* allocation;1685HRESULT hr = allocator->CreateResource(1686&allocationDesc,1687&resourceDesc,1688D3D12_RESOURCE_STATE_COPY_DEST,1689NULL,1690&allocation,1691IID_NULL, NULL);16921693// Use allocation->GetResource()...1694\endcode16951696You need to release the allocation object when no longer needed.1697This will also release the D3D12 resource.16981699\code1700allocation->Release();1701\endcode17021703The advantage of using the allocator instead of creating committed resource, and1704the main purpose of this library, is that it can decide to allocate bigger memory1705heap internally using `ID3D12Device::CreateHeap` and place multiple resources in1706it, at different offsets, using `ID3D12Device::CreatePlacedResource`. The library1707manages its own collection of allocated memory blocks (heaps) and remembers which1708parts of them are occupied and which parts are free to be used for new resources.17091710It is important to remember that resources created as placed don't have their memory1711initialized to zeros, but may contain garbage data, so they need to be fully initialized1712before usage, e.g. using Clear (`ClearRenderTargetView`), Discard (`DiscardResource`),1713or copy (`CopyResource`).17141715The library also automatically handles resource heap tier.1716When `D3D12_FEATURE_DATA_D3D12_OPTIONS::ResourceHeapTier` equals `D3D12_RESOURCE_HEAP_TIER_1`,1717resources of 3 types: buffers, textures that are render targets or depth-stencil,1718and other textures must be kept in separate heaps. When `D3D12_RESOURCE_HEAP_TIER_2`,1719they can be kept together. By using this library, you don't need to handle this1720manually.172117221723\section quick_start_resource_reference_counting Resource reference counting17241725`ID3D12Resource` and other interfaces of Direct3D 12 use COM, so they are reference-counted.1726Objects of this library are reference-counted as well.1727An object of type D3D12MA::Allocation remembers the resource (buffer or texture)1728that was created together with this memory allocation1729and holds a reference to the `ID3D12Resource` object.1730(Note this is a difference to Vulkan Memory Allocator, where a `VmaAllocation` object has no connection1731with the buffer or image that was created with it.)1732Thus, it is important to manage the resource reference counter properly.17331734<b>The simplest use case</b> is shown in the code snippet above.1735When only D3D12MA::Allocation object is obtained from a function call like D3D12MA::Allocator::CreateResource,1736it remembers the `ID3D12Resource` that was created with it and holds a reference to it.1737The resource can be obtained by calling `allocation->GetResource()`, which doesn't increment the resource1738reference counter.1739Calling `allocation->Release()` will decrease the resource reference counter, which is = 1 in this case,1740so the resource will be released.17411742<b>Second option</b> is to retrieve a pointer to the resource along with D3D12MA::Allocation.1743Last parameters of the resource creation function can be used for this purpose.17441745\code1746D3D12MA::Allocation* allocation;1747ID3D12Resource* resource;1748HRESULT hr = allocator->CreateResource(1749&allocationDesc,1750&resourceDesc,1751D3D12_RESOURCE_STATE_COPY_DEST,1752NULL,1753&allocation,1754IID_PPV_ARGS(&resource));17551756// Use resource...1757\endcode17581759In this case, returned pointer `resource` is equal to `allocation->GetResource()`,1760but the creation function additionally increases resource reference counter for the purpose of returning it from this call1761(it actually calls `QueryInterface` internally), so the resource will have the counter = 2.1762The resource then need to be released along with the allocation, in this particular order,1763to make sure the resource is destroyed before its memory heap can potentially be freed.17641765\code1766resource->Release();1767allocation->Release();1768\endcode17691770<b>More advanced use cases</b> are possible when we consider that an D3D12MA::Allocation object can just hold1771a reference to any resource.1772It can be changed by calling D3D12MA::Allocation::SetResource. This function1773releases the old resource and calls `AddRef` on the new one.17741775Special care must be taken when performing <b>defragmentation</b>.1776The new resource created at the destination place should be set as `pass.pMoves[i].pDstTmpAllocation->SetResource(newRes)`,1777but it is moved to the source allocation at end of the defragmentation pass,1778while the old resource accessible through `pass.pMoves[i].pSrcAllocation->GetResource()` is then released.1779For more information, see documentation chapter \ref defragmentation.178017811782\section quick_start_mapping_memory Mapping memory17831784The process of getting regular CPU-side pointer to the memory of a resource in1785Direct3D is called "mapping". There are rules and restrictions to this process,1786as described in D3D12 documentation of `ID3D12Resource::Map` method.17871788Mapping happens on the level of particular resources, not entire memory heaps,1789and so it is out of scope of this library. Just as the documentation of the `Map` function says:17901791- Returned pointer refers to data of particular subresource, not entire memory heap.1792- You can map same resource multiple times. It is ref-counted internally.1793- Mapping is thread-safe.1794- Unmapping is not required before resource destruction.1795- Unmapping may not be required before using written data - some heap types on1796some platforms support resources persistently mapped.17971798When using this library, you can map and use your resources normally without1799considering whether they are created as committed resources or placed resources in one large heap.18001801Example for buffer created and filled in `UPLOAD` heap type:18021803\code1804const UINT64 bufSize = 65536;1805const float* bufData = (...);18061807D3D12_RESOURCE_DESC resourceDesc = {};1808resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;1809resourceDesc.Alignment = 0;1810resourceDesc.Width = bufSize;1811resourceDesc.Height = 1;1812resourceDesc.DepthOrArraySize = 1;1813resourceDesc.MipLevels = 1;1814resourceDesc.Format = DXGI_FORMAT_UNKNOWN;1815resourceDesc.SampleDesc.Count = 1;1816resourceDesc.SampleDesc.Quality = 0;1817resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;1818resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;18191820D3D12MA::ALLOCATION_DESC allocationDesc = {};1821allocationDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;18221823D3D12Resource* resource;1824D3D12MA::Allocation* allocation;1825HRESULT hr = allocator->CreateResource(1826&allocationDesc,1827&resourceDesc,1828D3D12_RESOURCE_STATE_GENERIC_READ,1829NULL,1830&allocation,1831IID_PPV_ARGS(&resource));18321833void* mappedPtr;1834hr = resource->Map(0, NULL, &mappedPtr);18351836memcpy(mappedPtr, bufData, bufSize);18371838resource->Unmap(0, NULL);1839\endcode184018411842\page custom_pools Custom memory pools18431844A "pool" is a collection of memory blocks that share certain properties.1845Allocator creates 3 default pools: for `D3D12_HEAP_TYPE_DEFAULT`, `UPLOAD`, `READBACK`.1846A default pool automatically grows in size. Size of allocated blocks is also variable and managed automatically.1847Typical allocations are created in these pools. You can also create custom pools.18481849\section custom_pools_usage Usage18501851To create a custom pool, fill in structure D3D12MA::POOL_DESC and call function D3D12MA::Allocator::CreatePool1852to obtain object D3D12MA::Pool. Example:18531854\code1855POOL_DESC poolDesc = {};1856poolDesc.HeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;18571858Pool* pool;1859HRESULT hr = allocator->CreatePool(&poolDesc, &pool);1860\endcode18611862To allocate resources out of a custom pool, only set member D3D12MA::ALLOCATION_DESC::CustomPool.1863Example:18641865\code1866ALLOCATION_DESC allocDesc = {};1867allocDesc.CustomPool = pool;18681869D3D12_RESOURCE_DESC resDesc = ...1870Allocation* alloc;1871hr = allocator->CreateResource(&allocDesc, &resDesc,1872D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &alloc, IID_NULL, NULL);1873\endcode18741875All allocations must be released before releasing the pool.1876The pool must be released before relasing the allocator.18771878\code1879alloc->Release();1880pool->Release();1881\endcode18821883\section custom_pools_features_and_benefits Features and benefits18841885While it is recommended to use default pools whenever possible for simplicity and to give the allocator1886more opportunities for internal optimizations, custom pools may be useful in following cases:18871888- To keep some resources separate from others in memory.1889- To keep track of memory usage of just a specific group of resources. %Statistics can be queried using1890D3D12MA::Pool::CalculateStatistics.1891- To use specific size of a memory block (`ID3D12Heap`). To set it, use member D3D12MA::POOL_DESC::BlockSize.1892When set to 0, the library uses automatically determined, variable block sizes.1893- To reserve some minimum amount of memory allocated. To use it, set member D3D12MA::POOL_DESC::MinBlockCount.1894- To limit maximum amount of memory allocated. To use it, set member D3D12MA::POOL_DESC::MaxBlockCount.1895- To use extended parameters of the D3D12 memory allocation. While resources created from default pools1896can only specify `D3D12_HEAP_TYPE_DEFAULT`, `UPLOAD`, `READBACK`, a custom pool may use non-standard1897`D3D12_HEAP_PROPERTIES` (member D3D12MA::POOL_DESC::HeapProperties) and `D3D12_HEAP_FLAGS`1898(D3D12MA::POOL_DESC::HeapFlags), which is useful e.g. for cross-adapter sharing or UMA1899(see also D3D12MA::Allocator::IsUMA).19001901New versions of this library support creating **committed allocations in custom pools**.1902It is supported only when D3D12MA::POOL_DESC::BlockSize = 0.1903To use this feature, set D3D12MA::ALLOCATION_DESC::CustomPool to the pointer to your custom pool and1904D3D12MA::ALLOCATION_DESC::Flags to D3D12MA::ALLOCATION_FLAG_COMMITTED. Example:19051906\code1907ALLOCATION_DESC allocDesc = {};1908allocDesc.CustomPool = pool;1909allocDesc.Flags = ALLOCATION_FLAG_COMMITTED;19101911D3D12_RESOURCE_DESC resDesc = ...1912Allocation* alloc;1913ID3D12Resource* res;1914hr = allocator->CreateResource(&allocDesc, &resDesc,1915D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &alloc, IID_PPV_ARGS(&res));1916\endcode19171918This feature may seem unnecessary, but creating committed allocations from custom pools may be useful1919in some cases, e.g. to have separate memory usage statistics for some group of resources or to use1920extended allocation parameters, like custom `D3D12_HEAP_PROPERTIES`, which are available only in custom pools.192119221923\page defragmentation Defragmentation19241925Interleaved allocations and deallocations of many objects of varying size can1926cause fragmentation over time, which can lead to a situation where the library is unable1927to find a continuous range of free memory for a new allocation despite there is1928enough free space, just scattered across many small free ranges between existing1929allocations.19301931To mitigate this problem, you can use defragmentation feature.1932It doesn't happen automatically though and needs your cooperation,1933because %D3D12MA is a low level library that only allocates memory.1934It cannot recreate buffers and textures in a new place as it doesn't remember the contents of `D3D12_RESOURCE_DESC` structure.1935It cannot copy their contents as it doesn't record any commands to a command list.19361937Example:19381939\code1940D3D12MA::DEFRAGMENTATION_DESC defragDesc = {};1941defragDesc.Flags = D3D12MA::DEFRAGMENTATION_FLAG_ALGORITHM_FAST;19421943D3D12MA::DefragmentationContext* defragCtx;1944allocator->BeginDefragmentation(&defragDesc, &defragCtx);19451946for(;;)1947{1948D3D12MA::DEFRAGMENTATION_PASS_MOVE_INFO pass;1949HRESULT hr = defragCtx->BeginPass(&pass);1950if(hr == S_OK)1951break;1952else if(hr != S_FALSE)1953// Handle error...19541955for(UINT i = 0; i < pass.MoveCount; ++i)1956{1957// Inspect pass.pMoves[i].pSrcAllocation, identify what buffer/texture it represents.1958MyEngineResourceData* resData = (MyEngineResourceData*)pMoves[i].pSrcAllocation->GetPrivateData();19591960// Recreate this buffer/texture as placed at pass.pMoves[i].pDstTmpAllocation.1961D3D12_RESOURCE_DESC resDesc = ...1962ID3D12Resource* newRes;1963hr = device->CreatePlacedResource(1964pass.pMoves[i].pDstTmpAllocation->GetHeap(),1965pass.pMoves[i].pDstTmpAllocation->GetOffset(), &resDesc,1966D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&newRes));1967// Check hr...19681969// Store new resource in the pDstTmpAllocation.1970pass.pMoves[i].pDstTmpAllocation->SetResource(newRes);19711972// Copy its content to the new place.1973cmdList->CopyResource(1974pass.pMoves[i].pDstTmpAllocation->GetResource(),1975pass.pMoves[i].pSrcAllocation->GetResource());1976}19771978// Make sure the copy commands finished executing.1979cmdQueue->ExecuteCommandLists(...);1980// ...1981WaitForSingleObject(fenceEvent, INFINITE);19821983// Update appropriate descriptors to point to the new places...19841985hr = defragCtx->EndPass(&pass);1986if(hr == S_OK)1987break;1988else if(hr != S_FALSE)1989// Handle error...1990}19911992defragCtx->Release();1993\endcode19941995Although functions like D3D12MA::Allocator::CreateResource()1996create an allocation and a buffer/texture at once, these are just a shortcut for1997allocating memory and creating a placed resource.1998Defragmentation works on memory allocations only. You must handle the rest manually.1999Defragmentation is an iterative process that should repreat "passes" as long as related functions2000return `S_FALSE` not `S_OK`.2001In each pass:200220031. D3D12MA::DefragmentationContext::BeginPass() function call:2004- Calculates and returns the list of allocations to be moved in this pass.2005Note this can be a time-consuming process.2006- Reserves destination memory for them by creating temporary destination allocations2007that you can query for their `ID3D12Heap` + offset using methods like D3D12MA::Allocation::GetHeap().20082. Inside the pass, **you should**:2009- Inspect the returned list of allocations to be moved.2010- Create new buffers/textures as placed at the returned destination temporary allocations.2011- Copy data from source to destination resources if necessary.2012- Store the pointer to the new resource in the temporary destination allocation.20133. D3D12MA::DefragmentationContext::EndPass() function call:2014- Frees the source memory reserved for the allocations that are moved.2015- Modifies source D3D12MA::Allocation objects that are moved to point to the destination reserved memory2016and destination resource, while source resource is released.2017- Frees `ID3D12Heap` blocks that became empty.20182019Defragmentation algorithm tries to move all suitable allocations.2020You can, however, refuse to move some of them inside a defragmentation pass, by setting2021`pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.2022This is not recommended and may result in suboptimal packing of the allocations after defragmentation.2023If you cannot ensure any allocation can be moved, it is better to keep movable allocations separate in a custom pool.20242025Inside a pass, for each allocation that should be moved:20262027- You should copy its data from the source to the destination place by calling e.g. `CopyResource()`.2028- You need to make sure these commands finished executing before the source buffers/textures are released by D3D12MA::DefragmentationContext::EndPass().2029- If a resource doesn't contain any meaningful data, e.g. it is a transient render-target texture to be cleared,2030filled, and used temporarily in each rendering frame, you can just recreate this texture2031without copying its data.2032- If the resource is in `D3D12_HEAP_TYPE_READBACK` memory, you can copy its data on the CPU2033using `memcpy()`.2034- If you cannot move the allocation, you can set `pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.2035This will cancel the move.2036- D3D12MA::DefragmentationContext::EndPass() will then free the destination memory2037not the source memory of the allocation, leaving it unchanged.2038- If you decide the allocation is unimportant and can be destroyed instead of moved (e.g. it wasn't used for long time),2039you can set `pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY.2040- D3D12MA::DefragmentationContext::EndPass() will then free both source and destination memory, and will destroy the source D3D12MA::Allocation object.20412042You can defragment a specific custom pool by calling D3D12MA::Pool::BeginDefragmentation2043or all the default pools by calling D3D12MA::Allocator::BeginDefragmentation (like in the example above).20442045Defragmentation is always performed in each pool separately.2046Allocations are never moved between different heap types.2047The size of the destination memory reserved for a moved allocation is the same as the original one.2048Alignment of an allocation as it was determined using `GetResourceAllocationInfo()` is also respected after defragmentation.2049Buffers/textures should be recreated with the same `D3D12_RESOURCE_DESC` parameters as the original ones.20502051You can perform the defragmentation incrementally to limit the number of allocations and bytes to be moved2052in each pass, e.g. to call it in sync with render frames and not to experience too big hitches.2053See members: D3D12MA::DEFRAGMENTATION_DESC::MaxBytesPerPass, D3D12MA::DEFRAGMENTATION_DESC::MaxAllocationsPerPass.20542055<b>Thread safety:</b>2056It is safe to perform the defragmentation asynchronously to render frames and other Direct3D 12 and %D3D12MA2057usage, possibly from multiple threads, with the exception that allocations2058returned in D3D12MA::DEFRAGMENTATION_PASS_MOVE_INFO::pMoves shouldn't be released until the defragmentation pass is ended.2059During the call to D3D12MA::DefragmentationContext::BeginPass(), any operations on the memory pool2060affected by the defragmentation are blocked by a mutex.20612062What it means in practice is that you shouldn't free any allocations from the defragmented pool2063since the moment a call to `BeginPass` begins. Otherwise, a thread performing the `allocation->Release()`2064would block for the time `BeginPass` executes and then free the allocation when it finishes, while the allocation2065could have ended up on the list of allocations to move.2066A solution to freeing allocations during defragmentation is to find such allocation on the list2067`pass.pMoves[i]` and set its operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY instead of2068calling `allocation->Release()`, or simply deferring the release to the time after defragmentation finished.20692070<b>Mapping</b> is out of scope of this library and so it is not preserved after an allocation is moved during defragmentation.2071You need to map the new resource yourself if needed.20722073\note Defragmentation is not supported in custom pools created with D3D12MA::POOL_FLAG_ALGORITHM_LINEAR.207420752076\page statistics Statistics20772078This library contains several functions that return information about its internal state,2079especially the amount of memory allocated from D3D12.20802081\section statistics_numeric_statistics Numeric statistics20822083If you need to obtain basic statistics about memory usage per memory segment group, together with current budget,2084you can call function D3D12MA::Allocator::GetBudget() and inspect structure D3D12MA::Budget.2085This is useful to keep track of memory usage and stay withing budget.2086Example:20872088\code2089D3D12MA::Budget localBudget;2090allocator->GetBudget(&localBudget, NULL);20912092printf("My GPU memory currently has %u allocations taking %llu B,\n",2093localBudget.Statistics.AllocationCount,2094localBudget.Statistics.AllocationBytes);2095printf("allocated out of %u D3D12 memory heaps taking %llu B,\n",2096localBudget.Statistics.BlockCount,2097localBudget.Statistics.BlockBytes);2098printf("D3D12 reports total usage %llu B with budget %llu B.\n",2099localBudget.UsageBytes,2100localBudget.BudgetBytes);2101\endcode21022103You can query for more detailed statistics per heap type, memory segment group, and totals,2104including minimum and maximum allocation size and unused range size,2105by calling function D3D12MA::Allocator::CalculateStatistics() and inspecting structure D3D12MA::TotalStatistics.2106This function is slower though, as it has to traverse all the internal data structures,2107so it should be used only for debugging purposes.21082109You can query for statistics of a custom pool using function D3D12MA::Pool::GetStatistics()2110or D3D12MA::Pool::CalculateStatistics().21112112You can query for information about a specific allocation using functions of the D3D12MA::Allocation class,2113e.g. `GetSize()`, `GetOffset()`, `GetHeap()`.21142115\section statistics_json_dump JSON dump21162117You can dump internal state of the allocator to a string in JSON format using function D3D12MA::Allocator::BuildStatsString().2118The result is guaranteed to be correct JSON.2119It uses Windows Unicode (UTF-16) encoding.2120Any strings provided by user (see D3D12MA::Allocation::SetName())2121are copied as-is and properly escaped for JSON.2122It must be freed using function D3D12MA::Allocator::FreeStatsString().21232124The format of this JSON string is not part of official documentation of the library,2125but it will not change in backward-incompatible way without increasing library major version number2126and appropriate mention in changelog.21272128The JSON string contains all the data that can be obtained using D3D12MA::Allocator::CalculateStatistics().2129It can also contain detailed map of allocated memory blocks and their regions -2130free and occupied by allocations.2131This allows e.g. to visualize the memory or assess fragmentation.213221332134\page resource_aliasing Resource aliasing (overlap)21352136New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory2137management, give an opportunity to alias (overlap) multiple resources in the2138same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL).2139It can be useful to save video memory, but it must be used with caution.21402141For example, if you know the flow of your whole render frame in advance, you2142are going to use some intermediate textures or buffers only during a small range of render passes,2143and you know these ranges don't overlap in time, you can create these resources in2144the same place in memory, even if they have completely different parameters (width, height, format etc.).2145214621472148Such scenario is possible using D3D12MA, but you need to create your resources2149using special function D3D12MA::Allocator::CreateAliasingResource.2150Before that, you need to allocate memory with parameters calculated using formula:21512152- allocation size = max(size of each resource)2153- allocation alignment = max(alignment of each resource)21542155Following example shows two different textures created in the same place in memory,2156allocated to fit largest of them.21572158\code2159D3D12_RESOURCE_DESC resDesc1 = {};2160resDesc1.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;2161resDesc1.Alignment = 0;2162resDesc1.Width = 1920;2163resDesc1.Height = 1080;2164resDesc1.DepthOrArraySize = 1;2165resDesc1.MipLevels = 1;2166resDesc1.Format = DXGI_FORMAT_R8G8B8A8_UNORM;2167resDesc1.SampleDesc.Count = 1;2168resDesc1.SampleDesc.Quality = 0;2169resDesc1.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;2170resDesc1.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;21712172D3D12_RESOURCE_DESC resDesc2 = {};2173resDesc2.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;2174resDesc2.Alignment = 0;2175resDesc2.Width = 1024;2176resDesc2.Height = 1024;2177resDesc2.DepthOrArraySize = 1;2178resDesc2.MipLevels = 0;2179resDesc2.Format = DXGI_FORMAT_R8G8B8A8_UNORM;2180resDesc2.SampleDesc.Count = 1;2181resDesc2.SampleDesc.Quality = 0;2182resDesc2.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;2183resDesc2.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;21842185const D3D12_RESOURCE_ALLOCATION_INFO allocInfo1 =2186device->GetResourceAllocationInfo(0, 1, &resDesc1);2187const D3D12_RESOURCE_ALLOCATION_INFO allocInfo2 =2188device->GetResourceAllocationInfo(0, 1, &resDesc2);21892190D3D12_RESOURCE_ALLOCATION_INFO finalAllocInfo = {};2191finalAllocInfo.Alignment = std::max(allocInfo1.Alignment, allocInfo2.Alignment);2192finalAllocInfo.SizeInBytes = std::max(allocInfo1.SizeInBytes, allocInfo2.SizeInBytes);21932194D3D12MA::ALLOCATION_DESC allocDesc = {};2195allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;2196allocDesc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;21972198D3D12MA::Allocation* alloc;2199hr = allocator->AllocateMemory(&allocDesc, &finalAllocInfo, &alloc);2200assert(alloc != NULL && alloc->GetHeap() != NULL);22012202ID3D12Resource* res1;2203hr = allocator->CreateAliasingResource(2204alloc,22050, // AllocationLocalOffset2206&resDesc1,2207D3D12_RESOURCE_STATE_COMMON,2208NULL, // pOptimizedClearValue2209IID_PPV_ARGS(&res1));22102211ID3D12Resource* res2;2212hr = allocator->CreateAliasingResource(2213alloc,22140, // AllocationLocalOffset2215&resDesc2,2216D3D12_RESOURCE_STATE_COMMON,2217NULL, // pOptimizedClearValue2218IID_PPV_ARGS(&res2));22192220// You can use res1 and res2, but not at the same time!22212222res2->Release();2223res1->Release();2224alloc->Release();2225\endcode22262227Remember that using resouces that alias in memory requires proper synchronization.2228You need to issue a special barrier of type `D3D12_RESOURCE_BARRIER_TYPE_ALIASING`.2229You also need to treat a resource after aliasing as uninitialized - containing garbage data.2230For example, if you use `res1` and then want to use `res2`, you need to first initialize `res2`2231using either Clear, Discard, or Copy to the entire resource.22322233Additional considerations:22342235- D3D12 also allows to interpret contents of memory between aliasing resources consistently in some cases,2236which is called "data inheritance". For details, see2237Microsoft documentation chapter "Memory Aliasing and Data Inheritance".2238- You can create more complex layout where different textures and buffers are bound2239at different offsets inside one large allocation. For example, one can imagine2240a big texture used in some render passes, aliasing with a set of many small buffers2241used in some further passes. To bind a resource at non-zero offset of an allocation,2242call D3D12MA::Allocator::CreateAliasingResource with appropriate value of `AllocationLocalOffset` parameter.2243- Resources of the three categories: buffers, textures with `RENDER_TARGET` or `DEPTH_STENCIL` flags, and all other textures,2244can be placed in the same memory only when `allocator->GetD3D12Options().ResourceHeapTier >= D3D12_RESOURCE_HEAP_TIER_2`.2245Otherwise they must be placed in different memory heap types, and thus aliasing them is not possible.224622472248\page linear_algorithm Linear allocation algorithm22492250Each D3D12 memory block managed by this library has accompanying metadata that2251keeps track of used and unused regions. By default, the metadata structure and2252algorithm tries to find best place for new allocations among free regions to2253optimize memory usage. This way you can allocate and free objects in any order.2254225522562257Sometimes there is a need to use simpler, linear allocation algorithm. You can2258create custom pool that uses such algorithm by adding flag2259D3D12MA::POOL_FLAG_ALGORITHM_LINEAR to D3D12MA::POOL_DESC::Flags while creating2260D3D12MA::Pool object. Then an alternative metadata management is used. It always2261creates new allocations after last one and doesn't reuse free regions after2262allocations freed in the middle. It results in better allocation performance and2263less memory consumed by metadata.2264226522662267With this one flag, you can create a custom pool that can be used in many ways:2268free-at-once, stack, double stack, and ring buffer. See below for details.2269You don't need to specify explicitly which of these options you are going to use - it is detected automatically.22702271\section linear_algorithm_free_at_once Free-at-once22722273In a pool that uses linear algorithm, you still need to free all the allocations2274individually by calling `allocation->Release()`. You can free2275them in any order. New allocations are always made after last one - free space2276in the middle is not reused. However, when you release all the allocation and2277the pool becomes empty, allocation starts from the beginning again. This way you2278can use linear algorithm to speed up creation of allocations that you are going2279to release all at once.2280228122822283This mode is also available for pools created with D3D12MA::POOL_DESC::MaxBlockCount2284value that allows multiple memory blocks.22852286\section linear_algorithm_stack Stack22872288When you free an allocation that was created last, its space can be reused.2289Thanks to this, if you always release allocations in the order opposite to their2290creation (LIFO - Last In First Out), you can achieve behavior of a stack.2291229222932294This mode is also available for pools created with D3D12MA::POOL_DESC::MaxBlockCount2295value that allows multiple memory blocks.22962297\section linear_algorithm_double_stack Double stack22982299The space reserved by a custom pool with linear algorithm may be used by two2300stacks:23012302- First, default one, growing up from offset 0.2303- Second, "upper" one, growing down from the end towards lower offsets.23042305To make allocation from the upper stack, add flag D3D12MA::ALLOCATION_FLAG_UPPER_ADDRESS2306to D3D12MA::ALLOCATION_DESC::Flags.2307230823092310Double stack is available only in pools with one memory block -2311D3D12MA::POOL_DESC::MaxBlockCount must be 1. Otherwise behavior is undefined.23122313When the two stacks' ends meet so there is not enough space between them for a2314new allocation, such allocation fails with usual `E_OUTOFMEMORY` error.23152316\section linear_algorithm_ring_buffer Ring buffer23172318When you free some allocations from the beginning and there is not enough free space2319for a new one at the end of a pool, allocator's "cursor" wraps around to the2320beginning and starts allocation there. Thanks to this, if you always release2321allocations in the same order as you created them (FIFO - First In First Out),2322you can achieve behavior of a ring buffer / queue.2323232423252326Ring buffer is available only in pools with one memory block -2327D3D12MA::POOL_DESC::MaxBlockCount must be 1. Otherwise behavior is undefined.23282329\section linear_algorithm_additional_considerations Additional considerations23302331Linear algorithm can also be used with \ref virtual_allocator.2332See flag D3D12MA::VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR.233323342335\page virtual_allocator Virtual allocator23362337As an extra feature, the core allocation algorithm of the library is exposed through a simple and convenient API of "virtual allocator".2338It doesn't allocate any real GPU memory. It just keeps track of used and free regions of a "virtual block".2339You can use it to allocate your own memory or other objects, even completely unrelated to D3D12.2340A common use case is sub-allocation of pieces of one large GPU buffer.23412342\section virtual_allocator_creating_virtual_block Creating virtual block23432344To use this functionality, there is no main "allocator" object.2345You don't need to have D3D12MA::Allocator object created.2346All you need to do is to create a separate D3D12MA::VirtualBlock object for each block of memory you want to be managed by the allocator:23472348-# Fill in D3D12MA::ALLOCATOR_DESC structure.2349-# Call D3D12MA::CreateVirtualBlock. Get new D3D12MA::VirtualBlock object.23502351Example:23522353\code2354D3D12MA::VIRTUAL_BLOCK_DESC blockDesc = {};2355blockDesc.Size = 1048576; // 1 MB23562357D3D12MA::VirtualBlock *block;2358HRESULT hr = CreateVirtualBlock(&blockDesc, &block);2359\endcode23602361\section virtual_allocator_making_virtual_allocations Making virtual allocations23622363D3D12MA::VirtualBlock object contains internal data structure that keeps track of free and occupied regions2364using the same code as the main D3D12 memory allocator.2365A single allocation is identified by a lightweight structure D3D12MA::VirtualAllocation.2366You will also likely want to know the offset at which the allocation was made in the block.23672368In order to make an allocation:23692370-# Fill in D3D12MA::VIRTUAL_ALLOCATION_DESC structure.2371-# Call D3D12MA::VirtualBlock::Allocate. Get new D3D12MA::VirtualAllocation value that identifies the allocation.23722373Example:23742375\code2376D3D12MA::VIRTUAL_ALLOCATION_DESC allocDesc = {};2377allocDesc.Size = 4096; // 4 KB23782379D3D12MA::VirtualAllocation alloc;2380UINT64 allocOffset;2381hr = block->Allocate(&allocDesc, &alloc, &allocOffset);2382if(SUCCEEDED(hr))2383{2384// Use the 4 KB of your memory starting at allocOffset.2385}2386else2387{2388// Allocation failed - no space for it could be found. Handle this error!2389}2390\endcode23912392\section virtual_allocator_deallocation Deallocation23932394When no longer needed, an allocation can be freed by calling D3D12MA::VirtualBlock::FreeAllocation.23952396When whole block is no longer needed, the block object can be released by calling `block->Release()`.2397All allocations must be freed before the block is destroyed, which is checked internally by an assert.2398However, if you don't want to call `block->FreeAllocation` for each allocation, you can use D3D12MA::VirtualBlock::Clear to free them all at once -2399a feature not available in normal D3D12 memory allocator.24002401Example:24022403\code2404block->FreeAllocation(alloc);2405block->Release();2406\endcode24072408\section virtual_allocator_allocation_parameters Allocation parameters24092410You can attach a custom pointer to each allocation by using D3D12MA::VirtualBlock::SetAllocationPrivateData.2411Its default value is `NULL`.2412It can be used to store any data that needs to be associated with that allocation - e.g. an index, a handle, or a pointer to some2413larger data structure containing more information. Example:24142415\code2416struct CustomAllocData2417{2418std::string m_AllocName;2419};2420CustomAllocData* allocData = new CustomAllocData();2421allocData->m_AllocName = "My allocation 1";2422block->SetAllocationPrivateData(alloc, allocData);2423\endcode24242425The pointer can later be fetched, along with allocation offset and size, by passing the allocation handle to function2426D3D12MA::VirtualBlock::GetAllocationInfo and inspecting returned structure D3D12MA::VIRTUAL_ALLOCATION_INFO.2427If you allocated a new object to be used as the custom pointer, don't forget to delete that object before freeing the allocation!2428Example:24292430\code2431VIRTUAL_ALLOCATION_INFO allocInfo;2432block->GetAllocationInfo(alloc, &allocInfo);2433delete (CustomAllocData*)allocInfo.pPrivateData;24342435block->FreeAllocation(alloc);2436\endcode24372438\section virtual_allocator_alignment_and_units Alignment and units24392440It feels natural to express sizes and offsets in bytes.2441If an offset of an allocation needs to be aligned to a multiply of some number (e.g. 4 bytes), you can fill optional member2442D3D12MA::VIRTUAL_ALLOCATION_DESC::Alignment to request it. Example:24432444\code2445D3D12MA::VIRTUAL_ALLOCATION_DESC allocDesc = {};2446allocDesc.Size = 4096; // 4 KB2447allocDesc.Alignment = 4; // Returned offset must be a multiply of 4 B24482449D3D12MA::VirtualAllocation alloc;2450UINT64 allocOffset;2451hr = block->Allocate(&allocDesc, &alloc, &allocOffset);2452\endcode24532454Alignments of different allocations made from one block may vary.2455However, if all alignments and sizes are always multiply of some size e.g. 4 B or `sizeof(MyDataStruct)`,2456you can express all sizes, alignments, and offsets in multiples of that size instead of individual bytes.2457It might be more convenient, but you need to make sure to use this new unit consistently in all the places:24582459- D3D12MA::VIRTUAL_BLOCK_DESC::Size2460- D3D12MA::VIRTUAL_ALLOCATION_DESC::Size and D3D12MA::VIRTUAL_ALLOCATION_DESC::Alignment2461- Using offset returned by D3D12MA::VirtualBlock::Allocate and D3D12MA::VIRTUAL_ALLOCATION_INFO::Offset24622463\section virtual_allocator_statistics Statistics24642465You can obtain brief statistics of a virtual block using D3D12MA::VirtualBlock::GetStatistics().2466The function fills structure D3D12MA::Statistics - same as used by the normal D3D12 memory allocator.2467Example:24682469\code2470D3D12MA::Statistics stats;2471block->GetStatistics(&stats);2472printf("My virtual block has %llu bytes used by %u virtual allocations\n",2473stats.AllocationBytes, stats.AllocationCount);2474\endcode24752476More detailed statistics can be obtained using function D3D12MA::VirtualBlock::CalculateStatistics(),2477but they are slower to calculate.24782479You can also request a full list of allocations and free regions as a string in JSON format by calling2480D3D12MA::VirtualBlock::BuildStatsString.2481Returned string must be later freed using D3D12MA::VirtualBlock::FreeStatsString.2482The format of this string may differ from the one returned by the main D3D12 allocator, but it is similar.24832484\section virtual_allocator_additional_considerations Additional considerations24852486Alternative, linear algorithm can be used with virtual allocator - see flag2487D3D12MA::VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR and documentation: \ref linear_algorithm.24882489Note that the "virtual allocator" functionality is implemented on a level of individual memory blocks.2490Keeping track of a whole collection of blocks, allocating new ones when out of free space,2491deleting empty ones, and deciding which one to try first for a new allocation must be implemented by the user.249224932494\page configuration Configuration24952496Please check file `D3D12MemAlloc.cpp` lines between "Configuration Begin" and2497"Configuration End" to find macros that you can define to change the behavior of2498the library, primarily for debugging purposes.24992500\section custom_memory_allocator Custom CPU memory allocator25012502If you use custom allocator for CPU memory rather than default C++ operator `new`2503and `delete` or `malloc` and `free` functions, you can make this library using2504your allocator as well by filling structure D3D12MA::ALLOCATION_CALLBACKS and2505passing it as optional member D3D12MA::ALLOCATOR_DESC::pAllocationCallbacks.2506Functions pointed there will be used by the library to make any CPU-side2507allocations. Example:25082509\code2510#include <malloc.h>25112512void* CustomAllocate(size_t Size, size_t Alignment, void* pPrivateData)2513{2514void* memory = _aligned_malloc(Size, Alignment);2515// Your extra bookkeeping here...2516return memory;2517}25182519void CustomFree(void* pMemory, void* pPrivateData)2520{2521// Your extra bookkeeping here...2522_aligned_free(pMemory);2523}25242525(...)25262527D3D12MA::ALLOCATION_CALLBACKS allocationCallbacks = {};2528allocationCallbacks.pAllocate = &CustomAllocate;2529allocationCallbacks.pFree = &CustomFree;25302531D3D12MA::ALLOCATOR_DESC allocatorDesc = {};2532allocatorDesc.pDevice = device;2533allocatorDesc.pAdapter = adapter;2534allocatorDesc.pAllocationCallbacks = &allocationCallbacks;25352536D3D12MA::Allocator* allocator;2537HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);2538\endcode253925402541\section debug_margins Debug margins25422543By default, allocations are laid out in memory blocks next to each other if possible2544(considering required alignment returned by `ID3D12Device::GetResourceAllocationInfo`).2545254625472548Define macro `D3D12MA_DEBUG_MARGIN` to some non-zero value (e.g. 16) inside "D3D12MemAlloc.cpp"2549to enforce specified number of bytes as a margin after every allocation.2550255125522553If your bug goes away after enabling margins, it means it may be caused by memory2554being overwritten outside of allocation boundaries. It is not 100% certain though.2555Change in application behavior may also be caused by different order and distribution2556of allocations across memory blocks after margins are applied.25572558Margins work with all memory heap types.25592560Margin is applied only to placed allocations made out of memory heaps and not to committed2561allocations, which have their own, implicit memory heap of specific size.2562It is thus not applied to allocations made using D3D12MA::ALLOCATION_FLAG_COMMITTED flag2563or those automatically decided to put into committed allocations, e.g. due to its large size.25642565Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.25662567Note that enabling margins increases memory usage and fragmentation.25682569Margins do not apply to \ref virtual_allocator.257025712572\page general_considerations General considerations25732574\section general_considerations_thread_safety Thread safety25752576- The library has no global state, so separate D3D12MA::Allocator objects can be used independently.2577In typical applications there should be no need to create multiple such objects though - one per `ID3D12Device` is enough.2578- All calls to methods of D3D12MA::Allocator class are safe to be made from multiple2579threads simultaneously because they are synchronized internally when needed.2580- When the allocator is created with D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED,2581calls to methods of D3D12MA::Allocator class must be made from a single thread or synchronized by the user.2582Using this flag may improve performance.2583- D3D12MA::VirtualBlock is not safe to be used from multiple threads simultaneously.25842585\section general_considerations_versioning_and_compatibility Versioning and compatibility25862587The library uses [**Semantic Versioning**](https://semver.org/),2588which means version numbers follow convention: Major.Minor.Patch (e.g. 2.3.0), where:25892590- Incremented Patch version means a release is backward- and forward-compatible,2591introducing only some internal improvements, bug fixes, optimizations etc.2592or changes that are out of scope of the official API described in this documentation.2593- Incremented Minor version means a release is backward-compatible,2594so existing code that uses the library should continue to work, while some new2595symbols could have been added: new structures, functions, new values in existing2596enums and bit flags, new structure members, but not new function parameters.2597- Incrementing Major version means a release could break some backward compatibility.25982599All changes between official releases are documented in file "CHANGELOG.md".26002601\warning Backward compatiblity is considered on the level of C++ source code, not binary linkage.2602Adding new members to existing structures is treated as backward compatible if initializing2603the new members to binary zero results in the old behavior.2604You should always fully initialize all library structures to zeros and not rely on their2605exact binary size.26062607\section general_considerations_features_not_supported Features not supported26082609Features deliberately excluded from the scope of this library:26102611- **Descriptor allocation.** Although also called "heaps", objects that represent2612descriptors are separate part of the D3D12 API from buffers and textures.2613You can still use \ref virtual_allocator to manage descriptors and their ranges inside a descriptor heap.2614- **Support for reserved (tiled) resources.** We don't recommend using them.2615- Support for `ID3D12Device::Evict` and `MakeResident`. We don't recommend using them.2616You can call them on the D3D12 objects manually.2617Plese keep in mind, however, that eviction happens on the level of entire `ID3D12Heap` memory blocks2618and not individual buffers or textures which may be placed inside them.2619- **Handling CPU memory allocation failures.** When dynamically creating small C++2620objects in CPU memory (not the GPU memory), allocation failures are not2621handled gracefully, because that would complicate code significantly and2622is usually not needed in desktop PC applications anyway.2623Success of an allocation is just checked with an assert.2624- **Code free of any compiler warnings.**2625There are many preprocessor macros that make some variables unused, function parameters unreferenced,2626or conditional expressions constant in some configurations.2627The code of this library should not be bigger or more complicated just to silence these warnings.2628It is recommended to disable such warnings instead.2629- This is a C++ library. **Bindings or ports to any other programming languages** are welcome as external projects but2630are not going to be included into this repository.2631*/263226332634