There are a few similar questions on stackoverflow, but none of them seem to provide a tangible answer that someone without a solid understanding of NP-hard problems and algorithms can understand.
How does one perform 2D bin packing of rectangular objects? In my case, I'm trying to assemble several images into a single image, for use as a spritesheet, using the smallest amount of space. Each image possibly has wildly different bounds, but there is no set bounds to the container.
I was hoping someone with an understanding of bin packing algorithms could explain how this can be achieved programmatically, rather than providing a general overview of the bin packing method.
The two-dimensional bin packing problem (2D-BPP) consists of packing without overlap, a set I of two-dimensional rectangular items into the minimum number of two-dimensional rectangular bins [1–3]. All the bins are identical with width W and height H, and each item i ∈ I has a specific width wi and height hi.
The problem of material requirements planning can be formalized as a bin-packing problem, which can be solved using a mixed-integer linear program (MILP).
The bin packing problem is an optimization problem, in which items of different sizes must be packed into a finite number of bins or containers, each of a fixed given capacity, in a way that minimizes the number of bins used.
Best-fit is an online algorithm for bin packing. Its input is a list of items of different sizes. Its output is a packing - a partition of the items into bins of fixed capacity, such that the sum of sizes of items in each bin is at most the capacity.
I Googled "bin packing code" and this was my first hit: http://codeincomplete.com/posts/2011/5/7/bin_packing/
Here's a summary: build a binary tree. Each branch in the tree contains a sprite. Each leaf node represents available space. Initially the tree has just the root node, which represents all available space. To add a sprite to the tree, search the tree for an unoccupied (leaf) node big enough to hold the sprite. Turn that node from a leaf into a branch by setting the sprite as the node's occupant and giving the node two children. One child represents the remaining space to the right of the sprite; the other represents the remaining space below the sprite and the first child.
The article I linked above explains this much more fully, with diagrams and JavaScript code. It also explains how to dynamically grow the sprite sheet rather than choosing a fixed size in advance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With