Skip to content

Commit 18ccf7c

Browse files
committed
Cache Svg load result properly
This avoids trying to loading the file constantly on every frame.
1 parent 232d487 commit 18ccf7c

2 files changed

Lines changed: 22 additions & 20 deletions

File tree

wgpu/src/image.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -215,12 +215,9 @@ impl Pipeline {
215215
#[cfg(feature = "svg")]
216216
pub fn viewport_dimensions(&self, handle: &svg::Handle) -> (u32, u32) {
217217
let mut cache = self.vector_cache.borrow_mut();
218+
let svg = cache.load(&handle);
218219

219-
if let Some(svg) = cache.load(&handle) {
220-
svg.viewport_dimensions()
221-
} else {
222-
(1, 1)
223-
}
220+
svg.viewport_dimensions()
224221
}
225222

226223
pub fn draw(

wgpu/src/image/vector.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,21 @@ use std::{
44
rc::Rc,
55
};
66

7-
pub struct Svg {
8-
tree: resvg::usvg::Tree,
7+
pub enum Svg {
8+
Loaded { tree: resvg::usvg::Tree },
9+
NotFound,
910
}
1011

1112
impl Svg {
1213
pub fn viewport_dimensions(&self) -> (u32, u32) {
13-
let size = self.tree.svg_node().size;
14+
match self {
15+
Svg::Loaded { tree } => {
16+
let size = tree.svg_node().size;
1417

15-
(size.width() as u32, size.height() as u32)
18+
(size.width() as u32, size.height() as u32)
19+
}
20+
Svg::NotFound => (1, 1),
21+
}
1622
}
1723
}
1824

@@ -40,21 +46,20 @@ impl Cache {
4046
}
4147
}
4248

43-
pub fn load(&mut self, handle: &svg::Handle) -> Option<&Svg> {
49+
pub fn load(&mut self, handle: &svg::Handle) -> &Svg {
4450
if self.svgs.contains_key(&handle.id()) {
45-
return self.svgs.get(&handle.id());
51+
return self.svgs.get(&handle.id()).unwrap();
4652
}
4753

4854
let opt = resvg::Options::default();
4955

50-
match resvg::usvg::Tree::from_file(handle.path(), &opt.usvg) {
51-
Ok(tree) => {
52-
let _ = self.svgs.insert(handle.id(), Svg { tree });
53-
}
54-
Err(_) => {}
56+
let svg = match resvg::usvg::Tree::from_file(handle.path(), &opt.usvg) {
57+
Ok(tree) => Svg::Loaded { tree },
58+
Err(_) => Svg::NotFound,
5559
};
5660

57-
self.svgs.get(&handle.id())
61+
let _ = self.svgs.insert(handle.id(), svg);
62+
self.svgs.get(&handle.id()).unwrap()
5863
}
5964

6065
pub fn upload(
@@ -85,7 +90,7 @@ impl Cache {
8590
}
8691

8792
match self.load(handle) {
88-
Some(svg) => {
93+
Svg::Loaded { tree } => {
8994
let extent = wgpu::Extent3d {
9095
width,
9196
height,
@@ -113,7 +118,7 @@ impl Cache {
113118
);
114119

115120
resvg::backend_raqote::render_to_canvas(
116-
&svg.tree,
121+
&tree,
117122
&resvg::Options::default(),
118123
screen_size,
119124
&mut canvas,
@@ -171,7 +176,7 @@ impl Cache {
171176

172177
Some(bind_group)
173178
}
174-
None => None,
179+
Svg::NotFound => None,
175180
}
176181
}
177182

0 commit comments

Comments
 (0)