Split crates
Some checks failed
Build legacy Nix package on Ubuntu / build (push) Failing after 7m49s
Some checks failed
Build legacy Nix package on Ubuntu / build (push) Failing after 7m49s
This commit is contained in:
parent
99be029ff8
commit
b977f446d3
16 changed files with 84 additions and 110 deletions
14
crates/engine_vulkan/Cargo.toml
Normal file
14
crates/engine_vulkan/Cargo.toml
Normal 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 }
|
33
crates/engine_vulkan/src/lib.rs
Normal file
33
crates/engine_vulkan/src/lib.rs
Normal 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);
|
||||
}
|
||||
}
|
137
crates/engine_vulkan/src/utils.rs
Normal file
137
crates/engine_vulkan/src/utils.rs
Normal 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()
|
||||
}
|
88
crates/engine_vulkan/src/vulkan_context.rs
Normal file
88
crates/engine_vulkan/src/vulkan_context.rs
Normal 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,
|
||||
}
|
||||
}
|
||||
}
|
116
crates/engine_vulkan/src/window_render_context.rs
Normal file
116
crates/engine_vulkan/src/window_render_context.rs
Normal 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<_>>()
|
||||
}
|
12
crates/engine_window/Cargo.toml
Normal file
12
crates/engine_window/Cargo.toml
Normal file
|
@ -0,0 +1,12 @@
|
|||
[package]
|
||||
name = "engine_window"
|
||||
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 }
|
17
crates/engine_window/src/config.rs
Normal file
17
crates/engine_window/src/config.rs
Normal file
|
@ -0,0 +1,17 @@
|
|||
use bevy_ecs::resource::Resource;
|
||||
use winit::{dpi::PhysicalSize, window::WindowAttributes};
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct WindowConfig {
|
||||
pub title: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
impl Into<WindowAttributes> for &WindowConfig {
|
||||
fn into(self) -> WindowAttributes {
|
||||
WindowAttributes::default()
|
||||
.with_title(self.title.clone())
|
||||
.with_inner_size(PhysicalSize::new(self.width as f64, self.height as f64))
|
||||
}
|
||||
}
|
56
crates/engine_window/src/lib.rs
Normal file
56
crates/engine_window/src/lib.rs
Normal file
|
@ -0,0 +1,56 @@
|
|||
use bevy_app::{App, AppExit, Plugin, PluginsState};
|
||||
use config::WindowConfig;
|
||||
use raw_handle::{DisplayHandleWrapper, EventLoopProxyWrapper};
|
||||
use state::WindowState;
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
pub mod config;
|
||||
pub mod raw_handle;
|
||||
pub mod state;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum WindowError {
|
||||
#[error("Failed to create event loop")]
|
||||
FailedToCreateEventLoop,
|
||||
}
|
||||
|
||||
pub struct WindowPlugin {
|
||||
pub window_config: WindowConfig,
|
||||
}
|
||||
|
||||
impl Plugin for WindowPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let world = app.world_mut();
|
||||
world.insert_resource(self.window_config.clone());
|
||||
|
||||
let mut event_loop_builder = EventLoop::with_user_event();
|
||||
let event_loop = event_loop_builder
|
||||
.build()
|
||||
.map_err(|_| WindowError::FailedToCreateEventLoop)
|
||||
.expect("Failed to create event loop");
|
||||
|
||||
world.insert_resource(DisplayHandleWrapper(event_loop.owned_display_handle()));
|
||||
|
||||
app.set_runner(Box::new(move |app| runner(app, event_loop)));
|
||||
}
|
||||
}
|
||||
|
||||
fn runner(mut app: App, event_loop: EventLoop<()>) -> AppExit {
|
||||
if app.plugins_state() == PluginsState::Ready {
|
||||
app.finish();
|
||||
app.cleanup();
|
||||
}
|
||||
|
||||
app.world_mut()
|
||||
.insert_resource(EventLoopProxyWrapper::new(event_loop.create_proxy()));
|
||||
|
||||
let mut window_state = WindowState::new(app);
|
||||
|
||||
match event_loop.run_app(&mut window_state) {
|
||||
Ok(_) => AppExit::Success,
|
||||
Err(e) => {
|
||||
log::error!("Error running window state: {e}");
|
||||
AppExit::error()
|
||||
}
|
||||
}
|
||||
}
|
23
crates/engine_window/src/raw_handle.rs
Normal file
23
crates/engine_window/src/raw_handle.rs
Normal file
|
@ -0,0 +1,23 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use bevy_ecs::resource::Resource;
|
||||
use winit::{event_loop::EventLoopProxy, window::Window};
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct EventLoopProxyWrapper<T: 'static>(EventLoopProxy<T>);
|
||||
|
||||
impl<T: 'static> EventLoopProxyWrapper<T> {
|
||||
pub fn new(event_loop: EventLoopProxy<T>) -> Self {
|
||||
Self(event_loop)
|
||||
}
|
||||
|
||||
pub fn proxy(&self) -> &EventLoopProxy<T> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct DisplayHandleWrapper(pub winit::event_loop::OwnedDisplayHandle);
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct WindowWrapper(pub Arc<Window>);
|
63
crates/engine_window/src/state.rs
Normal file
63
crates/engine_window/src/state.rs
Normal file
|
@ -0,0 +1,63 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use bevy_app::{App, PluginsState};
|
||||
use bevy_ecs::world::World;
|
||||
use winit::{
|
||||
application::ApplicationHandler, event::WindowEvent, event_loop::ActiveEventLoop,
|
||||
window::WindowId,
|
||||
};
|
||||
|
||||
use super::{config::WindowConfig, raw_handle::WindowWrapper};
|
||||
|
||||
pub struct WindowState {
|
||||
app: App,
|
||||
}
|
||||
|
||||
impl WindowState {
|
||||
pub fn new(app: App) -> Self {
|
||||
Self { app }
|
||||
}
|
||||
|
||||
fn world(&self) -> &World {
|
||||
self.app.world()
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for WindowState {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window_config = self.world().get_resource::<WindowConfig>().unwrap();
|
||||
|
||||
let window = event_loop.create_window(window_config.into()).unwrap();
|
||||
self.app
|
||||
.world_mut()
|
||||
.insert_resource(WindowWrapper(Arc::new(window)));
|
||||
}
|
||||
|
||||
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
|
||||
if self.app.plugins_state() == PluginsState::Ready {
|
||||
self.app.finish();
|
||||
self.app.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
log::debug!("The close button was pressed; stopping");
|
||||
event_loop.exit();
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
if self.app.plugins_state() == PluginsState::Cleaned {
|
||||
self.app.update();
|
||||
}
|
||||
|
||||
let window_wrapper = self.app.world().get_resource::<WindowWrapper>().unwrap();
|
||||
|
||||
window_wrapper.0.request_redraw();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue