SpritePacker.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <limits.h>
  23. #define STBRP_LARGE_RECTS
  24. #define STB_RECT_PACK_IMPLEMENTATION
  25. #include "stb_rect_pack.h"
  26. #include <Urho3D/Urho3D.h>
  27. #include <Urho3D/Core/Context.h>
  28. #include <Urho3D/Container/Vector.h>
  29. #include <Urho3D/Core/ProcessUtils.h>
  30. #include <Urho3D/Core/StringUtils.h>
  31. #include <Urho3D/Math/MathDefs.h>
  32. #include <Urho3D/Resource/Image.h>
  33. #include <Urho3D/IO/FileSystem.h>
  34. #include <Urho3D/IO/File.h>
  35. #include <Urho3D/Resource/XMLElement.h>
  36. #include <Urho3D/Resource/XMLFile.h>
  37. #include <Urho3D/IO/Log.h>
  38. #include <Urho3D/Math/Color.h>
  39. #ifdef WIN32
  40. #include <windows.h>
  41. #endif
  42. #include <Urho3D/DebugNew.h>
  43. using namespace Urho3D;
  44. // number of nodes allocated to each packer info. since this packer is not suited for real time purposes we can over allocate.
  45. const int PACKER_NUM_NODES = 4096;
  46. const int MAX_TEXTURE_SIZE = 2048;
  47. int main(int argc, char** argv);
  48. void Run(Vector<String>& arguments);
  49. class PackerInfo : public RefCounted
  50. {
  51. public:
  52. String path;
  53. String name;
  54. int x;
  55. int y;
  56. int offsetX;
  57. int offsetY;
  58. int width;
  59. int height;
  60. int frameWidth;
  61. int frameHeight;
  62. int frameX;
  63. int frameY;
  64. PackerInfo(String path_, String name_) :
  65. path(path_),
  66. name(name_),
  67. x(0),
  68. y(0),
  69. offsetX(0),
  70. offsetY(0),
  71. frameX(0),
  72. frameY(0)
  73. {
  74. }
  75. ~PackerInfo() {}
  76. };
  77. void Help()
  78. {
  79. ErrorExit("Usage: SpritePacker -options <input file> <input file> <output png file>\n"
  80. "\n"
  81. "Options:\n"
  82. "-h Shows this help message.\n"
  83. "-px Adds x pixels of padding per image to width.\n"
  84. "-py Adds y pixels of padding per image to height.\n"
  85. "-ox Adds x pixels to the horizontal position per image.\n"
  86. "-oy Adds y pixels to the horizontal position per image.\n"
  87. "-frameHeight Sets a fixed height for image and centers within frame.\n"
  88. "-frameWidth Sets a fixed width for image and centers within frame.\n"
  89. "-trim Trims excess transparent space from individual images offsets by frame size.\n"
  90. "-xml \'path\' Generates an SpriteSheet xml file at path.\n"
  91. "-debug Draws allocation boxes on sprite.\n");
  92. }
  93. int main(int argc, char** argv)
  94. {
  95. Vector<String> arguments;
  96. #ifdef WIN32
  97. arguments = ParseArguments(GetCommandLineW());
  98. #else
  99. arguments = ParseArguments(argc, argv);
  100. #endif
  101. Run(arguments);
  102. return 0;
  103. }
  104. void Run(Vector<String>& arguments)
  105. {
  106. if (arguments.Size() < 2)
  107. Help();
  108. SharedPtr<Context> context(new Context());
  109. context->RegisterSubsystem(new FileSystem(context));
  110. context->RegisterSubsystem(new Log(context));
  111. FileSystem* fileSystem = context->GetSubsystem<FileSystem>();
  112. Vector<String> inputFiles;
  113. String outputFile;
  114. String spriteSheetFileName;
  115. bool debug = false;
  116. unsigned padX = 0;
  117. unsigned padY = 0;
  118. unsigned offsetX = 0;
  119. unsigned offsetY = 0;
  120. unsigned frameWidth = 0;
  121. unsigned frameHeight = 0;
  122. bool help = false;
  123. bool trim = false;
  124. while (arguments.Size() > 0)
  125. {
  126. String arg = arguments[0];
  127. arguments.Erase(0);
  128. if (arg.Empty())
  129. continue;
  130. if (arg.StartsWith("-"))
  131. {
  132. if (arg == "-px") { padX = ToUInt(arguments[0]); arguments.Erase(0); }
  133. else if (arg == "-py") { padY = ToUInt(arguments[0]); arguments.Erase(0); }
  134. else if (arg == "-ox") { offsetX = ToUInt(arguments[0]); arguments.Erase(0); }
  135. else if (arg == "-oy") { offsetY = ToUInt(arguments[0]); arguments.Erase(0); }
  136. else if (arg == "-frameWidth") { frameWidth = ToUInt(arguments[0]); arguments.Erase(0); }
  137. else if (arg == "-frameHeight") { frameHeight = ToUInt(arguments[0]); arguments.Erase(0); }
  138. else if (arg == "-trim") { trim = true; }
  139. else if (arg == "-xml") { spriteSheetFileName = arguments[0]; arguments.Erase(0); }
  140. else if (arg == "-h") { help = true; break; }
  141. else if (arg == "-debug") { debug = true; }
  142. }
  143. else
  144. inputFiles.Push(arg);
  145. }
  146. if (help)
  147. Help();
  148. if (inputFiles.Size() < 2)
  149. ErrorExit("An input and output file must be specified.");
  150. if (frameWidth ^ frameHeight)
  151. ErrorExit("Both frameHeight and frameWidth must be ommited or specified.");
  152. // take last input file as output
  153. if (inputFiles.Size() > 1)
  154. {
  155. outputFile = inputFiles[inputFiles.Size() - 1];
  156. LOGINFO("Output file set to " + outputFile + ".");
  157. inputFiles.Erase(inputFiles.Size() - 1);
  158. }
  159. // set spritesheet name to outputfile.xml if not specified
  160. if (spriteSheetFileName.Empty())
  161. spriteSheetFileName = ReplaceExtension(outputFile, ".xml");
  162. if (GetParentPath(spriteSheetFileName) != GetParentPath(outputFile))
  163. ErrorExit("Both output xml and png must be in the same folder");
  164. // check all input files exist
  165. for (unsigned i = 0; i < inputFiles.Size(); ++i)
  166. {
  167. LOGINFO("Checking " + inputFiles[i] + " to see if file exists.");
  168. if (!fileSystem->FileExists(inputFiles[i]))
  169. ErrorExit("File " + inputFiles[i] + " does not exist.");
  170. }
  171. // Set the max offset equal to padding to prevent images from going out of bounds
  172. offsetX = Min((int)offsetX, (int)padX);
  173. offsetY = Min((int)offsetY, (int)padY);
  174. Vector<SharedPtr<PackerInfo > > packerInfos;
  175. for (unsigned i = 0; i < inputFiles.Size(); ++i)
  176. {
  177. String path = inputFiles[i];
  178. String name = ReplaceExtension(GetFileName(path), "");
  179. File file(context, path);
  180. Image image(context);
  181. if (!image.Load(file))
  182. ErrorExit("Could not load image " + path + ".");
  183. if (image.IsCompressed())
  184. ErrorExit(path + " is compressed. Compressed images are not allowed.");
  185. SharedPtr<PackerInfo> packerInfo(new PackerInfo(path, name));
  186. int imageWidth = image.GetWidth();
  187. int imageHeight = image.GetHeight();
  188. int trimOffsetX = 0;
  189. int trimOffsetY = 0;
  190. int adjustedWidth = imageWidth;
  191. int adjustedHeight = imageHeight;
  192. if (trim)
  193. {
  194. int minX = imageWidth;
  195. int minY = imageHeight;
  196. int maxX = 0;
  197. int maxY = 0;
  198. for (int y = 0; y < imageHeight; ++y)
  199. {
  200. for (int x = 0; x < imageWidth; ++x)
  201. {
  202. bool found = (image.GetPixelInt(x, y) & 0x000000ff) != 0;
  203. if (found) {
  204. minX = Min(minX, x);
  205. minY = Min(minY, y);
  206. maxX = Max(maxX, x);
  207. maxY = Max(maxY, y);
  208. }
  209. }
  210. }
  211. trimOffsetX = minX;
  212. trimOffsetY = minY;
  213. adjustedWidth = maxX - minX + 1;
  214. adjustedHeight = maxY - minY + 1;
  215. }
  216. if (trim)
  217. {
  218. packerInfo->frameWidth = imageWidth;
  219. packerInfo->frameHeight = imageHeight;
  220. }
  221. else if (frameWidth || frameHeight)
  222. {
  223. packerInfo->frameWidth = frameWidth;
  224. packerInfo->frameHeight = frameHeight;
  225. }
  226. packerInfo->width = adjustedWidth;
  227. packerInfo->height = adjustedHeight;
  228. packerInfo->offsetX -= trimOffsetX;
  229. packerInfo->offsetY -= trimOffsetY;
  230. packerInfos.Push(packerInfo);
  231. }
  232. int packedWidth = MAX_TEXTURE_SIZE;
  233. int packedHeight = MAX_TEXTURE_SIZE;
  234. {
  235. // fill up an list of tries in increasing size and take the first win
  236. Vector<IntVector2> tries;
  237. for(unsigned x=2; x<11; ++x)
  238. {
  239. for(unsigned y=2; y<11; ++y)
  240. tries.Push(IntVector2((1<<x), (1<<y)));
  241. }
  242. // load rectangles
  243. stbrp_rect* packerRects = new stbrp_rect[packerInfos.Size()];
  244. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  245. {
  246. PackerInfo* packerInfo = packerInfos[i];
  247. stbrp_rect* packerRect = &packerRects[i];
  248. packerRect->id = i;
  249. packerRect->h = packerInfo->height + padY;
  250. packerRect->w = packerInfo->width + padX;
  251. }
  252. bool success = false;
  253. while (tries.Size() > 0)
  254. {
  255. IntVector2 size = tries[0];
  256. tries.Erase(0);
  257. bool fit = true;
  258. int textureHeight = size.y_;
  259. int textureWidth = size.x_;
  260. if (success && textureHeight * textureWidth > packedWidth * packedHeight)
  261. continue;
  262. stbrp_context packerContext;
  263. stbrp_node packerMemory[PACKER_NUM_NODES];
  264. stbrp_init_target(&packerContext, textureWidth, textureHeight, packerMemory, packerInfos.Size());
  265. stbrp_pack_rects(&packerContext, packerRects, packerInfos.Size());
  266. // check to see if everything fit
  267. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  268. {
  269. stbrp_rect* packerRect = &packerRects[i];
  270. if (!packerRect->was_packed)
  271. {
  272. fit = false;
  273. break;
  274. }
  275. }
  276. if (fit)
  277. {
  278. success = true;
  279. // distribute values to packer info
  280. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  281. {
  282. stbrp_rect* packerRect = &packerRects[i];
  283. PackerInfo* packerInfo = packerInfos[packerRect->id];
  284. packerInfo->x = packerRect->x;
  285. packerInfo->y = packerRect->y;
  286. }
  287. packedWidth = size.x_;
  288. packedHeight = size.y_;
  289. }
  290. }
  291. delete packerRects;
  292. if (!success)
  293. ErrorExit("Could not allocate for all images. The max sprite sheet texture size is " + String(MAX_TEXTURE_SIZE) + "x" + String(MAX_TEXTURE_SIZE) + ".");
  294. }
  295. // create image for spritesheet
  296. Image spriteSheetImage(context);
  297. spriteSheetImage.SetSize(packedWidth, packedHeight, 4);
  298. // zero out image
  299. spriteSheetImage.SetData((unsigned char*)calloc(sizeof(unsigned char), packedWidth * packedHeight * 4));
  300. XMLFile xml(context);
  301. XMLElement root = xml.CreateRoot("TextureAtlas");
  302. root.SetAttribute("imagePath", GetFileNameAndExtension(outputFile));
  303. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  304. {
  305. SharedPtr<PackerInfo> packerInfo = packerInfos[i];
  306. XMLElement subTexture = root.CreateChild("SubTexture");
  307. subTexture.SetString("name", packerInfo->name);
  308. subTexture.SetInt("x", packerInfo->x + offsetX);
  309. subTexture.SetInt("y", packerInfo->y + offsetY);
  310. subTexture.SetInt("width", packerInfo->width);
  311. subTexture.SetInt("height", packerInfo->height);
  312. if (packerInfo->frameWidth || packerInfo->frameHeight)
  313. {
  314. subTexture.SetInt("frameWidth", packerInfo->frameWidth);
  315. subTexture.SetInt("frameHeight", packerInfo->frameHeight);
  316. subTexture.SetInt("offsetX", packerInfo->offsetX);
  317. subTexture.SetInt("offsetY", packerInfo->offsetY);
  318. }
  319. LOGINFO("Transfering " + packerInfo->path + " to sprite sheet.");
  320. File file(context, packerInfo->path);
  321. Image image(context);
  322. if (!image.Load(file))
  323. ErrorExit("Could not load image " + packerInfo->path + ".");
  324. for (int y = 0; y < packerInfo->height; ++y)
  325. {
  326. for (int x = 0; x < packerInfo->width; ++x)
  327. {
  328. unsigned color = image.GetPixelInt(x - packerInfo->offsetX, y - packerInfo->offsetY);
  329. spriteSheetImage.SetPixelInt(
  330. packerInfo->x + offsetX + x,
  331. packerInfo->y + offsetY + y, color);
  332. }
  333. }
  334. }
  335. if (debug)
  336. {
  337. unsigned OUTER_BOUNDS_DEBUG_COLOR = Color::BLUE.ToUInt();
  338. unsigned INNER_BOUNDS_DEBUG_COLOR = Color::GREEN.ToUInt();
  339. LOGINFO("Drawing debug information.");
  340. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  341. {
  342. SharedPtr<PackerInfo> packerInfo = packerInfos[i];
  343. // Draw outer bounds
  344. for (int x = 0; x < packerInfo->frameWidth; ++x)
  345. {
  346. spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y, OUTER_BOUNDS_DEBUG_COLOR);
  347. spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y + packerInfo->frameHeight, OUTER_BOUNDS_DEBUG_COLOR);
  348. }
  349. for (int y = 0; y < packerInfo->frameHeight; ++y)
  350. {
  351. spriteSheetImage.SetPixelInt(packerInfo->x, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR);
  352. spriteSheetImage.SetPixelInt(packerInfo->x + packerInfo->frameWidth, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR);
  353. }
  354. // Draw inner bounds
  355. for (int x = 0; x < packerInfo->width; ++x)
  356. {
  357. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY, INNER_BOUNDS_DEBUG_COLOR);
  358. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY + packerInfo->height, INNER_BOUNDS_DEBUG_COLOR);
  359. }
  360. for (int y = 0; y < packerInfo->height; ++y)
  361. {
  362. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR);
  363. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + packerInfo->width, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR);
  364. }
  365. }
  366. }
  367. LOGINFO("Saving output image.");
  368. spriteSheetImage.SavePNG(outputFile);
  369. LOGINFO("Saving SpriteSheet xml file.");
  370. File spriteSheetFile(context);
  371. spriteSheetFile.Open(spriteSheetFileName, FILE_WRITE);
  372. xml.Save(spriteSheetFile);
  373. }