use std::sync::Arc; use vulkano::command_buffer::allocator::StandardCommandBufferAllocator; use vulkano::device::{Device, DeviceCreateInfo, DeviceExtensions, DeviceFeatures, Queue, QueueCreateInfo, QueueFlags}; use vulkano::device::physical::PhysicalDeviceType; use vulkano::instance::{Instance, InstanceCreateFlags, InstanceCreateInfo}; use vulkano::memory::allocator::StandardMemoryAllocator; use vulkano::swapchain::{acquire_next_image, Surface, SwapchainCreateInfo, SwapchainPresentInfo}; use vulkano::{sync, Validated, Version, VulkanError, VulkanLibrary}; use vulkano::command_buffer::{AutoCommandBufferBuilder, CommandBufferUsage, RenderingAttachmentInfo, RenderingInfo}; use vulkano::render_pass::{AttachmentLoadOp, AttachmentStoreOp}; use vulkano::sync::GpuFuture; use winit::application::ApplicationHandler; use winit::event::WindowEvent; use winit::event_loop::{ActiveEventLoop, EventLoop}; use winit::window::WindowId; use crate::renderer::render_context::RenderContext; use crate::renderer::{window_size_dependent_setup, Scene}; pub struct App { instance: Arc, device: Arc, queue: Arc, memory_allocator: Arc, command_buffer_allocator: Arc, rcx: Option, scene: Option, } impl App { pub fn new(event_loop: &EventLoop<()>) -> Self { let library = VulkanLibrary::new().unwrap(); let required_extensions = Surface::required_extensions(event_loop).unwrap(); let instance = Instance::new( library, InstanceCreateInfo { // Enable enumerating devices that use non-conformant Vulkan implementations. // (e.g. MoltenVK) flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, enabled_extensions: required_extensions, enabled_layers: vec![ String::from("VK_LAYER_KHRONOS_validation"), String::from("VK_LAYER_MANGOHUD_overlay_x86_64"), String::from("VK_LAYER_NV_optimus"), ], ..Default::default() }, ) .unwrap(); let mut device_extensions = DeviceExtensions { khr_swapchain: true, ..DeviceExtensions::empty() }; let (physical_device, queue_family_index) = instance .enumerate_physical_devices() .unwrap() .filter(|p| { p.api_version() >= Version::V1_3 || p.supported_extensions().khr_dynamic_rendering }) .filter(|p| { p.supported_extensions().contains(&device_extensions) }) .filter_map(|p| { p.queue_family_properties() .iter() .enumerate() .position(|(i, q)| { q.queue_flags.intersects(QueueFlags::GRAPHICS) && p.presentation_support(i as u32, event_loop).unwrap() }) .map(|i| (p, i as u32)) }) .min_by_key(|(p, _)| { match p.properties().device_type { PhysicalDeviceType::DiscreteGpu => 0, PhysicalDeviceType::IntegratedGpu => 1, PhysicalDeviceType::VirtualGpu => 2, PhysicalDeviceType::Cpu => 3, PhysicalDeviceType::Other => 4, _ => 5, } }) .expect("no suitable physical device found"); println!( "Using device: {} (type: {:?})", physical_device.properties().device_name, physical_device.properties().device_type, ); if physical_device.api_version() < Version::V1_3 { device_extensions.khr_dynamic_rendering = true; } let (device, mut queues) = Device::new( physical_device, DeviceCreateInfo { queue_create_infos: vec![QueueCreateInfo { queue_family_index, ..Default::default() }], enabled_extensions: device_extensions, enabled_features: DeviceFeatures { dynamic_rendering: true, ..DeviceFeatures::empty() }, ..Default::default() }, ) .unwrap(); let queue = queues.next().unwrap(); let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( device.clone(), Default::default(), )); Self { instance, device, queue, memory_allocator, command_buffer_allocator, rcx: None, scene: None, } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { let window_attributes = winit::window::Window::default_attributes() .with_title("Rust ASH Test") .with_inner_size(winit::dpi::PhysicalSize::new( f64::from(800), f64::from(600), )); let window = Arc::new( event_loop .create_window(window_attributes) .unwrap(), ); let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); self.rcx = Some(RenderContext::new(window, surface, &self.device)); self.scene = Some(Scene::initialize(&self.device, &self.rcx.as_ref().unwrap().swapchain, &self.memory_allocator)); } fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) { let rcx = self.rcx.as_mut().unwrap(); match event { WindowEvent::CloseRequested => { log::debug!("The close button was pressed; stopping"); event_loop.exit(); } WindowEvent::Resized(_) => { rcx.recreate_swapchain = true; } WindowEvent::RedrawRequested => { let window_size = rcx.window.inner_size(); if window_size.width == 0 || window_size.height == 0 { return; } rcx.previous_frame_end.as_mut().unwrap().cleanup_finished(); if rcx.recreate_swapchain { let (new_swapchain, new_images) = rcx .swapchain .recreate(SwapchainCreateInfo { image_extent: window_size.into(), ..rcx.swapchain.create_info() }) .expect("failed to recreate swapchain"); rcx.swapchain = new_swapchain; rcx.attachment_image_views = window_size_dependent_setup(&new_images); rcx.viewport.extent = window_size.into(); rcx.recreate_swapchain = false; } let (image_index, suboptimal, acquire_future) = match acquire_next_image( rcx.swapchain.clone(), None, ) .map_err(Validated::unwrap) { Ok(r) => r, Err(VulkanError::OutOfDate) => { rcx.recreate_swapchain = true; return; } Err(e) => panic!("failed to acquire next image: {e}"), }; if suboptimal { rcx.recreate_swapchain = true; } let mut builder = AutoCommandBufferBuilder::primary( self.command_buffer_allocator.clone(), self.queue.queue_family_index(), CommandBufferUsage::OneTimeSubmit, ) .unwrap(); builder .begin_rendering(RenderingInfo { color_attachments: vec![Some(RenderingAttachmentInfo { load_op: AttachmentLoadOp::Clear, store_op: AttachmentStoreOp::Store, clear_value: Some([0.0, 0.0, 0.0, 1.0].into()), ..RenderingAttachmentInfo::image_view( rcx.attachment_image_views[image_index as usize].clone(), ) })], ..Default::default() }) .unwrap() .set_viewport(0, [rcx.viewport.clone()].into_iter().collect()) .unwrap(); if let Some(scene) = self.scene.as_ref() { scene.render(&mut builder); } builder .end_rendering() .unwrap(); let command_buffer = builder.build().unwrap(); let future = rcx .previous_frame_end .take() .unwrap() .join(acquire_future) .then_execute(self.queue.clone(), command_buffer) .unwrap() .then_swapchain_present( self.queue.clone(), SwapchainPresentInfo::swapchain_image_index( rcx.swapchain.clone(), image_index, ), ) .then_signal_fence_and_flush(); match future.map_err(Validated::unwrap) { Ok(future) => { rcx.previous_frame_end = Some(future.boxed()); } Err(VulkanError::OutOfDate) => { rcx.recreate_swapchain = true; rcx.previous_frame_end = Some(sync::now(self.device.clone()).boxed()); } Err(e) => { println!("failed to flush future: {e}"); rcx.previous_frame_end = Some(sync::now(self.device.clone()).boxed()); } } } _ => {} } } fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { let rcx = self.rcx.as_mut().unwrap(); rcx.window.request_redraw(); } }