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