mewgpu 3.7.2

Maybe Easier Wgpu (mew), a thin abstraction over wgpu's chaos
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
#![doc(html_logo_url = "https://64-tesseract.ftp.sh/tesseract.gif", html_favicon_url = "https://64-tesseract.ftp.sh/tesseract.gif")]
#![doc = include_str!("../README.md")]

// Hide docs feature in docs
#![cfg_attr(doc, feature(doc_cfg))]
#![cfg_attr(doc, doc(auto_cfg(hide(doc))))]

use std::{
    any::TypeId,
    collections::BTreeMap,
};
#[cfg(not(feature = "sync"))]
use std::cell::RefCell;
#[cfg(feature = "sync")]
use std::sync::Mutex;

use thiserror::Error;

#[cfg(all(feature = "wgpu-29", feature = "wgpu-30", not(doc)))]
compile_error!("wgpu-29 and wgpu-30 conflict");
#[cfg(all(feature = "wgpu-29", not(feature = "wgpu-30")))]
pub use wgpu_29 as wgpu;
#[cfg(feature = "wgpu-30")]
pub use wgpu_30 as wgpu;

#[cfg(any(not(target_family = "wasm"), doc))]
pub use pollster;
#[cfg(any(target_family = "wasm", doc))]
pub use web_sys;

#[cfg(feature = "winit")]
pub use winit;

#[cfg(doc)]
pub mod doc_example;

mod macromath;
pub mod bindgroup;
pub mod buffer;
pub mod pipeline;
pub mod sampler;
pub mod shaderprimitive;
pub mod shaderstruct;
pub mod texture;
pub mod vertexformat;
pub mod vertexstruct;
#[cfg(any(feature = "winit", doc))]
pub mod winitutils;

pub mod prelude {
    //! All types, functions, and macros.

    pub use crate::{
        bindgroup::*,
        buffer::*,
        pipeline::*,
        sampler::*,
        shaderprimitive,
        shaderstruct::*,
        texture::*,
        vertexformat,
        vertexstruct::*,
        *,
    };
    #[cfg(feature = "winit")]
    pub use crate::winitutils::*;
}


/// Declare _mew_ types in a single block, rather than individual macro calls.
///
/// Individual macros need everything encapsulated in brackets, so things like
/// struct definitions look weird (imagine `struct! { Name { members } }`). By
/// dumping everything in a single macro block we can simplify a bit
/// (`struct Name { members }`).
///
/// Each declaration's syntax is exactly the same as the respective macro, plus
/// a semicolon. For example this:
///
/// ```
/// buffer! { ShaderBuffer <Struct> as STORAGE }
/// texture! { ShaderTexture {
///     usage: COPY_DST | TEXTURE_BINDING,
/// } }
/// ```
///
/// ...Becomes:
///
/// ```
/// mew! {
///     buffer ShaderBuffer <Struct> as STORAGE;
///     texture ShaderTexture {
///         usage: COPY_DST | TEXTURE_BINDING,
///     };
/// }
/// ```
///
/// It's entirely up to you if you want to use this.
#[macro_export]
macro_rules! mew {
    { bind_group $struct:ident [ $($params:tt)* ] ; $($rest:tt)* } => {
        $crate::bind_group! { $struct [ $($params)* ] }
        $crate::mew! { $($rest)* }
    };
    { buffer $struct:ident $(<$inner:ty>)? as $($usage:ident)|+ ; $($rest:tt)* } => {
        $crate::buffer! { $struct $(<$inner>)? as $($usage)|+ }
        $crate::mew! { $($rest)* }
    };
    { pipeline $struct:ident { $($params:tt)* } ; $($rest:tt)* } => {
        $crate::pipeline! { $struct { $($params)* } }
        $crate::mew! { $($rest)* }
    };
    { sampler $struct:ident as $filtering:ident $({$($params:tt)*})? ; $($rest:tt)* } => {
        $crate::sampler! { $struct as $filtering $({$($params)*})? }
        $crate::mew! { $($rest)* }
    };
    { shader_struct $struct:ident [ $($params:tt)* ] ; $($rest:tt)* } => {
        $crate::shader_struct! { $struct [ $($params)* ] }
        $crate::mew! { $($rest)* }
    };
    { texture $struct:ident { $($params:tt)* } ; $($rest:tt)* } => {
        $crate::texture! { $struct { $($params)* } }
        $crate::mew! { $($rest)* }
    };
    { vertex_struct $struct:ident $(step $step:ident)? $(+ $location:literal)? [ $($params:tt)* ] ; $($rest:tt)* } => {
        $crate::vertex_struct! { $struct $(step $step)? $(+ $location)? [ $($params)* ] }
        $crate::mew! { $($rest)* }
    };
    {} => {};
}


