image-atlas 0.1.0

A texture atlas generator for generic purpose.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! # image-atlas
//!
//! This library provides a texture atlas generator for general purpose. This library focuses on ease of use and simplicity.
//!
//! There are multiple generation way
//!
//! - No gaps between texture elements
//! - Simple gap between texture elements
//! - Smart gap between texture elements for mip map generation.
//!
//! and mip map generation option each texture elements
//!
//! - Single
//! - Repeat
//!
//! This library uses `image` crate for image backend and `rectangle-pack` crate for computing placements of atlas texture elements.
//!
//! # Examples
//!
//! ```rust
//! use std::collections::hash_map::RandomState;
//! use image_atlas::*;
//!
//! let atlas = create_atlas::<_, _, RandomState>(&AtlasDescriptor {
//!     max_page_count: 8,
//!     size: 2048,
//!     mip: AtlasMipOption::Block(32),
//!     entries: &[AtlasEntry {
//!         key: "example1",
//!         texture: image::RgbImage::new(512, 512),
//!         mip: AtlasEntryMipOption::Single,
//!     }],
//! })
//! .unwrap();
//!
//! println!("{:?}", atlas.texcoords.get("example1"));
//! ```

use std::{
    collections::{BTreeMap, HashMap},
    error, fmt, hash, ops,
};

/// A mip map generation method for texture atlas
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AtlasMipOption {
    NoneWithPadding(u32),
    Padding(u32),
    Block(u32),
}

impl Default for AtlasMipOption {
    fn default() -> Self {
        AtlasMipOption::NoneWithPadding(0)
    }
}

/// A mip map generation method each texture elements
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AtlasEntryMipOption {
    #[default]
    Single,
    Repeat,
}

/// A texture element description
#[derive(Clone, PartialEq, Eq, Default, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AtlasEntry<K, I: image::GenericImageView> {
    pub key: K,
    pub texture: I,
    pub mip: AtlasEntryMipOption,
}

/// A texture atlas description
#[derive(Clone, PartialEq, Eq, Default, Debug)]
pub struct AtlasDescriptor<'a, K, I: image::GenericImageView> {
    pub max_page_count: u32,
    pub size: u32,
    pub mip: AtlasMipOption,
    pub entries: &'a [AtlasEntry<K, I>],
}

/// Creates a new texture atlas.
pub fn create_atlas<K, I, S>(
    desc: &AtlasDescriptor<'_, K, I>,
) -> Result<Atlas<K, I::Pixel, S>, AtlasError>
where
    K: Clone + Eq + hash::Hash,
    I: image::GenericImage,
    I::Pixel: 'static,
    S: Default + hash::BuildHasher,
{
    match desc.mip {
        AtlasMipOption::NoneWithPadding(padding) => {
            create_atlas_with_padding(desc.max_page_count, desc.size, false, padding, desc.entries)
        }
        AtlasMipOption::Padding(padding) => {
            create_atlas_with_padding(desc.max_page_count, desc.size, true, padding, desc.entries)
        }
        AtlasMipOption::Block(block_size) => {
            create_atlas_with_block(desc.max_page_count, desc.size, block_size, desc.entries)
        }
    }
}

fn create_atlas_with_padding<K, I, S>(
    max_page_count: u32,
    size: u32,
    mip: bool,
    padding: u32,
    entries: &[AtlasEntry<K, I>],
) -> Result<Atlas<K, I::Pixel, S>, AtlasError>
where
    K: Eq + hash::Hash + Clone,
    I: image::GenericImage,
    I::Pixel: 'static,
    S: hash::BuildHasher + Default,
{
    if max_page_count == 0 {
        return Err(AtlasError::ZeroMaxPageCount);
    }

    if !size.is_power_of_two() {
        return Err(AtlasError::InvalidSize(size));
    }

    if entries.is_empty() {
        return Err(AtlasError::ZeroEntry);
    }

    let mut rects = rectangle_pack::GroupedRectsToPlace::<_, ()>::new();
    for (i, entry) in entries.iter().enumerate() {
        let rect = rectangle_pack::RectToInsert::new(
            entry.texture.width() + padding * 2,
            entry.texture.height() + padding * 2,
            1,
        );
        rects.push_rect(i, None, rect);
    }

    let mut target_bins = BTreeMap::new();
    target_bins.insert(
        (),
        rectangle_pack::TargetBin::new(size, size, max_page_count),
    );

    let locations = rectangle_pack::pack_rects(
        &rects,
        &mut target_bins,
        &rectangle_pack::volume_heuristic,
        &rectangle_pack::contains_smallest_box,
    )?;

    let page_count = locations
        .packed_locations()
        .iter()
        .map(|(_, (_, location))| location.z())
        .max()
        .unwrap()
        + 1;

    let mip_level_count = if mip { size.ilog2() + 1 } else { 1 };

    let mut textures = Textures::new_with(page_count, size, mip_level_count);
    let mut texcoords = HashMap::default();
    for (&i, (_, location)) in locations.packed_locations() {
        let entry = &entries[i];

        image::imageops::replace(
            &mut textures[location.z() as usize][0],
            &entry_with_padding(&entry.texture, padding, entry.mip),
            location.x() as i64,
            location.y() as i64,
        );

        let texcoord = Texcoord {
            page: location.z(),
            min_x: location.x() + padding,
            min_y: location.y() + padding,
            max_x: location.x() + padding + entry.texture.width(),
            max_y: location.y() + padding + entry.texture.height(),
            size,
        };
        texcoords.insert(entry.key.clone(), texcoord);
    }

    for page in 0..page_count {
        for mip_level in 1..mip_level_count {
            let mip_map = image::imageops::resize(
                &textures[page as usize][0],
                size >> mip_level,
                size >> mip_level,
                image::imageops::FilterType::Triangle,
            );
            image::imageops::replace(
                &mut textures[page as usize][mip_level as usize],
                &mip_map,
                0,
                0,
            );
        }
    }

    Ok(Atlas {
        textures,
        texcoords,
    })
}

