From 654f7f34229f70ceb878bdfa210073fd0cd0c924 Mon Sep 17 00:00:00 2001 From: marc0246 <40955683+marc0246@users.noreply.github.com> Date: Sat, 5 Oct 2024 21:48:37 +0200 Subject: [PATCH] fmt --- examples/async-update/main.rs | 889 +++++++++---------- examples/bloom/main.rs | 6 +- examples/buffer-allocator/main.rs | 472 ++++++----- examples/clear-attachments/main.rs | 303 +++---- examples/deferred/main.rs | 315 +++---- examples/gl-interop/main.rs | 889 +++++++++---------- examples/image-self-copy-blit/main.rs | 709 ++++++++-------- examples/image/main.rs | 607 ++++++------- examples/immutable-sampler/main.rs | 628 +++++++------- examples/indirect/main.rs | 624 +++++++------- examples/instancing/main.rs | 590 ++++++------- examples/interactive-fractal/main.rs | 308 +++---- examples/mesh-shader/main.rs | 567 +++++++------ examples/multi-window-game-of-life/main.rs | 24 +- examples/multi-window/main.rs | 513 +++++------ examples/occlusion-query/main.rs | 638 +++++++------- examples/push-descriptors/main.rs | 590 ++++++------- examples/runtime-array/main.rs | 824 +++++++++--------- examples/runtime-shader/main.rs | 473 ++++++----- examples/simple-particles/main.rs | 735 ++++++++-------- examples/teapot/main.rs | 478 ++++++----- examples/tessellation/main.rs | 539 ++++++------ examples/texture-array/main.rs | 624 +++++++------- examples/triangle-util/main.rs | 524 ++++++------ examples/triangle-v1_3/main.rs | 914 ++++++++++---------- examples/triangle/main.rs | 941 +++++++++++---------- 26 files changed, 7507 insertions(+), 7217 deletions(-) diff --git a/examples/async-update/main.rs b/examples/async-update/main.rs index 4b86896934..7669192c29 100644 --- a/examples/async-update/main.rs +++ b/examples/async-update/main.rs @@ -136,69 +136,69 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, graphics_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - // Since we are going to be updating the texture on a separate thread asynchronously from the - // execution of graphics commands, it would make sense to also do the transfer on a dedicated - // transfer queue, if such a queue family exists. That way, the graphics queue is not blocked - // during the transfers either and the two tasks are truly asynchronous. - // - // For this, we need to find the queue family with the fewest queue flags set, since if the - // queue family has more flags than `TRANSFER | SPARSE_BINDING`, that means it is not dedicated - // to transfer operations. - let transfer_family_index = physical_device - .queue_family_properties() - .iter() - .enumerate() - .filter(|(_, q)| { - q.queue_flags.intersects(QueueFlags::TRANSFER) - // Queue families dedicated to transfers are not required to support partial - // transfers of images, reported by a minimum granularity of [0, 0, 0]. If you need - // to do partial transfers of images like we do in this example, you therefore have + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, graphics_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + // Since we are going to be updating the texture on a separate thread asynchronously from + // the execution of graphics commands, it would make sense to also do the transfer on a + // dedicated transfer queue, if such a queue family exists. That way, the graphics queue is + // not blocked during the transfers either and the two tasks are truly asynchronous. + // + // For this, we need to find the queue family with the fewest queue flags set, since if the + // queue family has more flags than `TRANSFER | SPARSE_BINDING`, that means it is not + // dedicated to transfer operations. + let transfer_family_index = physical_device + .queue_family_properties() + .iter() + .enumerate() + .filter(|(_, q)| { + q.queue_flags.intersects(QueueFlags::TRANSFER) + // Queue families dedicated to transfers are not required to support partial + // transfers of images, reported by a minimum granularity of [0, 0, 0]. If you need + // to do partial transfers of images like we do in this example, you therefore have // to make sure the queue family supports that. && q.min_image_transfer_granularity != [0; 3] // Unlike queue families for graphics and/or compute, queue families dedicated to @@ -210,99 +210,82 @@ impl App { && q.min_image_transfer_granularity[0..2] .iter() .all(|&g| TRANSFER_GRANULARITY % g == 0) - }) - .min_by_key(|(_, q)| q.queue_flags.count()) - .unwrap() - .0 as u32; + }) + .min_by_key(|(_, q)| q.queue_flags.count()) + .unwrap() + .0 as u32; - let (device, mut queues) = { - let mut queue_create_infos = vec![QueueCreateInfo { - queue_family_index: graphics_family_index, - ..Default::default() - }]; - - // It's possible that the physical device doesn't have any queue families supporting - // transfers other than the graphics and/or compute queue family. In that case we must make - // sure we don't request the same queue family twice. - if transfer_family_index != graphics_family_index { - queue_create_infos.push(QueueCreateInfo { - queue_family_index: transfer_family_index, + let (device, mut queues) = { + let mut queue_create_infos = vec![QueueCreateInfo { + queue_family_index: graphics_family_index, ..Default::default() - }); - } else { - let queue_family_properties = - &physical_device.queue_family_properties()[graphics_family_index as usize]; - - // Even if we can't get an async transfer queue family, it's still better to use - // different queues on the same queue family. This way, at least the threads on the - // host don't have to lock the same queue when submitting. - if queue_family_properties.queue_count > 1 { - queue_create_infos[0].queues.push(0.5); + }]; + + // It's possible that the physical device doesn't have any queue families supporting + // transfers other than the graphics and/or compute queue family. In that case we must + // make sure we don't request the same queue family twice. + if transfer_family_index != graphics_family_index { + queue_create_infos.push(QueueCreateInfo { + queue_family_index: transfer_family_index, + ..Default::default() + }); + } else { + let queue_family_properties = + &physical_device.queue_family_properties()[graphics_family_index as usize]; + + // Even if we can't get an async transfer queue family, it's still better to use + // different queues on the same queue family. This way, at least the threads on the + // host don't have to lock the same queue when submitting. + if queue_family_properties.queue_count > 1 { + queue_create_infos[0].queues.push(0.5); + } } - } - Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos, - ..Default::default() - }, - ) - .unwrap() - }; + Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos, + ..Default::default() + }, + ) + .unwrap() + }; - let graphics_queue = queues.next().unwrap(); + let graphics_queue = queues.next().unwrap(); - // If we didn't get a dedicated transfer queue, fall back to the graphics queue for transfers. - let transfer_queue = queues.next().unwrap_or_else(|| graphics_queue.clone()); + // If we didn't get a dedicated transfer queue, fall back to the graphics queue for + // transfers. + let transfer_queue = queues.next().unwrap_or_else(|| graphics_queue.clone()); - println!( - "Using queue family {graphics_family_index} for graphics and queue family \ - {transfer_family_index} for transfers", - ); + println!( + "Using queue family {graphics_family_index} for graphics and queue family \ + {transfer_family_index} for transfers", + ); - let resources = Resources::new(&device, &Default::default()); + let resources = Resources::new(&device, &Default::default()); - let graphics_flight_id = resources.create_flight(MAX_FRAMES_IN_FLIGHT).unwrap(); - let transfer_flight_id = resources.create_flight(1).unwrap(); + let graphics_flight_id = resources.create_flight(MAX_FRAMES_IN_FLIGHT).unwrap(); + let transfer_flight_id = resources.create_flight(1).unwrap(); - let vertices = [ - MyVertex { - position: [-0.5, -0.5], - }, - MyVertex { - position: [-0.5, 0.5], - }, - MyVertex { - position: [0.5, -0.5], - }, - MyVertex { - position: [0.5, 0.5], - }, - ]; - let vertex_buffer_id = resources - .create_buffer( - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() + let vertices = [ + MyVertex { + position: [-0.5, -0.5], }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() + MyVertex { + position: [-0.5, 0.5], }, - DeviceLayout::from_layout(Layout::for_value(&vertices)).unwrap(), - ) - .unwrap(); - - // Create a pool of uniform buffers, one per frame in flight. This way we always have an - // available buffer to write during each frame while reusing them as much as possible. - let uniform_buffer_ids = [(); MAX_FRAMES_IN_FLIGHT as usize].map(|_| { - resources + MyVertex { + position: [0.5, -0.5], + }, + MyVertex { + position: [0.5, 0.5], + }, + ]; + let vertex_buffer_id = resources .create_buffer( BufferCreateInfo { - usage: BufferUsage::UNIFORM_BUFFER, + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, AllocationCreateInfo { @@ -310,339 +293,361 @@ impl App { | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - DeviceLayout::from_layout(Layout::new::()).unwrap(), + DeviceLayout::from_layout(Layout::for_value(&vertices)).unwrap(), ) - .unwrap() - }); + .unwrap(); - // Create two textures, where at any point in time one is used exclusively for reading and - // one is used exclusively for writing, swapping the two after each update. - let texture_ids = [(); 2].map(|_| { - resources - .create_image( - ImageCreateInfo { - image_type: ImageType::Dim2d, - format: Format::R8G8B8A8_UNORM, - extent: [TRANSFER_GRANULARITY * 2, TRANSFER_GRANULARITY * 2, 1], - usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, - sharing: if graphics_family_index != transfer_family_index { - Sharing::Concurrent( - [graphics_family_index, transfer_family_index] - .into_iter() - .collect(), - ) - } else { - Sharing::Exclusive + // Create a pool of uniform buffers, one per frame in flight. This way we always have an + // available buffer to write during each frame while reusing them as much as possible. + let uniform_buffer_ids = [(); MAX_FRAMES_IN_FLIGHT as usize].map(|_| { + resources + .create_buffer( + BufferCreateInfo { + usage: BufferUsage::UNIFORM_BUFFER, + ..Default::default() }, - ..Default::default() + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + DeviceLayout::from_layout(Layout::new::()).unwrap(), + ) + .unwrap() + }); + + // Create two textures, where at any point in time one is used exclusively for reading and + // one is used exclusively for writing, swapping the two after each update. + let texture_ids = [(); 2].map(|_| { + resources + .create_image( + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: Format::R8G8B8A8_UNORM, + extent: [TRANSFER_GRANULARITY * 2, TRANSFER_GRANULARITY * 2, 1], + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + sharing: if graphics_family_index != transfer_family_index { + Sharing::Concurrent( + [graphics_family_index, transfer_family_index] + .into_iter() + .collect(), + ) + } else { + Sharing::Exclusive + }, + ..Default::default() + }, + AllocationCreateInfo::default(), + ) + .unwrap() + }); + + // The index of the currently most up-to-date texture. The worker thread swaps the index + // after every finished write, which is always done to the, at that point in time, unused + // texture. + let current_texture_index = Arc::new(AtomicBool::new(false)); + + // Initialize the resources. + unsafe { + vulkano_taskgraph::execute( + &graphics_queue, + &resources, + graphics_flight_id, + |cbf, tcx| { + tcx.write_buffer::<[MyVertex]>(vertex_buffer_id, ..)? + .copy_from_slice(&vertices); + + for &texture_id in &texture_ids { + cbf.clear_color_image(&ClearColorImageInfo { + image: texture_id, + ..Default::default() + })?; + } + + Ok(()) }, - AllocationCreateInfo::default(), + [(vertex_buffer_id, HostAccessType::Write)], + [], + [ + ( + texture_ids[0], + AccessType::ClearTransferWrite, + ImageLayoutType::Optimal, + ), + ( + texture_ids[1], + AccessType::ClearTransferWrite, + ImageLayoutType::Optimal, + ), + ], ) - .unwrap() - }); + } + .unwrap(); - // The index of the currently most up-to-date texture. The worker thread swaps the index after - // every finished write, which is always done to the, at that point in time, unused texture. - let current_texture_index = Arc::new(AtomicBool::new(false)); + // Start the worker thread. + let (channel, receiver) = mpsc::channel(); + run_worker( + receiver, + graphics_family_index, + transfer_family_index, + transfer_queue.clone(), + resources.clone(), + graphics_flight_id, + transfer_flight_id, + texture_ids, + current_texture_index.clone(), + ); - // Initialize the resources. - unsafe { - vulkano_taskgraph::execute( - &graphics_queue, - &resources, + App { + instance, + device, + graphics_family_index, + transfer_family_index, + graphics_queue, + resources, graphics_flight_id, - |cbf, tcx| { - tcx.write_buffer::<[MyVertex]>(vertex_buffer_id, ..)? - .copy_from_slice(&vertices); + vertex_buffer_id, + uniform_buffer_ids, + texture_ids, + current_texture_index, + channel, + rcx: None, + } + } +} - for &texture_id in &texture_ids { - cbf.clear_color_image(&ClearColorImageInfo { - image: texture_id, +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let swapchain_format; + let swapchain_id = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + (swapchain_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + self.resources + .create_swapchain( + self.graphics_flight_id, + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(3), + image_format: swapchain_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), ..Default::default() - })?; - } + }, + ) + .unwrap() + }; - Ok(()) + let render_pass = vulkano::single_pass_renderpass!( + self.device.clone(), + attachments: { + color: { + format: swapchain_format, + samples: 1, + load_op: Clear, + store_op: Store, + }, + }, + pass: { + color: [color], + depth_stencil: {}, }, - [(vertex_buffer_id, HostAccessType::Write)], - [], - [ - ( - texture_ids[0], - AccessType::ClearTransferWrite, - ImageLayoutType::Optimal, - ), - ( - texture_ids[1], - AccessType::ClearTransferWrite, - ImageLayoutType::Optimal, - ), - ], ) - } - .unwrap(); + .unwrap(); - // Start the worker thread. - let (channel, receiver) = mpsc::channel(); - run_worker( - receiver, - graphics_family_index, - transfer_family_index, - transfer_queue.clone(), - resources.clone(), - graphics_flight_id, - transfer_flight_id, - texture_ids, - current_texture_index.clone(), - ); - - App { - instance, - device, - graphics_family_index, - transfer_family_index, - graphics_queue, - resources, - graphics_flight_id, - vertex_buffer_id, - uniform_buffer_ids, - texture_ids, - current_texture_index, - channel, - rcx: None, - } - } -} + let framebuffers = window_size_dependent_setup(&self.resources, swapchain_id, &render_pass); -impl ApplicationHandler for App { - fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new( - event_loop - .create_window(Window::default_attributes()) - .unwrap(), - ); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let swapchain_format; - let swapchain_id = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - (swapchain_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; - - self.resources - .create_swapchain( - self.graphics_flight_id, - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(3), - image_format: swapchain_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::TriangleStrip, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) }, ) .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain_format, - samples: 1, - load_op: Clear, - store_op: Store, - }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + }; - let framebuffers = window_size_dependent_setup(&self.resources, swapchain_id, &render_pass); + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + Default::default(), + )); + + // A byproduct of always using the same set of uniform buffers is that we can also create + // one descriptor set for each, reusing them in the same way as the buffers. + let uniform_buffer_sets = self.uniform_buffer_ids.map(|buffer_id| { + let buffer_state = self.resources.buffer(buffer_id).unwrap(); + let buffer = buffer_state.buffer(); + + DescriptorSet::new( + descriptor_set_allocator.clone(), + pipeline.layout().set_layouts()[0].clone(), + [WriteDescriptorSet::buffer(0, buffer.clone().into())], + [], + ) + .unwrap() + }); - GraphicsPipeline::new( + // Create the descriptor sets for sampling the textures. + let sampler = Sampler::new( self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::TriangleStrip, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, + SamplerCreateInfo::simple_repeat_linear(), ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - self.device.clone(), - Default::default(), - )); - - // A byproduct of always using the same set of uniform buffers is that we can also create one - // descriptor set for each, reusing them in the same way as the buffers. - let uniform_buffer_sets = self.uniform_buffer_ids.map(|buffer_id| { - let buffer_state = self.resources.buffer(buffer_id).unwrap(); - let buffer = buffer_state.buffer(); - - DescriptorSet::new( - descriptor_set_allocator.clone(), - pipeline.layout().set_layouts()[0].clone(), - [WriteDescriptorSet::buffer(0, buffer.clone().into())], - [], - ) - .unwrap() - }); - - // Create the descriptor sets for sampling the textures. - let sampler = Sampler::new( - self.device.clone(), - SamplerCreateInfo::simple_repeat_linear(), - ) - .unwrap(); - let sampler_sets = self.texture_ids.map(|texture_id| { - let texture_state = self.resources.image(texture_id).unwrap(); - let texture = texture_state.image(); - - DescriptorSet::new( - descriptor_set_allocator.clone(), - pipeline.layout().set_layouts()[1].clone(), - [ - WriteDescriptorSet::sampler(0, sampler.clone()), - WriteDescriptorSet::image_view(1, ImageView::new_default(texture.clone()).unwrap()), - ], - [], - ) - .unwrap() - }); - - let mut task_graph = TaskGraph::new(&self.resources, 1, 4); - - let virtual_swapchain_id = task_graph.add_swapchain(&SwapchainCreateInfo::default()); - let virtual_texture_id = task_graph.add_image(&ImageCreateInfo { - sharing: if self.graphics_family_index != self.transfer_family_index { - Sharing::Concurrent( - [self.graphics_family_index, self.transfer_family_index] - .into_iter() - .collect(), + .unwrap(); + let sampler_sets = self.texture_ids.map(|texture_id| { + let texture_state = self.resources.image(texture_id).unwrap(); + let texture = texture_state.image(); + + DescriptorSet::new( + descriptor_set_allocator.clone(), + pipeline.layout().set_layouts()[1].clone(), + [ + WriteDescriptorSet::sampler(0, sampler.clone()), + WriteDescriptorSet::image_view( + 1, + ImageView::new_default(texture.clone()).unwrap(), + ), + ], + [], ) - } else { - Sharing::Exclusive - }, - ..Default::default() - }); - let virtual_uniform_buffer_id = task_graph.add_buffer(&BufferCreateInfo::default()); + .unwrap() + }); - task_graph.add_host_buffer_access(virtual_uniform_buffer_id, HostAccessType::Write); + let mut task_graph = TaskGraph::new(&self.resources, 1, 4); - task_graph - .create_task_node( - "Render", - QueueFamilyType::Graphics, - RenderTask { - swapchain_id: virtual_swapchain_id, - vertex_buffer_id: self.vertex_buffer_id, - current_texture_index: self.current_texture_index.clone(), - pipeline, - uniform_buffer_id: virtual_uniform_buffer_id, - uniform_buffer_sets, - sampler_sets, + let virtual_swapchain_id = task_graph.add_swapchain(&SwapchainCreateInfo::default()); + let virtual_texture_id = task_graph.add_image(&ImageCreateInfo { + sharing: if self.graphics_family_index != self.transfer_family_index { + Sharing::Concurrent( + [self.graphics_family_index, self.transfer_family_index] + .into_iter() + .collect(), + ) + } else { + Sharing::Exclusive }, - ) - .image_access( - virtual_swapchain_id.current_image_id(), - AccessType::ColorAttachmentWrite, - ImageLayoutType::Optimal, - ) - .buffer_access(self.vertex_buffer_id, AccessType::VertexAttributeRead) - .image_access( - virtual_texture_id, - AccessType::FragmentShaderSampledRead, - ImageLayoutType::Optimal, - ) - .buffer_access( - virtual_uniform_buffer_id, - AccessType::VertexShaderUniformRead, - ); - - let task_graph = unsafe { - task_graph.compile(&CompileInfo { - queues: &[&self.graphics_queue], - present_queue: Some(&self.graphics_queue), - flight_id: self.graphics_flight_id, ..Default::default() - }) - } - .unwrap(); + }); + let virtual_uniform_buffer_id = task_graph.add_buffer(&BufferCreateInfo::default()); + + task_graph.add_host_buffer_access(virtual_uniform_buffer_id, HostAccessType::Write); + + task_graph + .create_task_node( + "Render", + QueueFamilyType::Graphics, + RenderTask { + swapchain_id: virtual_swapchain_id, + vertex_buffer_id: self.vertex_buffer_id, + current_texture_index: self.current_texture_index.clone(), + pipeline, + uniform_buffer_id: virtual_uniform_buffer_id, + uniform_buffer_sets, + sampler_sets, + }, + ) + .image_access( + virtual_swapchain_id.current_image_id(), + AccessType::ColorAttachmentWrite, + ImageLayoutType::Optimal, + ) + .buffer_access(self.vertex_buffer_id, AccessType::VertexAttributeRead) + .image_access( + virtual_texture_id, + AccessType::FragmentShaderSampledRead, + ImageLayoutType::Optimal, + ) + .buffer_access( + virtual_uniform_buffer_id, + AccessType::VertexShaderUniformRead, + ); + + let task_graph = unsafe { + task_graph.compile(&CompileInfo { + queues: &[&self.graphics_queue], + present_queue: Some(&self.graphics_queue), + flight_id: self.graphics_flight_id, + ..Default::default() + }) + } + .unwrap(); - self.rcx = Some(RenderContext { - window, - swapchain_id, - render_pass, - framebuffers, - viewport, - recreate_swapchain: false, - task_graph, - virtual_swapchain_id, - virtual_texture_id, - virtual_uniform_buffer_id, - }); + self.rcx = Some(RenderContext { + window, + swapchain_id, + render_pass, + framebuffers, + viewport, + recreate_swapchain: false, + task_graph, + virtual_swapchain_id, + virtual_texture_id, + virtual_uniform_buffer_id, + }); } fn window_event( diff --git a/examples/bloom/main.rs b/examples/bloom/main.rs index a301ee5cd3..6425be9ca2 100644 --- a/examples/bloom/main.rs +++ b/examples/bloom/main.rs @@ -182,7 +182,11 @@ impl App { impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); let window_size = window.inner_size(); diff --git a/examples/buffer-allocator/main.rs b/examples/buffer-allocator/main.rs index 9f2eb75997..2c063d449b 100644 --- a/examples/buffer-allocator/main.rs +++ b/examples/buffer-allocator/main.rs @@ -77,250 +77,250 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..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(), - )); - - // Using a buffer allocator allows multiple buffers to be "in-flight" simultaneously and is - // suited to highly dynamic data like vertex, index and uniform buffers. - let buffer_allocator = SubbufferAllocator::new( - memory_allocator, - SubbufferAllocatorCreateInfo { - // We want to use the allocated subbuffers as vertex buffers. - buffer_usage: BufferUsage::VERTEX_BUFFER, - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - ); - - App { - instance, - device, - queue, - command_buffer_allocator, - buffer_allocator, - rcx: None, + }, + ) + .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(), + )); + + // Using a buffer allocator allows multiple buffers to be "in-flight" simultaneously and is + // suited to highly dynamic data like vertex, index and uniform buffers. + let buffer_allocator = SubbufferAllocator::new( + memory_allocator, + SubbufferAllocatorCreateInfo { + // We want to use the allocated subbuffers as vertex buffers. + buffer_usage: BufferUsage::VERTEX_BUFFER, + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + ); + + App { + instance, + device, + queue, + command_buffer_allocator, + buffer_allocator, + rcx: None, + } } } -} impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new( - event_loop - .create_window(Window::default_attributes()) - .unwrap(), - ); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 - layout(location = 0) in vec2 position; + layout(location = 0) in vec2 position; - void main() { - gl_Position = vec4(position, 0.0, 1.0); - } - ", + void main() { + gl_Position = vec4(position, 0.0, 1.0); + } + ", + } } - } - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - layout(location = 0) out vec4 f_color; + layout(location = 0) out vec4 f_color; - void main() { - f_color = vec4(1.0, 0.0, 0.0, 1.0); - } - ", + void main() { + f_color = vec4(1.0, 0.0, 0.0, 1.0); + } + ", + } } - } - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState::default()), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - }); + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -362,15 +362,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -409,7 +413,10 @@ impl ApplicationHandler for App { let num_vertices = data.len() as u32; // Allocate a new subbuffer using the buffer allocator. - let buffer = self.buffer_allocator.allocate_slice(data.len() as _).unwrap(); + let buffer = self + .buffer_allocator + .allocate_slice(data.len() as _) + .unwrap(); buffer.write().unwrap().copy_from_slice(&data); let mut builder = RecordingCommandBuffer::new( @@ -458,7 +465,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/clear-attachments/main.rs b/examples/clear-attachments/main.rs index 6facb4f3f4..455514c93e 100644 --- a/examples/clear-attachments/main.rs +++ b/examples/clear-attachments/main.rs @@ -56,156 +56,156 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - App { - instance, - device, - queue, - command_buffer_allocator, - rcx: None, - } + }, + ) + .unwrap(); + + let queue = queues.next().unwrap(); + + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + App { + instance, + device, + queue, + command_buffer_allocator, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new( - event_loop - .create_window(Window::default_attributes()) - .unwrap(), - ); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); - - let framebuffers = window_size_dependent_setup(&images, &render_pass); - - let [width, height] = window_size.into(); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - width, - height, - recreate_swapchain: false, - previous_frame_end, - }); + ) + .unwrap(); + + let framebuffers = window_size_dependent_setup(&images, &render_pass); + + let [width, height] = window_size.into(); + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + width, + height, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -247,15 +247,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -330,7 +334,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/deferred/main.rs b/examples/deferred/main.rs index 8b4c0d9f3c..1fc0ae11c1 100644 --- a/examples/deferred/main.rs +++ b/examples/deferred/main.rs @@ -79,156 +79,160 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..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(), - StandardCommandBufferAllocatorCreateInfo { - secondary_buffer_count: 32, - ..Default::default() - }, - )); - - App { - instance, - device, - queue, - memory_allocator, - command_buffer_allocator, - rcx: None, - } + }, + ) + .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(), + StandardCommandBufferAllocatorCreateInfo { + secondary_buffer_count: 32, + ..Default::default() + }, + )); + + App { + instance, + device, + queue, + memory_allocator, + command_buffer_allocator, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + let (swapchain, images) = Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; - - let (swapchain, images) = Swapchain::new( - self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() - }, - ) - .unwrap(); - (swapchain, images) - }; - - let images = images - .into_iter() - .map(|image| ImageView::new_default(image).unwrap()) - .collect::>(); - - // Here is the basic initialization for the deferred system. - let frame_system = FrameSystem::new( - self.queue.clone(), - swapchain.image_format(), - self.memory_allocator.clone(), - self.command_buffer_allocator.clone(), - ); - let triangle_draw_system = TriangleDrawSystem::new( - self.queue.clone(), - frame_system.deferred_subpass(), - self.memory_allocator.clone(), - self.command_buffer_allocator.clone(), - ); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - images, - frame_system, - triangle_draw_system, - recreate_swapchain: false, - previous_frame_end, - }); + (swapchain, images) + }; + + let images = images + .into_iter() + .map(|image| ImageView::new_default(image).unwrap()) + .collect::>(); + + // Here is the basic initialization for the deferred system. + let frame_system = FrameSystem::new( + self.queue.clone(), + swapchain.image_format(), + self.memory_allocator.clone(), + self.command_buffer_allocator.clone(), + ); + let triangle_draw_system = TriangleDrawSystem::new( + self.queue.clone(), + frame_system.deferred_subpass(), + self.memory_allocator.clone(), + self.command_buffer_allocator.clone(), + ); + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + images, + frame_system, + triangle_draw_system, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -273,15 +277,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -297,7 +305,9 @@ impl ApplicationHandler for App { while let Some(pass) = frame.next_pass() { match pass { Pass::Deferred(mut draw_pass) => { - let cb = rcx.triangle_draw_system.draw(draw_pass.viewport_dimensions()); + let cb = rcx + .triangle_draw_system + .draw(draw_pass.viewport_dimensions()); draw_pass.execute(cb); } Pass::Lighting(mut lighting) => { @@ -317,7 +327,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/gl-interop/main.rs b/examples/gl-interop/main.rs index cc3ae3cd1c..6f65d37641 100644 --- a/examples/gl-interop/main.rs +++ b/examples/gl-interop/main.rs @@ -124,482 +124,496 @@ mod linux { impl App { fn new(event_loop: &EventLoop<()>) -> Self { - let event_loop_gl = winit_glium::event_loop::EventLoop::new(); - // For some reason, this must be created before the vulkan window - let hrb = glutin::ContextBuilder::new() - .with_gl_debug_flag(true) - .with_gl(glutin::GlRequest::Latest) - .build_surfaceless(&event_loop_gl) - .unwrap(); + let event_loop_gl = winit_glium::event_loop::EventLoop::new(); + // For some reason, this must be created before the vulkan window + let hrb = glutin::ContextBuilder::new() + .with_gl_debug_flag(true) + .with_gl(glutin::GlRequest::Latest) + .build_surfaceless(&event_loop_gl) + .unwrap(); - let hrb_vk = glutin::ContextBuilder::new() - .with_gl_debug_flag(true) - .with_gl(glutin::GlRequest::Latest) - .build_surfaceless(&event_loop_gl) + let hrb_vk = glutin::ContextBuilder::new() + .with_gl_debug_flag(true) + .with_gl(glutin::GlRequest::Latest) + .build_surfaceless(&event_loop_gl) + .unwrap(); + + // Used for checking device and driver UUIDs. + let display = glium::HeadlessRenderer::with_debug( + hrb_vk, + glium::debug::DebugCallbackBehavior::PrintAll, + ) .unwrap(); - // Used for checking device and driver UUIDs. - let display = glium::HeadlessRenderer::with_debug( - hrb_vk, - glium::debug::DebugCallbackBehavior::PrintAll, - ) - .unwrap(); - - let library = VulkanLibrary::new().unwrap(); - let required_extensions = Surface::required_extensions(event_loop).unwrap(); - let instance = Instance::new( - library, - InstanceCreateInfo { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: InstanceExtensions { - khr_get_physical_device_properties2: true, - khr_external_memory_capabilities: true, - khr_external_semaphore_capabilities: true, - khr_external_fence_capabilities: true, - ext_debug_utils: true, - ..required_extensions - }, - ..Default::default() - }, - ) - .unwrap(); - - let _debug_callback = unsafe { - DebugUtilsMessenger::new( - instance.clone(), - DebugUtilsMessengerCreateInfo::user_callback(DebugUtilsMessengerCallback::new( - |message_severity, message_type, callback_data| { - println!( - "{} {:?} {:?}: {}", - callback_data.message_id_name.unwrap_or("unknown"), - message_type, - message_severity, - callback_data.message, - ); + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: InstanceExtensions { + khr_get_physical_device_properties2: true, + khr_external_memory_capabilities: true, + khr_external_semaphore_capabilities: true, + khr_external_fence_capabilities: true, + ext_debug_utils: true, + ..required_extensions }, - )), + ..Default::default() + }, ) - .unwrap() - }; - - let device_extensions = DeviceExtensions { - khr_external_semaphore: true, - khr_external_semaphore_fd: true, - khr_external_memory: true, - khr_external_memory_fd: true, - khr_external_fence: true, - khr_external_fence_fd: true, - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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)) - }) - .filter(|(p, _)| p.properties().driver_uuid.unwrap() == display.driver_uuid().unwrap()) - .filter(|(p, _)| { - display - .device_uuids() - .unwrap() - .contains(&p.properties().device_uuid.unwrap()) - }) - .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, - }) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, - ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - let vertices = [ - MyVertex { - position: [-0.5, -0.5], - }, - MyVertex { - position: [-0.5, 0.5], - }, - MyVertex { - position: [0.5, -0.5], - }, - MyVertex { - position: [0.5, 0.5], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let raw_image = RawImage::new( - device.clone(), - ImageCreateInfo { - flags: ImageCreateFlags::MUTABLE_FORMAT, - image_type: ImageType::Dim2d, - format: Format::R16G16B16A16_UNORM, - extent: [200, 200, 1], - usage: ImageUsage::TRANSFER_SRC | ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, - external_memory_handle_types: ExternalMemoryHandleTypes::OPAQUE_FD, - ..Default::default() - }, - ) - .unwrap(); - - let image_requirements = raw_image.memory_requirements()[0]; - - let image_memory = DeviceMemory::allocate( - device.clone(), - MemoryAllocateInfo { - allocation_size: image_requirements.layout.size(), - memory_type_index: memory_allocator - .find_memory_type_index( - image_requirements.memory_type_bits, - MemoryTypeFilter::PREFER_DEVICE, - ) - .unwrap(), - dedicated_allocation: Some(DedicatedAllocation::Image(&raw_image)), - export_handle_types: ExternalMemoryHandleTypes::OPAQUE_FD, - ..Default::default() - }, - ) - .unwrap(); + let _debug_callback = unsafe { + DebugUtilsMessenger::new( + instance.clone(), + DebugUtilsMessengerCreateInfo::user_callback(DebugUtilsMessengerCallback::new( + |message_severity, message_type, callback_data| { + println!( + "{} {:?} {:?}: {}", + callback_data.message_id_name.unwrap_or("unknown"), + message_type, + message_severity, + callback_data.message, + ); + }, + )), + ) + .unwrap() + }; - let allocation_size = image_memory.allocation_size(); - let image_fd = image_memory - .export_fd(ExternalMemoryHandleType::OpaqueFd) - .unwrap(); + let device_extensions = DeviceExtensions { + khr_external_semaphore: true, + khr_external_semaphore_fd: true, + khr_external_memory: true, + khr_external_memory_fd: true, + khr_external_fence: true, + khr_external_fence_fd: true, + khr_swapchain: true, + ..DeviceExtensions::empty() + }; - // SAFETY: we just created this raw image and hasn't bound any memory to it. - let image = Arc::new(unsafe { - raw_image - .bind_memory([ResourceMemory::new_dedicated(image_memory)]) - .map_err(|(err, _, _)| err) + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() .unwrap() - }); + .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)) + }) + .filter(|(p, _)| { + p.properties().driver_uuid.unwrap() == display.driver_uuid().unwrap() + }) + .filter(|(p, _)| { + display + .device_uuids() + .unwrap() + .contains(&p.properties().device_uuid.unwrap()) + }) + .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, + }) + .unwrap(); - let image_view = ImageView::new_default(image).unwrap(); + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); - let sampler = Sampler::new( - device.clone(), - SamplerCreateInfo { - mag_filter: Filter::Linear, - min_filter: Filter::Linear, - address_mode: [SamplerAddressMode::Repeat; 3], - ..Default::default() - }, - ) - .unwrap(); + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() + }, + ) + .unwrap(); - let barrier = Arc::new(Barrier::new(2)); - let barrier_2 = Arc::new(Barrier::new(2)); + let queue = queues.next().unwrap(); - let acquire_sem = Arc::new( - Semaphore::new( + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( device.clone(), - SemaphoreCreateInfo { - export_handle_types: ExternalSemaphoreHandleTypes::OPAQUE_FD, + Default::default(), + )); + + let vertices = [ + MyVertex { + position: [-0.5, -0.5], + }, + MyVertex { + position: [-0.5, 0.5], + }, + MyVertex { + position: [0.5, -0.5], + }, + MyVertex { + position: [0.5, 0.5], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, + vertices, ) - .unwrap(), - ); - let release_sem = Arc::new( - Semaphore::new( + .unwrap(); + + let raw_image = RawImage::new( device.clone(), - SemaphoreCreateInfo { - export_handle_types: ExternalSemaphoreHandleTypes::OPAQUE_FD, + ImageCreateInfo { + flags: ImageCreateFlags::MUTABLE_FORMAT, + image_type: ImageType::Dim2d, + format: Format::R16G16B16A16_UNORM, + extent: [200, 200, 1], + usage: ImageUsage::TRANSFER_SRC + | ImageUsage::TRANSFER_DST + | ImageUsage::SAMPLED, + external_memory_handle_types: ExternalMemoryHandleTypes::OPAQUE_FD, ..Default::default() }, ) - .unwrap(), - ); + .unwrap(); - let acquire_fd = unsafe { - acquire_sem - .export_fd(ExternalSemaphoreHandleType::OpaqueFd) - .unwrap() - }; - let release_fd = unsafe { - release_sem - .export_fd(ExternalSemaphoreHandleType::OpaqueFd) - .unwrap() - }; - - let barrier_clone = barrier.clone(); - let barrier_2_clone = barrier_2.clone(); - - build_display(hrb, move |gl_display| { - let gl_tex = unsafe { - glium::texture::Texture2d::new_from_fd( - gl_display.as_ref(), - glium::texture::UncompressedFloatFormat::U16U16U16U16, - glium::texture::MipmapsOption::NoMipmap, - glium::texture::Dimensions::Texture2d { - width: 200, - height: 200, + let image_requirements = raw_image.memory_requirements()[0]; + + let image_memory = DeviceMemory::allocate( + device.clone(), + MemoryAllocateInfo { + allocation_size: image_requirements.layout.size(), + memory_type_index: memory_allocator + .find_memory_type_index( + image_requirements.memory_type_bits, + MemoryTypeFilter::PREFER_DEVICE, + ) + .unwrap(), + dedicated_allocation: Some(DedicatedAllocation::Image(&raw_image)), + export_handle_types: ExternalMemoryHandleTypes::OPAQUE_FD, + ..Default::default() + }, + ) + .unwrap(); + + let allocation_size = image_memory.allocation_size(); + let image_fd = image_memory + .export_fd(ExternalMemoryHandleType::OpaqueFd) + .unwrap(); + + // SAFETY: we just created this raw image and hasn't bound any memory to it. + let image = Arc::new(unsafe { + raw_image + .bind_memory([ResourceMemory::new_dedicated(image_memory)]) + .map_err(|(err, _, _)| err) + .unwrap() + }); + + let image_view = ImageView::new_default(image).unwrap(); + + let sampler = Sampler::new( + device.clone(), + SamplerCreateInfo { + mag_filter: Filter::Linear, + min_filter: Filter::Linear, + address_mode: [SamplerAddressMode::Repeat; 3], + ..Default::default() + }, + ) + .unwrap(); + + let barrier = Arc::new(Barrier::new(2)); + let barrier_2 = Arc::new(Barrier::new(2)); + + let acquire_sem = Arc::new( + Semaphore::new( + device.clone(), + SemaphoreCreateInfo { + export_handle_types: ExternalSemaphoreHandleTypes::OPAQUE_FD, + ..Default::default() }, - glium::texture::ImportParameters { - dedicated_memory: true, - size: allocation_size, - offset: 0, - tiling: glium::texture::ExternalTilingMode::Optimal, + ) + .unwrap(), + ); + let release_sem = Arc::new( + Semaphore::new( + device.clone(), + SemaphoreCreateInfo { + export_handle_types: ExternalSemaphoreHandleTypes::OPAQUE_FD, + ..Default::default() }, - image_fd, ) - } - .unwrap(); + .unwrap(), + ); - let gl_acquire_sem = unsafe { - glium::semaphore::Semaphore::new_from_fd(gl_display.as_ref(), acquire_fd).unwrap() + let acquire_fd = unsafe { + acquire_sem + .export_fd(ExternalSemaphoreHandleType::OpaqueFd) + .unwrap() }; - - let gl_release_sem = unsafe { - glium::semaphore::Semaphore::new_from_fd(gl_display.as_ref(), release_fd).unwrap() + let release_fd = unsafe { + release_sem + .export_fd(ExternalSemaphoreHandleType::OpaqueFd) + .unwrap() }; - let rotation_start = Instant::now(); + let barrier_clone = barrier.clone(); + let barrier_2_clone = barrier_2.clone(); + + build_display(hrb, move |gl_display| { + let gl_tex = unsafe { + glium::texture::Texture2d::new_from_fd( + gl_display.as_ref(), + glium::texture::UncompressedFloatFormat::U16U16U16U16, + glium::texture::MipmapsOption::NoMipmap, + glium::texture::Dimensions::Texture2d { + width: 200, + height: 200, + }, + glium::texture::ImportParameters { + dedicated_memory: true, + size: allocation_size, + offset: 0, + tiling: glium::texture::ExternalTilingMode::Optimal, + }, + image_fd, + ) + } + .unwrap(); - loop { - barrier_clone.wait(); - gl_acquire_sem - .wait_textures(Some(&[(&gl_tex, glium::semaphore::TextureLayout::General)])); + let gl_acquire_sem = unsafe { + glium::semaphore::Semaphore::new_from_fd(gl_display.as_ref(), acquire_fd) + .unwrap() + }; - gl_display.get_context().flush(); + let gl_release_sem = unsafe { + glium::semaphore::Semaphore::new_from_fd(gl_display.as_ref(), release_fd) + .unwrap() + }; - let elapsed = rotation_start.elapsed(); - let rotation = elapsed.as_nanos() as f64 / 2_000_000_000.0; + let rotation_start = Instant::now(); - use glium::Surface; - { - let mut fb = gl_tex.as_surface(); + loop { + barrier_clone.wait(); + gl_acquire_sem.wait_textures(Some(&[( + &gl_tex, + glium::semaphore::TextureLayout::General, + )])); - fb.clear_color( - 0.0, - (((rotation as f32).sin() + 1.) / 2.).powf(2.2), - 0.0, - 1.0, - ); - } - gl_release_sem - .signal_textures(Some(&[(&gl_tex, glium::semaphore::TextureLayout::General)])); - barrier_2_clone.wait(); + gl_display.get_context().flush(); - gl_display.get_context().finish(); + let elapsed = rotation_start.elapsed(); + let rotation = elapsed.as_nanos() as f64 / 2_000_000_000.0; - gl_display.get_context().assert_no_error(Some("err")); - } - }); + use glium::Surface; + { + let mut fb = gl_tex.as_surface(); - App { - instance, - device, - queue, - descriptor_set_allocator, - command_buffer_allocator, - vertex_buffer, - sampler, - image_view, - barrier, - barrier_2, - acquire_sem, - release_sem, - rcx: None, - } + fb.clear_color( + 0.0, + (((rotation as f32).sin() + 1.) / 2.).powf(2.2), + 0.0, + 1.0, + ); + } + gl_release_sem.signal_textures(Some(&[( + &gl_tex, + glium::semaphore::TextureLayout::General, + )])); + barrier_2_clone.wait(); + + gl_display.get_context().finish(); + + gl_display.get_context().assert_no_error(Some("err")); + } + }); + + App { + instance, + device, + queue, + descriptor_set_allocator, + command_buffer_allocator, + vertex_buffer, + sampler, + image_view, + barrier, + barrier_2, + acquire_sem, + release_sem, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::TriangleStrip, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState { + blend: Some(AttachmentBlend::alpha()), + ..Default::default() + }, + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let layout = &pipeline.layout().set_layouts()[0]; + + let descriptor_set = DescriptorSet::new( + self.descriptor_set_allocator.clone(), + layout.clone(), + [ + WriteDescriptorSet::sampler(0, self.sampler.clone()), + WriteDescriptorSet::image_view(1, self.image_view.clone()), + ], + [], ) .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::TriangleStrip, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState { - blend: Some(AttachmentBlend::alpha()), - ..Default::default() - }, - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let layout = &pipeline.layout().set_layouts()[0]; - - let descriptor_set = DescriptorSet::new( - self.descriptor_set_allocator.clone(), - layout.clone(), - [ - WriteDescriptorSet::sampler(0, self.sampler.clone()), - WriteDescriptorSet::image_view(1, self.image_view.clone()), - ], - [], - ) - .unwrap(); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - descriptor_set, - recreate_swapchain: false, - previous_frame_end, - }); + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + descriptor_set, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -667,24 +681,23 @@ mod linux { .expect("failed to recreate swapchain"); rcx.swapchain = new_swapchain; - rcx.framebuffers = window_size_dependent_setup(&new_images, &rcx.render_pass); + rcx.framebuffers = + window_size_dependent_setup(&new_images, &rcx.render_pass); 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}"), - }; + 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; @@ -727,7 +740,9 @@ mod linux { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); diff --git a/examples/image-self-copy-blit/main.rs b/examples/image-self-copy-blit/main.rs index 59599916fe..a8ea80935a 100644 --- a/examples/image-self-copy-blit/main.rs +++ b/examples/image-self-copy-blit/main.rs @@ -86,383 +86,389 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - let vertices = [ - MyVertex { - position: [-0.5, -0.5], - }, - MyVertex { - position: [-0.5, 0.5], - }, - MyVertex { - position: [0.5, -0.5], - }, - MyVertex { - position: [0.5, 0.5], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let mut uploads = RecordingCommandBuffer::new( - command_buffer_allocator.clone(), - queue.queue_family_index(), - CommandBufferLevel::Primary, - CommandBufferBeginInfo { - usage: CommandBufferUsage::OneTimeSubmit, - ..Default::default() - }, - ) - .unwrap(); - - let texture = { - let png_bytes = include_bytes!("image_img.png").as_slice(); - let decoder = png::Decoder::new(png_bytes); - let mut reader = decoder.read_info().unwrap(); - let info = reader.info(); - let img_size = [info.width, info.height]; - let extent = [info.width * 2, info.height * 2, 1]; - - let upload_buffer = Buffer::new_slice( + }, + ) + .unwrap(); + + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + let vertices = [ + MyVertex { + position: [-0.5, -0.5], + }, + MyVertex { + position: [-0.5, 0.5], + }, + MyVertex { + position: [0.5, -0.5], + }, + MyVertex { + position: [0.5, 0.5], + }, + ]; + let vertex_buffer = Buffer::from_iter( memory_allocator.clone(), BufferCreateInfo { - usage: BufferUsage::TRANSFER_SRC, + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_HOST + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - (info.width * info.height * 4) as DeviceSize, + vertices, ) .unwrap(); - reader - .next_frame(&mut upload_buffer.write().unwrap()) - .unwrap(); - - let image = Image::new( - memory_allocator, - ImageCreateInfo { - format: Format::R8G8B8A8_UNORM, - extent, - usage: ImageUsage::TRANSFER_SRC | ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + let mut uploads = RecordingCommandBuffer::new( + command_buffer_allocator.clone(), + queue.queue_family_index(), + CommandBufferLevel::Primary, + CommandBufferBeginInfo { + usage: CommandBufferUsage::OneTimeSubmit, ..Default::default() }, - AllocationCreateInfo::default(), ) .unwrap(); - // Here, we perform image copying and blitting on the same image. - uploads - // Clear the image buffer. - .clear_color_image(ClearColorImageInfo::image(image.clone())) - .unwrap() - // Put our image in the top left corner. - .copy_buffer_to_image(CopyBufferToImageInfo { - regions: [BufferImageCopy { - image_subresource: image.subresource_layers(), - image_extent: [img_size[0], img_size[1], 1], + let texture = { + let png_bytes = include_bytes!("image_img.png").as_slice(); + let decoder = png::Decoder::new(png_bytes); + let mut reader = decoder.read_info().unwrap(); + let info = reader.info(); + let img_size = [info.width, info.height]; + let extent = [info.width * 2, info.height * 2, 1]; + + let upload_buffer = Buffer::new_slice( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, ..Default::default() - }] - .into(), - ..CopyBufferToImageInfo::buffer_image(upload_buffer, image.clone()) - }) - .unwrap() - // Copy from the top left corner to the bottom right corner. - .copy_image(CopyImageInfo { - // Copying within the same image requires the General layout if the source and - // destination subresources overlap. - src_image_layout: ImageLayout::General, - dst_image_layout: ImageLayout::General, - regions: [ImageCopy { - src_subresource: image.subresource_layers(), - src_offset: [0, 0, 0], - dst_subresource: image.subresource_layers(), - dst_offset: [img_size[0], img_size[1], 0], - extent: [img_size[0], img_size[1], 1], + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() - }] - .into(), - ..CopyImageInfo::images(image.clone(), image.clone()) - }) - .unwrap() - // Blit from the bottom right corner to the top right corner (flipped). - .blit_image(BlitImageInfo { - // Same as above applies for blitting. - src_image_layout: ImageLayout::General, - dst_image_layout: ImageLayout::General, - regions: [ImageBlit { - src_subresource: image.subresource_layers(), - src_offsets: [ - [img_size[0], img_size[1], 0], - [img_size[0] * 2, img_size[1] * 2, 1], - ], - dst_subresource: image.subresource_layers(), - // Swapping the two corners results in flipped image. - dst_offsets: [ - [img_size[0] * 2 - 1, img_size[1] - 1, 0], - [img_size[0], 0, 1], - ], + }, + (info.width * info.height * 4) as DeviceSize, + ) + .unwrap(); + + reader + .next_frame(&mut upload_buffer.write().unwrap()) + .unwrap(); + + let image = Image::new( + memory_allocator, + ImageCreateInfo { + format: Format::R8G8B8A8_UNORM, + extent, + usage: ImageUsage::TRANSFER_SRC + | ImageUsage::TRANSFER_DST + | ImageUsage::SAMPLED, ..Default::default() - }] - .into(), - filter: Filter::Nearest, - ..BlitImageInfo::images(image.clone(), image.clone()) - }) + }, + AllocationCreateInfo::default(), + ) .unwrap(); - ImageView::new_default(image).unwrap() - }; + // Here, we perform image copying and blitting on the same image. + uploads + // Clear the image buffer. + .clear_color_image(ClearColorImageInfo::image(image.clone())) + .unwrap() + // Put our image in the top left corner. + .copy_buffer_to_image(CopyBufferToImageInfo { + regions: [BufferImageCopy { + image_subresource: image.subresource_layers(), + image_extent: [img_size[0], img_size[1], 1], + ..Default::default() + }] + .into(), + ..CopyBufferToImageInfo::buffer_image(upload_buffer, image.clone()) + }) + .unwrap() + // Copy from the top left corner to the bottom right corner. + .copy_image(CopyImageInfo { + // Copying within the same image requires the General layout if the source and + // destination subresources overlap. + src_image_layout: ImageLayout::General, + dst_image_layout: ImageLayout::General, + regions: [ImageCopy { + src_subresource: image.subresource_layers(), + src_offset: [0, 0, 0], + dst_subresource: image.subresource_layers(), + dst_offset: [img_size[0], img_size[1], 0], + extent: [img_size[0], img_size[1], 1], + ..Default::default() + }] + .into(), + ..CopyImageInfo::images(image.clone(), image.clone()) + }) + .unwrap() + // Blit from the bottom right corner to the top right corner (flipped). + .blit_image(BlitImageInfo { + // Same as above applies for blitting. + src_image_layout: ImageLayout::General, + dst_image_layout: ImageLayout::General, + regions: [ImageBlit { + src_subresource: image.subresource_layers(), + src_offsets: [ + [img_size[0], img_size[1], 0], + [img_size[0] * 2, img_size[1] * 2, 1], + ], + dst_subresource: image.subresource_layers(), + // Swapping the two corners results in flipped image. + dst_offsets: [ + [img_size[0] * 2 - 1, img_size[1] - 1, 0], + [img_size[0], 0, 1], + ], + ..Default::default() + }] + .into(), + filter: Filter::Nearest, + ..BlitImageInfo::images(image.clone(), image.clone()) + }) + .unwrap(); - let sampler = Sampler::new( - device.clone(), - SamplerCreateInfo { - mag_filter: Filter::Linear, - min_filter: Filter::Linear, - address_mode: [SamplerAddressMode::Repeat; 3], - ..Default::default() - }, - ) - .unwrap(); - - let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); - - App { - instance, - device, - queue, - descriptor_set_allocator, - command_buffer_allocator, - vertex_buffer, - texture, - sampler, - rcx: None, - } + ImageView::new_default(image).unwrap() + }; + + let sampler = Sampler::new( + device.clone(), + SamplerCreateInfo { + mag_filter: Filter::Linear, + min_filter: Filter::Linear, + address_mode: [SamplerAddressMode::Repeat; 3], + ..Default::default() + }, + ) + .unwrap(); + + let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); + + App { + instance, + device, + queue, + descriptor_set_allocator, + command_buffer_allocator, + vertex_buffer, + texture, + sampler, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::TriangleStrip, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState { + blend: Some(AttachmentBlend::alpha()), + ..Default::default() + }, + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let layout = &pipeline.layout().set_layouts()[0]; + let set = DescriptorSet::new( + self.descriptor_set_allocator.clone(), + layout.clone(), + [ + WriteDescriptorSet::sampler(0, self.sampler.clone()), + WriteDescriptorSet::image_view(1, self.texture.clone()), + ], + [], ) .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::TriangleStrip, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState { - blend: Some(AttachmentBlend::alpha()), - ..Default::default() - }, - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let layout = &pipeline.layout().set_layouts()[0]; - let set = DescriptorSet::new( - self.descriptor_set_allocator.clone(), - layout.clone(), - [ - WriteDescriptorSet::sampler(0, self.sampler.clone()), - WriteDescriptorSet::image_view(1, self.texture.clone()), - ], - [], - ) - .unwrap(); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - descriptor_set: set, - recreate_swapchain: false, - previous_frame_end, - }); + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + descriptor_set: set, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -504,15 +510,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -555,7 +565,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -570,7 +582,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/image/main.rs b/examples/image/main.rs index ec2283a4a4..45270752b3 100644 --- a/examples/image/main.rs +++ b/examples/image/main.rs @@ -84,330 +84,334 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) - .unwrap(); - - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - let vertices = [ - MyVertex { - position: [-0.5, -0.5], - }, - MyVertex { - position: [-0.5, 0.5], - }, - MyVertex { - position: [0.5, -0.5], - }, - MyVertex { - position: [0.5, 0.5], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let mut uploads = RecordingCommandBuffer::new( - command_buffer_allocator.clone(), - queue.queue_family_index(), - CommandBufferLevel::Primary, - CommandBufferBeginInfo { - usage: CommandBufferUsage::OneTimeSubmit, - ..Default::default() - }, - ) - .unwrap(); + }, + ) + .unwrap(); - let texture = { - let png_bytes = include_bytes!("image_img.png").as_slice(); - let decoder = png::Decoder::new(png_bytes); - let mut reader = decoder.read_info().unwrap(); - let info = reader.info(); - let extent = [info.width, info.height, 1]; + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); - let upload_buffer = Buffer::new_slice( + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() + }, + ) + .unwrap(); + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + let vertices = [ + MyVertex { + position: [-0.5, -0.5], + }, + MyVertex { + position: [-0.5, 0.5], + }, + MyVertex { + position: [0.5, -0.5], + }, + MyVertex { + position: [0.5, 0.5], + }, + ]; + let vertex_buffer = Buffer::from_iter( memory_allocator.clone(), BufferCreateInfo { - usage: BufferUsage::TRANSFER_SRC, + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_HOST + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - (info.width * info.height * 4) as DeviceSize, + vertices, ) .unwrap(); - reader - .next_frame(&mut upload_buffer.write().unwrap()) - .unwrap(); - - let image = Image::new( - memory_allocator, - ImageCreateInfo { - image_type: ImageType::Dim2d, - format: Format::R8G8B8A8_SRGB, - extent, - usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + let mut uploads = RecordingCommandBuffer::new( + command_buffer_allocator.clone(), + queue.queue_family_index(), + CommandBufferLevel::Primary, + CommandBufferBeginInfo { + usage: CommandBufferUsage::OneTimeSubmit, ..Default::default() }, - AllocationCreateInfo::default(), ) .unwrap(); - uploads - .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( - upload_buffer, - image.clone(), - )) + let texture = { + let png_bytes = include_bytes!("image_img.png").as_slice(); + let decoder = png::Decoder::new(png_bytes); + let mut reader = decoder.read_info().unwrap(); + let info = reader.info(); + let extent = [info.width, info.height, 1]; + + let upload_buffer = Buffer::new_slice( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + (info.width * info.height * 4) as DeviceSize, + ) + .unwrap(); + + reader + .next_frame(&mut upload_buffer.write().unwrap()) + .unwrap(); + + let image = Image::new( + memory_allocator, + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: Format::R8G8B8A8_SRGB, + extent, + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + ..Default::default() + }, + AllocationCreateInfo::default(), + ) .unwrap(); - ImageView::new_default(image).unwrap() - }; + uploads + .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( + upload_buffer, + image.clone(), + )) + .unwrap(); - let sampler = Sampler::new( - device.clone(), - SamplerCreateInfo { - mag_filter: Filter::Linear, - min_filter: Filter::Linear, - address_mode: [SamplerAddressMode::Repeat; 3], - ..Default::default() - }, - ) - .unwrap(); - - let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); - - App { - instance, - device, - queue, - descriptor_set_allocator, - command_buffer_allocator, - vertex_buffer, - texture, - sampler, - rcx: None, - } + ImageView::new_default(image).unwrap() + }; + + let sampler = Sampler::new( + device.clone(), + SamplerCreateInfo { + mag_filter: Filter::Linear, + min_filter: Filter::Linear, + address_mode: [SamplerAddressMode::Repeat; 3], + ..Default::default() + }, + ) + .unwrap(); + + let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); + + App { + instance, + device, + queue, + descriptor_set_allocator, + command_buffer_allocator, + vertex_buffer, + texture, + sampler, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window.inner_size().into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window.inner_size().into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::TriangleStrip, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState { + blend: Some(AttachmentBlend::alpha()), + ..Default::default() + }, + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let layout = &pipeline.layout().set_layouts()[0]; + let set = DescriptorSet::new( + self.descriptor_set_allocator.clone(), + layout.clone(), + [ + WriteDescriptorSet::sampler(0, self.sampler.clone()), + WriteDescriptorSet::image_view(1, self.texture.clone()), + ], + [], ) .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::TriangleStrip, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState { - blend: Some(AttachmentBlend::alpha()), - ..Default::default() - }, - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let layout = &pipeline.layout().set_layouts()[0]; - let set = DescriptorSet::new( - self.descriptor_set_allocator.clone(), - layout.clone(), - [ - WriteDescriptorSet::sampler(0, self.sampler.clone()), - WriteDescriptorSet::image_view(1, self.texture.clone()), - ], - [], - ) - .unwrap(); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - descriptor_set: set, - recreate_swapchain: false, - previous_frame_end, - }); + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + descriptor_set: set, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -449,15 +453,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -500,7 +508,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -515,7 +525,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/immutable-sampler/main.rs b/examples/immutable-sampler/main.rs index 43830982be..be5473507a 100644 --- a/examples/immutable-sampler/main.rs +++ b/examples/immutable-sampler/main.rs @@ -19,7 +19,7 @@ use vulkano::{ }, device::{ physical::PhysicalDeviceType, Device, DeviceCreateInfo, DeviceExtensions, Queue, - QueueCreateInfo, QueueFlags + QueueCreateInfo, QueueFlags, }, format::Format, image::{ @@ -90,342 +90,347 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) - .unwrap(); - - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - let vertices = [ - MyVertex { - position: [-0.5, -0.5], - }, - MyVertex { - position: [-0.5, 0.5], - }, - MyVertex { - position: [0.5, -0.5], - }, - MyVertex { - position: [0.5, 0.5], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let mut uploads = RecordingCommandBuffer::new( - command_buffer_allocator.clone(), - queue.queue_family_index(), - CommandBufferLevel::Primary, - CommandBufferBeginInfo { - usage: CommandBufferUsage::OneTimeSubmit, - ..Default::default() - }, - ) - .unwrap(); + }, + ) + .unwrap(); - let texture = { - let png_bytes = include_bytes!("image_img.png").as_slice(); - let decoder = png::Decoder::new(png_bytes); - let mut reader = decoder.read_info().unwrap(); - let info = reader.info(); - let extent = [info.width, info.height, 1]; + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); - let upload_buffer = Buffer::new_slice( + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() + }, + ) + .unwrap(); + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + let vertices = [ + MyVertex { + position: [-0.5, -0.5], + }, + MyVertex { + position: [-0.5, 0.5], + }, + MyVertex { + position: [0.5, -0.5], + }, + MyVertex { + position: [0.5, 0.5], + }, + ]; + let vertex_buffer = Buffer::from_iter( memory_allocator.clone(), BufferCreateInfo { - usage: BufferUsage::TRANSFER_SRC, + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_HOST + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - (info.width * info.height * 4) as DeviceSize, + vertices, ) .unwrap(); - reader - .next_frame(&mut upload_buffer.write().unwrap()) - .unwrap(); - - let image = Image::new( - memory_allocator, - ImageCreateInfo { - image_type: ImageType::Dim2d, - format: Format::R8G8B8A8_SRGB, - extent, - usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + let mut uploads = RecordingCommandBuffer::new( + command_buffer_allocator.clone(), + queue.queue_family_index(), + CommandBufferLevel::Primary, + CommandBufferBeginInfo { + usage: CommandBufferUsage::OneTimeSubmit, ..Default::default() }, - AllocationCreateInfo::default(), ) .unwrap(); - uploads - .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( - upload_buffer, - image.clone(), - )) + let texture = { + let png_bytes = include_bytes!("image_img.png").as_slice(); + let decoder = png::Decoder::new(png_bytes); + let mut reader = decoder.read_info().unwrap(); + let info = reader.info(); + let extent = [info.width, info.height, 1]; + + let upload_buffer = Buffer::new_slice( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + (info.width * info.height * 4) as DeviceSize, + ) .unwrap(); - ImageView::new_default(image).unwrap() - }; + reader + .next_frame(&mut upload_buffer.write().unwrap()) + .unwrap(); - let sampler = Sampler::new( - device.clone(), - SamplerCreateInfo { - mag_filter: Filter::Linear, - min_filter: Filter::Linear, - address_mode: [SamplerAddressMode::Repeat; 3], - ..Default::default() - }, - ) - .unwrap(); - - let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); - - App { - instance, - device, - queue, - descriptor_set_allocator, - command_buffer_allocator, - vertex_buffer, - texture, - sampler, - rcx: None, - } + let image = Image::new( + memory_allocator, + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: Format::R8G8B8A8_SRGB, + extent, + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + ..Default::default() + }, + AllocationCreateInfo::default(), + ) + .unwrap(); + + uploads + .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( + upload_buffer, + image.clone(), + )) + .unwrap(); + + ImageView::new_default(image).unwrap() + }; + + let sampler = Sampler::new( + device.clone(), + SamplerCreateInfo { + mag_filter: Filter::Linear, + min_filter: Filter::Linear, + address_mode: [SamplerAddressMode::Repeat; 3], + ..Default::default() + }, + ) + .unwrap(); + + let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); + + App { + instance, + device, + queue, + descriptor_set_allocator, + command_buffer_allocator, + vertex_buffer, + texture, + sampler, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = { - let mut layout_create_info = - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages); - - // Modify the auto-generated layout by setting an immutable sampler to set 0 binding 0. - layout_create_info.set_layouts[0] - .bindings - .get_mut(&0) + let pipeline = { + let vs = vs::load(self.device.clone()) .unwrap() - .immutable_samplers = vec![self.sampler.clone()]; + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = { + let mut layout_create_info = + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages); + + // Modify the auto-generated layout by setting an immutable sampler to set 0 + // binding 0. + layout_create_info.set_layouts[0] + .bindings + .get_mut(&0) + .unwrap() + .immutable_samplers = vec![self.sampler.clone()]; + + PipelineLayout::new( + self.device.clone(), + layout_create_info + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) + .unwrap() + }; + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - PipelineLayout::new( + GraphicsPipeline::new( self.device.clone(), - layout_create_info - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::TriangleStrip, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState { + blend: Some(AttachmentBlend::alpha()), + ..Default::default() + }, + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, ) .unwrap() }; - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::TriangleStrip, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState { - blend: Some(AttachmentBlend::alpha()), - ..Default::default() - }, - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, + let layout = &pipeline.layout().set_layouts()[0]; + + // Use `image_view` instead of `image_view_sampler`, since the sampler is already in the + // layout. + let set = DescriptorSet::new( + self.descriptor_set_allocator.clone(), + layout.clone(), + [WriteDescriptorSet::image_view(1, self.texture.clone())], + [], ) - .unwrap() - }; - - let layout = &pipeline.layout().set_layouts()[0]; - - // Use `image_view` instead of `image_view_sampler`, since the sampler is already in the - // layout. - let set = DescriptorSet::new( - self.descriptor_set_allocator.clone(), - layout.clone(), - [WriteDescriptorSet::image_view(1, self.texture.clone())], - [], - ) - .unwrap(); - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - descriptor_set: set, - recreate_swapchain: false, - previous_frame_end, - }); + .unwrap(); + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + descriptor_set: set, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -467,15 +472,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -518,7 +527,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -533,7 +544,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/indirect/main.rs b/examples/indirect/main.rs index 794208fdaf..f87c4a0b07 100644 --- a/examples/indirect/main.rs +++ b/examples/indirect/main.rs @@ -29,7 +29,7 @@ use vulkano::{ }, device::{ physical::PhysicalDeviceType, Device, DeviceCreateInfo, DeviceExtensions, Queue, - QueueCreateInfo, QueueFlags + QueueCreateInfo, QueueFlags, }, image::{view::ImageView, Image, ImageUsage}, instance::{Instance, InstanceCreateFlags, InstanceCreateInfo}, @@ -96,327 +96,331 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - khr_storage_buffer_storage_class: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) - .unwrap(); - - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - // Each frame we generate a new set of vertices and each frame we need a new - // `DrawIndirectCommand` struct to set the number of vertices to draw. - let indirect_buffer_allocator = SubbufferAllocator::new( - memory_allocator.clone(), - SubbufferAllocatorCreateInfo { - buffer_usage: BufferUsage::INDIRECT_BUFFER | BufferUsage::STORAGE_BUFFER, - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - ); - let vertex_buffer_allocator = SubbufferAllocator::new( - memory_allocator, - SubbufferAllocatorCreateInfo { - buffer_usage: BufferUsage::STORAGE_BUFFER | BufferUsage::VERTEX_BUFFER, - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - ); - - // A simple compute shader that generates vertices. It has two buffers bound: the first is - // where we output the vertices, the second is the `IndirectDrawArgs` struct we passed the - // `draw_indirect` so we can set the number to vertices to draw. - mod cs { - vulkano_shaders::shader! { - ty: "compute", - src: r" - #version 450 - - layout(local_size_x = 16, local_size_y = 1, local_size_z = 1) in; - - layout(set = 0, binding = 0) buffer Output { - vec2 pos[]; - } triangles; - - layout(set = 0, binding = 1) buffer IndirectDrawArgs { - uint vertices; - uint unused0; - uint unused1; - uint unused2; - }; - - void main() { - uint idx = gl_GlobalInvocationID.x; - - // Each invocation of the compute shader is going to increment the counter, so - // we need to use atomic operations for safety. The previous value of the - // counter is returned so that gives us the offset into the vertex buffer this - // thread can write it's vertices into. - uint offset = atomicAdd(vertices, 6); - - vec2 center = vec2(-0.8, -0.8) + idx * vec2(0.1, 0.1); - triangles.pos[offset + 0] = center + vec2(0.0, 0.0375); - triangles.pos[offset + 1] = center + vec2(0.025, -0.01725); - triangles.pos[offset + 2] = center + vec2(-0.025, -0.01725); - triangles.pos[offset + 3] = center + vec2(0.0, -0.0375); - triangles.pos[offset + 4] = center + vec2(0.025, 0.01725); - triangles.pos[offset + 5] = center + vec2(-0.025, 0.01725); - } - ", - } - } + }, + ) + .unwrap(); - let compute_pipeline = { - let cs = cs::load(device.clone()) + let device_extensions = DeviceExtensions { + khr_swapchain: true, + khr_storage_buffer_storage_class: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() .unwrap() - .entry_point("main") + .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, + }) .unwrap(); - let stage = PipelineShaderStageCreateInfo::new(cs); - let layout = PipelineLayout::new( - device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages([&stage]) - .into_pipeline_layout_create_info(device.clone()) - .unwrap(), + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() + }, ) .unwrap(); - ComputePipeline::new( + + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( device.clone(), - None, - ComputePipelineCreateInfo::stage_layout(stage, layout), - ) - .unwrap() - }; - - App { - instance, - device, - queue, - descriptor_set_allocator, - command_buffer_allocator, - indirect_buffer_allocator, - vertex_buffer_allocator, - compute_pipeline, - rcx: None, - } + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + // Each frame we generate a new set of vertices and each frame we need a new + // `DrawIndirectCommand` struct to set the number of vertices to draw. + let indirect_buffer_allocator = SubbufferAllocator::new( + memory_allocator.clone(), + SubbufferAllocatorCreateInfo { + buffer_usage: BufferUsage::INDIRECT_BUFFER | BufferUsage::STORAGE_BUFFER, + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + ); + let vertex_buffer_allocator = SubbufferAllocator::new( + memory_allocator, + SubbufferAllocatorCreateInfo { + buffer_usage: BufferUsage::STORAGE_BUFFER | BufferUsage::VERTEX_BUFFER, + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + ); + + // A simple compute shader that generates vertices. It has two buffers bound: the first is + // where we output the vertices, the second is the `IndirectDrawArgs` struct we passed the + // `draw_indirect` so we can set the number to vertices to draw. + mod cs { + vulkano_shaders::shader! { + ty: "compute", + src: r" + #version 450 + + layout(local_size_x = 16, local_size_y = 1, local_size_z = 1) in; + + layout(set = 0, binding = 0) buffer Output { + vec2 pos[]; + } triangles; + + layout(set = 0, binding = 1) buffer IndirectDrawArgs { + uint vertices; + uint unused0; + uint unused1; + uint unused2; + }; + + void main() { + uint idx = gl_GlobalInvocationID.x; + + // Each invocation of the compute shader is going to increment the counter, + // so we need to use atomic operations for safety. The previous value of + // the counter is returned so that gives us the offset into the vertex + // buffer this thread can write it's vertices into. + uint offset = atomicAdd(vertices, 6); + + vec2 center = vec2(-0.8, -0.8) + idx * vec2(0.1, 0.1); + triangles.pos[offset + 0] = center + vec2(0.0, 0.0375); + triangles.pos[offset + 1] = center + vec2(0.025, -0.01725); + triangles.pos[offset + 2] = center + vec2(-0.025, -0.01725); + triangles.pos[offset + 3] = center + vec2(0.0, -0.0375); + triangles.pos[offset + 4] = center + vec2(0.025, 0.01725); + triangles.pos[offset + 5] = center + vec2(-0.025, 0.01725); + } + ", + } + } + + let compute_pipeline = { + let cs = cs::load(device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let stage = PipelineShaderStageCreateInfo::new(cs); + let layout = PipelineLayout::new( + device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages([&stage]) + .into_pipeline_layout_create_info(device.clone()) + .unwrap(), + ) + .unwrap(); + ComputePipeline::new( + device.clone(), + None, + ComputePipelineCreateInfo::stage_layout(stage, layout), + ) + .unwrap() + }; + + App { + instance, + device, + queue, + descriptor_set_allocator, + command_buffer_allocator, + indirect_buffer_allocator, + vertex_buffer_allocator, + compute_pipeline, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 - // The triangle vertex positions. - layout(location = 0) in vec2 position; + // The triangle vertex positions. + layout(location = 0) in vec2 position; - void main() { - gl_Position = vec4(position, 0.0, 1.0); - } - ", + void main() { + gl_Position = vec4(position, 0.0, 1.0); + } + ", + } } - } - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - layout(location = 0) out vec4 f_color; + layout(location = 0) out vec4 f_color; - void main() { - f_color = vec4(1.0, 0.0, 0.0, 1.0); - } - ", + void main() { + f_color = vec4(1.0, 0.0, 0.0, 1.0); + } + ", + } } - } - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState::default()), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - }); + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -458,15 +462,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -493,7 +501,10 @@ impl ApplicationHandler for App { // Allocate a buffer to hold this frame's vertices. This needs to be large enough // to hold the worst case number of vertices generated by the compute shader. let iter = (0..(6 * 16)).map(|_| MyVertex { position: [0.0; 2] }); - let vertices = self.vertex_buffer_allocator.allocate_slice(iter.len() as _).unwrap(); + let vertices = self + .vertex_buffer_allocator + .allocate_slice(iter.len() as _) + .unwrap(); for (o, i) in vertices.write().unwrap().iter_mut().zip(iter) { *o = i; } @@ -576,7 +587,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/instancing/main.rs b/examples/instancing/main.rs index a7f18968ca..d92f653934 100644 --- a/examples/instancing/main.rs +++ b/examples/instancing/main.rs @@ -75,310 +75,314 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..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(), - )); - - // We now create a buffer that will store the shape of our triangle. This triangle is identical - // to the one in the `triangle.rs` example. - let vertices = [ - TriangleVertex { - position: [-0.5, -0.25], - }, - TriangleVertex { - position: [0.0, 0.5], - }, - TriangleVertex { - position: [0.25, -0.1], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - // Now we create another buffer that will store the unique data per instance. For this example, - // we'll have the instances form a 10x10 grid that slowly gets larger. - let instances = { - let rows = 10; - let cols = 10; - let n_instances = rows * cols; - let mut data = Vec::new(); - for c in 0..cols { - for r in 0..rows { - let half_cell_w = 0.5 / cols as f32; - let half_cell_h = 0.5 / rows as f32; - let x = half_cell_w + (c as f32 / cols as f32) * 2.0 - 1.0; - let y = half_cell_h + (r as f32 / rows as f32) * 2.0 - 1.0; - let position_offset = [x, y]; - let scale = (2.0 / rows as f32) * (c * rows + r) as f32 / n_instances as f32; - data.push(InstanceData { - position_offset, - scale, - }); + }, + ) + .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(), + )); + + // We now create a buffer that will store the shape of our triangle. This triangle is + // identical to the one in the `triangle.rs` example. + let vertices = [ + TriangleVertex { + position: [-0.5, -0.25], + }, + TriangleVertex { + position: [0.0, 0.5], + }, + TriangleVertex { + position: [0.25, -0.1], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); + + // Now we create another buffer that will store the unique data per instance. For this + // example, we'll have the instances form a 10x10 grid that slowly gets larger. + let instances = { + let rows = 10; + let cols = 10; + let n_instances = rows * cols; + let mut data = Vec::new(); + for c in 0..cols { + for r in 0..rows { + let half_cell_w = 0.5 / cols as f32; + let half_cell_h = 0.5 / rows as f32; + let x = half_cell_w + (c as f32 / cols as f32) * 2.0 - 1.0; + let y = half_cell_h + (r as f32 / rows as f32) * 2.0 - 1.0; + let position_offset = [x, y]; + let scale = (2.0 / rows as f32) * (c * rows + r) as f32 / n_instances as f32; + data.push(InstanceData { + position_offset, + scale, + }); + } } + data + }; + let instance_buffer = Buffer::from_iter( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + instances, + ) + .unwrap(); + + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + instance_buffer, + rcx: None, } - data - }; - let instance_buffer = Buffer::from_iter( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - instances, - ) - .unwrap(); - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - instance_buffer, - rcx: None, - } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 - // The triangle vertex positions. - layout(location = 0) in vec2 position; + // The triangle vertex positions. + layout(location = 0) in vec2 position; - // The per-instance data. - layout(location = 1) in vec2 position_offset; - layout(location = 2) in float scale; + // The per-instance data. + layout(location = 1) in vec2 position_offset; + layout(location = 2) in float scale; - void main() { - // Apply the scale and offset for the instance. - gl_Position = vec4(position * scale + position_offset, 0.0, 1.0); - } - ", + void main() { + // Apply the scale and offset for the instance. + gl_Position = vec4(position * scale + position_offset, 0.0, 1.0); + } + ", + } } - } - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - layout(location = 0) out vec4 f_color; + layout(location = 0) out vec4 f_color; - void main() { - f_color = vec4(1.0, 0.0, 0.0, 1.0); - } - ", + void main() { + f_color = vec4(1.0, 0.0, 0.0, 1.0); + } + ", + } } - } - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = [TriangleVertex::per_vertex(), InstanceData::per_instance()] + .definition(&vs) + .unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + // Use the implementations of the `Vertex` trait to describe to vulkano how the + // two vertex types are expected to be used. + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = [TriangleVertex::per_vertex(), InstanceData::per_instance()] - .definition(&vs) - .unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - // Use the implementations of the `Vertex` trait to describe to vulkano how the two - // vertex types are expected to be used. - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState::default()), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - }); + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -420,15 +424,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -461,7 +469,10 @@ impl ApplicationHandler for App { .bind_pipeline_graphics(rcx.pipeline.clone()) .unwrap() // We pass both our lists of vertices here. - .bind_vertex_buffers(0, (self.vertex_buffer.clone(), self.instance_buffer.clone())) + .bind_vertex_buffers( + 0, + (self.vertex_buffer.clone(), self.instance_buffer.clone()), + ) .unwrap(); unsafe { @@ -487,7 +498,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/interactive-fractal/main.rs b/examples/interactive-fractal/main.rs index 60cf7c788c..215544c845 100644 --- a/examples/interactive-fractal/main.rs +++ b/examples/interactive-fractal/main.rs @@ -10,15 +10,18 @@ // - A simple `FractalApp` to handle runtime state. // - A simple `InputState` to interact with the application. -use std::{error::Error, sync::Arc, time::{Duration, Instant}}; -use input::InputState; use fractal_compute_pipeline::FractalComputePipeline; use glam::Vec2; +use input::InputState; use place_over_frame::RenderPassPlaceOverFrame; +use std::{ + error::Error, + sync::Arc, + time::{Duration, Instant}, +}; use vulkano::{ command_buffer::allocator::{ - StandardCommandBufferAllocator, - StandardCommandBufferAllocatorCreateInfo, + StandardCommandBufferAllocator, StandardCommandBufferAllocatorCreateInfo, }, descriptor_set::allocator::StandardDescriptorSetAllocator, image::ImageUsage, @@ -106,85 +109,85 @@ struct RenderContext { impl App { fn new(_event_loop: &EventLoop<()>) -> Self { - let context = VulkanoContext::new(VulkanoConfig::default()); - let windows = VulkanoWindows::default(); - - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - context.device().clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - context.device().clone(), - StandardCommandBufferAllocatorCreateInfo { - secondary_buffer_count: 32, - ..Default::default() - }, - )); - - App { - context, - windows, - descriptor_set_allocator, - command_buffer_allocator, - rcx: None, - } + let context = VulkanoContext::new(VulkanoConfig::default()); + let windows = VulkanoWindows::default(); + + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + context.device().clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + context.device().clone(), + StandardCommandBufferAllocatorCreateInfo { + secondary_buffer_count: 32, + ..Default::default() + }, + )); + + App { + context, + windows, + descriptor_set_allocator, + command_buffer_allocator, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let _id = self.windows.create_window( - event_loop, - &self.context, - &WindowDescriptor { - title: "Fractal".to_string(), - present_mode: PresentMode::Fifo, - ..Default::default() - }, - |_| {}, - ); - - // Add our render target image onto which we'll be rendering our fractals. - let render_target_id = 0; - let window_renderer = self.windows.get_primary_renderer_mut().unwrap(); - - // Make sure the image usage is correct (based on your pipeline). - window_renderer.add_additional_image_view( - render_target_id, - DEFAULT_IMAGE_FORMAT, - ImageUsage::SAMPLED | ImageUsage::STORAGE | ImageUsage::TRANSFER_DST, - ); + let _id = self.windows.create_window( + event_loop, + &self.context, + &WindowDescriptor { + title: "Fractal".to_string(), + present_mode: PresentMode::Fifo, + ..Default::default() + }, + |_| {}, + ); + + // Add our render target image onto which we'll be rendering our fractals. + let render_target_id = 0; + let window_renderer = self.windows.get_primary_renderer_mut().unwrap(); - let gfx_queue = self.context.graphics_queue(); - - self.rcx = Some(RenderContext { - render_target_id, - fractal_pipeline: FractalComputePipeline::new( - gfx_queue.clone(), - self.context.memory_allocator().clone(), - self.command_buffer_allocator.clone(), - self.descriptor_set_allocator.clone(), - ), - place_over_frame: RenderPassPlaceOverFrame::new( - gfx_queue.clone(), - self.command_buffer_allocator.clone(), - self.descriptor_set_allocator.clone(), - window_renderer.swapchain_format(), - window_renderer.swapchain_image_views(), - ), - is_julia: false, - is_c_paused: false, - c: Vec2::new(0.0, 0.0), - scale: Vec2::new(4.0, 4.0), - translation: Vec2::new(0.0, 0.0), - max_iters: MAX_ITERS_INIT, - time: Instant::now(), - dt: 0.0, - dt_sum: 0.0, - frame_count: 0.0, - avg_fps: 0.0, - input_state: InputState::new(), - }); + // Make sure the image usage is correct (based on your pipeline). + window_renderer.add_additional_image_view( + render_target_id, + DEFAULT_IMAGE_FORMAT, + ImageUsage::SAMPLED | ImageUsage::STORAGE | ImageUsage::TRANSFER_DST, + ); + + let gfx_queue = self.context.graphics_queue(); + + self.rcx = Some(RenderContext { + render_target_id, + fractal_pipeline: FractalComputePipeline::new( + gfx_queue.clone(), + self.context.memory_allocator().clone(), + self.command_buffer_allocator.clone(), + self.descriptor_set_allocator.clone(), + ), + place_over_frame: RenderPassPlaceOverFrame::new( + gfx_queue.clone(), + self.command_buffer_allocator.clone(), + self.descriptor_set_allocator.clone(), + window_renderer.swapchain_format(), + window_renderer.swapchain_image_views(), + ), + is_julia: false, + is_c_paused: false, + c: Vec2::new(0.0, 0.0), + scale: Vec2::new(4.0, 4.0), + translation: Vec2::new(0.0, 0.0), + max_iters: MAX_ITERS_INIT, + time: Instant::now(), + dt: 0.0, + dt_sum: 0.0, + frame_count: 0.0, + avg_fps: 0.0, + input_state: InputState::new(), + }); } fn window_event( @@ -193,37 +196,39 @@ impl ApplicationHandler for App { _window_id: WindowId, event: WindowEvent, ) { - let renderer = self.windows.get_primary_renderer_mut().unwrap(); - let rcx = self.rcx.as_mut().unwrap(); - let window_size = renderer.window().inner_size(); + let renderer = self.windows.get_primary_renderer_mut().unwrap(); + let rcx = self.rcx.as_mut().unwrap(); + let window_size = renderer.window().inner_size(); - match event { - WindowEvent::CloseRequested => { - event_loop.exit(); - } - WindowEvent::Resized(..) | WindowEvent::ScaleFactorChanged { .. } => { - renderer.resize(); - } - WindowEvent::RedrawRequested => { - // Tasks for redrawing: - // 1. Update state based on events - // 2. Compute & Render - // 3. Reset input state - // 4. Update time & title - - // Skip this frame when minimized. - if window_size.width == 0 || window_size.height == 0 { - return; + match event { + WindowEvent::CloseRequested => { + event_loop.exit(); } - - rcx.update_state_after_inputs(renderer); - - // Start the frame. - let before_pipeline_future = - match renderer.acquire(Some(Duration::from_millis(1000)), |swapchain_image_views| { - rcx.place_over_frame - .recreate_framebuffers(swapchain_image_views) - }) { + WindowEvent::Resized(..) | WindowEvent::ScaleFactorChanged { .. } => { + renderer.resize(); + } + WindowEvent::RedrawRequested => { + // Tasks for redrawing: + // 1. Update state based on events + // 2. Compute & Render + // 3. Reset input state + // 4. Update time & title + + // Skip this frame when minimized. + if window_size.width == 0 || window_size.height == 0 { + return; + } + + rcx.update_state_after_inputs(renderer); + + // Start the frame. + let before_pipeline_future = match renderer.acquire( + Some(Duration::from_millis(1000)), + |swapchain_image_views| { + rcx.place_over_frame + .recreate_framebuffers(swapchain_image_views) + }, + ) { Err(e) => { println!("{e}"); return; @@ -231,53 +236,54 @@ impl ApplicationHandler for App { Ok(future) => future, }; - // Retrieve the target image. - let image = renderer.get_additional_image_view(rcx.render_target_id); - - // Compute our fractal (writes to target image). Join future with `before_pipeline_future`. - let after_compute = rcx - .fractal_pipeline - .compute( - image.clone(), - rcx.c, - rcx.scale, - rcx.translation, - rcx.max_iters, - rcx.is_julia, - ) - .join(before_pipeline_future); - - // Render the image over the swapchain image, inputting the previous future. - let after_renderpass_future = rcx.place_over_frame.render( - after_compute, - image, - renderer.swapchain_image_view(), - renderer.image_index(), - ); - - // Finish the frame (which presents the view), inputting the last future. Wait for the future - // so resources are not in use when we render. - renderer.present(after_renderpass_future, true); - - rcx.input_state.reset(); - rcx.update_time(); - renderer.window().set_title(&format!( - "{} fps: {:.2} dt: {:.2}, Max Iterations: {}", - if rcx.is_julia { "Julia" } else { "Mandelbrot" }, - rcx.avg_fps(), - rcx.dt(), - rcx.max_iters - )); - } - _ => { - // Pass event for the app to handle our inputs. - rcx.input_state.handle_input(window_size, &event); + // Retrieve the target image. + let image = renderer.get_additional_image_view(rcx.render_target_id); + + // Compute our fractal (writes to target image). Join future with + // `before_pipeline_future`. + let after_compute = rcx + .fractal_pipeline + .compute( + image.clone(), + rcx.c, + rcx.scale, + rcx.translation, + rcx.max_iters, + rcx.is_julia, + ) + .join(before_pipeline_future); + + // Render the image over the swapchain image, inputting the previous future. + let after_renderpass_future = rcx.place_over_frame.render( + after_compute, + image, + renderer.swapchain_image_view(), + renderer.image_index(), + ); + + // Finish the frame (which presents the view), inputting the last future. Wait for + // the future so resources are not in use when we render. + renderer.present(after_renderpass_future, true); + + rcx.input_state.reset(); + rcx.update_time(); + renderer.window().set_title(&format!( + "{} fps: {:.2} dt: {:.2}, Max Iterations: {}", + if rcx.is_julia { "Julia" } else { "Mandelbrot" }, + rcx.avg_fps(), + rcx.dt(), + rcx.max_iters + )); + } + _ => { + // Pass event for the app to handle our inputs. + rcx.input_state.handle_input(window_size, &event); + } } - } - if rcx.input_state.should_quit { - event_loop.exit(); - } + if rcx.input_state.should_quit { + event_loop.exit(); + } } fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { diff --git a/examples/mesh-shader/main.rs b/examples/mesh-shader/main.rs index 9644470bc6..a27368c2c1 100644 --- a/examples/mesh-shader/main.rs +++ b/examples/mesh-shader/main.rs @@ -92,297 +92,301 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ext_mesh_shader: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) + .unwrap(); + + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ext_mesh_shader: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + enabled_features: DeviceFeatures { + mesh_shader: true, + ..DeviceFeatures::default() + }, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - enabled_features: DeviceFeatures { - mesh_shader: true, - ..DeviceFeatures::default() + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + // We now create a buffer that will store the shape of our triangle. This triangle is + // identical to the one in the `triangle.rs` example. + let vertices = [ + TriangleVertex { + position: [-0.5, -0.25], + }, + TriangleVertex { + position: [0.0, 0.5], + }, + TriangleVertex { + position: [0.25, -0.1], }, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::STORAGE_BUFFER, ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - // We now create a buffer that will store the shape of our triangle. This triangle is identical - // to the one in the `triangle.rs` example. - let vertices = [ - TriangleVertex { - position: [-0.5, -0.25], - }, - TriangleVertex { - position: [0.0, 0.5], - }, - TriangleVertex { - position: [0.25, -0.1], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::STORAGE_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - // Now we create another buffer that will store the unique data per instance. For this example, - // we'll have the instances form a 10x10 grid that slowly gets larger. - let rows = 10; - let cols = 10; - let instances = { - let n_instances = rows * cols; - let mut data = Vec::new(); - for c in 0..cols { - for r in 0..rows { - let half_cell_w = 0.5 / cols as f32; - let half_cell_h = 0.5 / rows as f32; - let x = half_cell_w + (c as f32 / cols as f32) * 2.0 - 1.0; - let y = half_cell_h + (r as f32 / rows as f32) * 2.0 - 1.0; - let position_offset = [x, y]; - let scale = (2.0 / rows as f32) * (c * rows + r) as f32 / n_instances as f32; - data.push(InstanceData { - position_offset, - scale, - }); + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); + + // Now we create another buffer that will store the unique data per instance. For this + // example, we'll have the instances form a 10x10 grid that slowly gets larger. + let rows = 10; + let cols = 10; + let instances = { + let n_instances = rows * cols; + let mut data = Vec::new(); + for c in 0..cols { + for r in 0..rows { + let half_cell_w = 0.5 / cols as f32; + let half_cell_h = 0.5 / rows as f32; + let x = half_cell_w + (c as f32 / cols as f32) * 2.0 - 1.0; + let y = half_cell_h + (r as f32 / rows as f32) * 2.0 - 1.0; + let position_offset = [x, y]; + let scale = (2.0 / rows as f32) * (c * rows + r) as f32 / n_instances as f32; + data.push(InstanceData { + position_offset, + scale, + }); + } + } + data + }; + let instance_buffer = Buffer::new_unsized::( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::STORAGE_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + instances.len() as DeviceSize, + ) + .unwrap(); + { + let mut guard = instance_buffer.write().unwrap(); + for (i, instance) in instances.iter().enumerate() { + guard.instance[i] = Padded(*instance); } } - data - }; - let instance_buffer = Buffer::new_unsized::( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::STORAGE_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - instances.len() as DeviceSize, - ) - .unwrap(); - { - let mut guard = instance_buffer.write().unwrap(); - for (i, instance) in instances.iter().enumerate() { - guard.instance[i] = Padded(*instance); - } - } - App { - instance, - device, - queue, - vertex_buffer, - instance_buffer, - rows, - cols, - descriptor_set_allocator, - command_buffer_allocator, - rcx: None, - } + App { + instance, + device, + queue, + vertex_buffer, + instance_buffer, + rows, + cols, + descriptor_set_allocator, + command_buffer_allocator, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let mesh = mesh::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let mesh = mesh::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(mesh), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(mesh), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let descriptor_set = DescriptorSet::new( + self.descriptor_set_allocator.clone(), + pipeline.layout().set_layouts()[0].clone(), + [ + WriteDescriptorSet::buffer(0, self.vertex_buffer.clone()), + WriteDescriptorSet::buffer(1, self.instance_buffer.clone()), + ], + [], ) .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let descriptor_set = DescriptorSet::new( - self.descriptor_set_allocator.clone(), - pipeline.layout().set_layouts()[0].clone(), - [ - WriteDescriptorSet::buffer(0, self.vertex_buffer.clone()), - WriteDescriptorSet::buffer(1, self.instance_buffer.clone()), - ], - [], - ) - .unwrap(); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - descriptor_set, - recreate_swapchain: false, - previous_frame_end, - }); + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + descriptor_set, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -424,15 +428,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -489,7 +497,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/multi-window-game-of-life/main.rs b/examples/multi-window-game-of-life/main.rs index 4ef4d1d368..aeab5a584b 100644 --- a/examples/multi-window-game-of-life/main.rs +++ b/examples/multi-window-game-of-life/main.rs @@ -10,15 +10,18 @@ use game_of_life::GameOfLifeComputePipeline; use glam::{f32::Vec2, IVec2}; use render_pass::RenderPassPlaceOverFrame; +use std::{ + collections::HashMap, + error::Error, + sync::Arc, + time::{Duration, Instant}, +}; use vulkano::{ command_buffer::allocator::{ StandardCommandBufferAllocator, StandardCommandBufferAllocatorCreateInfo, }, descriptor_set::allocator::StandardDescriptorSetAllocator, }; -use std::{ - collections::HashMap, error::Error, sync::Arc, time::{Duration, Instant} -}; use vulkano_util::{ context::{VulkanoConfig, VulkanoContext}, renderer::VulkanoWindowRenderer, @@ -141,7 +144,7 @@ impl ApplicationHandler for App { life_color: [1.0, 0.0, 0.0, 1.0], dead_color: [0.0; 4], mouse_is_pressed: false, - } + }, ); self.rcxs.insert( id2, @@ -158,7 +161,7 @@ impl ApplicationHandler for App { life_color: [0.0, 0.0, 0.0, 1.0], dead_color: [1.0; 4], mouse_is_pressed: false, - } + }, ); } @@ -247,10 +250,7 @@ fn draw_life( } /// Compute game of life, then display result on target image. -fn compute_then_render( - window_renderer: &mut VulkanoWindowRenderer, - rcx: &mut RenderContext, -) { +fn compute_then_render(window_renderer: &mut VulkanoWindowRenderer, rcx: &mut RenderContext) { // Start the frame. let before_pipeline_future = match window_renderer.acquire(Some(Duration::from_millis(1000)), |swapchain_image_views| { @@ -265,9 +265,9 @@ fn compute_then_render( }; // Compute. - let after_compute = rcx - .compute_pipeline - .compute(before_pipeline_future, rcx.life_color, rcx.dead_color); + let after_compute = + rcx.compute_pipeline + .compute(before_pipeline_future, rcx.life_color, rcx.dead_color); // Render. let color_image = rcx.compute_pipeline.color_image(); diff --git a/examples/multi-window/main.rs b/examples/multi-window/main.rs index f77d314509..28f60c8d18 100644 --- a/examples/multi-window/main.rs +++ b/examples/multi-window/main.rs @@ -77,274 +77,276 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); + }, + ) + .unwrap(); - let queue = queues.next().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(), - )); + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); - let vertices = [ - MyVertex { - position: [-0.5, -0.25], - }, - MyVertex { - position: [0.0, 0.5], - }, - MyVertex { - position: [0.25, -0.1], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - // A hashmap that contains all of our created windows and their resources. - let rcxs = HashMap::new(); - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - rcxs, - } - } - - fn create_rcx(&self, window: Window) -> RenderContext { - let window = Arc::new(window); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - // The swapchain and framebuffer images for this particular window. - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; - - Swapchain::new( - self.device.clone(), - surface.clone(), - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), + let vertices = [ + MyVertex { + position: [-0.5, -0.25], + }, + MyVertex { + position: [0.0, 0.5], + }, + MyVertex { + position: [0.25, -0.1], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, ) - .unwrap() - }; - - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 + .unwrap(); - layout(location = 0) in vec2 position; + // A hashmap that contains all of our created windows and their resources. + let rcxs = HashMap::new(); - void main() { - gl_Position = vec4(position, 0.0, 1.0); - } - ", + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + rcxs, } } - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + fn create_rcx(&self, window: Window) -> RenderContext { + let window = Arc::new(window); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + // The swapchain and framebuffer images for this particular window. + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface.clone(), + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; + + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 - layout(location = 0) out vec4 f_color; + layout(location = 0) in vec2 position; - void main() { - f_color = vec4(1.0, 0.0, 0.0, 1.0); - } - ", + void main() { + gl_Position = vec4(position, 0.0, 1.0); + } + ", + } } - } - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, - }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - let framebuffers = window_size_dependent_setup(&images, &render_pass); + layout(location = 0) out vec4 f_color; - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + void main() { + f_color = vec4(1.0, 0.0, 0.0, 1.0); + } + ", + } + } - GraphicsPipeline::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState::default()), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, + }, + pass: { + color: [color], + depth_stencil: {}, }, ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - } + .unwrap(); + + let framebuffers = window_size_dependent_setup(&images, &render_pass); + + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) + .unwrap(); + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) + .unwrap() + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let window = event_loop + .create_window(Window::default_attributes()) + .unwrap(); - // Use the window's id as a means to access it from the hashmap. - let window_id = window.id(); + // Use the window's id as a means to access it from the hashmap. + let window_id = window.id(); - let rcx = self.create_rcx(window); + let rcx = self.create_rcx(window); - self.rcxs.insert(window_id, rcx); + self.rcxs.insert(window_id, rcx); } fn window_event( @@ -368,7 +370,9 @@ impl ApplicationHandler for App { }, .. } => { - let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let window = event_loop + .create_window(Window::default_attributes()) + .unwrap(); let window_id = window.id(); let rcx = self.create_rcx(window); @@ -400,15 +404,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -444,7 +452,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -459,7 +469,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); @@ -482,9 +495,7 @@ impl ApplicationHandler for App { } fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { - self.rcxs - .values() - .for_each(|s| s.window.request_redraw()); + self.rcxs.values().for_each(|s| s.window.request_redraw()); } } diff --git a/examples/occlusion-query/main.rs b/examples/occlusion-query/main.rs index 8c034dc36b..01bb004c05 100644 --- a/examples/occlusion-query/main.rs +++ b/examples/occlusion-query/main.rs @@ -80,336 +80,341 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..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(), - )); - - let vertices = [ - // The first triangle (red) is the same one as in the triangle example. - MyVertex { - position: [-0.5, -0.25, 0.5], - color: [1.0, 0.0, 0.0], - }, - MyVertex { - position: [0.0, 0.5, 0.5], - color: [1.0, 0.0, 0.0], - }, - MyVertex { - position: [0.25, -0.1, 0.5], - color: [1.0, 0.0, 0.0], - }, - // The second triangle (cyan) is the same shape and position as the first, but smaller, and - // moved behind a bit. It should be completely occluded by the first triangle. (You can - // lower its z value to put it in front.) - MyVertex { - position: [-0.25, -0.125, 0.6], - color: [0.0, 1.0, 1.0], - }, - MyVertex { - position: [0.0, 0.25, 0.6], - color: [0.0, 1.0, 1.0], - }, - MyVertex { - position: [0.125, -0.05, 0.6], - color: [0.0, 1.0, 1.0], - }, - // The third triangle (green) is the same shape and size as the first, but moved to the - // left and behind the second. It is partially occluded by the first two. - MyVertex { - position: [-0.25, -0.25, 0.7], - color: [0.0, 1.0, 0.0], - }, - MyVertex { - position: [0.25, 0.5, 0.7], - color: [0.0, 1.0, 0.0], - }, - MyVertex { - position: [0.5, -0.1, 0.7], - color: [0.0, 1.0, 0.0], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); + }, + ) + .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(), + )); + + let vertices = [ + // The first triangle (red) is the same one as in the triangle example. + MyVertex { + position: [-0.5, -0.25, 0.5], + color: [1.0, 0.0, 0.0], + }, + MyVertex { + position: [0.0, 0.5, 0.5], + color: [1.0, 0.0, 0.0], + }, + MyVertex { + position: [0.25, -0.1, 0.5], + color: [1.0, 0.0, 0.0], + }, + // The second triangle (cyan) is the same shape and position as the first, but smaller, + // and moved behind a bit. It should be completely occluded by the first triangle. (You + // can lower its z value to put it in front.) + MyVertex { + position: [-0.25, -0.125, 0.6], + color: [0.0, 1.0, 1.0], + }, + MyVertex { + position: [0.0, 0.25, 0.6], + color: [0.0, 1.0, 1.0], + }, + MyVertex { + position: [0.125, -0.05, 0.6], + color: [0.0, 1.0, 1.0], + }, + // The third triangle (green) is the same shape and size as the first, but moved to the + // left and behind the second. It is partially occluded by the first two. + MyVertex { + position: [-0.25, -0.25, 0.7], + color: [0.0, 1.0, 0.0], + }, + MyVertex { + position: [0.25, 0.5, 0.7], + color: [0.0, 1.0, 0.0], + }, + MyVertex { + position: [0.5, -0.1, 0.7], + color: [0.0, 1.0, 0.0], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); - // Create three buffer slices, one for each triangle. - let triangle1 = vertex_buffer.clone().slice(0..3); - let triangle2 = vertex_buffer.clone().slice(3..6); - let triangle3 = vertex_buffer.slice(6..9); - - // Create a query pool for occlusion queries, with 3 slots. - let query_pool = QueryPool::new( - device.clone(), - QueryPoolCreateInfo { - query_count: 3, - ..QueryPoolCreateInfo::query_type(QueryType::Occlusion) - }, - ) - .unwrap(); + // Create three buffer slices, one for each triangle. + let triangle1 = vertex_buffer.clone().slice(0..3); + let triangle2 = vertex_buffer.clone().slice(3..6); + let triangle3 = vertex_buffer.slice(6..9); + + // Create a query pool for occlusion queries, with 3 slots. + let query_pool = QueryPool::new( + device.clone(), + QueryPoolCreateInfo { + query_count: 3, + ..QueryPoolCreateInfo::query_type(QueryType::Occlusion) + }, + ) + .unwrap(); - // Create a buffer on the CPU to hold the results of the three queries. Query results are - // always represented as either `u32` or `u64`. For occlusion queries, you always need one - // element per query. You can ask for the number of elements needed at runtime by calling - // `QueryType::result_len`. If you retrieve query results with `with_availability` enabled, - // then this array needs to be 6 elements long instead of 3. - let query_results = [0u32; 3]; - - App { - instance, - device, - queue, - memory_allocator, - command_buffer_allocator, - triangle1, - triangle2, - triangle3, - query_pool, - query_results, - rcx: None, - } + // Create a buffer on the CPU to hold the results of the three queries. Query results are + // always represented as either `u32` or `u64`. For occlusion queries, you always need one + // element per query. You can ask for the number of elements needed at runtime by calling + // `QueryType::result_len`. If you retrieve query results with `with_availability` enabled, + // then this array needs to be 6 elements long instead of 3. + let query_results = [0u32; 3]; + + App { + instance, + device, + queue, + memory_allocator, + command_buffer_allocator, + triangle1, + triangle2, + triangle3, + query_pool, + query_results, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() - }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, + depth_stencil: { + format: Format::D16_UNORM, + samples: 1, + load_op: Clear, + store_op: DontCare, + }, }, - depth_stencil: { - format: Format::D16_UNORM, - samples: 1, - load_op: Clear, - store_op: DontCare, + pass: { + color: [color], + depth_stencil: {depth_stencil}, }, - }, - pass: { - color: [color], - depth_stencil: {depth_stencil}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass, &self.memory_allocator); + let framebuffers = + window_size_dependent_setup(&images, &render_pass, &self.memory_allocator); - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 - layout(location = 0) in vec3 position; - layout(location = 1) in vec3 color; + layout(location = 0) in vec3 position; + layout(location = 1) in vec3 color; - layout(location = 0) out vec3 v_color; + layout(location = 0) out vec3 v_color; - void main() { - v_color = color; - gl_Position = vec4(position, 1.0); - } - ", + void main() { + v_color = color; + gl_Position = vec4(position, 1.0); + } + ", + } } - } - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - layout(location = 0) in vec3 v_color; - layout(location = 0) out vec4 f_color; + layout(location = 0) in vec3 v_color; + layout(location = 0) out vec4 f_color; - void main() { - f_color = vec4(v_color, 1.0); - } - ", + void main() { + f_color = vec4(v_color, 1.0); + } + ", + } } - } - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + // Enable depth testing, which is needed for occlusion queries to make sense at + // all. If you disable depth testing, every pixel is considered to pass the + // depth test, so every query will return a nonzero result. + depth_stencil_state: Some(DepthStencilState { + depth: Some(DepthState::simple()), + ..Default::default() + }), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState::default()), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - // Enable depth testing, which is needed for occlusion queries to make sense at - // all. If you disable depth testing, every pixel is considered to pass the depth - // test, so every query will return a nonzero result. - depth_stencil_state: Some(DepthStencilState { - depth: Some(DepthState::simple()), - ..Default::default() - }), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - }); + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -455,15 +460,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -554,7 +563,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/push-descriptors/main.rs b/examples/push-descriptors/main.rs index ef9560198f..e1ccf0baca 100644 --- a/examples/push-descriptors/main.rs +++ b/examples/push-descriptors/main.rs @@ -77,321 +77,326 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - khr_push_descriptor: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, ..Default::default() - }], - ..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(), - )); - - let vertices = [ - MyVertex { - position: [-0.5, -0.5], - }, - MyVertex { - position: [-0.5, 0.5], - }, - MyVertex { - position: [0.5, -0.5], - }, - MyVertex { - position: [0.5, 0.5], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let mut uploads = RecordingCommandBuffer::new( - command_buffer_allocator.clone(), - queue.queue_family_index(), - CommandBufferLevel::Primary, - CommandBufferBeginInfo { - usage: CommandBufferUsage::OneTimeSubmit, - ..Default::default() - }, - ) - .unwrap(); + }, + ) + .unwrap(); + + let device_extensions = DeviceExtensions { + khr_swapchain: true, + khr_push_descriptor: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() + }, + ) + .unwrap(); + let queue = queues.next().unwrap(); - let texture = { - let png_bytes = include_bytes!("image_img.png").as_slice(); - let decoder = png::Decoder::new(png_bytes); - let mut reader = decoder.read_info().unwrap(); - let info = reader.info(); - let extent = [info.width, info.height, 1]; + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); - let upload_buffer = Buffer::new_slice( + let vertices = [ + MyVertex { + position: [-0.5, -0.5], + }, + MyVertex { + position: [-0.5, 0.5], + }, + MyVertex { + position: [0.5, -0.5], + }, + MyVertex { + position: [0.5, 0.5], + }, + ]; + let vertex_buffer = Buffer::from_iter( memory_allocator.clone(), BufferCreateInfo { - usage: BufferUsage::TRANSFER_SRC, + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_HOST + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - (info.width * info.height * 4) as DeviceSize, + vertices, ) .unwrap(); - reader - .next_frame(&mut upload_buffer.write().unwrap()) - .unwrap(); - - let image = Image::new( - memory_allocator, - ImageCreateInfo { - image_type: ImageType::Dim2d, - format: Format::R8G8B8A8_SRGB, - extent, - usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + let mut uploads = RecordingCommandBuffer::new( + command_buffer_allocator.clone(), + queue.queue_family_index(), + CommandBufferLevel::Primary, + CommandBufferBeginInfo { + usage: CommandBufferUsage::OneTimeSubmit, ..Default::default() }, - AllocationCreateInfo::default(), ) .unwrap(); - uploads - .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( - upload_buffer, - image.clone(), - )) + let texture = { + let png_bytes = include_bytes!("image_img.png").as_slice(); + let decoder = png::Decoder::new(png_bytes); + let mut reader = decoder.read_info().unwrap(); + let info = reader.info(); + let extent = [info.width, info.height, 1]; + + let upload_buffer = Buffer::new_slice( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + (info.width * info.height * 4) as DeviceSize, + ) .unwrap(); - ImageView::new_default(image).unwrap() - }; + reader + .next_frame(&mut upload_buffer.write().unwrap()) + .unwrap(); - let sampler = Sampler::new( - device.clone(), - SamplerCreateInfo { - mag_filter: Filter::Linear, - min_filter: Filter::Linear, - address_mode: [SamplerAddressMode::Repeat; 3], - ..Default::default() - }, - ) - .unwrap(); - - let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - texture, - sampler, - rcx: None, - } + let image = Image::new( + memory_allocator, + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: Format::R8G8B8A8_SRGB, + extent, + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + ..Default::default() + }, + AllocationCreateInfo::default(), + ) + .unwrap(); + + uploads + .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( + upload_buffer, + image.clone(), + )) + .unwrap(); + + ImageView::new_default(image).unwrap() + }; + + let sampler = Sampler::new( + device.clone(), + SamplerCreateInfo { + mag_filter: Filter::Linear, + min_filter: Filter::Linear, + address_mode: [SamplerAddressMode::Repeat; 3], + ..Default::default() + }, + ) + .unwrap(); + + let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); + + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + texture, + sampler, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; - Swapchain::new( + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; + + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = { - let mut layout_create_info = - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages); - let set_layout = &mut layout_create_info.set_layouts[0]; - set_layout.flags |= DescriptorSetLayoutCreateFlags::PUSH_DESCRIPTOR; - set_layout.bindings.get_mut(&0).unwrap().immutable_samplers = vec![self.sampler.clone()]; - - PipelineLayout::new( + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = { + let mut layout_create_info = + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages); + let set_layout = &mut layout_create_info.set_layouts[0]; + set_layout.flags |= DescriptorSetLayoutCreateFlags::PUSH_DESCRIPTOR; + set_layout.bindings.get_mut(&0).unwrap().immutable_samplers = + vec![self.sampler.clone()]; + + PipelineLayout::new( + self.device.clone(), + layout_create_info + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) + .unwrap() + }; + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( self.device.clone(), - layout_create_info - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::TriangleStrip, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState { + blend: Some(AttachmentBlend::alpha()), + ..Default::default() + }, + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, ) .unwrap() }; - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::TriangleStrip, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState { - blend: Some(AttachmentBlend::alpha()), - ..Default::default() - }, - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - }); + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -433,15 +438,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -491,7 +500,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -506,7 +517,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/runtime-array/main.rs b/examples/runtime-array/main.rs index 4974a4907f..0e4cbb7678 100644 --- a/examples/runtime-array/main.rs +++ b/examples/runtime-array/main.rs @@ -86,448 +86,459 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + 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 { + descriptor_indexing: true, + shader_sampled_image_array_non_uniform_indexing: true, + runtime_descriptor_array: true, + descriptor_binding_variable_descriptor_count: true, + ..DeviceFeatures::empty() + }, ..Default::default() - }], - enabled_extensions: device_extensions, - enabled_features: DeviceFeatures { - descriptor_indexing: true, - shader_sampled_image_array_non_uniform_indexing: true, - runtime_descriptor_array: true, - descriptor_binding_variable_descriptor_count: true, - ..DeviceFeatures::empty() }, - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - let vertices = [ - MyVertex { - position: [-0.1, -0.9], - tex_i: 0, - coords: [1.0, 0.0], - }, - MyVertex { - position: [-0.9, -0.9], - tex_i: 0, - coords: [0.0, 0.0], - }, - MyVertex { - position: [-0.9, -0.1], - tex_i: 0, - coords: [0.0, 1.0], - }, - MyVertex { - position: [-0.1, -0.9], - tex_i: 0, - coords: [1.0, 0.0], - }, - MyVertex { - position: [-0.9, -0.1], - tex_i: 0, - coords: [0.0, 1.0], - }, - MyVertex { - position: [-0.1, -0.1], - tex_i: 0, - coords: [1.0, 1.0], - }, - MyVertex { - position: [0.9, -0.9], - tex_i: 1, - coords: [1.0, 0.0], - }, - MyVertex { - position: [0.1, -0.9], - tex_i: 1, - coords: [0.0, 0.0], - }, - MyVertex { - position: [0.1, -0.1], - tex_i: 1, - coords: [0.0, 1.0], - }, - MyVertex { - position: [0.9, -0.9], - tex_i: 1, - coords: [1.0, 0.0], - }, - MyVertex { - position: [0.1, -0.1], - tex_i: 1, - coords: [0.0, 1.0], - }, - MyVertex { - position: [0.9, -0.1], - tex_i: 1, - coords: [1.0, 1.0], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let mut uploads = RecordingCommandBuffer::new( - command_buffer_allocator.clone(), - queue.queue_family_index(), - CommandBufferLevel::Primary, - CommandBufferBeginInfo { - usage: CommandBufferUsage::OneTimeSubmit, - ..Default::default() - }, - ) - .unwrap(); - - let mascot_texture = { - let png_bytes = include_bytes!("rust_mascot.png").to_vec(); - let cursor = Cursor::new(png_bytes); - let decoder = png::Decoder::new(cursor); - let mut reader = decoder.read_info().unwrap(); - let info = reader.info(); - let extent = [info.width, info.height, 1]; - - let upload_buffer = Buffer::new_slice( + ) + .unwrap(); + + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + let vertices = [ + MyVertex { + position: [-0.1, -0.9], + tex_i: 0, + coords: [1.0, 0.0], + }, + MyVertex { + position: [-0.9, -0.9], + tex_i: 0, + coords: [0.0, 0.0], + }, + MyVertex { + position: [-0.9, -0.1], + tex_i: 0, + coords: [0.0, 1.0], + }, + MyVertex { + position: [-0.1, -0.9], + tex_i: 0, + coords: [1.0, 0.0], + }, + MyVertex { + position: [-0.9, -0.1], + tex_i: 0, + coords: [0.0, 1.0], + }, + MyVertex { + position: [-0.1, -0.1], + tex_i: 0, + coords: [1.0, 1.0], + }, + MyVertex { + position: [0.9, -0.9], + tex_i: 1, + coords: [1.0, 0.0], + }, + MyVertex { + position: [0.1, -0.9], + tex_i: 1, + coords: [0.0, 0.0], + }, + MyVertex { + position: [0.1, -0.1], + tex_i: 1, + coords: [0.0, 1.0], + }, + MyVertex { + position: [0.9, -0.9], + tex_i: 1, + coords: [1.0, 0.0], + }, + MyVertex { + position: [0.1, -0.1], + tex_i: 1, + coords: [0.0, 1.0], + }, + MyVertex { + position: [0.9, -0.1], + tex_i: 1, + coords: [1.0, 1.0], + }, + ]; + let vertex_buffer = Buffer::from_iter( memory_allocator.clone(), BufferCreateInfo { - usage: BufferUsage::TRANSFER_SRC, + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_HOST + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - (info.width * info.height * 4) as DeviceSize, + vertices, ) .unwrap(); - reader - .next_frame(&mut upload_buffer.write().unwrap()) - .unwrap(); - - let image = Image::new( - memory_allocator.clone(), - ImageCreateInfo { - image_type: ImageType::Dim2d, - format: Format::R8G8B8A8_SRGB, - extent, - usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + let mut uploads = RecordingCommandBuffer::new( + command_buffer_allocator.clone(), + queue.queue_family_index(), + CommandBufferLevel::Primary, + CommandBufferBeginInfo { + usage: CommandBufferUsage::OneTimeSubmit, ..Default::default() }, - AllocationCreateInfo::default(), ) .unwrap(); - uploads - .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( - upload_buffer, - image.clone(), - )) + let mascot_texture = { + let png_bytes = include_bytes!("rust_mascot.png").to_vec(); + let cursor = Cursor::new(png_bytes); + let decoder = png::Decoder::new(cursor); + let mut reader = decoder.read_info().unwrap(); + let info = reader.info(); + let extent = [info.width, info.height, 1]; + + let upload_buffer = Buffer::new_slice( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + (info.width * info.height * 4) as DeviceSize, + ) .unwrap(); - ImageView::new_default(image).unwrap() - }; + reader + .next_frame(&mut upload_buffer.write().unwrap()) + .unwrap(); - let vulkano_texture = { - let png_bytes = include_bytes!("vulkano_logo.png").as_slice(); - let decoder = png::Decoder::new(png_bytes); - let mut reader = decoder.read_info().unwrap(); - let info = reader.info(); - let extent = [info.width, info.height, 1]; + let image = Image::new( + memory_allocator.clone(), + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: Format::R8G8B8A8_SRGB, + extent, + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + ..Default::default() + }, + AllocationCreateInfo::default(), + ) + .unwrap(); - let upload_buffer = Buffer::new_slice( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::TRANSFER_SRC, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_HOST - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - (info.width * info.height * 4) as DeviceSize, - ) - .unwrap(); + uploads + .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( + upload_buffer, + image.clone(), + )) + .unwrap(); + + ImageView::new_default(image).unwrap() + }; - reader - .next_frame(&mut upload_buffer.write().unwrap()) + let vulkano_texture = { + let png_bytes = include_bytes!("vulkano_logo.png").as_slice(); + let decoder = png::Decoder::new(png_bytes); + let mut reader = decoder.read_info().unwrap(); + let info = reader.info(); + let extent = [info.width, info.height, 1]; + + let upload_buffer = Buffer::new_slice( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + (info.width * info.height * 4) as DeviceSize, + ) + .unwrap(); + + reader + .next_frame(&mut upload_buffer.write().unwrap()) + .unwrap(); + + let image = Image::new( + memory_allocator, + ImageCreateInfo { + image_type: ImageType::Dim2d, + format: Format::R8G8B8A8_SRGB, + extent, + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + ..Default::default() + }, + AllocationCreateInfo::default(), + ) .unwrap(); - let image = Image::new( - memory_allocator, - ImageCreateInfo { - image_type: ImageType::Dim2d, - format: Format::R8G8B8A8_SRGB, - extent, - usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + uploads + .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( + upload_buffer, + image.clone(), + )) + .unwrap(); + + ImageView::new_default(image).unwrap() + }; + + let sampler = Sampler::new( + device.clone(), + SamplerCreateInfo { + mag_filter: Filter::Linear, + min_filter: Filter::Linear, + address_mode: [SamplerAddressMode::Repeat; 3], ..Default::default() }, - AllocationCreateInfo::default(), ) .unwrap(); - uploads - .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( - upload_buffer, - image.clone(), - )) - .unwrap(); - - ImageView::new_default(image).unwrap() - }; - - let sampler = Sampler::new( - device.clone(), - SamplerCreateInfo { - mag_filter: Filter::Linear, - min_filter: Filter::Linear, - address_mode: [SamplerAddressMode::Repeat; 3], - ..Default::default() - }, - ) - .unwrap(); - - let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); - - App { - instance, - device, - queue, - descriptor_set_allocator, - command_buffer_allocator, - vertex_buffer, - vulkano_texture, - mascot_texture, - sampler, - rcx: None, - } + let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); + + App { + instance, + device, + queue, + descriptor_set_allocator, + command_buffer_allocator, + vertex_buffer, + vulkano_texture, + mascot_texture, + sampler, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; - Swapchain::new( + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; + + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = { - let mut layout_create_info = - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages); - - // Adjust the info for set 0, binding 1 to make it variable with 2 descriptors. - let binding = layout_create_info.set_layouts[0] - .bindings - .get_mut(&1) + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") .unwrap(); - binding.binding_flags |= DescriptorBindingFlags::VARIABLE_DESCRIPTOR_COUNT; - binding.descriptor_count = 2; + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = { + let mut layout_create_info = + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages); + + // Adjust the info for set 0, binding 1 to make it variable with 2 descriptors. + let binding = layout_create_info.set_layouts[0] + .bindings + .get_mut(&1) + .unwrap(); + binding.binding_flags |= DescriptorBindingFlags::VARIABLE_DESCRIPTOR_COUNT; + binding.descriptor_count = 2; + + PipelineLayout::new( + self.device.clone(), + layout_create_info + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) + .unwrap() + }; + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - PipelineLayout::new( + GraphicsPipeline::new( self.device.clone(), - layout_create_info - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState { + blend: Some(AttachmentBlend::alpha()), + ..Default::default() + }, + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, ) .unwrap() }; - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState::default()), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState { - blend: Some(AttachmentBlend::alpha()), - ..Default::default() - }, - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let layout = &pipeline.layout().set_layouts()[0]; + let descriptor_set = DescriptorSet::new_variable( + self.descriptor_set_allocator.clone(), + layout.clone(), + 2, + [ + WriteDescriptorSet::sampler(0, self.sampler.clone()), + WriteDescriptorSet::image_view_array( + 1, + 0, + [ + self.mascot_texture.clone() as _, + self.vulkano_texture.clone() as _, + ], + ), + ], + [], ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let layout = &pipeline.layout().set_layouts()[0]; - let descriptor_set = DescriptorSet::new_variable( - self.descriptor_set_allocator.clone(), - layout.clone(), - 2, - [ - WriteDescriptorSet::sampler(0, self.sampler.clone()), - WriteDescriptorSet::image_view_array(1, 0, [self.mascot_texture.clone() as _, self.vulkano_texture.clone() as _]), - ], - [], - ) - .unwrap(); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - descriptor_set, - recreate_swapchain: false, - previous_frame_end, - }); + .unwrap(); + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + descriptor_set, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -569,15 +580,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -620,7 +635,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -635,7 +652,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/runtime-shader/main.rs b/examples/runtime-shader/main.rs index 1857263a2d..bddccba547 100644 --- a/examples/runtime-shader/main.rs +++ b/examples/runtime-shader/main.rs @@ -83,250 +83,256 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); + }, + ) + .unwrap(); - let queue = queues.next().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(), - )); + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); - let vertices = [ - MyVertex { - position: [-1.0, 1.0], - color: [1.0, 0.0, 0.0], - }, - MyVertex { - position: [0.0, -1.0], - color: [0.0, 1.0, 0.0], - }, - MyVertex { - position: [1.0, 1.0], - color: [0.0, 0.0, 1.0], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - rcx: None, - } + let vertices = [ + MyVertex { + position: [-1.0, 1.0], + color: [1.0, 0.0, 0.0], + }, + MyVertex { + position: [0.0, -1.0], + color: [0.0, 1.0, 0.0], + }, + MyVertex { + position: [1.0, 1.0], + color: [0.0, 0.0, 1.0], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); + + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = { - let code = read_spirv_words_from_file("vert.spv"); + let pipeline = { + let vs = { + let code = read_spirv_words_from_file("vert.spv"); - // Create a ShaderModule on a device the same Shader::load does it. - // NOTE: You will have to verify correctness of the data by yourself! - let module = unsafe { - ShaderModule::new(self.device.clone(), ShaderModuleCreateInfo::new(&code)).unwrap() + // Create a ShaderModule on a device the same Shader::load does it. + // NOTE: You will have to verify correctness of the data by yourself! + let module = unsafe { + ShaderModule::new(self.device.clone(), ShaderModuleCreateInfo::new(&code)) + .unwrap() + }; + module.entry_point("main").unwrap() }; - module.entry_point("main").unwrap() - }; - let fs = { - let code = read_spirv_words_from_file("frag.spv"); + let fs = { + let code = read_spirv_words_from_file("frag.spv"); - let module = unsafe { - ShaderModule::new(self.device.clone(), ShaderModuleCreateInfo::new(&code)).unwrap() + let module = unsafe { + ShaderModule::new(self.device.clone(), ShaderModuleCreateInfo::new(&code)) + .unwrap() + }; + module.entry_point("main").unwrap() }; - module.entry_point("main").unwrap() + + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) + .unwrap(); + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState::default()), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState { + cull_mode: CullMode::Front, + front_face: FrontFace::CounterClockwise, + ..Default::default() + }), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) + .unwrap() }; - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState::default()), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState { - cull_mode: CullMode::Front, - front_face: FrontFace::CounterClockwise, - ..Default::default() - }), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - }); + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + }); } - + fn window_event( &mut self, event_loop: &ActiveEventLoop, @@ -366,15 +372,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -410,7 +420,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -425,7 +437,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/simple-particles/main.rs b/examples/simple-particles/main.rs index 2799f965bc..eff0632027 100644 --- a/examples/simple-particles/main.rs +++ b/examples/simple-particles/main.rs @@ -89,403 +89,404 @@ struct RenderContext { impl App { 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 { - enabled_extensions: required_extensions, - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) - .unwrap(); - - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, - ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - // Apply scoped logic to create `DeviceLocalBuffer` initialized with vertex data. - let vertex_buffer = { - // Initialize vertex data as an iterator. - let vertices = (0..PARTICLE_COUNT).map(|i| { - let f = i as f32 / (PARTICLE_COUNT / 10) as f32; - MyVertex { - pos: [2. * f.fract() - 1., 0.2 * f.floor() - 1.], - vel: [0.; 2], - } - }); - - // Create a CPU-accessible buffer initialized with the vertex data. - let temporary_accessible_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - // Specify this buffer will be used as a transfer source. - usage: BufferUsage::TRANSFER_SRC, + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + enabled_extensions: required_extensions, + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, ..Default::default() }, - AllocationCreateInfo { - // Specify this buffer will be used for uploading to the GPU. - memory_type_filter: MemoryTypeFilter::PREFER_HOST - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, ) .unwrap(); - // Create a buffer in device-local memory with enough space for `PARTICLE_COUNT` number of - // `Vertex`. - let device_local_buffer = Buffer::new_slice::( - memory_allocator, - BufferCreateInfo { - // Specify use as a storage buffer, vertex buffer, and transfer destination. - usage: BufferUsage::STORAGE_BUFFER - | BufferUsage::TRANSFER_DST - | BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - // Specify this buffer will only be used by the device. - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE, - ..Default::default() - }, - PARTICLE_COUNT as DeviceSize, - ) - .unwrap(); + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); - // Create one-time command to copy between the buffers. - let mut cbb = RecordingCommandBuffer::new( - command_buffer_allocator.clone(), - queue.queue_family_index(), - CommandBufferLevel::Primary, - CommandBufferBeginInfo { - usage: CommandBufferUsage::OneTimeSubmit, + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() }, ) .unwrap(); - cbb.copy_buffer(CopyBufferInfo::buffers( - temporary_accessible_buffer, - device_local_buffer.clone(), - )) - .unwrap(); - let cb = cbb.end().unwrap(); - // Execute copy and wait for copy to complete before proceeding. - cb.execute(queue.clone()) - .unwrap() - .then_signal_fence_and_flush() - .unwrap() - .wait(None /* timeout */) + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + // Apply scoped logic to create `DeviceLocalBuffer` initialized with vertex data. + let vertex_buffer = { + // Initialize vertex data as an iterator. + let vertices = (0..PARTICLE_COUNT).map(|i| { + let f = i as f32 / (PARTICLE_COUNT / 10) as f32; + MyVertex { + pos: [2. * f.fract() - 1., 0.2 * f.floor() - 1.], + vel: [0.; 2], + } + }); + + // Create a CPU-accessible buffer initialized with the vertex data. + let temporary_accessible_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + // Specify this buffer will be used as a transfer source. + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + // Specify this buffer will be used for uploading to the GPU. + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) .unwrap(); - device_local_buffer - }; + // Create a buffer in device-local memory with enough space for `PARTICLE_COUNT` + // number of `Vertex`. + let device_local_buffer = Buffer::new_slice::( + memory_allocator, + BufferCreateInfo { + // Specify use as a storage buffer, vertex buffer, and transfer destination. + usage: BufferUsage::STORAGE_BUFFER + | BufferUsage::TRANSFER_DST + | BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + // Specify this buffer will only be used by the device. + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE, + ..Default::default() + }, + PARTICLE_COUNT as DeviceSize, + ) + .unwrap(); - // Create a compute-pipeline for applying the compute shader to vertices. - let compute_pipeline = { - let cs = cs::load(device.clone()) - .unwrap() - .entry_point("main") + // Create one-time command to copy between the buffers. + let mut cbb = RecordingCommandBuffer::new( + command_buffer_allocator.clone(), + queue.queue_family_index(), + CommandBufferLevel::Primary, + CommandBufferBeginInfo { + usage: CommandBufferUsage::OneTimeSubmit, + ..Default::default() + }, + ) .unwrap(); - let stage = PipelineShaderStageCreateInfo::new(cs); - let layout = PipelineLayout::new( - device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages([&stage]) - .into_pipeline_layout_create_info(device.clone()) - .unwrap(), + cbb.copy_buffer(CopyBufferInfo::buffers( + temporary_accessible_buffer, + device_local_buffer.clone(), + )) + .unwrap(); + let cb = cbb.end().unwrap(); + + // Execute copy and wait for copy to complete before proceeding. + cb.execute(queue.clone()) + .unwrap() + .then_signal_fence_and_flush() + .unwrap() + .wait(None /* timeout */) + .unwrap(); + + device_local_buffer + }; + + // Create a compute-pipeline for applying the compute shader to vertices. + let compute_pipeline = { + let cs = cs::load(device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let stage = PipelineShaderStageCreateInfo::new(cs); + let layout = PipelineLayout::new( + device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages([&stage]) + .into_pipeline_layout_create_info(device.clone()) + .unwrap(), + ) + .unwrap(); + + ComputePipeline::new( + device.clone(), + None, + ComputePipelineCreateInfo::stage_layout(stage, layout), + ) + .unwrap() + }; + + // Create a new descriptor set for binding vertices as a storage buffer. + let descriptor_set = DescriptorSet::new( + descriptor_set_allocator.clone(), + // 0 is the index of the descriptor set. + compute_pipeline.layout().set_layouts()[0].clone(), + [ + // 0 is the binding of the data in this set. We bind the `Buffer` of vertices here. + WriteDescriptorSet::buffer(0, vertex_buffer.clone()), + ], + [], ) .unwrap(); - ComputePipeline::new( - device.clone(), - None, - ComputePipelineCreateInfo::stage_layout(stage, layout), - ) - .unwrap() - }; - - // Create a new descriptor set for binding vertices as a storage buffer. - let descriptor_set = DescriptorSet::new( - descriptor_set_allocator.clone(), - // 0 is the index of the descriptor set. - compute_pipeline.layout().set_layouts()[0].clone(), - [ - // 0 is the binding of the data in this set. We bind the `Buffer` of vertices here. - WriteDescriptorSet::buffer(0, vertex_buffer.clone()), - ], - [], - ) - .unwrap(); - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - compute_pipeline, - descriptor_set, - rcx: None, - } + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + compute_pipeline, + descriptor_set, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new( - event_loop.create_window( - Window::default_attributes() - // For simplicity, we are going to assert that the window size is static. - .with_resizable(false) - .with_title("simple particles") - .with_inner_size(PhysicalSize::new(WINDOW_WIDTH, WINDOW_HEIGHT)), - ) - .unwrap(), - ); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; - - Swapchain::new( - self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: [WINDOW_WIDTH, WINDOW_HEIGHT], - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - present_mode: PresentMode::Fifo, - ..Default::default() - }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, - }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); - - let framebuffers = images - .into_iter() - .map(|img| { - let view = ImageView::new_default(img).unwrap(); - Framebuffer::new( - render_pass.clone(), - FramebufferCreateInfo { - attachments: vec![view], + let window = Arc::new( + event_loop + .create_window( + Window::default_attributes() + // For simplicity, we are going to assert that the window size is static. + .with_resizable(false) + .with_title("simple particles") + .with_inner_size(PhysicalSize::new(WINDOW_WIDTH, WINDOW_HEIGHT)), + ) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: [WINDOW_WIDTH, WINDOW_HEIGHT], + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + present_mode: PresentMode::Fifo, ..Default::default() }, ) .unwrap() - }) - .collect(); - - // The vertex shader determines color and is run once per particle. The vertices will be - // updated by the compute shader each frame. - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 - - layout(location = 0) in vec2 pos; - layout(location = 1) in vec2 vel; - - layout(location = 0) out vec4 outColor; - - // Keep this value in sync with the `maxSpeed` const in the compute shader. - const float maxSpeed = 10.0; - - void main() { - gl_Position = vec4(pos, 0.0, 1.0); - gl_PointSize = 1.0; - - // Mix colors based on position and velocity. - outColor = mix( - 0.2 * vec4(pos, abs(vel.x) + abs(vel.y), 1.0), - vec4(1.0, 0.5, 0.8, 1.0), - sqrt(length(vel) / maxSpeed) - ); - } - ", + }; + + let render_pass = vulkano::single_pass_renderpass!( + self.device.clone(), + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, + }, + pass: { + color: [color], + depth_stencil: {}, + }, + ) + .unwrap(); + + let framebuffers = images + .into_iter() + .map(|img| { + let view = ImageView::new_default(img).unwrap(); + Framebuffer::new( + render_pass.clone(), + FramebufferCreateInfo { + attachments: vec![view], + ..Default::default() + }, + ) + .unwrap() + }) + .collect(); + + // The vertex shader determines color and is run once per particle. The vertices will be + // updated by the compute shader each frame. + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 + + layout(location = 0) in vec2 pos; + layout(location = 1) in vec2 vel; + + layout(location = 0) out vec4 outColor; + + // Keep this value in sync with the `maxSpeed` const in the compute shader. + const float maxSpeed = 10.0; + + void main() { + gl_Position = vec4(pos, 0.0, 1.0); + gl_PointSize = 1.0; + + // Mix colors based on position and velocity. + outColor = mix( + 0.2 * vec4(pos, abs(vel.x) + abs(vel.y), 1.0), + vec4(1.0, 0.5, 0.8, 1.0), + sqrt(length(vel) / maxSpeed) + ); + } + ", + } } - } - // The fragment shader will only need to apply the color forwarded by the vertex shader, - // because the color of a particle should be identical over all pixels. - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + // The fragment shader will only need to apply the color forwarded by the vertex shader, + // because the color of a particle should be identical over all pixels. + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - layout(location = 0) in vec4 outColor; + layout(location = 0) in vec4 outColor; - layout(location = 0) out vec4 fragColor; + layout(location = 0) out vec4 fragColor; - void main() { - fragColor = outColor; - } - ", + void main() { + fragColor = outColor; + } + ", + } } - } - // Create a basic graphics pipeline for rendering particles. - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + // Create a basic graphics pipeline for rendering particles. + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass, 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + // Vertices will be rendered as a list of points. + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::PointList, + ..Default::default() + }), + viewport_state: Some(ViewportState { + viewports: [Viewport { + offset: [0.0, 0.0], + extent: [WINDOW_WIDTH as f32, WINDOW_HEIGHT as f32], + depth_range: 0.0..=1.0, + }] + .into_iter() + .collect(), + ..Default::default() + }), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass, 0).unwrap(); + }; - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - // Vertices will be rendered as a list of points. - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::PointList, - ..Default::default() - }), - viewport_state: Some(ViewportState { - viewports: [Viewport { - offset: [0.0, 0.0], - extent: [WINDOW_WIDTH as f32, WINDOW_HEIGHT as f32], - depth_range: 0.0..=1.0, - }] - .into_iter() - .collect(), - ..Default::default() - }), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - let start_time = SystemTime::now(); - - self.rcx = Some(RenderContext { - window, - swapchain, - framebuffers, - pipeline, - previous_frame_end, - start_time, - last_frame_time: start_time, - }); + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + let start_time = SystemTime::now(); + + self.rcx = Some(RenderContext { + window, + swapchain, + framebuffers, + pipeline, + previous_frame_end, + start_time, + last_frame_time: start_time, + }); } fn window_event( @@ -512,7 +513,10 @@ impl ApplicationHandler for App { // Update per-frame variables. let now = SystemTime::now(); let time = now.duration_since(rcx.start_time).unwrap().as_secs_f32(); - let delta_time = now.duration_since(rcx.last_frame_time).unwrap().as_secs_f32(); + let delta_time = now + .duration_since(rcx.last_frame_time) + .unwrap() + .as_secs_f32(); rcx.last_frame_time = now; // Create push constants to be passed to compute shader. @@ -531,8 +535,8 @@ impl ApplicationHandler for App { Err(e) => panic!("failed to acquire next image: {e}"), }; - // Since we disallow resizing, assert that the swapchain and surface are optimally - // configured. + // Since we disallow resizing, assert that the swapchain and surface are + // optimally configured. assert!( !suboptimal, "not handling sub-optimal swapchains in this sample code", @@ -603,7 +607,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/teapot/main.rs b/examples/teapot/main.rs index a93a2aa009..ad2d12fb9b 100644 --- a/examples/teapot/main.rs +++ b/examples/teapot/main.rs @@ -96,240 +96,244 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); + }, + ) + .unwrap(); - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - POSITIONS, - ) - .unwrap(); - let normals_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - NORMALS, - ) - .unwrap(); - let index_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::INDEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - INDICES, - ) - .unwrap(); + let queue = queues.next().unwrap(); - let uniform_buffer_allocator = SubbufferAllocator::new( - memory_allocator.clone(), - SubbufferAllocatorCreateInfo { - buffer_usage: BufferUsage::UNIFORM_BUFFER, - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - ); - - App { - instance, - device, - queue, - memory_allocator, - descriptor_set_allocator, - command_buffer_allocator, - vertex_buffer, - normals_buffer, - index_buffer, - uniform_buffer_allocator, - rcx: None, - } + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + let vertex_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + POSITIONS, + ) + .unwrap(); + let normals_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + NORMALS, + ) + .unwrap(); + let index_buffer = Buffer::from_iter( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::INDEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + INDICES, + ) + .unwrap(); + + let uniform_buffer_allocator = SubbufferAllocator::new( + memory_allocator.clone(), + SubbufferAllocatorCreateInfo { + buffer_usage: BufferUsage::UNIFORM_BUFFER, + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + ); + + App { + instance, + device, + queue, + memory_allocator, + descriptor_set_allocator, + command_buffer_allocator, + vertex_buffer, + normals_buffer, + index_buffer, + uniform_buffer_allocator, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() - }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, + depth_stencil: { + format: Format::D16_UNORM, + samples: 1, + load_op: Clear, + store_op: DontCare, + }, }, - depth_stencil: { - format: Format::D16_UNORM, - samples: 1, - load_op: Clear, - store_op: DontCare, + pass: { + color: [color], + depth_stencil: {depth_stencil}, }, - }, - pass: { - color: [color], - depth_stencil: {depth_stencil}, - }, - ) - .unwrap(); - - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") + ) .unwrap(); - let (framebuffers, pipeline) = window_size_dependent_setup( - window_size, - &images, - &render_pass, - &self.memory_allocator, - &vs, - &fs, - ); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - let rotation_start = Instant::now(); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - vs, - fs, - pipeline, - recreate_swapchain: false, - previous_frame_end, - rotation_start, - }); + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + + let (framebuffers, pipeline) = window_size_dependent_setup( + window_size, + &images, + &render_pass, + &self.memory_allocator, + &vs, + &fs, + ); + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + let rotation_start = Instant::now(); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + vs, + fs, + pipeline, + recreate_swapchain: false, + previous_frame_end, + rotation_start, + }); } fn window_event( @@ -339,7 +343,7 @@ impl ApplicationHandler for App { event: WindowEvent, ) { let rcx = self.rcx.as_mut().unwrap(); - + match event { WindowEvent::CloseRequested => { event_loop.exit(); @@ -385,8 +389,8 @@ impl ApplicationHandler for App { // NOTE: This teapot was meant for OpenGL where the origin is at the lower left // instead the origin is at the upper left in Vulkan, so we reverse the Y axis. - let aspect_ratio = - rcx.swapchain.image_extent()[0] as f32 / rcx.swapchain.image_extent()[1] as f32; + let aspect_ratio = rcx.swapchain.image_extent()[0] as f32 + / rcx.swapchain.image_extent()[1] as f32; let proj = Mat4::perspective_rh_gl( std::f32::consts::FRAC_PI_2, @@ -422,15 +426,19 @@ impl ApplicationHandler for App { ) .unwrap(); - 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}"), - }; + 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; @@ -470,7 +478,10 @@ impl ApplicationHandler for App { descriptor_set, ) .unwrap() - .bind_vertex_buffers(0, (self.vertex_buffer.clone(), self.normals_buffer.clone())) + .bind_vertex_buffers( + 0, + (self.vertex_buffer.clone(), self.normals_buffer.clone()), + ) .unwrap() .bind_index_buffer(self.index_buffer.clone()) .unwrap(); @@ -493,7 +504,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/tessellation/main.rs b/examples/tessellation/main.rs index 1c0e3fe110..f3f70ef918 100644 --- a/examples/tessellation/main.rs +++ b/examples/tessellation/main.rs @@ -83,277 +83,281 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let device_features = DeviceFeatures { - tessellation_shader: true, - fill_mode_non_solid: true, - ..DeviceFeatures::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .filter(|p| p.supported_extensions().contains(&device_extensions)) - .filter(|p| p.supported_features().contains(&device_features)) - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let device_features = DeviceFeatures { + tessellation_shader: true, + fill_mode_non_solid: true, + ..DeviceFeatures::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .filter(|p| p.supported_extensions().contains(&device_extensions)) + .filter(|p| p.supported_features().contains(&device_features)) + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + 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: device_features, ..Default::default() - }], - enabled_extensions: device_extensions, - enabled_features: device_features, - ..Default::default() - }, - ) - .unwrap(); + }, + ) + .unwrap(); - let queue = queues.next().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(), - )); + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); - let vertices = [ - MyVertex { - position: [-0.5, -0.25], - }, - MyVertex { - position: [0.0, 0.5], - }, - MyVertex { - position: [0.25, -0.1], - }, - MyVertex { - position: [0.9, 0.9], - }, - MyVertex { - position: [0.9, 0.8], - }, - MyVertex { - position: [0.8, 0.8], - }, - MyVertex { - position: [-0.9, 0.9], - }, - MyVertex { - position: [-0.7, 0.6], - }, - MyVertex { - position: [-0.5, 0.9], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - rcx: None, - } + let vertices = [ + MyVertex { + position: [-0.5, -0.25], + }, + MyVertex { + position: [0.0, 0.5], + }, + MyVertex { + position: [0.25, -0.1], + }, + MyVertex { + position: [0.9, 0.9], + }, + MyVertex { + position: [0.9, 0.8], + }, + MyVertex { + position: [0.8, 0.8], + }, + MyVertex { + position: [-0.9, 0.9], + }, + MyVertex { + position: [-0.7, 0.6], + }, + MyVertex { + position: [-0.5, 0.9], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); + + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window.inner_size().into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window.inner_size().into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let tcs = tcs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let tes = tes::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let tcs = tcs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let tes = tes::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(tcs), + PipelineShaderStageCreateInfo::new(tes), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::PatchList, + ..Default::default() + }), + tessellation_state: Some(TessellationState { + // Use a patch_control_points of 3, because we want to convert one + // *triangle* into lots of little ones. A value of 4 would convert a + // *rectangle* into lots of little triangles. + patch_control_points: 3, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState { + polygon_mode: PolygonMode::Line, + ..Default::default() + }), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(tcs), - PipelineShaderStageCreateInfo::new(tes), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::PatchList, - ..Default::default() - }), - tessellation_state: Some(TessellationState { - // Use a patch_control_points of 3, because we want to convert one *triangle* - // into lots of little ones. - // A value of 4 would convert a *rectangle* into lots of little triangles. - patch_control_points: 3, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState { - polygon_mode: PolygonMode::Line, - ..Default::default() - }), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain: false, - previous_frame_end, - }); + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -395,15 +399,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -439,7 +447,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 1, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 1, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -454,7 +464,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/texture-array/main.rs b/examples/texture-array/main.rs index ad553ffe12..7509cafaed 100644 --- a/examples/texture-array/main.rs +++ b/examples/texture-array/main.rs @@ -86,340 +86,345 @@ struct RenderContext { impl App { 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 { - flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, - enabled_extensions: required_extensions, - ..Default::default() - }, - ) - .unwrap(); - - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .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, - }) + let library = VulkanLibrary::new().unwrap(); + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + let instance = Instance::new( + library, + InstanceCreateInfo { + flags: InstanceCreateFlags::ENUMERATE_PORTABILITY, + enabled_extensions: required_extensions, + ..Default::default() + }, + ) .unwrap(); - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - let (device, mut queues) = Device::new( - physical_device, - DeviceCreateInfo { - enabled_extensions: device_extensions, - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .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, + }) + .unwrap(); + + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + let (device, mut queues) = Device::new( + physical_device, + DeviceCreateInfo { + enabled_extensions: device_extensions, + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], ..Default::default() - }], - ..Default::default() - }, - ) - .unwrap(); - - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( - device.clone(), - Default::default(), - )); - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - let vertices = [ - MyVertex { - position: [-0.2, -0.5], - }, - MyVertex { - position: [-0.5, 0.8], - }, - MyVertex { - position: [0.4, -0.5], - }, - MyVertex { - position: [0.5, 0.2], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator.clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let mut uploads = RecordingCommandBuffer::new( - command_buffer_allocator.clone(), - queue.queue_family_index(), - CommandBufferLevel::Primary, - CommandBufferBeginInfo { - usage: CommandBufferUsage::OneTimeSubmit, - ..Default::default() - }, - ) - .unwrap(); - - let texture = { - // Replace with your actual image array dimensions. - let format = Format::R8G8B8A8_SRGB; - let extent: [u32; 3] = [128, 128, 1]; - let array_layers = 3u32; - - let buffer_size = format.block_size() - * extent - .into_iter() - .map(|e| e as DeviceSize) - .product::() - * array_layers as DeviceSize; - let upload_buffer = Buffer::new_slice( + }, + ) + .unwrap(); + + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new( + device.clone(), + Default::default(), + )); + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + let vertices = [ + MyVertex { + position: [-0.2, -0.5], + }, + MyVertex { + position: [-0.5, 0.8], + }, + MyVertex { + position: [0.4, -0.5], + }, + MyVertex { + position: [0.5, 0.2], + }, + ]; + let vertex_buffer = Buffer::from_iter( memory_allocator.clone(), BufferCreateInfo { - usage: BufferUsage::TRANSFER_SRC, + usage: BufferUsage::VERTEX_BUFFER, ..Default::default() }, AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_HOST + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, ..Default::default() }, - buffer_size, + vertices, ) .unwrap(); - { - let mut image_data = &mut *upload_buffer.write().unwrap(); - - for png_bytes in [ - include_bytes!("square.png").as_slice(), - include_bytes!("star.png").as_slice(), - include_bytes!("asterisk.png").as_slice(), - ] { - let decoder = png::Decoder::new(png_bytes); - let mut reader = decoder.read_info().unwrap(); - reader.next_frame(image_data).unwrap(); - let info = reader.info(); - image_data = &mut image_data[(info.width * info.height * 4) as usize..]; - } - } - - let image = Image::new( - memory_allocator, - ImageCreateInfo { - image_type: ImageType::Dim2d, - format, - extent, - array_layers, - usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + let mut uploads = RecordingCommandBuffer::new( + command_buffer_allocator.clone(), + queue.queue_family_index(), + CommandBufferLevel::Primary, + CommandBufferBeginInfo { + usage: CommandBufferUsage::OneTimeSubmit, ..Default::default() }, - AllocationCreateInfo::default(), ) .unwrap(); - uploads - .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( - upload_buffer, - image.clone(), - )) + let texture = { + // Replace with your actual image array dimensions. + let format = Format::R8G8B8A8_SRGB; + let extent: [u32; 3] = [128, 128, 1]; + let array_layers = 3u32; + + let buffer_size = format.block_size() + * extent + .into_iter() + .map(|e| e as DeviceSize) + .product::() + * array_layers as DeviceSize; + let upload_buffer = Buffer::new_slice( + memory_allocator.clone(), + BufferCreateInfo { + usage: BufferUsage::TRANSFER_SRC, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_HOST + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + buffer_size, + ) + .unwrap(); + + { + let mut image_data = &mut *upload_buffer.write().unwrap(); + + for png_bytes in [ + include_bytes!("square.png").as_slice(), + include_bytes!("star.png").as_slice(), + include_bytes!("asterisk.png").as_slice(), + ] { + let decoder = png::Decoder::new(png_bytes); + let mut reader = decoder.read_info().unwrap(); + reader.next_frame(image_data).unwrap(); + let info = reader.info(); + image_data = &mut image_data[(info.width * info.height * 4) as usize..]; + } + } + + let image = Image::new( + memory_allocator, + ImageCreateInfo { + image_type: ImageType::Dim2d, + format, + extent, + array_layers, + usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED, + ..Default::default() + }, + AllocationCreateInfo::default(), + ) .unwrap(); - ImageView::new_default(image).unwrap() - }; + uploads + .copy_buffer_to_image(CopyBufferToImageInfo::buffer_image( + upload_buffer, + image.clone(), + )) + .unwrap(); - let sampler = Sampler::new(device.clone(), SamplerCreateInfo::simple_repeat_linear()).unwrap(); + ImageView::new_default(image).unwrap() + }; - let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); + let sampler = + Sampler::new(device.clone(), SamplerCreateInfo::simple_repeat_linear()).unwrap(); - App { - instance, - device, - queue, - descriptor_set_allocator, - command_buffer_allocator, - vertex_buffer, - texture, - sampler, - rcx: None, - } + let _ = uploads.end().unwrap().execute(queue.clone()).unwrap(); + + App { + instance, + device, + queue, + descriptor_set_allocator, + command_buffer_allocator, + vertex_buffer, + texture, + sampler, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - let (swapchain, images) = { - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + let (swapchain, images) = { + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + min_image_count: surface_capabilities.min_image_count.max(2), + image_format, + image_extent: window_size.into(), + image_usage: ImageUsage::COLOR_ATTACHMENT, + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - Swapchain::new( + let render_pass = vulkano::single_pass_renderpass!( self.device.clone(), - surface, - SwapchainCreateInfo { - min_image_count: surface_capabilities.min_image_count.max(2), - image_format, - image_extent: window_size.into(), - image_usage: ImageUsage::COLOR_ATTACHMENT, - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), - ..Default::default() + attachments: { + color: { + format: swapchain.image_format(), + samples: 1, + load_op: Clear, + store_op: Store, + }, }, - ) - .unwrap() - }; - - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - color: { - format: swapchain.image_format(), - samples: 1, - load_op: Clear, - store_op: Store, + pass: { + color: [color], + depth_stencil: {}, }, - }, - pass: { - color: [color], - depth_stencil: {}, - }, - ) - .unwrap(); + ) + .unwrap(); - let framebuffers = window_size_dependent_setup(&images, &render_pass); + let framebuffers = window_size_dependent_setup(&images, &render_pass); - let pipeline = { - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") + let pipeline = { + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + let layout = PipelineLayout::new( + self.device.clone(), + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) .unwrap(); - let fs = fs::load(self.device.clone()) + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + vertex_input_state: Some(vertex_input_state), + input_assembly_state: Some(InputAssemblyState { + topology: PrimitiveTopology::TriangleStrip, + ..Default::default() + }), + viewport_state: Some(ViewportState::default()), + rasterization_state: Some(RasterizationState::default()), + multisample_state: Some(MultisampleState::default()), + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState { + blend: Some(AttachmentBlend::alpha()), + ..Default::default() + }, + )), + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) .unwrap() - .entry_point("main") - .unwrap(); - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; - let layout = PipelineLayout::new( - self.device.clone(), - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), + }; + + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + let layout = &pipeline.layout().set_layouts()[0]; + let descriptor_set = DescriptorSet::new( + self.descriptor_set_allocator.clone(), + layout.clone(), + [ + WriteDescriptorSet::sampler(0, self.sampler.clone()), + WriteDescriptorSet::image_view(1, self.texture.clone()), + ], + [], ) .unwrap(); - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - vertex_input_state: Some(vertex_input_state), - input_assembly_state: Some(InputAssemblyState { - topology: PrimitiveTopology::TriangleStrip, - ..Default::default() - }), - viewport_state: Some(ViewportState::default()), - rasterization_state: Some(RasterizationState::default()), - multisample_state: Some(MultisampleState::default()), - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState { - blend: Some(AttachmentBlend::alpha()), - ..Default::default() - }, - )), - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - let layout = &pipeline.layout().set_layouts()[0]; - let descriptor_set = DescriptorSet::new( - self.descriptor_set_allocator.clone(), - layout.clone(), - [ - WriteDescriptorSet::sampler(0, self.sampler.clone()), - WriteDescriptorSet::image_view(1, self.texture.clone()), - ], - [], - ) - .unwrap(); - - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - descriptor_set, - recreate_swapchain: false, - previous_frame_end, - }); + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + descriptor_set, + recreate_swapchain: false, + previous_frame_end, + }); } fn window_event( @@ -461,15 +466,19 @@ impl ApplicationHandler for App { 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}"), - }; + 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; @@ -512,7 +521,9 @@ impl ApplicationHandler for App { .unwrap(); unsafe { - builder.draw(self.vertex_buffer.len() as u32, 3, 0, 0).unwrap(); + builder + .draw(self.vertex_buffer.len() as u32, 3, 0, 0) + .unwrap(); } builder.end_render_pass(Default::default()).unwrap(); @@ -527,7 +538,10 @@ impl ApplicationHandler for App { .unwrap() .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/triangle-util/main.rs b/examples/triangle-util/main.rs index 0cab3f355d..cbd3236def 100644 --- a/examples/triangle-util/main.rs +++ b/examples/triangle-util/main.rs @@ -68,272 +68,272 @@ struct RenderContext { impl App { fn new(_event_loop: &EventLoop<()>) -> Self { - let context = VulkanoContext::new(VulkanoConfig::default()); - - // Manages any windows and their rendering. - let windows = VulkanoWindows::default(); - - // Some little debug infos. - println!( - "Using device: {} (type: {:?})", - context.device().physical_device().properties().device_name, - context.device().physical_device().properties().device_type, - ); - - // Before we can start creating and recording command buffers, we need a way of allocating - // them. Vulkano provides a command buffer allocator, which manages raw Vulkan command pools - // underneath and provides a safe interface for them. - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - context.device().clone(), - Default::default(), - )); - - // We now create a buffer that will store the shape of our triangle. - let vertices = [ - MyVertex { - position: [-0.5, -0.25], - }, - MyVertex { - position: [0.0, 0.5], - }, - MyVertex { - position: [0.25, -0.1], - }, - ]; - let vertex_buffer = Buffer::from_iter( - context.memory_allocator().clone(), - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - App { - context, - windows, - command_buffer_allocator, - vertex_buffer, - rcx: None, - } + let context = VulkanoContext::new(VulkanoConfig::default()); + + // Manages any windows and their rendering. + let windows = VulkanoWindows::default(); + + // Some little debug infos. + println!( + "Using device: {} (type: {:?})", + context.device().physical_device().properties().device_name, + context.device().physical_device().properties().device_type, + ); + + // Before we can start creating and recording command buffers, we need a way of allocating + // them. Vulkano provides a command buffer allocator, which manages raw Vulkan command + // pools underneath and provides a safe interface for them. + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + context.device().clone(), + Default::default(), + )); + + // We now create a buffer that will store the shape of our triangle. + let vertices = [ + MyVertex { + position: [-0.5, -0.25], + }, + MyVertex { + position: [0.0, 0.5], + }, + MyVertex { + position: [0.25, -0.1], + }, + ]; + let vertex_buffer = Buffer::from_iter( + context.memory_allocator().clone(), + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); + + App { + context, + windows, + command_buffer_allocator, + vertex_buffer, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - if let Some(primary_window_id) = self.windows.primary_window_id() { - self.windows.remove_renderer(primary_window_id); - } - - self.windows.create_window(event_loop, &self.context, &Default::default(), |_| {}); - let window_renderer = self.windows.get_primary_renderer_mut().unwrap(); - let window_size = window_renderer.window().inner_size(); - - // The next step is to create the shaders. - // - // The raw shader creation API provided by the vulkano library is unsafe for various reasons, - // so The `shader!` macro provides a way to generate a Rust module from GLSL source - in the - // example below, the source is provided as a string input directly to the shader, but a path - // to a source file can be provided as well. Note that the user must specify the type of shader - // (e.g. "vertex", "fragment", etc.) using the `ty` option of the macro. - // - // The items generated by the `shader!` macro include a `load` function which loads the shader - // using an input logical device. The module also includes type definitions for layout - // structures defined in the shader source, for example uniforms and push constants. - // - // A more detailed overview of what the `shader!` macro generates can be found in the - // vulkano-shaders crate docs. You can view them at https://docs.rs/vulkano-shaders/ - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 - - layout(location = 0) in vec2 position; - - void main() { - gl_Position = vec4(position, 0.0, 1.0); - } - ", + if let Some(primary_window_id) = self.windows.primary_window_id() { + self.windows.remove_renderer(primary_window_id); } - } - - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 - layout(location = 0) out vec4 f_color; + self.windows + .create_window(event_loop, &self.context, &Default::default(), |_| {}); + let window_renderer = self.windows.get_primary_renderer_mut().unwrap(); + let window_size = window_renderer.window().inner_size(); - void main() { - f_color = vec4(1.0, 0.0, 0.0, 1.0); - } - ", + // The next step is to create the shaders. + // + // The raw shader creation API provided by the vulkano library is unsafe for various + // reasons, so The `shader!` macro provides a way to generate a Rust module from GLSL + // source - in the example below, the source is provided as a string input directly to the + // shader, but a path to a source file can be provided as well. Note that the user must + // specify the type of shader (e.g. "vertex", "fragment", etc.) using the `ty` option of + // the macro. + // + // The items generated by the `shader!` macro include a `load` function which loads the + // shader using an input logical device. The module also includes type definitions for + // layout structures defined in the shader source, for example uniforms and push constants. + // + // A more detailed overview of what the `shader!` macro generates can be found in the + // vulkano-shaders crate docs. You can view them at https://docs.rs/vulkano-shaders/ + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 + + layout(location = 0) in vec2 position; + + void main() { + gl_Position = vec4(position, 0.0, 1.0); + } + ", + } } - } - // The next step is to create a *render pass*, which is an object that describes where the - // output of the graphics pipeline will go. It describes the layout of the images where the - // colors, depth and/or stencil information will be written. - let render_pass = vulkano::single_pass_renderpass!( - self.context.device().clone(), - attachments: { - // `color` is a custom name we give to the first and only attachment. - color: { - // `format: ` indicates the type of the format of the image. This has to be one - // of the types of the `vulkano::format` module (or alternatively one of your - // structs that implements the `FormatDesc` trait). Here we use the same format as - // the swapchain. - format: window_renderer.swapchain_format(), - // `samples: 1` means that we ask the GPU to use one sample to determine the value - // of each pixel in the color attachment. We could use a larger value - // (multisampling) for antialiasing. An example of this can be found in - // msaa-renderpass.rs. - samples: 1, - // `load_op: Clear` means that we ask the GPU to clear the content of this - // attachment at the start of the drawing. - load_op: Clear, - // `store_op: Store` means that we ask the GPU to store the output of the draw in - // the actual image. We could also ask it to discard the result. - store_op: Store, - }, - }, - pass: { - // We use the attachment named `color` as the one and only color attachment. - color: [color], - // No depth-stencil attachment is indicated with empty brackets. - depth_stencil: {}, - }, - ) - .unwrap(); - - // The render pass we created above only describes the layout of our framebuffers. Before we - // can draw we also need to create the actual framebuffers. - // - // Since we need to draw to multiple images, we are going to create a different framebuffer for - // each image. - let framebuffers = window_size_dependent_setup( - window_renderer.swapchain_image_views(), - &render_pass, - ); - - // Before we draw, we have to create what is called a **pipeline**. A pipeline describes how - // a GPU operation is to be performed. It is similar to an OpenGL program, but it also contains - // many settings for customization, all baked into a single object. For drawing, we create - // a **graphics** pipeline, but there are also other types of pipeline. - let pipeline = { - // First, we load the shaders that the pipeline will use: - // the vertex shader and the fragment shader. - // - // A Vulkan shader can in theory contain multiple entry points, so we have to specify which - // one. - let vs = vs::load(self.context.device().clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.context.device().clone()) - .unwrap() - .entry_point("main") - .unwrap(); + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - // Automatically generate a vertex input state from the vertex shader's input interface, - // that takes a single vertex buffer containing `Vertex` structs. - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + layout(location = 0) out vec4 f_color; - // Make a list of the shader stages that the pipeline will have. - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; + void main() { + f_color = vec4(1.0, 0.0, 0.0, 1.0); + } + ", + } + } - // We must now create a **pipeline layout** object, which describes the locations and types - // of descriptor sets and push constants used by the shaders in the pipeline. - // - // Multiple pipelines can share a common layout object, which is more efficient. - // The shaders in a pipeline must use a subset of the resources described in its pipeline - // layout, but the pipeline layout is allowed to contain resources that are not present in - // the shaders; they can be used by shaders in other pipelines that share the same - // layout. Thus, it is a good idea to design shaders so that many pipelines have - // common resource locations, which allows them to share pipeline layouts. - let layout = PipelineLayout::new( + // The next step is to create a *render pass*, which is an object that describes where the + // output of the graphics pipeline will go. It describes the layout of the images where the + // colors, depth and/or stencil information will be written. + let render_pass = vulkano::single_pass_renderpass!( self.context.device().clone(), - // Since we only have one pipeline in this example, and thus one pipeline layout, - // we automatically generate the creation info for it from the resources used in the - // shaders. In a real application, you would specify this information manually so that - // you can re-use one layout in multiple pipelines. - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.context.device().clone()) - .unwrap(), + attachments: { + // `color` is a custom name we give to the first and only attachment. + color: { + // `format: ` indicates the type of the format of the image. This has to be + // one of the types of the `vulkano::format` module (or alternatively one of + // your structs that implements the `FormatDesc` trait). Here we use the same + // format as the swapchain. + format: window_renderer.swapchain_format(), + // `samples: 1` means that we ask the GPU to use one sample to determine the + // value of each pixel in the color attachment. We could use a larger value + // (multisampling) for antialiasing. An example of this can be found in + // msaa-renderpass.rs. + samples: 1, + // `load_op: Clear` means that we ask the GPU to clear the content of this + // attachment at the start of the drawing. + load_op: Clear, + // `store_op: Store` means that we ask the GPU to store the output of the draw + // in the actual image. We could also ask it to discard the result. + store_op: Store, + }, + }, + pass: { + // We use the attachment named `color` as the one and only color attachment. + color: [color], + // No depth-stencil attachment is indicated with empty brackets. + depth_stencil: {}, + }, ) .unwrap(); - // We have to indicate which subpass of which render pass this pipeline is going to be used - // in. The pipeline will only be usable from this particular subpass. - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + // The render pass we created above only describes the layout of our framebuffers. Before + // we can draw we also need to create the actual framebuffers. + // + // Since we need to draw to multiple images, we are going to create a different framebuffer + // for each image. + let framebuffers = + window_size_dependent_setup(window_renderer.swapchain_image_views(), &render_pass); + + // Before we draw, we have to create what is called a **pipeline**. A pipeline describes + // how a GPU operation is to be performed. It is similar to an OpenGL program, but it also + // contains many settings for customization, all baked into a single object. For drawing, + // we create a **graphics** pipeline, but there are also other types of pipeline. + let pipeline = { + // First, we load the shaders that the pipeline will use: the vertex shader and the + // fragment shader. + // + // A Vulkan shader can in theory contain multiple entry points, so we have to specify + // which one. + let vs = vs::load(self.context.device().clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.context.device().clone()) + .unwrap() + .entry_point("main") + .unwrap(); - // Finally, create the pipeline. - GraphicsPipeline::new( - self.context.device().clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - // How vertex data is read from the vertex buffers into the vertex shader. - vertex_input_state: Some(vertex_input_state), - // How vertices are arranged into primitive shapes. - // The default primitive shape is a triangle. - input_assembly_state: Some(InputAssemblyState::default()), - // How primitives are transformed and clipped to fit the framebuffer. - // We use a resizable viewport, set to draw over the entire window. - viewport_state: Some(ViewportState::default()), - // How polygons are culled and converted into a raster of pixels. - // The default value does not perform any culling. - rasterization_state: Some(RasterizationState::default()), - // How multiple fragment shader samples are converted to a single pixel value. - // The default value does not perform any multisampling. - multisample_state: Some(MultisampleState::default()), - // How pixel values are combined with the values already present in the framebuffer. - // The default value overwrites the old value with the new one, without any - // blending. - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - // Dynamic states allows us to specify parts of the pipeline settings when - // recording the command buffer, before we perform drawing. - // Here, we specify that the viewport should be dynamic. - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - // Dynamic viewports allow us to recreate just the viewport when the window is resized. - // Otherwise we would have to recreate the whole pipeline. - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - // In the `window_event` handler below we are going to submit commands to the GPU. Submitting a command produces - // an object that implements the `GpuFuture` trait, which holds the resources for as long as - // they are in use by the GPU. - - self.rcx = Some(RenderContext { - render_pass, - framebuffers, - pipeline, - viewport, - }); + // Automatically generate a vertex input state from the vertex shader's input + // interface, that takes a single vertex buffer containing `Vertex` structs. + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + + // Make a list of the shader stages that the pipeline will have. + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; + + // We must now create a **pipeline layout** object, which describes the locations and + // types of descriptor sets and push constants used by the shaders in the pipeline. + // + // Multiple pipelines can share a common layout object, which is more efficient. The + // shaders in a pipeline must use a subset of the resources described in its pipeline + // layout, but the pipeline layout is allowed to contain resources that are not present + // in the shaders; they can be used by shaders in other pipelines that share the same + // layout. Thus, it is a good idea to design shaders so that many pipelines have common + // resource locations, which allows them to share pipeline layouts. + let layout = PipelineLayout::new( + self.context.device().clone(), + // Since we only have one pipeline in this example, and thus one pipeline layout, + // we automatically generate the creation info for it from the resources used in + // the shaders. In a real application, you would specify this information manually + // so that you can re-use one layout in multiple pipelines. + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.context.device().clone()) + .unwrap(), + ) + .unwrap(); + + // We have to indicate which subpass of which render pass this pipeline is going to be + // used in. The pipeline will only be usable from this particular subpass. + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + // Finally, create the pipeline. + GraphicsPipeline::new( + self.context.device().clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + // How vertex data is read from the vertex buffers into the vertex shader. + vertex_input_state: Some(vertex_input_state), + // How vertices are arranged into primitive shapes. The default primitive shape + // is a triangle. + input_assembly_state: Some(InputAssemblyState::default()), + // How primitives are transformed and clipped to fit the framebuffer. We use a + // resizable viewport, set to draw over the entire window. + viewport_state: Some(ViewportState::default()), + // How polygons are culled and converted into a raster of pixels. The default + // value does not perform any culling. + rasterization_state: Some(RasterizationState::default()), + // How multiple fragment shader samples are converted to a single pixel value. + // The default value does not perform any multisampling. + multisample_state: Some(MultisampleState::default()), + // How pixel values are combined with the values already present in the + // framebuffer. The default value overwrites the old value with the new one, + // without any blending. + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + // Dynamic states allows us to specify parts of the pipeline settings when + // recording the command buffer, before we perform drawing. Here, we specify + // that the viewport should be dynamic. + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) + .unwrap() + }; + + // Dynamic viewports allow us to recreate just the viewport when the window is resized. + // Otherwise we would have to recreate the whole pipeline. + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + // In the `window_event` handler below we are going to submit commands to the GPU. + // Submitting a command produces an object that implements the `GpuFuture` trait, which + // holds the resources for as long as they are in use by the GPU. + + self.rcx = Some(RenderContext { + render_pass, + framebuffers, + pipeline, + viewport, + }); } fn window_event( @@ -368,15 +368,13 @@ impl ApplicationHandler for App { // on the window size. In this example that // includes the swapchain, the framebuffers // and the dynamic state viewport. - rcx.framebuffers = window_size_dependent_setup( - swapchain_images, - &rcx.render_pass, - ); + rcx.framebuffers = + window_size_dependent_setup(swapchain_images, &rcx.render_pass); }) .unwrap(); - // In order to draw, we have to record a *command buffer*. The command buffer object - // holds the list of commands that are going to be executed. + // In order to draw, we have to record a *command buffer*. The command buffer + // object holds the list of commands that are going to be executed. // // Recording a command buffer is an expensive operation (usually a few hundred // microseconds), but it is known to be a hot path in the driver and is expected to @@ -412,9 +410,9 @@ impl ApplicationHandler for App { ) }, SubpassBeginInfo { - // The contents of the first (and only) subpass. - // This can be either `Inline` or `SecondaryCommandBuffers`. - // The latter is a bit more advanced and is not covered here. + // The contents of the first (and only) subpass. This can be either + // `Inline` or `SecondaryCommandBuffers`. The latter is a bit more + // advanced and is not covered here. contents: SubpassContents::Inline, ..Default::default() }, @@ -451,14 +449,14 @@ impl ApplicationHandler for App { .unwrap() .boxed(); - // The color output is now expected to contain our triangle. But in order to - // show it on the screen, we have to *present* the image by calling - // `present` on the window renderer. + // The color output is now expected to contain our triangle. But in order to show + // it on the screen, we have to *present* the image by calling `present` on the + // window renderer. // // This function does not actually present the image immediately. Instead it - // submits a present command at the end of the queue. This means that it will - // only be presented once the GPU has finished executing the command buffer - // that draws the triangle. + // submits a present command at the end of the queue. This means that it will only + // be presented once the GPU has finished executing the command buffer that draws + // the triangle. window_renderer.present(future, false); } _ => {} diff --git a/examples/triangle-v1_3/main.rs b/examples/triangle-v1_3/main.rs index a2177d9bdd..2a74e1ed53 100644 --- a/examples/triangle-v1_3/main.rs +++ b/examples/triangle-v1_3/main.rs @@ -82,466 +82,475 @@ struct RenderContext { impl App { fn new(event_loop: &EventLoop<()>) -> Self { - let library = VulkanLibrary::new().unwrap(); - - // The first step of any Vulkan program is to create an instance. - // - // When we create an instance, we have to pass a list of extensions that we want to enable. - // - // All the window-drawing functionalities are part of non-core extensions that we need to - // enable manually. To do so, we ask `Surface` for the list of extensions required to draw to - // a window. - let required_extensions = Surface::required_extensions(event_loop).unwrap(); - - // Now creating the instance. - 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, - ..Default::default() - }, - ) - .unwrap(); - - // Choose device extensions that we're going to use. In order to present images to a surface, - // we need a `Swapchain`, which is provided by the `khr_swapchain` extension. - let mut device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - - // We then choose which physical device to use. First, we enumerate all the available physical - // devices, then apply filters to narrow them down to those that can support our needs. - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .filter(|p| { - // For this example, we require at least Vulkan 1.3, or a device that has the - // `khr_dynamic_rendering` extension available. - p.api_version() >= Version::V1_3 || p.supported_extensions().khr_dynamic_rendering - }) - .filter(|p| { - // Some devices may not support the extensions or features that your application, or - // report properties and limits that are not sufficient for your application. These - // should be filtered out here. - p.supported_extensions().contains(&device_extensions) - }) - .filter_map(|p| { - // For each physical device, we try to find a suitable queue family that will execute - // our draw commands. - // - // Devices can provide multiple queues to run commands in parallel (for example a draw - // queue and a compute queue), similar to CPU threads. This is something you have to - // have to manage manually in Vulkan. Queues of the same type belong to the same queue - // family. + let library = VulkanLibrary::new().unwrap(); + + // The first step of any Vulkan program is to create an instance. + // + // When we create an instance, we have to pass a list of extensions that we want to enable. + // + // All the window-drawing functionalities are part of non-core extensions that we need to + // enable manually. To do so, we ask `Surface` for the list of extensions required to draw + // to a window. + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + + // Now creating the instance. + 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, + ..Default::default() + }, + ) + .unwrap(); + + // Choose device extensions that we're going to use. In order to present images to a + // surface, we need a `Swapchain`, which is provided by the `khr_swapchain` extension. + let mut device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + + // We then choose which physical device to use. First, we enumerate all the available + // physical devices, then apply filters to narrow them down to those that can support our + // needs. + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .filter(|p| { + // For this example, we require at least Vulkan 1.3, or a device that has the + // `khr_dynamic_rendering` extension available. + p.api_version() >= Version::V1_3 || p.supported_extensions().khr_dynamic_rendering + }) + .filter(|p| { + // Some devices may not support the extensions or features that your application, + // or report properties and limits that are not sufficient for your application. + // These should be filtered out here. + p.supported_extensions().contains(&device_extensions) + }) + .filter_map(|p| { + // For each physical device, we try to find a suitable queue family that will + // execute our draw commands. + // + // Devices can provide multiple queues to run commands in parallel (for example a + // draw queue and a compute queue), similar to CPU threads. This is something you + // have to have to manage manually in Vulkan. Queues of the same type belong to the + // same queue family. + // + // Here, we look for a single queue family that is suitable for our purposes. In a + // real-world application, you may want to use a separate dedicated transfer queue + // to handle data transfers in parallel with graphics operations. You may also need + // a separate queue for compute operations, if your application uses those. + p.queue_family_properties() + .iter() + .enumerate() + .position(|(i, q)| { + // We select a queue family that supports graphics operations. When drawing + // to a window surface, as we do in this example, we also need to check + // that queues in this queue family are capable of presenting images to the + // surface. + q.queue_flags.intersects(QueueFlags::GRAPHICS) + && p.presentation_support(i as u32, event_loop).unwrap() + }) + // The code here searches for the first queue family that is suitable. If none + // is found, `None` is returned to `filter_map`, which disqualifies this + // physical device. + .map(|i| (p, i as u32)) + }) + // All the physical devices that pass the filters above are suitable for the + // application. However, not every device is equal, some are preferred over others. + // Now, we assign each physical device a score, and pick the device with the lowest + // ("best") score. // - // Here, we look for a single queue family that is suitable for our purposes. In a - // real-world application, you may want to use a separate dedicated transfer queue to - // handle data transfers in parallel with graphics operations. You may also need a - // separate queue for compute operations, if your application uses those. - p.queue_family_properties() - .iter() - .enumerate() - .position(|(i, q)| { - // We select a queue family that supports graphics operations. When drawing to - // a window surface, as we do in this example, we also need to check that - // queues in this queue family are capable of presenting images to the surface. - q.queue_flags.intersects(QueueFlags::GRAPHICS) - && p.presentation_support(i as u32, event_loop).unwrap() - }) - // The code here searches for the first queue family that is suitable. If none is - // found, `None` is returned to `filter_map`, which disqualifies this physical - // device. - .map(|i| (p, i as u32)) - }) - // All the physical devices that pass the filters above are suitable for the application. - // However, not every device is equal, some are preferred over others. Now, we assign each - // physical device a score, and pick the device with the lowest ("best") score. + // In this example, we simply select the best-scoring device to use in the application. + // In a real-world setting, you may want to use the best-scoring device only as a + // "default" or "recommended" device, and let the user choose the device themself. + .min_by_key(|(p, _)| { + // We assign a lower score to device types that are likely to be faster/better. + 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"); + + // Some little debug infos. + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + // If the selected device doesn't have Vulkan 1.3 available, then we need to enable the + // `khr_dynamic_rendering` extension manually. This extension became a core part of Vulkan + // in version 1.3 and later, so it's always available then and it does not need to be + // enabled. We can be sure that this extension will be available on the selected physical + // device, because we filtered out unsuitable devices in the device selection code above. + if physical_device.api_version() < Version::V1_3 { + device_extensions.khr_dynamic_rendering = true; + } + + // Now initializing the device. This is probably the most important object of Vulkan. // - // In this example, we simply select the best-scoring device to use in the application. - // In a real-world setting, you may want to use the best-scoring device only as a "default" - // or "recommended" device, and let the user choose the device themself. - .min_by_key(|(p, _)| { - // We assign a lower score to device types that are likely to be faster/better. - 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"); - - // Some little debug infos. - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - // If the selected device doesn't have Vulkan 1.3 available, then we need to enable the - // `khr_dynamic_rendering` extension manually. This extension became a core part of Vulkan - // in version 1.3 and later, so it's always available then and it does not need to be enabled. - // We can be sure that this extension will be available on the selected physical device, - // because we filtered out unsuitable devices in the device selection code above. - if physical_device.api_version() < Version::V1_3 { - device_extensions.khr_dynamic_rendering = true; - } + // An iterator of created queues is returned by the function alongside the device. + let (device, mut queues) = Device::new( + // Which physical device to connect to. + physical_device, + DeviceCreateInfo { + // The list of queues that we are going to use. Here we only use one queue, from + // the previously chosen queue family. + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + + // A list of optional features and extensions that our program needs to work + // correctly. Some parts of the Vulkan specs are optional and must be enabled + // manually at device creation. In this example the only things we are going to + // need are the `khr_swapchain` extension that allows us to draw to a window, and + // `khr_dynamic_rendering` if we don't have Vulkan 1.3 available. + enabled_extensions: device_extensions, + + // In order to render with Vulkan 1.3's dynamic rendering, we need to enable it + // here. Otherwise, we are only allowed to render with a render pass object, as in + // the standard triangle example. The feature is required to be supported by the + // device if it supports Vulkan 1.3 and higher, or if the `khr_dynamic_rendering` + // extension is available, so we don't need to check for support. + enabled_features: DeviceFeatures { + dynamic_rendering: true, + ..DeviceFeatures::empty() + }, - // Now initializing the device. This is probably the most important object of Vulkan. - // - // An iterator of created queues is returned by the function alongside the device. - let (device, mut queues) = Device::new( - // Which physical device to connect to. - physical_device, - DeviceCreateInfo { - // The list of queues that we are going to use. Here we only use one queue, from the - // previously chosen queue family. - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, ..Default::default() - }], - - // A list of optional features and extensions that our program needs to work correctly. - // Some parts of the Vulkan specs are optional and must be enabled manually at device - // creation. In this example the only things we are going to need are the - // `khr_swapchain` extension that allows us to draw to a window, and - // `khr_dynamic_rendering` if we don't have Vulkan 1.3 available. - enabled_extensions: device_extensions, - - // In order to render with Vulkan 1.3's dynamic rendering, we need to enable it here. - // Otherwise, we are only allowed to render with a render pass object, as in the - // standard triangle example. The feature is required to be supported by the device if - // it supports Vulkan 1.3 and higher, or if the `khr_dynamic_rendering` extension is - // available, so we don't need to check for support. - enabled_features: DeviceFeatures { - dynamic_rendering: true, - ..DeviceFeatures::empty() }, + ) + .unwrap(); - ..Default::default() - }, - ) - .unwrap(); - - // Since we can request multiple queues, the `queues` variable is in fact an iterator. We only - // use one queue in this example, so we just retrieve the first and only element of the - // iterator. - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - - // Before we can start creating and recording command buffers, we need a way of allocating - // them. Vulkano provides a command buffer allocator, which manages raw Vulkan command pools - // underneath and provides a safe interface for them. - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - // We now create a buffer that will store the shape of our triangle. - let vertices = [ - MyVertex { - position: [-0.5, -0.25], - }, - MyVertex { - position: [0.0, 0.5], - }, - MyVertex { - position: [0.25, -0.1], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - rcx: None, - } + // Since we can request multiple queues, the `queues` variable is in fact an iterator. We + // only use one queue in this example, so we just retrieve the first and only element of + // the iterator. + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + + // Before we can start creating and recording command buffers, we need a way of allocating + // them. Vulkano provides a command buffer allocator, which manages raw Vulkan command + // pools underneath and provides a safe interface for them. + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + // We now create a buffer that will store the shape of our triangle. + let vertices = [ + MyVertex { + position: [-0.5, -0.25], + }, + MyVertex { + position: [0.0, 0.5], + }, + MyVertex { + position: [0.25, -0.1], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); + + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + rcx: None, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - // The objective of this example is to draw a triangle on a window. To do so, we first need to - // create the window. We use the `WindowBuilder` from the `winit` crate to do that here. - // - // Before we can render to a window, we must first create a `vulkano::swapchain::Surface` - // object from it, which represents the drawable surface of a window. For that we must wrap the - // `winit::window::Window` in an `Arc`. - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - // Before we can draw on the surface, we have to create what is called a swapchain. Creating a - // swapchain allocates the color buffers that will contain the image that will ultimately be - // visible on the screen. These images are returned alongside the swapchain. - let (swapchain, images) = { - // Querying the capabilities of the surface. When we create the swapchain we can only pass - // values that are allowed by the capabilities. - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); + // The objective of this example is to draw a triangle on a window. To do so, we first need + // to create the window. We use the `WindowBuilder` from the `winit` crate to do that here. + // + // Before we can render to a window, we must first create a `vulkano::swapchain::Surface` + // object from it, which represents the drawable surface of a window. For that we must wrap + // the `winit::window::Window` in an `Arc`. + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + // Before we can draw on the surface, we have to create what is called a swapchain. + // Creating a swapchain allocates the color buffers that will contain the image that will + // ultimately be visible on the screen. These images are returned alongside the swapchain. + let (swapchain, images) = { + // Querying the capabilities of the surface. When we create the swapchain we can only + // pass values that are allowed by the capabilities. + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); - // Choosing the internal format that the images will have. - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; - - // Please take a look at the docs for the meaning of the parameters we didn't mention. - Swapchain::new( - self.device.clone(), - surface, - SwapchainCreateInfo { - // Some drivers report an `min_image_count` of 1, but fullscreen mode requires at - // least 2. Therefore we must ensure the count is at least 2, otherwise the program - // would crash when entering fullscreen mode on those drivers. - min_image_count: surface_capabilities.min_image_count.max(2), - - image_format, - - // The size of the window, only used to initially setup the swapchain. - // - // NOTE: - // On some drivers the swapchain extent is specified by - // `surface_capabilities.current_extent` and the swapchain size must use this - // extent. This extent is always the same as the window size. - // - // However, other drivers don't specify a value, i.e. - // `surface_capabilities.current_extent` is `None`. These drivers will allow - // anything, but the only sensible value is the window size. - // - // Both of these cases need the swapchain to use the window size, so we just - // use that. - image_extent: window_size.into(), - - image_usage: ImageUsage::COLOR_ATTACHMENT, - - // The alpha mode indicates how the alpha value of the final image will behave. For - // example, you can choose whether the window will be opaque or transparent. - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), + // Choosing the internal format that the images will have. + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + // Please take a look at the docs for the meaning of the parameters we didn't mention. + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + // Some drivers report an `min_image_count` of 1, but fullscreen mode requires + // at least 2. Therefore we must ensure the count is at least 2, otherwise the + // program would crash when entering fullscreen mode on those drivers. + min_image_count: surface_capabilities.min_image_count.max(2), + + image_format, + + // The size of the window, only used to initially setup the swapchain. + // + // NOTE: + // On some drivers the swapchain extent is specified by + // `surface_capabilities.current_extent` and the swapchain size must use this + // extent. This extent is always the same as the window size. + // + // However, other drivers don't specify a value, i.e. + // `surface_capabilities.current_extent` is `None`. These drivers will allow + // anything, but the only sensible value is the window size. + // + // Both of these cases need the swapchain to use the window size, so we just + // use that. + image_extent: window_size.into(), + + image_usage: ImageUsage::COLOR_ATTACHMENT, + + // The alpha mode indicates how the alpha value of the final image will behave. + // For example, you can choose whether the window will be opaque or + // transparent. + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), + + ..Default::default() + }, + ) + .unwrap() + }; - ..Default::default() - }, - ) - .unwrap() - }; - - // When creating the swapchain, we only created plain images. To use them as an attachment for - // rendering, we must wrap then in an image view. - // - // Since we need to draw to multiple images, we are going to create a different image view for - // each image. - let attachment_image_views = window_size_dependent_setup(&images); - - // The next step is to create the shaders. - // - // The raw shader creation API provided by the vulkano library is unsafe for various reasons, - // so The `shader!` macro provides a way to generate a Rust module from GLSL source - in the - // example below, the source is provided as a string input directly to the shader, but a path - // to a source file can be provided as well. Note that the user must specify the type of shader - // (e.g. "vertex", "fragment", etc.) using the `ty` option of the macro. - // - // The items generated by the `shader!` macro include a `load` function which loads the shader - // using an input logical device. The module also includes type definitions for layout - // structures defined in the shader source, for example uniforms and push constants. - // - // A more detailed overview of what the `shader!` macro generates can be found in the - // vulkano-shaders crate docs. You can view them at https://docs.rs/vulkano-shaders/ - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 - - layout(location = 0) in vec2 position; - - void main() { - gl_Position = vec4(position, 0.0, 1.0); - } - ", + // When creating the swapchain, we only created plain images. To use them as an attachment + // for rendering, we must wrap then in an image view. + // + // Since we need to draw to multiple images, we are going to create a different image view + // for each image. + let attachment_image_views = window_size_dependent_setup(&images); + + // The next step is to create the shaders. + // + // The raw shader creation API provided by the vulkano library is unsafe for various + // reasons, so The `shader!` macro provides a way to generate a Rust module from GLSL + // source - in the example below, the source is provided as a string input directly to the + // shader, but a path to a source file can be provided as well. Note that the user must + // specify the type of shader (e.g. "vertex", "fragment", etc.) using the `ty` option of + // the macro. + // + // The items generated by the `shader!` macro include a `load` function which loads the + // shader using an input logical device. The module also includes type definitions for + // layout structures defined in the shader source, for example uniforms and push constants. + // + // A more detailed overview of what the `shader!` macro generates can be found in the + // vulkano-shaders crate docs. You can view them at https://docs.rs/vulkano-shaders/ + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 + + layout(location = 0) in vec2 position; + + void main() { + gl_Position = vec4(position, 0.0, 1.0); + } + ", + } } - } - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - layout(location = 0) out vec4 f_color; + layout(location = 0) out vec4 f_color; - void main() { - f_color = vec4(1.0, 0.0, 0.0, 1.0); - } - ", + void main() { + f_color = vec4(1.0, 0.0, 0.0, 1.0); + } + ", + } } - } - // Before we draw, we have to create what is called a **pipeline**. A pipeline describes how - // a GPU operation is to be performed. It is similar to an OpenGL program, but it also contains - // many settings for customization, all baked into a single object. For drawing, we create - // a **graphics** pipeline, but there are also other types of pipeline. - let pipeline = { - // First, we load the shaders that the pipeline will use: - // the vertex shader and the fragment shader. - // - // A Vulkan shader can in theory contain multiple entry points, so we have to specify which - // one. - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); + // Before we draw, we have to create what is called a **pipeline**. A pipeline describes + // how a GPU operation is to be performed. It is similar to an OpenGL program, but it also + // contains many settings for customization, all baked into a single object. For drawing, + // we create a **graphics** pipeline, but there are also other types of pipeline. + let pipeline = { + // First, we load the shaders that the pipeline will use: the vertex shader and the + // fragment shader. + // + // A Vulkan shader can in theory contain multiple entry points, so we have to specify + // which one. + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); - // Automatically generate a vertex input state from the vertex shader's input interface, - // that takes a single vertex buffer containing `Vertex` structs. - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + // Automatically generate a vertex input state from the vertex shader's input + // interface, that takes a single vertex buffer containing `Vertex` structs. + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - // Make a list of the shader stages that the pipeline will have. - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; + // Make a list of the shader stages that the pipeline will have. + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; - // We must now create a **pipeline layout** object, which describes the locations and types - // of descriptor sets and push constants used by the shaders in the pipeline. - // - // Multiple pipelines can share a common layout object, which is more efficient. - // The shaders in a pipeline must use a subset of the resources described in its pipeline - // layout, but the pipeline layout is allowed to contain resources that are not present in - // the shaders; they can be used by shaders in other pipelines that share the same - // layout. Thus, it is a good idea to design shaders so that many pipelines have - // common resource locations, which allows them to share pipeline layouts. - let layout = PipelineLayout::new( - self.device.clone(), - // Since we only have one pipeline in this example, and thus one pipeline layout, - // we automatically generate the creation info for it from the resources used in the - // shaders. In a real application, you would specify this information manually so that - // you can re-use one layout in multiple pipelines. - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); + // We must now create a **pipeline layout** object, which describes the locations and + // types of descriptor sets and push constants used by the shaders in the pipeline. + // + // Multiple pipelines can share a common layout object, which is more efficient. The + // shaders in a pipeline must use a subset of the resources described in its pipeline + // layout, but the pipeline layout is allowed to contain resources that are not present + // in the shaders; they can be used by shaders in other pipelines that share the same + // layout. Thus, it is a good idea to design shaders so that many pipelines have common + // resource locations, which allows them to share pipeline layouts. + let layout = PipelineLayout::new( + self.device.clone(), + // Since we only have one pipeline in this example, and thus one pipeline layout, + // we automatically generate the creation info for it from the resources used in + // the shaders. In a real application, you would specify this information manually + // so that you can re-use one layout in multiple pipelines. + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) + .unwrap(); - // We describe the formats of attachment images where the colors, depth and/or stencil - // information will be written. The pipeline will only be usable with this particular - // configuration of the attachment images. - let subpass = PipelineRenderingCreateInfo { - // We specify a single color attachment that will be rendered to. When we begin - // rendering, we will specify a swapchain image to be used as this attachment, so here - // we set its format to be the same format as the swapchain. - color_attachment_formats: vec![Some(swapchain.image_format())], - ..Default::default() + // We describe the formats of attachment images where the colors, depth and/or stencil + // information will be written. The pipeline will only be usable with this particular + // configuration of the attachment images. + let subpass = PipelineRenderingCreateInfo { + // We specify a single color attachment that will be rendered to. When we begin + // rendering, we will specify a swapchain image to be used as this attachment, so + // here we set its format to be the same format as the swapchain. + color_attachment_formats: vec![Some(swapchain.image_format())], + ..Default::default() + }; + + // Finally, create the pipeline. + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + // How vertex data is read from the vertex buffers into the vertex shader. + vertex_input_state: Some(vertex_input_state), + // How vertices are arranged into primitive shapes. The default primitive shape + // is a triangle. + input_assembly_state: Some(InputAssemblyState::default()), + // How primitives are transformed and clipped to fit the framebuffer. We use a + // resizable viewport, set to draw over the entire window. + viewport_state: Some(ViewportState::default()), + // How polygons are culled and converted into a raster of pixels. The default + // value does not perform any culling. + rasterization_state: Some(RasterizationState::default()), + // How multiple fragment shader samples are converted to a single pixel value. + // The default value does not perform any multisampling. + multisample_state: Some(MultisampleState::default()), + // How pixel values are combined with the values already present in the + // framebuffer. The default value overwrites the old value with the new one, + // without any blending. + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.color_attachment_formats.len() as u32, + ColorBlendAttachmentState::default(), + )), + // Dynamic states allows us to specify parts of the pipeline settings when + // recording the command buffer, before we perform drawing. Here, we specify + // that the viewport should be dynamic. + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) + .unwrap() }; - // Finally, create the pipeline. - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - // How vertex data is read from the vertex buffers into the vertex shader. - vertex_input_state: Some(vertex_input_state), - // How vertices are arranged into primitive shapes. - // The default primitive shape is a triangle. - input_assembly_state: Some(InputAssemblyState::default()), - // How primitives are transformed and clipped to fit the framebuffer. - // We use a resizable viewport, set to draw over the entire window. - viewport_state: Some(ViewportState::default()), - // How polygons are culled and converted into a raster of pixels. - // The default value does not perform any culling. - rasterization_state: Some(RasterizationState::default()), - // How multiple fragment shader samples are converted to a single pixel value. - // The default value does not perform any multisampling. - multisample_state: Some(MultisampleState::default()), - // How pixel values are combined with the values already present in the framebuffer. - // The default value overwrites the old value with the new one, without any - // blending. - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.color_attachment_formats.len() as u32, - ColorBlendAttachmentState::default(), - )), - // Dynamic states allows us to specify parts of the pipeline settings when - // recording the command buffer, before we perform drawing. - // Here, we specify that the viewport should be dynamic. - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - // Dynamic viewports allow us to recreate just the viewport when the window is resized. - // Otherwise we would have to recreate the whole pipeline. - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - // 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, we need to recreate the swapchain by creating a new swapchain. Here, - // we remember that we need to do this for the next loop iteration. - let recreate_swapchain = false; - - // In the loop below we are going to submit commands to the GPU. Submitting a command produces - // an object that implements the `GpuFuture` trait, which holds the resources for as long as - // they are in use by the GPU. - // - // Destroying the `GpuFuture` blocks until the GPU is finished executing it. In order to avoid - // that, we store the submission of the previous frame here. - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - attachment_image_views, - pipeline, - viewport, - recreate_swapchain, - previous_frame_end, - }); + // Dynamic viewports allow us to recreate just the viewport when the window is resized. + // Otherwise we would have to recreate the whole pipeline. + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + // 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, we need to recreate the swapchain by creating a new + // swapchain. Here, we remember that we need to do this for the next loop iteration. + let recreate_swapchain = false; + + // In the loop below we are going to submit commands to the GPU. Submitting a command + // produces an object that implements the `GpuFuture` trait, which holds the resources for + // as long as they are in use by the GPU. + // + // Destroying the `GpuFuture` blocks until the GPU is finished executing it. In order to + // avoid that, we store the submission of the previous frame here. + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + attachment_image_views, + pipeline, + viewport, + recreate_swapchain, + previous_frame_end, + }); } fn window_event( @@ -562,8 +571,8 @@ impl ApplicationHandler for App { WindowEvent::RedrawRequested => { let window_size = rcx.window.inner_size(); - // Do not draw the frame when the screen size is zero. On Windows, this can - // occur when minimizing the application. + // Do not draw the frame when the screen size is zero. On Windows, this can occur + // when minimizing the application. if window_size.width == 0 || window_size.height == 0 { return; } @@ -604,15 +613,19 @@ impl ApplicationHandler for App { // // This function can block if no image is available. The parameter is an optional // timeout after which the function call will return an error. - 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}"), - }; + 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}"), + }; // `acquire_next_image` can be successful, but suboptimal. This means that the // swapchain image will still work, but it may not display correctly. With some @@ -622,8 +635,8 @@ impl ApplicationHandler for App { rcx.recreate_swapchain = true; } - // In order to draw, we have to record a *command buffer*. The command buffer object - // holds the list of commands that are going to be executed. + // In order to draw, we have to record a *command buffer*. The command buffer + // object holds the list of commands that are going to be executed. // // Recording a command buffer is an expensive operation (usually a few hundred // microseconds), but it is known to be a hot path in the driver and is expected to @@ -713,7 +726,10 @@ impl ApplicationHandler for App { // that draws the triangle. .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush(); diff --git a/examples/triangle/main.rs b/examples/triangle/main.rs index 4972ab0ed5..cc02a145d5 100644 --- a/examples/triangle/main.rs +++ b/examples/triangle/main.rs @@ -17,7 +17,7 @@ use vulkano::{ }, device::{ physical::PhysicalDeviceType, Device, DeviceCreateInfo, DeviceExtensions, Queue, - QueueCreateInfo, QueueFlags + QueueCreateInfo, QueueFlags, }, image::{view::ImageView, Image, ImageUsage}, instance::{Instance, InstanceCreateFlags, InstanceCreateInfo}, @@ -78,472 +78,482 @@ struct RenderContext { impl App { fn new(event_loop: &EventLoop<()>) -> Self { - let library = VulkanLibrary::new().unwrap(); - - // The first step of any Vulkan program is to create an instance. - // - // When we create an instance, we have to pass a list of extensions that we want to enable. - // - // All the window-drawing functionalities are part of non-core extensions that we need to - // enable manually. To do so, we ask `Surface` for the list of extensions required to draw to - // a window. - let required_extensions = Surface::required_extensions(event_loop).unwrap(); - - // Now creating the instance. - 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, - ..Default::default() - }, - ) - .unwrap(); - - // Choose device extensions that we're going to use. In order to present images to a surface, - // we need a `Swapchain`, which is provided by the `khr_swapchain` extension. - let device_extensions = DeviceExtensions { - khr_swapchain: true, - ..DeviceExtensions::empty() - }; - - // We then choose which physical device to use. First, we enumerate all the available physical - // devices, then apply filters to narrow them down to those that can support our needs. - let (physical_device, queue_family_index) = instance - .enumerate_physical_devices() - .unwrap() - .filter(|p| { - // Some devices may not support the extensions or features that your application, or - // report properties and limits that are not sufficient for your application. These - // should be filtered out here. - p.supported_extensions().contains(&device_extensions) - }) - .filter_map(|p| { - // For each physical device, we try to find a suitable queue family that will execute - // our draw commands. - // - // Devices can provide multiple queues to run commands in parallel (for example a draw - // queue and a compute queue), similar to CPU threads. This is something you have to - // have to manage manually in Vulkan. Queues of the same type belong to the same queue - // family. + let library = VulkanLibrary::new().unwrap(); + + // The first step of any Vulkan program is to create an instance. + // + // When we create an instance, we have to pass a list of extensions that we want to enable. + // + // All the window-drawing functionalities are part of non-core extensions that we need to + // enable manually. To do so, we ask `Surface` for the list of extensions required to draw + // to a window. + let required_extensions = Surface::required_extensions(event_loop).unwrap(); + + // Now creating the instance. + 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, + ..Default::default() + }, + ) + .unwrap(); + + // Choose device extensions that we're going to use. In order to present images to a + // surface, we need a `Swapchain`, which is provided by the `khr_swapchain` extension. + let device_extensions = DeviceExtensions { + khr_swapchain: true, + ..DeviceExtensions::empty() + }; + + // We then choose which physical device to use. First, we enumerate all the available + // physical devices, then apply filters to narrow them down to those that can support our + // needs. + let (physical_device, queue_family_index) = instance + .enumerate_physical_devices() + .unwrap() + .filter(|p| { + // Some devices may not support the extensions or features that your application, + // or report properties and limits that are not sufficient for your application. + // These should be filtered out here. + p.supported_extensions().contains(&device_extensions) + }) + .filter_map(|p| { + // For each physical device, we try to find a suitable queue family that will + // execute our draw commands. + // + // Devices can provide multiple queues to run commands in parallel (for example a + // draw queue and a compute queue), similar to CPU threads. This is + // something you have to have to manage manually in Vulkan. Queues + // of the same type belong to the same queue family. + // + // Here, we look for a single queue family that is suitable for our purposes. In a + // real-world application, you may want to use a separate dedicated transfer queue + // to handle data transfers in parallel with graphics operations. + // You may also need a separate queue for compute operations, if + // your application uses those. + p.queue_family_properties() + .iter() + .enumerate() + .position(|(i, q)| { + // We select a queue family that supports graphics operations. When drawing + // to a window surface, as we do in this example, we also need to check + // that queues in this queue family are capable of presenting images to the + // surface. + q.queue_flags.intersects(QueueFlags::GRAPHICS) + && p.presentation_support(i as u32, event_loop).unwrap() + }) + // The code here searches for the first queue family that is suitable. If none + // is found, `None` is returned to `filter_map`, which + // disqualifies this physical device. + .map(|i| (p, i as u32)) + }) + // All the physical devices that pass the filters above are suitable for the + // application. However, not every device is equal, some are preferred over others. + // Now, we assign each physical device a score, and pick the device with the lowest + // ("best") score. // - // Here, we look for a single queue family that is suitable for our purposes. In a - // real-world application, you may want to use a separate dedicated transfer queue to - // handle data transfers in parallel with graphics operations. You may also need a - // separate queue for compute operations, if your application uses those. - p.queue_family_properties() - .iter() - .enumerate() - .position(|(i, q)| { - // We select a queue family that supports graphics operations. When drawing to - // a window surface, as we do in this example, we also need to check that - // queues in this queue family are capable of presenting images to the surface. - q.queue_flags.intersects(QueueFlags::GRAPHICS) - && p.presentation_support(i as u32, event_loop).unwrap() - }) - // The code here searches for the first queue family that is suitable. If none is - // found, `None` is returned to `filter_map`, which disqualifies this physical - // device. - .map(|i| (p, i as u32)) - }) - // All the physical devices that pass the filters above are suitable for the application. - // However, not every device is equal, some are preferred over others. Now, we assign each - // physical device a score, and pick the device with the lowest ("best") score. + // In this example, we simply select the best-scoring device to use in the application. + // In a real-world setting, you may want to use the best-scoring device only as a + // "default" or "recommended" device, and let the user choose the device themself. + .min_by_key(|(p, _)| { + // We assign a lower score to device types that are likely to be faster/better. + 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"); + + // Some little debug infos. + println!( + "Using device: {} (type: {:?})", + physical_device.properties().device_name, + physical_device.properties().device_type, + ); + + // Now initializing the device. This is probably the most important object of Vulkan. // - // In this example, we simply select the best-scoring device to use in the application. - // In a real-world setting, you may want to use the best-scoring device only as a "default" - // or "recommended" device, and let the user choose the device themself. - .min_by_key(|(p, _)| { - // We assign a lower score to device types that are likely to be faster/better. - 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"); - - // Some little debug infos. - println!( - "Using device: {} (type: {:?})", - physical_device.properties().device_name, - physical_device.properties().device_type, - ); - - // Now initializing the device. This is probably the most important object of Vulkan. - // - // An iterator of created queues is returned by the function alongside the device. - let (device, mut queues) = Device::new( - // Which physical device to connect to. - physical_device, - DeviceCreateInfo { - // A list of optional features and extensions that our program needs to work correctly. - // Some parts of the Vulkan specs are optional and must be enabled manually at device - // creation. In this example the only thing we are going to need is the `khr_swapchain` - // extension that allows us to draw to a window. - enabled_extensions: device_extensions, - - // The list of queues that we are going to use. Here we only use one queue, from the - // previously chosen queue family. - queue_create_infos: vec![QueueCreateInfo { - queue_family_index, + // An iterator of created queues is returned by the function alongside the device. + let (device, mut queues) = Device::new( + // Which physical device to connect to. + physical_device, + DeviceCreateInfo { + // A list of optional features and extensions that our program needs to work + // correctly. Some parts of the Vulkan specs are optional and must be enabled + // manually at device creation. In this example the only thing we are going to need + // is the `khr_swapchain` extension that allows us to draw to a window. + enabled_extensions: device_extensions, + + // The list of queues that we are going to use. Here we only use one queue, from + // the previously chosen queue family. + queue_create_infos: vec![QueueCreateInfo { + queue_family_index, + ..Default::default() + }], + ..Default::default() - }], + }, + ) + .unwrap(); - ..Default::default() - }, - ) - .unwrap(); - - // Since we can request multiple queues, the `queues` variable is in fact an iterator. We only - // use one queue in this example, so we just retrieve the first and only element of the - // iterator. - let queue = queues.next().unwrap(); - - let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); - - // Before we can start creating and recording command buffers, we need a way of allocating - // them. Vulkano provides a command buffer allocator, which manages raw Vulkan command pools - // underneath and provides a safe interface for them. - let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( - device.clone(), - Default::default(), - )); - - // We now create a buffer that will store the shape of our triangle. - let vertices = [ - MyVertex { - position: [-0.5, -0.25], - }, - MyVertex { - position: [0.0, 0.5], - }, - MyVertex { - position: [0.25, -0.1], - }, - ]; - let vertex_buffer = Buffer::from_iter( - memory_allocator, - BufferCreateInfo { - usage: BufferUsage::VERTEX_BUFFER, - ..Default::default() - }, - AllocationCreateInfo { - memory_type_filter: MemoryTypeFilter::PREFER_DEVICE - | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, - ..Default::default() - }, - vertices, - ) - .unwrap(); - - let rcx = None; - - App { - instance, - device, - queue, - command_buffer_allocator, - vertex_buffer, - rcx, - } + // Since we can request multiple queues, the `queues` variable is in fact an iterator. We + // only use one queue in this example, so we just retrieve the first and only element of + // the iterator. + let queue = queues.next().unwrap(); + + let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone())); + + // Before we can start creating and recording command buffers, we need a way of allocating + // them. Vulkano provides a command buffer allocator, which manages raw Vulkan command + // pools underneath and provides a safe interface for them. + let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new( + device.clone(), + Default::default(), + )); + + // We now create a buffer that will store the shape of our triangle. + let vertices = [ + MyVertex { + position: [-0.5, -0.25], + }, + MyVertex { + position: [0.0, 0.5], + }, + MyVertex { + position: [0.25, -0.1], + }, + ]; + let vertex_buffer = Buffer::from_iter( + memory_allocator, + BufferCreateInfo { + usage: BufferUsage::VERTEX_BUFFER, + ..Default::default() + }, + AllocationCreateInfo { + memory_type_filter: MemoryTypeFilter::PREFER_DEVICE + | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, + ..Default::default() + }, + vertices, + ) + .unwrap(); + + let rcx = None; + + App { + instance, + device, + queue, + command_buffer_allocator, + vertex_buffer, + rcx, + } } } impl ApplicationHandler for App { fn resumed(&mut self, event_loop: &ActiveEventLoop) { - // The objective of this example is to draw a triangle on a window. To do so, we first need to - // create the window. We use the `WindowBuilder` from the `winit` crate to do that here. - // - // Before we can render to a window, we must first create a `vulkano::swapchain::Surface` - // object from it, which represents the drawable surface of a window. For that we must wrap the - // `winit::window::Window` in an `Arc`. - let window = Arc::new(event_loop.create_window(Window::default_attributes()).unwrap()); - let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); - let window_size = window.inner_size(); - - // Before we can draw on the surface, we have to create what is called a swapchain. Creating a - // swapchain allocates the color buffers that will contain the image that will ultimately be - // visible on the screen. These images are returned alongside the swapchain. - let (swapchain, images) = { - // Querying the capabilities of the surface. When we create the swapchain we can only pass - // values that are allowed by the capabilities. - let surface_capabilities = self - .device - .physical_device() - .surface_capabilities(&surface, Default::default()) - .unwrap(); + // The objective of this example is to draw a triangle on a window. To do so, we first need + // to create the window. We use the `WindowBuilder` from the `winit` crate to do that here. + // + // Before we can render to a window, we must first create a `vulkano::swapchain::Surface` + // object from it, which represents the drawable surface of a window. For that we must wrap + // the `winit::window::Window` in an `Arc`. + let window = Arc::new( + event_loop + .create_window(Window::default_attributes()) + .unwrap(), + ); + let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); + let window_size = window.inner_size(); + + // Before we can draw on the surface, we have to create what is called a swapchain. + // Creating a swapchain allocates the color buffers that will contain the image that will + // ultimately be visible on the screen. These images are returned alongside the swapchain. + let (swapchain, images) = { + // Querying the capabilities of the surface. When we create the swapchain we can only + // pass values that are allowed by the capabilities. + let surface_capabilities = self + .device + .physical_device() + .surface_capabilities(&surface, Default::default()) + .unwrap(); - // Choosing the internal format that the images will have. - let (image_format, _) = self - .device - .physical_device() - .surface_formats(&surface, Default::default()) - .unwrap()[0]; + // Choosing the internal format that the images will have. + let (image_format, _) = self + .device + .physical_device() + .surface_formats(&surface, Default::default()) + .unwrap()[0]; + + // Please take a look at the docs for the meaning of the parameters we didn't mention. + Swapchain::new( + self.device.clone(), + surface, + SwapchainCreateInfo { + // Some drivers report an `min_image_count` of 1, but fullscreen mode requires + // at least 2. Therefore we must ensure the count is at least 2, otherwise the + // program would crash when entering fullscreen mode on those drivers. + min_image_count: surface_capabilities.min_image_count.max(2), + + image_format, + + // The size of the window, only used to initially setup the swapchain. + // + // NOTE: + // On some drivers the swapchain extent is specified by + // `surface_capabilities.current_extent` and the swapchain size must use this + // extent. This extent is always the same as the window size. + // + // However, other drivers don't specify a value, i.e. + // `surface_capabilities.current_extent` is `None`. These drivers will allow + // anything, but the only sensible value is the window size. + // + // Both of these cases need the swapchain to use the window size, so we just + // use that. + image_extent: window_size.into(), - // Please take a look at the docs for the meaning of the parameters we didn't mention. - Swapchain::new( - self.device.clone(), - surface, - SwapchainCreateInfo { - // Some drivers report an `min_image_count` of 1, but fullscreen mode requires at - // least 2. Therefore we must ensure the count is at least 2, otherwise the program - // would crash when entering fullscreen mode on those drivers. - min_image_count: surface_capabilities.min_image_count.max(2), + image_usage: ImageUsage::COLOR_ATTACHMENT, - image_format, + // The alpha mode indicates how the alpha value of the final image will behave. + // For example, you can choose whether the window will be + // opaque or transparent. + composite_alpha: surface_capabilities + .supported_composite_alpha + .into_iter() + .next() + .unwrap(), - // The size of the window, only used to initially setup the swapchain. - // - // NOTE: - // On some drivers the swapchain extent is specified by - // `surface_capabilities.current_extent` and the swapchain size must use this - // extent. This extent is always the same as the window size. - // - // However, other drivers don't specify a value, i.e. - // `surface_capabilities.current_extent` is `None`. These drivers will allow - // anything, but the only sensible value is the window size. - // - // Both of these cases need the swapchain to use the window size, so we just - // use that. - image_extent: window_size.into(), - - image_usage: ImageUsage::COLOR_ATTACHMENT, - - // The alpha mode indicates how the alpha value of the final image will behave. For - // example, you can choose whether the window will be opaque or transparent. - composite_alpha: surface_capabilities - .supported_composite_alpha - .into_iter() - .next() - .unwrap(), + ..Default::default() + }, + ) + .unwrap() + }; - ..Default::default() - }, - ) - .unwrap() - }; - - // The next step is to create the shaders. - // - // The raw shader creation API provided by the vulkano library is unsafe for various reasons, - // so The `shader!` macro provides a way to generate a Rust module from GLSL source - in the - // example below, the source is provided as a string input directly to the shader, but a path - // to a source file can be provided as well. Note that the user must specify the type of shader - // (e.g. "vertex", "fragment", etc.) using the `ty` option of the macro. - // - // The items generated by the `shader!` macro include a `load` function which loads the shader - // using an input logical device. The module also includes type definitions for layout - // structures defined in the shader source, for example uniforms and push constants. - // - // A more detailed overview of what the `shader!` macro generates can be found in the - // vulkano-shaders crate docs. You can view them at https://docs.rs/vulkano-shaders/ - mod vs { - vulkano_shaders::shader! { - ty: "vertex", - src: r" - #version 450 - - layout(location = 0) in vec2 position; - - void main() { - gl_Position = vec4(position, 0.0, 1.0); - } - ", + // The next step is to create the shaders. + // + // The raw shader creation API provided by the vulkano library is unsafe for various + // reasons, so The `shader!` macro provides a way to generate a Rust module from GLSL + // source - in the example below, the source is provided as a string input directly to the + // shader, but a path to a source file can be provided as well. Note that the user must + // specify the type of shader (e.g. "vertex", "fragment", etc.) using the `ty` option of + // the macro. + // + // The items generated by the `shader!` macro include a `load` function which loads the + // shader using an input logical device. The module also includes type definitions for + // layout structures defined in the shader source, for example uniforms and push constants. + // + // A more detailed overview of what the `shader!` macro generates can be found in the + // vulkano-shaders crate docs. You can view them at https://docs.rs/vulkano-shaders/ + mod vs { + vulkano_shaders::shader! { + ty: "vertex", + src: r" + #version 450 + + layout(location = 0) in vec2 position; + + void main() { + gl_Position = vec4(position, 0.0, 1.0); + } + ", + } } - } - mod fs { - vulkano_shaders::shader! { - ty: "fragment", - src: r" - #version 450 + mod fs { + vulkano_shaders::shader! { + ty: "fragment", + src: r" + #version 450 - layout(location = 0) out vec4 f_color; + layout(location = 0) out vec4 f_color; - void main() { - f_color = vec4(1.0, 0.0, 0.0, 1.0); - } - ", + void main() { + f_color = vec4(1.0, 0.0, 0.0, 1.0); + } + ", + } } - } - // The next step is to create a *render pass*, which is an object that describes where the - // output of the graphics pipeline will go. It describes the layout of the images where the - // colors, depth and/or stencil information will be written. - let render_pass = vulkano::single_pass_renderpass!( - self.device.clone(), - attachments: { - // `color` is a custom name we give to the first and only attachment. - color: { - // `format: ` indicates the type of the format of the image. This has to be one - // of the types of the `vulkano::format` module (or alternatively one of your - // structs that implements the `FormatDesc` trait). Here we use the same format as - // the swapchain. - format: swapchain.image_format(), - // `samples: 1` means that we ask the GPU to use one sample to determine the value - // of each pixel in the color attachment. We could use a larger value - // (multisampling) for antialiasing. An example of this can be found in - // msaa-renderpass.rs. - samples: 1, - // `load_op: Clear` means that we ask the GPU to clear the content of this - // attachment at the start of the drawing. - load_op: Clear, - // `store_op: Store` means that we ask the GPU to store the output of the draw in - // the actual image. We could also ask it to discard the result. - store_op: Store, + // The next step is to create a *render pass*, which is an object that describes where the + // output of the graphics pipeline will go. It describes the layout of the images where the + // colors, depth and/or stencil information will be written. + let render_pass = vulkano::single_pass_renderpass!( + self.device.clone(), + attachments: { + // `color` is a custom name we give to the first and only attachment. + color: { + // `format: ` indicates the type of the format of the image. This has to be + // one of the types of the `vulkano::format` module (or alternatively one of + // your structs that implements the `FormatDesc` trait). Here we use the same + // format as the swapchain. + format: swapchain.image_format(), + // `samples: 1` means that we ask the GPU to use one sample to determine the + // value of each pixel in the color attachment. We could use a larger value + // (multisampling) for antialiasing. An example of this can be found in + // msaa-renderpass.rs. + samples: 1, + // `load_op: Clear` means that we ask the GPU to clear the content of this + // attachment at the start of the drawing. + load_op: Clear, + // `store_op: Store` means that we ask the GPU to store the output of the draw + // in the actual image. We could also ask it to discard the result. + store_op: Store, + }, }, - }, - pass: { - // We use the attachment named `color` as the one and only color attachment. - color: [color], - // No depth-stencil attachment is indicated with empty brackets. - depth_stencil: {}, - }, - ) - .unwrap(); - - // The render pass we created above only describes the layout of our framebuffers. Before we - // can draw we also need to create the actual framebuffers. - // - // Since we need to draw to multiple images, we are going to create a different framebuffer for - // each image. - let framebuffers = window_size_dependent_setup(&images, &render_pass); - - // Before we draw, we have to create what is called a **pipeline**. A pipeline describes how - // a GPU operation is to be performed. It is similar to an OpenGL program, but it also contains - // many settings for customization, all baked into a single object. For drawing, we create - // a **graphics** pipeline, but there are also other types of pipeline. - let pipeline = { - // First, we load the shaders that the pipeline will use: - // the vertex shader and the fragment shader. - // - // A Vulkan shader can in theory contain multiple entry points, so we have to specify which - // one. - let vs = vs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); - let fs = fs::load(self.device.clone()) - .unwrap() - .entry_point("main") - .unwrap(); + pass: { + // We use the attachment named `color` as the one and only color attachment. + color: [color], + // No depth-stencil attachment is indicated with empty brackets. + depth_stencil: {}, + }, + ) + .unwrap(); - // Automatically generate a vertex input state from the vertex shader's input interface, - // that takes a single vertex buffer containing `Vertex` structs. - let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); + // The render pass we created above only describes the layout of our framebuffers. Before + // we can draw we also need to create the actual framebuffers. + // + // Since we need to draw to multiple images, we are going to create a different framebuffer + // for each image. + let framebuffers = window_size_dependent_setup(&images, &render_pass); + + // Before we draw, we have to create what is called a **pipeline**. A pipeline describes + // how a GPU operation is to be performed. It is similar to an OpenGL program, but it also + // contains many settings for customization, all baked into a single object. For drawing, + // we create a **graphics** pipeline, but there are also other types of pipeline. + let pipeline = { + // First, we load the shaders that the pipeline will use: the vertex shader and the + // fragment shader. + // + // A Vulkan shader can in theory contain multiple entry points, so we have to specify + // which one. + let vs = vs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); + let fs = fs::load(self.device.clone()) + .unwrap() + .entry_point("main") + .unwrap(); - // Make a list of the shader stages that the pipeline will have. - let stages = [ - PipelineShaderStageCreateInfo::new(vs), - PipelineShaderStageCreateInfo::new(fs), - ]; + // Automatically generate a vertex input state from the vertex shader's input + // interface, that takes a single vertex buffer containing `Vertex` structs. + let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap(); - // We must now create a **pipeline layout** object, which describes the locations and types - // of descriptor sets and push constants used by the shaders in the pipeline. - // - // Multiple pipelines can share a common layout object, which is more efficient. - // The shaders in a pipeline must use a subset of the resources described in its pipeline - // layout, but the pipeline layout is allowed to contain resources that are not present in - // the shaders; they can be used by shaders in other pipelines that share the same - // layout. Thus, it is a good idea to design shaders so that many pipelines have - // common resource locations, which allows them to share pipeline layouts. - let layout = PipelineLayout::new( - self.device.clone(), - // Since we only have one pipeline in this example, and thus one pipeline layout, - // we automatically generate the creation info for it from the resources used in the - // shaders. In a real application, you would specify this information manually so that - // you can re-use one layout in multiple pipelines. - PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) - .into_pipeline_layout_create_info(self.device.clone()) - .unwrap(), - ) - .unwrap(); + // Make a list of the shader stages that the pipeline will have. + let stages = [ + PipelineShaderStageCreateInfo::new(vs), + PipelineShaderStageCreateInfo::new(fs), + ]; - // We have to indicate which subpass of which render pass this pipeline is going to be used - // in. The pipeline will only be usable from this particular subpass. - let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + // We must now create a **pipeline layout** object, which describes the locations and + // types of descriptor sets and push constants used by the shaders in the pipeline. + // + // Multiple pipelines can share a common layout object, which is more efficient. The + // shaders in a pipeline must use a subset of the resources described in its pipeline + // layout, but the pipeline layout is allowed to contain resources that are not present + // in the shaders; they can be used by shaders in other pipelines that share the same + // layout. Thus, it is a good idea to design shaders so that many pipelines have common + // resource locations, which allows them to share pipeline layouts. + let layout = PipelineLayout::new( + self.device.clone(), + // Since we only have one pipeline in this example, and thus one pipeline layout, + // we automatically generate the creation info for it from the resources used in + // the shaders. In a real application, you would specify this information manually + // so that you can re-use one layout in multiple pipelines. + PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages) + .into_pipeline_layout_create_info(self.device.clone()) + .unwrap(), + ) + .unwrap(); - // Finally, create the pipeline. - GraphicsPipeline::new( - self.device.clone(), - None, - GraphicsPipelineCreateInfo { - stages: stages.into_iter().collect(), - // How vertex data is read from the vertex buffers into the vertex shader. - vertex_input_state: Some(vertex_input_state), - // How vertices are arranged into primitive shapes. - // The default primitive shape is a triangle. - input_assembly_state: Some(InputAssemblyState::default()), - // How primitives are transformed and clipped to fit the framebuffer. - // We use a resizable viewport, set to draw over the entire window. - viewport_state: Some(ViewportState::default()), - // How polygons are culled and converted into a raster of pixels. - // The default value does not perform any culling. - rasterization_state: Some(RasterizationState::default()), - // How multiple fragment shader samples are converted to a single pixel value. - // The default value does not perform any multisampling. - multisample_state: Some(MultisampleState::default()), - // How pixel values are combined with the values already present in the framebuffer. - // The default value overwrites the old value with the new one, without any - // blending. - color_blend_state: Some(ColorBlendState::with_attachment_states( - subpass.num_color_attachments(), - ColorBlendAttachmentState::default(), - )), - // Dynamic states allows us to specify parts of the pipeline settings when - // recording the command buffer, before we perform drawing. - // Here, we specify that the viewport should be dynamic. - dynamic_state: [DynamicState::Viewport].into_iter().collect(), - subpass: Some(subpass.into()), - ..GraphicsPipelineCreateInfo::layout(layout) - }, - ) - .unwrap() - }; - - // Dynamic viewports allow us to recreate just the viewport when the window is resized. - // Otherwise we would have to recreate the whole pipeline. - let viewport = Viewport { - offset: [0.0, 0.0], - extent: window_size.into(), - depth_range: 0.0..=1.0, - }; - - // 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, we need to recreate the swapchain by creating a new swapchain. Here, - // we remember that we need to do this for the next loop iteration. - let recreate_swapchain = false; - - // In the `window_event` handler below we are going to submit commands to the GPU. Submitting a command produces - // an object that implements the `GpuFuture` trait, which holds the resources for as long as - // they are in use by the GPU. - // - // Destroying the `GpuFuture` blocks until the GPU is finished executing it. In order to avoid - // that, we store the submission of the previous frame here. - let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); - - self.rcx = Some(RenderContext { - window, - swapchain, - render_pass, - framebuffers, - pipeline, - viewport, - recreate_swapchain, - previous_frame_end, - }); + // We have to indicate which subpass of which render pass this pipeline is going to be + // used in. The pipeline will only be usable from this particular subpass. + let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); + + // Finally, create the pipeline. + GraphicsPipeline::new( + self.device.clone(), + None, + GraphicsPipelineCreateInfo { + stages: stages.into_iter().collect(), + // How vertex data is read from the vertex buffers into the vertex shader. + vertex_input_state: Some(vertex_input_state), + // How vertices are arranged into primitive shapes. The default primitive shape + // is a triangle. + input_assembly_state: Some(InputAssemblyState::default()), + // How primitives are transformed and clipped to fit the framebuffer. We use a + // resizable viewport, set to draw over the entire window. + viewport_state: Some(ViewportState::default()), + // How polygons are culled and converted into a raster of pixels. The default + // value does not perform any culling. + rasterization_state: Some(RasterizationState::default()), + // How multiple fragment shader samples are converted to a single pixel value. + // The default value does not perform any multisampling. + multisample_state: Some(MultisampleState::default()), + // How pixel values are combined with the values already present in the + // framebuffer. The default value overwrites the old value with the new one, + // without any blending. + color_blend_state: Some(ColorBlendState::with_attachment_states( + subpass.num_color_attachments(), + ColorBlendAttachmentState::default(), + )), + // Dynamic states allows us to specify parts of the pipeline settings when + // recording the command buffer, before we perform drawing. Here, we specify + // that the viewport should be dynamic. + dynamic_state: [DynamicState::Viewport].into_iter().collect(), + subpass: Some(subpass.into()), + ..GraphicsPipelineCreateInfo::layout(layout) + }, + ) + .unwrap() + }; + + // Dynamic viewports allow us to recreate just the viewport when the window is resized. + // Otherwise we would have to recreate the whole pipeline. + let viewport = Viewport { + offset: [0.0, 0.0], + extent: window_size.into(), + depth_range: 0.0..=1.0, + }; + + // 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, we need to recreate the swapchain by creating a new + // swapchain. Here, we remember that we need to do this for the next loop iteration. + let recreate_swapchain = false; + + // In the `window_event` handler below we are going to submit commands to the GPU. + // Submitting a command produces an object that implements the `GpuFuture` trait, which + // holds the resources for as long as they are in use by the GPU. + // + // Destroying the `GpuFuture` blocks until the GPU is finished executing it. In order to + // avoid that, we store the submission of the previous frame here. + let previous_frame_end = Some(sync::now(self.device.clone()).boxed()); + + self.rcx = Some(RenderContext { + window, + swapchain, + render_pass, + framebuffers, + pipeline, + viewport, + recreate_swapchain, + previous_frame_end, + }); } fn window_event( @@ -564,8 +574,8 @@ impl ApplicationHandler for App { WindowEvent::RedrawRequested => { let window_size = rcx.window.inner_size(); - // Do not draw the frame when the screen size is zero. On Windows, this can - // occur when minimizing the application. + // Do not draw the frame when the screen size is zero. On Windows, this can occur + // when minimizing the application. if window_size.width == 0 || window_size.height == 0 { return; } @@ -582,7 +592,8 @@ impl ApplicationHandler for App { if rcx.recreate_swapchain { // Use the new dimensions of the window. - let (new_swapchain, new_images) = rcx.swapchain + let (new_swapchain, new_images) = rcx + .swapchain .recreate(SwapchainCreateInfo { image_extent: window_size.into(), ..rcx.swapchain.create_info() @@ -593,10 +604,7 @@ impl ApplicationHandler for App { // Because framebuffers contains a reference to the old swapchain, we need to // recreate framebuffers as well. - rcx.framebuffers = window_size_dependent_setup( - &new_images, - &rcx.render_pass, - ); + rcx.framebuffers = window_size_dependent_setup(&new_images, &rcx.render_pass); rcx.viewport.extent = window_size.into(); @@ -610,15 +618,19 @@ impl ApplicationHandler for App { // // This function can block if no image is available. The parameter is an optional // timeout after which the function call will return an error. - 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}"), - }; + 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}"), + }; // `acquire_next_image` can be successful, but suboptimal. This means that the // swapchain image will still work, but it may not display correctly. With some @@ -628,8 +640,8 @@ impl ApplicationHandler for App { rcx.recreate_swapchain = true; } - // In order to draw, we have to record a *command buffer*. The command buffer object - // holds the list of commands that are going to be executed. + // In order to draw, we have to record a *command buffer*. The command buffer + // object holds the list of commands that are going to be executed. // // Recording a command buffer is an expensive operation (usually a few hundred // microseconds), but it is known to be a hot path in the driver and is expected to @@ -665,9 +677,9 @@ impl ApplicationHandler for App { ) }, SubpassBeginInfo { - // The contents of the first (and only) subpass. - // This can be either `Inline` or `SecondaryCommandBuffers`. - // The latter is a bit more advanced and is not covered here. + // The contents of the first (and only) subpass. This can be either + // `Inline` or `SecondaryCommandBuffers`. The latter is a bit more + // advanced and is not covered here. contents: SubpassContents::Inline, ..Default::default() }, @@ -716,7 +728,10 @@ impl ApplicationHandler for App { // that draws the triangle. .then_swapchain_present( self.queue.clone(), - SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index), + SwapchainPresentInfo::swapchain_image_index( + rcx.swapchain.clone(), + image_index, + ), ) .then_signal_fence_and_flush();