Skip to main content
HWDP
Participating Frequently
November 8, 2018
Question

2d bin packing problem

  • November 8, 2018
  • 1 reply
  • 1413 views

Hello. I found a script https://codeincomplete.com/posts/bin-packing/ for 2d bin packing.I would like to use it in the illustrator It starts correctly. Retrieves the size of the graphic from each layer and adds a new object to the array. However, when the figures (squares) are different sizes, the sort looks ugly

and when all rect are same size

I dont know what im doing wrong. Meaby i should rotare all object to vertical? I dont know. Can somone help or give any tips advice.

Thanks

Packer = function(w, h) {

  this.init(w, h);

};

Packer.prototype = {

  init: function(w, h) {

    this.root = { x: 0, y: 0, w: w, h: h };

  },

  fit: function(blocks) {

    var n, node, block;

    for (n = 0; n < blocks.length; n++) {

      block = blocks;

      if (node = this.findNode(this.root, block.w, block.h))

        block.fit = this.splitNode(node, block.w, block.h);

    }

  },

  findNode: function(root, w, h) {

    if (root.used)

      return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);

    else if ((w <= root.w) && (h <= root.h))

      return root;

    else

      return null;

  },

  splitNode: function(node, w, h) {

    node.used = true;

    node.down  = { x: node.x,     y: node.y + h, w: node.w,     h: node.h - h };

    node.right = { x: node.x + w, y: node.y,     w: node.w - w, h: h          };

    return node;

  }

}

////////USAGE

   var doc = app.activeDocument;

   var myLayers = doc.layers;

  var packer = new Packer(14000, 15000);

  var blocks = [];

 

  for( var i=0;i<myLayers.length;i++){

          

      myLayers.hasSelectedArtwork = true;

    

    

       var sel =  doc.selection[0]; 

        $.writeln(sel.height);

   

var obj = { w: sel.width, h: sel.height ,objSel:sel, name: myLayers.name};

    blocks.push(obj);

  

            myLayers.hasSelectedArtwork = false;

}

blocks.sort(function(a,b) { return (b.h < a.h); }); // sort inputs for best results

  packer.fit(blocks);

  for(var n = 0 ; n < blocks.length ; n++) {

      

    var block = blocks;

    if (block.fit) {

      $.writeln(block.fit.x+"-------"+ block.fit.y+"--------------"+ block.w+"------------"+block.h+block.name);

     block.objSel.position=[block.fit.x,block.fit.y];

     }

  }

This topic has been closed for replies.

1 reply

m1b
Community Expert
Community Expert
October 27, 2021

Hi @HWDP, I know it's late, but I have adapted a bin packing algorithm similar to what you ask for here.

- Mark