1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use crate::wgpu_ext::*;
pub struct WGPUSpriteAtlasBuilder<'a, Device: WGPUDevice> {
images: Vec<(image::Image, &'a mut Option<WGPUSprite<Device>>)>,
mag_filter: FilterMode,
min_filter: FilterMode,
max_height: u32,
total_width: u32,
}
impl<'a, Device> WGPUSpriteAtlasBuilder<'a, Device>
where
Device: WGPUDevice,
{
pub fn new() -> Self {
Self {
images: vec![],
max_height: 0,
total_width: 0,
mag_filter: Default::default(),
min_filter: Default::default(),
}
}
pub fn with_image(
mut self,
img: image::Image,
sprite: &'a mut Option<WGPUSprite<Device>>,
) -> Self {
self.total_width += img.width();
self.max_height = self.max_height.max(img.height());
self.images.push((img, sprite));
self
}
pub fn with_filter_modes(mut self, mag_filter: FilterMode, min_filter: FilterMode) -> Self {
self.mag_filter = mag_filter;
self.min_filter = min_filter;
self
}
pub fn build(self, renderer: &WGPURenderer<Device>) -> Result<()> {
let WGPUSpriteAtlasBuilder {
images,
mag_filter,
min_filter,
total_width,
max_height,
} = self;
let mut atlas = image::Image::new(total_width, max_height);
let mut sprite_bounds = vec![];
let mut x = 0;
for (img, sprite) in images {
sprite_bounds.push((
Rect {
location: Vector2 { x, y: 0 },
dimensions: img.dimensions(),
},
sprite,
));
atlas.blit(&img, Vector2 { x, y: 0 }.convert());
x += img.width();
}
let texture = renderer.wgpu_device().with_device_info(|info| {
WGPUTexture::from_image(
info.device,
info.queue,
atlas,
mag_filter,
min_filter,
TextureType::Plain,
)
})?;
for (bounds, sprite) in sprite_bounds {
*sprite = Some(WGPUSprite::from_texture_with_bounds(
renderer,
&texture,
bounds.convert(),
)?);
}
Ok(())
}
}
impl<'a, Device> Default for WGPUSpriteAtlasBuilder<'a, Device>
where
Device: WGPUDevice,
{
fn default() -> Self {
Self::new()
}
}