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
use {
    super::Op,
    crate::gpu::{
        driver::{CommandPool, Device, Driver, Fence},
        pool::{Lease, Pool},
        Data, Texture2d,
    },
    gfx_hal::{
        command::{BufferImageCopy, CommandBuffer, CommandBufferFlags, Level},
        format::Aspects,
        image::{Access as ImageAccess, Layout, Offset, SubresourceLayers},
        pool::CommandPool as _,
        pso::PipelineStage,
        queue::{CommandQueue as _, Submission},
        Backend,
    },
    gfx_impl::Backend as _Backend,
    image::{save_buffer, ColorType},
    std::{
        any::Any,
        io::Result as IoResult,
        iter::{empty, once},
        path::{Path, PathBuf},
    },
};

const DEFAULT_QUALITY: f32 = 0.9;

// TODO: Quality isn't hooked up!

/// A container of graphics types which allow the recording of encode operations and the saving
/// of renders to disk as regular image files.
pub struct EncodeOp {
    buf: Lease<Data>,
    cmd_buf: <_Backend as Backend>::CommandBuffer,
    cmd_pool: Lease<CommandPool>,
    driver: Driver,
    fence: Lease<Fence>,
    pool: Option<Lease<Pool>>,
    path: Option<PathBuf>,
    quality: f32,
    texture: Texture2d,
}

impl EncodeOp {
    #[must_use]
    pub(crate) fn new(
        #[cfg(feature = "debug-names")] name: &str,
        driver: &Driver,
        mut pool: Lease<Pool>,
        texture: &Texture2d,
    ) -> Self {
        let len = Self::byte_len(&texture);
        let buf = pool.data(
            #[cfg(feature = "debug-names")]
            name,
            &driver,
            len as _,
        );

        let family = Device::queue_family(&driver.borrow());
        let mut cmd_pool = pool.cmd_pool(&driver, family);

        Self {
            buf,
            cmd_buf: unsafe { cmd_pool.allocate_one(Level::Primary) },
            cmd_pool,
            driver: Driver::clone(driver),
            fence: pool.fence(
                #[cfg(feature = "debug-names")]
                name,
                &driver,
            ),
            pool: Some(pool),
            path: None,
            quality: DEFAULT_QUALITY,
            texture: Texture2d::clone(texture),
        }
    }

    // TODO: This is non-functional, hook it up!
    /// Sets the quality to encode with.
    #[must_use]
    pub fn with_quality(&mut self, quality: f32) -> &mut Self {
        self.quality = quality;
        self
    }

    fn byte_len(texture: &Texture2d) -> usize {
        let dims = texture.borrow().dims();
        (dims.x * dims.y * 4) as _
    }

    /// Waits for the hardware to finish processing all images, returning an error if something
    /// went wrong.
    ///
    /// _NOTE:_ The program will panic if there is an error while flushing _and_ you have not
    /// manually called the `flush` function. The `flush` function is calle automatically when
    /// an `EncodeOp` is dropped.
    pub fn flush(&mut self) -> IoResult<()> {
        // We only do this once
        if let Some(path) = self.path.take() {
            self.wait();
            let dims = self.texture.borrow().dims();
            let len = EncodeOp::byte_len(&self.texture);
            let buf = self.buf.map_range(0..len as _).unwrap(); // TODO: Error handling!

            // Encode the 32bpp RGBA source data into a JPEG
            save_buffer(path, &buf, dims.x, dims.y, ColorType::Rgba8).unwrap();
        }

        Ok(())
    }

    /// Submits the given encode for hardware processing.
    pub fn record<P: AsRef<Path>>(&mut self, path: P) {
        self.path = Some(path.as_ref().to_path_buf());

        unsafe {
            self.submit();
        };
    }

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

        let mut device = self.driver.borrow_mut();
        let len = Self::byte_len(&self.texture);
        let buf = &mut *self.buf;
        let mut texture = self.texture.borrow_mut();
        let dims = texture.dims();

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

        // Step 1: Copy the image to our temporary buffer (all on the GPU)
        texture.set_layout(
            &mut self.cmd_buf,
            Layout::TransferSrcOptimal,
            PipelineStage::TRANSFER,
            ImageAccess::TRANSFER_READ,
        );
        self.cmd_buf.copy_image_to_buffer(
            &texture.as_ref(),
            Layout::TransferSrcOptimal,
            buf.as_ref(),
            &[BufferImageCopy {
                buffer_offset: 0,
                buffer_width: dims.x,
                buffer_height: dims.y,
                image_layers: SubresourceLayers {
                    aspects: Aspects::COLOR,
                    level: 0,
                    layers: 0..1,
                },
                image_offset: Offset::ZERO,
                image_extent: dims.as_extent_depth(1),
            }],
        );

        // Step 2: Copy our GPU buffer down to the CPU
        buf.read_range(&mut self.cmd_buf, 0..len as _);

        // Finish
        self.cmd_buf.finish();

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

impl Drop for EncodeOp {
    fn drop(&mut self) {
        // If you don't manually call flush errors will be ignored
        self.flush().unwrap_or_default();
    }
}

impl Op for EncodeOp {
    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);
    }
}