/// Error returned when trying to build a context.
#[derive(Clone, Debug, Error)]
pub enum BuildContextError {
    /// Requesting the adapter failed, see
    /// [`wgpu::Instance::request_adapter`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html#method.request_adapter).
    #[error(transparent)]
    Adapter(#[from] wgpu::RequestAdapterError),
    /// Requesting the device failed, see
    /// [`wgpu::Adapter::request_device`](https://docs.rs/wgpu/latest/wgpu/struct.Adapter.html#method.request_device).
    #[error(transparent)]
    Device(#[from] wgpu::RequestDeviceError),
}


/// A configuration to build an
/// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html).
/// The main things to specify are:
///
/// - The enabled
///   [`wgpu::Backends`](https://docs.rs/wgpu/latest/wgpu/struct.Backends.html).
///   By default, all backends are enabled, or it's taken from the environment
///   variable `WGPU_BACKEND`.
///
/// - As of _wgpu_ 29.0, a
///   [`dyn wgpu::wgt::WgpuHasDisplayHandle`](https://docs.rs/wgpu-types/latest/wgpu_types/instance/trait.WgpuHasDisplayHandle.html)
///   needs to be provided manually, or surfaces will not be able to be
///   configured. If you're building a [`RenderContext`] manually you almost
///   certainly need to supply this from e.g.
///   [winit::event_loop::EventLoop::owned_display_handle](https://docs.rs/winit/latest/winit/event_loop/struct.EventLoop.html#method.owned_display_handle)
///   when building your app, or alternatively, [`winitutils::DeferredContext`]
///   can defer ~~(haha see what i did there)~~ construction of the instance
///   until an
///   [winit::event_loop::ActiveEventLoop](https://docs.rs/winit/latest/winit/event_loop/struct.ActiveEventLoop.html)
///   is passed in when creating a window.
#[derive(Debug)]
pub struct InstanceSettings {
    backends: wgpu::Backends,
    display_handle: Option<Box<dyn wgpu::wgt::WgpuHasDisplayHandle>>,
}
impl Default for InstanceSettings {
    fn default() -> Self {
        Self {
            backends: wgpu::Backends::all().with_env(),
            display_handle: None,
        }
    }
}

impl Into<wgpu::Instance> for InstanceSettings {
    /// Construct a
    /// [wgpu::InstanceDescriptor](https://docs.rs/wgpu/latest/wgpu/struct.InstanceDescriptor.html)
    /// using the configured settings (rest is default), then create an
/// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html).
    fn into(self) -> wgpu::Instance {
        #[cfg(debug_assertions)]
        if self.display_handle.is_none() {
            eprintln!("Warning: mew may not be able to configure a surface without a display handle (e.g. winit::OwnedDisplayHandle)");
        }

        wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: self.backends,
            flags: wgpu::InstanceFlags::default(),
            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
            backend_options: wgpu::BackendOptions::default(),
            display: self.display_handle,
        })
    }
}


/// A builder abstraction for making a [`RenderContext`].
///
/// It's possible to make one directly with [`RenderContext::new`], but you need
/// to provide everything manually. This builder takes care of initilizing the
/// _wgpu_ handles for you with default values.
#[must_use = "RenderContext has not been built"]
#[derive(Debug)]
pub struct RenderContextBuilder<I = InstanceSettings> {
    instance: I,
    compatible_surface: Option<std::sync::Arc<wgpu::Surface<'static>>>,
    features: wgpu::Features,
    limits: wgpu::Limits,
}

