Skip to content

Sprite Sheet Packer — Zig source

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

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

//! sprite-sheet-packer — MaxRects best-short-side-fit sheet packer. Zig 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. Caller owns result.rects
//! and the returned atlas/CSS strings (free with the passed allocator).
const std = @import("std");
const Allocator = std.mem.Allocator;

/// One input sprite.
pub const SpriteSize = struct { id: []const u8, w: i32, h: i32 };

/// One placed sprite on the sheet.
pub const PackedRect = struct {
    id: []const u8,
    x: i32,
    y: i32,
    w: i32,
    h: i32,
    rotated: bool,
};

/// The final sheet: power-of-two dims plus rects in input order.
pub const PackResult = struct {
    sheet_w: i32,
    sheet_h: i32,
    rects: []PackedRect,
};

/// Mirrors the TS PackOptions.
pub const PackOptions = struct {
    max_width: i32 = 4096,
    max_height: i32 = 4096,
    allow_rotate: bool = false,
};

/// Error codes mirror the TS PackErrorCode union.
pub const PackError = error{ Empty, Invalid, Overflow, OutOfMemory };

/// Failure detail for a PackError: the message text is written into the
/// caller-provided struct (error payloads travel out-of-band in Zig).
pub const PackFailure = struct {
    code: PackError = PackError.Empty,
    buf: [256]u8 = undefined,
    message: []const u8 = "",
};

const FreeRect = struct { x: i32, y: i32, w: i32, h: i32 };

const min_sheet = 64;

fn pow2ceil(n: i32) i32 {
    var p: i32 = 1;
    while (p < n) p *= 2;
    return p;
}

fn pow2floor(n: i32) i32 {
    var p: i32 = 1;
    while (p * 2 <= n) p *= 2;
    return p;
}

fn containsRect(outer: FreeRect, inner: FreeRect) bool {
    return outer.x <= inner.x and outer.y <= inner.y and
        outer.x + outer.w >= inner.x + inner.w and
        outer.y + outer.h >= inner.y + inner.h;
}

/// One candidate orientation: upright, plus the rotated twin when allowed.
const Cand = struct { w: i32, h: i32, rotated: bool };

/// 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 null.
const BestFit = struct { f: FreeRect, w: i32, h: i32, rotated: bool };

fn bestFit(free: []const FreeRect, s: SpriteSize, allow_rotate: bool) ?BestFit {
    var best: ?BestFit = null;
    var best_short: i32 = 0;
    var best_long: i32 = 0;
    var cands: [2]Cand = .{ .{ .w = s.w, .h = s.h, .rotated = false }, undefined };
    var n_cands: usize = 1;
    if (allow_rotate and s.w != s.h) {
        cands[1] = .{ .w = s.h, .h = s.w, .rotated = true };
        n_cands = 2;
    }
    for (free) |f| {
        for (cands[0..n_cands]) |c| {
            if (c.w > f.w or c.h > f.h) continue;
            const leftover_w = f.w - c.w;
            const leftover_h = f.h - c.h;
            const short_side = @min(leftover_w, leftover_h);
            const long_side = @max(leftover_w, leftover_h);
            const better = best == null or short_side < best_short or
                (short_side == best_short and long_side < best_long);
            if (better) {
                best = .{ .f = f, .w = c.w, .h = c.h, .rotated = c.rotated };
                best_short = short_side;
                best_long = long_side;
            }
        }
    }
    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). Caller owns the returned slice.
