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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
//! Contains the heart and soul of Screen 13.
//!
//! This module does the heavy-lifting work in this library and is made from a number of child
//! internal-only modules which support the functionality described here.
//!
//! ## Note About Operations
//!
//! All of the things `Render` allows are recorded internally using `Op` implementations which are
//! themselves just containers of graphics API resources and the commands to work on them.
//!
//! I think this structure is really flexible and clear and might live for a few good versions at
//! least.
//!
//! _NOTE:_ `Op` implementations should follow a few rules for sanity:
//! - Use a `Pool` instance to acquire new resources
//! - `new(...) -> Self`: function initializes with minimum settings
//! - `with_X(&mut self, ...) -> &mut Self`: Use the mutable borrow builder pattern for options/extras
//! - `record(&mut self, ...)`: function does three things:
//!   1. Initialize final settings/pipelines
//!   1. Write descriptors
//!   1. Submit all commands
//! - `submit_X(&self)`: functions which contain minimal "if" cases and logic; simple calls only.
//!
//! ## Note About `Rc`
//!
//! Screen 13 currently uses the `Rc` type in order to synchronize work between various operations.
//!
//! Unfortunately, this limits Screen 13 resources from being shared across threads. We could
//! simply replace those references with `Arc` and call it a day (that would work), but I'm not yet
//! sure that's a good pattern, it would introduce unessecery resource synchronization.
//!
//! I think as the API matures a better solution will become clearer, just not sure which types I
//! want to be `Send` yet. The driver really could be `Sync`.
//!
//! ## Note About `def`
//!
//! Internally Screen 13 uses pre-defined render passes and pipelines to function.
//!
//! All of these definitions exist in the `def` module and are *great*, but inflexible. They only
//! do what I programmed them to do. Lame.
//!
//! Instead, these definitions should be built and cached at runtime based on the operation which
//! have been recorded. There are follow-on things such as shaders to handle and so I'm not ready
//! for this change yet.
//!
//! Similiarly, the handling of command buffers and submission queues is currently on a
//! per-operation basis which is very limiting. We should keep running command buffers and only
//! close them when the graph of operations says so.

pub mod clear {
    //! Types for clearing textures with a configurable color.

    pub use super::op::ClearOp;
}

pub mod copy {
    //! Types for copying textures with configurable source and destination coordinates.

    pub use super::op::CopyOp;
}

pub mod draw {
    //! Types for drawing user-specified models and lights onto textures.

    pub use super::op::{
        Draw, DrawOp, LineCommand, Material, Mesh, ModelCommand, PointLightCommand,
        RectLightCommand, Skydome, SpotlightCommand, SunlightCommand,
    };
}

pub mod encode {
    //! Types for encoding textures into the `.jpg` or `.png` file formats.

    pub use super::op::EncodeOp;
}

pub mod font {
    //! Types for writing text onto textures using stylized fonts.

    pub use super::op::{Font, FontOp};
}

pub mod gradient {
    //! Types for filling textures with linear and radial gradients.

    pub use super::op::GradientOp;
}

pub mod write {
    //! Types for pasting/splatting textures with configurable source and destination transforms.

    pub use super::op::{Write, WriteMode, WriteOp};
}

mod data;
mod def;
mod driver;
mod model;
mod op;
mod pool;
mod render;
mod spirv {
    include!(concat!(env!("OUT_DIR"), "/spirv/mod.rs"));
}
mod swapchain;
mod texture;

pub use self::{
    def::vertex,
    model::{MeshFilter, Model, Pose},
    op::Bitmap,
    render::Render,
    texture::Texture,
};

pub(crate) use self::{driver::Driver, op::Op, pool::Pool, swapchain::Swapchain};

use {
    self::{
        data::{Data, Mapping},
        driver::{Device, Image2d, Surface},
        font::*,
        op::BitmapOp,
        pool::{Lease, PoolRef},
        vertex::Vertex,
    },
    crate::{
        error::Error,
        math::Extent,
        pak::{model::Mesh, AnimationId, BitmapFormat, BitmapId, IndexType, ModelId, Pak},
    },
    gfx_hal::{
        adapter::Adapter, buffer::Usage, device::Device as _, queue::QueueFamily,
        window::Surface as _, Instance as _,
    },
    gfx_impl::{Backend as _Backend, Instance},
    num_traits::Num,
    std::{
        cell::RefCell,
        fmt::Debug,
        io::{Read, Seek},
        rc::Rc,
    },
    winit::window::Window,
};

#[cfg(debug_assertions)]
use {
    num_format::{Locale, ToFormattedString},
    std::time::Instant,
};

/// A two dimensional rendering result.
pub type Texture2d = TextureRef<Image2d>;

/// A helpful alias used to share `Bitmap` instances used with rendering operations.
pub type BitmapRef = Rc<Bitmap>;

/// A helpful alias used to share `Model` instances used with rendering operations.
pub type ModelRef = Rc<Model>;

pub(crate) type TextureRef<I> = Rc<RefCell<Texture<I>>>;

type LoadCache = RefCell<Pool>;
type OpCache = RefCell<Option<Vec<Box<dyn Op>>>>;

/// Rounds down a multiple of atom; panics if atom is zero
fn align_down<N: Copy + Num>(size: N, atom: N) -> N {
    size - size % atom
}

/// Rounds up to a multiple of atom; panics if either parameter is zero
fn align_up<N: Copy + Num>(size: N, atom: N) -> N {
    (size - <N>::one()) - (size - <N>::one()) % atom + atom
}

fn create_instance() -> (Adapter<_Backend>, Instance) {
    let instance = Instance::create("attackgoat/screen-13", 1).unwrap();
    let mut adapters = instance.enumerate_adapters();
    if adapters.is_empty() {
        // TODO: Error::adapter
    }
    let adapter = adapters.remove(0);
    (adapter, instance)
}

// TODO: Different path for webgl and need this -> #[cfg(any(feature = "vulkan", feature = "metal"))]
fn create_surface(window: &Window) -> (Adapter<_Backend>, Surface) {
    let (adapter, instance) = create_instance();
    let surface = Surface::new(instance, window).unwrap();
    (adapter, surface)
}

/// Indicates the provided data was bad.
#[derive(Debug)]
pub struct BadData;

/// Specifies a method for combining two images using a mathmatical formula.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum BlendMode {
    /// Blend formula: a + b
    Add,

    /// Blend formula:
    AlphaAdd,

    /// Blend formula: 1 - (1 - a) / b
    ColorBurn,

    /// Blend formula: a / (1 - b)
    ColorDodge,

    /// Blend formula:
    Color,

    /// Blend formula: min(a, b)
    Darken,

    /// Blend formula: min(a, b) (_per-component_)
    DarkerColor,

    /// Blend formula: abs(a - b)
    Difference,

    /// Blend formula: a / b
    Divide,

    /// Blend formula: a + b - 2 * a * b
    Exclusion,

    /// Blend formula: hard_light(a, b) (_per-component_)
    ///
    /// Where:
    /// - hard_light(a, b) = if b < 0.5 {
    ///                          2 * a * b
    ///                      } else {
    ///                          1 - 2 * (1 - a) * (1 - b)
    ///                      }
    HardLight,

    // TODO: It looks like this formula is correct and hard light and overlay are wrong or the
    // other way around?
    /// Blend formula: hard_mix(a, b) (_per-component_)
    ///
    /// Where:
    /// - hard_mix(a, b) = if b < 0.5 {
    ///                        2 * a * b
    ///                    } else {
    ///                        1 - 2 * (1 - a) * (1 - b)
    ///                    }
    HardMix,

    /// Blend formula: a + b - 1
    LinearBurn,

    /// Blend formula: a * b
    Multiply,

    /// Blend formula: b
    ///
    /// _NOTE:_ This is the default blend mode.
    Normal,

    /// Blend formula: overlay(a, b) (_per-component_)
    ///
    /// Where:
    /// - overlay(a, b) = if b < 0.5 {
    ///                       2 * a * b
    ///                   } else {
    ///                       1 - 2 * (1 - a) * (1 - b)
    ///                   }
    Overlay,

    /// Blend formula: 1 - (1 - a) * (1 - b)
    Screen,

    /// Blend formula: a - b
    Subtract,

    /// Blend formula: vivid_light(a, b) (_per-component_)
    ///
    /// Where:
    /// - vivid_light(a, b) = if b < 0.5 {
    ///                           1 - (1 - a) / b
    ///                       } else {
    ///                           a / (1 - b)
    ///                       }
    VividLight,
}

impl Default for BlendMode {
    fn default() -> Self {
        Self::Normal
    }
}

// TODO: Make this drainable?
/// An opaque cache of graphics API handles and resources.
///
/// For optimal performance, `Cache` instances should remain as owned values for at least three
/// hardware frames after their last use.
///
/// _NOTE:_ Program execution will halt for a few milliseconds after `Cache` types with active
/// internal operations are dropped.
#[derive(Default)]
pub struct Cache(PoolRef<Pool>);

/// Allows you to load resources and begin rendering operations.
pub struct Gpu {
    driver: Driver,
    loads: LoadCache,
    ops: OpCache,
    renders: Cache,
}

impl Gpu {
    pub(super) fn new(window: &Window) -> (Self, Driver, Surface) {
        let (adapter, surface) = create_surface(window);

        info!(
            "Device: {} ({:?})",
            &adapter.info.name, adapter.info.device_type
        );

        let queue = adapter
            .queue_families
            .iter()
            .find(|family| {
                let ty = family.queue_type();
                surface.supports_queue_family(family)
                    && ty.supports_graphics()
                    && ty.supports_compute()
            })
            .ok_or_else(Error::graphics_queue_family)
            .unwrap();
        let driver = Driver::new(RefCell::new(
            Device::new(adapter.physical_device, queue).unwrap(),
        ));
        let driver_copy = Driver::clone(&driver);
        (
            Self {
                driver,
                loads: Default::default(),
                ops: Default::default(),
                renders: Default::default(),
            },
            driver_copy,
            surface,
        )
    }

    // TODO: Enable sharing between this and "on-screen"
    /// Creates a `Gpu` for off-screen or headless use.
    ///
    /// _NOTE_: Resources loaded or read from a `Gpu` created in headless or screen modes cannot be
    /// used with other instances, including of the same mode. This is a limitation only because
    /// the code to share the resources properly has not be started yet.
    pub fn offscreen() -> Self {
        let (adapter, _) = create_instance();
        let queue = adapter
            .queue_families
            .iter()
            .find(|family| {
                let ty = family.queue_type();
                ty.supports_graphics() && ty.supports_compute()
            })
            .ok_or_else(Error::graphics_queue_family)
            .unwrap();
        let driver = Driver::new(RefCell::new(
            Device::new(adapter.physical_device, queue).unwrap(),
        ));

        Self {
            driver,
            loads: Default::default(),
            ops: Default::default(),
            renders: Default::default(),
        }
    }

    /// Loads a bitmap at runtime from the given data.
    ///
    ///
    pub fn load_bitmap(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        pixel_ty: BitmapFormat,
        pixels: &[u8],
        width: u32,
        stride: u32,
    ) -> Bitmap {
        #[cfg(feature = "debug-names")]
        let _ = name;
        let _ = pixel_ty;
        let _ = pixels;
        let _ = width;
        let _ = stride;

        todo!();
    }

    /// Loads an indexed model at runtime from the given data.
    ///
    ///
    pub fn load_indexed_model<
        M: IntoIterator<Item = Mesh>,
        I: IntoIterator<Item = u32>,
        V: IntoIterator<Item = VV>,
        VV: Copy + Into<Vertex>,
    >(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        meshes: M,
        _indices: I,
        _vertices: V,
    ) -> Result<Model, BadData> {
        let meshes = meshes.into_iter().collect::<Vec<_>>();
        // let indices = indices.into_iter().collect::<Vec<_>>();
        // let vertices = vertices.into_iter().collect::<Vec<_>>();

        // Make sure the incoming meshes are valid
        for mesh in &meshes {
            if mesh.vertex_count() % 3 != 0 {
                return Err(BadData);
            }
        }

        let mut pool = self.loads.borrow_mut();

        let idx_buf_len = 0;
        let idx_buf = pool.data_usage(
            #[cfg(feature = "debug-names")]
            name,
            &self.driver,
            idx_buf_len,
            Usage::INDEX | Usage::STORAGE,
        );

        let vertex_buf_len = 0;
        let vertex_buf = pool.data_usage(
            #[cfg(feature = "debug-names")]
            name,
            &self.driver,
            vertex_buf_len,
            Usage::VERTEX | Usage::STORAGE,
        );

        let staging_buf_len = 0;
        let staging_buf = pool.data_usage(
            #[cfg(feature = "debug-names")]
            name,
            &self.driver,
            staging_buf_len,
            Usage::VERTEX | Usage::STORAGE,
        );

        let write_mask_len = 0;
        let write_mask = pool.data_usage(
            #[cfg(feature = "debug-names")]
            name,
            &self.driver,
            write_mask_len,
            Usage::STORAGE,
        );

        Ok(Model::new(
            meshes,
            IndexType::U32,
            (idx_buf, idx_buf_len),
            (vertex_buf, vertex_buf_len),
            (staging_buf, staging_buf_len, write_mask),
        ))
    }

    /// Loads a regular model at runtime from the given data.
    ///
    ///
    pub fn load_model<
        IM: IntoIterator<Item = M>,
        IV: IntoIterator<Item = V>,
        M: Into<Mesh>,
        V: Copy + Into<Vertex>,
    >(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        meshes: IM,
        vertices: IV,
    ) -> Result<Model, BadData> {
        let mut meshes = meshes
            .into_iter()
            .map(|mesh| mesh.into())
            .collect::<Vec<_>>();
        let vertices = vertices.into_iter().collect::<Vec<_>>();
        let mut indices = vec![];

        // Add index data to the meshes (and build a buffer)
        let mut base_vertex = 0;
        for mesh in &mut meshes {
            let base_idx = indices.len();
            let mut cache: Vec<Vertex> = vec![];
            let vertex_count = mesh.vertex_count() as usize;

            // First we index the vertices ...
            for idx in base_vertex..base_vertex + vertex_count {
                let vertex = if let Some(vertex) = vertices.get(idx) {
                    (*vertex).into()
                } else {
                    return Err(BadData);
                };

                debug_assert!(vertex.is_finite());

                if let Err(idx) = cache.binary_search_by(|probe| probe.cmp(&vertex)) {
                    cache.insert(idx, vertex);
                }
            }

            // ... and then we push all the indices into the buffer
            for idx in base_vertex..base_vertex + vertex_count {
                let vertex = vertices.get(idx).unwrap();
                let vertex = (*vertex).into();
                let idx = cache.binary_search_by(|probe| probe.cmp(&vertex)).unwrap();
                indices.push(idx as _);
            }

            mesh.indices = base_idx as u32..(base_idx + indices.len()) as u32;
            base_vertex += vertex_count;
        }

        self.load_indexed_model(
            #[cfg(feature = "debug-names")]
            name,
            meshes,
            indices,
            vertices,
        )
    }

    // TODO: Finish this bit!
    /// Reads the `Animation` with the given id from the pak.
    pub fn read_animation<R: Read + Seek>(
        &self,
        #[cfg(debug_assertions)] _name: &str,
        _pak: &mut Pak<R>,
        _id: AnimationId,
    ) -> ModelRef {
        //let _pool = PoolRef::clone(&self.pool);
        //let _anim = pak.read_animation(id);
        // let indices = model.indices();
        // let index_buf_len = indices.len() as _;
        // let mut index_buf = pool.borrow_mut().data_usage(
        //     #[cfg(debug_assertions)]
        //     name,
        //     index_buf_len,
        //     Usage::INDEX,
        // );

        // {
        //     let mut mapped_range = index_buf.map_range_mut(0..index_buf_len).unwrap();
        //     mapped_range.copy_from_slice(&indices);
        //     Mapping::flush(&mut mapped_range).unwrap();
        // }

        // let vertices = model.vertices();
        // let vertex_buf_len = vertices.len() as _;
        // let mut vertex_buf = pool.borrow_mut().data_usage(
        //     #[cfg(debug_assertions)]
        //     name,
        //     vertex_buf_len,
        //     Usage::VERTEX,
        // );

        // {
        //     let mut mapped_range = vertex_buf.map_range_mut(0..vertex_buf_len).unwrap();
        //     mapped_range.copy_from_slice(&vertices);
        //     Mapping::flush(&mut mapped_range).unwrap();
        // }

        // let model = Model::new(
        //     model.meshes().map(Clone::clone).collect(),
        //     index_buf,
        //     vertex_buf,
        // );

        // ModelRef::new(model)
        todo!()
    }

    /// Reads the `Bitmap` with the given key from the pak.
    pub fn read_bitmap<K: AsRef<str>, R: Read + Seek>(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        pak: &mut Pak<R>,
        key: K,
    ) -> Bitmap {
        let id = pak.bitmap_id(key).unwrap();

        self.read_bitmap_with_id(
            #[cfg(feature = "debug-names")]
            name,
            pak,
            id,
        )
    }

    /// Reads the `Bitmap` with the given id from the pak.
    pub fn read_bitmap_with_id<R: Read + Seek>(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        pak: &mut Pak<R>,
        id: BitmapId,
    ) -> Bitmap {
        let bitmap = pak.read_bitmap(id);
        let mut pool = self.loads.borrow_mut();

        unsafe {
            BitmapOp::new(
                #[cfg(feature = "debug-names")]
                name,
                &self.driver,
                &mut pool,
                &bitmap,
            )
            .record()
        }
    }

