Skip to main content

vulkan/
vulkan.rs

1//! taut under Vulkan. The program renders with Vulkan as usual, and the interface lies over it:
2//! `taut::layer_vulkan::Layer`, made once from the program's device and queue, draws it with one
3//! call per frame, inside the program's render pass.
4//!
5//! Around it is a windowless program: it renders its own picture, the interface over it,
6//! changes something and renders again, and writes the frame to a PNG file. (A windowed program
7//! has a swap chain, whose images are drawn into the same way.)
8//!   cargo run --example vulkan [<file.png>]
9//!
10//! Only the system's Vulkan loader (vulkan-1.dll, libvulkan.so.1), opened by name; the API used
11//! is declared here as vulkan_core.h declares it. (A program using a Vulkan bindings crate hands
12//! the layer its handles' raw values.)
13// The handles handed to the functions here are the program's own Vulkan objects, trusted as
14// Vulkan trusts them.
15#![allow(clippy::not_unsafe_ptr_arg_deref)]
16use std::ffi::{c_char, c_void};
17use std::ptr::{null, null_mut};
18use taut::geom::Size;
19use taut::layer_vulkan::{Handles, Layer};
20use taut::text::TextSystem;
21use taut::{Color, Event, Key, Length, LocalClipboard, Mods, Ui};
22
23/// Declares a set of Vulkan's functions, found by name.
24macro_rules! functions {
25    ($set:ident { $($name:ident: fn($($arg:ty),*) $(-> $out:ty)?;)* }) => {
26        /// Functions of Vulkan's, found by name.
27        #[allow(non_snake_case)]
28        pub struct $set {
29            $(pub $name: unsafe extern "system" fn($($arg),*) $(-> $out)?,)*
30        }
31        impl $set {
32            /// Finds each function with `find`, which is handed its name ending in a zero.
33            pub fn load(find: &mut dyn FnMut(&str) -> *const c_void) -> Option<$set> {
34                let mut found = |name: &str| Some(find(name)).filter(|found| !found.is_null());
35                // SAFETY: each function is declared as Vulkan declares it.
36                Some($set { $($name: unsafe { std::mem::transmute::<*const c_void, unsafe extern "system" fn($($arg),*) $(-> $out)?>(found(concat!(stringify!($name), "\0"))?) },)* })
37            }
38        }
39    };
40}
41
42/// Declares structures of Vulkan's, as vulkan_core.h lays them out. Each starts out all
43/// zero, which says nothing in any of them: no pointers, no flags, nothing chained.
44macro_rules! structures {
45    ($($name:ident { $($field:ident: $type:ty,)* })*) => {$(
46        #[repr(C)]
47        #[derive(Clone, Copy)]
48        #[allow(non_snake_case)]
49        pub struct $name {
50            $(pub $field: $type,)*
51        }
52        impl Default for $name {
53            fn default() -> Self {
54                // SAFETY: every field is a number or a pointer, for which zero is a value.
55                unsafe { std::mem::zeroed() }
56            }
57        }
58    )*};
59}
60
61/// A handle that is a number (an image, a buffer, a render pass), not a pointer.
62pub type Handle = u64;
63/// A handle that is a pointer (the instance, the device, a queue, a command buffer).
64pub type Object = *mut c_void;
65
66structures! {
67    VkApplicationInfo { kind: u32, next: *const c_void, name: *const c_char, version: u32, engine: *const c_char, engine_version: u32, api_version: u32, }
68    VkInstanceCreateInfo { kind: u32, next: *const c_void, flags: u32, application: *const VkApplicationInfo, layer_count: u32, layers: *const *const c_char, extension_count: u32, extensions: *const *const c_char, }
69    VkQueueFamilyProperties { flags: u32, count: u32, timestamp_bits: u32, granularity: [u32; 3], }
70    VkDeviceQueueCreateInfo { kind: u32, next: *const c_void, flags: u32, family: u32, count: u32, priorities: *const f32, }
71    VkDeviceCreateInfo { kind: u32, next: *const c_void, flags: u32, queue_count: u32, queues: *const VkDeviceQueueCreateInfo, layer_count: u32, layers: *const *const c_char, extension_count: u32, extensions: *const *const c_char, features: *const c_void, }
72    VkMemoryType { flags: u32, heap: u32, }
73    VkMemoryHeap { size: u64, flags: u32, }
74    VkPhysicalDeviceMemoryProperties { type_count: u32, types: [VkMemoryType; 32], heap_count: u32, heaps: [VkMemoryHeap; 16], }
75    VkMemoryRequirements { size: u64, alignment: u64, type_bits: u32, }
76    VkMemoryAllocateInfo { kind: u32, next: *const c_void, size: u64, type_index: u32, }
77    VkImageCreateInfo { kind: u32, next: *const c_void, flags: u32, image_type: u32, format: u32, extent: [u32; 3], mip_levels: u32, array_layers: u32, samples: u32, tiling: u32, usage: u32, sharing_mode: u32, queue_family_count: u32, queue_families: *const u32, initial_layout: u32, }
78    VkImageViewCreateInfo { kind: u32, next: *const c_void, flags: u32, image: Handle, view_type: u32, format: u32, components: [u32; 4], range: [u32; 5], }
79    VkBufferCreateInfo { kind: u32, next: *const c_void, flags: u32, size: u64, usage: u32, sharing_mode: u32, queue_family_count: u32, queue_families: *const u32, }
80    VkAttachmentDescription { flags: u32, format: u32, samples: u32, load: u32, store: u32, stencil_load: u32, stencil_store: u32, initial_layout: u32, final_layout: u32, }
81    VkAttachmentReference { attachment: u32, layout: u32, }
82    VkSubpassDescription { flags: u32, bind_point: u32, input_count: u32, inputs: *const VkAttachmentReference, colour_count: u32, colours: *const VkAttachmentReference, resolves: *const VkAttachmentReference, depth_stencil: *const VkAttachmentReference, preserve_count: u32, preserves: *const u32, }
83    VkRenderPassCreateInfo { kind: u32, next: *const c_void, flags: u32, attachment_count: u32, attachments: *const VkAttachmentDescription, subpass_count: u32, subpasses: *const VkSubpassDescription, dependency_count: u32, dependencies: *const c_void, }
84    VkFramebufferCreateInfo { kind: u32, next: *const c_void, flags: u32, render_pass: Handle, attachment_count: u32, attachments: *const Handle, width: u32, height: u32, layers: u32, }
85    VkCommandPoolCreateInfo { kind: u32, next: *const c_void, flags: u32, family: u32, }
86    VkCommandBufferAllocateInfo { kind: u32, next: *const c_void, pool: Handle, level: u32, count: u32, }
87    VkCommandBufferBeginInfo { kind: u32, next: *const c_void, flags: u32, inheritance: *const c_void, }
88    VkRect2D { offset: [i32; 2], extent: [u32; 2], }
89    VkRenderPassBeginInfo { kind: u32, next: *const c_void, render_pass: Handle, framebuffer: Handle, area: VkRect2D, clear_count: u32, clears: *const c_void, }
90    VkSubmitInfo { kind: u32, next: *const c_void, wait_count: u32, waits: *const Handle, wait_stages: *const u32, buffer_count: u32, buffers: *const Object, signal_count: u32, signals: *const Handle, }
91    VkFenceCreateInfo { kind: u32, next: *const c_void, flags: u32, }
92    VkMemoryBarrier { kind: u32, next: *const c_void, source_access: u32, destination_access: u32, }
93    VkImageMemoryBarrier { kind: u32, next: *const c_void, source_access: u32, destination_access: u32, old_layout: u32, new_layout: u32, source_family: u32, destination_family: u32, image: Handle, range: [u32; 5], }
94    VkBufferImageCopy { buffer_offset: u64, row_length: u32, image_height: u32, layers: [u32; 4], offset: [i32; 3], extent: [u32; 3], }
95}
96
97functions!(Program {
98    vkDestroyInstance: fn(Object, *const c_void);
99    vkEnumeratePhysicalDevices: fn(Object, *mut u32, *mut Object) -> i32;
100    vkGetPhysicalDeviceQueueFamilyProperties: fn(Object, *mut u32, *mut VkQueueFamilyProperties);
101    vkGetPhysicalDeviceMemoryProperties: fn(Object, *mut VkPhysicalDeviceMemoryProperties);
102    vkCreateDevice: fn(Object, *const VkDeviceCreateInfo, *const c_void, *mut Object) -> i32;
103    vkDestroyDevice: fn(Object, *const c_void);
104    vkGetDeviceQueue: fn(Object, u32, u32, *mut Object);
105    vkCreateImage: fn(Object, *const VkImageCreateInfo, *const c_void, *mut Handle) -> i32;
106    vkDestroyImage: fn(Object, Handle, *const c_void);
107    vkGetImageMemoryRequirements: fn(Object, Handle, *mut VkMemoryRequirements);
108    vkBindImageMemory: fn(Object, Handle, Handle, u64) -> i32;
109    vkCreateImageView: fn(Object, *const VkImageViewCreateInfo, *const c_void, *mut Handle) -> i32;
110    vkDestroyImageView: fn(Object, Handle, *const c_void);
111    vkCreateBuffer: fn(Object, *const VkBufferCreateInfo, *const c_void, *mut Handle) -> i32;
112    vkDestroyBuffer: fn(Object, Handle, *const c_void);
113    vkGetBufferMemoryRequirements: fn(Object, Handle, *mut VkMemoryRequirements);
114    vkBindBufferMemory: fn(Object, Handle, Handle, u64) -> i32;
115    vkAllocateMemory: fn(Object, *const VkMemoryAllocateInfo, *const c_void, *mut Handle) -> i32;
116    vkFreeMemory: fn(Object, Handle, *const c_void);
117    vkMapMemory: fn(Object, Handle, u64, u64, u32, *mut *mut c_void) -> i32;
118    vkCreateRenderPass: fn(Object, *const VkRenderPassCreateInfo, *const c_void, *mut Handle) -> i32;
119    vkDestroyRenderPass: fn(Object, Handle, *const c_void);
120    vkCreateFramebuffer: fn(Object, *const VkFramebufferCreateInfo, *const c_void, *mut Handle) -> i32;
121    vkDestroyFramebuffer: fn(Object, Handle, *const c_void);
122    vkCreateCommandPool: fn(Object, *const VkCommandPoolCreateInfo, *const c_void, *mut Handle) -> i32;
123    vkDestroyCommandPool: fn(Object, Handle, *const c_void);
124    vkAllocateCommandBuffers: fn(Object, *const VkCommandBufferAllocateInfo, *mut Object) -> i32;
125    vkBeginCommandBuffer: fn(Object, *const VkCommandBufferBeginInfo) -> i32;
126    vkEndCommandBuffer: fn(Object) -> i32;
127    vkCmdBeginRenderPass: fn(Object, *const VkRenderPassBeginInfo, u32);
128    vkCmdEndRenderPass: fn(Object);
129    vkCmdCopyBufferToImage: fn(Object, Handle, Handle, u32, u32, *const VkBufferImageCopy);
130    vkCmdCopyImageToBuffer: fn(Object, Handle, u32, Handle, u32, *const VkBufferImageCopy);
131    vkCmdPipelineBarrier: fn(Object, u32, u32, u32, u32, *const VkMemoryBarrier, u32, *const c_void, u32, *const VkImageMemoryBarrier);
132    vkCreateFence: fn(Object, *const VkFenceCreateInfo, *const c_void, *mut Handle) -> i32;
133    vkDestroyFence: fn(Object, Handle, *const c_void);
134    vkWaitForFences: fn(Object, u32, *const Handle, u32, u64) -> i32;
135    vkResetFences: fn(Object, u32, *const Handle) -> i32;
136    vkQueueSubmit: fn(Object, u32, *const VkSubmitInfo, Handle) -> i32;
137    vkDeviceWaitIdle: fn(Object) -> i32;
138});
139
140/// Pixels of B8G8R8A8_UNORM: blue, green, red and alpha bytes, as the interface's are.
141pub const B8G8R8A8_UNORM: u32 = 44;
142/// All of an image's colour: aspect, first level, levels, first layer, layers.
143pub const WHOLE: [u32; 5] = [0x1, 0, 1, 0, 1];
144
145/// Stops the program with what Vulkan said, where it said something went wrong.
146pub fn check(result: i32, what: &str) {
147    assert!(result >= 0, "{what} failed: {result}");
148}
149
150/// An image's layout changing, and what was done to it before made visible to what is done
151/// after.
152pub fn barrier(image: Handle, old_layout: u32, new_layout: u32, source_access: u32, destination_access: u32) -> VkImageMemoryBarrier {
153    VkImageMemoryBarrier { kind: 45, source_access, destination_access, old_layout, new_layout, source_family: !0, destination_family: !0, image, range: WHOLE, ..Default::default() }
154}
155
156#[cfg(windows)]
157#[link(name = "kernel32")]
158unsafe extern "system" {
159    fn LoadLibraryA(name: *const c_char) -> isize;
160    fn GetProcAddress(library: isize, name: *const u8) -> *const c_void;
161}
162#[cfg(unix)]
163unsafe extern "C" {
164    fn dlopen(file: *const c_char, flags: i32) -> *mut c_void;
165    fn dlsym(library: *mut c_void, name: *const c_char) -> *mut c_void;
166}
167
168/// The loader's one function that finds all the others, if the system has a loader.
169fn loader() -> Option<unsafe extern "system" fn(Object, *const c_char) -> *const c_void> {
170    // SAFETY: the names end in a zero; the library stays open while the program runs.
171    #[cfg(windows)]
172    let found = unsafe { Some(LoadLibraryA(c"vulkan-1.dll".as_ptr())).filter(|library| *library != 0).map(|library| GetProcAddress(library, c"vkGetInstanceProcAddr".as_ptr().cast())) };
173    #[cfg(unix)]
174    let found = unsafe { Some(dlopen(c"libvulkan.so.1".as_ptr(), 2)).filter(|library| !library.is_null()).map(|library| dlsym(library, c"vkGetInstanceProcAddr".as_ptr()).cast_const()) };
175    // SAFETY: the loader's function is declared as vulkan_core.h declares it.
176    found.filter(|found| !found.is_null()).map(|found| unsafe { std::mem::transmute(found) })
177}
178
179/// A Vulkan device with a queue that draws, a command buffer, and a fence to wait on it.
180pub struct Device {
181    pub program: Program,
182    instance: Object,
183    physical: Object,
184    pub device: Object,
185    memory: VkPhysicalDeviceMemoryProperties,
186    pub queue: Object,
187    family: u32,
188    pool: Handle,
189    pub commands: Object,
190    fence: Handle,
191}
192
193impl Device {
194    /// The first device the system has that draws; nothing, where there is none.
195    pub fn new() -> Option<Device> {
196        type Make = unsafe extern "system" fn(*const VkInstanceCreateInfo, *const c_void, *mut Object) -> i32;
197        let find = loader()?;
198        let application = VkApplicationInfo { name: c"taut".as_ptr(), api_version: 1 << 22, ..Default::default() };
199        let mut instance = null_mut();
200        // SAFETY: the loader hands out functions by name; the instance is made once.
201        unsafe {
202            let make = Some(find(null_mut(), c"vkCreateInstance".as_ptr())).filter(|make| !make.is_null())?;
203            let asked = VkInstanceCreateInfo { kind: 1, application: &application, ..Default::default() };
204            (std::mem::transmute::<*const c_void, Make>(make)(&asked, null(), &mut instance) >= 0).then_some(())?;
205        }
206        let program = Program::load(&mut |name| unsafe { find(instance, name.as_ptr().cast()) })?;
207        Device::on_first(program, instance)
208    }
209
210    /// The device, on the first of the system's that has a queue that draws.
211    fn on_first(program: Program, instance: Object) -> Option<Device> {
212        let (mut count, mut physical, mut families, mut family) = (1, null_mut(), [VkQueueFamilyProperties::default(); 16], 16);
213        let priority = 1.0f32;
214        // SAFETY: the instance is alive; each list has room for as many as is said.
215        unsafe {
216            (program.vkEnumeratePhysicalDevices)(instance, &mut count, &mut physical);
217            (count == 1).then_some(())?;
218            (program.vkGetPhysicalDeviceQueueFamilyProperties)(physical, &mut family, families.as_mut_ptr());
219            let family = families[..family as usize].iter().position(|kind| kind.flags & 1 == 1)? as u32;
220            let queue = VkDeviceQueueCreateInfo { kind: 2, family, count: 1, priorities: &priority, ..Default::default() };
221            let asked = VkDeviceCreateInfo { kind: 3, queue_count: 1, queues: &queue, ..Default::default() };
222            let (mut device, mut memory) = (null_mut(), VkPhysicalDeviceMemoryProperties::default());
223            (program.vkGetPhysicalDeviceMemoryProperties)(physical, &mut memory);
224            ((program.vkCreateDevice)(physical, &asked, null(), &mut device) >= 0).then_some(())?;
225            Some(Device::with_commands(program, instance, physical, device, memory, family))
226        }
227    }
228
229    /// The device's queue, a command buffer that is used again and again, and its fence.
230    fn with_commands(program: Program, instance: Object, physical: Object, device: Object, memory: VkPhysicalDeviceMemoryProperties, family: u32) -> Device {
231        let (mut queue, mut pool, mut commands, mut fence) = (null_mut(), 0, null_mut(), 0);
232        // SAFETY: the device is alive; each description is whole.
233        unsafe {
234            (program.vkGetDeviceQueue)(device, family, 0, &mut queue);
235            let pooled = VkCommandPoolCreateInfo { kind: 39, flags: 0x2, family, ..Default::default() };
236            check((program.vkCreateCommandPool)(device, &pooled, null(), &mut pool), "making a command pool");
237            let asked = VkCommandBufferAllocateInfo { kind: 40, pool, count: 1, ..Default::default() };
238            check((program.vkAllocateCommandBuffers)(device, &asked, &mut commands), "making a command buffer");
239            check((program.vkCreateFence)(device, &VkFenceCreateInfo { kind: 8, ..Default::default() }, null(), &mut fence), "making a fence");
240        }
241        Device { program, instance, physical, device, memory, queue, family, pool, commands, fence }
242    }
243
244    /// What the layer is given: the device, its queue, and the render pass it is drawn in.
245    pub fn handles(&self, render_pass: Handle) -> Handles {
246        Handles { instance: self.instance, physical_device: self.physical, device: self.device, queue: self.queue, queue_family: self.family, render_pass, subpass: 0 }
247    }
248
249    /// Memory for something with these needs, of a kind that is `wanted` (device-local, or
250    /// that the processor writes and reads without flushing).
251    pub fn memory(&self, needs: VkMemoryRequirements, wanted: u32) -> Handle {
252        let fits = |at: &u32| needs.type_bits >> at & 1 == 1 && self.memory.types[*at as usize].flags & wanted == wanted;
253        let kind = (0..self.memory.type_count).find(fits).expect("the device has no memory of the kind needed");
254        let asked = VkMemoryAllocateInfo { kind: 5, size: needs.size, type_index: kind, ..Default::default() };
255        let mut memory = 0;
256        // SAFETY: the device is alive, and the description is whole.
257        check(unsafe { (self.program.vkAllocateMemory)(self.device, &asked, null(), &mut memory) }, "allocating memory");
258        memory
259    }
260
261    /// A buffer of `size` bytes for `usage`, in memory the processor writes and reads, which
262    /// stays where the processor can see it: there.
263    pub fn buffer(&self, size: usize, usage: u32) -> (Handle, Handle, *mut u32) {
264        let made = VkBufferCreateInfo { kind: 12, size: size as u64, usage, ..Default::default() };
265        let (program, mut buffer, mut needs, mut there) = (&self.program, 0, VkMemoryRequirements::default(), null_mut());
266        // SAFETY: the device is alive; the buffer is made, given memory, and the memory mapped.
267        unsafe {
268            check((program.vkCreateBuffer)(self.device, &made, null(), &mut buffer), "making a buffer");
269            (program.vkGetBufferMemoryRequirements)(self.device, buffer, &mut needs);
270            let memory = self.memory(needs, 0x2 | 0x4);
271            check((program.vkBindBufferMemory)(self.device, buffer, memory, 0), "binding a buffer's memory");
272            check((program.vkMapMemory)(self.device, memory, 0, u64::MAX, 0, &mut there), "mapping memory");
273            (buffer, memory, there.cast())
274        }
275    }
276
277    /// An image `width` by `height` for `usage`, in the device's own memory; and a view of it.
278    pub fn image(&self, width: usize, height: usize, usage: u32) -> (Handle, Handle, Handle) {
279        let extent = [width as u32, height as u32, 1];
280        let made = VkImageCreateInfo { kind: 14, image_type: 1, format: B8G8R8A8_UNORM, extent, mip_levels: 1, array_layers: 1, samples: 1, usage, ..Default::default() };
281        let (program, mut image, mut needs, mut view) = (&self.program, 0, VkMemoryRequirements::default(), 0);
282        // SAFETY: the device is alive; the image is made, given memory, and looked at whole.
283        unsafe {
284            check((program.vkCreateImage)(self.device, &made, null(), &mut image), "making an image");
285            (program.vkGetImageMemoryRequirements)(self.device, image, &mut needs);
286            let memory = self.memory(needs, 0x1);
287            check((program.vkBindImageMemory)(self.device, image, memory, 0), "binding an image's memory");
288            let view_info = VkImageViewCreateInfo { kind: 15, image, view_type: 1, format: B8G8R8A8_UNORM, range: WHOLE, ..Default::default() };
289            check((program.vkCreateImageView)(self.device, &view_info, null(), &mut view), "making an image's view");
290            (image, memory, view)
291        }
292    }
293
294    /// Starts recording the command buffer.
295    pub fn begin(&self) {
296        // SAFETY: the device is done with the buffer: every submit was waited for.
297        check(unsafe { (self.program.vkBeginCommandBuffer)(self.commands, &VkCommandBufferBeginInfo { kind: 42, flags: 0x1, ..Default::default() }) }, "recording");
298    }
299
300    /// Hands what was recorded to the device, and waits until it is done.
301    pub fn submit(&self) {
302        let submit = VkSubmitInfo { kind: 4, buffer_count: 1, buffers: &self.commands, ..Default::default() };
303        // SAFETY: the buffer was recorded; the fence is this device's, and not in use.
304        unsafe {
305            check((self.program.vkEndCommandBuffer)(self.commands), "ending the recording");
306            check((self.program.vkQueueSubmit)(self.queue, 1, &submit, self.fence), "submitting");
307            check((self.program.vkWaitForFences)(self.device, 1, &self.fence, 1, u64::MAX), "waiting");
308            check((self.program.vkResetFences)(self.device, 1, &self.fence), "resetting the fence");
309        }
310    }
311
312    /// Waits until the device has done everything it was given.
313    pub fn wait(&self) {
314        // SAFETY: the device is alive.
315        check(unsafe { (self.program.vkDeviceWaitIdle)(self.device) }, "waiting for the device");
316    }
317}
318
319impl Drop for Device {
320    fn drop(&mut self) {
321        let (program, device) = (&self.program, self.device);
322        // SAFETY: the device is done with everything (it is waited for first).
323        unsafe {
324            (program.vkDeviceWaitIdle)(device);
325            (program.vkDestroyFence)(device, self.fence, null());
326            (program.vkDestroyCommandPool)(device, self.pool, null());
327            (program.vkDestroyDevice)(device, null());
328            (program.vkDestroyInstance)(self.instance, null());
329        }
330    }
331}
332
333/// The image the program draws into, `width` by `height`; the render pass that draws into it,
334/// keeping what is there; and a buffer the processor writes the program's own picture into
335/// and reads the frame back from.
336pub struct Target {
337    pub render_pass: Handle,
338    pub image: Handle,
339    memory: Handle,
340    view: Handle,
341    framebuffer: Handle,
342    buffer: Handle,
343    buffer_memory: Handle,
344    there: *mut u32,
345    pub width: usize,
346    pub height: usize,
347}
348
349impl Target {
350    pub fn new(device: &Device, width: usize, height: usize) -> Target {
351        let program = &device.program;
352        // Copied to and from (0x2, 0x1), drawn into (0x10); the buffer both ways too.
353        let (image, memory, view) = device.image(width, height, 0x1 | 0x2 | 0x10);
354        let (buffer, buffer_memory, there) = device.buffer(width * height * 4, 0x1 | 0x2);
355        // One colour attachment, its pixels kept (load 0, store 0), in the layout for drawing (2).
356        let attachment = VkAttachmentDescription { format: B8G8R8A8_UNORM, samples: 1, stencil_load: 2, stencil_store: 1, initial_layout: 2, final_layout: 2, ..Default::default() };
357        let colour = VkAttachmentReference { attachment: 0, layout: 2 };
358        let subpass = VkSubpassDescription { colour_count: 1, colours: &colour, ..Default::default() };
359        let pass = VkRenderPassCreateInfo { kind: 38, attachment_count: 1, attachments: &attachment, subpass_count: 1, subpasses: &subpass, ..Default::default() };
360        let (mut render_pass, mut framebuffer) = (0, 0);
361        // SAFETY: the device is alive; each description is whole.
362        unsafe {
363            check((program.vkCreateRenderPass)(device.device, &pass, null(), &mut render_pass), "making the render pass");
364            let made = VkFramebufferCreateInfo { kind: 37, render_pass, attachment_count: 1, attachments: &view, width: width as u32, height: height as u32, layers: 1, ..Default::default() };
365            check((program.vkCreateFramebuffer)(device.device, &made, null(), &mut framebuffer), "making the framebuffer");
366        }
367        Target { render_pass, image, memory, view, framebuffer, buffer, buffer_memory, there, width, height }
368    }
369
370    /// One frame: `picture`, the program's own, copied into the image; `draw` called inside
371    /// the render pass with the command buffer; and the frame read back.
372    pub fn frame(&self, device: &Device, picture: &[u32], draw: &mut dyn FnMut(Object)) -> Vec<u32> {
373        let (program, commands) = (&device.program, device.commands);
374        let whole = VkBufferImageCopy { row_length: self.width as u32, layers: [0x1, 0, 0, 1], extent: [self.width as u32, self.height as u32, 1], ..Default::default() };
375        let area = VkRect2D { offset: [0, 0], extent: [self.width as u32, self.height as u32] };
376        let begun = VkRenderPassBeginInfo { kind: 43, render_pass: self.render_pass, framebuffer: self.framebuffer, area, ..Default::default() };
377        // The image: copied to, drawn into, copied from; and the buffer read by the processor.
378        let (to_copy, to_draw) = (barrier(self.image, 0, 7, 0, 0x1000), barrier(self.image, 7, 2, 0x1000, 0x80 | 0x100));
379        let (to_read, by_hand) = (barrier(self.image, 2, 6, 0x100, 0x800), VkMemoryBarrier { kind: 46, source_access: 0x1000, destination_access: 0x2000, ..Default::default() });
380        // SAFETY: the buffer is as large as the picture; the device is done with it (each
381        // frame is waited for); the command buffer is recorded and submitted once.
382        unsafe {
383            std::ptr::copy_nonoverlapping(picture.as_ptr(), self.there, self.width * self.height);
384            device.begin();
385            (program.vkCmdPipelineBarrier)(commands, 0x1, 0x1000, 0, 0, null(), 0, null(), 1, &to_copy);
386            (program.vkCmdCopyBufferToImage)(commands, self.buffer, self.image, 7, 1, &whole);
387            (program.vkCmdPipelineBarrier)(commands, 0x1000, 0x400, 0, 0, null(), 0, null(), 1, &to_draw);
388            (program.vkCmdBeginRenderPass)(commands, &begun, 0);
389            draw(commands);
390            (program.vkCmdEndRenderPass)(commands);
391            (program.vkCmdPipelineBarrier)(commands, 0x400, 0x1000, 0, 0, null(), 0, null(), 1, &to_read);
392            (program.vkCmdCopyImageToBuffer)(commands, self.image, 6, self.buffer, 1, &whole);
393            (program.vkCmdPipelineBarrier)(commands, 0x1000, 0x4000, 0, 1, &by_hand, 0, null(), 0, null());
394            device.submit();
395            std::slice::from_raw_parts(self.there, self.width * self.height).to_vec()
396        }
397    }
398
399    /// Lets go of all of it. (The device is done with it.)
400    pub fn destroy(self, device: &Device) {
401        let (program, gpu) = (&device.program, device.device);
402        // SAFETY: each is this target's.
403        unsafe {
404            (program.vkDestroyFramebuffer)(gpu, self.framebuffer, null());
405            (program.vkDestroyRenderPass)(gpu, self.render_pass, null());
406            (program.vkDestroyImageView)(gpu, self.view, null());
407            (program.vkDestroyImage)(gpu, self.image, null());
408            (program.vkFreeMemory)(gpu, self.memory, null());
409            (program.vkDestroyBuffer)(gpu, self.buffer, null());
410            (program.vkFreeMemory)(gpu, self.buffer_memory, null());
411        }
412    }
413}
414
415/// What the program's own parts are set to.
416#[derive(Default)]
417struct App {
418    on: bool,
419    level: f32,
420    name: String,
421}
422
423fn describe(app: &mut App, ui: &mut Ui) {
424    let t = ui.theme;
425    ui.column().w(Length::Px(260.0)).offset(16.0, 16.0).pad(14.0).gap(10.0).fill(t.panel.with_alpha(0.9)).border(t.line_strong, 1.0).radius(10.0).shadow(12.0).open();
426    ui.text("Over Vulkan", t.font.bold(), t.text);
427    ui.switch(&mut app.on, "A switch");
428    ui.slider(&mut app.level, 0.0..=4.0);
429    ui.text_box(&mut app.name, "Type here");
430    ui.close();
431}
432
433/// The letters of the system, where this library knows how to reach them.
434fn letters() -> Box<dyn TextSystem> {
435    taut::platform::system_text()
436}
437
438fn main() {
439    let file = std::env::args().nth(1).unwrap_or("vulkan.png".into());
440    let Some(device) = Device::new() else { return println!("there is no Vulkan here: no loader, or no device that draws") };
441    let (width, height) = (480, 320);
442    let target = Target::new(&device, width, height);
443    // SAFETY: the program's own handles, which live longer than the layer.
444    let mut layer = unsafe { Layer::new(&device.handles(target.render_pass)) }.unwrap_or_else(|failed| panic!("{failed}"));
445    let mut ui = Ui::new(letters(), Box::new(LocalClipboard::default()));
446    ui.theme.bg = Color::NONE;
447    ui.resize(Size { w: width as f32, h: height as f32 }, 1.0);
448    let mut app = App::default();
449    // The program's own picture: a gradient.
450    let picture: Vec<u32> = (0..width * height).map(|at| 0xff00_0000 | ((at % width * 255 / width) as u32) << 16 | ((at / width * 255 / height) as u32) << 8 | 0x60).collect();
451    // The first frame copies all of the interface; the next, after the keyboard has come to
452    // the switch and turned it on, only the places that changed.
453    for event in [None, Some(Event::Key(Key::Tab, Mods::NONE)), Some(Event::Key(Key::Space, Mods::NONE))] {
454        if let Some(event) = event {
455            ui.event(event);
456        }
457        ui.run(&mut |ui| describe(&mut app, ui));
458        // SAFETY: the command buffer is the program's, recording, in its render pass.
459        let frame = target.frame(&device, &picture, &mut |commands| unsafe { layer.draw(&mut ui, commands, [0, 0, width as i32, height as i32]) }.unwrap_or_else(|failed| panic!("{failed}")));
460        std::fs::write(&file, taut::Surface { width, height, pixels: frame }.to_png()).expect("the picture could not be written");
461    }
462    println!("the last frame is in {file}");
463    device.wait();
464    // SAFETY: the device is done with every frame.
465    unsafe { layer.delete() };
466    target.destroy(&device);
467}