unity_asset_binary/texture/
converter.rs1use super::decoders::TextureDecoder;
7use super::types::Texture2D;
8use crate::error::{BinaryError, Result};
9use crate::object::UnityObject;
10use crate::unity_version::UnityVersion;
11use image::RgbaImage;
12
13pub struct Texture2DConverter {
18 #[allow(dead_code)]
19 version: UnityVersion,
20 decoder: TextureDecoder,
21}
22
23impl Texture2DConverter {
24 pub fn new(version: UnityVersion) -> Self {
26 Self {
27 version,
28 decoder: TextureDecoder::new(),
29 }
30 }
31
32 pub fn from_unity_object(&self, obj: &UnityObject) -> Result<Texture2D> {
37 self.parse_binary_data(&obj.info.data)
40 }
41
42 fn parse_binary_data(&self, data: &[u8]) -> Result<Texture2D> {
44 if data.is_empty() {
45 return Err(BinaryError::invalid_data("Empty texture data"));
46 }
47
48 let mut reader = crate::reader::BinaryReader::new(data, crate::reader::ByteOrder::Little);
49
50 #[allow(clippy::field_reassign_with_default)]
52 {
53 let mut texture = Texture2D::default();
54
55 texture.name = reader
57 .read_aligned_string()
58 .unwrap_or_else(|_| "UnknownTexture".to_string());
59
60 texture.width = reader.read_i32().unwrap_or(0);
62 texture.height = reader.read_i32().unwrap_or(0);
63 texture.complete_image_size = reader.read_i32().unwrap_or(0);
64
65 let format_val = reader.read_i32().unwrap_or(0);
66 texture.format = super::formats::TextureFormat::from(format_val);
67
68 texture.mip_map = reader.read_bool().unwrap_or(false);
70 texture.is_readable = reader.read_bool().unwrap_or(false);
71
72 texture.data_size = reader.read_i32().unwrap_or(0);
74
75 if texture.data_size > 0 && reader.remaining() >= texture.data_size as usize {
77 texture.image_data = reader
78 .read_bytes(texture.data_size as usize)
79 .unwrap_or_default();
80 } else if reader.remaining() > 0 {
81 let remaining_data = reader.read_remaining();
83 texture.image_data = remaining_data.to_vec();
84 texture.data_size = texture.image_data.len() as i32;
85 }
86
87 Ok(texture)
88 }
89 }
90
91 pub fn decode_to_image(&self, texture: &Texture2D) -> Result<RgbaImage> {
95 self.decoder.decode(texture)
97 }
98}
99
100pub type Texture2DProcessor = Texture2DConverter;