1 // stb_rect_pack.h - v1.00 - public domain - rectangle packing
4 // Useful for e.g. packing rectangular textures into an atlas.
5 // Does not do rotation.
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).
11 // Has only had a few tests run, may have issues.
15 // No memory allocations; uses qsort() and assert() from stdlib.
16 // Can override those by defining STBRP_SORT and STBRP_ASSERT.
18 // This library currently uses the Skyline Bottom-Left algorithm.
20 // Please note: better rectangle packers are welcome! Please
21 // implement them to the same API, but with a different init
30 // github:IntellectualKitty
32 // Bugfixes / warning fixes
38 // 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
39 // 0.99 (2019-02-07) warning fixes
40 // 0.11 (2017-03-03) return packing success/fail result
41 // 0.10 (2016-10-25) remove cast-away-const to avoid warnings
42 // 0.09 (2016-08-27) fix compiler warnings
43 // 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
44 // 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
45 // 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
46 // 0.05: added STBRP_ASSERT to allow replacing assert
47 // 0.04: fixed minor bug in STBRP_LARGE_RECTS support
48 // 0.01: initial release
52 // See end of file for license information.
54 //////////////////////////////////////////////////////////////////////////////
59 #ifndef STB_INCLUDE_STB_RECT_PACK_H
60 #define STB_INCLUDE_STB_RECT_PACK_H
62 #define STB_RECT_PACK_VERSION 1
65 #define STBRP_DEF static
67 #define STBRP_DEF extern
74 typedef struct stbrp_context stbrp_context;
75 typedef struct stbrp_node stbrp_node;
76 typedef struct stbrp_rect stbrp_rect;
78 #ifdef STBRP_LARGE_RECTS
79 typedef int stbrp_coord;
81 typedef unsigned short stbrp_coord;
84 STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
85 // Assign packed locations to rectangles. The rectangles are of type
86 // 'stbrp_rect' defined below, stored in the array 'rects', and there
87 // are 'num_rects' many of them.
89 // Rectangles which are successfully packed have the 'was_packed' flag
90 // set to a non-zero value and 'x' and 'y' store the minimum location
91 // on each axis (i.e. bottom-left in cartesian coordinates, top-left
92 // if you imagine y increasing downwards). Rectangles which do not fit
93 // have the 'was_packed' flag set to 0.
95 // You should not try to access the 'rects' array from another thread
96 // while this function is running, as the function temporarily reorders
97 // the array while it executes.
99 // To pack into another rectangle, you need to call stbrp_init_target
100 // again. To continue packing into the same rectangle, you can call
101 // this function again. Calling this multiple times with multiple rect
102 // arrays will probably produce worse packing results than calling it
103 // a single time with the full rectangle array, but the option is
106 // The function returns 1 if all of the rectangles were successfully
107 // packed and 0 otherwise.
111 // reserved for your use:
119 int was_packed; // non-zero if valid packing
121 }; // 16 bytes, nominally
124 STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
125 // Initialize a rectangle packer to:
126 // pack a rectangle that is 'width' by 'height' in dimensions
127 // using temporary storage provided by the array 'nodes', which is 'num_nodes' long
129 // You must call this function every time you start packing into a new target.
131 // There is no "shutdown" function. The 'nodes' memory must stay valid for
132 // the following stbrp_pack_rects() call (or calls), but can be freed after
133 // the call (or calls) finish.
135 // Note: to guarantee best results, either:
136 // 1. make sure 'num_nodes' >= 'width'
137 // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
139 // If you don't do either of the above things, widths will be quantized to multiples
140 // of small integers to guarantee the algorithm doesn't run out of temporary storage.
142 // If you do #2, then the non-quantized algorithm will be used, but the algorithm
143 // may run out of temporary storage and be unable to pack some rectangles.
145 STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
146 // Optionally call this function after init but before doing any packing to
147 // change the handling of the out-of-temp-memory scenario, described above.
148 // If you call init again, this will be reset to the default (false).
151 STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
152 // Optionally select which packing heuristic the library should use. Different
153 // heuristics will produce better/worse results for different data sets.
154 // If you call init again, this will be reset to the default.
158 STBRP_HEURISTIC_Skyline_default=0,
159 STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
160 STBRP_HEURISTIC_Skyline_BF_sortHeight
164 //////////////////////////////////////////////////////////////////////////////
166 // the details of the following structures don't matter to you, but they must
167 // be visible so you can handle the memory allocations for them
183 stbrp_node *active_head;
184 stbrp_node *free_head;
185 stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
194 //////////////////////////////////////////////////////////////////////////////
196 // IMPLEMENTATION SECTION
199 #ifdef STB_RECT_PACK_IMPLEMENTATION
202 #define STBRP_SORT qsort
207 #define STBRP_ASSERT assert
211 #define STBRP__NOTUSED(v) (void)(v)
213 #define STBRP__NOTUSED(v) (void)sizeof(v)
218 STBRP__INIT_skyline = 1
221 STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
223 switch (context->init_mode) {
224 case STBRP__INIT_skyline:
225 STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
226 context->heuristic = heuristic;
233 STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
235 if (allow_out_of_mem)
236 // if it's ok to run out of memory, then don't bother aligning them;
237 // this gives better packing, but may fail due to OOM (even though
238 // the rectangles easily fit). @TODO a smarter approach would be to only
239 // quantize once we've hit OOM, then we could get rid of this parameter.
242 // if it's not ok to run out of memory, then quantize the widths
243 // so that num_nodes is always enough nodes.
245 // I.e. num_nodes * align >= width
246 // align >= width / num_nodes
247 // align = ceil(width/num_nodes)
249 context->align = (context->width + context->num_nodes-1) / context->num_nodes;
253 STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
256 #ifndef STBRP_LARGE_RECTS
257 STBRP_ASSERT(width <= 0xffff && height <= 0xffff);
260 for (i=0; i < num_nodes-1; ++i)
261 nodes[i].next = &nodes[i+1];
262 nodes[i].next = NULL;
263 context->init_mode = STBRP__INIT_skyline;
264 context->heuristic = STBRP_HEURISTIC_Skyline_default;
265 context->free_head = &nodes[0];
266 context->active_head = &context->extra[0];
267 context->width = width;
268 context->height = height;
269 context->num_nodes = num_nodes;
270 stbrp_setup_allow_out_of_mem(context, 0);
272 // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
273 context->extra[0].x = 0;
274 context->extra[0].y = 0;
275 context->extra[0].next = &context->extra[1];
276 context->extra[1].x = (stbrp_coord) width;
277 #ifdef STBRP_LARGE_RECTS
278 context->extra[1].y = (1<<30);
280 context->extra[1].y = 65535;
282 context->extra[1].next = NULL;
285 // find minimum y position if it starts at x1
286 static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
288 stbrp_node *node = first;
290 int min_y, visited_width, waste_area;
294 STBRP_ASSERT(first->x <= x0);
297 // skip in case we're past the node
298 while (node->next->x <= x0)
301 STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
304 STBRP_ASSERT(node->x <= x0);
309 while (node->x < x1) {
310 if (node->y > min_y) {
311 // raise min_y higher.
312 // we've accounted for all waste up to min_y,
313 // but we'll now add more waste for everything we've visted
314 waste_area += visited_width * (node->y - min_y);
316 // the first time through, visited_width might be reduced
318 visited_width += node->next->x - x0;
320 visited_width += node->next->x - node->x;
323 int under_width = node->next->x - node->x;
324 if (under_width + visited_width > width)
325 under_width = width - visited_width;
326 waste_area += under_width * (min_y - node->y);
327 visited_width += under_width;
332 *pwaste = waste_area;
339 stbrp_node **prev_link;
342 static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
344 int best_waste = (1<<30), best_x, best_y = (1 << 30);
345 stbrp__findresult fr;
346 stbrp_node **prev, *node, *tail, **best = NULL;
348 // align to multiple of c->align
349 width = (width + c->align - 1);
350 width -= width % c->align;
351 STBRP_ASSERT(width % c->align == 0);
353 // if it can't possibly fit, bail immediately
354 if (width > c->width || height > c->height) {
360 node = c->active_head;
361 prev = &c->active_head;
362 while (node->x + width <= c->width) {
364 y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
365 if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
373 if (y + height <= c->height) {
374 // can only use it if it first vertically
375 if (y < best_y || (y == best_y && waste < best_waste)) {
386 best_x = (best == NULL) ? 0 : (*best)->x;
388 // if doing best-fit (BF), we also have to try aligning right edge to each node position
392 // ____________________
393 // |____________________|
401 // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
403 // This makes BF take about 2x the time
405 if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
406 tail = c->active_head;
407 node = c->active_head;
408 prev = &c->active_head;
409 // find first node that's admissible
410 while (tail->x < width)
413 int xpos = tail->x - width;
415 STBRP_ASSERT(xpos >= 0);
416 // find the left position that matches this
417 while (node->next->x <= xpos) {
421 STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
422 y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
423 if (y + height <= c->height) {
425 if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
427 STBRP_ASSERT(y <= best_y);
444 static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
446 // find best position according to heuristic
447 stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
448 stbrp_node *node, *cur;
452 // 2. the best node doesn't fit (we don't always check this)
453 // 3. we're out of memory
454 if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
455 res.prev_link = NULL;
459 // on success, create new node
460 node = context->free_head;
461 node->x = (stbrp_coord) res.x;
462 node->y = (stbrp_coord) (res.y + height);
464 context->free_head = node->next;
466 // insert the new node into the right starting point, and
467 // let 'cur' point to the remaining nodes needing to be
470 cur = *res.prev_link;
471 if (cur->x < res.x) {
472 // preserve the existing one, so start testing with the next one
473 stbrp_node *next = cur->next;
477 *res.prev_link = node;
480 // from here, traverse cur and free the nodes, until we get to one
481 // that shouldn't be freed
482 while (cur->next && cur->next->x <= res.x + width) {
483 stbrp_node *next = cur->next;
484 // move the current node to the free list
485 cur->next = context->free_head;
486 context->free_head = cur;
490 // stitch the list back in
493 if (cur->x < res.x + width)
494 cur->x = (stbrp_coord) (res.x + width);
497 cur = context->active_head;
498 while (cur->x < context->width) {
499 STBRP_ASSERT(cur->x < cur->next->x);
502 STBRP_ASSERT(cur->next == NULL);
506 cur = context->active_head;
511 cur = context->free_head;
516 STBRP_ASSERT(count == context->num_nodes+2);
523 static int rect_height_compare(const void *a, const void *b)
525 const stbrp_rect *p = (const stbrp_rect *) a;
526 const stbrp_rect *q = (const stbrp_rect *) b;
531 return (p->w > q->w) ? -1 : (p->w < q->w);
534 static int rect_original_order(const void *a, const void *b)
536 const stbrp_rect *p = (const stbrp_rect *) a;
537 const stbrp_rect *q = (const stbrp_rect *) b;
538 return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
541 #ifdef STBRP_LARGE_RECTS
542 #define STBRP__MAXVAL 0xffffffff
544 #define STBRP__MAXVAL 0xffff
547 STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
549 int i, all_rects_packed = 1;
551 // we use the 'was_packed' field internally to allow sorting/unsorting
552 for (i=0; i < num_rects; ++i) {
553 rects[i].was_packed = i;
556 // sort according to heuristic
557 STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
559 for (i=0; i < num_rects; ++i) {
560 if (rects[i].w == 0 || rects[i].h == 0) {
561 rects[i].x = rects[i].y = 0; // empty rect needs no space
563 stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
565 rects[i].x = (stbrp_coord) fr.x;
566 rects[i].y = (stbrp_coord) fr.y;
568 rects[i].x = rects[i].y = STBRP__MAXVAL;
574 STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
576 // set was_packed flags and all_rects_packed status
577 for (i=0; i < num_rects; ++i) {
578 rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
579 if (!rects[i].was_packed)
580 all_rects_packed = 0;
583 // return the all_rects_packed status
584 return all_rects_packed;
589 ------------------------------------------------------------------------------
590 This software is available under 2 licenses -- choose whichever you prefer.
591 ------------------------------------------------------------------------------
592 ALTERNATIVE A - MIT License
593 Copyright (c) 2017 Sean Barrett
594 Permission is hereby granted, free of charge, to any person obtaining a copy of
595 this software and associated documentation files (the "Software"), to deal in
596 the Software without restriction, including without limitation the rights to
597 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
598 of the Software, and to permit persons to whom the Software is furnished to do
599 so, subject to the following conditions:
600 The above copyright notice and this permission notice shall be included in all
601 copies or substantial portions of the Software.
602 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
603 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
604 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
605 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
606 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
607 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
609 ------------------------------------------------------------------------------
610 ALTERNATIVE B - Public Domain (www.unlicense.org)
611 This is free and unencumbered software released into the public domain.
612 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
613 software, either in source code form or as a compiled binary, for any purpose,
614 commercial or non-commercial, and by any means.
615 In jurisdictions that recognize copyright laws, the author or authors of this
616 software dedicate any and all copyright interest in the software to the public
617 domain. We make this dedication for the benefit of the public at large and to
618 the detriment of our heirs and successors. We intend this dedication to be an
619 overt act of relinquishment in perpetuity of all present and future rights to
620 this software under copyright law.
621 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
622 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
623 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
624 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
625 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
626 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
627 ------------------------------------------------------------------------------