impl<I: Clone> Clone for RenderContextBuilder<I> {
    fn clone(&self) -> Self {
        Self {
            instance: self.instance.clone(),
            compatible_surface: self.compatible_surface.clone(),
            features: self.features,
            limits: self.limits.clone(),
        }
    }
}

impl RenderContextBuilder<wgpu::Instance> {
    /// Prepare a new builder, providing your own
    /// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html).
    pub fn new_with_instance(instance: wgpu::Instance) -> Self {
        #[allow(unused_mut)]
        let mut builder = Self {
            instance,
            compatible_surface: None,
            features: wgpu::Features::default(),
            limits: wgpu::Limits::default(),
        };
        #[cfg(target_family = "wasm")]
        builder.set_limits(wgpu::Limits::downlevel_webgl2_defaults());
        builder
    }

    fn get_instance(&self) -> wgpu::Instance {
        self.instance.clone()
    }

    /// Put this builder into a [`winitutils::DeferredContext`], which simplifies
    /// the caller's workflow.
    ///
    /// In contrast with [`Self::deferred`], this method assumes you already have
    /// a [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html),
    /// so it will skip getting the display handle internally.
    ///
    /// On WebGL, we also need to run [`Self::with_compatible_surface`] after
    /// creating a window, but before configuring the surface - the steps are
    /// pretty intertwined, so this is managed automatically.
    #[cfg(any(feature = "winit", doc))]
    pub fn deferred_with_instance(self) -> winitutils::DeferredContext {
        winitutils::DeferredContext::new_with_instance(self)
    }
}

impl<I> RenderContextBuilder<I> {
    /// Specify a compatible surface for the
    /// [`wgpu::Adapter`](https://docs.rs/wgpu/latest/wgpu/struct.Adapter.html).
    ///
    /// This is required by WebGL and really annoying to set up, see
    /// [`winitutils::DeferredContext`].
    pub fn with_compatible_surface(mut self, surface: Option<std::sync::Arc<wgpu::Surface<'static>>>) -> Self {
        self.set_compatible_surface(surface);
        self
    }

    /// Specify a compatible surface for the
    /// [`wgpu::Adapter`](https://docs.rs/wgpu/latest/wgpu/struct.Adapter.html).
    ///
    /// This is required by WebGL and really annoying to set up, see
    /// [`winitutils::DeferredContext`].
    pub fn set_compatible_surface(&mut self, surface: Option<std::sync::Arc<wgpu::Surface<'static>>>) -> &mut Self {
        self.compatible_surface = surface;
        self
    }

    /// Specify the
    /// [`wgpu::Features`](https://docs.rs/wgpu/latest/wgpu/struct.Features.html)
    /// the
    /// [`wgpu::Device`](https://docs.rs/wgpu/latest/wgpu/struct.Device.html)
    /// will require.
    pub fn with_features(mut self, features: wgpu::Features) -> Self {
        self.set_features(features);
        self
    }

    /// Specify the
    /// [`wgpu::Features`](https://docs.rs/wgpu/latest/wgpu/struct.Features.html)
    /// the
    /// [`wgpu::Device`](https://docs.rs/wgpu/latest/wgpu/struct.Device.html)
    /// will require.
    pub fn set_features(&mut self, features: wgpu::Features) -> &mut Self {
        self.features = features;
        self
    }

    /// Specify the
    /// [`wgpu::Limits`](https://docs.rs/wgpu/latest/wgpu/struct.Limits.html)
    /// the
    /// [`wgpu::Device`](https://docs.rs/wgpu/latest/wgpu/struct.Device.html)
    /// will require.
    ///
    /// On web, this is automatically set to
    /// [`wgpu::Limits::downlevel_webgl2_defaults`](https://docs.rs/wgpu/latest/wgpu/struct.Limits.html#method.downlevel_webgl2_defaults),
    /// but is overridable if you really want to.  
    /// On native, it's just [`Default::default`].
    pub fn with_limits(mut self, limits: wgpu::Limits) -> Self {
        self.set_limits(limits);
        self
    }

