      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271

    // Copyright (c) 2016 The vulkano developers
    // Licensed under the Apache License, Version 2.0
    // <LICENSE-APACHE or
    // http://www.apache.org/licenses/LICENSE-2.0> or the MIT
    // license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
    // at your option. All files in the project carrying such
    // notice may not be copied, modified, or distributed except
    // according to those terms.

    //! Vulkan implementation loading system.
    //!
    //! Before vulkano can do anything, it first needs to find an implementation of Vulkan. A Vulkan
    //! implementation is defined as a single `vkGetInstanceProcAddr` function, which can be accessed
    //! through the `Loader` trait.
    //!
    //! This module provides various implementations of the `Loader` trait.
    //!
    //! Once you have a struct that implements `Loader`, you can create a `FunctionPointers` struct
    //! from it and use this `FunctionPointers` struct to build an `Instance`.
    //!
    //! By default vulkano will use the `auto_loader()` function, which tries to automatically load
    //! a Vulkan implementation from the system.

    use shared_library;
    use std::error;
    use std::fmt;
    use std::mem;
    use std::ops::Deref;
    use std::os::raw::c_char;
    use std::os::raw::c_void;
    use std::path::Path;

    use SafeDeref;
    use vk;

    /// Implemented on objects that grant access to a Vulkan implementation.
    pub unsafe trait Loader {
        /// Calls the `vkGetInstanceProcAddr` function. The parameters are the same.
        ///
        /// The returned function must stay valid for as long as `self` is alive.
        fn get_instance_proc_addr(&self, instance: vk::Instance, name: *const c_char)
                                  -> extern "system" fn() -> ();
    }

    unsafe impl<T> Loader for T
        where T: SafeDeref,
              T::Target: Loader
    {
        #[inline]
        fn get_instance_proc_addr(&self, instance: vk::Instance, name: *const c_char)
                                  -> extern "system" fn() -> () {
            (**self).get_instance_proc_addr(instance, name)
        }
    }

    /// Implementation of `Loader` that loads Vulkan from a dynamic library.
    pub struct DynamicLibraryLoader {
        vk_lib: shared_library::dynamic_library::DynamicLibrary,
        get_proc_addr: extern "system" fn(instance: vk::Instance, pName: *const c_char)
                                          -> extern "system" fn() -> (),
    }

    impl DynamicLibraryLoader {
        /// Tries to load the dynamic library at the given path, and tries to
        /// load `vkGetInstanceProcAddr` in it.
        ///
        /// # Safety
        ///
        /// - The dynamic library must be a valid Vulkan implementation.
        ///
        pub unsafe fn new<P>(path: P) -> Result<DynamicLibraryLoader, LoadingError>
            where P: AsRef<Path>
        {
            let vk_lib = shared_library::dynamic_library::DynamicLibrary::open(Some(path.as_ref()))
                .map_err(LoadingError::LibraryLoadFailure)?;

            let get_proc_addr = {
                let ptr: *mut c_void =
                    vk_lib
                        .symbol("vkGetInstanceProcAddr")
                        .map_err(|_| {
                                     LoadingError::MissingEntryPoint("vkGetInstanceProcAddr".to_owned())
                                 })?;
                mem::transmute(ptr)
            };

            Ok(DynamicLibraryLoader {
                   vk_lib,
                   get_proc_addr,
               })
        }
    }

    unsafe impl Loader for DynamicLibraryLoader {
        #[inline]
        fn get_instance_proc_addr(&self, instance: vk::Instance, name: *const c_char)
                                  -> extern "system" fn() -> () {
            (self.get_proc_addr)(instance, name)
        }
    }

    /// Wraps around a loader and contains function pointers.
    pub struct FunctionPointers<L> {
        loader: L,
        entry_points: vk::EntryPoints,
    }

    impl<L> FunctionPointers<L> {
        /// Loads some global function pointer from the loader.
        pub fn new(loader: L) -> FunctionPointers<L>
            where L: Loader
        {
            let entry_points = vk::EntryPoints::load(|name| unsafe { mem::transmute(loader.get_instance_proc_addr(0, name.as_ptr())) });

            FunctionPointers {
                loader,
                entry_points,
            }
        }

        /// Returns the collection of Vulkan entry points from the Vulkan loader.
        #[inline]
        pub(crate) fn entry_points(&self) -> &vk::EntryPoints {
            &self.entry_points
        }

        /// Calls `get_instance_proc_addr` on the underlying loader.
        #[inline]
        pub fn get_instance_proc_addr(&self, instance: vk::Instance, name: *const c_char)
                                      -> extern "system" fn() -> ()
            where L: Loader
        {
            self.loader.get_instance_proc_addr(instance, name)
        }
    }

    /// Expression that returns a loader that assumes that Vulkan is linked to the executable you're
    /// compiling.
    ///
    /// If you use this macro, you must linked to a library that provides the `vkGetInstanceProcAddr`
    /// symbol.
    ///
    /// This is provided as a macro and not as a regular function, because the macro contains an
    /// `extern {}` block.
    // TODO: should this be unsafe?
    #[macro_export]
    macro_rules! statically_linked_vulkan_loader {
        () => ({
            extern "C" {
                fn vkGetInstanceProcAddr(instance: vk::Instance, pName: *const c_char)
                                        -> vk::PFN_vkVoidFunction;
            }

            struct StaticallyLinkedVulkanLoader;
            unsafe impl Loader for StaticallyLinkedVulkanLoader {
                fn get_instance_proc_addr(&self, instance: vk::Instance, name: *const c_char)
                                        -> extern "system" fn() -> () {
                    unsafe { vkGetInstanceProcAddr(instance, name) }
                }
            }

            StaticallyLinkedVulkanLoader
        })
    }

    /// Returns the default `FunctionPointers` for this system.
    ///
    /// This function tries to auto-guess where to find the Vulkan implementation, and loads it in a
    /// `lazy_static!`. The content of the lazy_static is then returned, or an error if we failed to
    /// load Vulkan.
    pub fn auto_loader()
        -> Result<&'static FunctionPointers<Box<dyn Loader + Send + Sync>>, LoadingError>
    {
        #[cfg(target_os = "ios")]
        #[allow(non_snake_case)]
        fn def_loader_impl() -> Result<Box<Loader + Send + Sync>, LoadingError> {
            let loader = statically_linked_vulkan_loader!();
            Ok(Box::new(loader))
        }

        #[cfg(not(target_os = "ios"))]
        fn def_loader_impl() -> Result<Box<dyn Loader + Send + Sync>, LoadingError> {
            #[cfg(windows)]
            fn get_path() -> &'static Path {
                Path::new("vulkan-1.dll")
            }
            #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
            fn get_path() -> &'static Path {
                Path::new("libvulkan.so.1")
            }
            #[cfg(target_os = "macos")]
            fn get_path() -> &'static Path {
                Path::new("libvulkan.1.dylib")
            }
            #[cfg(target_os = "android")]
            fn get_path() -> &'static Path {
                Path::new("libvulkan.so")
            }

            let loader = unsafe { DynamicLibraryLoader::new(get_path())? };

            Ok(Box::new(loader))
        }

        lazy_static! {
            static ref DEFAULT_LOADER: Result<FunctionPointers<Box<dyn Loader + Send + Sync>>, LoadingError> = {
                def_loader_impl().map(FunctionPointers::new)
            };
        }

        match DEFAULT_LOADER.deref() {
            &Ok(ref ptr) => Ok(ptr),
            &Err(ref err) => Err(err.clone()),
        }
    }

    /// Error that can happen when loading the Vulkan loader.
    #[derive(Debug, Clone)]
    pub enum LoadingError {
        /// Failed to load the Vulkan shared library.
        LibraryLoadFailure(String), // TODO: meh for error type, but this needs changes in shared_library

        /// One of the entry points required to be supported by the Vulkan implementation is missing.
        MissingEntryPoint(String),
    }

    impl error::Error for LoadingError {
        #[inline]
        fn description(&self) -> &str {
            match *self {
                LoadingError::LibraryLoadFailure(_) => {
                    "failed to load the Vulkan shared library"
                },
                LoadingError::MissingEntryPoint(_) => {
                    "one of the entry points required to be supported by the Vulkan implementation \
                     is missing"
                },
            }
        }

        /*#[inline]
        fn cause(&self) -> Option<&error::Error> {
            match *self {
                LoadingError::LibraryLoadFailure(ref err) => Some(err),
                _ => None
            }
        }*/
    }

    impl fmt::Display for LoadingError {
        #[inline]
        fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
            write!(fmt, "{}", error::Error::description(self))
        }
    }

    #[cfg(test)]
    mod tests {
        use instance::loader::DynamicLibraryLoader;
        use instance::loader::LoadingError;

        #[test]
        fn dl_open_error() {
            unsafe {
                match DynamicLibraryLoader::new("_non_existing_library.void") {
                    Err(LoadingError::LibraryLoadFailure(_)) => (),
                    _ => panic!(),
                }
            }
        }
    }

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g., `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g., `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g., `str,u8` or `String,struct:Vec,test`)