1use std::{error, fmt};
2
3use crate::{RequestRect, solve_offline, solve_online, Bin};
4
5#[repr(C)]
7#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, Debug)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub enum AtlasAlgorithm {
10 #[default]
12 Offline,
13 Online,
15}
16
17#[repr(C)]
19#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub enum AtlasPadding {
22 Padding(u32),
24 Block(u32),
26}
27
28impl Default for AtlasPadding {
29 fn default() -> Self {
30 AtlasPadding::Padding(Default::default())
31 }
32}
33
34#[repr(C)]
36#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
37#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
38pub enum AtlasMipOption {
39 NoMip(AtlasPadding),
41 Mip(AtlasPadding, image::imageops::FilterType),
43}
44
45impl Default for AtlasMipOption {
46 fn default() -> Self {
47 AtlasMipOption::NoMip(Default::default())
48 }
49}
50
51#[repr(C)]
53#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, Debug)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55pub enum AtlasEntryMipOption {
56 #[default]
58 Clamp,
59 Repeat,
61 Mirror,
63}
64
65#[derive(Clone, PartialEq, Eq, Default, Debug)]
67#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
68pub struct AtlasEntry<I: image::GenericImageView> {
69 pub texture: I,
71 pub mip: AtlasEntryMipOption,
73}
74
75#[derive(Clone, PartialEq, Eq, Default, Debug)]
77pub struct AtlasDescriptor<'a, I: image::GenericImageView> {
78 pub size: u32,
80 pub mip: AtlasMipOption,
82 pub entries: &'a [AtlasEntry<I>],
84 pub algorithm: AtlasAlgorithm,
86}
87
88#[rustfmt::skip]
118pub fn create_atlas<I>(desc: &AtlasDescriptor<'_, I>) -> Result<Atlas<I::Pixel>, AtlasError>
119where
120 I: image::GenericImage,
121 I::Pixel: 'static,
122{
123 match desc.mip {
124 AtlasMipOption::NoMip(AtlasPadding::Padding(_)) => create_atlas_with_padding(desc),
125 AtlasMipOption::Mip(AtlasPadding::Padding(_), _) => create_atlas_with_padding(desc),
126 AtlasMipOption::NoMip(AtlasPadding::Block(_)) => create_atlas_with_block(desc),
127 AtlasMipOption::Mip(AtlasPadding::Block(_), _) => create_atlas_with_block(desc),
128 }
129}
130
131fn create_atlas_with_padding<I>(desc: &AtlasDescriptor<'_, I>) -> Result<Atlas<I::Pixel>, AtlasError>
132where
133 I: image::GenericImage,
134 I::Pixel: 'static,
135{
136 if let AtlasMipOption::Mip(_, _) = desc.mip && !desc.size.is_power_of_two() {
138 return Err(AtlasError::InvalidSize(desc.size));
139 }
140
141 let padding = match desc.mip {
143 AtlasMipOption::NoMip(AtlasPadding::Padding(padding)) => padding,
144 AtlasMipOption::Mip(AtlasPadding::Padding(padding), _) => padding,
145 _ => unreachable!(),
146 };
147
148 let mut requests = Vec::new();
149 for (i, entry) in desc.entries.iter().enumerate() {
150 let request = RequestRect {
151 id: i,
152 width: entry.texture.width() + padding * 2,
153 height: entry.texture.height() + padding * 2,
154 };
155 requests.push(request);
156 }
157 let pages = solve_packing(desc.algorithm, &requests, desc.size).ok_or(AtlasError::Packing)?;
158 let page_count = pages.len();
159 let packed_locations = pages.into_iter()
160 .enumerate()
161 .flat_map(|(page_id, page)| {
162 page.occupied_rects.into_iter()
163 .map(move |rect| (page_id, rect.id, rect.rect))
164 })
165 .collect::<Vec<_>>();
166
167 let mut texcoords = vec![Texcoord::default(); requests.len()];
168 for (page_id, rect_id, rect) in &packed_locations {
169 let texcoord = Texcoord {
170 page_id: *page_id,
171 min_x: rect.x + padding,
172 min_y: rect.y + padding,
173 max_x: rect.x + rect.width - padding,
174 max_y: rect.y + rect.height - padding,
175 size: desc.size,
176 };
177 texcoords[*rect_id] = texcoord;
178 }
179
180 let mip_level_count = if let AtlasMipOption::Mip(_, _) = desc.mip { desc.size.ilog2() + 1 } else { 1 };
182 let mut textures = vec![Texture::new(desc.size, mip_level_count); page_count];
183 for (page_id, rect_id, rect) in &packed_locations {
184 let entry = &desc.entries[*rect_id];
185 let src = resample_entry(&entry.texture, entry.mip, padding, padding, rect.width, rect.height);
186 let target = &mut textures[*page_id].mip_maps[0];
187 image::imageops::replace(target, &src, rect.x as i64, rect.y as i64);
188 }
189
190 if let AtlasMipOption::Mip(_, filter) = desc.mip {
192 for mip_level in 1..mip_level_count {
193 let size = desc.size >> mip_level;
194
195 for texture in &mut textures {
196 let src = &texture.mip_maps[0];
197
198 let mip_map = image::imageops::resize(src, size, size, filter);
199
200 let target = &mut texture.mip_maps[mip_level as usize];
201 image::imageops::replace(target, &mip_map, 0, 0);
202 }
203 }
204 }
205
206 Ok(Atlas {
207 page_count,
208 size: desc.size,
209 mip_level_count,
210 textures,
211 texcoords,
212 })
213}
214
215fn create_atlas_with_block<I>(desc: &AtlasDescriptor<'_, I>) -> Result<Atlas<I::Pixel>, AtlasError>
216where
217 I: image::GenericImage,
218 I::Pixel: 'static,
219{
220 if let AtlasMipOption::Mip(_, _) = desc.mip && !desc.size.is_power_of_two() {
222 return Err(AtlasError::InvalidSize(desc.size));
223 }
224
225 let block_size = match desc.mip {
226 AtlasMipOption::NoMip(AtlasPadding::Block(block_size)) => block_size,
227 AtlasMipOption::Mip(AtlasPadding::Block(block_size), _) => block_size,
228 _ => unreachable!(),
229 };
230 if !block_size.is_power_of_two() {
231 return Err(AtlasError::InvalidBlockSize(block_size));
232 }
233 let padding = block_size >> 1;
234
235 let mut requests = Vec::new();
236 for (i, entry) in desc.entries.iter().enumerate() {
237 let request = RequestRect {
238 id: i,
239 width: ((entry.texture.width() + block_size) as f32 / block_size as f32).ceil() as u32,
240 height: ((entry.texture.height() + block_size) as f32 / block_size as f32).ceil() as u32,
241 };
242 requests.push(request);
243 }
244 let pages = solve_packing(desc.algorithm, &requests, desc.size).ok_or(AtlasError::Packing)?;
245 let page_count = pages.len();
246 let packed_locations = pages.into_iter()
247 .enumerate()
248 .flat_map(|(page_id, page)| {
249 page.occupied_rects.into_iter()
250 .map(move |rect| (page_id, rect.id, rect.rect))
251 })
252 .collect::<Vec<_>>();
253
254 let mut texcoords = vec![Texcoord::default(); requests.len()];
255 for (page_id, rect_id, rect) in &packed_locations {
256 let texture = &desc.entries[*rect_id].texture;
257
258 let texcoord = Texcoord {
259 page_id: *page_id,
260 min_x: rect.x * block_size + padding,
261 min_y: rect.y * block_size + padding,
262 max_x: rect.x * block_size + padding + texture.width(),
263 max_y: rect.y * block_size + padding + texture.height(),
264 size: desc.size,
265 };
266 texcoords[*rect_id] = texcoord;
267 }
268
269 let mip_level_count = if let AtlasMipOption::Mip(_, _) = desc.mip { block_size.ilog2() + 1 } else { 1 };
271 let mut textures = vec![Texture::new(desc.size, mip_level_count); page_count];
272 for (page_id, rect_id, rect) in &packed_locations {
273 let entry = &desc.entries[*rect_id];
274 let src = resample_entry(&entry.texture, entry.mip, padding, padding, rect.width * block_size, rect.height * block_size);
275 let target = &mut textures[*page_id].mip_maps[0];
276 image::imageops::replace(target, &src, (rect.x * block_size) as i64, (rect.y * block_size) as i64);
277 }
278
279 if let AtlasMipOption::Mip(_, filter) = desc.mip {
281 for (page_id, rect_id, rect) in &packed_locations {
282 let entry = &desc.entries[*rect_id];
283 let src = resample_entry(&entry.texture, entry.mip, padding, padding, rect.width * block_size, rect.height * block_size);
284
285 for mip_level in 1..mip_level_count {
286 let width = src.width() >> mip_level;
287 let height = src.height() >> mip_level;
288 let mip_map = image::imageops::resize(&src, width, height, filter);
289
290 let target = &mut textures[*page_id].mip_maps[mip_level as usize];
291 let x = rect.x as i64 * (block_size >> mip_level) as i64;
292 let y = rect.y as i64 * (block_size >> mip_level) as i64;
293 image::imageops::replace(target, &mip_map, x, y);
294 }
295 }
296 }
297
298 Ok(Atlas {
299 page_count,
300 size: desc.size,
301 mip_level_count,
302 textures,
303 texcoords,
304 })
305}
306
307#[inline]
308fn solve_packing(
309 algorithm: AtlasAlgorithm,
310 requests: &[RequestRect],
311 size: u32
312) -> Option<Vec<Bin>> {
313 match algorithm {
314 AtlasAlgorithm::Offline => solve_offline(requests, size, size, false),
315 AtlasAlgorithm::Online => solve_online(requests, size, size, false),
316 }
317}
318
319#[inline]
320#[rustfmt::skip]
321fn resample_entry<I>(
322 src: &I,
323 mip: AtlasEntryMipOption,
324 shift_x: u32,
325 shift_y: u32,
326 width: u32,
327 height: u32,
328) -> image::ImageBuffer<I::Pixel, Vec<<I::Pixel as image::Pixel>::Subpixel>>
329where
330 I: image::GenericImage,
331{
332 let mut target = image::ImageBuffer::new(width, height);
333 match mip {
334 AtlasEntryMipOption::Clamp => {
335 for x in 0..width {
336 for y in 0..height {
337 let sx = u32::min(x.saturating_sub(shift_x), src.width() - 1);
338 let sy = u32::min(y.saturating_sub(shift_y), src.height() - 1);
339 *target.get_pixel_mut(x, y) = src.get_pixel(sx, sy);
340 }
341 }
342 }
343 AtlasEntryMipOption::Repeat => {
344 for x in 0..width {
345 for y in 0..height {
346 let sx = x.saturating_sub(shift_x).rem_euclid(src.width());
347 let sy = y.saturating_sub(shift_y).rem_euclid(src.height());
348 *target.get_pixel_mut(x, y) = src.get_pixel(sx, sy);
349 }
350 }
351 }
352 AtlasEntryMipOption::Mirror => {
353 for x in 0..width {
354 for y in 0..height {
355 let mut sx = x.saturating_sub(shift_x).rem_euclid(src.width());
356 let mut sy = y.saturating_sub(shift_y).rem_euclid(src.height());
357 let xx = x.saturating_sub(shift_x).div_euclid(src.width());
358 let yy = y.saturating_sub(shift_y).div_euclid(src.height());
359 if xx & 1 == 0 { sx = src.width() - 1 - sx; }
360 if yy & 1 == 0 { sy = src.height() - 1 - sy; }
361 *target.get_pixel_mut(x, y) = src.get_pixel(sx, sy);
362 }
363 }
364 }
365 }
366 target
367}
368
369#[derive(Clone, Default)]
371pub struct Atlas<P: image::Pixel> {
372 pub page_count: usize,
374 pub size: u32,
376 pub mip_level_count: u32,
378 pub textures: Vec<Texture<P>>,
380 pub texcoords: Vec<Texcoord>,
382}
383
384impl<P> fmt::Debug for Atlas<P>
385where
386 P: image::Pixel + fmt::Debug,
387 P::Subpixel: fmt::Debug,
388{
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 f.debug_struct("Atlas")
391 .field("page_count", &self.page_count)
392 .field("size", &self.size)
393 .field("mip_level_count", &self.mip_level_count)
394 .field("textures", &self.textures)
395 .field("texcoords", &self.texcoords)
396 .finish()
397 }
398}
399
400#[derive(Clone, Default)]
402pub struct Texture<P: image::Pixel> {
403 pub size: u32,
405 pub mip_level_count: u32,
407 pub mip_maps: Vec<image::ImageBuffer<P, Vec<P::Subpixel>>>,
409}
410
411impl<P: image::Pixel> Texture<P> {
412 #[inline]
413 fn new(size: u32, mip_level_count: u32) -> Self {
414 let mip_maps = (0..mip_level_count)
415 .map(|mip_level| size >> mip_level)
416 .map(|size| image::ImageBuffer::new(size, size))
417 .collect::<Vec<_>>();
418 Self {
419 size,
420 mip_level_count,
421 mip_maps,
422 }
423 }
424}
425
426impl<P> fmt::Debug for Texture<P>
427where
428 P: image::Pixel + fmt::Debug,
429 P::Subpixel: fmt::Debug,
430{
431 #[inline]
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 f.debug_struct("Texture")
434 .field("size", &self.size)
435 .field("mip_level_count", &self.mip_level_count)
436 .field("mip_maps", &self.mip_maps)
437 .finish()
438 }
439}
440
441#[repr(C)]
445#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
446#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
447pub struct Texcoord {
448 pub page_id: usize,
450 pub min_x: u32,
452 pub min_y: u32,
454 pub max_x: u32,
456 pub max_y: u32,
458 pub size: u32,
460}
461
462impl Texcoord {
463 #[inline]
465 pub fn to_f32(self) -> Texcoord32 {
466 Texcoord32 {
467 page_id: self.page_id,
468 min_x: self.min_x as f32 / self.size as f32,
469 min_y: self.min_y as f32 / self.size as f32,
470 max_x: self.max_x as f32 / self.size as f32,
471 max_y: self.max_y as f32 / self.size as f32,
472 }
473 }
474
475 #[inline]
477 pub fn to_f64(self) -> Texcoord64 {
478 Texcoord64 {
479 page_id: self.page_id,
480 min_x: self.min_x as f64 / self.size as f64,
481 min_y: self.min_y as f64 / self.size as f64,
482 max_x: self.max_x as f64 / self.size as f64,
483 max_y: self.max_y as f64 / self.size as f64,
484 }
485 }
486}
487
488#[repr(C)]
490#[derive(Clone, Copy, PartialEq, Default, Debug)]
491#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
492pub struct Texcoord32 {
493 pub page_id: usize,
495 pub min_x: f32,
497 pub min_y: f32,
499 pub max_x: f32,
501 pub max_y: f32,
503}
504
505impl From<Texcoord> for Texcoord32 {
506 #[inline]
507 fn from(value: Texcoord) -> Self {
508 value.to_f32()
509 }
510}
511
512#[repr(C)]
514#[derive(Clone, Copy, PartialEq, Default, Debug)]
515#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
516pub struct Texcoord64 {
517 pub page_id: usize,
519 pub min_x: f64,
521 pub min_y: f64,
523 pub max_x: f64,
525 pub max_y: f64,
527}
528
529impl From<Texcoord> for Texcoord64 {
530 #[inline]
531 fn from(value: Texcoord) -> Self {
532 value.to_f64()
533 }
534}
535
536#[derive(Debug)]
538pub enum AtlasError {
539 InvalidSize(u32),
541 InvalidBlockSize(u32),
543 Packing,
545}
546
547impl fmt::Display for AtlasError {
548 #[rustfmt::skip]
549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550 match self {
551 AtlasError::InvalidSize(size) => write!(f, "size is not power of two: {}.", size),
552 AtlasError::InvalidBlockSize(block_size) => write!(f, "block size is not power of two: {}.", block_size),
553 AtlasError::Packing => write!(f, "packing error occurred. entry width and/or height is too large."),
554 }
555 }
556}
557
558impl error::Error for AtlasError {}