Newer
Older
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
use clap::Parser;
use std::collections::HashMap;
use std::fmt::Display;
use std::fs::File;
use image::{
image_dimensions, GenericImage, GenericImageView, ImageFormat, Pixel, Rgba, RgbaImage,
};
use num_traits::AsPrimitive;
use serde::{Deserialize, Serialize};
use crate::format::load_image;
use etagere::{AllocId, AtlasAllocator, Rectangle, Size};
use glob::MatchOptions;
use rayon::prelude::{IntoParallelIterator, ParallelBridge, ParallelIterator};
use std::path::{Path, PathBuf};
use thiserror::__private::DisplayAsDisplay;
#[inline(always)]
fn tile_size() -> u32 {
32
}
fn default_max_size() -> usize {
2048
}
/// Given a set of images, create a single atlas image and metadata file containing all of the original
/// set
#[derive(Parser, Serialize, Deserialize, Clone, Debug)]
#[clap(author, version = "0.7.0")]
pub struct Atlas {
/// A pattern evaluating to one or more image files
#[serde(default)]
pub glob: String,
/// The path to use when writing the texture atlas
#[serde(default)]
pub output: String,
/// The maximum width of the output texture
#[serde(default = "default_max_size")]
#[clap(short = 'w', long = "max_width")]
pub max_frame_width: usize,
/// The maximum height of the output texture
#[serde(default = "default_max_size")]
#[clap(short = 'h', long = "max_height")]
pub max_frame_height: usize,
}
#[derive(Copy, Clone, Hash, Eq, PartialEq)]
struct AtlasIdent {
page: usize,
id: u32,
}
struct SliceData {
path: PathBuf,
}
struct AtlasBuilder {
wh: (usize, usize),
pages: Vec<AtlasAllocator>,
}
impl AtlasBuilder {
pub fn new(wh: (usize, usize)) -> Self {
Self {
wh,
pages: Vec::with_capacity(1),
}
}
pub fn insert(
&mut self,
width: u32,
height: u32,
path: PathBuf,
) -> Option<(AtlasIdent, SliceData)> {
for (idx, page) in self.pages.iter_mut().enumerate() {
if let Some(alloc) = page.allocate(Size::new(width as i32, height as i32)) {
return Some((
AtlasIdent {
page: idx,
id: alloc.id.serialize(),
},
SliceData { path },
));
}
}
let mut new_page = AtlasAllocator::new(Size::new(self.wh.0 as i32, self.wh.1 as i32));
if let Some(alloc) = new_page.allocate(Size::new(width as i32, height as i32)) {
let idx = self.pages.len();
self.pages.push(new_page);
Some((
AtlasIdent {
page: idx,
id: alloc.id.serialize(),
},
SliceData { path },
))
} else {
None
}
}
pub fn get(&self, ident: AtlasIdent) -> Option<Rectangle> {
self.pages
.get(ident.page)
.map(|page| page.get(AllocId::deserialize(ident.id)))
}
}
impl Atlas {
pub fn run(&self) -> anyhow::Result<()> {
let pattern = glob::glob(self.glob.as_str())?;
let mut builder = AtlasBuilder::new((self.max_frame_width, self.max_frame_height));
let page_content_map: HashMap<usize, Vec<(PathBuf, Rectangle)>> = pattern
.into_iter()
.filter_map(Result::ok)
.flat_map(|path| image_dimensions(&path).map(|(w, h)| (w, h, path)))
.flat_map(|(w, h, path)| builder.insert(w, h, path))
.collect::<Vec<(AtlasIdent, SliceData)>>()
.into_iter()
.flat_map(|(ident, slice)| {
builder
.get(ident)
.map(|rect| (ident.page, slice.path, rect))
})
.fold(HashMap::default(), |mut map, (page, path, rect)| {
let mut entry = map.entry(page).or_default();
entry.push((path, rect));
map
});
page_content_map.into_par_iter().for_each(|(page, items)| {
if let Err(err) = write_atlas(
self.output.clone(),
(self.max_frame_width as u32, self.max_frame_height as u32),
page,
items,
) {
log::error!("{}", err);
}
});
Ok(())
}
}
#[derive(Serialize, Deserialize)]
struct IndexArea {
left: usize,
right: usize,
top: usize,
bottom: usize,
}
#[derive(Serialize, Deserialize)]
struct IndexEntry {
name: String,
area: IndexArea,
}
fn write_atlas(
output_path: impl Display,
image_wh: (u32, u32),
page_num: usize,
items: Vec<(PathBuf, Rectangle)>,
) -> anyhow::Result<()> {
let mut new_image = RgbaImage::from_pixel(image_wh.0, image_wh.1, Rgba::from([0, 0, 0, 0]));
let mut metadata_index = Vec::with_capacity(items.len());
for (source, spacing) in items {
let base_name = source
.file_stem()
.ok_or(anyhow::Error::msg("Path had no stem"))?
.to_str()
.ok_or(anyhow::Error::msg("Path was not unicode"))?
.to_string();
let source_image = load_image(
source
.to_str()
.ok_or(anyhow::Error::msg("Path was wrong"))?,
None,
)?;
metadata_index.push(IndexEntry {
name: base_name,
area: IndexArea {
left: spacing.min.x as usize,
right: spacing.max.x as usize,
bottom: spacing.max.y as usize,
top: spacing.min.y as usize,
},
});
new_image.copy_from(&source_image, spacing.min.x as u32, spacing.min.y as u32)?;
}
new_image.save(format!("{}_{}.png", output_path, page_num))?;
let new_file = File::create(format!("{}_{}.json", output_path, page_num))?;
serde_json::to_writer_pretty(new_file, &metadata_index)?;
Ok(())
}