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
use {
    crate::{
        graphics::vulkan::{
            raii, AcquireImageStatus, PresentImageStatus, Swapchain,
            VulkanContext,
        },
        trace,
    },
    anyhow::{Context, Result},
    ash::vk,
    std::sync::Arc,
};

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum FrameStatus {
    /// Indicates that the frame is started.
    ///
    /// The command buffer is still owned by the FramesInFlight and does not
    /// need to be freed by the caller.
    FrameStarted(Frame),

    /// Indicates that the swapchain needs to be rebuilt.
    SwapchainNeedsRebuild,
}

/// A Frame is guaranteed to be synchronized such that no two frames with the
/// same frame_index can be in-flight on the GPU at the same time.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Frame {
    command_buffer: vk::CommandBuffer,
    swapchain_image_index: u32,
    frame_index: usize,
    swapchain_image: vk::Image,
}

impl Frame {
    pub fn command_buffer(&self) -> vk::CommandBuffer {
        self.command_buffer
    }

    pub fn swapchain_image_index(&self) -> u32 {
        self.swapchain_image_index
    }

    pub fn frame_index(&self) -> usize {
        self.frame_index
    }

    pub fn swapchain_image(&self) -> vk::Image {
        self.swapchain_image
    }
}

/// Per-frame synchronization primitives.
#[derive(Debug)]
struct FrameSync {
    swapchain_image_acquired: raii::Semaphore,
    color_attachment_written: raii::Semaphore,
    graphics_commands_complete: raii::Fence,
    command_pool: raii::CommandPool,
    command_buffer: vk::CommandBuffer,
}

/// The primary synchronization mechanism for managing multiple in-flight
/// frames.
///
/// There can be 1-N frames in flight for the application, decided at the time
/// of construction. This is independent from the number of swapchain images,
/// though there is little-to-no benefit to having more frames in flight than
/// swapchain images.
///
/// Synchronization is performed such that when [Self::start_frame] returns, all
/// commands submitted to that frame are guaranteed to be complete. Thus, the
/// application can keep N copies of a resource and use the frame_index to
/// prevent synchronization errors.
#[derive(Debug)]
pub struct FramesInFlight {
    frames: Vec<FrameSync>,
    frame_index: usize,
    cxt: Arc<VulkanContext>,
}

impl FramesInFlight {
    /// Creates a new instance with `frame_count` frames.
    pub fn new(cxt: Arc<VulkanContext>, frame_count: usize) -> Result<Self> {
        let mut frames = Vec::with_capacity(frame_count);
        for index in 0..frame_count {
            let command_pool = raii::CommandPool::new(
                cxt.device.clone(),
                &vk::CommandPoolCreateInfo {
                    flags: vk::CommandPoolCreateFlags::TRANSIENT,
                    queue_family_index: cxt.graphics_queue_family_index,
                    ..Default::default()
                },
            )
            .with_context(trace!(
                "Error while creating command pool for frame {}",
                index
            ))?;
            let command_buffer = unsafe {
                cxt.allocate_command_buffers(&vk::CommandBufferAllocateInfo {
                    command_pool: command_pool.raw,
                    level: vk::CommandBufferLevel::PRIMARY,
                    command_buffer_count: 1,
                    ..Default::default()
                })?[0]
            };
            frames.push(FrameSync {
                swapchain_image_acquired: raii::Semaphore::new(
                    cxt.device.clone(),
                    &vk::SemaphoreCreateInfo::default(),
                )
                .with_context(trace!(
                    "Error while creating semaphore for frame {}",
                    index
                ))?,
                color_attachment_written: raii::Semaphore::new(
                    cxt.device.clone(),
                    &vk::SemaphoreCreateInfo::default(),
                )
                .with_context(trace!(
                    "Error while creating semaphore for frame {}",
                    index
                ))?,
                graphics_commands_complete: raii::Fence::new(
                    cxt.device.clone(),
                    &vk::FenceCreateInfo {
                        flags: vk::FenceCreateFlags::SIGNALED,
                        ..Default::default()
                    },
                )
                .with_context(trace!(
                    "Error creating fence for frame {}",
                    index
                ))?,
                command_pool,
                command_buffer,
            });
        }
        Ok(Self {
            frames,
            frame_index: 0,
            cxt,
        })
    }

    /// Get the total number of configured frames in flight.
    pub fn frame_count(&self) -> usize {
        self.frames.len()
    }

