Skip to content

Sprite Sheet Packer — C# source

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

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

// sprite-sheet-packer — MaxRects best-short-side-fit sheet packer. C# 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.
using System;
using System.Collections.Generic;
using System.Text;

namespace CosmoDev.SpriteSheetPacker
{
    /// One input sprite.
    public sealed class SpriteSize
    {
        public string Id { get; }
        public int W { get; }
        public int H { get; }

        public SpriteSize(string id, int w, int h) { Id = id; W = w; H = h; }
    }

    /// One placed sprite on the sheet.
    public sealed class PackedRect
    {
        public string Id { get; }
        public int X { get; }
        public int Y { get; }
        public int W { get; }
        public int H { get; }
        public bool Rotated { get; }

        public PackedRect(string id, int x, int y, int w, int h, bool rotated)
        {
            Id = id; X = x; Y = y; W = w; H = h; Rotated = rotated;
        }
    }

    /// The final sheet: power-of-two dims plus rects in input order.
    public sealed class PackResult
    {
        public int SheetW { get; }
        public int SheetH { get; }
        public IReadOnlyList<PackedRect> Rects { get; }

        public PackResult(int sheetW, int sheetH, IReadOnlyList<PackedRect> rects)
        {
            SheetW = sheetW; SheetH = sheetH; Rects = rects;
        }
    }

    /// Mirrors the TS PackOptions.
    public sealed class PackOptions
    {
        public int MaxWidth { get; }
        public int MaxHeight { get; }
        public bool AllowRotate { get; }

        public PackOptions(int maxWidth = 4096, int maxHeight = 4096, bool allowRotate = false)
        {
            if (maxWidth <= 0) maxWidth = 4096;
            if (maxHeight <= 0) maxHeight = 4096;
            MaxWidth = maxWidth; MaxHeight = maxHeight; AllowRotate = allowRotate;
        }
    }

    /// The C# twin of the TS PackError class.
    public sealed class PackError : Exception
    {
        /// 'empty' | 'invalid' | 'overflow'
        public string Code { get; }

        public PackError(string code, string message) : base(message) { Code = code; }
    }

    internal readonly struct FreeRect
    {
        public readonly int X, Y, W, H;

        public FreeRect(int x, int y, int w, int h) { X = x; Y = y; W = w; H = h; }
    }

    public static class SpriteSheetPacker
    {
        private const int MinSheet = 64;

        /// MaxRects best-short-side-fit packing over a growing power-of-two sheet.
        public static PackResult Pack(IReadOnlyList<SpriteSize> sizes) =>
            Pack(sizes, new PackOptions());

