Rectangle packing

Started by
2 comments, last by Iftah 17 years, 11 months ago
hi I have lots of small rectangular (vertical) textures and I want to pack them into one big power-of-two texture. I think that to do the optimal packing is NPC problem so Id settle for something decent (not optimal). I've seen it done in AngelCode's bitmap font program - you choose the letters you want and it packs them into single texture, unfortunatly its not open-source. Using google I found lots of unrelated PDF's and one related site - titled packing lightmaps it is a great tutorial but I have some unanswered questions, 1) the tutorial starts from a big square and splits it into rectangles as the small textures come. How do I know what size the big square should be? 2) He indicates in the tutorial that for best results the rectangles should be sorted by size (inserted largest first), but by what dimension should I sort? The tallest may not be the widest. 3) As my textures are mostly vertical oriented (height>width) Im afraid I will have lots of wasted space there... maybe the algorithm should be edited to attempt rotating the rectangles? 4) Do you know of other references/algorithms for this problem? ps. Im not sure if this is the right forum to put this thread in... thanks in advance, Iftah.
Advertisement
Quote:1) the tutorial starts from a big square and splits it into rectangles as the small textures come. How do I know what size the big square should be?
Probably arbitrary; just empirically determined based on the average size of your lightmaps.
Quote:2) He indicates in the tutorial that for best results the rectangles should be sorted by size (inserted largest first), but by what dimension should I sort? The tallest may not be the widest.
I imagine you would want to sort by area rather than one or the other dimension.
Quote:3) As my textures are mostly vertical oriented (height>width) Im afraid I will have lots of wasted space there... maybe the algorithm should be edited to attempt rotating the rectangles?
When looking for a lightmap to fit an available slot, you could try both orientations instead of just the 'default' orientation, and rotate it if it will fit that way.
Quote:4) Do you know of other references/algorithms for this problem?
There's a good discussion in the second Watt & Policarpo book. I think it's basically the same algorithm, although it may go into a bit more detail.

Those are just some observations; I'm not an expert on the topic, and it may be that another algorithm would be more suitable for consistently oriented rectangles. However, you might just try the approach discussed in the article. If you look at his example images there are quite a few rectangles that are longer in one dimension than the other; it may be that it would work fine for your purposes (although the rotating of the textures does add a little complexity).
Strangely enough I actually needed to solve a similar problem in my project (packing elongated lightmaps), so I went ahead and wrote a binpacker this afternoon. Here's an example of the output:



The coverage is quite good (a little too good actually - makes me wonder if I messed up somewhere). The algorithm is similar to the link you posted, and to the Watt & Policarpo text, but I added the option of rotating the rectangles to get them to fit in the working area. This seemed to help with regard to the elongated dimensions.

I'll post the code for the bin packer here. There are no dependencies, so if you'd like to try it it should be easy to do so. If you do, let me know if it works, or if you run into any problems. The code has not been rigorously tested, but the above images suggest that it seems to be working. Here it is:

#ifndef BINPACKER_H#define BINPACKER_H#include <vector>class BinPacker{public:    // The input and output are in terms of vectors of ints to avoid    // dependencies (although I suppose a public member struct could have been    // used). The parameters are:        // rects : An array containing the width and height of each input rect in    // sequence, i.e. [w0][h0][w1][w2]... The IDs for the rects are    // derived from the order in which they appear in the array.        // packs : After packing, the outer array contains the packs (therefore    // the number of packs is packs.size()). Each inner array contains a    // sequence of sets of 4 ints. Each set represents a rectangle in the    // pack. The elements in the set are 1) the rect ID, 2) the x position    // of the rect with respect to the pack, 3) the y position of the rect    // with respect to the pack, and 4) whether the rect was rotated (1) or    // not (0). The widths and heights of the rects are not included, as it's    // assumed they are stored on the caller's side (they were after all the    // input to the function).        // allowRotation : when true (the default value), the packer is allowed    // the option of rotating the rects in the process of trying to fit them    // into the current working area.    void Pack(        const std::vector<int>&          rects,        std::vector< std::vector<int> >& packs,        int                              packSize,        bool                             allowRotation = true    );private:    struct Rect    {        Rect(int size)            : x(0), y(0), w(size), h(size), ID(-1), rotated(false), packed(false)        {            children[0] = -1;            children[1] = -1;        }        Rect(int x, int y, int w, int h, int ID = 1)            : x(x), y(y), w(w), h(h), ID(ID), rotated(false), packed(false)        {            children[0] = -1;            children[1] = -1;        }                int GetArea() const {            return w * h;        }                void Rotate() {            std::swap(w, h);            rotated = !rotated;        }                bool operator<(const Rect& rect) const {            return GetArea() < rect.GetArea();        }        int  x;        int  y;        int  w;        int  h;        int  ID;        int  children[2];        bool rotated;        bool packed;    };    void Clear();    void Fill(int pack, bool allowRotation);    void Split(int pack, int rect);    bool Fits(Rect& rect1, const Rect& rect2, bool allowRotation);    void AddPackToArray(int pack, std::vector<int>& array) const;        bool RectIsValid(int i) const;    bool PackIsValid(int i) const;        int               m_packSize;    int               m_numPacked;    std::vector<Rect> m_rects;    std::vector<Rect> m_packs;    std::vector<int>  m_roots;};#endif // #ifndef BINPACKER_H

#include "BinPacker.hpp"#include <algorithm>// ---------------------------------------------------------------------------void BinPacker::Pack(    const std::vector<int>&          rects,    std::vector< std::vector<int> >& packs,    int                              packSize,    bool                             allowRotation){    assert(!(rects.size() % 2));        Clear();        m_packSize = packSize;    // Add rects to member array, and check to make sure none is too big    for (size_t i = 0; i < rects.size(); i += 2) {        if (rects > m_packSize || rects &gt; m_packSize) {<br>            assert(!<span class="cpp-literal">"All rect dimensions must be &lt;= the pack size"</span>);<br>        }<br>        m_rects.push_back(Rect(<span class="cpp-number">0</span>, <span class="cpp-number">0</span>, rects<span style="font-weight:bold;">, rects, i &gt;&gt; <span class="cpp-number">1</span>));<br>    }<br>    <br>    <span class="cpp-comment">// Sort from greatest to least area</span><br>    std::sort(m_rects.rbegin(), m_rects.rend());<br><br>    <span class="cpp-comment">// Pack</span><br>    <span class="cpp-keyword">while</span> (m_numPacked &lt; (<span class="cpp-keyword">int</span>)m_rects.size()) {<br>        <span class="cpp-keyword">int</span> i = m_packs.size();<br>        m_packs.push_back(Rect(m_packSize));<br>        m_roots.push_back(i);<br>        Fill(i, allowRotation);<br>    }<br>    <br>    <span class="cpp-comment">// Write out</span><br>    packs.resize(m_roots.size());<br>    <span class="cpp-keyword">for</span> (size_t i = <span class="cpp-number">0</span>; i &lt; m_roots.size(); ++i) {<br>        packs<span style="font-weight:bold;">.clear();<br>        AddPackToArray(m_roots<span style="font-weight:bold;">, packs<span style="font-weight:bold;">);<br>    }<br><br>    <span class="cpp-comment">// Check and make sure all rects were packed</span><br>    <span class="cpp-keyword">for</span> (size_t i = <span class="cpp-number">0</span>; i &lt; m_rects.size(); ++i) {<br>        <span class="cpp-keyword">if</span> (!m_rects<span style="font-weight:bold;">.packed) {<br>            assert(!<span class="cpp-literal">"Not all rects were packed"</span>);<br>        }<br>    }<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><span class="cpp-keyword">void</span> BinPacker::Clear()<br>{<br>    m_packSize = <span class="cpp-number">0</span>;<br>    m_numPacked = <span class="cpp-number">0</span>;<br>    m_rects.clear();<br>    m_packs.clear();<br>    m_roots.clear();<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><span class="cpp-keyword">void</span> BinPacker::Fill(<span class="cpp-keyword">int</span> pack, <span class="cpp-keyword">bool</span> allowRotation)<br>{<br>    assert(PackIsValid(pack));<br><br>    <span class="cpp-keyword">int</span> i = pack;<br>    <br>    <span class="cpp-comment">// For each rect</span><br>    <span class="cpp-keyword">for</span> (size_t j = <span class="cpp-number">0</span>; j &lt; m_rects.size(); ++j) {<br>        <span class="cpp-comment">// If it's not already packed</span><br>        <span class="cpp-keyword">if</span> (!m_rects[j].packed) {<br>            <span class="cpp-comment">// If it fits in the current working area</span><br>            <span class="cpp-keyword">if</span> (Fits(m_rects[j], m_packs<span style="font-weight:bold;">, allowRotation)) {<br>                <span class="cpp-comment">// Store in lower-left of working area, split, and recurse</span><br>                ++m_numPacked;<br>                Split(i, j);<br>                Fill(m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">0</span>], allowRotation);<br>                Fill(m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">1</span>], allowRotation);<br>                <span class="cpp-keyword">return</span>;<br>            }<br>        }<br>    }<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><span class="cpp-keyword">void</span> BinPacker::Split(<span class="cpp-keyword">int</span> pack, <span class="cpp-keyword">int</span> rect)<br>{<br>    assert(PackIsValid(pack));<br>    assert(RectIsValid(rect));<br>    <br>    <span class="cpp-keyword">int</span> i = pack;<br>    <span class="cpp-keyword">int</span> j = rect;<br><br>    <span class="cpp-comment">// Split the working area either horizontally or vertically with respect</span><br>    <span class="cpp-comment">// to the rect we're storing, such that we get the largest possible child</span><br>    <span class="cpp-comment">// area.</span><br><br>    Rect left = m_packs<span style="font-weight:bold;">;<br>    Rect right = m_packs<span style="font-weight:bold;">;<br>    Rect bottom = m_packs<span style="font-weight:bold;">;<br>    Rect top = m_packs<span style="font-weight:bold;">;<br><br>    left.y += m_rects[j].h;<br>    left.w = m_rects[j].w;<br>    left.h -= m_rects[j].h;<br>    right.x += m_rects[j].w;<br>    right.w -= m_rects[j].w;<br>    <br>    bottom.x += m_rects[j].w;<br>    bottom.h = m_rects[j].h;<br>    bottom.w -= m_rects[j].w;<br>    top.y += m_rects[j].h;<br>    top.h -= m_rects[j].h;<br>    <br>    <span class="cpp-keyword">int</span> maxLeftRightArea = left.GetArea();<br>    <span class="cpp-keyword">if</span> (right.GetArea() &gt; maxLeftRightArea) {<br>        maxLeftRightArea = right.GetArea();<br>    }<br>    <br>    <span class="cpp-keyword">int</span> maxBottomTopArea = bottom.GetArea();<br>    <span class="cpp-keyword">if</span> (top.GetArea() &gt; maxBottomTopArea) {<br>        maxBottomTopArea = top.GetArea();<br>    }<br><br>    <span class="cpp-keyword">if</span> (maxLeftRightArea &gt; maxBottomTopArea) {<br>        <span class="cpp-keyword">if</span> (left.GetArea() &gt; right.GetArea()) {<br>            m_packs.push_back(left);<br>            m_packs.push_back(right);<br>        } <span class="cpp-keyword">else</span> {<br>            m_packs.push_back(right);<br>            m_packs.push_back(left);<br>        }<br>    } <span class="cpp-keyword">else</span> {<br>        <span class="cpp-keyword">if</span> (bottom.GetArea() &gt; top.GetArea()) {<br>            m_packs.push_back(bottom);<br>            m_packs.push_back(top);<br>        } <span class="cpp-keyword">else</span> {<br>            m_packs.push_back(top);<br>            m_packs.push_back(bottom);<br>        }<br>    }<br>    <br>    <span class="cpp-comment">// This pack area now represents the rect we've just stored, so save the</span><br>    <span class="cpp-comment">// relevant info to it, and assign children.</span><br>    m_packs<span style="font-weight:bold;">.w = m_rects[j].w;<br>    m_packs<span style="font-weight:bold;">.h = m_rects[j].h;<br>    m_packs<span style="font-weight:bold;">.ID = m_rects[j].ID;<br>    m_packs<span style="font-weight:bold;">.rotated = m_rects[j].rotated;<br>    m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">0</span>] = m_packs.size() - <span class="cpp-number">2</span>;<br>    m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">1</span>] = m_packs.size() - <span class="cpp-number">1</span>;<br>    <br>    <span class="cpp-comment">// Done with the rect</span><br>    m_rects[j].packed = <span class="cpp-keyword">true</span>;<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><span class="cpp-keyword">bool</span> BinPacker::Fits(Rect&amp; rect1, <span class="cpp-keyword">const</span> Rect&amp; rect2, <span class="cpp-keyword">bool</span> allowRotation)<br>{<br>    <span class="cpp-comment">// Check to see if rect1 fits in rect2, and rotate rect1 if that will</span><br>    <span class="cpp-comment">// enable it to fit.</span><br><br>    <span class="cpp-keyword">if</span> (rect1.w &lt;= rect2.w &amp;&amp; rect1.h &lt;= rect2.h) {<br>        <span class="cpp-keyword">return</span> <span class="cpp-keyword">true</span>;<br>    } <span class="cpp-keyword">else</span> <span class="cpp-keyword">if</span> (allowRotation &amp;&amp; rect1.h &lt;= rect2.w &amp;&amp; rect1.w &lt;= rect2.h) {<br>        rect1.Rotate();<br>        <span class="cpp-keyword">return</span> <span class="cpp-keyword">true</span>;<br>    } <span class="cpp-keyword">else</span> {<br>        <span class="cpp-keyword">return</span> <span class="cpp-keyword">false</span>;<br>    }<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><span class="cpp-keyword">void</span> BinPacker::AddPackToArray(<span class="cpp-keyword">int</span> pack, std::vector&lt;<span class="cpp-keyword">int</span>&gt;&amp; array) <span class="cpp-keyword">const</span><br>{<br>    assert(PackIsValid(pack));<br>    <br>    <span class="cpp-keyword">int</span> i = pack;<br>    <span class="cpp-keyword">if</span> (m_packs<span style="font-weight:bold;">.ID != -<span class="cpp-number">1</span>) {<br>        array.push_back(m_packs<span style="font-weight:bold;">.ID);<br>        array.push_back(m_packs<span style="font-weight:bold;">.x);<br>        array.push_back(m_packs<span style="font-weight:bold;">.y);<br>        array.push_back(m_packs<span style="font-weight:bold;">.rotated);<br>        <br>        <span class="cpp-keyword">if</span> (m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">0</span>] != -<span class="cpp-number">1</span>) {<br>            AddPackToArray(m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">0</span>], array);<br>        }<br>        <span class="cpp-keyword">if</span> (m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">1</span>] != -<span class="cpp-number">1</span>) {<br>            AddPackToArray(m_packs<span style="font-weight:bold;">.children[<span class="cpp-number">1</span>], array);<br>        }<br>    }<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><span class="cpp-keyword">bool</span> BinPacker::RectIsValid(<span class="cpp-keyword">int</span> i) <span class="cpp-keyword">const</span><br>{<br>    <span class="cpp-keyword">return</span> i &gt;= <span class="cpp-number">0</span> &amp;&amp; i &lt; (<span class="cpp-keyword">int</span>)m_rects.size();<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><span class="cpp-keyword">bool</span> BinPacker::PackIsValid(<span class="cpp-keyword">int</span> i) <span class="cpp-keyword">const</span><br>{<br>    <span class="cpp-keyword">return</span> i &gt;= <span class="cpp-number">0</span> &amp;&amp; i &lt; (<span class="cpp-keyword">int</span>)m_packs.size();<br>}<br><span class="cpp-comment">// —————————————————————————</span><br><br><br></pre></div><!–ENDSCRIPT–> <br><br><!–EDIT–><span class=editedby><!–/EDIT–>[Edited by - jyk on May 12, 2006 12:02:20 AM]<!–EDIT–></span><!–/EDIT–>
thanks alot for your replies!

I wrote the code as the web tutorial instructed and it works very nicely (see images). The vertical orientation doesnt seem to be a problem for the algorithm, but I guess it can be better if it attempts rotations.

I will translate your code (am writing in C#) and test it later today or tomorrow and post the results. Thanks again!

note: the graphics here are copyright to little-fighters2, I am only using them to test my editors and game-engine until I get my own graphics.

unpacked


packed (into 512x512 texture)

and again.. thanks!
Iftah.

This topic is closed to new replies.

Advertisement