using System; using System.Collections.Generic; using System.Drawing; using System.Security.Cryptography; using System.IO; using System.Configuration; using System.Drawing.Text; using System.Drawing.Imaging; using System.Text; using System.Linq; namespace SpritePacker { public class SpritePacker { /// /// A list of all the sprites added to the sprite packer. /// private List sprites = new List(); /// /// Whether debug information should be outputted to the console. /// /// true if verbose; false otherwise. public bool Verbose { get; private set; } /// /// Gets a list of the current sprites. /// public Sprite[] CurrentSprites { get { return sprites.ToArray(); } } /// /// Initializes a new SpritePacker. /// /// Whether to output debug information to the console. public SpritePacker(bool inVerbose = false) { Verbose = inVerbose; } /// /// Adds a sprite to the sprite packer. /// /// Sprite. public void Add(Sprite sprite) { if(Verbose) Console.WriteLine("Adding {0}.", sprite); sprites.Add(sprite); } public void Add(IEnumerable sprites) { foreach (Sprite sprite in sprites) Add(sprite); } /// /// Adds a sprite to the sprite packer. /// /// Whether a sprite was actually removed or not. public bool Remove(Sprite sprite) { return sprites.Remove(sprite); } /// /// Clears the list of sprites added to the current sprite packer. /// public void Clear() { sprites.Clear(); } /// /// Packs all the added sprites in as small a area as possible. /// Note that this operation may potentially be very computationally expensive. /// public void Arrange() { sortBySize(); List arrangedSprites = sprites.Where((Sprite spr) => spr.Placed).ToList(); List spritesToPack = sprites.Where((Sprite spr) => !spr.Placed).ToList(); foreach(Sprite cspr in spritesToPack) { if(Verbose) Console.WriteLine("Attempting to place {0}.", cspr); Point scanLines = Point.Empty; Point nextScanLines = new Point(int.MaxValue, int.MaxValue); while(true) { if (!cspr.IntersectsWith(arrangedSprites)) break; if(Verbose) Console.WriteLine("Scan lines: {0}", scanLines); if(Verbose) Console.WriteLine("Scanning X..."); // Scan along the X axis cspr.X = 0; cspr.Y = scanLines.Y; bool foundPosition = false; while(cspr.X <= scanLines.X) { if(Verbose) Console.Write("Position: {0} ", cspr.X); if (!cspr.IntersectsWith(arrangedSprites)) { if(Verbose) Console.WriteLine("Found position on the X axis."); foundPosition = true; break; } // Get the edge furthest to the right List problems = cspr.GetIntersectors(arrangedSprites); Sprite rightProblem = problems[0]; foreach (Sprite probSpr in problems) { if (probSpr.Right > rightProblem.Right) rightProblem = probSpr; // If the current problem's bottom edge is less than the bottom of the next scan line, // move the next scan line up a bit. // Also make sure that the next scan line and the current scan line don't touch or cross. if (probSpr.Bottom < nextScanLines.Y && probSpr.Bottom > scanLines.Y) nextScanLines.Y = probSpr.Bottom; // NOTE: Add one here? } if(Verbose) Console.WriteLine("Found rightmost problem: {0}", rightProblem); // Move up to the position furthest to the right cspr.X = rightProblem.Right; // NOTE: Add one here? } if (!foundPosition) { if(Verbose) Console.WriteLine("Failed to find anything on the X axis. Scanning Y..."); // We didn't find anything along the x axis - let's scan the y axis next cspr.X = scanLines.X; cspr.Y = 0; while (cspr.Y <= scanLines.Y) { if(Verbose) Console.Write("Position: {0} ", cspr.Y); if (!cspr.IntersectsWith(arrangedSprites)) { if(Verbose) Console.WriteLine("Found position on the Y axis."); foundPosition = true; break; } // Get the edge furthest downwards List problems = cspr.GetIntersectors(arrangedSprites); Sprite downProblem = problems[0]; foreach (Sprite probSpr in problems) { if (probSpr.Bottom > downProblem.Bottom) downProblem = probSpr; // If the current problem's right edge is further in than the current next scan line, // move the next scan line up to meet it. // Also make sure that the next scan line and the current scan line don't touch or cross. if (probSpr.Right < nextScanLines.X && probSpr.Right > scanLines.X) nextScanLines.X = probSpr.Right; // NOTE: Add one here? } if(Verbose) Console.WriteLine("Found downProblem {0}", downProblem); // Move up to the position furthest downwards cspr.Y = downProblem.Bottom; // NOTE: Add one here? } } // If we found a new position, then we don't need to move the scan lines up and try again if (foundPosition) { cspr.Placed = true; break; } if(Verbose) Console.WriteLine("Failed to find a position along the current scan lines."); if(Verbose) Console.WriteLine("Next candidate scan lines: {0}", nextScanLines); // Make sure that the next scan lines are sane if (nextScanLines.X == int.MaxValue) nextScanLines.X = scanLines.X; if (nextScanLines.Y == int.MaxValue) nextScanLines.Y = scanLines.Y; if(Verbose) Console.WriteLine("Actual next scan lines: {0}", nextScanLines); // If the next scan lines and the current scan lines are identical, // then something is very wrong if(nextScanLines.Equals(scanLines)) throw new Exception("Failed to find the next set of lines to scan!"); // Move the scan lines up to the next nearest ones we've found scanLines = nextScanLines; nextScanLines = new Point(int.MaxValue, int.MaxValue); } arrangedSprites.Add(cspr); if(Verbose) Console.WriteLine("Finished positioning {0}.", cspr); } // We don't need to copy the list of arranged sprites across to the main list here // because Sprite is a class and classes are passed by _reference_. } /// /// Generates an image that contains all the currently added sprites. /// You probably want to call Arrage() before calling this method. /// Returns null if you haven't added any sprites to the SpritePacker yet. /// /// The generated image. public Bitmap GenerateImage() { // Calculate the size of the image we are about to output Point imageSize = new Point(0, 0); foreach(Sprite spr in sprites) { if (spr.Bottom > imageSize.Y) imageSize.Y = spr.Bottom; if (spr.Right > imageSize.X) imageSize.X = spr.Right; } if (imageSize.IsEmpty) return null; Bitmap finalImage = new Bitmap(imageSize.X, imageSize.Y, PixelFormat.Format32bppArgb); finalImage.MakeTransparent(); using (Graphics context = Graphics.FromImage(finalImage)) { foreach(Sprite spr in sprites) { context.DrawImage(spr.Image, spr.Location); } } return finalImage; } /// /// Output the packed sprite as an image to the specified filename. /// You probably want to call Arrage() before calling this method. /// /// The filename to save the generated image to. public void Output(string outputFilename) { using (Bitmap finalImage = GenerateImage()) { finalImage.Save(outputFilename); } } /// /// Gets a the details of the currently added sprites as a string of CSV. /// /// Details of the current sprites as a string of CSV. /// Whether to include a header in the generated CSV. public string GetSpritePositionsCSV(bool header = true) { StringWriter result = new StringWriter(); if (header) result.WriteLine("index,filename,x,y,width,height"); int i = 0; foreach(Sprite spr in sprites) { result.WriteLine("{0},{1},{2},{3},{4},{5}", new object[] { i, spr.Filename, spr.X, spr.Y, spr.Width, spr.Height }); i++; } return result.ToString(); } /// /// Sorts the sprites by size. /// private void sortBySize() { sprites.Sort((a, b) => -a.AreaSize.CompareTo(b.AreaSize)); } /// /// Returns a string that represents the current sprite packer. /// /// A string that represents the current sprite packer. public override string ToString() { string result = string.Format("SpritePacker:") + Environment.NewLine; foreach (Sprite spr in sprites) result += string.Format("\t{0}\n", spr); return result; } } }