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
use {
    super::Op,
    crate::{
        color::TRANSPARENT_BLACK,
        gpu::{
            def::{
                push_const::WritePushConsts, ColorRenderPassMode, Graphics, GraphicsMode,
                RenderPassMode,
            },
            driver::{
                bind_graphics_descriptor_set, CommandPool, Device, Driver, Fence, Framebuffer2d,
            },
            pool::{Lease, Pool},
            BlendMode, Texture2d,
        },
        math::{vec3, Area, CoordF, Mat4, RectF, Vec2},
    },
    gfx_hal::{
        command::{CommandBuffer as _, CommandBufferFlags, ImageCopy, Level, SubpassContents},
        device::Device as _,
        format::Aspects,
        image::{Access, Layout, Offset, SubresourceLayers, Usage},
        pool::CommandPool as _,
        pso::{Descriptor, DescriptorSetWrite, PipelineStage, ShaderStageFlags, Viewport},
        queue::{CommandQueue as _, Submission},
        Backend,
    },
    gfx_impl::Backend as _Backend,
    std::{
        any::Any,
        iter::{empty, once},
        u8,
    },
};

const SUBPASS_IDX: u8 = 0;

/// Describes the way `WriteOp` will write a given texture onto the destination texture.
#[derive(Clone, Copy, Hash, PartialEq)]
pub enum Mode {
    /// Blends source (a) with destination (b) using the given mode.
    Blend((u8, BlendMode)),

    /// Writes source directly onto destination, with no blending.
    Texture,
}

/// An expressive type which allows specification of individual texture writes. Texture writes may either specify the
/// entire source texture or a tile sub-portion. Tiles are always specified using integer texel coordinates.
pub struct Write<'s> {
    src: &'s Texture2d,
    src_region: Area,
    transform: Mat4,
}

// TODO: Add multi-sampled builder function
impl<'s> Write<'s> {
    /// Writes the whole source texture to the destination at the given position.
    pub fn position<D: Into<CoordF>>(src: &'s Texture2d, dst: D) -> Self {
        Self::tile_position(src, src.borrow().dims().into(), dst)
    }

    /// Writes the whole source texture to the destination at the given rectangle.
    pub fn region<D: Into<RectF>>(src: &'s Texture2d, dst: D) -> Self {
        Self::tile_region(src, src.borrow().dims().into(), dst)
    }

    /// Writes a tile area of the source texture to the destination at the given position.
    pub fn tile_position<D: Into<CoordF>>(src: &'s Texture2d, src_tile: Area, dst: D) -> Self {
        Self::tile_region(
            src,
            src_tile,
            RectF {
                dims: src.borrow().dims().into(),
                pos: dst.into(),
            },
        )
    }

    /// Writes a tile area of the source texture to the destination at the given rectangle.
    pub fn tile_region<D: Into<RectF>>(src: &'s Texture2d, src_tile: Area, dst: D) -> Self {
        let dst = dst.into();
        let src_dims: CoordF = src.borrow().dims().into();
        let dst_transform = Mat4::from_translation(vec3(-1.0, -1.0, 0.0))
            * Mat4::from_scale(vec3(
                dst.dims.x * 2.0 / src_dims.x,
                dst.dims.y * 2.0 / src_dims.y,
                1.0,
            ))
            * Mat4::from_translation(vec3(dst.pos.x / dst.dims.x, dst.pos.y / dst.dims.y, 0.0));

        Self::tile_transform(src, src_tile, dst_transform)
    }

    /// Writes a tile area of the source texture to the destination using the given transformation matrix.
    pub fn tile_transform(src: &'s Texture2d, src_tile: Area, dst: Mat4) -> Self {
        Self {
            src,
            src_region: src_tile,
            transform: dst,
        }
    }

    /// Writes the whole source texture to the destination using the given transformation matrix.
    pub fn transform(src: &'s Texture2d, dst: Mat4) -> Self {
        Self::tile_transform(src, src.borrow().dims().into(), dst)
    }
}

