Skip to main content

oa/ui/
text.rs

1//! Embedded hinted text atlas and OpenType shaping.
2//!
3//! Donor: `oa/ui/text.h` and `oa/ui/text.cpp`. Rasterization remains an
4//! offline build input; runtime shaping uses the same embedded face bytes.
5
6use std::sync::OnceLock;
7
8pub use crate::ui::type_gen::{GlyphInfo, TextLayoutConfig};
9use crate::{
10	Color, Error, Result,
11	runtime::{EngineHandle, Storage},
12};
13
14const COVERAGE: &[u8] = include_bytes!("../../../font/coverage.bin");
15const GLYPHS: &[u8] = include_bytes!("../../../font/glyphs.bin");
16const SUPPORT: &[u8] = include_bytes!("../../../font/support.bin");
17const METADATA: &str = include_str!("../../../font/metadata.json");
18const SANS: &[u8] = include_bytes!("../../../font/IBMPlexSans/IBMPlexSans-Regular.ttf");
19const MONO: &[u8] = include_bytes!("../../../font/IntelOneMono/IntelOneMono-Regular.ttf");
20const SANS_SEMIBOLD: &[u8] = include_bytes!("../../../font/IBMPlexSans/IBMPlexSans-SemiBold.ttf");
21const GLYPH_RECORD_BYTES: usize = 40;
22
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24#[repr(u8)]
25pub enum FontId {
26	#[default]
27	Sans = 0,
28	Mono = 1,
29	SansSemibold = 2,
30}
31
32struct AtlasMetadata {
33	width: u32,
34	height: u32,
35	strikes: Vec<u32>,
36	codepoints: Vec<u32>,
37}
38
39fn metadata() -> &'static AtlasMetadata {
40	static META: OnceLock<AtlasMetadata> = OnceLock::new();
41	META.get_or_init(|| {
42		let value: serde_json::Value = serde_json::from_str(METADATA).expect("generated text metadata");
43		AtlasMetadata {
44			width: value["width"].as_u64().expect("atlas width") as u32,
45			height: value["height"].as_u64().expect("atlas height") as u32,
46			strikes: value["strikes"]
47				.as_array()
48				.expect("atlas strikes")
49				.iter()
50				.map(|v| v.as_u64().unwrap() as u32)
51				.collect(),
52			codepoints: value["codepoints"]
53				.as_array()
54				.expect("atlas codepoints")
55				.iter()
56				.map(|v| v.as_u64().unwrap() as u32)
57				.collect(),
58		}
59	})
60}
61
62pub struct TextAtlas {
63	_storage: Storage,
64	descriptor: u32,
65}
66
67impl TextAtlas {
68	pub(super) fn storage(&self) -> &Storage {
69		&self._storage
70	}
71
72	pub(crate) fn new(engine: &EngineHandle) -> Result<Self> {
73		let storage = engine.create_storage(COVERAGE)?;
74		let descriptor = engine.storage_descriptor_index(&storage)?;
75		Ok(Self {
76			_storage: storage,
77			descriptor,
78		})
79	}
80
81	pub fn width(&self) -> u32 {
82		metadata().width
83	}
84	pub fn height(&self) -> u32 {
85		metadata().height
86	}
87	pub(crate) fn descriptor(&self) -> u32 {
88		self.descriptor
89	}
90
91	pub fn find_glyph(&self, font: FontId, codepoint: char, pixel_size: f32) -> Option<GlyphInfo> {
92		if !pixel_size.is_finite() || pixel_size <= 0.0 {
93			return None;
94		}
95		let meta = metadata();
96		let cp_index = meta.codepoints.binary_search(&(codepoint as u32)).ok()?;
97		let font_index = font as usize;
98		if SUPPORT
99			.get(font_index * meta.codepoints.len() + cp_index)
100			.copied()?
101			== 0
102		{
103			return None;
104		}
105		let strike_index = meta
106			.strikes
107			.iter()
108			.enumerate()
109			.min_by(|(_, a), (_, b)| {
110				((**a as f32 - pixel_size).abs()).total_cmp(&((**b as f32 - pixel_size).abs()))
111			})?
112			.0;
113		let index = (font_index * meta.strikes.len() + strike_index) * meta.codepoints.len() + cp_index;
114		let record = GLYPHS.get(index * GLYPH_RECORD_BYTES..(index + 1) * GLYPH_RECORD_BYTES)?;
115		let u32_at = |offset| u32::from_le_bytes(record[offset..offset + 4].try_into().unwrap());
116		let f32_at = |offset| f32::from_le_bytes(record[offset..offset + 4].try_into().unwrap());
117		Some(GlyphInfo {
118			codepoint: u32_at(8),
119			atlas_x: u32_at(12) as f32,
120			atlas_y: u32_at(16) as f32,
121			atlas_w: u32_at(20) as f32,
122			atlas_h: u32_at(24) as f32,
123			bearing_x: f32_at(28),
124			bearing_y: f32_at(32),
125			advance: f32_at(36),
126			ink_w: u32_at(20) as f32,
127			ink_h: u32_at(24) as f32,
128			raster_size: meta.strikes[strike_index] as f32,
129		})
130	}
131}
132
133impl Default for TextLayoutConfig {
134	fn default() -> Self {
135		Self {
136			font: FontId::Sans,
137			size: 14.0,
138			wrap_width: 0.0,
139			monospace: false,
140		}
141	}
142}
143
144#[derive(Clone, Copy, Debug, PartialEq)]
145pub struct PositionedGlyph {
146	pub x: f32,
147	pub y: f32,
148	/// Pen advance applied after this glyph, in scaled pixels.
149	pub advance: f32,
150	pub codepoint: char,
151	pub cluster: u32,
152	pub color: Color,
153	pub font: FontId,
154}
155
156pub struct TextLayout;
157
158impl TextLayout {
159	pub fn shape(
160		atlas: &TextAtlas,
161		text: &str,
162		origin: [f32; 2],
163		config: TextLayoutConfig,
164		color: Color,
165	) -> Result<Vec<PositionedGlyph>> {
166		if !config.size.is_finite()
167			|| config.size <= 0.0
168			|| !config.wrap_width.is_finite()
169			|| config.wrap_width < 0.0
170		{
171			return Err(Error::invalid_argument(
172				"text size must be positive and wrap width non-negative",
173			));
174		}
175		let font = if config.monospace {
176			FontId::Mono
177		} else {
178			config.font
179		};
180		let bytes = match font {
181			FontId::Sans => SANS,
182			FontId::Mono => MONO,
183			FontId::SansSemibold => SANS_SEMIBOLD,
184		};
185		let face = rustybuzz::Face::from_slice(bytes, 0)
186			.ok_or_else(|| Error::failed_precondition("embedded UI font is invalid"))?;
187		let mut reverse: std::collections::HashMap<u32, char> = std::collections::HashMap::new();
188		for &cp in &metadata().codepoints {
189			if let Some(ch) = char::from_u32(cp)
190				&& let Some(glyph) = face.glyph_index(ch)
191			{
192				reverse.entry(u32::from(glyph.0)).or_insert(ch);
193			}
194		}
195		let mut buffer = rustybuzz::UnicodeBuffer::new();
196		buffer.push_str(text);
197		buffer.set_direction(rustybuzz::Direction::LeftToRight);
198		let output = rustybuzz::shape(&face, &[], buffer);
199		let scale = config.size / face.units_per_em() as f32;
200		let mut x = origin[0];
201		let mut result = Vec::with_capacity(output.len());
202		for (info, position) in output.glyph_infos().iter().zip(output.glyph_positions()) {
203			let ch = reverse.get(&info.glyph_id).copied().unwrap_or('?');
204			if atlas.find_glyph(font, ch, config.size).is_none() {
205				continue;
206			}
207			let advance = position.x_advance as f32 * scale;
208			result.push(PositionedGlyph {
209				x: x + position.x_offset as f32 * scale,
210				y: origin[1] - position.y_offset as f32 * scale,
211				advance,
212				codepoint: ch,
213				cluster: info.cluster,
214				color,
215				font,
216			});
217			x += advance;
218		}
219		Ok(result)
220	}
221}
222
223// ── GPU glyph batches ─────────────────────────────────────────────────────────
224//
225// Donor: `oa/ui/text.h` `GlyphInstance`/`GlyphBuffer`. One source-anchored
226// glyph quad: the anchor is normalized to the source image while offsets and
227// dimensions are compose-target pixels, so labels remain readable while the
228// image camera pans and zooms.
229
230/// One source-anchored glyph quad record, exactly 48 bytes.
231///
232/// `anchor_x`/`anchor_y` are normalized to the source image;
233/// `offset_x`/`offset_y` and `width`/`height` are compose-target pixels.
234/// `flags` bit 0 rotates the source coverage counter-clockwise for
235/// bottom-to-top text; higher bits are reserved for `Ui`'s deterministic
236/// non-overlap batching.
237#[repr(C)]
238#[derive(Clone, Copy, Debug, PartialEq)]
239pub struct GlyphInstance {
240	pub anchor_x: f32,
241	pub anchor_y: f32,
242	pub offset_x: f32,
243	pub offset_y: f32,
244	pub width: f32,
245	pub height: f32,
246	pub atlas_x: u32,
247	pub atlas_y: u32,
248	pub atlas_w: u32,
249	pub atlas_h: u32,
250	pub color: u32,
251	pub flags: u32,
252}
253
254const _: () = assert!(std::mem::size_of::<GlyphInstance>() == 48);
255
256impl Default for GlyphInstance {
257	fn default() -> Self {
258		Self {
259			anchor_x: 0.0,
260			anchor_y: 0.0,
261			offset_x: 0.0,
262			offset_y: 0.0,
263			width: 0.0,
264			height: 0.0,
265			atlas_x: 0,
266			atlas_y: 0,
267			atlas_w: 0,
268			atlas_h: 0,
269			color: 0xF5F5F5FF,
270			flags: 0,
271		}
272	}
273}
274
275/// A fixed-capacity GPU-consumable glyph-instance buffer.
276///
277/// Records are replaced through [`GlyphBuffer::upload`] while
278/// [`GlyphBuffer::mark_consumed`] pins the exact [`crate::Event`] a GPU
279/// consumer must complete before the next overwrite. Dropping the buffer
280/// never waits; the engine's retirement service keeps submitted resources
281/// alive through completion.
282pub struct GlyphBuffer {
283	engine: EngineHandle,
284	storage: crate::Matrix,
285	consumer: Option<crate::Event>,
286	count: u32,
287	capacity: u32,
288}
289
290impl GlyphBuffer {
291	/// Allocate a host-uploadable buffer for `capacity` glyph records.
292	///
293	/// # Errors
294	///
295	/// Returns an error when `capacity` is zero, the capacity byte extent
296	/// overflows, or allocation fails.
297	pub fn create_host_upload(capacity: u32) -> Result<Self> {
298		Self::create_host_upload_on(&crate::Engine::current()?, capacity)
299	}
300
301	pub fn create_host_upload_on(engine: &crate::Engine, capacity: u32) -> Result<Self> {
302		if capacity == 0 {
303			return Err(Error::invalid_argument(
304				"oa::ui::GlyphBuffer::create_host_upload: capacity must be non-zero",
305			));
306		}
307		let byte_len = usize::try_from(capacity)
308			.ok()
309			.and_then(|count| count.checked_mul(std::mem::size_of::<GlyphInstance>()))
310			.ok_or_else(|| {
311				Error::invalid_argument(
312					"oa::ui::GlyphBuffer::create_host_upload: capacity byte extent overflows usize",
313				)
314			})?;
315		let storage = crate::Matrix::new_from_slice_on(engine, [byte_len], &vec![0_u8; byte_len])?;
316		Ok(Self {
317			engine: engine.handle(),
318			storage,
319			consumer: None,
320			count: 0,
321			capacity,
322		})
323	}
324
325	/// Replace the current records.
326	///
327	/// # Errors
328	///
329	/// Returns [`crate::ErrorKind::NotReady`] while a previous render
330	/// submission still consumes this slot,
331	/// [`crate::ErrorKind::ResourceExhausted`] when `glyphs` exceeds capacity,
332	/// or an upload error.
333	pub fn upload(&mut self, glyphs: &[GlyphInstance]) -> Result<()> {
334		if !self.is_ready()? {
335			return Err(Error::not_ready(
336				"oa::ui::GlyphBuffer::upload: buffer is still consumed by the GPU",
337			));
338		}
339		if glyphs.len() > usize::try_from(self.capacity).unwrap_or(usize::MAX) {
340			return Err(Error::resource_exhausted(
341				"oa::ui::GlyphBuffer::upload: glyph count exceeds capacity",
342			));
343		}
344		let used = std::mem::size_of_val(glyphs);
345		let mut bytes = vec![0_u8; self.storage.num_elements()];
346		if used > 0 {
347			// SAFETY: `GlyphInstance` is `repr(C)`, plain data with a
348			// statically checked layout; the used prefix never exceeds the
349			// byte capacity.
350			let source = unsafe { std::slice::from_raw_parts(glyphs.as_ptr().cast::<u8>(), used) };
351			bytes[..used].copy_from_slice(source);
352		}
353		self.storage.write_values::<u8>(&bytes)?;
354		self.count = u32::try_from(glyphs.len())
355			.map_err(|_| Error::invalid_argument("glyph count exceeds u32"))?;
356		self.consumer = None;
357		Ok(())
358	}
359
360	/// Pin `completion` as the event that must complete before the next
361	/// [`upload`](Self::upload).
362	///
363	/// # Errors
364	///
365	/// Returns an error when `completion` does not belong to this buffer's
366	/// engine or completion cannot be queried.
367	pub fn mark_consumed(&mut self, completion: &crate::Event) -> Result<()> {
368		if !self.engine.owns_event(completion) {
369			return Err(Error::invalid_argument(
370				"oa::ui::GlyphBuffer::mark_consumed requires an event from its engine",
371			));
372		}
373		self.consumer = if completion.is_complete()? {
374			None
375		} else {
376			Some(completion.clone())
377		};
378		Ok(())
379	}
380
381	/// Return whether no pinned consumer event is still in flight.
382	///
383	/// # Errors
384	///
385	/// Returns an error when consumer completion cannot be queried.
386	pub fn is_ready(&self) -> Result<bool> {
387		match &self.consumer {
388			Some(completion) => completion.is_complete(),
389			None => Ok(true),
390		}
391	}
392
393	/// Return the number of records written by the last [`upload`](Self::upload).
394	pub const fn count(&self) -> u32 {
395		self.count
396	}
397
398	/// Return the record capacity fixed at creation.
399	pub const fn capacity(&self) -> u32 {
400		self.capacity
401	}
402
403	/// Bindless storage-buffer descriptor index for UI draw consumers.
404	pub(crate) fn bindless_index(&self) -> Result<u32> {
405		self.engine.storage_descriptor_index(self.storage.storage())
406	}
407
408	/// The packed record storage retained by UI draw commands.
409	pub(crate) const fn storage(&self) -> &crate::Matrix {
410		&self.storage
411	}
412
413	/// The engine that owns this buffer's storage.
414	pub(crate) const fn engine_handle(&self) -> &EngineHandle {
415		&self.engine
416	}
417}