Expand description
Link between Vulkan and a window and/or the screen.
Before you can draw on the screen or a window, you have to create two objects:
- Create a
Surface
object that represents the location where the image will show up (either a window or a monitor). - Create a
Swapchain
that uses thatSurface
.
Creating a surface can be done with only an Instance
object. However creating a swapchain
requires a Device
object.
Once you have a swapchain, you can retrieve Image
objects from it and draw to them just like
you would draw on any other image.
§Surfaces
A surface is an object that represents a location where to render. It can be created from an instance and either a window handle (in a platform-specific way) or a monitor.
In order to use surfaces, you will have to enable the VK_KHR_surface
extension on the
instance. See the instance
module for more information about how to enable extensions.
§Creating a surface from a window
There are 5 extensions that each allow you to create a surface from a type of window:
VK_KHR_xlib_surface
VK_KHR_xcb_surface
VK_KHR_wayland_surface
VK_KHR_android_surface
VK_KHR_win32_surface
For example if you want to create a surface from an Android surface, you will have to enable
the VK_KHR_android_surface
extension and use Surface::from_android
.
See the documentation of Surface
for all the possible constructors.
Trying to use one of these functions without enabling the proper extension will result in an error.
Note that the Surface
object is potentially unsafe. It is your responsibility to
keep the window alive for at least as long as the surface exists. In many cases Surface
may be able to do this for you, if you pass it ownership of your Window (or a
reference-counting container for it).
§Examples
use std::ptr;
use vulkano::{
instance::{Instance, InstanceCreateInfo, InstanceExtensions},
swapchain::Surface,
Version, VulkanLibrary,
};
let instance = {
let library = VulkanLibrary::new()
.unwrap_or_else(|err| panic!("Couldn't load Vulkan library: {:?}", err));
let extensions = InstanceExtensions {
khr_surface: true,
khr_win32_surface: true, // If you don't enable this, `from_hwnd` will fail.
..InstanceExtensions::empty()
};
Instance::new(
library,
InstanceCreateInfo {
enabled_extensions: extensions,
..Default::default()
},
)
.unwrap_or_else(|err| panic!("Couldn't create instance: {:?}", err))
};
let window = build_window(); // Third-party function, not provided by vulkano
let _surface = {
let hinstance: ash::vk::HINSTANCE = 0; // Windows-specific object
unsafe {
Surface::from_win32(
instance.clone(),
hinstance,
window.hwnd() as ash::vk::HWND,
Some(window),
)
}
.unwrap()
};
§Swapchains
A surface represents a location on the screen and can be created from an instance. Once you have a surface, the next step is to create a swapchain. Creating a swapchain requires a device, and allocates the resources that will be used to display images on the screen.
A swapchain is composed of one or multiple images. Each image of the swapchain is presented in turn on the screen, one after another. More information below.
Swapchains have several properties:
- The number of images that will cycle on the screen.
- The format of the images.
- The 2D dimensions of the images, plus a number of layers, for a total of three dimensions.
- The usage of the images, similar to creating other images.
- The queue families that are going to use the images, similar to creating other images.
- An additional transformation (rotation or mirroring) to perform on the final output.
- How the alpha of the final output will be interpreted.
- How to perform the cycling between images in regard to vsync.
You can query the supported values of all these properties from the physical device.
§Creating a swapchain
In order to create a swapchain, you will first have to enable the VK_KHR_swapchain
extension
on the device (and not on the instance like VK_KHR_surface
):
let ext = DeviceExtensions {
khr_swapchain: true,
..DeviceExtensions::empty()
};
Then, query the capabilities of the surface with
PhysicalDevice::surface_capabilities
and
PhysicalDevice::surface_formats
and choose which values you are going to use.
let surface_capabilities = device
.physical_device()
.surface_capabilities(&surface, Default::default())?;
// Use the current window size or some fixed resolution.
let image_extent = surface_capabilities.current_extent.unwrap_or([640, 480]);
// Try to use double-buffering.
let min_image_count = match surface_capabilities.max_image_count {
None => max(2, surface_capabilities.min_image_count),
Some(limit) => min(max(2, surface_capabilities.min_image_count), limit)
};
// Preserve the current surface transform.
let pre_transform = surface_capabilities.current_transform;
// Use the first available format.
let (image_format, color_space) = device
.physical_device()
.surface_formats(&surface, Default::default())?[0];
Then, call Swapchain::new
.
// Create the swapchain and its images.
let (swapchain, images) = Swapchain::new(
// Create the swapchain in this `device`'s memory.
device,
// The surface where the images will be presented.
surface,
// The creation parameters.
SwapchainCreateInfo {
// How many images to use in the swapchain.
min_image_count,
// The format of the images.
image_format,
// The size of each image.
image_extent,
// The created swapchain images will be used as a color attachment for rendering.
image_usage: ImageUsage::COLOR_ATTACHMENT,
// What transformation to use with the surface.
pre_transform,
// How to handle the alpha channel.
composite_alpha,
// How to present images.
present_mode,
// How to handle full-screen exclusivity
full_screen_exclusive,
..Default::default()
}
)?;
Creating a swapchain not only returns the swapchain object, but also all the images that belong to it.
§Acquiring and presenting images
Once you created a swapchain and retrieved all the images that belong to it (see previous section), you can draw on it. This is done in three steps:
- Call
swapchain::acquire_next_image
. This function will return the index of the image (within the list returned bySwapchain::new
) that is available to draw, plus a future representing the moment when the GPU will gain access to that image. - Draw on that image just like you would draw to any other image (see the documentation of the
pipeline
module). You need to chain the draw after the future that was returned byacquire_next_image
. - Call
Swapchain::present
with the same index and by chaining the futures, in order to tell the implementation that you are finished drawing to the image and that it can queue a command to present the image on the screen after the draw operations are finished.
use vulkano::swapchain::{self, SwapchainPresentInfo};
use vulkano::sync::GpuFuture;
// let mut (swapchain, images) = Swapchain::new(...);
loop {
let (image_index, suboptimal, acquire_future)
= swapchain::acquire_next_image(swapchain.clone(), None).unwrap();
// The command_buffer contains the draw commands that modify the framebuffer
// constructed from images[image_index]
acquire_future
.then_execute(queue.clone(), command_buffer)
.unwrap()
.then_swapchain_present(
queue.clone(),
SwapchainPresentInfo::swapchain_image_index(swapchain.clone(), image_index),
)
.then_signal_fence_and_flush()
.unwrap();
}
§Recreating a swapchain
In some situations, the swapchain will become invalid by itself. This includes for example when the window is resized (as the images of the swapchain will no longer match the window’s) or, on Android, when the application went to the background and goes back to the foreground.
In this situation, acquiring a swapchain image or presenting it will return an error. Rendering to an image of that swapchain will not produce any error, but may or may not work. To continue rendering, you will need to recreate the swapchain by creating a new swapchain and passing as last parameter the old swapchain.
use vulkano::{
swapchain::{self, SwapchainCreateInfo, SwapchainPresentInfo},
sync::GpuFuture,
Validated, VulkanError,
};
// let (swapchain, images) = Swapchain::new(...);
let mut recreate_swapchain = false;
loop {
if recreate_swapchain {
let (new_swapchain, new_images) = swapchain
.recreate(SwapchainCreateInfo {
image_extent: [1024, 768],
..swapchain.create_info()
})
.unwrap();
swapchain = new_swapchain;
images = new_images;
recreate_swapchain = false;
}
let (image_index, suboptimal, acq_future) =
match swapchain::acquire_next_image(swapchain.clone(), None).map_err(Validated::unwrap)
{
Ok(r) => r,
Err(VulkanError::OutOfDate) => {
recreate_swapchain = true;
continue;
}
Err(err) => panic!("{:?}", err),
};
// ...
let final_future = acq_future
// .then_execute(...)
.then_swapchain_present(
queue.clone(),
SwapchainPresentInfo::swapchain_image_index(swapchain.clone(), image_index),
)
.then_signal_fence_and_flush()
.unwrap(); // TODO: PresentError?
if suboptimal {
recreate_swapchain = true;
}
}
Structs§
- Acquire
Next Image Info - Parameters to acquire the next image from a swapchain.
- Acquired
Image - An image that will be acquired from a swapchain.
- Composite
Alphas - A set of
CompositeAlpha
values. - Display
Surface Create Info - Parameters to create a surface from a display mode and plane.
- Present
Future - Represents a swapchain image being presented on the screen.
- Present
Gravity Flags - A set of
PresentGravity
values. - Present
Info - Parameters to execute present operations on a queue.
- Present
Scaling Flags - A set of
PresentScaling
values. - Rectangle
Layer - Represents a rectangular region on an image layer.
- Semaphore
Present Info - Parameters for a semaphore wait operation in a queue present operation.
- Surface
- Represents a surface on the screen.
- Surface
Capabilities - The capabilities of a surface when used by a physical device.
- Surface
Info - Parameters for
PhysicalDevice::surface_capabilities
andPhysicalDevice::surface_formats
. - Surface
Transforms - A set of
SurfaceTransform
values. - Swapchain
- Contains the swapping system and the images that can be shown on a surface.
- Swapchain
Acquire Future - Represents the moment when the GPU will have access to a swapchain image.
- Swapchain
Create Flags - Flags specifying additional properties of a swapchain.
- Swapchain
Create Info - Parameters to create a new
Swapchain
. - Swapchain
Present Info - Parameters for a single present operation on a swapchain.
- Win32
Monitor - A wrapper around a Win32 monitor handle.
Enums§
- Color
Space - How the presentation engine should interpret the data.
- Composite
Alpha - How the alpha values of the pixels of the window are treated.
- From
Window Error - Error that can happen when creating a
Surface
from a window. - Full
Screen Exclusive - The way full-screen exclusivity is handled.
- Present
Gravity - The way a swapchain image is aligned, if it does not exactly fit the surface.
- Present
Mode - The mode of action when a swapchain image is presented.
- Present
Scaling - The way a swapchain image is scaled, if it does not exactly fit the surface.
- Surface
Api - The windowing API function that was used to construct a surface.
- Surface
Transform - The presentation transform to apply when presenting a swapchain image to a surface.
Functions§
- acquire_
next_ image - Tries to take ownership of an image in order to draw on it.
- acquire_
next_ ⚠image_ raw Deprecated - Unsafe variant of
acquire_next_image
. - present
- Presents an image on the screen.
- wait_
for_ present Deprecated - Wait for an image to be presented to the user. Must be used with a
present_id
given topresent_with_id
.