fn splitFree(gpa: Allocator, free: []FreeRect, p: PackedRect) ![]FreeRect {
    var next: std.ArrayList(FreeRect) = .empty;
    errdefer next.deinit(gpa);
    for (free) |f| {
        const intersects = p.x < f.x + f.w and p.x + p.w > f.x and
            p.y < f.y + f.h and p.y + p.h > f.y;
        if (!intersects) {
            try next.append(gpa, f);
            continue;
        }
        if (p.x > f.x) try next.append(gpa, .{ .x = f.x, .y = f.y, .w = p.x - f.x, .h = f.h });
        if (p.x + p.w < f.x + f.w)
            try next.append(gpa, .{ .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) try next.append(gpa, .{ .x = f.x, .y = f.y, .w = f.w, .h = p.y - f.y });
        if (p.y + p.h < f.y + f.h)
            try next.append(gpa, .{ .x = f.x, .y = p.y + p.h, .w = f.w, .h = f.y + f.h - (p.y + p.h) });
    }
    // Prune in place: keep a when no other b (with the j<i identical-pair
    // clause) fully contains it.
    var kept: usize = 0;
    outer: for (next.items, 0..) |a, i| {
        for (next.items, 0..) |b, j| {
            if (j != i and containsRect(b, a) and !(containsRect(a, b) and j > i)) continue :outer;
        }
        next.items[kept] = a;
        kept += 1;
    }
    next.shrinkRetainingCapacity(kept);
    return next.toOwnedSlice(gpa);
}

/// One MaxRects pass over a fixed candidate sheet: all rects, or the first id
/// that failed (returned through failed_id).
fn tryPack(gpa: Allocator, order: []const SpriteSize, W: i32, H: i32, allow_rotate: bool, placed: []PackedRect, failed_id: *[]const u8) !bool {
    var free: std.ArrayList(FreeRect) = .empty;
    defer free.deinit(gpa);
    try free.append(gpa, .{ .x = 0, .y = 0, .w = W, .h = H });
    for (order, 0..) |s, i| {
        const best = bestFit(free.items, s, allow_rotate) orelse {
            failed_id.* = s.id;
            return false;
        };
        placed[i] = .{
            .id = s.id,
            .x = best.f.x,
            .y = best.f.y,
            .w = best.w,
            .h = best.h,
            .rotated = best.rotated,
        };
        const split = try splitFree(gpa, free.items, placed[i]);
        free.deinit(gpa);
        free = .fromOwnedSlice(split);
    }
    return true;
}

/// Reorder to input order and round the bounding box up to power-of-two
/// sheet dims.
fn finish(gpa: Allocator, sizes: []const SpriteSize, placed: []const PackedRect) !PackResult {
    var bw: i32 = 1;
    var bh: i32 = 1;
    for (placed) |p| {
        bw = @max(bw, p.x + p.w);
        bh = @max(bh, p.y + p.h);
    }
    const rects = try gpa.alloc(PackedRect, sizes.len);
    for (sizes, 0..) |s, i| {
        for (placed) |p| {
            if (std.mem.eql(u8, p.id, s.id)) {
                rects[i] = p;
                break;
            }
        }
    }
    return .{ .sheet_w = pow2ceil(bw), .sheet_h = pow2ceil(bh), .rects = rects };
}

/// MaxRects best-short-side-fit packing over a growing power-of-two sheet.
/// On error, `failure` (when non-null) carries the human-readable message;
/// on success the caller owns `result.rects`.
pub fn pack(gpa: Allocator, sizes: []const SpriteSize, opts: PackOptions, failure: ?*PackFailure) PackError!PackResult {
    if (failure) |f| f.* = .{};
    const fail = struct {
        fn with(f: ?*PackFailure, code: PackError, comptime fmt: []const u8, args: anytype) PackError {
            if (f) |fp| {
                fp.code = code;
                fp.message = std.fmt.bufPrint(&fp.buf, fmt, args) catch fmt;
            }
            return code;
        }
    }.with;

    if (sizes.len == 0) return fail(failure, error.Empty, "Nothing to pack — add at least one sprite.", .{});
    for (sizes) |s| {
        if (s.w <= 0 or s.h <= 0)
            return fail(failure, error.Invalid, "Sprite \"{s}\" needs positive pixel dimensions.", .{s.id});
    }
    for (sizes, 0..) |s, i| {
        for (sizes[0..i]) |seen| {
            if (std.mem.eql(u8, seen.id, s.id))
                return fail(failure, error.Invalid, "Duplicate sprite id \"{s}\".", .{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.
    const order = gpa.dupe(SpriteSize, sizes) catch return error.OutOfMemory;
    defer gpa.free(order);
    std.mem.sort(SpriteSize, order, {}, struct {
        fn lessThan(_: void, a: SpriteSize, b: SpriteSize) bool {
            const ma = @max(a.w, a.h);
            const mb = @max(b.w, b.h);
            if (ma != mb) return ma > mb;
            const aa = a.w * a.h;
            const ab = b.w * b.h;
            if (aa != ab) return aa > ab;
            return std.mem.order(u8, a.id, b.id) == .lt;
        }
    }.lessThan);

    var sheet_w = pow2floor(@min(min_sheet, opts.max_width));
    var sheet_h = pow2floor(@min(min_sheet, opts.max_height));
    const placed = gpa.alloc(PackedRect, sizes.len) catch return error.OutOfMemory;
    while (true) {
        var failed_id: []const u8 = "";
        if (tryPack(gpa, order, sheet_w, sheet_h, opts.allow_rotate, placed, &failed_id) catch return error.OutOfMemory) {
            const result = finish(gpa, sizes, placed) catch {
                gpa.free(placed);
                return error.OutOfMemory;
            };
            gpa.free(placed);
            return result;
        }
        var next_w = sheet_w;
        var next_h = sheet_h;
        if (sheet_w <= sheet_h) next_w = sheet_w * 2 else next_h = sheet_h * 2;
        if (next_w > opts.max_width or next_h > opts.max_height) {
            gpa.free(placed);
            return fail(failure, error.Overflow, "\"{s}\" does not fit within {d}×{d} — split the batch or raise the cap.", .{ failed_id, opts.max_width, opts.max_height });
        }
        sheet_w = next_w;
        sheet_h = next_h;
    }
}

/// Append formatted text to a growable buffer.
fn appendFmt(gpa: Allocator, out: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) !void {
    const piece = try std.fmt.allocPrint(gpa, fmt, args);
    defer gpa.free(piece);
    try out.appendSlice(gpa, piece);
}

/// Minimal JSON string escaping (the atlas ids are plain slugs).
fn jsonStr(gpa: Allocator, s: []const u8) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    errdefer out.deinit(gpa);
    try out.append(gpa, '"');
    for (s) |c| {
        switch (c) {
            '"', '\\' => {
                try out.append(gpa, '\\');
                try out.append(gpa, c);
            },
            else => {
                if (c < 0x20) {
                    try appendFmt(gpa, &out, "\\u{x:0>4}", .{c});
                } else {
                    try out.append(gpa, c);
                }
            },
        }
    }
    try out.append(gpa, '"');
    return out.toOwnedSlice(gpa);
}

/// Generic JSON atlas: one frame entry per sprite (assembled manually so the
/// entries stay in pack-input order), sheet metadata for engines. Caller owns
/// the returned string.
pub fn atlasJson(gpa: Allocator, name: []const u8, r: PackResult) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    errdefer out.deinit(gpa);
    try out.appendSlice(gpa, "{\n  \"frames\": {");
    for (r.rects, 0..) |rect, i| {
        const key = try jsonStr(gpa, rect.id);
        defer gpa.free(key);
        try appendFmt(gpa, &out, "{s}\n    {s}: {{\n      \"frame\": {{\n        \"x\": {d},\n        \"y\": {d},\n        \"w\": {d},\n        \"h\": {d}\n      }},\n      \"rotated\": {}\n    }}", .{ if (i > 0) "," else "", key, rect.x, rect.y, rect.w, rect.h, rect.rotated });
    }
    const name_key = try jsonStr(gpa, name);
    defer gpa.free(name_key);
    try appendFmt(gpa, &out, "\n  }},\n  \"meta\": {{\n    \"size\": {{\n      \"w\": {d},\n      \"h\": {d}\n    }},\n    \"name\": {s}\n  }}\n}}", .{ r.sheet_w, r.sheet_h, name_key });
    return out.toOwnedSlice(gpa);
}

/// One .sprite-<id> class per rect, positioned against the shared sheet
/// image. Caller owns the returned string.
pub fn spriteCss(gpa: Allocator, r: PackResult, sheet_name: []const u8) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    errdefer out.deinit(gpa);
    for (r.rects, 0..) |rect, i| {
        try appendFmt(gpa, &out, "{s}.sprite-{s} {{\n  width: {d}px;\n  height: {d}px;\n  background-image: url('{s}');\n  background-position: -{d}px -{d}px;\n}}", .{ if (i > 0) "\n" else "", rect.id, rect.w, rect.h, sheet_name, rect.x, rect.y });
    }
    return out.toOwnedSlice(gpa);
}

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 →