dxwr 0.4.3

Direct3D12 and DXGI wrapper library
Documentation
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
use super::*;
use windows::Win32::Graphics::Direct3D::*;
use windows::Win32::Graphics::Direct3D12::*;

#[derive(Clone, Debug)]
#[repr(transparent)]
pub struct DescriptorRange(D3D12_DESCRIPTOR_RANGE);

impl DescriptorRange {
    #[inline]
    pub fn new(t: D3D12_DESCRIPTOR_RANGE_TYPE) -> Self {
        Self(D3D12_DESCRIPTOR_RANGE {
            RangeType: t,
            OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
            ..Default::default()
        })
    }

    #[inline]
    pub fn cbv() -> Self {
        Self(D3D12_DESCRIPTOR_RANGE {
            RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
            OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
            ..Default::default()
        })
    }

    #[inline]
    pub fn srv() -> Self {
        Self(D3D12_DESCRIPTOR_RANGE {
            RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
            OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
            ..Default::default()
        })
    }

    #[inline]
    pub fn uav() -> Self {
        Self(D3D12_DESCRIPTOR_RANGE {
            RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
            OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
            ..Default::default()
        })
    }

    #[inline]
    pub fn sampler() -> Self {
        Self(D3D12_DESCRIPTOR_RANGE {
            RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
            OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
            ..Default::default()
        })
    }

    #[inline]
    pub fn num_descriptors(mut self, n: u32) -> Self {
        self.0.NumDescriptors = n;
        self
    }

    #[inline]
    pub fn base_shader_register(mut self, reg: u32) -> Self {
        self.0.BaseShaderRegister = reg;
        self
    }

    #[inline]
    pub fn register_space(mut self, space: u32) -> Self {
        self.0.RegisterSpace = space;
        self
    }

    #[inline]
    pub fn offset_in_descriptors_from_table_start(mut self, offset: Option<u32>) -> Self {
        self.0.OffsetInDescriptorsFromTableStart =
            offset.unwrap_or(D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND);
        self
    }
}

pub trait RootParameterType {
    const VALUE: D3D12_ROOT_PARAMETER_TYPE;
}

pub mod root_parameter_type {
    use super::*;

    pub struct DescriptorTable;

    impl RootParameterType for DescriptorTable {
        const VALUE: D3D12_ROOT_PARAMETER_TYPE = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
    }

    pub struct Constants32bit;

    impl RootParameterType for Constants32bit {
        const VALUE: D3D12_ROOT_PARAMETER_TYPE = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
    }

    pub struct Cbv;

    impl RootParameterType for Cbv {
        const VALUE: D3D12_ROOT_PARAMETER_TYPE = D3D12_ROOT_PARAMETER_TYPE_CBV;
    }

    pub struct Srv;

    impl RootParameterType for Srv {
        const VALUE: D3D12_ROOT_PARAMETER_TYPE = D3D12_ROOT_PARAMETER_TYPE_SRV;
    }

    pub struct Uav;

    impl RootParameterType for Uav {
        const VALUE: D3D12_ROOT_PARAMETER_TYPE = D3D12_ROOT_PARAMETER_TYPE_UAV;
    }
}

#[derive(Clone)]
pub struct RootParameter<T = ()> {
    param: D3D12_ROOT_PARAMETER,
    ranges: Option<Vec<D3D12_DESCRIPTOR_RANGE>>,
    _t: std::marker::PhantomData<T>,
}

impl RootParameter<()> {
    #[inline]
    pub fn new<T>(_t: T) -> RootParameter<T>
    where
        T: RootParameterType,
    {
        RootParameter {
            param: D3D12_ROOT_PARAMETER {
                ParameterType: T::VALUE,
                ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
                ..Default::default()
            },
            ranges: None,
            _t: std::marker::PhantomData,
        }
    }

    #[inline]
    pub fn cbv() -> RootParameter<root_parameter_type::Cbv> {
        Self::new(root_parameter_type::Cbv)
    }

    #[inline]
    pub fn srv() -> RootParameter<root_parameter_type::Srv> {
        Self::new(root_parameter_type::Srv)
    }

    #[inline]
    pub fn uav() -> RootParameter<root_parameter_type::Uav> {
        Self::new(root_parameter_type::Uav)
    }

    #[inline]
    pub fn constants_32bit() -> RootParameter<root_parameter_type::Constants32bit> {
        Self::new(root_parameter_type::Constants32bit)
    }

    #[inline]
    pub fn descriptor_table() -> RootParameter<root_parameter_type::DescriptorTable> {
        Self::new(root_parameter_type::DescriptorTable)
    }
}

impl<T> RootParameter<T>
where
    T: RootParameterType,
{
    #[inline]
    pub fn shader_visibility(mut self, visibility: D3D12_SHADER_VISIBILITY) -> Self {
        self.param.ShaderVisibility = visibility;
        self
    }
}