    /// Specify the
    /// [`wgpu::Limits`](https://docs.rs/wgpu/latest/wgpu/struct.Limits.html)
    /// the
    /// [`wgpu::Device`](https://docs.rs/wgpu/latest/wgpu/struct.Device.html)
    /// will require.
    ///
    /// On web, this is automatically set to
    /// [`wgpu::Limits::downlevel_webgl2_defaults`](https://docs.rs/wgpu/latest/wgpu/struct.Limits.html#method.downlevel_webgl2_defaults),
    /// but is overridable if you really want to.  
    /// On native, it's just [`Default::default`].
    pub fn set_limits(&mut self, limits: wgpu::Limits) -> &mut Self {
        self.limits = limits;
        self
    }
}

impl RenderContextBuilder {
    /// Prepare a new builder.
    ///
    /// The
    /// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html)
    /// will be built later when needed.
    pub fn new() -> Self {
        #[allow(unused_mut)]
        let mut builder = Self {
            instance: InstanceSettings::default(),
            compatible_surface: None,
            features: wgpu::Features::default(),
            limits: wgpu::Limits::default(),
        };
        #[cfg(target_family = "wasm")]
        builder.set_limits(wgpu::Limits::downlevel_webgl2_defaults());
        builder
    }

    /// Specify the
    /// [wgpu::Backends](https://docs.rs/wgpu/latest/wgpu/struct.Backends.html)
    /// you want to construct the
    /// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html)
    /// for.
    pub fn with_backends(mut self, backends: wgpu::Backends) -> Self {
        self.set_backends(backends);
        self
    }

    /// Specify the
    /// [wgpu::Backends](https://docs.rs/wgpu/latest/wgpu/struct.Backends.html)
    /// you want to construct the
    /// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html)
    /// for.
    pub fn set_backends(&mut self, backends: wgpu::Backends) -> &mut Self {
        self.instance.backends = backends;
        self
    }

    /// As of _wgpu_ 29.0, a
    /// [`dyn wgpu::wgt::WgpuHasDisplayHandle`](https://docs.rs/wgpu-types/latest/wgpu_types/instance/trait.WgpuHasDisplayHandle.html)
    /// needs to be provided manually, or surfaces will not be able to be
    /// configured.
    ///
    /// This is somewhat annoying to set up, see [`winitutils::DeferredContext`].
    pub fn with_display_handle(mut self, display_handle: Box<dyn wgpu::wgt::WgpuHasDisplayHandle>) -> Self {
        self.set_display_handle(display_handle);
        self
    }

    /// As of _wgpu_ 29.0, a
    /// [`dyn wgpu::wgt::WgpuHasDisplayHandle`](https://docs.rs/wgpu-types/latest/wgpu_types/instance/trait.WgpuHasDisplayHandle.html)
    /// needs to be provided manually, or surfaces will not be able to be
    /// configured.
    ///
    /// This is somewhat annoying to set up, see [`winitutils::DeferredContext`].
    pub fn set_display_handle(&mut self, display_handle: Box<dyn wgpu::wgt::WgpuHasDisplayHandle>) -> &mut Self {
        self.instance.display_handle = Some(display_handle);
        self
    }

    /// Put this builder into a [`winitutils::DeferredContext`], which simplifies
    /// the caller's workflow.
    ///
    /// By deferring the builder's construction, we don't have to immediately
    /// provide a 
    /// [`dyn wgpu::wgt::WgpuHasDisplayHandle`](https://docs.rs/wgpu-types/latest/wgpu_types/instance/trait.WgpuHasDisplayHandle.html)
    /// as this can be retrieved from an
    /// [`winit::event_loop::ActiveEventLoop`](https://docs.rs/winit/latest/winit/event_loop/struct.ActiveEventLoop.html)
    /// when creating a new window.
    ///
    /// On WebGL, we also need to run [`Self::with_compatible_surface`] after
    /// creating a window, but before configuring the surface - the steps are
    /// pretty intertwined, so this is managed automatically.
    #[cfg(any(feature = "winit", doc))]
    pub fn deferred(self) -> winitutils::DeferredContext {
        winitutils::DeferredContext::new(self)
    }
}

