Debian Codegraph @

third_party/rust/wgpu-hal/src/gles/mod.rs

raw
1 /*!
2 # OpenGL ES3 API (aka GLES3).
3
4 Designed to work on Linux and Android, with context provided by EGL.
5
6 ## Texture views
7
8 GLES3 doesn't really have separate texture view objects. We have to remember the
9 original texture and the sub-range into it. Problem is, however, that there is
10 no way to expose a subset of array layers or mip levels of a sampled texture.
11
12 ## Binding model
13
14 Binding model is very different from WebGPU, especially with regards to samplers.
15 GLES3 has sampler objects, but they aren't separately bindable to the shaders.
16 Each sampled texture is exposed to the shader as a combined texture-sampler binding.
17
18 When building the pipeline layout, we linearize binding entries based on the groups
19 (uniform/storage buffers, uniform/storage textures), and record the mapping into
20 `BindGroupLayoutInfo`.
21 When a pipeline gets created, and we track all the texture-sampler associations
22 from the static use in the shader.
23 We only support at most one sampler used with each texture so far. The linear index
24 of this sampler is stored per texture slot in `SamplerBindMap` array.
25
26 The texture-sampler pairs get potentially invalidated in 2 places:
27 - when a new pipeline is set, we update the linear indices of associated samplers
28 - when a new bind group is set, we update both the textures and the samplers
29
30 We expect that the changes to sampler states between any 2 pipelines of the same layout
31 will be minimal, if any.
32
33 ## Vertex data
34
35 Generally, vertex buffers are marked as dirty and lazily bound on draw.
36
37 GLES3 doesn't support `first_instance` semantics. However, it's easy to support,
38 since we are forced to do late binding anyway. We just adjust the offsets
39 into the vertex data.
40
41 ### Old path
42
43 In GLES-3.0 and WebGL2, vertex buffer layout is provided
44 together with the actual buffer binding.
45 We invalidate the attributes on the vertex buffer change, and re-bind them.
46
47 ### New path
48
49 In GLES-3.1 and higher, the vertex buffer layout can be declared separately
50 from the vertex data itself. This mostly matches WebGPU, however there is a catch:
51 `stride` needs to be specified with the data, not as a part of the layout.
52
53 To address this, we invalidate the vertex buffers based on:
54 - whether or not `first_instance` is used
55 - stride has changed
56
57 ## Handling of `base_vertex`, `first_instance`, and `first_vertex`
58
59 Between indirect, the lack of `first_instance` semantics, and the availability of `gl_BaseInstance`
60 in shaders, getting buffers and builtins to work correctly is a bit tricky.
61
62 We never emulate `base_vertex` and gl_VertexID behaves as `@builtin(vertex_index)` does, so we
63 never need to do anything about that.
64
65 ### GL 4.2+ with ARB_shader_draw_parameters
66
67 - `@builtin(instance_index)` translates to `gl_InstanceID + gl_BaseInstance`
68 - We bind instance buffers without any offset emulation.
69 - We advertise support for the `INDIRECT_FIRST_INSTANCE` feature.
70
71 While we can theoretically have a card with 4.2+ support but without ARB_shader_draw_parameters,
72 we don't bother with that combination.
73
74 ### GLES & GL 4.1
75
76 - `@builtin(instance_index)` translates to `gl_InstanceID + naga_vs_first_instance`
77 - We bind instance buffers with offset emulation.
78 - We _do not_ advertise support for `INDIRECT_FIRST_INSTANCE` and cpu-side pretend the `first_instance` is 0 on indirect calls.
79
80 */
81
82 ///cbindgen:ignore
83 #[cfg(not(any(windows, webgl)))]
84 mod egl;
85 #[cfg(Emscripten)]
86 mod emscripten;
87 #[cfg(webgl)]
88 mod web;
89 #[cfg(windows)]
90 mod wgl;
91
92 mod adapter;
93 mod command;
94 mod conv;
95 mod device;
96 mod fence;
97 mod queue;
98
99 pub use fence::Fence;
100
101 #[cfg(not(any(windows, webgl)))]
102 pub use self::egl::{AdapterContext, AdapterContextLock};
103 #[cfg(not(any(windows, webgl)))]
104 use self::egl::{Instance, Surface};
105
106 #[cfg(webgl)]
107 pub use self::web::AdapterContext;
108 #[cfg(webgl)]
109 use self::web::{Instance, Surface};
110
111 #[cfg(windows)]
112 use self::wgl::AdapterContext;
113 #[cfg(windows)]
114 use self::wgl::{Instance, Surface};
115
116 use alloc::{boxed::Box, string::String, string::ToString as _, sync::Arc, vec::Vec};
117 use core::{
118 fmt,
119 ops::Range,
120 sync::atomic::{AtomicU32, AtomicU8},
121 };
122 use parking_lot::Mutex;
123
124 use arrayvec::ArrayVec;
125 use glow::HasContext;
126 use naga::FastHashMap;
127
128 use crate::{CopyExtent, TextureDescriptor};
129
130 #[derive(Clone, Debug)]
131 pub struct Api;
132
133 //Note: we can support more samplers if not every one of them is used at a time,
134 // but it probably doesn't worth it.
135 const MAX_TEXTURE_SLOTS: usize = 16;
136 const MAX_SAMPLERS: usize = 16;
137 const MAX_VERTEX_ATTRIBUTES: usize = 16;
138 const ZERO_BUFFER_SIZE: usize = 256 << 10;
139 const MAX_PUSH_CONSTANTS: usize = 64;
140 // We have to account for each push constant may need to be set for every shader.
141 const MAX_PUSH_CONSTANT_COMMANDS: usize = MAX_PUSH_CONSTANTS * crate::MAX_CONCURRENT_SHADER_STAGES;
142
143 impl crate::Api for Api {
144 type Instance = Instance;
145 type Surface = Surface;
146 type Adapter = Adapter;
147 type Device = Device;
148
149 type Queue = Queue;
150 type CommandEncoder = CommandEncoder;
151 type CommandBuffer = CommandBuffer;
152
153 type Buffer = Buffer;
154 type Texture = Texture;
155 type SurfaceTexture = Texture;
156 type TextureView = TextureView;
157 type Sampler = Sampler;
158 type QuerySet = QuerySet;
159 type Fence = Fence;
160 type AccelerationStructure = AccelerationStructure;
161 type PipelineCache = PipelineCache;
162
163 type BindGroupLayout = BindGroupLayout;
164 type BindGroup = BindGroup;
165 type PipelineLayout = PipelineLayout;
166 type ShaderModule = ShaderModule;
167 type RenderPipeline = RenderPipeline;
168 type ComputePipeline = ComputePipeline;
169 }
170
171 crate::impl_dyn_resource!(
172 Adapter,
173 AccelerationStructure,
174 BindGroup,
175 BindGroupLayout,
176 Buffer,
177 CommandBuffer,
178 CommandEncoder,
179 ComputePipeline,
180 Device,
181 Fence,
182 Instance,
183 PipelineCache,
184 PipelineLayout,
185 QuerySet,
186 Queue,
187 RenderPipeline,
188 Sampler,
189 ShaderModule,
190 Surface,
191 Texture,
192 TextureView
193 );
194
195 bitflags::bitflags! {
196 /// Flags that affect internal code paths but do not
197 /// change the exposed feature set.
198 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
199 struct PrivateCapabilities: u32 {
200 /// Indicates support for `glBufferStorage` allocation.
201 const BUFFER_ALLOCATION = 1 << 0;
202 /// Support explicit layouts in shader.
203 const SHADER_BINDING_LAYOUT = 1 << 1;
204 /// Support extended shadow sampling instructions.
205 const SHADER_TEXTURE_SHADOW_LOD = 1 << 2;
206 /// Support memory barriers.
207 const MEMORY_BARRIERS = 1 << 3;
208 /// Vertex buffer layouts separate from the data.
209 const VERTEX_BUFFER_LAYOUT = 1 << 4;
210 /// Indicates that buffers used as `GL_ELEMENT_ARRAY_BUFFER` may be created / initialized / used
211 /// as other targets, if not present they must not be mixed with other targets.
212 const INDEX_BUFFER_ROLE_CHANGE = 1 << 5;
213 /// Supports `glGetBufferSubData`
214 const GET_BUFFER_SUB_DATA = 1 << 7;
215 /// Supports `f16` color buffers
216 const COLOR_BUFFER_HALF_FLOAT = 1 << 8;
217 /// Supports `f11/f10` and `f32` color buffers
218 const COLOR_BUFFER_FLOAT = 1 << 9;
219 /// Supports query buffer objects.
220 const QUERY_BUFFERS = 1 << 11;
221 /// Supports 64 bit queries via `glGetQueryObjectui64v`
222 const QUERY_64BIT = 1 << 12;
223 /// Supports `glTexStorage2D`, etc.
224 const TEXTURE_STORAGE = 1 << 13;
225 /// Supports `push_debug_group`, `pop_debug_group` and `debug_message_insert`.
226 const DEBUG_FNS = 1 << 14;
227 /// Supports framebuffer invalidation.
228 const INVALIDATE_FRAMEBUFFER = 1 << 15;
229 /// Indicates support for `glDrawElementsInstancedBaseVertexBaseInstance` and `ARB_shader_draw_parameters`
230 ///
231 /// When this is true, instance offset emulation via vertex buffer rebinding and a shader uniform will be disabled.
232 const FULLY_FEATURED_INSTANCING = 1 << 16;
233 }
234 }
235
236 bitflags::bitflags! {
237 /// Flags that indicate necessary workarounds for specific devices or driver bugs
238 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
239 struct Workarounds: u32 {
240 // Needs workaround for Intel Mesa bug:
241 // https://gitlab.freedesktop.org/mesa/mesa/-/issues/2565.
242 //
243 // This comment
244 // (https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/4972/diffs?diff_id=75888#22f5d1004713c9bbf857988c7efb81631ab88f99_323_327)
245 // seems to indicate all skylake models are effected.
246 const MESA_I915_SRGB_SHADER_CLEAR = 1 << 0;
247 /// Buffer map must emulated because it is not supported natively
248 const EMULATE_BUFFER_MAP = 1 << 1;
249 }
250 }
251
252 type BindTarget = u32;
253
254 #[derive(Debug, Clone, Copy)]
255 enum VertexAttribKind {
256 Float, // glVertexAttribPointer
257 Integer, // glVertexAttribIPointer
258 //Double, // glVertexAttribLPointer
259 }
260
261 impl Default for VertexAttribKind {
262 fn default() -> Self {
263 Self::Float
264 }
265 }
266
267 #[derive(Clone, Debug)]
268 pub struct TextureFormatDesc {
269 pub internal: u32,
270 pub external: u32,
271 pub data_type: u32,
272 }
273
274 struct AdapterShared {
275 context: AdapterContext,
276 private_caps: PrivateCapabilities,
277 features: wgt::Features,
278 limits: wgt::Limits,
279 workarounds: Workarounds,
280 options: wgt::GlBackendOptions,
281 shading_language_version: naga::back::glsl::Version,
282 next_shader_id: AtomicU32,
283 program_cache: Mutex<ProgramCache>,
284 es: bool,
285
286 /// Result of `gl.get_parameter_i32(glow::MAX_SAMPLES)`.
287 /// Cached here so it doesn't need to be queried every time texture format capabilities are requested.
288 /// (this has been shown to be a significant enough overhead)
289 max_msaa_samples: i32,
290 }
291
292 pub struct Adapter {
293 shared: Arc<AdapterShared>,
294 }
295
296 pub struct Device {
297 shared: Arc<AdapterShared>,
298 main_vao: glow::VertexArray,
299 #[cfg(all(native, feature = "renderdoc"))]
300 render_doc: crate::auxil::renderdoc::RenderDoc,
301 counters: Arc<wgt::HalCounters>,
302 }
303
304 impl Drop for Device {
305 fn drop(&mut self) {
306 let gl = &self.shared.context.lock();
307 unsafe { gl.delete_vertex_array(self.main_vao) };
308 }
309 }
310
311 pub struct ShaderClearProgram {
312 pub program: glow::Program,
313 pub color_uniform_location: glow::UniformLocation,
314 }
315
316 pub struct Queue {
317 shared: Arc<AdapterShared>,
318 features: wgt::Features,
319 draw_fbo: glow::Framebuffer,
320 copy_fbo: glow::Framebuffer,
321 /// Shader program used to clear the screen for [`Workarounds::MESA_I915_SRGB_SHADER_CLEAR`]
322 /// devices.
323 shader_clear_program: Option<ShaderClearProgram>,
324 /// Keep a reasonably large buffer filled with zeroes, so that we can implement `ClearBuffer` of
325 /// zeroes by copying from it.
326 zero_buffer: glow::Buffer,
327 temp_query_results: Mutex<Vec<u64>>,
328 draw_buffer_count: AtomicU8,
329 current_index_buffer: Mutex<Option<glow::Buffer>>,
330 }
331
332 impl Drop for Queue {
333 fn drop(&mut self) {
334 let gl = &self.shared.context.lock();
335 unsafe { gl.delete_framebuffer(self.draw_fbo) };
336 unsafe { gl.delete_framebuffer(self.copy_fbo) };
337 unsafe { gl.delete_buffer(self.zero_buffer) };
338 }
339 }
340
341 #[derive(Clone, Debug)]
342 pub struct Buffer {
343 raw: Option<glow::Buffer>,
344 target: BindTarget,
345 size: wgt::BufferAddress,
346 map_flags: u32,
347 data: Option<Arc<MaybeMutex<Vec<u8>>>>,
348 offset_of_current_mapping: Arc<MaybeMutex<wgt::BufferAddress>>,
349 }
350
351 #[cfg(send_sync)]
352 unsafe impl Sync for Buffer {}
353 #[cfg(send_sync)]
354 unsafe impl Send for Buffer {}
355
356 impl crate::DynBuffer for Buffer {}
357
358 #[derive(Clone, Debug)]
359 pub enum TextureInner {
360 Renderbuffer {
361 raw: glow::Renderbuffer,
362 },
363 DefaultRenderbuffer,
364 Texture {
365 raw: glow::Texture,
366 target: BindTarget,
367 },
368 #[cfg(webgl)]
369 ExternalFramebuffer {
370 inner: web_sys::WebGlFramebuffer,
371 },
372 }
373
374 #[cfg(send_sync)]
375 unsafe impl Sync for TextureInner {}
376 #[cfg(send_sync)]
377 unsafe impl Send for TextureInner {}
378
379 impl TextureInner {
380 fn as_native(&self) -> (glow::Texture, BindTarget) {
381 match *self {
382 Self::Renderbuffer { .. } | Self::DefaultRenderbuffer => {
383 panic!("Unexpected renderbuffer");
384 }
385 Self::Texture { raw, target } => (raw, target),
386 #[cfg(webgl)]
387 Self::ExternalFramebuffer { .. } => panic!("Unexpected external framebuffer"),
388 }
389 }
390 }
391
392 #[derive(Debug)]
393 pub struct Texture {
394 pub inner: TextureInner,
395 pub drop_guard: Option<crate::DropGuard>,
396 pub mip_level_count: u32,
397 pub array_layer_count: u32,
398 pub format: wgt::TextureFormat,
399 #[allow(unused)]
400 pub format_desc: TextureFormatDesc,
401 pub copy_size: CopyExtent,
402 }
403
404 impl crate::DynTexture for Texture {}
405 impl crate::DynSurfaceTexture for Texture {}
406
407 impl core::borrow::Borrow<dyn crate::DynTexture> for Texture {
408 fn borrow(&self) -> &dyn crate::DynTexture {
409 self
410 }
411 }
412
413 impl Texture {
414 pub fn default_framebuffer(format: wgt::TextureFormat) -> Self {
415 Self {
416 inner: TextureInner::DefaultRenderbuffer,
417 drop_guard: None,
418 mip_level_count: 1,
419 array_layer_count: 1,
420 format,
421 format_desc: TextureFormatDesc {
422 internal: 0,
423 external: 0,
424 data_type: 0,
425 },
426 copy_size: CopyExtent {
427 width: 0,
428 height: 0,
429 depth: 0,
430 },
431 }
432 }
433
434 /// Returns the `target`, whether the image is 3d and whether the image is a cubemap.
435 fn get_info_from_desc(desc: &TextureDescriptor) -> u32 {
436 match desc.dimension {
437 // WebGL (1 and 2) as well as some GLES versions do not have 1D textures, so we are
438 // doing `TEXTURE_2D` instead
439 wgt::TextureDimension::D1 => glow::TEXTURE_2D,
440 wgt::TextureDimension::D2 => {
441 // HACK: detect a cube map; forces cube compatible textures to be cube textures
442 match (desc.is_cube_compatible(), desc.size.depth_or_array_layers) {
443 (false, 1) => glow::TEXTURE_2D,
444 (false, _) => glow::TEXTURE_2D_ARRAY,
445 (true, 6) => glow::TEXTURE_CUBE_MAP,
446 (true, _) => glow::TEXTURE_CUBE_MAP_ARRAY,
447 }
448 }
449 wgt::TextureDimension::D3 => glow::TEXTURE_3D,
450 }
451 }
452
453 /// More information can be found in issues #1614 and #1574
454 fn log_failing_target_heuristics(view_dimension: wgt::TextureViewDimension, target: u32) {
455 let expected_target = match view_dimension {
456 wgt::TextureViewDimension::D1 => glow::TEXTURE_2D,
457 wgt::TextureViewDimension::D2 => glow::TEXTURE_2D,
458 wgt::TextureViewDimension::D2Array => glow::TEXTURE_2D_ARRAY,
459 wgt::TextureViewDimension::Cube => glow::TEXTURE_CUBE_MAP,
460 wgt::TextureViewDimension::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY,
461 wgt::TextureViewDimension::D3 => glow::TEXTURE_3D,
462 };
463
464 if expected_target == target {
465 return;
466 }
467
468 let buffer;
469 let got = match target {
470 glow::TEXTURE_2D => "D2",
471 glow::TEXTURE_2D_ARRAY => "D2Array",
472 glow::TEXTURE_CUBE_MAP => "Cube",
473 glow::TEXTURE_CUBE_MAP_ARRAY => "CubeArray",
474 glow::TEXTURE_3D => "D3",
475 target => {
476 buffer = target.to_string();
477 &buffer
478 }
479 };
480
481 log::error!(
482 concat!(
483 "wgpu-hal heuristics assumed that ",
484 "the view dimension will be equal to `{}` rather than `{:?}`.\n",
485 "`D2` textures with ",
486 "`depth_or_array_layers == 1` ",
487 "are assumed to have view dimension `D2`\n",
488 "`D2` textures with ",
489 "`depth_or_array_layers > 1` ",
490 "are assumed to have view dimension `D2Array`\n",
491 "`D2` textures with ",
492 "`depth_or_array_layers == 6` ",
493 "are assumed to have view dimension `Cube`\n",
494 "`D2` textures with ",
495 "`depth_or_array_layers > 6 && depth_or_array_layers % 6 == 0` ",
496 "are assumed to have view dimension `CubeArray`\n",
497 ),
498 got,
499 view_dimension,
500 );
501 }
502 }
503
504 #[derive(Clone, Debug)]
505 pub struct TextureView {
506 inner: TextureInner,
507 aspects: crate::FormatAspects,
508 mip_levels: Range<u32>,
509 array_layers: Range<u32>,
510 format: wgt::TextureFormat,
511 }
512
513 impl crate::DynTextureView for TextureView {}
514
515 #[derive(Debug)]
516 pub struct Sampler {
517 raw: glow::Sampler,
518 }
519
520 impl crate::DynSampler for Sampler {}
521
522 #[derive(Debug)]
523 pub struct BindGroupLayout {
524 entries: Arc<[wgt::BindGroupLayoutEntry]>,
525 }
526
527 impl crate::DynBindGroupLayout for BindGroupLayout {}
528
529 #[derive(Debug)]
530 struct BindGroupLayoutInfo {
531 entries: Arc<[wgt::BindGroupLayoutEntry]>,
532 /// Mapping of resources, indexed by `binding`, into the whole layout space.
533 /// For texture resources, the value is the texture slot index.
534 /// For sampler resources, the value is the index of the sampler in the whole layout.
535 /// For buffers, the value is the uniform or storage slot index.
536 /// For unused bindings, the value is `!0`
537 binding_to_slot: Box<[u8]>,
538 }
539
540 #[derive(Debug)]
541 pub struct PipelineLayout {
542 group_infos: Box<[BindGroupLayoutInfo]>,
543 naga_options: naga::back::glsl::Options,
544 }
545
546 impl crate::DynPipelineLayout for PipelineLayout {}
547
548 impl PipelineLayout {
549 fn get_slot(&self, br: &naga::ResourceBinding) -> u8 {
550 let group_info = &self.group_infos[br.group as usize];
551 group_info.binding_to_slot[br.binding as usize]
552 }
553 }
554
555 #[derive(Debug)]
556 enum BindingRegister {
557 UniformBuffers,
558 StorageBuffers,
559 Textures,
560 Images,
561 }
562
563 #[derive(Debug)]
564 enum RawBinding {
565 Buffer {
566 raw: glow::Buffer,
567 offset: i32,
568 size: i32,
569 },
570 Texture {
571 raw: glow::Texture,
572 target: BindTarget,
573 aspects: crate::FormatAspects,
574 mip_levels: Range<u32>,
575 //TODO: array layers
576 },
577 Image(ImageBinding),
578 Sampler(glow::Sampler),
579 }
580
581 #[derive(Debug)]
582 pub struct BindGroup {
583 contents: Box<[RawBinding]>,
584 }
585
586 impl crate::DynBindGroup for BindGroup {}
587
588 type ShaderId = u32;
589
590 #[derive(Debug)]
591 pub struct ShaderModule {
592 naga: crate::NagaShader,
593 label: Option<String>,
594 id: ShaderId,
595 }
596
597 impl crate::DynShaderModule for ShaderModule {}
598
599 #[derive(Clone, Debug, Default)]
600 struct VertexFormatDesc {
601 element_count: i32,
602 element_format: u32,
603 attrib_kind: VertexAttribKind,
604 }
605
606 #[derive(Clone, Debug, Default)]
607 struct AttributeDesc {
608 location: u32,
609 offset: u32,
610 buffer_index: u32,
611 format_desc: VertexFormatDesc,
612 }
613
614 #[derive(Clone, Debug)]
615 struct BufferBinding {
616 raw: glow::Buffer,
617 offset: wgt::BufferAddress,
618 }
619
620 #[derive(Clone, Debug)]
621 struct ImageBinding {
622 raw: glow::Texture,
623 mip_level: u32,
624 array_layer: Option<u32>,
625 access: u32,
626 format: u32,
627 }
628
629 #[derive(Clone, Debug, Default, PartialEq)]
630 struct VertexBufferDesc {
631 step: wgt::VertexStepMode,
632 stride: u32,
633 }
634
635 #[derive(Clone, Debug)]
636 struct PushConstantDesc {
637 location: glow::UniformLocation,
638 ty: naga::TypeInner,
639 offset: u32,
640 size_bytes: u32,
641 }
642
643 #[cfg(send_sync)]
644 unsafe impl Sync for PushConstantDesc {}
645 #[cfg(send_sync)]
646 unsafe impl Send for PushConstantDesc {}
647
648 /// For each texture in the pipeline layout, store the index of the only
649 /// sampler (in this layout) that the texture is used with.
650 type SamplerBindMap = [Option<u8>; MAX_TEXTURE_SLOTS];
651
652 #[derive(Debug)]
653 struct PipelineInner {
654 program: glow::Program,
655 sampler_map: SamplerBindMap,
656 first_instance_location: Option<glow::UniformLocation>,
657 push_constant_descs: ArrayVec<PushConstantDesc, MAX_PUSH_CONSTANT_COMMANDS>,
658 }
659
660 #[derive(Clone, Debug)]
661 struct DepthState {
662 function: u32,
663 mask: bool,
664 }
665
666 #[derive(Clone, Debug, PartialEq)]
667 struct BlendComponent {
668 src: u32,
669 dst: u32,
670 equation: u32,
671 }
672
673 #[derive(Clone, Debug, PartialEq)]
674 struct BlendDesc {
675 alpha: BlendComponent,
676 color: BlendComponent,
677 }
678
679 #[derive(Clone, Debug, Default, PartialEq)]
680 struct ColorTargetDesc {
681 mask: wgt::ColorWrites,
682 blend: Option<BlendDesc>,
683 }
684
685 #[derive(PartialEq, Eq, Hash)]
686 struct ProgramStage {
687 naga_stage: naga::ShaderStage,
688 shader_id: ShaderId,
689 entry_point: String,
690 zero_initialize_workgroup_memory: bool,
691 }
692
693 #[derive(PartialEq, Eq, Hash)]
694 struct ProgramCacheKey {
695 stages: ArrayVec<ProgramStage, 3>,
696 group_to_binding_to_slot: Box<[Box<[u8]>]>,
697 }
698
699 type ProgramCache = FastHashMap<ProgramCacheKey, Result<Arc<PipelineInner>, crate::PipelineError>>;
700
701 #[derive(Debug)]
702 pub struct RenderPipeline {
703 inner: Arc<PipelineInner>,
704 primitive: wgt::PrimitiveState,
705 vertex_buffers: Box<[VertexBufferDesc]>,
706 vertex_attributes: Box<[AttributeDesc]>,
707 color_targets: Box<[ColorTargetDesc]>,
708 depth: Option<DepthState>,
709 depth_bias: wgt::DepthBiasState,
710 stencil: Option<StencilState>,
711 alpha_to_coverage_enabled: bool,
712 }
713
714 impl crate::DynRenderPipeline for RenderPipeline {}
715
716 #[cfg(send_sync)]
717 unsafe impl Sync for RenderPipeline {}
718 #[cfg(send_sync)]
719 unsafe impl Send for RenderPipeline {}
720
721 #[derive(Debug)]
722 pub struct ComputePipeline {
723 inner: Arc<PipelineInner>,
724 }
725
726 impl crate::DynComputePipeline for ComputePipeline {}
727
728 #[cfg(send_sync)]
729 unsafe impl Sync for ComputePipeline {}
730 #[cfg(send_sync)]
731 unsafe impl Send for ComputePipeline {}
732
733 #[derive(Debug)]
734 pub struct QuerySet {
735 queries: Box<[glow::Query]>,
736 target: BindTarget,
737 }
738
739 impl crate::DynQuerySet for QuerySet {}
740
741 #[derive(Debug)]
742 pub struct AccelerationStructure;
743
744 impl crate::DynAccelerationStructure for AccelerationStructure {}
745
746 #[derive(Debug)]
747 pub struct PipelineCache;
748
749 impl crate::DynPipelineCache for PipelineCache {}
750
751 #[derive(Clone, Debug, PartialEq)]
752 struct StencilOps {
753 pass: u32,
754 fail: u32,
755 depth_fail: u32,
756 }
757
758 impl Default for StencilOps {
759 fn default() -> Self {
760 Self {
761 pass: glow::KEEP,
762 fail: glow::KEEP,
763 depth_fail: glow::KEEP,
764 }
765 }
766 }
767
768 #[derive(Clone, Debug, PartialEq)]
769 struct StencilSide {
770 function: u32,
771 mask_read: u32,
772 mask_write: u32,
773 reference: u32,
774 ops: StencilOps,
775 }
776
777 impl Default for StencilSide {
778 fn default() -> Self {
779 Self {
780 function: glow::ALWAYS,
781 mask_read: 0xFF,
782 mask_write: 0xFF,
783 reference: 0,
784 ops: StencilOps::default(),
785 }
786 }
787 }
788
789 #[derive(Debug, Clone, Default)]
790 struct StencilState {
791 front: StencilSide,
792 back: StencilSide,
793 }
794
795 #[derive(Clone, Debug, Default, PartialEq)]
796 struct PrimitiveState {
797 front_face: u32,
798 cull_face: u32,
799 unclipped_depth: bool,
800 polygon_mode: u32,
801 }
802
803 type InvalidatedAttachments = ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>;
804
805 #[derive(Debug)]
806 enum Command {
807 Draw {
808 topology: u32,
809 first_vertex: u32,
810 vertex_count: u32,
811 first_instance: u32,
812 instance_count: u32,
813 first_instance_location: Option<glow::UniformLocation>,
814 },
815 DrawIndexed {
816 topology: u32,
817 index_type: u32,
818 index_count: u32,
819 index_offset: wgt::BufferAddress,
820 base_vertex: i32,
821 first_instance: u32,
822 instance_count: u32,
823 first_instance_location: Option<glow::UniformLocation>,
824 },
825 DrawIndirect {
826 topology: u32,
827 indirect_buf: glow::Buffer,
828 indirect_offset: wgt::BufferAddress,
829 first_instance_location: Option<glow::UniformLocation>,
830 },
831 DrawIndexedIndirect {
832 topology: u32,
833 index_type: u32,
834 indirect_buf: glow::Buffer,
835 indirect_offset: wgt::BufferAddress,
836 first_instance_location: Option<glow::UniformLocation>,
837 },
838 Dispatch([u32; 3]),
839 DispatchIndirect {
840 indirect_buf: glow::Buffer,
841 indirect_offset: wgt::BufferAddress,
842 },
843 ClearBuffer {
844 dst: Buffer,
845 dst_target: BindTarget,
846 range: crate::MemoryRange,
847 },
848 CopyBufferToBuffer {
849 src: Buffer,
850 src_target: BindTarget,
851 dst: Buffer,
852 dst_target: BindTarget,
853 copy: crate::BufferCopy,
854 },
855 #[cfg(webgl)]
856 CopyExternalImageToTexture {
857 src: wgt::CopyExternalImageSourceInfo,
858 dst: glow::Texture,
859 dst_target: BindTarget,
860 dst_format: wgt::TextureFormat,
861 dst_premultiplication: bool,
862 copy: crate::TextureCopy,
863 },
864 CopyTextureToTexture {
865 src: glow::Texture,
866 src_target: BindTarget,
867 dst: glow::Texture,
868 dst_target: BindTarget,
869 copy: crate::TextureCopy,
870 },
871 CopyBufferToTexture {
872 src: Buffer,
873 #[allow(unused)]
874 src_target: BindTarget,
875 dst: glow::Texture,
876 dst_target: BindTarget,
877 dst_format: wgt::TextureFormat,
878 copy: crate::BufferTextureCopy,
879 },
880 CopyTextureToBuffer {
881 src: glow::Texture,
882 src_target: BindTarget,
883 src_format: wgt::TextureFormat,
884 dst: Buffer,
885 #[allow(unused)]
886 dst_target: BindTarget,
887 copy: crate::BufferTextureCopy,
888 },
889 SetIndexBuffer(glow::Buffer),
890 BeginQuery(glow::Query, BindTarget),
891 EndQuery(BindTarget),
892 TimestampQuery(glow::Query),
893 CopyQueryResults {
894 query_range: Range<u32>,
895 dst: Buffer,
896 dst_target: BindTarget,
897 dst_offset: wgt::BufferAddress,
898 },
899 ResetFramebuffer {
900 is_default: bool,
901 },
902 BindAttachment {
903 attachment: u32,
904 view: TextureView,
905 depth_slice: Option<u32>,
906 },
907 ResolveAttachment {
908 attachment: u32,
909 dst: TextureView,
910 size: wgt::Extent3d,
911 },
912 InvalidateAttachments(InvalidatedAttachments),
913 SetDrawColorBuffers(u8),
914 ClearColorF {
915 draw_buffer: u32,
916 color: [f32; 4],
917 is_srgb: bool,
918 },
919 ClearColorU(u32, [u32; 4]),
920 ClearColorI(u32, [i32; 4]),
921 ClearDepth(f32),
922 ClearStencil(u32),
923 // Clearing both the depth and stencil buffer individually appears to
924 // result in the stencil buffer failing to clear, atleast in WebGL.
925 // It is also more efficient to emit a single command instead of two for
926 // this.
927 ClearDepthAndStencil(f32, u32),
928 BufferBarrier(glow::Buffer, wgt::BufferUses),
929 TextureBarrier(wgt::TextureUses),
930 SetViewport {
931 rect: crate::Rect<i32>,
932 depth: Range<f32>,
933 },
934 SetScissor(crate::Rect<i32>),
935 SetStencilFunc {
936 face: u32,
937 function: u32,
938 reference: u32,
939 read_mask: u32,
940 },
941 SetStencilOps {
942 face: u32,
943 write_mask: u32,
944 ops: StencilOps,
945 },
946 SetDepth(DepthState),
947 SetDepthBias(wgt::DepthBiasState),
948 ConfigureDepthStencil(crate::FormatAspects),
949 SetAlphaToCoverage(bool),
950 SetVertexAttribute {
951 buffer: Option<glow::Buffer>,
952 buffer_desc: VertexBufferDesc,
953 attribute_desc: AttributeDesc,
954 },
955 UnsetVertexAttribute(u32),
956 SetVertexBuffer {
957 index: u32,
958 buffer: BufferBinding,
959 buffer_desc: VertexBufferDesc,
960 },
961 SetProgram(glow::Program),
962 SetPrimitive(PrimitiveState),
963 SetBlendConstant([f32; 4]),
964 SetColorTarget {
965 draw_buffer_index: Option<u32>,
966 desc: ColorTargetDesc,
967 },
968 BindBuffer {
969 target: BindTarget,
970 slot: u32,
971 buffer: glow::Buffer,
972 offset: i32,
973 size: i32,
974 },
975 BindSampler(u32, Option<glow::Sampler>),
976 BindTexture {
977 slot: u32,
978 texture: glow::Texture,
979 target: BindTarget,
980 aspects: crate::FormatAspects,
981 mip_levels: Range<u32>,
982 },
983 BindImage {
984 slot: u32,
985 binding: ImageBinding,
986 },
987 InsertDebugMarker(Range<u32>),
988 PushDebugGroup(Range<u32>),
989 PopDebugGroup,
990 SetPushConstants {
991 uniform: PushConstantDesc,
992 /// Offset from the start of the `data_bytes`
993 offset: u32,
994 },
995 }
996
997 #[derive(Default)]
998 pub struct CommandBuffer {
999 label: Option<String>,
1000 commands: Vec<Command>,
1001 data_bytes: Vec<u8>,
1002 queries: Vec<glow::Query>,
1003 }
1004
1005 impl crate::DynCommandBuffer for CommandBuffer {}
1006
1007 impl fmt::Debug for CommandBuffer {
1008 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009 let mut builder = f.debug_struct("CommandBuffer");
1010 if let Some(ref label) = self.label {
1011 builder.field("label", label);
1012 }
1013 builder.finish()
1014 }
1015 }
1016
1017 #[cfg(send_sync)]
1018 unsafe impl Sync for CommandBuffer {}
1019 #[cfg(send_sync)]
1020 unsafe impl Send for CommandBuffer {}
1021
1022 //TODO: we would have something like `Arc<typed_arena::Arena>`
1023 // here and in the command buffers. So that everything grows
1024 // inside the encoder and stays there until `reset_all`.
1025
1026 pub struct CommandEncoder {
1027 cmd_buffer: CommandBuffer,
1028 state: command::State,
1029 private_caps: PrivateCapabilities,
1030 counters: Arc<wgt::HalCounters>,
1031 }
1032
1033 impl fmt::Debug for CommandEncoder {
1034 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1035 f.debug_struct("CommandEncoder")
1036 .field("cmd_buffer", &self.cmd_buffer)
1037 .finish()
1038 }
1039 }
1040
1041 #[cfg(send_sync)]
1042 unsafe impl Sync for CommandEncoder {}
1043 #[cfg(send_sync)]
1044 unsafe impl Send for CommandEncoder {}
1045
1046 #[cfg(not(webgl))]
1047 fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
1048 let source_str = match source {
1049 glow::DEBUG_SOURCE_API => "API",
1050 glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
1051 glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
1052 glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
1053 glow::DEBUG_SOURCE_APPLICATION => "Application",
1054 glow::DEBUG_SOURCE_OTHER => "Other",
1055 _ => unreachable!(),
1056 };
1057
1058 let log_severity = match severity {
1059 glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
1060 glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
1061 glow::DEBUG_SEVERITY_LOW => log::Level::Info,
1062 glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
1063 _ => unreachable!(),
1064 };
1065
1066 let type_str = match gltype {
1067 glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
1068 glow::DEBUG_TYPE_ERROR => "Error",
1069 glow::DEBUG_TYPE_MARKER => "Marker",
1070 glow::DEBUG_TYPE_OTHER => "Other",
1071 glow::DEBUG_TYPE_PERFORMANCE => "Performance",
1072 glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
1073 glow::DEBUG_TYPE_PORTABILITY => "Portability",
1074 glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
1075 glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
1076 _ => unreachable!(),
1077 };
1078
1079 let _ = std::panic::catch_unwind(|| {
1080 log::log!(
1081 log_severity,
1082 "GLES: [{}/{}] ID {} : {}",
1083 source_str,
1084 type_str,
1085 id,
1086 message
1087 );
1088 });
1089
1090 if cfg!(debug_assertions) && log_severity == log::Level::Error {
1091 // Set canary and continue
1092 crate::VALIDATION_CANARY.add(message.to_string());
1093 }
1094 }
1095
1096 // If we are using `std`, then use `Mutex` to provide `Send` and `Sync`
1097 cfg_if::cfg_if! {
1098 if #[cfg(gles_with_std)] {
1099 type MaybeMutex<T> = std::sync::Mutex<T>;
1100
1101 fn lock<T>(mutex: &MaybeMutex<T>) -> std::sync::MutexGuard<'_, T> {
1102 mutex.lock().unwrap()
1103 }
1104 } else {
1105 // It should be impossible for any build configuration to trigger this error
1106 // It is intended only as a guard against changes elsewhere causing the use of
1107 // `RefCell` here to become unsound.
1108 #[cfg(all(send_sync, not(feature = "fragile-send-sync-non-atomic-wasm")))]
1109 compile_error!("cannot provide non-fragile Send+Sync without std");
1110
1111 type MaybeMutex<T> = core::cell::RefCell<T>;
1112
1113 fn lock<T>(mutex: &MaybeMutex<T>) -> core::cell::RefMut<'_, T> {
1114 mutex.borrow_mut()
1115 }
1116 }
1117 }