Skip to main content

oa/runtime/
presentation.rs

1//! SDL3-created Vulkan surface retained by the public Presenter session.
2
3use super::device::NativeFlagBits;
4use std::sync::Arc;
5
6use std::marker::PhantomData;
7
8use crate::{Error, Result, runtime::SdlWindow};
9
10use super::{
11	Device,
12	device::logical::swapchain::{PresentationSwapchain, SwapchainConfig},
13};
14pub use crate::runtime::types::PresentationCapabilities;
15
16pub struct PresentationSurface<'window> {
17	_device: Arc<Device>,
18	handle: vk::SurfaceKHR,
19	graphics_present_supported: bool,
20	prefer_transparent: bool,
21	/// The queue-family index that can present to this surface.
22	/// May differ from the graphics queue family on some devices.
23	present_queue_family: Option<u32>,
24	_window: PhantomData<&'window SdlWindow>,
25}
26
27impl<'window> PresentationSurface<'window> {
28	pub(in crate::runtime) fn validate_ui_runtime(
29		&self,
30		runtime: &super::RuntimeHandle,
31	) -> Result<()> {
32		runtime.validate_ui_presentation(&self._device)
33	}
34
35	pub(in crate::runtime) fn create(
36		device: &Arc<Device>,
37		window: &'window SdlWindow,
38	) -> Result<Self> {
39		let instance = device.instance();
40		// SAFETY: the SDL window and Vulkan instance are retained by the two
41		// lifetimes carried by this object; SDL received the required extensions.
42		// SDL's surface factory takes the raw VkInstance handle.
43		let handle = unsafe {
44			window
45				.window
46				.vulkan_create_surface(instance.raw().handle().0.cast())
47		}
48		.map_err(|source| Error::backend_failure("SDL3", "Vulkan surface creation", source))?;
49		let handle = vk::SurfaceKHR(handle as u64);
50
51		// Determine whether the graphics queue family can present to this surface.
52		// If it cannot, search all queue families for one that can.
53		let physical = device.physical();
54		let graphics_family = physical.graphics_queue_family;
55		let graphics_present_supported = graphics_family
56			.map(|family| surface_support(instance.raw(), physical.handle, family, handle))
57			.transpose()
58			.map_err(|source| Error::backend_failure("Vulkan", "surface present-support query", source))?
59			.unwrap_or(false);
60
61		// Find a dedicated present family when the graphics family cannot present.
62		// Enumerate all queue families and pick the first that supports presenting
63		// to this surface (including the graphics family itself as a fallback).
64		let present_queue_family = if graphics_present_supported {
65			graphics_family
66		} else {
67			let queue_families = unsafe {
68				instance
69					.raw()
70					.get_physical_device_queue_family_properties(physical.handle)
71			}
72			.map_err(|source| Error::backend_failure("Vulkan", "queue-family property query", source))?;
73			let mut found = None;
74			for (index, _props) in queue_families.iter().enumerate() {
75				let supported =
76					surface_support(instance.raw(), physical.handle, index as u32, handle).unwrap_or(false);
77				if supported {
78					found = Some(index as u32);
79					break;
80				}
81			}
82			found
83		};
84
85		Ok(Self {
86			_device: device.clone(),
87			handle,
88			graphics_present_supported,
89			prefer_transparent: window.window.window_flags().0
90				& sdl3::sys::video::SDL_WINDOW_TRANSPARENT.0
91				!= 0,
92			present_queue_family,
93			_window: PhantomData,
94		})
95	}
96
97	/// Return the queue-family index that can present to this surface, if known.
98	pub(in crate::runtime) fn present_queue_family(&self) -> Option<u32> {
99		self.present_queue_family
100	}
101
102	pub const fn graphics_present_supported(&self) -> bool {
103		self.graphics_present_supported
104	}
105
106	pub(in crate::runtime) fn has_graphics(&self) -> bool {
107		self._device.has_graphics_queue()
108	}
109
110	pub(in crate::runtime) fn supports_swapchain(&self) -> bool {
111		self._device.supports_swapchain()
112	}
113
114	pub fn capabilities(&self) -> Result<PresentationCapabilities> {
115		let (raw, formats, modes) = self.raw_capabilities()?;
116		Ok(PresentationCapabilities {
117			min_image_count: raw.min_image_count,
118			max_image_count: (raw.max_image_count != 0).then_some(raw.max_image_count),
119			current_extent: (raw.current_extent.width != u32::MAX)
120				.then_some([raw.current_extent.width, raw.current_extent.height]),
121			min_extent: [raw.min_image_extent.width, raw.min_image_extent.height],
122			max_extent: [raw.max_image_extent.width, raw.max_image_extent.height],
123			format_count: formats.len(),
124			present_mode_count: modes.len(),
125			supports_color_attachment: raw
126				.supported_usage_flags
127				.contains(vk::ImageUsageFlagBits::COLOR_ATTACHMENT_BIT),
128			supports_transfer_dst: raw
129				.supported_usage_flags
130				.contains(vk::ImageUsageFlagBits::TRANSFER_DST_BIT),
131		})
132	}
133
134	/// Select the valid swapchain extent for one SDL drawable-pixel extent.
135	///
136	/// `None` means the window is minimized and callers must defer allocation or
137	/// acquisition until SDL reports a non-zero drawable extent.
138	pub fn swapchain_extent(&self, drawable_extent: [u32; 2]) -> Result<Option<[u32; 2]>> {
139		let (raw, _, _) = self.raw_capabilities()?;
140		if raw.current_extent.width != u32::MAX {
141			return Ok(Some([raw.current_extent.width, raw.current_extent.height]));
142		}
143		if drawable_extent.contains(&0) {
144			return Ok(None);
145		}
146		Ok(Some([
147			drawable_extent[0].clamp(raw.min_image_extent.width, raw.max_image_extent.width),
148			drawable_extent[1].clamp(raw.min_image_extent.height, raw.max_image_extent.height),
149		]))
150	}
151
152	pub(in crate::runtime) fn swapchain_config(
153		&self,
154		drawable_extent: [u32; 2],
155	) -> Result<Option<SwapchainConfig>> {
156		let (raw, formats, modes) = self.raw_capabilities()?;
157		let extent = if raw.current_extent.width != u32::MAX {
158			vk::Extent2D::new()
159				.set_width(raw.current_extent.width)
160				.set_height(raw.current_extent.height)
161		} else {
162			if drawable_extent.contains(&0) {
163				return Ok(None);
164			}
165			vk::Extent2D::new()
166				.set_width(drawable_extent[0].clamp(raw.min_image_extent.width, raw.max_image_extent.width))
167				.set_height(
168					drawable_extent[1].clamp(raw.min_image_extent.height, raw.max_image_extent.height),
169				)
170		};
171		// Donor: oa/runtime/runtime/presenter.cpp::recreateSwapchain.
172		// Texture/UI pixels are already sRGB-encoded RGBA8. A blit into an
173		// *_SRGB image would apply the transfer function again (128 → ~188).
174		// UNORM preserves encoded values; SRGB_NONLINEAR tells WSI how to
175		// display them. Storage format and presentation color space differ.
176		let format = formats
177			.iter()
178			.copied()
179			.map(|mut format| {
180				// The legacy single-UNDEFINED offer allows application selection.
181				if formats.len() == 1 && format.format == vk::Format::UNDEFINED {
182					format.format = vk::Format::B8G8R8A8_UNORM;
183				}
184				format
185			})
186			.find(|format| {
187				matches!(
188					format.format,
189					vk::Format::B8G8R8A8_UNORM | vk::Format::R8G8B8A8_UNORM
190				)
191					&& format.color_space == vk::ColorSpaceKHR::SRGB_NONLINEAR_KHR
192			})
193			.ok_or_else(|| {
194				Error::missing_capability(
195					"encoded RGBA8 presentation requires an RGBA8/BGRA8 UNORM surface with sRGB nonlinear color space; other formats need an explicit color-conversion path",
196				)
197			})?;
198		if !modes.contains(&vk::PresentModeKHR::FIFO_KHR) {
199			return Err(Error::missing_capability(
200				"surface does not expose mandatory FIFO presentation",
201			));
202		}
203		if !raw.supported_usage_flags.contains(
204			vk::ImageUsageFlagBits::COLOR_ATTACHMENT_BIT | vk::ImageUsageFlagBits::TRANSFER_DST_BIT,
205		) {
206			return Err(Error::missing_capability(
207				"surface swapchain images do not support color-attachment and transfer-destination usage",
208			));
209		}
210		let source_features = vk::FormatFeatureFlagBits::BLIT_SRC_BIT
211			| vk::FormatFeatureFlagBits::SAMPLED_IMAGE_FILTER_LINEAR_BIT;
212		if !self
213			._device
214			.optimal_format_supports(vk::Format::R8G8B8A8_UNORM, source_features)
215		{
216			return Err(Error::missing_capability(
217				"R8G8B8A8_UNORM images do not support linear-filtered blit sources",
218			));
219		}
220		if !self
221			._device
222			.optimal_format_supports(format.format, vk::FormatFeatureFlagBits::BLIT_DST_BIT)
223		{
224			return Err(Error::missing_capability(format!(
225				"selected swapchain format {:?} does not support blit destinations",
226				format.format
227			)));
228		}
229		// Donor Presenter: request premultiplied alpha only for a transparent
230		// SDL client frame; ordinary windows keep the opaque-first policy.
231		let preferred = if self.prefer_transparent {
232			vk::CompositeAlphaFlagBitsKHR::PRE_MULTIPLIED_BIT_KHR
233		} else {
234			vk::CompositeAlphaFlagBitsKHR::OPAQUE_BIT_KHR
235		};
236		let composite_alpha = [
237			preferred,
238			vk::CompositeAlphaFlagBitsKHR::OPAQUE_BIT_KHR,
239			vk::CompositeAlphaFlagBitsKHR::PRE_MULTIPLIED_BIT_KHR,
240			vk::CompositeAlphaFlagBitsKHR::POST_MULTIPLIED_BIT_KHR,
241			vk::CompositeAlphaFlagBitsKHR::INHERIT_BIT_KHR,
242		]
243		.into_iter()
244		.find(|candidate| (raw.supported_composite_alpha & *candidate) == *candidate)
245		.ok_or_else(|| Error::missing_capability("surface exposes no composite-alpha mode"))?;
246		let image_count = raw
247			.min_image_count
248			.saturating_add(1)
249			.min(if raw.max_image_count == 0 {
250				u32::MAX
251			} else {
252				raw.max_image_count
253			});
254		Ok(Some(SwapchainConfig {
255			extent,
256			image_count,
257			format,
258			present_mode: vk::PresentModeKHR::FIFO_KHR,
259			composite_alpha,
260			transparent: self.prefer_transparent
261				&& composite_alpha == vk::CompositeAlphaFlagBitsKHR::PRE_MULTIPLIED_BIT_KHR,
262			pre_transform: raw.current_transform,
263		}))
264	}
265
266	pub(in crate::runtime) fn create_swapchain(
267		&self,
268		drawable_extent: [u32; 2],
269	) -> Result<Option<PresentationSwapchain>> {
270		// Require a present-capable queue (may differ from the graphics family).
271		if self.present_queue_family.is_none() || !self.supports_swapchain() {
272			return Err(Error::missing_capability(
273				"selected device cannot create a presentation swapchain",
274			));
275		}
276		let Some(config) = self.swapchain_config(drawable_extent)? else {
277			return Ok(None);
278		};
279		PresentationSwapchain::create(
280			&self._device,
281			self.handle,
282			self.present_queue_family,
283			config,
284		)
285		.map(Some)
286	}
287
288	fn raw_capabilities(
289		&self,
290	) -> Result<(
291		vk::SurfaceCapabilitiesKHR,
292		Vec<vk::SurfaceFormatKHR>,
293		Vec<vk::PresentModeKHR>,
294	)> {
295		let physical = self._device.physical();
296		let instance = self._device.instance().raw();
297		let mut raw = vk::SurfaceCapabilitiesKHR::new();
298		// SAFETY: the retained instance owns both device and surface.
299		match unsafe {
300			instance.get_physical_device_surface_capabilities_khr(physical.handle, self.handle, &mut raw)
301		} {
302			Ok(vk::Result::SUCCESS) => {}
303			other => {
304				return Err(Error::backend_dispatch_failure(
305					"Vulkan",
306					"surface-capability query",
307					other,
308				));
309			}
310		}
311		let formats = surface_formats(instance, physical.handle, self.handle)
312			.map_err(|source| Error::backend_failure("Vulkan", "surface-format query", source))?;
313		let modes = surface_present_modes(instance, physical.handle, self.handle)
314			.map_err(|source| Error::backend_failure("Vulkan", "surface present-mode query", source))?;
315		Ok((raw, formats, modes))
316	}
317}
318
319impl Drop for PresentationSurface<'_> {
320	fn drop(&mut self) {
321		// SAFETY: this object uniquely owns the SDL-created surface and retains its instance.
322		unsafe {
323			let _ = self
324				._device
325				.instance()
326				.raw()
327				.destroy_surface_khr(self.handle, std::ptr::null());
328		}
329	}
330}
331
332fn surface_support(
333	instance: &vk::Instance,
334	physical: vk::PhysicalDevice,
335	family: u32,
336	surface: vk::SurfaceKHR,
337) -> Result<bool> {
338	let mut supported = 0_u32;
339	// SAFETY: `supported` is a writable Bool32 out-param.
340	unsafe {
341		instance.get_physical_device_surface_support_khr(physical, family, surface, &mut supported)
342	}
343	.map(|_| supported != vk::FALSE)
344	.map_err(|source| Error::backend_failure("Vulkan", "surface present-support query", source))
345}
346
347fn surface_formats(
348	instance: &vk::Instance,
349	physical: vk::PhysicalDevice,
350	surface: vk::SurfaceKHR,
351) -> Result<Vec<vk::SurfaceFormatKHR>> {
352	let mut count = 0_u32;
353	// SAFETY: null output pointer requests only the element count.
354	match unsafe {
355		instance.get_physical_device_surface_formats_khr(
356			physical,
357			surface,
358			&mut count,
359			std::ptr::null_mut(),
360		)
361	} {
362		Ok(vk::Result::SUCCESS) => {}
363		other => {
364			return Err(Error::backend_dispatch_failure(
365				"Vulkan",
366				"surface-format count",
367				other,
368			));
369		}
370	}
371	let mut formats = vec![vk::SurfaceFormatKHR::new(); count as usize];
372	// SAFETY: `formats` provides `count` writable records.
373	match unsafe {
374		instance.get_physical_device_surface_formats_khr(
375			physical,
376			surface,
377			&mut count,
378			formats.as_mut_ptr(),
379		)
380	} {
381		Ok(vk::Result::SUCCESS) => {
382			formats.truncate(count as usize);
383			Ok(formats)
384		}
385		other => Err(Error::backend_dispatch_failure(
386			"Vulkan",
387			"surface-format query",
388			other,
389		)),
390	}
391}
392
393fn surface_present_modes(
394	instance: &vk::Instance,
395	physical: vk::PhysicalDevice,
396	surface: vk::SurfaceKHR,
397) -> Result<Vec<vk::PresentModeKHR>> {
398	let mut count = 0_u32;
399	// SAFETY: null output pointer requests only the element count.
400	match unsafe {
401		instance.get_physical_device_surface_present_modes_khr(
402			physical,
403			surface,
404			&mut count,
405			std::ptr::null_mut(),
406		)
407	} {
408		Ok(vk::Result::SUCCESS) => {}
409		other => {
410			return Err(Error::backend_dispatch_failure(
411				"Vulkan",
412				"present-mode count",
413				other,
414			));
415		}
416	}
417	let mut modes = vec![vk::PresentModeKHR::default(); count as usize];
418	// SAFETY: `modes` provides `count` writable records.
419	match unsafe {
420		instance.get_physical_device_surface_present_modes_khr(
421			physical,
422			surface,
423			&mut count,
424			modes.as_mut_ptr(),
425		)
426	} {
427		Ok(vk::Result::SUCCESS) => {
428			modes.truncate(count as usize);
429			Ok(modes)
430		}
431		other => Err(Error::backend_dispatch_failure(
432			"Vulkan",
433			"present-mode query",
434			other,
435		)),
436	}
437}