SpritePacker.cpp 15 KB

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