vulkane 0.4.0

Vulkan API bindings generated entirely from vk.xml, with a complete safe RAII wrapper covering compute and graphics: instance/device/queue, buffer, image, sampler, render pass, framebuffer, graphics + compute pipelines, swapchain, a VMA-style sub-allocator with TLSF + linear pools and defragmentation, sync primitives (fences, binary + timeline semaphores, sync2 barriers), query pools, and an optional naga GLSL/WGSL→SPIR-V feature. Supports Vulkan 1.2.175 onward — swap vk.xml and rebuild.
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
//! Safe wrappers for descriptor sets, layouts, and pools.
//!
//! In Vulkan, descriptor sets are how shaders access resources (buffers,
//! images, samplers). To bind a buffer to a compute shader you need:
//!
//! 1. A [`DescriptorSetLayout`] describing the bindings the shader expects.
//! 2. A [`DescriptorPool`] from which to allocate descriptor sets.
//! 3. A [`DescriptorSet`] allocated from the pool, with bindings written to
//!    point at actual buffers/images.
//!
//! The set layout becomes part of the [`PipelineLayout`](super::PipelineLayout),
//! which is in turn part of the [`ComputePipeline`](super::ComputePipeline).

use super::device::DeviceInner;
use super::image::{ImageLayout, ImageView, Sampler};
use super::{Buffer, Device, Error, Result, check};
use crate::raw::bindings::*;
use std::sync::Arc;

/// What kind of resource a descriptor binding represents.
///
/// `STORAGE_BUFFER`, `UNIFORM_BUFFER`, and `STORAGE_IMAGE` are sufficient for
/// the entire compute path. Sampler / sampled-image variants land with the
/// graphics work.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DescriptorType(pub VkDescriptorType);

impl DescriptorType {
    pub const STORAGE_BUFFER: Self = Self(VkDescriptorType::DESCRIPTOR_TYPE_STORAGE_BUFFER);
    pub const UNIFORM_BUFFER: Self = Self(VkDescriptorType::DESCRIPTOR_TYPE_UNIFORM_BUFFER);
    pub const STORAGE_IMAGE: Self = Self(VkDescriptorType::DESCRIPTOR_TYPE_STORAGE_IMAGE);
    pub const COMBINED_IMAGE_SAMPLER: Self =
        Self(VkDescriptorType::DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
    pub const SAMPLED_IMAGE: Self = Self(VkDescriptorType::DESCRIPTOR_TYPE_SAMPLED_IMAGE);
    pub const SAMPLER: Self = Self(VkDescriptorType::DESCRIPTOR_TYPE_SAMPLER);
}

/// Which pipeline stages may access a descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShaderStageFlags(pub u32);

impl ShaderStageFlags {
    pub const VERTEX: Self = Self(0x1);
    pub const FRAGMENT: Self = Self(0x10);
    pub const COMPUTE: Self = Self(0x20);
    pub const ALL_GRAPHICS: Self = Self(0x1F);
    pub const ALL: Self = Self(0x7FFFFFFF);

    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }
}