fn create_atlas_with_block<K, I, S>(
    max_page_count: u32,
    size: u32,
    block_size: u32,
    entries: &[AtlasEntry<K, I>],
) -> Result<Atlas<K, I::Pixel, S>, AtlasError>
where
    K: Clone + Eq + hash::Hash,
    I: image::GenericImage,
    I::Pixel: 'static,
    S: Default + hash::BuildHasher,
{
    if max_page_count == 0 {
        return Err(AtlasError::ZeroMaxPageCount);
    }

    if !size.is_power_of_two() {
        return Err(AtlasError::InvalidSize(size));
    }

    if !block_size.is_power_of_two() {
        return Err(AtlasError::InvalidBlockSize(block_size));
    }

    if entries.is_empty() {
        return Err(AtlasError::ZeroEntry);
    }

    let mut rects = rectangle_pack::GroupedRectsToPlace::<_, ()>::new();
    for (i, entry) in entries.iter().enumerate() {
        let rect = rectangle_pack::RectToInsert::new(
            ((entry.texture.width() + block_size) as f32 / block_size as f32).ceil() as u32,
            ((entry.texture.height() + block_size) as f32 / block_size as f32).ceil() as u32,
            1,
        );
        rects.push_rect(i, None, rect);
    }

    let bin_size = size / block_size;
    let mut target_bins = BTreeMap::new();
    target_bins.insert(
        (),
        rectangle_pack::TargetBin::new(bin_size, bin_size, max_page_count),
    );

    let locations = rectangle_pack::pack_rects(
        &rects,
        &mut target_bins,
        &rectangle_pack::volume_heuristic,
        &rectangle_pack::contains_smallest_box,
    )?;

    let page_count = locations
        .packed_locations()
        .iter()
        .map(|(_, (_, location))| location.z())
        .max()
        .unwrap()
        + 1;

    let padding = block_size >> 1;
    let mip_level_count = block_size.ilog2() + 1;

    let mut textures = Textures::new_with(page_count, size, mip_level_count);
    let mut texcoords = HashMap::default();
    for (&i, (_, location)) in locations.packed_locations() {
        let entry = &entries[i];

        let texture = entry_with_padding(&entry.texture, padding, entry.mip);

        for mip_level in 0..mip_level_count {
            let mip_map = image::imageops::resize(
                &texture,
                texture.width() >> mip_level,
                texture.height() >> mip_level,
                image::imageops::FilterType::Triangle,
            );

            image::imageops::replace(
                &mut textures[location.z() as usize][mip_level as usize],
                &mip_map,
                (location.x() * block_size >> mip_level) as i64,
                (location.y() * block_size >> mip_level) as i64,
            );
        }

        let texcoord = Texcoord {
            page: location.z(),
            min_x: location.x() * block_size + padding,
            min_y: location.y() * block_size + padding,
            max_x: location.x() * block_size + padding + entry.texture.width(),
            max_y: location.y() * block_size + padding + entry.texture.height(),
            size,
        };
        texcoords.insert(entry.key.clone(), texcoord);
    }

    Ok(Atlas {
        textures,
        texcoords,
    })
}

fn entry_with_padding<I>(
    src: &I,
    padding: u32,
    leak: AtlasEntryMipOption,
) -> image::ImageBuffer<I::Pixel, Vec<<I::Pixel as image::Pixel>::Subpixel>>
where
    I: image::GenericImage,
{
    match leak {
        AtlasEntryMipOption::Single => {
            let mut target =
                image::ImageBuffer::new(src.width() + padding * 2, src.height() + padding * 2);
            image::imageops::replace(&mut target, src, padding as i64, padding as i64);
            target
        }
        AtlasEntryMipOption::Repeat => {
            let mut target =
                image::ImageBuffer::new(src.width() + padding * 2, src.height() + padding * 2);
            for x in -1..=1 {
                for y in -1..=1 {
                    let x = padding as i32 + src.width() as i32 * x;
                    let y = padding as i32 + src.height() as i32 * y;
                    image::imageops::replace(&mut target, src, x as i64, y as i64);
                }
            }
            target
        }
    }
}

