| 1 |
//! Sampler management for DX12. |
| 2 |
//! |
| 3 |
//! Nearly identical to the Vulkan sampler cache, with added descriptor heap management. |
| 4 |
|
| 5 |
use alloc::vec::Vec; |
| 6 |
|
| 7 |
use hashbrown::{hash_map::Entry, HashMap}; |
| 8 |
|
| 9 |
use ordered_float::OrderedFloat; |
| 10 |
use parking_lot::Mutex; |
| 11 |
use windows::Win32::Graphics::Direct3D12::*; |
| 12 |
|
| 13 |
use crate::dx12::HResult; |
| 14 |
|
| 15 |
/// The index of a sampler in the global sampler heap. |
| 16 |
/// |
| 17 |
/// This is a type-safe, transparent wrapper around a u32. |
| 18 |
#[repr(transparent)] |
| 19 |
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 20 |
pub(crate) struct SamplerIndex(u32); |
| 21 |
|
| 22 |
/// [`D3D12_SAMPLER_DESC`] is not hashable, so we wrap it in a newtype that is. |
| 23 |
/// |
| 24 |
/// We use [`OrderedFloat`] to allow for floating point values to be compared and |
| 25 |
/// hashed in a defined way. |
| 26 |
#[derive(Debug, Copy, Clone)] |
| 27 |
struct HashableSamplerDesc(D3D12_SAMPLER_DESC); |
| 28 |
|
| 29 |
impl PartialEq for HashableSamplerDesc { |
| 30 |
fn eq(&self, other: &Self) -> bool { |
| 31 |
self.0.Filter == other.0.Filter |
| 32 |
&& self.0.AddressU == other.0.AddressU |
| 33 |
&& self.0.AddressV == other.0.AddressV |
| 34 |
&& self.0.AddressW == other.0.AddressW |
| 35 |
&& OrderedFloat(self.0.MipLODBias) == OrderedFloat(other.0.MipLODBias) |
| 36 |
&& self.0.MaxAnisotropy == other.0.MaxAnisotropy |
| 37 |
&& self.0.ComparisonFunc == other.0.ComparisonFunc |
| 38 |
&& self.0.BorderColor.map(OrderedFloat) == other.0.BorderColor.map(OrderedFloat) |
| 39 |
&& OrderedFloat(self.0.MinLOD) == OrderedFloat(other.0.MinLOD) |
| 40 |
&& OrderedFloat(self.0.MaxLOD) == OrderedFloat(other.0.MaxLOD) |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
impl Eq for HashableSamplerDesc {} |
| 45 |
|
| 46 |
impl core::hash::Hash for HashableSamplerDesc { |
| 47 |
fn hash<H: core::hash::Hasher>(&self, state: &mut H) { |
| 48 |
self.0.Filter.0.hash(state); |
| 49 |
self.0.AddressU.0.hash(state); |
| 50 |
self.0.AddressV.0.hash(state); |
| 51 |
self.0.AddressW.0.hash(state); |
| 52 |
OrderedFloat(self.0.MipLODBias).hash(state); |
| 53 |
self.0.MaxAnisotropy.hash(state); |
| 54 |
self.0.ComparisonFunc.0.hash(state); |
| 55 |
self.0.BorderColor.map(OrderedFloat).hash(state); |
| 56 |
OrderedFloat(self.0.MinLOD).hash(state); |
| 57 |
OrderedFloat(self.0.MaxLOD).hash(state); |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
/// Entry in the sampler cache. |
| 62 |
struct CacheEntry { |
| 63 |
index: SamplerIndex, |
| 64 |
ref_count: u32, |
| 65 |
} |
| 66 |
|
| 67 |
/// Container for the mutable management state of the sampler heap. |
| 68 |
/// |
| 69 |
/// We have this separated, using interior mutability, to allow for the outside world |
| 70 |
/// to access the heap directly without needing to take the lock. |
| 71 |
pub(crate) struct SamplerHeapState { |
| 72 |
/// Mapping from the sampler description to the index within the heap and the refcount. |
| 73 |
mapping: HashMap<HashableSamplerDesc, CacheEntry>, |
| 74 |
/// List of free sampler indices. |
| 75 |
freelist: Vec<SamplerIndex>, |
| 76 |
} |
| 77 |
|
| 78 |
/// Global sampler heap for the device. |
| 79 |
/// |
| 80 |
/// As D3D12 only allows 2048 samplers to be in a single heap, we need to cache |
| 81 |
/// samplers aggressively and refer to them in shaders by index. |
| 82 |
pub(crate) struct SamplerHeap { |
| 83 |
/// Mutable management state of the sampler heap. |
| 84 |
state: Mutex<SamplerHeapState>, |
| 85 |
|
| 86 |
/// The heap itself. |
| 87 |
heap: ID3D12DescriptorHeap, |
| 88 |
/// The CPU-side handle to the first descriptor in the heap. |
| 89 |
/// |
| 90 |
/// Both the CPU and GPU handles point to the same descriptor, just in |
| 91 |
/// different contexts. |
| 92 |
heap_cpu_start_handle: D3D12_CPU_DESCRIPTOR_HANDLE, |
| 93 |
/// The GPU-side handle to the first descriptor in the heap. |
| 94 |
/// |
| 95 |
/// Both the CPU and GPU handles point to the same descriptor, just in |
| 96 |
/// different contexts. |
| 97 |
heap_gpu_start_handle: D3D12_GPU_DESCRIPTOR_HANDLE, |
| 98 |
|
| 99 |
/// This is the device-specific size of sampler descriptors. |
| 100 |
descriptor_stride: u32, |
| 101 |
} |
| 102 |
|
| 103 |
impl SamplerHeap { |
| 104 |
pub fn new( |
| 105 |
device: &ID3D12Device, |
| 106 |
private_caps: &super::PrivateCapabilities, |
| 107 |
) -> Result<Self, crate::DeviceError> { |
| 108 |
profiling::scope!("SamplerHeap::new"); |
| 109 |
|
| 110 |
// WARP can report this as 2M or more. We clamp it to 64k to be safe. |
| 111 |
const SAMPLER_HEAP_SIZE_CLAMP: u32 = 64 * 1024; |
| 112 |
|
| 113 |
let max_unique_samplers = private_caps |
| 114 |
.max_sampler_descriptor_heap_size |
| 115 |
.min(SAMPLER_HEAP_SIZE_CLAMP); |
| 116 |
|
| 117 |
let desc = D3D12_DESCRIPTOR_HEAP_DESC { |
| 118 |
Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, |
| 119 |
NumDescriptors: max_unique_samplers, |
| 120 |
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, |
| 121 |
NodeMask: 0, |
| 122 |
}; |
| 123 |
let heap = unsafe { device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc) } |
| 124 |
.into_device_result("Failed to create global GPU-Visible Sampler Descriptor Heap")?; |
| 125 |
|
| 126 |
let heap_cpu_start_handle = unsafe { heap.GetCPUDescriptorHandleForHeapStart() }; |
| 127 |
let heap_gpu_start_handle = unsafe { heap.GetGPUDescriptorHandleForHeapStart() }; |
| 128 |
|
| 129 |
let descriptor_stride = |
| 130 |
unsafe { device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) }; |
| 131 |
|
| 132 |
Ok(Self { |
| 133 |
state: Mutex::new(SamplerHeapState { |
| 134 |
mapping: HashMap::new(), |
| 135 |
// Reverse so that samplers get allocated starting from zero. |
| 136 |
freelist: (0..max_unique_samplers).map(SamplerIndex).rev().collect(), |
| 137 |
}), |
| 138 |
heap, |
| 139 |
heap_cpu_start_handle, |
| 140 |
heap_gpu_start_handle, |
| 141 |
descriptor_stride, |
| 142 |
}) |
| 143 |
} |
| 144 |
|
| 145 |
/// Returns a reference to the raw descriptor heap. |
| 146 |
pub fn heap(&self) -> &ID3D12DescriptorHeap { |
| 147 |
&self.heap |
| 148 |
} |
| 149 |
|
| 150 |
/// Returns a reference the handle to be bound to the descriptor table. |
| 151 |
pub fn gpu_descriptor_table(&self) -> D3D12_GPU_DESCRIPTOR_HANDLE { |
| 152 |
self.heap_gpu_start_handle |
| 153 |
} |
| 154 |
|
| 155 |
/// Add a sampler with the given description to the heap. |
| 156 |
/// |
| 157 |
/// If the sampler already exists, the refcount is incremented and the existing index is returned. |
| 158 |
/// |
| 159 |
/// If the sampler does not exist, a new sampler is created and the index is returned. |
| 160 |
/// |
| 161 |
/// If the heap is full, an error is returned. |
| 162 |
pub fn create_sampler( |
| 163 |
&self, |
| 164 |
device: &ID3D12Device, |
| 165 |
desc: D3D12_SAMPLER_DESC, |
| 166 |
) -> Result<SamplerIndex, crate::DeviceError> { |
| 167 |
profiling::scope!("SamplerHeap::create_sampler"); |
| 168 |
|
| 169 |
let hashable_desc = HashableSamplerDesc(desc); |
| 170 |
|
| 171 |
// Eagarly dereference the lock to allow split borrows. |
| 172 |
let state = &mut *self.state.lock(); |
| 173 |
|
| 174 |
// Lookup the sampler in the mapping. |
| 175 |
match state.mapping.entry(hashable_desc) { |
| 176 |
Entry::Occupied(occupied_entry) => { |
| 177 |
// We have found a match, so increment the refcount and return the index. |
| 178 |
let entry = occupied_entry.into_mut(); |
| 179 |
entry.ref_count += 1; |
| 180 |
Ok(entry.index) |
| 181 |
} |
| 182 |
Entry::Vacant(vacant_entry) => { |
| 183 |
// We need to create a new sampler. |
| 184 |
|
| 185 |
// Try to get a new index from the freelist. |
| 186 |
let Some(index) = state.freelist.pop() else { |
| 187 |
// If the freelist is empty, we have hit the maximum number of samplers. |
| 188 |
log::error!("There is no more room in the global sampler heap for more unique samplers. Your device supports a maximum of {} unique samplers.", state.mapping.len()); |
| 189 |
return Err(crate::DeviceError::OutOfMemory); |
| 190 |
}; |
| 191 |
|
| 192 |
// Compute the CPU side handle for the new sampler. |
| 193 |
let handle = D3D12_CPU_DESCRIPTOR_HANDLE { |
| 194 |
ptr: self.heap_cpu_start_handle.ptr |
| 195 |
+ self.descriptor_stride as usize * index.0 as usize, |
| 196 |
}; |
| 197 |
|
| 198 |
unsafe { |
| 199 |
device.CreateSampler(&desc, handle); |
| 200 |
} |
| 201 |
|
| 202 |
// Insert the new sampler into the mapping. |
| 203 |
vacant_entry.insert(CacheEntry { |
| 204 |
index, |
| 205 |
ref_count: 1, |
| 206 |
}); |
| 207 |
|
| 208 |
Ok(index) |
| 209 |
} |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
/// Decrement the refcount of the sampler with the given description. |
| 214 |
/// |
| 215 |
/// If the refcount reaches zero, the sampler is destroyed and the index is returned to the freelist. |
| 216 |
/// |
| 217 |
/// The provided index is checked against the index of the sampler with the given description, ensuring |
| 218 |
/// that there isn't a clerical error from the caller. |
| 219 |
pub fn destroy_sampler(&self, desc: D3D12_SAMPLER_DESC, provided_index: SamplerIndex) { |
| 220 |
profiling::scope!("SamplerHeap::destroy_sampler"); |
| 221 |
|
| 222 |
// Eagarly dereference the lock to allow split borrows. |
| 223 |
let state = &mut *self.state.lock(); |
| 224 |
|
| 225 |
// Get the index of the sampler to destroy. |
| 226 |
let Entry::Occupied(mut hash_map_entry) = state.mapping.entry(HashableSamplerDesc(desc)) |
| 227 |
else { |
| 228 |
log::error!( |
| 229 |
"Tried to destroy a sampler that doesn't exist. Sampler description: {:#?}", |
| 230 |
desc |
| 231 |
); |
| 232 |
return; |
| 233 |
}; |
| 234 |
let cache_entry = hash_map_entry.get_mut(); |
| 235 |
|
| 236 |
// Ensure that the provided index matches the index of the sampler to destroy. |
| 237 |
assert_eq!( |
| 238 |
cache_entry.index, provided_index, |
| 239 |
"Mismatched sampler index, this is an implementation bug" |
| 240 |
); |
| 241 |
|
| 242 |
// Decrement the refcount of the sampler. |
| 243 |
cache_entry.ref_count -= 1; |
| 244 |
|
| 245 |
// If we are the last reference, remove the sampler from the mapping and return the index to the freelist. |
| 246 |
// |
| 247 |
// As samplers only exist as descriptors in the heap, there is nothing needed to be done to destroy the sampler. |
| 248 |
if cache_entry.ref_count == 0 { |
| 249 |
state.freelist.push(cache_entry.index); |
| 250 |
hash_map_entry.remove(); |
| 251 |
} |
| 252 |
} |
| 253 |
} |