2
0

stb_rect_pack.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. #if defined(__GNUC__) || defined(__clang__)
  2. # pragma GCC diagnostic ignored "-Wtype-limits"
  3. # pragma GCC diagnostic ignored "-Wunused-function"
  4. # pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #else
  6. # pragma warning(disable:4100) // C4100: 'c': unreferenced formal parameter
  7. #endif
  8. // stb_rect_pack.h - v0.08 - public domain - rectangle packing
  9. // Sean Barrett 2014
  10. //
  11. // Useful for e.g. packing rectangular textures into an atlas.
  12. // Does not do rotation.
  13. //
  14. // Not necessarily the awesomest packing method, but better than
  15. // the totally naive one in stb_truetype (which is primarily what
  16. // this is meant to replace).
  17. //
  18. // Has only had a few tests run, may have issues.
  19. //
  20. // More docs to come.
  21. //
  22. // No memory allocations; uses qsort() and assert() from stdlib.
  23. // Can override those by defining STBRP_SORT and STBRP_ASSERT.
  24. //
  25. // This library currently uses the Skyline Bottom-Left algorithm.
  26. //
  27. // Please note: better rectangle packers are welcome! Please
  28. // implement them to the same API, but with a different init
  29. // function.
  30. //
  31. // Credits
  32. //
  33. // Library
  34. // Sean Barrett
  35. // Minor features
  36. // Martins Mozeiko
  37. // Bugfixes / warning fixes
  38. // Jeremy Jaussaud
  39. //
  40. // Version history:
  41. //
  42. // 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
  43. // 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
  44. // 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
  45. // 0.05: added STBRP_ASSERT to allow replacing assert
  46. // 0.04: fixed minor bug in STBRP_LARGE_RECTS support
  47. // 0.01: initial release
  48. //
  49. // LICENSE
  50. //
  51. // This software is dual-licensed to the public domain and under the following
  52. // license: you are granted a perpetual, irrevocable license to copy, modify,
  53. // publish, and distribute this file as you see fit.
  54. //////////////////////////////////////////////////////////////////////////////
  55. //
  56. // INCLUDE SECTION
  57. //
  58. #ifndef STB_INCLUDE_STB_RECT_PACK_H
  59. #define STB_INCLUDE_STB_RECT_PACK_H
  60. #define STB_RECT_PACK_VERSION 1
  61. #ifdef STBRP_STATIC
  62. #define STBRP_DEF static
  63. #else
  64. #define STBRP_DEF extern
  65. #endif
  66. #ifdef __cplusplus
  67. extern "C" {
  68. #endif
  69. typedef struct stbrp_context stbrp_context;
  70. typedef struct stbrp_node stbrp_node;
  71. typedef struct stbrp_rect stbrp_rect;
  72. #ifdef STBRP_LARGE_RECTS
  73. typedef int stbrp_coord;
  74. #else
  75. typedef unsigned short stbrp_coord;
  76. #endif
  77. STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
  78. // Assign packed locations to rectangles. The rectangles are of type
  79. // 'stbrp_rect' defined below, stored in the array 'rects', and there
  80. // are 'num_rects' many of them.
  81. //
  82. // Rectangles which are successfully packed have the 'was_packed' flag
  83. // set to a non-zero value and 'x' and 'y' store the minimum location
  84. // on each axis (i.e. bottom-left in cartesian coordinates, top-left
  85. // if you imagine y increasing downwards). Rectangles which do not fit
  86. // have the 'was_packed' flag set to 0.
  87. //
  88. // You should not try to access the 'rects' array from another thread
  89. // while this function is running, as the function temporarily reorders
  90. // the array while it executes.
  91. //
  92. // To pack into another rectangle, you need to call stbrp_init_target
  93. // again. To continue packing into the same rectangle, you can call
  94. // this function again. Calling this multiple times with multiple rect
  95. // arrays will probably produce worse packing results than calling it
  96. // a single time with the full rectangle array, but the option is
  97. // available.
  98. struct stbrp_rect
  99. {
  100. // reserved for your use:
  101. int id;
  102. // input:
  103. stbrp_coord w, h;
  104. // output:
  105. stbrp_coord x, y;
  106. int was_packed; // non-zero if valid packing
  107. }; // 16 bytes, nominally
  108. STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
  109. // Initialize a rectangle packer to:
  110. // pack a rectangle that is 'width' by 'height' in dimensions
  111. // using temporary storage provided by the array 'nodes', which is 'num_nodes' long
  112. //
  113. // You must call this function every time you start packing into a new target.
  114. //
  115. // There is no "shutdown" function. The 'nodes' memory must stay valid for
  116. // the following stbrp_pack_rects() call (or calls), but can be freed after
  117. // the call (or calls) finish.
  118. //
  119. // Note: to guarantee best results, either:
  120. // 1. make sure 'num_nodes' >= 'width'
  121. // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
  122. //
  123. // If you don't do either of the above things, widths will be quantized to multiples
  124. // of small integers to guarantee the algorithm doesn't run out of temporary storage.
  125. //
  126. // If you do #2, then the non-quantized algorithm will be used, but the algorithm
  127. // may run out of temporary storage and be unable to pack some rectangles.
  128. STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
  129. // Optionally call this function after init but before doing any packing to
  130. // change the handling of the out-of-temp-memory scenario, described above.
  131. // If you call init again, this will be reset to the default (false).
  132. STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
  133. // Optionally select which packing heuristic the library should use. Different
  134. // heuristics will produce better/worse results for different data sets.
  135. // If you call init again, this will be reset to the default.
  136. enum
  137. {
  138. STBRP_HEURISTIC_Skyline_default=0,
  139. STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
  140. STBRP_HEURISTIC_Skyline_BF_sortHeight,
  141. };
  142. //////////////////////////////////////////////////////////////////////////////
  143. //
  144. // the details of the following structures don't matter to you, but they must
  145. // be visible so you can handle the memory allocations for them
  146. struct stbrp_node
  147. {
  148. stbrp_coord x,y;
  149. stbrp_node *next;
  150. };
  151. struct stbrp_context
  152. {
  153. int width;
  154. int height;
  155. int align;
  156. int init_mode;
  157. int heuristic;
  158. int num_nodes;
  159. stbrp_node *active_head;
  160. stbrp_node *free_head;
  161. stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
  162. };
  163. #ifdef __cplusplus
  164. }
  165. #endif
  166. #endif
  167. //////////////////////////////////////////////////////////////////////////////
  168. //
  169. // IMPLEMENTATION SECTION
  170. //
  171. #ifdef STB_RECT_PACK_IMPLEMENTATION
  172. #ifndef STBRP_SORT
  173. #include <stdlib.h>
  174. #define STBRP_SORT qsort
  175. #endif
  176. #ifndef STBRP_ASSERT
  177. #include <assert.h>
  178. #define STBRP_ASSERT assert
  179. #endif
  180. enum
  181. {
  182. STBRP__INIT_skyline = 1,
  183. };
  184. STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
  185. {
  186. switch (context->init_mode) {
  187. case STBRP__INIT_skyline:
  188. STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
  189. context->heuristic = heuristic;
  190. break;
  191. default:
  192. STBRP_ASSERT(0);
  193. }
  194. }
  195. STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
  196. {
  197. if (allow_out_of_mem)
  198. // if it's ok to run out of memory, then don't bother aligning them;
  199. // this gives better packing, but may fail due to OOM (even though
  200. // the rectangles easily fit). @TODO a smarter approach would be to only
  201. // quantize once we've hit OOM, then we could get rid of this parameter.
  202. context->align = 1;
  203. else {
  204. // if it's not ok to run out of memory, then quantize the widths
  205. // so that num_nodes is always enough nodes.
  206. //
  207. // I.e. num_nodes * align >= width
  208. // align >= width / num_nodes
  209. // align = ceil(width/num_nodes)
  210. context->align = (context->width + context->num_nodes-1) / context->num_nodes;
  211. }
  212. }
  213. STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
  214. {
  215. int i;
  216. #ifndef STBRP_LARGE_RECTS
  217. STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
  218. #endif
  219. for (i=0; i < num_nodes-1; ++i)
  220. nodes[i].next = &nodes[i+1];
  221. nodes[i].next = NULL;
  222. context->init_mode = STBRP__INIT_skyline;
  223. context->heuristic = STBRP_HEURISTIC_Skyline_default;
  224. context->free_head = &nodes[0];
  225. context->active_head = &context->extra[0];
  226. context->width = width;
  227. context->height = height;
  228. context->num_nodes = num_nodes;
  229. stbrp_setup_allow_out_of_mem(context, 0);
  230. // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
  231. context->extra[0].x = 0;
  232. context->extra[0].y = 0;
  233. context->extra[0].next = &context->extra[1];
  234. context->extra[1].x = (stbrp_coord) width;
  235. #ifdef STBRP_LARGE_RECTS
  236. context->extra[1].y = (1<<30);
  237. #else
  238. context->extra[1].y = 65535;
  239. #endif
  240. context->extra[1].next = NULL;
  241. }
  242. // find minimum y position if it starts at x1
  243. static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
  244. {
  245. stbrp_node *node = first;
  246. int x1 = x0 + width;
  247. int min_y, visited_width, waste_area;
  248. STBRP_ASSERT(first->x <= x0);
  249. #if 0
  250. // skip in case we're past the node
  251. while (node->next->x <= x0)
  252. ++node;
  253. #else
  254. STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
  255. #endif
  256. STBRP_ASSERT(node->x <= x0);
  257. min_y = 0;
  258. waste_area = 0;
  259. visited_width = 0;
  260. while (node->x < x1) {
  261. if (node->y > min_y) {
  262. // raise min_y higher.
  263. // we've accounted for all waste up to min_y,
  264. // but we'll now add more waste for everything we've visted
  265. waste_area += visited_width * (node->y - min_y);
  266. min_y = node->y;
  267. // the first time through, visited_width might be reduced
  268. if (node->x < x0)
  269. visited_width += node->next->x - x0;
  270. else
  271. visited_width += node->next->x - node->x;
  272. } else {
  273. // add waste area
  274. int under_width = node->next->x - node->x;
  275. if (under_width + visited_width > width)
  276. under_width = width - visited_width;
  277. waste_area += under_width * (min_y - node->y);
  278. visited_width += under_width;
  279. }
  280. node = node->next;
  281. }
  282. *pwaste = waste_area;
  283. return min_y;
  284. }
  285. typedef struct
  286. {
  287. int x,y;
  288. stbrp_node **prev_link;
  289. } stbrp__findresult;
  290. static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
  291. {
  292. int best_waste = (1<<30), best_x, best_y = (1 << 30);
  293. stbrp__findresult fr;
  294. stbrp_node **prev, *node, *tail, **best = NULL;
  295. // align to multiple of c->align
  296. width = (width + c->align - 1);
  297. width -= width % c->align;
  298. STBRP_ASSERT(width % c->align == 0);
  299. node = c->active_head;
  300. prev = &c->active_head;
  301. while (node->x + width <= c->width) {
  302. int y,waste;
  303. y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
  304. if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
  305. // bottom left
  306. if (y < best_y) {
  307. best_y = y;
  308. best = prev;
  309. }
  310. } else {
  311. // best-fit
  312. if (y + height <= c->height) {
  313. // can only use it if it first vertically
  314. if (y < best_y || (y == best_y && waste < best_waste)) {
  315. best_y = y;
  316. best_waste = waste;
  317. best = prev;
  318. }
  319. }
  320. }
  321. prev = &node->next;
  322. node = node->next;
  323. }
  324. best_x = (best == NULL) ? 0 : (*best)->x;
  325. // if doing best-fit (BF), we also have to try aligning right edge to each node position
  326. //
  327. // e.g, if fitting
  328. //
  329. // ____________________
  330. // |____________________|
  331. //
  332. // into
  333. //
  334. // | |
  335. // | ____________|
  336. // |____________|
  337. //
  338. // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
  339. //
  340. // This makes BF take about 2x the time
  341. if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
  342. tail = c->active_head;
  343. node = c->active_head;
  344. prev = &c->active_head;
  345. // find first node that's admissible
  346. while (tail->x < width)
  347. tail = tail->next;
  348. while (tail) {
  349. int xpos = tail->x - width;
  350. int y,waste;
  351. STBRP_ASSERT(xpos >= 0);
  352. // find the left position that matches this
  353. while (node->next->x <= xpos) {
  354. prev = &node->next;
  355. node = node->next;
  356. }
  357. STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
  358. y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
  359. if (y + height < c->height) {
  360. if (y <= best_y) {
  361. if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
  362. best_x = xpos;
  363. STBRP_ASSERT(y <= best_y);
  364. best_y = y;
  365. best_waste = waste;
  366. best = prev;
  367. }
  368. }
  369. }
  370. tail = tail->next;
  371. }
  372. }
  373. fr.prev_link = best;
  374. fr.x = best_x;
  375. fr.y = best_y;
  376. return fr;
  377. }
  378. static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
  379. {
  380. // find best position according to heuristic
  381. stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
  382. stbrp_node *node, *cur;
  383. // bail if:
  384. // 1. it failed
  385. // 2. the best node doesn't fit (we don't always check this)
  386. // 3. we're out of memory
  387. if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
  388. res.prev_link = NULL;
  389. return res;
  390. }
  391. // on success, create new node
  392. node = context->free_head;
  393. node->x = (stbrp_coord) res.x;
  394. node->y = (stbrp_coord) (res.y + height);
  395. context->free_head = node->next;
  396. // insert the new node into the right starting point, and
  397. // let 'cur' point to the remaining nodes needing to be
  398. // stiched back in
  399. cur = *res.prev_link;
  400. if (cur->x < res.x) {
  401. // preserve the existing one, so start testing with the next one
  402. stbrp_node *next = cur->next;
  403. cur->next = node;
  404. cur = next;
  405. } else {
  406. *res.prev_link = node;
  407. }
  408. // from here, traverse cur and free the nodes, until we get to one
  409. // that shouldn't be freed
  410. while (cur->next && cur->next->x <= res.x + width) {
  411. stbrp_node *next = cur->next;
  412. // move the current node to the free list
  413. cur->next = context->free_head;
  414. context->free_head = cur;
  415. cur = next;
  416. }
  417. // stitch the list back in
  418. node->next = cur;
  419. if (cur->x < res.x + width)
  420. cur->x = (stbrp_coord) (res.x + width);
  421. #ifdef _DEBUG
  422. cur = context->active_head;
  423. while (cur->x < context->width) {
  424. STBRP_ASSERT(cur->x < cur->next->x);
  425. cur = cur->next;
  426. }
  427. STBRP_ASSERT(cur->next == NULL);
  428. {
  429. stbrp_node *L1 = NULL, *L2 = NULL;
  430. int count=0;
  431. cur = context->active_head;
  432. while (cur) {
  433. L1 = cur;
  434. cur = cur->next;
  435. ++count;
  436. }
  437. cur = context->free_head;
  438. while (cur) {
  439. L2 = cur;
  440. cur = cur->next;
  441. ++count;
  442. }
  443. STBRP_ASSERT(count == context->num_nodes+2);
  444. }
  445. #endif
  446. return res;
  447. }
  448. static int rect_height_compare(const void *a, const void *b)
  449. {
  450. stbrp_rect *p = (stbrp_rect *) a;
  451. stbrp_rect *q = (stbrp_rect *) b;
  452. if (p->h > q->h)
  453. return -1;
  454. if (p->h < q->h)
  455. return 1;
  456. return (p->w > q->w) ? -1 : (p->w < q->w);
  457. }
  458. static int rect_width_compare(const void *a, const void *b)
  459. {
  460. stbrp_rect *p = (stbrp_rect *) a;
  461. stbrp_rect *q = (stbrp_rect *) b;
  462. if (p->w > q->w)
  463. return -1;
  464. if (p->w < q->w)
  465. return 1;
  466. return (p->h > q->h) ? -1 : (p->h < q->h);
  467. }
  468. static int rect_original_order(const void *a, const void *b)
  469. {
  470. stbrp_rect *p = (stbrp_rect *) a;
  471. stbrp_rect *q = (stbrp_rect *) b;
  472. return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
  473. }
  474. #ifdef STBRP_LARGE_RECTS
  475. #define STBRP__MAXVAL 0xffffffff
  476. #else
  477. #define STBRP__MAXVAL 0xffff
  478. #endif
  479. STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
  480. {
  481. int i;
  482. // we use the 'was_packed' field internally to allow sorting/unsorting
  483. for (i=0; i < num_rects; ++i) {
  484. rects[i].was_packed = i;
  485. #ifndef STBRP_LARGE_RECTS
  486. STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff);
  487. #endif
  488. }
  489. // sort according to heuristic
  490. STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
  491. for (i=0; i < num_rects; ++i) {
  492. if (rects[i].w == 0 || rects[i].h == 0) {
  493. rects[i].x = rects[i].y = 0; // empty rect needs no space
  494. } else {
  495. stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
  496. if (fr.prev_link) {
  497. rects[i].x = (stbrp_coord) fr.x;
  498. rects[i].y = (stbrp_coord) fr.y;
  499. } else {
  500. rects[i].x = rects[i].y = STBRP__MAXVAL;
  501. }
  502. }
  503. }
  504. // unsort
  505. STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
  506. // set was_packed flags
  507. for (i=0; i < num_rects; ++i)
  508. rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
  509. }
  510. #endif