impl std::ops::BitOr for ShaderStageFlags {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

/// One binding in a [`DescriptorSetLayout`] — a `(binding, type, count, stages)` tuple.
#[derive(Debug, Clone, Copy)]
pub struct DescriptorSetLayoutBinding {
    /// The binding number that the shader uses (e.g., `layout(binding = 0)` in GLSL).
    pub binding: u32,
    /// What kind of resource lives at this binding.
    pub descriptor_type: DescriptorType,
    /// Number of descriptors at this binding (e.g., for arrays of buffers).
    pub descriptor_count: u32,
    /// Which shader stages may access this binding.
    pub stage_flags: ShaderStageFlags,
}

/// A safe wrapper around `VkDescriptorSetLayout`.
///
/// Set layouts describe the *shape* of descriptor sets. They are referenced by
/// pipeline layouts and by descriptor set allocations. They are destroyed
/// automatically on drop.
pub struct DescriptorSetLayout {
    pub(crate) handle: VkDescriptorSetLayout,
    pub(crate) device: Arc<DeviceInner>,
}

impl DescriptorSetLayout {
    /// Create a new descriptor set layout from a list of bindings.
    pub fn new(device: &Device, bindings: &[DescriptorSetLayoutBinding]) -> Result<Self> {
        let create = device
            .inner
            .dispatch
            .vkCreateDescriptorSetLayout
            .ok_or(Error::MissingFunction("vkCreateDescriptorSetLayout"))?;

        let raw_bindings: Vec<VkDescriptorSetLayoutBinding> = bindings
            .iter()
            .map(|b| VkDescriptorSetLayoutBinding {
                binding: b.binding,
                descriptorType: b.descriptor_type.0,
                descriptorCount: b.descriptor_count,
                stageFlags: b.stage_flags.0,
                pImmutableSamplers: std::ptr::null(),
            })
            .collect();

        let info = VkDescriptorSetLayoutCreateInfo {
            sType: VkStructureType::STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
            bindingCount: raw_bindings.len() as u32,
            pBindings: raw_bindings.as_ptr(),
            ..Default::default()
        };

        let mut handle: VkDescriptorSetLayout = 0;
        // Safety: info is valid for the call, raw_bindings outlives it.
        check(unsafe { create(device.inner.handle, &info, std::ptr::null(), &mut handle) })?;

        Ok(Self {
            handle,
            device: Arc::clone(&device.inner),
        })
    }

    /// Returns the raw `VkDescriptorSetLayout` handle.
    pub fn raw(&self) -> VkDescriptorSetLayout {
        self.handle
    }
}

impl Drop for DescriptorSetLayout {
    fn drop(&mut self) {
        if let Some(destroy) = self.device.dispatch.vkDestroyDescriptorSetLayout {
            // Safety: handle is valid; we are the sole owner.
            unsafe { destroy(self.device.handle, self.handle, std::ptr::null()) };
        }
    }
}

/// Pool size for one descriptor type — `(type, count)` pair.
#[derive(Debug, Clone, Copy)]
pub struct DescriptorPoolSize {
    pub descriptor_type: DescriptorType,
    pub descriptor_count: u32,
}

/// A safe wrapper around `VkDescriptorPool`.
///
/// Descriptor pools are arenas from which descriptor sets are allocated.
/// They are destroyed automatically on drop, which also frees all sets
/// allocated from them.
pub struct DescriptorPool {
    pub(crate) handle: VkDescriptorPool,
    pub(crate) device: Arc<DeviceInner>,
}

impl DescriptorPool {
    /// Create a new descriptor pool that can hold `max_sets` descriptor sets,
    /// with the given per-type budget.
    pub fn new(device: &Device, max_sets: u32, sizes: &[DescriptorPoolSize]) -> Result<Self> {
        let create = device
            .inner
            .dispatch
            .vkCreateDescriptorPool
            .ok_or(Error::MissingFunction("vkCreateDescriptorPool"))?;

        let raw_sizes: Vec<VkDescriptorPoolSize> = sizes
            .iter()
            .map(|s| VkDescriptorPoolSize {
                r#type: s.descriptor_type.0,
                descriptorCount: s.descriptor_count,
            })
            .collect();

        let info = VkDescriptorPoolCreateInfo {
            sType: VkStructureType::STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
            maxSets: max_sets,
            poolSizeCount: raw_sizes.len() as u32,
            pPoolSizes: raw_sizes.as_ptr(),
            ..Default::default()
        };

        let mut handle: VkDescriptorPool = 0;
        // Safety: info and raw_sizes are valid for the call.
        check(unsafe { create(device.inner.handle, &info, std::ptr::null(), &mut handle) })?;

        Ok(Self {
            handle,
            device: Arc::clone(&device.inner),
        })
    }

    /// Returns the raw `VkDescriptorPool` handle.
    pub fn raw(&self) -> VkDescriptorPool {
        self.handle
    }

