Files
ab_glyph_rasterizer
addr2line
adler
andrew
approx
arrayvec
ash
atom
backtrace
bitflags
byteorder
calloop
cfg_if
colorful
conrod_core
conrod_derive
conrod_example_shared
conrod_gfx
conrod_glium
conrod_piston
conrod_rendy
conrod_vulkano
conrod_wgpu
conrod_winit
copyless
copypasta
crossbeam
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
daggy
dlib
downcast_rs
draw_state
either
fixedbitset
float
fnv
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
fxhash
getrandom
gfx
gfx_backend_empty
gfx_backend_vulkan
gfx_core
gfx_descriptor
gfx_hal
gfx_memory
gimli
glium
glutin
glutin_egl_sys
glutin_glx_sys
graphics
half
hibitset
inplace_it
input
instant
interpolation
iovec
itoa
lazy_static
lazycell
libc
libloading
line_drawing
linked_hash_map
lock_api
log
maybe_uninit
memchr
memmap
memoffset
miniz_oxide
mio
mio_extras
naga
net2
nix
nom
num
num_bigint
num_complex
num_cpus
num_integer
num_iter
num_rational
num_traits
object
once_cell
ordered_float
ordermap
osmesa_sys
owned_ttf_parser
parking_lot
parking_lot_core
percent_encoding
petgraph
pin_project
pin_project_internal
pin_project_lite
pin_utils
ppv_lite86
proc_macro2
proc_macro_hack
proc_macro_nested
quote
rand
rand_chacha
rand_core
raw_window_handle
read_color
relevant
rendy
rendy_chain
rendy_command
rendy_core
rendy_descriptor
rendy_factory
rendy_frame
rendy_graph
rendy_init
rendy_memory
rendy_mesh
rendy_resource
rendy_shader
rendy_texture
rendy_wsi
rustc_demangle
rustc_hash
rusttype
ryu
same_file
scoped_tls
scopeguard
serde
serde_derive
serde_json
shaderc
shaderc_sys
shared_library
slab
smallvec
smithay_client_toolkit
smithay_clipboard
spirv_headers
stb_truetype
syn
takeable_option
texture
thiserror
thiserror_impl
thread_profiler
time
tracing
tracing_core
ttf_parser
typed_arena
unicode_xid
vecmath
viewport
vk_sys
void
vulkano
buffer
command_buffer
descriptor
device
framebuffer
image
instance
memory
pipeline
query
swapchain
sync
vulkano_shaders
walkdir
wayland_client
wayland_commons
wayland_cursor
wayland_egl
wayland_protocols
wayland_sys
wgpu
wgpu_core
wgpu_types
winit
x11
x11_clipboard
x11_dl
xcb
xcursor
xdg
xml
  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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*! Swap chain management.

    ## Lifecycle

    At the low level, the swap chain is using the new simplified model of gfx-rs.

    A swap chain is a separate object that is backend-dependent but shares the index with
    the parent surface, which is backend-independent. This ensures a 1:1 correspondence
    between them.

    `get_next_image()` requests a new image from the surface. It becomes a part of
    `TextureViewInner::SwapChain` of the resulted view. The view is registered in the HUB
    but not in the device tracker.

    The only operation allowed on the view is to be either a color or a resolve attachment.
    It can only be used in one command buffer, which needs to be submitted before presenting.
    Command buffer tracker knows about the view, but only for the duration of recording.
    The view ID is erased from it at the end, so that it's not merged into the device tracker.

    When a swapchain view is used in `begin_render_pass()`, we assume the start and end image
    layouts purely based on whether or not this view was used in this command buffer before.
    It always starts with `Uninitialized` and ends with `Present`, so that no barriers are
    needed when we need to actually present it.

    In `queue_submit()` we make sure to signal the semaphore whenever we render to a swap
    chain view.

    In `present()` we return the swap chain image back and wait on the semaphore.
!*/

#[cfg(feature = "trace")]
use crate::device::trace::Action;
use crate::{
    conv,
    device::DeviceError,
    hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token},
    id::{DeviceId, SwapChainId, TextureViewId, Valid},
    resource, span,
    track::TextureSelector,
    LifeGuard, PrivateFeatures, Stored, SubmissionIndex,
};

use hal::{self, device::Device as _, queue::CommandQueue as _, window::PresentationSurface as _};
use thiserror::Error;
use wgt::{SwapChainDescriptor, SwapChainStatus};

const FRAME_TIMEOUT_MS: u64 = 1000;
pub const DESIRED_NUM_FRAMES: u32 = 3;

