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