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
mod data;

/// Definitions of all of the GFX-HAL layouts and pipelines this engine uses.
mod def;

/// A collection of smart-pointer types used internally to operate the GFX-HAL API.
mod driver;

mod model;

/// A collection of operation implementations used to fulfill the Render API.
mod op;

/// A collection of resource pool types used internally to cache GFX-HAL types.
mod pool;

mod render;
mod spirv {
    include!(concat!(env!("OUT_DIR"), "/spirv/mod.rs"));
}
mod swapchain;
mod texture;

pub use self::{
    model::{MeshFilter, Model, Pose, Vertex},
    op::{Bitmap, Draw, Font, Material, Skydome, Write, WriteMode},
    pool::Pool,
    render::Render,
    swapchain::Swapchain,
    texture::Texture,
};

pub(crate) use self::{driver::Driver, op::Op};

use {
    self::{
        data::{Data, Mapping},
        driver::{Device, Image2d, Surface},
        op::BitmapOp,
        pool::{Lease, PoolRef},
    },
    crate::{
        error::Error,
        math::Extent,
        pak::{model::Mesh, AnimationId, 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>;

pub type BitmapRef = Rc<Bitmap>;
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;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum BlendMode {
    Add,
    AlphaAdd,
    ColorBurn,
    ColorDodge,
    Color,
    Darken,
    DarkerColor,
    Difference,
    Divide,
    Exclusion,
    HardLight,
    HardMix,
    LinearBurn,
    Multiply,
    Normal,
    Overlay,
    Screen,
    Subtract,
    VividLight,
}

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

/// Helpful GPU cache; only required if multiple renders happen per frame and they have very different contents.
///
/// Remark: If you drop this the program will stutter, so it is best to wait a few frames before dropping it.
#[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: This is a useful function, but things you end up rendering with it cannot be used with the window's presentation
    // surface. Maybe change the way this whole thing works. Or document better?
    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(),
        }
    }

    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),
        ))
    }

    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,
        )
    }

    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!()
    }

    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,
        )
    }

    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()
        }
    }

    /// 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(),
        )
    }

    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,
        )
    }

    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),
        )
    }

    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,
        )
    }

    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();
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MaskMode {
    Add,
    Darken,
    Difference,
    Intersect,
    Lighten,
    Subtract,
}

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

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MatteMode {
    Alpha,
    AlphaInverted,
    Luminance,
    LuminanceInverted,
}

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