mugl 0.1.2

Minimalistic Low-level WebGL 2.0 / WebGPU 3D graphics abstraction layer for Rust and WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;
use core::ops::Range;

use std::sync::{RwLock, RwLockWriteGuard};

use async_trait::async_trait;
use raw_window_handle::HasRawWindowHandle;

use super::conv::wgpu_operations;
use super::resource::{
    WGPUBindGroup, WGPUBindGroupLayout, WGPUBuffer, WGPUBufferView, WGPUDeviceDescriptor,
    WGPUFeatures, WGPURenderPass, WGPURenderPipeline, WGPUSampler, WGPUShader,
    WGPUSurfaceDescriptor, WGPUTexture,
};
use crate::descriptor::{
    BindGroupDescriptor, BindGroupLayoutDescriptor, BufferDescriptor, ColorTargetStates,
    ImageCopyTexture, ImageDataLayout, RenderPassDescriptor, RenderPipelineDescriptor,
    SamplerDescriptor, ShaderDescriptor, TextureDescriptor,
};
use crate::gpu::{GPUDevice, GPURefTypes, GPURenderPassEncoder, GPU};
use crate::primitive::{BufferSize, Color, Extent2D, Extent3D, TextureUsage};

/// WebGPU interface.
#[derive(Debug)]
pub struct WGPU;

/// WebGPU device.
#[derive(Debug)]
pub struct WGPUDevice {
    #[allow(dead_code)]
    instance: wgpu::Instance,
    #[allow(dead_code)]
    adapter: wgpu::Adapter,
    device: wgpu::Device,
    queue: wgpu::Queue,
    surface: wgpu::Surface,

    surface_config: RwLock<wgpu::SurfaceConfiguration>,
    surface_texture: RwLock<WGPUSurfaceTexture>,
    surface_depth_format: Option<wgpu::TextureFormat>,
    surface_msaa_sample_count: u32,

    commands: RwLock<Vec<wgpu::CommandBuffer>>,
    encoder: RwLock<Option<wgpu::CommandEncoder>>,
}

/// WebGPU surface texture.
#[derive(Debug, Default)]
struct WGPUSurfaceTexture {
    texture: Option<wgpu::SurfaceTexture>,
    texture_view: Option<wgpu::TextureView>,
    msaa_texture: Option<wgpu::Texture>,
    msaa_texture_view: Option<wgpu::TextureView>,
    depth_texture: Option<wgpu::Texture>,
    depth_texture_view: Option<wgpu::TextureView>,
}

/// WebGPU render pass encoder.
#[derive(Debug)]
pub struct WGPURenderPassEncoder<'a> {
    device: &'a WGPUDevice,
    // The pass must be declare before encoder so that it will be dropped first.
    pass: RwLock<Option<wgpu::RenderPass<'a>>>,
    // Must Box the encoder to provide a stable address for RenderPass to reference to.
    encoder: RwLock<Box<wgpu::CommandEncoder>>,
    index_format: RwLock<wgpu::IndexFormat>,
}

impl WGPU {
    /// Requests a new WGPU device asynchronously
    pub async fn request_device<W: HasRawWindowHandle>(
        window: &W,
        descriptor: WGPUDeviceDescriptor,
        surface_descriptor: WGPUSurfaceDescriptor,
    ) -> Option<WGPUDevice> {
        let instance = wgpu::Instance::new(wgpu::Backends::all());
        let surface = unsafe { instance.create_surface(window) };

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: descriptor.power_preference.into(),
                compatible_surface: Some(&surface),
                force_fallback_adapter: descriptor.force_fallback_adapter,
            })
            .await?;

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    features: wgpu::Features::empty(),
                    limits: wgpu::Limits::default(),
                    label: None,
                },
                None, // Trace path
            )
            .await
            .ok()?;

        let surface_config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface.get_preferred_format(&adapter)?,
            width: surface_descriptor.size.0,
            height: surface_descriptor.size.1,
            present_mode: wgpu::PresentMode::Fifo,
        };
        surface.configure(&device, &surface_config);

        let surface_depth_format = surface_descriptor.depth_stencil_format.map(Into::into);
        let surface_msaa_sample_count = surface_descriptor.sample_count;
        let mut surface_texture = WGPUSurfaceTexture::default();
        update_surface_depth_msaa(
            &mut surface_texture,
            &device,
            &surface_config,
            surface_depth_format,
            surface_msaa_sample_count,
        );

        Some(WGPUDevice {
            instance,
            adapter,
            device,
            queue,
            surface,
            surface_config: RwLock::new(surface_config),
            surface_texture: RwLock::new(surface_texture),
            surface_depth_format,
            surface_msaa_sample_count,
            commands: RwLock::default(),
            encoder: RwLock::default(),
        })
    }
}

impl GPU for WGPU {
    type Features = WGPUFeatures;
    type Device = WGPUDevice;
    type Buffer = WGPUBuffer;
    type Texture = WGPUTexture;
    type Sampler = WGPUSampler;
    type Shader = WGPUShader;
    type RenderPass = WGPURenderPass;
    type RenderPipeline = WGPURenderPipeline;
    type BindGroup = WGPUBindGroup;
    type BindGroupLayout = WGPUBindGroupLayout;
}

impl<'a> GPURefTypes<'a, WGPU> for WGPU {
    type RenderPassEncoder = WGPURenderPassEncoder<'a>;
    type BufferView = WGPUBufferView<'a>;
}

impl WGPUDevice {
    /// Submits a command buffer.
    fn submit(&self, buffer: wgpu::CommandBuffer) {
        if let Ok(mut commands) = self.commands.write() {
            // Push any pending commands in device encoder first

            if let Some(encoder) = self.encoder.write().unwrap().take() {
                commands.push(encoder.finish());
            }

            commands.push(buffer);
        }
    }

    fn get_encoder(&self) -> RwLockWriteGuard<Option<wgpu::CommandEncoder>> {
        let mut encoder = self.encoder.write().unwrap();
        if encoder.is_none() {
            *encoder = Some(
                self.device
                    .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }),
            );
        }
        encoder
    }
}

#[async_trait(?Send)]
impl GPUDevice<WGPU> for WGPUDevice {
    fn features(&self) -> WGPUFeatures {
        WGPUFeatures::empty()
    }

    fn create_buffer(&self, descriptor: BufferDescriptor) -> WGPUBuffer {
        WGPUBuffer {
            buffer: self.device.create_buffer(&wgpu::BufferDescriptor {
                label: None,
                size: descriptor.size as u64,
                usage: descriptor.usage.into(),
                mapped_at_creation: false,
            }),
        }
    }

    fn create_texture(&self, descriptor: TextureDescriptor) -> WGPUTexture {
        let msaa_resolve = !descriptor.format.is_depth_stencil()  // depth-stencil cannot be MSAA resolved
            && descriptor.sample_count > 1
            && descriptor.usage.contains(TextureUsage::RENDER_ATTACHMENT);

        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
            label: None,
            size: descriptor.size.into(),
            mip_level_count: descriptor.mip_level_count,
            sample_count: if msaa_resolve {
                1 // sample count of resolve target must be 1
            } else {
                descriptor.sample_count
            },
            dimension: descriptor.dimension.into(),
            format: descriptor.format.into(),
            usage: descriptor.usage.into(),
        });

        WGPUTexture {
            view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
            texture,
            msaa_texture: if msaa_resolve {
                Some(self.device.create_texture(&wgpu::TextureDescriptor {
                    label: None,
                    size: wgpu::Extent3d {
                        width: descriptor.size.0,
                        height: descriptor.size.1,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: descriptor.sample_count,
                    dimension: wgpu::TextureDimension::D2,
                    format: descriptor.format.into(),
                    usage: descriptor.usage.into(),
                }))
            } else {
                None
            },
            format: descriptor.format,
            dimension: descriptor.dimension,
        }
    }

    fn create_sampler(&self, descriptor: SamplerDescriptor) -> WGPUSampler {
        WGPUSampler {
            sampler: self.device.create_sampler(&wgpu::SamplerDescriptor {
                label: None,
                address_mode_u: descriptor.address_mode_u.into(),
                address_mode_v: descriptor.address_mode_v.into(),
                address_mode_w: descriptor.address_mode_w.into(),
                mag_filter: descriptor.mag_filter.into(),
                min_filter: descriptor.min_filter.into(),
                mipmap_filter: descriptor.mipmap_filter.into(),
                lod_min_clamp: descriptor.lod_min_clamp,
                lod_max_clamp: descriptor.lod_max_clamp,
                compare: descriptor.compare.map(Into::into),
                anisotropy_clamp: core::num::NonZeroU8::new(descriptor.max_anisotropy),
                border_color: None,
            }),
        }
    }

    fn create_shader(&self, descriptor: ShaderDescriptor) -> WGPUShader {
        WGPUShader {
            shader: self
                .device
                .create_shader_module(&wgpu::ShaderModuleDescriptor {
                    label: None,
                    source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(descriptor.code)),
                }),
        }
    }

    fn create_render_pipeline(
        &self,
        descriptor: RenderPipelineDescriptor<WGPU>,
    ) -> WGPURenderPipeline {
        let attributes = {
            let mut attributes = Vec::<wgpu::VertexAttribute>::new();
            for layout in descriptor.buffers {
                for attr in layout.attributes {
                    attributes.push(wgpu::VertexAttribute {
                        format: attr.format.into(),
                        offset: attr.offset as u64,
                        shader_location: attr.shader_location,
                    });
                }
            }
            attributes
        };
        let buffers = {
            let mut buffers = Vec::<wgpu::VertexBufferLayout>::new();
            let mut i = 0;
            for layout in descriptor.buffers {
                buffers.push(wgpu::VertexBufferLayout {
                    array_stride: layout.stride as u64,
                    step_mode: layout.step_mode.into(),
                    attributes: &attributes[i..(i + layout.attributes.len())],
                });
                i += layout.attributes.len();
            }
            buffers
        };

        WGPURenderPipeline {
            pipeline: self
                .device
                .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                    label: None,
                    layout: Some(
                        &self
                            .device
                            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                                label: None,
                                bind_group_layouts: &descriptor
                                    .bind_groups
                                    .iter()
                                    .map(|layout| &layout.layout)
                                    .collect::<Vec<_>>(),
                                push_constant_ranges: &[],
                            }),
                    ),
                    vertex: wgpu::VertexState {
                        module: &descriptor.vertex.shader,
                        entry_point: "vs_main", // TODO: should this be customizable?
                        buffers: &buffers,
                    },
                    primitive: descriptor.primitive.into(),
                    depth_stencil: descriptor.depth_stencil.map(Into::into),
                    multisample: descriptor.multisample.into(),
                    fragment: Some(wgpu::FragmentState {
                        module: &descriptor.fragment.shader,
                        entry_point: "fs_main", // TODO: should this be customizable?
                        targets: &(match descriptor.targets {
                            ColorTargetStates::Default { blend, write_mask } => {
                                vec![wgpu::ColorTargetState {
                                    format: self
                                        .surface
                                        .get_preferred_format(&self.adapter)
                                        .unwrap(),
                                    blend: blend.map(Into::into),
                                    write_mask: write_mask.into(),
                                }]
                            }
                            ColorTargetStates::Offscreen { targets } => targets
                                .iter()
                                .map(|target| wgpu::ColorTargetState {
                                    format: target.format.into(),
                                    blend: target.blend.map(Into::into),
                                    write_mask: target.write_mask.into(),
                                })
                                .collect::<Vec<_>>(),
                        }),
                    }),
                    multiview: None, // TODO: multiview
                }),
            index_format: descriptor
                .primitive
                .index_format
                .map(Into::into)
                .unwrap_or(wgpu::IndexFormat::Uint16),
        }
    }

    fn create_render_pass(&self, descriptor: RenderPassDescriptor<WGPU>) -> WGPURenderPass {
        match descriptor {
            RenderPassDescriptor::Default {
                clear_color,
                clear_depth,
                clear_stencil,
            } => {
                WGPURenderPass {
                    // Leave texture view as empty for default pass. They must be recreated every frame
                    color_views: Vec::default(),
                    resolve_targets: Vec::default(),
                    depth_view: None,
                    color_ops: vec![wgpu_operations(clear_color.map(Into::into))],
                    depth_ops: Some(wgpu_operations(clear_depth)),
                    stencil_ops: Some(wgpu_operations(clear_stencil)),
                }
            }
            RenderPassDescriptor::Offscreen {
                colors,
                depth_stencil,
                clear_depth,
                clear_stencil,
            } => WGPURenderPass {
                color_views: colors
                    .iter()
                    .map(|color| {
                        color
                            .view
                            .texture
                            .msaa_texture
                            .as_ref()
                            .map(|texture| {
                                texture.create_view(&wgpu::TextureViewDescriptor::default())
                            })
                            .unwrap_or_else(|| color.view.into())
                    })
                    .collect(),
                resolve_targets: colors
                    .iter()
                    .map(|color| {
                        if color.view.texture.msaa_texture.is_some() {
                            Some(color.view.into())
                        } else {
                            None
                        }
                    })
                    .collect(),
                depth_view: depth_stencil.map(Into::into),
                color_ops: colors
                    .iter()
                    .map(|color| wgpu_operations(color.clear.map(Into::into)))
                    .collect(),
                depth_ops: depth_stencil.map(|_| wgpu_operations(clear_depth)),
                stencil_ops: depth_stencil.map(|_| wgpu_operations(clear_stencil)),
            },
        }
    }

    fn create_bind_group_layout(
        &self,
        descriptor: BindGroupLayoutDescriptor,
    ) -> WGPUBindGroupLayout {
        WGPUBindGroupLayout {
            layout: self
                .device
                .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                    label: None,
                    entries: &descriptor
                        .entries
                        .iter()
                        .map(|entry| wgpu::BindGroupLayoutEntry {
                            binding: entry.binding,
                            visibility: entry.visibility.into(),
                            ty: entry.ty.into(),
                            count: None,
                        })
                        .collect::<Vec<_>>(),
                }),
        }
    }

    fn create_bind_group(&self, descriptor: BindGroupDescriptor<WGPU>) -> WGPUBindGroup {
        WGPUBindGroup {
            bind_group: self.device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: None,
                layout: &descriptor.layout.layout,
                entries: &descriptor
                    .entries
                    .iter()
                    .map(|entry| wgpu::BindGroupEntry {
                        binding: entry.binding,
                        resource: entry.resource.into(),
                    })
                    .collect::<Vec<_>>(),
            }),
        }
    }

    fn render<'a>(&'a self, pass: &'a WGPURenderPass) -> WGPURenderPassEncoder<'a> {
        let is_default_pass = pass.color_views.is_empty();

        if is_default_pass {
            update_surface_texture(self);
        }

        let surface_texture = self.surface_texture.read().unwrap();
        let encoder = RwLock::new(Box::new(
            self.device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }),
        ));

        WGPURenderPassEncoder {
            device: &self,
            pass: RwLock::new(if is_default_pass && surface_texture.texture.is_none() {
                None // TODO: Not able to get a valid surface texture
            } else {
                let mut encoder = encoder.write().unwrap();
                let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: None,
                    color_attachments: &(if is_default_pass {
                        vec![wgpu::RenderPassColorAttachment {
                            view: surface_texture
                                .msaa_texture_view
                                .as_ref()
                                .unwrap_or(surface_texture.texture_view.as_ref().unwrap()),
                            resolve_target: if surface_texture.msaa_texture_view.is_some() {
                                surface_texture.texture_view.as_ref()
                            } else {
                                None
                            },
                            ops: pass.color_ops[0],
                        }]
                    } else {
                        pass.color_views
                            .iter()
                            .enumerate()
                            .map(|(i, ref view)| wgpu::RenderPassColorAttachment {
                                view,
                                resolve_target: pass.resolve_targets[i].as_ref(),
                                ops: pass.color_ops[i],
                            })
                            .collect::<Vec<_>>()
                    }),
                    depth_stencil_attachment: (if is_default_pass {
                        surface_texture.depth_texture_view.as_ref()
                    } else {
                        pass.depth_view.as_ref()
                    })
                    .map(|view| wgpu::RenderPassDepthStencilAttachment {
                        view,
                        depth_ops: pass.depth_ops,
                        stencil_ops: pass.stencil_ops,
                    }),
                });

                Some(unsafe {
                    // Bypassing brrow checker.
                    // We have to make sure that RenderPass is dropped before the encoder
                    core::mem::transmute::<wgpu::RenderPass<'_>, wgpu::RenderPass<'a>>(render_pass)
                })
            }),
            encoder,
            index_format: RwLock::new(wgpu::IndexFormat::Uint16),
        }
    }

    fn write_buffer(&self, buffer: &WGPUBuffer, buffer_offset: BufferSize, data: &[u8]) {
        self.queue
            .write_buffer(&buffer.buffer, buffer_offset as u64, data);
    }

    fn write_texture(
        &self,
        texture: ImageCopyTexture<WGPU>,
        data: &[u8],
        layout: ImageDataLayout,
        size: Extent3D,
    ) {
        self.queue
            .write_texture(texture.into(), data, layout.into(), size.into())
    }

    async fn read_buffer<'a>(
        &self,
        buffer: &'a WGPUBuffer,
        range: Range<BufferSize>,
    ) -> Result<WGPUBufferView<'a>, ()> {
        let slice = buffer
            .buffer
            .slice((range.start as u64)..(range.end as u64));
        Ok(WGPUBufferView {
            buffer: &buffer.buffer,
            view: if let Ok(_) = slice.map_async(wgpu::MapMode::Read).await {
                Some(slice.get_mapped_range())
            } else {
                None
            },
        })
    }

    fn copy_buffer(
        &self,
        src: &WGPUBuffer,
        src_offset: BufferSize,
        dst: &WGPUBuffer,
        dst_offset: BufferSize,
        size: BufferSize,
    ) {
        self.get_encoder().as_mut().map(|encoder| {
            encoder.copy_buffer_to_buffer(
                &src.buffer,
                src_offset as u64,
                &dst.buffer,
                dst_offset as u64,
                size as u64,
            );
        });
    }

    fn copy_texture(
        &self,
        src: ImageCopyTexture<WGPU>,
        dst: ImageCopyTexture<WGPU>,
        size: Extent3D,
    ) {
        self.get_encoder()
            .as_mut()
            .map(|encoder| encoder.copy_texture_to_texture(src.into(), dst.into(), size.into()));
    }

    fn copy_texture_to_buffer(
        &self,
        src: ImageCopyTexture<WGPU>,
        dst: &WGPUBuffer,
        layout: ImageDataLayout,
        size: Extent3D,
    ) {
        self.get_encoder().as_mut().map(|encoder| {
            encoder.copy_texture_to_buffer(
                src.into(),
                wgpu::ImageCopyBuffer {
                    buffer: &dst.buffer,
                    layout: layout.into(),
                },
                size.into(),
            )
        });
    }

    fn is_lost(&self) -> bool {
        // TODO
        std::dbg!("is_lost is currently unsupported by WGPU backend");
        false
    }

    fn flush(&self) {
        if let Ok(mut commands) = self.commands.write() {
            if commands.len() > 0 {
                self.queue.submit(core::mem::take(&mut *commands));
            }
        }
    }

    fn present(&self) {
        self.flush();

        if let Some(texture) = self.surface_texture.write().unwrap().texture.take() {
            texture.present();
        }
    }

    fn resize_surface(&self, size: Extent2D) {
        let surface_config = {
            let mut surface_config = self.surface_config.write().unwrap();
            if size.0 > 0 && size.1 > 0 {
                surface_config.width = size.0;
                surface_config.height = size.1;
            }
            surface_config.clone()
        };
        self.surface.configure(&self.device, &surface_config);

        update_surface_depth_msaa(
            &mut *self.surface_texture.write().unwrap(),
            &self.device,
            &surface_config,
            self.surface_depth_format,
            self.surface_msaa_sample_count,
        );
    }
}

