text2.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. use async_lock::Mutex;
  2. use freetype as ft;
  3. use harfbuzz_sys::{
  4. freetype::hb_ft_font_create_referenced, hb_buffer_add_utf8, hb_buffer_create,
  5. hb_buffer_destroy, hb_buffer_get_glyph_infos, hb_buffer_get_glyph_positions,
  6. hb_buffer_guess_segment_properties, hb_buffer_set_cluster_level, hb_buffer_set_content_type,
  7. hb_feature_t, hb_font_destroy, hb_glyph_info_t, hb_glyph_position_t, hb_shape,
  8. HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS, HB_BUFFER_CONTENT_TYPE_UNICODE,
  9. };
  10. use miniquad::TextureId;
  11. use std::{
  12. collections::HashMap,
  13. os,
  14. sync::{Arc, Weak},
  15. };
  16. use crate::{
  17. error::Result,
  18. gfx2::{Rectangle, RenderApiPtr},
  19. util::ansi_texture,
  20. };
  21. // From https://sourceforge.net/projects/freetype/files/freetype2/2.6/
  22. //
  23. // * An `FT_Face' object can only be safely used from one thread at
  24. // a time.
  25. //
  26. // * An `FT_Library' object can now be used without modification
  27. // from multiple threads at the same time.
  28. //
  29. // * `FT_Face' creation and destruction with the same `FT_Library'
  30. // object can only be done from one thread at a time.
  31. //
  32. // One can use a single `FT_Library' object across threads as long
  33. // as a mutex lock is used around `FT_New_Face' and `FT_Done_Face'.
  34. // Any calls to `FT_Load_Glyph' and similar API are safe and do not
  35. // need the lock to be held as long as the same `FT_Face' is not
  36. // used from multiple threads at the same time.
  37. // Harfbuzz is threadsafe.
  38. // Notes:
  39. // * All ft init and face creation should happen at startup.
  40. // * FT faces protected behind an async Mutex
  41. // * Glyph cache. Key is (glyph_id, font_size)
  42. // * Glyph texture cache: (glyph_id, font_size, color)
  43. pub struct RenderedAtlas {
  44. pub uv_rects: Vec<Rectangle>,
  45. pub texture_id: TextureId,
  46. }
  47. const ATLAS_GAP: usize = 2;
  48. pub async fn make_texture_atlas(
  49. render_api: RenderApiPtr,
  50. font_size: f32,
  51. glyphs: &Vec<Glyph>,
  52. ) -> Result<RenderedAtlas> {
  53. // First compute total size of the atlas
  54. let mut total_width = ATLAS_GAP;
  55. let mut total_height = ATLAS_GAP;
  56. // Glyph IDs already rendered so we don't do it twice
  57. let mut rendered = vec![];
  58. for (idx, glyph) in glyphs.iter().enumerate() {
  59. let sprite = &glyph.sprite;
  60. assert_eq!(sprite.bmp.len(), 4 * sprite.bmp_width * sprite.bmp_height);
  61. // Already done this one so skip
  62. if rendered.contains(&glyph.glyph_id) {
  63. continue
  64. }
  65. rendered.push(glyph.glyph_id);
  66. total_width += sprite.bmp_width + ATLAS_GAP;
  67. total_height = std::cmp::max(total_height, sprite.bmp_height);
  68. }
  69. total_width += ATLAS_GAP;
  70. total_height += 2 * ATLAS_GAP;
  71. // Allocate the big texture now
  72. let mut atlas_bmp = vec![0; 4 * total_width * total_height];
  73. // For debug lines we want a single white pixel.
  74. atlas_bmp[0] = 255;
  75. atlas_bmp[1] = 255;
  76. atlas_bmp[2] = 255;
  77. atlas_bmp[3] = 255;
  78. // Calculate dimensions of final product first
  79. let mut current_x = ATLAS_GAP;
  80. let mut rendered_glyphs: Vec<u32> = vec![];
  81. let mut uv_rects: Vec<Rectangle> = vec![];
  82. for (idx, glyph) in glyphs.iter().enumerate() {
  83. let sprite = &glyph.sprite;
  84. // Did we already rendered this glyph?
  85. // If so just copy the UV rect from before.
  86. let mut uv_rect = None;
  87. for (rendered_glyph_id, rendered_uv_rect) in rendered_glyphs.iter().zip(uv_rects.iter()) {
  88. if *rendered_glyph_id == glyph.glyph_id {
  89. uv_rect = Some(rendered_uv_rect.clone());
  90. }
  91. }
  92. let uv_rect = match uv_rect {
  93. Some(uv_rect) => uv_rect,
  94. // Allocating a new glyph sprite in the atlas
  95. None => {
  96. copy_image(sprite, &mut atlas_bmp, total_width, current_x);
  97. // Compute UV coords
  98. let uv_rect = Rectangle {
  99. x: (ATLAS_GAP + current_x) as f32 / total_width as f32,
  100. y: ATLAS_GAP as f32 / total_height as f32,
  101. w: sprite.bmp_width as f32 / total_width as f32,
  102. h: sprite.bmp_height as f32 / total_height as f32,
  103. };
  104. current_x += sprite.bmp_width + ATLAS_GAP;
  105. uv_rect
  106. }
  107. };
  108. rendered_glyphs.push(glyph.glyph_id);
  109. uv_rects.push(uv_rect);
  110. }
  111. // Finally allocate the texture
  112. let texture_id =
  113. render_api.new_texture(total_width as u16, total_height as u16, atlas_bmp).await?;
  114. Ok(RenderedAtlas { uv_rects, texture_id })
  115. }
  116. fn copy_image(sprite: &Sprite, atlas_bmp: &mut Vec<u8>, total_width: usize, current_x: usize) {
  117. for i in 0..sprite.bmp_height {
  118. for j in 0..sprite.bmp_width {
  119. let off_dest = 4 * ((i + ATLAS_GAP) * total_width + j + current_x + ATLAS_GAP);
  120. let off_src = 4 * (i * sprite.bmp_width + j);
  121. atlas_bmp[off_dest] = sprite.bmp[off_src];
  122. atlas_bmp[off_dest + 1] = sprite.bmp[off_src + 1];
  123. atlas_bmp[off_dest + 2] = sprite.bmp[off_src + 2];
  124. atlas_bmp[off_dest + 3] = sprite.bmp[off_src + 3];
  125. }
  126. }
  127. }
  128. pub struct GlyphPositionIter<'a> {
  129. font_size: f32,
  130. glyphs: &'a Vec<Glyph>,
  131. current_x: f32,
  132. current_y: f32,
  133. i: usize,
  134. }
  135. impl<'a> GlyphPositionIter<'a> {
  136. pub fn new(font_size: f32, glyphs: &'a Vec<Glyph>, baseline_y: f32) -> Self {
  137. Self { font_size, glyphs, current_x: 0., current_y: baseline_y, i: 0 }
  138. }
  139. }
  140. impl<'a> Iterator for GlyphPositionIter<'a> {
  141. type Item = Rectangle;
  142. fn next(&mut self) -> Option<Self::Item> {
  143. assert!(self.i <= self.glyphs.len());
  144. if self.i == self.glyphs.len() {
  145. return None;
  146. }
  147. let glyph = &self.glyphs[self.i];
  148. let sprite = &glyph.sprite;
  149. let rect = if sprite.has_fixed_sizes {
  150. // Downscale by height
  151. let w = (sprite.bmp_width as f32 * self.font_size) / sprite.bmp_height as f32;
  152. let h = self.font_size;
  153. let x = self.current_x;
  154. let y = self.current_y - h;
  155. self.current_x += w;
  156. Rectangle { x, y, w, h }
  157. } else {
  158. let (w, h) = (sprite.bmp_width as f32, sprite.bmp_height as f32);
  159. let off_x = glyph.x_offset as f32 / 64.;
  160. let off_y = glyph.y_offset as f32 / 64.;
  161. let x = self.current_x + off_x + sprite.bearing_x;
  162. let y = self.current_y - off_y - sprite.bearing_y;
  163. let x_advance = glyph.x_advance;
  164. let y_advance = glyph.y_advance;
  165. self.current_x += x_advance;
  166. self.current_y += y_advance;
  167. Rectangle { x, y, w, h }
  168. };
  169. self.i += 1;
  170. Some(rect)
  171. }
  172. }
  173. pub struct TextShaper {
  174. font_faces: Mutex<FtFaces>,
  175. cache: Mutex<TextShaperCache>,
  176. }
  177. impl TextShaper {
  178. pub fn new() -> Arc<Self> {
  179. let ftlib = ft::Library::init().unwrap();
  180. let mut faces = vec![];
  181. let font_data = include_bytes!("../ibm-plex-mono-light.otf") as &[u8];
  182. let ft_face = ftlib.new_memory_face2(font_data, 0).unwrap();
  183. faces.push(ft_face);
  184. let font_data = include_bytes!("../NotoColorEmoji.ttf") as &[u8];
  185. let ft_face = ftlib.new_memory_face2(font_data, 0).unwrap();
  186. faces.push(ft_face);
  187. Arc::new(Self { font_faces: Mutex::new(FtFaces(faces)), cache: Mutex::new(HashMap::new()) })
  188. }
  189. pub fn split_into_substrs(
  190. font_faces: &Vec<FreetypeFace>,
  191. text: String,
  192. ) -> Vec<(usize, String)> {
  193. let mut current_idx = 0;
  194. let mut current_str = String::new();
  195. let mut substrs = vec![];
  196. 'next_char: for chr in text.chars() {
  197. let idx = 'get_idx: {
  198. for i in 0..font_faces.len() {
  199. let ft_face = &font_faces[i];
  200. if ft_face.get_char_index(chr as usize).is_some() {
  201. break 'get_idx i
  202. }
  203. }
  204. drop(font_faces);
  205. warn!(target: "text", "no font fallback for char: '{}'", chr);
  206. // Skip this char
  207. continue 'next_char
  208. };
  209. if current_idx != idx {
  210. if !current_str.is_empty() {
  211. // Push
  212. substrs.push((current_idx, current_str.clone()));
  213. }
  214. current_str.clear();
  215. current_idx = idx;
  216. }
  217. current_str.push(chr);
  218. }
  219. if !current_str.is_empty() {
  220. // Push
  221. substrs.push((current_idx, current_str));
  222. }
  223. substrs
  224. }
  225. pub async fn shape(&self, text: String, font_size: f32) -> Vec<Glyph> {
  226. // Lock font faces
  227. // Freetype faces are not threadsafe
  228. let mut faces = self.font_faces.lock().await;
  229. let mut cache = self.cache.lock().await;
  230. let substrs = Self::split_into_substrs(&faces.0, text.clone());
  231. let mut glyphs: Vec<Glyph> = vec![];
  232. let mut current_x = 0.;
  233. let mut current_y = 0.;
  234. for (face_idx, text) in substrs {
  235. //debug!("substr {}", text);
  236. let face = &mut faces.0[face_idx];
  237. if face.has_fixed_sizes() {
  238. // emojis required a fixed size
  239. //face.set_char_size(109 * 64, 0, 72, 72).unwrap();
  240. face.select_size(0).unwrap();
  241. } else {
  242. face.set_char_size(font_size as isize * 64, 0, 96, 96).unwrap();
  243. }
  244. /*
  245. let hb_font = harfbuzz_rs::Font::from_freetype_face(face.clone());
  246. let buffer = harfbuzz_rs::UnicodeBuffer::new()
  247. .set_cluster_level(harfbuzz_rs::ClusterLevel::MonotoneCharacters)
  248. .add_str(&text);
  249. let output = harfbuzz_rs::shape(&hb_font, buffer, &[]);
  250. let positions = output.get_glyph_positions();
  251. let infos = output.get_glyph_infos();
  252. */
  253. let utf8_ptr = text.as_ptr() as *const _;
  254. // https://harfbuzz.github.io/a-simple-shaping-example.html
  255. let (hb_font, buf, glyph_infos, glyph_pos, glyph_infos_iter, glyph_pos_iter) = unsafe {
  256. let ft_face_ptr: freetype::freetype_sys::FT_Face = face.raw_mut();
  257. let hb_font = hb_ft_font_create_referenced(ft_face_ptr);
  258. let buf = hb_buffer_create();
  259. hb_buffer_set_content_type(buf, HB_BUFFER_CONTENT_TYPE_UNICODE);
  260. hb_buffer_set_cluster_level(buf, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS);
  261. hb_buffer_add_utf8(
  262. buf,
  263. utf8_ptr,
  264. text.len() as os::raw::c_int,
  265. 0 as os::raw::c_uint,
  266. text.len() as os::raw::c_int,
  267. );
  268. hb_buffer_guess_segment_properties(buf);
  269. hb_shape(hb_font, buf, std::ptr::null(), 0 as os::raw::c_uint);
  270. let mut length: u32 = 0;
  271. let glyph_infos = hb_buffer_get_glyph_infos(buf, &mut length as *mut u32);
  272. let glyph_infos_iter: &[hb_glyph_info_t] =
  273. std::slice::from_raw_parts(glyph_infos as *const _, length as usize);
  274. let glyph_pos = hb_buffer_get_glyph_positions(buf, &mut length as *mut u32);
  275. let glyph_pos_iter: &[hb_glyph_position_t] =
  276. std::slice::from_raw_parts(glyph_pos as *const _, length as usize);
  277. (hb_font, buf, glyph_infos, glyph_pos, glyph_infos_iter, glyph_pos_iter)
  278. };
  279. let mut prev_cluster = 0;
  280. //for (i, (position, info)) in positions.iter().zip(infos).enumerate() {
  281. for (i, (position, info)) in glyph_pos_iter.iter().zip(glyph_infos_iter.iter()).enumerate() {
  282. let glyph_id = info.codepoint as u32;
  283. // Index within this substr
  284. let curr_cluster = info.cluster as usize;
  285. // Skip first time
  286. if i != 0 {
  287. let substr = text[prev_cluster..curr_cluster].to_string();
  288. glyphs.last_mut().unwrap().substr = substr;
  289. }
  290. prev_cluster = curr_cluster;
  291. let x_offset = position.x_offset as f32 / 64.;
  292. let y_offset = position.y_offset as f32 / 64.;
  293. let x_advance = position.x_advance as f32 / 64.;
  294. let y_advance = position.y_advance as f32 / 64.;
  295. // Check cache
  296. // If it exists in the cache then skip
  297. // Relevant info:
  298. // * glyph_id
  299. // * font_size (for non-fixed size faces)
  300. // * face_idx
  301. let cache_key = CacheKey {
  302. glyph_id,
  303. font_size: if face.has_fixed_sizes() {
  304. FontSize::Fixed
  305. } else {
  306. FontSize::from(font_size)
  307. },
  308. face_idx,
  309. };
  310. //debug!(target: "text", "cache_key: {:?}", cache_key);
  311. if let Some(sprite) = cache.get(&cache_key) {
  312. let Some(sprite) = sprite.upgrade() else { break };
  313. let glyph = Glyph {
  314. glyph_id,
  315. substr: String::new(),
  316. sprite,
  317. x_offset,
  318. y_offset,
  319. x_advance,
  320. y_advance,
  321. };
  322. glyphs.push(glyph);
  323. continue
  324. }
  325. let mut flags = ft::face::LoadFlag::DEFAULT;
  326. if face.has_color() {
  327. flags |= ft::face::LoadFlag::COLOR;
  328. }
  329. //debug!("load_glyph {}", glyph_id);
  330. if let Err(err) = face.load_glyph(glyph_id, flags) {
  331. error!(target: "text", "error loading glyph: {}", glyph_id);
  332. continue
  333. }
  334. //debug!("load_glyph {} [done]", glyph_id);
  335. // https://gist.github.com/jokertarot/7583938?permalink_comment_id=3327566#gistcomment-3327566
  336. let glyph = face.glyph();
  337. glyph.render_glyph(ft::RenderMode::Normal).unwrap();
  338. let bmp = glyph.bitmap();
  339. let buffer = bmp.buffer();
  340. let bmp_width = bmp.width() as usize;
  341. let bmp_height = bmp.rows() as usize;
  342. let bearing_x = glyph.bitmap_left() as f32;
  343. let bearing_y = glyph.bitmap_top() as f32;
  344. let has_fixed_sizes = face.has_fixed_sizes();
  345. let pixel_mode = bmp.pixel_mode().unwrap();
  346. let bmp = match pixel_mode {
  347. ft::bitmap::PixelMode::Bgra => {
  348. let mut tdata = vec![];
  349. tdata.resize(4 * bmp_width * bmp_height, 0);
  350. // Convert from BGRA to RGBA
  351. for i in 0..bmp_width * bmp_height {
  352. let idx = i * 4;
  353. let b = buffer[idx];
  354. let g = buffer[idx + 1];
  355. let r = buffer[idx + 2];
  356. let a = buffer[idx + 3];
  357. tdata[idx] = r;
  358. tdata[idx + 1] = g;
  359. tdata[idx + 2] = b;
  360. tdata[idx + 3] = a;
  361. }
  362. tdata
  363. }
  364. ft::bitmap::PixelMode::Gray => {
  365. // Convert from greyscale to RGBA8
  366. let tdata: Vec<_> = buffer
  367. .iter()
  368. .flat_map(|coverage| vec![255, 255, 255, *coverage])
  369. .collect();
  370. tdata
  371. }
  372. _ => panic!("unsupport pixel mode: {:?}", pixel_mode),
  373. };
  374. let sprite = Arc::new(Sprite {
  375. bmp,
  376. bmp_width,
  377. bmp_height,
  378. bearing_x,
  379. bearing_y,
  380. has_fixed_sizes,
  381. });
  382. cache.insert(cache_key, Arc::downgrade(&sprite));
  383. let glyph = Glyph {
  384. glyph_id,
  385. substr: String::new(),
  386. sprite,
  387. x_offset,
  388. y_offset,
  389. x_advance,
  390. y_advance,
  391. };
  392. glyphs.push(glyph);
  393. }
  394. let substr = text[prev_cluster..].to_string();
  395. glyphs.last_mut().unwrap().substr = substr;
  396. unsafe {
  397. hb_buffer_destroy(buf);
  398. hb_font_destroy(hb_font);
  399. }
  400. }
  401. glyphs
  402. }
  403. }
  404. #[derive(Eq, Hash, PartialEq, Debug)]
  405. enum FontSize {
  406. Fixed,
  407. Size(u32),
  408. }
  409. impl FontSize {
  410. /// You can't use f32 in Hash and Eq impls
  411. fn from(size: f32) -> Self {
  412. Self::Size((size * 1000.).round() as u32)
  413. }
  414. }
  415. #[derive(Eq, Hash, PartialEq, Debug)]
  416. struct CacheKey {
  417. glyph_id: u32,
  418. font_size: FontSize,
  419. face_idx: usize,
  420. }
  421. pub type SpritePtr = Arc<Sprite>;
  422. pub struct Sprite {
  423. bmp: Vec<u8>,
  424. pub bmp_width: usize,
  425. pub bmp_height: usize,
  426. pub bearing_x: f32,
  427. pub bearing_y: f32,
  428. pub has_fixed_sizes: bool,
  429. }
  430. pub struct Glyph {
  431. pub glyph_id: u32,
  432. // Substring this glyph corresponds to
  433. pub substr: String,
  434. pub sprite: SpritePtr,
  435. // Normally these are i32, we provide the conversions
  436. pub x_offset: f32,
  437. pub y_offset: f32,
  438. pub x_advance: f32,
  439. pub y_advance: f32,
  440. }
  441. type FreetypeFace = ft::Face<&'static [u8]>;
  442. struct FtFaces(Vec<FreetypeFace>);
  443. unsafe impl Send for FtFaces {}
  444. unsafe impl Sync for FtFaces {}
  445. pub type TextShaperPtr = Arc<TextShaper>;
  446. type TextShaperCache = HashMap<CacheKey, Weak<Sprite>>;