    /// Reads the `Font` with the given face from the pak.
    ///
    /// Only bitmapped fonts are supported.
    pub fn read_font<F: AsRef<str>, R: Read + Seek>(&self, pak: &mut Pak<R>, face: F) -> Font {
        #[cfg(debug_assertions)]
        debug!("Loading font `{}`", face.as_ref());

        Font::load(
            &self.driver,
            &mut self.loads.borrow_mut(),
            pak,
            face.as_ref(),
        )
    }

    /// Reads the `Model` with the given key from the pak.
    pub fn read_model<K: AsRef<str>, R: Read + Seek>(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        pak: &mut Pak<R>,
        key: K,
    ) -> Model {
        let id = pak.model_id(key).unwrap();

        self.read_model_with_id(
            #[cfg(feature = "debug-names")]
            name,
            pak,
            id,
        )
    }

    /// Reads the `Model` with the given id from the pak.
    pub fn read_model_with_id<R: Read + Seek>(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        pak: &mut Pak<R>,
        id: ModelId,
    ) -> Model {
        let mut pool = self.loads.borrow_mut();
        let model = pak.read_model(id);

        // Create an index buffer
        let (idx_buf, idx_buf_len) = {
            let src = model.indices();
            let len = src.len() as _;
            let mut buf = pool.data_usage(
                #[cfg(feature = "debug-names")]
                name,
                &self.driver,
                len,
                Usage::INDEX | Usage::STORAGE,
            );

            // Fill the index buffer
            {
                let mut mapped_range = buf.map_range_mut(0..len).unwrap();
                mapped_range.copy_from_slice(src);
                Mapping::flush(&mut mapped_range).unwrap();
            }

            (buf, len)
        };

        // Create a staging buffer (holds vertices before we calculate additional vertex attributes)
        let (staging_buf, staging_buf_len) = {
            let src = model.vertices();
            let len = src.len() as _;
            let mut buf = pool.data_usage(
                #[cfg(feature = "debug-names")]
                name,
                &self.driver,
                len,
                Usage::STORAGE,
            );

            // Fill the staging buffer
            {
                let mut mapped_range = buf.map_range_mut(0..len).unwrap();
                mapped_range.copy_from_slice(src);
                Mapping::flush(&mut mapped_range).unwrap();
            }

            (buf, len)
        };

        // The write mask is the used during vertex attribute calculation
        let write_mask = {
            let src = model.write_mask();
            let len = src.len() as _;
            let mut buf = pool.data_usage(
                #[cfg(feature = "debug-names")]
                name,
                &self.driver,
                len,
                Usage::STORAGE,
            );

            // Fill the write mask buffer
            {
                let mut mapped_range = buf.map_range_mut(0..len).unwrap();
                mapped_range.copy_from_slice(src);
                Mapping::flush(&mut mapped_range).unwrap();
            }

            buf
        };

        let idx_ty = model.idx_ty();
        let mut meshes = model.take_meshes();
        let mut vertex_buf_len = 0;
        for mesh in &mut meshes {
            let stride = if mesh.is_animated() { 80 } else { 48 };

            // We pad each mesh in the vertex buffer so that drawing is easier (no vertex
            // re-binds; but this requires that all vertices in the buffer have a compatible
            // alignment. Because we have static (12 floats/48 bytes) and animated (20 floats/
            // 80 bytes) vertices, we round up to 60 floats/240 bytes. This means any possible
            // boundary we try to draw at will start at some multiple of either the static
            // or animated vertices.
            vertex_buf_len += vertex_buf_len % 240;
            mesh.set_base_vertex((vertex_buf_len / stride) as _);

            // Account for the vertices, updating the base vertex
            vertex_buf_len += mesh.vertex_count() as u64 * stride;
        }

        // This is the real vertex buffer which will hold the calculated attributes
        let vertex_buf = pool.data_usage(
            #[cfg(feature = "debug-names")]
            name,
            &self.driver,
            vertex_buf_len,
            Usage::STORAGE | Usage::VERTEX,
        );

        Model::new(
            meshes,
            idx_ty,
            (idx_buf, idx_buf_len),
            (vertex_buf, vertex_buf_len),
            (staging_buf, staging_buf_len, write_mask),
        )
    }

