gfx_hal/lib.rs
1#![warn(
2 trivial_casts,
3 trivial_numeric_casts,
4 unused_extern_crates,
5 unused_import_braces,
6 unused_qualifications
7)]
8#![deny(
9 broken_intra_doc_links,
10 missing_debug_implementations,
11 missing_docs,
12 unused
13)]
14
15//! Low-level graphics abstraction for Rust. Mostly operates on data, not types.
16//! Designed for use by libraries and higher-level abstractions only.
17//!
18//! This crate provides a [hardware abstraction layer][hal] for [graphics adapters][gpus],
19//! for both compute and graphics operations. The API design is heavily inspired by
20//! the [Vulkan API](https://www.khronos.org/vulkan/), and borrows some of the terminology.
21//!
22//! [hal]: https://en.wikipedia.org/wiki/Hardware_abstraction
23//! [gpus]: https://en.wikipedia.org/wiki/Video_card
24//!
25//! # Usage
26//!
27//! Most of the functionality is implemented in separate crates, one for each backend.
28//! This crate only exposes a few generic traits and structures. You can import
29//! all the necessary traits through the [`prelude`][prelude] module.
30//!
31//! The first step to using `gfx-hal` is to initialize one of the available
32//! [backends][Backend], by creating an [`Instance`][Instance]. Then proceed by
33//! [enumerating][Instance::enumerate_adapters] the available
34//! [graphics adapters][adapter::Adapter] and querying their available
35//! [features][Features] and [queues][queue::family::QueueFamily].
36//!
37//! You can use the [`open`][adapter::PhysicalDevice::open] method on a
38//! [`PhysicalDevice`][adapter::PhysicalDevice] to get a [logical device
39//! handle][device::Device], from which you can manage all the other device-specific
40//! resources.
41
42#[macro_use]
43extern crate bitflags;
44
45#[cfg(feature = "serde")]
46#[macro_use]
47extern crate serde;
48
49use std::{any::Any, fmt, hash::Hash};
50
51pub mod adapter;
52pub mod buffer;
53pub mod command;
54pub mod device;
55pub mod display;
56pub mod external_memory;
57pub mod format;
58pub mod image;
59pub mod memory;
60pub mod pass;
61pub mod pool;
62pub mod pso;
63pub mod query;
64pub mod queue;
65pub mod window;
66
67/// Prelude module re-exports all the traits necessary to use `gfx-hal`.
68pub mod prelude {
69 pub use crate::{
70 adapter::PhysicalDevice,
71 command::CommandBuffer,
72 device::Device,
73 pool::CommandPool,
74 pso::DescriptorPool,
75 queue::{Queue, QueueFamily},
76 window::{PresentationSurface, Surface},
77 Instance,
78 };
79}
80
81/// Draw vertex count.
82pub type VertexCount = u32;
83/// Draw vertex base offset.
84pub type VertexOffset = i32;
85/// Draw number of indices.
86pub type IndexCount = u32;
87/// Draw number of instances.
88pub type InstanceCount = u32;
89/// Indirect draw calls count.
90pub type DrawCount = u32;
91/// Number of work groups.
92pub type WorkGroupCount = [u32; 3];
93/// Number of tasks.
94pub type TaskCount = u32;
95
96bitflags! {
97 //TODO: add a feature for non-normalized samplers
98 //TODO: add a feature for mutable comparison samplers
99 /// Features that the device supports.
100 ///
101 /// These only include features of the core interface and not API extensions.
102 ///
103 /// Can be obtained from a [physical device][adapter::PhysicalDevice] by calling
104 /// [`features`][adapter::PhysicalDevice::features].
105 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
106 pub struct Features: u128 {
107 /// Bit mask of Vulkan Core/Extension features.
108 const CORE_MASK = 0xFFFF_FFFF_FFFF_FFFF;
109 /// Bit mask of Vulkan Portability features.
110 const PORTABILITY_MASK = 0xFFFF << 64;
111 /// Bit mask for extra WebGPU features.
112 const WEBGPU_MASK = 0xFFFF << 80;
113 /// Bit mask for all extensions.
114 const EXTENSIONS_MASK = 0xFFFF_FFFF << 96;
115
116 // Bits for Vulkan Core/Extension features
117
118 /// Support for robust buffer access.
119 /// Buffer access by SPIR-V shaders is checked against the buffer/image boundaries.
120 const ROBUST_BUFFER_ACCESS = 0x0000_0000_0000_0001;
121 /// Support the full 32-bit range of indexed for draw calls.
122 /// If not supported, the maximum index value is determined by `Limits::max_draw_index_value`.
123 const FULL_DRAW_INDEX_U32 = 0x0000_0000_0000_0002;
124 /// Support cube array image views.
125 const IMAGE_CUBE_ARRAY = 0x0000_0000_0000_0004;
126 /// Support different color blending settings per attachments on graphics pipeline creation.
127 const INDEPENDENT_BLENDING = 0x0000_0000_0000_0008;
128 /// Support geometry shader.
129 const GEOMETRY_SHADER = 0x0000_0000_0000_0010;
130 /// Support tessellation shaders.
131 const TESSELLATION_SHADER = 0x0000_0000_0000_0020;
132 /// Support per-sample shading and multisample interpolation.
133 const SAMPLE_RATE_SHADING = 0x0000_0000_0000_0040;
134 /// Support dual source blending.
135 const DUAL_SRC_BLENDING = 0x0000_0000_0000_0080;
136 /// Support logic operations.
137 const LOGIC_OP = 0x0000_0000_0000_0100;
138 /// Support multiple draws per indirect call.
139 const MULTI_DRAW_INDIRECT = 0x0000_0000_0000_0200;
140 /// Support indirect drawing with first instance value.
141 /// If not supported the first instance value **must** be 0.
142 const DRAW_INDIRECT_FIRST_INSTANCE = 0x0000_0000_0000_0400;
143 /// Support depth clamping.
144 const DEPTH_CLAMP = 0x0000_0000_0000_0800;
145 /// Support depth bias clamping.
146 const DEPTH_BIAS_CLAMP = 0x0000_0000_0000_1000;
147 /// Support non-fill polygon modes.
148 const NON_FILL_POLYGON_MODE = 0x0000_0000_0000_2000;
149 /// Support depth bounds test.
150 const DEPTH_BOUNDS = 0x0000_0000_0000_4000;
151 /// Support lines with width other than 1.0.
152 const LINE_WIDTH = 0x0000_0000_0000_8000;
153 /// Support points with size greater than 1.0.
154 const POINT_SIZE = 0x0000_0000_0001_0000;
155 /// Support replacing alpha values with 1.0.
156 const ALPHA_TO_ONE = 0x0000_0000_0002_0000;
157 /// Support multiple viewports and scissors.
158 const MULTI_VIEWPORTS = 0x0000_0000_0004_0000;
159 /// Support anisotropic filtering.
160 const SAMPLER_ANISOTROPY = 0x0000_0000_0008_0000;
161 /// Support ETC2 texture compression formats.
162 const FORMAT_ETC2 = 0x0000_0000_0010_0000;
163 /// Support ASTC (LDR) texture compression formats.
164 const FORMAT_ASTC_LDR = 0x0000_0000_0020_0000;
165 /// Support BC texture compression formats.
166 const FORMAT_BC = 0x0000_0000_0040_0000;
167 /// Support precise occlusion queries, returning the actual number of samples.
168 /// If not supported, queries return a non-zero value when at least **one** sample passes.
169 const PRECISE_OCCLUSION_QUERY = 0x0000_0000_0080_0000;
170 /// Support query of pipeline statistics.
171 const PIPELINE_STATISTICS_QUERY = 0x0000_0000_0100_0000;
172 /// Support unordered access stores and atomic ops in the vertex, geometry
173 /// and tessellation shader stage.
174 /// If not supported, the shader resources **must** be annotated as read-only.
175 const VERTEX_STORES_AND_ATOMICS = 0x0000_0000_0200_0000;
176 /// Support unordered access stores and atomic ops in the fragment shader stage
177 /// If not supported, the shader resources **must** be annotated as read-only.
178 const FRAGMENT_STORES_AND_ATOMICS = 0x0000_0000_0400_0000;
179 ///
180 const SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE = 0x0000_0000_0800_0000;
181 ///
182 const SHADER_IMAGE_GATHER_EXTENDED = 0x0000_0000_1000_0000;
183 ///
184 const SHADER_STORAGE_IMAGE_EXTENDED_FORMATS = 0x0000_0000_2000_0000;
185 ///
186 const SHADER_STORAGE_IMAGE_MULTISAMPLE = 0x0000_0000_4000_0000;
187 ///
188 const SHADER_STORAGE_IMAGE_READ_WITHOUT_FORMAT = 0x0000_0000_8000_0000;
189 ///
190 const SHADER_STORAGE_IMAGE_WRITE_WITHOUT_FORMAT = 0x0000_0001_0000_0000;
191 ///
192 const SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING = 0x0000_0002_0000_0000;
193 ///
194 const SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING = 0x0000_0004_0000_0000;
195 ///
196 const SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING = 0x0000_0008_0000_0000;
197 ///
198 const SHADER_STORAGE_IMAGE_ARRAY_DYNAMIC_INDEXING = 0x0000_0010_0000_0000;
199 ///
200 const SHADER_CLIP_DISTANCE = 0x0000_0020_0000_0000;
201 ///
202 const SHADER_CULL_DISTANCE = 0x0000_0040_0000_0000;
203 ///
204 const SHADER_FLOAT64 = 0x0000_0080_0000_0000;
205 ///
206 const SHADER_INT64 = 0x0000_0100_0000_0000;
207 ///
208 const SHADER_INT16 = 0x0000_0200_0000_0000;
209 ///
210 const SHADER_RESOURCE_RESIDENCY = 0x0000_0400_0000_0000;
211 ///
212 const SHADER_RESOURCE_MIN_LOD = 0x0000_0800_0000_0000;
213 ///
214 const SPARSE_BINDING = 0x0000_1000_0000_0000;
215 ///
216 const SPARSE_RESIDENCY_BUFFER = 0x0000_2000_0000_0000;
217 ///
218 const SPARSE_RESIDENCY_IMAGE_2D = 0x0000_4000_0000_0000;
219 ///
220 const SPARSE_RESIDENCY_IMAGE_3D = 0x0000_8000_0000_0000;
221 ///
222 const SPARSE_RESIDENCY_2_SAMPLES = 0x0001_0000_0000_0000;
223 ///
224 const SPARSE_RESIDENCY_4_SAMPLES = 0x0002_0000_0000_0000;
225 ///
226 const SPARSE_RESIDENCY_8_SAMPLES = 0x0004_0000_0000_0000;
227 ///
228 const SPARSE_RESIDENCY_16_SAMPLES = 0x0008_0000_0000_0000;
229 ///
230 const SPARSE_RESIDENCY_ALIASED = 0x0010_0000_0000_0000;
231 ///
232 const VARIABLE_MULTISAMPLE_RATE = 0x0020_0000_0000_0000;
233 ///
234 const INHERITED_QUERIES = 0x0040_0000_0000_0000;
235 /// Support for arrays of texture descriptors
236 const TEXTURE_DESCRIPTOR_ARRAY = 0x0080_0000_0000_0000;
237 /// Support for
238 const SAMPLER_MIRROR_CLAMP_EDGE = 0x0100_0000_0000_0000;
239 /// Allow indexing sampled texture descriptor arrays with dynamically non-uniform data
240 const SAMPLED_TEXTURE_DESCRIPTOR_INDEXING = 0x0200_0000_0000_0000;
241 /// Allow indexing storage texture descriptor arrays with dynamically non-uniform data
242 const STORAGE_TEXTURE_DESCRIPTOR_INDEXING = 0x0400_0000_0000_0000;
243 /// Allow descriptor arrays to be unsized in shaders
244 const UNSIZED_DESCRIPTOR_ARRAY = 0x0800_0000_0000_0000;
245 /// Mask for all the features associated with descriptor indexing.
246 const DESCRIPTOR_INDEXING_MASK = Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING.bits | Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING.bits | Features::UNSIZED_DESCRIPTOR_ARRAY.bits | Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING.bits | Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING.bits;
247
248 /// Enable draw_indirect_count and draw_indexed_indirect_count
249 const DRAW_INDIRECT_COUNT = 0x1000_0000_0000_0000;
250
251 /// Support for conservative rasterization. Presence of this flag only indicates basic overestimation rasterization for triangles only.
252 /// (no guarantee on underestimation, overestimation, handling of degenerate primitives, fragment shader coverage reporting and uncertainty ranges)
253 const CONSERVATIVE_RASTERIZATION = 0x2000_0000_0000_0000;
254
255 /// Support for arrays of buffer descriptors
256 const BUFFER_DESCRIPTOR_ARRAY = 0x4000_0000_0000_0000;
257 /// Allow indexing uniform buffer descriptor arrays with dynamically non-uniform data
258 const UNIFORM_BUFFER_DESCRIPTOR_INDEXING = 0x8000_0000_0000_0000;
259 /// Allow indexing storage buffer descriptor arrays with dynamically non-uniform data
260 const STORAGE_BUFFER_DESCRIPTOR_INDEXING = 0x0001_0000_0000_0000_0000;
261
262 // Bits for Vulkan Portability features
263
264 /// Support triangle fan primitive topology.
265 const TRIANGLE_FAN = 0x0001 << 64;
266 /// Support separate stencil reference values for front and back sides.
267 const SEPARATE_STENCIL_REF_VALUES = 0x0002 << 64;
268 /// Support manually specified vertex attribute rates (divisors).
269 const INSTANCE_RATE = 0x0004 << 64;
270 /// Support non-zero mipmap bias on samplers.
271 const SAMPLER_MIP_LOD_BIAS = 0x0008 << 64;
272 /// Support sampler wrap mode that clamps to border.
273 const SAMPLER_BORDER_COLOR = 0x0010 << 64;
274 /// Can create comparison samplers in regular descriptor sets.
275 const MUTABLE_COMPARISON_SAMPLER = 0x0020 << 64;
276 /// Can create non-normalized samplers in regular descriptor sets.
277 const MUTABLE_UNNORMALIZED_SAMPLER = 0x0040 << 64;
278
279 // Bits for WebGPU features
280
281 /// Make the NDC coordinate system pointing Y up, to match D3D and Metal.
282 const NDC_Y_UP = 0x0001 << 80;
283
284 // Bits for Extensions
285
286 /// Supports task shader stage.
287 const TASK_SHADER = 0x0001 << 96;
288 /// Supports mesh shader stage.
289 const MESH_SHADER = 0x0002 << 96;
290 /// Mask for all the features associated with mesh shader stages.
291 const MESH_SHADER_MASK = Features::TASK_SHADER.bits | Features::MESH_SHADER.bits;
292 /// Support sampler min/max reduction mode.
293 const SAMPLER_REDUCTION = 0x0004 << 96;
294 /// Supports external memory import and export.
295 const EXTERNAL_MEMORY = 0x0008 << 96;
296 }
297}
298
299bitflags! {
300 /// Features that the device doesn't support natively, but is able to emulate
301 /// at some performance cost.
302 #[derive(Default)]
303 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
304 pub struct PerformanceCaveats: u32 {
305 /// Emulate indexed, instanced drawing with base vertex and instance.
306 const BASE_VERTEX_INSTANCE_DRAWING = 0x0001;
307 }
308}
309
310bitflags! {
311 /// Dynamic pipeline states.
312 #[derive(Default)]
313 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
314 pub struct DynamicStates: u32 {
315 /// Supports `BakedStates::viewport == None`
316 const VIEWPORT = 0x0001;
317 /// Supports `BakedStates::scissor == None`
318 const SCISSOR = 0x0002;
319 /// Supports `Rasterizer::line_width == State::Dynamic(_)`
320 const LINE_WIDTH = 0x0004;
321 /// Supports `BakedStates::blend_constants == None`
322 const BLEND_CONSTANTS = 0x0008;
323 /// Supports `Rasterizer::depth_bias == Some(State::Dynamic(_))`
324 const DEPTH_BIAS = 0x0010;
325 /// Supports `BakedStates::depth_bounds == None`
326 const DEPTH_BOUNDS = 0x0020;
327 /// Supports `StencilTest::read_masks == State::Dynamic(_)`
328 const STENCIL_READ_MASK = 0x0100;
329 /// Supports `StencilTest::write_masks == State::Dynamic(_)`
330 const STENCIL_WRITE_MASK = 0x0200;
331 /// Supports `StencilTest::reference_values == State::Dynamic(_)`
332 const STENCIL_REFERENCE = 0x0400;
333 }
334}
335
336/// Properties of physical devices that are exposed but do not need to be explicitly opted into.
337///
338/// This contains things like resource limits, alignment requirements, and finer-grained feature
339/// capabilities.
340#[derive(Clone, Copy, Debug, Default, PartialEq)]
341#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
342pub struct PhysicalDeviceProperties {
343 /// Core limits.
344 pub limits: Limits,
345 /// Descriptor Indexing properties.
346 pub descriptor_indexing: DescriptorIndexingProperties,
347 /// Mesh Shader properties.
348 pub mesh_shader: MeshShaderProperties,
349 /// Sampler reduction modes.
350 pub sampler_reduction: SamplerReductionProperties,
351 /// Downlevel properties.
352 pub downlevel: DownlevelProperties,
353 /// Performance caveats.
354 pub performance_caveats: PerformanceCaveats,
355 /// Dynamic pipeline states.
356 pub dynamic_pipeline_states: DynamicStates,
357 /// External memory limits
358 pub external_memory_limits: ExternalMemoryLimits,
359}
360
361///
362#[derive(Clone, Copy, Debug, Default, PartialEq)]
363#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
364pub struct DescriptorLimits {
365 ///
366 pub max_per_stage_descriptor_samplers: u32,
367 ///
368 pub max_per_stage_descriptor_uniform_buffers: u32,
369 ///
370 pub max_per_stage_descriptor_storage_buffers: u32,
371 ///
372 pub max_per_stage_descriptor_sampled_images: u32,
373 ///
374 pub max_per_stage_descriptor_storage_images: u32,
375 ///
376 pub max_per_stage_descriptor_input_attachments: u32,
377 ///
378 pub max_per_stage_resources: u32,
379 ///
380 pub max_descriptor_set_samplers: u32,
381 ///
382 pub max_descriptor_set_uniform_buffers: u32,
383 ///
384 pub max_descriptor_set_uniform_buffers_dynamic: u32,
385 ///
386 pub max_descriptor_set_storage_buffers: u32,
387 ///
388 pub max_descriptor_set_storage_buffers_dynamic: u32,
389 ///
390 pub max_descriptor_set_sampled_images: u32,
391 ///
392 pub max_descriptor_set_storage_images: u32,
393 ///
394 pub max_descriptor_set_input_attachments: u32,
395}
396
397/// Resource limits of a particular graphics device.
398#[derive(Clone, Copy, Debug, Default, PartialEq)]
399#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
400pub struct Limits {
401 /// Maximum supported image 1D size.
402 pub max_image_1d_size: image::Size,
403 /// Maximum supported image 2D size.
404 pub max_image_2d_size: image::Size,
405 /// Maximum supported image 3D size.
406 pub max_image_3d_size: image::Size,
407 /// Maximum supported image cube size.
408 pub max_image_cube_size: image::Size,
409 /// Maximum supporter image array size.
410 pub max_image_array_layers: image::Layer,
411 /// Maximum number of elements for the BufferView to see.
412 pub max_texel_elements: usize,
413 ///
414 pub max_uniform_buffer_range: buffer::Offset,
415 ///
416 pub max_storage_buffer_range: buffer::Offset,
417 ///
418 pub max_push_constants_size: usize,
419 ///
420 pub max_memory_allocation_count: usize,
421 ///
422 pub max_sampler_allocation_count: usize,
423 ///
424 pub max_bound_descriptor_sets: pso::DescriptorSetIndex,
425 ///
426 pub max_framebuffer_layers: usize,
427 ///
428 pub descriptor_limits: DescriptorLimits,
429
430 /// Maximum number of vertex input attributes that can be specified for a graphics pipeline.
431 pub max_vertex_input_attributes: usize,
432 /// Maximum number of vertex buffers that can be specified for providing vertex attributes to a graphics pipeline.
433 pub max_vertex_input_bindings: usize,
434 /// Maximum vertex input attribute offset that can be added to the vertex input binding stride.
435 pub max_vertex_input_attribute_offset: usize,
436 /// Maximum vertex input binding stride that can be specified in a vertex input binding.
437 pub max_vertex_input_binding_stride: usize,
438 /// Maximum number of components of output variables which can be output by a vertex shader.
439 pub max_vertex_output_components: usize,
440
441 /// Maximum number of vertices for each patch.
442 pub max_patch_size: pso::PatchSize,
443 ///
444 pub max_geometry_shader_invocations: usize,
445 ///
446 pub max_geometry_input_components: usize,
447 ///
448 pub max_geometry_output_components: usize,
449 ///
450 pub max_geometry_output_vertices: usize,
451 ///
452 pub max_geometry_total_output_components: usize,
453 ///
454 pub max_fragment_input_components: usize,
455 ///
456 pub max_fragment_output_attachments: usize,
457 ///
458 pub max_fragment_dual_source_attachments: usize,
459 ///
460 pub max_fragment_combined_output_resources: usize,
461
462 ///
463 pub max_compute_shared_memory_size: usize,
464 ///
465 pub max_compute_work_group_count: WorkGroupCount,
466 ///
467 pub max_compute_work_group_invocations: usize,
468 ///
469 pub max_compute_work_group_size: [u32; 3],
470
471 ///
472 pub max_draw_indexed_index_value: IndexCount,
473 ///
474 pub max_draw_indirect_count: InstanceCount,
475
476 ///
477 pub max_sampler_lod_bias: f32,
478 /// Maximum degree of sampler anisotropy.
479 pub max_sampler_anisotropy: f32,
480
481 /// Maximum number of viewports.
482 pub max_viewports: usize,
483 ///
484 pub max_viewport_dimensions: [image::Size; 2],
485 ///
486 pub max_framebuffer_extent: image::Extent,
487
488 ///
489 pub min_memory_map_alignment: usize,
490 ///
491 pub buffer_image_granularity: buffer::Offset,
492 /// The alignment of the start of buffer used as a texel buffer, in bytes, non-zero.
493 pub min_texel_buffer_offset_alignment: buffer::Offset,
494 /// The alignment of the start of buffer used for uniform buffer updates, in bytes, non-zero.
495 pub min_uniform_buffer_offset_alignment: buffer::Offset,
496 /// The alignment of the start of buffer used as a storage buffer, in bytes, non-zero.
497 pub min_storage_buffer_offset_alignment: buffer::Offset,
498 /// Number of samples supported for color attachments of framebuffers (floating/fixed point).
499 pub framebuffer_color_sample_counts: image::NumSamples,
500 /// Number of samples supported for depth attachments of framebuffers.
501 pub framebuffer_depth_sample_counts: image::NumSamples,
502 /// Number of samples supported for stencil attachments of framebuffers.
503 pub framebuffer_stencil_sample_counts: image::NumSamples,
504 /// Timestamp queries are supported on all compute and graphics queues.
505 pub timestamp_compute_and_graphics: bool,
506 /// Maximum number of color attachments that can be used by a subpass in a render pass.
507 pub max_color_attachments: usize,
508 ///
509 pub standard_sample_locations: bool,
510 /// The alignment of the start of the buffer used as a GPU copy source, in bytes, non-zero.
511 pub optimal_buffer_copy_offset_alignment: buffer::Offset,
512 /// The alignment of the row pitch of the texture data stored in a buffer that is
513 /// used in a GPU copy operation, in bytes, non-zero.
514 pub optimal_buffer_copy_pitch_alignment: buffer::Offset,
515 /// Size and alignment in bytes that bounds concurrent access to host-mapped device memory.
516 pub non_coherent_atom_size: usize,
517
518 /// The alignment of the vertex buffer stride.
519 pub min_vertex_input_binding_stride_alignment: buffer::Offset,
520}
521
522/// Feature capabilities related to Descriptor Indexing.
523#[derive(Clone, Copy, Debug, Default, PartialEq)]
524#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
525pub struct DescriptorIndexingProperties {
526 ///
527 pub shader_uniform_buffer_array_non_uniform_indexing_native: bool,
528 ///
529 pub shader_sampled_image_array_non_uniform_indexing_native: bool,
530 ///
531 pub shader_storage_buffer_array_non_uniform_indexing_native: bool,
532 ///
533 pub shader_storage_image_array_non_uniform_indexing_native: bool,
534 ///
535 pub shader_input_attachment_array_non_uniform_indexing_native: bool,
536 ///
537 pub quad_divergent_implicit_lod: bool,
538}
539
540/// Resource limits related to the Mesh Shaders.
541#[derive(Clone, Copy, Debug, Default, PartialEq)]
542#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
543pub struct MeshShaderProperties {
544 /// The maximum number of local workgroups that can be launched by a single draw mesh tasks command
545 pub max_draw_mesh_tasks_count: u32,
546 /// The maximum total number of task shader invocations in a single local workgroup. The product of the X, Y, and
547 /// Z sizes, as specified by the LocalSize execution mode in shader modules or by the object decorated by the
548 /// WorkgroupSize decoration, must be less than or equal to this limit.
549 pub max_task_work_group_invocations: u32,
550 /// The maximum size of a local task workgroup. These three values represent the maximum local workgroup size in
551 /// the X, Y, and Z dimensions, respectively. The x, y, and z sizes, as specified by the LocalSize execution mode
552 /// or by the object decorated by the WorkgroupSize decoration in shader modules, must be less than or equal to
553 /// the corresponding limit.
554 pub max_task_work_group_size: [u32; 3],
555 /// The maximum number of bytes that the task shader can use in total for shared and output memory combined.
556 pub max_task_total_memory_size: u32,
557 /// The maximum number of output tasks a single task shader workgroup can emit.
558 pub max_task_output_count: u32,
559 /// The maximum total number of mesh shader invocations in a single local workgroup. The product of the X, Y, and
560 /// Z sizes, as specified by the LocalSize execution mode in shader modules or by the object decorated by the
561 /// WorkgroupSize decoration, must be less than or equal to this limit.
562 pub max_mesh_work_group_invocations: u32,
563 /// The maximum size of a local mesh workgroup. These three values represent the maximum local workgroup size in
564 /// the X, Y, and Z dimensions, respectively. The x, y, and z sizes, as specified by the LocalSize execution mode
565 /// or by the object decorated by the WorkgroupSize decoration in shader modules, must be less than or equal to the
566 /// corresponding limit.
567 pub max_mesh_work_group_size: [u32; 3],
568 /// The maximum number of bytes that the mesh shader can use in total for shared and output memory combined.
569 pub max_mesh_total_memory_size: u32,
570 /// The maximum number of vertices a mesh shader output can store.
571 pub max_mesh_output_vertices: u32,
572 /// The maximum number of primitives a mesh shader output can store.
573 pub max_mesh_output_primitives: u32,
574 /// The maximum number of multi-view views a mesh shader can use.
575 pub max_mesh_multiview_view_count: u32,
576 /// The granularity with which mesh vertex outputs are allocated. The value can be used to compute the memory size
577 /// used by the mesh shader, which must be less than or equal to maxMeshTotalMemorySize.
578 pub mesh_output_per_vertex_granularity: u32,
579 /// The granularity with which mesh outputs qualified as per-primitive are allocated. The value can be used to
580 /// compute the memory size used by the mesh shader, which must be less than or equal to
581 pub mesh_output_per_primitive_granularity: u32,
582}
583
584/// Resource limits related to the reduction samplers.
585#[derive(Clone, Copy, Debug, Default, PartialEq)]
586#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
587pub struct SamplerReductionProperties {
588 /// Support for the minimum set of required formats support min/max filtering
589 pub single_component_formats: bool,
590 /// Support for the non-identity component mapping of the image when doing min/max filtering.
591 pub image_component_mapping: bool,
592}
593
594/// Propterties to indicate when the backend does not support full vulkan compliance.
595#[derive(Clone, Copy, Debug, Default, PartialEq)]
596#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
597pub struct DownlevelProperties {
598 /// Supports compute shaders.
599 pub compute_shaders: bool,
600 /// Which collections of features shaders support. Defined in terms of D3D's shader models.
601 pub shader_model: DownlevelShaderModel,
602 /// Supports creating storage images.
603 pub storage_images: bool,
604 /// Supports RODS
605 pub read_only_depth_stencil: bool,
606 /// Supports copies to/from device-local memory and device-local images.
607 pub device_local_image_copies: bool,
608 /// Supports textures with mipmaps which are non power of two.
609 pub non_power_of_two_mipmapped_textures: bool,
610}
611
612impl DownlevelProperties {
613 /// Enables all properties for a vulkan-complient backend.
614 pub fn all_enabled() -> Self {
615 Self {
616 compute_shaders: true,
617 shader_model: DownlevelShaderModel::ShaderModel5,
618 storage_images: true,
619 read_only_depth_stencil: true,
620 device_local_image_copies: true,
621 non_power_of_two_mipmapped_textures: true,
622 }
623 }
624}
625
626/// Collections of shader features shaders support if they support less than vulkan does.
627#[derive(Clone, Copy, Debug, PartialEq)]
628#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
629pub enum DownlevelShaderModel {
630 /// Extremely limited shaders, including a total instruction limit.
631 ShaderModel2,
632 /// Missing minor features and storage images.
633 ShaderModel4,
634 /// Vulkan shaders are SM5
635 ShaderModel5,
636}
637
638impl Default for DownlevelShaderModel {
639 fn default() -> Self {
640 Self::ShaderModel2
641 }
642}
643
644/// An enum describing the type of an index value in a slice's index buffer
645#[allow(missing_docs)]
646#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
648#[repr(u8)]
649pub enum IndexType {
650 U16,
651 U32,
652}
653
654/// Error creating an instance of a backend on the platform that
655/// doesn't support this backend.
656#[derive(Copy, Clone, Debug, Eq, PartialEq, thiserror::Error)]
657#[error("Backend is not supported on this platform")]
658pub struct UnsupportedBackend;
659
660#[derive(Clone, Copy, Debug, PartialEq)]
661#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
662/// Physical device limits for external memory management
663pub struct ExternalMemoryLimits {
664 /// Alignment required for an imported host pointer
665 pub min_imported_host_pointer_alignment: u64,
666}
667impl Default for ExternalMemoryLimits {
668 fn default() -> Self {
669 Self {
670 min_imported_host_pointer_alignment: 0,
671 }
672 }
673}
674
675/// An instantiated backend.
676///
677/// Any startup the backend needs to perform will be done when creating the type that implements
678/// `Instance`.
679///
680/// # Examples
681///
682/// ```rust
683/// # extern crate gfx_backend_empty;
684/// # extern crate gfx_hal;
685/// use gfx_backend_empty as backend;
686/// use gfx_hal::Instance;
687///
688/// // Create a concrete instance of our backend (this is backend-dependent and may be more
689/// // complicated for some backends).
690/// let instance = backend::Instance::create("My App", 1).unwrap();
691/// // We can get a list of the available adapters, which are either physical graphics
692/// // devices, or virtual adapters. Because we are using the dummy `empty` backend,
693/// // there will be nothing in this list.
694/// for (idx, adapter) in instance.enumerate_adapters().iter().enumerate() {
695/// println!("Adapter {}: {:?}", idx, adapter.info);
696/// }
697/// ```
698pub trait Instance<B: Backend>: Any + Send + Sync + Sized {
699 /// Create a new instance.
700 ///
701 /// # Arguments
702 ///
703 /// * `name` - name of the application using the API.
704 /// * `version` - free form representation of the application's version.
705 ///
706 /// This metadata is passed further down the graphics stack.
707 ///
708 /// # Errors
709 ///
710 /// Returns an `Err` variant if the requested backend [is not supported
711 /// on the current platform][UnsupportedBackend].
712 fn create(name: &str, version: u32) -> Result<Self, UnsupportedBackend>;
713
714 /// Return all available [graphics adapters][adapter::Adapter].
715 fn enumerate_adapters(&self) -> Vec<adapter::Adapter<B>>;
716
717 /// Create a new [surface][window::Surface].
718 ///
719 /// Surfaces can be used to render to windows.
720 ///
721 /// # Safety
722 ///
723 /// This method can cause undefined behavior if `raw_window_handle` isn't
724 /// a handle to a valid window for the current platform.
725 unsafe fn create_surface(
726 &self,
727 raw_window_handle: &impl raw_window_handle::HasRawWindowHandle,
728 ) -> Result<B::Surface, window::InitError>;
729
730 /// Destroy a surface, freeing the resources associated with it and
731 /// releasing it from this graphics API.
732 ///
733 /// # Safety
734 ///
735 unsafe fn destroy_surface(&self, surface: B::Surface);
736
737 /// Create a new [surface][window::Surface] from a [display plane][display::DisplayPlane].
738 ///
739 /// Surfaces can be used to render to windows.
740 ///
741 /// # Safety
742 ///
743 /// This method can cause undefined behavior if `raw_window_handle` isn't
744 /// a handle to a valid window for the current platform.
745 unsafe fn create_display_plane_surface<'a>(
746 &self,
747 display_plane: &display::DisplayPlane<'a, B>,
748 plane_stack_index: u32,
749 transformation: display::SurfaceTransform,
750 alpha: display::DisplayPlaneAlpha,
751 image_extent: window::Extent2D,
752 ) -> Result<B::Surface, display::DisplayPlaneSurfaceError>;
753}
754
755/// A strongly-typed index to a particular `MemoryType`.
756#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
757#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
758pub struct MemoryTypeId(pub usize);
759
760impl From<usize> for MemoryTypeId {
761 fn from(id: usize) -> Self {
762 MemoryTypeId(id)
763 }
764}
765
766struct PseudoVec<T>(Option<T>);
767
768impl<T> Extend<T> for PseudoVec<T> {
769 fn extend<I: IntoIterator<Item = T>>(&mut self, into_iter: I) {
770 let mut iter = into_iter.into_iter();
771 self.0 = iter.next();
772 assert!(iter.next().is_none());
773 }
774}
775
776/// Wraps together all the types needed for a graphics backend.
777///
778/// Each backend module, such as OpenGL or Metal, will implement this trait
779/// with its own concrete types.
780pub trait Backend: 'static + Sized + Eq + Clone + Hash + fmt::Debug + Any + Send + Sync {
781 /// The corresponding [instance][Instance] type for this backend.
782 type Instance: Instance<Self>;
783 /// The corresponding [physical device][adapter::PhysicalDevice] type for this backend.
784 type PhysicalDevice: adapter::PhysicalDevice<Self>;
785 /// The corresponding [logical device][device::Device] type for this backend.
786 type Device: device::Device<Self>;
787 /// The corresponding [surface][window::PresentationSurface] type for this backend.
788 type Surface: window::PresentationSurface<Self>;
789
790 /// The corresponding [queue family][queue::QueueFamily] type for this backend.
791 type QueueFamily: queue::QueueFamily;
792 /// The corresponding [command queue][queue::Queue] type for this backend.
793 type Queue: queue::Queue<Self>;
794 /// The corresponding [command buffer][command::CommandBuffer] type for this backend.
795 type CommandBuffer: command::CommandBuffer<Self>;
796
797 /// The corresponding shader module type for this backend.
798 type ShaderModule: fmt::Debug + Any + Send + Sync;
799 /// The corresponding render pass type for this backend.
800 type RenderPass: fmt::Debug + Any + Send + Sync;
801 /// The corresponding framebuffer type for this backend.
802 type Framebuffer: fmt::Debug + Any + Send + Sync;
803
804 /// The corresponding memory type for this backend.
805 type Memory: fmt::Debug + Any + Send + Sync;
806 /// The corresponding [command pool][pool::CommandPool] type for this backend.
807 type CommandPool: pool::CommandPool<Self>;
808
809 /// The corresponding buffer type for this backend.
810 type Buffer: fmt::Debug + Any + Send + Sync;
811 /// The corresponding buffer view type for this backend.
812 type BufferView: fmt::Debug + Any + Send + Sync;
813 /// The corresponding image type for this backend.
814 type Image: fmt::Debug + Any + Send + Sync;
815 /// The corresponding image view type for this backend.
816 type ImageView: fmt::Debug + Any + Send + Sync;
817 /// The corresponding sampler type for this backend.
818 type Sampler: fmt::Debug + Any + Send + Sync;
819
820 /// The corresponding compute pipeline type for this backend.
821 type ComputePipeline: fmt::Debug + Any + Send + Sync;
822 /// The corresponding graphics pipeline type for this backend.
823 type GraphicsPipeline: fmt::Debug + Any + Send + Sync;
824 /// The corresponding pipeline cache type for this backend.
825 type PipelineCache: fmt::Debug + Any + Send + Sync;
826 /// The corresponding pipeline layout type for this backend.
827 type PipelineLayout: fmt::Debug + Any + Send + Sync;
828 /// The corresponding [descriptor pool][pso::DescriptorPool] type for this backend.
829 type DescriptorPool: pso::DescriptorPool<Self>;
830 /// The corresponding descriptor set type for this backend.
831 type DescriptorSet: fmt::Debug + Any + Send + Sync;
832 /// The corresponding descriptor set layout type for this backend.
833 type DescriptorSetLayout: fmt::Debug + Any + Send + Sync;
834
835 /// The corresponding fence type for this backend.
836 type Fence: fmt::Debug + Any + Send + Sync;
837 /// The corresponding semaphore type for this backend.
838 type Semaphore: fmt::Debug + Any + Send + Sync;
839 /// The corresponding event type for this backend.
840 type Event: fmt::Debug + Any + Send + Sync;
841 /// The corresponding query pool type for this backend.
842 type QueryPool: fmt::Debug + Any + Send + Sync;
843 /// The corresponding display type for this backend.
844 type Display: fmt::Debug + Any + Send + Sync;
845 /// The corresponding display mode type for this backend
846 type DisplayMode: fmt::Debug + Any + Send + Sync;
847}