15120
|
1 |
use integral_geometry::{Rect, Size};
|
|
2 |
use std::cmp::{max, min, Ordering};
|
|
3 |
|
|
4 |
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone)]
|
|
5 |
struct Fit {
|
|
6 |
short_side: u32,
|
|
7 |
long_side: u32,
|
|
8 |
}
|
|
9 |
|
|
10 |
impl Fit {
|
|
11 |
fn new() -> Self {
|
|
12 |
Self {
|
|
13 |
short_side: u32::max_value(),
|
|
14 |
long_side: u32::max_value(),
|
|
15 |
}
|
|
16 |
}
|
|
17 |
|
|
18 |
fn measure(container: Size, size: Size) -> Option<Self> {
|
|
19 |
if container.contains(size) {
|
|
20 |
let x_leftover = container.width - size.width;
|
|
21 |
let y_leftover = container.height - size.height;
|
|
22 |
Some(Self {
|
|
23 |
short_side: min(x_leftover, y_leftover) as u32,
|
|
24 |
long_side: max(x_leftover, y_leftover) as u32,
|
|
25 |
})
|
|
26 |
} else {
|
|
27 |
None
|
|
28 |
}
|
|
29 |
}
|
|
30 |
}
|
|
31 |
|
|
32 |
#[derive(PartialEq, Eq)]
|
|
33 |
pub struct UsedSpace {
|
|
34 |
used_area: usize,
|
|
35 |
total_area: usize,
|
|
36 |
}
|
|
37 |
|
|
38 |
impl UsedSpace {
|
|
39 |
const fn new(used_area: usize, total_area: usize) -> Self {
|
|
40 |
Self {
|
|
41 |
used_area,
|
|
42 |
total_area,
|
|
43 |
}
|
|
44 |
}
|
|
45 |
|
|
46 |
const fn used(&self) -> usize {
|
|
47 |
self.used_area
|
|
48 |
}
|
|
49 |
|
|
50 |
const fn total(&self) -> usize {
|
|
51 |
self.total_area
|
|
52 |
}
|
|
53 |
}
|
|
54 |
|
|
55 |
impl std::fmt::Debug for UsedSpace {
|
|
56 |
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
|
|
57 |
write!(
|
|
58 |
f,
|
|
59 |
"{:.2}%",
|
|
60 |
self.used() as f32 / self.total() as f32 / 100.0
|
|
61 |
)?;
|
|
62 |
Ok(())
|
|
63 |
}
|
|
64 |
}
|
|
65 |
|
|
66 |
pub struct Atlas {
|
|
67 |
size: Size,
|
|
68 |
free_rects: Vec<Rect>,
|
|
69 |
used_rects: Vec<Rect>,
|
|
70 |
splits: Vec<Rect>,
|
|
71 |
}
|
|
72 |
|
|
73 |
impl Atlas {
|
|
74 |
pub fn new(size: Size) -> Self {
|
|
75 |
Self {
|
|
76 |
size,
|
|
77 |
free_rects: vec![Rect::at_origin(size)],
|
|
78 |
used_rects: vec![],
|
|
79 |
splits: vec![],
|
|
80 |
}
|
|
81 |
}
|
|
82 |
|
|
83 |
pub fn size(&self) -> Size {
|
|
84 |
self.size
|
|
85 |
}
|
|
86 |
|
|
87 |
pub fn used_space(&self) -> UsedSpace {
|
|
88 |
let used = self.used_rects.iter().map(|r| r.size().area()).sum();
|
|
89 |
UsedSpace::new(used, self.size.area())
|
|
90 |
}
|
|
91 |
|
|
92 |
fn find_position(&self, size: Size) -> Option<(Rect, Fit)> {
|
|
93 |
let mut best_rect = Rect::EMPTY;
|
|
94 |
let mut best_fit = Fit::new();
|
|
95 |
|
|
96 |
for rect in &self.free_rects {
|
|
97 |
if let Some(fit) = Fit::measure(rect.size(), size) {
|
|
98 |
if fit < best_fit {
|
|
99 |
best_fit = fit;
|
|
100 |
best_rect = Rect::from_size(rect.top_left(), size);
|
|
101 |
}
|
|
102 |
}
|
|
103 |
|
|
104 |
if let Some(fit) = Fit::measure(rect.size(), size.transpose()) {
|
|
105 |
if fit < best_fit {
|
|
106 |
best_fit = fit;
|
|
107 |
best_rect = Rect::from_size(rect.top_left(), size.transpose());
|
|
108 |
}
|
|
109 |
}
|
|
110 |
}
|
|
111 |
|
|
112 |
if best_rect == Rect::EMPTY {
|
|
113 |
None
|
|
114 |
} else {
|
|
115 |
Some((best_rect, best_fit))
|
|
116 |
}
|
|
117 |
}
|
|
118 |
|
|
119 |
fn split_insert(&mut self, rect: Rect) {
|
|
120 |
let mut splits = std::mem::replace(&mut self.splits, vec![]);
|
|
121 |
let mut buffer = [Rect::EMPTY; 4];
|
|
122 |
|
|
123 |
for i in (0..self.free_rects.len()).rev() {
|
|
124 |
if let Some(count) = split_rect(self.free_rects[i], rect, &mut splits, &mut buffer) {
|
|
125 |
self.free_rects.swap_remove(i as usize);
|
|
126 |
splits.extend_from_slice(&buffer[0..count]);
|
|
127 |
}
|
|
128 |
}
|
|
129 |
|
|
130 |
filter_swap_remove(&mut splits, |s| {
|
|
131 |
self.free_rects.iter().any(|r| r.contains_rect(s))
|
|
132 |
});
|
|
133 |
self.free_rects.extend(splits.drain(..));
|
|
134 |
std::mem::replace(&mut self.splits, splits);
|
|
135 |
|
|
136 |
self.used_rects.push(rect);
|
|
137 |
}
|
|
138 |
|
|
139 |
pub fn insert(&mut self, size: Size) -> Option<Rect> {
|
|
140 |
let (rect, _) = self.find_position(size)?;
|
|
141 |
self.split_insert(rect);
|
|
142 |
Some(rect)
|
|
143 |
}
|
|
144 |
|
|
145 |
pub fn insert_set<Iter>(&mut self, sizes: Iter) -> Vec<Rect>
|
|
146 |
where
|
|
147 |
Iter: Iterator<Item = Size>,
|
|
148 |
{
|
|
149 |
let mut sizes: Vec<_> = sizes.collect();
|
|
150 |
let mut result = vec![];
|
|
151 |
|
|
152 |
while let Some((index, (rect, _))) = sizes
|
|
153 |
.iter()
|
|
154 |
.enumerate()
|
|
155 |
.filter_map(|(i, s)| self.find_position(*s).map(|res| (i, res)))
|
|
156 |
.min_by_key(|(_, (_, fit))| fit.clone())
|
|
157 |
{
|
|
158 |
self.split_insert(rect);
|
|
159 |
|
|
160 |
result.push(rect);
|
|
161 |
sizes.swap_remove(index);
|
|
162 |
}
|
|
163 |
result
|
|
164 |
}
|
|
165 |
|
|
166 |
pub fn reset(&mut self) {
|
|
167 |
self.free_rects.clear();
|
|
168 |
self.used_rects.clear();
|
|
169 |
self.free_rects.push(Rect::at_origin(self.size));
|
|
170 |
}
|
|
171 |
}
|
|
172 |
|
|
173 |
pub struct AtlasCollection {
|
|
174 |
texture_size: Size,
|
|
175 |
atlases: Vec<Atlas>,
|
|
176 |
}
|
|
177 |
|
|
178 |
impl AtlasCollection {
|
|
179 |
pub fn new(texture_size: Size) -> Self {
|
|
180 |
Self {
|
|
181 |
texture_size,
|
|
182 |
atlases: vec![],
|
|
183 |
}
|
|
184 |
}
|
|
185 |
|
|
186 |
fn repack(&mut self, size: Size) -> bool {
|
|
187 |
for atlas in &mut self.atlases {
|
|
188 |
let mut temp_atlas = Atlas::new(atlas.size());
|
|
189 |
let sizes = atlas
|
|
190 |
.used_rects
|
|
191 |
.iter()
|
|
192 |
.map(|r| r.size())
|
|
193 |
.chain(std::iter::once(size));
|
|
194 |
if !temp_atlas.insert_set(sizes).is_empty() {
|
|
195 |
std::mem::swap(atlas, &mut temp_atlas);
|
|
196 |
return true;
|
|
197 |
}
|
|
198 |
}
|
|
199 |
false
|
|
200 |
}
|
|
201 |
|
|
202 |
pub fn insert_sprite(&mut self, size: Size) -> bool {
|
|
203 |
if !self.texture_size.contains(size) {
|
|
204 |
false
|
|
205 |
} else {
|
|
206 |
if let Some(rect) = self.atlases.iter_mut().find_map(|a| a.insert(size)) {
|
|
207 |
|
|
208 |
} else if !self.repack(size) {
|
|
209 |
let mut atlas = Atlas::new(self.texture_size);
|
|
210 |
atlas.insert(size);
|
|
211 |
self.atlases.push(atlas);
|
|
212 |
}
|
|
213 |
true
|
|
214 |
}
|
|
215 |
}
|
|
216 |
}
|
|
217 |
|
|
218 |
#[inline]
|
|
219 |
fn filter_swap_remove<T, F>(vec: &mut Vec<T>, predicate: F)
|
|
220 |
where
|
|
221 |
F: Fn(&T) -> bool,
|
|
222 |
{
|
|
223 |
let mut i = 0;
|
|
224 |
while i < vec.len() {
|
|
225 |
if predicate(&vec[i]) {
|
|
226 |
vec.swap_remove(i);
|
|
227 |
} else {
|
|
228 |
i += 1;
|
|
229 |
}
|
|
230 |
}
|
|
231 |
}
|
|
232 |
|
|
233 |
#[inline]
|
|
234 |
fn prune_push(
|
|
235 |
previous_splits: &mut Vec<Rect>,
|
|
236 |
buffer: &mut [Rect; 4],
|
|
237 |
buffer_size: &mut usize,
|
|
238 |
rect: Rect,
|
|
239 |
) {
|
|
240 |
if !previous_splits.iter().any(|r| r.contains_rect(&rect)) {
|
|
241 |
filter_swap_remove(previous_splits, |s| rect.contains_rect(s));
|
|
242 |
buffer[*buffer_size] = rect;
|
|
243 |
*buffer_size += 1;
|
|
244 |
}
|
|
245 |
}
|
|
246 |
|
|
247 |
fn split_rect(
|
|
248 |
free_rect: Rect,
|
|
249 |
rect: Rect,
|
|
250 |
previous_splits: &mut Vec<Rect>,
|
|
251 |
buffer: &mut [Rect; 4],
|
|
252 |
) -> Option<usize> {
|
|
253 |
let mut buffer_size = 0usize;
|
|
254 |
let split = free_rect.intersects(&rect);
|
|
255 |
if split {
|
|
256 |
if rect.left() > free_rect.left() {
|
|
257 |
let trim = free_rect.right() - rect.left() + 1;
|
|
258 |
prune_push(
|
|
259 |
previous_splits,
|
|
260 |
buffer,
|
|
261 |
&mut buffer_size,
|
|
262 |
free_rect.with_margins(0, -trim, 0, 0),
|
|
263 |
);
|
|
264 |
}
|
|
265 |
if rect.right() < free_rect.right() {
|
|
266 |
let trim = rect.right() - free_rect.left() + 1;
|
|
267 |
prune_push(
|
|
268 |
previous_splits,
|
|
269 |
buffer,
|
|
270 |
&mut buffer_size,
|
|
271 |
free_rect.with_margins(-trim, 0, 0, 0),
|
|
272 |
);
|
|
273 |
}
|
|
274 |
if rect.top() > free_rect.top() {
|
|
275 |
let trim = free_rect.bottom() - rect.top() + 1;
|
|
276 |
prune_push(
|
|
277 |
previous_splits,
|
|
278 |
buffer,
|
|
279 |
&mut buffer_size,
|
|
280 |
free_rect.with_margins(0, 0, 0, -trim),
|
|
281 |
);;
|
|
282 |
}
|
|
283 |
if rect.bottom() < free_rect.bottom() {
|
|
284 |
let trim = rect.bottom() - free_rect.top() + 1;
|
|
285 |
prune_push(
|
|
286 |
previous_splits,
|
|
287 |
buffer,
|
|
288 |
&mut buffer_size,
|
|
289 |
free_rect.with_margins(0, 0, -trim, 0),
|
|
290 |
);;
|
|
291 |
}
|
|
292 |
}
|
|
293 |
if split {
|
|
294 |
Some(buffer_size)
|
|
295 |
} else {
|
|
296 |
None
|
|
297 |
}
|
|
298 |
}
|
|
299 |
|
|
300 |
#[cfg(test)]
|
|
301 |
mod tests {
|
|
302 |
use super::Atlas;
|
|
303 |
use integral_geometry::{Rect, Size};
|
|
304 |
use itertools::Itertools as _;
|
|
305 |
use proptest::prelude::*;
|
|
306 |
|
|
307 |
#[test]
|
|
308 |
fn insert() {
|
|
309 |
let atlas_size = Size::square(16);
|
|
310 |
let mut atlas = Atlas::new(atlas_size);
|
|
311 |
|
|
312 |
assert_eq!(None, atlas.insert(Size::square(20)));
|
|
313 |
|
|
314 |
let rect_size = Size::new(11, 3);
|
|
315 |
let rect = atlas.insert(rect_size).unwrap();
|
|
316 |
|
|
317 |
assert_eq!(rect, Rect::at_origin(rect_size));
|
|
318 |
assert_eq!(2, atlas.free_rects.len());
|
|
319 |
}
|
|
320 |
|
|
321 |
#[derive(Debug, Clone)]
|
|
322 |
struct TestRect(Size);
|
|
323 |
struct TestRectParameters(Size);
|
|
324 |
|
|
325 |
impl Default for TestRectParameters {
|
|
326 |
fn default() -> Self {
|
|
327 |
Self(Size::square(64))
|
|
328 |
}
|
|
329 |
}
|
|
330 |
|
|
331 |
impl Arbitrary for TestRect {
|
|
332 |
type Parameters = TestRectParameters;
|
|
333 |
|
|
334 |
fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
|
|
335 |
(1..=args.0.width, 1..=args.0.height)
|
|
336 |
.prop_map(|(w, h)| TestRect(Size::new(w, h)))
|
|
337 |
.boxed()
|
|
338 |
}
|
|
339 |
|
|
340 |
type Strategy = BoxedStrategy<TestRect>;
|
|
341 |
}
|
|
342 |
|
|
343 |
trait HasSize {
|
|
344 |
fn size(&self) -> Size;
|
|
345 |
}
|
|
346 |
|
|
347 |
impl HasSize for TestRect {
|
|
348 |
fn size(&self) -> Size {
|
|
349 |
self.0
|
|
350 |
}
|
|
351 |
}
|
|
352 |
|
|
353 |
impl HasSize for Rect {
|
|
354 |
fn size(&self) -> Size {
|
|
355 |
self.size()
|
|
356 |
}
|
|
357 |
}
|
|
358 |
|
|
359 |
fn sum_area<S: HasSize>(items: &[S]) -> usize {
|
|
360 |
items.iter().map(|s| s.size().area()).sum()
|
|
361 |
}
|
|
362 |
|
|
363 |
proptest! {
|
|
364 |
#[test]
|
|
365 |
fn prop_insert(rects in Vec::<TestRect>::arbitrary()) {
|
|
366 |
let container = Rect::at_origin(Size::square(2048));
|
|
367 |
let mut atlas = Atlas::new(container.size());
|
|
368 |
let inserted: Vec<_> = rects.iter().filter_map(|TestRect(size)| atlas.insert(*size)).collect();
|
|
369 |
|
|
370 |
let mut inserted_pairs = inserted.iter().cartesian_product(inserted.iter());
|
|
371 |
|
|
372 |
assert!(inserted.iter().all(|r| container.contains_rect(r)));
|
|
373 |
assert!(inserted_pairs.all(|(r1, r2)| r1 == r2 || r1 != r2 && !r1.intersects(r2)));
|
|
374 |
|
|
375 |
assert_eq!(inserted.len(), rects.len());
|
|
376 |
assert_eq!(sum_area(&inserted), sum_area(&rects));
|
|
377 |
}
|
|
378 |
}
|
|
379 |
|
|
380 |
proptest! {
|
|
381 |
#[test]
|
|
382 |
fn prop_insert_set(rects in Vec::<TestRect>::arbitrary()) {
|
|
383 |
let container = Rect::at_origin(Size::square(2048));
|
|
384 |
let mut atlas = Atlas::new(container.size());
|
|
385 |
let mut set_atlas = Atlas::new(container.size());
|
|
386 |
|
|
387 |
let inserted: Vec<_> = rects.iter().filter_map(|TestRect(size)| atlas.insert(*size)).collect();
|
|
388 |
let set_inserted: Vec<_> = set_atlas.insert_set(rects.iter().map(|TestRect(size)| *size));
|
|
389 |
|
|
390 |
let mut set_inserted_pairs = set_inserted.iter().cartesian_product(set_inserted.iter());
|
|
391 |
|
|
392 |
assert!(set_inserted_pairs.all(|(r1, r2)| r1 == r2 || r1 != r2 && !r1.intersects(r2)));
|
|
393 |
assert!(set_atlas.used_space().used() <= atlas.used_space().used());
|
|
394 |
|
|
395 |
assert_eq!(sum_area(&set_inserted), sum_area(&inserted));
|
|
396 |
}
|
|
397 |
}
|
|
398 |
}
|