From 04927c3bcc048d6af441b23b45d8c314ce6351f9 Mon Sep 17 00:00:00 2001 From: itycodes Date: Mon, 22 Apr 2024 01:43:01 +0200 Subject: [PATCH] Initial commit --- .gitignore | 3 + Cargo.toml | 15 +++ LICENSE.txt | 287 ++++++++++++++++++++++++++++++++++++++++++++++ build.rs | 29 +++++ clib/wrapper.h | 1 + src/lib.rs | 254 ++++++++++++++++++++++++++++++++++++++++ src/native/mod.rs | 4 + tests/tests.rs | 53 +++++++++ 8 files changed, 646 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 LICENSE.txt create mode 100644 build.rs create mode 100644 clib/wrapper.h create mode 100644 src/lib.rs create mode 100644 src/native/mod.rs create mode 100644 tests/tests.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c640ca5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +Cargo.lock +.vscode diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..fd0149d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "vulk-rs" +version = "0.0.1" +edition = "2021" +license = "EUPL 1.2" +repository = "https://gitea.itycodes.org/itycodes/vulk" +description = """ +# Opinionated Rust bindings for Vulkan. +For the duration of the GitHub requirement on crates.io, this crate's presence on crates.io is temporary, and moving onto a registry that does not require a GitHub account is top priority. +""" + +[dependencies] + +[build-dependencies] +bindgen = "0.69.4" diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..4153cd3 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,287 @@ + EUROPEAN UNION PUBLIC LICENCE v. 1.2 + EUPL © the European Union 2007, 2016 + +This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined +below) which is provided under the terms of this Licence. Any use of the Work, +other than as authorised under this Licence is prohibited (to the extent such +use is covered by a right of the copyright holder of the Work). + +The Work is provided under the terms of this Licence when the Licensor (as +defined below) has placed the following notice immediately following the +copyright notice for the Work: + + Licensed under the EUPL + +or has expressed by any other means his willingness to license under the EUPL. + +1. Definitions + +In this Licence, the following terms have the following meaning: + +- ‘The Licence’: this Licence. + +- ‘The Original Work’: the work or software distributed or communicated by the + Licensor under this Licence, available as Source Code and also as Executable + Code as the case may be. + +- ‘Derivative Works’: the works or software that could be created by the + Licensee, based upon the Original Work or modifications thereof. This Licence + does not define the extent of modification or dependence on the Original Work + required in order to classify a work as a Derivative Work; this extent is + determined by copyright law applicable in the country mentioned in Article 15. + +- ‘The Work’: the Original Work or its Derivative Works. + +- ‘The Source Code’: the human-readable form of the Work which is the most + convenient for people to study and modify. + +- ‘The Executable Code’: any code which has generally been compiled and which is + meant to be interpreted by a computer as a program. + +- ‘The Licensor’: the natural or legal person that distributes or communicates + the Work under the Licence. + +- ‘Contributor(s)’: any natural or legal person who modifies the Work under the + Licence, or otherwise contributes to the creation of a Derivative Work. + +- ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of + the Work under the terms of the Licence. + +- ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, + renting, distributing, communicating, transmitting, or otherwise making + available, online or offline, copies of the Work or providing access to its + essential functionalities at the disposal of any other natural or legal + person. + +2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, +sublicensable licence to do the following, for the duration of copyright vested +in the Original Work: + +- use the Work in any circumstance and for all usage, +- reproduce the Work, +- modify the Work, and make Derivative Works based upon the Work, +- communicate to the public, including the right to make available or display + the Work or copies thereof to the public and perform publicly, as the case may + be, the Work, +- distribute the Work or copies thereof, +- lend and rent the Work or copies thereof, +- sublicense rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now +known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to +exercise his moral right to the extent allowed by law in order to make effective +the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to +any patents held by the Licensor, to the extent necessary to make use of the +rights granted on the Work under this Licence. + +3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as +Executable Code. If the Work is provided as Executable Code, the Licensor +provides in addition a machine-readable copy of the Source Code of the Work +along with each copy of the Work that the Licensor distributes or indicates, in +a notice following the copyright notice attached to the Work, a repository where +the Source Code is easily and freely accessible for as long as the Licensor +continues to distribute or communicate the Work. + +4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from +any exception or limitation to the exclusive rights of the rights owners in the +Work, of the exhaustion of those rights or of other applicable limitations +thereto. + +5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and +obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: The Licensee shall keep intact all copyright, patent or +trademarks notices and all notices that refer to the Licence and to the +disclaimer of warranties. The Licensee must include a copy of such notices and a +copy of the Licence with every copy of the Work he/she distributes or +communicates. The Licensee must cause any Derivative Work to carry prominent +notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes or communicates copies of the +Original Works or Derivative Works, this Distribution or Communication will be +done under the terms of this Licence or of a later version of this Licence +unless the Original Work is expressly distributed only under this version of the +Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee +(becoming Licensor) cannot offer or impose any additional terms or conditions on +the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes or Communicates Derivative +Works or copies thereof based upon both the Work and another work licensed under +a Compatible Licence, this Distribution or Communication can be done under the +terms of this Compatible Licence. For the sake of this clause, ‘Compatible +Licence’ refers to the licences listed in the appendix attached to this Licence. +Should the Licensee's obligations under the Compatible Licence conflict with +his/her obligations under this Licence, the obligations of the Compatible +Licence shall prevail. + +Provision of Source Code: When distributing or communicating copies of the Work, +the Licensee will provide a machine-readable copy of the Source Code or indicate +a repository where this Source will be easily and freely available for as long +as the Licensee continues to distribute or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, +trademarks, service marks, or names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the copyright notice. + +6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted +hereunder is owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings +to the Work are owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent +Contributors grant You a licence to their contributions to the Work, under the +terms of this Licence. + +7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous +Contributors. It is not a finished work and may therefore contain defects or +‘bugs’ inherent to this type of development. + +For the above reason, the Work is provided under the Licence on an ‘as is’ basis +and without warranties of any kind concerning the Work, including without +limitation merchantability, fitness for a particular purpose, absence of defects +or errors, accuracy, non-infringement of intellectual property rights other than +copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition +for the grant of any rights to the Work. + +8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural +persons, the Licensor will in no event be liable for any direct or indirect, +material or moral, damages of any kind, arising out of the Licence or of the use +of the Work, including without limitation, damages for loss of goodwill, work +stoppage, computer failure or malfunction, loss of data or any commercial +damage, even if the Licensor has been advised of the possibility of such damage. +However, the Licensor will be liable under statutory product liability laws as +far such laws apply to the Work. + +9. Additional agreements + +While distributing the Work, You may choose to conclude an additional agreement, +defining obligations or services consistent with this Licence. However, if +accepting obligations, You may act only on your own behalf and on your sole +responsibility, not on behalf of the original Licensor or any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor harmless +for any liability incurred by, or claims asserted against such Contributor by +the fact You have accepted any warranty or additional liability. + +10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ +placed under the bottom of a window displaying the text of this Licence or by +affirming consent in any other similar way, in accordance with the rules of +applicable law. Clicking on that icon indicates your clear and irrevocable +acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and +conditions by exercising any rights granted to You by Article 2 of this Licence, +such as the use of the Work, the creation by You of a Derivative Work or the +Distribution or Communication by You of the Work or copies thereof. + +11. Information to the public + +In case of any Distribution or Communication of the Work by means of electronic +communication by You (for example, by offering to download the Work from a +remote location) the distribution channel or media (for example, a website) must +at least provide to the public the information requested by the applicable law +regarding the Licensor, the Licence and the way it may be accessible, concluded, +stored and reproduced by the Licensee. + +12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon +any breach by the Licensee of the terms of the Licence. + +Such a termination will not terminate the licences of any person who has +received the Work from the Licensee under the Licence, provided such persons +remain in full compliance with the Licence. + +13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete +agreement between the Parties as to the Work. + +If any provision of the Licence is invalid or unenforceable under applicable +law, this will not affect the validity or enforceability of the Licence as a +whole. Such provision will be construed or reformed so as necessary to make it +valid and enforceable. + +The European Commission may publish other linguistic versions or new versions of +this Licence or updated versions of the Appendix, so far this is required and +reasonable, without reducing the scope of the rights granted by the Licence. New +versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, +have identical value. Parties can take advantage of the linguistic version of +their choice. + +14. Jurisdiction + +Without prejudice to specific agreement between parties, + +- any litigation resulting from the interpretation of this License, arising + between the European Union institutions, bodies, offices or agencies, as a + Licensor, and any Licensee, will be subject to the jurisdiction of the Court + of Justice of the European Union, as laid down in article 272 of the Treaty on + the Functioning of the European Union, + +- any litigation arising between other parties and resulting from the + interpretation of this License, will be subject to the exclusive jurisdiction + of the competent court where the Licensor resides or conducts its primary + business. + +15. Applicable Law + +Without prejudice to specific agreement between parties, + +- this Licence shall be governed by the law of the European Union Member State + where the Licensor has his seat, resides or has his registered office, + +- this licence shall be governed by Belgian law if the Licensor has no seat, + residence or registered office inside a European Union Member State. + +Appendix + +‘Compatible Licences’ according to Article 5 EUPL are: + +- GNU General Public License (GPL) v. 2, v. 3 +- GNU Affero General Public License (AGPL) v. 3 +- Open Software License (OSL) v. 2.1, v. 3.0 +- Eclipse Public License (EPL) v. 1.0 +- CeCILL v. 2.0, v. 2.1 +- Mozilla Public Licence (MPL) v. 2 +- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for + works other than software +- European Union Public Licence (EUPL) v. 1.1, v. 1.2 +- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong + Reciprocity (LiLiQ-R+). + +The European Commission may update this Appendix to later versions of the above +licences without producing a new version of the EUPL, as long as they provide +the rights granted in Article 2 of this Licence and protect the covered Source +Code from exclusive appropriation. + +All other changes or additions to this Appendix require the production of a new +EUPL version. diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..707b26e --- /dev/null +++ b/build.rs @@ -0,0 +1,29 @@ +use std::env; +use std::path::PathBuf; + +fn main() { + // Tell cargo to tell rustc to link the system bzip2 + // shared library. + println!("cargo:rustc-link-lib=vulkan"); + + // The bindgen::Builder is the main entry point + // to bindgen, and lets you build up options for + // the resulting bindings. + let bindings = bindgen::Builder::default() + // The input header we would like to generate + // bindings for. + .header("clib/wrapper.h") + // Tell cargo to invalidate the built crate whenever any of the + // included header files changed. + .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) + // Finish the builder and generate the bindings. + .generate() + // Unwrap the Result and panic on failure. + .expect("Unable to generate bindings"); + + // Write the bindings to the $OUT_DIR/bindings.rs file. + let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); + bindings + .write_to_file(out_path.join("bindings.rs")) + .expect("Couldn't write bindings!"); +} diff --git a/clib/wrapper.h b/clib/wrapper.h new file mode 100644 index 0000000..48ce5f5 --- /dev/null +++ b/clib/wrapper.h @@ -0,0 +1 @@ +#include diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..1efc25e --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,254 @@ +//! # Opinionated low-level Rust bindings for Vulkan +//! Bindgen used to generate the native unsafe bindings. +//! +//! Provides an opinionated OOP wrapper around the Vulkan API. +//! +//! Currently heavily *work in progress*. +//! +//! Relies on the `VK_LAYER_KHRONOS_validation` layer and `VK_EXT_debug_utils` extension in debug mode, however they are stripped out in release mode. + +#[allow(unused)] + +mod native; +pub mod vk { + pub use native::VkPhysicalDeviceProperties as PhysicalDeviceProperties; + pub use native::VkQueueFamilyProperties as QueueFamilyProperties; + pub use native::VkPhysicalDeviceFeatures as PhysicalDeviceFeatures; + + use crate::*; + + pub struct Instance { + __instance: native::VkInstance, + __validation: native::VkDebugUtilsMessengerEXT, + } + + impl Drop for Instance { + /// Calls `vkDestroyInstance` on the Vulkan instance. + fn drop(&mut self) { + unsafe { + if cfg!(debug_assertions) { + assert!(!self.__validation.is_null()); + + let vk_destroy_debug_utils_messenger_ext: + unsafe extern "system" fn( + native::VkInstance, + native::VkDebugUtilsMessengerEXT, + *const ::std::ffi::c_void) + = std::mem::transmute(native::vkGetInstanceProcAddr + (self.__instance, + std::ffi::CString::new("vkDestroyDebugUtilsMessengerEXT") + .unwrap() + .to_owned() + .as_ptr())); + + vk_destroy_debug_utils_messenger_ext(self.__instance, self.__validation, std::ptr::null()); + } + native::vkDestroyInstance(self.__instance, std::ptr::null()); + } + } + } + + + /// A Vulkan physical device. + /// Maps the `VkPhysicalDevice` struct. + /// Represents a device that hasn't been initialized yet. + pub struct PhysicalDevice { + __physical_device: native::VkPhysicalDevice, + } + + + pub trait InstanceMethods { + /// Enumerate the physical devices available to the instance. + /// Maps the `vkEnumeratePhysicalDevices` function. + fn enumerate_physical_devices(&self) -> Vec; + } + + impl InstanceMethods for Instance { + fn enumerate_physical_devices(&self) -> Vec { + unsafe { + let mut num_devices: u32 = 0; + native::vkEnumeratePhysicalDevices(self.__instance, &mut num_devices, std::ptr::null_mut()); + assert!(num_devices > 0); + + let mut physical_devices: Vec = Vec::with_capacity(num_devices as usize); + native::vkEnumeratePhysicalDevices(self.__instance, &mut num_devices, physical_devices.as_mut_ptr()); + physical_devices.set_len(num_devices as usize); + + let mut devices: Vec = Vec::with_capacity(num_devices as usize); + + for i in 0..num_devices { + dbg!(physical_devices[i as usize]); + let device = PhysicalDevice { __physical_device: physical_devices[i as usize] }; + assert!(!device.__physical_device.is_null()); + devices.push(device); + } + + return devices; + } + } + } + + pub trait PhysicalDeviceMethods { + /// Get the properties of the physical device + /// + /// Maps the `vkGetPhysicalDeviceProperties` function + fn get_properties(&self) -> native::VkPhysicalDeviceProperties; + /// Get the queue family properties of the physical device + /// + /// Maps the `vkGetPhysicalDeviceQueueFamilyProperties` function + fn get_queue_family_properties(&self) -> Vec; + /// Get the features of the physical device + /// + /// Maps the `vkGetPhysicalDeviceFeatures` function + fn get_features(&self) -> native::VkPhysicalDeviceFeatures; + } + + impl PhysicalDeviceMethods for PhysicalDevice { + fn get_properties(&self) -> native::VkPhysicalDeviceProperties { + unsafe { + let mut properties: native::VkPhysicalDeviceProperties = std::mem::zeroed(); + native::vkGetPhysicalDeviceProperties(self.__physical_device, &mut properties); + return properties; + } + } + fn get_queue_family_properties(&self) -> Vec { + unsafe { + let mut num_queue_families: u32 = 0; + native::vkGetPhysicalDeviceQueueFamilyProperties(self.__physical_device, &mut num_queue_families, std::ptr::null_mut()); + assert!(num_queue_families > 0); + + let mut queue_families: Vec = Vec::with_capacity(num_queue_families as usize); + native::vkGetPhysicalDeviceQueueFamilyProperties(self.__physical_device, &mut num_queue_families, queue_families.as_mut_ptr()); + queue_families.set_len(num_queue_families as usize); + + return queue_families; + } + } + fn get_features(&self) -> native::VkPhysicalDeviceFeatures { + unsafe { + let mut features: native::VkPhysicalDeviceFeatures = std::mem::zeroed(); + native::vkGetPhysicalDeviceFeatures(self.__physical_device, &mut features); + return features; + } + } + } + + /// Create a Vulkan version number. + /// Similar to the `VK_MAKE_VERSION` macro from C Vulkan headers. + pub fn make_version(major: u32, minor: u32, patch: u32) -> u32 { + return (patch<<0) | (minor<<12) | (major<<22) | (0<<29); + } + + #[cfg(debug_assertions)] + extern "C" fn debug_callback( + _message_severity: native::VkDebugUtilsMessageSeverityFlagBitsEXT, + _message_types: native::VkDebugUtilsMessageTypeFlagsEXT, + _callback_data: *const native::VkDebugUtilsMessengerCallbackDataEXT, + _user_data: *mut ::std::os::raw::c_void, + ) -> native::VkBool32 { + unsafe { + let message = std::ffi::CStr::from_ptr((*_callback_data).pMessage); + if (_message_severity & + (native::VkDebugUtilsMessageSeverityFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT + |native::VkDebugUtilsMessageSeverityFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)) + != 0 { + panic!("Failed validating, message from layer: {:?}", message); + } + println!("{}", format!("Validation layer debug: {}", message.to_str().unwrap())); + } + return native::VK_TRUE; + } + + #[cfg(debug_assertions)] + fn setup_validation_layer(instance: native::VkInstance) -> native::VkDebugUtilsMessengerEXT { + let debug_utils_create_info = native::VkDebugUtilsMessengerCreateInfoEXT { + sType: native::VkStructureType_VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, + pNext: std::ptr::null(), + flags: 0, + messageSeverity: + native::VkDebugUtilsMessageSeverityFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | + native::VkDebugUtilsMessageSeverityFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | + native::VkDebugUtilsMessageSeverityFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | + native::VkDebugUtilsMessageSeverityFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT, + messageType: + native::VkDebugUtilsMessageTypeFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | + native::VkDebugUtilsMessageTypeFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | + native::VkDebugUtilsMessageTypeFlagBitsEXT_VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, + pfnUserCallback: Some(debug_callback), + pUserData: std::ptr::null_mut(), + }; + unsafe { + let vk_create_debug_utils_messenger_ext: + unsafe extern "system" fn( + native::VkInstance, + *const native::VkDebugUtilsMessengerCreateInfoEXT, + *const ::std::ffi::c_void, + *mut native::VkDebugUtilsMessengerEXT) + -> native::VkResult + = std::mem::transmute(native::vkGetInstanceProcAddr + (instance, + std::ffi::CString::new("vkCreateDebugUtilsMessengerEXT") + .unwrap() + .to_owned() + .as_ptr())); + let mut out: native::VkDebugUtilsMessengerEXT = std::mem::zeroed(); + vk_create_debug_utils_messenger_ext(instance, &debug_utils_create_info, std::ptr::null(), &mut out); + return out; + } + } + + + /// Create a Vulkan instance. + /// In debug mode, the Vulkan instance will have the validation layer enabled. + /// In release mode, the Vulkan instance will not have the validation layer enabled. + /// The instance is automatically destroyed when it goes out of scope. + /// The instance is asserted to be valid with an `assert!(!instance.is_null())` call. + /// Will panic if the instance creation fails. + /// Maps the `vkCreateInstance` function. + pub fn create_instance() -> Instance { + let enabled_layers: Vec<&str> = + vec!["VK_LAYER_KHRONOS_validation\0"]; + let layer_count = enabled_layers.len(); + let enabled_layers: *const *const i8 = Box::into_raw(enabled_layers.into_boxed_slice()).cast_const() as *const *const i8; + + let enabled_exts: Vec<&str> = + vec!["VK_EXT_debug_utils\0"]; + let ext_count = enabled_exts.len(); + let enabled_exts: *const *const i8 = Box::into_raw(enabled_exts.into_boxed_slice()).cast_const() as *const *const i8; + + let application_info = native::VkApplicationInfo { + sType: native::VkStructureType_VK_STRUCTURE_TYPE_APPLICATION_INFO, + pNext: std::ptr::null(), + pApplicationName: c"vulk".as_ptr(), + applicationVersion: make_version(0, 1, 0), + pEngineName: c"vulk".as_ptr(), + engineVersion: make_version(0, 1, 0), + apiVersion: make_version(1, 3, 0), + }; + let instance_info = native::VkInstanceCreateInfo { + sType: native::VkStructureType_VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + pNext: std::ptr::null(), + flags: 0, + pApplicationInfo: &application_info, + enabledLayerCount: if cfg!(debug_assertions) { layer_count as u32 } else { 0 }, + ppEnabledLayerNames: if cfg!(debug_assertions) { enabled_layers } else { std::ptr::null() }, + enabledExtensionCount: if cfg!(debug_assertions) { ext_count as u32 } else { 0 }, + ppEnabledExtensionNames: if cfg!(debug_assertions) { enabled_exts } else { std::ptr::null() }, + }; + + unsafe { + let mut instance: native::VkInstance = { std::mem::zeroed() }; + native::vkCreateInstance(&instance_info, std::ptr::null(), &mut instance); + assert!(!instance.is_null()); + #[cfg(debug_assertions)] { + let validation = setup_validation_layer(instance); + return Instance { __instance: instance, __validation: validation}; + } + #[cfg(not(debug_assertions))] + { + return Instance { __instance: instance, __validation: std::ptr::null_mut()}; + } + } + } + +} \ No newline at end of file diff --git a/src/native/mod.rs b/src/native/mod.rs new file mode 100644 index 0000000..2474ec1 --- /dev/null +++ b/src/native/mod.rs @@ -0,0 +1,4 @@ +#![allow(non_upper_case_globals)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +include!(concat!(env!("OUT_DIR"), "/bindings.rs")); diff --git a/tests/tests.rs b/tests/tests.rs new file mode 100644 index 0000000..f491907 --- /dev/null +++ b/tests/tests.rs @@ -0,0 +1,53 @@ +use std::hint::black_box; + +#[cfg(test)] + +use vulk::vk; +use vk::*; + +#[test] +fn create_instance() { + let instance: vk::Instance = vk::create_instance(); + drop(instance); +} + +#[test] +fn enumerate_physical_devices() { + let instance: vk::Instance = vk::create_instance(); + let devices: Vec = instance.enumerate_physical_devices(); + assert!(devices.len() > 0); + drop(instance); +} + +#[test] +fn physical_devices_properties() { + let instance: vk::Instance = vk::create_instance(); + let devices: Vec = instance.enumerate_physical_devices(); + for device in devices { + let properties: vk::PhysicalDeviceProperties = device.get_properties(); + assert!(!properties.deviceName.is_empty()); + } + drop(instance); +} + +#[test] +fn physical_devices_queue_family_properties() { + let instance: vk::Instance = vk::create_instance(); + let devices: Vec = instance.enumerate_physical_devices(); + for device in devices { + let properties: Vec = device.get_queue_family_properties(); + assert!(properties.len() > 0); + } + drop(instance); +} + +#[test] +fn physical_devices_features() { + let instance: vk::Instance = vk::create_instance(); + let devices: Vec = instance.enumerate_physical_devices(); + for device in devices { + let features: vk::PhysicalDeviceFeatures = device.get_features(); + black_box(features); + } + drop(instance); +} \ No newline at end of file