/// Writes an iterator of source textures onto a destination texture, using optional modes.
///
/// `WriteOp` is intended to provide high speed image splatting for tile maps, bitmap drawing,
/// filtered image stretching, _etc..._ Although generic 3D transforms are offered, the main
/// use of this operation is 2D image composition.
///
/// _NOTE:_ When no image filtering or resizing is required the `CopyOp` may provide higher
/// performance. TODO: We can specialize for this so the API is the same, round the edge.
///
/// ## Examples
///
/// Writing a nine-sliced UI graphic:
///
/// ```
/// use screen_13::prelude_all::*;
///
/// ...
///
/// fn render_ui() {
///     // We've already sliced up a UI box image (🔪 top left, 🔪 top, 🔪 top right, ...)
///     let slices: [BitmapRef; 9] = ...
///     let render: &Render = ...
///
///     render.write().
///         .with_mode(WriteMode::Blend(0x7f, BlendMode::ColorDodge))
///         .with_preserve()
///         .record(&mut [
///             // top left
///             Write::tile_position(&slices[0], Area::new(0, 0, 32, 32), Coord::new(0, 0)),
///
///             // top
///             Write::tile_position(&slices[1], Area::new(32, 0, 384, 32), Coord::new(32, 0)),
///
///             // top right
///             Write::tile_position(&slices[2], Area::new(426, 0, 32, 32), Coord::new(426, 0)),
///
///             ...
///         ]);
/// }
/// ```
pub struct WriteOp {
    back_buf: Lease<Texture2d>,
    cmd_buf: <_Backend as Backend>::CommandBuffer,
    cmd_pool: Lease<CommandPool>,
    driver: Driver,
    dst: Texture2d,
    dst_preserve: bool,
    fence: Lease<Fence>,
    frame_buf: Option<Framebuffer2d>,
    graphics: Option<Lease<Graphics>>,
    mode: Mode,

    #[cfg(feature = "debug-names")]
    name: String,

    pool: Option<Lease<Pool>>,
    src_textures: Vec<Texture2d>,
}

impl WriteOp {
    #[must_use]
    pub(crate) fn new(
        #[cfg(feature = "debug-names")] name: &str,
        driver: &Driver,
        mut pool: Lease<Pool>,
        dst: &Texture2d,
    ) -> Self {
        let family = Device::queue_family(&driver.borrow());
        let mut cmd_pool = pool.cmd_pool(driver, family);
        let (dims, fmt) = {
            let dst = dst.borrow();
            (dst.dims(), dst.format())
        };
        let fence = pool.fence(
            #[cfg(feature = "debug-names")]
            name,
            driver,
        );

        Self {
            back_buf: pool.texture(
                #[cfg(feature = "debug-names")]
                &format!("{} backbuffer", name),
                driver,
                dims,
                fmt,
                Layout::Undefined,
                Usage::COLOR_ATTACHMENT | Usage::INPUT_ATTACHMENT,
                1,
                1,
                1,
            ),
            cmd_buf: unsafe { cmd_pool.allocate_one(Level::Primary) },
            cmd_pool,
            driver: Driver::clone(driver),
            dst: Texture2d::clone(dst),
            dst_preserve: false,
            fence,
            frame_buf: None,
            graphics: None,
            mode: Mode::Texture,
            #[cfg(feature = "debug-names")]
            name: name.to_owned(),
            pool: Some(pool),
            src_textures: Default::default(),
        }
    }

    /// Sets the current write mode.
    #[must_use]
    pub fn with_mode(&mut self, mode: Mode) -> &mut Self {
        self.mode = mode;
        self
    }

    /// Preserves the contents of the destination texture. Without calling this function the
    /// existing contents of the destination texture will not be composited into the final result.
    #[must_use]
    pub fn with_preserve(&mut self) -> &mut Self {
        self.with_preserve_is(true)
    }

    /// Sets whether the destination texture will be composited into the final result or not.
    #[must_use]
    pub fn with_preserve_is(&mut self, val: bool) -> &mut Self {
        self.dst_preserve = val;
        self
    }

    /// Submits the given writes for hardware processing.
    pub fn record(&mut self, writes: &mut [Write]) {
        assert!(self.src_textures.is_empty());
        assert_ne!(writes.len(), 0);

        if writes.len() > 1 {
            // Keeps track of the textures used while the GPU is still busy (so our caller can drop their references)
            for write in writes.iter() {
                let write_src_ptr = Texture2d::as_ptr(&write.src);
                if let Err(idx) = self.src_textures.binary_search_by(|probe| {
                    let probe = Texture2d::as_ptr(probe);
                    probe.cmp(&write_src_ptr)
                }) {
                    self.src_textures.insert(idx, Texture2d::clone(write.src));
                }
            }

            // Sort the writes by texture so that we minimize the number of descriptor sets and how often we change sets during submit
            // NOTE: Unstable sort because we don't claim to support ordering or blending of the individual writes within each batch
            writes.sort_unstable_by(|lhs, rhs| {
                let lhs = Texture2d::as_ptr(&lhs.src);
                let rhs = Texture2d::as_ptr(&rhs.src);
                lhs.cmp(&rhs)
            });
        } else {
            // We only have one write - and the above sort logic would not be called (there would be no right-hand-side!)
            self.src_textures.push(Texture2d::clone(writes[0].src));
        }

        let render_pass_mode = RenderPassMode::Color(ColorRenderPassMode {
            fmt: self.dst.borrow().format(),
            preserve: self.dst_preserve,
        });

        // Final setup bits
        {
            let pool = self.pool.as_mut().unwrap();
            let render_pass = pool.render_pass(&self.driver, render_pass_mode);

            // Setup the framebuffer
            self.frame_buf.replace(Framebuffer2d::new(
                #[cfg(feature = "debug-names")]
                self.name.as_str(),
                &self.driver,
                render_pass,
                once(self.back_buf.borrow().as_default_view().as_ref()),
                self.dst.borrow().dims(),
            ));

            // Setup the graphics pipeline(s) using one descriptor set per unique source texture
            let graphics_mode = match self.mode {
                Mode::Blend((_, mode)) => GraphicsMode::Blend(mode),
                Mode::Texture => GraphicsMode::Texture,
            };
            self.graphics.replace(pool.graphics_desc_sets(
                #[cfg(feature = "debug-names")]
                &self.name,
                &self.driver,
                render_pass_mode,
                SUBPASS_IDX,
                graphics_mode,
                self.src_textures.len(),
            ));
        }

        unsafe {
            self.write_descriptors();
            self.submit_begin(render_pass_mode);

            let mut set_idx = 0;
            for write in writes.iter() {
                self.submit_write(write, &mut set_idx);
            }

            self.submit_finish();
        }
    }

