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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use {
super::BitmapFont,
anyhow::{Context, bail},
bmfont::BMFont,
log::info,
std::sync::Arc,
vk_graph::{
Graph,
driver::{
DriverError,
ash::vk,
buffer::{Buffer, BufferInfo},
compute::{ComputePipeline, ComputePipelineInfo},
device::Device,
image::{Image, ImageInfo},
shader::Shader,
sync::AccessType,
},
pool::{Pool as _, hash::HashPool},
},
vk_shader_macros::include_glsl,
};
#[cfg(debug_assertions)]
use log::warn;
/// Describes the channels and pixel stride of an image format
#[derive(Clone, Copy, Debug)]
pub enum ImageFormat {
/// Single-channel 8-bit image data.
R8,
/// Two-channel 8-bit image data.
R8G8,
/// Three-channel 8-bit image data.
R8G8B8,
/// Four-channel 8-bit image data.
R8G8B8A8,
}
impl ImageFormat {
fn stride(self) -> usize {
match self {
Self::R8 => 1,
Self::R8G8 => 2,
Self::R8G8B8 => 3,
Self::R8G8B8A8 => 4,
}
}
}
/// Helper for decoding CPU bitmap data into `vk-graph` images.
#[derive(Debug)]
pub struct ImageLoader {
pool: HashPool,
_decode_r_rg: ComputePipeline,
decode_rgb_rgba: ComputePipeline,
/// The device used to create temporary buffers, images, and decode pipelines.
pub device: Device,
}
impl ImageLoader {
/// Creates a new image loader and its internal decode pipelines.
pub fn new(device: &Device) -> Result<Self, DriverError> {
Ok(Self {
pool: HashPool::new(device),
_decode_r_rg: ComputePipeline::create(
device,
ComputePipelineInfo::default(),
Shader::new_compute(
include_glsl!("res/shader/compute/decode_bitmap_r_rg.comp").as_slice(),
),
)?,
decode_rgb_rgba: ComputePipeline::create(
device,
ComputePipelineInfo::default(),
Shader::new_compute(
include_glsl!("res/shader/compute/decode_bitmap_rgb_rgba.comp").as_slice(),
),
)?,
device: device.clone(),
})
}
fn create_image(
&self,
format: ImageFormat,
width: u32,
height: u32,
is_srgb: bool,
is_temporary: bool,
) -> anyhow::Result<Arc<Image>> {
let format = match format {
ImageFormat::R8 | ImageFormat::R8G8 => {
if is_temporary {
vk::Format::R8G8_UINT
} else if is_srgb {
panic!("Unsupported format: R8G8_SRGB");
} else {
vk::Format::R8G8_UNORM
}
}
ImageFormat::R8G8B8 | ImageFormat::R8G8B8A8 => {
if is_temporary {
vk::Format::R8G8B8A8_UINT
} else if is_srgb {
vk::Format::R8G8B8A8_SRGB
} else {
vk::Format::R8G8B8A8_UNORM
}
}
};
let usage = if is_temporary {
vk::ImageUsageFlags::STORAGE
| vk::ImageUsageFlags::TRANSFER_DST
| vk::ImageUsageFlags::TRANSFER_SRC
} else {
vk::ImageUsageFlags::SAMPLED
| vk::ImageUsageFlags::TRANSFER_DST
| vk::ImageUsageFlags::TRANSFER_SRC
};
Ok(Arc::new(
Image::create(
&self.device,
ImageInfo::image_2d(width, height, format, usage),
)
.context("Unable to create new image")?,
))
}
/// Decodes bitmap pixels into an image and uploads it through a temporary graph submission.
#[allow(clippy::too_many_arguments)]
pub fn decode_bitmap(
&mut self,
queue_family_index: u32,
queue_index: u32,
pixels: &[u8],
format: ImageFormat,
width: u32,
height: u32,
is_srgb: bool,
) -> anyhow::Result<Arc<Image>> {
info!(
"decoding {}x{} {:?} bitmap ({} K)",
width,
height,
format,
pixels.len() / 1024
);
debug_assert!(
pixels.len() >= format.stride() * (width * height) as usize,
"insufficient data"
);
#[cfg(debug_assertions)]
if pixels.len() > (format.stride() as u32 * width * height).next_multiple_of(4) as usize {
warn!("unused data");
}
let mut graph = Graph::default();
let image = graph.bind_resource(self.create_image(format, width, height, is_srgb, false)?);
// Fill the image from the temporary buffer
match format {
ImageFormat::R8 => {
// This format requires a conversion
info!("Converting R to RG");
bail!("unsupported bitmap decode format: R8")
}
ImageFormat::R8G8B8 => {
// This format requires a conversion
//info!("Converting RGB to RGBA");
let stride = width * format.stride() as u32;
//trace!("{bitmap_width}x{bitmap_height} Stride={bitmap_stride}");
let pixel_buf_stride = stride.next_multiple_of(12);
let pixel_buf_len = (pixel_buf_stride * height) as vk::DeviceSize;
//trace!("pixel_buf_len={pixel_buf_len} pixel_buf_stride={pixel_buf_stride}");
// Lease a temporary buffer from the cache pool
let mut pixel_buf = self.pool.resource(BufferInfo::host_mem(
pixel_buf_len,
vk::BufferUsageFlags::STORAGE_BUFFER,
))?;
{
let pixel_buf =
&mut Buffer::mapped_slice_mut(&mut pixel_buf)[0..pixel_buf_len as usize];
// Fill the temporary buffer with the bitmap pixels - it has a different stride
for y in 0..height {
let src_offset = y * stride;
let src = &pixels[src_offset as usize..(src_offset + stride) as usize];
let dst_offset = y * pixel_buf_stride;
let dst =
&mut pixel_buf[dst_offset as usize..(dst_offset + stride) as usize];
dst.copy_from_slice(src);
}
}
let pixel_buf = graph.bind_resource(pixel_buf);
// We create a temporary storage image because SRGB support isn't wide enough to
// have SRGB storage images directly
let temp_image =
graph.bind_resource(self.create_image(format, width, height, false, true)?);
// Copy host-local data in the buffer to the temporary buffer on the GPU and then
// use a compute shader to decode it before copying it over the output image
let dispatch_x = (width + 3) >> 2;
let dispatch_y = height;
graph
.begin_cmd()
.debug_name("Decode RGB image")
.bind_pipeline(&self.decode_rgb_rgba)
.shader_resource_access(0, pixel_buf, AccessType::ComputeShaderReadOther)
.shader_resource_access(1, temp_image, AccessType::ComputeShaderWrite)
.record_cmd(move |cmd| {
cmd.push_constants(0, &(pixel_buf_stride >> 2).to_ne_bytes())
.dispatch(dispatch_x, dispatch_y, 1);
})
.end_cmd()
.copy_image(temp_image, image);
}
ImageFormat::R8G8 | ImageFormat::R8G8B8A8 => {
// Lease a temporary buffer from the pool
let mut pixel_buf = self.pool.resource(BufferInfo::host_mem(
pixels.len() as _,
vk::BufferUsageFlags::TRANSFER_SRC,
))?;
{
// Fill the temporary buffer with the bitmap pixels
let pixel_buf = &mut Buffer::mapped_slice_mut(&mut pixel_buf)[0..pixels.len()];
pixel_buf.copy_from_slice(pixels);
}
let pixel_buf = graph.bind_resource(pixel_buf);
graph.copy_buffer_to_image(pixel_buf, image);
}
}
let image = graph.resource(image).clone();
graph
.into_submission()
.queue_submit(&mut self.pool, queue_family_index, queue_index)?;
Ok(image)
}
/// Decodes a linear-color bitmap into an image.
pub fn decode_linear(
&mut self,
queue_family_index: u32,
queue_index: u32,
pixels: &[u8],
format: ImageFormat,
width: u32,
height: u32,
) -> anyhow::Result<Arc<Image>> {
self.decode_bitmap(
queue_family_index,
queue_index,
pixels,
format,
width,
height,
false,
)
}
/// Decodes an sRGB bitmap into an image.
pub fn decode_srgb(
&mut self,
queue_family_index: u32,
queue_index: u32,
pixels: &[u8],
format: ImageFormat,
width: u32,
height: u32,
) -> anyhow::Result<Arc<Image>> {
self.decode_bitmap(
queue_family_index,
queue_index,
pixels,
format,
width,
height,
true,
)
}
/// Loads a bitmap font by decoding each supplied page image and pairing it with the font data.
pub fn load_bitmap_font<'a>(
&mut self,
queue_family_index: u32,
queue_index: u32,
font: BMFont,
pages: impl IntoIterator<Item = (&'a [u8], u32, u32)>,
) -> anyhow::Result<BitmapFont> {
let pages = pages
.into_iter()
.map(|(pixels, width, height)| {
self.decode_linear(
queue_family_index,
queue_index,
pixels,
ImageFormat::R8G8B8,
width,
height,
)
})
.collect::<Result<Vec<_>, _>>()?;
BitmapFont::new(&self.device, font, pages)
}
}
#[cfg(test)]
mod test {
use super::ImageFormat;
#[test]
fn image_format_stride_matches_channel_count() {
assert_eq!(ImageFormat::R8.stride(), 1);
assert_eq!(ImageFormat::R8G8.stride(), 2);
assert_eq!(ImageFormat::R8G8B8.stride(), 3);
assert_eq!(ImageFormat::R8G8B8A8.stride(), 4);
}
}