MaxRectsBinPack

Description
Author : Jukka Jylänki's ( http://clb.demon.fi/projects/more-rectangle-bin-packing )

A shortcoming of the GUILLOTINE data structure is that the split planes fragment the free area of the bin into disjoint rectangles, and new placements cannot straddle these split lines. The MAXRECTS data structure removes this limitation by tracking all the maximal rectangles of the free area remaining in the bin.

The maximal rectangles will not be disjoint, so extra care is needed to maintain consistency of the data structure when placing new rectangles. In the paper, I argue that the number of maximal rectangles in a rectilinear polygon is at most 2n^2, which gives a worst case O(n^5) time complexity for the whole algorithm. This holds if the rectangles were placed arbitrarily, but since we are placing the rectangles as conservatively as possible, the number of maximal rectangles is far less. In practice, I have observed that the number of maximal rectangles is strictly sublinear, which lends to an average-case n^3 algorithm.

The MAXRECTS data structure can be used to implement two interesting heuristics:

1) The Contact Point heuristics. In this rule, the new rectangle is placed to a position where its edge touches the edges of previously placed rectangles as much as possible.

2) The Bottom Left heuristics. This rule effectively implements the commonly cited Tetris method for rectangle packing: Each rectangle is placed to a position (possibly rotating it) where its top side lies as low as possible.

Both of these variants perform very well. For the example input, the MAXRECTS-BL-BNF variant achieved an occupancy rate of 90.92%, and the MAXRECTS-CP-BNF variant got an occupancy rate of 93.35%. However, the best performance was given by the MAXRECTS-BSSF-BNF algorithm. The occupancy rate in the example was 94.06%.

Note : this method cannot be used for building atlases if they require mip-mapping due to it not currently supporting padding (this may be added in the near future). In that case, see nVidia Texture Atlas Tools. In fact, remember to disable the automatic mip chain generation whenever you're building atlases of this type.

Edit : Modified the code so you can turn off rotations.