        public static PackResult Pack(IReadOnlyList<SpriteSize> sizes, PackOptions opts)
        {
            if (sizes.Count == 0)
                throw new PackError("empty", "Nothing to pack — add at least one sprite.");
            foreach (SpriteSize s in sizes)
            {
                if (s.W <= 0 || s.H <= 0)
                    throw new PackError("invalid", $"Sprite \"{s.Id}\" needs positive pixel dimensions.");
                foreach (SpriteSize seen in sizes)
                {
                    if (ReferenceEquals(seen, s)) break;
                    if (seen.Id == s.Id)
                        throw new 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.
            var order = new List<SpriteSize>(sizes);
            order.Sort((a, b) =>
            {
                int ma = Math.Max(a.W, a.H), mb = Math.Max(b.W, b.H);
                if (ma != mb) return mb - ma;
                long areaA = (long)a.W * a.H, areaB = (long)b.W * b.H;
                if (areaA != areaB) return areaB > areaA ? 1 : -1;
                return string.CompareOrdinal(a.Id, b.Id);
            });

            int sheetW = Pow2Floor(Math.Min(MinSheet, opts.MaxWidth));
            int sheetH = Pow2Floor(Math.Min(MinSheet, opts.MaxHeight));
            for (; ; )
            {
                List<PackedRect> placed = TryPack(order, sheetW, sheetH, opts.AllowRotate, out string failed);
                if (placed != null) return Finish(sizes, placed);

                int nextW = sheetW <= sheetH ? sheetW * 2 : sheetW;
                int 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 = nextW;
                sheetH = nextH;
            }
        }

        /// One MaxRects pass over a fixed candidate sheet: all rects, or null
        /// with failedId set to the first id that failed.
        private static List<PackedRect> TryPack(
            IReadOnlyList<SpriteSize> order, int W, int H, bool allowRotate, out string failedId)
        {
            failedId = null;
            var free = new List<FreeRect> { new FreeRect(0, 0, W, H) };
            var placed = new List<PackedRect>(order.Count);
            foreach (SpriteSize s in order)
            {
                FreeRect f;
                int w, h;
                bool rotated;
                if (!BestFit(free, s, allowRotate, out f, out w, out h, out rotated))
                {
                    failedId = s.Id;
                    return null;
                }
                PackedRect rect = new PackedRect(s.Id, f.X, f.Y, w, h, rotated);
                placed.Add(rect);
                free = SplitFree(free, rect);
            }
            return placed;
        }

        /// Best short side fit, ties broken by the long side, then by
        /// first-seen free rect. Returns false when nothing fits.
        private static bool BestFit(
            IReadOnlyList<FreeRect> free, SpriteSize s, bool allowRotate,
            out FreeRect outF, out int outW, out int outH, out bool outRotated)
        {
            bool found = false;
            outF = default;
            outW = 0; outH = 0; outRotated = false;
            int bestShort = 0, bestLong = 0;

            int[,] cands = allowRotate && s.W != s.H
                ? new[,] { { s.W, s.H, 0 }, { s.H, s.W, 1 } }
                : new[,] { { s.W, s.H, 0 } };
            int nCands = cands.GetLength(0);

            foreach (FreeRect f in free)
            {
                for (int c = 0; c < nCands; c++)
                {
                    int cw = cands[c, 0], ch = cands[c, 1];
                    if (cw > f.W || ch > f.H) continue;
                    int leftoverW = f.W - cw;
                    int leftoverH = f.H - ch;
                    int shortSide = Math.Min(leftoverW, leftoverH);
                    int longSide = Math.Max(leftoverW, leftoverH);
                    if (!found || shortSide < bestShort || (shortSide == bestShort && longSide < bestLong))
                    {
                        outF = f;
                        outW = cw;
                        outH = ch;
                        outRotated = cands[c, 2] == 1;
                        bestShort = shortSide;
                        bestLong = longSide;
                        found = true;
                    }
                }
            }
            return found;
        }

        /// 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 static List<FreeRect> SplitFree(IReadOnlyList<FreeRect> free, PackedRect p)
        {
            var next = new List<FreeRect>();
            foreach (FreeRect f in free)
            {
                bool 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(new FreeRect(f.X, f.Y, p.X - f.X, f.H));
                if (p.X + p.W < f.X + f.W)
                    next.Add(new FreeRect(p.X + p.W, f.Y, f.X + f.W - (p.X + p.W), f.H));
                if (p.Y > f.Y) next.Add(new FreeRect(f.X, f.Y, f.W, p.Y - f.Y));
                if (p.Y + p.H < f.Y + f.H)
                    next.Add(new FreeRect(f.X, p.Y + p.H, f.W, f.Y + f.H - (p.Y + p.H)));
            }
            var kept = new List<FreeRect>(next.Count);
            for (int i = 0; i < next.Count; i++)
            {
                bool keep = true;
                for (int j = 0; j < next.Count; j++)
                {
                    if (j != i && Contains(next[j], next[i]) && !(Contains(next[i], next[j]) && j > i))
                    {
                        keep = false;
                        break;
                    }
                }
                if (keep) kept.Add(next[i]);
            }
            return kept;
        }

        private static bool Contains(FreeRect outer, FreeRect inner) =>
            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.
        private static PackResult Finish(IReadOnlyList<SpriteSize> sizes, IReadOnlyList<PackedRect> placed)
        {
            int bw = 1, bh = 1;
            foreach (PackedRect p in placed)
            {
                bw = Math.Max(bw, p.X + p.W);
                bh = Math.Max(bh, p.Y + p.H);
            }
            var rects = new List<PackedRect>(sizes.Count);
            foreach (SpriteSize s in sizes)
            {
                foreach (PackedRect p in placed)
                {
                    if (p.Id == s.Id)
                    {
                        rects.Add(p);
                        break;
                    }
                }
            }
            return new PackResult(Pow2Ceil(bw), Pow2Ceil(bh), rects);
        }

        private static int Pow2Ceil(int n)
        {
            int p = 1;
            while (p < n) p *= 2;
            return p;
        }

        private static int Pow2Floor(int n)
        {
            int p = 1;
            while (p * 2 <= n) p *= 2;
            return p;
        }

        /// Minimal JSON string escaping (the atlas ids are plain slugs).
        private static string JsonStr(string s)
        {
            var outB = new StringBuilder(s.Length + 2);
            outB.Append('"');
            foreach (char c in s)
            {
                if (c == '"' || c == '\\')
                {
                    outB.Append('\\').Append(c);
                }
                else if (c < 0x20)
                {
                    outB.AppendFormat("\\u{0:x4}", (int)c);
                }
                else
                {
                    outB.Append(c);
                }
            }
            outB.Append('"');
            return outB.ToString();
        }

        /// Generic JSON atlas: one frame entry per sprite (assembled manually
        /// so the entries stay in pack-input order), sheet metadata for engines.
        public static string AtlasJson(string name, PackResult r)
        {
            var outB = new StringBuilder("{\n  \"frames\": {");
            for (int i = 0; i < r.Rects.Count; i++)
            {
                PackedRect rect = r.Rects[i];
                if (i > 0) outB.Append(',');
                outB.Append("\n    ").Append(JsonStr(rect.Id)).Append(": {\n");
                outB.Append("      \"frame\": {\n");
                outB.Append("        \"x\": ").Append(rect.X).Append(",\n");
                outB.Append("        \"y\": ").Append(rect.Y).Append(",\n");
                outB.Append("        \"w\": ").Append(rect.W).Append(",\n");
                outB.Append("        \"h\": ").Append(rect.H).Append("\n");
                outB.Append("      },\n");
                outB.Append("      \"rotated\": ").Append(rect.Rotated ? "true" : "false").Append("\n");
                outB.Append("    }");
            }
            outB.Append("\n  },\n  \"meta\": {\n");
            outB.Append("    \"size\": {\n");
            outB.Append("      \"w\": ").Append(r.SheetW).Append(",\n");
            outB.Append("      \"h\": ").Append(r.SheetH).Append("\n");
            outB.Append("    },\n");
            outB.Append("    \"name\": ").Append(JsonStr(name)).Append("\n");
            outB.Append("  }\n}");
            return outB.ToString();
        }

        /// One .sprite-<id> class per rect, positioned against the shared
        /// sheet image.
        public static string SpriteCss(PackResult r, string sheetName)
        {
            var outB = new StringBuilder();
            for (int i = 0; i < r.Rects.Count; i++)
            {
                PackedRect rect = r.Rects[i];
                if (i > 0) outB.Append('\n');
                outB.Append(".sprite-").Append(rect.Id).Append(" {\n");
                outB.Append("  width: ").Append(rect.W).Append("px;\n");
                outB.Append("  height: ").Append(rect.H).Append("px;\n");
                outB.Append("  background-image: url('").Append(sheetName).Append("');\n");
                outB.Append("  background-position: -").Append(rect.X).Append("px -").Append(rect.Y).Append("px;\n");
                outB.Append('}');
            }
            return outB.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 →