Skip to content

Sprite Sheet Packer — Swift source

Pack loose sprites into one optimized sheet with atlas JSON and CSS — entirely in your browser. Nothing uploads.

This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.

// sprite-sheet-packer — MaxRects best-short-side-fit sheet packer. Swift port
// (canonical TS: src/lib/sprite-packer.ts), standard library only: validation,
// biggest-first ordering, sheet growth, MaxRects splitting, power-of-two
// rounding, plus the JSON-atlas and CSS emitters (Foundation for
// String(format:) in the JSON escaper).
import Foundation

// One input sprite.
struct SpriteSize {
  let id: String
  let w: Int
  let h: Int
}

// One placed sprite on the sheet.
struct PackedRect {
  let id: String
  let x: Int, y: Int, w: Int, h: Int
  let rotated: Bool
}

// The final sheet: power-of-two dims plus rects in input order.
struct PackResult {
  let sheetW: Int
  let sheetH: Int
  let rects: [PackedRect]
}

// Mirrors the TS PackOptions.
struct PackOptions {
  var maxWidth = 4096
  var maxHeight = 4096
  var allowRotate = false
}

// Error codes mirror the TS PackErrorCode union.
enum PackErrorCode {
  case empty
  case invalid
  case overflow
}

// The Swift twin of the TS PackError class.
struct PackError: Error {
  let code: PackErrorCode
  let message: String
}

struct FreeRect {
  let x: Int, y: Int, w: Int, h: Int
}

let MIN_SHEET = 64

func pow2ceil(_ n: Int) -> Int {
  var p = 1
  while p < n { p *= 2 }
  return p
}

func pow2floor(_ n: Int) -> Int {
  var p = 1
  while p * 2 <= n { p *= 2 }
  return p
}

func containsRect(_ 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
}

// Best short side fit, ties broken by the long side, then by first-seen free
// rect. Returns the winning (free rect, w, h, rotated) or nil.
func bestFit(_ free: [FreeRect], _ s: SpriteSize, _ allowRotate: Bool)
  -> (FreeRect, Int, Int, Bool)? {
  var best: (FreeRect, Int, Int, Bool)? = nil
  var bestShort = 0, bestLong = 0
  var candidates: [(Int, Int, Bool)] = [(s.w, s.h, false)]
  if allowRotate && s.w != s.h { candidates.append((s.h, s.w, true)) }
  for f in free {
    for (cw, ch, rotated) in candidates {
      if cw > f.w || ch > f.h { continue }
      let leftoverW = f.w - cw
      let leftoverH = f.h - ch
      let shortSide = min(leftoverW, leftoverH)
      let longSide = max(leftoverW, leftoverH)
      if best == nil || shortSide < bestShort || (shortSide == bestShort && longSide < bestLong) {
        best = (f, cw, ch, rotated)
        bestShort = shortSide
        bestLong = longSide
      }
    }
  }
  return best
}

// MaxRects split: carve the placed rect out of every free rect it touches,
// then prune contained ones (the j<i clause keeps exactly one of an identical
// pair).
func splitFree(_ free: [FreeRect], _ p: PackedRect) -> [FreeRect] {
  var next: [FreeRect] = []
  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.append(f)
      continue
    }
    if p.x > f.x { next.append(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.append(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.append(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.append(FreeRect(x: f.x, y: p.y + p.h, w: f.w, h: f.y + f.h - (p.y + p.h)))
    }
  }
  return next.enumerated().filter { i, a in
    !next.enumerated().contains { j, b in
      j != i && containsRect(b, a) && !(containsRect(a, b) && j > i)
    }
  }.map { $0.1 }
}

// One MaxRects pass over a fixed candidate sheet: all rects, or the first id
// that failed (nil result carries the failed id).
func tryPack(_ order: [SpriteSize], _ W: Int, _ H: Int, _ allowRotate: Bool)
  -> ([PackedRect], String?) {
  var free = [FreeRect(x: 0, y: 0, w: W, h: H)]
  var placed: [PackedRect] = []
  for s in order {
    guard let (f, cw, ch, rotated) = bestFit(free, s, allowRotate) else {
      return (placed, s.id)
    }
    let rect = PackedRect(id: s.id, x: f.x, y: f.y, w: cw, h: ch, rotated: rotated)
    placed.append(rect)
    free = splitFree(free, rect)
  }
  return (placed, nil)
}

// Reorder to input order and round the bounding box up to power-of-two sheet
// dims.
func finish(_ sizes: [SpriteSize], _ placed: [PackedRect]) -> PackResult {
  var byId: [String: PackedRect] = [:]
  var bw = 1, bh = 1
  for p in placed {
    byId[p.id] = p
    bw = max(bw, p.x + p.w)
    bh = max(bh, p.y + p.h)
  }
  return PackResult(
    sheetW: pow2ceil(bw),
    sheetH: pow2ceil(bh),
    rects: sizes.map { byId[$0.id]! })
}

/// MaxRects best-short-side-fit packing over a growing power-of-two sheet.
func pack(_ sizes: [SpriteSize], opts: PackOptions = PackOptions()) throws -> PackResult {
  if sizes.isEmpty { throw PackError(code: .empty, message: "Nothing to pack — add at least one sprite.") }
  for s in sizes {
    if s.w <= 0 || s.h <= 0 {
      throw PackError(code: .invalid, message: "Sprite \"\(s.id)\" needs positive pixel dimensions.")
    }
  }
  for s in sizes where sizes.filter({ $0.id == s.id }).count > 1 {
    throw PackError(code: .invalid, message: "Duplicate sprite id \"\(s.id)\".")
  }

  // Biggest sprites first (max side, then area, then id). Ids are unique
  // (validated above), so the key is a total order and sort instability
  // cannot change the result.
  let order = sizes.sorted {
    let ma = max($0.w, $0.h), mb = max($1.w, $1.h)
    if ma != mb { return ma > mb }
    let areaA = $0.w * $0.h, areaB = $1.w * $1.h
    if areaA != areaB { return areaA > areaB }
    return $0.id < $1.id
  }

  var sheetW = pow2floor(min(MIN_SHEET, opts.maxWidth))
  var sheetH = pow2floor(min(MIN_SHEET, opts.maxHeight))
  while true {
    let (placed, failed) = tryPack(order, sheetW, sheetH, opts.allowRotate)
    if failed == nil { return finish(sizes, placed) }

    let nextW = sheetW <= sheetH ? sheetW * 2 : sheetW
    let nextH = sheetW <= sheetH ? sheetH : sheetH * 2
    if nextW > opts.maxWidth || nextH > opts.maxHeight {
      throw PackError(
        code: .overflow,
        message: "\"\(failed!)\" does not fit within \(opts.maxWidth)×\(opts.maxHeight)"
          + " — split the batch or raise the cap.")
    }
    sheetW = nextW
    sheetH = nextH
  }
}

// Minimal JSON string escaping (the atlas ids are plain slugs).
func jsonStr(_ s: String) -> String {
  var out = "\""
  for c in s.unicodeScalars {
    switch c {
    case "\"", "\\": out.unicodeScalars += ["\\"]
      out.unicodeScalars.append(c)
    case let c where c.value < 0x20: out += String(format: "\\u%04x", c.value)
    default: out.unicodeScalars.append(c)
    }
  }
  return out + "\""
}

/// Generic JSON atlas: one frame entry per sprite (assembled manually so the
/// entries stay in pack-input order), sheet metadata for engines.
func atlasJson(_ name: String, _ r: PackResult) -> String {
  var out = "{\n  \"frames\": {"
  for (i, rect) in r.rects.enumerated() {
    if i > 0 { out += "," }
    out += "\n    \(jsonStr(rect.id)): {\n"
    out += "      \"frame\": {\n"
    out += "        \"x\": \(rect.x),\n"
    out += "        \"y\": \(rect.y),\n"
    out += "        \"w\": \(rect.w),\n"
    out += "        \"h\": \(rect.h)\n"
    out += "      },\n"
    out += "      \"rotated\": \(rect.rotated)\n"
    out += "    }"
  }
  out += "\n  },\n  \"meta\": {\n"
  out += "    \"size\": {\n"
  out += "      \"w\": \(r.sheetW),\n"
  out += "      \"h\": \(r.sheetH)\n"
  out += "    },\n"
  out += "    \"name\": \(jsonStr(name))\n"
  out += "  }\n}"
  return out
}

/// One .sprite-<id> class per rect, positioned against the shared sheet image.
func spriteCss(_ r: PackResult, _ sheetName: String) -> String {
  r.rects.map { rect in
    """
    .sprite-\(rect.id) {
      width: \(rect.w)px;
      height: \(rect.h)px;
      background-image: url('\(sheetName)');
      background-position: -\(rect.x)px -\(rect.y)px;
    }
    """
  }.joined(separator: "\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 →