    /// Allocate one descriptor set from this pool, using the given layout.
    pub fn allocate(&self, layout: &DescriptorSetLayout) -> Result<DescriptorSet> {
        let allocate = self
            .device
            .dispatch
            .vkAllocateDescriptorSets
            .ok_or(Error::MissingFunction("vkAllocateDescriptorSets"))?;

        let info = VkDescriptorSetAllocateInfo {
            sType: VkStructureType::STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
            descriptorPool: self.handle,
            descriptorSetCount: 1,
            pSetLayouts: &layout.handle,
            ..Default::default()
        };

        let mut handle: VkDescriptorSet = 0;
        // Safety: info is valid for the call.
        check(unsafe { allocate(self.device.handle, &info, &mut handle) })?;

        Ok(DescriptorSet {
            handle,
            device: Arc::clone(&self.device),
        })
    }
}

impl Drop for DescriptorPool {
    fn drop(&mut self) {
        if let Some(destroy) = self.device.dispatch.vkDestroyDescriptorPool {
            // Safety: handle is valid; this also frees all sets allocated
            // from the pool, so we don't need a separate vkFreeDescriptorSets.
            unsafe { destroy(self.device.handle, self.handle, std::ptr::null()) };
        }
    }
}

/// A safe wrapper around `VkDescriptorSet`.
///
/// Descriptor sets are allocated from a [`DescriptorPool`]; their lifetime is
/// tied to the pool. We don't implement `Drop` for `DescriptorSet` because
/// the pool's `Drop` frees all its sets in one operation.
pub struct DescriptorSet {
    pub(crate) handle: VkDescriptorSet,
    pub(crate) device: Arc<DeviceInner>,
}

impl DescriptorSet {
    /// Returns the raw `VkDescriptorSet` handle.
    pub fn raw(&self) -> VkDescriptorSet {
        self.handle
    }

    /// Update one binding in this set to point at a buffer.
    ///
    /// Equivalent to a single `vkUpdateDescriptorSets` call with one
    /// `VkWriteDescriptorSet` of type `STORAGE_BUFFER` or `UNIFORM_BUFFER`.
    pub fn write_buffer(
        &self,
        binding: u32,
        descriptor_type: DescriptorType,
        buffer: &Buffer,
        offset: u64,
        range: u64,
    ) {
        let update = self
            .device
            .dispatch
            .vkUpdateDescriptorSets
            .expect("vkUpdateDescriptorSets is required by Vulkan 1.0");

        let info = VkDescriptorBufferInfo {
            buffer: buffer.handle,
            offset,
            range,
        };

        let write = VkWriteDescriptorSet {
            sType: VkStructureType::STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
            dstSet: self.handle,
            dstBinding: binding,
            descriptorCount: 1,
            descriptorType: descriptor_type.0,
            pBufferInfo: &info,
            ..Default::default()
        };

        // Safety: handle is valid, write/info live for the duration of the call.
        unsafe { update(self.device.handle, 1, &write, 0, std::ptr::null()) };
    }

    /// Update one binding in this set to point at a (sampler, image
    /// view, layout) triple, suitable for a `COMBINED_IMAGE_SAMPLER`
    /// descriptor binding. The shader sees both the sampler and the
    /// sampled image at the same binding number — this is the
    /// OpenGL-style "texture2D" binding.
    ///
    /// `image_layout` is the layout the shader will see when it
    /// samples the image; typically
    /// [`ImageLayout::SHADER_READ_ONLY_OPTIMAL`](super::ImageLayout::SHADER_READ_ONLY_OPTIMAL).
    pub fn write_combined_image_sampler(
        &self,
        binding: u32,
        sampler: &Sampler,
        view: &ImageView,
        image_layout: ImageLayout,
    ) {
        let update = self
            .device
            .dispatch
            .vkUpdateDescriptorSets
            .expect("vkUpdateDescriptorSets is required by Vulkan 1.0");

        let info = VkDescriptorImageInfo {
            sampler: sampler.handle,
            imageView: view.handle,
            imageLayout: image_layout.0,
        };

        let write = VkWriteDescriptorSet {
            sType: VkStructureType::STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
            dstSet: self.handle,
            dstBinding: binding,
            descriptorCount: 1,
            descriptorType: VkDescriptorType::DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
            pImageInfo: &info,
            ..Default::default()
        };

        // Safety: handle is valid; write/info live for the duration of the call.
        unsafe { update(self.device.handle, 1, &write, 0, std::ptr::null()) };
    }

    /// Update one binding in this set to point at an image view used as
    /// a `SAMPLED_IMAGE` descriptor (i.e. a texture without an attached
    /// sampler — pair it with a separate `SAMPLER` binding from
    /// [`write_sampler`](Self::write_sampler)). This is the binding
    /// shape produced by WGSL's `texture_2d` declarations.
    ///
    /// `image_layout` is the layout the shader will see when it
    /// samples the image; typically
    /// [`ImageLayout::SHADER_READ_ONLY_OPTIMAL`](super::ImageLayout::SHADER_READ_ONLY_OPTIMAL).
    pub fn write_sampled_image(&self, binding: u32, view: &ImageView, image_layout: ImageLayout) {
        let update = self
            .device
            .dispatch
            .vkUpdateDescriptorSets
            .expect("vkUpdateDescriptorSets is required by Vulkan 1.0");

        let info = VkDescriptorImageInfo {
            sampler: 0,
            imageView: view.handle,
            imageLayout: image_layout.0,
        };

        let write = VkWriteDescriptorSet {
            sType: VkStructureType::STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
            dstSet: self.handle,
            dstBinding: binding,
            descriptorCount: 1,
            descriptorType: VkDescriptorType::DESCRIPTOR_TYPE_SAMPLED_IMAGE,
            pImageInfo: &info,
            ..Default::default()
        };

        // Safety: handle is valid; write/info live for the duration of the call.
        unsafe { update(self.device.handle, 1, &write, 0, std::ptr::null()) };
    }

    /// Update one binding in this set to point at a standalone
    /// [`Sampler`] (`SAMPLER` descriptor type). Pair with
    /// [`write_sampled_image`](Self::write_sampled_image) when using a
    /// WGSL-style separated texture/sampler binding.
    pub fn write_sampler(&self, binding: u32, sampler: &Sampler) {
        let update = self
            .device
            .dispatch
            .vkUpdateDescriptorSets
            .expect("vkUpdateDescriptorSets is required by Vulkan 1.0");

        let info = VkDescriptorImageInfo {
            sampler: sampler.handle,
            imageView: 0,
            imageLayout: VkImageLayout::IMAGE_LAYOUT_UNDEFINED,
        };

        let write = VkWriteDescriptorSet {
            sType: VkStructureType::STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
            dstSet: self.handle,
            dstBinding: binding,
            descriptorCount: 1,
            descriptorType: VkDescriptorType::DESCRIPTOR_TYPE_SAMPLER,
            pImageInfo: &info,
            ..Default::default()
        };

        // Safety: handle is valid; write/info live for the duration of the call.
        unsafe { update(self.device.handle, 1, &write, 0, std::ptr::null()) };
    }

    /// Update one binding in this set to point at an image view (currently
    /// only `STORAGE_IMAGE` is supported by the safe wrapper).
    ///
    /// `image_layout` is the layout the shader will see when it accesses
    /// the image — for `STORAGE_IMAGE` this should be
    /// [`ImageLayout::GENERAL`](super::ImageLayout::GENERAL).
    pub fn write_storage_image(&self, binding: u32, view: &ImageView, image_layout: ImageLayout) {
        let update = self
            .device
            .dispatch
            .vkUpdateDescriptorSets
            .expect("vkUpdateDescriptorSets is required by Vulkan 1.0");

        let info = VkDescriptorImageInfo {
            sampler: 0,
            imageView: view.handle,
            imageLayout: image_layout.0,
        };

        let write = VkWriteDescriptorSet {
            sType: VkStructureType::STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
            dstSet: self.handle,
            dstBinding: binding,
            descriptorCount: 1,
            descriptorType: VkDescriptorType::DESCRIPTOR_TYPE_STORAGE_IMAGE,
            pImageInfo: &info,
            ..Default::default()
        };

        // Safety: handle is valid, write/info live for the duration of the call.
        unsafe { update(self.device.handle, 1, &write, 0, std::ptr::null()) };
    }
}