1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4mod buffer;
5mod descriptors;
6mod util;
7mod vulkan_context;
8mod vulkan_texture;
9
10use ash::util::read_spv;
11pub use ash::vk;
12use buffer::Buffer;
13use bytemuck::{bytes_of, Pod, Zeroable};
14pub use descriptors::Descriptors;
15use std::{collections::HashMap, ffi::CStr, io::Cursor};
16pub use vulkan_context::VulkanContext;
17use vulkan_texture::{UploadQueue, NO_TEXTURE_ID};
18pub use vulkan_texture::{VulkanTexture, VulkanTextureCreateInfo};
19
20use yakui_core as yakui;
21use yakui_core::geometry::UVec2;
22use yakui_core::{paint::Vertex as YakuiVertex, ManagedTextureId};
23
24pub struct YakuiVulkan {
34 pipeline_layout: vk::PipelineLayout,
36 graphics_pipeline: vk::Pipeline,
38 index_buffer: Buffer<u32>,
40 vertex_buffer: Buffer<Vertex>,
42 initial_textures_synced: bool,
44 yakui_managed_textures: HashMap<ManagedTextureId, VulkanTexture>,
46 user_textures: thunderdome::Arena<VulkanTexture>,
48 descriptors: Descriptors,
50 uploads: UploadQueue,
51}
52
53#[non_exhaustive]
55#[derive(Default)]
56pub struct Options {
57 pub dynamic_rendering_format: Option<vk::Format>,
59 pub render_pass: vk::RenderPass,
61 pub subpass: u32,
63}
64
65#[derive(Clone, Copy, Debug)]
66struct DrawCall {
68 index_offset: u32,
69 index_count: u32,
70 clip: Option<yakui::geometry::Rect>,
71 texture_id: u32,
72 workflow: Workflow,
73}
74
75#[repr(C)]
76#[derive(Clone, Copy, Debug)]
77struct PushConstant {
79 texture_id: u32,
80 workflow: Workflow,
81}
82
83unsafe impl Zeroable for PushConstant {}
84unsafe impl Pod for PushConstant {}
85
86impl PushConstant {
87 pub fn new(texture_id: u32, workflow: Workflow) -> Self {
88 Self {
89 texture_id,
90 workflow,
91 }
92 }
93}
94
95#[repr(u32)]
96#[derive(Clone, Copy, Debug)]
97enum Workflow {
99 Main,
100 Text,
101}
102
103unsafe impl bytemuck::Zeroable for Workflow {}
104unsafe impl bytemuck::Pod for Workflow {}
105
106impl From<yakui::paint::Pipeline> for Workflow {
107 fn from(p: yakui::paint::Pipeline) -> Self {
108 match p {
109 yakui::paint::Pipeline::Main => Workflow::Main,
110 yakui::paint::Pipeline::Text => Workflow::Text,
111 _ => panic!("Unknown pipeline {p:?}"),
112 }
113 }
114}
115
116#[repr(C)]
117#[derive(Clone, Copy, Default, Debug)]
118struct Vertex {
119 position: yakui::geometry::Vec2,
120 texcoord: yakui::geometry::Vec2,
121 color: yakui::geometry::Vec4,
122}
123
124impl From<&YakuiVertex> for Vertex {
125 fn from(y: &YakuiVertex) -> Self {
126 Self {
127 position: y.position,
128 texcoord: y.texcoord,
129 color: y.color,
130 }
131 }
132}
133
134impl YakuiVulkan {
135 pub fn new(vulkan_context: &VulkanContext, options: Options) -> Self {
141 let device = vulkan_context.device;
142 let descriptors = Descriptors::new(vulkan_context);
143
144 let index_buffer = Buffer::new(vulkan_context, vk::BufferUsageFlags::INDEX_BUFFER, &[]);
145 let vertex_buffer = Buffer::new(vulkan_context, vk::BufferUsageFlags::VERTEX_BUFFER, &[]);
146
147 let mut vertex_spv_file = Cursor::new(&include_bytes!("../shaders/main.vert.spv")[..]);
148 let mut frag_spv_file = Cursor::new(&include_bytes!("../shaders/main.frag.spv")[..]);
149
150 let vertex_code =
151 read_spv(&mut vertex_spv_file).expect("Failed to read vertex shader spv file");
152 let vertex_shader_info = vk::ShaderModuleCreateInfo::default().code(&vertex_code);
153
154 let frag_code =
155 read_spv(&mut frag_spv_file).expect("Failed to read fragment shader spv file");
156 let frag_shader_info = vk::ShaderModuleCreateInfo::default().code(&frag_code);
157
158 let vertex_shader_module = unsafe {
159 device
160 .create_shader_module(&vertex_shader_info, None)
161 .expect("Vertex shader module error")
162 };
163
164 let fragment_shader_module = unsafe {
165 device
166 .create_shader_module(&frag_shader_info, None)
167 .expect("Fragment shader module error")
168 };
169
170 let pipeline_layout = unsafe {
171 device
172 .create_pipeline_layout(
173 &vk::PipelineLayoutCreateInfo::default()
174 .push_constant_ranges(std::slice::from_ref(
175 &vk::PushConstantRange::default()
176 .stage_flags(vk::ShaderStageFlags::FRAGMENT)
177 .size(std::mem::size_of::<PushConstant>() as _),
178 ))
179 .set_layouts(std::slice::from_ref(&descriptors.layout)),
180 None,
181 )
182 .unwrap()
183 };
184
185 let shader_entry_name = unsafe { CStr::from_bytes_with_nul_unchecked(b"main\0") };
186 let shader_stage_create_infos = [
187 vk::PipelineShaderStageCreateInfo {
188 module: vertex_shader_module,
189 p_name: shader_entry_name.as_ptr(),
190 stage: vk::ShaderStageFlags::VERTEX,
191 ..Default::default()
192 },
193 vk::PipelineShaderStageCreateInfo {
194 s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
195 module: fragment_shader_module,
196 p_name: shader_entry_name.as_ptr(),
197 stage: vk::ShaderStageFlags::FRAGMENT,
198 ..Default::default()
199 },
200 ];
201 let vertex_input_binding_descriptions = [vk::VertexInputBindingDescription {
202 binding: 0,
203 stride: std::mem::size_of::<Vertex>() as u32,
204 input_rate: vk::VertexInputRate::VERTEX,
205 }];
206
207 let vertex_input_attribute_descriptions = [
208 vk::VertexInputAttributeDescription {
210 location: 0,
211 binding: 0,
212 format: vk::Format::R32G32_SFLOAT,
213 offset: bytemuck::offset_of!(Vertex, position) as _,
214 },
215 vk::VertexInputAttributeDescription {
217 location: 1,
218 binding: 0,
219 format: vk::Format::R32G32_SFLOAT,
220 offset: bytemuck::offset_of!(Vertex, texcoord) as _,
221 },
222 vk::VertexInputAttributeDescription {
224 location: 2,
225 binding: 0,
226 format: vk::Format::R32G32B32A32_SFLOAT,
227 offset: bytemuck::offset_of!(Vertex, color) as _,
228 },
229 ];
230
231 let vertex_input_state_info = vk::PipelineVertexInputStateCreateInfo::default()
232 .vertex_attribute_descriptions(&vertex_input_attribute_descriptions)
233 .vertex_binding_descriptions(&vertex_input_binding_descriptions);
234 let vertex_input_assembly_state_info = vk::PipelineInputAssemblyStateCreateInfo {
235 topology: vk::PrimitiveTopology::TRIANGLE_LIST,
236 ..Default::default()
237 };
238 let viewport_state_info = vk::PipelineViewportStateCreateInfo::default()
239 .scissor_count(1)
240 .viewport_count(1);
241
242 let rasterization_info = vk::PipelineRasterizationStateCreateInfo {
243 front_face: vk::FrontFace::COUNTER_CLOCKWISE,
244 line_width: 1.0,
245 polygon_mode: vk::PolygonMode::FILL,
246 ..Default::default()
247 };
248 let multisample_state_info = vk::PipelineMultisampleStateCreateInfo {
249 rasterization_samples: vk::SampleCountFlags::TYPE_1,
250 ..Default::default()
251 };
252 let noop_stencil_state = vk::StencilOpState {
253 fail_op: vk::StencilOp::KEEP,
254 pass_op: vk::StencilOp::KEEP,
255 depth_fail_op: vk::StencilOp::KEEP,
256 compare_op: vk::CompareOp::ALWAYS,
257 ..Default::default()
258 };
259 let depth_state_info = vk::PipelineDepthStencilStateCreateInfo {
260 depth_test_enable: 1,
261 depth_write_enable: 1,
262 depth_compare_op: vk::CompareOp::LESS_OR_EQUAL,
263 front: noop_stencil_state,
264 back: noop_stencil_state,
265 max_depth_bounds: 1.0,
266 ..Default::default()
267 };
268 let color_blend_attachment_states = [vk::PipelineColorBlendAttachmentState {
269 blend_enable: 1,
270 src_color_blend_factor: vk::BlendFactor::SRC_ALPHA,
271 dst_color_blend_factor: vk::BlendFactor::ONE_MINUS_SRC_ALPHA,
272 color_blend_op: vk::BlendOp::ADD,
273 src_alpha_blend_factor: vk::BlendFactor::ONE,
274 dst_alpha_blend_factor: vk::BlendFactor::ZERO,
275 alpha_blend_op: vk::BlendOp::ADD,
276 color_write_mask: vk::ColorComponentFlags::RGBA,
277 }];
278 let color_blend_state = vk::PipelineColorBlendStateCreateInfo::default()
279 .logic_op(vk::LogicOp::CLEAR)
280 .attachments(&color_blend_attachment_states);
281
282 let dynamic_state = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR];
283 let dynamic_state_info =
284 vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_state);
285
286 let mut graphic_pipeline_info = vk::GraphicsPipelineCreateInfo::default()
287 .stages(&shader_stage_create_infos)
288 .vertex_input_state(&vertex_input_state_info)
289 .input_assembly_state(&vertex_input_assembly_state_info)
290 .viewport_state(&viewport_state_info)
291 .rasterization_state(&rasterization_info)
292 .multisample_state(&multisample_state_info)
293 .depth_stencil_state(&depth_state_info)
294 .color_blend_state(&color_blend_state)
295 .dynamic_state(&dynamic_state_info)
296 .layout(pipeline_layout);
297 let rendering_info_formats;
298 let mut rendering_info;
299 assert!(
300 options.dynamic_rendering_format.is_some()
301 || options.render_pass != vk::RenderPass::null(),
302 "either dynamic_rendering_format or render_pass must be set"
303 );
304 if let Some(format) = options.dynamic_rendering_format {
305 rendering_info_formats = [format];
306 rendering_info = vk::PipelineRenderingCreateInfo::default()
307 .color_attachment_formats(&rendering_info_formats);
308 graphic_pipeline_info = graphic_pipeline_info.push_next(&mut rendering_info);
309 } else {
310 graphic_pipeline_info = graphic_pipeline_info
311 .render_pass(options.render_pass)
312 .subpass(options.subpass);
313 }
314
315 let graphics_pipelines = unsafe {
316 device
317 .create_graphics_pipelines(
318 vk::PipelineCache::null(),
319 &[graphic_pipeline_info],
320 None,
321 )
322 .expect("Unable to create graphics pipeline")
323 };
324
325 let graphics_pipeline = graphics_pipelines[0];
326
327 unsafe {
328 device.destroy_shader_module(vertex_shader_module, None);
329 device.destroy_shader_module(fragment_shader_module, None);
330 }
331
332 Self {
333 descriptors,
334 pipeline_layout,
335 graphics_pipeline,
336 index_buffer,
337 vertex_buffer,
338 user_textures: Default::default(),
339 yakui_managed_textures: Default::default(),
340 initial_textures_synced: false,
341 uploads: UploadQueue::new(),
342 }
343 }
344
345 pub unsafe fn transfer(
350 &mut self,
351 paint: &yakui_core::paint::PaintDom,
352 vulkan_context: &VulkanContext,
353 cmd: vk::CommandBuffer,
354 ) {
355 self.update_textures(vulkan_context, paint);
356 self.uploads.record(vulkan_context, cmd);
357 }
358
359 pub fn transfers_submitted(&mut self) {
364 self.uploads.phase_submitted();
365 }
366
367 pub unsafe fn transfers_finished(&mut self, vulkan_context: &VulkanContext) {
374 self.uploads.phase_executed(vulkan_context);
375 }
376
377 pub unsafe fn paint(
383 &mut self,
384 paint: &yakui_core::paint::PaintDom,
385 vulkan_context: &VulkanContext,
386 cmd: vk::CommandBuffer,
387 resolution: vk::Extent2D,
388 ) {
389 let layers = paint.layers();
391 if layers.iter().all(|layer| layer.calls.is_empty()) {
392 return;
393 }
394
395 let draw_calls = self.build_draw_calls(vulkan_context, paint);
396
397 self.render(vulkan_context, resolution, cmd, &draw_calls);
398 }
399
400 fn render(
402 &self,
403 vulkan_context: &VulkanContext,
404 resolution: vk::Extent2D,
405 command_buffer: vk::CommandBuffer,
406 draw_calls: &[DrawCall],
407 ) {
408 let device = vulkan_context.device;
409
410 let surface_size = UVec2::new(resolution.width, resolution.height);
411
412 unsafe {
413 device.cmd_bind_pipeline(
414 command_buffer,
415 vk::PipelineBindPoint::GRAPHICS,
416 self.graphics_pipeline,
417 );
418 let default_scissor = [resolution.into()];
419
420 device.cmd_bind_vertex_buffers(command_buffer, 0, &[self.vertex_buffer.handle], &[0]);
421 device.cmd_bind_index_buffer(
422 command_buffer,
423 self.index_buffer.handle,
424 0,
425 vk::IndexType::UINT32,
426 );
427 device.cmd_bind_descriptor_sets(
428 command_buffer,
429 vk::PipelineBindPoint::GRAPHICS,
430 self.pipeline_layout,
431 0,
432 std::slice::from_ref(&self.descriptors.set),
433 &[],
434 );
435 let mut last_clip = None;
436 for draw_call in draw_calls {
437 if draw_call.clip != last_clip {
438 last_clip = draw_call.clip;
439
440 match draw_call.clip {
442 Some(rect) => {
443 let pos = rect.pos().as_uvec2();
444 let size = rect.size().as_uvec2();
445
446 let max = (pos + size).min(surface_size);
447 let size = UVec2::new(
448 max.x.saturating_sub(pos.x),
449 max.y.saturating_sub(pos.y),
450 );
451
452 if pos.x > surface_size.x
455 || pos.y > surface_size.y
456 || size.x == 0
457 || size.y == 0
458 {
459 continue;
460 }
461
462 let scissors = [vk::Rect2D {
463 offset: vk::Offset2D {
464 x: pos.x as _,
465 y: pos.y as _,
466 },
467 extent: vk::Extent2D {
468 width: size.x,
469 height: size.y,
470 },
471 }];
472 device.cmd_set_scissor(command_buffer, 0, &scissors);
474 }
475 None => {
476 device.cmd_set_scissor(command_buffer, 0, &default_scissor);
478 }
479 }
480 }
481
482 device.cmd_push_constants(
485 command_buffer,
486 self.pipeline_layout,
487 vk::ShaderStageFlags::FRAGMENT,
488 0,
489 bytes_of(&PushConstant::new(draw_call.texture_id, draw_call.workflow)),
490 );
491
492 device.cmd_draw_indexed(
494 command_buffer,
495 draw_call.index_count,
496 1,
497 draw_call.index_offset,
498 0,
499 1,
500 );
501 }
502 }
503 }
504
505 pub fn create_user_texture(
511 &mut self,
512 vulkan_context: &VulkanContext,
513 texture_create_info: VulkanTextureCreateInfo<Vec<u8>>,
514 ) -> yakui::TextureId {
515 let texture = VulkanTexture::new(
516 vulkan_context,
517 &mut self.descriptors,
518 texture_create_info,
519 &mut self.uploads,
520 );
521 yakui::TextureId::User(self.user_textures.insert(texture).to_bits())
522 }
523
524 pub fn add_user_texture(&mut self, texture: VulkanTexture) -> yakui::TextureId {
531 yakui::TextureId::User(self.user_textures.insert(texture).to_bits())
532 }
533
534 pub unsafe fn cleanup(&mut self, device: &ash::Device) {
542 device.device_wait_idle().unwrap();
543 self.descriptors.cleanup(device);
544 for (_, texture) in self.yakui_managed_textures.drain() {
545 texture.cleanup(device);
546 }
547 for (_, texture) in self.user_textures.drain() {
548 texture.cleanup(device);
549 }
550 device.destroy_pipeline_layout(self.pipeline_layout, None);
551 device.destroy_pipeline(self.graphics_pipeline, None);
552 self.index_buffer.cleanup(device);
553 self.vertex_buffer.cleanup(device);
554 self.uploads.cleanup(device);
555 }
556
557 pub fn descriptors(&mut self) -> &mut Descriptors {
560 &mut self.descriptors
561 }
562
563 fn update_textures(&mut self, vulkan_context: &VulkanContext, paint: &yakui::paint::PaintDom) {
564 use yakui::paint::TextureChange;
565 if !self.initial_textures_synced {
566 self.initial_textures_synced = true;
567 for (id, texture) in paint.textures() {
568 let texture = VulkanTexture::from_yakui_texture(
569 vulkan_context,
570 &mut self.descriptors,
571 texture,
572 &mut self.uploads,
573 );
574 self.yakui_managed_textures.insert(id, texture);
575 }
576
577 return;
578 }
579
580 for (id, change) in paint.texture_edits() {
581 match change {
582 TextureChange::Added => {
583 let texture = paint.texture(id).unwrap();
584 let texture = VulkanTexture::from_yakui_texture(
585 vulkan_context,
586 &mut self.descriptors,
587 texture,
588 &mut self.uploads,
589 );
590 self.yakui_managed_textures.insert(id, texture);
591 }
592
593 TextureChange::Removed => {
594 if let Some(removed) = self.yakui_managed_textures.remove(&id) {
595 unsafe {
596 self.uploads.dispose(removed);
597 }
598 }
599 }
600
601 TextureChange::Modified => {
602 if let Some(old) = self.yakui_managed_textures.remove(&id) {
603 unsafe {
604 self.uploads.dispose(old);
605 }
606 }
607 let new = paint.texture(id).unwrap();
608 let texture = VulkanTexture::from_yakui_texture(
609 vulkan_context,
610 &mut self.descriptors,
611 new,
612 &mut self.uploads,
613 );
614 self.yakui_managed_textures.insert(id, texture);
615 }
616 }
617 }
618 }
619
620 fn build_draw_calls(
621 &mut self,
622 vulkan_context: &VulkanContext,
623 paint: &yakui::paint::PaintDom,
624 ) -> Vec<DrawCall> {
625 let mut vertices: Vec<Vertex> = Default::default();
626 let mut indices: Vec<u32> = Default::default();
627 let mut draw_calls: Vec<DrawCall> = Default::default();
628
629 let calls = paint.layers().iter().flat_map(|layer| &layer.calls);
630
631 for call in calls {
632 let base = vertices.len() as u32;
633 let index_offset = indices.len() as u32;
634 let index_count = call.indices.len() as u32;
635
636 for index in &call.indices {
637 indices.push(*index as u32 + base);
638 }
639 for vertex in &call.vertices {
640 vertices.push(vertex.into())
641 }
642
643 let texture_id = call
644 .texture
645 .and_then(|id| match id {
646 yakui::TextureId::Managed(managed) => {
647 let texture = self.yakui_managed_textures.get(&managed)?;
648 Some(texture.id)
649 }
650 yakui::TextureId::User(bits) => {
651 let texture = self
652 .user_textures
653 .get(thunderdome::Index::from_bits(bits)?)?;
654 Some(texture.id)
655 }
656 })
657 .unwrap_or(NO_TEXTURE_ID);
658
659 draw_calls.push(DrawCall {
660 index_offset,
661 index_count,
662 clip: call.clip,
663 texture_id,
664 workflow: call.pipeline.into(),
665 });
666 }
667
668 unsafe {
669 self.index_buffer.write(vulkan_context, 0, &indices);
670 self.vertex_buffer.write(vulkan_context, 0, &vertices);
671 }
672
673 draw_calls
674 }
675}