/// A texture atlas
#[derive(Clone, Default)]
pub struct Atlas<K, P: image::Pixel, S> {
    pub textures: Textures<P>,
    pub texcoords: HashMap<K, Texcoord, S>,
}

impl<K, P, S> fmt::Debug for Atlas<K, P, S>
where
    K: fmt::Debug,
    P: image::Pixel + fmt::Debug,
    P::Subpixel: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Atlas")
            .field("textures", &self.textures)
            .field("texcoords", &self.texcoords)
            .finish()
    }
}

/// A texture collection
#[derive(Clone, Default)]
pub struct Textures<P: image::Pixel>(Vec<Texture<P>>);

impl<P: image::Pixel> Textures<P> {
    /// Creates a new texture collection with given parameters.
    #[inline]
    pub fn new_with(page_count: u32, size: u32, mip_level_count: u32) -> Self {
        let textures = (0..page_count)
            .map(|_| Texture::new_with(size, mip_level_count))
            .collect::<Vec<_>>();
        Self(textures)
    }
}

impl<P> fmt::Debug for Textures<P>
where
    P: image::Pixel + fmt::Debug,
    P::Subpixel: fmt::Debug,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<P: image::Pixel> ops::Deref for Textures<P> {
    type Target = Vec<Texture<P>>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<P: image::Pixel> ops::DerefMut for Textures<P> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// A texture
#[derive(Clone, Default)]
pub struct Texture<P: image::Pixel>(Vec<image::ImageBuffer<P, Vec<P::Subpixel>>>);

impl<P: image::Pixel> Texture<P> {
    /// Creates a new texture with given parameters.
    #[inline]
    pub fn new_with(size: u32, mip_level_count: u32) -> Self {
        let mip_maps = (0..mip_level_count)
            .map(|mip_level| image::ImageBuffer::new(size >> mip_level, size >> mip_level))
            .collect::<Vec<_>>();
        Self(mip_maps)
    }
}

impl<P> fmt::Debug for Texture<P>
where
    P: image::Pixel + fmt::Debug,
    P::Subpixel: fmt::Debug,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<P: image::Pixel> ops::Deref for Texture<P> {
    type Target = Vec<image::ImageBuffer<P, Vec<P::Subpixel>>>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<P: image::Pixel> ops::DerefMut for Texture<P> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// A texture element coordinate representing `u32` position
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Texcoord {
    pub page: u32,
    pub min_x: u32,
    pub min_y: u32,
    pub max_x: u32,
    pub max_y: u32,
    pub size: u32,
}

impl Texcoord {
    /// Returns a normalized texcoord using f32.
    #[inline]
    pub fn to_f32(self) -> Texcoord32 {
        Texcoord32 {
            page: self.page,
            min_x: self.min_x as f32 / self.size as f32,
            min_y: self.min_y as f32 / self.size as f32,
            max_x: self.max_x as f32 / self.size as f32,
            max_y: self.max_y as f32 / self.size as f32,
        }
    }

    /// Returns a normalized texcoord using f64.
    #[inline]
    pub fn to_f64(self) -> Texcoord64 {
        Texcoord64 {
            page: self.page,
            min_x: self.min_x as f64 / self.size as f64,
            min_y: self.min_y as f64 / self.size as f64,
            max_x: self.max_x as f64 / self.size as f64,
            max_y: self.max_y as f64 / self.size as f64,
        }
    }
}

/// A texture element coordinate representing normalized `f32` position
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Default, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Texcoord32 {
    pub page: u32,
    pub min_x: f32,
    pub min_y: f32,
    pub max_x: f32,
    pub max_y: f32,
}

impl From<Texcoord> for Texcoord32 {
    #[inline]
    fn from(value: Texcoord) -> Self {
        value.to_f32()
    }
}

/// A texture element coordinate representing normalized `f64` position
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Default, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Texcoord64 {
    pub page: u32,
    pub min_x: f64,
    pub min_y: f64,
    pub max_x: f64,
    pub max_y: f64,
}

impl From<Texcoord> for Texcoord64 {
    #[inline]
    fn from(value: Texcoord) -> Self {
        value.to_f64()
    }
}

/// A texture atlas generation error
#[derive(Debug)]
pub enum AtlasError {
    ZeroMaxPageCount,
    InvalidSize(u32),
    InvalidBlockSize(u32),
    ZeroEntry,
    Packing(rectangle_pack::RectanglePackError),
}

impl fmt::Display for AtlasError {
    #[rustfmt::skip]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AtlasError::ZeroMaxPageCount => write!(f, "max page count is zero."),
            AtlasError::InvalidSize(size) => write!(f, "size is not power of two: {}.", size),
            AtlasError::InvalidBlockSize(block_size) => write!(f, "block size is not power of two: {}.", block_size),
            AtlasError::ZeroEntry => write!(f, "entry is empty."),
            AtlasError::Packing(err) => err.fmt(f),
        }
    }
}

impl error::Error for AtlasError {}

impl From<rectangle_pack::RectanglePackError> for AtlasError {
    fn from(value: rectangle_pack::RectanglePackError) -> Self {
        AtlasError::Packing(value)
    }
}