Compare commits
1 commit
main
...
main-refac
Author | SHA1 | Date | |
---|---|---|---|
42db1a33a0 |
46 changed files with 1308 additions and 2624 deletions
10
.cursor/mcp.json
Normal file
10
.cursor/mcp.json
Normal file
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"mcpServers": {
|
||||
"run-program": {
|
||||
"command": "cargo",
|
||||
"args": [
|
||||
"run"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
991
Cargo.lock
generated
991
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
30
Cargo.toml
30
Cargo.toml
|
@ -5,13 +5,8 @@ edition = "2024"
|
|||
authors = ["Florian RICHER <florian.richer@protonmail.com>"]
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.dependencies]
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
thiserror = "2.0"
|
||||
winit = { version = "0.30", features = ["rwh_06"] }
|
||||
|
||||
vulkano = "0.35"
|
||||
|
@ -21,27 +16,8 @@ vulkano-shaders = "0.35"
|
|||
glam = { version = "0.30" }
|
||||
|
||||
# ECS
|
||||
bevy_ecs = "0.16"
|
||||
bevy_app = "0.16"
|
||||
apecs = "0.8"
|
||||
|
||||
# Log and tracing
|
||||
log = "0.4"
|
||||
env_logger = "0.11"
|
||||
|
||||
engine_vulkan = { path = "crates/engine_vulkan" }
|
||||
engine_window = { path = "crates/engine_window" }
|
||||
engine_render = { path = "crates/engine_render" }
|
||||
|
||||
[dependencies]
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
bevy_app = { workspace = true }
|
||||
bevy_ecs = { workspace = true }
|
||||
winit = { workspace = true }
|
||||
vulkano = { workspace = true }
|
||||
vulkano-shaders = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
|
||||
engine_vulkan = { workspace = true }
|
||||
engine_window = { workspace = true }
|
||||
engine_render = { workspace = true }
|
||||
env_logger = "0.11.5"
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
# Project
|
||||
|
||||
## Usefull links
|
||||
|
||||
- https://vulkan-tutorial.com/fr/Introduction
|
||||
- https://github.com/bwasty/vulkan-tutorial-rs
|
|
@ -1,12 +0,0 @@
|
|||
[package]
|
||||
name = "engine_render"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
log = { workspace = true }
|
||||
bevy_app = { workspace = true }
|
||||
bevy_ecs = { workspace = true }
|
||||
vulkano = { workspace = true }
|
||||
engine_vulkan = { workspace = true }
|
||||
engine_window = { workspace = true }
|
|
@ -1,113 +0,0 @@
|
|||
use bevy_app::{App, AppLabel, Last, Plugin, SubApp};
|
||||
use bevy_ecs::{
|
||||
schedule::{IntoScheduleConfigs, Schedule, ScheduleLabel, SystemSet},
|
||||
system::{Commands, Res},
|
||||
world::World,
|
||||
};
|
||||
use engine_vulkan::{
|
||||
VulkanCommandBufferAllocator, VulkanDescriptorSetAllocator, VulkanDevice, VulkanGraphicsQueue,
|
||||
VulkanInstance, VulkanMemoryAllocator,
|
||||
};
|
||||
use engine_window::raw_handle::WindowWrapper;
|
||||
use window::WindowRenderPlugin;
|
||||
|
||||
pub mod window;
|
||||
|
||||
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
|
||||
pub enum RenderSystems {
|
||||
ManageViews,
|
||||
Prepare,
|
||||
Queue,
|
||||
Render,
|
||||
Present,
|
||||
}
|
||||
|
||||
#[derive(ScheduleLabel, Debug, Hash, PartialEq, Eq, Clone, Default)]
|
||||
pub struct Render;
|
||||
|
||||
impl Render {
|
||||
pub fn base_schedule() -> Schedule {
|
||||
use RenderSystems::*;
|
||||
|
||||
let mut schedule = Schedule::new(Self);
|
||||
|
||||
schedule.configure_sets((ManageViews, Prepare, Queue, Render, Present).chain());
|
||||
|
||||
schedule
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, AppLabel)]
|
||||
pub struct RenderApp;
|
||||
|
||||
pub struct RenderPlugin;
|
||||
|
||||
impl Plugin for RenderPlugin {
|
||||
fn build(&self, _app: &mut App) {}
|
||||
|
||||
fn ready(&self, app: &App) -> bool {
|
||||
let world = app.world();
|
||||
|
||||
world.get_resource::<WindowWrapper>().is_some()
|
||||
&& world.get_resource::<VulkanInstance>().is_some()
|
||||
&& world.get_resource::<VulkanDevice>().is_some()
|
||||
&& world.get_resource::<VulkanGraphicsQueue>().is_some()
|
||||
&& world.get_resource::<VulkanMemoryAllocator>().is_some()
|
||||
&& world
|
||||
.get_resource::<VulkanCommandBufferAllocator>()
|
||||
.is_some()
|
||||
&& world
|
||||
.get_resource::<VulkanDescriptorSetAllocator>()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
let mut render_app = SubApp::new();
|
||||
render_app.update_schedule = Some(Render.intern());
|
||||
render_app.add_schedule(Render::base_schedule());
|
||||
|
||||
extract_app_resources(app.world_mut(), render_app.world_mut());
|
||||
|
||||
app.insert_sub_app(RenderApp, render_app);
|
||||
|
||||
app.add_plugins(WindowRenderPlugin);
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_app_resources(world: &mut World, render_world: &mut World) {
|
||||
let window_wrapper = world
|
||||
.get_resource::<WindowWrapper>()
|
||||
.expect("Failed to get WindowWrapper. Check is WindowPlugin is added before RenderPlugin.");
|
||||
|
||||
let vulkan_instance = world.get_resource::<VulkanInstance>().expect(
|
||||
"Failed to get Vulkan instance. Check is VulkanPlugin is added before RenderPlugin.",
|
||||
);
|
||||
|
||||
let vulkan_device = world
|
||||
.get_resource::<VulkanDevice>()
|
||||
.expect("Failed to get Vulkan device. Check is VulkanPlugin is added before RenderPlugin.");
|
||||
|
||||
let vulkan_graphics_queue = world.get_resource::<VulkanGraphicsQueue>().expect(
|
||||
"Failed to get Vulkan graphics queue. Check is VulkanPlugin is added before RenderPlugin.",
|
||||
);
|
||||
|
||||
let vulkan_memory_allocator = world
|
||||
.get_resource::<VulkanMemoryAllocator>()
|
||||
.expect("Failed to get Vulkan memory allocator. Check is VulkanPlugin is added before RenderPlugin.");
|
||||
|
||||
let vulkan_command_buffer_allocator = world
|
||||
.get_resource::<VulkanCommandBufferAllocator>()
|
||||
.expect("Failed to get Vulkan command buffer allocator. Check is VulkanPlugin is added before RenderPlugin.");
|
||||
|
||||
let vulkan_descriptor_set_allocator = world
|
||||
.get_resource::<VulkanDescriptorSetAllocator>()
|
||||
.expect("Failed to get Vulkan descriptor set allocator. Check is VulkanPlugin is added before RenderPlugin.");
|
||||
|
||||
render_world.insert_resource(vulkan_instance.clone());
|
||||
render_world.insert_resource(vulkan_device.clone());
|
||||
render_world.insert_resource(vulkan_graphics_queue.clone());
|
||||
render_world.insert_resource(vulkan_memory_allocator.clone());
|
||||
render_world.insert_resource(vulkan_command_buffer_allocator.clone());
|
||||
render_world.insert_resource(vulkan_descriptor_set_allocator.clone());
|
||||
render_world.insert_resource(window_wrapper.clone());
|
||||
}
|
|
@ -1,224 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_ecs::{
|
||||
resource::Resource,
|
||||
schedule::IntoScheduleConfigs,
|
||||
system::{Res, ResMut},
|
||||
};
|
||||
use engine_vulkan::{VulkanDevice, VulkanInstance};
|
||||
use engine_window::raw_handle::WindowWrapper;
|
||||
use vulkano::{
|
||||
image::{Image, ImageUsage, view::ImageView},
|
||||
pipeline::graphics::viewport::Viewport,
|
||||
swapchain::{Surface, Swapchain, SwapchainCreateInfo},
|
||||
sync::{self, GpuFuture},
|
||||
};
|
||||
|
||||
use super::{Render, RenderApp, RenderSystems};
|
||||
|
||||
pub struct WindowSurfaceData {
|
||||
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>>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
pub struct WindowSurface {
|
||||
pub surface: Option<WindowSurfaceData>,
|
||||
}
|
||||
|
||||
pub struct WindowRenderPlugin;
|
||||
|
||||
impl Plugin for WindowRenderPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let render_app = app
|
||||
.get_sub_app_mut(RenderApp)
|
||||
.expect("Failed to get RenderApp. Check is RenderPlugin is added.");
|
||||
|
||||
render_app.init_resource::<WindowSurface>();
|
||||
|
||||
render_app.add_systems(
|
||||
Render,
|
||||
create_window_surface
|
||||
.in_set(RenderSystems::ManageViews)
|
||||
.run_if(need_create_window_surface)
|
||||
.before(need_update_window_surface),
|
||||
);
|
||||
|
||||
render_app.add_systems(
|
||||
Render,
|
||||
update_window_surface
|
||||
.in_set(RenderSystems::ManageViews)
|
||||
.run_if(need_update_window_surface),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn need_create_window_surface(window_surface: Res<WindowSurface>) -> bool {
|
||||
window_surface.surface.is_none()
|
||||
}
|
||||
|
||||
fn create_window_surface(
|
||||
mut window_surface: ResMut<WindowSurface>,
|
||||
window_handle: Res<WindowWrapper>,
|
||||
vulkan_instance: Res<VulkanInstance>,
|
||||
vulkan_device: Res<VulkanDevice>,
|
||||
) {
|
||||
let window_size = window_handle.0.inner_size();
|
||||
|
||||
let surface = Surface::from_window(vulkan_instance.0.clone(), window_handle.0.clone())
|
||||
.expect("Failed to create surface");
|
||||
log::debug!("Surface created");
|
||||
|
||||
let (swapchain, images) = {
|
||||
let surface_capabilities = vulkan_device
|
||||
.0
|
||||
.physical_device()
|
||||
.surface_capabilities(&surface, Default::default())
|
||||
.unwrap();
|
||||
|
||||
let (image_format, _) = vulkan_device
|
||||
.0
|
||||
.physical_device()
|
||||
.surface_formats(&surface, Default::default())
|
||||
.unwrap()[0];
|
||||
|
||||
Swapchain::new(
|
||||
vulkan_device.0.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()
|
||||
};
|
||||
log_swapchain_info(&swapchain, false);
|
||||
|
||||
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,
|
||||
};
|
||||
log_viewport_info(&viewport, false);
|
||||
|
||||
let recreate_swapchain = false;
|
||||
let previous_frame_end = Some(sync::now(vulkan_device.0.clone()).boxed_send_sync());
|
||||
|
||||
window_surface.surface = Some(WindowSurfaceData {
|
||||
swapchain,
|
||||
attachment_image_views,
|
||||
viewport,
|
||||
recreate_swapchain,
|
||||
previous_frame_end,
|
||||
});
|
||||
}
|
||||
|
||||
fn window_size_dependent_setup(images: &[Arc<Image>]) -> Vec<Arc<ImageView>> {
|
||||
images
|
||||
.iter()
|
||||
.map(|image| ImageView::new_default(image.clone()).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
fn need_update_window_surface(window_surface: Res<WindowSurface>) -> bool {
|
||||
match &window_surface.surface {
|
||||
Some(surface) => surface.recreate_swapchain,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn update_window_surface(
|
||||
mut window_surface: ResMut<WindowSurface>,
|
||||
window_handle: Res<WindowWrapper>,
|
||||
) {
|
||||
if window_surface.surface.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let window_surface = window_surface.surface.as_mut().unwrap();
|
||||
|
||||
if !window_surface.recreate_swapchain {
|
||||
return;
|
||||
}
|
||||
|
||||
let window_size = window_handle.0.inner_size();
|
||||
let (new_swapchain, new_images) = window_surface
|
||||
.swapchain
|
||||
.recreate(SwapchainCreateInfo {
|
||||
image_extent: window_size.into(),
|
||||
..window_surface.swapchain.create_info()
|
||||
})
|
||||
.expect("Failed to recreate swapchain");
|
||||
|
||||
window_surface.swapchain = new_swapchain;
|
||||
window_surface.attachment_image_views = window_size_dependent_setup(&new_images);
|
||||
window_surface.viewport.extent = window_size.into();
|
||||
window_surface.recreate_swapchain = false;
|
||||
|
||||
log_swapchain_info(&window_surface.swapchain, true);
|
||||
log_viewport_info(&window_surface.viewport, true);
|
||||
}
|
||||
|
||||
fn log_swapchain_info(swapchain: &Swapchain, recreate_swapchain: bool) {
|
||||
if recreate_swapchain {
|
||||
log::debug!("Swapchain recreated");
|
||||
} else {
|
||||
log::debug!("Swapchain created");
|
||||
}
|
||||
log::debug!(
|
||||
"\tMin image count: {}",
|
||||
swapchain.create_info().min_image_count
|
||||
);
|
||||
log::debug!("\tImage format: {:?}", swapchain.create_info().image_format);
|
||||
log::debug!("\tImage extent: {:?}", swapchain.create_info().image_extent);
|
||||
log::debug!("\tImage usage: {:?}", swapchain.create_info().image_usage);
|
||||
log::debug!(
|
||||
"\tComposite alpha: {:?}",
|
||||
swapchain.create_info().composite_alpha
|
||||
);
|
||||
log::debug!("\tPresent mode: {:?}", swapchain.create_info().present_mode);
|
||||
log::debug!(
|
||||
"\tImage sharing: {:?}",
|
||||
swapchain.create_info().image_sharing
|
||||
);
|
||||
log::debug!(
|
||||
"\tPre transform: {:?}",
|
||||
swapchain.create_info().pre_transform
|
||||
);
|
||||
log::debug!(
|
||||
"\tComposite alpha: {:?}",
|
||||
swapchain.create_info().composite_alpha
|
||||
);
|
||||
log::debug!("\tPresent mode: {:?}", swapchain.create_info().present_mode);
|
||||
log::debug!(
|
||||
"\tFull screen exclusive: {:?}",
|
||||
swapchain.create_info().full_screen_exclusive
|
||||
);
|
||||
}
|
||||
|
||||
fn log_viewport_info(viewport: &Viewport, recreate_viewport: bool) {
|
||||
if recreate_viewport {
|
||||
log::debug!("Viewport recreated");
|
||||
} else {
|
||||
log::debug!("Viewport created");
|
||||
}
|
||||
log::debug!("\tOffset: {:?}", viewport.offset);
|
||||
log::debug!("\tExtent: {:?}", viewport.extent);
|
||||
log::debug!("\tDepth range: {:?}", viewport.depth_range);
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
[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 }
|
|
@ -1,83 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use bevy_ecs::resource::Resource;
|
||||
use utils::{device::create_and_insert_device, instance::create_and_insert_instance};
|
||||
use vulkano::{
|
||||
command_buffer::allocator::StandardCommandBufferAllocator,
|
||||
descriptor_set::allocator::StandardDescriptorSetAllocator,
|
||||
device::{Device, DeviceExtensions, DeviceFeatures, Queue},
|
||||
instance::Instance,
|
||||
memory::allocator::StandardMemoryAllocator,
|
||||
};
|
||||
|
||||
use bevy_app::{App, Plugin};
|
||||
|
||||
mod utils;
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanInstance(pub Arc<Instance>);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanDevice(pub Arc<Device>);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanGraphicsQueue(pub Arc<Queue>);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanComputeQueue(pub Arc<Queue>);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanTransferQueue(pub Arc<Queue>);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanMemoryAllocator(pub Arc<StandardMemoryAllocator>);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanCommandBufferAllocator(pub Arc<StandardCommandBufferAllocator>);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct VulkanDescriptorSetAllocator(pub Arc<StandardDescriptorSetAllocator>);
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum VulkanError {
|
||||
#[error("Failed to create vulkan context")]
|
||||
FailedToCreateVulkanContext,
|
||||
}
|
||||
|
||||
pub struct VulkanConfig {
|
||||
pub instance_layers: Vec<String>,
|
||||
pub device_extensions: DeviceExtensions,
|
||||
pub device_features: DeviceFeatures,
|
||||
pub with_window_surface: bool,
|
||||
pub with_graphics_queue: bool,
|
||||
pub with_compute_queue: bool,
|
||||
pub with_transfer_queue: bool,
|
||||
}
|
||||
|
||||
impl Default for VulkanConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
instance_layers: Vec::default(),
|
||||
device_extensions: DeviceExtensions::default(),
|
||||
device_features: DeviceFeatures::default(),
|
||||
with_window_surface: true,
|
||||
with_graphics_queue: true,
|
||||
with_compute_queue: true,
|
||||
with_transfer_queue: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct VulkanPlugin {
|
||||
pub vulkan_config: VulkanConfig,
|
||||
}
|
||||
|
||||
impl Plugin for VulkanPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let world = app.world_mut();
|
||||
|
||||
create_and_insert_instance(world, &self.vulkan_config);
|
||||
create_and_insert_device(world, &self.vulkan_config);
|
||||
}
|
||||
}
|
|
@ -1,346 +0,0 @@
|
|||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use bevy_ecs::world::World;
|
||||
use engine_window::raw_handle::DisplayHandleWrapper;
|
||||
use vulkano::{
|
||||
VulkanError,
|
||||
command_buffer::allocator::StandardCommandBufferAllocator,
|
||||
descriptor_set::allocator::StandardDescriptorSetAllocator,
|
||||
device::{
|
||||
Device, DeviceCreateInfo, DeviceExtensions, Queue, QueueCreateInfo, QueueFlags,
|
||||
physical::{PhysicalDevice, PhysicalDeviceType},
|
||||
},
|
||||
memory::allocator::StandardMemoryAllocator,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
VulkanCommandBufferAllocator, VulkanComputeQueue, VulkanConfig, VulkanDescriptorSetAllocator,
|
||||
VulkanDevice, VulkanGraphicsQueue, VulkanInstance, VulkanMemoryAllocator, VulkanTransferQueue,
|
||||
};
|
||||
|
||||
pub fn create_and_insert_device(world: &mut World, config: &VulkanConfig) {
|
||||
let picked_device =
|
||||
pick_physical_device(world, &config).expect("Failed to pick physical device");
|
||||
|
||||
let device = picked_device.device;
|
||||
let physical_device = device.physical_device();
|
||||
|
||||
log::debug!("Vulkan device created");
|
||||
log::debug!(
|
||||
"\tPhysical device: {:?} ({:?})",
|
||||
physical_device.properties().device_name,
|
||||
physical_device.properties().device_type
|
||||
);
|
||||
log::debug!("\tDevice extensions: {:?}", device.enabled_extensions());
|
||||
log::debug!("\tDevice features: {:?}", device.enabled_features());
|
||||
|
||||
world.insert_resource(VulkanDevice(device.clone()));
|
||||
|
||||
log::debug!("\tDevice selected queues:");
|
||||
if config.with_graphics_queue {
|
||||
world.insert_resource(VulkanGraphicsQueue(
|
||||
picked_device
|
||||
.graphics_queue
|
||||
.expect("Failed to get graphics queue"),
|
||||
));
|
||||
log::debug!("\t\t- Graphics queue");
|
||||
}
|
||||
|
||||
if config.with_compute_queue {
|
||||
world.insert_resource(VulkanComputeQueue(
|
||||
picked_device
|
||||
.compute_queue
|
||||
.expect("Failed to get compute queue"),
|
||||
));
|
||||
log::debug!("\t\t- Compute queue");
|
||||
}
|
||||
|
||||
if config.with_transfer_queue {
|
||||
world.insert_resource(VulkanTransferQueue(
|
||||
picked_device
|
||||
.transfer_queue
|
||||
.expect("Failed to get transfer queue"),
|
||||
));
|
||||
log::debug!("\t\t- Transfer queue");
|
||||
}
|
||||
|
||||
world.insert_resource(VulkanMemoryAllocator(Arc::new(
|
||||
StandardMemoryAllocator::new_default(device.clone()),
|
||||
)));
|
||||
world.insert_resource(VulkanCommandBufferAllocator(Arc::new(
|
||||
StandardCommandBufferAllocator::new(device.clone(), Default::default()),
|
||||
)));
|
||||
world.insert_resource(VulkanDescriptorSetAllocator(Arc::new(
|
||||
StandardDescriptorSetAllocator::new(device.clone(), Default::default()),
|
||||
)));
|
||||
}
|
||||
|
||||
struct PickedDevice {
|
||||
pub device: Arc<Device>,
|
||||
pub graphics_queue: Option<Arc<Queue>>,
|
||||
pub compute_queue: Option<Arc<Queue>>,
|
||||
pub transfer_queue: Option<Arc<Queue>>,
|
||||
}
|
||||
|
||||
fn pick_physical_device(world: &World, config: &VulkanConfig) -> Option<PickedDevice> {
|
||||
let instance = world
|
||||
.get_resource::<VulkanInstance>()
|
||||
.expect("Failed to get VulkanInstance during vulkan plugin initialization");
|
||||
|
||||
instance
|
||||
.0
|
||||
.enumerate_physical_devices()
|
||||
.expect("Failed to enumerate physical devices")
|
||||
.filter_map(|p| check_physical_device_support(world, &p, config).and_then(|r| Some((p, r))))
|
||||
.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,
|
||||
})
|
||||
.take()
|
||||
.and_then(|(p, (device_extensions, picked_queues_info))| {
|
||||
Some(create_device(
|
||||
config,
|
||||
&p,
|
||||
device_extensions,
|
||||
&picked_queues_info,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn check_device_extensions_support(
|
||||
physical_device: &Arc<PhysicalDevice>,
|
||||
config: &VulkanConfig,
|
||||
) -> Option<DeviceExtensions> {
|
||||
let device_extensions = DeviceExtensions {
|
||||
khr_swapchain: config.with_window_surface,
|
||||
..config.device_extensions
|
||||
};
|
||||
|
||||
if physical_device
|
||||
.supported_extensions()
|
||||
.contains(&device_extensions)
|
||||
{
|
||||
log::debug!(
|
||||
"\t\t[OK] Device supports required extensions {:?}",
|
||||
device_extensions
|
||||
);
|
||||
Some(device_extensions)
|
||||
} else {
|
||||
log::debug!(
|
||||
"\t\t[FAILED] Device does not support required extensions {:?}",
|
||||
device_extensions
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
struct PickedQueuesInfo {
|
||||
graphics_queue_family_index: Option<u32>,
|
||||
compute_queue_family_index: Option<u32>,
|
||||
transfer_queue_family_index: Option<u32>,
|
||||
}
|
||||
|
||||
fn check_queues_support(
|
||||
world: &World,
|
||||
physical_device: &Arc<PhysicalDevice>,
|
||||
config: &VulkanConfig,
|
||||
) -> Option<PickedQueuesInfo> {
|
||||
let mut graphics_queue_family_index: Option<u32> = None;
|
||||
let mut compute_queue_family_index: Option<u32> = None;
|
||||
let mut transfer_queue_family_index: Option<u32> = None;
|
||||
|
||||
for (i, queue_family_property) in physical_device.queue_family_properties().iter().enumerate() {
|
||||
if config.with_graphics_queue && graphics_queue_family_index.is_none() {
|
||||
let graphics_supported = queue_family_property
|
||||
.queue_flags
|
||||
.intersects(QueueFlags::GRAPHICS);
|
||||
|
||||
let presentation_valid = if config.with_window_surface {
|
||||
let display_handle = world
|
||||
.get_resource::<DisplayHandleWrapper>()
|
||||
.expect("DisplayHandleWrapper must be added before VulkanPlugin");
|
||||
|
||||
physical_device
|
||||
.presentation_support(i as u32, &display_handle.0)
|
||||
.expect("Failed to check presentation support")
|
||||
} else {
|
||||
true
|
||||
};
|
||||
|
||||
if graphics_supported && presentation_valid {
|
||||
graphics_queue_family_index = Some(i as u32);
|
||||
}
|
||||
}
|
||||
|
||||
if config.with_compute_queue && compute_queue_family_index.is_none() {
|
||||
let compute_supported = queue_family_property
|
||||
.queue_flags
|
||||
.intersects(QueueFlags::COMPUTE);
|
||||
|
||||
if compute_supported {
|
||||
compute_queue_family_index = Some(i as u32);
|
||||
}
|
||||
}
|
||||
|
||||
if config.with_transfer_queue && transfer_queue_family_index.is_none() {
|
||||
let transfer_supported = queue_family_property
|
||||
.queue_flags
|
||||
.intersects(QueueFlags::TRANSFER);
|
||||
|
||||
if transfer_supported {
|
||||
transfer_queue_family_index = Some(i as u32);
|
||||
}
|
||||
}
|
||||
|
||||
if (!config.with_graphics_queue || graphics_queue_family_index.is_some())
|
||||
&& (!config.with_compute_queue || compute_queue_family_index.is_some())
|
||||
&& (!config.with_transfer_queue || transfer_queue_family_index.is_some())
|
||||
{
|
||||
// We found all required queues, no need to continue iterating
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !config.with_graphics_queue {
|
||||
log::debug!("\t\t[SKIPPED] Graphics queue is not required");
|
||||
} else if graphics_queue_family_index.is_some() {
|
||||
log::debug!(
|
||||
"\t\t[OK] Graphics queue is supported (family index: {:?})",
|
||||
graphics_queue_family_index
|
||||
);
|
||||
} else {
|
||||
log::debug!("\t\t[FAILED] Graphics queue is not supported");
|
||||
return None;
|
||||
}
|
||||
|
||||
if !config.with_compute_queue {
|
||||
log::debug!("\t\t[SKIPPED] Compute queue is not required");
|
||||
} else if compute_queue_family_index.is_some() {
|
||||
log::debug!(
|
||||
"\t\t[OK] Compute queue is supported (family index: {:?})",
|
||||
compute_queue_family_index
|
||||
);
|
||||
} else {
|
||||
log::debug!("\t\t[FAILED] Compute queue is not supported");
|
||||
return None;
|
||||
}
|
||||
|
||||
if !config.with_transfer_queue {
|
||||
log::debug!("\t\t[SKIPPED] Transfer queue is not required");
|
||||
} else if transfer_queue_family_index.is_some() {
|
||||
log::debug!(
|
||||
"\t\t[OK] Transfer queue is supported (family index: {:?})",
|
||||
transfer_queue_family_index
|
||||
);
|
||||
} else {
|
||||
log::debug!("\t\t[FAILED] Transfer queue is not supported");
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(PickedQueuesInfo {
|
||||
graphics_queue_family_index,
|
||||
compute_queue_family_index,
|
||||
transfer_queue_family_index,
|
||||
})
|
||||
}
|
||||
|
||||
fn check_physical_device_support(
|
||||
world: &World,
|
||||
physical_device: &Arc<PhysicalDevice>,
|
||||
config: &VulkanConfig,
|
||||
) -> Option<(DeviceExtensions, PickedQueuesInfo)> {
|
||||
log::debug!("Checking physical device");
|
||||
log::debug!("\tProperties");
|
||||
log::debug!("\t\tName: {}", physical_device.properties().device_name);
|
||||
log::debug!("\t\tAPI version: {}", physical_device.api_version());
|
||||
log::debug!(
|
||||
"\t\tDevice type: {:?}",
|
||||
physical_device.properties().device_type
|
||||
);
|
||||
log::debug!("\tRequired supports checking report");
|
||||
|
||||
let device_extensions = check_device_extensions_support(physical_device, config)?;
|
||||
let picked_queues_info = check_queues_support(world, physical_device, config)?;
|
||||
|
||||
Some((device_extensions, picked_queues_info))
|
||||
}
|
||||
|
||||
fn create_device(
|
||||
config: &VulkanConfig,
|
||||
physical_device: &Arc<PhysicalDevice>,
|
||||
device_extensions: DeviceExtensions,
|
||||
picked_queues_info: &PickedQueuesInfo,
|
||||
) -> PickedDevice {
|
||||
let mut queue_create_infos = HashMap::<u32, QueueCreateInfo>::new();
|
||||
|
||||
if config.with_graphics_queue {
|
||||
let entry = queue_create_infos
|
||||
.entry(picked_queues_info.graphics_queue_family_index.unwrap())
|
||||
.or_insert(QueueCreateInfo {
|
||||
queue_family_index: picked_queues_info.graphics_queue_family_index.unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
entry.queues.push(1.0);
|
||||
}
|
||||
|
||||
if config.with_compute_queue {
|
||||
let entry = queue_create_infos
|
||||
.entry(picked_queues_info.compute_queue_family_index.unwrap())
|
||||
.or_insert(QueueCreateInfo {
|
||||
queue_family_index: picked_queues_info.compute_queue_family_index.unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
entry.queues.push(1.0);
|
||||
}
|
||||
|
||||
if config.with_transfer_queue {
|
||||
let entry = queue_create_infos
|
||||
.entry(picked_queues_info.transfer_queue_family_index.unwrap())
|
||||
.or_insert(QueueCreateInfo {
|
||||
queue_family_index: picked_queues_info.transfer_queue_family_index.unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
entry.queues.push(1.0);
|
||||
}
|
||||
|
||||
let (device, mut queues) = Device::new(
|
||||
physical_device.clone(),
|
||||
DeviceCreateInfo {
|
||||
queue_create_infos: queue_create_infos.values().cloned().collect(),
|
||||
enabled_extensions: device_extensions,
|
||||
enabled_features: config.device_features,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("Failed to create device");
|
||||
|
||||
let mut graphics_queue = None;
|
||||
let mut compute_queue = None;
|
||||
let mut transfer_queue = None;
|
||||
|
||||
if config.with_graphics_queue {
|
||||
graphics_queue = queues.next();
|
||||
}
|
||||
|
||||
if config.with_compute_queue {
|
||||
compute_queue = queues.next();
|
||||
}
|
||||
|
||||
if config.with_transfer_queue {
|
||||
transfer_queue = queues.next();
|
||||
}
|
||||
|
||||
PickedDevice {
|
||||
device,
|
||||
graphics_queue,
|
||||
compute_queue,
|
||||
transfer_queue,
|
||||
}
|
||||
}
|
|
@ -1,70 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use bevy_ecs::world::World;
|
||||
use engine_window::raw_handle::DisplayHandleWrapper;
|
||||
use vulkano::{
|
||||
VulkanLibrary,
|
||||
instance::{Instance, InstanceCreateFlags, InstanceCreateInfo, InstanceExtensions},
|
||||
swapchain::Surface,
|
||||
};
|
||||
|
||||
use crate::{VulkanConfig, VulkanInstance};
|
||||
|
||||
fn load_library() -> Arc<VulkanLibrary> {
|
||||
let library = VulkanLibrary::new().unwrap();
|
||||
|
||||
log::debug!("Available Instance layers:");
|
||||
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 fn create_and_insert_instance(world: &mut World, config: &VulkanConfig) {
|
||||
let library = load_library();
|
||||
|
||||
let instance_extensions = {
|
||||
if config.with_window_surface {
|
||||
let display_handle = world
|
||||
.get_resource::<DisplayHandleWrapper>()
|
||||
.expect("DisplayHandleWrapper must be added before VulkanPlugin");
|
||||
|
||||
Surface::required_extensions(&display_handle.0)
|
||||
.expect("Failed to get surface required extensions")
|
||||
} else {
|
||||
InstanceExtensions::default()
|
||||
}
|
||||
};
|
||||
|
||||
let instance = Instance::new(
|
||||
library,
|
||||
InstanceCreateInfo {
|
||||
// Enable enumerating devices that use non-conformant Vulkan implementations.
|
||||
// (e.g. MoltenVK)
|
||||
flags: InstanceCreateFlags::ENUMERATE_PORTABILITY,
|
||||
enabled_extensions: instance_extensions,
|
||||
enabled_layers: config.instance_layers.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("Failed to create vulkan instance");
|
||||
|
||||
log::debug!("Instance created");
|
||||
log::debug!(
|
||||
"\t- Enabled extensions: {:?}",
|
||||
instance.enabled_extensions()
|
||||
);
|
||||
log::debug!("\t- Enabled layers: {:?}", instance.enabled_layers());
|
||||
log::debug!("\t- API version: {:?}", instance.api_version());
|
||||
log::debug!("\t- Max API version: {:?}", instance.max_api_version());
|
||||
log::debug!("\t- Flags: {:?}", instance.flags());
|
||||
|
||||
world.insert_resource(VulkanInstance(instance));
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
pub mod device;
|
||||
pub mod instance;
|
|
@ -1,11 +0,0 @@
|
|||
[package]
|
||||
name = "engine_window"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
bevy_app = { workspace = true }
|
||||
bevy_ecs = { workspace = true }
|
||||
winit = { workspace = true }
|
|
@ -1,17 +0,0 @@
|
|||
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))
|
||||
}
|
||||
}
|
|
@ -1,56 +0,0 @@
|
|||
use bevy_app::{App, AppExit, Plugin, PluginsState};
|
||||
use config::WindowConfig;
|
||||
use raw_handle::{DisplayHandleWrapper, EventLoopProxyWrapper, WindowWrapper};
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
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, Clone)]
|
||||
pub struct DisplayHandleWrapper(pub winit::event_loop::OwnedDisplayHandle);
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct WindowWrapper(pub Arc<Window>);
|
|
@ -1,63 +0,0 @@
|
|||
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) {}
|
||||
}
|
12
flake.lock
generated
12
flake.lock
generated
|
@ -44,11 +44,11 @@
|
|||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1747312588,
|
||||
"narHash": "sha256-MmJvj6mlWzeRwKGLcwmZpKaOPZ5nJb/6al5CXqJsgjo=",
|
||||
"lastModified": 1742546557,
|
||||
"narHash": "sha256-QyhimDBaDBtMfRc7kyL28vo+HTwXRPq3hz+BgSJDotw=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "b1bebd0fe266bbd1820019612ead889e96a8fa2d",
|
||||
"rev": "bfa9810ff7104a17555ab68ebdeafb6705f129b1",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
@ -73,11 +73,11 @@
|
|||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1747363019,
|
||||
"narHash": "sha256-N4dwkRBmpOosa4gfFkFf/LTD8oOcNkAyvZ07JvRDEf0=",
|
||||
"lastModified": 1742524367,
|
||||
"narHash": "sha256-KzTwk/5ETJavJZYV1DEWdCx05M4duFCxCpRbQSKWpng=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "0e624f2b1972a34be1a9b35290ed18ea4b419b6f",
|
||||
"rev": "70bf752d176b2ce07417e346d85486acea9040ef",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
|
14
flake.nix
14
flake.nix
|
@ -31,10 +31,14 @@
|
|||
cargo = rust;
|
||||
});
|
||||
|
||||
renderdoc = pkgs.renderdoc.overrideAttrs (oldAttrs: {
|
||||
cmakeFlags = oldAttrs.cmakeFlags ++ [
|
||||
(pkgs.lib.cmakeBool "ENABLE_UNSUPPORTED_EXPERIMENTAL_POSSIBLY_BROKEN_WAYLAND" true)
|
||||
];
|
||||
});
|
||||
|
||||
buildInputs = with pkgs; [ vulkan-headers vulkan-loader vulkan-validation-layers renderdoc ]
|
||||
++ pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux (with pkgs; [
|
||||
stdenv.cc.cc.lib
|
||||
|
||||
# Wayland
|
||||
libxkbcommon
|
||||
wayland
|
||||
|
@ -56,7 +60,7 @@
|
|||
|
||||
mkCustomShell = { packages ? [ ] }: pkgs.mkShell {
|
||||
nativeBuildInputs = [
|
||||
pkgs.renderdoc
|
||||
renderdoc
|
||||
(rust.override { extensions = [ "rust-src" "rust-analyzer" ]; })
|
||||
] ++ nativeBuildInputs;
|
||||
|
||||
|
@ -64,8 +68,8 @@
|
|||
++ packages;
|
||||
|
||||
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath buildInputs;
|
||||
VK_LAYER_PATH = "${pkgs.vulkan-validation-layers}/share/vulkan/explicit_layer.d:${pkgs.renderdoc}/share/vulkan/implicit_layer.d";
|
||||
RUST_LOG = "debug,rust_vulkan_test=trace";
|
||||
VK_LAYER_PATH = "${pkgs.vulkan-validation-layers}/share/vulkan/explicit_layer.d:${renderdoc}/share/vulkan/implicit_layer.d";
|
||||
RUST_LOG = "info,rust_vulkan_test=trace";
|
||||
};
|
||||
in
|
||||
{
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
[toolchain]
|
||||
channel = "1.87.0"
|
||||
channel = "1.85.1"
|
||||
|
|
|
@ -1,19 +0,0 @@
|
|||
use bevy_ecs::component::Component;
|
||||
use glam::{Mat4, Quat, Vec3};
|
||||
|
||||
pub trait Camera: Into<Mat4> + Component {}
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Camera3D {
|
||||
pub projection: Mat4,
|
||||
pub position: Vec3,
|
||||
pub rotation: Quat,
|
||||
}
|
||||
|
||||
impl Into<Mat4> for Camera3D {
|
||||
fn into(self) -> Mat4 {
|
||||
Mat4::from_rotation_translation(self.rotation, self.position) * self.projection
|
||||
}
|
||||
}
|
||||
|
||||
impl Camera for Camera3D {}
|
|
@ -1,2 +0,0 @@
|
|||
pub mod camera;
|
||||
pub mod render;
|
|
@ -1,7 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use bevy_ecs::component::Component;
|
||||
use vulkano::pipeline::GraphicsPipeline;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Material(pub Arc<GraphicsPipeline>);
|
|
@ -1,14 +0,0 @@
|
|||
use bevy_ecs::component::Component;
|
||||
|
||||
use super::vertex::Vertex2D;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Mesh2D {
|
||||
pub vertices: Vec<Vertex2D>,
|
||||
}
|
||||
|
||||
impl Mesh2D {
|
||||
pub fn new(vertices: Vec<Vertex2D>) -> Self {
|
||||
Self { vertices }
|
||||
}
|
||||
}
|
|
@ -1,3 +0,0 @@
|
|||
pub mod material;
|
||||
pub mod mesh;
|
||||
pub mod vertex;
|
|
@ -1,36 +0,0 @@
|
|||
use bevy_app::App;
|
||||
use engine_render::RenderPlugin;
|
||||
use engine_vulkan::{VulkanConfig, VulkanPlugin};
|
||||
use engine_window::{WindowPlugin, config::WindowConfig};
|
||||
use vulkano::device::{DeviceExtensions, DeviceFeatures};
|
||||
|
||||
pub fn init(app: &mut App) {
|
||||
let window_config = WindowConfig {
|
||||
title: "Rust ASH Test".to_string(),
|
||||
width: 800,
|
||||
height: 600,
|
||||
};
|
||||
|
||||
let device_extensions = DeviceExtensions {
|
||||
khr_dynamic_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let device_features = DeviceFeatures {
|
||||
dynamic_rendering: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let vulkan_config = VulkanConfig {
|
||||
instance_layers: vec![String::from("VK_LAYER_KHRONOS_validation")],
|
||||
device_extensions,
|
||||
device_features,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
app.add_plugins((
|
||||
WindowPlugin { window_config },
|
||||
VulkanPlugin { vulkan_config },
|
||||
RenderPlugin,
|
||||
));
|
||||
}
|
42
src/main.rs
42
src/main.rs
|
@ -1,40 +1,14 @@
|
|||
use winit::event_loop::{ControlFlow, EventLoop};
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
use bevy_app::{App, AppExit};
|
||||
mod renderer;
|
||||
mod vulkan;
|
||||
|
||||
pub mod core;
|
||||
pub mod game;
|
||||
pub mod old_app;
|
||||
use renderer::app::App;
|
||||
use vulkan::context::VulkanContext;
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
run_new_app();
|
||||
// run_old_app();
|
||||
}
|
||||
|
||||
fn run_new_app() {
|
||||
let mut app = App::default();
|
||||
game::init(&mut app);
|
||||
match app.run() {
|
||||
AppExit::Success => {}
|
||||
AppExit::Error(e) => {
|
||||
log::error!("Error running new app: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_old_app() {
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
|
||||
let vulkan_context = old_app::vulkan_context::VulkanContext::from(&event_loop);
|
||||
let mut app = old_app::app::App::from(vulkan_context);
|
||||
|
||||
match event_loop.run_app(&mut app) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::error!("Error running old app: {e}");
|
||||
}
|
||||
}
|
||||
let vulkan_context = VulkanContext::new(&event_loop).unwrap();
|
||||
let mut app = App::new(vulkan_context);
|
||||
event_loop.run_app(&mut app).unwrap();
|
||||
}
|
||||
|
|
|
@ -1,178 +0,0 @@
|
|||
use crate::old_app::scene::Scene;
|
||||
use crate::old_app::vulkan_context::VulkanContext;
|
||||
use crate::old_app::window_render_context::WindowRenderContext;
|
||||
use std::sync::Arc;
|
||||
use vulkano::command_buffer::{RenderingAttachmentInfo, RenderingInfo};
|
||||
use vulkano::render_pass::{AttachmentLoadOp, AttachmentStoreOp};
|
||||
use vulkano::swapchain::{SwapchainPresentInfo, acquire_next_image};
|
||||
use vulkano::sync::GpuFuture;
|
||||
use vulkano::{Validated, VulkanError, sync};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::window::WindowId;
|
||||
|
||||
pub struct App {
|
||||
vulkan_context: VulkanContext,
|
||||
window_render_context: Option<WindowRenderContext>,
|
||||
scene: Option<Scene>,
|
||||
}
|
||||
|
||||
impl From<VulkanContext> for App {
|
||||
fn from(vulkan_context: VulkanContext) -> Self {
|
||||
Self {
|
||||
vulkan_context,
|
||||
window_render_context: None,
|
||||
scene: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window_attributes = winit::window::Window::default_attributes()
|
||||
.with_title("Rust ASH Test")
|
||||
.with_inner_size(winit::dpi::PhysicalSize::new(
|
||||
f64::from(800),
|
||||
f64::from(600),
|
||||
));
|
||||
|
||||
let window = Arc::new(event_loop.create_window(window_attributes).unwrap());
|
||||
|
||||
let surface = self.vulkan_context.create_surface(window.clone());
|
||||
|
||||
self.window_render_context = Some(WindowRenderContext::new(
|
||||
window,
|
||||
surface,
|
||||
&self.vulkan_context.device,
|
||||
));
|
||||
self.scene = Some(
|
||||
Scene::load(
|
||||
&self.vulkan_context,
|
||||
self.window_render_context.as_ref().unwrap(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
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::Resized(_) => {
|
||||
let rcx = self.window_render_context.as_mut().unwrap();
|
||||
rcx.recreate_swapchain = true;
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
let (image_index, acquire_future) = {
|
||||
let rcx = self.window_render_context.as_mut().unwrap();
|
||||
let window_size = rcx.window.inner_size();
|
||||
|
||||
if window_size.width == 0 || window_size.height == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
rcx.previous_frame_end.as_mut().unwrap().cleanup_finished();
|
||||
rcx.update_swapchain().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}"),
|
||||
};
|
||||
|
||||
if suboptimal {
|
||||
rcx.recreate_swapchain = true;
|
||||
}
|
||||
|
||||
(image_index, acquire_future)
|
||||
};
|
||||
|
||||
let mut builder = self.vulkan_context.create_render_builder();
|
||||
|
||||
{
|
||||
let rcx = self.window_render_context.as_ref().unwrap();
|
||||
builder
|
||||
.begin_rendering(RenderingInfo {
|
||||
color_attachments: vec![Some(RenderingAttachmentInfo {
|
||||
load_op: AttachmentLoadOp::Clear,
|
||||
store_op: AttachmentStoreOp::Store,
|
||||
clear_value: Some([0.0, 0.0, 0.0, 1.0].into()),
|
||||
..RenderingAttachmentInfo::image_view(
|
||||
rcx.attachment_image_views[image_index as usize].clone(),
|
||||
)
|
||||
})],
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
.set_viewport(0, [rcx.viewport.clone()].into_iter().collect())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
if let Some(scene) = self.scene.as_ref() {
|
||||
scene
|
||||
.render(
|
||||
&self.vulkan_context,
|
||||
&self.window_render_context.as_ref().unwrap(),
|
||||
&mut builder,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
builder.end_rendering().unwrap();
|
||||
|
||||
let command_buffer = builder.build().unwrap();
|
||||
|
||||
{
|
||||
let rcx = self.window_render_context.as_mut().unwrap();
|
||||
|
||||
let future = rcx
|
||||
.previous_frame_end
|
||||
.take()
|
||||
.unwrap()
|
||||
.join(acquire_future)
|
||||
.then_execute(self.vulkan_context.graphics_queue.clone(), command_buffer)
|
||||
.unwrap()
|
||||
.then_swapchain_present(
|
||||
self.vulkan_context.graphics_queue.clone(),
|
||||
SwapchainPresentInfo::swapchain_image_index(
|
||||
rcx.swapchain.clone(),
|
||||
image_index,
|
||||
),
|
||||
)
|
||||
.then_signal_fence_and_flush();
|
||||
|
||||
match future.map_err(Validated::unwrap) {
|
||||
Ok(future) => {
|
||||
rcx.previous_frame_end = Some(future.boxed());
|
||||
}
|
||||
Err(VulkanError::OutOfDate) => {
|
||||
rcx.recreate_swapchain = true;
|
||||
rcx.previous_frame_end =
|
||||
Some(sync::now(self.vulkan_context.device.clone()).boxed());
|
||||
}
|
||||
Err(e) => {
|
||||
println!("failed to flush future: {e}");
|
||||
rcx.previous_frame_end =
|
||||
Some(sync::now(self.vulkan_context.device.clone()).boxed());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
let rcx = self.window_render_context.as_mut().unwrap();
|
||||
rcx.window.request_redraw();
|
||||
}
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
pub mod app;
|
||||
pub mod pipelines;
|
||||
pub mod scene;
|
||||
pub mod vulkan_context;
|
||||
pub mod window_render_context;
|
|
@ -1 +0,0 @@
|
|||
pub mod triangle_pipeline;
|
|
@ -1,111 +0,0 @@
|
|||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use vulkano::descriptor_set::layout::{
|
||||
DescriptorSetLayoutBinding, DescriptorSetLayoutCreateInfo, DescriptorType,
|
||||
};
|
||||
use vulkano::device::Device;
|
||||
use vulkano::pipeline::graphics::GraphicsPipelineCreateInfo;
|
||||
use vulkano::pipeline::graphics::color_blend::{ColorBlendAttachmentState, ColorBlendState};
|
||||
use vulkano::pipeline::graphics::input_assembly::InputAssemblyState;
|
||||
use vulkano::pipeline::graphics::multisample::MultisampleState;
|
||||
use vulkano::pipeline::graphics::rasterization::RasterizationState;
|
||||
use vulkano::pipeline::graphics::subpass::PipelineRenderingCreateInfo;
|
||||
use vulkano::pipeline::graphics::vertex_input::{Vertex, VertexDefinition};
|
||||
use vulkano::pipeline::graphics::viewport::ViewportState;
|
||||
use vulkano::pipeline::layout::{PipelineDescriptorSetLayoutCreateInfo, PipelineLayoutCreateFlags};
|
||||
use vulkano::pipeline::{
|
||||
DynamicState, GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo,
|
||||
};
|
||||
use vulkano::shader::{EntryPoint, ShaderStages};
|
||||
use vulkano::swapchain::Swapchain;
|
||||
|
||||
use crate::core::render::vertex::Vertex2D;
|
||||
|
||||
pub mod shaders {
|
||||
pub mod vs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "vertex",
|
||||
path: r"res/shaders/vertex.vert",
|
||||
}
|
||||
}
|
||||
|
||||
pub mod fs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "fragment",
|
||||
path: r"res/shaders/vertex.frag",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_triangle_pipeline(
|
||||
device: &Arc<Device>,
|
||||
swapchain: &Arc<Swapchain>,
|
||||
) -> Result<Arc<GraphicsPipeline>, Box<dyn Error>> {
|
||||
let (vs, fs) = load_shaders(device)?;
|
||||
let vertex_input_state = Vertex2D::per_vertex().definition(&vs)?;
|
||||
|
||||
let stages = [
|
||||
PipelineShaderStageCreateInfo::new(vs),
|
||||
PipelineShaderStageCreateInfo::new(fs),
|
||||
];
|
||||
|
||||
let mut bindings = BTreeMap::<u32, DescriptorSetLayoutBinding>::new();
|
||||
let mut descriptor_set_layout_binding =
|
||||
DescriptorSetLayoutBinding::descriptor_type(DescriptorType::UniformBuffer);
|
||||
descriptor_set_layout_binding.stages = ShaderStages::VERTEX;
|
||||
bindings.insert(0, descriptor_set_layout_binding);
|
||||
|
||||
let descriptor_set_layout = DescriptorSetLayoutCreateInfo {
|
||||
bindings,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let create_info = PipelineDescriptorSetLayoutCreateInfo {
|
||||
set_layouts: vec![descriptor_set_layout],
|
||||
flags: PipelineLayoutCreateFlags::default(),
|
||||
push_constant_ranges: vec![],
|
||||
}
|
||||
.into_pipeline_layout_create_info(device.clone())?;
|
||||
|
||||
let layout = PipelineLayout::new(device.clone(), create_info)?;
|
||||
|
||||
let subpass = PipelineRenderingCreateInfo {
|
||||
color_attachment_formats: vec![Some(swapchain.image_format())],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let pipeline = GraphicsPipeline::new(
|
||||
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.color_attachment_formats.len() as u32,
|
||||
ColorBlendAttachmentState::default(),
|
||||
)),
|
||||
dynamic_state: [DynamicState::Viewport].into_iter().collect(),
|
||||
subpass: Some(subpass.into()),
|
||||
..GraphicsPipelineCreateInfo::layout(layout)
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(pipeline)
|
||||
}
|
||||
|
||||
fn load_shaders(device: &Arc<Device>) -> Result<(EntryPoint, EntryPoint), Box<dyn Error>> {
|
||||
let vs = shaders::vs::load(device.clone())?
|
||||
.entry_point("main")
|
||||
.ok_or("Failed find main entry point of vertex shader".to_string())?;
|
||||
|
||||
let fs = shaders::fs::load(device.clone())?
|
||||
.entry_point("main")
|
||||
.ok_or("Failed find main entry point of fragment shader".to_string())?;
|
||||
|
||||
Ok((vs, fs))
|
||||
}
|
|
@ -1,175 +0,0 @@
|
|||
use crate::old_app::pipelines::triangle_pipeline::shaders::vs;
|
||||
use glam::{Mat3, Mat4, Vec3};
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use vulkano::buffer::{Buffer, BufferCreateInfo, BufferUsage, Subbuffer};
|
||||
use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer};
|
||||
use vulkano::descriptor_set::{DescriptorSet, WriteDescriptorSet};
|
||||
use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter};
|
||||
use vulkano::pipeline::{GraphicsPipeline, Pipeline, PipelineBindPoint};
|
||||
|
||||
use crate::core::render::vertex::Vertex2D;
|
||||
use crate::old_app::pipelines::triangle_pipeline::create_triangle_pipeline;
|
||||
|
||||
use super::vulkan_context::VulkanContext;
|
||||
use super::window_render_context::WindowRenderContext;
|
||||
|
||||
const VERTICES: [Vertex2D; 12] = [
|
||||
// Triangle en haut à gauche
|
||||
Vertex2D {
|
||||
position: [-0.5, -0.75],
|
||||
color: [1.0, 0.0, 0.0],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [-0.75, -0.25],
|
||||
color: [0.0, 1.0, 0.0],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [-0.25, -0.25],
|
||||
color: [0.0, 0.0, 1.0],
|
||||
},
|
||||
// Triangle en bas à gauche
|
||||
Vertex2D {
|
||||
position: [-0.5, 0.25],
|
||||
color: [0.5, 0.5, 0.5],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [-0.75, 0.75],
|
||||
color: [0.2, 0.8, 0.2],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [-0.25, 0.75],
|
||||
color: [0.8, 0.2, 0.2],
|
||||
},
|
||||
// Triangle en haut à droite
|
||||
Vertex2D {
|
||||
position: [0.5, -0.75],
|
||||
color: [1.0, 1.0, 0.0],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [0.25, -0.25],
|
||||
color: [0.0, 1.0, 1.0],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [0.75, -0.25],
|
||||
color: [1.0, 0.0, 1.0],
|
||||
},
|
||||
// Triangle en bas à droite
|
||||
Vertex2D {
|
||||
position: [0.5, 0.25],
|
||||
color: [0.1, 0.5, 0.8],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [0.25, 0.75],
|
||||
color: [0.8, 0.6, 0.1],
|
||||
},
|
||||
Vertex2D {
|
||||
position: [0.75, 0.75],
|
||||
color: [0.3, 0.4, 0.6],
|
||||
},
|
||||
];
|
||||
|
||||
pub struct Scene {
|
||||
pipeline: Arc<GraphicsPipeline>,
|
||||
vertex_buffer: Subbuffer<[Vertex2D]>,
|
||||
|
||||
rotation_start: Instant,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
pub fn load(
|
||||
vulkan_context: &VulkanContext,
|
||||
window_render_context: &WindowRenderContext,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
let pipeline =
|
||||
create_triangle_pipeline(&vulkan_context.device, &window_render_context.swapchain)?;
|
||||
let vertex_buffer =
|
||||
Vertex2D::create_buffer(Vec::from_iter(VERTICES), &vulkan_context.memory_allocator)?;
|
||||
|
||||
Ok(Scene {
|
||||
pipeline,
|
||||
vertex_buffer,
|
||||
rotation_start: Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&self,
|
||||
vulkan_context: &VulkanContext,
|
||||
window_render_context: &WindowRenderContext,
|
||||
builder: &mut AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let vertex_count = self.vertex_buffer.len() as u32;
|
||||
let instance_count = vertex_count / 3;
|
||||
|
||||
let uniform_buffer = self.get_uniform_buffer(vulkan_context, window_render_context);
|
||||
let layout = &self.pipeline.layout().set_layouts()[0];
|
||||
let descriptor_set = DescriptorSet::new(
|
||||
vulkan_context.descriptor_set_allocator.clone(),
|
||||
layout.clone(),
|
||||
[WriteDescriptorSet::buffer(0, uniform_buffer)],
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
unsafe {
|
||||
builder
|
||||
.bind_pipeline_graphics(self.pipeline.clone())?
|
||||
.bind_descriptor_sets(
|
||||
PipelineBindPoint::Graphics,
|
||||
self.pipeline.layout().clone(),
|
||||
0,
|
||||
descriptor_set,
|
||||
)?
|
||||
.bind_vertex_buffers(0, self.vertex_buffer.clone())?
|
||||
.draw(vertex_count, instance_count, 0, 0)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_uniform_buffer(
|
||||
&self,
|
||||
vulkan_context: &VulkanContext,
|
||||
window_render_context: &WindowRenderContext,
|
||||
) -> Subbuffer<vs::MVPData> {
|
||||
let swapchain = &window_render_context.swapchain;
|
||||
let elapsed = self.rotation_start.elapsed();
|
||||
let rotation = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 / 1_000_000_000.0;
|
||||
let rotation = Mat3::from_rotation_y(rotation as f32);
|
||||
|
||||
// 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 = swapchain.image_extent()[0] as f32 / swapchain.image_extent()[1] as f32;
|
||||
|
||||
let proj = Mat4::perspective_rh_gl(std::f32::consts::FRAC_PI_2, aspect_ratio, 0.01, 100.0);
|
||||
let view = Mat4::look_at_rh(
|
||||
Vec3::new(0.3, 0.3, 1.0),
|
||||
Vec3::new(0.0, 0.0, 0.0),
|
||||
Vec3::new(0.0, -1.0, 0.0),
|
||||
);
|
||||
let scale = Mat4::from_scale(Vec3::splat(1.0));
|
||||
|
||||
let uniform_data = vs::MVPData {
|
||||
world: Mat4::from_mat3(rotation).to_cols_array_2d(),
|
||||
view: (view * scale).to_cols_array_2d(),
|
||||
projection: proj.to_cols_array_2d(),
|
||||
};
|
||||
|
||||
Buffer::from_data(
|
||||
vulkan_context.memory_allocator.clone(),
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::UNIFORM_BUFFER,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
uniform_data,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
|
@ -1,213 +0,0 @@
|
|||
use std::{any::Any, sync::Arc};
|
||||
|
||||
use vulkano::{
|
||||
Version, VulkanLibrary,
|
||||
command_buffer::{
|
||||
AutoCommandBufferBuilder, CommandBufferUsage, PrimaryAutoCommandBuffer,
|
||||
allocator::StandardCommandBufferAllocator,
|
||||
},
|
||||
descriptor_set::allocator::StandardDescriptorSetAllocator,
|
||||
device::{
|
||||
Device, DeviceCreateInfo, DeviceExtensions, DeviceFeatures, Queue, QueueCreateInfo,
|
||||
QueueFlags,
|
||||
physical::{PhysicalDevice, PhysicalDeviceType},
|
||||
},
|
||||
instance::{Instance, InstanceCreateFlags, InstanceCreateInfo, InstanceExtensions},
|
||||
memory::allocator::StandardMemoryAllocator,
|
||||
swapchain::Surface,
|
||||
};
|
||||
use winit::{
|
||||
event_loop::EventLoop,
|
||||
raw_window_handle::{HasDisplayHandle, HasWindowHandle},
|
||||
};
|
||||
|
||||
pub struct VulkanContext {
|
||||
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 From<&EventLoop<()>> for VulkanContext {
|
||||
fn from(event_loop: &EventLoop<()>) -> Self {
|
||||
let library = load_library();
|
||||
|
||||
let enabled_extensions = Surface::required_extensions(event_loop).unwrap();
|
||||
log::debug!("Surface required extensions: {enabled_extensions:?}");
|
||||
|
||||
let instance = create_instance(library.clone(), enabled_extensions);
|
||||
|
||||
let (device, mut queues) = pick_graphics_device(&instance, event_loop);
|
||||
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,
|
||||
device,
|
||||
graphics_queue,
|
||||
memory_allocator,
|
||||
command_buffer_allocator,
|
||||
descriptor_set_allocator,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
fn find_physical_device_queue_family_indexes(
|
||||
physical_device: &Arc<PhysicalDevice>,
|
||||
event_loop: &EventLoop<()>,
|
||||
) -> 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, event_loop)
|
||||
.unwrap()
|
||||
{
|
||||
graphic_queue_family_index = Some(i as u32);
|
||||
}
|
||||
}
|
||||
|
||||
graphic_queue_family_index
|
||||
}
|
||||
|
||||
fn pick_physical_device_and_queue_family_indexes(
|
||||
instance: &Arc<Instance>,
|
||||
event_loop: &EventLoop<()>,
|
||||
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, event_loop)
|
||||
.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,
|
||||
})
|
||||
}
|
||||
|
||||
fn pick_graphics_device(
|
||||
instance: &Arc<Instance>,
|
||||
event_loop: &EventLoop<()>,
|
||||
) -> (
|
||||
Arc<Device>,
|
||||
impl ExactSizeIterator<Item = Arc<Queue>> + use<>,
|
||||
) {
|
||||
let mut device_extensions = DeviceExtensions {
|
||||
khr_swapchain: true,
|
||||
..DeviceExtensions::empty()
|
||||
};
|
||||
|
||||
let (physical_device, graphics_family_index) =
|
||||
pick_physical_device_and_queue_family_indexes(instance, event_loop, &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()
|
||||
}
|
|
@ -1,102 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
use vulkano::device::Device;
|
||||
use vulkano::image::view::ImageView;
|
||||
use vulkano::image::{Image, ImageUsage};
|
||||
use vulkano::pipeline::graphics::viewport::Viewport;
|
||||
use vulkano::swapchain::{Surface, Swapchain, SwapchainCreateInfo};
|
||||
use vulkano::sync::GpuFuture;
|
||||
use vulkano::{Validated, VulkanError, sync};
|
||||
use winit::window::Window;
|
||||
|
||||
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>>,
|
||||
}
|
||||
|
||||
impl WindowRenderContext {
|
||||
pub fn new(window: Arc<Window>, surface: Arc<Surface>, device: &Arc<Device>) -> Self {
|
||||
let window_size = window.inner_size();
|
||||
|
||||
let (swapchain, images) = {
|
||||
let surface_capabilities = device
|
||||
.physical_device()
|
||||
.surface_capabilities(&surface, Default::default())
|
||||
.unwrap();
|
||||
|
||||
let (image_format, _) = device
|
||||
.physical_device()
|
||||
.surface_formats(&surface, Default::default())
|
||||
.unwrap()[0];
|
||||
|
||||
Swapchain::new(
|
||||
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(device.clone()).boxed());
|
||||
|
||||
Self {
|
||||
window,
|
||||
swapchain,
|
||||
attachment_image_views,
|
||||
viewport,
|
||||
recreate_swapchain,
|
||||
previous_frame_end,
|
||||
}
|
||||
}
|
||||
|
||||
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<_>>()
|
||||
}
|
262
src/renderer/app.rs
Normal file
262
src/renderer/app.rs
Normal file
|
@ -0,0 +1,262 @@
|
|||
use crate::renderer::components::{Entity, Material, Mesh, Transform};
|
||||
use crate::vulkan::context::VulkanContext;
|
||||
use crate::vulkan::pipeline::{Pipeline, triangle::TrianglePipeline};
|
||||
use crate::vulkan::renderer::VulkanRenderer;
|
||||
use crate::vulkan::resources::vertex::{MVPData, Vertex2D};
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use vulkano::VulkanError;
|
||||
use vulkano::buffer::{Buffer, BufferCreateInfo, BufferUsage};
|
||||
use vulkano::command_buffer::{
|
||||
AutoCommandBufferBuilder, CommandBufferUsage, PrimaryAutoCommandBuffer,
|
||||
RenderingAttachmentInfo, RenderingInfo,
|
||||
};
|
||||
use vulkano::descriptor_set::{DescriptorSet, WriteDescriptorSet};
|
||||
use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter};
|
||||
use vulkano::pipeline::{Pipeline as VulkanPipeline, PipelineBindPoint};
|
||||
use vulkano::render_pass::{AttachmentLoadOp, AttachmentStoreOp};
|
||||
use vulkano::swapchain::Surface;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::window::WindowId;
|
||||
|
||||
pub struct App {
|
||||
pub vulkan_context: VulkanContext,
|
||||
pub renderer: Option<VulkanRenderer>,
|
||||
pub entities: Vec<Entity>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(vulkan_context: VulkanContext) -> Self {
|
||||
Self {
|
||||
vulkan_context,
|
||||
renderer: None,
|
||||
entities: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setup_test_entities(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
// Créer un pipeline de test
|
||||
let pipeline = TrianglePipeline::new(&self.vulkan_context.device);
|
||||
|
||||
// Créer un buffer de vertex pour un triangle
|
||||
let vertices = [
|
||||
Vertex2D {
|
||||
position: [-0.5, -0.5],
|
||||
color: [1.0, 0.0, 0.0], // Rouge
|
||||
},
|
||||
Vertex2D {
|
||||
position: [0.5, -0.5],
|
||||
color: [0.0, 1.0, 0.0], // Vert
|
||||
},
|
||||
Vertex2D {
|
||||
position: [0.0, 0.5],
|
||||
color: [0.0, 0.0, 1.0], // Bleu
|
||||
},
|
||||
];
|
||||
|
||||
let vertex_buffer =
|
||||
Vertex2D::create_buffer(vertices.to_vec(), &self.vulkan_context.memory_allocator)
|
||||
.unwrap();
|
||||
|
||||
// Créer un buffer uniform pour les matrices MVP
|
||||
let mvp_data = MVPData {
|
||||
world: [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
view: [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
projection: [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
};
|
||||
|
||||
let uniform_buffer = Buffer::from_data(
|
||||
self.vulkan_context.memory_allocator.clone(),
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::UNIFORM_BUFFER,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
mvp_data,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Créer un descriptor set de test
|
||||
let descriptor_set = DescriptorSet::new(
|
||||
self.vulkan_context.descriptor_set_allocator.clone(),
|
||||
pipeline
|
||||
.get_pipeline()
|
||||
.layout()
|
||||
.set_layouts()
|
||||
.get(0)
|
||||
.unwrap()
|
||||
.clone(),
|
||||
[WriteDescriptorSet::buffer(0, uniform_buffer)],
|
||||
[],
|
||||
)?;
|
||||
|
||||
let material = Material {
|
||||
pipeline: pipeline.get_pipeline().clone(),
|
||||
descriptor_set,
|
||||
};
|
||||
|
||||
// Créer quelques entités de test
|
||||
let mut entities = Vec::new();
|
||||
for i in 0..3 {
|
||||
entities.push(Entity {
|
||||
mesh: Mesh {
|
||||
vertex_buffer: vertex_buffer.clone(),
|
||||
vertex_count: 3,
|
||||
instance_count: 1,
|
||||
},
|
||||
material: material.clone(),
|
||||
transform: Transform {
|
||||
position: [i as f32 * 0.5 - 0.5, 0.0, 0.0],
|
||||
rotation: [0.0, 0.0, 0.0],
|
||||
scale: [1.0, 1.0, 1.0],
|
||||
},
|
||||
});
|
||||
}
|
||||
self.entities = entities;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&self,
|
||||
command_buffer: &mut AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
for entity in &self.entities {
|
||||
command_buffer
|
||||
.bind_pipeline_graphics(entity.material.pipeline.clone())
|
||||
.unwrap()
|
||||
.bind_descriptor_sets(
|
||||
PipelineBindPoint::Graphics,
|
||||
entity.material.pipeline.layout().clone(),
|
||||
0,
|
||||
entity.material.descriptor_set.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.bind_vertex_buffers(0, entity.mesh.vertex_buffer.clone())
|
||||
.unwrap();
|
||||
unsafe {
|
||||
command_buffer
|
||||
.draw(entity.mesh.vertex_count, 1, 0, 0)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window_attributes = winit::window::Window::default_attributes()
|
||||
.with_title("Rust ASH Test")
|
||||
.with_inner_size(winit::dpi::PhysicalSize::new(
|
||||
f64::from(800),
|
||||
f64::from(600),
|
||||
));
|
||||
|
||||
let window = Arc::new(event_loop.create_window(window_attributes).unwrap());
|
||||
|
||||
let surface =
|
||||
Surface::from_window(self.vulkan_context.instance.clone(), window.clone()).unwrap();
|
||||
|
||||
self.renderer = Some(VulkanRenderer::new(
|
||||
window,
|
||||
surface,
|
||||
self.vulkan_context.device.clone(),
|
||||
self.vulkan_context.queue.clone(),
|
||||
));
|
||||
|
||||
self.setup_test_entities().unwrap();
|
||||
}
|
||||
|
||||
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::Resized(_) => {
|
||||
let renderer = self.renderer.as_mut().unwrap();
|
||||
renderer.recreate_swapchain = true;
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
let (image_index, acquire_future) =
|
||||
match self.renderer.as_mut().unwrap().begin_frame() {
|
||||
Ok(r) => r,
|
||||
Err(VulkanError::OutOfDate) => return,
|
||||
Err(e) => panic!("failed to acquire next image: {e}"),
|
||||
};
|
||||
|
||||
let mut builder = AutoCommandBufferBuilder::primary(
|
||||
self.vulkan_context.command_buffer_allocator.clone(),
|
||||
self.vulkan_context.queue.queue_family_index(),
|
||||
CommandBufferUsage::OneTimeSubmit,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
builder
|
||||
.begin_rendering(RenderingInfo {
|
||||
color_attachments: vec![Some(RenderingAttachmentInfo {
|
||||
load_op: AttachmentLoadOp::Clear,
|
||||
store_op: AttachmentStoreOp::Store,
|
||||
clear_value: Some([0.0, 0.0, 0.0, 1.0].into()),
|
||||
..RenderingAttachmentInfo::image_view(
|
||||
self.renderer.as_ref().unwrap().attachment_image_views
|
||||
[image_index as usize]
|
||||
.clone(),
|
||||
)
|
||||
})],
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
.set_viewport(
|
||||
0,
|
||||
[self.renderer.as_ref().unwrap().viewport.clone()]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
self.render(&mut builder).unwrap();
|
||||
|
||||
{
|
||||
builder.end_rendering().unwrap();
|
||||
}
|
||||
|
||||
self.renderer
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.end_frame(image_index, acquire_future, builder)
|
||||
.unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
let renderer = self.renderer.as_mut().unwrap();
|
||||
renderer.window.request_redraw();
|
||||
}
|
||||
}
|
71
src/renderer/components.rs
Normal file
71
src/renderer/components.rs
Normal file
|
@ -0,0 +1,71 @@
|
|||
use std::sync::Arc;
|
||||
use vulkano::buffer::Subbuffer;
|
||||
use vulkano::buffer::allocator::SubbufferAllocator;
|
||||
use vulkano::command_buffer::allocator::StandardCommandBufferAllocator;
|
||||
use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer};
|
||||
use vulkano::descriptor_set::DescriptorSet;
|
||||
use vulkano::descriptor_set::allocator::StandardDescriptorSetAllocator;
|
||||
use vulkano::device::Device;
|
||||
use vulkano::memory::allocator::StandardMemoryAllocator;
|
||||
use vulkano::pipeline::GraphicsPipeline;
|
||||
use vulkano::pipeline::Pipeline;
|
||||
|
||||
use crate::vulkan::resources::vertex::Vertex2D;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Mesh {
|
||||
pub vertex_buffer: Subbuffer<[Vertex2D]>,
|
||||
pub vertex_count: u32,
|
||||
pub instance_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Material {
|
||||
pub pipeline: Arc<GraphicsPipeline>,
|
||||
pub descriptor_set: Arc<DescriptorSet>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Transform {
|
||||
pub position: [f32; 3],
|
||||
pub rotation: [f32; 3],
|
||||
pub scale: [f32; 3],
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RenderResources {
|
||||
pub device: Arc<Device>,
|
||||
pub memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
pub command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
|
||||
pub uniform_buffer_allocator: Arc<SubbufferAllocator>,
|
||||
pub descriptor_set_allocator: Arc<StandardDescriptorSetAllocator>,
|
||||
}
|
||||
|
||||
pub struct Entity {
|
||||
pub mesh: Mesh,
|
||||
pub material: Material,
|
||||
pub transform: Transform,
|
||||
}
|
||||
|
||||
pub fn render_system(
|
||||
_resources: &RenderResources,
|
||||
builder: &mut AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>,
|
||||
entities: &[Entity],
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
for entity in entities {
|
||||
unsafe {
|
||||
builder
|
||||
.bind_pipeline_graphics(entity.material.pipeline.clone())?
|
||||
.bind_descriptor_sets(
|
||||
vulkano::pipeline::PipelineBindPoint::Graphics,
|
||||
entity.material.pipeline.layout().clone(),
|
||||
0,
|
||||
entity.material.descriptor_set.clone(),
|
||||
)?
|
||||
.bind_vertex_buffers(0, entity.mesh.vertex_buffer.clone())?
|
||||
.draw(entity.mesh.vertex_count, entity.mesh.instance_count, 0, 0)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
2
src/renderer/mod.rs
Normal file
2
src/renderer/mod.rs
Normal file
|
@ -0,0 +1,2 @@
|
|||
pub mod app;
|
||||
pub mod components;
|
135
src/vulkan/context.rs
Normal file
135
src/vulkan/context.rs
Normal file
|
@ -0,0 +1,135 @@
|
|||
use std::sync::Arc;
|
||||
use vulkano::buffer::BufferUsage;
|
||||
use vulkano::buffer::allocator::{SubbufferAllocator, SubbufferAllocatorCreateInfo};
|
||||
use vulkano::command_buffer::allocator::StandardCommandBufferAllocator;
|
||||
use vulkano::descriptor_set::allocator::StandardDescriptorSetAllocator;
|
||||
use vulkano::device::physical::PhysicalDeviceType;
|
||||
use vulkano::device::{
|
||||
Device, DeviceCreateInfo, DeviceExtensions, DeviceFeatures, Queue, QueueCreateInfo, QueueFlags,
|
||||
};
|
||||
use vulkano::instance::{Instance, InstanceCreateFlags, InstanceCreateInfo};
|
||||
use vulkano::memory::allocator::{MemoryTypeFilter, StandardMemoryAllocator};
|
||||
use vulkano::swapchain::Surface;
|
||||
use vulkano::{Version, VulkanLibrary};
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
pub struct VulkanContext {
|
||||
pub instance: Arc<Instance>,
|
||||
pub device: Arc<Device>,
|
||||
pub queue: Arc<Queue>,
|
||||
pub memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
pub command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
|
||||
pub uniform_buffer_allocator: Arc<SubbufferAllocator>,
|
||||
pub descriptor_set_allocator: Arc<StandardDescriptorSetAllocator>,
|
||||
}
|
||||
|
||||
impl VulkanContext {
|
||||
pub fn new(event_loop: &EventLoop<()>) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let library = VulkanLibrary::new().unwrap();
|
||||
for layer in library.layer_properties().unwrap() {
|
||||
log::debug!("Available layer: {}", layer.name());
|
||||
}
|
||||
|
||||
let required_extensions = Surface::required_extensions(event_loop).unwrap();
|
||||
let instance = Instance::new(
|
||||
library,
|
||||
InstanceCreateInfo {
|
||||
flags: InstanceCreateFlags::ENUMERATE_PORTABILITY,
|
||||
enabled_extensions: required_extensions,
|
||||
enabled_layers: vec![String::from("VK_LAYER_KHRONOS_validation")],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut device_extensions = DeviceExtensions {
|
||||
khr_swapchain: true,
|
||||
..DeviceExtensions::empty()
|
||||
};
|
||||
|
||||
let (physical_device, queue_family_index) = instance
|
||||
.enumerate_physical_devices()
|
||||
.unwrap()
|
||||
.filter(|p| {
|
||||
p.api_version() >= Version::V1_3 || p.supported_extensions().khr_dynamic_rendering
|
||||
})
|
||||
.filter(|p| p.supported_extensions().contains(&device_extensions))
|
||||
.filter_map(|p| {
|
||||
p.queue_family_properties()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.position(|(_i, q)| q.queue_flags.intersects(QueueFlags::GRAPHICS))
|
||||
.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");
|
||||
|
||||
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);
|
||||
|
||||
let (device, mut queues) = Device::new(
|
||||
physical_device,
|
||||
DeviceCreateInfo {
|
||||
queue_create_infos: vec![QueueCreateInfo {
|
||||
queue_family_index,
|
||||
..Default::default()
|
||||
}],
|
||||
enabled_extensions: device_extensions,
|
||||
enabled_features: DeviceFeatures {
|
||||
dynamic_rendering: true,
|
||||
..DeviceFeatures::empty()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let queue = queues.next().unwrap();
|
||||
let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(device.clone()));
|
||||
let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new(
|
||||
device.clone(),
|
||||
Default::default(),
|
||||
));
|
||||
|
||||
let uniform_buffer_allocator = Arc::new(SubbufferAllocator::new(
|
||||
memory_allocator.clone(),
|
||||
SubbufferAllocatorCreateInfo {
|
||||
buffer_usage: BufferUsage::UNIFORM_BUFFER,
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
|
||||
let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new(
|
||||
device.clone(),
|
||||
Default::default(),
|
||||
));
|
||||
|
||||
Ok(Self {
|
||||
instance,
|
||||
device,
|
||||
queue,
|
||||
memory_allocator,
|
||||
command_buffer_allocator,
|
||||
uniform_buffer_allocator,
|
||||
descriptor_set_allocator,
|
||||
})
|
||||
}
|
||||
}
|
4
src/vulkan/mod.rs
Normal file
4
src/vulkan/mod.rs
Normal file
|
@ -0,0 +1,4 @@
|
|||
pub mod context;
|
||||
pub mod pipeline;
|
||||
pub mod renderer;
|
||||
pub mod resources;
|
30
src/vulkan/pipeline/mod.rs
Normal file
30
src/vulkan/pipeline/mod.rs
Normal file
|
@ -0,0 +1,30 @@
|
|||
pub mod triangle;
|
||||
|
||||
use std::sync::Arc;
|
||||
use vulkano::device::Device;
|
||||
use vulkano::pipeline::GraphicsPipeline;
|
||||
|
||||
pub trait Pipeline {
|
||||
fn create_pipeline(device: &Arc<Device>) -> Arc<GraphicsPipeline>;
|
||||
fn get_pipeline(&self) -> &Arc<GraphicsPipeline>;
|
||||
}
|
||||
|
||||
pub struct PipelineManager {
|
||||
pipelines: std::collections::HashMap<String, Arc<GraphicsPipeline>>,
|
||||
}
|
||||
|
||||
impl PipelineManager {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pipelines: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_pipeline(&mut self, name: String, pipeline: Arc<GraphicsPipeline>) {
|
||||
self.pipelines.insert(name, pipeline);
|
||||
}
|
||||
|
||||
pub fn get_pipeline(&self, name: &str) -> Option<&Arc<GraphicsPipeline>> {
|
||||
self.pipelines.get(name)
|
||||
}
|
||||
}
|
127
src/vulkan/pipeline/triangle.rs
Normal file
127
src/vulkan/pipeline/triangle.rs
Normal file
|
@ -0,0 +1,127 @@
|
|||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use vulkano::descriptor_set::layout::{
|
||||
DescriptorSetLayoutBinding, DescriptorSetLayoutCreateInfo, DescriptorType,
|
||||
};
|
||||
use vulkano::device::Device;
|
||||
use vulkano::pipeline::graphics::GraphicsPipelineCreateInfo;
|
||||
use vulkano::pipeline::graphics::color_blend::{ColorBlendAttachmentState, ColorBlendState};
|
||||
use vulkano::pipeline::graphics::input_assembly::InputAssemblyState;
|
||||
use vulkano::pipeline::graphics::multisample::MultisampleState;
|
||||
use vulkano::pipeline::graphics::rasterization::RasterizationState;
|
||||
use vulkano::pipeline::graphics::subpass::PipelineRenderingCreateInfo;
|
||||
use vulkano::pipeline::graphics::vertex_input::{Vertex, VertexDefinition};
|
||||
use vulkano::pipeline::graphics::viewport::ViewportState;
|
||||
use vulkano::pipeline::layout::{PipelineDescriptorSetLayoutCreateInfo, PipelineLayoutCreateFlags};
|
||||
use vulkano::pipeline::{
|
||||
DynamicState, GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo,
|
||||
};
|
||||
use vulkano::shader::{EntryPoint, ShaderStages};
|
||||
|
||||
use crate::vulkan::resources::vertex::Vertex2D;
|
||||
|
||||
use super::Pipeline;
|
||||
|
||||
mod shaders {
|
||||
pub mod vs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "vertex",
|
||||
path: r"res/shaders/vertex.vert",
|
||||
}
|
||||
}
|
||||
|
||||
pub mod fs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "fragment",
|
||||
path: r"res/shaders/vertex.frag",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TrianglePipeline {
|
||||
pipeline: Arc<GraphicsPipeline>,
|
||||
}
|
||||
|
||||
impl super::Pipeline for TrianglePipeline {
|
||||
fn create_pipeline(device: &Arc<Device>) -> Arc<GraphicsPipeline> {
|
||||
let (vs, fs) = load_shaders(device).unwrap();
|
||||
let vertex_input_state = Vertex2D::per_vertex().definition(&vs).unwrap();
|
||||
|
||||
let stages = [
|
||||
PipelineShaderStageCreateInfo::new(vs),
|
||||
PipelineShaderStageCreateInfo::new(fs),
|
||||
];
|
||||
|
||||
let mut bindings = BTreeMap::<u32, DescriptorSetLayoutBinding>::new();
|
||||
let mut descriptor_set_layout_binding =
|
||||
DescriptorSetLayoutBinding::descriptor_type(DescriptorType::UniformBuffer);
|
||||
descriptor_set_layout_binding.stages = ShaderStages::VERTEX;
|
||||
bindings.insert(0, descriptor_set_layout_binding);
|
||||
|
||||
let descriptor_set_layout = DescriptorSetLayoutCreateInfo {
|
||||
bindings,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let create_info = PipelineDescriptorSetLayoutCreateInfo {
|
||||
set_layouts: vec![descriptor_set_layout],
|
||||
flags: PipelineLayoutCreateFlags::default(),
|
||||
push_constant_ranges: vec![],
|
||||
}
|
||||
.into_pipeline_layout_create_info(device.clone())
|
||||
.unwrap();
|
||||
|
||||
let layout = PipelineLayout::new(device.clone(), create_info).unwrap();
|
||||
|
||||
let subpass = PipelineRenderingCreateInfo {
|
||||
color_attachment_formats: vec![Some(vulkano::format::Format::B8G8R8A8_UNORM)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
GraphicsPipeline::new(
|
||||
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.color_attachment_formats.len() as u32,
|
||||
ColorBlendAttachmentState::default(),
|
||||
)),
|
||||
dynamic_state: [DynamicState::Viewport].into_iter().collect(),
|
||||
subpass: Some(subpass.into()),
|
||||
..GraphicsPipelineCreateInfo::layout(layout)
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn get_pipeline(&self) -> &Arc<GraphicsPipeline> {
|
||||
&self.pipeline
|
||||
}
|
||||
}
|
||||
|
||||
impl TrianglePipeline {
|
||||
pub fn new(device: &Arc<Device>) -> Self {
|
||||
Self {
|
||||
pipeline: Self::create_pipeline(device),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_shaders(device: &Arc<Device>) -> Result<(EntryPoint, EntryPoint), Box<dyn Error>> {
|
||||
let vs = shaders::vs::load(device.clone())?
|
||||
.entry_point("main")
|
||||
.ok_or("Failed find main entry point of vertex shader".to_string())?;
|
||||
|
||||
let fs = shaders::fs::load(device.clone())?
|
||||
.entry_point("main")
|
||||
.ok_or("Failed find main entry point of fragment shader".to_string())?;
|
||||
|
||||
Ok((vs, fs))
|
||||
}
|
167
src/vulkan/renderer.rs
Normal file
167
src/vulkan/renderer.rs
Normal file
|
@ -0,0 +1,167 @@
|
|||
use std::sync::Arc;
|
||||
use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer};
|
||||
use vulkano::device::Queue;
|
||||
use vulkano::image::view::ImageView;
|
||||
use vulkano::pipeline::graphics::viewport::Viewport;
|
||||
use vulkano::swapchain::{Surface, Swapchain, SwapchainCreateInfo, SwapchainPresentInfo};
|
||||
use vulkano::sync::{self, GpuFuture};
|
||||
use vulkano::{Validated, VulkanError};
|
||||
use winit::window::Window;
|
||||
|
||||
pub struct VulkanRenderer {
|
||||
pub window: Arc<Window>,
|
||||
pub surface: Arc<Surface>,
|
||||
pub swapchain: Arc<Swapchain>,
|
||||
pub queue: Arc<Queue>,
|
||||
pub attachment_image_views: Vec<Arc<ImageView>>,
|
||||
pub previous_frame_end: Option<Box<dyn GpuFuture>>,
|
||||
pub recreate_swapchain: bool,
|
||||
pub viewport: Viewport,
|
||||
}
|
||||
|
||||
impl VulkanRenderer {
|
||||
pub fn new(
|
||||
window: Arc<Window>,
|
||||
surface: Arc<Surface>,
|
||||
device: Arc<vulkano::device::Device>,
|
||||
queue: Arc<Queue>,
|
||||
) -> Self {
|
||||
let window_size = window.inner_size();
|
||||
let surface_formats = device
|
||||
.physical_device()
|
||||
.surface_formats(&surface, Default::default())
|
||||
.unwrap();
|
||||
let surface_format = surface_formats[0];
|
||||
|
||||
let (swapchain, images) = Swapchain::new(
|
||||
device.clone(),
|
||||
surface.clone(),
|
||||
SwapchainCreateInfo {
|
||||
image_extent: window_size.into(),
|
||||
image_usage: vulkano::image::ImageUsage::COLOR_ATTACHMENT,
|
||||
image_format: surface_format.0,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let attachment_image_views = images
|
||||
.into_iter()
|
||||
.map(|image| ImageView::new_default(image).unwrap())
|
||||
.collect();
|
||||
|
||||
let viewport = Viewport {
|
||||
offset: [0.0, 0.0],
|
||||
extent: window_size.into(),
|
||||
depth_range: 0.0..=1.0,
|
||||
};
|
||||
|
||||
Self {
|
||||
window,
|
||||
surface,
|
||||
swapchain,
|
||||
queue,
|
||||
attachment_image_views,
|
||||
previous_frame_end: Some(sync::now(device).boxed()),
|
||||
recreate_swapchain: false,
|
||||
viewport,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_frame(&mut self) -> Result<(u32, Box<dyn GpuFuture>), VulkanError> {
|
||||
self.previous_frame_end.as_mut().unwrap().cleanup_finished();
|
||||
|
||||
if self.recreate_swapchain {
|
||||
self.recreate_swapchain();
|
||||
self.recreate_swapchain = false;
|
||||
}
|
||||
|
||||
let (image_index, suboptimal, acquire_future) =
|
||||
match vulkano::swapchain::acquire_next_image(self.swapchain.clone(), None)
|
||||
.map_err(Validated::unwrap)
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(VulkanError::OutOfDate) => {
|
||||
self.recreate_swapchain = true;
|
||||
return Err(VulkanError::OutOfDate);
|
||||
}
|
||||
Err(e) => panic!("failed to acquire next image: {e}"),
|
||||
};
|
||||
|
||||
if suboptimal {
|
||||
self.recreate_swapchain = true;
|
||||
}
|
||||
|
||||
Ok((image_index, acquire_future.boxed()))
|
||||
}
|
||||
|
||||
pub fn end_frame(
|
||||
&mut self,
|
||||
image_index: u32,
|
||||
acquire_future: Box<dyn GpuFuture>,
|
||||
command_buffer: AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>,
|
||||
) -> Result<(), VulkanError> {
|
||||
let command_buffer = command_buffer.build().unwrap();
|
||||
let future = self
|
||||
.previous_frame_end
|
||||
.take()
|
||||
.unwrap()
|
||||
.join(acquire_future)
|
||||
.then_execute(self.queue.clone(), command_buffer)
|
||||
.unwrap()
|
||||
.then_swapchain_present(
|
||||
self.queue.clone(),
|
||||
SwapchainPresentInfo::swapchain_image_index(self.swapchain.clone(), image_index),
|
||||
)
|
||||
.then_signal_fence_and_flush();
|
||||
|
||||
match future.map_err(Validated::unwrap) {
|
||||
Ok(future) => {
|
||||
self.previous_frame_end = Some(future.boxed());
|
||||
Ok(())
|
||||
}
|
||||
Err(VulkanError::OutOfDate) => {
|
||||
self.recreate_swapchain = true;
|
||||
self.previous_frame_end = Some(sync::now(self.queue.device().clone()).boxed());
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
println!("failed to flush future: {e}");
|
||||
self.previous_frame_end = Some(sync::now(self.queue.device().clone()).boxed());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recreate_swapchain(&mut self) {
|
||||
let image_extent: [u32; 2] = self.window.inner_size().into();
|
||||
if image_extent.contains(&0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let surface_formats = self
|
||||
.queue
|
||||
.device()
|
||||
.physical_device()
|
||||
.surface_formats(&self.surface, Default::default())
|
||||
.unwrap();
|
||||
let surface_format = surface_formats[0];
|
||||
|
||||
let (new_swapchain, new_images) = self
|
||||
.swapchain
|
||||
.recreate(SwapchainCreateInfo {
|
||||
image_extent,
|
||||
image_usage: vulkano::image::ImageUsage::COLOR_ATTACHMENT,
|
||||
image_format: surface_format.0,
|
||||
..self.swapchain.create_info()
|
||||
})
|
||||
.expect("failed to recreate swapchain");
|
||||
|
||||
self.swapchain = new_swapchain;
|
||||
self.attachment_image_views = new_images
|
||||
.into_iter()
|
||||
.map(|image| ImageView::new_default(image).unwrap())
|
||||
.collect();
|
||||
self.viewport.extent = [image_extent[0] as f32, image_extent[1] as f32];
|
||||
}
|
||||
}
|
65
src/vulkan/resources/buffer.rs
Normal file
65
src/vulkan/resources/buffer.rs
Normal file
|
@ -0,0 +1,65 @@
|
|||
use std::sync::Arc;
|
||||
use vulkano::buffer::BufferContents;
|
||||
use vulkano::buffer::{Buffer, BufferCreateInfo, BufferUsage, Subbuffer};
|
||||
use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator};
|
||||
|
||||
pub struct BufferManager {
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
}
|
||||
|
||||
impl BufferManager {
|
||||
pub fn new(memory_allocator: Arc<StandardMemoryAllocator>) -> Self {
|
||||
Self { memory_allocator }
|
||||
}
|
||||
|
||||
pub fn create_vertex_buffer<T: BufferContents + Clone>(&self, data: &[T]) -> Subbuffer<[T]> {
|
||||
Buffer::from_iter(
|
||||
self.memory_allocator.clone(),
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::VERTEX_BUFFER,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
data.iter().cloned(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn create_index_buffer(&self, data: &[u32]) -> Subbuffer<[u32]> {
|
||||
Buffer::from_iter(
|
||||
self.memory_allocator.clone(),
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::INDEX_BUFFER,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
data.iter().cloned(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn create_uniform_buffer<T: BufferContents + Copy>(&self, data: &T) -> Subbuffer<T> {
|
||||
Buffer::from_data(
|
||||
self.memory_allocator.clone(),
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::UNIFORM_BUFFER,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
*data,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
47
src/vulkan/resources/descriptor.rs
Normal file
47
src/vulkan/resources/descriptor.rs
Normal file
|
@ -0,0 +1,47 @@
|
|||
use std::sync::Arc;
|
||||
use vulkano::descriptor_set::DescriptorSet;
|
||||
use vulkano::descriptor_set::WriteDescriptorSet;
|
||||
use vulkano::descriptor_set::allocator::StandardDescriptorSetAllocator;
|
||||
use vulkano::descriptor_set::layout::{
|
||||
DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutCreateInfo, DescriptorType,
|
||||
};
|
||||
use vulkano::device::Device;
|
||||
use vulkano::shader::ShaderStages;
|
||||
|
||||
pub struct DescriptorManager {
|
||||
device: Arc<Device>,
|
||||
allocator: Arc<StandardDescriptorSetAllocator>,
|
||||
}
|
||||
|
||||
impl DescriptorManager {
|
||||
pub fn new(device: Arc<Device>, allocator: Arc<StandardDescriptorSetAllocator>) -> Self {
|
||||
Self { device, allocator }
|
||||
}
|
||||
|
||||
pub fn create_descriptor_set_layout(
|
||||
&self,
|
||||
bindings: &[(u32, DescriptorType, u32)],
|
||||
) -> Arc<DescriptorSetLayout> {
|
||||
let mut bindings_map = std::collections::BTreeMap::new();
|
||||
for (binding_index, ty, _count) in bindings {
|
||||
let mut binding = DescriptorSetLayoutBinding::descriptor_type(*ty);
|
||||
binding.stages = ShaderStages::all_graphics();
|
||||
bindings_map.insert(*binding_index, binding);
|
||||
}
|
||||
|
||||
let create_info = DescriptorSetLayoutCreateInfo {
|
||||
bindings: bindings_map,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
DescriptorSetLayout::new(self.device.clone(), create_info).unwrap()
|
||||
}
|
||||
|
||||
pub fn create_descriptor_set(
|
||||
&self,
|
||||
layout: &Arc<DescriptorSetLayout>,
|
||||
writes: Vec<WriteDescriptorSet>,
|
||||
) -> Arc<DescriptorSet> {
|
||||
DescriptorSet::new(self.allocator.clone(), layout.clone(), writes, []).unwrap()
|
||||
}
|
||||
}
|
3
src/vulkan/resources/mod.rs
Normal file
3
src/vulkan/resources/mod.rs
Normal file
|
@ -0,0 +1,3 @@
|
|||
pub mod buffer;
|
||||
pub mod descriptor;
|
||||
pub mod vertex;
|
|
@ -6,7 +6,7 @@ use vulkano::buffer::{
|
|||
use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator};
|
||||
use vulkano::pipeline::graphics::vertex_input::Vertex;
|
||||
|
||||
#[derive(BufferContents, Vertex)]
|
||||
#[derive(BufferContents, Vertex, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct Vertex2D {
|
||||
#[format(R32G32_SFLOAT)]
|
||||
|
@ -16,6 +16,14 @@ pub struct Vertex2D {
|
|||
pub color: [f32; 3],
|
||||
}
|
||||
|
||||
#[derive(BufferContents, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct MVPData {
|
||||
pub world: [[f32; 4]; 4],
|
||||
pub view: [[f32; 4]; 4],
|
||||
pub projection: [[f32; 4]; 4],
|
||||
}
|
||||
|
||||
impl Vertex2D {
|
||||
pub fn create_buffer(
|
||||
vertices: Vec<Vertex2D>,
|
||||
|
@ -32,7 +40,7 @@ impl Vertex2D {
|
|||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
vertices,
|
||||
vertices.into_iter(),
|
||||
)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue