fastpack_core/algorithms/
maxrects.rs1use rayon::prelude::*;
2
3use crate::{
4 error::CoreError,
5 types::{
6 config::{LayoutConfig, MaxRectsHeuristic},
7 rect::{Rect, Size},
8 sprite::Sprite,
9 },
10};
11
12use super::packer::{PackInput, PackOutput, PlacedSprite, Placement};
13
14#[derive(Default)]
24pub struct MaxRects {
25 pub heuristic: MaxRectsHeuristic,
27}
28
29impl super::packer::Packer for MaxRects {
30 fn pack(&self, input: PackInput) -> Result<PackOutput, CoreError> {
31 if input.sprites.is_empty() {
32 return Err(CoreError::NoSprites);
33 }
34 Ok(pack_sprites(input, self.heuristic))
35 }
36
37 fn name(&self) -> &'static str {
38 "maxrects"
39 }
40}
41
42fn pack_sprites(input: PackInput, heuristic: MaxRectsHeuristic) -> PackOutput {
43 use crate::types::config::PackMode;
44
45 let cfg = &input.config;
46 let mut sprites = input.sprites;
47 sprites.sort_unstable_by(|a, b| {
49 let area_a = a.image.width() * a.image.height();
50 let area_b = b.image.width() * b.image.height();
51 area_b.cmp(&area_a)
52 });
53
54 let pack_with = |h: MaxRectsHeuristic| match cfg.pack_mode {
55 PackMode::Fast => pack_at_width(&sprites, cfg, h, cfg.max_width),
56 PackMode::Good => binary_search_width(&sprites, cfg, h),
57 PackMode::Best => exhaustive_width_search(&sprites, cfg, h),
58 };
59
60 if heuristic != MaxRectsHeuristic::Best {
61 return pack_with(heuristic);
62 }
63
64 MaxRectsHeuristic::CONCRETE
68 .par_iter()
69 .map(|&h| pack_with(h))
70 .min_by_key(|out| {
71 (
72 out.overflow.len(),
73 out.atlas_size.w as u64 * out.atlas_size.h as u64,
74 )
75 })
76 .expect("CONCRETE is non-empty")
77}
78
79fn min_viable_width(sprites: &[Sprite], cfg: &LayoutConfig) -> u32 {
81 let bp = cfg.border_padding;
82 let sp = cfg.shape_padding;
83 sprites
84 .iter()
85 .map(|s| {
86 let w = s.image.width() + sp + bp * 2;
87 let h = s.image.height() + sp + bp * 2;
88 if cfg.allow_rotation { w.min(h) } else { w }
89 })
90 .max()
91 .unwrap_or(64)
92 .min(cfg.max_width)
93}
94
95fn binary_search_width(
96 sprites: &[Sprite],
97 cfg: &LayoutConfig,
98 heuristic: MaxRectsHeuristic,
99) -> PackOutput {
100 let lo_start = min_viable_width(sprites, cfg);
102 let mut lo = lo_start;
103 let mut hi = cfg.max_width;
104 let mut w_min = cfg.max_width;
105
106 while lo <= hi {
107 let mid = lo + (hi - lo) / 2;
108 let result = pack_at_width(sprites, cfg, heuristic, mid);
109 if result.overflow.is_empty() {
110 w_min = mid;
111 if mid == 0 {
112 break;
113 }
114 hi = mid - 1;
115 } else {
116 lo = mid + 1;
117 }
118 }
119
120 let step = (w_min / 64).max(2);
127 let fine_end = (w_min + w_min / 4).min(cfg.max_width);
128 let mut candidates: Vec<u32> = (w_min..=fine_end).step_by(step as usize).collect();
129 let mut w = fine_end;
131 loop {
132 let next = ((w as f64 * 1.414) as u32).min(cfg.max_width);
133 if next == w {
134 break;
135 }
136 candidates.push(next);
137 w = next;
138 if w >= cfg.max_width {
139 break;
140 }
141 }
142
143 let best = candidates
144 .par_iter()
145 .filter_map(|&cw| {
146 let result = pack_at_width(sprites, cfg, heuristic, cw);
147 if result.overflow.is_empty() {
148 let area = result.atlas_size.w * result.atlas_size.h;
149 Some((area, result))
150 } else {
151 None
152 }
153 })
154 .min_by_key(|(area, _)| *area)
155 .map(|(_, result)| result);
156
157 best.unwrap_or_else(|| pack_at_width(sprites, cfg, heuristic, cfg.max_width))
158}
159
160fn exhaustive_width_search(
161 sprites: &[Sprite],
162 cfg: &LayoutConfig,
163 heuristic: MaxRectsHeuristic,
164) -> PackOutput {
165 let lo_start = min_viable_width(sprites, cfg);
166 let good = binary_search_width(sprites, cfg, heuristic);
169 let best_w = good.atlas_size.w;
170
171 let sweep_lo = lo_start.max(best_w.saturating_sub(best_w / 8));
172 let sweep_hi = (best_w + best_w / 8).min(cfg.max_width);
173
174 let mut best = good;
175 if let Some(candidate) = (sweep_lo..=sweep_hi)
176 .into_par_iter()
177 .filter_map(|w| {
178 let candidate = pack_at_width(sprites, cfg, heuristic, w);
179 if candidate.overflow.is_empty() {
180 let area = candidate.atlas_size.w * candidate.atlas_size.h;
181 Some((area, candidate))
182 } else {
183 None
184 }
185 })
186 .min_by_key(|(area, _)| *area)
187 .map(|(_, c)| c)
188 && candidate.atlas_size.w * candidate.atlas_size.h < best.atlas_size.w * best.atlas_size.h
189 {
190 best = candidate;
191 }
192 best
193}
194
195fn pack_at_width(
196 sprites: &[Sprite],
197 cfg: &LayoutConfig,
198 heuristic: MaxRectsHeuristic,
199 width: u32,
200) -> PackOutput {
201 let bp = cfg.border_padding;
202 let sp = cfg.shape_padding;
203
204 let canvas_w = width.saturating_sub(bp * 2);
205 let canvas_h = cfg.max_height.saturating_sub(bp * 2);
206 let mut free_rects: Vec<Rect> = vec![Rect::new(bp, bp, canvas_w, canvas_h)];
207
208 let mut placed: Vec<PlacedSprite> = Vec::with_capacity(sprites.len());
209 let mut overflow: Vec<Sprite> = Vec::new();
210
211 for sprite in sprites {
212 let sw = sprite.image.width();
213 let sh = sprite.image.height();
214 let fw = sw + sp;
216 let fh = sh + sp;
217
218 match find_best(&free_rects, fw, fh, cfg.allow_rotation, heuristic) {
219 None => overflow.push(sprite.clone()),
220 Some((dest_x, dest_y, rotated)) => {
221 let (placed_w, placed_h) = if rotated { (sh, sw) } else { (sw, sh) };
222 let (foot_w, foot_h) = if rotated {
223 (sh + sp, sw + sp)
224 } else {
225 (fw, fh)
226 };
227 let dest = Rect::new(dest_x, dest_y, placed_w, placed_h);
228 let footprint = Rect::new(dest_x, dest_y, foot_w, foot_h);
229 split_and_prune(&mut free_rects, footprint);
230 placed.push(PlacedSprite {
231 placement: Placement {
232 sprite_id: sprite.id.clone(),
233 dest,
234 rotated,
235 },
236 sprite: sprite.clone(),
237 });
238 }
239 }
240 }
241
242 let atlas_size = compute_atlas_size(&placed, bp, cfg);
243 PackOutput {
244 placed,
245 atlas_size,
246 overflow,
247 }
248}
249
250fn find_best(
251 free_rects: &[Rect],
252 fw: u32,
253 fh: u32,
254 allow_rotation: bool,
255 heuristic: MaxRectsHeuristic,
256) -> Option<(u32, u32, bool)> {
257 let mut best_x = 0u32;
258 let mut best_y = 0u32;
259 let mut best_rotated = false;
260 let mut best_primary = i64::MAX;
261 let mut best_secondary = i64::MAX;
262 let mut found = false;
263
264 for r in free_rects {
265 if fw <= r.w && fh <= r.h {
266 let (p, s) = score(r, fw, fh, heuristic);
267 if p < best_primary || (p == best_primary && s < best_secondary) {
268 best_primary = p;
269 best_secondary = s;
270 best_x = r.x;
271 best_y = r.y;
272 best_rotated = false;
273 found = true;
274 }
275 }
276 if allow_rotation && fw != fh && fh <= r.w && fw <= r.h {
277 let (p, s) = score(r, fh, fw, heuristic);
278 if p < best_primary || (p == best_primary && s < best_secondary) {
279 best_primary = p;
280 best_secondary = s;
281 best_x = r.x;
282 best_y = r.y;
283 best_rotated = true;
284 found = true;
285 }
286 }
287 }
288
289 if found {
290 Some((best_x, best_y, best_rotated))
291 } else {
292 None
293 }
294}
295
296fn score(rect: &Rect, fw: u32, fh: u32, heuristic: MaxRectsHeuristic) -> (i64, i64) {
297 let lw = (rect.w - fw) as i64;
298 let lh = (rect.h - fh) as i64;
299 match heuristic {
300 MaxRectsHeuristic::BestShortSideFit | MaxRectsHeuristic::Best => (lw.min(lh), lw.max(lh)),
303 MaxRectsHeuristic::BestLongSideFit => (lw.max(lh), lw.min(lh)),
304 MaxRectsHeuristic::BestAreaFit | MaxRectsHeuristic::ContactPointRule => {
305 let waste = (rect.w * rect.h - fw * fh) as i64;
306 (waste, lw.min(lh))
307 }
308 MaxRectsHeuristic::BottomLeftRule => (rect.y as i64, rect.x as i64),
309 }
310}
311
312fn split_and_prune(free_rects: &mut Vec<Rect>, placed: Rect) {
313 let mut splits: Vec<Rect> = Vec::new();
314 let mut i = 0;
315
316 while i < free_rects.len() {
317 if free_rects[i].intersects(&placed) {
318 let r = free_rects.remove(i);
319 if placed.x > r.x {
320 splits.push(Rect::new(r.x, r.y, placed.x - r.x, r.h));
321 }
322 if placed.right() < r.right() {
323 splits.push(Rect::new(
324 placed.right(),
325 r.y,
326 r.right() - placed.right(),
327 r.h,
328 ));
329 }
330 if placed.y > r.y {
331 splits.push(Rect::new(r.x, r.y, r.w, placed.y - r.y));
332 }
333 if placed.bottom() < r.bottom() {
334 splits.push(Rect::new(
335 r.x,
336 placed.bottom(),
337 r.w,
338 r.bottom() - placed.bottom(),
339 ));
340 }
341 } else {
342 i += 1;
343 }
344 }
345
346 free_rects.extend(splits);
347 prune(free_rects);
348}
349
350fn prune(rects: &mut Vec<Rect>) {
351 let mut i = 0;
352 while i < rects.len() {
353 let mut dominated = false;
354 for j in 0..rects.len() {
355 if i != j && rects[j].contains(&rects[i]) {
356 dominated = true;
357 break;
358 }
359 }
360 if dominated {
361 rects.remove(i);
362 } else {
363 i += 1;
364 }
365 }
366}
367
368fn compute_atlas_size(placed: &[PlacedSprite], border_padding: u32, cfg: &LayoutConfig) -> Size {
369 if placed.is_empty() {
370 return Size { w: 0, h: 0 };
371 }
372
373 let mut max_x = 0u32;
374 let mut max_y = 0u32;
375 for ps in placed {
376 max_x = max_x.max(ps.placement.dest.right());
377 max_y = max_y.max(ps.placement.dest.bottom());
378 }
379
380 let w = cfg.size_constraint.apply(max_x + border_padding);
381 let h = cfg.size_constraint.apply(max_y + border_padding);
382
383 let (w, h) = if cfg.force_square {
384 let side = w.max(h);
385 (side, side)
386 } else {
387 (w, h)
388 };
389
390 Size {
391 w: w.min(cfg.max_width),
392 h: h.min(cfg.max_height),
393 }
394}