stb_rect_pack.h 17 KB

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