    unsafe fn submit_begin(&mut self, render_pass_mode: RenderPassMode) {
        trace!("submit_begin");

        let pool = self.pool.as_mut().unwrap();
        let render_pass = pool.render_pass(&self.driver, render_pass_mode);
        let mut back_buf = self.back_buf.borrow_mut();
        let mut dst = self.dst.borrow_mut();
        let graphics = self.graphics.as_ref().unwrap();
        let dims = dst.dims();
        let rect = dims.into();
        let viewport = Viewport {
            rect,
            depth: 0.0..1.0,
        };

        // Begin
        self.cmd_buf
            .begin_primary(CommandBufferFlags::ONE_TIME_SUBMIT);

        // Optional step: Fill dst into the backbuffer in order to preserve it in the output
        if self.dst_preserve {
            dst.set_layout(
                &mut self.cmd_buf,
                Layout::TransferSrcOptimal,
                PipelineStage::TRANSFER,
                Access::TRANSFER_READ,
            );
            back_buf.set_layout(
                &mut self.cmd_buf,
                Layout::TransferDstOptimal,
                PipelineStage::TRANSFER,
                Access::TRANSFER_WRITE,
            );
            self.cmd_buf.copy_image(
                dst.as_ref(),
                Layout::TransferSrcOptimal,
                back_buf.as_ref(),
                Layout::TransferDstOptimal,
                once(ImageCopy {
                    src_subresource: SubresourceLayers {
                        aspects: Aspects::COLOR,
                        level: 0,
                        layers: 0..1,
                    },
                    src_offset: Offset::ZERO,
                    dst_subresource: SubresourceLayers {
                        aspects: Aspects::COLOR,
                        level: 0,
                        layers: 0..1,
                    },
                    dst_offset: Offset::ZERO,
                    extent: dims.as_extent_depth(1),
                }),
            );
            dst.set_layout(
                &mut self.cmd_buf,
                Layout::ShaderReadOnlyOptimal,
                PipelineStage::FRAGMENT_SHADER,
                Access::SHADER_READ,
            );
        }

        // Step 1: Write src into the backbuffer, but blending using our shader `mode`
        back_buf.set_layout(
            &mut self.cmd_buf,
            Layout::ColorAttachmentOptimal,
            PipelineStage::COLOR_ATTACHMENT_OUTPUT,
            Access::COLOR_ATTACHMENT_WRITE,
        );
        // src.set_layout(
        //     &mut self.cmd_buf,
        //     Layout::ShaderReadOnlyOptimal,
        //     PipelineStage::FRAGMENT_SHADER,
        //     Access::SHADER_READ,
        // );
        self.cmd_buf.begin_render_pass(
            render_pass,
            self.frame_buf.as_ref().unwrap(),
            rect,
            &[TRANSPARENT_BLACK.into()],
            SubpassContents::Inline,
        );
        self.cmd_buf.bind_graphics_pipeline(graphics.pipeline());
        self.cmd_buf.set_scissors(0, &[rect]);
        self.cmd_buf.set_viewports(0, &[viewport]);
        bind_graphics_descriptor_set(&mut self.cmd_buf, graphics.layout(), graphics.desc_set(0));
    }