impl Default for RenderContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl<I: Into<wgpu::Instance>> RenderContextBuilder<I> {
    /// Make sure an
    /// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html)
    /// is constructed and ready for use.
    fn build_instance(self) -> RenderContextBuilder<wgpu::Instance> {
        RenderContextBuilder::<_> {
            instance: self.instance.into(),
            compatible_surface: self.compatible_surface,
            features: self.features,
            limits: self.limits,
        }
    }

    /// Try to build the [`RenderContext`] with the configured settings.
    ///
    /// This function is `async` because
    /// [`wgpu::Instance::request_adapter`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html#method.request_adapter)
    /// and
    /// [`wgpu::Adapter::request_device`](https://docs.rs/wgpu/latest/wgpu/struct.Adapter.html#method.request_device)
    /// are for some reason.  
    /// On native, you can use [`Self::build_poll`]. On web, you need to spawn a JS
    /// thread to await this, or use [`Self::deferred`] which does this internally.
    pub async fn build(self) -> Result<RenderContext, BuildContextError> {
        let this = self.build_instance();
        let instance = this.get_instance();

        let adapter = instance.request_adapter(
            &wgpu::RequestAdapterOptions {
                compatible_surface: this.compatible_surface.as_deref(),
                ..Default::default()
            },
        ).await?;

        let (device, queue) = adapter.request_device(
            &wgpu::DeviceDescriptor {
                label: Some("Device"),
                required_features: this.features,
                required_limits: this.limits,
                ..Default::default()
            }
        ).await?;

        Ok(RenderContext::new(instance, adapter, device, queue))
    }

    /// Try to build the [`RenderContext`] with the configured settings, but block
    /// on the result with _pollster_.
    #[cfg(any(not(target_family = "wasm"), doc))]
    pub fn build_poll(self) -> Result<RenderContext, BuildContextError> {
        pollster::block_on(self.build())
    }
}


#[cfg(not(feature = "sync"))]
#[derive(Debug)]
struct LayoutMaps {
    bind_groups: RefCell<BTreeMap<TypeId, wgpu::BindGroupLayout>>,
    pipelines: RefCell<BTreeMap<TypeId, wgpu::PipelineLayout>>,
}

#[cfg(feature = "sync")]
#[derive(Debug)]
struct LayoutMaps {
    bind_groups: Mutex<BTreeMap<TypeId, wgpu::BindGroupLayout>>,
    pipelines: Mutex<BTreeMap<TypeId, wgpu::PipelineLayout>>,
}

impl LayoutMaps {
    fn new() -> Self {
        Self {
            bind_groups: BTreeMap::new().into(),
            pipelines: BTreeMap::new().into(),
        }
    }
}


/// The heart of _mew_. Bundles all necessary _wgpu_ handles and takes care of
/// constructing buffers, bind groups, & pipelines with a single function call.
#[derive(Debug)]
pub struct RenderContext<Instance = wgpu::Instance> {
    pub instance: Instance,
    pub adapter: wgpu::Adapter,
    pub device: wgpu::Device,
    pub queue: wgpu::Queue,
    // TODO: Potentially put in Rc & allow Clone
    layouts: LayoutMaps,
}

