🎉 Tile rendering system

This commit is contained in:
Aitor Moreno 2025-02-17 12:54:51 +01:00 committed by Alejandro Alonso
parent b727f2fe1f
commit 084816fb9f
17 changed files with 956 additions and 408 deletions

View file

@ -1,18 +0,0 @@
use super::{Image, Viewbox};
use skia::Contains;
use skia_safe as skia;
pub(crate) struct CachedSurfaceImage {
pub image: Image,
pub viewbox: Viewbox,
pub invalid: bool,
pub has_all_shapes: bool,
}
impl CachedSurfaceImage {
pub fn invalidate_if_dirty(&mut self, viewbox: &Viewbox) {
if !self.has_all_shapes && !self.viewbox.area.contains(viewbox.area) {
self.invalid = true;
}
}
}

View file

@ -1,71 +1,216 @@
use crate::shapes::Shape;
use skia_safe as skia;
use skia_safe::{self as skia, Rect};
use super::{RenderState, SurfaceId};
use super::{tiles, RenderState, SurfaceId};
use crate::run_script;
const DEBUG_SCALE: f32 = 0.2;
fn get_debug_rect(rect: Rect) -> Rect {
skia::Rect::from_xywh(
100. + rect.x() * DEBUG_SCALE,
100. + rect.y() * DEBUG_SCALE,
rect.width() * DEBUG_SCALE,
rect.height() * DEBUG_SCALE,
)
}
fn render_debug_view(render_state: &mut RenderState) {
let mut paint = skia::Paint::default();
paint.set_style(skia::PaintStyle::Stroke);
paint.set_color(skia::Color::from_argb(255, 255, 0, 255));
paint.set_color(skia::Color::from_rgb(255, 0, 255));
paint.set_stroke_width(1.);
let mut scaled_rect = render_state.viewbox.area.clone();
let x = 100. + scaled_rect.x() * 0.2;
let y = 100. + scaled_rect.y() * 0.2;
let width = scaled_rect.width() * 0.2;
let height = scaled_rect.height() * 0.2;
scaled_rect.set_xywh(x, y, width, height);
let rect = get_debug_rect(render_state.viewbox.area.clone());
render_state
.surfaces
.canvas(SurfaceId::Debug)
.draw_rect(scaled_rect, &paint);
.draw_rect(rect, &paint);
}
pub fn render_wasm_label(render_state: &mut RenderState) {
let font_provider = render_state.fonts().font_provider();
let typeface = font_provider
.match_family_style("robotomono-regular", skia::FontStyle::default())
.unwrap();
let canvas = render_state.surfaces.canvas(SurfaceId::Current);
let canvas = render_state.surfaces.canvas(SurfaceId::Debug);
let skia::ISize { width, height } = canvas.base_layer_size();
let p = skia::Point::new(width as f32 - 100.0, height as f32 - 25.0);
let mut paint = skia::Paint::default();
paint.set_color(skia::Color::from_argb(100, 0, 0, 0));
let font = skia::Font::new(typeface, 10.0);
canvas.draw_str("WASM RENDERER", p, &font, &paint);
let str = if render_state.options.is_debug_visible() {
"WASM RENDERER (DEBUG)"
} else {
"WASM RENDERER"
};
let (scalar, _) = render_state.fonts.debug_font().measure_str(str, None);
let p = skia::Point::new(width as f32 - 25.0 - scalar, height as f32 - 25.0);
let debug_font = render_state.fonts.debug_font();
canvas.draw_str(str, p, &debug_font, &paint);
}
pub fn render_debug_shape(render_state: &mut RenderState, element: &Shape, intersected: bool) {
let mut paint = skia::Paint::default();
paint.set_style(skia::PaintStyle::Stroke);
paint.set_color(if intersected {
skia::Color::from_argb(255, 255, 255, 0)
skia::Color::from_rgb(255, 255, 0)
} else {
skia::Color::from_argb(255, 0, 255, 255)
skia::Color::from_rgb(0, 255, 255)
});
paint.set_stroke_width(1.);
let mut scaled_rect = element.selrect();
let x = 100. + scaled_rect.x() * 0.2;
let y = 100. + scaled_rect.y() * 0.2;
let width = scaled_rect.width() * 0.2;
let height = scaled_rect.height() * 0.2;
scaled_rect.set_xywh(x, y, width, height);
let rect = get_debug_rect(element.extrect());
render_state
.surfaces
.canvas(SurfaceId::Debug)
.draw_rect(scaled_rect, &paint);
.draw_rect(rect, &paint);
}
pub fn render_debug_tiles_for_viewbox(
render_state: &mut RenderState,
sx: i32,
sy: i32,
ex: i32,
ey: i32,
) {
let canvas = render_state.surfaces.canvas(SurfaceId::Debug);
let mut paint = skia::Paint::default();
paint.set_style(skia::PaintStyle::Stroke);
paint.set_color(skia::Color::from_rgb(255, 0, 127));
paint.set_stroke_width(1.);
let str_rect = format!("{} {} {} {}", sx, sy, ex, ey);
let debug_font = render_state.fonts.debug_font();
canvas.draw_str(
str_rect,
skia::Point::new(100.0, 150.0),
&debug_font,
&paint,
);
}
// Renders the tiles in the viewbox
pub fn render_debug_viewbox_tiles(render_state: &mut RenderState) {
let canvas = render_state.surfaces.canvas(SurfaceId::Debug);
let mut paint = skia::Paint::default();
paint.set_style(skia::PaintStyle::Stroke);
paint.set_color(skia::Color::from_rgb(255, 0, 127));
paint.set_stroke_width(1.);
let tile_size = tiles::get_tile_size(render_state.viewbox);
let (sx, sy, ex, ey) = tiles::get_tiles_for_rect(render_state.viewbox.area, tile_size);
let str_rect = format!("{} {} {} {}", sx, sy, ex, ey);
let debug_font = render_state.fonts.debug_font();
canvas.draw_str(
str_rect,
skia::Point::new(100.0, 100.0),
&debug_font,
&paint,
);
for y in sy..=ey {
for x in sx..=ex {
let rect = Rect::from_xywh(
x as f32 * tile_size,
y as f32 * tile_size,
tile_size,
tile_size,
);
let debug_rect = get_debug_rect(rect);
let p = skia::Point::new(debug_rect.x(), debug_rect.y() - 1.);
let str = format!("{}:{}", x, y);
let debug_font = render_state.fonts.debug_font();
canvas.draw_str(str, p, &debug_font, &paint);
canvas.draw_rect(&debug_rect, &paint);
}
}
}
pub fn render_debug_tiles(render_state: &mut RenderState) {
let canvas = render_state.surfaces.canvas(SurfaceId::Debug);
let mut paint = skia::Paint::default();
paint.set_style(skia::PaintStyle::Stroke);
paint.set_color(skia::Color::from_rgb(127, 0, 255));
paint.set_stroke_width(1.);
let tile_size = tiles::get_tile_size(render_state.viewbox);
let (sx, sy, ex, ey) = tiles::get_tiles_for_rect(render_state.viewbox.area, tile_size);
for y in sy..=ey {
for x in sx..=ex {
let tile = (x, y);
let shape_count = render_state.tiles.get_shapes_at(tile).iter().len();
if shape_count == 0 {
continue;
}
let rect = Rect::from_xywh(
x as f32 * tile_size,
y as f32 * tile_size,
tile_size,
tile_size,
);
let debug_rect = get_debug_rect(rect);
let p = skia::Point::new(debug_rect.x(), debug_rect.y() - 1.);
let str = format!("{}:{} {}", x, y, shape_count);
let debug_font = render_state.fonts.debug_font();
canvas.draw_str(str, p, &debug_font, &paint);
canvas.draw_rect(&debug_rect, &paint);
}
}
}
pub fn render(render_state: &mut RenderState) {
render_debug_view(render_state);
render_debug_viewbox_tiles(render_state);
render_debug_tiles(render_state);
render_state.surfaces.draw_into(
SurfaceId::Debug,
SurfaceId::Current,
SurfaceId::Target,
Some(&skia::Paint::default()),
);
}
#[allow(dead_code)]
pub fn console_debug_tile_surface(render_state: &mut RenderState, tile: tiles::Tile) {
let base64_image = render_state.surfaces.base64_snapshot_tile(tile);
run_script!(format!("console.log('%c ', 'font-size: 1px; background: url(data:image/png;base64,{base64_image}) no-repeat; padding: 100px; background-size: contain;')"))
}
#[allow(dead_code)]
pub fn console_debug_surface(render_state: &mut RenderState, id: SurfaceId) {
let base64_image = render_state.surfaces.base64_snapshot(id);
run_script!(format!("console.log('%c ', 'font-size: 1px; background: url(data:image/png;base64,{base64_image}) no-repeat; padding: 100px; background-size: contain;')"))
}
#[allow(dead_code)]
pub fn console_debug_surface_rect(render_state: &mut RenderState, id: SurfaceId, rect: skia::Rect) {
let int_rect = skia::IRect::from_ltrb(
rect.left as i32,
rect.top as i32,
rect.right as i32,
rect.bottom as i32,
);
let base64_image = render_state.surfaces.base64_snapshot_rect(id, int_rect);
if let Some(base64_image) = base64_image {
run_script!(format!("console.log('%c ', 'font-size: 1px; background: url(data:image/png;base64,{base64_image}) no-repeat; padding: 100px; background-size: contain;')"))
}
}
pub fn render_workspace_current_tile(
render_state: &mut RenderState,
prefix: String,
tile: tiles::Tile,
rect: skia::Rect,
) {
let canvas = render_state.surfaces.canvas(SurfaceId::Target);
let mut p = skia::Paint::default();
p.set_stroke_width(1.);
p.set_style(skia::PaintStyle::Stroke);
canvas.draw_rect(&rect, &p);
let point = skia::Point::new(rect.x() + 10., rect.y() + 20.);
p.set_stroke_width(1.);
let str = format!("{prefix} {}:{}", tile.0, tile.1);
let debug_font = render_state.fonts.debug_font();
canvas.draw_str(str, point, &debug_font, &p);
}