#[derive(Debug)]
pub struct SwapChain<B: hal::Backend> {
    pub(crate) life_guard: LifeGuard,
    pub(crate) device_id: Stored<DeviceId>,
    pub(crate) desc: SwapChainDescriptor,
    pub(crate) num_frames: hal::window::SwapImageIndex,
    pub(crate) semaphore: B::Semaphore,
    pub(crate) acquired_view_id: Option<Stored<TextureViewId>>,
    pub(crate) acquired_framebuffers: Vec<B::Framebuffer>,
    pub(crate) active_submission_index: SubmissionIndex,
}

#[derive(Clone, Debug, Error)]
pub enum SwapChainError {
    #[error("swap chain is invalid")]
    Invalid,
    #[error("parent surface is invalid")]
    InvalidSurface,
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error("swap chain image is already acquired")]
    AlreadyAcquired,
}

#[derive(Clone, Debug, Error)]
pub enum CreateSwapChainError {
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error("invalid surface")]
    InvalidSurface,
    #[error("`SwapChainOutput` must be dropped before a new `SwapChain` is made")]
    SwapChainOutputExists,
    #[error("surface does not support the adapter's queue family")]
    UnsupportedQueueFamily,
    #[error("requested format {requested:?} is not in list of supported formats: {available:?}")]
    UnsupportedFormat {
        requested: hal::format::Format,
        available: Vec<hal::format::Format>,
    },
}

pub(crate) fn swap_chain_descriptor_to_hal(
    desc: &SwapChainDescriptor,
    num_frames: u32,
    private_features: PrivateFeatures,
) -> hal::window::SwapchainConfig {
    let mut config = hal::window::SwapchainConfig::new(
        desc.width,
        desc.height,
        conv::map_texture_format(desc.format, private_features),
        num_frames,
    );
    //TODO: check for supported
    config.image_usage = conv::map_texture_usage(desc.usage, hal::format::Aspects::COLOR);
    config.composite_alpha_mode = hal::window::CompositeAlphaMode::OPAQUE;
    config.present_mode = match desc.present_mode {
        wgt::PresentMode::Immediate => hal::window::PresentMode::IMMEDIATE,
        wgt::PresentMode::Mailbox => hal::window::PresentMode::MAILBOX,
        wgt::PresentMode::Fifo => hal::window::PresentMode::FIFO,
    };
    config
}

#[repr(C)]
#[derive(Debug)]
pub struct SwapChainOutput {
    pub status: SwapChainStatus,
    pub view_id: Option<TextureViewId>,
}

#[error("swap chain is invalid")]
#[derive(Clone, Debug, Error)]
pub struct InvalidSwapChain;

impl<G: GlobalIdentityHandlerFactory> Global<G> {
    pub fn swap_chain_get_preferred_format<B: GfxBackend>(
        &self,
        _swap_chain_id: SwapChainId,
    ) -> Result<wgt::TextureFormat, InvalidSwapChain> {
        span!(_guard, INFO, "SwapChain::get_next_texture");
        //TODO: we can query the formats like done in `device_create_swapchain`,
        // but its not clear which format in the list to return.
        // For now, return `Bgra8UnormSrgb` that we know is supported everywhere.
        Ok(wgt::TextureFormat::Bgra8UnormSrgb)
    }

