Path: blob/main/crates/bevy_image/src/exr_texture_loader.rs
9366 views
use crate::{Image, TextureAccessError, TextureFormatPixelInfo};1use bevy_asset::{io::Reader, AssetLoader, LoadContext, RenderAssetUsages};2use bevy_reflect::TypePath;3use image::ImageDecoder;4use serde::{Deserialize, Serialize};5use thiserror::Error;6use wgpu_types::{Extent3d, TextureDimension, TextureFormat};78/// Loads EXR textures as Texture assets9#[derive(Clone, Default, TypePath)]10#[cfg(feature = "exr")]11pub struct ExrTextureLoader;1213#[derive(Serialize, Deserialize, Default, Debug)]14#[cfg(feature = "exr")]15pub struct ExrTextureLoaderSettings {16pub asset_usage: RenderAssetUsages,17}1819/// Possible errors that can be produced by [`ExrTextureLoader`]20#[non_exhaustive]21#[derive(Debug, Error, TypePath)]22#[cfg(feature = "exr")]23pub enum ExrTextureLoaderError {24#[error(transparent)]25Io(#[from] std::io::Error),26#[error(transparent)]27ImageError(#[from] image::ImageError),28#[error("Texture access error: {0}")]29TextureAccess(#[from] TextureAccessError),30}3132impl AssetLoader for ExrTextureLoader {33type Asset = Image;34type Settings = ExrTextureLoaderSettings;35type Error = ExrTextureLoaderError;3637async fn load(38&self,39reader: &mut dyn Reader,40settings: &Self::Settings,41_load_context: &mut LoadContext<'_>,42) -> Result<Image, Self::Error> {43let format = TextureFormat::Rgba32Float;44debug_assert_eq!(45format.pixel_size()?,464 * 4,47"Format should have 32bit x 4 size"48);4950let mut bytes = Vec::new();51reader.read_to_end(&mut bytes).await?;52let decoder = image::codecs::openexr::OpenExrDecoder::with_alpha_preference(53std::io::Cursor::new(bytes),54Some(true),55)?;56let (width, height) = decoder.dimensions();5758let total_bytes = decoder.total_bytes() as usize;5960let mut buf = vec![0u8; total_bytes];61decoder.read_image(buf.as_mut_slice())?;6263Ok(Image::new(64Extent3d {65width,66height,67depth_or_array_layers: 1,68},69TextureDimension::D2,70buf,71format,72settings.asset_usage,73))74}7576fn extensions(&self) -> &[&str] {77&["exr"]78}79}808182