Skip to content

Sprite Sheet Packer — Ruby source

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

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

# sprite-sheet-packer — MaxRects best-short-side-fit sheet packer. Ruby port
# (canonical TS: src/lib/sprite-packer.ts), stdlib only (json): validation,
# biggest-first ordering, sheet growth, MaxRects splitting, power-of-two
# rounding, plus the JSON-atlas and CSS emitters.
require 'json'

module SpriteSheetPacker
  # The Ruby twin of the TS PackError class.
  PackError = Class.new(StandardError) do
    attr_reader :code # 'empty' | 'invalid' | 'overflow'

    def initialize(code, message)
      super(message)
      @code = code
    end
  end

  SpriteSize = Struct.new(:id, :w, :h)
  PackedRect = Struct.new(:id, :x, :y, :w, :h, :rotated)
  PackResult = Struct.new(:sheet_w, :sheet_h, :rects)
  PackOptions = Struct.new(:max_width, :max_height, :allow_rotate) do
    def initialize(max_width = 4096, max_height = 4096, allow_rotate = false)
      super
    end
  end

  FreeRect = Struct.new(:x, :y, :w, :h)

  MIN_SHEET = 64

  module_function

  def pow2ceil(n)
    p = 1
    p *= 2 while p < n
    p
  end

  def pow2floor(n)
    p = 1
    p *= 2 while p * 2 <= n
    p
  end

  def contains(outer, inner)
    outer.x <= inner.x && outer.y <= inner.y &&
      outer.x + outer.w >= inner.x + inner.w &&
      outer.y + outer.h >= inner.y + inner.h
  end

  # Best short side fit, ties broken by the long side, then by first-seen
  # free rect. Returns (free_rect, w, h, rotated) or nil.
  def best_fit(free, s, allow_rotate)
    best = nil
    best_short = 0
    best_long = 0
    candidates = [[s.w, s.h, false]]
    candidates << [s.h, s.w, true] if allow_rotate && s.w != s.h
    free.each do |f|
      candidates.each do |cw, ch, rotated|
        next if cw > f.w || ch > f.h
        leftover_w = f.w - cw
        leftover_h = f.h - ch
        short_side = [leftover_w, leftover_h].min
        long_side = [leftover_w, leftover_h].max
        if best.nil? || short_side < best_short || (short_side == best_short && long_side < best_long)
          best = [f, cw, ch, rotated, short_side, long_side]
          best_short = short_side
          best_long = long_side
        end
      end
    end
    best
  end

  # 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).
  def split_free(free, p)
    nxt = []
    free.each do |f|
      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
      unless intersects
        nxt << f
        next
      end
      nxt << FreeRect.new(f.x, f.y, p.x - f.x, f.h) if p.x > f.x
      nxt << FreeRect.new(p.x + p.w, f.y, f.x + f.w - (p.x + p.w), f.h) if p.x + p.w < f.x + f.w
      nxt << FreeRect.new(f.x, f.y, f.w, p.y - f.y) if p.y > f.y
      nxt << FreeRect.new(f.x, p.y + p.h, f.w, f.y + f.h - (p.y + p.h)) if p.y + p.h < f.y + f.h
    end
    nxt.each_with_index.select do |(a, i)|
      nxt.each_with_index.none? do |b, j|
        j != i && contains(b, a) && !(contains(a, b) && j > i)
      end
    end.map { |(a, _i)| a }
  end

  # One MaxRects pass over a fixed candidate sheet: rects, or the failed id.
  def try_pack(order, w, h, allow_rotate)
    free = [FreeRect.new(0, 0, w, h)]
    placed = []
    order.each do |s|
      best = best_fit(free, s, allow_rotate)
      return placed, s.id unless best
      f, cw, ch, rotated = best
      rect = PackedRect.new(s.id, f.x, f.y, cw, ch, rotated)
      placed << rect
      free = split_free(free, rect)
    end
    [placed, nil]
  end

  # Reorder to input order and round the bounding box up to power-of-two
  # sheet dims.
  def finish(sizes, placed)
    by_id = placed.each_with_object({}) { |p, h| h[p.id] = p }
    bw = 1
    bh = 1
    placed.each do |p|
      bw = [bw, p.x + p.w].max
      bh = [bh, p.y + p.h].max
    end
    PackResult.new(pow2ceil(bw), pow2ceil(bh), sizes.map { |s| by_id.fetch(s.id) })
  end

  # MaxRects best-short-side-fit packing over a growing power-of-two sheet.
  def pack(sizes, opts = PackOptions.new)
    raise PackError.new('empty', 'Nothing to pack — add at least one sprite.') if sizes.empty?

    sizes.each do |s|
      raise PackError.new('invalid', "Sprite \"#{s.id}\" needs positive pixel dimensions.") if s.w <= 0 || s.h <= 0
    end
    ids = sizes.map(&:id)
    sizes.each do |s|
      raise PackError.new('invalid', "Duplicate sprite id \"#{s.id}\".") if ids.count(s.id) > 1
    end

    # 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.
    order = sizes.sort_by { |s| [-[s.w, s.h].max, -(s.w * s.h), s.id] }

    sheet_w = pow2floor([MIN_SHEET, opts.max_width].min)
    sheet_h = pow2floor([MIN_SHEET, opts.max_height].min)
    loop do
      placed, failed = try_pack(order, sheet_w, sheet_h, opts.allow_rotate)
      return finish(sizes, placed) unless failed

      next_w = sheet_w <= sheet_h ? sheet_w * 2 : sheet_w
      next_h = sheet_w <= sheet_h ? sheet_h : sheet_h * 2
      if next_w > opts.max_width || next_h > opts.max_height
        raise PackError.new(
          'overflow',
          "\"#{failed}\" does not fit within #{opts.max_width}×#{opts.max_height}" \
          ' — split the batch or raise the cap.'
        )
      end
      sheet_w = next_w
      sheet_h = next_h
    end
  end

  # Minimal JSON string escaping (the atlas ids are plain slugs).
  def json_str(s)
    out = '"'
    s.each_char do |c|
      if c == '"' || c == '\\'
        out << '\\' << c
      elsif c.ord < 0x20
        out << format('\u%04x', c.ord)
      else
        out << c
      end
    end
    out << '"'
  end

  # Generic JSON atlas: one frame entry per sprite (assembled manually so the
  # entries stay in pack-input order), sheet metadata for engines.
  def atlas_json(name, r)
    out = +"{\n  \"frames\": {"
    r.rects.each_with_index do |rect, i|
      out << ',' if i.positive?
      out << "\n    " << json_str(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 << "    }"
    end
    out << "\n  },\n  \"meta\": {\n"
    out << "    \"size\": {\n"
    out << "      \"w\": #{r.sheet_w},\n"
    out << "      \"h\": #{r.sheet_h}\n"
    out << "    },\n"
    out << "    \"name\": " << json_str(name) << "\n"
    out << "  }\n}"
  end

  # One .sprite-<id> class per rect, positioned against the shared sheet image.
  def sprite_css(r, sheet_name)
    r.rects.map do |rect|
      ".sprite-#{rect.id} {\n" \
        "  width: #{rect.w}px;\n" \
        "  height: #{rect.h}px;\n" \
        "  background-image: url('#{sheet_name}');\n" \
        "  background-position: -#{rect.x}px -#{rect.y}px;\n" \
        '}'
    end.join("\n")
  end
end

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 →