use std::{error::Error, fmt};
use sim_engine::{
FrameComposer, FramePassOptions, ImageBatchPlacement, ImageSampling, LogicalScreenVector,
TextAtlas2d, TextRun2d, WgpuRenderer,
};
use crate::{
ExtractedFrame, ResolvedScreenText,
identity::{LogicEntity, WorldGeneration},
text::{TextError, TextFont},
};
#[path = "text/prepared.rs"]
mod prepared;
use prepared::DesktopPreparedLine;
#[path = "text/batches.rs"]
mod batches;
pub use batches::DesktopTextUpdates;
#[derive(Debug)]
pub enum DesktopTextError {
Settings {
source: LogicEntity,
error: TextError,
},
Engine {
source: LogicEntity,
error: sim_engine::TextError,
},
Prepared {
source: LogicEntity,
error: sim_engine::PreparedTextError,
},
Batch {
source: LogicEntity,
error: sim_engine::GlyphError,
},
BatchSizeOverflow,
Allocation {
requested_bytes: usize,
},
InvalidDrawPlan,
}
impl fmt::Display for DesktopTextError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Settings { source, error } => write!(f, "text {source:?} settings: {error}"),
Self::Engine { source, error } => write!(f, "text {source:?} preparation: {error}"),
Self::Prepared { source, error } => {
write!(f, "text {source:?} prepared layout: {error}")
}
Self::Batch { source, error } => {
write!(f, "text group starting at {source:?}: {error}")
}
Self::BatchSizeOverflow => f.write_str("text group size exceeds addressable limits"),
Self::Allocation { requested_bytes } => {
write!(f, "text cache could not reserve {requested_bytes} bytes")
}
Self::InvalidDrawPlan => f.write_str("text snapshot and desktop cache disagree"),
}
}
}
impl Error for DesktopTextError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Settings { error, .. } => Some(error),
Self::Engine { error, .. } => Some(error),
Self::Prepared { error, .. } => Some(error),
Self::Batch { error, .. } => Some(error),
_ => None,
}
}
}
struct FontEntry {
font: TextFont,
atlas: TextAtlas2d,
}
struct RunEntry {
source: LogicEntity,
font: TextFont,
run: TextRun2d,
}
#[derive(Default)]
pub(super) struct DesktopText {
cache: RetainedTextCache<FontEntry, RunEntry>,
batches: Vec<batches::BatchEntry>,
pub(super) updates: DesktopTextUpdates,
}
struct RetainedTextCache<Font, Run> {
fonts: Vec<Font>,
runs: Vec<Run>,
live: Vec<u64>,
generation: Option<WorldGeneration>,
scale_bits: Option<u32>,
}
impl<Font, Run> Default for RetainedTextCache<Font, Run> {
fn default() -> Self {
Self {
fonts: Vec::new(),
runs: Vec::new(),
live: Vec::new(),
generation: None,
scale_bits: None,
}
}
}
impl<Font, Run> RetainedTextCache<Font, Run> {
fn clear(&mut self) {
self.runs.clear();
self.fonts.clear();
self.live.clear();
self.generation = None;
self.scale_bits = None;
}
fn begin_frame(
&mut self,
generation: WorldGeneration,
scale: f32,
clear_frame_bindings: impl FnOnce(),
) {
if self.scale_bits != Some(scale.to_bits()) {
if self.scale_bits.is_some() {
clear_frame_bindings();
}
self.clear();
self.scale_bits = Some(scale.to_bits());
}
if self.generation != Some(generation) {
self.runs.clear();
self.generation = Some(generation);
}
}
fn retain_visible_runs(
&mut self,
labels: impl ExactSizeIterator<Item = (LogicEntity, bool)>,
source: impl Fn(&Run) -> LogicEntity,
) -> Result<(), DesktopTextError> {
self.live.clear();
self.live
.try_reserve(labels.len())
.map_err(|_| DesktopTextError::Allocation {
requested_bytes: labels.len().saturating_mul(size_of::<u64>()),
})?;
self.live.extend(
labels.filter_map(|(source, nonempty)| nonempty.then_some(source.stable_bits())),
);
self.live.sort_unstable();
self.runs
.retain(|run| self.live.binary_search(&source(run).stable_bits()).is_ok());
Ok(())
}
}
impl DesktopText {
pub(super) fn has_runs(&self) -> bool {
!self.cache.runs.is_empty()
}
pub(super) fn clear(&mut self) {
self.batches.clear();
self.cache.clear();
self.updates = DesktopTextUpdates::default();
}
pub(super) fn prepare(
&mut self,
renderer: &mut WgpuRenderer,
extracted: &ExtractedFrame,
batching: bool,
) -> Result<(), DesktopTextError> {
let started = std::time::Instant::now();
self.updates = DesktopTextUpdates::default();
let scale = renderer.scale_factor() as f32;
if self.cache.generation != Some(extracted.world_generation())
|| self.cache.scale_bits != Some(scale.to_bits())
|| !batching
{
self.batches.clear();
}
self.cache
.begin_frame(extracted.world_generation(), scale, || {
renderer.clear_frame_cache()
});
self.cache.retain_visible_runs(
extracted.resolved_screen_texts().iter().map(|text| {
(
text.source(),
!text.text().is_empty()
&& text.visual().clip() != crate::screen::ScreenClip::Empty,
)
}),
|run| run.source,
)?;
for visual in extracted.resolved_screen_texts() {
if !visual.text().is_empty()
&& visual.visual().clip() != crate::screen::ScreenClip::Empty
{
self.prepare_one(renderer, visual, scale)?;
}
}
self.updates.source_cpu_time = started.elapsed();
if batching {
if let Err(error) = self.prepare_batches(renderer, extracted) {
self.batches.clear();
return Err(error);
}
}
Ok(())
}
fn prepare_one(
&mut self,
renderer: &WgpuRenderer,
visual: &ResolvedScreenText,
scale: f32,
) -> Result<(), DesktopTextError> {
let source = visual.source();
let font = visual.font();
let font_index = match self
.cache
.fonts
.binary_search_by_key(&font.slot(), |entry| entry.font.slot())
{
Ok(index) => index,
Err(index) => {
self.cache
.fonts
.try_reserve(1)
.map_err(|_| DesktopTextError::Allocation {
requested_bytes: size_of::<FontEntry>(),
})?;
let settings = font.settings();
let style = settings
.style(scale)
.map_err(|error| DesktopTextError::Settings { source, error })?;
let atlas = TextAtlas2d::new(
renderer,
font.face().clone(),
style,
settings.atlas_budget(),
)
.map_err(|error| DesktopTextError::Engine { source, error })?;
self.cache.fonts.insert(
index,
FontEntry {
font: font.clone(),
atlas,
},
);
index
}
};
let atlas = &mut self.cache.fonts[font_index].atlas;
let existing = self
.cache
.runs
.binary_search_by_key(&source.stable_bits(), |entry| entry.source.stable_bits());
if let Ok(index) = existing {
let entry = &self.cache.runs[index];
if entry.font == *font && entry.run.text() == visual.text() {
return Ok(());
}
}
let prepared = DesktopPreparedLine::new(visual.visual(), scale)
.map_err(|error| DesktopTextError::Settings { source, error })?;
let shaped = prepared.line();
match existing {
Ok(index) => {
let entry = &mut self.cache.runs[index];
if entry.font != *font {
let run = atlas
.prepare_from_shaped(renderer, shaped, font.settings().layout_budget())
.map_err(|error| DesktopTextError::Prepared { source, error })?;
*entry = RunEntry {
source,
font: font.clone(),
run,
};
} else if entry.run.text() != visual.text() {
atlas
.update_from_shaped(
renderer,
&mut entry.run,
shaped,
font.settings().layout_budget(),
)
.map_err(|error| DesktopTextError::Prepared { source, error })?;
}
}
Err(index) => {
self.cache
.runs
.try_reserve(1)
.map_err(|_| DesktopTextError::Allocation {
requested_bytes: size_of::<RunEntry>(),
})?;
let run = atlas
.prepare_from_shaped(renderer, shaped, font.settings().layout_budget())
.map_err(|error| DesktopTextError::Prepared { source, error })?;
self.cache.runs.insert(
index,
RunEntry {
source,
font: font.clone(),
run,
},
);
}
}
Ok(())
}
pub(super) fn draw<'a>(
&'a self,
frame: &mut FrameComposer<'a>,
visual: &ResolvedScreenText,
options: FramePassOptions,
) -> Result<(), super::images::ScreenPresentationError> {
let font_index = self
.cache
.fonts
.binary_search_by_key(&visual.font().slot(), |entry| entry.font.slot())
.map_err(|_| DesktopTextError::InvalidDrawPlan)?;
let run_index = self
.cache
.runs
.binary_search_by_key(&visual.source().stable_bits(), |entry| {
entry.source.stable_bits()
})
.map_err(|_| DesktopTextError::InvalidDrawPlan)?;
let run = &self.cache.runs[run_index];
if run.source != visual.source()
|| run.font != *visual.font()
|| run.run.text() != visual.text()
{
return Err(DesktopTextError::InvalidDrawPlan.into());
}
let position = visual.baseline_origin().to_vec2();
let placement = ImageBatchPlacement::new(
LogicalScreenVector::new(position.x(), position.y()),
visual.tint(),
)
.map_err(|error| DesktopTextError::Engine {
source: visual.source(),
error: sim_engine::TextError::Glyph(sim_engine::GlyphError::Image(error)),
})?;
frame.draw_glyph_run_placed(
self.cache.fonts[font_index].atlas.atlas(),
run.run.glyph_run(),
placement,
ImageSampling::Linear,
options,
)?;
Ok(())
}
}
#[cfg(test)]
#[path = "text/batch_tests.rs"]
mod batch_tests;
#[cfg(test)]
#[path = "text/tests.rs"]
mod tests;