Sprite Sheet Packer — PHP source
Pack loose sprites into one optimized sheet with atlas JSON and CSS — entirely in your browser. Nothing uploads.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* sprite-sheet-packer — MaxRects best-short-side-fit sheet packer (stdlib only).
* PHP 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 (json ext only).
*/
declare(strict_types=1);
final class PackError extends RuntimeException
{
public function __construct(
public readonly string $code_, // 'empty' | 'invalid' | 'overflow'
string $message,
) {
parent::__construct($message);
}
}
final class SpriteSize
{
public function __construct(
public readonly string $id,
public readonly int $w,
public readonly int $h,
) {}
}
final class PackedRect
{
public function __construct(
public readonly string $id,
public readonly int $x,
public readonly int $y,
public readonly int $w,
public readonly int $h,
public readonly bool $rotated,
) {}
}
final class PackResult
{
/**
* @param list<PackedRect> $rects
*/
public function __construct(
public readonly int $sheetW,
public readonly int $sheetH,
public readonly array $rects,
) {}
}
final class PackOptions
{
public function __construct(
public readonly int $maxWidth = 4096,
public readonly int $maxHeight = 4096,
public readonly bool $allowRotate = false,
) {}
}
final class FreeRect
{
public function __construct(
public readonly int $x,
public readonly int $y,
public readonly int $w,
public readonly int $h,
) {}
}
const MIN_SHEET = 64;
const DEFAULT_CAP = 4096;
/**
* MaxRects best-short-side-fit packing over a growing power-of-two sheet.
* Named packSprites because pack() is a PHP built-in.
*
* @param list<SpriteSize> $sizes
*/
function packSprites(array $sizes, ?PackOptions $opts = null): PackResult
{
$opts = $opts ?? new PackOptions();
if ($sizes === []) {
throw new PackError('empty', 'Nothing to pack — add at least one sprite.');
}
$seen = [];
foreach ($sizes as $s) {
if (!($s->w > 0 && $s->h > 0)) {
throw new PackError('invalid', "Sprite \"{$s->id}\" needs positive pixel dimensions.");
}
if (isset($seen[$s->id])) {
throw new PackError('invalid', "Duplicate sprite id \"{$s->id}\".");
}
$seen[$s->id] = true;
}
// Biggest sprites first (max side, then area, then id).
$order = $sizes;
usort($order, function (SpriteSize $a, SpriteSize $b): int {
$side = max($b->w, $b->h) <=> max($a->w, $a->h);
if ($side !== 0) {
return $side;
}
$area = ($b->w * $b->h) <=> ($a->w * $a->h);
if ($area !== 0) {
return $area;
}
return $a->id <=> $b->id;
});
$sheetW = pow2floor(min(MIN_SHEET, $opts->maxWidth));
$sheetH = pow2floor(min(MIN_SHEET, $opts->maxHeight));
for (;;) {
[$placed, $failed] = tryPack($order, $sheetW, $sheetH, $opts->allowRotate);
if ($failed === null) {
return finishPack($sizes, $placed);
}
$nextW = $sheetW <= $sheetH ? $sheetW * 2 : $sheetW;
$nextH = $sheetW <= $sheetH ? $sheetH : $sheetH * 2;
if ($nextW > $opts->maxWidth || $nextH > $opts->maxHeight) {
throw new PackError(
'overflow',
"\"{$failed}\" does not fit within {$opts->maxWidth}×{$opts->maxHeight} — split the batch or raise the cap."
);
}
[$sheetW, $sheetH] = [$nextW, $nextH];
}
}
/**
* One MaxRects pass over a fixed candidate sheet.
* @return array{0: list<PackedRect>|null, 1: ?string}
*/
function tryPack(array $order, int $w, int $h, bool $allowRotate): array
{
$free = [new FreeRect(0, 0, $w, $h)];
$placed = [];
foreach ($order as $s) {
$best = bestFit($free, $s, $allowRotate);
if ($best === null) {
return [null, $s->id];
}
$rect = new PackedRect($s->id, $best['f']->x, $best['f']->y, $best['w'], $best['h'], $best['rotated']);
$placed[] = $rect;
$free = splitFree($free, $rect);
}
return [$placed, null];
}
/**
* Best short side fit, ties broken by the long side, then by first-seen free rect.
* @return null|array{f: FreeRect, w: int, h: int, rotated: bool}
*/
function bestFit(array $free, SpriteSize $s, bool $allowRotate): ?array
{
$best = null;
$bestShort = PHP_INT_MAX;
$bestLong = PHP_INT_MAX;
$candidates = [['w' => $s->w, 'h' => $s->h, 'rotated' => false]];
if ($allowRotate && $s->w !== $s->h) {
$candidates[] = ['w' => $s->h, 'h' => $s->w, 'rotated' => true];
}
foreach ($free as $f) {
foreach ($candidates as $c) {
if ($c['w'] > $f->w || $c['h'] > $f->h) {
continue;
}
$leftoverW = $f->w - $c['w'];
$leftoverH = $f->h - $c['h'];
$short = min($leftoverW, $leftoverH);
$long = max($leftoverW, $leftoverH);
if ($short < $bestShort || ($short === $bestShort && $long < $bestLong)) {
$best = ['f' => $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.
* @param list<FreeRect> $free
* @return list<FreeRect>
*/
function splitFree(array $free, PackedRect $p): array
{
$next = [];
foreach ($free as $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;
if (!$intersects) {
$next[] = $f;
continue;
}
if ($p->x > $f->x) {
$next[] = new FreeRect($f->x, $f->y, $p->x - $f->x, $f->h);
}
if ($p->x + $p->w < $f->x + $f->w) {
$next[] = new FreeRect($p->x + $p->w, $f->y, $f->x + $f->w - ($p->x + $p->w), $f->h);
}
if ($p->y > $f->y) {
$next[] = new FreeRect($f->x, $f->y, $f->w, $p->y - $f->y);
}
if ($p->y + $p->h < $f->y + $f->h) {
$next[] = new FreeRect($f->x, $p->y + $p->h, $f->w, $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.
$out = [];
foreach ($next as $i => $a) {
$keep = true;
foreach ($next as $j => $b) {
if ($j !== $i && rectContains($b, $a) && !(rectContains($a, $b) && $j > $i)) {
$keep = false;
break;
}
}
if ($keep) {
$out[] = $a;
}
}
return $out;
}
function rectContains(FreeRect $outer, FreeRect $inner): bool
{
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 dims.
* @param list<SpriteSize> $sizes
* @param list<PackedRect> $placed
*/
function finishPack(array $sizes, array $placed): PackResult
{
$byId = [];
$bw = 1;
$bh = 1;
foreach ($placed as $p) {
$byId[$p->id] = $p;
$bw = max($bw, $p->x + $p->w);
$bh = max($bh, $p->y + $p->h);
}
$rects = [];
foreach ($sizes as $s) {
$rects[] = $byId[$s->id];
}
return new PackResult(pow2ceil($bw), pow2ceil($bh), $rects);
}
function pow2ceil(int $n): int
{
$p = 1;
while ($p < $n) {
$p *= 2;
}
return $p;
}
function pow2floor(int $n): int
{
$p = 1;
while ($p * 2 <= $n) {
$p *= 2;
}
return $p;
}
/** Generic JSON atlas: one frame entry per sprite, sheet metadata for engines. */
function atlasJson(string $name, PackResult $r): string
{
$frames = new stdClass(); // property insertion order is preserved by json_encode
foreach ($r->rects as $rect) {
$frames->{$rect->id} = [
'frame' => ['x' => $rect->x, 'y' => $rect->y, 'w' => $rect->w, 'h' => $rect->h],
'rotated' => $rect->rotated,
];
}
return json_encode(
[
'frames' => $frames,
'meta' => ['size' => ['w' => $r->sheetW, 'h' => $r->sheetH], 'name' => $name],
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
}
/** One .sprite-<id> class per rect, positioned against the shared sheet image. */
function spriteCss(PackResult $r, string $sheetName): string
{
$blocks = [];
foreach ($r->rects as $rect) {
$blocks[] = ".sprite-{$rect->id} {\n"
. " width: {$rect->w}px;\n"
. " height: {$rect->h}px;\n"
. " background-image: url('{$sheetName}');\n"
. " background-position: -{$rect->x}px -{$rect->y}px;\n"
. "}";
}
return implode("\n", $blocks);
}
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 →