Sprite Sheet Packer — Rust source
Pack loose sprites into one optimized sheet with atlas JSON and CSS — entirely in your browser. Nothing uploads.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! sprite-sheet-packer — MaxRects best-short-side-fit sheet packer (std only).
//! Rust port of src/lib/sprite-packer.ts: the TS lib is already pure (no
//! canvas, no DOM), so this mirrors the full contract — validation,
//! biggest-first ordering, sheet growth, MaxRects splitting, power-of-two
//! rounding, plus the JSON-atlas and CSS emitters. No crates required.
use std::collections::HashMap;
use std::fmt;
/// Error kinds mirror the TS PackErrorCode union.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackErrorKind {
Empty,
Invalid,
Overflow,
}
/// The Rust twin of the TS PackError class.
#[derive(Debug)]
pub struct PackError {
pub kind: PackErrorKind,
pub message: String,
}
impl PackError {
fn new(kind: PackErrorKind, message: impl Into<String>) -> Self {
Self { kind, message: message.into() }
}
}
impl fmt::Display for PackError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for PackError {}
/// One input sprite.
#[derive(Debug, Clone)]
pub struct SpriteSize {
pub id: String,
pub w: i32,
pub h: i32,
}
/// One placed sprite on the sheet.
#[derive(Debug, Clone)]
pub struct PackedRect {
pub id: String,
pub x: i32,
pub y: i32,
pub w: i32,
pub h: i32,
pub rotated: bool,
}
/// The final sheet: power-of-two dims plus rects in input order.
#[derive(Debug, Clone)]
pub struct PackResult {
pub sheet_w: i32,
pub sheet_h: i32,
pub rects: Vec<PackedRect>,
}
/// Mirrors the TS PackOptions.
#[derive(Debug, Clone)]
pub struct PackOptions {
pub max_width: i32,
pub max_height: i32,
pub allow_rotate: bool,
}
impl Default for PackOptions {
fn default() -> Self {
Self { max_width: DEFAULT_CAP, max_height: DEFAULT_CAP, allow_rotate: false }
}
}
#[derive(Debug, Clone, Copy)]
struct FreeRect {
x: i32,
y: i32,
w: i32,
h: i32,
}
const MIN_SHEET: i32 = 64;
const DEFAULT_CAP: i32 = 4096;
/// MaxRects best-short-side-fit packing over a growing power-of-two sheet.
pub fn pack(sizes: &[SpriteSize], opts: &PackOptions) -> Result<PackResult, PackError> {
if sizes.is_empty() {
return Err(PackError::new(PackErrorKind::Empty, "Nothing to pack — add at least one sprite."));
}
let mut seen: Vec<&str> = Vec::new();
for s in sizes {
if s.w <= 0 || s.h <= 0 {
return Err(PackError::new(
PackErrorKind::Invalid,
format!("Sprite \"{}\" needs positive pixel dimensions.", s.id),
));
}
if seen.contains(&s.id.as_str()) {
return Err(PackError::new(
PackErrorKind::Invalid,
format!("Duplicate sprite id \"{}\".", s.id),
));
}
seen.push(&s.id);
}
// Biggest sprites first (max side, then area, then id).
let mut order: Vec<&SpriteSize> = sizes.iter().collect();
order.sort_by(|a, b| {
b.w.max(b.h).cmp(&a.w.max(a.h))
.then((b.w * b.h).cmp(&(a.w * a.h)))
.then(a.id.cmp(&b.id))
});
let mut sheet_w = pow2_floor(opts.max_width.min(MIN_SHEET));
let mut sheet_h = pow2_floor(opts.max_height.min(MIN_SHEET));
loop {
match try_pack(&order, sheet_w, sheet_h, opts.allow_rotate) {
Ok(placed) => return Ok(finish(sizes, placed)),
Err(failed) => {
let (next_w, next_h) = if sheet_w <= sheet_h {
(sheet_w * 2, sheet_h)
} else {
(sheet_w, sheet_h * 2)
};
if next_w > opts.max_width || next_h > opts.max_height {
return Err(PackError::new(
PackErrorKind::Overflow,
format!(
"\"{}\" does not fit within {}×{} — split the batch or raise the cap.",
failed, opts.max_width, opts.max_height
),
));
}
sheet_w = next_w;
sheet_h = next_h;
}
}
}
}
/// One MaxRects pass over a fixed candidate sheet: all rects, or the first id that failed.
fn try_pack(order: &[&SpriteSize], w: i32, h: i32, allow_rotate: bool) -> Result<Vec<PackedRect>, String> {
let mut free = vec![FreeRect { x: 0, y: 0, w, h }];
let mut placed = Vec::with_capacity(order.len());
for s in order {
let Some(fit) = best_fit(&free, s, allow_rotate) else {
return Err(s.id.clone());
};
let rect = PackedRect {
id: s.id.clone(),
x: fit.f.x,
y: fit.f.y,
w: fit.w,
h: fit.h,
rotated: fit.rotated,
};
free = split_free(free, &rect);
placed.push(rect);
}
Ok(placed)
}
/// A winning placement plus the short/long leftover scores used for the ranking.
struct Fit {
f: FreeRect,
w: i32,
h: i32,
rotated: bool,
short: i32,
long: i32,
}
/// Best short side fit, ties broken by the long side, then by first-seen free rect.
fn best_fit(free: &[FreeRect], s: &SpriteSize, allow_rotate: bool) -> Option<Fit> {
let mut best: Option<Fit> = None;
let mut candidates = vec![(s.w, s.h, false)];
if allow_rotate && s.w != s.h {
candidates.push((s.h, s.w, true));
}
for f in free {
for (cw, ch, rotated) in &candidates {
if *cw > f.w || *ch > f.h {
continue;
}
let leftover_w = f.w - cw;
let leftover_h = f.h - ch;
let short = leftover_w.min(leftover_h);
let long = leftover_w.max(leftover_h);
let better = match &best {
None => true,
Some(b) => short < b.short || (short == b.short && long < b.long),
};
if better {
best = Some(Fit { f: *f, w: *cw, h: *ch, rotated: *rotated, short, long });
}
}
}
best
}
/// MaxRects split: carve the placed rect out of every free rect it touches, then prune contained ones.
fn split_free(free: Vec<FreeRect>, p: &PackedRect) -> Vec<FreeRect> {
let mut next: Vec<FreeRect> = Vec::new();
for f in free {
let intersects =
p.x < f.x + f.w && p.x + p.w > f.x && p.y < f.y + f.h && p.y + p.h > f.y;
if !intersects {
next.push(f);
continue;
}
if p.x > f.x {
next.push(FreeRect { x: f.x, y: f.y, w: p.x - f.x, h: f.h });
}
if p.x + p.w < f.x + f.w {
next.push(FreeRect { x: p.x + p.w, y: f.y, w: f.x + f.w - (p.x + p.w), h: f.h });
}
if p.y > f.y {
next.push(FreeRect { x: f.x, y: f.y, w: f.w, h: p.y - f.y });
}
if p.y + p.h < f.y + f.h {
next.push(FreeRect { x: f.x, y: p.y + p.h, w: f.w, h: f.y + f.h - (p.y + p.h) });
}
}
// Prune free rects fully contained in another; the j<i clause keeps exactly
// one of an identical pair.
let snapshot = next.clone();
next.into_iter()
.enumerate()
.filter(|(i, a)| {
!snapshot.iter().enumerate().any(|(j, b)| {
j != *i && contains(b, *a) && !(contains(*a, b) && j > *i)
})
})
.map(|(_, a)| a)
.collect()
}
fn contains(outer: FreeRect, inner: FreeRect) -> bool {
outer.x <= inner.x
&& outer.y <= inner.y
&& outer.x + outer.w >= inner.x + inner.w
&& outer.y + outer.h >= inner.y + inner.h
}
/// Reorder to input order and round the bounding box up to power-of-two sheet dims.
fn finish(sizes: &[SpriteSize], placed: Vec<PackedRect>) -> PackResult {
let mut by_id: HashMap<String, PackedRect> =
placed.into_iter().map(|p| (p.id.clone(), p)).collect();
let mut bw = 1;
let mut bh = 1;
for s in sizes {
if let Some(p) = by_id.get(&s.id) {
bw = bw.max(p.x + p.w);
bh = bh.max(p.y + p.h);
}
}
let rects = sizes
.iter()
.map(|s| by_id.remove(&s.id).expect("validated ids always place"))
.collect();
PackResult { sheet_w: pow2_ceil(bw), sheet_h: pow2_ceil(bh), rects }
}
fn pow2_ceil(n: i32) -> i32 {
let mut p = 1;
while p < n {
p *= 2;
}
p
}
fn pow2_floor(n: i32) -> i32 {
let mut p = 1;
while p * 2 <= n {
p *= 2;
}
p
}
/// Minimal JSON string escaping (std-only; the atlas ids are plain slugs).
fn json_str(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// Generic JSON atlas: one frame entry per sprite (in pack-input order — the
/// object is assembled manually to keep that order deterministic), sheet
/// metadata for engines.
pub fn atlas_json(name: &str, r: &PackResult) -> String {
let mut parts = Vec::with_capacity(r.rects.len());
for rect in &r.rects {
parts.push(format!(
"\n {}: {{\n \"frame\": {{ \"x\": {}, \"y\": {}, \"w\": {}, \"h\": {} }},\n \"rotated\": {}\n }}",
json_str(&rect.id),
rect.x,
rect.y,
rect.w,
rect.h,
rect.rotated
));
}
format!(
"{{\n \"frames\": {{{},\n }},\n \"meta\": {{\n \"size\": {{ \"w\": {}, \"h\": {} }},\n \"name\": {}\n }}\n}}",
parts.join(","),
r.sheet_w,
r.sheet_h,
json_str(name)
)
}
/// One .sprite-<id> class per rect, positioned against the shared sheet image.
pub fn sprite_css(r: &PackResult, sheet_name: &str) -> String {
r.rects
.iter()
.map(|rect| {
format!(
".sprite-{} {{\n width: {}px;\n height: {}px;\n background-image: url('{}');\n background-position: -{}px -{}px;\n}}",
rect.id, rect.w, rect.h, sheet_name, rect.x, rect.y
)
})
.collect::<Vec<_>>()
.join("\n")
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →