1use std::sync::Arc;
7use unityrs_core::Bytes;
8use unityrs_core::budget::DecodeBuf;
9use unityrs_core::error::LimitKind;
10use unityrs_core::limits::{Charge, ChargeError, Meter, heap_cost};
11use unityrs_imageio::writers::resample::{self, Filter};
12use unityrs_imageio::{Buffer, Charger, Image};
13
14#[cfg(feature = "encode")]
15mod encoders;
16#[cfg(feature = "encode")]
17mod ffi;
18mod lab;
19mod object;
20mod source;
21mod ycbcr;
22pub use object::set_image;
23pub use source::Source;
24
25#[derive(Debug, thiserror::Error)]
27pub enum WriteError {
28 #[error("encoder unavailable for TextureFormat {0}")]
30 EncoderUnavailable(i32),
31 #[error("texture encoder failed with code {0}")]
33 Encoder(i32),
34 #[error("unsupported set_image: {0}")]
36 Unsupported(&'static str),
37 #[error("invalid set_image input: {0}")]
39 Invalid(&'static str),
40 #[error(transparent)]
42 Charge(#[from] ChargeError),
43 #[error(transparent)]
45 Decode(#[from] crate::DecodeError),
46 #[error(transparent)]
48 Resize(#[from] unityrs_imageio::writers::SaveError<ChargeError>),
49 #[error(transparent)]
51 Parse(#[from] unityrs_core::walk::ParseError),
52 #[error(transparent)]
54 Save(#[from] unityrs_core::files::SaveError),
55}
56const _: () = crate::send_sync::<WriteError>();
57
58#[derive(Clone, Copy, Debug)]
60pub struct Options<'a> {
61 pub format: i32,
63 pub platform: i32,
65 pub platform_blob: Option<&'a [u8]>,
67 pub flip: bool,
69 pub mipmap_count: i32,
71}
72const _: () = crate::send_sync::<Options<'static>>();
73impl Options<'_> {
74 #[must_use]
76 pub const fn new(format: i32) -> Self {
77 Self {
78 format,
79 platform: 0,
80 platform_blob: None,
81 flip: true,
82 mipmap_count: 1,
83 }
84 }
85}
86
87#[derive(Debug)]
89pub struct Encoded {
90 pub data: Bytes,
92 pub format: i32,
94 pub mipmap_count: i32,
96}
97const _: () = crate::send_sync::<Encoded>();
98
99struct Budget<'a>(&'a Arc<Meter>);
100impl Charger for Budget<'_> {
101 type Charge = Charge;
102 type Refusal = ChargeError;
103 fn charge(&mut self, _: Buffer, requests: &[usize]) -> Result<Charge, ChargeError> {
104 self.0.charge(
105 requests
106 .iter()
107 .fold(0u64, |n, &r| n.saturating_add(heap_cost(r as u64))),
108 )
109 }
110}
111
112fn mapped(format: i32, rgb: bool) -> Result<(i32, usize, bool), WriteError> {
114 if crate::texture_format_name(format).is_none() {
115 return Err(WriteError::Invalid("unknown TextureFormat"));
116 }
117 let (format, channels, encoder) = match format {
118 10 | 28 => (10, 4, true),
119 12 | 29 => (12, 4, true),
120 25..=27 | 48..=59 => (format, 4, true),
121 66..=71 => (format - if rgb { 18 } else { 12 }, 4, true),
122 34 | 64 | 60 => (if format == 60 { 60 } else { 34 }, 4, true),
123 45 => (45, 4, true),
124 46 | 47 | 65 => (47, 4, true),
125 1 => (1, 1, false),
126 63 | 9 | 15 | 18 | 41 | 42 => (63, 1, false),
127 7 | 3 | 8 | 22 | 30 | 32 | 35 => (3, 3, false),
128 _ => (4, 4, false),
129 };
130 Ok((format, channels, encoder))
131}
132
133pub fn image_to_texture2d(
138 source: &Source<'_>,
139 options: Options<'_>,
140 meter: &Arc<Meter>,
141) -> Result<Encoded, WriteError> {
142 let (format, mut channels, encoder) = mapped(options.format, source.mode() == "RGB")?;
143 let switch = crate::is_switch_swizzled(options.platform, options.platform_blob);
144 let empty = source.width() == 0 || source.height() == 0;
145 if switch && empty {
146 return Err(WriteError::Unsupported("zero-size Switch texture"));
147 }
148 if switch && options.mipmap_count > 1 && source.width() >= 8 && source.height() >= 8 {
149 return Err(WriteError::Unsupported("Switch mip chain"));
150 }
151 let switch_format = if format == 3 { 4 } else { format };
152 if switch && crate::platform::switch_block(switch_format).is_none() {
153 return Err(WriteError::Unsupported("Switch texel block"));
154 }
155 if !empty && options.platform == crate::XBOX360 && crate::XBOX_SWAP_FORMATS.contains(&format) {
156 return Err(WriteError::Unsupported("Xbox byte-swapped write"));
157 }
158 if empty {
159 return Ok(Encoded {
160 data: Bytes::new(),
161 format,
162 mipmap_count: if options.mipmap_count > 1 {
163 1
164 } else {
165 options.mipmap_count
166 },
167 });
168 }
169 source.check_convertible()?;
170 if encoder && !cfg!(feature = "encode") {
171 return Err(WriteError::EncoderUnavailable(format));
172 }
173 if switch && format == 3 {
174 channels = 4;
175 }
176 let prepared = source.prepare(channels, format == 1, meter)?;
177 let mut image = prepared.image()?;
178 let mut out = DecodeBuf::new(meter, 0, i32::MAX as u64, LimitKind::BlockOutput)?;
179 write_level(
180 &image,
181 options,
182 format,
183 channels,
184 (prepared.alpha_band, source.auxiliary()),
185 meter,
186 &mut out,
187 )?;
188 let mut mipmap_count = options.mipmap_count;
189 let mut resized = None;
190 let mut width = image.width();
191 let mut height = image.height();
192 for i in 1..options.mipmap_count {
193 width /= 2;
194 height /= 2;
195 if width < 4 || height < 4 {
196 mipmap_count = i;
197 break;
198 }
199 meter.count_decode((image.pixels().len() as u64).saturating_mul(8))?;
200 let next = resample::resize(&image, width, height, Filter::Bicubic, &mut Budget(meter))?;
201 resized = Some(next);
203 let Some(level) = &resized else {
204 return Err(WriteError::Invalid("missing mip storage"));
205 };
206 image = Image::new(width, height, prepared.mode, &level.bytes)
207 .map_err(|_| WriteError::Invalid("mip size"))?;
208 write_level(
209 &image,
210 Options {
211 platform: 0,
212 platform_blob: None,
213 ..options
214 },
215 format,
216 channels,
217 (prepared.alpha_band, Some(&[])),
218 meter,
219 &mut out,
220 )?;
221 }
222 drop(resized);
224 Ok(Encoded {
225 data: out.into_bytes()?,
226 format,
227 mipmap_count,
228 })
229}
230
231fn write_level(
232 image: &Image<'_>,
233 options: Options<'_>,
234 format: i32,
235 channels: usize,
236 (alpha_band, auxiliary): (usize, Option<&[u8]>),
237 meter: &Arc<Meter>,
238 out: &mut DecodeBuf,
239) -> Result<(), WriteError> {
240 let layout = if crate::is_switch_swizzled(options.platform, options.platform_blob) {
241 let exponent = options
242 .platform_blob
243 .and_then(|b| b.get(8..12))
244 .and_then(|b| <[u8; 4]>::try_from(b).ok())
245 .map(u32::from_le_bytes)
246 .ok_or(WriteError::Invalid("Switch blob"))?;
247 Some(crate::platform::switch_layout(
248 if format == 3 { 4 } else { format },
249 i32::try_from(image.width()).map_err(|_| WriteError::Invalid("width"))?,
250 i32::try_from(image.height()).map_err(|_| WriteError::Invalid("height"))?,
251 exponent,
252 )?)
253 } else {
254 None
255 };
256 let (width, height) = layout.as_ref().map_or(
257 (image.width(), image.height()),
258 crate::platform::SwitchLayout::padded_size,
259 );
260 #[cfg(feature = "encode")]
261 let (width, height) = if encoders::is_encoded(format) {
262 encoders::padded_size(format, width, height)?
263 } else {
264 (width, height)
265 };
266 let len = u64::from(width) * u64::from(height) * channels as u64;
267 meter.count_decode(len)?;
268 let mut linear = DecodeBuf::new(meter, len, len, LimitKind::BlockOutput)?;
269 for y in 0..height {
270 let bottom = y >= image.height();
271 let y = y.min(image.height() - 1);
272 let y = if options.flip {
273 image.height() - 1 - y
274 } else {
275 y
276 };
277 for x in 0..width {
278 let at = (y as usize * image.width() as usize + x.min(image.width() - 1) as usize)
279 * image.mode().channels();
280 let pixel = image
281 .pixels()
282 .get(at..at + image.mode().channels())
283 .ok_or(WriteError::Invalid("pixel span"))?;
284 if channels == 1 {
285 linear.extend_from_slice(
286 pixel
287 .get(if format == 1 { alpha_band } else { 0 }..)
288 .and_then(|b| b.get(..1))
289 .ok_or(WriteError::Invalid("band"))?,
290 )?;
291 } else if channels == 4 && image.mode() == unityrs_imageio::Mode::Rgb {
292 linear.extend_from_slice(pixel)?;
295 let padding = if bottom && x >= image.width() {
299 255
300 } else {
301 auxiliary.map_or(255, |b| b.get(at / 3).copied().unwrap_or(0))
302 };
303 linear.extend_from_slice(&[padding])?;
304 } else {
305 linear.extend_from_slice(
306 pixel
307 .get(..channels)
308 .ok_or(WriteError::Invalid("channels"))?,
309 )?;
310 }
311 }
312 }
313 #[cfg(feature = "encode")]
314 let compressed = if encoders::is_encoded(format) {
315 Some(encoders::encode(
316 linear.as_slice(),
317 width,
318 height,
319 format,
320 meter,
321 )?)
322 } else {
323 None
324 };
325 #[cfg(feature = "encode")]
326 let data = compressed
327 .as_ref()
328 .map_or(linear.as_slice(), |v| v.as_slice());
329 #[cfg(not(feature = "encode"))]
330 let data = linear.as_slice();
331 if let Some(layout) = layout {
332 let swizzled = crate::platform::swizzle(data, &layout, meter)?;
333 out.extend_from_slice(swizzled.as_slice())?;
334 } else {
335 out.extend_from_slice(data)?;
336 }
337 Ok(())
338}
339
340pub fn astc_context(
342 rgba: &[u8],
343 width: u32,
344 height: u32,
345 block: (u8, u8),
346 meter: &Arc<Meter>,
347) -> Result<unityrs_core::limits::MeteredVec<u8>, WriteError> {
348 #[cfg(feature = "encode")]
349 {
350 encoders::astc_context(rgba, width, height, block, meter)
351 }
352 #[cfg(not(feature = "encode"))]
353 {
354 let _ = (rgba, width, height, block, meter);
355 Err(WriteError::EncoderUnavailable(54))
356 }
357}