    pub fn swap_chain_get_current_texture_view<B: GfxBackend>(
        &self,
        swap_chain_id: SwapChainId,
        view_id_in: Input<G, TextureViewId>,
    ) -> Result<SwapChainOutput, SwapChainError> {
        span!(_guard, INFO, "SwapChain::get_next_texture");

        let hub = B::hub(self);
        let mut token = Token::root();

        let (mut surface_guard, mut token) = self.surfaces.write(&mut token);
        let surface = surface_guard
            .get_mut(swap_chain_id.to_surface_id())
            .map_err(|_| SwapChainError::InvalidSurface)?;
        let (device_guard, mut token) = hub.devices.read(&mut token);
        let (mut swap_chain_guard, mut token) = hub.swap_chains.write(&mut token);
        let sc = swap_chain_guard
            .get_mut(swap_chain_id)
            .map_err(|_| SwapChainError::Invalid)?;
        #[cfg_attr(not(feature = "trace"), allow(unused_variables))]
        let device = &device_guard[sc.device_id.value];

        let suf = B::get_surface_mut(surface);
        let (image, status) = match unsafe { suf.acquire_image(FRAME_TIMEOUT_MS * 1_000_000) } {
            Ok((surface_image, None)) => (Some(surface_image), SwapChainStatus::Good),
            Ok((surface_image, Some(_))) => (Some(surface_image), SwapChainStatus::Suboptimal),
            Err(err) => (
                None,
                match err {
                    hal::window::AcquireError::OutOfMemory(_) => Err(DeviceError::OutOfMemory)?,
                    hal::window::AcquireError::NotReady => unreachable!(), // we always set a timeout
                    hal::window::AcquireError::Timeout => SwapChainStatus::Timeout,
                    hal::window::AcquireError::OutOfDate => SwapChainStatus::Outdated,
                    hal::window::AcquireError::SurfaceLost(_) => SwapChainStatus::Lost,
                    hal::window::AcquireError::DeviceLost(_) => Err(DeviceError::Lost)?,
                },
            ),
        };

        let view_id = match image {
            Some(image) => {
                let view = resource::TextureView {
                    inner: resource::TextureViewInner::SwapChain {
                        image,
                        source_id: Stored {
                            value: Valid(swap_chain_id),
                            ref_count: sc.life_guard.add_ref(),
                        },
                    },
                    aspects: hal::format::Aspects::COLOR,
                    format: sc.desc.format,
                    extent: hal::image::Extent {
                        width: sc.desc.width,
                        height: sc.desc.height,
                        depth: 1,
                    },
                    samples: 1,
                    selector: TextureSelector {
                        layers: 0..1,
                        levels: 0..1,
                    },
                    life_guard: LifeGuard::new(),
                };

                let ref_count = view.life_guard.add_ref();
                let id = hub
                    .texture_views
                    .register_identity(view_id_in, view, &mut token);

                if sc.acquired_view_id.is_some() {
                    return Err(SwapChainError::AlreadyAcquired);
                }

                sc.acquired_view_id = Some(Stored {
                    value: id,
                    ref_count,
                });

                Some(id.0)
            }
            None => None,
        };

        #[cfg(feature = "trace")]
        match device.trace {
            Some(ref trace) => trace.lock().add(Action::GetSwapChainTexture {
                id: view_id,
                parent_id: swap_chain_id,
            }),
            None => (),
        };

        Ok(SwapChainOutput { status, view_id })
    }

    pub fn swap_chain_present<B: GfxBackend>(
        &self,
        swap_chain_id: SwapChainId,
    ) -> Result<SwapChainStatus, SwapChainError> {
        span!(_guard, INFO, "SwapChain::present");

        let hub = B::hub(self);
        let mut token = Token::root();

        let (mut surface_guard, mut token) = self.surfaces.write(&mut token);
        let surface = surface_guard
            .get_mut(swap_chain_id.to_surface_id())
            .map_err(|_| SwapChainError::InvalidSurface)?;
        let (mut device_guard, mut token) = hub.devices.write(&mut token);
        let (mut swap_chain_guard, mut token) = hub.swap_chains.write(&mut token);
        let sc = swap_chain_guard
            .get_mut(swap_chain_id)
            .map_err(|_| SwapChainError::Invalid)?;
        let device = &mut device_guard[sc.device_id.value];

        #[cfg(feature = "trace")]
        match device.trace {
            Some(ref trace) => trace.lock().add(Action::PresentSwapChain(swap_chain_id)),
            None => (),
        };

        let view_id = sc
            .acquired_view_id
            .take()
            .ok_or(SwapChainError::AlreadyAcquired)?;
        let (view, _) = hub.texture_views.unregister(view_id.value.0, &mut token);
        let image = match view.inner {
            resource::TextureViewInner::Native { .. } => unreachable!(),
            resource::TextureViewInner::SwapChain { image, .. } => image,
        };

        let sem = if sc.active_submission_index > device.last_completed_submission_index() {
            Some(&sc.semaphore)
        } else {
            None
        };
        let queue = &mut device.queue_group.queues[0];
        let result = unsafe { queue.present(B::get_surface_mut(surface), image, sem) };

        tracing::debug!(trace = true, "Presented. End of Frame");

        for fbo in sc.acquired_framebuffers.drain(..) {
            unsafe {
                device.raw.destroy_framebuffer(fbo);
            }
        }

        match result {
            Ok(None) => Ok(SwapChainStatus::Good),
            Ok(Some(_)) => Ok(SwapChainStatus::Suboptimal),
            Err(err) => match err {
                hal::window::PresentError::OutOfMemory(_) => {
                    Err(SwapChainError::Device(DeviceError::OutOfMemory))
                }
                hal::window::PresentError::OutOfDate => Ok(SwapChainStatus::Outdated),
                hal::window::PresentError::SurfaceLost(_) => Ok(SwapChainStatus::Lost),
                hal::window::PresentError::DeviceLost(_) => {
                    Err(SwapChainError::Device(DeviceError::Lost))
                }
            },
        }
    }
}