vulkan-rust 0.10.0

Ergonomic Vulkan bindings for Rust, generated from vk.xml
Documentation
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use std::sync::Arc;

use crate::device::Device;
use crate::error::{VkResult, check};
use crate::loader::Loader;
use crate::vk;
use vk::Handle;

/// Wrapper around a `VkInstance` handle and its loaded command table.
///
/// Owns a `Box<InstanceCommands>` containing all instance-level function
/// pointers, loaded at construction via `vkGetInstanceProcAddr`. Also
/// stores `vkGetDeviceProcAddr` for later use when creating a `Device`.
///
/// Holds an optional reference to the Vulkan shared library so that
/// function pointers remain valid even if the originating `Entry` is
/// dropped. When created via `from_raw_parts`, the caller manages the
/// library lifetime and this field is `None`.
///
/// Does **not** implement `Drop`, the caller must explicitly call
/// `destroy_instance` when done. This avoids double-destroy bugs when
/// wrapping externally managed handles via `from_raw_parts`.
///
/// **Guide:** [The Vulkan Object Model](https://hiddentale.github.io/vulkan_rust/concepts/object-model.html)
/// covers handles, lifetimes, and parent-child relationships.
///
/// # Examples
///
/// ```no_run
/// use vulkan_rust::vk::*;
///
/// # let (entry, instance) = vulkan_rust::test_helpers::create_test_instance().unwrap();
/// // Enumerate GPUs and query properties.
/// let devices = unsafe { instance.enumerate_physical_devices() }
///     .expect("no devices");
/// let props = unsafe { instance.get_physical_device_properties(devices[0]) };
///
/// // Clean up.
/// unsafe { instance.destroy_instance(None) };
/// ```
pub struct Instance {
    handle: vk::Instance,
    commands: Box<vk::commands::InstanceCommands>,
    get_device_proc_addr: vk::commands::PFN_vkGetDeviceProcAddr,
    _loader: Option<Arc<dyn Loader>>,
}

impl Instance {
    /// Internal construction path. Called by `Entry::create_instance`.
    ///
    /// Loads all instance-level function pointers using the real instance
    /// handle, which gives instance-specific trampolines that skip a layer
    /// of dispatch compared to the global `vkGetInstanceProcAddr`.
    ///
    /// # Safety
    ///
    /// - `handle` must be a valid `VkInstance`.
    /// - `get_instance_proc_addr` must resolve instance-level commands for
    ///   this handle.
    /// - `get_device_proc_addr` must be the function used to load
    ///   device-level commands later.
    pub(crate) unsafe fn load(
        handle: vk::Instance,
        get_instance_proc_addr: vk::commands::PFN_vkGetInstanceProcAddr,
        get_device_proc_addr: vk::commands::PFN_vkGetDeviceProcAddr,
        loader: Option<Arc<dyn Loader>>,
    ) -> Self {
        let get_instance_proc_addr_fn =
            get_instance_proc_addr.expect("vkGetInstanceProcAddr not loaded");
        // SAFETY: handle is valid per caller contract; transmute converts raw fn ptrs.
        let commands = Box::new(unsafe {
            vk::commands::InstanceCommands::load(|name| {
                std::mem::transmute(get_instance_proc_addr_fn(handle, name.as_ptr()))
            })
        });
        Self {
            handle,
            commands,
            get_device_proc_addr,
            _loader: loader,
        }
    }