impl RenderContext {
    /// Build a context manually by providing the
    /// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html),
    /// [`wgpu::Adapter`](https://docs.rs/wgpu/latest/wgpu/struct.Adapter.html),
    /// [`wgpu::Device`](https://docs.rs/wgpu/latest/wgpu/struct.Device.html),
    /// and
    /// [`wgpu::Queue`](https://docs.rs/wgpu/latest/wgpu/struct.Queue.html).
    ///
    /// You can build this directly, but a [`RenderContextBuilder`] takes care of
    /// the annoying stuff for you.
    pub fn new(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Self {
        Self {
            instance,
            adapter,
            device,
            queue,
            layouts: LayoutMaps::new(),
        }
    }
}

impl RenderContext<()> {
    /// Technically a
    /// [`wgpu::Instance`](https://docs.rs/wgpu/latest/wgpu/struct.Instance.html) is
    /// only needed if you're going to be creating windows (through
    /// [`winitutils::DeferredContext`]), but if you're getting the _wgpu_ handles
    /// from another library like _egui_, the `Instance` may not be provided. In
    /// this case we're not managing windows anyway, so you don't need to construct
    /// a [`winitutils::DeferredContext`].
    ///
    /// By default, non-atomic interior mutability is used, which means it's not
    /// `Send + Sync`. You may like to enable the `sync` feature which changes this.
    pub fn new_without_instance(adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Self {
        RenderContext {
            instance: (),
            adapter,
            device,
            queue,
            layouts: LayoutMaps::new(),
        }
    }
}

impl<I> RenderContext<I> {
    /// Build a new buffer with an internal capacity to fit its internal type.
    ///
    /// The type of buffer it makes is determined by its type parameter.
    ///
    /// ```
    /// buffer! { SomeBuffer <InternalType> as STORAGE | COPY_DST }
    /// let buffer: SomeBuffer = context.new_buffer(10);
    /// assert_eq!(buffer.size() as usize, size_of::<InternalType>() * 10);
    /// ```
    pub fn new_buffer<BUFFER: buffer::MewBuffer>(&self, inner_size: u64) -> BUFFER {
        let raw_buffer = self.device.create_buffer(&BUFFER::buffer_desc(inner_size));
        BUFFER::new(raw_buffer)
    }

    /// Build a new sampler.
    ///
    /// The type of sampler it makes is determined by its type parameter.
    ///
    /// ```
    /// sampler! { SomeSampler as Filtering }
    /// let sampler: SomeSampler = context.new_sampler();
    /// ```
    pub fn new_sampler<SAMPLER: sampler::MewSampler>(&self) -> SAMPLER {
        let raw_sampler = self.device.create_sampler(&SAMPLER::buffer_desc());
        SAMPLER::new(raw_sampler)
    }

    /// Build a new sampler with dimensions and a
    /// [`wgpu::TextureFormat`](https://docs.rs/wgpu/latest/wgpu/enum.TextureFormat.html).
    ///
    /// The type of texture it makes is determined by its type parameter.
    ///
    /// ```
    /// texture! { SomeTexture { .. } }
    /// let texture: SomeTexture = context.new_texture((64, 64, 1), wgpu::TextureFormat::Rgba8Unorm);
    /// ```
    pub fn new_texture<TEXTURE: texture::MewTexture>(&self, inner_size: (u32, u32, u32), format: wgpu::TextureFormat) -> TEXTURE {
        let raw_texture = self.device.create_texture(&TEXTURE::buffer_desc(inner_size, format));
        TEXTURE::new(raw_texture)
    }

    /// Get a handle to a
    /// [wgpu::BindGroupLayout](https://docs.rs/wgpu/latest/wgpu/struct.BindGroupLayout.html)
    /// by the type ID of a _mew_ bind group, or create & insert a new one by its
    /// [wgpu::BindGroupLayoutDescriptor](https://docs.rs/wgpu/latest/wgpu/struct.BindGroupLayoutDescriptor.html).
    fn get_bind_group_layout_manual(&self, type_id: TypeId, desc: &wgpu::BindGroupLayoutDescriptor<'static>) -> wgpu::BindGroupLayout {
        #[cfg(not(feature = "sync"))]
        let mut layouts = self.layouts.bind_groups.borrow_mut();
        #[cfg(feature = "sync")]
        let mut layouts = self.layouts.bind_groups.lock().expect("Bind group layouts poisoned");
        layouts.entry(type_id).or_insert_with(|| self.device.create_bind_group_layout(desc)).clone()
    }

    /// Call [`get_bind_group_layout_manual`] by getting the type ID of a _mew_ bind
    /// group and its layout descriptor.
    fn get_bind_group_layout<BIND: bindgroup::MewBindGroup + 'static>(&self) -> bindgroup::MewBindGroupLayout<BIND> {
        let layout = self.get_bind_group_layout_manual(TypeId::of::<BIND>(), &BIND::layout_desc());
        bindgroup::MewBindGroupLayout::new(layout)
    }

