use std::{collections::HashMap, sync::Arc}; use crate::texture_atlas::{AtlasLocation, TextureAtlas}; use parley::{ FontContext, Layout, LayoutContext, PositionedLayoutItem, Run, TextStyle, TreeBuilder, }; use swash::{ FontRef, scale::{Render, ScaleContext, Source, StrikeWith, image::Content}, zeno::Placement, }; use vk_graph::prelude::*; #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)] pub struct GlyphKey { size: u8, glyph_id: u32, font: u64, } pub struct TextRenderer { pub font_ctx: FontContext, pub layout_ctx: LayoutContext, pub scale_ctx: ScaleContext, pub glyph_atlas: TextureAtlas, pub placement_cache: HashMap, pub pipeline: Arc, pub vertex_buffer: Arc>, pub index_buffer: Arc>, // pos, colour, uv staging_vertices: Vec<([f32; 3], [f32; 3], [f32; 2])>, staging_indices: Vec<[u16; 3]>, } impl TextRenderer { pub fn new(device: &Arc, pool: &mut HashPool) -> Result { let pipeline = Arc::new(GraphicPipeline::create( device, GraphicPipelineInfoBuilder::default().blend(BlendMode::ALPHA), [ Shader::new_vertex( inline_spirv::include_spirv!("assets/triangle.vert", vert).as_slice(), ), Shader::new_fragment( inline_spirv::include_spirv!("assets/triangle.frag", frag).as_slice(), ), ], )?); let vertex_buffer = Arc::new(pool.lease(BufferInfo::device_mem( 2048, vk::BufferUsageFlags::VERTEX_BUFFER | vk::BufferUsageFlags::TRANSFER_DST, ))?); let index_buffer = Arc::new(pool.lease(BufferInfo::device_mem( 2048, vk::BufferUsageFlags::INDEX_BUFFER | vk::BufferUsageFlags::TRANSFER_DST, ))?); Ok(TextRenderer { font_ctx: FontContext::new(), layout_ctx: LayoutContext::new(), scale_ctx: ScaleContext::new(), glyph_atlas: TextureAtlas::new(device, 512, 512, 0), placement_cache: HashMap::new(), pipeline, vertex_buffer, index_buffer, staging_vertices: vec![], staging_indices: vec![], }) } pub fn push_layout(&mut self, layout: &Layout<[u8; 4]>, offset: f32) { let mut idx = self.staging_vertices.len() as u16; for line in layout.lines() { let trail = line.metrics().trailing_whitespace; for item in line.items() { match item { PositionedLayoutItem::GlyphRun(glyph_run) => { let mut run_x = glyph_run.offset() + offset - trail; let run_y = glyph_run.baseline(); let style = glyph_run.style(); let color = style .brush .into_iter() .map(|v| v as f32 / 255.0) .collect::>(); let run = glyph_run.run(); let font = run.font(); let font_size = run.font_size(); for glyph in glyph_run.glyphs() { let glyph_key = GlyphKey { size: font_size as u8, glyph_id: glyph.id, font: font.data.id(), }; let font_ref = FontRef::from_index(font.data.as_ref(), font.index as usize) .unwrap(); let Some((atlas_loc, placement)) = self.get_atlas_location(&glyph_key, run, font_ref) else { continue; }; let glyph_x = run_x + glyph.x + placement.left as f32; let glyph_y = run_y - glyph.y - placement.top as f32; let glyph_width = placement.width as f32; let glyph_height = placement.height as f32; run_x += glyph.advance; if glyph_height == 0.0 || glyph_width == 0.0 { continue; } self.staging_vertices.extend_from_slice(&[ ( [glyph_x, glyph_y, 0.0], [color[0], color[1], color[2]], [atlas_loc.x, atlas_loc.y], ), ( [glyph_x, glyph_y + glyph_height, 0.0], [color[0], color[1], color[2]], [atlas_loc.x, atlas_loc.y + atlas_loc.h], ), ( [glyph_x + glyph_width, glyph_y + glyph_height, 0.0], [color[0], color[1], color[2]], [atlas_loc.x + atlas_loc.w, atlas_loc.y + atlas_loc.h], ), ( [glyph_x + glyph_width, glyph_y, 0.0], [color[0], color[1], color[2]], [atlas_loc.x + atlas_loc.w, atlas_loc.y], ), ]); self.staging_indices.extend_from_slice(&[ [idx, idx + 1, idx + 2], [idx, idx + 2, idx + 3], ]); idx += 4; } } PositionedLayoutItem::InlineBox(_positioned_inline_box) => { todo!() } } } } } pub fn upload( &mut self, pool: &mut HashPool, render_graph: &mut RenderGraph, window_width: u32, window_height: u32, ) -> Result { let vertices = self .staging_vertices .drain(..) .flat_map(|(v, c, t)| { [ 2. * v[0] / window_width as f32 - 1.0, 2. * v[1] / window_height as f32 - 1.0, v[2], c[0], c[1], c[2], t[0], t[1], ] }) .flat_map(f32::to_ne_bytes) .collect::>(); let index_count = self.staging_indices.len() as u32 * 3; let indices = self .staging_indices .drain(..) .flatten() .flat_map(u16::to_ne_bytes) .collect::>(); let mut vertex_staging_buffer = pool.lease(BufferInfo::host_mem( (vertices.len() as u64).next_power_of_two(), vk::BufferUsageFlags::empty(), ))?; Buffer::copy_from_slice(&mut vertex_staging_buffer, 0, &*vertices); if vertex_staging_buffer.info.size > self.vertex_buffer.info.size { self.vertex_buffer = Arc::new(pool.lease(BufferInfo::device_mem( vertex_staging_buffer.info.size, vk::BufferUsageFlags::VERTEX_BUFFER | vk::BufferUsageFlags::TRANSFER_DST, ))?); } let mut index_staging_buffer = pool.lease(BufferInfo::host_mem( (indices.len() as u64).next_power_of_two(), vk::BufferUsageFlags::empty(), ))?; Buffer::copy_from_slice(&mut index_staging_buffer, 0, &*indices); if index_staging_buffer.info.size > self.index_buffer.info.size { self.index_buffer = Arc::new(pool.lease(BufferInfo::device_mem( index_staging_buffer.info.size, vk::BufferUsageFlags::INDEX_BUFFER | vk::BufferUsageFlags::TRANSFER_DST, ))?); } let index_node = render_graph.bind_node(&self.index_buffer); let vertex_node = render_graph.bind_node(&self.vertex_buffer); let staging_node = render_graph.bind_node(vertex_staging_buffer); render_graph.copy_buffer(staging_node, vertex_node); let staging_node = render_graph.bind_node(index_staging_buffer); render_graph.copy_buffer(staging_node, index_node); let atlas_node = self.glyph_atlas.upload(pool, render_graph); Ok(TextPipelineInfo { index_node, vertex_node, atlas_node, index_count, }) } pub fn draw( &self, render_graph: &mut RenderGraph, pipeline_info: TextPipelineInfo, target: impl Into + Copy, ) { render_graph .begin_pass("text") .bind_pipeline(&self.pipeline) .access_node(pipeline_info.index_node, AccessType::IndexBuffer) .access_node(pipeline_info.vertex_node, AccessType::VertexBuffer) .read_descriptor(0, pipeline_info.atlas_node) .store_color(0, target) .clear_color_value(0, target, [0.0, 0.0, 0.0, 1.0]) .record_subpass(move |subpass, _| { subpass.bind_index_buffer(pipeline_info.index_node, vk::IndexType::UINT16); subpass.bind_vertex_buffer(pipeline_info.vertex_node); subpass.draw_indexed(pipeline_info.index_count, 1, 0, 0, 0); }) .submit_pass(); } fn get_atlas_location( &mut self, glyph_key: &GlyphKey, run: &Run<[u8; 4]>, font_ref: FontRef, ) -> Option<(AtlasLocation, Placement)> { let mut scaler = self .scale_ctx .builder(font_ref) .size(glyph_key.size.into()) .hint(true) .normalized_coords(run.normalized_coords()) .build(); match self.glyph_atlas.get(glyph_key) { Some(x) => Some((x, self.placement_cache[glyph_key])), None => { let image = Render::new(&[ Source::ColorOutline(0), Source::ColorBitmap(StrikeWith::BestFit), Source::Outline, ]) .render(&mut scaler, glyph_key.glyph_id as u16)?; let new_data = match image.content { Content::Mask => image.data.into_iter().flat_map(|v| [v, v, v, v]).collect(), Content::Color => image.data, Content::SubpixelMask => unimplemented!(), }; self.placement_cache.insert(*glyph_key, image.placement); let atlas_loc = self .glyph_atlas .insert( *glyph_key, &new_data, image.placement.width, image.placement.height, ) .unwrap(); Some((atlas_loc, image.placement)) } } } pub fn layout_builder( &mut self, scale: f32, quantize: bool, root_style: &TextStyle<[u8; 4]>, ) -> TreeBuilder<'_, [u8; 4]> { self.layout_ctx .tree_builder(&mut self.font_ctx, scale, quantize, root_style) } } pub struct TextPipelineInfo { pub index_node: BufferLeaseNode, pub vertex_node: BufferLeaseNode, pub atlas_node: ImageNode, pub index_count: u32, }