    unsafe fn submit_write(&mut self, write: &Write, set_idx: &mut usize) {
        trace!("submit_write");

        let graphics = self.graphics.as_ref().unwrap();
        let layout = graphics.layout();

        // If this write (writes are sorted identically to `self.src_textures` except the writes have more items) is a different
        // texture we will need to switch to the next descriptor set - this won't happen on the first write of course.
        if !Texture2d::ptr_eq(write.src, &self.src_textures[*set_idx]) {
            *set_idx += 1;
            bind_graphics_descriptor_set(&mut self.cmd_buf, layout, graphics.desc_set(*set_idx));
        }

        let offset = Vec2::zero();
        let scale = Vec2::one();
        self.cmd_buf.push_graphics_constants(
            graphics.layout(),
            ShaderStageFlags::VERTEX,
            0,
            WritePushConsts {
                offset,
                scale,
                transform: write.transform,
            }
            .as_ref(),
        );

        if let Mode::Blend((ab, _)) = self.mode {
            let ab = ab as f32 / u8::MAX as f32;
            let inv = 1.0 - ab;
            self.cmd_buf.push_graphics_constants(
                graphics.layout(),
                ShaderStageFlags::FRAGMENT,
                WritePushConsts::BYTE_LEN,
                &[ab.to_bits(), inv.to_bits()],
            );
        }

        self.cmd_buf.draw(0..6, 0..1);
    }

    unsafe fn submit_finish(&mut self) {
        trace!("submit_finish");

        let mut device = self.driver.borrow_mut();
        let mut back_buf = self.back_buf.borrow_mut();
        let mut dst = self.dst.borrow_mut();
        let dims = dst.dims();

        // End of the previous step...
        self.cmd_buf.end_render_pass();

        // Step 2: Copy the now-composited backbuffer to the `dst` texture
        back_buf.set_layout(
            &mut self.cmd_buf,
            Layout::TransferSrcOptimal,
            PipelineStage::TRANSFER,
            Access::TRANSFER_READ,
        );
        dst.set_layout(
            &mut self.cmd_buf,
            Layout::TransferDstOptimal,
            PipelineStage::TRANSFER,
            Access::TRANSFER_WRITE,
        );
        self.cmd_buf.copy_image(
            back_buf.as_ref(),
            Layout::TransferSrcOptimal,
            dst.as_ref(),
            Layout::TransferDstOptimal,
            once(ImageCopy {
                src_subresource: SubresourceLayers {
                    aspects: Aspects::COLOR,
                    level: 0,
                    layers: 0..1,
                },
                src_offset: Offset::ZERO,
                dst_subresource: SubresourceLayers {
                    aspects: Aspects::COLOR,
                    level: 0,
                    layers: 0..1,
                },
                dst_offset: Offset::ZERO,
                extent: dims.as_extent_depth(1),
            }),
        );

        // Finish
        self.cmd_buf.finish();

        Device::queue_mut(&mut device).submit(
            Submission {
                command_buffers: once(&self.cmd_buf),
                wait_semaphores: empty(),
                signal_semaphores: empty::<&<_Backend as Backend>::Semaphore>(),
            },
            Some(&self.fence),
        );
    }

    unsafe fn write_descriptors(&mut self) {
        trace!("write_descriptors");

        let dst = self.dst.borrow();
        let dst_view = dst.as_default_view();
        let graphics = self.graphics.as_ref().unwrap();
        let sampler = graphics.sampler(0).as_ref();

        // Each source texture requres a unique descriptor set
        for (idx, src) in self.src_textures.iter().enumerate() {
            let set = graphics.desc_set(idx);

            // A descriptor for this source texture
            let src_ref = src.borrow();
            let src_view = src_ref.as_default_view();
            let src_desc = DescriptorSetWrite {
                set,
                binding: 0,
                array_offset: 0,
                descriptors: once(Descriptor::CombinedImageSampler(
                    &**src_view,
                    Layout::ShaderReadOnlyOptimal,
                    sampler,
                )),
            };

            // Blend mode requires a descriptor for the destination texture
            if let Mode::Blend(_) = self.mode {
                let dst_desc = DescriptorSetWrite {
                    set,
                    binding: 1,
                    array_offset: 0,
                    descriptors: once(Descriptor::CombinedImageSampler(
                        &**dst_view,
                        Layout::ShaderReadOnlyOptimal,
                        sampler,
                    )),
                };
                // TODO: Borrow in a loop? Can these be lifted?
                self.driver
                    .borrow_mut()
                    .write_descriptor_sets(vec![src_desc, dst_desc]); // TODO: Slice/Tuple?
            } else {
                self.driver
                    .borrow_mut()
                    .write_descriptor_sets(once(src_desc));
            }
        }
    }
}

impl Drop for WriteOp {
    fn drop(&mut self) {
        self.wait();
    }
}

impl Op for WriteOp {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn take_pool(&mut self) -> Option<Lease<Pool>> {
        self.pool.take()
    }

    fn wait(&self) {
        Fence::wait(&self.fence);
    }
}