    /// Constructs a `Render` of the given dimensions.
    ///
    /// _NOTE:_ This function uses an internal cache.
    ///
    /// ## Examples:
    ///
    /// ```
    /// use screen_13::prelude_all::*;
    ///
    /// struct Foo;
    ///
    /// impl Screen for Foo {
    ///     fn render(&self, gpu: &Gpu, dims: Extent) -> Render {
    ///         let frame = gpu.render(dims);
    ///
    ///         ...
    ///     }
    ///
    ///     ...
    /// }
    pub fn render<D: Into<Extent>>(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        dims: D,
    ) -> Render {
        self.render_with_cache(
            #[cfg(feature = "debug-names")]
            name,
            dims,
            &self.renders,
        )
    }

    /// Constructs a `Render` of the given dimensions, using the provided cache.
    ///
    /// ## Examples:
    ///
    /// ```
    /// use screen_13::prelude_all::*;
    ///
    /// #[derive(Default)]
    /// struct Foo(Cache);
    ///
    /// impl Screen for Foo {
    ///     fn render(&self, gpu: &Gpu, dims: Extent) -> Render {
    ///         let cache = &self.0;
    ///         let frame = gpu.render(dims, cache);
    ///
    ///         ...
    ///     }
    ///
    ///     ...
    /// }
    pub fn render_with_cache<D: Into<Extent>>(
        &self,
        #[cfg(feature = "debug-names")] name: &str,
        dims: D,
        cache: &Cache,
    ) -> Render {
        // There may be pending operations from a previously resolved render; if so
        // we just stick them into the next render that goes out the door.
        let ops = if let Some(ops) = self.ops.borrow_mut().take() {
            ops
        } else {
            Default::default()
        };

        // Pull a rendering pool from the cache or we create and lease a new one
        let pool = if let Some(pool) = cache.0.borrow_mut().pop_back() {
            pool
        } else {
            debug!("Creating new render pool");
            Default::default()
        };
        let pool = Lease::new(pool, &cache.0);

        Render::new(
            #[cfg(feature = "debug-names")]
            name,
            &self.driver,
            dims.into(),
            pool,
            ops,
        )
    }

    /// Resolves a render into a texture which can be written to other renders.
    pub fn resolve(&self, render: Render) -> Lease<Texture2d> {
        let (target, ops) = render.resolve();
        let mut cache = self.ops.borrow_mut();
        if let Some(cache) = cache.as_mut() {
            cache.extend(ops);
        } else {
            cache.replace(ops);
        }

        target
    }

    pub(crate) fn wait_idle(&self) {
        #[cfg(debug_assertions)]
        let started = Instant::now();

        // We are required to wait for the GPU to finish what we submitted before dropping the driver
        self.driver.borrow().wait_idle().unwrap();

        #[cfg(debug_assertions)]
        {
            let elapsed = Instant::now() - started;
            debug!(
                "Wait for GPU idle took {}ms",
                elapsed.as_millis().to_formatted_string(&Locale::en)
            );
        }
    }
}

impl Drop for Gpu {
    fn drop(&mut self) {
        self.wait_idle();
    }
}

/// Masking is the process of modifying a target image alpha channel using a series of
/// blend-like operations.
///
/// TODO: This feature isn't fully implemented yet
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MaskMode {
    /// Mask formula: a + b
    Add,

    /// Mask formula: min(a, b)
    Darken,

    /// Mask formula: abs(a - b)
    Difference,

    /// Mask formula: a * b
    Intersect,

    /// Mask formula: max(a, b)
    Lighten,

    /// Mask formula: a - b
    Subtract,
}

impl Default for MaskMode {
    fn default() -> Self {
        Self::Add
    }
}

/// Matting blends two images (a into b) based on the features of a matte image.
///
/// TODO: This feature isn't fully implemented yet
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MatteMode {
    /// Matte formula: alpha = min(a, matte)
    ///                color = a * alpha;
    Alpha,

    /// Matte formula: alpha = min(a, 1 - matte)
    ///                color = a * alpha;
    AlphaInverted,

    /// Matte formula: gray = hsl-based gray function
    ///                alpha = min(a, gray(matte))
    ///                color = a * alpha;
    Luminance,

    /// Matte formula: gray = hsl-based gray function
    ///                alpha = min(a, 1 - gray(matte))
    ///                color = a * alpha;
    LuminanceInverted,
}

impl Default for MatteMode {
    fn default() -> Self {
        Self::Alpha
    }
}