Skip to content

Sprite Sheet Packer — TypeScript source

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

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

// sprite-packer — pure MaxRects sheet packer (FEAT-036, BR-02). No canvas,
// no DOM: sprite sizes in, placed rects + atlas documents out, so the packing
// decisions are unit-testable and the island owns all drawing.
export type PackErrorCode = 'empty' | 'invalid' | 'overflow';

export class PackError extends Error {
  code: PackErrorCode;
  constructor(code: PackErrorCode, message: string) {
    super(message);
    this.code = code;
  }
}

export interface SpriteSize {
  id: string;
  w: number;
  h: number;
}

export interface PackedRect {
  id: string;
  x: number;
  y: number;
  w: number;
  h: number;
  rotated: boolean;
}

export interface PackResult {
  sheetW: number;
  sheetH: number;
  rects: PackedRect[];
}

export interface PackOptions {
  maxWidth?: number;
  maxHeight?: number;
  allowRotate?: boolean;
}

interface FreeRect {
  x: number;
  y: number;
  w: number;
  h: number;
}

const MIN_SHEET = 64;
const DEFAULT_CAP = 4096;

/**
 * MaxRects best-short-side-fit packing. The sheet starts at the smallest
 * power-of-two candidate that respects the caps (min 64×64) and doubles its
 * smaller dimension until every sprite places; the returned sheet is the
 * power-of-two ceiling of the placed bounding box, so it stays tight AND
 * GPU-friendly. Throws PackError('overflow') naming the sprite that outgrew
 * the caps, and never lets the final sheet exceed them.
 */
export function pack(sizes: SpriteSize[], opts: PackOptions = {}): PackResult {
  if (sizes.length === 0) throw new PackError('empty', 'Nothing to pack — add at least one sprite.');

  const seen = new Set<string>();
  for (const s of sizes) {
    if (!Number.isFinite(s.w) || !Number.isFinite(s.h) || s.w <= 0 || s.h <= 0) {
      throw new PackError('invalid', `Sprite "${s.id}" needs positive pixel dimensions.`);
    }
    if (seen.has(s.id)) throw new PackError('invalid', `Duplicate sprite id "${s.id}".`);
    seen.add(s.id);
  }

  const maxWidth = opts.maxWidth ?? DEFAULT_CAP;
  const maxHeight = opts.maxHeight ?? DEFAULT_CAP;

  // Biggest sprites first (max side, then area, then id) — late small sprites
  // fill gaps instead of fragmenting the sheet. Ids are unique (validated
  // above), so the tiebreak never sees equality.
  const order = [...sizes].sort(
    (a, b) =>
      Math.max(b.w, b.h) - Math.max(a.w, a.h) || b.w * b.h - a.w * a.h || (a.id < b.id ? -1 : 1),
  );

  let sheetW = pow2floor(Math.min(MIN_SHEET, maxWidth));
  let sheetH = pow2floor(Math.min(MIN_SHEET, maxHeight));
  for (;;) {
    const attempt = tryPack(order, sheetW, sheetH, opts.allowRotate === true);
    if (Array.isArray(attempt)) return finish(sizes, attempt);

    const nextW = sheetW <= sheetH ? sheetW * 2 : sheetW;
    const nextH = sheetW <= sheetH ? sheetH : sheetH * 2;
    if (nextW > maxWidth || nextH > maxHeight) {
      throw new PackError(
        'overflow',
        `"${attempt}" does not fit within ${maxWidth}×${maxHeight} — split the batch or raise the cap.`,
      );
    }
    sheetW = nextW;
    sheetH = nextH;
  }
}

/** One MaxRects pass over a fixed candidate sheet: all rects, or the first id that failed. */
function tryPack(order: SpriteSize[], W: number, H: number, allowRotate: boolean): PackedRect[] | string {
  let free: FreeRect[] = [{ x: 0, y: 0, w: W, h: H }];
  const placed: PackedRect[] = [];
  for (const s of order) {
    const best = bestFit(free, s, allowRotate);
    if (!best) return s.id;
    const rect: PackedRect = {
      id: s.id,
      x: best.f.x,
      y: best.f.y,
      w: best.w,
      h: best.h,
      rotated: best.rotated,
    };
    placed.push(rect);
    free = splitFree(free, rect);
  }
  return placed;
}

interface Fit {
  f: FreeRect;
  w: number;
  h: number;
  rotated: boolean;
}

/** Best short side fit, ties broken by the long side, then by first-seen free rect. */
function bestFit(free: FreeRect[], s: SpriteSize, allowRotate: boolean): Fit | null {
  let best: Fit | null = null;
  let bestShort = Infinity;
  let bestLong = Infinity;
  const candidates: { w: number; h: number; rotated: boolean }[] = [{ w: s.w, h: s.h, rotated: false }];
  if (allowRotate && s.w !== s.h) candidates.push({ w: s.h, h: s.w, rotated: true });
  for (const f of free) {
    for (const c of candidates) {
      if (c.w > f.w || c.h > f.h) continue;
      const leftoverW = f.w - c.w;
      const leftoverH = f.h - c.h;
      const short = Math.min(leftoverW, leftoverH);
      const long = Math.max(leftoverW, leftoverH);
      if (short < bestShort || (short === bestShort && long < bestLong)) {
        best = { f, w: c.w, h: c.h, rotated: c.rotated };
        bestShort = short;
        bestLong = long;
      }
    }
  }
  return best;
}

/** MaxRects split: carve the placed rect out of every free rect it touches, then prune contained ones. */
function splitFree(free: FreeRect[], p: PackedRect): FreeRect[] {
  const next: FreeRect[] = [];
  for (const f of free) {
    const 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({ 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({ 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({ 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({ 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 (defensive — splits coincide only in degenerate
  // configs, so the branch is spec-unreachable in practice).
  /* v8 ignore next 1 */
  return next.filter((a, i) => !next.some((b, j) => j !== i && contains(b, a) && !(contains(a, b) && j > i)));
}

function contains(outer: FreeRect, inner: FreeRect): boolean {
  return (
    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. */
function finish(sizes: SpriteSize[], placed: PackedRect[]): PackResult {
  const byId = new Map(placed.map((p) => [p.id, p]));
  let bw = 1;
  let bh = 1;
  for (const p of placed) {
    bw = Math.max(bw, p.x + p.w);
    bh = Math.max(bh, p.y + p.h);
  }
  return {
    sheetW: pow2ceil(bw),
    sheetH: pow2ceil(bh),
    rects: sizes.map((s) => byId.get(s.id)!),
  };
}

function pow2ceil(n: number): number {
  let p = 1;
  while (p < n) p *= 2;
  return p;
}

function pow2floor(n: number): number {
  let p = 1;
  while (p * 2 <= n) p *= 2;
  return p;
}

/** Generic JSON atlas: one frame entry per sprite, sheet metadata for engines. */
export function atlasJson(name: string, r: PackResult): string {
  const frames: Record<string, { frame: { x: number; y: number; w: number; h: number }; rotated: boolean }> = {};
  for (const rect of r.rects) {
    frames[rect.id] = { frame: { x: rect.x, y: rect.y, w: rect.w, h: rect.h }, rotated: rect.rotated };
  }
  return JSON.stringify({ frames, meta: { size: { w: r.sheetW, h: r.sheetH }, name } }, null, 2);
}

/** One .sprite-<id> class per rect, positioned against the shared sheet image. */
export function spriteCss(r: PackResult, sheetName: string): string {
  return r.rects
    .map((rect) =>
      [
        `.sprite-${rect.id} {`,
        `  width: ${rect.w}px;`,
        `  height: ${rect.h}px;`,
        `  background-image: url('${sheetName}');`,
        `  background-position: -${rect.x}px -${rect.y}px;`,
        '}',
      ].join('\n'),
    )
    .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 →