Skip to content

Sprite Sheet Packer — Kotlin source

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

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

// sprite-sheet-packer — MaxRects best-short-side-fit sheet packer. Kotlin 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.

// One input sprite.
data class SpriteSize(val id: String, val w: Int, val h: Int)

// One placed sprite on the sheet.
data class PackedRect(
    val id: String,
    val x: Int,
    val y: Int,
    val w: Int,
    val h: Int,
    val rotated: Boolean,
)

// The final sheet: power-of-two dims plus rects in input order.
data class PackResult(val sheetW: Int, val sheetH: Int, val rects: List<PackedRect>)

// Mirrors the TS PackOptions.
data class PackOptions(
    val maxWidth: Int = 4096,
    val maxHeight: Int = 4096,
    val allowRotate: Boolean = false,
)

// The Kotlin twin of the TS PackError class.
class PackError(val code: String, message: String) : Exception(message)

// One candidate free rectangle.
class FreeRect(val x: Int, val y: Int, val w: Int, val h: Int)

private const val MIN_SHEET = 64

private fun pow2ceil(n: Int): Int {
    var p = 1
    while (p < n) p *= 2
    return p
}

private fun pow2floor(n: Int): Int {
    var p = 1
    while (p * 2 <= n) p *= 2
    return p
}

private fun contains(outer: FreeRect, inner: FreeRect): Boolean =
    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 fit as (free rect, w, h, rotated), or null. */
private fun bestFit(free: List<FreeRect>, s: SpriteSize, allowRotate: Boolean): Array<out Any>? {
    var best: Array<out Any>? = null
    var bestShort = 0
    var bestLong = 0
    val candidates = mutableListOf(Triple(s.w, s.h, false))
    if (allowRotate && s.w != s.h) candidates.add(Triple(s.h, s.w, true))
    for (f in free) {
        for ((cw, ch, rotated) in candidates) {
            if (cw > f.w || ch > f.h) continue
            val leftoverW = f.w - cw
            val leftoverH = f.h - ch
            val shortSide = minOf(leftoverW, leftoverH)
            val longSide = maxOf(leftoverW, leftoverH)
            if (best == null || shortSide < bestShort || (shortSide == bestShort && longSide < bestLong)) {
                best = arrayOf(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). */
private fun splitFree(free: List<FreeRect>, p: PackedRect): List<FreeRect> {
    val next = mutableListOf<FreeRect>()
    for (f in free) {
        val 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.add(f)
            continue
        }
        if (p.x > f.x) next.add(FreeRect(f.x, f.y, p.x - f.x, f.h))
        if (p.x + p.w < f.x + f.w) next.add(FreeRect(p.x + p.w, f.y, f.x + f.w - (p.x + p.w), f.h))
        if (p.y > f.y) next.add(FreeRect(f.x, f.y, f.w, p.y - f.y))
        if (p.y + p.h < f.y + f.h) next.add(FreeRect(f.x, p.y + p.h, f.w, f.y + f.h - (p.y + p.h)))
    }
    val kept = mutableListOf<FreeRect>()
    for (i in next.indices) {
        val a = next[i]
        var contained = false
        for (j in next.indices) {
            val b = next[j]
            if (j != i && contains(b, a) && !(contains(a, b) && j > i)) {
                contained = true
                break
            }
        }
        if (!contained) kept.add(a)
    }
    return kept
}

/** One MaxRects pass over a fixed candidate sheet: all rects, or the first id
 *  that failed (null result carries the failed id). */
private fun tryPack(order: List<SpriteSize>, W: Int, H: Int, allowRotate: Boolean): Pair<List<PackedRect>, String?> {
    var free = listOf(FreeRect(0, 0, W, H))
    val placed = mutableListOf<PackedRect>()
    for (s in order) {
        val best = bestFit(free, s, allowRotate) ?: return placed to s.id
        val f = best[0] as FreeRect
        val rect = PackedRect(s.id, f.x, f.y, best[1] as Int, best[2] as Int, best[3] as Boolean)
        placed.add(rect)
        free = splitFree(free, rect)
    }
    return placed to null
}

/** Reorder to input order and round the bounding box up to power-of-two
 *  sheet dims. */
private fun finish(sizes: List<SpriteSize>, placed: List<PackedRect>): PackResult {
    val byId = placed.associateBy { it.id }
    var bw = 1
    var bh = 1
    for (p in placed) {
        bw = maxOf(bw, p.x + p.w)
        bh = maxOf(bh, p.y + p.h)
    }
    return PackResult(
        sheetW = pow2ceil(bw),
        sheetH = pow2ceil(bh),
        rects = sizes.map { s -> byId.getValue(s.id) },
    )
}

/** MaxRects best-short-side-fit packing over a growing power-of-two sheet. */
fun pack(sizes: List<SpriteSize>, opts: PackOptions = PackOptions()): PackResult {
    if (sizes.isEmpty()) {
        throw PackError("empty", "Nothing to pack — add at least one sprite.")
    }
    for (s in sizes) {
        if (s.w <= 0 || s.h <= 0) {
            throw PackError("invalid", "Sprite \"${s.id}\" needs positive pixel dimensions.")
        }
        val seen = sizes.takeWhile { it !== s }
        if (seen.any { it.id == s.id }) {
            throw PackError("invalid", "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 stability
    // cannot change the result.
    val order = sizes.sortedWith(
        compareByDescending<SpriteSize> { maxOf(it.w, it.h) }
            .thenByDescending { it.w * it.h }
            .thenBy { it.id },
    )

    var sheetW = pow2floor(minOf(MIN_SHEET, opts.maxWidth))
    var sheetH = pow2floor(minOf(MIN_SHEET, opts.maxHeight))
    while (true) {
        val (placed, failed) = tryPack(order, sheetW, sheetH, opts.allowRotate)
        if (failed == null) return finish(sizes, placed)

        val nextW = if (sheetW <= sheetH) sheetW * 2 else sheetW
        val nextH = if (sheetW <= sheetH) sheetH else sheetH * 2
        if (nextW > opts.maxWidth || nextH > opts.maxHeight) {
            throw PackError(
                "overflow",
                "\"$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). */
private fun jsonStr(s: String): String {
    val out = StringBuilder(s.length + 2)
    out.append('"')
    for (c in s) {
        when {
            c == '"' || c == '\\' -> out.append('\\').append(c)
            c < ' ' -> out.append("\\u%04x".format(c.code))
            else -> out.append(c)
        }
    }
    out.append('"')
    return out.toString()
}

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

/** One .sprite-<id> class per rect, positioned against the shared sheet image. */
fun spriteCss(r: PackResult, sheetName: String): String =
    r.rects.joinToString("\n") { rect ->
        StringBuilder()
            .append(".sprite-").append(rect.id).append(" {\n")
            .append("  width: ").append(rect.w).append("px;\n")
            .append("  height: ").append(rect.h).append("px;\n")
            .append("  background-image: url('").append(sheetName).append("');\n")
            .append("  background-position: -").append(rect.x).append("px -").append(rect.y).append("px;\n")
            .append("}")
            .toString()
    }

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 →