// stb_rect_pack.h - v1.01 - public domain - rectangle packing1// Sean Barrett 20142//3// Useful for e.g. packing rectangular textures into an atlas.4// Does not do rotation.5//6// Before #including,7//8// #define STB_RECT_PACK_IMPLEMENTATION9//10// in the file that you want to have the implementation.11//12// Not necessarily the awesomest packing method, but better than13// the totally naive one in stb_truetype (which is primarily what14// this is meant to replace).15//16// Has only had a few tests run, may have issues.17//18// More docs to come.19//20// No memory allocations; uses qsort() and assert() from stdlib.21// Can override those by defining STBRP_SORT and STBRP_ASSERT.22//23// This library currently uses the Skyline Bottom-Left algorithm.24//25// Please note: better rectangle packers are welcome! Please26// implement them to the same API, but with a different init27// function.28//29// Credits30//31// Library32// Sean Barrett33// Minor features34// Martins Mozeiko35// github:IntellectualKitty36//37// Bugfixes / warning fixes38// Jeremy Jaussaud39// Fabian Giesen40//41// Version history:42//43// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section44// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles45// 0.99 (2019-02-07) warning fixes46// 0.11 (2017-03-03) return packing success/fail result47// 0.10 (2016-10-25) remove cast-away-const to avoid warnings48// 0.09 (2016-08-27) fix compiler warnings49// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)50// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)51// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort52// 0.05: added STBRP_ASSERT to allow replacing assert53// 0.04: fixed minor bug in STBRP_LARGE_RECTS support54// 0.01: initial release55//56// LICENSE57//58// See end of file for license information.5960//////////////////////////////////////////////////////////////////////////////61//62// INCLUDE SECTION63//6465#ifndef STB_INCLUDE_STB_RECT_PACK_H66#define STB_INCLUDE_STB_RECT_PACK_H6768#define STB_RECT_PACK_VERSION 16970#ifdef STBRP_STATIC71#define STBRP_DEF static72#else73#define STBRP_DEF extern74#endif7576#ifdef __cplusplus77extern "C" {78#endif7980typedef struct stbrp_context stbrp_context;81typedef struct stbrp_node stbrp_node;82typedef struct stbrp_rect stbrp_rect;8384typedef int stbrp_coord;8586#define STBRP__MAXVAL 0x7fffffff87// Mostly for internal use, but this is the maximum supported coordinate value.8889STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);90// Assign packed locations to rectangles. The rectangles are of type91// 'stbrp_rect' defined below, stored in the array 'rects', and there92// are 'num_rects' many of them.93//94// Rectangles which are successfully packed have the 'was_packed' flag95// set to a non-zero value and 'x' and 'y' store the minimum location96// on each axis (i.e. bottom-left in cartesian coordinates, top-left97// if you imagine y increasing downwards). Rectangles which do not fit98// have the 'was_packed' flag set to 0.99//100// You should not try to access the 'rects' array from another thread101// while this function is running, as the function temporarily reorders102// the array while it executes.103//104// To pack into another rectangle, you need to call stbrp_init_target105// again. To continue packing into the same rectangle, you can call106// this function again. Calling this multiple times with multiple rect107// arrays will probably produce worse packing results than calling it108// a single time with the full rectangle array, but the option is109// available.110//111// The function returns 1 if all of the rectangles were successfully112// packed and 0 otherwise.113114struct stbrp_rect115{116// reserved for your use:117int id;118119// input:120stbrp_coord w, h;121122// output:123stbrp_coord x, y;124int was_packed; // non-zero if valid packing125126}; // 16 bytes, nominally127128129STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);130// Initialize a rectangle packer to:131// pack a rectangle that is 'width' by 'height' in dimensions132// using temporary storage provided by the array 'nodes', which is 'num_nodes' long133//134// You must call this function every time you start packing into a new target.135//136// There is no "shutdown" function. The 'nodes' memory must stay valid for137// the following stbrp_pack_rects() call (or calls), but can be freed after138// the call (or calls) finish.139//140// Note: to guarantee best results, either:141// 1. make sure 'num_nodes' >= 'width'142// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'143//144// If you don't do either of the above things, widths will be quantized to multiples145// of small integers to guarantee the algorithm doesn't run out of temporary storage.146//147// If you do #2, then the non-quantized algorithm will be used, but the algorithm148// may run out of temporary storage and be unable to pack some rectangles.149150STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);151// Optionally call this function after init but before doing any packing to152// change the handling of the out-of-temp-memory scenario, described above.153// If you call init again, this will be reset to the default (false).154155156STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);157// Optionally select which packing heuristic the library should use. Different158// heuristics will produce better/worse results for different data sets.159// If you call init again, this will be reset to the default.160161enum162{163STBRP_HEURISTIC_Skyline_default=0,164STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,165STBRP_HEURISTIC_Skyline_BF_sortHeight166};167168169//////////////////////////////////////////////////////////////////////////////170//171// the details of the following structures don't matter to you, but they must172// be visible so you can handle the memory allocations for them173174struct stbrp_node175{176stbrp_coord x,y;177stbrp_node *next;178};179180struct stbrp_context181{182int width;183int height;184int align;185int init_mode;186int heuristic;187int num_nodes;188stbrp_node *active_head;189stbrp_node *free_head;190stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'191};192193#ifdef __cplusplus194}195#endif196197#endif198199//////////////////////////////////////////////////////////////////////////////200//201// IMPLEMENTATION SECTION202//203204#ifdef STB_RECT_PACK_IMPLEMENTATION205#ifndef STBRP_SORT206#include <stdlib.h>207#define STBRP_SORT qsort208#endif209210#ifndef STBRP_ASSERT211#include <assert.h>212#define STBRP_ASSERT assert213#endif214215#ifdef _MSC_VER216#define STBRP__NOTUSED(v) (void)(v)217#define STBRP__CDECL __cdecl218#else219#define STBRP__NOTUSED(v) (void)sizeof(v)220#define STBRP__CDECL221#endif222223enum224{225STBRP__INIT_skyline = 1226};227228STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)229{230switch (context->init_mode) {231case STBRP__INIT_skyline:232STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);233context->heuristic = heuristic;234break;235default:236STBRP_ASSERT(0);237}238}239240STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)241{242if (allow_out_of_mem)243// if it's ok to run out of memory, then don't bother aligning them;244// this gives better packing, but may fail due to OOM (even though245// the rectangles easily fit). @TODO a smarter approach would be to only246// quantize once we've hit OOM, then we could get rid of this parameter.247context->align = 1;248else {249// if it's not ok to run out of memory, then quantize the widths250// so that num_nodes is always enough nodes.251//252// I.e. num_nodes * align >= width253// align >= width / num_nodes254// align = ceil(width/num_nodes)255256context->align = (context->width + context->num_nodes-1) / context->num_nodes;257}258}259260STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)261{262int i;263264for (i=0; i < num_nodes-1; ++i)265nodes[i].next = &nodes[i+1];266nodes[i].next = NULL;267context->init_mode = STBRP__INIT_skyline;268context->heuristic = STBRP_HEURISTIC_Skyline_default;269context->free_head = &nodes[0];270context->active_head = &context->extra[0];271context->width = width;272context->height = height;273context->num_nodes = num_nodes;274stbrp_setup_allow_out_of_mem(context, 0);275276// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)277context->extra[0].x = 0;278context->extra[0].y = 0;279context->extra[0].next = &context->extra[1];280context->extra[1].x = (stbrp_coord) width;281context->extra[1].y = (1<<30);282context->extra[1].next = NULL;283}284285// find minimum y position if it starts at x1286static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)287{288stbrp_node *node = first;289int x1 = x0 + width;290int min_y, visited_width, waste_area;291292STBRP__NOTUSED(c);293294STBRP_ASSERT(first->x <= x0);295296#if 0297// skip in case we're past the node298while (node->next->x <= x0)299++node;300#else301STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency302#endif303304STBRP_ASSERT(node->x <= x0);305306min_y = 0;307waste_area = 0;308visited_width = 0;309while (node->x < x1) {310if (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 visted314waste_area += visited_width * (node->y - min_y);315min_y = node->y;316// the first time through, visited_width might be reduced317if (node->x < x0)318visited_width += node->next->x - x0;319else320visited_width += node->next->x - node->x;321} else {322// add waste area323int under_width = node->next->x - node->x;324if (under_width + visited_width > width)325under_width = width - visited_width;326waste_area += under_width * (min_y - node->y);327visited_width += under_width;328}329node = node->next;330}331332*pwaste = waste_area;333return min_y;334}335336typedef struct337{338int x,y;339stbrp_node **prev_link;340} stbrp__findresult;341342static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)343{344int best_waste = (1<<30), best_x, best_y = (1 << 30);345stbrp__findresult fr;346stbrp_node **prev, *node, *tail, **best = NULL;347348// align to multiple of c->align349width = (width + c->align - 1);350width -= width % c->align;351STBRP_ASSERT(width % c->align == 0);352353// if it can't possibly fit, bail immediately354if (width > c->width || height > c->height) {355fr.prev_link = NULL;356fr.x = fr.y = 0;357return fr;358}359360node = c->active_head;361prev = &c->active_head;362while (node->x + width <= c->width) {363int y,waste;364y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);365if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL366// bottom left367if (y < best_y) {368best_y = y;369best = prev;370}371} else {372// best-fit373if (y + height <= c->height) {374// can only use it if it first vertically375if (y < best_y || (y == best_y && waste < best_waste)) {376best_y = y;377best_waste = waste;378best = prev;379}380}381}382prev = &node->next;383node = node->next;384}385386best_x = (best == NULL) ? 0 : (*best)->x;387388// if doing best-fit (BF), we also have to try aligning right edge to each node position389//390// e.g, if fitting391//392// ____________________393// |____________________|394//395// into396//397// | |398// | ____________|399// |____________|400//401// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned402//403// This makes BF take about 2x the time404405if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {406tail = c->active_head;407node = c->active_head;408prev = &c->active_head;409// find first node that's admissible410while (tail->x < width)411tail = tail->next;412while (tail) {413int xpos = tail->x - width;414int y,waste;415STBRP_ASSERT(xpos >= 0);416// find the left position that matches this417while (node->next->x <= xpos) {418prev = &node->next;419node = node->next;420}421STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);422y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);423if (y + height <= c->height) {424if (y <= best_y) {425if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {426best_x = xpos;427STBRP_ASSERT(y <= best_y);428best_y = y;429best_waste = waste;430best = prev;431}432}433}434tail = tail->next;435}436}437438fr.prev_link = best;439fr.x = best_x;440fr.y = best_y;441return fr;442}443444static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)445{446// find best position according to heuristic447stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);448stbrp_node *node, *cur;449450// bail if:451// 1. it failed452// 2. the best node doesn't fit (we don't always check this)453// 3. we're out of memory454if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {455res.prev_link = NULL;456return res;457}458459// on success, create new node460node = context->free_head;461node->x = (stbrp_coord) res.x;462node->y = (stbrp_coord) (res.y + height);463464context->free_head = node->next;465466// insert the new node into the right starting point, and467// let 'cur' point to the remaining nodes needing to be468// stiched back in469470cur = *res.prev_link;471if (cur->x < res.x) {472// preserve the existing one, so start testing with the next one473stbrp_node *next = cur->next;474cur->next = node;475cur = next;476} else {477*res.prev_link = node;478}479480// from here, traverse cur and free the nodes, until we get to one481// that shouldn't be freed482while (cur->next && cur->next->x <= res.x + width) {483stbrp_node *next = cur->next;484// move the current node to the free list485cur->next = context->free_head;486context->free_head = cur;487cur = next;488}489490// stitch the list back in491node->next = cur;492493if (cur->x < res.x + width)494cur->x = (stbrp_coord) (res.x + width);495496#ifdef _DEBUG497cur = context->active_head;498while (cur->x < context->width) {499STBRP_ASSERT(cur->x < cur->next->x);500cur = cur->next;501}502STBRP_ASSERT(cur->next == NULL);503504{505int count=0;506cur = context->active_head;507while (cur) {508cur = cur->next;509++count;510}511cur = context->free_head;512while (cur) {513cur = cur->next;514++count;515}516STBRP_ASSERT(count == context->num_nodes+2);517}518#endif519520return res;521}522523static int STBRP__CDECL rect_height_compare(const void *a, const void *b)524{525const stbrp_rect *p = (const stbrp_rect *) a;526const stbrp_rect *q = (const stbrp_rect *) b;527if (p->h > q->h)528return -1;529if (p->h < q->h)530return 1;531return (p->w > q->w) ? -1 : (p->w < q->w);532}533534static int STBRP__CDECL rect_original_order(const void *a, const void *b)535{536const stbrp_rect *p = (const stbrp_rect *) a;537const stbrp_rect *q = (const stbrp_rect *) b;538return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);539}540541STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)542{543int i, all_rects_packed = 1;544545// we use the 'was_packed' field internally to allow sorting/unsorting546for (i=0; i < num_rects; ++i) {547rects[i].was_packed = i;548}549550// sort according to heuristic551STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);552553for (i=0; i < num_rects; ++i) {554if (rects[i].w == 0 || rects[i].h == 0) {555rects[i].x = rects[i].y = 0; // empty rect needs no space556} else {557stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);558if (fr.prev_link) {559rects[i].x = (stbrp_coord) fr.x;560rects[i].y = (stbrp_coord) fr.y;561} else {562rects[i].x = rects[i].y = STBRP__MAXVAL;563}564}565}566567// unsort568STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);569570// set was_packed flags and all_rects_packed status571for (i=0; i < num_rects; ++i) {572rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);573if (!rects[i].was_packed)574all_rects_packed = 0;575}576577// return the all_rects_packed status578return all_rects_packed;579}580#endif581582/*583------------------------------------------------------------------------------584This software is available under 2 licenses -- choose whichever you prefer.585------------------------------------------------------------------------------586ALTERNATIVE A - MIT License587Copyright (c) 2017 Sean Barrett588Permission is hereby granted, free of charge, to any person obtaining a copy of589this software and associated documentation files (the "Software"), to deal in590the Software without restriction, including without limitation the rights to591use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies592of the Software, and to permit persons to whom the Software is furnished to do593so, subject to the following conditions:594The above copyright notice and this permission notice shall be included in all595copies or substantial portions of the Software.596THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR597IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,598FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE599AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER600LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,601OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE602SOFTWARE.603------------------------------------------------------------------------------604ALTERNATIVE B - Public Domain (www.unlicense.org)605This is free and unencumbered software released into the public domain.606Anyone is free to copy, modify, publish, use, compile, sell, or distribute this607software, either in source code form or as a compiled binary, for any purpose,608commercial or non-commercial, and by any means.609In jurisdictions that recognize copyright laws, the author or authors of this610software dedicate any and all copyright interest in the software to the public611domain. We make this dedication for the benefit of the public at large and to612the detriment of our heirs and successors. We intend this dedication to be an613overt act of relinquishment in perpetuity of all present and future rights to614this software under copyright law.615THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR616IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,617FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE618AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN619ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION620WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.621------------------------------------------------------------------------------622*/623624625