Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stb_rect_pack.h 16KB

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