    /// Wrap a raw handle created externally (OpenXR, middleware, testing).
    ///
    /// Resolves `vkGetDeviceProcAddr` from the instance automatically, so
    /// the caller only needs to provide `vkGetInstanceProcAddr`.
    ///
    /// # Safety
    ///
    /// - `handle` must be a valid `VkInstance` that was created externally.
    /// - `get_instance_proc_addr` must be the function used to load
    ///   instance-level commands for this handle.
    /// - The caller is responsible for the instance's lifetime, it must
    ///   outlive this wrapper and not be destroyed while in use.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use vulkan_rust::Instance;
    /// # let entry = vulkan_rust::test_helpers::create_test_entry().unwrap();
    ///
    /// // Given a raw instance handle from OpenXR or another source:
    /// let raw_instance = unsafe { entry.create_instance_raw(
    ///     &Default::default(), None,
    /// ) }.unwrap();
    ///
    /// let instance = unsafe {
    ///     Instance::from_raw_parts(raw_instance, entry.get_instance_proc_addr())
    /// };
    /// // Use instance...
    /// unsafe { instance.destroy_instance(None) };
    /// ```
    pub unsafe fn from_raw_parts(
        handle: vk::Instance,
        get_instance_proc_addr: vk::commands::PFN_vkGetInstanceProcAddr,
    ) -> Self {
        let get_instance_proc_addr_fn =
            get_instance_proc_addr.expect("vkGetInstanceProcAddr not loaded");

        // SAFETY: resolving vkGetDeviceProcAddr from a valid instance handle.
        let get_device_proc_addr: vk::commands::PFN_vkGetDeviceProcAddr = unsafe {
            std::mem::transmute(get_instance_proc_addr_fn(
                handle,
                c"vkGetDeviceProcAddr".as_ptr(),
            ))
        };

        // SAFETY: forwards caller's safety guarantees to `load`.
        unsafe { Self::load(handle, get_instance_proc_addr, get_device_proc_addr, None) }
    }

    /// Returns the raw `VkInstance` handle.
    pub fn handle(&self) -> vk::Instance {
        self.handle
    }

    /// Returns the loaded instance-level command table.
    ///
    /// Use this to call any of the ~90 instance-level commands directly,
    /// including those without hand-written ergonomic wrappers.
    pub fn commands(&self) -> &vk::commands::InstanceCommands {
        &self.commands
    }

