Split crates
Some checks failed
Build legacy Nix package on Ubuntu / build (push) Failing after 7m49s

This commit is contained in:
Florian RICHER 2025-05-18 13:15:29 +02:00
parent 99be029ff8
commit b977f446d3
Signed by: florian.richer
GPG key ID: C73D37CBED7BFC77
16 changed files with 84 additions and 110 deletions

View file

@ -0,0 +1,14 @@
[package]
name = "engine_vulkan"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
log = { workspace = true }
env_logger = { workspace = true }
bevy_app = { workspace = true }
bevy_ecs = { workspace = true }
winit = { workspace = true }
vulkano = { workspace = true }
engine_window = { workspace = true }

View file

@ -0,0 +1,33 @@
use engine_window::raw_handle::WindowWrapper;
use vulkan_context::VulkanContext;
use window_render_context::WindowRenderContext;
use bevy_app::{App, Plugin};
mod utils;
mod vulkan_context;
mod window_render_context;
#[derive(Debug, thiserror::Error)]
pub enum VulkanError {
#[error("Failed to create vulkan context")]
FailedToCreateVulkanContext,
}
pub struct VulkanPlugin;
impl Plugin for VulkanPlugin {
fn build(&self, app: &mut App) {
let vulkan_context = VulkanContext::from(app as &App);
app.world_mut().insert_resource(vulkan_context);
}
fn ready(&self, app: &App) -> bool {
app.world().get_resource::<WindowWrapper>().is_some()
}
fn finish(&self, app: &mut App) {
let window_render_context = WindowRenderContext::from(app as &App);
app.world_mut().insert_resource(window_render_context);
}
}

View file

@ -0,0 +1,137 @@
use std::sync::Arc;
use vulkano::{
Version, VulkanLibrary,
device::{
Device, DeviceCreateInfo, DeviceExtensions, DeviceFeatures, Queue, QueueCreateInfo,
QueueFlags,
physical::{PhysicalDevice, PhysicalDeviceType},
},
instance::{Instance, InstanceCreateFlags, InstanceCreateInfo, InstanceExtensions},
};
use winit::raw_window_handle::HasDisplayHandle;
pub(super) fn load_library() -> Arc<VulkanLibrary> {
let library = VulkanLibrary::new().unwrap();
log::debug!("Available layer:");
for layer in library.layer_properties().unwrap() {
log::debug!(
"\t - Layer name: {}, Description: {}, Implementation Version: {}, Vulkan Version: {}",
layer.name(),
layer.description(),
layer.implementation_version(),
layer.vulkan_version()
);
}
library
}
pub(super) fn create_instance(
library: Arc<VulkanLibrary>,
required_extensions: InstanceExtensions,
) -> Arc<Instance> {
Instance::new(
library,
InstanceCreateInfo {
// Enable enumerating devices that use non-conformant Vulkan implementations.
// (e.g. MoltenVK)
flags: InstanceCreateFlags::ENUMERATE_PORTABILITY,
enabled_extensions: required_extensions,
enabled_layers: vec![String::from("VK_LAYER_KHRONOS_validation")],
..Default::default()
},
)
.unwrap()
}
pub(super) fn find_physical_device_queue_family_indexes(
physical_device: &Arc<PhysicalDevice>,
display_handle: &impl HasDisplayHandle,
) -> Option<u32> {
let mut graphic_queue_family_index = None;
for (i, queue_family_property) in physical_device.queue_family_properties().iter().enumerate() {
if queue_family_property
.queue_flags
.intersects(QueueFlags::GRAPHICS)
&& physical_device
.presentation_support(i as u32, display_handle)
.unwrap()
{
graphic_queue_family_index = Some(i as u32);
}
}
graphic_queue_family_index
}
pub(super) fn pick_physical_device_and_queue_family_indexes(
instance: &Arc<Instance>,
display_handle: &impl HasDisplayHandle,
device_extensions: &DeviceExtensions,
) -> Option<(Arc<PhysicalDevice>, u32)> {
instance
.enumerate_physical_devices()
.unwrap()
.filter(|p| {
p.api_version() >= Version::V1_3 || p.supported_extensions().khr_dynamic_rendering
})
.filter(|p| p.supported_extensions().contains(device_extensions))
.filter_map(|p| {
find_physical_device_queue_family_indexes(&p, display_handle)
.and_then(|indexes| Some((p, indexes)))
})
.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,
})
}
pub(super) fn pick_graphics_device(
instance: &Arc<Instance>,
display_handle: &impl HasDisplayHandle,
) -> (Arc<Device>, impl ExactSizeIterator<Item = Arc<Queue>>) {
let mut device_extensions = DeviceExtensions {
khr_swapchain: true,
..DeviceExtensions::empty()
};
let (physical_device, graphics_family_index) =
pick_physical_device_and_queue_family_indexes(instance, display_handle, &device_extensions)
.unwrap();
log::debug!(
"Using device: {} (type: {:?})",
physical_device.properties().device_name,
physical_device.properties().device_type,
);
if physical_device.api_version() < Version::V1_3 {
device_extensions.khr_dynamic_rendering = true;
}
log::debug!("Using device extensions: {:#?}", device_extensions);
Device::new(
physical_device,
DeviceCreateInfo {
queue_create_infos: vec![QueueCreateInfo {
queue_family_index: graphics_family_index,
..Default::default()
}],
enabled_extensions: device_extensions,
enabled_features: DeviceFeatures {
dynamic_rendering: true,
..DeviceFeatures::empty()
},
..Default::default()
},
)
.unwrap()
}

View file

@ -0,0 +1,88 @@
use std::{any::Any, sync::Arc};
use bevy_app::App;
use bevy_ecs::resource::Resource;
use engine_window::raw_handle::DisplayHandleWrapper;
use vulkano::{
command_buffer::{
AutoCommandBufferBuilder, CommandBufferUsage, PrimaryAutoCommandBuffer,
allocator::StandardCommandBufferAllocator,
},
descriptor_set::allocator::StandardDescriptorSetAllocator,
device::{Device, Queue},
instance::Instance,
memory::allocator::StandardMemoryAllocator,
swapchain::Surface,
};
use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use super::utils;
#[derive(Resource)]
pub struct VulkanContext {
pub instance: Arc<Instance>,
pub device: Arc<Device>,
pub graphics_queue: Arc<Queue>,
pub memory_allocator: Arc<StandardMemoryAllocator>,
pub command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
pub descriptor_set_allocator: Arc<StandardDescriptorSetAllocator>,
}
impl VulkanContext {
pub fn create_surface(
&self,
window: Arc<impl HasWindowHandle + HasDisplayHandle + Any + Send + Sync>,
) -> Arc<Surface> {
Surface::from_window(self.instance.clone(), window).unwrap()
}
pub fn create_render_builder(&self) -> AutoCommandBufferBuilder<PrimaryAutoCommandBuffer> {
AutoCommandBufferBuilder::primary(
self.command_buffer_allocator.clone(),
self.graphics_queue.queue_family_index(),
CommandBufferUsage::OneTimeSubmit,
)
.unwrap()
}
}
impl From<&App> for VulkanContext {
fn from(app: &App) -> Self {
let library = utils::load_library();
let world = app.world();
let display_handle: &DisplayHandleWrapper =
world.get_resource::<DisplayHandleWrapper>().unwrap();
let enabled_extensions = Surface::required_extensions(&display_handle.0).unwrap();
log::debug!("Surface required extensions: {enabled_extensions:?}");
let instance = utils::create_instance(library.clone(), enabled_extensions);
let (device, mut queues) = utils::pick_graphics_device(&instance, &display_handle.0);
let graphics_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 descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new(
device.clone(),
Default::default(),
));
Self {
instance: instance.clone(),
device,
graphics_queue,
memory_allocator,
command_buffer_allocator,
descriptor_set_allocator,
}
}
}

View file

@ -0,0 +1,116 @@
use bevy_app::App;
use bevy_ecs::resource::Resource;
use engine_window::raw_handle::WindowWrapper;
use std::sync::Arc;
use vulkano::image::view::ImageView;
use vulkano::image::{Image, ImageUsage};
use vulkano::pipeline::graphics::viewport::Viewport;
use vulkano::swapchain::{Swapchain, SwapchainCreateInfo};
use vulkano::sync::{self, GpuFuture};
use vulkano::{Validated, VulkanError};
use winit::window::Window;
use super::vulkan_context::VulkanContext;
#[derive(Resource)]
pub struct WindowRenderContext {
pub window: Arc<Window>,
pub swapchain: Arc<Swapchain>,
pub attachment_image_views: Vec<Arc<ImageView>>,
pub viewport: Viewport,
pub recreate_swapchain: bool,
pub previous_frame_end: Option<Box<dyn GpuFuture + Send + Sync>>,
}
impl From<&App> for WindowRenderContext {
fn from(app: &App) -> Self {
let world = app.world();
let vulkan_context = world.get_resource::<VulkanContext>().unwrap();
let window_handle = world.get_resource::<WindowWrapper>().unwrap();
let window_size = window_handle.0.inner_size();
let surface = vulkan_context.create_surface(window_handle.0.clone());
let (swapchain, images) = {
let surface_capabilities = vulkan_context
.device
.physical_device()
.surface_capabilities(&surface, Default::default())
.unwrap();
let (image_format, _) = vulkan_context
.device
.physical_device()
.surface_formats(&surface, Default::default())
.unwrap()[0];
Swapchain::new(
vulkan_context.device.clone(),
surface,
SwapchainCreateInfo {
// 2 because with some graphics driver, it crash on fullscreen because fullscreen need to min image to works.
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 attachment_image_views = window_size_dependent_setup(&images);
let viewport = Viewport {
offset: [0.0, 0.0],
extent: window_size.into(),
depth_range: 0.0..=1.0,
};
let recreate_swapchain = false;
let previous_frame_end = Some(sync::now(vulkan_context.device.clone()).boxed_send_sync());
Self {
window: window_handle.0.clone(),
swapchain,
attachment_image_views,
viewport,
recreate_swapchain,
previous_frame_end,
}
}
}
impl WindowRenderContext {
pub fn update_swapchain(&mut self) -> Result<(), Validated<VulkanError>> {
if !self.recreate_swapchain {
return Ok(());
}
let window_size = self.window.inner_size();
let (new_swapchain, new_images) = self.swapchain.recreate(SwapchainCreateInfo {
image_extent: window_size.into(),
..self.swapchain.create_info()
})?;
self.swapchain = new_swapchain;
self.attachment_image_views = window_size_dependent_setup(&new_images);
self.viewport.extent = window_size.into();
self.recreate_swapchain = false;
Ok(())
}
}
fn window_size_dependent_setup(images: &[Arc<Image>]) -> Vec<Arc<ImageView>> {
images
.iter()
.map(|image| ImageView::new_default(image.clone()).unwrap())
.collect::<Vec<_>>()
}