    /// Build a new buffer with a tuple of its bind groups.
    ///
    /// The type of bind group it makes is determined by its type parameter.
    ///
    /// ```
    /// bind_group! { StuffBindGroup [
    ///     0 buffer_one @ VERTEX => SomeBuffer,
    ///     1 other_buffer @ FRAGMENT => SomeOtherBuffer,
    /// ] }
    /// let bind_group: SomeBindGroup = render_context.new_bind_group((buffer, other_buffer));
    /// ```
    pub fn new_bind_group<BIND: bindgroup::MewBindGroup + 'static>(&self, buffers: BIND::BufferSet) -> BIND {
        let raw_bind_group = {
            let layout = self.get_bind_group_layout::<BIND>();
            let entries = BIND::bind_group_entries(&buffers);
            let desc = BIND::bind_group_desc(&layout, &entries);
            self.device.create_bind_group(&desc)
        };
        BIND::new(raw_bind_group, buffers)
    }

    /// Get a handle to a
    /// [wgpu::PipelineLayout](https://docs.rs/wgpu/latest/wgpu/struct.PipelineLayout.html)
    /// by the type ID of the _mew_ pipeline, or create & insert a new one by its
    /// [wgpu::PipelineLayoutDescriptor](https://docs.rs/wgpu/latest/wgpu/struct.PipelineLayoutDescriptor.html)
    /// and the layours of all its bind groups.
    fn get_pipeline_layout<PIPE: pipeline::MewPipeline + 'static>(&self) -> pipeline::MewPipelineLayout<PIPE> {
        let layout = {
            #[cfg(not(feature = "sync"))]
            let mut layouts = self.layouts.pipelines.borrow_mut();
            #[cfg(feature = "sync")]
            let mut layouts = self.layouts.pipelines.lock().expect("Pipeline layouts poisoned");
            layouts.entry(TypeId::of::<PIPE>()).or_insert_with(|| {
                let bind_group_descs = PIPE::bind_group_layout_types_array();
                let bind_group_layouts = PIPE::map_bind_group_array(&bind_group_descs, |(type_id, desc)| self.get_bind_group_layout_manual(*type_id, desc));
                //let bind_group_refs = PIPE::bind_group_ref_array(&bind_group_layouts);
                // &[_] -> [Option<&_>]
                let bind_group_refs = PIPE::map_bind_group_array(&bind_group_layouts, Some);
                let desc = PIPE::layout_desc(&bind_group_refs);
                self.device.create_pipeline_layout(&desc)
            }).clone()
        };
        pipeline::MewPipelineLayout::new(layout)
    }

    /// Build a new pipeline given a
    /// [`wgpu::TextureFormat`](https://docs.rs/wgpu/latest/wgpu/enum.TextureFormat.html),
    /// a
    /// [`wgpu::ShaderModule`](https://docs.rs/wgpu/latest/wgpu/enum.ShaderModule.html)
    /// (that you need to construct yourself), and the shader's entry points (or
    /// `None` if you only have one entry point).
    ///
    /// The type of pipeline it makes is determined by its type parameter.
    ///
    /// ```
    /// pipeline! { Pipeline { .. } }
    /// let pipeline: Pipeline = render_context.new_pipeline(wgpu::Rgba8Unorm, shader, Some("vs_main"), None);
    /// ```
    pub fn new_pipeline<PIPE: pipeline::MewPipeline + 'static>(
        &self,
        surface_fmt: wgpu::TextureFormat,
        shader: &wgpu::ShaderModule,
        vertex_entry: Option<&str>,
        fragment_entry: Option<&str>,
    ) -> PIPE {
        let raw_pipeline = {
            let layout = self.get_pipeline_layout::<PIPE>();
            let targets = PIPE::fragment_targets(surface_fmt);
            let desc = &PIPE::pipeline_desc(&layout, shader, vertex_entry, fragment_entry, &targets);
            self.device.create_render_pipeline(desc)
        };
        PIPE::new(raw_pipeline)
    }
}