Openhood

Building a sprite atlas cli in Odin

odin gamedev tools Estimated reading time:
Image by by Kenney on Kenney.nl

Let's build a small sprite atlas CLI in Odin and use it to compare six rectangle-packing algorithms on the same folder of PNGs. Given loose sprites and a width limit, the tool packs them into one RGBA8 texture and writes each sprite's name and rectangle as JSON or a Godot 4 SpriteFrames resource.

Odin fits this kind of data-oriented tool well: the packers operate on plain slices of sizes and rectangles, and we only touch pixel buffers once every sprite has coordinates. Odin's core library covers the rest without third-party packages: core:flags parses command-line flags, core:image/png decodes and encodes PNGs, and core:encoding/json serializes the layout struct.

Install Odin (installation instructions) and check your setup with odin version. Every example below targets dev-2026-11a.

From loose PNGs to one texture

Take three CC0 sprites from Kenney's Scribble Planes pack: effect_spark.png, projectile_round.png, and unit_plane_a.png. Packing them with a 1-pixel transparent gutter on every side produces a 132 x 196 PNG where unit_plane_a lands at (1, 67). Those coordinates describe its region inside the atlas, not its position on screen; a game reads that rectangle once and draws the sprite wherever it wants.

Three loose Scribble Planes PNGs, a spark, a projectile, and a plane, packed into one 132 by 196 pixel atlas.

Set up the project

Create a sprite-atlas directory, open a terminal there, and run every command from that root, even when building a package in a subdirectory.

The project ZIP includes the finished CLI source and Kenney's Scribble Planes pack. To run the finished tool, extract everything into sprite-atlas/ and skip to Run it end to end.

If you're coding along, copy just the sprites/ folder from the ZIP into your empty project. You should now have sprites/PNG/Default/unit_plane_a.png and sprites/License.txt. Create build/ for the output; we'll add the source files one at a time.

Here's the layout we'll use, leaving out files we won't need (Large* matches the 2x sprite folder without renaming it):

sprite-atlas/
  atlas/
    build.odin
    pack.odin
    pack_test.odin
    strategies.odin
    grids.odin
  cmd/
    main.odin
    stages.odin
    inspect_sprite/
      main.odin
  exporters/
    export.odin
    extract.odin
  sprites/
    License.txt
    PNG/
      Default/
      Large*/
  build/

In Odin, each directory of .odin files forms a package. Our first package answers one question: how big is unit_plane_a.png?

Start by reading one PNG

Create cmd/inspect_sprite/main.odin. Placement only needs dimensions, so pass {.return_header} to png.load to read the PNG header without decoding pixel data:

package main

import "core:flags"
import "core:fmt"
import "core:image/png"
import "core:os"

Options :: struct {
    path: string `args:"pos=0,required" usage:"Input PNG path."`,
}

main :: proc() {
    options: Options
    flags.parse_or_exit(&options, os.args, .Unix)

    header, err := png.load(options.path, {.return_header})
    if err != nil {
        fmt.eprintln("reading PNG:", err)
        os.exit(1)
    }
    defer png.destroy(header)

    fmt.printf("%d x %d\n", header.width, header.height)
}

From the project root, compile and run the cmd/inspect_sprite package with odin run:

odin run cmd/inspect_sprite -- sprites/PNG/Default/unit_plane_a.png
(out)128 x 128

Everything after -- goes to the compiled program rather than odin. Here that's sprites/PNG/Default/unit_plane_a.png, resolved from the project root, which the pos=0,required tag binds to options.path.

odin run deletes its temporary binary when the program exits. Running odin build cmd/inspect_sprite compiles without executing and writes inspect_sprite (inspect_sprite.exe on Windows) into the current working directory rather than cmd/inspect_sprite/. For the main CLI, we'll pass -out:build/sprite-atlas to name the binary explicitly and keep it inside build/.

Next, create cmd/main.odin for the packer CLI. Its first positional argument selects a subcommand validated against the Command enum. Because each subcommand owns different flags (pack takes a width limit and output directory, while export reads a directory produced by pack), main parses only the subcommand name first and delegates the remaining arguments to run. Leave run as a stub for now:

package main

import "core:flags"
import "core:fmt"
import "core:os"

Command :: enum {
    pack,
    export,
    gen,
    extract,
}

Command_Options :: struct {
    command: Command `args:"pos=0,required" usage:"pack, export, gen, or extract."`,
}

main :: proc() {
    // Parse only the command first; each command owns its own options.
    head_len := min(len(os.args), 2)
    if len(os.args) > 2 && (os.args[1] == "--command" || os.args[1] == "-command" || os.args[1] == "--") {
        head_len = 3
    }

    options: Command_Options
    flags.parse_or_exit(&options, os.args[:head_len], .Unix)
    sub_args := make([]string, len(os.args) - head_len + 1, context.temp_allocator)
    copy(sub_args[1:], os.args[head_len:])
    sub_args[0] = fmt.tprint(options.command)
    if message := run(options.command, sub_args); message != "" {
        fmt.eprintfln("sprite-atlas: %s", message)
        os.exit(1)
    }
}

run :: proc(command: Command, args: []string) -> string {
    panic("not implemented")
}

Help and subcommand validation already work before run is implemented:

odin run cmd -- --help

Passing an unknown subcommand exits with a core:flags error as well. Now we can set the CLI aside and build the rectangle packers without opening a single image.

Pack sizes, not images

Create atlas/pack.odin for the atlas package. Each placement procedure takes a slice of Size values and fills a caller-allocated slice of Rect values, with no file paths, pixel buffers, or engine types involved.

Our baseline Shelf packer starts a row at (0, 0) and pads every sprite with a 1-pixel gutter on all four sides. When the next padded width exceeds max_width, it wraps onto a new shelf below the tallest padded sprite in the current row; if that row would exceed max_height, packing fails.

Placement cost for n sprites: O(n) time, O(1) extra space.

The diagram and test below trace three small rectangles inside a 9-pixel-wide limit. Once gutters are counted, the first two fill the top shelf completely, forcing the third onto a new shelf below the taller second rectangle rather than into the gap beneath the first.

Three numbered rectangles pack onto two shelves. The third wraps below the taller rectangle, leaving a gap under the shorter one.
package atlas

Max_Size :: 4096
Gutter :: 1 // Transparent pixels on each side of every sprite.

Size :: struct {
    width, height: int,
}

Rect :: struct {
    x, y, width, height: int,
}

Pack_Error :: enum {
    None,
    Bad_Arguments,
    Sprite_Too_Large,
    Atlas_Full,
}

// Check before adding gutters so even an oversized input can't overflow.
check_sizes :: proc(sizes: []Size, regions: []Rect, max_width, max_height: int) -> (Pack_Error, int) {
    if len(sizes) == 0 || len(sizes) != len(regions) ||
       max_width < 1 || max_width > Max_Size || max_height < 1 || max_height > Max_Size {
        return .Bad_Arguments, -1
    }
    for size, i in sizes {
        if size.width < 1 || size.height < 1 ||
           size.width > max_width - 2*Gutter || size.height > max_height - 2*Gutter {
            return .Sprite_Too_Large, i
        }
    }
    return .None, -1
}

// Pack in the caller's order. Regions are valid only on success.
pack_shelves :: proc(sizes: []Size, regions: []Rect, max_width, max_height: int) -> (used: Size, err: Pack_Error, index: int) {
    if e, i := check_sizes(sizes, regions, max_width, max_height); e != .None { return {}, e, i }

    x, y, shelf_height := 0, 0, 0
    for size, i in sizes {
        w, h := size.width + 2*Gutter, size.height + 2*Gutter
        if x + w > max_width {
            y += shelf_height
            x, shelf_height = 0, 0
        }
        if y + h > max_height {
            return {}, .Atlas_Full, i
        }

        regions[i] = {x + Gutter, y + Gutter, size.width, size.height}
        x += w
        shelf_height = max(shelf_height, h)
        used.width = max(used.width, x)
    }
    used.height = y + shelf_height
    return used, .None, -1
}

Watch how the cursor and output rectangle differ: x advances by the padded width w, while regions[i] stores (x + Gutter, y + Gutter) with the unpadded sprite dimensions so draw calls never sample the gutter.

Shelves leave unused space beneath shorter sprites on a row, but the arithmetic is easy to verify by hand. Put the diagram's layout and three failure cases into atlas/pack_test.odin; odin test discovers any procedure marked @(test):

package atlas

import "core:testing"

@(test)
shelves_wrap_at_the_tallest_item :: proc(t: ^testing.T) {
    sizes := []Size{{3, 1}, {2, 4}, {6, 2}}
    regions: [3]Rect
    used, err, _ := pack_shelves(sizes, regions[:], 9, 10)
    testing.expect_value(t, err, Pack_Error.None)
    testing.expect_value(t, used, Size{9, 10})
    testing.expect_value(t, regions, [3]Rect{{1, 1, 3, 1}, {6, 1, 2, 4}, {1, 7, 6, 2}})
}

@(test)
rejects_invalid_or_unplaceable_sprites :: proc(t: ^testing.T) {
    regions: [2]Rect
    _, empty_err, _ := pack_shelves(nil, nil, 8, 8)
    testing.expect_value(t, empty_err, Pack_Error.Bad_Arguments)
    _, err, index := pack_shelves({{7, 1}}, regions[:1], 8, 8)
    testing.expect_value(t, err, Pack_Error.Sprite_Too_Large)
    testing.expect_value(t, index, 0)
    _, err, index = pack_shelves({{6, 4}, {6, 4}}, regions[:], 8, 8)
    testing.expect_value(t, err, Pack_Error.Atlas_Full)
    testing.expect_value(t, index, 1)
}

Run the package tests from the project root (your timing will vary):

odin test atlas
(out)Finished 2 tests in 12.837866ms. All tests were successful.

Copy rows into a texture

Once every sprite has a target rectangle, we can copy pixels into the atlas buffer. Within any single row, pixels are contiguous in both images, but the row stride changes: 3 pixels per row in the sprite below versus 8 in the atlas.

Three rows from a 3-pixel-wide sprite are copied into an 8-pixel-wide atlas, starting at column 2, row 1.

Append blit_rgba to atlas/pack.odin. Source rows advance by region.width, destination rows advance by stride_pixels (the atlas width), and multiplying by 4 converts pixel counts into RGBA8 byte offsets:

// Copy tightly packed RGBA8 rows. The caller supplies an in-bounds region
// matching the source dimensions and a destination of whole rows.
blit_rgba :: proc(dst, src: []byte, stride_pixels: int, region: Rect) {
    row_bytes := region.width * 4
    for row in 0..<region.height {
        from := row * row_bytes
        to := ((region.y + row) * stride_pixels + region.x) * 4
        copy(dst[to:to + row_bytes], src[from:from + row_bytes])
    }
}

Packing copies raw RGBA8 bytes without alpha blending. Semitransparent wing edges in unit_plane_a.png keep their exact color and alpha values in the atlas, leaving compositing to the renderer when the sprite is drawn over a scene background.

Gutters come for free from zero initialization: a fresh canvas buffer starts filled with (0, 0, 0, 0) (transparent black), and each copy stops at the sprite's edge, so surrounding gutter pixels remain untouched.

Append a test to atlas/pack_test.odin with one opaque pixel (alpha = 255) and one semitransparent pixel (alpha = 127) to confirm that blit_rgba preserves straight RGBA values and leaves the 1-pixel border zeroed:

@(test)
blit_preserves_rgba_and_leaves_gutters_clear :: proc(t: ^testing.T) {
    dst: [3*4*4]byte
    src := []byte{7, 8, 9, 255, 10, 11, 12, 127}
    blit_rgba(dst[:], src, 4, {1, 1, 1, 2})
    expected: [3*4*4]byte = {20 = 7, 21 = 8, 22 = 9, 23 = 255, 36 = 10, 37 = 11, 38 = 12, 39 = 127}
    testing.expect_value(t, dst, expected)
}

Run the suite again to include the pixel-copy test:

odin test atlas
(out)Finished 3 tests in 12.626272ms. All tests were successful.

Packing algorithms

Shelves aren't the only way to pack an atlas. Feed the same four test rectangles, labeled A through D below, into Shelf, Skyline, and MaxRects. All three place A, B, and C at identical coordinates; they diverge on D because each algorithm tracks empty space differently. Jukka Jylänki's RectangleBinPack surveys the classic variants of all three; we'll implement one compact variant of each in Odin.

Side by side, Shelf starts a new row for D, Skyline puts it below C, and MaxRects fits it beside A in an earlier gap. The same four sprites occupy heights of 10, 9, and 7 pixels.

Skyline (--algorithm skyline) tracks only the highest occupied pixel in each column. Slide the padded sprite across that profile and pick the lowest valid y (breaking ties toward the left); testing the left edge of each flat span is enough. Uneven heights pack tighter than on shelves, though any gap roofed over by a wider sprite above it disappears from the profile.

Worst case: O(n W w) time, O(W) extra space (W is the atlas width limit; w is the widest padded sprite).

Create atlas/strategies.odin:

package atlas

// Skyline bottom-left: at equal heights, keep the leftmost placement.
pack_skyline :: proc(sizes: []Size, regions: []Rect, max_width, max_height: int) -> (used: Size, err: Pack_Error, index: int) {
    if e, i := check_sizes(sizes, regions, max_width, max_height); e != .None { return {}, e, i }
    heights := make([]int, max_width)
    defer delete(heights)
    for size, i in sizes {
        w, h := size.width + 2*Gutter, size.height + 2*Gutter
        best_x, best_y := -1, max_height
        for x in 0..=max_width - w {
            // Sliding right along a flat span can't improve on its left edge.
            if x > 0 && heights[x] == heights[x - 1] { continue }
            y := 0
            for top in heights[x:x+w] { y = max(y, top) }
            if y + h <= max_height && y < best_y { best_x, best_y = x, y }
        }
        if best_x < 0 { return {}, .Atlas_Full, i }
        for &top in heights[best_x:best_x+w] { top = best_y + h }
        regions[i] = {best_x + Gutter, best_y + Gutter, size.width, size.height}
        used.width = max(used.width, best_x + w)
        used.height = max(used.height, best_y + h)
    }
    return used, .None, -1
}

