-
Notifications
You must be signed in to change notification settings - Fork 960
/
lib.rs
3919 lines (3714 loc) · 158 KB
/
lib.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
/*! This library describes the API surface of WebGPU that is agnostic of the backend.
* This API is used for targeting both Web and Native.
*/
#![allow(
// We don't use syntax sugar where it's not necessary.
clippy::match_like_matches_macro,
)]
#![warn(missing_docs)]
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{num::NonZeroU32, ops::Range};
/// Integral type used for buffer offsets.
pub type BufferAddress = u64;
/// Integral type used for buffer slice sizes.
pub type BufferSize = std::num::NonZeroU64;
/// Integral type used for binding locations in shaders.
pub type ShaderLocation = u32;
/// Integral type used for dynamic bind group offsets.
pub type DynamicOffset = u32;
/// Buffer-Texture copies must have [`bytes_per_row`] aligned to this number.
///
/// This doesn't apply to [`Queue::write_texture`].
///
/// [`bytes_per_row`]: ImageDataLayout::bytes_per_row
pub const COPY_BYTES_PER_ROW_ALIGNMENT: u32 = 256;
/// An offset into the query resolve buffer has to be aligned to this.
pub const QUERY_RESOLVE_BUFFER_ALIGNMENT: BufferAddress = 256;
/// Buffer to buffer copy as well as buffer clear offsets and sizes must be aligned to this number.
pub const COPY_BUFFER_ALIGNMENT: BufferAddress = 4;
/// Size to align mappings.
pub const MAP_ALIGNMENT: BufferAddress = 8;
/// Vertex buffer strides have to be aligned to this number.
pub const VERTEX_STRIDE_ALIGNMENT: BufferAddress = 4;
/// Alignment all push constants need
pub const PUSH_CONSTANT_ALIGNMENT: u32 = 4;
/// Maximum queries in a query set
pub const QUERY_SET_MAX_QUERIES: u32 = 8192;
/// Size of a single piece of query data.
pub const QUERY_SIZE: u32 = 8;
/// Backends supported by wgpu.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "trace", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum Backend {
/// Dummy backend, used for testing.
Empty = 0,
/// Vulkan API
Vulkan = 1,
/// Metal API (Apple platforms)
Metal = 2,
/// Direct3D-12 (Windows)
Dx12 = 3,
/// Direct3D-11 (Windows)
Dx11 = 4,
/// OpenGL ES-3 (Linux, Android)
Gl = 5,
/// WebGPU in the browser
BrowserWebGpu = 6,
}
/// Power Preference when choosing a physical adapter.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "trace", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum PowerPreference {
/// Adapter that uses the least possible power. This is often an integrated GPU.
LowPower = 0,
/// Adapter that has the highest performance. This is often a discrete GPU.
HighPerformance = 1,
}
impl Default for PowerPreference {
fn default() -> Self {
Self::LowPower
}
}
bitflags::bitflags! {
/// Represents the backends that wgpu will use.
#[repr(transparent)]
pub struct Backends: u32 {
/// Supported on Windows, Linux/Android, and macOS/iOS via Vulkan Portability (with the Vulkan feature enabled)
const VULKAN = 1 << Backend::Vulkan as u32;
/// Currently unsupported
const GL = 1 << Backend::Gl as u32;
/// Supported on macOS/iOS
const METAL = 1 << Backend::Metal as u32;
/// Supported on Windows 10
const DX12 = 1 << Backend::Dx12 as u32;
/// Supported on Windows 7+
const DX11 = 1 << Backend::Dx11 as u32;
/// Supported when targeting the web through webassembly
const BROWSER_WEBGPU = 1 << Backend::BrowserWebGpu as u32;
/// All the apis that wgpu offers first tier of support for.
///
/// Vulkan + Metal + DX12 + Browser WebGPU
const PRIMARY = Self::VULKAN.bits
| Self::METAL.bits
| Self::DX12.bits
| Self::BROWSER_WEBGPU.bits;
/// All the apis that wgpu offers second tier of support for. These may
/// be unsupported/still experimental.
///
/// OpenGL + DX11
const SECONDARY = Self::GL.bits | Self::DX11.bits;
}
}
#[cfg(feature = "bitflags_serde_shim")]
bitflags_serde_shim::impl_serde_for_bitflags!(Backends);
impl From<Backend> for Backends {
fn from(backend: Backend) -> Self {
Self::from_bits(1 << backend as u32).unwrap()
}
}
/// Options for requesting adapter.
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "trace", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct RequestAdapterOptions<S> {
/// Power preference for the adapter.
pub power_preference: PowerPreference,
/// Indicates that only a fallback adapter can be returned. This is generally a "software"
/// implementation on the system.
pub force_fallback_adapter: bool,
/// Surface that is required to be presentable with the requested adapter. This does not
/// create the surface, only guarantees that the adapter can present to said surface.
pub compatible_surface: Option<S>,
}
impl<S> Default for RequestAdapterOptions<S> {
fn default() -> Self {
Self {
power_preference: PowerPreference::default(),
force_fallback_adapter: false,
compatible_surface: None,
}
}
}
//TODO: make robust resource access configurable
bitflags::bitflags! {
/// Features that are not guaranteed to be supported.
///
/// These are either part of the webgpu standard, or are extension features supported by
/// wgpu when targeting native.
///
/// If you want to use a feature, you need to first verify that the adapter supports
/// the feature. If the adapter does not support the feature, requesting a device with it enabled
/// will panic.
#[repr(transparent)]
#[derive(Default)]
pub struct Features: u64 {
/// By default, polygon depth is clipped to 0-1 range before/during rasterization.
/// Anything outside of that range is rejected, and respective fragments are not touched.
///
/// With this extension, we can disabling clipping. That allows
/// shadow map occluders to be rendered into a tighter depth range.
///
/// Supported platforms:
/// - desktops
/// - some mobile chips
///
/// This is a web and native feature.
const DEPTH_CLIP_CONTROL = 1 << 0;
/// Enables BCn family of compressed textures. All BCn textures use 4x4 pixel blocks
/// with 8 or 16 bytes per block.
///
/// Compressed textures sacrifice some quality in exchange for significantly reduced
/// bandwidth usage.
///
/// Support for this feature guarantees availability of [`TextureUsages::COPY_SRC | TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING`] for BCn formats.
/// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] may enable additional usages.
///
/// Supported Platforms:
/// - desktops
///
/// This is a web and native feature.
const TEXTURE_COMPRESSION_BC = 1 << 1;
/// Allows non-zero value for the "first instance" in indirect draw calls.
///
/// Supported Platforms:
/// - Vulkan (mostly)
/// - DX12
/// - Metal
///
/// This is a web and native feature.
const INDIRECT_FIRST_INSTANCE = 1 << 2;
/// Enables use of Timestamp Queries. These queries tell the current gpu timestamp when
/// all work before the query is finished. Call [`CommandEncoder::write_timestamp`],
/// [`RenderPassEncoder::write_timestamp`], or [`ComputePassEncoder::write_timestamp`] to
/// write out a timestamp.
///
/// They must be resolved using [`CommandEncoder::resolve_query_sets`] into a buffer,
/// then the result must be multiplied by the timestamp period [`Device::get_timestamp_period`]
/// to get the timestamp in nanoseconds. Multiple timestamps can then be diffed to get the
/// time for operations between them to finish.
///
/// Due to wgpu-hal limitations, this is only supported on vulkan for now.
///
/// Supported Platforms:
/// - Vulkan (works)
/// - DX12 (works)
///
/// This is a web and native feature.
const TIMESTAMP_QUERY = 1 << 3;
/// Enables use of Pipeline Statistics Queries. These queries tell the count of various operations
/// performed between the start and stop call. Call [`RenderPassEncoder::begin_pipeline_statistics_query`] to start
/// a query, then call [`RenderPassEncoder::end_pipeline_statistics_query`] to stop one.
///
/// They must be resolved using [`CommandEncoder::resolve_query_sets`] into a buffer.
/// The rules on how these resolve into buffers are detailed in the documentation for [`PipelineStatisticsTypes`].
///
/// Due to wgpu-hal limitations, this is only supported on vulkan for now.
///
/// Supported Platforms:
/// - Vulkan (works)
/// - DX12 (works)
///
/// This is a web and native feature.
const PIPELINE_STATISTICS_QUERY = 1 << 4;
/// Webgpu only allows the MAP_READ and MAP_WRITE buffer usage to be matched with
/// COPY_DST and COPY_SRC respectively. This removes this requirement.
///
/// This is only beneficial on systems that share memory between CPU and GPU. If enabled
/// on a system that doesn't, this can severely hinder performance. Only use if you understand
/// the consequences.
///
/// Supported platforms:
/// - All
///
/// This is a native only feature.
const MAPPABLE_PRIMARY_BUFFERS = 1 << 16;
/// Allows the user to create uniform arrays of textures in shaders:
///
/// eg. `uniform texture2D textures[10]`.
///
/// If [`Features::STORAGE_RESOURCE_BINDING_ARRAY`] is supported as well as this, the user
/// may also create uniform arrays of storage textures.
///
/// eg. `uniform image2D textures[10]`.
///
/// This capability allows them to exist and to be indexed by dynamically uniform
/// values.
///
/// Supported platforms:
/// - DX12
/// - Metal (with MSL 2.0+ on macOS 10.13+)
/// - Vulkan
///
/// This is a native only feature.
const TEXTURE_BINDING_ARRAY = 1 << 17;
/// Allows the user to create arrays of buffers in shaders:
///
/// eg. `uniform myBuffer { .... } buffer_array[10]`.
///
/// This capability allows them to exist and to be indexed by dynamically uniform
/// values.
///
/// If [`Features::STORAGE_RESOURCE_BINDING_ARRAY`] is supported as well as this, the user
/// may also create arrays of storage buffers.
///
/// eg. `buffer myBuffer { ... } buffer_array[10]`
///
/// Supported platforms:
/// - DX12
/// - Vulkan
///
/// This is a native only feature.
const BUFFER_BINDING_ARRAY = 1 << 18;
/// Allows the user to create uniform arrays of storage buffers or textures in shaders,
/// if resp. [`Features::BUFFER_BINDING_ARRAY`] or [`Features::TEXTURE_BINDING_ARRAY`]
/// is supported.
///
/// This capability allows them to exist and to be indexed by dynamically uniform
/// values.
///
/// Supported platforms:
/// - Metal (with MSL 2.2+ on macOS 10.13+)
/// - Vulkan
///
/// This is a native only feature.
const STORAGE_RESOURCE_BINDING_ARRAY = 1 << 19;
/// Allows shaders to index sampled texture and storage buffer resource arrays with dynamically non-uniform values:
///
/// eg. `texture_array[vertex_data]`
///
/// In order to use this capability, the corresponding GLSL extension must be enabled like so:
///
/// `#extension GL_EXT_nonuniform_qualifier : require`
///
/// and then used either as `nonuniformEXT` qualifier in variable declaration:
///
/// eg. `layout(location = 0) nonuniformEXT flat in int vertex_data;`
///
/// or as `nonuniformEXT` constructor:
///
/// eg. `texture_array[nonuniformEXT(vertex_data)]`
///
/// HLSL does not need any extension.
///
/// Supported platforms:
/// - DX12
/// - Metal (with MSL 2.0+ on macOS 10.13+)
/// - Vulkan 1.2+ (or VK_EXT_descriptor_indexing)'s shaderSampledImageArrayNonUniformIndexing & shaderStorageBufferArrayNonUniformIndexing feature)
///
/// This is a native only feature.
const SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING = 1 << 20;
/// Allows shaders to index uniform buffer and storage texture resource arrays with dynamically non-uniform values:
///
/// eg. `texture_array[vertex_data]`
///
/// In order to use this capability, the corresponding GLSL extension must be enabled like so:
///
/// `#extension GL_EXT_nonuniform_qualifier : require`
///
/// and then used either as `nonuniformEXT` qualifier in variable declaration:
///
/// eg. `layout(location = 0) nonuniformEXT flat in int vertex_data;`
///
/// or as `nonuniformEXT` constructor:
///
/// eg. `texture_array[nonuniformEXT(vertex_data)]`
///
/// HLSL does not need any extension.
///
/// Supported platforms:
/// - DX12
/// - Metal (with MSL 2.0+ on macOS 10.13+)
/// - Vulkan 1.2+ (or VK_EXT_descriptor_indexing)'s shaderUniformBufferArrayNonUniformIndexing & shaderStorageTextureArrayNonUniformIndexing feature)
///
/// This is a native only feature.
const UNIFORM_BUFFER_AND_STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING = 1 << 21;
/// Allows the user to create bind groups continaing arrays with less bindings than the BindGroupLayout.
///
/// This is a native only feature.
const PARTIALLY_BOUND_BINDING_ARRAY = 1 << 22;
/// Allows the user to create unsized uniform arrays of bindings:
///
/// eg. `uniform texture2D textures[]`.
///
/// Supported platforms:
/// - DX12
/// - Vulkan 1.2+ (or VK_EXT_descriptor_indexing)'s runtimeDescriptorArray feature
///
/// This is a native only feature.
const UNSIZED_BINDING_ARRAY = 1 << 23;
/// Allows the user to call [`RenderPass::multi_draw_indirect`] and [`RenderPass::multi_draw_indexed_indirect`].
///
/// Allows multiple indirect calls to be dispatched from a single buffer.
///
/// Supported platforms:
/// - DX12
/// - Vulkan
///
/// This is a native only feature.
const MULTI_DRAW_INDIRECT = 1 << 24;
/// Allows the user to call [`RenderPass::multi_draw_indirect_count`] and [`RenderPass::multi_draw_indexed_indirect_count`].
///
/// This allows the use of a buffer containing the actual number of draw calls.
///
/// Supported platforms:
/// - DX12
/// - Vulkan 1.2+ (or VK_KHR_draw_indirect_count)
///
/// This is a native only feature.
const MULTI_DRAW_INDIRECT_COUNT = 1 << 25;
/// Allows the use of push constants: small, fast bits of memory that can be updated
/// inside a [`RenderPass`].
///
/// Allows the user to call [`RenderPass::set_push_constants`], provide a non-empty array
/// to [`PipelineLayoutDescriptor`], and provide a non-zero limit to [`Limits::max_push_constant_size`].
///
/// A block of push constants can be declared with `layout(push_constant) uniform Name {..}` in shaders.
///
/// Supported platforms:
/// - DX12
/// - Vulkan
/// - Metal
/// - DX11 (emulated with uniforms)
/// - OpenGL (emulated with uniforms)
///
/// This is a native only feature.
const PUSH_CONSTANTS = 1 << 26;
/// Allows the use of [`AddressMode::ClampToBorder`] with a border color
/// other than [`SamplerBorderColor::Zero`].
///
/// Supported platforms:
/// - DX12
/// - Vulkan
/// - Metal (macOS 10.12+ only)
/// - DX11
/// - OpenGL
///
/// This is a web and native feature.
const ADDRESS_MODE_CLAMP_TO_BORDER = 1 << 27;
/// Allows the user to set [`PolygonMode::Line`] in [`PrimitiveState::polygon_mode`]
///
/// This allows drawing polygons/triangles as lines (wireframe) instead of filled
///
/// Supported platforms:
/// - DX12
/// - Vulkan
/// - Metal
///
/// This is a native only feature.
const POLYGON_MODE_LINE= 1 << 28;
/// Allows the user to set [`PolygonMode::Point`] in [`PrimitiveState::polygon_mode`]
///
/// This allows only drawing the vertices of polygons/triangles instead of filled
///
/// Supported platforms:
/// - DX12
/// - Vulkan
///
/// This is a native only feature.
const POLYGON_MODE_POINT = 1 << 29;
/// Enables ETC family of compressed textures. All ETC textures use 4x4 pixel blocks.
/// ETC2 RGB and RGBA1 are 8 bytes per block. RTC2 RGBA8 and EAC are 16 bytes per block.
///
/// Compressed textures sacrifice some quality in exchange for significantly reduced
/// bandwidth usage.
///
/// Support for this feature guarantees availability of [`TextureUsages::COPY_SRC | TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING`] for ETC2 formats.
/// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] may enable additional usages.
///
/// Supported Platforms:
/// - Intel/Vulkan
/// - Mobile (some)
///
/// This is a native-only feature.
const TEXTURE_COMPRESSION_ETC2 = 1 << 30;
/// Enables ASTC family of compressed textures. ASTC textures use pixel blocks varying from 4x4 to 12x12.
/// Blocks are always 16 bytes.
///
/// Compressed textures sacrifice some quality in exchange for significantly reduced
/// bandwidth usage.
///
/// Support for this feature guarantees availability of [`TextureUsages::COPY_SRC | TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING`] for ASTC formats.
/// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] may enable additional usages.
///
/// Supported Platforms:
/// - Intel/Vulkan
/// - Mobile (some)
///
/// This is a native-only feature.
const TEXTURE_COMPRESSION_ASTC_LDR = 1 << 31;
/// Enables device specific texture format features.
///
/// See `TextureFormatFeatures` for a listing of the features in question.
///
/// By default only texture format properties as defined by the WebGPU specification are allowed.
/// Enabling this feature flag extends the features of each format to the ones supported by the current device.
/// Note that without this flag, read/write storage access is not allowed at all.
///
/// This extension does not enable additional formats.
///
/// This is a native-only feature.
const TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES = 1 << 32;
/// Enables 64-bit floating point types in SPIR-V shaders.
///
/// Note: even when supported by GPU hardware, 64-bit floating point operations are
/// frequently between 16 and 64 _times_ slower than equivalent operations on 32-bit floats.
///
/// Supported Platforms:
/// - Vulkan
///
/// This is a native-only feature.
const SHADER_FLOAT64 = 1 << 33;
/// Enables using 64-bit types for vertex attributes.
///
/// Requires SHADER_FLOAT64.
///
/// Supported Platforms: N/A
///
/// This is a native-only feature.
const VERTEX_ATTRIBUTE_64BIT = 1 << 34;
/// Allows the user to set a overestimation-conservative-rasterization in [`PrimitiveState::conservative`]
///
/// Processing of degenerate triangles/lines is hardware specific.
/// Only triangles are supported.
///
/// Supported platforms:
/// - Vulkan
///
/// This is a native only feature.
const CONSERVATIVE_RASTERIZATION = 1 << 35;
/// Enables bindings of writable storage buffers and textures visible to vertex shaders.
///
/// Note: some (tiled-based) platforms do not support vertex shaders with any side-effects.
///
/// Supported Platforms:
/// - All
///
/// This is a native-only feature.
const VERTEX_WRITABLE_STORAGE = 1 << 36;
/// Enables clear to zero for textures.
///
/// Supported platforms:
/// - All
///
/// This is a native only feature.
const CLEAR_TEXTURE = 1 << 37;
/// Enables creating shader modules from SPIR-V binary data (unsafe).
///
/// SPIR-V data is not parsed or interpreted in any way; you can use
/// [`wgpu::make_spirv_raw!`] to check for alignment and magic number when converting from
/// raw bytes.
///
/// Supported platforms:
/// - Vulkan, in case shader's requested capabilities and extensions agree with
/// Vulkan implementation.
///
/// This is a native only feature.
const SPIRV_SHADER_PASSTHROUGH = 1 << 38;
/// Enables `builtin(primitive_index)` in fragment shaders.
///
/// Note: enables geometry processing for pipelines using the builtin.
/// This may come with a significant performance impact on some hardware.
/// Other pipelines are not affected.
///
/// Supported platforms:
/// - Vulkan
///
/// This is a native only feature.
const SHADER_PRIMITIVE_INDEX = 1 << 39;
/// Enables multiview render passes and `builtin(view_index)` in vertex shaders.
///
/// Supported platforms:
/// - Vulkan
///
/// This is a native only feature.
const MULTIVIEW = 1 << 40;
/// Enables normalized `16-bit` texture formats.
///
/// Supported platforms:
/// - Vulkan
/// - DX12
/// - Metal
///
/// This is a native only feature.
const TEXTURE_FORMAT_16BIT_NORM = 1 << 41;
/// Allows the use of [`AddressMode::ClampToBorder`] with a border color
/// of [`SamplerBorderColor::Zero`].
///
/// Supported platforms:
/// - DX12
/// - Vulkan
/// - Metal
/// - DX11
/// - OpenGL
///
/// This is a native only feature.
const ADDRESS_MODE_CLAMP_TO_ZERO = 1 << 42;
}
}
#[cfg(feature = "bitflags_serde_shim")]
bitflags_serde_shim::impl_serde_for_bitflags!(Features);
impl Features {
/// Mask of all features which are part of the upstream WebGPU standard.
pub const fn all_webgpu_mask() -> Self {
Self::from_bits_truncate(0x0000_0000_0000_FFFF)
}
/// Mask of all features that are only available when targeting native (not web).
pub const fn all_native_mask() -> Self {
Self::from_bits_truncate(0xFFFF_FFFF_FFFF_0000)
}
}
/// Represents the sets of limits an adapter/device supports.
///
/// We provide three different defaults.
/// - [`Limits::downlevel_defaults()`]. This is a set of limits that is guarenteed to work on almost
/// all backends, including "downlevel" backends such as OpenGL and D3D11, other than WebGL. For
/// most applications we recommend using these limits, assuming they are high enough for your
/// application, and you do not intent to support WebGL.
/// - [`Limits::downlevel_webgl2_defaults()`] This is a set of limits that is lower even than the
/// [`downlevel_defaults()`], configured to be low enough to support running in the browser using
/// WebGL2.
/// - [`Limits::default()`]. This is the set of limits that is guarenteed to work on all modern
/// backends and is guarenteed to be supported by WebGPU. Applications needing more modern
/// features can use this as a reasonable set of limits if they are targetting only desktop and
/// modern mobile devices.
///
/// We recommend starting with the most restrictive limits you can and manually increasing the
/// limits you need boosted. This will let you stay running on all hardware that supports the limits
/// you need.
///
/// Limits "better" than the default must be supported by the adapter and requested when requesting
/// a device. If limits "better" than the adapter supports are requested, requesting a device will
/// panic. Once a device is requested, you may only use resources up to the limits requested _even_
/// if the adapter supports "better" limits.
///
/// Requesting limits that are "better" than you need may cause performance to decrease because the
/// implementation needs to support more than is needed. You should ideally only request exactly
/// what you need.
///
/// See also: <https://gpuweb.github.io/gpuweb/#dictdef-gpulimits>
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "trace", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Limits {
/// Maximum allowed value for the `size.width` of a texture created with `TextureDimension::D1`.
/// Defaults to 8192. Higher is "better".
pub max_texture_dimension_1d: u32,
/// Maximum allowed value for the `size.width` and `size.height` of a texture created with `TextureDimension::D2`.
/// Defaults to 8192. Higher is "better".
pub max_texture_dimension_2d: u32,
/// Maximum allowed value for the `size.width`, `size.height`, and `size.depth_or_array_layers`
/// of a texture created with `TextureDimension::D3`.
/// Defaults to 2048. Higher is "better".
pub max_texture_dimension_3d: u32,
/// Maximum allowed value for the `size.depth_or_array_layers` of a texture created with
/// `TextureDimension::D1` or `TextureDimension::D2`.
/// Defaults to 256. Higher is "better".
pub max_texture_array_layers: u32,
/// Amount of bind groups that can be attached to a pipeline at the same time. Defaults to 4. Higher is "better".
pub max_bind_groups: u32,
/// Amount of uniform buffer bindings that can be dynamic in a single pipeline. Defaults to 8. Higher is "better".
pub max_dynamic_uniform_buffers_per_pipeline_layout: u32,
/// Amount of storage buffer bindings that can be dynamic in a single pipeline. Defaults to 4. Higher is "better".
pub max_dynamic_storage_buffers_per_pipeline_layout: u32,
/// Amount of sampled textures visible in a single shader stage. Defaults to 16. Higher is "better".
pub max_sampled_textures_per_shader_stage: u32,
/// Amount of samplers visible in a single shader stage. Defaults to 16. Higher is "better".
pub max_samplers_per_shader_stage: u32,
/// Amount of storage buffers visible in a single shader stage. Defaults to 8. Higher is "better".
pub max_storage_buffers_per_shader_stage: u32,
/// Amount of storage textures visible in a single shader stage. Defaults to 8. Higher is "better".
pub max_storage_textures_per_shader_stage: u32,
/// Amount of uniform buffers visible in a single shader stage. Defaults to 12. Higher is "better".
pub max_uniform_buffers_per_shader_stage: u32,
/// Maximum size in bytes of a binding to a uniform buffer. Defaults to 64 KB. Higher is "better".
pub max_uniform_buffer_binding_size: u32,
/// Maximum size in bytes of a binding to a storage buffer. Defaults to 128 MB. Higher is "better".
pub max_storage_buffer_binding_size: u32,
/// Maximum length of `VertexState::buffers` when creating a `RenderPipeline`.
/// Defaults to 8. Higher is "better".
pub max_vertex_buffers: u32,
/// Maximum length of `VertexBufferLayout::attributes`, summed over all `VertexState::buffers`,
/// when creating a `RenderPipeline`.
/// Defaults to 16. Higher is "better".
pub max_vertex_attributes: u32,
/// Maximum value for `VertexBufferLayout::array_stride` when creating a `RenderPipeline`.
/// Defaults to 2048. Higher is "better".
pub max_vertex_buffer_array_stride: u32,
/// Amount of storage available for push constants in bytes. Defaults to 0. Higher is "better".
/// Requesting more than 0 during device creation requires [`Features::PUSH_CONSTANTS`] to be enabled.
///
/// Expect the size to be:
/// - Vulkan: 128-256 bytes
/// - DX12: 256 bytes
/// - Metal: 4096 bytes
/// - DX11 & OpenGL don't natively support push constants, and are emulated with uniforms,
/// so this number is less useful but likely 256.
pub max_push_constant_size: u32,
/// Required `BufferBindingType::Uniform` alignment for `BufferBinding::offset`
/// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`.
/// Defaults to 256. Lower is "better".
pub min_uniform_buffer_offset_alignment: u32,
/// Required `BufferBindingType::Storage` alignment for `BufferBinding::offset`
/// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`.
/// Defaults to 256. Lower is "better".
pub min_storage_buffer_offset_alignment: u32,
/// Maximum allowed number of components (scalars) of input or output locations for
/// inter-stage communication (vertex outputs to fragment inputs). Defaults to 60.
pub max_inter_stage_shader_components: u32,
/// Maximum number of bytes used for workgroup memory in a compute entry point. Defaults to
/// 16352.
pub max_compute_workgroup_storage_size: u32,
/// Maximum value of the product of the `workgroup_size` dimensions for a compute entry-point.
/// Defaults to 256.
pub max_compute_invocations_per_workgroup: u32,
/// The maximum value of the workgroup_size X dimension for a compute stage `ShaderModule` entry-point.
/// Defaults to 256.
pub max_compute_workgroup_size_x: u32,
/// The maximum value of the workgroup_size Y dimension for a compute stage `ShaderModule` entry-point.
/// Defaults to 256.
pub max_compute_workgroup_size_y: u32,
/// The maximum value of the workgroup_size Z dimension for a compute stage `ShaderModule` entry-point.
/// Defaults to 64.
pub max_compute_workgroup_size_z: u32,
/// The maximum value for each dimension of a `ComputePass::dispatch(x, y, z)` operation.
/// Defaults to 65535.
pub max_compute_workgroups_per_dimension: u32,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_texture_dimension_1d: 8192,
max_texture_dimension_2d: 8192,
max_texture_dimension_3d: 2048,
max_texture_array_layers: 256,
max_bind_groups: 4,
max_dynamic_uniform_buffers_per_pipeline_layout: 8,
max_dynamic_storage_buffers_per_pipeline_layout: 4,
max_sampled_textures_per_shader_stage: 16,
max_samplers_per_shader_stage: 16,
max_storage_buffers_per_shader_stage: 8,
max_storage_textures_per_shader_stage: 8,
max_uniform_buffers_per_shader_stage: 12,
max_uniform_buffer_binding_size: 64 << 10,
max_storage_buffer_binding_size: 128 << 20,
max_vertex_buffers: 8,
max_vertex_attributes: 16,
max_vertex_buffer_array_stride: 2048,
max_push_constant_size: 0,
min_uniform_buffer_offset_alignment: 256,
min_storage_buffer_offset_alignment: 256,
max_inter_stage_shader_components: 60,
max_compute_workgroup_storage_size: 16352,
max_compute_invocations_per_workgroup: 256,
max_compute_workgroup_size_x: 256,
max_compute_workgroup_size_y: 256,
max_compute_workgroup_size_z: 64,
max_compute_workgroups_per_dimension: 65535,
}
}
}
impl Limits {
/// These default limits are guarenteed to be compatible with GLES-3.1, and D3D11
pub fn downlevel_defaults() -> Self {
Self {
max_texture_dimension_1d: 2048,
max_texture_dimension_2d: 2048,
max_texture_dimension_3d: 256,
max_texture_array_layers: 256,
max_bind_groups: 4,
max_dynamic_uniform_buffers_per_pipeline_layout: 8,
max_dynamic_storage_buffers_per_pipeline_layout: 4,
max_sampled_textures_per_shader_stage: 16,
max_samplers_per_shader_stage: 16,
max_storage_buffers_per_shader_stage: 4,
max_storage_textures_per_shader_stage: 4,
max_uniform_buffers_per_shader_stage: 12,
max_uniform_buffer_binding_size: 16 << 10,
max_storage_buffer_binding_size: 128 << 20,
max_vertex_buffers: 8,
max_vertex_attributes: 16,
max_vertex_buffer_array_stride: 2048,
max_push_constant_size: 0,
min_uniform_buffer_offset_alignment: 256,
min_storage_buffer_offset_alignment: 256,
max_inter_stage_shader_components: 60,
max_compute_workgroup_storage_size: 16352,
max_compute_invocations_per_workgroup: 256,
max_compute_workgroup_size_x: 256,
max_compute_workgroup_size_y: 256,
max_compute_workgroup_size_z: 64,
max_compute_workgroups_per_dimension: 65535,
}
}
/// These default limits are guarenteed to be compatible with GLES-3.0, and D3D11, and WebGL2
pub fn downlevel_webgl2_defaults() -> Self {
Self {
max_uniform_buffers_per_shader_stage: 11,
max_storage_buffers_per_shader_stage: 0,
max_storage_textures_per_shader_stage: 0,
max_dynamic_storage_buffers_per_pipeline_layout: 0,
max_storage_buffer_binding_size: 0,
max_vertex_buffer_array_stride: 255,
max_compute_workgroup_storage_size: 0,
max_compute_invocations_per_workgroup: 0,
max_compute_workgroup_size_x: 0,
max_compute_workgroup_size_y: 0,
max_compute_workgroup_size_z: 0,
max_compute_workgroups_per_dimension: 0,
// Most of the values should be the same as the downlevel defaults
..Self::downlevel_defaults()
}
}
/// Modify the current limits to use the resolution limits of the other.
///
/// This is useful because the swapchain might need to be larger than any other image in the application.
///
/// If your application only needs 512x512, you might be running on a 4k display and need extremely high resolution limits.
pub fn using_resolution(self, other: Self) -> Self {
Self {
max_texture_dimension_1d: other.max_texture_dimension_1d,
max_texture_dimension_2d: other.max_texture_dimension_2d,
max_texture_dimension_3d: other.max_texture_dimension_3d,
..self
}
}
/// Modify the current limits to use the buffer alignment limits of the adapter.
///
/// This is useful for when you'd like to dynamically use the "best" supported buffer alignments.
pub fn using_alignment(self, other: Self) -> Self {
Self {
min_uniform_buffer_offset_alignment: other.min_uniform_buffer_offset_alignment,
min_storage_buffer_offset_alignment: other.min_storage_buffer_offset_alignment,
..self
}
}
}
/// Represents the sets of additional limits on an adapter,
/// which take place when running on downlevel backends.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DownlevelLimits {}
#[allow(unknown_lints)] // derivable_impls is nightly only currently
#[allow(clippy::derivable_impls)]
impl Default for DownlevelLimits {
fn default() -> Self {
DownlevelLimits {}
}
}
/// Lists various ways the underlying platform does not conform to the WebGPU standard.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DownlevelCapabilities {
/// Combined boolean flags.
pub flags: DownlevelFlags,
/// Additional limits
pub limits: DownlevelLimits,
/// Which collections of features shaders support. Defined in terms of D3D's shader models.
pub shader_model: ShaderModel,
}
impl Default for DownlevelCapabilities {
fn default() -> Self {
Self {
flags: DownlevelFlags::compliant(),
limits: DownlevelLimits::default(),
shader_model: ShaderModel::Sm5,
}
}
}
impl DownlevelCapabilities {
/// Returns true if the underlying platform offers complete support of the baseline WebGPU standard.
///
/// If this returns false, some parts of the API will result in validation errors where they would not normally.
/// These parts can be determined by the values in this structure.
pub fn is_webgpu_compliant(&self) -> bool {
self.flags.contains(DownlevelFlags::compliant())
&& self.limits == DownlevelLimits::default()
&& self.shader_model >= ShaderModel::Sm5
}
}
bitflags::bitflags! {
/// Binary flags listing features that may or may not be present on downlevel adapters.
///
/// A downlevel adapter is a GPU adapter that WGPU supports, but with potentially limited
/// features, due to the lack of hardware feature support.
///
/// Flags that are **not** present for a downlevel adapter or device usually indicates
/// non-compliance with the WebGPU specification, but not always.
///
/// You can check whether a set of flags is compliant through the
/// [`DownlevelCapabilities::is_webgpu_compliant()`] function.
pub struct DownlevelFlags: u32 {
/// The device supports compiling and using compute shaders.
const COMPUTE_SHADERS = 1 << 0;
/// Supports binding storage buffers and textures to fragment shaders.
const FRAGMENT_WRITABLE_STORAGE = 1 << 1;
/// Supports indirect drawing and dispatching.
const INDIRECT_EXECUTION = 1 << 2;
/// Supports non-zero `base_vertex` parameter to indexed draw calls.
const BASE_VERTEX = 1 << 3;
/// Supports reading from a depth/stencil buffer while using as a read-only depth/stencil
/// attachment.
const READ_ONLY_DEPTH_STENCIL = 1 << 4;
/// Supports:
/// - copy_image_to_image
/// - copy_buffer_to_image and copy_image_to_buffer with a buffer without a MAP_* usage
const DEVICE_LOCAL_IMAGE_COPIES = 1 << 5;
/// Supports textures with mipmaps which have a non power of two size.
const NON_POWER_OF_TWO_MIPMAPPED_TEXTURES = 1 << 6;
/// Supports textures that are cube arrays.
const CUBE_ARRAY_TEXTURES = 1 << 7;
/// Supports comparison samplers.
const COMPARISON_SAMPLERS = 1 << 8;
/// Supports different blending modes per color target.
const INDEPENDENT_BLENDING = 1 << 9;
/// Supports storage buffers in vertex shaders.
const VERTEX_STORAGE = 1 << 10;
/// Supports samplers with anisotropic filtering. Note this isn't actually required by
/// WebGPU, the implementation is allowed to completely ignore aniso clamp. This flag is
/// here for native backends so they can comunicate to the user of aniso is enabled.
const ANISOTROPIC_FILTERING = 1 << 11;
/// Supports storage buffers in fragment shaders.
const FRAGMENT_STORAGE = 1 << 12;
}
}
#[cfg(feature = "bitflags_serde_shim")]
bitflags_serde_shim::impl_serde_for_bitflags!(DownlevelFlags);
impl DownlevelFlags {
/// All flags that indicate if the backend is WebGPU compliant
pub const fn compliant() -> Self {
// We use manual bit twiddling to make this a const fn as `Sub` and `.remove` aren't const
// WebGPU doesn't actually require aniso
Self::from_bits_truncate(Self::all().bits() & !Self::ANISOTROPIC_FILTERING.bits)
}
}
/// Collections of shader features a device supports if they support less than WebGPU normally allows.
// TODO: Fill out the differences between shader models more completely
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ShaderModel {
/// Extremely limited shaders, including a total instruction limit.
Sm2,
/// Missing minor features and storage images.
Sm4,
/// WebGPU supports shader module 5.
Sm5,
}
/// Supported physical device types.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "trace", derive(serde::Serialize))]
#[cfg_attr(feature = "replay", derive(serde::Deserialize))]
pub enum DeviceType {
/// Other.
Other,
/// Integrated GPU with shared CPU/GPU memory.
IntegratedGpu,
/// Discrete GPU with separate CPU/GPU memory.
DiscreteGpu,
/// Virtual / Hosted.
VirtualGpu,
/// Cpu / Software Rendering.
Cpu,
}
//TODO: convert `vendor` and `device` to `u32`
/// Information about an adapter.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "trace", derive(serde::Serialize))]
#[cfg_attr(feature = "replay", derive(serde::Deserialize))]
pub struct AdapterInfo {
/// Adapter name
pub name: String,
/// Vendor PCI id of the adapter
pub vendor: usize,
/// PCI id of the adapter
pub device: usize,
/// Type of device
pub device_type: DeviceType,
/// Backend used for device
pub backend: Backend,
}
/// Describes a [`Device`].
#[repr(C)]
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "trace", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct DeviceDescriptor<L> {
/// Debug label for the device.
pub label: L,
/// Features that the device should support. If any feature is not supported by
/// the adapter, creating a device will panic.
pub features: Features,
/// Limits that the device should support. If any limit is "better" than the limit exposed by
/// the adapter, creating a device will panic.
pub limits: Limits,
}
impl<L> DeviceDescriptor<L> {
///
pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> DeviceDescriptor<K> {
DeviceDescriptor {
label: fun(&self.label),
features: self.features,
limits: self.limits.clone(),
}