-
Notifications
You must be signed in to change notification settings - Fork 935
/
device.rs
1572 lines (1455 loc) · 59.6 KB
/
device.rs
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
use crate::{
auxil::{self, dxgi::result::HResult as _},
dx12::shader_compilation,
};
use super::{conv, descriptor, view};
use parking_lot::Mutex;
use std::{ffi, mem, num::NonZeroU32, ptr, sync::Arc};
use winapi::{
shared::{dxgiformat, dxgitype, minwindef::BOOL, winerror},
um::{d3d12 as d3d12_ty, synchapi, winbase},
Interface,
};
// this has to match Naga's HLSL backend, and also needs to be null-terminated
const NAGA_LOCATION_SEMANTIC: &[u8] = b"LOC\0";
impl super::Device {
pub(super) fn new(
raw: d3d12::Device,
present_queue: d3d12::CommandQueue,
limits: &wgt::Limits,
private_caps: super::PrivateCapabilities,
library: &Arc<d3d12::D3D12Lib>,
dxc_container: Option<Arc<shader_compilation::DxcContainer>>,
) -> Result<Self, crate::DeviceError> {
let mem_allocator = if private_caps.suballocation_supported {
super::suballocation::create_allocator_wrapper(&raw)?
} else {
None
};
let mut idle_fence = d3d12::Fence::null();
let hr = unsafe {
profiling::scope!("ID3D12Device::CreateFence");
raw.CreateFence(
0,
d3d12_ty::D3D12_FENCE_FLAG_NONE,
&d3d12_ty::ID3D12Fence::uuidof(),
idle_fence.mut_void(),
)
};
hr.into_device_result("Idle fence creation")?;
let mut zero_buffer = d3d12::Resource::null();
unsafe {
let raw_desc = d3d12_ty::D3D12_RESOURCE_DESC {
Dimension: d3d12_ty::D3D12_RESOURCE_DIMENSION_BUFFER,
Alignment: 0,
Width: super::ZERO_BUFFER_SIZE,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
Format: dxgiformat::DXGI_FORMAT_UNKNOWN,
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: d3d12_ty::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: d3d12_ty::D3D12_RESOURCE_FLAG_NONE,
};
let heap_properties = d3d12_ty::D3D12_HEAP_PROPERTIES {
Type: d3d12_ty::D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: d3d12_ty::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
MemoryPoolPreference: match private_caps.memory_architecture {
super::MemoryArchitecture::Unified { .. } => d3d12_ty::D3D12_MEMORY_POOL_L0,
super::MemoryArchitecture::NonUnified => d3d12_ty::D3D12_MEMORY_POOL_L1,
},
CreationNodeMask: 0,
VisibleNodeMask: 0,
};
profiling::scope!("Zero Buffer Allocation");
raw.CreateCommittedResource(
&heap_properties,
d3d12_ty::D3D12_HEAP_FLAG_NONE,
&raw_desc,
d3d12_ty::D3D12_RESOURCE_STATE_COMMON,
ptr::null(),
&d3d12_ty::ID3D12Resource::uuidof(),
zero_buffer.mut_void(),
)
.into_device_result("Zero buffer creation")?;
// Note: without `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`
// this resource is zeroed by default.
};
// maximum number of CBV/SRV/UAV descriptors in heap for Tier 1
let capacity_views = limits.max_non_sampler_bindings as u64;
let capacity_samplers = 2_048;
let shared = super::DeviceShared {
zero_buffer,
cmd_signatures: super::CommandSignatures {
draw: raw
.create_command_signature(
d3d12::RootSignature::null(),
&[d3d12::IndirectArgument::draw()],
mem::size_of::<wgt::DrawIndirectArgs>() as u32,
0,
)
.into_device_result("Command (draw) signature creation")?,
draw_indexed: raw
.create_command_signature(
d3d12::RootSignature::null(),
&[d3d12::IndirectArgument::draw_indexed()],
mem::size_of::<wgt::DrawIndexedIndirectArgs>() as u32,
0,
)
.into_device_result("Command (draw_indexed) signature creation")?,
dispatch: raw
.create_command_signature(
d3d12::RootSignature::null(),
&[d3d12::IndirectArgument::dispatch()],
mem::size_of::<wgt::DispatchIndirectArgs>() as u32,
0,
)
.into_device_result("Command (dispatch) signature creation")?,
},
heap_views: descriptor::GeneralHeap::new(
raw.clone(),
d3d12::DescriptorHeapType::CbvSrvUav,
capacity_views,
)?,
heap_samplers: descriptor::GeneralHeap::new(
raw.clone(),
d3d12::DescriptorHeapType::Sampler,
capacity_samplers,
)?,
};
let mut rtv_pool = descriptor::CpuPool::new(raw.clone(), d3d12::DescriptorHeapType::Rtv);
let null_rtv_handle = rtv_pool.alloc_handle();
// A null pResource is used to initialize a null descriptor,
// which guarantees D3D11-like null binding behavior (reading 0s, writes are discarded)
raw.create_render_target_view(
d3d12::ComPtr::null(),
&d3d12::RenderTargetViewDesc::texture_2d(
winapi::shared::dxgiformat::DXGI_FORMAT_R8G8B8A8_UNORM,
0,
0,
),
null_rtv_handle.raw,
);
Ok(super::Device {
raw: raw.clone(),
present_queue,
idler: super::Idler {
fence: idle_fence,
event: d3d12::Event::create(false, false),
},
private_caps,
shared: Arc::new(shared),
rtv_pool: Mutex::new(rtv_pool),
dsv_pool: Mutex::new(descriptor::CpuPool::new(
raw.clone(),
d3d12::DescriptorHeapType::Dsv,
)),
srv_uav_pool: Mutex::new(descriptor::CpuPool::new(
raw.clone(),
d3d12::DescriptorHeapType::CbvSrvUav,
)),
sampler_pool: Mutex::new(descriptor::CpuPool::new(
raw,
d3d12::DescriptorHeapType::Sampler,
)),
library: Arc::clone(library),
#[cfg(feature = "renderdoc")]
render_doc: Default::default(),
null_rtv_handle,
mem_allocator,
dxc_container,
})
}
// Blocks until the dedicated present queue is finished with all of its work.
//
// Once this method completes, the surface is able to be resized or deleted.
pub(super) unsafe fn wait_for_present_queue_idle(&self) -> Result<(), crate::DeviceError> {
let cur_value = self.idler.fence.get_value();
if cur_value == !0 {
return Err(crate::DeviceError::Lost);
}
let value = cur_value + 1;
log::info!("Waiting for idle with value {}", value);
self.present_queue.signal(&self.idler.fence, value);
let hr = self
.idler
.fence
.set_event_on_completion(self.idler.event, value);
hr.into_device_result("Set event")?;
unsafe { synchapi::WaitForSingleObject(self.idler.event.0, winbase::INFINITE) };
Ok(())
}
fn load_shader(
&self,
stage: &crate::ProgrammableStage<super::Api>,
layout: &super::PipelineLayout,
naga_stage: naga::ShaderStage,
) -> Result<super::CompiledShader, crate::PipelineError> {
use naga::back::hlsl;
let stage_bit = crate::auxil::map_naga_stage(naga_stage);
let module = &stage.module.naga.module;
//TODO: reuse the writer
let mut source = String::new();
let mut writer = hlsl::Writer::new(&mut source, &layout.naga_options);
let reflection_info = {
profiling::scope!("naga::back::hlsl::write");
writer
.write(module, &stage.module.naga.info)
.map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("HLSL: {e:?}")))?
};
let full_stage = format!(
"{}_{}\0",
naga_stage.to_hlsl_str(),
layout.naga_options.shader_model.to_str()
);
let ep_index = module
.entry_points
.iter()
.position(|ep| ep.stage == naga_stage && ep.name == stage.entry_point)
.ok_or(crate::PipelineError::EntryPoint(naga_stage))?;
let raw_ep = reflection_info.entry_point_names[ep_index]
.as_ref()
.map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("{e}")))?;
let source_name = stage
.module
.raw_name
.as_ref()
.and_then(|cstr| cstr.to_str().ok())
.unwrap_or_default();
// Compile with DXC if available, otherwise fall back to FXC
let (result, log_level) = if let Some(ref dxc_container) = self.dxc_container {
super::shader_compilation::compile_dxc(
self,
&source,
source_name,
raw_ep,
stage_bit,
full_stage,
dxc_container,
)
} else {
super::shader_compilation::compile_fxc(
self,
&source,
source_name,
&ffi::CString::new(raw_ep.as_str()).unwrap(),
stage_bit,
full_stage,
)
};
log::log!(
log_level,
"Naga generated shader for {:?} at {:?}:\n{}",
raw_ep,
naga_stage,
source
);
result
}
pub fn raw_device(&self) -> &d3d12::Device {
&self.raw
}
pub fn raw_queue(&self) -> &d3d12::CommandQueue {
&self.present_queue
}
pub unsafe fn texture_from_raw(
resource: d3d12::Resource,
format: wgt::TextureFormat,
dimension: wgt::TextureDimension,
size: wgt::Extent3d,
mip_level_count: u32,
sample_count: u32,
) -> super::Texture {
super::Texture {
resource,
format,
dimension,
size,
mip_level_count,
sample_count,
allocation: None,
}
}
pub unsafe fn buffer_from_raw(
resource: d3d12::Resource,
size: wgt::BufferAddress,
) -> super::Buffer {
super::Buffer {
resource,
size,
allocation: None,
}
}
}
impl crate::Device<super::Api> for super::Device {
unsafe fn exit(mut self, _queue: super::Queue) {
self.rtv_pool.lock().free_handle(self.null_rtv_handle);
self.mem_allocator = None;
}
unsafe fn create_buffer(
&self,
desc: &crate::BufferDescriptor,
) -> Result<super::Buffer, crate::DeviceError> {
let mut resource = d3d12::Resource::null();
let mut size = desc.size;
if desc.usage.contains(crate::BufferUses::UNIFORM) {
let align_mask = d3d12_ty::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT as u64 - 1;
size = ((size - 1) | align_mask) + 1;
}
let raw_desc = d3d12_ty::D3D12_RESOURCE_DESC {
Dimension: d3d12_ty::D3D12_RESOURCE_DIMENSION_BUFFER,
Alignment: 0,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
Format: dxgiformat::DXGI_FORMAT_UNKNOWN,
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: d3d12_ty::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: conv::map_buffer_usage_to_resource_flags(desc.usage),
};
let (hr, allocation) =
super::suballocation::create_buffer_resource(self, desc, raw_desc, &mut resource)?;
hr.into_device_result("Buffer creation")?;
if let Some(label) = desc.label {
let cwstr = conv::map_label(label);
unsafe { resource.SetName(cwstr.as_ptr()) };
}
Ok(super::Buffer {
resource,
size,
allocation,
})
}
unsafe fn destroy_buffer(&self, mut buffer: super::Buffer) {
// Only happens when it's using the windows_rs feature and there's an allocation
if let Some(alloc) = buffer.allocation.take() {
super::suballocation::free_buffer_allocation(
alloc,
// SAFETY: for allocations to exist, the allocator must exist
unsafe { self.mem_allocator.as_ref().unwrap_unchecked() },
);
}
}
unsafe fn map_buffer(
&self,
buffer: &super::Buffer,
range: crate::MemoryRange,
) -> Result<crate::BufferMapping, crate::DeviceError> {
let mut ptr = ptr::null_mut();
// TODO: 0 for subresource should be fine here until map and unmap buffer is subresource aware?
let hr = unsafe { (*buffer.resource).Map(0, ptr::null(), &mut ptr) };
hr.into_device_result("Map buffer")?;
Ok(crate::BufferMapping {
ptr: ptr::NonNull::new(unsafe { ptr.offset(range.start as isize).cast::<u8>() })
.unwrap(),
//TODO: double-check this. Documentation is a bit misleading -
// it implies that Map/Unmap is needed to invalidate/flush memory.
is_coherent: true,
})
}
unsafe fn unmap_buffer(&self, buffer: &super::Buffer) -> Result<(), crate::DeviceError> {
unsafe { (*buffer.resource).Unmap(0, ptr::null()) };
Ok(())
}
unsafe fn flush_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {}
unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {}
unsafe fn create_texture(
&self,
desc: &crate::TextureDescriptor,
) -> Result<super::Texture, crate::DeviceError> {
use super::suballocation::create_texture_resource;
let mut resource = d3d12::Resource::null();
let raw_desc = d3d12_ty::D3D12_RESOURCE_DESC {
Dimension: conv::map_texture_dimension(desc.dimension),
Alignment: 0,
Width: desc.size.width as u64,
Height: desc.size.height,
DepthOrArraySize: desc.size.depth_or_array_layers as u16,
MipLevels: desc.mip_level_count as u16,
Format: auxil::dxgi::conv::map_texture_format_for_resource(
desc.format,
desc.usage,
!desc.view_formats.is_empty(),
self.private_caps.casting_fully_typed_format_supported,
),
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: desc.sample_count,
Quality: 0,
},
Layout: d3d12_ty::D3D12_TEXTURE_LAYOUT_UNKNOWN,
Flags: conv::map_texture_usage_to_resource_flags(desc.usage),
};
let (hr, allocation) = create_texture_resource(self, desc, raw_desc, &mut resource)?;
hr.into_device_result("Texture creation")?;
if let Some(label) = desc.label {
let cwstr = conv::map_label(label);
unsafe { resource.SetName(cwstr.as_ptr()) };
}
Ok(super::Texture {
resource,
format: desc.format,
dimension: desc.dimension,
size: desc.size,
mip_level_count: desc.mip_level_count,
sample_count: desc.sample_count,
allocation,
})
}
unsafe fn destroy_texture(&self, mut texture: super::Texture) {
if let Some(alloc) = texture.allocation.take() {
super::suballocation::free_texture_allocation(
alloc,
// SAFETY: for allocations to exist, the allocator must exist
unsafe { self.mem_allocator.as_ref().unwrap_unchecked() },
);
}
}
unsafe fn create_texture_view(
&self,
texture: &super::Texture,
desc: &crate::TextureViewDescriptor,
) -> Result<super::TextureView, crate::DeviceError> {
let view_desc = desc.to_internal(texture);
Ok(super::TextureView {
raw_format: view_desc.rtv_dsv_format,
aspects: view_desc.aspects,
target_base: (
texture.resource.clone(),
texture.calc_subresource(desc.range.base_mip_level, desc.range.base_array_layer, 0),
),
handle_srv: if desc.usage.intersects(crate::TextureUses::RESOURCE) {
let raw_desc = unsafe { view_desc.to_srv() };
raw_desc.map(|raw_desc| {
let handle = self.srv_uav_pool.lock().alloc_handle();
unsafe {
self.raw.CreateShaderResourceView(
texture.resource.as_mut_ptr(),
&raw_desc,
handle.raw,
)
};
handle
})
} else {
None
},
handle_uav: if desc.usage.intersects(
crate::TextureUses::STORAGE_READ | crate::TextureUses::STORAGE_READ_WRITE,
) {
let raw_desc = unsafe { view_desc.to_uav() };
raw_desc.map(|raw_desc| {
let handle = self.srv_uav_pool.lock().alloc_handle();
unsafe {
self.raw.CreateUnorderedAccessView(
texture.resource.as_mut_ptr(),
ptr::null_mut(),
&raw_desc,
handle.raw,
)
};
handle
})
} else {
None
},
handle_rtv: if desc.usage.intersects(crate::TextureUses::COLOR_TARGET) {
let raw_desc = unsafe { view_desc.to_rtv() };
let handle = self.rtv_pool.lock().alloc_handle();
unsafe {
self.raw.CreateRenderTargetView(
texture.resource.as_mut_ptr(),
&raw_desc,
handle.raw,
)
};
Some(handle)
} else {
None
},
handle_dsv_ro: if desc
.usage
.intersects(crate::TextureUses::DEPTH_STENCIL_READ)
{
let raw_desc = unsafe { view_desc.to_dsv(true) };
let handle = self.dsv_pool.lock().alloc_handle();
unsafe {
self.raw.CreateDepthStencilView(
texture.resource.as_mut_ptr(),
&raw_desc,
handle.raw,
)
};
Some(handle)
} else {
None
},
handle_dsv_rw: if desc
.usage
.intersects(crate::TextureUses::DEPTH_STENCIL_WRITE)
{
let raw_desc = unsafe { view_desc.to_dsv(false) };
let handle = self.dsv_pool.lock().alloc_handle();
unsafe {
self.raw.CreateDepthStencilView(
texture.resource.as_mut_ptr(),
&raw_desc,
handle.raw,
)
};
Some(handle)
} else {
None
},
})
}
unsafe fn destroy_texture_view(&self, view: super::TextureView) {
if view.handle_srv.is_some() || view.handle_uav.is_some() {
let mut pool = self.srv_uav_pool.lock();
if let Some(handle) = view.handle_srv {
pool.free_handle(handle);
}
if let Some(handle) = view.handle_uav {
pool.free_handle(handle);
}
}
if let Some(handle) = view.handle_rtv {
self.rtv_pool.lock().free_handle(handle);
}
if view.handle_dsv_ro.is_some() || view.handle_dsv_rw.is_some() {
let mut pool = self.dsv_pool.lock();
if let Some(handle) = view.handle_dsv_ro {
pool.free_handle(handle);
}
if let Some(handle) = view.handle_dsv_rw {
pool.free_handle(handle);
}
}
}
unsafe fn create_sampler(
&self,
desc: &crate::SamplerDescriptor,
) -> Result<super::Sampler, crate::DeviceError> {
let handle = self.sampler_pool.lock().alloc_handle();
let reduction = match desc.compare {
Some(_) => d3d12_ty::D3D12_FILTER_REDUCTION_TYPE_COMPARISON,
None => d3d12_ty::D3D12_FILTER_REDUCTION_TYPE_STANDARD,
};
let mut filter = conv::map_filter_mode(desc.min_filter) << d3d12_ty::D3D12_MIN_FILTER_SHIFT
| conv::map_filter_mode(desc.mag_filter) << d3d12_ty::D3D12_MAG_FILTER_SHIFT
| conv::map_filter_mode(desc.mipmap_filter) << d3d12_ty::D3D12_MIP_FILTER_SHIFT
| reduction << d3d12_ty::D3D12_FILTER_REDUCTION_TYPE_SHIFT;
if desc.anisotropy_clamp != 1 {
filter |= d3d12_ty::D3D12_FILTER_ANISOTROPIC;
};
let border_color = conv::map_border_color(desc.border_color);
self.raw.create_sampler(
handle.raw,
filter,
[
conv::map_address_mode(desc.address_modes[0]),
conv::map_address_mode(desc.address_modes[1]),
conv::map_address_mode(desc.address_modes[2]),
],
0.0,
desc.anisotropy_clamp as u32,
conv::map_comparison(desc.compare.unwrap_or(wgt::CompareFunction::Always)),
border_color,
desc.lod_clamp.clone(),
);
Ok(super::Sampler { handle })
}
unsafe fn destroy_sampler(&self, sampler: super::Sampler) {
self.sampler_pool.lock().free_handle(sampler.handle);
}
unsafe fn create_command_encoder(
&self,
desc: &crate::CommandEncoderDescriptor<super::Api>,
) -> Result<super::CommandEncoder, crate::DeviceError> {
let allocator = self
.raw
.create_command_allocator(d3d12::CmdListType::Direct)
.into_device_result("Command allocator creation")?;
if let Some(label) = desc.label {
let cwstr = conv::map_label(label);
unsafe { allocator.SetName(cwstr.as_ptr()) };
}
Ok(super::CommandEncoder {
allocator,
device: self.raw.clone(),
shared: Arc::clone(&self.shared),
null_rtv_handle: self.null_rtv_handle,
list: None,
free_lists: Vec::new(),
pass: super::PassState::new(),
temp: super::Temp::default(),
end_of_pass_timer_query: None,
})
}
unsafe fn destroy_command_encoder(&self, encoder: super::CommandEncoder) {
if let Some(list) = encoder.list {
list.close();
}
}
unsafe fn create_bind_group_layout(
&self,
desc: &crate::BindGroupLayoutDescriptor,
) -> Result<super::BindGroupLayout, crate::DeviceError> {
let (mut num_buffer_views, mut num_samplers, mut num_texture_views) = (0, 0, 0);
for entry in desc.entries.iter() {
let count = entry.count.map_or(1, NonZeroU32::get);
match entry.ty {
wgt::BindingType::Buffer {
has_dynamic_offset: true,
..
} => {}
wgt::BindingType::Buffer { .. } => num_buffer_views += count,
wgt::BindingType::Texture { .. } | wgt::BindingType::StorageTexture { .. } => {
num_texture_views += count
}
wgt::BindingType::Sampler { .. } => num_samplers += count,
}
}
let num_views = num_buffer_views + num_texture_views;
Ok(super::BindGroupLayout {
entries: desc.entries.to_vec(),
cpu_heap_views: if num_views != 0 {
let heap = descriptor::CpuHeap::new(
self.raw.clone(),
d3d12::DescriptorHeapType::CbvSrvUav,
num_views,
)?;
Some(heap)
} else {
None
},
cpu_heap_samplers: if num_samplers != 0 {
let heap = descriptor::CpuHeap::new(
self.raw.clone(),
d3d12::DescriptorHeapType::Sampler,
num_samplers,
)?;
Some(heap)
} else {
None
},
copy_counts: vec![1; num_views.max(num_samplers) as usize],
})
}
unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) {}
unsafe fn create_pipeline_layout(
&self,
desc: &crate::PipelineLayoutDescriptor<super::Api>,
) -> Result<super::PipelineLayout, crate::DeviceError> {
use naga::back::hlsl;
// Pipeline layouts are implemented as RootSignature for D3D12.
//
// Push Constants are implemented as root constants.
//
// Each descriptor set layout will be one table entry of the root signature.
// We have the additional restriction that SRV/CBV/UAV and samplers need to be
// separated, so each set layout will actually occupy up to 2 entries!
// SRV/CBV/UAV tables are added to the signature first, then Sampler tables,
// and finally dynamic uniform descriptors.
//
// Buffers with dynamic offsets are implemented as root descriptors.
// This is easier than trying to patch up the offset on the shader side.
//
// Root signature layout:
// Root Constants: Parameter=0, Space=0
// ...
// (bind group [0]) - Space=0
// View descriptor table, if any
// Sampler descriptor table, if any
// Root descriptors (for dynamic offset buffers)
// (bind group [1]) - Space=0
// ...
// (bind group [2]) - Space=0
// Special constant buffer: Space=0
//TODO: put lower bind group indices futher down the root signature. See:
// https://microsoft.github.io/DirectX-Specs/d3d/ResourceBinding.html#binding-model
// Currently impossible because wgpu-core only re-binds the descriptor sets based
// on Vulkan-like layout compatibility rules.
fn native_binding(bt: &hlsl::BindTarget) -> d3d12::Binding {
d3d12::Binding {
space: bt.space as u32,
register: bt.register,
}
}
log::debug!(
"Creating Root Signature '{}'",
desc.label.unwrap_or_default()
);
let mut binding_map = hlsl::BindingMap::default();
let (mut bind_cbv, mut bind_srv, mut bind_uav, mut bind_sampler) = (
hlsl::BindTarget::default(),
hlsl::BindTarget::default(),
hlsl::BindTarget::default(),
hlsl::BindTarget::default(),
);
let mut parameters = Vec::new();
let mut push_constants_target = None;
let mut root_constant_info = None;
let mut pc_start = u32::MAX;
let mut pc_end = u32::MIN;
for pc in desc.push_constant_ranges.iter() {
pc_start = pc_start.min(pc.range.start);
pc_end = pc_end.max(pc.range.end);
}
if pc_start != u32::MAX && pc_end != u32::MIN {
let parameter_index = parameters.len();
let size = (pc_end - pc_start) / 4;
log::debug!(
"\tParam[{}] = push constant (count = {})",
parameter_index,
size,
);
parameters.push(d3d12::RootParameter::constants(
d3d12::ShaderVisibility::All,
native_binding(&bind_cbv),
size,
));
let binding = bind_cbv.clone();
bind_cbv.register += 1;
root_constant_info = Some(super::RootConstantInfo {
root_index: parameter_index as u32,
range: (pc_start / 4)..(pc_end / 4),
});
push_constants_target = Some(binding);
bind_cbv.space += 1;
}
// Collect the whole number of bindings we will create upfront.
// It allows us to preallocate enough storage to avoid reallocation,
// which could cause invalid pointers.
let total_non_dynamic_entries = desc
.bind_group_layouts
.iter()
.flat_map(|bgl| {
bgl.entries.iter().map(|entry| match entry.ty {
wgt::BindingType::Buffer {
has_dynamic_offset: true,
..
} => 0,
_ => 1,
})
})
.sum();
let mut ranges = Vec::with_capacity(total_non_dynamic_entries);
let mut bind_group_infos =
arrayvec::ArrayVec::<super::BindGroupInfo, { crate::MAX_BIND_GROUPS }>::default();
for (index, bgl) in desc.bind_group_layouts.iter().enumerate() {
let mut info = super::BindGroupInfo {
tables: super::TableTypes::empty(),
base_root_index: parameters.len() as u32,
dynamic_buffers: Vec::new(),
};
let mut visibility_view_static = wgt::ShaderStages::empty();
let mut visibility_view_dynamic = wgt::ShaderStages::empty();
let mut visibility_sampler = wgt::ShaderStages::empty();
for entry in bgl.entries.iter() {
match entry.ty {
wgt::BindingType::Sampler { .. } => visibility_sampler |= entry.visibility,
wgt::BindingType::Buffer {
has_dynamic_offset: true,
..
} => visibility_view_dynamic |= entry.visibility,
_ => visibility_view_static |= entry.visibility,
}
}
// SRV/CBV/UAV descriptor tables
let mut range_base = ranges.len();
for entry in bgl.entries.iter() {
let range_ty = match entry.ty {
wgt::BindingType::Buffer {
has_dynamic_offset: true,
..
} => continue,
ref other => conv::map_binding_type(other),
};
let bt = match range_ty {
d3d12::DescriptorRangeType::CBV => &mut bind_cbv,
d3d12::DescriptorRangeType::SRV => &mut bind_srv,
d3d12::DescriptorRangeType::UAV => &mut bind_uav,
d3d12::DescriptorRangeType::Sampler => continue,
};
binding_map.insert(
naga::ResourceBinding {
group: index as u32,
binding: entry.binding,
},
hlsl::BindTarget {
binding_array_size: entry.count.map(NonZeroU32::get),
..bt.clone()
},
);
ranges.push(d3d12::DescriptorRange::new(
range_ty,
entry.count.map_or(1, |count| count.get()),
native_binding(bt),
d3d12_ty::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
));
bt.register += entry.count.map(NonZeroU32::get).unwrap_or(1);
}
if ranges.len() > range_base {
log::debug!(
"\tParam[{}] = views (vis = {:?}, count = {})",
parameters.len(),
visibility_view_static,
ranges.len() - range_base,
);
parameters.push(d3d12::RootParameter::descriptor_table(
conv::map_visibility(visibility_view_static),
&ranges[range_base..],
));
info.tables |= super::TableTypes::SRV_CBV_UAV;
}
// Sampler descriptor tables
range_base = ranges.len();
for entry in bgl.entries.iter() {
let range_ty = match entry.ty {
wgt::BindingType::Sampler { .. } => d3d12::DescriptorRangeType::Sampler,
_ => continue,
};
binding_map.insert(
naga::ResourceBinding {
group: index as u32,
binding: entry.binding,
},
hlsl::BindTarget {
binding_array_size: entry.count.map(NonZeroU32::get),
..bind_sampler.clone()
},
);
ranges.push(d3d12::DescriptorRange::new(
range_ty,
entry.count.map_or(1, |count| count.get()),
native_binding(&bind_sampler),
d3d12_ty::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
));
bind_sampler.register += entry.count.map(NonZeroU32::get).unwrap_or(1);
}
if ranges.len() > range_base {
log::debug!(
"\tParam[{}] = samplers (vis = {:?}, count = {})",
parameters.len(),
visibility_sampler,
ranges.len() - range_base,
);
parameters.push(d3d12::RootParameter::descriptor_table(
conv::map_visibility(visibility_sampler),
&ranges[range_base..],
));
info.tables |= super::TableTypes::SAMPLERS;
}
// Root (dynamic) descriptor tables
let dynamic_buffers_visibility = conv::map_visibility(visibility_view_dynamic);
for entry in bgl.entries.iter() {
let buffer_ty = match entry.ty {
wgt::BindingType::Buffer {
has_dynamic_offset: true,
ty,
..
} => ty,
_ => continue,
};
let (kind, parameter_ty, bt) = match buffer_ty {
wgt::BufferBindingType::Uniform => (
super::BufferViewKind::Constant,
d3d12_ty::D3D12_ROOT_PARAMETER_TYPE_CBV,
&mut bind_cbv,
),
wgt::BufferBindingType::Storage { read_only: true } => (
super::BufferViewKind::ShaderResource,
d3d12_ty::D3D12_ROOT_PARAMETER_TYPE_SRV,
&mut bind_srv,
),
wgt::BufferBindingType::Storage { read_only: false } => (
super::BufferViewKind::UnorderedAccess,
d3d12_ty::D3D12_ROOT_PARAMETER_TYPE_UAV,
&mut bind_uav,
),
};
binding_map.insert(
naga::ResourceBinding {
group: index as u32,
binding: entry.binding,
},
hlsl::BindTarget {
binding_array_size: entry.count.map(NonZeroU32::get),
..bt.clone()
},
);
info.dynamic_buffers.push(kind);
log::debug!(
"\tParam[{}] = dynamic {:?} (vis = {:?})",
parameters.len(),
buffer_ty,
dynamic_buffers_visibility,
);
parameters.push(d3d12::RootParameter::descriptor(
parameter_ty,
dynamic_buffers_visibility,
native_binding(bt),
));
bt.register += entry.count.map_or(1, NonZeroU32::get);
}
bind_group_infos.push(info);
}
// Ensure that we didn't reallocate!
debug_assert_eq!(ranges.len(), total_non_dynamic_entries);
let (special_constants_root_index, special_constants_binding) = if desc.flags.intersects(
crate::PipelineLayoutFlags::BASE_VERTEX_INSTANCE
| crate::PipelineLayoutFlags::NUM_WORK_GROUPS,
) {
let parameter_index = parameters.len();
log::debug!("\tParam[{}] = special", parameter_index);
parameters.push(d3d12::RootParameter::constants(
d3d12::ShaderVisibility::All, // really needed for VS and CS only
native_binding(&bind_cbv),
3, // 0 = base vertex, 1 = base instance, 2 = other
));
let binding = bind_cbv.clone();
bind_cbv.register += 1;
(Some(parameter_index as u32), Some(binding))
} else {
(None, None)