MaxRects (--algorithm maxrects) maintains explicit free rectangles instead of a 1D horizon. Using best short-side fit, it picks the free rectangle with the smallest leftover margin on either axis, places the padded sprite at its top-left corner, and subtracts that footprint from every intersecting free rectangle. The leftover strips can overlap one another, though never a placed sprite, so any strip wholly contained inside another is pruned. That extra bookkeeping preserves the pocket beside A so D can claim it later.

Worst case: O(n F²) time, O(F) extra space (F is the peak free-list length, including rectangles not yet pruned).

Append split_free and pack_maxrects to atlas/strategies.odin, keeping the caller's input order and 1-pixel gutters:

// Subtract a padded placement from one free rectangle. The leftovers may overlap.
split_free :: proc(next: ^[dynamic]Rect, f, p: Rect) {
    right, bottom := f.x + f.width, f.y + f.height
    pr, pb := p.x + p.width, p.y + p.height
    if p.x >= right || pr <= f.x || p.y >= bottom || pb <= f.y {
        append(next, f)
        return
    }
    if p.x > f.x { append(next, Rect{f.x, f.y, p.x - f.x, f.height}) }
    if pr < right { append(next, Rect{pr, f.y, right - pr, f.height}) }
    if p.y > f.y { append(next, Rect{f.x, f.y, f.width, p.y - f.y}) }
    if pb < bottom { append(next, Rect{f.x, pb, f.width, bottom - pb}) }
}

// MaxRects best short side fit. Break ties on the long side, then list order.
pack_maxrects :: proc(sizes: []Size, regions: []Rect, max_width, max_height: int) -> (used: Size, err: Pack_Error, index: int) {
    if e, i := check_sizes(sizes, regions, max_width, max_height); e != .None { return {}, e, i }
    free, next: [dynamic]Rect
    append(&free, Rect{0, 0, max_width, max_height})
    defer delete(free)
    defer delete(next)
    for size, i in sizes {
        w, h := size.width + 2*Gutter, size.height + 2*Gutter
        best, short, long := -1, Max_Size + 1, Max_Size + 1
        for f, j in free {
            dw, dh := f.width - w, f.height - h
            if dw < 0 || dh < 0 { continue }
            s, l := min(dw, dh), max(dw, dh)
            if s < short || (s == short && l < long) { best, short, long = j, s, l }
        }
        if best < 0 { return {}, .Atlas_Full, i }
        p := Rect{free[best].x, free[best].y, w, h}
        regions[i] = {p.x + Gutter, p.y + Gutter, size.width, size.height}
        used.width = max(used.width, p.x + w)
        used.height = max(used.height, p.y + h)

        clear(&next)
        for f in free { split_free(&next, f, p) }
        // Drop contained rectangles, including duplicates. Keep the other overlaps.
        for j := len(next) - 1; j >= 0; j -= 1 {
            a := next[j]
            for b, k in next {
                if j != k && a.x >= b.x && a.y >= b.y &&
                   a.x + a.width <= b.x + b.width && a.y + a.height <= b.y + b.height {
                    ordered_remove(&next, j)
                    break
                }
            }
        }
        free, next = next, free
    }
    return used, .None, -1
}

Three ways to use a grid

Next, test three grid-based packers inside a 16 x 16 limit using a second sequence of four rectangles. Including gutters, their padded sizes are A (6 x 3), B (7 x 6), C (8 x 3), and D (4 x 3), passed in that order.

Fixed grid (--algorithm grid) gives every sprite one uniform cell sized to the widest and tallest padded inputs: 8 x 6 here, or two cells per row. A sprite's position follows directly from its index, at the cost of charging tiny D a full 8 x 6 cell.

Four padded sprites take one 8 by 6 cell each. A and B fill the first row, C and D fill the second. The result is 16 by 12 pixels.

Placement cost: O(n) time, O(1) extra space.

Create atlas/grids.odin. The atlas dimensions span whole occupied cells, while each exported Rect still wraps only the sprite inside its cell:

package atlas

import "core:math"

// One whole cell per sprite, indexed left to right and then top to bottom.
pack_fixed_grid :: proc(sizes: []Size, regions: []Rect, max_width, max_height: int) -> (used: Size, err: Pack_Error, index: int) {
    if e, i := check_sizes(sizes, regions, max_width, max_height); e != .None { return {}, e, i }
    cell: Size
    for s in sizes {
        cell.width = max(cell.width, s.width + 2*Gutter)
        cell.height = max(cell.height, s.height + 2*Gutter)
    }
    cols, rows := max_width / cell.width, max_height / cell.height
    for s, i in sizes {
        if i / cols >= rows { return {}, .Atlas_Full, i }
        x, y := (i % cols) * cell.width, (i / cols) * cell.height
        regions[i] = {x + Gutter, y + Gutter, s.width, s.height}
        used.width = max(used.width, x + cell.width)
        used.height = y + cell.height
    }
    return used, .None, -1
}

Quadtree (--algorithm quadtree) starts from a power-of-two root square and recursively splits free squares into four equal quadrants until one matches the smallest power of two that holds the padded sprite. A, B, and C each claim an 8 x 8 leaf; the fourth 8 x 8 quadrant splits once more so D takes a 4 x 4 leaf. Long, narrow sprites pay a steep tax here because their longer side dictates the square size.

Split a 16 by 16 root into four 8 by 8 squares. Put A, B, and C in separate leaves. Split the last leaf into four and give D its top-left 4 by 4 square. The result is 16 by 16 pixels.

Worst case: O(n (Q + D)) time, O(Q) extra space (Q is the peak number of free leaves; D is the maximum split depth).

Append pack_quadtree to atlas/grids.odin. Rather than building pointer nodes, it tracks only free leaf squares: pick the smallest leaf whose top-left need x need region fits inside (max_width, max_height), split downward into its top-left child, and push the three unused siblings onto the free list. A virtual power-of-two root can extend past a non-square atlas as long as every reserved square stays within both limits:

Quad :: struct { x, y, side: int }

// Store only the free leaves. A virtual root covers even a non-square atlas.
pack_quadtree :: proc(sizes: []Size, regions: []Rect, max_width, max_height: int) -> (used: Size, err: Pack_Error, index: int) {
    if e, i := check_sizes(sizes, regions, max_width, max_height); e != .None { return {}, e, i }
    free: [dynamic]Quad
    defer delete(free)
    append(&free, Quad{0, 0, math.next_power_of_two(max(max_width, max_height))})
    for s, i in sizes {
        need := math.next_power_of_two(max(s.width, s.height) + 2*Gutter)
        best := -1
        for q, j in free {
            if q.side < need || q.x + need > max_width || q.y + need > max_height { continue }
            if best < 0 || q.side < free[best].side { best = j }
        }
        if best < 0 { return {}, .Atlas_Full, i }
        q := free[best]
        ordered_remove(&free, best)
        for q.side > need {
            q.side /= 2
            // Descend into the top-left child; keep its three siblings for later.
            append(&free, Quad{q.x + q.side, q.y, q.side})
            append(&free, Quad{q.x, q.y + q.side, q.side})
            append(&free, Quad{q.x + q.side, q.y + q.side, q.side})
        }
        regions[i] = {q.x + Gutter, q.y + Gutter, s.width, s.height}
        used.width = max(used.width, q.x + need)
        used.height = max(used.height, q.y + need)
    }
    return used, .None, -1
}

Occupancy-grid search (--algorithm occupancy) scans from the top-left corner for every sprite, testing positions across each row and down the grid until an entire padded footprint is clear. In the diagram, C is too wide for the gap beneath A and drops to row 6, while narrower D backfills that gap. Unlike Fixed grid, a single sprite spans multiple cells and reserves nothing beyond its own gutters.

Search a grid of 1 by 3 pixel cells from the top left. A and B occupy the top row. C is too wide for the gap under A; D fits there. The result is 13 by 9 pixels.

Worst case: O(n (G A + log L)) time, O(G) extra space (G is the grid's cell count, A the largest padded sprite's cell count, and L the larger atlas limit).

Append pack_occupancy to atlas/grids.odin. Taking math.gcd across all padded widths and heights coarsens the grid whenever inputs share a common unit: here every padded height is a multiple of 3, collapsing three pixel rows into one grid row. Coprime sizes fall back to 1-pixel cells and slower scans. Storing each placed sprite's exclusive right edge in its occupied cells lets failed checks jump straight past the blocking sprite:

// First fit, scanning rows from the top. Zero means free; a marked cell
// stores the exclusive right edge (in cells) of the sprite blocking it.
pack_occupancy :: proc(sizes: []Size, regions: []Rect, max_width, max_height: int) -> (used: Size, err: Pack_Error, index: int) {
    if e, i := check_sizes(sizes, regions, max_width, max_height); e != .None { return {}, e, i }
    cw, ch := 0, 0
    for s in sizes {
        cw = math.gcd(cw, s.width + 2*Gutter)
        ch = math.gcd(ch, s.height + 2*Gutter)
    }
    cols, rows := max_width / cw, max_height / ch
    grid := make([]u16, cols * rows) // Max_Size is 4096.
    defer delete(grid)
    sprites: for s, i in sizes {
        w, h := (s.width + 2*Gutter) / cw, (s.height + 2*Gutter) / ch
        for y in 0..=rows - h {
            search_x: for x := 0; x + w <= cols; {
                for dy in 0..<h {
                    start := (y + dy) * cols + x
                    for edge in grid[start:start+w] {
                        if edge != 0 { x = int(edge); continue search_x }
                    }
                }
                for dy in 0..<h {
                    start := (y + dy) * cols + x
                    for &edge in grid[start:start+w] { edge = u16(x + w) }
                }
                regions[i] = {x*cw + Gutter, y*ch + Gutter, s.width, s.height}
                used.width = max(used.width, (x + w)*cw)
                used.height = max(used.height, (y + h)*ch)
                continue sprites
            }
        }
        return {}, .Atlas_Full, i
    }
    return used, .None, -1
}

Append the Algorithm enum and pack_regions dispatcher to atlas/strategies.odin. Because all six procedures share the same slice and limit signature, the rest of the tool calls pack_regions without caring which strategy placed the rectangles:

Algorithm :: enum { shelf, skyline, maxrects, grid, quadtree, occupancy }

pack_regions :: proc(algorithm: Algorithm, sizes: []Size, regions: []Rect, w, h: int) -> (Size, Pack_Error, int) {
    switch algorithm {
    case .shelf:    return pack_shelves(sizes, regions, w, h)
    case .skyline:  return pack_skyline(sizes, regions, w, h)
    case .maxrects: return pack_maxrects(sizes, regions, w, h)
    case .grid:     return pack_fixed_grid(sizes, regions, w, h)
    case .quadtree: return pack_quadtree(sizes, regions, w, h)
    case .occupancy: return pack_occupancy(sizes, regions, w, h)
    }
    return {}, .Bad_Arguments, -1
}

Add tests covering both sets of diagrams and a non-square boundary case to atlas/pack_test.odin:

@(test)
strategies_place_the_fourth_sprite_differently :: proc(t: ^testing.T) {
    sizes := []Size{{4, 1}, {3, 2}, {3, 1}, {2, 1}}
    last := [3]Rect{{1, 8, 2, 1}, {6, 7, 2, 1}, {7, 1, 2, 1}}
    heights := [3]int{10, 9, 7}
    for algorithm, i in ([]Algorithm{.shelf, .skyline, .maxrects}) {
        regions: [4]Rect
        used, err, _ := pack_regions(algorithm, sizes, regions[:], 10, 16)
        testing.expect_value(t, err, Pack_Error.None)
        testing.expect_value(t, used, Size{10, heights[i]})
        testing.expect_value(t, regions, [4]Rect{{1, 1, 4, 1}, {1, 4, 3, 2}, {6, 4, 3, 1}, last[i]})
        _, full, index := pack_regions(algorithm, {{8, 8}, {1, 1}}, regions[:2], 10, 10)
        testing.expect_value(t, full, Pack_Error.Atlas_Full)
        testing.expect_value(t, index, 1)
    }
}

@(test)
grid_placements_match_the_diagrams :: proc(t: ^testing.T) {
    sizes := []Size{{4, 1}, {5, 4}, {6, 1}, {2, 1}}
    for a in ([]Algorithm{.grid, .quadtree, .occupancy}) {
        rs: [4]Rect
        used, err, _ := pack_regions(a, sizes, rs[:], 16, 16)
        testing.expect_value(t, err, Pack_Error.None)
        #partial switch a {
        case .grid:
            testing.expect_value(t, used, Size{16, 12})
            testing.expect_value(t, rs, [4]Rect{{1, 1, 4, 1}, {9, 1, 5, 4}, {1, 7, 6, 1}, {9, 7, 2, 1}})
        case .quadtree:
            testing.expect_value(t, used, Size{16, 16})
            testing.expect_value(t, rs, [4]Rect{{1, 1, 4, 1}, {9, 1, 5, 4}, {1, 9, 6, 1}, {9, 9, 2, 1}})
        case .occupancy:
            testing.expect_value(t, used, Size{13, 9})
            testing.expect_value(t, rs, [4]Rect{{1, 1, 4, 1}, {7, 1, 5, 4}, {1, 7, 6, 1}, {1, 4, 2, 1}})
        }
    }
}