    /// Create a logical device for the given physical device.
    ///
    /// # Safety
    ///
    /// - `physical_device` must be a valid handle obtained from this instance.
    /// - `create_info` must be a valid, fully populated `DeviceCreateInfo`.
    /// - The caller is responsible for calling `device.destroy_device` when done.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use vulkan_rust::vk::*;
    /// # let (entry, instance) = vulkan_rust::test_helpers::create_test_instance().expect("test setup failed");
    /// let physical_devices = unsafe { instance.enumerate_physical_devices() }
    ///     .expect("no devices");
    /// let physical_device = physical_devices[0];
    ///
    /// let priorities = [1.0f32];
    /// let queue_info = DeviceQueueCreateInfo::builder()
    ///     .queue_family_index(0)
    ///     .queue_priorities(&priorities);
    /// let queue_infos = [*queue_info];
    /// let device_info = DeviceCreateInfo::builder()
    ///     .queue_create_infos(&queue_infos);
    /// let device = unsafe {
    ///     instance.create_device(physical_device, &device_info, None)
    /// }.expect("device creation failed");
    /// // Use device...
    /// unsafe { device.destroy_device(None) };
    /// # unsafe { instance.destroy_instance(None) };
    /// ```
    pub unsafe fn create_device(
        &self,
        physical_device: vk::PhysicalDevice,
        create_info: &vk::DeviceCreateInfo,
        allocator: Option<&vk::AllocationCallbacks>,
    ) -> VkResult<Device> {
        let fp = self
            .commands
            .create_device
            .expect("vkCreateDevice not loaded");
        let mut raw = vk::Device::null();
        // SAFETY: caller guarantees physical_device and create_info are valid.
        let result = unsafe {
            fp(
                physical_device,
                create_info,
                allocator.map_or(std::ptr::null(), |a| a),
                &mut raw,
            )
        };
        check(result)?;
        // SAFETY: raw is a freshly created valid device handle.
        let device = unsafe { Device::load(raw, self.get_device_proc_addr, self._loader.clone()) };
        Ok(device)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::c_char;
    use vk::Handle;

    fn fake_handle() -> vk::Instance {
        vk::Instance::from_raw(0xDEAD)
    }

    /// Stub `vkGetInstanceProcAddr` that returns null for all lookups.
    unsafe extern "system" fn mock_get_instance_proc_addr(
        _instance: vk::Instance,
        _name: *const c_char,
    ) -> vk::PFN_vkVoidFunction {
        None
    }

    #[test]
    fn from_raw_parts_stores_handle() {
        let instance =
            unsafe { Instance::from_raw_parts(fake_handle(), Some(mock_get_instance_proc_addr)) };
        assert_eq!(instance.handle().as_raw(), fake_handle().as_raw());
    }

    #[test]
    fn handle_returns_value_from_construction() {
        let instance =
            unsafe { Instance::load(fake_handle(), Some(mock_get_instance_proc_addr), None, None) };
        assert_eq!(instance.handle().as_raw(), fake_handle().as_raw());
    }

    #[test]
    fn commands_returns_reference() {
        let instance =
            unsafe { Instance::load(fake_handle(), Some(mock_get_instance_proc_addr), None, None) };
        // Commands were loaded with a null-returning proc addr, so all
        // function pointers are None,but the reference is valid.
        let _ = instance.commands();
    }

    // -- Rich mock for testing create_device without Vulkan ------------------

    /// A `vkGetInstanceProcAddr` that returns fake fps for key commands.
    unsafe extern "system" fn rich_instance_proc_addr(
        _instance: vk::Instance,
        name: *const c_char,
    ) -> vk::PFN_vkVoidFunction {
        let name = unsafe { std::ffi::CStr::from_ptr(name) };
        match name.to_bytes() {
            b"vkGetDeviceProcAddr" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(vk::Device, *const c_char) -> vk::PFN_vkVoidFunction,
                    unsafe extern "system" fn(),
                >(mock_device_proc_addr)
            }),
            b"vkCreateDevice" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(
                        vk::PhysicalDevice,
                        *const vk::DeviceCreateInfo,
                        *const vk::AllocationCallbacks,
                        *mut vk::Device,
                    ) -> vk::Result,
                    unsafe extern "system" fn(),
                >(mock_create_device)
            }),
            _ => None,
        }
    }

    unsafe extern "system" fn mock_device_proc_addr(
        _device: vk::Device,
        _name: *const c_char,
    ) -> vk::PFN_vkVoidFunction {
        None
    }

    unsafe extern "system" fn mock_create_device(
        _physical_device: vk::PhysicalDevice,
        _p_create_info: *const vk::DeviceCreateInfo,
        _p_allocator: *const vk::AllocationCallbacks,
        p_device: *mut vk::Device,
    ) -> vk::Result {
        unsafe {
            *p_device = std::mem::transmute::<usize, vk::Device>(0xBEEF_usize);
        }
        vk::Result::SUCCESS
    }

    fn mock_instance() -> Instance {
        unsafe {
            Instance::load(
                fake_handle(),
                Some(rich_instance_proc_addr),
                Some(mock_device_proc_addr),
                None,
            )
        }
    }

    #[test]
    fn create_device_succeeds_with_mock() {
        let instance = mock_instance();
        let physical_device = vk::PhysicalDevice::from_raw(0xCAFE);
        let create_info: vk::DeviceCreateInfo = unsafe { std::mem::zeroed() };
        let device = unsafe { instance.create_device(physical_device, &create_info, None) }
            .expect("create_device should succeed");
        assert_eq!(device.handle().as_raw(), 0xBEEF);
    }

    #[test]
    fn create_device_with_allocator() {
        let instance = mock_instance();
        let physical_device = vk::PhysicalDevice::from_raw(0xCAFE);
        let create_info: vk::DeviceCreateInfo = unsafe { std::mem::zeroed() };
        let allocator: vk::AllocationCallbacks = unsafe { std::mem::zeroed() };
        let device =
            unsafe { instance.create_device(physical_device, &create_info, Some(&allocator)) }
                .expect("create_device should succeed");
        assert_eq!(device.handle().as_raw(), 0xBEEF);
    }

    #[test]
    fn from_raw_parts_resolves_device_proc_addr() {
        // rich_instance_proc_addr returns a non-null vkGetDeviceProcAddr,
        // so from_raw_parts should store it.
        let instance =
            unsafe { Instance::from_raw_parts(fake_handle(), Some(rich_instance_proc_addr)) };
        assert_eq!(instance.handle().as_raw(), fake_handle().as_raw());
        // Verify create_device works, proving get_device_proc_addr was resolved.
        let physical_device = vk::PhysicalDevice::from_raw(0xCAFE);
        let create_info: vk::DeviceCreateInfo = unsafe { std::mem::zeroed() };
        let device = unsafe { instance.create_device(physical_device, &create_info, None) }
            .expect("create_device should succeed via from_raw_parts path");
        assert_eq!(device.handle().as_raw(), 0xBEEF);
    }

    #[test]
    fn load_with_loader_reference() {
        use std::ffi::{CStr, c_void};
        struct DummyLoader;
        unsafe impl Loader for DummyLoader {
            unsafe fn load(&self, _name: &CStr) -> *const c_void {
                std::ptr::null()
            }
        }
        let loader: Arc<dyn Loader> = Arc::new(DummyLoader);
        let instance = unsafe {
            Instance::load(
                fake_handle(),
                Some(mock_get_instance_proc_addr),
                None,
                Some(loader.clone()),
            )
        };
        // The loader Arc should have 2 strong refs: our local + instance.
        assert_eq!(Arc::strong_count(&loader), 2);
        assert_eq!(instance.handle().as_raw(), fake_handle().as_raw());
    }

    // -- Error-path mock for create_device ------------------------------------

    unsafe extern "system" fn failing_instance_proc_addr(
        _instance: vk::Instance,
        name: *const c_char,
    ) -> vk::PFN_vkVoidFunction {
        let name = unsafe { std::ffi::CStr::from_ptr(name) };
        match name.to_bytes() {
            b"vkGetDeviceProcAddr" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(vk::Device, *const c_char) -> vk::PFN_vkVoidFunction,
                    unsafe extern "system" fn(),
                >(mock_device_proc_addr)
            }),
            b"vkCreateDevice" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(
                        vk::PhysicalDevice,
                        *const vk::DeviceCreateInfo,
                        *const vk::AllocationCallbacks,
                        *mut vk::Device,
                    ) -> vk::Result,
                    unsafe extern "system" fn(),
                >(failing_create_device)
            }),
            _ => None,
        }
    }

    unsafe extern "system" fn failing_create_device(
        _physical_device: vk::PhysicalDevice,
        _p_create_info: *const vk::DeviceCreateInfo,
        _p_allocator: *const vk::AllocationCallbacks,
        _p_device: *mut vk::Device,
    ) -> vk::Result {
        vk::Result::ERROR_INITIALIZATION_FAILED
    }

    #[test]
    fn from_raw_parts_stores_no_loader() {
        let instance =
            unsafe { Instance::from_raw_parts(fake_handle(), Some(mock_get_instance_proc_addr)) };
        // from_raw_parts passes None for loader; verify handle is stored correctly.
        assert_eq!(instance.handle().as_raw(), fake_handle().as_raw());
    }

    #[test]
    fn load_with_loader_keeps_arc_alive() {
        use std::ffi::{CStr, c_void};
        struct DummyLoader;
        unsafe impl Loader for DummyLoader {
            unsafe fn load(&self, _name: &CStr) -> *const c_void {
                std::ptr::null()
            }
        }
        let loader: Arc<dyn Loader> = Arc::new(DummyLoader);
        let weak = Arc::downgrade(&loader);
        let instance = unsafe {
            Instance::load(
                fake_handle(),
                Some(mock_get_instance_proc_addr),
                None,
                Some(loader),
            )
        };
        assert!(weak.upgrade().is_some(), "loader should still be alive");
        drop(instance);
        assert!(weak.upgrade().is_none(), "loader should be dropped");
    }

    #[test]
    fn commands_all_none_from_null_mock() {
        let instance =
            unsafe { Instance::load(fake_handle(), Some(mock_get_instance_proc_addr), None, None) };
        // All commands should be None since mock returns null for everything.
        assert!(instance.commands().enumerate_physical_devices.is_none());
        assert!(instance.commands().destroy_instance.is_none());
        assert!(instance.commands().create_device.is_none());
    }

    // -- Rich mock that resolves additional instance commands ------------------

    /// Mock enumerate_physical_devices: returns 2 fake physical devices.
    unsafe extern "system" fn mock_enumerate_physical_devices(
        _instance: vk::Instance,
        p_count: *mut u32,
        p_devices: *mut vk::PhysicalDevice,
    ) -> vk::Result {
        unsafe { *p_count = 2 };
        if !p_devices.is_null() {
            unsafe {
                *p_devices = vk::PhysicalDevice::from_raw(0xAA);
                *p_devices.add(1) = vk::PhysicalDevice::from_raw(0xBB);
            }
        }
        vk::Result::SUCCESS
    }

    unsafe extern "system" fn mock_destroy_instance(
        _instance: vk::Instance,
        _p_allocator: *const vk::AllocationCallbacks,
    ) {
    }

    /// Richer `vkGetInstanceProcAddr` that resolves core instance commands.
    unsafe extern "system" fn rich_instance_proc_addr_v2(
        _instance: vk::Instance,
        name: *const c_char,
    ) -> vk::PFN_vkVoidFunction {
        let name = unsafe { std::ffi::CStr::from_ptr(name) };
        match name.to_bytes() {
            b"vkGetDeviceProcAddr" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(vk::Device, *const c_char) -> vk::PFN_vkVoidFunction,
                    unsafe extern "system" fn(),
                >(mock_device_proc_addr)
            }),
            b"vkCreateDevice" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(
                        vk::PhysicalDevice,
                        *const vk::DeviceCreateInfo,
                        *const vk::AllocationCallbacks,
                        *mut vk::Device,
                    ) -> vk::Result,
                    unsafe extern "system" fn(),
                >(mock_create_device)
            }),
            b"vkEnumeratePhysicalDevices" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(
                        vk::Instance,
                        *mut u32,
                        *mut vk::PhysicalDevice,
                    ) -> vk::Result,
                    unsafe extern "system" fn(),
                >(mock_enumerate_physical_devices)
            }),
            b"vkDestroyInstance" => Some(unsafe {
                std::mem::transmute::<
                    unsafe extern "system" fn(vk::Instance, *const vk::AllocationCallbacks),
                    unsafe extern "system" fn(),
                >(mock_destroy_instance)
            }),
            _ => None,
        }
    }

    #[test]
    fn from_raw_parts_populates_commands_from_rich_mock() {
        let instance =
            unsafe { Instance::from_raw_parts(fake_handle(), Some(rich_instance_proc_addr_v2)) };
        assert!(instance.commands().enumerate_physical_devices.is_some());
        assert!(instance.commands().destroy_instance.is_some());
        assert!(instance.commands().create_device.is_some());
        // Commands not returned by the mock should be None.
        assert!(instance.commands().get_physical_device_properties.is_none());
    }

    #[test]
    fn enumerate_physical_devices_with_mock() {
        let instance =
            unsafe { Instance::from_raw_parts(fake_handle(), Some(rich_instance_proc_addr_v2)) };
        let devices =
            unsafe { instance.enumerate_physical_devices() }.expect("enumerate should succeed");
        assert_eq!(devices.len(), 2);
        assert_eq!(devices[0].as_raw(), 0xAA);
        assert_eq!(devices[1].as_raw(), 0xBB);
    }

    #[test]
    fn destroy_instance_with_mock() {
        let instance =
            unsafe { Instance::from_raw_parts(fake_handle(), Some(rich_instance_proc_addr_v2)) };
        // Should not panic; mock destroy is a no-op.
        unsafe { instance.destroy_instance(None) };
    }

    #[test]
    fn create_device_from_raw_parts_instance() {
        // Verify the full flow: from_raw_parts resolves get_device_proc_addr,
        // then create_device uses it to load device commands.
        let instance =
            unsafe { Instance::from_raw_parts(fake_handle(), Some(rich_instance_proc_addr_v2)) };
        let create_info: vk::DeviceCreateInfo = unsafe { std::mem::zeroed() };
        let device = unsafe {
            instance.create_device(vk::PhysicalDevice::from_raw(0xAA), &create_info, None)
        }
        .expect("create_device should succeed");
        assert_eq!(device.handle().as_raw(), 0xBEEF);
    }

    #[test]
    fn create_device_propagates_error() {
        let instance = unsafe {
            Instance::load(
                fake_handle(),
                Some(failing_instance_proc_addr),
                Some(mock_device_proc_addr),
                None,
            )
        };
        let physical_device = vk::PhysicalDevice::from_raw(0xCAFE);
        let create_info: vk::DeviceCreateInfo = unsafe { std::mem::zeroed() };
        let result = unsafe { instance.create_device(physical_device, &create_info, None) };
        match result {
            Err(e) => assert_eq!(e, vk::Result::ERROR_INITIALIZATION_FAILED),
            Ok(_) => panic!("expected error, got Ok"),
        }
    }

    #[test]
    #[ignore] // requires Vulkan runtime
    fn enumerate_physical_devices_returns_at_least_one() {
        let _vk = crate::VK_TEST_MUTEX.lock().expect("VK_TEST_MUTEX poisoned");
        let instance = create_real_instance();
        let devices = unsafe { instance.enumerate_physical_devices() }
            .expect("enumerate_physical_devices failed");
        assert!(!devices.is_empty(), "expected at least one physical device");
    }

    #[test]
    #[ignore] // requires Vulkan runtime
    fn get_physical_device_properties_succeeds() {
        let _vk = crate::VK_TEST_MUTEX.lock().expect("VK_TEST_MUTEX poisoned");
        let instance = create_real_instance();
        let devices = unsafe { instance.enumerate_physical_devices() }
            .expect("enumerate_physical_devices failed");
        let props = unsafe { instance.get_physical_device_properties(devices[0]) };
        let name_bytes: Vec<u8> = props
            .device_name
            .iter()
            .take_while(|&&c| c != 0)
            .map(|&c| c as u8)
            .collect();
        let name = String::from_utf8_lossy(&name_bytes);
        println!("GPU: {name}");
        assert!(!name.is_empty());
    }

    #[test]
    #[ignore] // requires Vulkan runtime
    fn get_physical_device_queue_family_properties_returns_at_least_one() {
        let _vk = crate::VK_TEST_MUTEX.lock().expect("VK_TEST_MUTEX poisoned");
        let instance = create_real_instance();
        let devices = unsafe { instance.enumerate_physical_devices() }
            .expect("enumerate_physical_devices failed");
        let families = unsafe { instance.get_physical_device_queue_family_properties(devices[0]) };
        assert!(!families.is_empty(), "expected at least one queue family");
    }

    #[test]
    #[ignore] // requires Vulkan runtime
    fn get_physical_device_memory_properties_succeeds() {
        let _vk = crate::VK_TEST_MUTEX.lock().expect("VK_TEST_MUTEX poisoned");
        let instance = create_real_instance();
        let devices = unsafe { instance.enumerate_physical_devices() }
            .expect("enumerate_physical_devices failed");
        let mem_props = unsafe { instance.get_physical_device_memory_properties(devices[0]) };
        assert!(
            mem_props.memory_type_count > 0,
            "expected at least one memory type"
        );
        assert!(
            mem_props.memory_heap_count > 0,
            "expected at least one memory heap"
        );
    }

    #[test]
    #[ignore] // requires Vulkan runtime
    fn get_physical_device_features_succeeds() {
        let _vk = crate::VK_TEST_MUTEX.lock().expect("VK_TEST_MUTEX poisoned");
        let instance = create_real_instance();
        let devices = unsafe { instance.enumerate_physical_devices() }
            .expect("enumerate_physical_devices failed");
        // Just verify the call completes without crashing; feature
        // availability is driver-dependent.
        let _features = unsafe { instance.get_physical_device_features(devices[0]) };
    }

    fn create_real_instance() -> Instance {
        use crate::entry::Entry;
        use crate::loader::LibloadingLoader;

        let loader = LibloadingLoader::new().expect("failed to load Vulkan");
        let entry = unsafe { Entry::new(loader) }.expect("failed to create Entry");

        let api_version_1_0 = crate::Version::new(1, 0, 0).to_raw();

        let app_info = vk::ApplicationInfo {
            s_type: vk::StructureType::APPLICATION_INFO,
            p_next: std::ptr::null(),
            p_application_name: std::ptr::null(),
            application_version: 0,
            p_engine_name: std::ptr::null(),
            engine_version: 0,
            api_version: api_version_1_0,
        };
        let create_info = vk::InstanceCreateInfo {
            s_type: vk::StructureType::INSTANCE_CREATE_INFO,
            p_next: std::ptr::null(),
            flags: vk::InstanceCreateFlagBits::empty(),
            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(),
        };

        unsafe { entry.create_instance(&create_info, None) }.expect("failed to create instance")
    }
}