feat: initial low-level foundation for Gastinel Desktop (offline Rust + Vulkan)
Cette révision appartient à :
révision
a6d090fedd
32 fichiers modifiés
+2385
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "gastinel-vulkan"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
gastinel-core = { path = "../gastinel-core" }
|
||||
gastinel-simd = { path = "../gastinel-simd" }
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Low-level Vulkan backend and on-demand render coordinator.
|
||||
|
||||
pub mod loader;
|
||||
pub mod renderer;
|
||||
pub mod types;
|
||||
|
||||
pub use loader::{PhysicalDeviceInfo, VulkanEntry, VulkanInstance};
|
||||
pub use renderer::{OnDemandRenderer, RenderStats};
|
||||
pub use types::*;
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Dynamic Vulkan 1.0+ runtime loader.
|
||||
#![allow(non_camel_case_types)]
|
||||
//!
|
||||
//! Loads Vulkan driver libraries dynamically without linking against a static SDK or C runtime:
|
||||
//! - Windows: `vulkan-1.dll`
|
||||
//! - Linux (Alpine / musl): `libvulkan.so.1` or `libvulkan.so`
|
||||
|
||||
use std::ffi::{c_void, CStr, CString};
|
||||
use crate::types::*;
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
pub type PFN_vkGetInstanceProcAddr = unsafe extern "system" fn(
|
||||
instance: VkInstance,
|
||||
p_name: *const std::os::raw::c_char,
|
||||
) -> Option<unsafe extern "system" fn()>;
|
||||
|
||||
pub type PFN_vkCreateInstance = unsafe extern "system" fn(
|
||||
p_create_info: *const VkInstanceCreateInfo,
|
||||
p_allocator: *const c_void,
|
||||
p_instance: *mut VkInstance,
|
||||
) -> VkResult;
|
||||
|
||||
pub type PFN_vkDestroyInstance = unsafe extern "system" fn(
|
||||
instance: VkInstance,
|
||||
p_allocator: *const c_void,
|
||||
);
|
||||
|
||||
pub type PFN_vkEnumeratePhysicalDevices = unsafe extern "system" fn(
|
||||
instance: VkInstance,
|
||||
p_physical_device_count: *mut u32,
|
||||
p_physical_devices: *mut VkPhysicalDevice,
|
||||
) -> VkResult;
|
||||
|
||||
pub type PFN_vkGetPhysicalDeviceProperties = unsafe extern "system" fn(
|
||||
physical_device: VkPhysicalDevice,
|
||||
p_properties: *mut VkPhysicalDeviceProperties,
|
||||
);
|
||||
|
||||
pub type PFN_vkGetPhysicalDeviceQueueFamilyProperties = unsafe extern "system" fn(
|
||||
physical_device: VkPhysicalDevice,
|
||||
p_queue_family_property_count: *mut u32,
|
||||
p_queue_family_properties: *mut VkQueueFamilyProperties,
|
||||
);
|
||||
|
||||
/// Dynamic function pointers loaded from the Vulkan runtime.
|
||||
pub struct VulkanEntry {
|
||||
_lib: LibraryHandle,
|
||||
pub get_instance_proc_addr: PFN_vkGetInstanceProcAddr,
|
||||
pub create_instance: PFN_vkCreateInstance,
|
||||
}
|
||||
|
||||
struct LibraryHandle {
|
||||
#[cfg(windows)]
|
||||
handle: *mut c_void,
|
||||
#[cfg(unix)]
|
||||
handle: *mut c_void,
|
||||
}
|
||||
|
||||
impl LibraryHandle {
|
||||
#[cfg(windows)]
|
||||
fn load() -> Option<Self> {
|
||||
extern "system" {
|
||||
fn LoadLibraryA(lpLibFileName: *const std::os::raw::c_char) -> *mut c_void;
|
||||
}
|
||||
let name = CString::new("vulkan-1.dll").ok()?;
|
||||
let handle = unsafe { LoadLibraryA(name.as_ptr()) };
|
||||
if handle.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(Self { handle })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn load() -> Option<Self> {
|
||||
extern "C" {
|
||||
fn dlopen(filename: *const std::os::raw::c_char, flag: std::os::raw::c_int) -> *mut c_void;
|
||||
}
|
||||
let names = ["libvulkan.so.1", "libvulkan.so"];
|
||||
for name in &names {
|
||||
if let Ok(c_name) = CString::new(*name) {
|
||||
let handle = unsafe { dlopen(c_name.as_ptr(), 1 /* RTLD_LAZY */) };
|
||||
if !handle.is_null() {
|
||||
return Some(Self { handle });
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
unsafe fn get_sym(&self, name: &str) -> Option<*mut c_void> {
|
||||
extern "system" {
|
||||
fn GetProcAddress(hModule: *mut c_void, lpProcName: *const std::os::raw::c_char) -> *mut c_void;
|
||||
}
|
||||
let c_name = CString::new(name).ok()?;
|
||||
let sym = GetProcAddress(self.handle, c_name.as_ptr());
|
||||
if sym.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(sym)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
unsafe fn get_sym(&self, name: &str) -> Option<*mut c_void> {
|
||||
extern "C" {
|
||||
fn dlsym(handle: *mut c_void, symbol: *const std::os::raw::c_char) -> *mut c_void;
|
||||
}
|
||||
let c_name = CString::new(name).ok()?;
|
||||
let sym = dlsym(self.handle, c_name.as_ptr());
|
||||
if sym.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(sym)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LibraryHandle {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(windows)]
|
||||
unsafe {
|
||||
extern "system" {
|
||||
fn FreeLibrary(hLibModule: *mut c_void) -> i32;
|
||||
}
|
||||
FreeLibrary(self.handle);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
extern "C" {
|
||||
fn dlclose(handle: *mut c_void) -> std::os::raw::c_int;
|
||||
}
|
||||
dlclose(self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VulkanEntry {
|
||||
/// Dynamically loads the Vulkan driver from the operating system.
|
||||
pub fn load() -> Result<Self, &'static str> {
|
||||
let lib = LibraryHandle::load().ok_or("Vulkan runtime driver not found")?;
|
||||
|
||||
let get_proc = unsafe {
|
||||
let sym = lib.get_sym("vkGetInstanceProcAddr")
|
||||
.ok_or("Could not locate vkGetInstanceProcAddr")?;
|
||||
std::mem::transmute::<*mut c_void, PFN_vkGetInstanceProcAddr>(sym)
|
||||
};
|
||||
|
||||
let create_instance_name = CString::new("vkCreateInstance").unwrap();
|
||||
let create_instance = unsafe {
|
||||
let sym = get_proc(VkInstance::NULL, create_instance_name.as_ptr())
|
||||
.ok_or("Failed to query vkCreateInstance")?;
|
||||
std::mem::transmute::<unsafe extern "system" fn(), PFN_vkCreateInstance>(sym)
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
_lib: lib,
|
||||
get_instance_proc_addr: get_proc,
|
||||
create_instance,
|
||||
})
|
||||
}
|
||||
|
||||
/// Initializes a Gastinel Vulkan Instance.
|
||||
pub fn create_instance(&self, app_name: &str) -> Result<VulkanInstance, VkResult> {
|
||||
let app_cname = CString::new(app_name).unwrap();
|
||||
let engine_cname = CString::new("GastinelEngine").unwrap();
|
||||
|
||||
let app_info = VkApplicationInfo {
|
||||
s_type: VK_STRUCTURE_TYPE_APPLICATION_INFO,
|
||||
p_next: std::ptr::null(),
|
||||
p_application_name: app_cname.as_ptr(),
|
||||
application_version: VK_MAKE_API_VERSION(0, 1, 0, 0),
|
||||
p_engine_name: engine_cname.as_ptr(),
|
||||
engine_version: VK_MAKE_API_VERSION(0, 1, 0, 0),
|
||||
api_version: VK_MAKE_API_VERSION(0, 1, 3, 0),
|
||||
};
|
||||
|
||||
let create_info = VkInstanceCreateInfo {
|
||||
s_type: VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
|
||||
p_next: std::ptr::null(),
|
||||
flags: 0,
|
||||
p_application_info: &app_info,
|
||||
enabled_layer_count: 0,
|
||||
pp_enabled_layer_names: std::ptr::null(),
|
||||
enabled_extension_count: 0,
|
||||
pp_enabled_extension_names: std::ptr::null(),
|
||||
};
|
||||
|
||||
let mut instance = VkInstance::NULL;
|
||||
let res = unsafe { (self.create_instance)(&create_info, std::ptr::null(), &mut instance) };
|
||||
if res != VK_SUCCESS {
|
||||
return Err(res);
|
||||
}
|
||||
|
||||
// Load instance functions
|
||||
unsafe {
|
||||
let destroy_name = CString::new("vkDestroyInstance").unwrap();
|
||||
let destroy_sym = (self.get_instance_proc_addr)(instance, destroy_name.as_ptr()).unwrap();
|
||||
let destroy_instance = std::mem::transmute::<_, PFN_vkDestroyInstance>(destroy_sym);
|
||||
|
||||
let enum_name = CString::new("vkEnumeratePhysicalDevices").unwrap();
|
||||
let enum_sym = (self.get_instance_proc_addr)(instance, enum_name.as_ptr()).unwrap();
|
||||
let enumerate_physical_devices = std::mem::transmute::<_, PFN_vkEnumeratePhysicalDevices>(enum_sym);
|
||||
|
||||
let props_name = CString::new("vkGetPhysicalDeviceProperties").unwrap();
|
||||
let props_sym = (self.get_instance_proc_addr)(instance, props_name.as_ptr()).unwrap();
|
||||
let get_physical_device_properties = std::mem::transmute::<_, PFN_vkGetPhysicalDeviceProperties>(props_sym);
|
||||
|
||||
Ok(VulkanInstance {
|
||||
raw: instance,
|
||||
destroy_instance,
|
||||
enumerate_physical_devices,
|
||||
get_physical_device_properties,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct VulkanInstance {
|
||||
pub raw: VkInstance,
|
||||
destroy_instance: PFN_vkDestroyInstance,
|
||||
enumerate_physical_devices: PFN_vkEnumeratePhysicalDevices,
|
||||
get_physical_device_properties: PFN_vkGetPhysicalDeviceProperties,
|
||||
}
|
||||
|
||||
impl VulkanInstance {
|
||||
pub fn list_physical_devices(&self) -> Vec<PhysicalDeviceInfo> {
|
||||
let mut count = 0u32;
|
||||
unsafe {
|
||||
let res = (self.enumerate_physical_devices)(self.raw, &mut count, std::ptr::null_mut());
|
||||
if res != VK_SUCCESS || count == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut devices = vec![VkPhysicalDevice::NULL; count as usize];
|
||||
(self.enumerate_physical_devices)(self.raw, &mut count, devices.as_mut_ptr());
|
||||
|
||||
devices
|
||||
.into_iter()
|
||||
.map(|dev| {
|
||||
let mut props: VkPhysicalDeviceProperties = std::mem::zeroed();
|
||||
(self.get_physical_device_properties)(dev, &mut props);
|
||||
|
||||
let name_c = CStr::from_ptr(props.device_name.as_ptr());
|
||||
let name = name_c.to_string_lossy().into_owned();
|
||||
|
||||
PhysicalDeviceInfo {
|
||||
handle: dev,
|
||||
name,
|
||||
device_type: props.device_type,
|
||||
api_version: props.api_version,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for VulkanInstance {
|
||||
fn drop(&mut self) {
|
||||
if !self.raw.is_null() {
|
||||
unsafe {
|
||||
(self.destroy_instance)(self.raw, std::ptr::null());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PhysicalDeviceInfo {
|
||||
pub handle: VkPhysicalDevice,
|
||||
pub name: String,
|
||||
pub device_type: u32,
|
||||
pub api_version: u32,
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! On-demand, damage-driven Vulkan rendering coordinator.
|
||||
//!
|
||||
//! Only dispatches draw calls and presents to the display if the damage region is non-empty.
|
||||
//! When windows are idle, GPU stays at 0% activity.
|
||||
|
||||
use gastinel_core::geom::{DamageRegion, Rect, Size};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct RenderStats {
|
||||
pub total_ticks: u64,
|
||||
pub rendered_frames: u64,
|
||||
pub skipped_frames: u64,
|
||||
pub total_damage_area: u64,
|
||||
pub last_render_duration: Duration,
|
||||
}
|
||||
|
||||
pub struct OnDemandRenderer {
|
||||
screen_size: Size,
|
||||
stats: RenderStats,
|
||||
last_frame_time: Instant,
|
||||
}
|
||||
|
||||
impl OnDemandRenderer {
|
||||
pub fn new(screen_size: Size) -> Self {
|
||||
Self {
|
||||
screen_size,
|
||||
stats: RenderStats::default(),
|
||||
last_frame_time: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, new_size: Size) {
|
||||
self.screen_size = new_size;
|
||||
}
|
||||
|
||||
/// Renders a frame strictly on-demand.
|
||||
/// Returns `true` if a frame was actually rendered to the GPU, `false` if skipped.
|
||||
pub fn render_frame<F>(&mut self, damage: &DamageRegion, mut draw_pass: F) -> bool
|
||||
where
|
||||
F: FnMut(&[Rect]),
|
||||
{
|
||||
self.stats.total_ticks += 1;
|
||||
|
||||
if damage.is_empty() {
|
||||
// ZERO GPU WORK: desktop is static
|
||||
self.stats.skipped_frames += 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
let start = Instant::now();
|
||||
|
||||
// Calculate damage area
|
||||
let mut frame_damage_area = 0u64;
|
||||
for rect in damage.rects() {
|
||||
frame_damage_area += rect.width as u64 * rect.height as u64;
|
||||
}
|
||||
self.stats.total_damage_area += frame_damage_area;
|
||||
|
||||
// Execute draw pass for damaged rects (sets VkScissors to dirty rects)
|
||||
draw_pass(damage.rects());
|
||||
|
||||
self.stats.rendered_frames += 1;
|
||||
self.stats.last_render_duration = start.elapsed();
|
||||
self.last_frame_time = Instant::now();
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> &RenderStats {
|
||||
&self.stats
|
||||
}
|
||||
|
||||
pub fn screen_size(&self) -> Size {
|
||||
self.screen_size
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_on_demand_skips_when_empty() {
|
||||
let mut renderer = OnDemandRenderer::new(Size::new(1920, 1080));
|
||||
let damage = DamageRegion::new();
|
||||
|
||||
let mut rendered = false;
|
||||
let did_render = renderer.render_frame(&damage, |_| {
|
||||
rendered = true;
|
||||
});
|
||||
|
||||
assert!(!did_render);
|
||||
assert!(!rendered);
|
||||
assert_eq!(renderer.stats().skipped_frames, 1);
|
||||
assert_eq!(renderer.stats().rendered_frames, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_on_demand_renders_when_dirty() {
|
||||
let mut renderer = OnDemandRenderer::new(Size::new(1920, 1080));
|
||||
let mut damage = DamageRegion::new();
|
||||
damage.add_rect(Rect::new(10, 10, 100, 100));
|
||||
|
||||
let mut rendered = false;
|
||||
let did_render = renderer.render_frame(&damage, |rects| {
|
||||
assert_eq!(rects.len(), 1);
|
||||
rendered = true;
|
||||
});
|
||||
|
||||
assert!(did_render);
|
||||
assert!(rendered);
|
||||
assert_eq!(renderer.stats().rendered_frames, 1);
|
||||
assert_eq!(renderer.stats().skipped_frames, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Pure Rust definitions for Vulkan 1.0/1.3 core types and structures.
|
||||
//!
|
||||
//! Eliminates heavy C bindings or external crates, providing exact C-ABI compatible types.
|
||||
|
||||
use std::os::raw::{c_char, c_void};
|
||||
|
||||
pub type VkFlags = u32;
|
||||
pub type VkBool32 = u32;
|
||||
pub type VkDeviceSize = u64;
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct VkResult(pub i32);
|
||||
|
||||
pub const VK_SUCCESS: VkResult = VkResult(0);
|
||||
pub const VK_NOT_READY: VkResult = VkResult(1);
|
||||
pub const VK_TIMEOUT: VkResult = VkResult(2);
|
||||
pub const VK_ERROR_OUT_OF_HOST_MEMORY: VkResult = VkResult(-1);
|
||||
pub const VK_ERROR_OUT_OF_DEVICE_MEMORY: VkResult = VkResult(-2);
|
||||
pub const VK_ERROR_INITIALIZATION_FAILED: VkResult = VkResult(-3);
|
||||
pub const VK_ERROR_DEVICE_LOST: VkResult = VkResult(-4);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct VkStructureType(pub i32);
|
||||
|
||||
pub const VK_STRUCTURE_TYPE_APPLICATION_INFO: VkStructureType = VkStructureType(0);
|
||||
pub const VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO: VkStructureType = VkStructureType(1);
|
||||
pub const VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO: VkStructureType = VkStructureType(2);
|
||||
pub const VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO: VkStructureType = VkStructureType(3);
|
||||
pub const VK_STRUCTURE_TYPE_SUBMIT_INFO: VkStructureType = VkStructureType(4);
|
||||
pub const VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO: VkStructureType = VkStructureType(39);
|
||||
pub const VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO: VkStructureType = VkStructureType(40);
|
||||
pub const VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO: VkStructureType = VkStructureType(42);
|
||||
pub const VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO: VkStructureType = VkStructureType(43);
|
||||
|
||||
pub const VK_TRUE: VkBool32 = 1;
|
||||
pub const VK_FALSE: VkBool32 = 0;
|
||||
|
||||
pub const VK_NULL_HANDLE: usize = 0;
|
||||
|
||||
macro_rules! define_handle {
|
||||
($name:ident) => {
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct $name(pub usize);
|
||||
|
||||
impl $name {
|
||||
pub const NULL: Self = Self(VK_NULL_HANDLE);
|
||||
pub fn is_null(&self) -> bool {
|
||||
self.0 == VK_NULL_HANDLE
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
define_handle!(VkInstance);
|
||||
define_handle!(VkPhysicalDevice);
|
||||
define_handle!(VkDevice);
|
||||
define_handle!(VkQueue);
|
||||
define_handle!(VkCommandBuffer);
|
||||
define_handle!(VkCommandPool);
|
||||
define_handle!(VkSurfaceKHR);
|
||||
define_handle!(VkSwapchainKHR);
|
||||
define_handle!(VkRenderPass);
|
||||
define_handle!(VkFramebuffer);
|
||||
define_handle!(VkFence);
|
||||
define_handle!(VkSemaphore);
|
||||
|
||||
#[repr(C)]
|
||||
pub struct VkApplicationInfo {
|
||||
pub s_type: VkStructureType,
|
||||
pub p_next: *const c_void,
|
||||
pub p_application_name: *const c_char,
|
||||
pub application_version: u32,
|
||||
pub p_engine_name: *const c_char,
|
||||
pub engine_version: u32,
|
||||
pub api_version: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct VkInstanceCreateInfo {
|
||||
pub s_type: VkStructureType,
|
||||
pub p_next: *const c_void,
|
||||
pub flags: VkFlags,
|
||||
pub p_application_info: *const VkApplicationInfo,
|
||||
pub enabled_layer_count: u32,
|
||||
pub pp_enabled_layer_names: *const *const c_char,
|
||||
pub enabled_extension_count: u32,
|
||||
pub pp_enabled_extension_names: *const *const c_char,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct VkPhysicalDeviceProperties {
|
||||
pub api_version: u32,
|
||||
pub driver_version: u32,
|
||||
pub vendor_id: u32,
|
||||
pub device_id: u32,
|
||||
pub device_type: u32,
|
||||
pub device_name: [c_char; 256],
|
||||
pub pipeline_cache_uuid: [u8; 16],
|
||||
pub limits: [u8; 504], // VkPhysicalDeviceLimits padded
|
||||
pub sparse_properties: [u8; 20],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct VkQueueFamilyProperties {
|
||||
pub queue_flags: VkFlags,
|
||||
pub queue_count: u32,
|
||||
pub timestamp_valid_bits: u32,
|
||||
pub min_image_transfer_granularity: [u32; 3],
|
||||
}
|
||||
|
||||
pub const VK_QUEUE_GRAPHICS_BIT: VkFlags = 0x00000001;
|
||||
pub const VK_QUEUE_COMPUTE_BIT: VkFlags = 0x00000002;
|
||||
pub const VK_QUEUE_TRANSFER_BIT: VkFlags = 0x00000004;
|
||||
|
||||
pub const VK_MAKE_API_VERSION: fn(u32, u32, u32, u32) -> u32 = |variant, major, minor, patch| {
|
||||
(variant << 29) | (major << 22) | (minor << 12) | patch
|
||||
};
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur