1// The Vulkan device: Vulkan 1.1 with dynamic rendering and2// synchronization2, core in 1.3. Buffers and textures live in the GPU's3// memory; writes wait in a staging buffer until the next submission copies4// them in, and reads copy out through a buffer the host reads after5// waiting. Textures rest between commands in the layout their usage asks6// for, and every pass, copy and dispatch ends with a full barrier: simple7// rules, enough until measurements ask for more. Clip space keeps y up,8// as WebGPU's, through a viewport of negative height.910import std::ffi;11import std::option;12import std::string;13import std::vector;14import std::process;1516import gpu;17import commands;18import shader::blob;19import shader::compiler;20import pkg::alloy::window;21import vk;22import slots;2324const SLOTS: u64 = 4;25// a surface's current extent when the swap chain's decides it26const EXTENT_OF_SWAPCHAIN: u32 = 0xFFFFFFFF;2728type VulkanBuffer = struct {29 buffer: u64 = 0, // 0 for none30 memory: u64 = 0,31 size: u64 = 0,32};3334type VulkanTexture = struct {35 image: u64,36 memory: u64,37 view: u64,38 width: u32,39 height: u32,40 rest: ImageLayout, // the layout it has between commands41 // a swap chain's image: its contents are dropped when a pass starts42 discard: bool,43 drawn: bool, // a pass drew into the swap chain's image since acquired44};4546// A window's surface and its swap chain, made when first acquired and47// again when the window's size changes.48type VulkanSurface = struct {49 surface: u64,50 format: Format,51 swapchain: u64 = 0,52 width: u32 = 0,53 height: u32 = 0,54 // the size asked for when the swap chain was made, which the surface55 // may have given otherwise56 asked: [u32 : 2] = [0, 0],57 images: Vector<u32> = Vector<u32>::empty(), // the swap chain's images, as textures58 views: Vector<u64> = Vector<u64>::empty(),59 finished: Vector<u64> = Vector<u64>::empty(), // per image, signalled once its frame is drawn60 current: Option<u32> = ::None, // the image acquired61 stale: bool = false, // the swap chain no longer fits the surface62};6364type VulkanShader = struct {65 module: u64,66 resources: Vector<ShaderResource>,67 set_layouts: Vector<u64>,68 layout: u64,69};7071type VulkanPipeline = struct {72 pipeline: u64,73 shader: u32,74};7576// A submission's command buffer, with the staging buffer its writes go77// through; busy until its fence is waited on.78type Slot = struct {79 commands: c_pointer = 0,80 fence: u64 = 0,81 busy: bool = false,82 staging: VulkanBuffer = VulkanBuffer {},83 mapped: c_pointer = 0,84 waited: u64 = 0, // the semaphore the submission waited on, 0 for none85 serial: u64 = 0, // the submission's number, from 186};8788type VulkanGroup = struct {89 set: u64,90 pool: u64,91};9293// An object released, freed once the submissions made before have run.94type Release = struct {95 kind: ObjectKind,96 index: u32,97 after: u64, // the submissions there were98};99100pub type VulkanDevice : Driver = struct {101 library: Library,102 instance_functions: InstanceFunctions,103 f: DeviceFunctions,104 instance: c_pointer,105 physical: c_pointer,106 device: c_pointer,107 queue: c_pointer,108 family: u32,109 pub name: String,110 memory_types: Vector<u32>, // each type's properties111 command_pool: u64 = 0,112 slots: [Slot : SLOTS] = [Slot {} : SLOTS],113 next_slot: u64 = 0,114 buffers: Vector<VulkanBuffer> = Vector<VulkanBuffer>::empty(),115 textures: Vector<VulkanTexture> = Vector<VulkanTexture>::empty(),116 samplers: Vector<u64> = Vector<u64>::empty(),117 shaders: Vector<VulkanShader> = Vector<VulkanShader>::empty(),118 pipelines: Vector<VulkanPipeline> = Vector<VulkanPipeline>::empty(),119 computes: Vector<VulkanPipeline> = Vector<VulkanPipeline>::empty(),120 groups: Vector<VulkanGroup> = Vector<VulkanGroup>::empty(),121 pool: u64 = 0, // the descriptor pool sets come from, replaced when full122 released: Released = Released {},123 releases: Vector<Release> = Vector<Release>::empty(),124 serial: u64 = 0, // the submissions made125 staged: Staged = Staged {},126 fresh: Vector<u32> = Vector<u32>::empty(), // textures still to move into their resting layout127 readback: VulkanBuffer = VulkanBuffer {},128 readback_mapped: c_pointer = 0,129 surface_functions: Option<SurfaceFunctions>,130 surfaces: Vector<VulkanSurface> = Vector<VulkanSurface>::empty(),131 semaphores: Vector<u64> = Vector<u64>::empty(), // free ones, for acquiring images132 acquired: u64 = 0, // the semaphore of the image acquired, for the next submission to wait on133};134135/* --- Opening --- */136137pub fn VulkanDevice::open() -> Result<VulkanDevice> {138 const library_name: &[u8] = if (139 target() == "windows-x86_64"140 ) &"vulkan-1.dll" else &"libvulkan.so.1";141 const library = if (Library::open(&library_name) is ::Some |l|) l else {142 return ::Error(f"{library_name} cannot be loaded");143 };144 const get = if (library.symbol<GetProcAddr>(&"vkGetInstanceProcAddr") is ::Some |g|) g else {145 return ::Error(String::from(&"the Vulkan loader lacks vkGetInstanceProcAddr"));146 };147 const enumerate_version = if (148 find<extern (c_pointer) -> i32>(get, 0, &"vkEnumerateInstanceVersion") is ::Some |e|149 ) e else {150 return ::Error(String::from(&"the Vulkan loader only knows Vulkan 1.0"));151 };152 var version: [u32 : 1] = [0];153 enumerate_version(c_pointer::of(&version[..]));154 if (version[0] < API_VERSION_1_1) {155 return ::Error(String::from(&"the Vulkan loader only knows Vulkan 1.0"));156 }157 const application_name = text(&"alloy");158 const application = ApplicationInfo {159 .application_name = c_pointer::of(&application_name.view()),160 .application_version = 0,161 .engine_name = c_pointer::of(&application_name.view()),162 .engine_version = 0,163 .api_version = API_VERSION_1_3164 };165 // surfaces where the loader has both extensions166 const platform_extension: &[u8] = if (167 target() == "windows-x86_64"168 ) &"VK_KHR_win32_surface" else &"VK_KHR_wayland_surface";169 const surface_name = text(&"VK_KHR_surface");170 const platform_name = text(&platform_extension);171 const instance_extensions: [c_pointer : 2] = [172 c_pointer::of(&surface_name.view()),173 c_pointer::of(&platform_name.view())174 ];175 const surfaces = has_instance_extension(get, &"VK_KHR_surface") && has_instance_extension(176 get,177 &platform_extension178 );179 const instance_info = InstanceCreateInfo {180 .application_info = c_pointer::from(&application),181 .extension_count = if (surfaces) 2 else 0,182 .extensions = if (surfaces) c_pointer::of(&instance_extensions[..]) else 0183 };184 const create_instance: Create = function(get, 0, &"vkCreateInstance", &"");185 var instance: [c_pointer : 1] = [0];186 const created = create_instance(187 c_pointer::from(&instance_info),188 0,189 c_pointer::of(&instance[..]),190 0191 );192 if (created != SUCCESS) {193 return ::Error(f"vkCreateInstance failed ({created})");194 }195 const functions = InstanceFunctions::load(get, instance[0]);196 const chosen = if (choose(&functions, instance[0]) is ::Some |move c|) move c else {197 return ::Error(198 String::from(&"no Vulkan 1.1 device with dynamic rendering and synchronization2")199 );200 };201 const swapchain = surfaces && has_extension(&functions, chosen.physical, &"VK_KHR_swapchain");202 const device = if (create_device(&functions, &chosen, swapchain) is ::Some |d|) d else {203 return ::Error(String::from(&"vkCreateDevice failed"));204 };205 const f = DeviceFunctions::load(functions.get_device_proc_addr, device);206 var surface_functions = Option<SurfaceFunctions>::None;207 if (swapchain) {208 surface_functions = ::Some(SurfaceFunctions::load(209 get,210 instance[0],211 functions.get_device_proc_addr,212 device,213 if (214 target() == "windows-x86_64"215 ) &"vkCreateWin32SurfaceKHR" else &"vkCreateWaylandSurfaceKHR"216 ));217 }218 var queue: [c_pointer : 1] = [0];219 f.get_queue(device, chosen.family, 0, c_pointer::of(&queue[..]));220 var memory: [u8 : 1024] = [0 : 1024];221 functions.get_memory_properties(chosen.physical, c_pointer::of(&memory[..]));222 var memory_types = Vector<u32>::empty();223 for ([..word(&memory, 0) to u64]) |k| {224 memory_types.push(word(&memory, 4 + k * 8));225 }226 var v = VulkanDevice {227 .library = library,228 .instance_functions = functions,229 .f = f,230 .instance = instance[0],231 .physical = chosen.physical,232 .device = device,233 .queue = queue[0],234 .family = chosen.family,235 .name = copy chosen.name,236 .memory_types = move memory_types,237 .surface_functions = move surface_functions238 };239 const pool_info = CommandPoolCreateInfo {240 .flags = COMMAND_POOL_RESET_BUFFER,241 .family = chosen.family242 };243 v.command_pool = v.made(244 v.f.create_command_pool,245 c_pointer::from(&pool_info),246 &"vkCreateCommandPool"247 );248 for (v.slots) |&var slot| {249 const allocate = CommandBufferAllocateInfo {250 .pool = v.command_pool,251 .level = CommandBufferLevel::Primary,252 .count = 1253 };254 var commands: [c_pointer : 1] = [0];255 check(256 v.f.allocate_command_buffers(257 device,258 c_pointer::from(&allocate),259 c_pointer::of(&commands[..])260 ),261 &"vkAllocateCommandBuffers"262 );263 const fence_info = FenceCreateInfo {};264 slot.commands = commands[0];265 slot.fence = v.made(v.f.create_fence, c_pointer::from(&fence_info), &"vkCreateFence");266 }267 return ::Ok(move v);268}269270type ChosenDevice = struct {271 physical: c_pointer,272 family: u32,273 version: u32, // the Vulkan version used: the device's, at most 1.3274 name: String,275};276277// The device to use: a discrete GPU before an integrated one, before the278// rest; each needs Vulkan 1.1, dynamic rendering and synchronization2, and279// a queue family that draws and computes.280fn choose(functions: &InstanceFunctions, instance: c_pointer) -> Option<ChosenDevice> {281 var count: [u32 : 1] = [0];282 functions.enumerate_physical_devices(instance, c_pointer::of(&count[..]), 0);283 var devices: [c_pointer : 16] = [0 : 16];284 count[0] = if (count[0] > 16) 16 else count[0];285 functions.enumerate_physical_devices(286 instance,287 c_pointer::of(&count[..]),288 c_pointer::of(&devices[..])289 );290 var best = Option<ChosenDevice>::None;291 var best_score: u32 = 0;292 for (devices[..count[0] to u64]) |physical| {293 var properties: [u8 : 1024] = [0 : 1024];294 functions.get_properties(physical, c_pointer::of(&properties[..]));295 const api = word(&properties, 0);296 if (api < API_VERSION_1_1) {297 continue;298 }299 const version = if (api >= API_VERSION_1_3) API_VERSION_1_3 else api;300 if (version < API_VERSION_1_3 && !(301 has_extension(&functions, physical, &"VK_KHR_dynamic_rendering") && has_extension(302 &functions,303 physical,304 &"VK_KHR_synchronization2"305 )306 )) {307 continue;308 }309 const family = if (graphics_family(&functions, physical) is ::Some |f|) f else {310 continue;311 };312 const score: u32 = match (word(&properties, 16)) {313 PHYSICAL_DEVICE_DISCRETE 3;314 PHYSICAL_DEVICE_INTEGRATED 2;315 else 1;316 };317 if (score > best_score) {318 best_score = score;319 best = ::Some(ChosenDevice {320 .physical = physical,321 .family = family,322 .version = version,323 .name = String::from(&c_string_in(&properties[20..276]))324 });325 }326 }327 return move best;328}329330// The first queue family that draws and computes.331fn graphics_family(functions: &InstanceFunctions, physical: c_pointer) -> Option<u32> {332 var count: [u32 : 1] = [0];333 functions.get_queue_families(physical, c_pointer::of(&count[..]), 0);334 count[0] = if (count[0] > 16) 16 else count[0];335 var families: [u8 : 384] = [0 : 384];336 functions.get_queue_families(physical, c_pointer::of(&count[..]), c_pointer::of(&families[..]));337 const both = QUEUE_GRAPHICS | QUEUE_COMPUTE;338 for ([..count[0] to u64]) |k| {339 if ((word(&families, k * 24) & both) == both) {340 return ::Some(k to u32);341 }342 }343 return ::None;344}345346fn has_extension(functions: &InstanceFunctions, physical: c_pointer, name: &[u8]) -> bool {347 var count: [u32 : 1] = [0];348 functions.enumerate_device_extensions(physical, 0, c_pointer::of(&count[..]), 0);349 var properties = Vector<u8>::filled(0, count[0] to u64 * EXTENSION_PROPERTIES);350 functions.enumerate_device_extensions(351 physical,352 0,353 c_pointer::of(&count[..]),354 c_pointer::of(&properties.view())355 );356 return names_extension(&properties.view(), count[0], &name);357}358359fn has_instance_extension(get: GetProcAddr, name: &[u8]) -> bool {360 const enumerate = if (361 find<extern (c_pointer, c_pointer, c_pointer) -> i32>(362 get,363 0,364 &"vkEnumerateInstanceExtensionProperties"365 ) is ::Some |e|366 ) e else {367 return false;368 };369 var count: [u32 : 1] = [0];370 enumerate(0, c_pointer::of(&count[..]), 0);371 var properties = Vector<u8>::filled(0, count[0] to u64 * EXTENSION_PROPERTIES);372 enumerate(0, c_pointer::of(&count[..]), c_pointer::of(&properties.view()));373 return names_extension(&properties.view(), count[0], &name);374}375376// The size of a VkExtensionProperties: its name, then its version.377const EXTENSION_PROPERTIES: u64 = 260;378379// Whether one of the extensions' properties names the extension.380fn names_extension(properties: &[u8], count: u32, name: &[u8]) -> bool {381 for ([..count to u64]) |k| {382 const at = k * EXTENSION_PROPERTIES;383 if (c_string_in(&properties[at..at + 256]) == name) {384 return true;385 }386 }387 return false;388}389390fn create_device(391 functions: &InstanceFunctions,392 chosen: &ChosenDevice,393 swapchain: bool394) -> Option<c_pointer> {395 const priority: [f32 : 1] = [1.0];396 const queue_info = DeviceQueueCreateInfo {397 .family = chosen.family,398 .count = 1,399 .priorities = c_pointer::of(&priority[..])400 };401 // Vulkan 1.3 has both features in its own structure; before, each has402 // its extension403 const features13 = Vulkan13Features {404 .synchronization2 = 1,405 .dynamic_rendering = 1406 };407 const synchronization2 = FeatureFlag {408 .kind = StructureType::PhysicalDeviceSynchronization2Features,409 .enabled = 1410 };411 const dynamic_rendering = FeatureFlag {412 .kind = StructureType::PhysicalDeviceDynamicRenderingFeatures,413 .next = c_pointer::from(&synchronization2),414 .enabled = 1415 };416 const dynamic_rendering_name = text(&"VK_KHR_dynamic_rendering");417 const synchronization2_name = text(&"VK_KHR_synchronization2");418 const swapchain_name = text(&"VK_KHR_swapchain");419 const modern = chosen.version >= API_VERSION_1_3;420 var extensions = Vector<c_pointer>::empty();421 if (!modern) {422 extensions.push(c_pointer::of(&dynamic_rendering_name.view()));423 extensions.push(c_pointer::of(&synchronization2_name.view()));424 }425 if (swapchain) {426 extensions.push(c_pointer::of(&swapchain_name.view()));427 }428 const info = DeviceCreateInfo {429 .next = if (modern) c_pointer::from(&features13) else c_pointer::from(&dynamic_rendering),430 .queue_info_count = 1,431 .queue_infos = c_pointer::from(&queue_info),432 .extension_count = extensions.length() to u32,433 .extensions = c_pointer::of(&extensions.view())434 };435 var device: [c_pointer : 1] = [0];436 if (functions.create_device(437 chosen.physical,438 c_pointer::from(&info),439 0,440 c_pointer::of(&device[..])441 ) != SUCCESS) {442 return ::None;443 }444 return ::Some(device[0]);445}446447/* --- Helpers --- */448449fn check(result: i32, what: &[u8]) {450 if (result != SUCCESS) {451 const message = f"pkg::alloy::gpu: {what} failed ({result})";452 panic message.view();453 }454}455456// The object a `vkCreate...` function makes from the info.457fn made(self v: &VulkanDevice, create: Create, info: c_pointer, what: &[u8]) -> u64 {458 var out: [u64 : 1] = [0];459 check(create(v.device, info, 0, c_pointer::of(&out[..])), &what);460 return out[0];461}462463fn text(value: &[u8]) -> String {464 var out = String::from(&value);465 out.push(0);466 return move out;467}468469fn word(bytes: &[u8], at: u64) -> u32 {470 return bytes[at] to u32 | (bytes[at + 1] to u32 << 8) | (471 bytes[at + 2] to u32 << 16472 ) | (bytes[at + 3] to u32 << 24);473}474475fn c_string_in(bytes: &[u8]) -> &[u8] {476 for ([..bytes.length()]) |k| {477 if (bytes[k] == 0) {478 return &bytes[..k];479 }480 }481 return &bytes;482}483484// Memory of a type the requirements allow with the properties, the485// first properties found among those given.486fn allocate(self v: &VulkanDevice, requirements: &MemoryRequirements, wanted: &[u32]) -> u64 {487 for (wanted) |properties| {488 for ([..v.memory_types.length()]) |k| {489 const allowed = ((requirements.memory_types >> k to u32) & 1) == 1;490 if (allowed && (v.memory_types.get(k) & properties) == properties) {491 const info = MemoryAllocateInfo {492 .size = requirements.size,493 .memory_type = k to u32494 };495 return v.made(v.f.allocate_memory, c_pointer::from(&info), &"vkAllocateMemory");496 }497 }498 }499 panic "pkg::alloy::gpu: no Vulkan memory for the resource";500}501502fn make_buffer(self v: &VulkanDevice, size: u64, usage: u32, wanted: &[u32]) -> VulkanBuffer {503 const info = BufferCreateInfo {504 .size = if (size < 4) 4 else size,505 .usage = usage506 };507 const buffer = v.made(v.f.create_buffer, c_pointer::from(&info), &"vkCreateBuffer");508 var requirements = MemoryRequirements { .size = 0, .alignment = 0, .memory_types = 0 };509 v.f.buffer_requirements(v.device, buffer, c_pointer::from(&requirements));510 const memory = v.allocate(&requirements, &wanted);511 check(v.f.bind_buffer_memory(v.device, buffer, memory, 0), &"vkBindBufferMemory");512 return VulkanBuffer { .buffer = buffer, .memory = memory, .size = size };513}514515fn map(self v: &VulkanDevice, buffer: &VulkanBuffer) -> c_pointer {516 var out: [c_pointer : 1] = [0];517 check(518 v.f.map_memory(v.device, buffer.memory, 0, buffer.size, 0, c_pointer::of(&out[..])),519 &"vkMapMemory"520 );521 return out[0];522}523524fn free(self v: &VulkanDevice, buffer: &VulkanBuffer) {525 if (buffer.buffer != 0) {526 v.f.destroy_buffer(v.device, buffer.buffer, 0);527 v.f.free_memory(v.device, buffer.memory, 0);528 }529}530531fn host_buffer(self v: &VulkanDevice, size: u64, usage: u32) -> VulkanBuffer {532 return v.make_buffer(size, usage, &[533 MEMORY_HOST_VISIBLE | MEMORY_HOST_COHERENT | MEMORY_HOST_CACHED,534 MEMORY_HOST_VISIBLE | MEMORY_HOST_COHERENT535 ]);536}537538/* --- Making objects --- */539540fn vulkan_format(format: TextureFormat) -> Format {541 return match (format) {542 ::Rgba8Unorm Format::R8G8B8A8Unorm;543 ::Bgra8Unorm Format::B8G8R8A8Unorm;544 ::R8Unorm Format::R8Unorm;545 };546}547548pub fn buffer(self v: &var VulkanDevice, size: u64, usage: u32) -> Buffer {549 var flags = BUFFER_USAGE_TRANSFER_SOURCE | BUFFER_USAGE_TRANSFER_DESTINATION;550 if ((usage & BUFFER_VERTEX) != 0) {551 flags |= BUFFER_USAGE_VERTEX;552 }553 if ((usage & BUFFER_INDEX) != 0) {554 flags |= BUFFER_USAGE_INDEX;555 }556 if ((usage & BUFFER_UNIFORM) != 0) {557 flags |= BUFFER_USAGE_UNIFORM;558 }559 if ((usage & BUFFER_STORAGE) != 0) {560 flags |= BUFFER_USAGE_STORAGE;561 }562 const made = v.make_buffer(size, flags, &[MEMORY_DEVICE_LOCAL, 0]);563 const index = v.released.place(::Buffer, &var v.buffers, made);564 return Buffer { .generation = 0, .index = index, .size = size };565}566567pub fn write_buffer(self v: &var VulkanDevice, buffer: Buffer, offset: u64, bytes: &[u8]) {568 v.staged.write_buffer(buffer.index, offset, &bytes);569}570571pub fn texture(self v: &var VulkanDevice, d: &TextureDescriptor) -> Texture {572 const format = vulkan_format(d.format);573 var usage = IMAGE_USAGE_TRANSFER_SOURCE | IMAGE_USAGE_TRANSFER_DESTINATION;574 if ((d.usage & TEXTURE_SAMPLED) != 0) {575 usage |= IMAGE_USAGE_SAMPLED;576 }577 if ((d.usage & TEXTURE_RENDER_TARGET) != 0) {578 usage |= IMAGE_USAGE_COLOR_ATTACHMENT;579 }580 const info = ImageCreateInfo {581 .image_type = ImageType::Type2D,582 .format = format,583 .extent = Extent3D { .width = d.width, .height = d.height, .depth = 1 },584 .mip_levels = 1,585 .array_layers = 1,586 .samples = SAMPLE_COUNT_1,587 .tiling = ImageTiling::Optimal,588 .usage = usage,589 .initial_layout = ImageLayout::Undefined590 };591 const image = v.made(v.f.create_image, c_pointer::from(&info), &"vkCreateImage");592 var requirements = MemoryRequirements { .size = 0, .alignment = 0, .memory_types = 0 };593 v.f.image_requirements(v.device, image, c_pointer::from(&requirements));594 const memory = v.allocate(&requirements, &[MEMORY_DEVICE_LOCAL, 0]);595 check(v.f.bind_image_memory(v.device, image, memory, 0), &"vkBindImageMemory");596 const view_info = ImageViewCreateInfo {597 .image = image,598 .view_type = ImageViewType::Type2D,599 .format = format,600 .components = [0 : 4],601 .range = SubresourceRange::color()602 };603 const view = v.made(v.f.create_image_view, c_pointer::from(&view_info), &"vkCreateImageView");604 const texture = VulkanTexture {605 .image = image,606 .memory = memory,607 .view = view,608 .width = d.width,609 .height = d.height,610 .rest = if (611 (d.usage & TEXTURE_SAMPLED) != 0612 ) ImageLayout::ShaderReadOnly else ImageLayout::General,613 .discard = false,614 .drawn = false615 };616 const index = v.released.place(::Texture, &var v.textures, texture);617 v.fresh.push(index);618 return Texture {619 .generation = 0,620 .index = index,621 .width = d.width,622 .height = d.height,623 .format = d.format624 };625}626627pub fn write_texture(628 self v: &var VulkanDevice,629 texture: Texture,630 x: u32,631 y: u32,632 width: u32,633 height: u32,634 bytes: &[u8]635) {636 const size = width to u64 * height to u64 * texture.format.bytes_per_pixel();637 v.staged.write_texture(638 texture.index,639 Region { .x = x, .y = y, .width = width, .height = height },640 size,641 &bytes642 );643}644645pub fn sampler(self v: &var VulkanDevice, d: &SamplerDescriptor) -> Sampler {646 const filter = if (d.linear) Filter::Linear else Filter::Nearest;647 const address = if (d.repeat) SamplerAddressMode::Repeat else SamplerAddressMode::ClampToEdge;648 const info = SamplerCreateInfo {649 .mag_filter = filter,650 .min_filter = filter,651 .address_u = address,652 .address_v = address,653 .address_w = address,654 .max_anisotropy = 1.0655 };656 const sampler = v.made(v.f.create_sampler, c_pointer::from(&info), &"vkCreateSampler");657 const index = v.released.place(::Sampler, &var v.samplers, sampler);658 return Sampler { .generation = 0, .index = index };659}660661fn descriptor_type(kind: ResourceKind) -> DescriptorType => match (kind) {662 ::Uniform DescriptorType::UniformBuffer;663 ::Storage, ::StorageRead DescriptorType::StorageBuffer;664 ::Texture DescriptorType::SampledImage;665 ::Sampler DescriptorType::Sampler;666};667668pub fn shader(self v: &var VulkanDevice, compiled: &[u8]) -> Shader {669 const decoded = if (decode(&compiled) is ::Some |move d|) move d else {670 panic "not a shader #shader compiled";671 };672 const module_info = ShaderModuleCreateInfo {673 .size = (decoded.spirv.length() * 4) to c_size,674 .code = c_pointer::of(&decoded.spirv.view())675 };676 const module = v.made(677 v.f.create_shader_module,678 c_pointer::from(&module_info),679 &"vkCreateShaderModule"680 );681 // a set layout for each group up to the last the shader binds682 var groups: u32 = 0;683 for (decoded.resources.view()) |&r| {684 groups = if (r.group + 1 > groups) r.group + 1 else groups;685 }686 var set_layouts = Vector<u64>::empty();687 for ([..groups]) |group| {688 var bindings = Vector<DescriptorSetLayoutBinding>::empty();689 for (decoded.resources.view()) |&r| {690 if (r.group == group) {691 bindings.push(DescriptorSetLayoutBinding {692 .binding = r.binding,693 .descriptor_type = descriptor_type(r.kind),694 .count = 1,695 .stages = SHADER_STAGE_VERTEX | SHADER_STAGE_FRAGMENT | SHADER_STAGE_COMPUTE696 });697 }698 }699 const info = DescriptorSetLayoutCreateInfo {700 .binding_count = bindings.length() to u32,701 .bindings = c_pointer::of(&bindings.view())702 };703 set_layouts.push(v.made(704 v.f.create_set_layout,705 c_pointer::from(&info),706 &"vkCreateDescriptorSetLayout"707 ));708 }709 const layout_info = PipelineLayoutCreateInfo {710 .set_layout_count = set_layouts.length() to u32,711 .set_layouts = c_pointer::of(&set_layouts.view())712 };713 const layout = v.made(714 v.f.create_pipeline_layout,715 c_pointer::from(&layout_info),716 &"vkCreatePipelineLayout"717 );718 v.shaders.push(VulkanShader {719 .module = module,720 .resources = copy decoded.resources,721 .set_layouts = move set_layouts,722 .layout = layout723 });724 return Shader { .generation = 0, .index = v.shaders.length() to u32 - 1 };725}726727fn vertex_format(format: VertexFormat) -> Format {728 return match (format) {729 ::Float32 Format::R32Sfloat;730 ::Float32x2 Format::R32G32Sfloat;731 ::Float32x3 Format::R32G32B32Sfloat;732 ::Float32x4 Format::R32G32B32A32Sfloat;733 ::Uint32 Format::R32Uint;734 ::Sint32 Format::R32Sint;735 ::Unorm8x4 Format::R8G8B8A8Unorm;736 };737}738739fn stage(kind: u32, module: u64, name: &String) -> PipelineShaderStageCreateInfo {740 return PipelineShaderStageCreateInfo {741 .stage = kind,742 .module = module,743 .name = c_pointer::of(&name.view())744 };745}746747pub fn render_pipeline(self v: &var VulkanDevice, d: &RenderPipelineDescriptor) -> RenderPipeline {748 const shader = &v.shaders.get(d.shader.index to u64);749 const vertex_name = text(&d.vertex.view());750 const fragment_name = text(&d.fragment.view());751 const stages: [PipelineShaderStageCreateInfo : 2] = [752 stage(SHADER_STAGE_VERTEX, shader.module, &vertex_name),753 stage(SHADER_STAGE_FRAGMENT, shader.module, &fragment_name)754 ];755 var bindings = Vector<VertexInputBinding>::empty();756 var attributes = Vector<VertexInputAttribute>::empty();757 for ([..d.buffers.length()]) |slot| {758 const layout = &d.buffers.get(slot);759 bindings.push(VertexInputBinding {760 .binding = slot to u32,761 .stride = layout.stride,762 .rate = if (layout.instanced) VertexInputRate::Instance else VertexInputRate::Vertex763 });764 for (layout.attributes.view()) |&a| {765 attributes.push(VertexInputAttribute {766 .location = a.location,767 .binding = slot to u32,768 .format = vertex_format(a.format),769 .offset = a.offset770 });771 }772 }773 const vertex_input = PipelineVertexInputStateCreateInfo {774 .binding_count = bindings.length() to u32,775 .bindings = c_pointer::of(&bindings.view()),776 .attribute_count = attributes.length() to u32,777 .attributes = c_pointer::of(&attributes.view())778 };779 const input_assembly = PipelineInputAssemblyStateCreateInfo { .kind = StructureType::PipelineInputAssemblyStateCreateInfo, .next = 0, .flags = 0, .topology = if (780 d.topology is ::TriangleStrip781 ) PrimitiveTopology::TriangleStrip else PrimitiveTopology::TriangleList, .primitive_restart = 0 };782 const viewport = PipelineViewportStateCreateInfo {783 .viewport_count = 1,784 .scissor_count = 1785 };786 const rasterization = PipelineRasterizationStateCreateInfo {787 .line_width = 1.0788 };789 const multisample = PipelineMultisampleStateCreateInfo {790 .samples = SAMPLE_COUNT_1791 };792 // the color by its alpha unless premultiplied, alpha by one793 const blending = !(d.blend is ::Replace);794 const attachment = ColorBlendAttachment {795 .enable = if (blending) 1 else 0,796 .source_color = if (797 d.blend is ::Premultiplied798 ) BlendFactor::One else BlendFactor::SourceAlpha,799 .destination_color = BlendFactor::OneMinusSourceAlpha,800 .color_op = 0,801 .source_alpha = BlendFactor::One,802 .destination_alpha = BlendFactor::OneMinusSourceAlpha,803 .alpha_op = 0,804 .write_mask = COLOR_COMPONENTS_ALL805 };806 const color_blend = PipelineColorBlendStateCreateInfo {807 .attachment_count = 1,808 .attachments = c_pointer::from(&attachment)809 };810 const dynamic_states: [DynamicState : 2] = [::Viewport, ::Scissor];811 const dynamic = PipelineDynamicStateCreateInfo {812 .count = 2,813 .states = c_pointer::of(&dynamic_states[..])814 };815 const formats: [Format : 1] = [vulkan_format(d.format)];816 const rendering = PipelineRenderingCreateInfo {817 .color_count = 1,818 .color_formats = c_pointer::of(&formats[..])819 };820 const info = GraphicsPipelineCreateInfo {821 .next = c_pointer::from(&rendering),822 .stage_count = 2,823 .stages = c_pointer::of(&stages[..]),824 .vertex_input = c_pointer::from(&vertex_input),825 .input_assembly = c_pointer::from(&input_assembly),826 .viewport = c_pointer::from(&viewport),827 .rasterization = c_pointer::from(&rasterization),828 .multisample = c_pointer::from(&multisample),829 .color_blend = c_pointer::from(&color_blend),830 .dynamic = c_pointer::from(&dynamic),831 .layout = shader.layout832 };833 var pipeline: [u64 : 1] = [0];834 check(835 v.f.create_graphics_pipelines(836 v.device,837 0,838 1,839 c_pointer::from(&info),840 0,841 c_pointer::of(&pipeline[..])842 ),843 &"vkCreateGraphicsPipelines"844 );845 const index = v.released.place(846 ::RenderPipeline,847 &var v.pipelines,848 VulkanPipeline { .pipeline = pipeline[0], .shader = d.shader.index }849 );850 return RenderPipeline { .generation = 0, .index = index };851}852853pub fn compute_pipeline(854 self v: &var VulkanDevice,855 shader: Shader,856 entry: &[u8]857) -> ComputePipeline {858 const s = &v.shaders.get(shader.index to u64);859 const name = text(&entry);860 const info = ComputePipelineCreateInfo {861 .stage = stage(SHADER_STAGE_COMPUTE, s.module, &name),862 .layout = s.layout863 };864 var pipeline: [u64 : 1] = [0];865 check(866 v.f.create_compute_pipelines(867 v.device,868 0,869 1,870 c_pointer::from(&info),871 0,872 c_pointer::of(&pipeline[..])873 ),874 &"vkCreateComputePipelines"875 );876 const index = v.released.place(877 ::ComputePipeline,878 &var v.computes,879 VulkanPipeline { .pipeline = pipeline[0], .shader = shader.index }880 );881 return ComputePipeline { .generation = 0, .index = index };882}883884pub fn render_bind_group(885 self v: &var VulkanDevice,886 pipeline: RenderPipeline,887 group: u32,888 bindings: &[Binding]889) -> BindGroup {890 return v.bind_group(v.pipelines.get(pipeline.index to u64).shader, group, &bindings);891}892893pub fn compute_bind_group(894 self v: &var VulkanDevice,895 pipeline: ComputePipeline,896 group: u32,897 bindings: &[Binding]898) -> BindGroup {899 return v.bind_group(v.computes.get(pipeline.index to u64).shader, group, &bindings);900}901902// A descriptor set from the pool, a new pool when it is full.903fn allocate_set(self v: &var VulkanDevice, layout: u64) -> VulkanGroup {904 for ([..2]) {905 if (v.pool != 0) {906 const layouts: [u64 : 1] = [layout];907 const info = DescriptorSetAllocateInfo {908 .pool = v.pool,909 .count = 1,910 .layouts = c_pointer::of(&layouts[..])911 };912 var set: [u64 : 1] = [0];913 const result = v.f.allocate_sets(914 v.device,915 c_pointer::from(&info),916 c_pointer::of(&set[..])917 );918 match (result) {919 SUCCESS {920 return VulkanGroup { .set = set[0], .pool = v.pool };921 }922 ERROR_OUT_OF_POOL_MEMORY, ERROR_FRAGMENTED_POOL {}923 else {924 check(result, &"vkAllocateDescriptorSets");925 }926 }927 }928 const sizes: [DescriptorPoolSize : 4] = [929 DescriptorPoolSize { .descriptor_type = DescriptorType::Sampler, .count = 256 },930 DescriptorPoolSize { .descriptor_type = DescriptorType::SampledImage, .count = 256 },931 DescriptorPoolSize { .descriptor_type = DescriptorType::UniformBuffer, .count = 256 },932 DescriptorPoolSize { .descriptor_type = DescriptorType::StorageBuffer, .count = 256 }933 ];934 const pool_info = DescriptorPoolCreateInfo {935 .flags = DESCRIPTOR_POOL_FREE_SET,936 .max_sets = 256,937 .size_count = 4,938 .sizes = c_pointer::of(&sizes[..])939 };940 v.pool = v.made(941 v.f.create_descriptor_pool,942 c_pointer::from(&pool_info),943 &"vkCreateDescriptorPool"944 );945 }946 panic "pkg::alloy::gpu: a descriptor set does not fit a new pool";947}948949fn bind_group(950 self v: &var VulkanDevice,951 shader: u32,952 group: u32,953 bindings: &[Binding]954) -> BindGroup {955 const s = &v.shaders.get(shader to u64);956 if (group to u64 >= s.set_layouts.length()) {957 panic "pkg::alloy::gpu: the shader binds nothing in that group";958 }959 const allocated = v.allocate_set(s.set_layouts.get(group to u64));960 const set = allocated.set;961 // the infos first, which the writes then point at962 var buffer_infos = Vector<DescriptorBufferInfo>::empty();963 var image_infos = Vector<DescriptorImageInfo>::empty();964 for (bindings) |&b| {965 match (b.resource) {966 ::Buffer |buffer| {967 buffer_infos.push(DescriptorBufferInfo {968 .buffer = v.buffers.get(buffer.index to u64).buffer,969 .offset = 0,970 .range = buffer.size971 });972 }973 ::BufferRange |range| {974 buffer_infos.push(DescriptorBufferInfo {975 .buffer = v.buffers.get(range.buffer.index to u64).buffer,976 .offset = range.offset,977 .range = range.size978 });979 }980 ::Texture |texture| {981 image_infos.push(DescriptorImageInfo {982 .sampler = 0,983 .view = v.textures.get(texture.index to u64).view,984 .layout = ImageLayout::ShaderReadOnly985 });986 }987 ::Sampler |sampler| {988 image_infos.push(DescriptorImageInfo {989 .sampler = v.samplers.get(sampler.index to u64),990 .view = 0,991 .layout = ImageLayout::Undefined992 });993 }994 }995 }996 var writes = Vector<WriteDescriptorSet>::empty();997 var next_buffer: u64 = 0;998 var next_image: u64 = 0;999 for (bindings) |&b| {1000 var kind = DescriptorType::StorageBuffer;1001 for (s.resources.view()) |&r| {1002 if (r.group == group && r.binding == b.binding) {1003 kind = descriptor_type(r.kind);1004 }1005 }1006 const is_buffer = b.resource is ::Buffer || b.resource is ::BufferRange;1007 writes.push(WriteDescriptorSet {1008 .set = set,1009 .binding = b.binding,1010 .count = 1,1011 .descriptor_type = kind,1012 .image_info = if (is_buffer) 0 else c_pointer::of(&image_infos.view()[next_image..]),1013 .buffer_info = if (is_buffer) c_pointer::of(&buffer_infos.view()[next_buffer..]) else 01014 });1015 if (is_buffer) {1016 next_buffer += 1;1017 } else {1018 next_image += 1;1019 }1020 }1021 v.f.update_sets(v.device, writes.length() to u32, c_pointer::of(&writes.view()), 0, 0);1022 const index = v.released.place(::BindGroup, &var v.groups, allocated);1023 return BindGroup { .generation = 0, .index = index, .group = group };1024}10251026/* --- Running commands --- */10271028fn image_barrier(1029 self v: &VulkanDevice,1030 commands: c_pointer,1031 image: u64,1032 old: ImageLayout,1033 new_layout: ImageLayout1034) {1035 const barrier = ImageMemoryBarrier2 {1036 .source_stages = STAGE_2_ALL_COMMANDS,1037 .source_access = ACCESS_2_MEMORY_READ | ACCESS_2_MEMORY_WRITE,1038 .destination_stages = STAGE_2_ALL_COMMANDS,1039 .destination_access = ACCESS_2_MEMORY_READ | ACCESS_2_MEMORY_WRITE,1040 .old_layout = old,1041 .new_layout = new_layout,1042 .source_family = QUEUE_FAMILY_IGNORED,1043 .destination_family = QUEUE_FAMILY_IGNORED,1044 .image = image,1045 .range = SubresourceRange::color()1046 };1047 const dependency = DependencyInfo {1048 .image_count = 1,1049 .images = c_pointer::from(&barrier)1050 };1051 v.f.pipeline_barrier(commands, c_pointer::from(&dependency));1052}10531054// Everything before done before anything after starts, its writes seen;1055// by the host too, for reads.1056fn memory_barrier(self v: &VulkanDevice, commands: c_pointer) {1057 const barrier = MemoryBarrier2 {1058 .source_stages = STAGE_2_ALL_COMMANDS,1059 .source_access = ACCESS_2_MEMORY_READ | ACCESS_2_MEMORY_WRITE,1060 .destination_stages = STAGE_2_ALL_COMMANDS | STAGE_2_HOST,1061 .destination_access = ACCESS_2_MEMORY_READ | ACCESS_2_MEMORY_WRITE | ACCESS_2_HOST_READ1062 };1063 const dependency = DependencyInfo {1064 .memory_count = 1,1065 .memory = c_pointer::from(&barrier)1066 };1067 v.f.pipeline_barrier(commands, c_pointer::from(&dependency));1068}10691070fn wait(self v: &var VulkanDevice, slot: u64) {1071 if (v.slots[slot].busy) {1072 const fences: [u64 : 1] = [v.slots[slot].fence];1073 check(1074 v.f.wait_for_fences(v.device, 1, c_pointer::of(&fences[..]), 1, 0xFFFFFFFFFFFFFFFF),1075 &"vkWaitForFences"1076 );1077 check(v.f.reset_fences(v.device, 1, c_pointer::of(&fences[..])), &"vkResetFences");1078 v.slots[slot].busy = false;1079 const waited = v.slots[slot].waited;1080 if (waited != 0) {1081 v.semaphores.push(waited);1082 v.slots[slot].waited = 0;1083 }1084 }1085}10861087// Starts recording into the next slot's command buffer, the writes1088// waiting copied in first.1089fn begin(self v: &var VulkanDevice) -> u64 {1090 const slot = v.next_slot;1091 v.next_slot = (slot + 1) % SLOTS;1092 v.wait(slot);1093 v.collect();1094 const commands = v.slots[slot].commands;1095 const begin_info = CommandBufferBeginInfo {1096 .flags = COMMAND_BUFFER_ONE_TIME_SUBMIT1097 };1098 check(1099 v.f.begin_command_buffer(commands, c_pointer::from(&begin_info)),1100 &"vkBeginCommandBuffer"1101 );1102 for (v.fresh.view()) |index| {1103 const t = &v.textures.get(index to u64);1104 v.image_barrier(commands, t.image, ImageLayout::Undefined, t.rest);1105 }1106 v.fresh.clear();1107 const size = v.staged.bytes.length();1108 if (size == 0) {1109 return slot;1110 }1111 if (v.slots[slot].staging.size < size) {1112 v.free(&v.slots[slot].staging);1113 const staging = v.host_buffer(1114 if (size < 65536) 65536 else size,1115 BUFFER_USAGE_TRANSFER_SOURCE1116 );1117 v.slots[slot].mapped = v.map(&staging);1118 v.slots[slot].staging = staging;1119 }1120 const s = &v.slots[slot];1121 var target = &var s.mapped.view_var<u8>(size);1122 target[..] = v.staged.bytes.view();1123 // a texture taking copies in a row is moved to the transfer layout1124 // and back once, not once a copy (a glyph's)1125 var open = Option<u32>::None;1126 for (v.staged.uploads.view()) |&u| {1127 if (open is ::Some |texture| && !u.writes(::Texture, texture)) {1128 const was = &v.textures.get(texture to u64);1129 v.image_barrier(commands, was.image, ImageLayout::TransferDestination, was.rest);1130 open = ::None;1131 }1132 match (u.destination) {1133 ::Texture |into| {1134 const t = &v.textures.get(into.index to u64);1135 if (open is ::None) {1136 v.image_barrier(commands, t.image, t.rest, ImageLayout::TransferDestination);1137 open = ::Some(into.index);1138 }1139 const region = BufferImageCopy {1140 .buffer_offset = u.at,1141 .row_length = 0,1142 .image_height = 0,1143 .subresource = SubresourceLayers::color(),1144 .offset = Offset3D {1145 .x = into.region.x to i32,1146 .y = into.region.y to i32,1147 .z = 01148 },1149 .extent = Extent3D {1150 .width = into.region.width,1151 .height = into.region.height,1152 .depth = 11153 }1154 };1155 v.f.copy_buffer_to_image(1156 commands,1157 s.staging.buffer,1158 t.image,1159 ImageLayout::TransferDestination,1160 1,1161 c_pointer::from(®ion)1162 );1163 }1164 ::Buffer |into| {1165 const region = BufferCopy {1166 .source_offset = u.at,1167 .destination_offset = into.offset,1168 .size = u.size1169 };1170 v.f.copy_buffer(1171 commands,1172 s.staging.buffer,1173 v.buffers.get(into.index to u64).buffer,1174 1,1175 c_pointer::from(®ion)1176 );1177 }1178 }1179 }1180 if (open is ::Some |texture|) {1181 const was = &v.textures.get(texture to u64);1182 v.image_barrier(commands, was.image, ImageLayout::TransferDestination, was.rest);1183 }1184 v.memory_barrier(commands);1185 v.staged.clear();1186 return slot;1187}11881189// Submits the slot's commands, after the image acquired is ready when1190// one is, signalling the semaphore when one is given.1191fn end(self v: &var VulkanDevice, slot: u64, signal: u64) {1192 const s = &v.slots[slot];1193 check(v.f.end_command_buffer(s.commands), &"vkEndCommandBuffer");1194 const buffers: [c_pointer : 1] = [s.commands];1195 const waits: [u64 : 1] = [v.acquired];1196 const stages: [u32 : 1] = [STAGE_ALL_COMMANDS];1197 const signals: [u64 : 1] = [signal];1198 const info = SubmitInfo {1199 .wait_count = if (v.acquired != 0) 1 else 0,1200 .waits = c_pointer::of(&waits[..]),1201 .wait_stages = c_pointer::of(&stages[..]),1202 .buffer_count = 1,1203 .buffers = c_pointer::of(&buffers[..]),1204 .signal_count = if (signal != 0) 1 else 0,1205 .signals = c_pointer::of(&signals[..])1206 };1207 check(v.f.queue_submit(v.queue, 1, c_pointer::from(&info), s.fence), &"vkQueueSubmit");1208 v.serial += 1;1209 v.slots[slot].busy = true;1210 v.slots[slot].serial = v.serial;1211 v.slots[slot].waited = v.acquired;1212 v.acquired = 0;1213}12141215fn bind_groups(1216 self v: &VulkanDevice,1217 commands: c_pointer,1218 point: PipelineBindPoint,1219 shader: u32,1220 groups: &Vector<Option<u32>>1221) {1222 const layouts = v.shaders.get(shader to u64).set_layouts.length();1223 for (groups.view(), [..groups.length()]) |set, group| {1224 if (set is ::Some |index| && group < layouts) {1225 const sets: [u64 : 1] = [v.groups.get(index to u64).set];1226 v.f.bind_sets(1227 commands,1228 point,1229 v.shaders.get(shader to u64).layout,1230 group to u32,1231 1,1232 c_pointer::of(&sets[..]),1233 0,1234 01235 );1236 }1237 }1238}12391240pub fn submit(self v: &var VulkanDevice, encoder: &Encoder) {1241 const slot = v.begin();1242 const commands = v.slots[slot].commands;1243 var target: u32 = 0; // the pass's texture1244 var pipeline = Option<u32>::None;1245 var compute = Option<u32>::None;1246 var groups = Vector<Option<u32>>::empty();1247 for (encoder.commands.view()) |&command| {1248 match (command) {1249 ::BeginRenderPass |&pass| {1250 target = pass.target.index;1251 const t = &v.textures.get(target to u64);1252 const old = if (t.discard && !t.drawn) ImageLayout::Undefined else t.rest;1253 v.image_barrier(commands, t.image, old, ImageLayout::ColorAttachment);1254 var clear: [f32 : 4] = [0.0 : 4];1255 if (pass.clear is ::Some |color|) {1256 clear = [color.r, color.g, color.b, color.a];1257 }1258 const attachment = RenderingAttachmentInfo {1259 .view = t.view,1260 .layout = ImageLayout::ColorAttachment,1261 .load = if (1262 pass.clear is ::Some1263 ) AttachmentLoadOp::Clear else AttachmentLoadOp::Load,1264 .store = AttachmentStoreOp::Store,1265 .clear = clear1266 };1267 const area = Rect2D {1268 .offset = Offset2D { .x = 0, .y = 0 },1269 .extent = Extent2D { .width = t.width, .height = t.height }1270 };1271 const rendering = RenderingInfo {1272 .area = area,1273 .layer_count = 1,1274 .color_count = 1,1275 .colors = c_pointer::from(&attachment)1276 };1277 v.f.begin_rendering(commands, c_pointer::from(&rendering));1278 const viewport = Viewport {1279 .x = 0.0,1280 .y = t.height to f32,1281 .width = t.width to f32,1282 .height = -(t.height to f32),1283 .min_depth = 0.0,1284 .max_depth = 1.01285 };1286 v.f.set_viewport(commands, 0, 1, c_pointer::from(&viewport));1287 v.f.set_scissor(commands, 0, 1, c_pointer::from(&area));1288 }1289 ::EndRenderPass {1290 v.f.end_rendering(commands);1291 const t = &v.textures.get(target to u64);1292 v.image_barrier(commands, t.image, ImageLayout::ColorAttachment, t.rest);1293 v.textures.get_var(target to u64).drawn = true;1294 }1295 ::SetPipeline |p| {1296 pipeline = ::Some(p.index);1297 v.f.bind_pipeline(1298 commands,1299 PipelineBindPoint::Graphics,1300 v.pipelines.get(p.index to u64).pipeline1301 );1302 }1303 ::SetComputePipeline |p| {1304 compute = ::Some(p.index);1305 v.f.bind_pipeline(1306 commands,1307 PipelineBindPoint::Compute,1308 v.computes.get(p.index to u64).pipeline1309 );1310 }1311 ::SetBindGroup |group| {1312 while (groups.length() <= group.group to u64) {1313 groups.push(::None);1314 }1315 groups.get_var(group.group to u64) = ::Some(group.index);1316 }1317 ::SetVertexBuffer |&b| {1318 const buffers: [u64 : 1] = [v.buffers.get(b.buffer.index to u64).buffer];1319 const offsets: [u64 : 1] = [b.offset];1320 v.f.bind_vertex_buffers(1321 commands,1322 b.slot,1323 1,1324 c_pointer::of(&buffers[..]),1325 c_pointer::of(&offsets[..])1326 );1327 }1328 ::SetIndexBuffer |&i| {1329 v.f.bind_index_buffer(1330 commands,1331 v.buffers.get(i.buffer.index to u64).buffer,1332 i.offset,1333 if (i.wide) IndexType::Uint32 else IndexType::Uint161334 );1335 }1336 ::SetScissor |s| {1337 const rect = Rect2D {1338 .offset = Offset2D { .x = s.x to i32, .y = s.y to i32 },1339 .extent = Extent2D { .width = s.width, .height = s.height }1340 };1341 v.f.set_scissor(commands, 0, 1, c_pointer::from(&rect));1342 }1343 ::Draw |&d| {1344 if (pipeline is ::Some |p|) {1345 v.bind_groups(1346 commands,1347 PipelineBindPoint::Graphics,1348 v.pipelines.get(p to u64).shader,1349 &groups1350 );1351 v.f.draw(commands, d.count, d.instances, d.first, d.first_instance);1352 }1353 }1354 ::DrawIndexed |&d| {1355 if (pipeline is ::Some |p|) {1356 v.bind_groups(1357 commands,1358 PipelineBindPoint::Graphics,1359 v.pipelines.get(p to u64).shader,1360 &groups1361 );1362 v.f.draw_indexed(1363 commands,1364 d.count,1365 d.instances,1366 d.first,1367 d.base_vertex,1368 d.first_instance1369 );1370 }1371 }1372 ::Dispatch |size| {1373 if (compute is ::Some |p|) {1374 v.bind_groups(1375 commands,1376 PipelineBindPoint::Compute,1377 v.computes.get(p to u64).shader,1378 &groups1379 );1380 v.f.dispatch(commands, size[0], size[1], size[2]);1381 v.memory_barrier(commands);1382 }1383 }1384 ::CopyBuffer |&c| {1385 const region = BufferCopy {1386 .source_offset = c.source_offset,1387 .destination_offset = c.destination_offset,1388 .size = c.size1389 };1390 v.f.copy_buffer(1391 commands,1392 v.buffers.get(c.source.index to u64).buffer,1393 v.buffers.get(c.destination.index to u64).buffer,1394 1,1395 c_pointer::from(®ion)1396 );1397 v.memory_barrier(commands);1398 }1399 ::CopyTexture |&c| {1400 const s = &v.textures.get(c.source.index to u64);1401 const d = &v.textures.get(c.destination.index to u64);1402 const old = if (d.discard && !d.drawn) ImageLayout::Undefined else d.rest;1403 v.image_barrier(commands, s.image, s.rest, ImageLayout::TransferSource);1404 v.image_barrier(commands, d.image, old, ImageLayout::TransferDestination);1405 const region = ImageCopy {1406 .source_subresource = SubresourceLayers::color(),1407 .source_offset = Offset3D { .x = 0, .y = 0, .z = 0 },1408 .destination_subresource = SubresourceLayers::color(),1409 .destination_offset = Offset3D { .x = 0, .y = 0, .z = 0 },1410 .extent = Extent3D { .width = s.width, .height = s.height, .depth = 1 }1411 };1412 v.f.copy_image(1413 commands,1414 s.image,1415 ImageLayout::TransferSource,1416 d.image,1417 ImageLayout::TransferDestination,1418 1,1419 c_pointer::from(®ion)1420 );1421 v.image_barrier(commands, s.image, ImageLayout::TransferSource, s.rest);1422 v.image_barrier(commands, d.image, ImageLayout::TransferDestination, d.rest);1423 v.textures.get_var(c.destination.index to u64).drawn = true;1424 }1425 }1426 }1427 v.end(slot, 0);1428}14291430// Waits for every submission.1431fn finish(self v: &var VulkanDevice) {1432 for ([..SLOTS]) |slot| {1433 v.wait(slot);1434 }1435 v.collect();1436}14371438// The readback buffer, at least that large, its contents to come.1439fn readback_of(self v: &var VulkanDevice, size: u64) -> u64 {1440 if (v.readback.size < size) {1441 v.free(&v.readback);1442 v.readback = v.host_buffer(size, BUFFER_USAGE_TRANSFER_DESTINATION);1443 v.readback_mapped = v.map(&v.readback);1444 }1445 return v.readback.buffer;1446}14471448pub fn read_texture(self v: &var VulkanDevice, texture: Texture) -> Vector<u8> {1449 const size = texture.width to u64 * texture.height to u64 * texture.format.bytes_per_pixel();1450 v.finish();1451 const readback = v.readback_of(size);1452 const slot = v.begin();1453 const commands = v.slots[slot].commands;1454 const t = &v.textures.get(texture.index to u64);1455 v.image_barrier(commands, t.image, t.rest, ImageLayout::TransferSource);1456 const region = BufferImageCopy {1457 .buffer_offset = 0,1458 .row_length = 0,1459 .image_height = 0,1460 .subresource = SubresourceLayers::color(),1461 .offset = Offset3D { .x = 0, .y = 0, .z = 0 },1462 .extent = Extent3D { .width = t.width, .height = t.height, .depth = 1 }1463 };1464 v.f.copy_image_to_buffer(1465 commands,1466 t.image,1467 ImageLayout::TransferSource,1468 readback,1469 1,1470 c_pointer::from(®ion)1471 );1472 v.image_barrier(commands, t.image, ImageLayout::TransferSource, t.rest);1473 v.memory_barrier(commands);1474 v.end(slot, 0);1475 v.finish();1476 return Vector<u8>::from(&v.readback_mapped.view<u8>(size));1477}14781479pub fn read_buffer(self v: &var VulkanDevice, buffer: Buffer) -> Vector<u8> {1480 v.finish();1481 const readback = v.readback_of(buffer.size);1482 const slot = v.begin();1483 const commands = v.slots[slot].commands;1484 const region = BufferCopy { .source_offset = 0, .destination_offset = 0, .size = buffer.size };1485 v.f.copy_buffer(1486 commands,1487 v.buffers.get(buffer.index to u64).buffer,1488 readback,1489 1,1490 c_pointer::from(®ion)1491 );1492 v.memory_barrier(commands);1493 v.end(slot, 0);1494 v.finish();1495 return Vector<u8>::from(&v.readback_mapped.view<u8>(buffer.size));1496}14971498/* --- Surfaces --- */14991500pub fn surface(self v: &var VulkanDevice, window: &Window) -> Result<u32> {1501 const f = if (v.surface_functions is ::Some |&f|) f else {1502 return ::Error(String::from(&"the Vulkan implementation has no surfaces here"));1503 };1504 var surface: [u64 : 1] = [0];1505 var result = SUCCESS;1506 match (window.target()) {1507 ::Wayland |t| {1508 const info = WaylandSurfaceCreateInfo {1509 .display = t.display,1510 .surface = t.surface1511 };1512 result = f.create_surface(1513 v.instance,1514 c_pointer::from(&info),1515 0,1516 c_pointer::of(&surface[..])1517 );1518 }1519 ::Win32 |t| {1520 const info = Win32SurfaceCreateInfo {1521 .instance = t.instance,1522 .hwnd = t.window1523 };1524 result = f.create_surface(1525 v.instance,1526 c_pointer::from(&info),1527 0,1528 c_pointer::of(&surface[..])1529 );1530 }1531 else {1532 return ::Error(String::from(&"the window has no surface for the GPU"));1533 }1534 }1535 if (result != SUCCESS) {1536 return ::Error(f"the surface cannot be made ({result})");1537 }1538 var supported: [u32 : 1] = [0];1539 f.surface_support(v.physical, v.family, surface[0], c_pointer::of(&supported[..]));1540 if (supported[0] == 0) {1541 f.destroy_surface(v.instance, surface[0], 0);1542 return ::Error(String::from(&"the GPU cannot present to the window"));1543 }1544 // 8-bit BGRA or RGBA, unconverted, as the CPU device draws1545 var count: [u32 : 1] = [0];1546 f.surface_formats(v.physical, surface[0], c_pointer::of(&count[..]), 0);1547 var formats = Vector<SurfaceFormat>::filled(1548 SurfaceFormat { .format = 0, .color_space = 0 },1549 count[0] to u641550 );1551 f.surface_formats(1552 v.physical,1553 surface[0],1554 c_pointer::of(&count[..]),1555 c_pointer::of(&formats.view())1556 );1557 var chosen: Option<Format> = ::None;1558 for ([Format::B8G8R8A8Unorm, Format::R8G8B8A8Unorm]) |wanted| {1559 for (formats.view()) |&offered| {1560 if (1561 chosen is ::None1562 && offered.format == wanted to u321563 && offered.color_space == ColorSpace::SrgbNonlinear to u321564 ) {1565 chosen = ::Some(wanted);1566 }1567 }1568 }1569 const format = if (chosen is ::Some |found|) found else {1570 f.destroy_surface(v.instance, surface[0], 0);1571 return ::Error(String::from(&"the window takes no 8-bit RGBA or BGRA format"));1572 };1573 const index = v.released.place(::Surface, &var v.surfaces, VulkanSurface {1574 .surface = surface[0],1575 .format = format1576 });1577 return ::Ok(index);1578}15791580pub fn surface_format(self v: &VulkanDevice, surface: u32) -> TextureFormat {1581 return if (1582 v.surfaces.get(surface to u64).format == Format::B8G8R8A8Unorm1583 ) TextureFormat::Bgra8Unorm else TextureFormat::Rgba8Unorm;1584}15851586fn semaphore(self v: &var VulkanDevice) -> u64 {1587 if (v.semaphores.pop() is ::Some |s|) {1588 return s;1589 }1590 const f = if (v.surface_functions is ::Some |&f|) f else {1591 panic "no surfaces";1592 };1593 const info = SemaphoreCreateInfo {};1594 return v.made(f.create_semaphore, c_pointer::from(&info), &"vkCreateSemaphore");1595}15961597// Makes the surface's swap chain, of the size unless the surface decides,1598// replacing the one there; false when the window has no area.1599fn rebuild(self v: &var VulkanDevice, index: u32, width: u32, height: u32) -> bool {1600 const f = if (v.surface_functions is ::Some |&f|) f else {1601 return false;1602 };1603 const s = &v.surfaces.get(index to u64);1604 var capabilities = SurfaceCapabilities {1605 .min_images = 0,1606 .max_images = 0,1607 .current_extent = Extent2D { .width = 0, .height = 0 },1608 .min_extent = Extent2D { .width = 0, .height = 0 },1609 .max_extent = Extent2D { .width = 0, .height = 0 },1610 .max_layers = 0,1611 .supported_transforms = 0,1612 .current_transform = 0,1613 .supported_alpha = 0,1614 .supported_usage = 01615 };1616 check(1617 f.surface_capabilities(v.physical, s.surface, c_pointer::from(&capabilities)),1618 &"vkGetPhysicalDeviceSurfaceCapabilitiesKHR"1619 );1620 var extent = capabilities.current_extent;1621 if (extent.width == EXTENT_OF_SWAPCHAIN) {1622 extent = Extent2D {1623 .width = clamp(width, capabilities.min_extent.width, capabilities.max_extent.width),1624 .height = clamp(height, capabilities.min_extent.height, capabilities.max_extent.height)1625 };1626 }1627 if (extent.width == 0 || extent.height == 0) {1628 return false;1629 }1630 var images = capabilities.min_images + 1;1631 if (capabilities.max_images != 0 && images > capabilities.max_images) {1632 images = capabilities.max_images;1633 }1634 var alpha = COMPOSITE_ALPHA_OPAQUE;1635 if ((capabilities.supported_alpha & COMPOSITE_ALPHA_OPAQUE) == 0) {1636 alpha = capabilities.supported_alpha & (~capabilities.supported_alpha + 1);1637 }1638 var usage = IMAGE_USAGE_COLOR_ATTACHMENT;1639 if ((capabilities.supported_usage & IMAGE_USAGE_TRANSFER_SOURCE) != 0) {1640 usage |= IMAGE_USAGE_TRANSFER_SOURCE;1641 }1642 if ((capabilities.supported_usage & IMAGE_USAGE_TRANSFER_DESTINATION) != 0) {1643 usage |= IMAGE_USAGE_TRANSFER_DESTINATION;1644 }1645 const old = s.swapchain;1646 const info = SwapchainCreateInfo {1647 .surface = s.surface,1648 .min_images = images,1649 .format = s.format,1650 .color_space = ColorSpace::SrgbNonlinear,1651 .extent = extent,1652 .array_layers = 1,1653 .usage = usage,1654 .transform = capabilities.current_transform,1655 .composite_alpha = alpha,1656 .present_mode = PresentMode::Fifo,1657 .clipped = 1,1658 .old_swapchain = old1659 };1660 // nothing may still use the old swap chain's images1661 v.finish();1662 check(v.f.wait_idle(v.device), &"vkDeviceWaitIdle");1663 const swapchain = v.made(f.create_swapchain, c_pointer::from(&info), &"vkCreateSwapchainKHR");1664 for (s.views.view()) |view| {1665 v.f.destroy_image_view(v.device, view, 0);1666 }1667 if (old != 0) {1668 f.destroy_swapchain(v.device, old, 0);1669 }1670 var count: [u32 : 1] = [0];1671 f.swapchain_images(v.device, swapchain, c_pointer::of(&count[..]), 0);1672 var handles = Vector<u64>::filled(0, count[0] to u64);1673 check(1674 f.swapchain_images(1675 v.device,1676 swapchain,1677 c_pointer::of(&count[..]),1678 c_pointer::of(&handles.view())1679 ),1680 &"vkGetSwapchainImagesKHR"1681 );1682 var views = Vector<u64>::empty();1683 var textures = copy s.images;1684 var finished = copy s.finished;1685 for (handles.view(), [..handles.length()]) |image, k| {1686 const view_info = ImageViewCreateInfo {1687 .image = image,1688 .view_type = ImageViewType::Type2D,1689 .format = s.format,1690 .components = [0 : 4],1691 .range = SubresourceRange::color()1692 };1693 const view = v.made(1694 v.f.create_image_view,1695 c_pointer::from(&view_info),1696 &"vkCreateImageView"1697 );1698 views.push(view);1699 const texture = VulkanTexture {1700 .image = image,1701 .memory = 0,1702 .view = view,1703 .width = extent.width,1704 .height = extent.height,1705 .rest = ImageLayout::PresentSource,1706 .discard = true,1707 .drawn = false1708 };1709 if (k < textures.length()) {1710 v.textures.get_var(textures.get(k) to u64) = texture;1711 } else {1712 v.textures.push(texture);1713 textures.push(v.textures.length() to u32 - 1);1714 }1715 if (k >= finished.length()) {1716 finished.push(v.semaphore());1717 }1718 }1719 var target = &var v.surfaces.get_var(index to u64);1720 target.swapchain = swapchain;1721 target.width = extent.width;1722 target.asked = [width, height];1723 target.height = extent.height;1724 target.images = move textures;1725 target.views = move views;1726 target.finished = move finished;1727 target.stale = false;1728 return true;1729}17301731fn clamp(value: u32, low: u32, high: u32) -> u32 {1732 return if (value < low) low else if (value > high) high else value;1733}17341735// The texture to draw the surface's next frame into, the size given;1736// None when the window has no area.1737pub fn acquire(self v: &var VulkanDevice, index: u32, width: u32, height: u32) -> Option<Texture> {1738 const f = if (v.surface_functions is ::Some |&f|) f else {1739 return ::None;1740 };1741 // acquired again before presenting: the image still held, whose1742 // semaphore is still to be waited on1743 const held = &v.surfaces.get(index to u64);1744 if (held.current is ::Some |image| && held.asked[0] == width && held.asked[1] == height) {1745 return ::Some(Texture {1746 .generation = 0,1747 .index = held.images.get(image to u64),1748 .width = held.width,1749 .height = held.height,1750 .format = v.surface_format(index)1751 });1752 }1753 for ([..2]) {1754 const s = &v.surfaces.get(index to u64);1755 if (s.swapchain == 0 || s.stale || s.asked[0] != width || s.asked[1] != height) {1756 if (!v.rebuild(index, width, height)) {1757 return ::None;1758 }1759 }1760 const semaphore = v.semaphore();1761 var image: [u32 : 1] = [0];1762 const result = f.acquire_next_image(1763 v.device,1764 v.surfaces.get(index to u64).swapchain,1765 0xFFFFFFFFFFFFFFFF,1766 semaphore,1767 0,1768 c_pointer::of(&image[..])1769 );1770 match (result) {1771 SUCCESS, SUBOPTIMAL {}1772 ERROR_OUT_OF_DATE {1773 v.semaphores.push(semaphore);1774 v.surfaces.get_var(index to u64).stale = true;1775 continue;1776 }1777 else {1778 check(result, &"vkAcquireNextImageKHR");1779 }1780 }1781 var s2 = &var v.surfaces.get_var(index to u64);1782 s2.stale = result == SUBOPTIMAL;1783 s2.current = ::Some(image[0]);1784 const texture = s2.images.get(image[0] to u64);1785 if (v.acquired != 0) {1786 // an image acquired and never presented1787 v.semaphores.push(v.acquired);1788 }1789 v.acquired = semaphore;1790 v.textures.get_var(texture to u64).drawn = false;1791 return ::Some(Texture {1792 .generation = 0,1793 .index = texture,1794 .width = s2.width,1795 .height = s2.height,1796 .format = v.surface_format(index)1797 });1798 }1799 return ::None;1800}18011802// Shows the image acquired once the commands submitted before have drawn1803// it.1804pub fn present(self v: &var VulkanDevice, index: u32) {1805 const f = if (v.surface_functions is ::Some |&f|) f else {1806 return;1807 };1808 const s = &v.surfaces.get(index to u64);1809 const image = if (s.current is ::Some |i|) i else {1810 return;1811 };1812 const texture = s.images.get(image to u64);1813 const finished = s.finished.get(image to u64);1814 const swapchain = s.swapchain;1815 const slot = v.begin();1816 const t = &v.textures.get(texture to u64);1817 if (!t.drawn) {1818 v.image_barrier(1819 v.slots[slot].commands,1820 t.image,1821 ImageLayout::Undefined,1822 ImageLayout::PresentSource1823 );1824 }1825 v.end(slot, finished);1826 const waits: [u64 : 1] = [finished];1827 const swapchains: [u64 : 1] = [swapchain];1828 const indices: [u32 : 1] = [image];1829 const info = PresentInfo {1830 .wait_count = 1,1831 .waits = c_pointer::of(&waits[..]),1832 .swapchain_count = 1,1833 .swapchains = c_pointer::of(&swapchains[..]),1834 .indices = c_pointer::of(&indices[..])1835 };1836 const result = f.queue_present(v.queue, c_pointer::from(&info));1837 var target = &var v.surfaces.get_var(index to u64);1838 target.current = ::None;1839 match (result) {1840 SUCCESS {}1841 SUBOPTIMAL, ERROR_OUT_OF_DATE {1842 target.stale = true;1843 }1844 else {1845 check(result, &"vkQueuePresentKHR");1846 }1847 }1848}18491850/* --- Releasing objects --- */18511852// Releases the object once the submissions made so far have run. Writes1853// to it still waiting are dropped; a shader's slot is not taken again,1854// the pipelines made from it reading its layouts.1855pub fn release(self v: &var VulkanDevice, kind: ObjectKind, index: u32) {1856 match (kind) {1857 ::Buffer {1858 v.staged.forget(kind, index);1859 }1860 ::Texture {1861 if (v.textures.get(index to u64).discard) {1862 panic "pkg::alloy::gpu: a surface's texture goes with its surface";1863 }1864 v.staged.forget(kind, index);1865 var k: u64 = 0;1866 while (k < v.fresh.length()) {1867 if (v.fresh.get(k) == index) {1868 v.fresh.remove(k);1869 } else {1870 k += 1;1871 }1872 }1873 }1874 }1875 v.releases.push(Release { .kind = kind, .index = index, .after = v.serial });1876 v.collect();1877}18781879// Frees the objects released whose submissions have all run.1880fn collect(self v: &var VulkanDevice) {1881 var k: u64 = 0;1882 while (k < v.releases.length()) {1883 const r = v.releases.get(k);1884 var running = false;1885 for (v.slots) |&s| {1886 if (s.busy && s.serial <= r.after) {1887 running = true;1888 }1889 }1890 if (running) {1891 k += 1;1892 } else {1893 v.releases.swap_remove(k);1894 v.destroy(r.kind, r.index);1895 }1896 }1897}18981899fn destroy(self v: &var VulkanDevice, kind: ObjectKind, index: u32) {1900 const at = index to u64;1901 match (kind) {1902 ::Buffer {1903 v.free(&v.buffers.get(at));1904 }1905 ::Texture {1906 const t = &v.textures.get(at);1907 v.f.destroy_image_view(v.device, t.view, 0);1908 v.f.destroy_image(v.device, t.image, 0);1909 v.f.free_memory(v.device, t.memory, 0);1910 }1911 ::Sampler {1912 v.f.destroy_sampler(v.device, v.samplers.get(at), 0);1913 }1914 ::Shader {1915 // its index is not taken again: pipelines read its layouts1916 v.f.destroy_shader_module(v.device, v.shaders.get(at).module, 0);1917 return;1918 }1919 ::RenderPipeline {1920 v.f.destroy_pipeline(v.device, v.pipelines.get(at).pipeline, 0);1921 }1922 ::ComputePipeline {1923 v.f.destroy_pipeline(v.device, v.computes.get(at).pipeline, 0);1924 }1925 ::BindGroup {1926 const g = v.groups.get(at);1927 const sets: [u64 : 1] = [g.set];1928 check(1929 v.f.free_sets(v.device, g.pool, 1, c_pointer::of(&sets[..])),1930 &"vkFreeDescriptorSets"1931 );1932 }1933 ::Surface {}1934 }1935 v.released.push(kind, index);1936}19371938// Frees the surface, its swap chain and its images' textures, whose1939// indices it gives.1940pub fn release_surface(self v: &var VulkanDevice, index: u32) -> Vector<u32> {1941 const f = if (v.surface_functions is ::Some |&f|) f else {1942 return Vector<u32>::empty();1943 };1944 v.finish();1945 check(v.f.wait_idle(v.device), &"vkDeviceWaitIdle");1946 if (v.acquired != 0) {1947 v.semaphores.push(v.acquired);1948 v.acquired = 0;1949 }1950 const s = &v.surfaces.get(index to u64);1951 for (s.views.view()) |view| {1952 v.f.destroy_image_view(v.device, view, 0);1953 }1954 for (s.finished.view()) |semaphore| {1955 f.destroy_semaphore(v.device, semaphore, 0);1956 }1957 if (s.swapchain != 0) {1958 f.destroy_swapchain(v.device, s.swapchain, 0);1959 }1960 f.destroy_surface(v.instance, s.surface, 0);1961 var textures = copy s.images;1962 for (textures.view()) |t| {1963 v.released.push(::Texture, t);1964 }1965 var target = &var v.surfaces.get_var(index to u64);1966 target.swapchain = 0;1967 target.images = Vector<u32>::empty();1968 target.views = Vector<u64>::empty();1969 target.finished = Vector<u64>::empty();1970 target.current = ::None;1971 v.released.push(::Surface, index);1972 return move textures;1973}19741975/* --- As the device's driver --- */19761977pub fn device_name(self v: &VulkanDevice) -> String => copy v.name;19781979pub fn window_surface(self v: &var VulkanDevice, window: &Window) -> Result<Surface> {1980 match (v.surface(&window)) {1981 ::Ok |index| {1982 return ::Ok(Surface {1983 .generation = 0,1984 .index = index,1985 .format = v.surface_format(index)1986 });1987 }1988 ::Error |move error| {1989 return ::Error(move error);1990 }1991 }1992}19931994pub fn show(self v: &var VulkanDevice, surface: u32, window: &var Window) {1995 v.present(surface);1996 window.surface_presented();1997}