Packing squares/UVs in Unity

Simon Pasi
2 min readAug 17, 2020

Github: https://github.com/vitefaittt/Square-packing

Result of the packing

Process

This process by blackpawn and Team Hypersomnia handles packing rectangles and squares inside of an area of custom proportions.

Steps:

Basic concept from blackpawn
Process
  • Pick an area of size (x;y). Add a first empty space that consists of the whole area.
  • Try to fit a square inside of this empty space. If this is successful, split the empty space into two parts, along two lines A and B (B splits the space in two, and A splits the remaining part in two, see the basic concept from blackpawn). Then, remove the previous empty space and add these empty spaces instead (add the smaller one first for performance).
  • Repeat until all squares are packed.
  • If some squares couldn’t be packed, increase the available area of size (x;y) and try again.
    If all the squares could be packed, decrease the available area of size (x;y) and try again. If this new attempt fails, keep the previous result (we are trying to find the smallest packing area possible).
  • Trim the remaining space of the packing area.

Remarks

  • The squares should be ordered from bigger to smaller.
  • While increasing the area, you can use the smallest width or height from all the squares as the increment.

Based on https://github.com/TeamHypersomnia/rectpack2D#algorithm and https://blackpawn.com/texts/lightmaps/default.html

--

--