From a8bb208ed31b41850e6c4dd562aeb43206af22d3 Mon Sep 17 00:00:00 2001 From: atlv Date: Sun, 29 Jun 2025 17:59:56 -0400 Subject: [PATCH] optimize ktx2 level data concatenation (#19845) # Objective - avoid several internal vec copies while collecting all the level data in ktx2 load - merge another little piece of #18411 (benchmarks there found this to be a significant win) ## Solution - reserve and extend ## Testing - ran a few examples that load ktx2 images, like ssr. looks fine ## Future work - fast path logic to skip the reading into different vecs and just read it all in one go into the final buffer instead - as above, but directly into gpu staging buffer perhaps --- crates/bevy_image/src/ktx2.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/bevy_image/src/ktx2.rs b/crates/bevy_image/src/ktx2.rs index b4d838b4a9..61304c2145 100644 --- a/crates/bevy_image/src/ktx2.rs +++ b/crates/bevy_image/src/ktx2.rs @@ -238,11 +238,16 @@ pub fn ktx2_buffer_to_image( ))); } + // Collect all level data into a contiguous buffer + let mut image_data = Vec::new(); + image_data.reserve_exact(levels.iter().map(Vec::len).sum()); + levels.iter().for_each(|level| image_data.extend(level)); + // Assign the data and fill in the rest of the metadata now the possible // error cases have been handled let mut image = Image::default(); image.texture_descriptor.format = texture_format; - image.data = Some(levels.into_iter().flatten().collect::>()); + image.data = Some(image_data); image.data_order = wgpu_types::TextureDataOrder::MipMajor; // Note: we must give wgpu the logical texture dimensions, so it can correctly compute mip sizes. // However this currently causes wgpu to panic if the dimensions arent a multiple of blocksize.