impl<'a> GPURenderPassEncoder<'a, WGPU> for WGPURenderPassEncoder<'a> {
    fn pipeline(&self, pipeline: &'a WGPURenderPipeline) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_pipeline(&pipeline.pipeline);
                *self.index_format.write().unwrap() = pipeline.index_format;
            }
        }
    }

    fn index(&self, buffer: &'a WGPUBuffer) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_index_buffer(buffer.buffer.slice(..), *self.index_format.read().unwrap());
            }
        }
    }

    fn vertex(&self, slot: u32, buffer: &'a WGPUBuffer, offset: BufferSize) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_vertex_buffer(slot, buffer.buffer.slice((offset as u64)..));
            }
        }
    }

    fn bind_group(&self, slot: u32, bind_group: &'a WGPUBindGroup, offsets: &[u32]) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_bind_group(
                    slot,
                    &bind_group.bind_group,
                    &offsets.iter().map(|offset| *offset).collect::<Vec<_>>(),
                );
            }
        }
    }

    fn draw(&self, vertices: Range<u32>, instances: Range<u32>) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.draw(vertices, instances);
            }
        }
    }

    fn draw_indexed(&self, indices: Range<u32>, instances: Range<u32>) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.draw_indexed(indices, 0, instances);
            }
        }
    }

    fn viewport(&self, x: f32, y: f32, width: f32, height: f32, min_depth: f32, max_depth: f32) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_viewport(x, y, width, height, min_depth, max_depth);
            }
        }
    }

    fn scissor_rect(&self, x: u32, y: u32, width: u32, height: u32) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_scissor_rect(x, y, width, height);
            }
        }
    }

    fn blend_const(&self, color: Color) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_blend_constant(color.into());
            }
        }
    }

    fn stencil_ref(&self, reference: u32) {
        if let Ok(mut lock) = self.pass.write() {
            if let Some(pass) = lock.as_mut() {
                pass.set_stencil_reference(reference);
            }
        }
    }

    fn submit(self) {
        {
            // Drops the render pass before consuming encoder
            let _pass = self.pass.into_inner();
        }
        self.device
            .submit(self.encoder.into_inner().unwrap().finish());
    }
}