    /// Blocks until all submitted commands for all frames have completed.
    pub fn wait_for_all_frames_to_complete(&self) -> Result<()> {
        let fences = self
            .frames
            .iter()
            .map(|frame_sync| frame_sync.graphics_commands_complete.raw)
            .collect::<Vec<vk::Fence>>();
        unsafe {
            self.cxt
                .wait_for_fences(&fences, true, u64::MAX)
                .with_context(trace!(
                    "Error while waiting for all frames to finish rendering!"
                ))?;
        }
        Ok(())
    }

    /// Starts the next frame in flight.
    ///
    /// This method *can* block if all frames are in flight. It will block until
    /// the next frame is available.
    ///
    /// # Returns
    ///
    /// A [FrameStatus] containing one of:
    /// * A [Frame] that must be returned to [Self::present_frame]
    /// * A flag indicating that the Swapchain needs to be rebuilt before the
    ///   next frame.
    pub fn start_frame(
        &mut self,
        swapchain: &Swapchain,
    ) -> Result<FrameStatus> {
        self.frame_index = (self.frame_index + 1) % self.frames.len();

        // Start the Frame
        let frame_sync = &self.frames[self.frame_index];
        unsafe {
            // Wait for the last frame's submission to complete, if its still
            // running.
            self.cxt
                .wait_for_fences(
                    &[frame_sync.graphics_commands_complete.raw],
                    true,
                    u64::MAX,
                )
                .with_context(trace!(
                    "Error while waiting for frame's commands to complete!"
                ))?;
            self.cxt
                .reset_fences(&[frame_sync.graphics_commands_complete.raw])
                .with_context(trace!(
                    "Error while resetting the frame's fence!"
                ))?;
        };

        // Acquire the next Swapchain image
        let status = swapchain
            .acquire_image(frame_sync.swapchain_image_acquired.raw)
            .with_context(trace!(
                "Error while acquiring swapchain image for frame!"
            ))?;
        let swapchain_image_index = match status {
            AcquireImageStatus::ImageAcquired(index) => index,
            _ => {
                return Ok(FrameStatus::SwapchainNeedsRebuild);
            }
        };

        // Start the Frame's command buffer.
        unsafe {
            self.cxt
                .reset_command_pool(
                    frame_sync.command_pool.raw,
                    vk::CommandPoolResetFlags::empty(),
                )
                .with_context(trace!(
                    "Error while resetting command buffer for frame!"
                ))?;
            self.cxt
                .begin_command_buffer(
                    frame_sync.command_buffer,
                    &vk::CommandBufferBeginInfo {
                        flags: vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT,
                        ..Default::default()
                    },
                )
                .with_context(trace!(
                    "Error while beginning the frame's command buffer!"
                ))?;
        };

        Ok(FrameStatus::FrameStarted(Frame {
            command_buffer: frame_sync.command_buffer,
            swapchain_image_index,
            frame_index: self.frame_index,
            swapchain_image: swapchain.images()[swapchain_image_index as usize],
        }))
    }

    /// Queues the [Frame]'s command buffer and swapchain presentation.
    pub fn present_frame(
        &mut self,
        swapchain: &Swapchain,
        frame: Frame,
    ) -> Result<PresentImageStatus> {
        let frame_sync = &self.frames[frame.frame_index()];
        unsafe {
            self.cxt
                .end_command_buffer(frame_sync.command_buffer)
                .with_context(trace!(
                    "Error while ending the command buffer!"
                ))?;

            let wait_stage = vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT;
            self.cxt
                .queue_submit(
                    self.cxt.graphics_queue,
                    &[vk::SubmitInfo {
                        wait_semaphore_count: 1,
                        p_wait_semaphores: &frame_sync
                            .swapchain_image_acquired
                            .raw,
                        p_wait_dst_stage_mask: &wait_stage,
                        command_buffer_count: 1,
                        p_command_buffers: &frame_sync.command_buffer,
                        signal_semaphore_count: 1,
                        p_signal_semaphores: &frame_sync
                            .color_attachment_written
                            .raw,
                        ..Default::default()
                    }],
                    frame_sync.graphics_commands_complete.raw,
                )
                .with_context(trace!(
                    "Error while submitting frame commands!"
                ))?;
        }

        swapchain
            .present_image(
                frame_sync.color_attachment_written.raw,
                frame.swapchain_image_index(),
            )
            .with_context(trace!("Error while presenting swapchain image!"))
    }
}

impl Drop for FramesInFlight {
    fn drop(&mut self) {
        self.wait_for_all_frames_to_complete().unwrap();
        unsafe {
            self.cxt.device_wait_idle().unwrap();
        }
    }
}