View file

@ -1,4 +1,4 @@
use skia_safe::{self as skia, textlayout, FontMgr};
use skia_safe::{self as skia, textlayout, Font};
use crate::shapes::FontFamily;
@ -11,6 +11,7 @@ pub struct FontStore {
// TODO: we should probably have just one of those
font_provider: textlayout::TypefaceFontProvider,
font_collection: textlayout::FontCollection,
debug_font: Font,
}
impl FontStore {
@ -30,12 +31,19 @@ impl FontStore {
font_provider.register_typeface(emoji_font, DEFAULT_EMOJI_FONT);
let mut font_collection = skia::textlayout::FontCollection::new();
font_collection.set_default_font_manager(FontMgr::default(), None);
font_collection.set_dynamic_font_manager(FontMgr::from(font_provider.clone()));
font_collection.set_default_font_manager(Some(font_provider.clone().into()), None);
font_collection.set_dynamic_font_manager(Some(font_provider.clone().into()));
let debug_typeface = font_provider
.match_family_style("robotomono-regular", skia::FontStyle::default())
.unwrap();
let debug_font = skia::Font::new(debug_typeface, 10.0);
Self {
font_provider,
font_collection,
debug_font,
}
}
@ -47,6 +55,10 @@ impl FontStore {
&self.font_collection
}
pub fn debug_font(&self) -> &Font {
&self.debug_font
}
pub fn add(&mut self, family: FontFamily, font_data: &[u8]) -> Result<(), String> {
if self.has_family(&family) {
return Ok(());
@ -60,8 +72,6 @@ impl FontStore {
self.font_provider
.register_typeface(typeface, alias.as_str());
self.refresh_font_collection();
Ok(())
}
@ -69,12 +79,4 @@ impl FontStore {
let serialized = format!("{}", family);
self.font_provider.family_names().any(|x| x == serialized)
}
fn refresh_font_collection(&mut self) {
self.font_collection = skia::textlayout::FontCollection::new();
self.font_collection
.set_default_font_manager(FontMgr::default(), None);
self.font_collection
.set_dynamic_font_manager(FontMgr::from(self.font_provider.clone()));
}
}

View file

@ -69,8 +69,10 @@ fn draw_stroke_on_path(
match stroke.render_kind(is_open) {
// For inner stroke we draw a center stroke (with double width) and clip to the original path (that way the extra outer stroke is removed)
StrokeKind::InnerStroke => {
canvas.save(); // As we are using clear for surfaces we use save and restore here to still be able to clean the full surface
canvas.clip_path(&skia_path, skia::ClipOp::Intersect, true);
canvas.draw_path(&skia_path, &paint_stroke);
canvas.restore();
}
// For center stroke we don't need to do anything extra
StrokeKind::CenterStroke => {
@ -381,9 +383,9 @@ fn draw_image_stroke_in_container(
let is_open = p.is_open();
let mut paint = stroke.to_stroked_paint(is_open, &outer_rect, svg_attrs, dpr_scale);
canvas.draw_path(&path, &paint);
canvas.restore();
if stroke.render_kind(is_open) == StrokeKind::OuterStroke {
// Small extra inner stroke to overlap with the fill and avoid unnecesary artifacts
// Small extra inner stroke to overlap with the fill
// and avoid unnecesary artifacts.
paint.set_stroke_width(1. / dpr_scale);
canvas.draw_path(&path, &paint);
}
@ -396,13 +398,16 @@ fn draw_image_stroke_in_container(
svg_attrs,
dpr_scale,
);
canvas.restore();
}
}
_ => unreachable!("This shape should not have strokes"),
}
// Draw the image. We are using now the SrcIn blend mode, so the rendered piece of image will the area of the stroke over the image.
// Draw the image. We are using now the SrcIn blend mode,
// so the rendered piece of image will the area of the
// stroke over the image.
let mut image_paint = skia::Paint::default();
image_paint.set_blend_mode(skia::BlendMode::SrcIn);
image_paint.set_anti_alias(true);

View file

@ -1,7 +1,12 @@
use super::gpu_state::GpuState;
use crate::shapes::Shape;
use crate::view::Viewbox;
use skia_safe::{self as skia, Paint, RRect};
use super::{gpu_state::GpuState, tiles::Tile};
use base64::{engine::general_purpose, Engine as _};
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum SurfaceId {
Target,
@ -31,8 +36,10 @@ pub struct Surfaces {
overlay: skia::Surface,
// for drawing debug info.
debug: skia::Surface,
// for drawing tiles.
tiles: TileSurfaceCache,
sampling_options: skia::SamplingOptions,
margins: skia::ISize,
}
impl Surfaces {
@ -40,16 +47,32 @@ impl Surfaces {
gpu_state: &mut GpuState,
(width, height): (i32, i32),
sampling_options: skia::SamplingOptions,
tile_dims: skia::ISize,
) -> Self {
// This is the amount of extra space we're going
// to give to all the surfaces to render shapes.
// If it's too big it could affect performance.
let extra_tile_size = 2;
let extra_tile_dims = skia::ISize::new(
tile_dims.width * extra_tile_size,
tile_dims.height * extra_tile_size,
);
let margins = skia::ISize::new(extra_tile_dims.width / 4, extra_tile_dims.height / 4);
let mut target = gpu_state.create_target_surface(width, height);
let current = target.new_surface_with_dimensions((width, height)).unwrap();
let shadow = target.new_surface_with_dimensions((width, height)).unwrap();
let drop_shadows = target.new_surface_with_dimensions((width, height)).unwrap();
let overlay = target.new_surface_with_dimensions((width, height)).unwrap();
let shape_fills = target.new_surface_with_dimensions((width, height)).unwrap();
let shape_strokes = target.new_surface_with_dimensions((width, height)).unwrap();
let current = target.new_surface_with_dimensions(extra_tile_dims).unwrap();
let shadow = target.new_surface_with_dimensions(extra_tile_dims).unwrap();
let drop_shadows = target.new_surface_with_dimensions(extra_tile_dims).unwrap();
let overlay = target.new_surface_with_dimensions(extra_tile_dims).unwrap();
let shape_fills = target.new_surface_with_dimensions(extra_tile_dims).unwrap();
let shape_strokes = target.new_surface_with_dimensions(extra_tile_dims).unwrap();
let debug = target.new_surface_with_dimensions((width, height)).unwrap();
const POOL_CAPACITY_THRESHOLD: i32 = 4;
let pool_capacity =
(width / tile_dims.width) * (height / tile_dims.height) * POOL_CAPACITY_THRESHOLD;
let pool = SurfacePool::with_capacity(&mut target, tile_dims, pool_capacity as usize);
let tiles = TileSurfaceCache::new(pool);
Surfaces {
target,
current,
@ -60,6 +83,8 @@ impl Surfaces {
shape_strokes,
debug,
sampling_options,
tiles,
margins,
}
}
@ -67,8 +92,36 @@ impl Surfaces {
self.reset_from_target(gpu_state.create_target_surface(new_width, new_height));
}
pub fn snapshot(&mut self, id: SurfaceId) -> skia::Image {
self.get_mut(id).image_snapshot()
pub fn base64_snapshot_tile(&mut self, tile: Tile) -> String {
let surface = self.tiles.get(tile).unwrap();
let image = surface.image_snapshot();
let mut context = surface.direct_context();
let encoded_image = image
.encode(context.as_mut(), skia::EncodedImageFormat::PNG, None)
.unwrap();
general_purpose::STANDARD.encode(&encoded_image.as_bytes())
}
pub fn base64_snapshot(&mut self, id: SurfaceId) -> String {
let surface = self.get_mut(id);
let image = surface.image_snapshot();
let mut context = surface.direct_context();
let encoded_image = image
.encode(context.as_mut(), skia::EncodedImageFormat::PNG, None)
.unwrap();
general_purpose::STANDARD.encode(&encoded_image.as_bytes())
}
pub fn base64_snapshot_rect(&mut self, id: SurfaceId, irect: skia::IRect) -> Option<String> {
let surface = self.get_mut(id);
if let Some(image) = surface.image_snapshot_with_bounds(irect) {
let mut context = surface.direct_context();
let encoded_image = image
.encode(context.as_mut(), skia::EncodedImageFormat::PNG, None)
.unwrap();
return Some(general_purpose::STANDARD.encode(&encoded_image.as_bytes()));
}
None
}
pub fn canvas(&mut self, id: SurfaceId) -> &skia::Canvas {
@ -95,6 +148,21 @@ impl Surfaces {
}
}
pub fn update_render_context(&mut self, render_area: skia::Rect, viewbox: Viewbox) {
let translation = (
-render_area.left() + self.margins.width as f32 / viewbox.zoom,
-render_area.top() + self.margins.height as f32 / viewbox.zoom,
);
self.apply_mut(
&[SurfaceId::Fills, SurfaceId::Strokes, SurfaceId::DropShadows],
|s| {
s.canvas().restore();
s.canvas().save();
s.canvas().translate(translation);
},
);
}
fn get_mut(&mut self, id: SurfaceId) -> &mut skia::Surface {
match id {
SurfaceId::Target => &mut self.target,
@ -111,12 +179,8 @@ impl Surfaces {
fn reset_from_target(&mut self, target: skia::Surface) {
let dim = (target.width(), target.height());
self.target = target;
self.current = self.target.new_surface_with_dimensions(dim).unwrap();
self.overlay = self.target.new_surface_with_dimensions(dim).unwrap();
self.shadow = self.target.new_surface_with_dimensions(dim).unwrap();
self.drop_shadows = self.target.new_surface_with_dimensions(dim).unwrap();
self.shape_fills = self.target.new_surface_with_dimensions(dim).unwrap();
self.debug = self.target.new_surface_with_dimensions(dim).unwrap();
// The rest are tile size surfaces
}
pub fn draw_rect_to(&mut self, id: SurfaceId, shape: &Shape, paint: &Paint) {
@ -137,4 +201,145 @@ impl Surfaces {
self.canvas(id).draw_path(&path, paint);
}
}
pub fn reset(&mut self, color: skia::Color) {
self.canvas(SurfaceId::Fills).restore_to_count(1);
self.canvas(SurfaceId::DropShadows).restore_to_count(1);
self.canvas(SurfaceId::Strokes).restore_to_count(1);
self.canvas(SurfaceId::Current).restore_to_count(1);
self.apply_mut(
&[
SurfaceId::Fills,
SurfaceId::Strokes,
SurfaceId::Current,
SurfaceId::DropShadows,
SurfaceId::Shadow,
SurfaceId::Overlay,
],
|s| {
s.canvas().clear(color).reset_matrix();
},
);
self.canvas(SurfaceId::Debug)
.clear(skia::Color::TRANSPARENT)
.reset_matrix();
}
pub fn cache_tile_surface(&mut self, tile: Tile, id: SurfaceId, color: skia::Color) {
let sampling_options = self.sampling_options;
let mut tile_surface = self.tiles.get_or_create(tile).unwrap();
let margins = self.margins;
let surface = self.get_mut(id);
tile_surface.canvas().clear(color);
surface.draw(
tile_surface.canvas(),
(-margins.width, -margins.height),
sampling_options,
Some(&skia::Paint::default()),
);
}
pub fn has_cached_tile_surface(&mut self, tile: Tile) -> bool {
self.tiles.has(tile)
}
pub fn remove_cached_tile_surface(&mut self, tile: Tile) -> bool {
self.tiles.remove(tile)
}
pub fn draw_cached_tile_surface(&mut self, tile: Tile, rect: skia::Rect) {
let sampling_options = self.sampling_options;
let tile_surface = self.tiles.get(tile).unwrap();
tile_surface.draw(
self.target.canvas(),
(rect.x(), rect.y()),
sampling_options,
Some(&skia::Paint::default()),
);
}
pub fn remove_cached_tiles(&mut self) {
self.tiles.clear();
}
}
pub struct SurfaceRef {
pub surface: skia::Surface,
}
pub struct SurfacePool {
pub surfaces: Vec<SurfaceRef>,
pub index: usize,
}
impl SurfacePool {
pub fn with_capacity(surface: &mut skia::Surface, dims: skia::ISize, capacity: usize) -> Self {
let mut surfaces = Vec::with_capacity(capacity);
for _ in 0..capacity {
surfaces.push(surface.new_surface_with_dimensions(dims).unwrap())
}
SurfacePool {
index: 0,
surfaces: surfaces
.into_iter()
.map(|surface| SurfaceRef { surface: surface })
.collect(),
}
}
pub fn allocate(&mut self) -> Result<skia::Surface, String> {
let start = self.index;
let len = self.surfaces.len();
loop {
self.index = (self.index + 1) % len;
if self.index == start {
return Err("Not enough surfaces in the pool".into());
}
if let Some(surface_ref) = self.surfaces.get(self.index) {
return Ok(surface_ref.surface.clone());
}
}
}
}
pub struct TileSurfaceCache {
pool: SurfacePool,
grid: HashMap<Tile, skia::Surface>,
}
impl TileSurfaceCache {
pub fn new(pool: SurfacePool) -> Self {
TileSurfaceCache {
pool,
grid: HashMap::new(),
}
}
pub fn has(&mut self, tile: Tile) -> bool {
return self.grid.contains_key(&tile);
}
pub fn get_or_create(&mut self, tile: Tile) -> Result<skia::Surface, String> {
let surface = self.pool.allocate()?;
self.grid.insert(tile, surface.clone());
Ok(surface)
}
pub fn get(&mut self, tile: Tile) -> Result<&mut skia::Surface, String> {
Ok(self.grid.get_mut(&tile).unwrap())
}
pub fn remove(&mut self, tile: Tile) -> bool {
if !self.grid.contains_key(&tile) {
return false;
}
self.grid.remove(&tile);
true
}
pub fn clear(&mut self) {
self.grid.clear();
}
}

View file

@ -0,0 +1,95 @@
use skia_safe as skia;
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
use crate::view::Viewbox;
use indexmap::IndexSet;
pub type Tile = (i32, i32);
pub const TILE_SIZE: f32 = 512.;
pub fn get_tile_dimensions() -> skia::ISize {
(TILE_SIZE as i32, TILE_SIZE as i32).into()
}
pub fn get_tiles_for_rect(rect: skia::Rect, tile_size: f32) -> (i32, i32, i32, i32) {
// start
let sx = (rect.left / tile_size).floor() as i32;
let sy = (rect.top / tile_size).floor() as i32;
// end
let ex = (rect.right / tile_size).floor() as i32;
let ey = (rect.bottom / tile_size).floor() as i32;
(sx, sy, ex, ey)
}
pub fn get_tiles_for_viewbox(viewbox: Viewbox) -> (i32, i32, i32, i32) {
let tile_size = get_tile_size(viewbox);
get_tiles_for_rect(viewbox.area, tile_size)
}
pub fn get_tile_pos(viewbox: Viewbox, (x, y): Tile) -> (f32, f32) {
(
x as f32 * get_tile_size(viewbox),
y as f32 * get_tile_size(viewbox),
)
}
pub fn get_tile_size(viewbox: Viewbox) -> f32 {
// TODO: * self.options.dpr() too?
1. / viewbox.zoom * TILE_SIZE
}
pub fn get_tile_rect(viewbox: Viewbox, tile: Tile) -> skia::Rect {
let (tx, ty) = get_tile_pos(viewbox, tile);
let ts = get_tile_size(viewbox);
skia::Rect::from_xywh(tx, ty, ts, ts)
}
// This structure is usseful to keep all the shape uuids by shape id.
pub struct TileHashMap {
grid: HashMap<Tile, IndexSet<Uuid>>,
index: HashMap<Uuid, HashSet<Tile>>,
}
impl TileHashMap {
pub fn new() -> Self {
TileHashMap {
grid: HashMap::new(),
index: HashMap::new(),
}
}
pub fn has_shapes_at(&mut self, tile: Tile) -> bool {
return self.grid.contains_key(&tile);
}
pub fn get_shapes_at(&mut self, tile: Tile) -> Option<&IndexSet<Uuid>> {
return self.grid.get(&tile);
}
pub fn get_tiles_of(&mut self, shape_id: Uuid) -> Option<&HashSet<Tile>> {
self.index.get(&shape_id)
}
pub fn add_shape_at(&mut self, tile: Tile, shape_id: Uuid) {
if !self.grid.contains_key(&tile) {
self.grid.insert(tile, IndexSet::new());
}
if !self.index.contains_key(&shape_id) {
self.index.insert(shape_id, HashSet::new());
}
let tile_set = self.grid.get_mut(&tile).unwrap();
tile_set.insert(shape_id);
let index_set = self.index.get_mut(&shape_id).unwrap();
index_set.insert(tile);
}
pub fn invalidate(&mut self) {
self.grid.clear();
self.index.clear();
}
}