impl RootParameter<root_parameter_type::DescriptorTable> {
    #[inline]
    pub fn ranges(
        self,
        ranges: impl IntoIterator<Item = DescriptorRange>,
    ) -> RootParameter<root_parameter_type::DescriptorTable> {
        let ranges = ranges
            .into_iter()
            .map(|range| range.0)
            .collect::<Vec<D3D12_DESCRIPTOR_RANGE>>();
        RootParameter {
            param: D3D12_ROOT_PARAMETER {
                ParameterType: self.param.ParameterType,
                ShaderVisibility: self.param.ShaderVisibility,
                Anonymous: D3D12_ROOT_PARAMETER_0 {
                    DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE {
                        NumDescriptorRanges: ranges.len() as u32,
                        pDescriptorRanges: ranges.as_ptr(),
                    },
                },
            },
            ranges: Some(ranges),
            _t: std::marker::PhantomData,
        }
    }
}

impl RootParameter<root_parameter_type::Constants32bit> {
    #[inline]
    pub fn shader_register(mut self, reg: u32) -> Self {
        self.param.Anonymous.Constants.ShaderRegister = reg;
        self
    }

    #[inline]
    pub fn register_space(mut self, space: u32) -> Self {
        self.param.Anonymous.Constants.RegisterSpace = space;
        self
    }

    #[inline]
    pub fn num_32bit_values(mut self, n: u32) -> Self {
        self.param.Anonymous.Constants.Num32BitValues = n;
        self
    }
}

impl RootParameter<root_parameter_type::Cbv> {
    #[inline]
    pub fn shader_register(mut self, reg: u32) -> Self {
        self.param.Anonymous.Descriptor.ShaderRegister = reg;
        self
    }

    #[inline]
    pub fn register_space(mut self, space: u32) -> Self {
        self.param.Anonymous.Descriptor.RegisterSpace = space;
        self
    }
}

impl RootParameter<root_parameter_type::Srv> {
    #[inline]
    pub fn shader_register(mut self, reg: u32) -> Self {
        self.param.Anonymous.Descriptor.ShaderRegister = reg;
        self
    }

    #[inline]
    pub fn register_space(mut self, space: u32) -> Self {
        self.param.Anonymous.Descriptor.RegisterSpace = space;
        self
    }
}

impl RootParameter<root_parameter_type::Uav> {
    #[inline]
    pub fn shader_register(mut self, reg: u32) -> Self {
        self.param.Anonymous.Descriptor.ShaderRegister = reg;
        self
    }

    #[inline]
    pub fn register_space(mut self, space: u32) -> Self {
        self.param.Anonymous.Descriptor.RegisterSpace = space;
        self
    }
}

impl<T> From<RootParameter<T>> for RootParameter<()>
where
    T: RootParameterType,
{
    fn from(value: RootParameter<T>) -> Self {
        Self {
            param: value.param,
            ranges: value.ranges,
            _t: std::marker::PhantomData,
        }
    }
}

impl<T> std::fmt::Debug for RootParameter<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RootParameter {{ {:?} .. }}", self.ranges)
    }
}

#[derive(Clone, Debug)]
#[repr(transparent)]
pub struct StaticSamplerDesc(D3D12_STATIC_SAMPLER_DESC);

impl StaticSamplerDesc {
    #[inline]
    pub fn new() -> Self {
        Self(D3D12_STATIC_SAMPLER_DESC {
            Filter: D3D12_FILTER_ANISOTROPIC,
            AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
            AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
            AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
            MaxAnisotropy: 16,
            ComparisonFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
            BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK,
            MaxLOD: f32::MAX,
            ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
            ..Default::default()
        })
    }

    #[inline]
    pub fn filter(mut self, filter: D3D12_FILTER) -> Self {
        self.0.Filter = filter;
        self
    }

    #[inline]
    pub fn address_u(mut self, mode: D3D12_TEXTURE_ADDRESS_MODE) -> Self {
        self.0.AddressU = mode;
        self
    }

    #[inline]
    pub fn address_v(mut self, mode: D3D12_TEXTURE_ADDRESS_MODE) -> Self {
        self.0.AddressV = mode;
        self
    }

    #[inline]
    pub fn address_w(mut self, mode: D3D12_TEXTURE_ADDRESS_MODE) -> Self {
        self.0.AddressW = mode;
        self
    }

    #[inline]
    pub fn mip_lod_bias(mut self, value: f32) -> Self {
        self.0.MipLODBias = value;
        self
    }

    #[inline]
    pub fn max_anisotropy(mut self, value: u32) -> Self {
        self.0.MaxAnisotropy = value;
        self
    }

    #[inline]
    pub fn comparison_func(mut self, func: D3D12_COMPARISON_FUNC) -> Self {
        self.0.ComparisonFunc = func;
        self
    }

    #[inline]
    pub fn border_color(mut self, color: D3D12_STATIC_BORDER_COLOR) -> Self {
        self.0.BorderColor = color;
        self
    }

    #[inline]
    pub fn min_lod(mut self, lod: f32) -> Self {
        self.0.MinLOD = lod;
        self
    }

    #[inline]
    pub fn max_lod(mut self, lod: f32) -> Self {
        self.0.MaxLOD = lod;
        self
    }

