diff --git a/src/api/rendering.rs b/src/api/rendering.rs index 78cd121..0d9f416 100644 --- a/src/api/rendering.rs +++ b/src/api/rendering.rs @@ -1,7 +1,7 @@ use crate::{ api::image_handle::image_handle_texture_id, color::Srgba, - dpi::Uv, + dpi::LogicalPoint, fonts::{Alignment, FontStyle, LayoutJob}, lua::Context, math::{Point, Quad, Rect, Size}, @@ -88,7 +88,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int 1 => { let esc_str = str_from_stack!(state, -nargs); let color = Srgba::from_escape_code(esc_str); - ctx.layers().set_draw_color(color); + ctx.recorder().set_draw_color(color); } // rgb 3 => { @@ -96,7 +96,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int let g = f32_from_stack!(state, -nargs + 1); let b = f32_from_stack!(state, -nargs + 2); let color = Srgba::new_f32(r, g, b, 1.0); - ctx.layers().set_draw_color(color); + ctx.recorder().set_draw_color(color); } // rgba 4 => { @@ -105,7 +105,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int let b = f32_from_stack!(state, -nargs + 2); let a = f32_from_stack!(state, -nargs + 3); let color = Srgba::new_f32(r, g, b, a); - ctx.layers().set_draw_color(color); + ctx.recorder().set_draw_color(color); } _ => panic!("Unexpected number of arguments"), } @@ -118,7 +118,7 @@ unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap(); - let color: [f32; 4] = ctx.layers().get_draw_color().into(); + let color: [f32; 4] = ctx.recorder().get_draw_color().into(); unsafe { ffi::lua_pushnumber(state, color[0] as f64) }; unsafe { ffi::lua_pushnumber(state, color[1] as f64) }; unsafe { ffi::lua_pushnumber(state, color[2] as f64) }; @@ -135,7 +135,7 @@ unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int { let nargs = unsafe { ffi::lua_gettop(state) }; match nargs { 0 => ctx - .layers() + .recorder() .set_viewport_from_size(ctx.window().logical_size()), 4 => { let x = f32_from_stack!(state, -nargs); @@ -143,7 +143,7 @@ unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int { let w = f32_from_stack!(state, -nargs + 2); let h = f32_from_stack!(state, -nargs + 3); let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h)); - ctx.layers().set_viewport(rect); + ctx.recorder().set_viewport(rect); } _ => panic!("Unexpected number of arguments"), } @@ -161,7 +161,7 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int match nargs { 1 => { let layer = i32_from_stack!(state, -nargs); - ctx.layers().set_draw_layer(layer, 0); + ctx.recorder().set_draw_layer(layer, 0); } 2 => { let layer = match unsafe { ffi::lua_type(state, -nargs) } { @@ -174,9 +174,9 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int }; let sublayer = i32_from_stack!(state, -nargs + 1); if let Some(layer) = layer { - ctx.layers().set_draw_layer(layer, sublayer); + ctx.recorder().set_draw_layer(layer, sublayer); } else { - ctx.layers().set_draw_sublayer(sublayer); + ctx.recorder().set_draw_sublayer(sublayer); } } _ => panic!("Unexpected number of arguments"), @@ -216,9 +216,9 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { let u2 = f32_from_stack!(state, -nargs + i + 2); let v2 = f32_from_stack!(state, -nargs + i + 3); i += 4; - Rect::new(Point::new(u1, v1), Point::new(u2, v2)) + Some(Rect::new(Point::new(u1, v1), Point::new(u2, v2))) } else { - Rect::default_uv() + None }; let layer_idx = if parse_layer_idx { @@ -228,7 +228,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { 0 }; - ctx.layers().draw_rect(texture_id, rect, uv, layer_idx); + ctx.recorder().draw_image(rect, texture_id, uv, layer_idx); 0 } @@ -277,14 +277,14 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int let u4 = f32_from_stack!(state, -nargs + i + 6); let v4 = f32_from_stack!(state, -nargs + i + 7); i += 8; - Quad::new( + Some(Quad::new( Point::new(u1, v1), Point::new(u2, v2), Point::new(u3, v3), Point::new(u4, v4), - ) + )) } else { - Quad::default_uv() + None }; let layer_idx = if parse_layer_idx { @@ -294,7 +294,8 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int 0 }; - ctx.layers().draw_quad(texture_id, quad, uv, layer_idx); + ctx.recorder() + .draw_image_quad(quad, texture_id, uv, layer_idx); 0 } @@ -320,7 +321,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { panic!("Invalid font type"); }; - let mut position = Point::new(x, y); + let mut position = LogicalPoint::new(x, y); let mut is_absolute_position = false; // the position needs to be adjusted for some alignments to match PoBs behavior let screen_size = ctx.window().logical_size(); @@ -340,7 +341,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { PoBTextAlignment::RightX => Alignment::Max, }; - let current_draw_color = ctx.layers().get_draw_color(); + let current_draw_color = ctx.recorder().get_draw_color(); let job = build_layout_job( text, current_draw_color, @@ -352,12 +353,32 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { // NOTE: color escape codes modify the current draw color. // set current draw color to color of last segment to match PoB's behavior if let Some(last_segment) = job.segments.last() { - ctx.layers().set_draw_color(last_segment.color); + ctx.recorder().set_draw_color(last_segment.color); } + // TODO: align to physical grid? + // + // Make sure the layout origin aligns with the physical pixel grid so + // that each glyph aligns correctly. Glyphs are positioned relative + // to the layout origin and assume that it ends up on the start of + // a physical pixel. + /* + let position = position + .to_physical::(pixels_per_point) + .round() + .to_logical(pixels_per_point); + */ + let layout = ctx.fonts().layout(job, ctx.window().scale_factor()); - ctx.layers() - .draw_text(position, layout, is_absolute_position); + for glyph in &layout.glyphs { + ctx.recorder().draw_glyph( + glyph.rect.translate(position.to_vector()), + glyph.uv, + glyph.color, + glyph.layer_idx, + is_absolute_position, + ); + } 0 } @@ -378,7 +399,8 @@ unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_in }; let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None); - let width = ctx.fonts().get_text_width(job, ctx.window().scale_factor()); + let layout = ctx.fonts().layout(job, ctx.window().scale_factor()); + let width = layout.width(); unsafe { ffi::lua_pushnumber(state, width as f64) }; 1 @@ -394,11 +416,8 @@ fn get_index_at_cur( let font_type = font_type.parse::()?; let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None); - let index_stripped = ctx.fonts().get_text_index_at_cursor( - job, - Point::new(cur_x, cur_y), - ctx.window().scale_factor(), - ); + let layout = ctx.fonts().layout(job, ctx.window().scale_factor()); + let index_stripped = layout.cursor_index_at(Point::new(cur_x, cur_y)); // build_layout_job() strips all color escape strings from the original string. The // resulting [`LayoutJob`] is then passed to get_text_index_at_cursor() which returns an diff --git a/src/app.rs b/src/app.rs index 67acd61..e3b7bfb 100644 --- a/src/app.rs +++ b/src/app.rs @@ -114,10 +114,9 @@ impl App { { RenderJob::Skip } else { - let meshes = self.tessellator.convert_clipped_primitives( - mode_output.primitives, - self.state.window.scale_factor(), - ); + let meshes = self + .tessellator + .convert_draw_commands(mode_output.draw_commands); RenderJob::Render { meshes, diff --git a/src/draw_commands.rs b/src/draw_commands.rs new file mode 100644 index 0000000..809cec5 --- /dev/null +++ b/src/draw_commands.rs @@ -0,0 +1,185 @@ +use std::{ + collections::BTreeMap, + hash::{Hash, Hasher}, +}; + +use ahash::AHasher; +use euclid::Size2D; +use ordered_float::OrderedFloat; + +use crate::{ + color::Srgba, + dpi::{LogicalQuad, LogicalRect, LogicalSize, NormalizedQuad, NormalizedRect, Uv}, + math::{Point, Quad, Rect}, + renderer::textures::TextureId, +}; + +#[derive(Copy, Clone, Debug)] +pub struct DrawCommand { + pub positions: LogicalQuad, + pub uvs: NormalizedQuad, + pub color: Srgba, + pub texture_id: TextureId, + pub texture_layer_idx: u32, + pub clip_rect: LogicalRect, +} + +impl Hash for DrawCommand { + fn hash(&self, state: &mut H) { + hash_quad(&self.positions, state); + hash_quad(&self.uvs, state); + self.color.hash(state); + self.texture_id.hash(state); + self.texture_layer_idx.hash(state); + hash_rect(&self.clip_rect, state); + } +} + +#[inline] +fn hash_quad(quad: &Quad, state: &mut H) { + hash_point(&quad.p0, state); + hash_point(&quad.p1, state); + hash_point(&quad.p2, state); + hash_point(&quad.p3, state); +} + +#[inline] +fn hash_rect(rect: &Rect, state: &mut H) { + hash_point(&rect.min, state); + hash_point(&rect.max, state); +} + +#[inline] +fn hash_point(point: &Point, state: &mut H) { + OrderedFloat(point.x).hash(state); + OrderedFloat(point.y).hash(state); +} + +#[derive(Default)] +pub struct DrawCommandRecorder { + layers: BTreeMap<(i32, i32), Vec>, + current_layer: (i32, i32), + current_viewport: LogicalRect, + current_draw_color: Srgba, + hasher: AHasher, +} + +impl DrawCommandRecorder { + fn push(&mut self, cmd: DrawCommand) { + cmd.hash(&mut self.hasher); + self.layers.entry(self.current_layer).or_default().push(cmd); + } + + pub fn reset(&mut self) { + for layer in self.layers.values_mut() { + layer.clear(); + } + self.current_layer = (0, 0); + self.current_viewport = LogicalRect::from_size(Size2D::new(f32::INFINITY, f32::INFINITY)); + self.current_draw_color = Srgba::WHITE; + self.hasher = AHasher::default(); + } + + pub fn set_viewport(&mut self, viewport: LogicalRect) { + self.current_viewport = viewport; + } + + pub fn set_viewport_from_size(&mut self, size: LogicalSize) { + self.set_viewport(LogicalRect::from_size(size).cast()); + } + + pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) { + self.current_layer = (layer, sublayer); + } + + pub fn set_draw_sublayer(&mut self, sublayer: i32) { + self.set_draw_layer(self.current_layer.0, sublayer); + } + + pub fn set_draw_color(&mut self, color: Srgba) { + self.current_draw_color = color; + } + + pub fn get_draw_color(&self) -> Srgba { + self.current_draw_color + } + + pub fn draw_image( + &mut self, + rect: LogicalRect, + texture_id: Option, + uv: Option, + layer_idx: u32, + ) { + let (texture_id, uvs, texture_layer_idx) = match texture_id { + Some(texture_id) => ( + texture_id, + uv.map_or(NormalizedQuad::default_uv(), |uv_rect| uv_rect.into()), + layer_idx, + ), + None => (TextureId::default(), NormalizedQuad::white_uv(), 0), + }; + + self.push(DrawCommand { + positions: rect.translate(self.current_viewport.min.to_vector()).into(), + uvs, + color: self.current_draw_color, + texture_id, + texture_layer_idx, + clip_rect: self.current_viewport, + }); + } + + pub fn draw_image_quad( + &mut self, + quad: LogicalQuad, + texture_id: Option, + uv: Option, + layer_idx: u32, + ) { + let (texture_id, uvs, texture_layer_idx) = match texture_id { + Some(texture_id) => ( + texture_id, + uv.unwrap_or(NormalizedQuad::default_uv()), + layer_idx, + ), + None => (TextureId::default(), NormalizedQuad::white_uv(), 0), + }; + + self.push(DrawCommand { + positions: quad.translate(self.current_viewport.min.to_vector()), + uvs, + color: self.current_draw_color, + texture_id, + texture_layer_idx, + clip_rect: self.current_viewport, + }); + } + + pub fn draw_glyph( + &mut self, + rect: LogicalRect, + uv: NormalizedRect, + color: Srgba, + layer_idx: u32, + is_absolute_position: bool, + ) { + if !is_absolute_position { + rect.translate(self.current_viewport.min.to_vector()); + } + + self.push(DrawCommand { + positions: rect.translate(self.current_viewport.min.to_vector()).into(), + uvs: uv.into(), + color, + // font atlas always lives at default texture ID + texture_id: TextureId::default(), + texture_layer_idx: layer_idx, + clip_rect: self.current_viewport, + }); + } + + pub fn finish(&mut self) -> (u64, &BTreeMap<(i32, i32), Vec>) { + (self.hasher.finish(), &self.layers) + } +} diff --git a/src/fonts.rs b/src/fonts.rs index 54a9f94..fa226d9 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -1,8 +1,9 @@ use crate::{ color::Srgba, - dpi::{LogicalPoint, LogicalVector}, + dpi::LogicalVector, fonts::{ - atlas::FontAtlas, glyph_key::SubpixelBin, layout::LayoutRow, rasterizer::GlyphRasterizer, + atlas::FontAtlas, glyph_key::SubpixelBin, layout::PositionedGlyph, + layout_cache::LayoutCache, rasterizer::GlyphRasterizer, }, renderer::image::ImageDelta, util::calculate_hash, @@ -13,13 +14,14 @@ use parley::{ FontContext, FontFamily, FontFamilyName, FontWeight, GenericFamily, LayoutContext, StyleProperty, TextStyle, fontique::Blob, }; -use std::sync::Arc; +use std::{rc::Rc, sync::Arc}; pub use layout::{Alignment, FontStyle, Layout, LayoutJob}; mod atlas; mod glyph_key; mod layout; +mod layout_cache; mod rasterizer; /// Data of a .ttf or .otf file @@ -65,7 +67,7 @@ impl Fonts { layout_context: LayoutContext::new(), atlas: FontAtlas::new(1024, 1024), glyph_rasterizer: GlyphRasterizer::new(), - layout_cache: LayoutCache::default(), + layout_cache: Default::default(), }; fonts.register_fonts(); @@ -182,13 +184,21 @@ impl Fonts { } } - pub fn layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Arc { + pub fn layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Rc { let hash = calculate_hash(&(&job, OrderedFloat(pixels_per_point))); if let Some(cached_layout) = self.layout_cache.get(hash) { return cached_layout; } + let layout = Rc::new(self.build_layout(job, pixels_per_point)); + + self.layout_cache.insert(hash, Rc::clone(&layout)); + + layout + } + + fn build_layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Layout { let default_style = TextStyle::default(); let style = TextStyle { font_family: job.font_family, @@ -233,13 +243,9 @@ impl Fonts { parley_layout.align(alignment, parley::AlignmentOptions::default()); } - let mut layout_rows = Vec::new(); - let mut num_of_vertices = 0; - let mut num_of_indices = 0; + let mut glyphs = Vec::new(); for line in parley_layout.lines() { - let mut layout_row = LayoutRow::default(); - for item in line.items() { let parley::PositionedLayoutItem::GlyphRun(run) = item else { continue; @@ -255,85 +261,20 @@ impl Fonts { continue; }; - layout_row.glyphs.push(glyph); - num_of_vertices += 4; - num_of_indices += 6; + glyphs.push(PositionedGlyph { + rect: glyph.rect, + uv: glyph.uv, + layer_idx: glyph.texture_layer_idx, + color: glyph.color, + }); } } - - if !layout_row.glyphs.is_empty() { - layout_rows.push(layout_row); - } } - let layout = Arc::new(Layout { - job_hash: hash, + Layout { + width: parley_layout.width(), + glyphs, parley_layout, - rows: layout_rows, - num_of_vertices, - num_of_indices, - }); - - self.layout_cache.insert(hash, Arc::clone(&layout)); - - layout - } - - /// Width of laid out text - pub fn get_text_width(&mut self, job: LayoutJob, pixels_per_point: f32) -> i32 { - let layout = self.layout(job, pixels_per_point); - layout.width() as i32 - } - - /// Text index at cursor location - pub fn get_text_index_at_cursor( - &mut self, - job: LayoutJob, - cursor: LogicalPoint, - pixels_per_point: f32, - ) -> usize { - let layout = self.layout(job, pixels_per_point); - layout.cursor_index(cursor) - } -} - -struct CachedLayout { - generation: u32, - layout: Arc, -} - -#[derive(Default)] -struct LayoutCache { - current_generation: u32, - cache: nohash_hasher::IntMap, -} - -impl LayoutCache { - fn get(&mut self, hash: u64) -> Option> { - match self.cache.entry(hash) { - std::collections::hash_map::Entry::Occupied(entry) => { - let cached = entry.into_mut(); - cached.generation = self.current_generation; - Some(Arc::clone(&cached.layout)) - } - std::collections::hash_map::Entry::Vacant(_) => None, } } - - fn insert(&mut self, hash: u64, layout: Arc) { - self.cache.insert( - hash, - CachedLayout { - generation: self.current_generation, - layout, - }, - ); - } - - /// Removes unused layouts - pub fn flush(&mut self) { - self.cache - .retain(|_key, cached| cached.generation == self.current_generation); - self.current_generation = self.current_generation.wrapping_add(1); - } } diff --git a/src/fonts/layout.rs b/src/fonts/layout.rs index c08d565..0e6ce14 100644 --- a/src/fonts/layout.rs +++ b/src/fonts/layout.rs @@ -1,4 +1,7 @@ -use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph}; +use crate::{ + color::Srgba, + dpi::{LogicalPoint, LogicalRect, NormalizedRect}, +}; use ordered_float::OrderedFloat; use parley::{FontFamily, FontFamilyName}; @@ -99,33 +102,28 @@ impl std::hash::Hash for LayoutJob<'_> { } } -#[derive(Default)] -pub struct LayoutRow { - pub glyphs: Vec, +pub struct PositionedGlyph { + // relative to layout origin + // TODO: introduce new "layout space"? + pub rect: LogicalRect, + pub uv: NormalizedRect, + pub layer_idx: u32, + pub color: Srgba, } pub struct Layout { - pub job_hash: u64, + pub glyphs: Vec, + pub width: f32, + // kept for parley's cursor helper pub parley_layout: parley::Layout, - pub rows: Vec, - pub num_of_vertices: usize, - pub num_of_indices: usize, } impl Layout { pub fn width(&self) -> f32 { - self.parley_layout.full_width() + self.width } - /// Returns text index at cursor position - pub fn cursor_index(&self, cursor: LogicalPoint) -> usize { - let cursor = parley::Cursor::from_point(&self.parley_layout, cursor.x, cursor.y); - cursor.index() - } -} - -impl std::hash::Hash for Layout { - fn hash(&self, state: &mut H) { - self.job_hash.hash(state); + pub fn cursor_index_at(&self, point: LogicalPoint) -> usize { + parley::Cursor::from_point(&self.parley_layout, point.x, point.y).index() } } diff --git a/src/fonts/layout_cache.rs b/src/fonts/layout_cache.rs new file mode 100644 index 0000000..428938b --- /dev/null +++ b/src/fonts/layout_cache.rs @@ -0,0 +1,45 @@ +use std::rc::Rc; + +use crate::fonts::Layout; + +struct CachedLayout { + layout: Rc, + // used to identify unused layouts + generation: u32, +} + +#[derive(Default)] +pub struct LayoutCache { + cache: nohash_hasher::IntMap, + current_generation: u32, +} + +impl LayoutCache { + pub fn get(&mut self, hash: u64) -> Option> { + match self.cache.entry(hash) { + std::collections::hash_map::Entry::Occupied(entry) => { + let cached = entry.into_mut(); + cached.generation = self.current_generation; + Some(Rc::clone(&cached.layout)) + } + std::collections::hash_map::Entry::Vacant(_) => None, + } + } + + pub fn insert(&mut self, hash: u64, layout: Rc) { + self.cache.insert( + hash, + CachedLayout { + generation: self.current_generation, + layout, + }, + ); + } + + /// Removes unused layouts + pub fn flush(&mut self) { + self.cache + .retain(|_key, cached| cached.generation == self.current_generation); + self.current_generation = self.current_generation.wrapping_add(1); + } +} diff --git a/src/installer.rs b/src/installer.rs index 1a4246f..acd6cfb 100644 --- a/src/installer.rs +++ b/src/installer.rs @@ -3,13 +3,14 @@ use crate::{ args::Game, color::Srgba, dpi::{LogicalPoint, LogicalRect}, + draw_commands::DrawCommand, fonts::{Alignment, FontStyle, LayoutJob}, installer::download::{ DownloadEvent, ExtractionRule, build_client, download_and_extract_tarball, download_file_to_disk, fetch_file_contents, }, mode::{AppEvent, ModeFrameOutput, ModeTransition}, - renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive}, + renderer::textures::TextureId, util::replace_in_matching_lines, }; use parley::{FontFamily, FontFamilyName, GenericFamily}; @@ -67,10 +68,10 @@ impl InstallMode { } pub fn frame(&mut self, app_state: &mut AppState) -> anyhow::Result { - let primitives = self.draw_current_progress(app_state); + let draw_commands = self.draw_current_progress(app_state); Ok(ModeFrameOutput { - primitives, + draw_commands, can_elide: false, should_continue: true, }) @@ -106,10 +107,12 @@ impl InstallMode { Ok(()) } - fn draw_current_progress( - &self, - app_state: &mut AppState, - ) -> Box> { + fn draw_current_progress(&self, app_state: &mut AppState) -> Vec { + let mut draw_commands = Vec::new(); + + let screen_size = app_state.window.logical_size().cast::(); + let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0); + let mut job = LayoutJob::new( FontFamily::Single(FontFamilyName::Generic(GenericFamily::SansSerif)), 32.0, @@ -122,18 +125,19 @@ impl InstallMode { job.append(&self.status, Srgba::WHITE); let layout = app_state.fonts.layout(job, app_state.window.scale_factor()); + for glyph in &layout.glyphs { + draw_commands.push(DrawCommand { + positions: glyph.rect.translate(pos.to_vector()).into(), + uvs: glyph.uv.into(), + color: glyph.color, + // font atlas always lives at default texture ID + texture_id: TextureId::default(), + texture_layer_idx: glyph.layer_idx, + clip_rect: LogicalRect::from_size(app_state.window.logical_size().cast()), + }); + } - let screen_size = app_state.window.logical_size().cast::(); - let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0); - - let primitive = TextPrimitive::new(pos, layout); - - let clipped_primitive = ClippedPrimitive { - clip_rect: LogicalRect::from_size(app_state.window.logical_size().cast()), - primitive: DrawPrimitive::Text(primitive), - }; - - Box::new(vec![clipped_primitive].into_iter()) + draw_commands } } diff --git a/src/layers.rs b/src/layers.rs deleted file mode 100644 index 8ded933..0000000 --- a/src/layers.rs +++ /dev/null @@ -1,153 +0,0 @@ -use std::collections::BTreeMap; - -use crate::{ - color::Srgba, - dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, NormalizedQuad, NormalizedRect}, - fonts::Layout, - renderer::{ - primitives::{ - ClippedPrimitive, DrawPrimitive, QuadPrimitive, QuadTexture, RectPrimitive, - RectTexture, TextPrimitive, - }, - textures::TextureId, - }, - util::calculate_hash, -}; - -/// Holds the draw primitives for each layer. -/// -/// Adding a primitive places it in currently set layer. Positions are interpreted as being relative to -/// the current viewport. They are translated into absolute positions (screen positions) and -/// clipped by the viewport. -#[derive(Default)] -pub struct Layers { - layers: BTreeMap<(i32, i32), Vec>, - current_layer: (i32, i32), - viewport: LogicalRect, - current_draw_color: Srgba, -} - -impl Layers { - pub fn reset(&mut self) { - self.current_layer = (0, 0); - self.layers.clear(); - self.current_draw_color = Srgba::TRANSPARENT; - } - - /// Consume primitives and return an iterator over them in drawing order. - pub fn consume_layers(&mut self) -> Box> { - let layers = std::mem::take(&mut self.layers); - Box::new(layers.into_values().flatten()) - } - - pub fn set_viewport(&mut self, viewport: LogicalRect) { - self.viewport = viewport; - } - - pub fn set_viewport_from_size(&mut self, size: LogicalSize) { - self.set_viewport(LogicalRect::from_size(size).cast()); - } - - pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) { - self.current_layer = (layer, sublayer); - } - - pub fn set_draw_sublayer(&mut self, sublayer: i32) { - self.set_draw_layer(self.current_layer.0, sublayer); - } - - pub fn set_draw_color(&mut self, color: Srgba) { - self.current_draw_color = color; - } - - pub fn get_draw_color(&self) -> Srgba { - self.current_draw_color - } - - pub fn draw_rect( - &mut self, - texture_id: Option, - rect: LogicalRect, - uv: NormalizedRect, - layer_idx: u32, - ) { - let texture = texture_id.map(|id| RectTexture::new(id, uv, layer_idx)); - let primitive = RectPrimitive::new(rect, self.current_draw_color, texture); - self.add_rect(primitive); - } - - pub fn draw_quad( - &mut self, - texture_id: Option, - quad: LogicalQuad, - uv: NormalizedQuad, - layer_idx: u32, - ) { - let texture = texture_id.map(|id| QuadTexture::new(id, uv, layer_idx)); - let primitive = QuadPrimitive::new(quad, self.current_draw_color, texture); - self.add_quad(primitive); - } - - pub fn draw_text( - &mut self, - position: LogicalPoint, - layout: std::sync::Arc, - is_absolute_position: bool, - ) { - let primitive = TextPrimitive::new(position, layout); - self.add_text(primitive, is_absolute_position); - } - - pub fn add_rect(&mut self, mut rect: RectPrimitive) { - rect.translate(self.viewport.min.to_vector()); - - let clipped_primitive = ClippedPrimitive { - clip_rect: self.viewport, - primitive: DrawPrimitive::Rect(rect), - }; - - self.push(clipped_primitive); - } - - pub fn add_quad(&mut self, mut quad: QuadPrimitive) { - quad.translate(self.viewport.min.to_vector()); - - let clipped_primitive = ClippedPrimitive { - clip_rect: self.viewport, - primitive: DrawPrimitive::Quad(quad), - }; - - self.push(clipped_primitive); - } - - pub fn add_text(&mut self, mut text: TextPrimitive, is_absolute_position: bool) { - if !is_absolute_position { - text.translate(self.viewport.min.to_vector()); - } - - let clipped_primitive = ClippedPrimitive { - clip_rect: self.viewport, - primitive: DrawPrimitive::Text(text), - }; - - self.push(clipped_primitive); - } - - #[inline] - fn push(&mut self, clipped_primitive: ClippedPrimitive) { - self.layers - .entry(self.current_layer) - .or_default() - .push(clipped_primitive); - } - - pub fn get_hash(&self) -> u64 { - calculate_hash(self) - } -} - -impl std::hash::Hash for Layers { - fn hash(&self, state: &mut H) { - self.layers.hash(state); - } -} diff --git a/src/lua.rs b/src/lua.rs index 8db5ae9..f66600a 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -2,9 +2,9 @@ use crate::{ api::{self, get_callback}, app::AppState, args::Args, + draw_commands::DrawCommandRecorder, fonts::Fonts, input::InputState, - layers::Layers, pob::PoBState, renderer::textures::WrappedTextureManager, subscript::{NativeMultiValue, SubscriptManager, SubscriptResult, register_subscript_globals}, @@ -50,7 +50,7 @@ pub struct Context { texture_manager: Cell<*mut WrappedTextureManager>, script_dir: Cell<*const PathBuf>, current_working_dir: Cell<*mut PathBuf>, - layers: Cell<*mut Layers>, + recorder: Cell<*mut DrawCommandRecorder>, needs_restart: Cell<*mut bool>, should_exit: Cell<*mut bool>, is_dpi_aware: Cell<*mut bool>, @@ -65,7 +65,7 @@ impl Context { texture_manager: Cell::new(std::ptr::null_mut()), script_dir: Cell::new(std::ptr::null()), current_working_dir: Cell::new(std::ptr::null_mut()), - layers: Cell::new(std::ptr::null_mut()), + recorder: Cell::new(std::ptr::null_mut()), needs_restart: Cell::new(std::ptr::null_mut()), should_exit: Cell::new(std::ptr::null_mut()), is_dpi_aware: Cell::new(std::ptr::null_mut()), @@ -80,7 +80,7 @@ impl Context { self.script_dir.set(&ctx.app.script_dir); self.current_working_dir .set(&mut ctx.pob.current_working_dir); - self.layers.set(&mut ctx.pob.layers); + self.recorder.set(&mut ctx.pob.recorder); self.needs_restart.set(&mut ctx.pob.needs_restart); self.should_exit.set(&mut ctx.app.should_exit); self.is_dpi_aware.set(&mut ctx.pob.is_dpi_aware); @@ -93,7 +93,7 @@ impl Context { self.texture_manager.set(std::ptr::null_mut()); self.script_dir.set(std::ptr::null()); self.current_working_dir.set(std::ptr::null_mut()); - self.layers.set(std::ptr::null_mut()); + self.recorder.set(std::ptr::null_mut()); self.needs_restart.set(std::ptr::null_mut()); self.should_exit.set(std::ptr::null_mut()); self.is_dpi_aware.set(std::ptr::null_mut()); @@ -105,7 +105,7 @@ impl Context { ctx_accessor!(texture_manager: &mut WrappedTextureManager); ctx_accessor!(script_dir: &PathBuf); ctx_accessor!(current_working_dir: &mut PathBuf); - ctx_accessor!(layers: &mut Layers); + ctx_accessor!(recorder: &mut DrawCommandRecorder); ctx_accessor!(needs_restart: &mut bool); ctx_accessor!(should_exit: &mut bool); ctx_accessor!(is_dpi_aware: &mut bool); diff --git a/src/main.rs b/src/main.rs index c3a15b7..954a3f1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,11 +9,11 @@ mod args; mod clipboard; mod color; mod dpi; +mod draw_commands; mod fonts; mod gfx; mod input; mod installer; -mod layers; mod lua; mod math; mod mode; diff --git a/src/math/quad.rs b/src/math/quad.rs index ed85cc1..8796f87 100644 --- a/src/math/quad.rs +++ b/src/math/quad.rs @@ -1,4 +1,4 @@ -use crate::math::{Point, Size, Vector}; +use crate::math::{Corners, Point, Rect, Size, Vector}; use bytemuck::{Pod, Zeroable}; use euclid::num::Zero; use std::fmt; @@ -121,3 +121,17 @@ where Self::new(self.p0 + by, self.p1 + by, self.p2 + by, self.p3 + by) } } + +impl From> for Quad +where + T: Copy, +{ + fn from(value: Rect) -> Self { + Self::new( + value.top_left(), + value.top_right(), + value.bottom_right(), + value.bottom_left(), + ) + } +} diff --git a/src/mode.rs b/src/mode.rs index 9203445..b70369c 100644 --- a/src/mode.rs +++ b/src/mode.rs @@ -1,6 +1,4 @@ -use crate::{ - app::AppState, installer::InstallMode, pob::PoBMode, renderer::primitives::ClippedPrimitive, -}; +use crate::{app::AppState, draw_commands::DrawCommand, installer::InstallMode, pob::PoBMode}; use winit::{event::MouseButton, keyboard::Key}; pub enum AppEvent { @@ -32,7 +30,7 @@ pub enum ModeTransition { } pub struct ModeFrameOutput { - pub primitives: Box>, + pub draw_commands: Vec, pub can_elide: bool, /// Indicates that this should be redrawn again next frame even if user is not interacting with /// window diff --git a/src/pob.rs b/src/pob.rs index a219e21..a9a613c 100644 --- a/src/pob.rs +++ b/src/pob.rs @@ -1,15 +1,15 @@ use crate::{ app::AppState, dpi::{LogicalRect, LogicalSize}, + draw_commands::DrawCommandRecorder, input::{key_as_str, mousebutton_as_str}, - layers::Layers, lua::{LuaInstance, PoBContext, PoBEvent}, mode::{AppEvent, ModeFrameOutput, ModeTransition}, }; use std::path::PathBuf; pub struct PoBState { - pub layers: Layers, + pub recorder: DrawCommandRecorder, pub current_working_dir: PathBuf, pub needs_restart: bool, pub is_dpi_aware: bool, @@ -28,7 +28,7 @@ pub struct PoBMode { impl PoBMode { pub fn new(app_state: &mut AppState) -> anyhow::Result { let mut state = PoBState { - layers: Layers::default(), + recorder: DrawCommandRecorder::default(), current_working_dir: PathBuf::default(), needs_restart: false, is_dpi_aware: false, @@ -51,7 +51,7 @@ impl PoBMode { profiling::scope!("frame"); // reset layers and viewport - self.state.layers.reset(); + self.state.recorder.reset(); self.reset_viewport(app_state.window.logical_size()); let mut ctx = PoBContext::new(app_state, &mut self.state); @@ -60,11 +60,12 @@ impl PoBMode { self.lua_instance.handle_subscripts(&mut ctx); // run PoB's draw code. - // this will "fill up" up the layers with draw primitives + // this will "fill up" up the layers with draw commands self.lua_instance.handle_event(PoBEvent::Frame, &mut ctx)?; // check if draw prmitives are identical to primitives from last frame - let layers_hash = self.state.layers.get_hash(); + let (layers_hash, layers) = self.state.recorder.finish(); + //let layers_hash = self.state.layers.get_hash(); let identical = layers_hash == self.previous_layers_hash; self.previous_layers_hash = layers_hash; @@ -73,7 +74,7 @@ impl PoBMode { let should_continue = has_active_subscript || has_active_coroutine; Ok(ModeFrameOutput { - primitives: self.state.layers.consume_layers(), + draw_commands: layers.values().flatten().copied().collect(), can_elide: identical, should_continue, }) @@ -154,7 +155,7 @@ impl PoBMode { fn reset_viewport(&mut self, size: LogicalSize) { self.state - .layers + .recorder .set_viewport(LogicalRect::from_size(size).cast()); } } diff --git a/src/renderer.rs b/src/renderer.rs index e531845..6b2632c 100644 --- a/src/renderer.rs +++ b/src/renderer.rs @@ -14,7 +14,6 @@ use wgpu::util::DeviceExt; pub mod image; pub mod mesh; mod mipmap; -pub mod primitives; pub mod tessellator; pub mod textures; diff --git a/src/renderer/mesh.rs b/src/renderer/mesh.rs index a6ae526..02eaf4a 100644 --- a/src/renderer/mesh.rs +++ b/src/renderer/mesh.rs @@ -14,8 +14,6 @@ pub struct Vertex { pub uv: NormalizedPoint, pub color: Srgba, /// Index into texture array - /// TODO: Remove from Vertex and put into Mesh. Use push constant to set index - /// before each draw call. Not sure if actually faster, profiling needed. pub layer_idx: u32, } @@ -27,6 +25,7 @@ pub struct Mesh { } impl Mesh { + #[allow(dead_code)] #[inline] pub fn add_rect( &mut self, diff --git a/src/renderer/primitives.rs b/src/renderer/primitives.rs deleted file mode 100644 index 30706c0..0000000 --- a/src/renderer/primitives.rs +++ /dev/null @@ -1,192 +0,0 @@ -use crate::{ - color::Srgba, - dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalVector, NormalizedQuad, NormalizedRect}, - fonts::Layout, - math::Point, - renderer::textures::TextureId, -}; -use ordered_float::OrderedFloat; -use std::{ - hash::{Hash, Hasher}, - sync::Arc, -}; - -#[derive(Clone)] -pub struct ClippedPrimitive { - pub clip_rect: LogicalRect, - pub primitive: DrawPrimitive, -} - -impl Hash for ClippedPrimitive { - fn hash(&self, state: &mut H) { - hash_pos(&self.clip_rect.min, state); - hash_pos(&self.clip_rect.max, state); - self.primitive.hash(state); - } -} - -#[derive(Clone, Hash)] -pub enum DrawPrimitive { - Rect(RectPrimitive), - Quad(QuadPrimitive), - Text(TextPrimitive), -} - -impl DrawPrimitive { - pub fn texture_id(&self) -> TextureId { - match self { - Self::Rect(rect_primitive) => rect_primitive - .texture - .map_or_else(TextureId::default, |tex| tex.texture_id), - Self::Quad(quad_primitive) => quad_primitive - .texture - .map_or_else(TextureId::default, |tex| tex.texture_id), - Self::Text(_) => TextureId::default(), - } - } -} - -#[derive(Clone, Copy)] -pub struct RectPrimitive { - pub rect: LogicalRect, - pub color: Srgba, - pub texture: Option, -} - -impl RectPrimitive { - pub fn new(rect: LogicalRect, color: Srgba, texture: Option) -> Self { - Self { - rect, - color, - texture, - } - } - - pub fn translate(&mut self, direction: LogicalVector) { - self.rect = self.rect.translate(direction); - } -} - -impl Hash for RectPrimitive { - fn hash(&self, state: &mut H) { - hash_pos(&self.rect.min, state); - hash_pos(&self.rect.max, state); - self.color.hash(state); - self.texture.hash(state); - } -} - -#[derive(Clone, Copy)] -pub struct RectTexture { - pub texture_id: TextureId, - pub uv: NormalizedRect, - pub layer_idx: u32, -} - -impl RectTexture { - pub fn new(texture_id: TextureId, uv: NormalizedRect, layer_idx: u32) -> Self { - Self { - texture_id, - uv, - layer_idx, - } - } -} - -impl Hash for RectTexture { - fn hash(&self, state: &mut H) { - self.texture_id.hash(state); - hash_pos(&self.uv.min, state); - hash_pos(&self.uv.max, state); - self.layer_idx.hash(state); - } -} - -#[derive(Clone, Copy)] -pub struct QuadPrimitive { - pub quad: LogicalQuad, - pub color: Srgba, - pub texture: Option, -} - -impl QuadPrimitive { - pub fn new(quad: LogicalQuad, color: Srgba, texture: Option) -> Self { - Self { - quad, - color, - texture, - } - } - - pub fn translate(&mut self, direction: LogicalVector) { - self.quad = self.quad.translate(direction); - } -} - -impl Hash for QuadPrimitive { - fn hash(&self, state: &mut H) { - hash_pos(&self.quad.p0, state); - hash_pos(&self.quad.p1, state); - hash_pos(&self.quad.p2, state); - hash_pos(&self.quad.p3, state); - self.color.hash(state); - self.texture.hash(state); - } -} - -#[derive(Clone, Copy)] -pub struct QuadTexture { - pub texture_id: TextureId, - pub uv: NormalizedQuad, - pub layer_idx: u32, -} - -impl QuadTexture { - pub fn new(texture_id: TextureId, uv: NormalizedQuad, layer_idx: u32) -> Self { - Self { - texture_id, - uv, - layer_idx, - } - } -} - -impl Hash for QuadTexture { - fn hash(&self, state: &mut H) { - self.texture_id.hash(state); - hash_pos(&self.uv.p0, state); - hash_pos(&self.uv.p1, state); - hash_pos(&self.uv.p2, state); - hash_pos(&self.uv.p3, state); - self.layer_idx.hash(state); - } -} - -#[derive(Clone)] -pub struct TextPrimitive { - pub pos: LogicalPoint, - pub layout: Arc, -} - -impl TextPrimitive { - pub fn new(pos: LogicalPoint, layout: Arc) -> Self { - Self { pos, layout } - } - - #[inline(always)] - pub fn translate(&mut self, direction: LogicalVector) { - self.pos += direction; - } -} - -impl Hash for TextPrimitive { - fn hash(&self, state: &mut H) { - hash_pos(&self.pos, state); - self.layout.hash(state); - } -} - -fn hash_pos(pos: &Point, state: &mut H) { - OrderedFloat(pos.x).hash(state); - OrderedFloat(pos.y).hash(state); -} diff --git a/src/renderer/tessellator.rs b/src/renderer/tessellator.rs index 2cac38d..4d92086 100644 --- a/src/renderer/tessellator.rs +++ b/src/renderer/tessellator.rs @@ -1,13 +1,6 @@ use crate::{ - dpi::{ConvertToLogical, ConvertToPhysical, NormalizedQuad, NormalizedRect, Uv}, - renderer::{ - mesh::{ClippedMesh, Mesh}, - primitives::{ - ClippedPrimitive, DrawPrimitive, QuadPrimitive, QuadTexture, RectPrimitive, - RectTexture, TextPrimitive, - }, - textures::TextureId, - }, + draw_commands::DrawCommand, + renderer::mesh::{ClippedMesh, Mesh}, }; /// Converts [`DrawPrimitive`]s into [`Mesh`]es. @@ -17,37 +10,32 @@ pub struct Tessellator { } impl Tessellator { - pub fn convert_clipped_primitives( - &mut self, - clipped_primitives: impl Iterator, - pixels_per_point: f32, - ) -> Vec { + pub fn convert_draw_commands(&mut self, draw_commands: Vec) -> Vec { profiling::scope!("convert_primitives"); let mut clipped_meshes = Vec::with_capacity(self.last_clipped_meshes_size); - for clipped_primitive in clipped_primitives { - self.convert_clipped_primitive( - clipped_primitive, - pixels_per_point, - &mut clipped_meshes, - ); + for cmd in draw_commands { + self.convert_draw_command(cmd, &mut clipped_meshes); } self.last_clipped_meshes_size = clipped_meshes.len(); clipped_meshes } - pub fn convert_clipped_primitive( + pub fn convert_draw_command( &mut self, - clipped_primitive: ClippedPrimitive, - pixels_per_point: f32, + cmd: DrawCommand, out_clipped_meshes: &mut Vec, ) { - let ClippedPrimitive { + let DrawCommand { + positions, + uvs, + color, + texture_id, + texture_layer_idx, clip_rect, - primitive, - } = clipped_primitive; + } = cmd; if clip_rect.is_empty() { return; @@ -57,7 +45,7 @@ impl Tessellator { // append to previous mesh if clip_rect and texture_id match. // otherwise, start a new mesh. !(last_clipped_mesh.clip_rect == clip_rect - && last_clipped_mesh.mesh.texture_id == primitive.texture_id()) + && last_clipped_mesh.mesh.texture_id == texture_id) }); if start_new_mesh { @@ -69,21 +57,10 @@ impl Tessellator { let last_clipped_mesh = out_clipped_meshes.last_mut().unwrap(); - match primitive { - DrawPrimitive::Rect(rect_primitive) => { - self.convert_rect_primitive(rect_primitive, &mut last_clipped_mesh.mesh); - } - DrawPrimitive::Quad(quad_primitive) => { - self.convert_quad_primitive(quad_primitive, &mut last_clipped_mesh.mesh); - } - DrawPrimitive::Text(text_primitive) => { - self.convert_text_primitive( - text_primitive, - pixels_per_point, - &mut last_clipped_mesh.mesh, - ); - } - } + last_clipped_mesh + .mesh + .add_quad(positions, uvs, color, texture_layer_idx); + last_clipped_mesh.mesh.texture_id = texture_id; // This can be empty if a new mesh was started but the conversion from a text primitive // didn't add any vertices. Our renderer doesn't support empty meshes so remove it @@ -91,79 +68,4 @@ impl Tessellator { out_clipped_meshes.pop(); } } - - fn convert_rect_primitive(&self, rect_primitive: RectPrimitive, out: &mut Mesh) { - let RectPrimitive { - rect, - color, - texture, - } = rect_primitive; - - let (texture_id, uv, layer_idx) = match texture { - Some(RectTexture { - texture_id, - uv, - layer_idx, - }) => (texture_id, uv, layer_idx), - None => (TextureId::default(), NormalizedRect::white_uv(), 0), - }; - - out.add_rect(rect, uv, color, layer_idx); - out.texture_id = texture_id; - } - - fn convert_quad_primitive(&self, quad_primitive: QuadPrimitive, out: &mut Mesh) { - let QuadPrimitive { - quad, - color, - texture, - } = quad_primitive; - - let (texture_id, uv, layer_idx) = match texture { - Some(QuadTexture { - texture_id, - uv, - layer_idx, - }) => (texture_id, uv, layer_idx), - None => (TextureId::default(), NormalizedQuad::white_uv(), 0), - }; - - out.add_quad(quad, uv, color, layer_idx); - out.texture_id = texture_id; - } - - fn convert_text_primitive( - &self, - text_primitive: TextPrimitive, - pixels_per_point: f32, - out: &mut Mesh, - ) { - let TextPrimitive { - pos: layout_pos, - layout, - } = text_primitive; - - if layout.rows.is_empty() { - return; - } - - out.vertices.reserve(layout.num_of_vertices); - out.indices.reserve(layout.num_of_indices); - - // Make sure the layout origin aligns with the physical pixel grid so - // that each glyph aligns correctly. Glyphs are positioned relative - // to the layout origin and assume that it ends up on the start of - // a physical pixel. - let layout_pos = layout_pos - .to_physical::(pixels_per_point) - .round() - .to_logical(pixels_per_point); - - for row in &layout.rows { - for glyph in &row.glyphs { - let rect = glyph.rect.translate(layout_pos.to_vector()); - out.add_rect(rect, glyph.uv, glyph.color, glyph.texture_layer_idx); - } - } - } }