1#[cfg(not(any(windows, webgl)))]
84mod egl;
85#[cfg(Emscripten)]
86mod emscripten;
87#[cfg(webgl)]
88mod web;
89#[cfg(windows)]
90mod wgl;
91
92mod adapter;
93mod command;
94mod conv;
95mod debug_text;
96mod device;
97mod fence;
98mod gl_state;
99mod queue;
100
101pub use fence::Fence;
102
103#[cfg(not(any(windows, webgl)))]
104pub use self::egl::{AdapterContext, AdapterContextLock};
105#[cfg(not(any(windows, webgl)))]
106pub use self::egl::{Instance, Surface};
107
108#[cfg(webgl)]
109pub use self::web::AdapterContext;
110#[cfg(webgl)]
111pub use self::web::{Instance, Surface, ask_only_for_used_extensions};
112
113#[cfg(windows)]
114use self::wgl::AdapterContext;
115#[cfg(windows)]
116pub use self::wgl::{Instance, Surface};
117
118use alloc::{boxed::Box, string::String, string::ToString as _, sync::Arc, vec::Vec};
119use core::{
120 fmt,
121 ops::Range,
122 sync::atomic::{AtomicU32, AtomicU8, AtomicUsize},
123};
124use parking_lot::Mutex;
125
126use arrayvec::ArrayVec;
127use glow::HasContext;
128use naga::FastHashMap;
129
130use crate::{CopyExtent, TextureDescriptor};
131
132#[derive(Clone, Debug)]
133pub struct Api;
134
135const MAX_TEXTURE_SLOTS: usize = 16;
138const MAX_SAMPLERS: usize = 16;
139const MAX_VERTEX_ATTRIBUTES: usize = 16;
140const ZERO_BUFFER_SIZE: usize = 256 << 10;
141const MAX_IMMEDIATES: usize = 64;
142const MAX_IMMEDIATES_COMMANDS: usize = MAX_IMMEDIATES * crate::MAX_CONCURRENT_SHADER_STAGES;
144
145impl crate::Api for Api {
146 const VARIANT: wgt::Backend = wgt::Backend::Gl;
147
148 type Instance = Instance;
149 type Surface = Surface;
150 type Adapter = Adapter;
151 type Device = Device;
152
153 type Queue = Queue;
154 type CommandEncoder = CommandEncoder;
155 type CommandBuffer = CommandBuffer;
156
157 type Buffer = Buffer;
158 type Texture = Texture;
159 type SurfaceTexture = Texture;
160 type TextureView = TextureView;
161 type Sampler = Sampler;
162 type QuerySet = QuerySet;
163 type Fence = Fence;
164 type AccelerationStructure = AccelerationStructure;
165 type PipelineCache = PipelineCache;
166
167 type BindGroupLayout = BindGroupLayout;
168 type BindGroup = BindGroup;
169 type PipelineLayout = PipelineLayout;
170 type ShaderModule = ShaderModule;
171 type RenderPipeline = RenderPipeline;
172 type ComputePipeline = ComputePipeline;
173 type RayTracingPipeline = RayTracingPipeline;
174}
175
176crate::impl_dyn_resource!(
177 Adapter,
178 AccelerationStructure,
179 BindGroup,
180 BindGroupLayout,
181 Buffer,
182 CommandBuffer,
183 CommandEncoder,
184 ComputePipeline,
185 Device,
186 Fence,
187 Instance,
188 PipelineCache,
189 PipelineLayout,
190 QuerySet,
191 Queue,
192 RenderPipeline,
193 RayTracingPipeline,
194 Sampler,
195 ShaderModule,
196 Surface,
197 Texture,
198 TextureView
199);
200
201bitflags::bitflags! {
202 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
205 struct PrivateCapabilities: u32 {
206 const BUFFER_ALLOCATION = 1 << 0;
208 const SHADER_BINDING_LAYOUT = 1 << 1;
210 const SHADER_TEXTURE_SHADOW_LOD = 1 << 2;
212 const MEMORY_BARRIERS = 1 << 3;
214 const VERTEX_BUFFER_LAYOUT = 1 << 4;
216 const INDEX_BUFFER_ROLE_CHANGE = 1 << 5;
219 const GET_BUFFER_SUB_DATA = 1 << 7;
221 const COLOR_BUFFER_HALF_FLOAT = 1 << 8;
223 const COLOR_BUFFER_FLOAT = 1 << 9;
225 const QUERY_BUFFERS = 1 << 11;
227 const QUERY_64BIT = 1 << 12;
229 const TEXTURE_STORAGE = 1 << 13;
231 const DEBUG_FNS = 1 << 14;
233 const INVALIDATE_FRAMEBUFFER = 1 << 15;
235 const FULLY_FEATURED_INSTANCING = 1 << 16;
239 const MULTISAMPLED_RENDER_TO_TEXTURE = 1 << 17;
241 const TEXTURE_FORMAT_NORM16 = 1 << 18;
245 const TEXTURE_FORMAT_SNORM16_RENDERABLE = 1 << 19;
249 const TEXTURE_FORMAT_NORM16_STORAGE = 1 << 20;
254 }
255}
256
257bitflags::bitflags! {
258 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
260 struct Workarounds: u32 {
261 const MESA_I915_SRGB_SHADER_CLEAR = 1 << 0;
268 const EMULATE_BUFFER_MAP = 1 << 1;
270 }
271}
272
273type BindTarget = u32;
274
275#[derive(Debug, Default, Clone, Copy)]
276enum VertexAttribKind {
277 #[default]
278 Float, Integer, }
282
283#[derive(Clone, Debug)]
284pub struct TextureFormatDesc {
285 pub internal: u32,
286 pub external: u32,
287 pub data_type: u32,
288}
289
290struct AdapterShared {
291 context: AdapterContext,
292 private_caps: PrivateCapabilities,
293 features: wgt::Features,
294 limits: wgt::Limits,
295 workarounds: Workarounds,
296 options: wgt::GlBackendOptions,
297 shading_language_version: naga::back::glsl::Version,
298 next_shader_id: AtomicU32,
299 program_cache: Mutex<ProgramCache>,
300 unread_links: AtomicUsize,
303 es: bool,
304
305 max_msaa_samples: i32,
309}
310
311impl fmt::Debug for AdapterShared {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 let Self {
314 context: _, private_caps,
316 features,
317 limits,
318 workarounds,
319 options,
320 shading_language_version,
321 next_shader_id,
322 program_cache: _,
323 unread_links,
324 es,
325 max_msaa_samples,
326 } = self;
327 f.debug_struct("AdapterShared")
328 .field("private_caps", private_caps)
329 .field("features", features)
330 .field("limits", limits)
331 .field("workarounds", workarounds)
332 .field("options", options)
333 .field("shading_language_version", shading_language_version)
334 .field("next_shader_id", next_shader_id)
335 .field("unread_links", unread_links)
336 .field("es", es)
337 .field("max_msaa_samples", max_msaa_samples)
338 .finish_non_exhaustive()
339 }
340}
341
342#[derive(Debug)]
343pub struct Adapter {
344 shared: Arc<AdapterShared>,
345}
346
347#[derive(Debug)]
348pub struct Device {
349 shared: Arc<AdapterShared>,
350 main_vao: glow::VertexArray,
351 #[cfg(all(native, feature = "renderdoc"))]
352 render_doc: crate::auxil::renderdoc::RenderDoc,
353 counters: Arc<wgt::HalCounters>,
354}
355
356impl Drop for Device {
357 fn drop(&mut self) {
358 let gl = &self.shared.context.lock();
359 unsafe { gl.delete_vertex_array(self.main_vao) };
360 }
361}
362
363#[derive(Debug)]
364pub struct ShaderClearProgram {
365 pub program: glow::Program,
366 pub color_uniform_location: glow::UniformLocation,
367}
368
369#[derive(Debug)]
370pub struct Queue {
371 shared: Arc<AdapterShared>,
372 features: wgt::Features,
373 draw_fbo: glow::Framebuffer,
374 copy_fbo: glow::Framebuffer,
375 shader_clear_program: Option<ShaderClearProgram>,
378 zero_buffer: glow::Buffer,
381 temp_query_results: Mutex<Vec<u64>>,
382 draw_buffer_count: AtomicU8,
383 current_index_buffer: Mutex<Option<glow::Buffer>>,
384 gl_state: Mutex<gl_state::GlState>,
387}
388
389impl Drop for Queue {
390 fn drop(&mut self) {
391 let gl = &self.shared.context.lock();
392 unsafe { gl.delete_framebuffer(self.draw_fbo) };
393 unsafe { gl.delete_framebuffer(self.copy_fbo) };
394 unsafe { gl.delete_buffer(self.zero_buffer) };
395 }
396}
397
398#[derive(Clone, Debug)]
399pub struct Buffer {
400 raw: Option<glow::Buffer>,
401 target: BindTarget,
402 size: wgt::BufferAddress,
403 map_flags: u32,
405 map_state: Arc<MaybeMutex<BufferMapState>>,
409 drop_guard: Option<Arc<crate::DropGuard>>,
415}
416
417#[derive(Clone, Debug)]
418struct BufferMapState {
419 mapped: bool,
422 data: Option<Vec<u8>>,
423 offset_of_current_mapping: wgt::BufferAddress,
424}
425
426#[cfg(send_sync)]
427static_assertions::assert_impl_all!(Buffer: Send, Sync);
428
429impl crate::DynBuffer for Buffer {}
430
431#[derive(Clone, Debug)]
432pub enum TextureInner {
433 Renderbuffer {
434 raw: glow::Renderbuffer,
435 },
436 DefaultRenderbuffer,
437 Texture {
438 raw: glow::Texture,
439 target: BindTarget,
440 },
441 #[cfg(webgl)]
442 ExternalFramebuffer {
446 inner: web_sys::WebGlFramebuffer,
447 },
448 #[cfg(native)]
449 ExternalNativeFramebuffer {
455 inner: glow::NativeFramebuffer,
456 },
457}
458
459#[cfg(send_sync)]
460unsafe impl Sync for TextureInner {}
461#[cfg(send_sync)]
462unsafe impl Send for TextureInner {}
463
464impl TextureInner {
465 fn as_native(&self) -> (glow::Texture, BindTarget) {
466 match *self {
467 Self::Renderbuffer { .. } | Self::DefaultRenderbuffer => {
468 panic!("Unexpected renderbuffer");
469 }
470 Self::Texture { raw, target } => (raw, target),
471 #[cfg(webgl)]
472 Self::ExternalFramebuffer { .. } => panic!("Unexpected external framebuffer"),
473 #[cfg(native)]
474 Self::ExternalNativeFramebuffer { .. } => panic!("unexpected external framebuffer"),
475 }
476 }
477}
478
479#[derive(Debug)]
480pub struct Texture {
481 pub inner: TextureInner,
482 pub mip_level_count: u32,
483 pub array_layer_count: u32,
484 pub format: wgt::TextureFormat,
485 pub format_desc: TextureFormatDesc,
486 pub copy_size: CopyExtent,
487
488 pub drop_guard: Option<crate::DropGuard>,
491}
492
493impl crate::DynTexture for Texture {}
494impl crate::DynSurfaceTexture for Texture {
495 fn image_id(&self) -> Option<u64> {
500 match self.inner {
501 TextureInner::DefaultRenderbuffer => None,
502 _ => Some(0),
503 }
504 }
505}
506
507impl core::borrow::Borrow<dyn crate::DynTexture> for Texture {
508 fn borrow(&self) -> &dyn crate::DynTexture {
509 self
510 }
511}
512
513impl Texture {
514 pub fn default_framebuffer(format: wgt::TextureFormat) -> Self {
515 Self {
516 inner: TextureInner::DefaultRenderbuffer,
517 drop_guard: None,
518 mip_level_count: 1,
519 array_layer_count: 1,
520 format,
521 format_desc: TextureFormatDesc {
522 internal: 0,
523 external: 0,
524 data_type: 0,
525 },
526 copy_size: CopyExtent {
527 width: 0,
528 height: 0,
529 depth: 0,
530 },
531 }
532 }
533
534 fn get_info_from_desc(desc: &TextureDescriptor) -> u32 {
536 match desc.dimension {
537 wgt::TextureDimension::D1 => glow::TEXTURE_2D,
540 wgt::TextureDimension::D2 => {
541 match (desc.is_cube_compatible(), desc.size.depth_or_array_layers) {
543 (false, 1) => glow::TEXTURE_2D,
544 (false, _) => glow::TEXTURE_2D_ARRAY,
545 (true, 6) => glow::TEXTURE_CUBE_MAP,
546 (true, _) => glow::TEXTURE_CUBE_MAP_ARRAY,
547 }
548 }
549 wgt::TextureDimension::D3 => glow::TEXTURE_3D,
550 }
551 }
552
553 fn log_failing_target_heuristics(view_dimension: wgt::TextureViewDimension, target: u32) {
555 let expected_target = match view_dimension {
556 wgt::TextureViewDimension::D1 => glow::TEXTURE_2D,
557 wgt::TextureViewDimension::D2 => glow::TEXTURE_2D,
558 wgt::TextureViewDimension::D2Array => glow::TEXTURE_2D_ARRAY,
559 wgt::TextureViewDimension::Cube => glow::TEXTURE_CUBE_MAP,
560 wgt::TextureViewDimension::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY,
561 wgt::TextureViewDimension::D3 => glow::TEXTURE_3D,
562 };
563
564 if expected_target == target {
565 return;
566 }
567
568 let buffer;
569 let got = match target {
570 glow::TEXTURE_2D => "D2",
571 glow::TEXTURE_2D_ARRAY => "D2Array",
572 glow::TEXTURE_CUBE_MAP => "Cube",
573 glow::TEXTURE_CUBE_MAP_ARRAY => "CubeArray",
574 glow::TEXTURE_3D => "D3",
575 target => {
576 buffer = target.to_string();
577 &buffer
578 }
579 };
580
581 log::error!(
582 concat!(
583 "wgpu-hal heuristics assumed that ",
584 "the view dimension will be equal to `{}` rather than `{:?}`.\n",
585 "`D2` textures with ",
586 "`depth_or_array_layers == 1` ",
587 "are assumed to have view dimension `D2`\n",
588 "`D2` textures with ",
589 "`depth_or_array_layers > 1` ",
590 "are assumed to have view dimension `D2Array`\n",
591 "`D2` textures with ",
592 "`depth_or_array_layers == 6` ",
593 "are assumed to have view dimension `Cube`\n",
594 "`D2` textures with ",
595 "`depth_or_array_layers > 6 && depth_or_array_layers % 6 == 0` ",
596 "are assumed to have view dimension `CubeArray`\n",
597 ),
598 got,
599 view_dimension,
600 );
601 }
602}
603
604#[derive(Clone, Debug)]
605pub struct TextureView {
606 inner: TextureInner,
607 aspects: crate::FormatAspects,
608 mip_levels: Range<u32>,
609 array_layers: Range<u32>,
610 format: wgt::TextureFormat,
611}
612
613impl crate::DynTextureView for TextureView {}
614
615#[derive(Debug)]
616pub struct Sampler {
617 raw: glow::Sampler,
618}
619
620impl crate::DynSampler for Sampler {}
621
622#[derive(Debug)]
623pub struct BindGroupLayout {
624 entries: Arc<[wgt::BindGroupLayoutEntry]>,
625}
626
627impl crate::DynBindGroupLayout for BindGroupLayout {}
628
629#[derive(Debug)]
630struct BindGroupLayoutInfo {
631 entries: Arc<[wgt::BindGroupLayoutEntry]>,
632 binding_to_slot: Box<[u8]>,
638}
639
640#[derive(Debug)]
641pub struct PipelineLayout {
642 group_infos: Box<[Option<BindGroupLayoutInfo>]>,
643 naga_options: naga::back::glsl::Options,
644}
645
646impl crate::DynPipelineLayout for PipelineLayout {}
647
648impl PipelineLayout {
649 fn get_slot(&self, br: &naga::ResourceBinding) -> u8 {
653 let group_info = self.group_infos[br.group as usize].as_ref().unwrap();
654 group_info.binding_to_slot[br.binding as usize]
655 }
656}
657
658#[derive(Debug)]
659enum BindingRegister {
660 UniformBuffers,
661 StorageBuffers,
662 Textures,
663 Images,
664}
665
666#[derive(Debug)]
667enum RawBinding {
668 Buffer {
669 raw: glow::Buffer,
670 offset: i32,
671 size: i32,
672 },
673 Texture {
674 raw: glow::Texture,
675 target: BindTarget,
676 aspects: crate::FormatAspects,
677 mip_levels: Range<u32>,
678 },
680 Image(ImageBinding),
681 Sampler(glow::Sampler),
682}
683
684#[derive(Debug)]
685pub struct BindGroup {
686 contents: Box<[RawBinding]>,
687}
688
689impl crate::DynBindGroup for BindGroup {}
690
691type ShaderId = u32;
692
693#[derive(Debug)]
694pub enum ShaderModuleSource {
695 Naga(crate::NagaShader),
696 Passthrough { source: String },
697 Templates(&'static [crate::GlslTemplate]),
698}
699
700#[derive(Debug)]
701pub struct ShaderModule {
702 source: ShaderModuleSource,
703 label: Option<String>,
704 id: ShaderId,
705}
706
707impl crate::DynShaderModule for ShaderModule {}
708
709#[derive(Clone, Debug, Default)]
710struct VertexFormatDesc {
711 element_count: i32,
712 element_format: u32,
713 attrib_kind: VertexAttribKind,
714}
715
716#[derive(Clone, Debug, Default)]
717struct AttributeDesc {
718 location: u32,
719 offset: u32,
720 buffer_index: u32,
721 format_desc: VertexFormatDesc,
722}
723
724#[derive(Clone, Debug)]
725struct BufferBinding {
726 raw: glow::Buffer,
727 offset: wgt::BufferAddress,
728}
729
730#[derive(Clone, Debug)]
731struct ImageBinding {
732 raw: glow::Texture,
733 mip_level: u32,
734 array_layer: Option<u32>,
735 access: u32,
736 format: u32,
737}
738
739#[derive(Clone, Debug, Default, PartialEq)]
740struct VertexBufferDesc {
741 step: wgt::VertexStepMode,
742 stride: u32,
743}
744
745#[derive(Clone, Debug)]
746struct ImmediateDesc {
747 location: glow::UniformLocation,
748 ty: nt::glsl::GlslUniformType,
749 offset: u32,
750}
751
752#[cfg(send_sync)]
753unsafe impl Sync for ImmediateDesc {}
754#[cfg(send_sync)]
755unsafe impl Send for ImmediateDesc {}
756
757type SamplerBindMap = [Option<u8>; MAX_TEXTURE_SLOTS];
760
761#[derive(Debug)]
762struct PipelineInner {
763 program: glow::Program,
764 sampler_map: SamplerBindMap,
765 clip_distance_count: u32,
766 link: Mutex<ProgramLink>,
769}
770
771#[derive(Debug)]
773struct ProgramLink {
774 pending: Option<Box<device::PendingLink>>,
775 linked: Option<Arc<LinkedProgram>>,
776}
777
778#[derive(Debug, Default)]
780struct LinkedProgram {
781 first_instance_location: Option<glow::UniformLocation>,
782 immediates_descs: ArrayVec<ImmediateDesc, MAX_IMMEDIATES_COMMANDS>,
783}
784
785#[cfg(send_sync)]
786unsafe impl Sync for PipelineInner {}
787#[cfg(send_sync)]
788unsafe impl Send for PipelineInner {}
789
790#[derive(Clone, Debug)]
791struct DepthState {
792 function: u32,
793 mask: bool,
794}
795
796#[derive(Clone, Debug, PartialEq)]
797struct BlendComponent {
798 src: u32,
799 dst: u32,
800 equation: u32,
801}
802
803#[derive(Clone, Debug, PartialEq)]
804struct BlendDesc {
805 alpha: BlendComponent,
806 color: BlendComponent,
807}
808
809#[derive(Clone, Debug, Default, PartialEq)]
810struct ColorTargetDesc {
811 mask: wgt::ColorWrites,
812 blend: Option<BlendDesc>,
813}
814
815#[derive(Debug, PartialEq, Eq, Hash)]
816struct ProgramStage {
817 naga_stage: naga::ShaderStage,
818 shader_id: ShaderId,
819 entry_point: String,
820 zero_initialize_workgroup_memory: bool,
821 constant_hash: Vec<u8>,
822}
823
824#[derive(Debug, PartialEq, Eq, Hash)]
825struct ProgramCacheKey {
826 stages: ArrayVec<ProgramStage, 3>,
827 group_to_binding_to_slot: Box<[Option<Box<[u8]>>]>,
828 force_point_size: bool,
829}
830
831type ProgramCache = FastHashMap<ProgramCacheKey, Result<Arc<PipelineInner>, crate::PipelineError>>;
832
833#[derive(Debug)]
834pub struct RenderPipeline {
835 inner: Arc<PipelineInner>,
836 primitive: wgt::PrimitiveState,
837 vertex_buffers: Box<[Option<VertexBufferDesc>]>,
838 vertex_attributes: Box<[AttributeDesc]>,
839 color_targets: Box<[ColorTargetDesc]>,
840 depth: Option<DepthState>,
841 depth_bias: wgt::DepthBiasState,
842 stencil: Option<StencilState>,
843 alpha_to_coverage_enabled: bool,
844}
845
846impl crate::DynRenderPipeline for RenderPipeline {}
847
848#[cfg(send_sync)]
849static_assertions::assert_impl_all!(RenderPipeline: Send, Sync);
850
851#[derive(Debug)]
852pub struct ComputePipeline {
853 inner: Arc<PipelineInner>,
854}
855
856impl crate::DynComputePipeline for ComputePipeline {}
857
858#[derive(Debug)]
859pub struct RayTracingPipeline {}
860
861impl crate::DynRayTracingPipeline for RayTracingPipeline {}
862
863#[cfg(send_sync)]
864static_assertions::assert_impl_all!(ComputePipeline: Send, Sync);
865
866#[derive(Debug)]
867pub struct QuerySet {
868 queries: Box<[glow::Query]>,
869 target: BindTarget,
870}
871
872impl crate::DynQuerySet for QuerySet {}
873
874#[derive(Debug)]
875pub struct AccelerationStructure;
876
877impl crate::DynAccelerationStructure for AccelerationStructure {}
878
879#[derive(Debug)]
880pub struct PipelineCache;
881
882impl crate::DynPipelineCache for PipelineCache {}
883
884#[derive(Clone, Debug, PartialEq)]
885struct StencilOps {
886 pass: u32,
887 fail: u32,
888 depth_fail: u32,
889}
890
891impl Default for StencilOps {
892 fn default() -> Self {
893 Self {
894 pass: glow::KEEP,
895 fail: glow::KEEP,
896 depth_fail: glow::KEEP,
897 }
898 }
899}
900
901#[derive(Clone, Debug, PartialEq)]
902struct StencilSide {
903 function: u32,
904 mask_read: u32,
905 mask_write: u32,
906 reference: u32,
907 ops: StencilOps,
908}
909
910impl Default for StencilSide {
911 fn default() -> Self {
912 Self {
913 function: glow::ALWAYS,
914 mask_read: 0xFF,
915 mask_write: 0xFF,
916 reference: 0,
917 ops: StencilOps::default(),
918 }
919 }
920}
921
922#[derive(Debug, Clone, Default)]
923struct StencilState {
924 front: StencilSide,
925 back: StencilSide,
926}
927
928#[derive(Clone, Debug, Default, PartialEq)]
929struct PrimitiveState {
930 front_face: u32,
931 cull_face: u32,
932 unclipped_depth: bool,
933 polygon_mode: u32,
934}
935
936type InvalidatedAttachments = ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>;
937
938#[derive(Debug)]
939struct ClearBufferOp {
940 dst: Buffer,
941 dst_target: BindTarget,
942 range: crate::MemoryRange,
943}
944
945#[derive(Debug)]
946struct BufferToBufferCopy {
947 src: Buffer,
948 src_target: BindTarget,
949 dst: Buffer,
950 dst_target: BindTarget,
951 copy: crate::BufferCopy,
952}
953
954#[cfg(webgl)]
955#[derive(Debug)]
956struct ExternalImageToTextureCopy {
957 src: wgt::CopyExternalImageSourceInfo,
958 dst: glow::Texture,
959 dst_target: BindTarget,
960 dst_format: wgt::TextureFormat,
961 dst_premultiplication: bool,
962 copy: crate::TextureCopy,
963}
964
965#[derive(Debug)]
966struct TextureToTextureCopy {
967 src: glow::Texture,
968 src_target: BindTarget,
969 dst: glow::Texture,
970 dst_target: BindTarget,
971 copy: crate::TextureCopy,
972}
973
974#[derive(Debug)]
977struct CanvasCopy {
978 texture: glow::Texture,
979 target: BindTarget,
980 copy: crate::TextureCopy,
981}
982
983#[derive(Debug)]
984struct BufferToTextureCopy {
985 src: Buffer,
986 #[allow(unused)]
987 src_target: BindTarget,
988 dst: glow::Texture,
989 dst_target: BindTarget,
990 dst_format: wgt::TextureFormat,
991 copy: crate::BufferTextureCopy,
992}
993
994#[derive(Debug)]
995struct TextureToBufferCopy {
996 src: glow::Texture,
997 src_target: BindTarget,
998 src_format: wgt::TextureFormat,
999 dst: Buffer,
1000 #[allow(unused)]
1001 dst_target: BindTarget,
1002 copy: crate::BufferTextureCopy,
1003}
1004
1005#[derive(Debug)]
1006struct QueryResultsCopy {
1007 query_range: Range<u32>,
1008 dst: Buffer,
1009 dst_target: BindTarget,
1010 dst_offset: wgt::BufferAddress,
1011}
1012
1013#[derive(Debug)]
1014struct AttachmentBinding {
1015 attachment: u32,
1016 view: TextureView,
1017 depth_slice: Option<u32>,
1018 sample_count: u32,
1019}
1020
1021#[derive(Debug)]
1022struct AttachmentResolve {
1023 attachment: u32,
1024 dst: TextureView,
1025 size: wgt::Extent3d,
1026}
1027
1028#[derive(Debug)]
1029enum Command {
1030 Draw {
1031 topology: u32,
1032 first_vertex: u32,
1033 vertex_count: u32,
1034 first_instance: u32,
1035 instance_count: u32,
1036 },
1037 DrawIndexed {
1038 topology: u32,
1039 index_type: u32,
1040 index_count: u32,
1041 index_offset: wgt::BufferAddress,
1042 base_vertex: i32,
1043 first_instance: u32,
1044 instance_count: u32,
1045 },
1046 DrawIndirect {
1047 topology: u32,
1048 indirect_buf: glow::Buffer,
1049 indirect_offset: wgt::BufferAddress,
1050 },
1051 DrawIndexedIndirect {
1052 topology: u32,
1053 index_type: u32,
1054 indirect_buf: glow::Buffer,
1055 indirect_offset: wgt::BufferAddress,
1056 },
1057 Dispatch([u32; 3]),
1058 DispatchIndirect {
1059 indirect_buf: glow::Buffer,
1060 indirect_offset: wgt::BufferAddress,
1061 },
1062 ClearBuffer(Box<ClearBufferOp>),
1063 CopyBufferToBuffer(Box<BufferToBufferCopy>),
1064 #[cfg(webgl)]
1065 CopyExternalImageToTexture(Box<ExternalImageToTextureCopy>),
1066 CopyTextureToTexture(Box<TextureToTextureCopy>),
1067 CopyCanvasToTexture(Box<CanvasCopy>),
1068 CopyTextureToCanvas(Box<CanvasCopy>),
1069 CopyBufferToTexture(Box<BufferToTextureCopy>),
1070 CopyTextureToBuffer(Box<TextureToBufferCopy>),
1071 SetIndexBuffer(glow::Buffer),
1072 BeginQuery(glow::Query, BindTarget),
1073 EndQuery(BindTarget),
1074 TimestampQuery(glow::Query),
1075 CopyQueryResults(Box<QueryResultsCopy>),
1076 ResetFramebuffer {
1077 is_default: bool,
1078 },
1079 BindAttachment(Box<AttachmentBinding>),
1080 ResolveAttachment(Box<AttachmentResolve>),
1081 InvalidateAttachments(InvalidatedAttachments),
1082 SetDrawColorBuffers(u8),
1083 ClearColorF {
1084 draw_buffer: u32,
1085 color: [f32; 4],
1086 is_srgb: bool,
1087 },
1088 ClearColorU(u32, [u32; 4]),
1089 ClearColorI(u32, [i32; 4]),
1090 ClearDepth(f32),
1091 ClearStencil(u32),
1092 ClearDepthAndStencil(f32, u32),
1097 BufferBarrier(glow::Buffer, wgt::BufferUses),
1098 TextureBarrier(wgt::TextureUses),
1099 SetViewport {
1100 rect: crate::Rect<i32>,
1101 depth: Range<f32>,
1102 },
1103 SetScissor(crate::Rect<i32>),
1104 SetStencilFunc {
1105 face: u32,
1106 function: u32,
1107 reference: u32,
1108 read_mask: u32,
1109 },
1110 SetStencilOps {
1111 face: u32,
1112 write_mask: u32,
1113 ops: StencilOps,
1114 },
1115 SetDepth(DepthState),
1116 SetDepthBias(wgt::DepthBiasState),
1117 ConfigureDepthStencil(crate::FormatAspects),
1118 SetAlphaToCoverage(bool),
1119 SetVertexAttribute {
1120 buffer: Option<glow::Buffer>,
1121 buffer_desc: VertexBufferDesc,
1122 attribute_desc: AttributeDesc,
1123 },
1124 UnsetVertexAttribute(u32),
1125 SetVertexBuffer {
1126 index: u32,
1127 buffer: BufferBinding,
1128 buffer_desc: VertexBufferDesc,
1129 },
1130 SetProgram(Arc<PipelineInner>),
1131 SetPrimitive(PrimitiveState),
1132 SetBlendConstant([f32; 4]),
1133 SetColorTarget {
1134 draw_buffer_index: Option<u32>,
1135 desc: ColorTargetDesc,
1136 },
1137 BindBuffer {
1138 target: BindTarget,
1139 slot: u32,
1140 buffer: glow::Buffer,
1141 offset: i32,
1142 size: i32,
1143 },
1144 BindSampler(u32, Option<glow::Sampler>),
1145 BindTexture {
1146 slot: u32,
1147 texture: glow::Texture,
1148 target: BindTarget,
1149 aspects: crate::FormatAspects,
1150 mip_levels: Range<u32>,
1151 },
1152 BindImage {
1153 slot: u32,
1154 binding: ImageBinding,
1155 },
1156 InsertDebugMarker(Range<u32>),
1157 PushDebugGroup(Range<u32>),
1158 PopDebugGroup,
1159 SetImmediates {
1160 data: Range<u32>,
1163 },
1164 SetClipDistances {
1165 old_count: u32,
1166 new_count: u32,
1167 },
1168}
1169
1170#[derive(Default)]
1171pub struct CommandBuffer {
1172 label: Option<alloc::ffi::CString>,
1174 commands: Vec<Command>,
1175 data_bytes: Vec<u8>,
1176 queries: Vec<glow::Query>,
1177}
1178
1179impl crate::DynCommandBuffer for CommandBuffer {}
1180
1181impl fmt::Debug for CommandBuffer {
1182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1183 let mut builder = f.debug_struct("CommandBuffer");
1184 if let Some(ref label) = self.label {
1185 builder.field("label", label);
1186 }
1187 builder.finish()
1188 }
1189}
1190
1191#[cfg(send_sync)]
1192unsafe impl Sync for CommandBuffer {}
1193#[cfg(send_sync)]
1194unsafe impl Send for CommandBuffer {}
1195
1196pub struct CommandEncoder {
1201 cmd_buffer: CommandBuffer,
1202 state: command::State,
1203 private_caps: PrivateCapabilities,
1204 counters: Arc<wgt::HalCounters>,
1205}
1206
1207impl fmt::Debug for CommandEncoder {
1208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1209 f.debug_struct("CommandEncoder")
1210 .field("cmd_buffer", &self.cmd_buffer)
1211 .finish()
1212 }
1213}
1214
1215#[cfg(send_sync)]
1216unsafe impl Sync for CommandEncoder {}
1217#[cfg(send_sync)]
1218unsafe impl Send for CommandEncoder {}
1219
1220#[cfg(not(webgl))]
1221fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
1222 let source_str = match source {
1223 glow::DEBUG_SOURCE_API => "API",
1224 glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
1225 glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
1226 glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
1227 glow::DEBUG_SOURCE_APPLICATION => "Application",
1228 glow::DEBUG_SOURCE_OTHER => "Other",
1229 _ => unreachable!(),
1230 };
1231
1232 let log_severity = match severity {
1233 glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
1234 glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
1235 glow::DEBUG_SEVERITY_LOW => log::Level::Debug,
1236 glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
1237 _ => unreachable!(),
1238 };
1239
1240 let type_str = match gltype {
1241 glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
1242 glow::DEBUG_TYPE_ERROR => "Error",
1243 glow::DEBUG_TYPE_MARKER => "Marker",
1244 glow::DEBUG_TYPE_OTHER => "Other",
1245 glow::DEBUG_TYPE_PERFORMANCE => "Performance",
1246 glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
1247 glow::DEBUG_TYPE_PORTABILITY => "Portability",
1248 glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
1249 glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
1250 _ => unreachable!(),
1251 };
1252
1253 let _ = std::panic::catch_unwind(|| {
1254 log::log!(
1255 log_severity,
1256 "GLES: [{source_str}/{type_str}] ID {id} : {message}"
1257 );
1258 });
1259
1260 #[cfg(feature = "validation_canary")]
1261 if cfg!(debug_assertions) && log_severity == log::Level::Error {
1262 crate::VALIDATION_CANARY.add(message.to_string());
1264 }
1265}
1266
1267cfg_if::cfg_if! {
1269 if #[cfg(gles_with_std)] {
1270 type MaybeMutex<T> = std::sync::Mutex<T>;
1271
1272 fn lock<T>(mutex: &MaybeMutex<T>) -> std::sync::MutexGuard<'_, T> {
1273 mutex.lock().unwrap()
1274 }
1275 } else {
1276 #[cfg(all(send_sync, not(feature = "fragile-send-sync-non-atomic-wasm")))]
1280 compile_error!("cannot provide non-fragile Send+Sync without std");
1281
1282 type MaybeMutex<T> = core::cell::RefCell<T>;
1283
1284 fn lock<T>(mutex: &MaybeMutex<T>) -> core::cell::RefMut<'_, T> {
1285 mutex.borrow_mut()
1286 }
1287 }
1288}