fn update_surface_texture(device: &WGPUDevice) {
    match device.surface.get_current_texture() {
        Ok(surface_texture) => {
            let view = surface_texture
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default());
            let mut lock = device.surface_texture.write().unwrap();
            lock.texture = Some(surface_texture);
            lock.texture_view = Some(view);
        }
        Err(wgpu::SurfaceError::Lost) => {
            // Reconfigure surface if lost
            device.resize_surface(Extent2D(0, 0));
        }
        // Outdated, Timeout and hopefully OutOfMemory should be resolved by the next frame
        _ => (),
    }
}

fn update_surface_depth_msaa(
    surface_texture: &mut WGPUSurfaceTexture,
    device: &wgpu::Device,
    surface_config: &wgpu::SurfaceConfiguration,
    depth_format: Option<wgpu::TextureFormat>,
    sample_count: u32,
) {
    if sample_count > 1 {
        let msaa_tex = create_surface_texture(
            &device,
            &surface_config,
            surface_config.format,
            sample_count,
        );
        surface_texture.msaa_texture_view =
            Some(msaa_tex.create_view(&wgpu::TextureViewDescriptor::default()));
        surface_texture.msaa_texture = Some(msaa_tex);
    }
    if let Some(format) = depth_format {
        let depth_tex = create_surface_texture(&device, &surface_config, format, sample_count);
        surface_texture.depth_texture_view =
            Some(depth_tex.create_view(&wgpu::TextureViewDescriptor::default()));
        surface_texture.depth_texture = Some(depth_tex);
    }
}

fn create_surface_texture(
    device: &wgpu::Device,
    surface_config: &wgpu::SurfaceConfiguration,
    format: wgpu::TextureFormat,
    sample_count: u32,
) -> wgpu::Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: None,
        size: wgpu::Extent3d {
            width: surface_config.width,
            height: surface_config.height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        dimension: wgpu::TextureDimension::D2,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        sample_count,
        format,
    })
}