@(test)
grid_packers_respect_non_square_limits :: proc(t: ^testing.T) {
    for a in ([]Algorithm{.grid, .quadtree, .occupancy}) {
        rs: [5]Rect
        // Four padded 4 x 4 tiles fit; the fifth can't use the slivers.
        used, ok, _ := pack_regions(a, {{2, 2}, {2, 2}, {2, 2}, {2, 2}}, rs[:4], 11, 9)
        testing.expect_value(t, ok, Pack_Error.None)
        testing.expect_value(t, used, Size{8, 8})
        _, full, at := pack_regions(a, {{2, 2}, {2, 2}, {2, 2}, {2, 2}, {2, 2}}, rs[:], 11, 9)
        testing.expect_value(t, full, Pack_Error.Atlas_Full)
        testing.expect_value(t, at, 4)
        _, too_big, _ := pack_regions(a, {{10, 1}}, rs[:1], 11, 9)
        testing.expect_value(t, too_big, Pack_Error.Sprite_Too_Large)
    }
}

Run all six tests in atlas:

odin test atlas
(out)Finished 6 tests in 186.688µs. All tests were successful.

Build the packing library

Create atlas/build.odin to connect PNG loading, pack_regions, and blit_rgba. Derive each sprite's name from its filename stem and sort inputs alphabetically so unit_plane_a lands at the same coordinates regardless of how the shell orders input paths. Read headers in that sorted order and run the packer before decoding full images so oversized inputs fail fast without allocating pixel buffers.

In the three-sprite opening example, 256 is the width limit while the placed sprites use only 132 x 196 pixels. build allocates an RGBA8 canvas of that exact used size and pairs it with an in-memory Layout of named rectangles.

Scratch slices inside build (inputs, sizes, regions) use make paired with defer delete, while ownership of canvas.pixels and layout.sprites transfers to the caller (destroy frees both). A long-running tool rebuilding atlases in a loop could route those scratch slices through an arena allocator and reset the arena after each build, keeping only the returned Packed bundle outside it.

Three Scribble Planes PNGs and a width limit go into atlas.build. It reads headers, places rectangles, then copies pixels. It returns an RGBA8 canvas and a separate layout of named rectangles.
package atlas

import "core:fmt"
import "core:image"
import "core:image/png"
import "core:path/filepath"
import "core:slice"
import "core:strings"

Atlas_File :: "atlas.png"

Sprite_Entry :: struct {
    name: string,
    x, y, width, height: int,
}

Layout :: struct {
    version: int,
    image: string,
    width, height: int,
    sprites: [dynamic]Sprite_Entry,
}

Packed :: struct {
    canvas: image.Image,
    layout: Layout,
}

Input :: struct {
    name, path: string,
}

// The caller owns the pixels and entries. Sprite names borrow from paths.
build :: proc(width: int, paths: []string, algorithm: Algorithm = .shelf) -> (packed: Packed, message: string) {
    if width < 1 || width > Max_Size {
        return {}, fmt.tprintf("width must be from 1 to %d", Max_Size)
    }
    if len(paths) == 0 {
        return {}, "provide at least one input PNG"
    }

    count := len(paths)
    inputs := make([]Input, count)
    defer delete(inputs)
    for path, i in paths {
        name := filepath.stem(path)
        if !strings.equal_fold(filepath.ext(path), ".png") || !valid_name(name) {
            return {}, fmt.tprintf("expected a .png file with an ASCII letter, digit, _ or - stem: %s", path)
        }
        inputs[i] = {name, path}
    }
    slice.sort_by(inputs, proc(a, b: Input) -> bool { return a.name < b.name })
    for i in 1..<count {
        if inputs[i - 1].name == inputs[i].name {
            return {}, fmt.tprintf("duplicate sprite name: %s", inputs[i].name)
        }
    }

    // Read headers and pack first so an oversized image is rejected before decoding pixels.
    sizes := make([]Size, count)
    defer delete(sizes)
    regions := make([]Rect, count)
    defer delete(regions)
    for input, i in inputs {
        header, err := png.load(input.path, {.return_header})
        if err != nil {
            return {}, fmt.tprintf("reading %s: %v", input.path, err)
        }
        defer png.destroy(header)
        sizes[i] = {header.width, header.height}
    }
    used, err, index := pack_regions(algorithm, sizes, regions, width, Max_Size)
    if err != .None {
        if index < 0 { return {}, "invalid packing arguments" }
        return {}, fmt.tprintf("packing %s: %v (limit %d x %d, including gutters)", inputs[index].path, err, width, Max_Size)
    }

    canvas := image.Image{
        width = used.width,
        height = used.height,
        channels = 4,
        depth = 8,
        pixels = make([dynamic]byte, used.width * used.height * 4),
    }
    defer if message != "" { delete(canvas.pixels) }
    for input, i in inputs {
        sprite, decode_err := png.load(input.path, {.alpha_add_if_missing})
        if decode_err != nil {
            return {}, fmt.tprintf("decoding %s: %v", input.path, decode_err)
        }
        defer png.destroy(sprite)
        size := sizes[i]
        if sprite.width != size.width || sprite.height != size.height ||
           sprite.depth != 8 || sprite.channels != 4 ||
           len(sprite.pixels) != size.width * size.height * 4 {
            return {}, fmt.tprintf("expected RGBA8 after decoding %s (16-bit PNGs are not supported)", input.path)
        }
        blit_rgba(canvas.pixels[:], sprite.pixels[:], canvas.width, regions[i])
    }

    entries := make([dynamic]Sprite_Entry, count)
    for rect, i in regions {
        entries[i] = {inputs[i].name, rect.x, rect.y, rect.width, rect.height}
    }
    return {canvas, {1, Atlas_File, used.width, used.height, entries}}, ""
}

destroy :: proc(packed: ^Packed) {
    delete(packed.canvas.pixels)
    delete(packed.layout.sprites)
}

// Use the same sprite name in the JSON entry and the Godot animation.
valid_name :: proc(name: string) -> bool {
    if len(name) == 0 { return false }
    for c in transmute([]u8)name {
        if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' ||
             c >= '0' && c <= '9' || c == '_' || c == '-') {
            return false
        }
    }
    return true
}

Build the export library

Running packing and exporting as separate stages means saving Layout to disk. In exporters/export.odin, core:encoding/json marshals Layout directly for both the intermediate layout.json and the exported atlas.json manifest. On reload, read_layout checks the schema version, image filename, atlas bounds, sprite names, and rectangle coordinates before accepting the file.

Godot 4 consumes those same coordinates through a text .tres SpriteFrames resource: each sprite gets an AtlasTexture sub-resource pointing at the shared atlas.png (such as Rect2(1, 67, 128, 128) for unit_plane_a) and a single-frame animation carrying the sprite's name, without repacking or guessing multi-frame sequences.

Each export writes atlas.png plus one metadata file: atlas.json by default or atlas.tres with --format godot. Supporting another engine later only means adding a Format enum value and a Writer entry in writer_for; nothing in atlas/ needs to change.

The export command takes a saved layout and atlas PNG. The plane's rectangle becomes either a JSON entry or a Godot region. The PNG stays unchanged.
package exporters

import "../atlas"
import "core:encoding/json"
import "core:fmt"
import "core:os"
import "core:strings"

Layout_File :: "layout.json"
Format :: enum { json, godot }

Writer :: struct {
    filename: string,
    write: proc(path: string, doc: atlas.Layout) -> string,
}

Staging :: Writer{Layout_File, write_json}
writer_for :: proc(format: Format) -> Writer {
    writers := [Format]Writer{
        .json  = {"atlas.json", write_json},
        .godot = {"atlas.tres", write_godot},
    }
    return writers[format]
}

// Both the intermediate layout and the exported manifest use the v1 schema.
write_json :: proc(path: string, doc: atlas.Layout) -> string {
    data, err := json.marshal(doc, {pretty = true, use_spaces = true, spaces = 2})
    if err != nil {
        return fmt.tprintf("encoding JSON: %v", err)
    }
    defer delete(data)
    return write_text(path, string(data))
}

// The document and its strings live in the caller's temporary allocator.
read_layout :: proc(path: string) -> (doc: atlas.Layout, message: string) {
    scratch := context.temp_allocator
    data, read_err := os.read_entire_file(path, scratch)
    if read_err != nil {
        return {}, fmt.tprintf("reading manifest %s: %v", path, read_err)
    }
    if err := json.unmarshal(data, &doc, allocator = scratch); err != nil {
        return {}, fmt.tprintf("decoding manifest: %v", err)
    }
    if doc.version != 1 {
        return {}, fmt.tprintf("unsupported atlas manifest version: %d", doc.version)
    }
    if doc.image != atlas.Atlas_File || doc.width < 1 || doc.height < 1 ||
       doc.width > atlas.Max_Size || doc.height > atlas.Max_Size || len(doc.sprites) == 0 {
        return {}, "invalid atlas image, dimensions or sprite list"
    }

    seen := make(map[string]bool, len(doc.sprites))
    defer delete(seen)
    for s in doc.sprites {
        if !atlas.valid_name(s.name) || s.name in seen {
            return {}, fmt.tprintf("invalid or duplicate sprite name: %q", s.name)
        }
        if s.x < 0 || s.y < 0 || s.width < 1 || s.height < 1 ||
           s.width > doc.width || s.height > doc.height ||
           s.x > doc.width - s.width || s.y > doc.height - s.height {
            return {}, fmt.tprintf("invalid atlas rectangle for %s", s.name)
        }
        seen[s.name] = true
    }
    return doc, ""
}

write_godot :: proc(path: string, doc: atlas.Layout) -> string {
    b := strings.builder_make()
    defer strings.builder_destroy(&b)

    fmt.sbprintf(&b, "[gd_resource type=\"SpriteFrames\" load_steps=%d format=3]\n\n", len(doc.sprites) + 2)
    fmt.sbprintf(&b, "[ext_resource type=\"Texture2D\" path=\"%s\" id=\"1\"]\n", doc.image)
    for r, i in doc.sprites {
        fmt.sbprintf(&b, "\n[sub_resource type=\"AtlasTexture\" id=\"region_%d\"]\n", i)
        fmt.sbprint(&b, "atlas = ExtResource(\"1\")\n")
        fmt.sbprintf(&b, "region = Rect2(%d, %d, %d, %d)\n", r.x, r.y, r.width, r.height)
        fmt.sbprint(&b, "filter_clip = true\n")
    }

    // One named, single-frame animation per still sprite. No guessed timing or grouping.
    fmt.sbprint(&b, "\n[resource]\nanimations = [\n")
    for input, i in doc.sprites {
        if i > 0 { fmt.sbprint(&b, ",\n") }
        fmt.sbprint(&b, "{\n\"frames\": [{\"duration\": 1.0, \"texture\": ")
        fmt.sbprintf(&b, "SubResource(\"region_%d\")", i)
        fmt.sbprint(&b, "}],\n")
        fmt.sbprintf(&b, "\"loop\": false,\n\"name\": &\"%s\",\n\"speed\": 1.0\n}", input.name)
    }
    fmt.sbprint(&b, "\n]\n")
    return write_text(path, strings.to_string(b))
}

write_text :: proc(path, data: string) -> string {
    if err := os.write_entire_file(path, data); err != nil {
        return fmt.tprintf("writing %s: %v", path, err)
    }
    return ""
}

To verify that atlas.json and atlas.png alone are enough to recover any sprite, create exporters/extract.odin. It looks up a sprite entry by name and reverses the row copy, reading from the atlas stride into a tight w x h buffer so the cropped output matches the source sprite pixel for pixel:

package exporters

import "../atlas"
import "core:fmt"
import "core:image"
import "core:image/png"
import "core:path/filepath"

extract :: proc(manifest_path, name, output: string) -> string {
    doc, message := read_layout(manifest_path)
    if message != "" { return message }

    entry: atlas.Sprite_Entry
    for sprite in doc.sprites {
        if sprite.name == name {
            entry = sprite
            break
        }
    }
    if entry.name == "" {
        return fmt.tprintf("no such sprite: %s", name)
    }
    atlas_path, path_err := filepath.join({filepath.dir(manifest_path), doc.image}, context.temp_allocator)
    if path_err != nil {
        return fmt.tprintf("joining atlas path: %v", path_err)
    }
    sheet, png_err := png.load(atlas_path)
    if png_err != nil {
        return fmt.tprintf("reading atlas PNG: %v", png_err)
    }
    defer png.destroy(sheet)

    if sheet.width != doc.width || sheet.height != doc.height ||
       sheet.channels != 4 || sheet.depth != 8 {
        return "atlas PNG must be RGBA8 and match the manifest dimensions"
    }
    x, y, w, h := entry.x, entry.y, entry.width, entry.height

    crop := image.Image{
        width = w, height = h, channels = 4, depth = 8,
        pixels = make([dynamic]byte, w * h * 4),
    }
    defer delete(crop.pixels)
    for row in 0..<h {
        from := ((y + row) * sheet.width + x) * 4
        to := row * w * 4
        copy(crop.pixels[to:to + w * 4], sheet.pixels[from:from + w * 4])
    }
    if err := png.save(output, &crop); err != nil {
        return fmt.tprintf("writing sprite PNG: %v", err)
    }
    return ""
}

Wire the subcommands together

Create cmd/stages.odin to connect atlas and exporters. pack writes atlas.png plus the staged layout.json; export_packed validates that pair, copies atlas.png without re-encoding it, and writes the chosen metadata format into a new directory; gen calls pack directly with the selected format writer to skip layout.json:

package main

import "../atlas"
import "../exporters"
import "core:fmt"
import "core:image"
import "core:image/png"
import "core:os"
import "core:path/filepath"

pack :: proc(algorithm: atlas.Algorithm, width: int, out: string, paths: []string, writer: exporters.Writer) -> string {
    bundle, message := atlas.build(width, paths, algorithm)
    if message != "" { return message }
    defer atlas.destroy(&bundle)

    if err := write_bundle(out, bundle.layout, &bundle.canvas, "", writer); err != "" {
        return err
    }
    fmt.printfln("Packed %d sprites into %d x %d: %s",
                 len(bundle.layout.sprites), bundle.layout.width, bundle.layout.height, out)
    return ""
}

export_packed :: proc(packed_dir, out: string, writer: exporters.Writer) -> string {
    layout_path, layout_err := filepath.join({packed_dir, exporters.Layout_File}, context.temp_allocator)
    source_path, source_err := filepath.join({packed_dir, atlas.Atlas_File}, context.temp_allocator)
    if layout_err != nil || source_err != nil {
        return fmt.tprintf("could not construct paths in %s", packed_dir)
    }

    doc, message := exporters.read_layout(layout_path)
    if message != "" { return message }
    header, err := png.load(source_path, {.return_header})
    if err != nil { return fmt.tprintf("reading %s: %v", source_path, err) }
    defer png.destroy(header)
    if header.width != doc.width || header.height != doc.height ||
       header.channels != 4 || header.depth != 8 {
        return "packed PNG must be RGBA8 and match the layout dimensions"
    }

    if err := write_bundle(out, doc, nil, source_path, writer); err != "" {
        return err
    }
    fmt.printfln("Exported %d sprites: %s", len(doc.sprites), out)
    return ""
}

// Supply either a canvas to encode or an existing atlas PNG to copy.
write_bundle :: proc(out: string, doc: atlas.Layout, canvas: ^image.Image,
                     source_path: string, writer: exporters.Writer) -> (message: string) {
    png_path, png_err := filepath.join({out, atlas.Atlas_File}, context.temp_allocator)
    metadata_path, metadata_err := filepath.join({out, writer.filename}, context.temp_allocator)
    if png_err != nil || metadata_err != nil {
        return fmt.tprintf("could not construct paths in %s", out)
    }
    if err := os.make_directory(out); err != nil {
        return fmt.tprintf("creating new output directory %s: %v", out, err)
    }
    defer if message != "" {
        os.remove(png_path)
        os.remove(metadata_path)
        os.remove(out)
    }

    if canvas != nil {
        if err := png.save(png_path, canvas); err != nil {
            return fmt.tprintf("writing %s: %v", png_path, err)
        }
    } else if err := os.copy_file(png_path, source_path); err != nil {
        return fmt.tprintf("copying %s to %s: %v", source_path, png_path, err)
    }

    return writer.write(metadata_path, doc)
}

Return to cmd/main.odin, add import "../atlas" and import "../exporters", and replace the run stub with the option structs and run procedure below. Each branch hands its slice of args to core:flags. --algorithm maps directly to atlas.Algorithm, whose zero value is .shelf. Only gen and export accept --format, since pack always writes layout.json. Because core:flags in dev-2026-11a cannot attach both a long flag and a short alias to one field, every option uses its full name (such as --max-width and --output):

Pack_Options :: struct {
    algorithm: atlas.Algorithm `usage:"Placement: shelf (default), skyline, maxrects, grid, quadtree, or occupancy."`,
    max_width: int `args:"required" usage:"Maximum atlas width in pixels, including gutters."`,
    output: string `args:"required" usage:"New output directory."`,
    overflow: [dynamic]string `usage:"Input PNG paths (at least one)."`,
}

Gen_Options :: struct {
    format: exporters.Format `usage:"Metadata: json (default) or godot."`,
    algorithm: atlas.Algorithm `usage:"Placement: shelf (default), skyline, maxrects, grid, quadtree, or occupancy."`,
    max_width: int `args:"required" usage:"Maximum atlas width in pixels, including gutters."`,
    output: string `args:"required" usage:"New output directory."`,
    overflow: [dynamic]string `usage:"Input PNG paths (at least one)."`,
}

Export_Options :: struct {
    format: exporters.Format `usage:"Metadata: json (default) or godot."`,
    packed_dir: string `args:"required" usage:"Directory produced by pack."`,
    output: string `args:"required" usage:"New output directory."`,
}

Extract_Options :: struct {
    manifest: string `args:"required" usage:"Atlas JSON manifest path."`,
    name: string `args:"required" usage:"Sprite name to extract."`,
    output: string `args:"required" usage:"Output PNG path."`,
}

run :: proc(command: Command, args: []string) -> string {
    // args[0] is the subcommand name for core:flags' usage message.
    switch command {
    case .pack:
        options: Pack_Options
        flags.parse_or_exit(&options, args, .Unix)
        defer delete(options.overflow)
        return pack(options.algorithm, options.max_width, options.output, options.overflow[:], exporters.Staging)
    case .gen:
        options: Gen_Options
        flags.parse_or_exit(&options, args, .Unix)
        defer delete(options.overflow)
        return pack(options.algorithm, options.max_width, options.output, options.overflow[:], exporters.writer_for(options.format))
    case .export:
        options: Export_Options
        flags.parse_or_exit(&options, args, .Unix)
        return export_packed(options.packed_dir, options.output, exporters.writer_for(options.format))
    case .extract:
        options: Extract_Options
        flags.parse_or_exit(&options, args, .Unix)
        return exporters.extract(options.manifest, options.name, options.output)
    }
    return ""
}

Run it end to end

From the project root, ensure build/ exists, compile the CLI, and pack the three sprites from the opening diagram. Each command creates only the final --output directory (its parent must already exist) and refuses to overwrite an existing one, so pick a fresh --output path whenever you rerun a step.

On macOS or Linux:

mkdir -p build
odin build cmd -out:build/sprite-atlas
./build/sprite-atlas pack --max-width 256 --output build/packed sprites/PNG/Default/{effect_spark,projectile_round,unit_plane_a}.png
(out)Packed 3 sprites into 132 x 196: build/packed
./build/sprite-atlas export --packed-dir build/packed --output build/exported
(out)Exported 3 sprites: build/exported

On Windows (PowerShell):

New-Item -ItemType Directory -Force build > $null
odin build cmd -out:build/sprite-atlas.exe
$sampleSprites = @('effect_spark', 'projectile_round', 'unit_plane_a') | ForEach-Object { "sprites/PNG/Default/$_.png" }
& .\build\sprite-atlas.exe pack --max-width 256 --output build/packed @sampleSprites
& .\build\sprite-atlas.exe export --packed-dir build/packed --output build/exported

build/packed/ now holds atlas.png and layout.json, and build/exported/ contains an identical atlas.png alongside atlas.json. To generate a Godot resource from those same three sprites without rerunning pack, run export again with --format godot and a fresh --output directory.

For the full 111-sprite sets, gen packs and exports in a single pass. Keep Default/ and Large*/ in separate atlases: both sets reuse filenames like unit_plane_a.png, and atlas.build rejects duplicate sprite names.

On macOS or Linux:

./build/sprite-atlas gen --max-width 1024 --output build/scribble sprites/PNG/Default/*.png
(out)Packed 111 sprites into 990 x 980: build/scribble
./build/sprite-atlas gen --max-width 2048 --output build/scribble-2x sprites/PNG/Large*/*.png
(out)Packed 111 sprites into 1950 x 1940: build/scribble-2x

On Windows, PowerShell doesn't expand wildcards for native executables, so collect the file paths explicitly first:

$defaultSprites = @(Get-ChildItem -LiteralPath 'sprites/PNG/Default' -Filter '*.png' -File | ForEach-Object { $_.FullName })
$largeSprites = @(Get-ChildItem -Path 'sprites/PNG/Large*/*.png' -File | ForEach-Object { $_.FullName })
& .\build\sprite-atlas.exe gen --max-width 1024 --output build/scribble @defaultSprites
& .\build\sprite-atlas.exe gen --max-width 2048 --output build/scribble-2x @largeSprites

--max-width is an upper bound, not a fixed canvas width: Shelf packs the default set into 990 x 980 pixels and the 2x set into 1950 x 1940. To compare the remaining five strategies on the default set, pass --algorithm to pack or gen with a fresh output directory each time (export doesn't accept --algorithm because coordinates are already fixed in layout.json):

./build/sprite-atlas pack --algorithm skyline --max-width 1024 --output build/skyline sprites/PNG/Default/*.png
(out)Packed 111 sprites into 990 x 916: build/skyline
./build/sprite-atlas pack --algorithm maxrects --max-width 1024 --output build/maxrects sprites/PNG/Default/*.png
(out)Packed 111 sprites into 990 x 916: build/maxrects
./build/sprite-atlas pack --algorithm grid --max-width 1024 --output build/grid sprites/PNG/Default/*.png
(out)Packed 111 sprites into 910 x 2080: build/grid
./build/sprite-atlas pack --algorithm quadtree --max-width 1024 --output build/quadtree sprites/PNG/Default/*.png
(out)Packed 111 sprites into 1024 x 3072: build/quadtree
./build/sprite-atlas pack --algorithm occupancy --max-width 1024 --output build/occupancy sprites/PNG/Default/*.png
(out)Packed 111 sprites into 990 x 916: build/occupancy

On Windows, substitute @defaultSprites for the glob. Skyline, MaxRects, and Occupancy tie at 990 x 916 (64 rows shorter than Shelf), while Fixed grid (910 x 2080) and Quadtree (1024 x 3072) pay for uniform cells and power-of-two squares. That overhead bites harder at 2x scale: once gutters turn a 256 x 256 sprite into 258 x 258, Fixed grid allocates 258 x 258 cells and Quadtree jumps to 512 x 512 leaves. Both hit the 4096-pixel height limit at --max-width 2048 and require --max-width 4096, whereas the other four packers fit within 2048.

When would you pick something other than MaxRects?

Aside from the deliberate 1-pixel gutters, unused atlas space still costs memory: in an uncompressed RGBA8 texture, a transparent pixel takes the same four bytes as a painted one. For a fixed set of mixed-size sprites, MaxRects is a strong starting point, though its greedy per-sprite fit doesn't guarantee the smallest width * height overall.

You can reproduce a small counterexample with pack_regions: pass four test sprites (6 x 2, 2 x 6, 2 x 4, and 2 x 6, in that order) with max_width = 16 and the standard 1-pixel gutters. Both MaxRects and Skyline place the first three sprites identically. On the fourth, MaxRects picks the tighter short-side fit beneath the third sprite for a 16 x 14 atlas, while Skyline places it beneath the shorter first sprite and finishes at 16 x 12.

Atlas area isn't the only tradeoff to weigh:

  • Shelf: When animation frames share a similar height, little space is lost beneath shorter frames, and single-pass O(n) placement with a row cursor and shelf height is fast enough to rerun on every asset edit.
  • Skyline: Tracking one height per column avoids splitting and pruning free rectangles while matching MaxRects' 990 x 916 dimensions on Scribble Planes.
  • Fixed grid: For uniform tilesets (such as 16 x 16 tiles in 18 x 18 padded cells), there is zero slack inside a cell, and a tile editor or renderer can compute tile i from its row and column without a rectangle lookup.
  • Quadtree: If a renderer already manages power-of-two square slots (32, 64, and 128 pixels), leaf coordinates land on aligned slot boundaries and suit runtime caches where four evicted siblings coalesce back into their parent square. This CLI only builds static atlases; it doesn't implement eviction.
  • Occupancy grid: When padded sprite sizes share a coarse gcd, scanning cells in row order is straightforward to inspect and reuses interior holes without maintaining MaxRects' free list. When sizes are coprime and cells shrink to 1 x 1 pixels, that scan becomes much less attractive.

Try it in Godot

To export all 111 default sprites directly for Godot 4 instead of JSON, pass --format godot to gen:

./build/sprite-atlas gen --format godot --max-width 1024 --output build/godot sprites/PNG/Default/*.png
(out)Packed 111 sprites into 990 x 980: build/godot

On Windows, reuse @defaultSprites:

& .\build\sprite-atlas.exe gen --format godot --max-width 1024 --output build/godot @defaultSprites

Copy atlas.png and atlas.tres from build/godot/ into the same folder in your Godot project (res://sprites/ in the screenshots below). Once the editor imports the PNG, both files appear in the FileSystem dock; Godot doesn't need atlas.json.

Add an AnimatedSprite2D node (named Plane here) to a 2D scene and select it in the scene tree. Drag atlas.tres from the FileSystem dock onto the empty Sprite Frames property in the Inspector. Assign the .tres resource rather than atlas.png: the resource already defines all 111 AtlasTexture regions.

Godot's FileSystem dock shows atlas.png and the selected atlas.tres together under sprites. The Inspector for Plane shows AnimatedSprite2D with an empty Sprite Frames field.
Drag from the highlighted file on the left to Sprite Frames on the right.

Click the assigned resource to open the SpriteFrames panel, then select unit_plane_a under Animations. The panel shows its single frame, and the viewport renders just the plane rather than the whole sheet. Each AtlasTexture sets filter_clip = true, which pairs with the 1-pixel transparent gutters to prevent neighbor bleed at the base mip level (Godot's default Fix Alpha Border import option also fills RGB values on alpha = 0 gutter pixels to avoid dark linear-filtering fringes; if you enable mipmaps, use nearest filtering or extrude sprite edges).

Godot 4.5.1 shows the plane in the 2D viewport. The SpriteFrames panel has unit_plane_a selected with one frame; the Inspector shows atlas.tres assigned to Sprite Frames.
The selected frame in Godot 4.5.1. Open the screenshot for a closer look.

Check the JSON export

To verify the JSON export without Godot, extract unit_plane_a by name into a standalone PNG (pick an --output path you don't mind overwriting):

On macOS or Linux:

./build/sprite-atlas extract --manifest build/scribble/atlas.json --name unit_plane_a --output build/plane.png

On Windows (PowerShell):

& .\build\sprite-atlas.exe extract --manifest build/scribble/atlas.json --name unit_plane_a --output build/plane.png

Open build/plane.png and you'll get the 128 x 128 plane back cleanly, without a single pixel from its neighbors. Its decoded RGBA8 pixels match the original byte for byte, though the .png file sizes differ because Kenney's source unit_plane_a.png is palette-indexed while extract writes RGBA8.

Download the finished example

To compare your Odin code against the complete project, download the project ZIP. The code and tests are MIT-licensed. Kenney's Scribble Planes is included under CC0; you'll find the original license in sprites/License.txt.