forked from GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathD3D12MemAlloc.h
1643 lines (1298 loc) · 66.4 KB
/
D3D12MemAlloc.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2019-2021 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
/** \mainpage D3D12 Memory Allocator
<b>Version 2.0.0-development</b> (2021-07-26)
Copyright (c) 2019-2021 Advanced Micro Devices, Inc. All rights reserved. \n
License: MIT
Documentation of all members: D3D12MemAlloc.h
\section main_table_of_contents Table of contents
- <b>User guide</b>
- \subpage quick_start
- [Project setup](@ref quick_start_project_setup)
- [Creating resources](@ref quick_start_creating_resources)
- [Mapping memory](@ref quick_start_mapping_memory)
- \subpage custom_pools
- \subpage resource_aliasing
- \subpage virtual_allocator
- \subpage configuration
- [Custom CPU memory allocator](@ref custom_memory_allocator)
- \subpage general_considerations
- [Thread safety](@ref general_considerations_thread_safety)
- [Future plans](@ref general_considerations_future_plans)
- [Features not supported](@ref general_considerations_features_not_supported)
\section main_see_also See also
- [Product page on GPUOpen](https://gpuopen.com/gaming-product/d3d12-memory-allocator/)
- [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator)
*/
// If using this library on a platform different than Windows PC or want to use different version of DXGI,
// you should include D3D12-compatible headers before this library on your own and define this macro.
#ifndef D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
#include <d3d12.h>
#include <dxgi1_4.h>
#endif
// Define this macro to 0 to disable usage of DXGI 1.4 (needed for IDXGIAdapter3 and query for memory budget).
#ifndef D3D12MA_DXGI_1_4
#ifdef __IDXGIAdapter3_INTERFACE_DEFINED__
#define D3D12MA_DXGI_1_4 1
#else
#define D3D12MA_DXGI_1_4 0
#endif
#endif
/*
When defined to value other than 0, the library will try to use
D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT or D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT
for created textures when possible, which can save memory because some small textures
may get their alignment 4K and their size a multiply of 4K instead of 64K.
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 0
Disables small texture alignment.
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 1
Enables conservative algorithm that will use small alignment only for some textures
that are surely known to support it.
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 2
Enables query for small alignment to D3D12 (based on Microsoft sample) which will
enable small alignment for more textures, but will also generate D3D Debug Layer
error #721 on call to ID3D12Device::GetResourceAllocationInfo, which you should just
ignore.
*/
#ifndef D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 1
#endif
/// \cond INTERNAL
#define D3D12MA_CLASS_NO_COPY(className) \
private: \
className(const className&) = delete; \
className(className&&) = delete; \
className& operator=(const className&) = delete; \
className& operator=(className&&) = delete;
// To be used with MAKE_HRESULT to define custom error codes.
#define FACILITY_D3D12MA 3542
/*
If providing your own implementation, you need to implement a subset of std::atomic.
*/
#if !defined(D3D12MA_ATOMIC_UINT32) || !defined(D3D12MA_ATOMIC_UINT64)
#include <atomic>
#endif
#ifndef D3D12MA_ATOMIC_UINT32
#define D3D12MA_ATOMIC_UINT32 std::atomic<UINT>
#endif
#ifndef D3D12MA_ATOMIC_UINT64
#define D3D12MA_ATOMIC_UINT64 std::atomic<UINT64>
#endif
namespace D3D12MA
{
class IUnknownImpl : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, _COM_Outptr_ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef();
virtual ULONG STDMETHODCALLTYPE Release();
protected:
virtual void ReleaseThis() { delete this; }
private:
D3D12MA_ATOMIC_UINT32 m_RefCount = 1;
};
} // namespace D3D12MA
/// \endcond
namespace D3D12MA
{
/// \cond INTERNAL
class AllocatorPimpl;
class PoolPimpl;
class NormalBlock;
class BlockVector;
class CommittedAllocationList;
class JsonWriter;
class VirtualBlockPimpl;
/// \endcond
class Pool;
class Allocator;
struct StatInfo;
/// Pointer to custom callback function that allocates CPU memory.
typedef void* (*ALLOCATE_FUNC_PTR)(size_t Size, size_t Alignment, void* pUserData);
/**
\brief Pointer to custom callback function that deallocates CPU memory.
`pMemory = null` should be accepted and ignored.
*/
typedef void (*FREE_FUNC_PTR)(void* pMemory, void* pUserData);
/// Custom callbacks to CPU memory allocation functions.
struct ALLOCATION_CALLBACKS
{
/// %Allocation function.
ALLOCATE_FUNC_PTR pAllocate;
/// Dellocation function.
FREE_FUNC_PTR pFree;
/// Custom data that will be passed to allocation and deallocation functions as `pUserData` parameter.
void* pUserData;
};
/// \brief Bit flags to be used with ALLOCATION_DESC::Flags.
typedef enum ALLOCATION_FLAGS
{
/// Zero
ALLOCATION_FLAG_NONE = 0,
/**
Set this flag if the allocation should have its own dedicated memory allocation (committed resource with implicit heap).
Use it for special, big resources, like fullscreen textures used as render targets.
*/
ALLOCATION_FLAG_COMMITTED = 0x1,
/**
Set this flag to only try to allocate from existing memory heaps and never create new such heap.
If new allocation cannot be placed in any of the existing heaps, allocation
fails with `E_OUTOFMEMORY` error.
You should not use D3D12MA::ALLOCATION_FLAG_COMMITTED and
D3D12MA::ALLOCATION_FLAG_NEVER_ALLOCATE at the same time. It makes no sense.
*/
ALLOCATION_FLAG_NEVER_ALLOCATE = 0x2,
/** Create allocation only if additional memory required for it, if any, won't exceed
memory budget. Otherwise return `E_OUTOFMEMORY`.
*/
ALLOCATION_FLAG_WITHIN_BUDGET = 0x4,
} ALLOCATION_FLAGS;
/// \brief Parameters of created D3D12MA::Allocation object. To be used with Allocator::CreateResource.
struct ALLOCATION_DESC
{
/// Flags.
ALLOCATION_FLAGS Flags;
/** \brief The type of memory heap where the new allocation should be placed.
It must be one of: `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`.
When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.
*/
D3D12_HEAP_TYPE HeapType;
/** \brief Additional heap flags to be used when allocating memory.
In most cases it can be 0.
- If you use D3D12MA::Allocator::CreateResource(), you don't need to care.
Necessary flag `D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`, `D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
or `D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES` is added automatically.
- If you use D3D12MA::Allocator::AllocateMemory(), you should specify one of those `ALLOW_ONLY` flags.
Except when you validate that D3D12MA::Allocator::GetD3D12Options()`.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1` -
then you can leave it 0.
- You can specify additional flags if needed. Then the memory will always be allocated as
separate block using `D3D12Device::CreateCommittedResource` or `CreateHeap`, not as part of an existing larget block.
When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.
*/
D3D12_HEAP_FLAGS ExtraHeapFlags;
/** \brief Custom pool to place the new resource in. Optional.
When not NULL, the resource will be created inside specified custom pool.
It will then never be created as committed.
*/
Pool* CustomPool;
};
/** \brief Represents single memory allocation.
It may be either implicit memory heap dedicated to a single resource or a
specific region of a bigger heap plus unique offset.
To create such object, fill structure D3D12MA::ALLOCATION_DESC and call function
Allocator::CreateResource.
The object remembers size and some other information.
To retrieve this information, use methods of this class.
The object also remembers `ID3D12Resource` and "owns" a reference to it,
so it calls `%Release()` on the resource when destroyed.
*/
class Allocation : public IUnknownImpl
{
public:
/** \brief Returns offset in bytes from the start of memory heap.
You usually don't need to use this offset. If you create a buffer or a texture together with the allocation using function
D3D12MA::Allocator::CreateResource, functions that operate on that resource refer to the beginning of the resource,
not entire memory heap.
If the Allocation represents committed resource with implicit heap, returns 0.
*/
UINT64 GetOffset() const;
/** \brief Returns size in bytes of the allocation.
- If you created a buffer or a texture together with the allocation using function D3D12MA::Allocator::CreateResource,
this is the size of the resource returned by `ID3D12Device::GetResourceAllocationInfo`.
- For allocations made out of bigger memory blocks, this also is the size of the memory region assigned exclusively to this allocation.
- For resources created as committed, this value may not be accurate. DirectX implementation may optimize memory usage internally
so that you may even observe regions of `ID3D12Resource::GetGPUVirtualAddress()` + Allocation::GetSize() to overlap in memory and still work correctly.
*/
UINT64 GetSize() const { return m_Size; }
/** \brief Returns D3D12 resource associated with this object.
Calling this method doesn't increment resource's reference counter.
*/
ID3D12Resource* GetResource() const { return m_Resource; }
/** \brief Returns memory heap that the resource is created in.
If the Allocation represents committed resource with implicit heap, returns NULL.
*/
ID3D12Heap* GetHeap() const;
/** \brief Associates a name with the allocation object. This name is for use in debug diagnostics and tools.
Internal copy of the string is made, so the memory pointed by the argument can be
changed of freed immediately after this call.
`Name` can be null.
*/
void SetName(LPCWSTR Name);
/** \brief Returns the name associated with the allocation object.
Returned string points to an internal copy.
If no name was associated with the allocation, returns null.
*/
LPCWSTR GetName() const { return m_Name; }
/** \brief Returns `TRUE` if the memory of the allocation was filled with zeros when the allocation was created.
Returns `TRUE` only if the allocator is sure that the entire memory where the
allocation was created was filled with zeros at the moment the allocation was made.
Returns `FALSE` if the memory could potentially contain garbage data.
If it's a render-target or depth-stencil texture, it then needs proper
initialization with `ClearRenderTargetView`, `ClearDepthStencilView`, `DiscardResource`,
or a copy operation, as described on page:
[ID3D12Device::CreatePlacedResource method - Notes on the required resource initialization](https://docs.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource#notes-on-the-required-resource-initialization).
Please note that rendering a fullscreen triangle or quad to the texture as
a render target is not a proper way of initialization!
See also articles:
["Coming to DirectX 12: More control over memory allocation"](https://devblogs.microsoft.com/directx/coming-to-directx-12-more-control-over-memory-allocation/),
["Initializing DX12 Textures After Allocation and Aliasing"](https://asawicki.info/news_1724_initializing_dx12_textures_after_allocation_and_aliasing).
*/
BOOL WasZeroInitialized() const { return m_PackedData.WasZeroInitialized(); }
protected:
virtual void ReleaseThis();
private:
friend class AllocatorPimpl;
friend class BlockVector;
friend class CommittedAllocationList;
friend class JsonWriter;
friend struct CommittedAllocationListItemTraits;
template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
template<typename T> friend class PoolAllocator;
enum Type
{
TYPE_COMMITTED,
TYPE_PLACED,
TYPE_HEAP,
TYPE_COUNT
};
AllocatorPimpl* m_Allocator;
UINT64 m_Size;
ID3D12Resource* m_Resource;
UINT m_CreationFrameIndex;
wchar_t* m_Name;
union
{
struct
{
CommittedAllocationList* list;
Allocation* prev;
Allocation* next;
} m_Committed;
struct
{
UINT64 offset;
NormalBlock* block;
} m_Placed;
struct
{
// Beginning must be compatible with m_Committed.
CommittedAllocationList* list;
Allocation* prev;
Allocation* next;
ID3D12Heap* heap;
} m_Heap;
};
struct PackedData
{
public:
PackedData() :
m_Type(0), m_ResourceDimension(0), m_ResourceFlags(0), m_TextureLayout(0), m_WasZeroInitialized(0) { }
Type GetType() const { return (Type)m_Type; }
D3D12_RESOURCE_DIMENSION GetResourceDimension() const { return (D3D12_RESOURCE_DIMENSION)m_ResourceDimension; }
D3D12_RESOURCE_FLAGS GetResourceFlags() const { return (D3D12_RESOURCE_FLAGS)m_ResourceFlags; }
D3D12_TEXTURE_LAYOUT GetTextureLayout() const { return (D3D12_TEXTURE_LAYOUT)m_TextureLayout; }
BOOL WasZeroInitialized() const { return (BOOL)m_WasZeroInitialized; }
void SetType(Type type);
void SetResourceDimension(D3D12_RESOURCE_DIMENSION resourceDimension);
void SetResourceFlags(D3D12_RESOURCE_FLAGS resourceFlags);
void SetTextureLayout(D3D12_TEXTURE_LAYOUT textureLayout);
void SetWasZeroInitialized(BOOL wasZeroInitialized) { m_WasZeroInitialized = wasZeroInitialized ? 1 : 0; }
private:
UINT m_Type : 2; // enum Type
UINT m_ResourceDimension : 3; // enum D3D12_RESOURCE_DIMENSION
UINT m_ResourceFlags : 24; // flags D3D12_RESOURCE_FLAGS
UINT m_TextureLayout : 9; // enum D3D12_TEXTURE_LAYOUT
UINT m_WasZeroInitialized : 1; // BOOL
} m_PackedData;
Allocation(AllocatorPimpl* allocator, UINT64 size, BOOL wasZeroInitialized);
~Allocation();
void InitCommitted(CommittedAllocationList* list);
void InitPlaced(UINT64 offset, UINT64 alignment, NormalBlock* block);
void InitHeap(CommittedAllocationList* list, ID3D12Heap* heap);
template<typename D3D12_RESOURCE_DESC_T>
void SetResource(ID3D12Resource* resource, const D3D12_RESOURCE_DESC_T* pResourceDesc);
void FreeName();
D3D12MA_CLASS_NO_COPY(Allocation)
};
/// \brief Parameters of created D3D12MA::Pool object. To be used with D3D12MA::Allocator::CreatePool.
struct POOL_DESC
{
/** \brief The parameters of memory heap where allocations of this pool should be placed.
In the simplest case, just fill it with zeros and set `Type` to one of: `D3D12_HEAP_TYPE_DEFAULT`,
`D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`. Additional parameters can be used e.g. to utilize UMA.
*/
D3D12_HEAP_PROPERTIES HeapProperties;
/** \brief Heap flags to be used when allocating heaps of this pool.
It should contain one of these values, depending on type of resources you are going to create in this heap:
`D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,
`D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
`D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.
Except if ResourceHeapTier = 2, then it may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.
You can specify additional flags if needed.
*/
D3D12_HEAP_FLAGS HeapFlags;
/** \brief Size of a single heap (memory block) to be allocated as part of this pool, in bytes. Optional.
Specify nonzero to set explicit, constant size of memory blocks used by this pool.
Leave 0 to use default and let the library manage block sizes automatically.
Then sizes of particular blocks may vary.
*/
UINT64 BlockSize;
/** \brief Minimum number of heaps (memory blocks) to be always allocated in this pool, even if they stay empty. Optional.
Set to 0 to have no preallocated blocks and allow the pool be completely empty.
*/
UINT MinBlockCount;
/** \brief Maximum number of heaps (memory blocks) that can be allocated in this pool. Optional.
Set to 0 to use default, which is `UINT64_MAX`, which means no limit.
Set to same value as D3D12MA::POOL_DESC::MinBlockCount to have fixed amount of memory allocated
throughout whole lifetime of this pool.
*/
UINT MaxBlockCount;
/** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.
Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.
*/
UINT64 MinAllocationAlignment;
};
/** \brief Custom memory pool
Represents a separate set of heaps (memory blocks) that can be used to create
D3D12MA::Allocation-s and resources in it. Usually there is no need to create custom
pools - creating resources in default pool is sufficient.
To create custom pool, fill D3D12MA::POOL_DESC and call D3D12MA::Allocator::CreatePool.
*/
class Pool : public IUnknownImpl
{
public:
/** \brief Returns copy of parameters of the pool.
These are the same parameters as passed to D3D12MA::Allocator::CreatePool.
*/
POOL_DESC GetDesc() const;
/** \brief Retrieves statistics from the current state of this pool.
*/
void CalculateStats(StatInfo* pStats);
/** \brief Associates a name with the pool. This name is for use in debug diagnostics and tools.
Internal copy of the string is made, so the memory pointed by the argument can be
changed of freed immediately after this call.
`Name` can be NULL.
*/
void SetName(LPCWSTR Name);
/** \brief Returns the name associated with the pool object.
Returned string points to an internal copy.
If no name was associated with the allocation, returns NULL.
*/
LPCWSTR GetName() const;
protected:
virtual void ReleaseThis();
private:
friend class Allocator;
friend class AllocatorPimpl;
template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
PoolPimpl* m_Pimpl;
Pool(Allocator* allocator, const POOL_DESC &desc);
~Pool();
D3D12MA_CLASS_NO_COPY(Pool)
};
/// \brief Bit flags to be used with ALLOCATOR_DESC::Flags.
typedef enum ALLOCATOR_FLAGS
{
/// Zero
ALLOCATOR_FLAG_NONE = 0,
/**
Allocator and all objects created from it will not be synchronized internally,
so you must guarantee they are used from only one thread at a time or
synchronized by you.
Using this flag may increase performance because internal mutexes are not used.
*/
ALLOCATOR_FLAG_SINGLETHREADED = 0x1,
/**
Every allocation will have its own memory block.
To be used for debugging purposes.
*/
ALLOCATOR_FLAG_ALWAYS_COMMITTED = 0x2,
} ALLOCATOR_FLAGS;
/// \brief Parameters of created Allocator object. To be used with CreateAllocator().
struct ALLOCATOR_DESC
{
/// Flags.
ALLOCATOR_FLAGS Flags;
/** Direct3D device object that the allocator should be attached to.
Allocator is doing `AddRef`/`Release` on this object.
*/
ID3D12Device* pDevice;
/** \brief Preferred size of a single `ID3D12Heap` block to be allocated.
Set to 0 to use default, which is currently 64 MiB.
*/
UINT64 PreferredBlockSize;
/** \brief Custom CPU memory allocation callbacks. Optional.
Optional, can be null. When specified, will be used for all CPU-side memory allocations.
*/
const ALLOCATION_CALLBACKS* pAllocationCallbacks;
/** DXGI Adapter object that you use for D3D12 and this allocator.
Allocator is doing `AddRef`/`Release` on this object.
*/
IDXGIAdapter* pAdapter;
};
/**
\brief Number of D3D12 memory heap types supported.
*/
const UINT HEAP_TYPE_COUNT = 4;
/**
\brief Calculated statistics of memory usage in entire allocator.
*/
struct StatInfo
{
/// Number of memory blocks (heaps) allocated.
UINT BlockCount;
/// Number of D3D12MA::Allocation objects allocated.
UINT AllocationCount;
/// Number of free ranges of memory between allocations.
UINT UnusedRangeCount;
/// Total number of bytes occupied by all allocations.
UINT64 UsedBytes;
/// Total number of bytes occupied by unused ranges.
UINT64 UnusedBytes;
UINT64 AllocationSizeMin;
UINT64 AllocationSizeAvg;
UINT64 AllocationSizeMax;
UINT64 UnusedRangeSizeMin;
UINT64 UnusedRangeSizeAvg;
UINT64 UnusedRangeSizeMax;
};
/**
\brief General statistics from the current state of the allocator.
*/
struct Stats
{
/// Total statistics from all heap types.
StatInfo Total;
/**
One StatInfo for each type of heap located at the following indices:
0 - DEFAULT, 1 - UPLOAD, 2 - READBACK, 3 - CUSTOM.
*/
StatInfo HeapType[HEAP_TYPE_COUNT];
};
/** \brief Statistics of current memory usage and available budget, in bytes, for GPU or CPU memory.
*/
struct Budget
{
/** \brief Sum size of all memory blocks allocated from particular heap type, in bytes.
*/
UINT64 BlockBytes;
/** \brief Sum size of all allocations created in particular heap type, in bytes.
Always less or equal than `BlockBytes`.
Difference `BlockBytes - AllocationBytes` is the amount of memory allocated but unused -
available for new allocations or wasted due to fragmentation.
*/
UINT64 AllocationBytes;
/** \brief Estimated current memory usage of the program, in bytes.
Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if enabled.
It might be different than `BlockBytes` (usually higher) due to additional implicit objects
also occupying the memory, like swapchain, pipeline state objects, descriptor heaps, command lists, or
memory blocks allocated outside of this library, if any.
*/
UINT64 UsageBytes;
/** \brief Estimated amount of memory available to the program, in bytes.
Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if enabled.
It might be different (most probably smaller) than memory sizes reported in `DXGI_ADAPTER_DESC` due to factors
external to the program, like other programs also consuming system resources.
Difference `BudgetBytes - UsageBytes` is the amount of additional memory that can probably
be allocated without problems. Exceeding the budget may result in various problems.
*/
UINT64 BudgetBytes;
};
/**
\brief Represents main object of this library initialized for particular `ID3D12Device`.
Fill structure D3D12MA::ALLOCATOR_DESC and call function CreateAllocator() to create it.
Call method `Release()` to destroy it.
It is recommended to create just one object of this type per `ID3D12Device` object,
right after Direct3D 12 is initialized and keep it alive until before Direct3D device is destroyed.
*/
class Allocator : public IUnknownImpl
{
public:
/// Returns cached options retrieved from D3D12 device.
const D3D12_FEATURE_DATA_D3D12_OPTIONS& GetD3D12Options() const;
/** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::UMA` was found to be true.
For more information about how to use it, see articles in Microsoft Docs:
- https://docs.microsoft.com/en-us/windows/win32/direct3d12/default-texture-mapping
- https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture
- https://docs.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcustomheapproperties
*/
BOOL IsUMA() const;
/** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::CacheCoherentUMA` was found to be true.
For more information about how to use it, see articles in Microsoft Docs:
- https://docs.microsoft.com/en-us/windows/win32/direct3d12/default-texture-mapping
- https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_architecture
- https://docs.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getcustomheapproperties
*/
BOOL IsCacheCoherentUMA() const;
/** \brief Allocates memory and creates a D3D12 resource (buffer or texture). This is the main allocation function.
The function is similar to `ID3D12Device::CreateCommittedResource`, but it may
really call `ID3D12Device::CreatePlacedResource` to assign part of a larger,
existing memory heap to the new resource, which is the main purpose of this
whole library.
If `ppvResource` is null, you receive only `ppAllocation` object from this function.
It holds pointer to `ID3D12Resource` that can be queried using function D3D12MA::Allocation::GetResource().
Reference count of the resource object is 1.
It is automatically destroyed when you destroy the allocation object.
If `ppvResource` is not null, you receive pointer to the resource next to allocation object.
Reference count of the resource object is then increased by calling `QueryInterface`, so you need to manually `Release` it
along with the allocation.
\param pAllocDesc Parameters of the allocation.
\param pResourceDesc Description of created resource.
\param InitialResourceState Initial resource state.
\param pOptimizedClearValue Optional. Either null or optimized clear value.
\param[out] ppAllocation Filled with pointer to new allocation object created.
\param riidResource IID of a resource to be returned via `ppvResource`.
\param[out] ppvResource Optional. If not null, filled with pointer to new resouce created.
\note This function creates a new resource. Sub-allocation of parts of one large buffer,
although recommended as a good practice, is out of scope of this library and could be implemented
by the user as a higher-level logic on top of it, e.g. using the \ref virtual_allocator feature.
*/
HRESULT CreateResource(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource);
#ifdef __ID3D12Device4_INTERFACE_DEFINED__
/** \brief Similar to Allocator::CreateResource, but supports additional parameter `pProtectedSession`.
If `pProtectedSession` is not null, current implementation always creates the resource as committed
using `ID3D12Device4::CreateCommittedResource1`.
To work correctly, `ID3D12Device4` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.
*/
HRESULT CreateResource1(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
ID3D12ProtectedResourceSession *pProtectedSession,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource);
#endif // #ifdef __ID3D12Device4_INTERFACE_DEFINED__
#ifdef __ID3D12Device8_INTERFACE_DEFINED__
/** \brief Similar to Allocator::CreateResource1, but supports new structure `D3D12_RESOURCE_DESC1`.
It internally uses `ID3D12Device8::CreateCommittedResource2` or `ID3D12Device8::CreatePlacedResource1`.
To work correctly, `ID3D12Device8` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.
*/
HRESULT CreateResource2(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_DESC1* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
ID3D12ProtectedResourceSession *pProtectedSession,
Allocation** ppAllocation,
REFIID riidResource,
void** ppvResource);
#endif // #ifdef __ID3D12Device4_INTERFACE_DEFINED__
/** \brief Allocates memory without creating any resource placed in it.
This function is similar to `ID3D12Device::CreateHeap`, but it may really assign
part of a larger, existing heap to the allocation.
`pAllocDesc->heapFlags` should contain one of these values, depending on type of resources you are going to create in this memory:
`D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,
`D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
`D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.
Except if you validate that ResourceHeapTier = 2 - then `heapFlags`
may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.
Additional flags in `heapFlags` are allowed as well.
`pAllocInfo->SizeInBytes` must be multiply of 64KB.
`pAllocInfo->Alignment` must be one of the legal values as described in documentation of `D3D12_HEAP_DESC`.
If you use D3D12MA::ALLOCATION_FLAG_COMMITTED you will get a separate memory block -
a heap that always has offset 0.
*/
HRESULT AllocateMemory(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,
Allocation** ppAllocation);
#ifdef __ID3D12Device4_INTERFACE_DEFINED__
/** \brief Similar to Allocator::AllocateMemory, but supports additional parameter `pProtectedSession`.
If `pProtectedSession` is not null, current implementation always creates separate heap
using `ID3D12Device4::CreateHeap1`.
To work correctly, `ID3D12Device4` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.
*/
HRESULT AllocateMemory1(
const ALLOCATION_DESC* pAllocDesc,
const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,
ID3D12ProtectedResourceSession *pProtectedSession,
Allocation** ppAllocation);
#endif // #ifdef __ID3D12Device4_INTERFACE_DEFINED__
/** \brief Creates a new resource in place of an existing allocation. This is useful for memory aliasing.
\param pAllocation Existing allocation indicating the memory where the new resource should be created.
It can be created using D3D12MA::Allocator::CreateResource and already have a resource bound to it,
or can be a raw memory allocated with D3D12MA::Allocator::AllocateMemory.
It must not be created as committed so that `ID3D12Heap` is available and not implicit.
\param AllocationLocalOffset Additional offset in bytes to be applied when allocating the resource.
Local from the start of `pAllocation`, not the beginning of the whole `ID3D12Heap`!
If the new resource should start from the beginning of the `pAllocation` it should be 0.
\param pResourceDesc Description of the new resource to be created.
\param InitialResourceState
\param pOptimizedClearValue
\param riidResource
\param[out] ppvResource Returns pointer to the new resource.
The resource is not bound with `pAllocation`.
This pointer must not be null - you must get the resource pointer and `Release` it when no longer needed.
Memory requirements of the new resource are checked for validation.
If its size exceeds the end of `pAllocation` or required alignment is not fulfilled
considering `pAllocation->GetOffset() + AllocationLocalOffset`, the function
returns `E_INVALIDARG`.
*/
HRESULT CreateAliasingResource(
Allocation* pAllocation,
UINT64 AllocationLocalOffset,
const D3D12_RESOURCE_DESC* pResourceDesc,
D3D12_RESOURCE_STATES InitialResourceState,
const D3D12_CLEAR_VALUE *pOptimizedClearValue,
REFIID riidResource,
void** ppvResource);
/** \brief Creates custom pool.
*/
HRESULT CreatePool(
const POOL_DESC* pPoolDesc,
Pool** ppPool);
/** \brief Sets the index of the current frame.
This function is used to set the frame index in the allocator when a new game frame begins.
*/
void SetCurrentFrameIndex(UINT frameIndex);
/** \brief Retrieves statistics from the current state of the allocator.
*/
void CalculateStats(Stats* pStats);
/** \brief Retrieves information about current memory budget.
\param[out] pGpuBudget Optional, can be null.
\param[out] pCpuBudget Optional, can be null.
This function is called "get" not "calculate" because it is very fast, suitable to be called
every frame or every allocation. For more detailed statistics use CalculateStats().
Note that when using allocator from multiple threads, returned information may immediately
become outdated.
*/
void GetBudget(Budget* pGpuBudget, Budget* pCpuBudget);
/// Builds and returns statistics as a string in JSON format.
/** @param[out] ppStatsString Must be freed using Allocator::FreeStatsString.
@param DetailedMap `TRUE` to include full list of allocations (can make the string quite long), `FALSE` to only return statistics.
*/
void BuildStatsString(WCHAR** ppStatsString, BOOL DetailedMap) const;
/// Frees memory of a string returned from Allocator::BuildStatsString.
void FreeStatsString(WCHAR* pStatsString) const;
protected:
virtual void ReleaseThis();
private:
friend HRESULT CreateAllocator(const ALLOCATOR_DESC*, Allocator**);
template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
friend class Pool;
Allocator(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc);
~Allocator();
AllocatorPimpl* m_Pimpl;
D3D12MA_CLASS_NO_COPY(Allocator)
};
/// Parameters of created D3D12MA::VirtualBlock object to be passed to CreateVirtualBlock().
struct VIRTUAL_BLOCK_DESC
{
/** \brief Total size of the block.
Sizes can be expressed in bytes or any units you want as long as you are consistent in using them.
For example, if you allocate from some array of structures, 1 can mean single instance of entire structure.
*/
UINT64 Size;
/** \brief Custom CPU memory allocation callbacks. Optional.
Optional, can be null. When specified, will be used for all CPU-side memory allocations.
*/
const ALLOCATION_CALLBACKS* pAllocationCallbacks;
};
/// Parameters of created virtual allocation to be passed to VirtualBlock::Allocate().
struct VIRTUAL_ALLOCATION_DESC
{
/** \brief Size of the allocation.
Cannot be zero.
*/
UINT64 Size;
/** \brief Required alignment of the allocation.
Must 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.
*/
UINT64 Alignment;
/** \brief Custom pointer to be associated with the allocation.
It can be fetched or changed later.
*/
void* pUserData;
};
/// Parameters of an existing virtual allocation, returned by VirtualBlock::GetAllocationInfo().
struct VIRTUAL_ALLOCATION_INFO
{
/** \brief Size of the allocation.
Same value as passed in VIRTUAL_ALLOCATION_DESC::Size.
*/
UINT64 size;
/** \brief Custom pointer associated with the allocation.
Same value as passed in VIRTUAL_ALLOCATION_DESC::pUserData or VirtualBlock::SetAllocationUserData().
*/
void* pUserData;
};
/** \brief Represents pure allocation algorithm and a data structure with allocations in some memory block, without actually allocating any GPU memory.
This class allows to use the core algorithm of the library custom allocations e.g. CPU memory or
sub-allocation regions inside a single GPU buffer.
To create this object, fill in D3D12MA::VIRTUAL_BLOCK_DESC and call CreateVirtualBlock().
To destroy it, call its method `VirtualBlock::Release()`.
You need to free all the allocations within this block or call Clear() before destroying it.
*/
class VirtualBlock : public IUnknownImpl
{
public:
/** \brief Returns true if the block is empty - contains 0 allocations.
*/
BOOL IsEmpty() const;
/** \brief Returns information about an allocation at given offset - its size and custom pointer.
*/
void GetAllocationInfo(UINT64 offset, VIRTUAL_ALLOCATION_INFO* pInfo) const;
/** \brief Creates new allocation.
\param pDesc
\param[out] pOffset Offset of the new allocation, which can also be treated as an unique identifier of the allocation within this block. `UINT64_MAX` if allocation failed.
\return `S_OK` if allocation succeeded, `E_OUTOFMEMORY` if it failed.
*/
HRESULT Allocate(const VIRTUAL_ALLOCATION_DESC* pDesc, UINT64* pOffset);
/** \brief Frees the allocation at given offset.
*/
void FreeAllocation(UINT64 offset);
/** \brief Frees all the allocations.
*/
void Clear();
/** \brief Changes custom pointer for an allocation at given offset to a new value.
*/
void SetAllocationUserData(UINT64 offset, void* pUserData);
/** \brief Retrieves statistics from the current state of the block.
*/
void CalculateStats(StatInfo* pInfo) const;
/** \brief Builds and returns statistics as a string in JSON format, including the list of allocations with their parameters.
@param[out] ppStatsString Must be freed using VirtualBlock::FreeStatsString.
*/
void BuildStatsString(WCHAR** ppStatsString) const;
/** \brief Frees memory of a string returned from VirtualBlock::BuildStatsString.
*/
void FreeStatsString(WCHAR* pStatsString) const;
protected:
virtual void ReleaseThis();
private:
friend HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC*, VirtualBlock**);
template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
VirtualBlockPimpl* m_Pimpl;
VirtualBlock(const ALLOCATION_CALLBACKS& allocationCallbacks, const VIRTUAL_BLOCK_DESC& desc);
~VirtualBlock();
D3D12MA_CLASS_NO_COPY(VirtualBlock)
};
/** \brief Creates new main D3D12MA::Allocator object and returns it through `ppAllocator`.
You normally only need to call it once and keep a single Allocator object for your `ID3D12Device`.
*/
HRESULT CreateAllocator(const ALLOCATOR_DESC* pDesc, Allocator** ppAllocator);
/** \brief Creates new D3D12MA::VirtualBlock object and returns it through `ppVirtualBlock`.
Note you don't need to create D3D12MA::Allocator to use virtual blocks.