    #[inline]
    pub fn shader_register(mut self, reg: u32) -> Self {
        self.0.ShaderRegister = reg;
        self
    }

    #[inline]
    pub fn register_space(mut self, space: u32) -> Self {
        self.0.RegisterSpace = space;
        self
    }

    #[inline]
    pub fn shader_visibility(mut self, visibility: D3D12_SHADER_VISIBILITY) -> Self {
        self.0.ShaderVisibility = visibility;
        self
    }
}

impl Default for StaticSamplerDesc {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Clone)]
pub struct RootSignatureDesc<'params, 'samplers> {
    params: Option<&'params [RootParameter<()>]>,
    samplers: Option<&'samplers [StaticSamplerDesc]>,
    flags: D3D12_ROOT_SIGNATURE_FLAGS,
}

impl<'params, 'samplers> RootSignatureDesc<'params, 'samplers> {
    #[inline]
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            params: None,
            samplers: None,
            flags: D3D12_ROOT_SIGNATURE_FLAG_NONE,
        }
    }

    #[inline]
    pub fn parameters<'a>(
        self,
        params: &'a [RootParameter<()>],
    ) -> RootSignatureDesc<'a, 'samplers> {
        RootSignatureDesc {
            params: Some(params),
            samplers: self.samplers,
            flags: self.flags,
        }
    }

    #[inline]
    pub fn static_samplers<'b>(
        self,
        samplers: &'b [StaticSamplerDesc],
    ) -> RootSignatureDesc<'params, 'b> {
        RootSignatureDesc {
            params: self.params,
            samplers: Some(samplers),
            flags: self.flags,
        }
    }

    #[inline]
    pub fn flags(mut self, flags: D3D12_ROOT_SIGNATURE_FLAGS) -> Self {
        self.flags = flags;
        self
    }
}

pub struct Builder<Desc = ()> {
    device: ID3D12Device,
    node_mask: u32,
    name: Option<String>,
    desc: Desc,
}

impl Builder<()> {
    fn new<T>(device: &T) -> Self
    where
        T: Into<ID3D12Device> + Clone,
    {
        let device: ID3D12Device = device.clone().into();
        Self {
            device,
            node_mask: 0,
            name: None,
            desc: (),
        }
    }
}

impl<Desc> Builder<Desc> {
    #[inline]
    pub fn node_mask(mut self, mask: u32) -> Self {
        self.node_mask = mask;
        self
    }

    #[inline]
    pub fn name(mut self, name: impl AsRef<str>) -> Self {
        self.name = Some(name.as_ref().to_string());
        self
    }

    #[inline]
    pub fn desc<'a, 'p, 's>(
        self,
        desc: &'a RootSignatureDesc<'p, 's>,
    ) -> Builder<&'a RootSignatureDesc<'p, 's>> {
        Builder {
            device: self.device,
            node_mask: self.node_mask,
            name: self.name,
            desc,
        }
    }
}

impl<'a, 'p, 's> Builder<&'a RootSignatureDesc<'p, 's>> {
    #[inline]
    pub fn build(self) -> windows::core::Result<RootSignature> {
        let parameters = self
            .desc
            .params
            .as_ref()
            .map(|params| params.iter().map(|p| p.param).collect::<Vec<_>>())
            .unwrap_or_default();
        let samplers = self
            .desc
            .samplers
            .as_ref()
            .map(|samplers| samplers.to_vec())
            .unwrap_or_default();
        let desc = D3D12_ROOT_SIGNATURE_DESC {
            NumParameters: parameters.len() as u32,
            pParameters: parameters.as_ptr(),
            NumStaticSamplers: samplers.len() as u32,
            pStaticSamplers: samplers.as_ptr() as *const D3D12_STATIC_SAMPLER_DESC,
            Flags: self.desc.flags,
        };
        let blob = unsafe {
            let mut blob: Option<ID3DBlob> = None;
            D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)
                .map(|_| blob.unwrap())?
        };
        let handle = unsafe {
            let data = std::slice::from_raw_parts(
                blob.GetBufferPointer() as *const u8,
                blob.GetBufferSize(),
            );
            self.device.CreateRootSignature(self.node_mask, data)?
        };
        let name = self.name.as_ref().map(|n| Name::new(&handle, n));
        Ok(RootSignature { handle, name })
    }
}

#[derive(Clone, Debug)]
pub struct RootSignature {
    handle: ID3D12RootSignature,
    name: Option<Name>,
}

impl RootSignature {
    #[inline]
    #[allow(clippy::new_ret_no_self)]
    pub fn new(device: &Device) -> Builder {
        Builder::new(device.handle())
    }

    #[inline]
    pub fn handle(&self) -> &ID3D12RootSignature {
        &self.handle
    }

    #[inline]
    pub fn name(&self) -> Option<&str> {
        self.name.as_ref().map(|n| n.as_str())
    }

    #[inline]
    pub fn set_name(&mut self, name: impl AsRef<str>) {
        self.name = Some(Name::new(self.handle(), name));
    }
}