Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#target "illustrator"
(function(){
var rect = (function() {
var rect = function(x, y, w, h) {
this.obj = null;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
var r = rect.prototype;
r.set = function(obj) {
this.obj = obj;
this.w = obj.width;
this.h = obj.height;
};
return rect;
})();
var node = (function() {
var node = function(rect) {
this.rect = rect;
this.left = null;
this.right = null;
};
var n = node.prototype;
n.insert = function(r, margin) {
if (this.rect != null) {
if (((r.w + margin) > this.rect.w) || ((r.h + margin) > this.rect.h)) {
return false;
}
r.x = this.rect.x;
r.y = this.rect.y;
var w = r.w + margin;
var h = r.h + margin;
var dw = this.rect.w - w;
var dh = this.rect.h - h;
if (dw > dh) {
this.left = new node(new rect(this.rect.x, this.rect.y + h, w, dh));
this.right = new node(new rect(this.rect.x + w, this.rect.y, dw, this.rect.h));
}
else {
this.left = new node(new rect(this.rect.x + w, this.rect.y, dw, h));
this.right = new node(new rect(this.rect.x, this.rect.y + h, this.rect.w, dh));
}
this.rect = null;
return true;
}
else {
if (this.left.insert(r, margin)) {
return true;
}
return this.right.insert(r, margin);
}
};
return node;
})();
//main
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;
try {
if (app.documents.length > 0 ) {
var objList = [];
for (var i = 0 ; i < app.selection.length ; i++) {
var o = new rect(0, 0, 0, 0);
o.set(app.selection[i]);
objList.push(o);
}
var select = prompt("配置優先ロジックを選択してください\n1:面積, 2:長辺\n3:width, 4:height", "1", "ロジック選択");
if (select == "2") {
objList.sort(
function(a, b) {
var la = a.h > a.w ? a.h : a.w;
var lb = b.h > b.w ? b.h : b.w;
return (lb - la);
}
);
}
else if (select == "3") {
objList.sort(
function(a, b) {
return (b.w - a.w);
}
);
}
else if (select == "4") {
objList.sort(
function(a, b) {
return (b.h - a.h);
}
);
}
else {
objList.sort(
function(a, b) {
return ((b.h * b.w) - (a.h * a.w));
}
);
}
var margin = Number(prompt("Marginを入力してください", "8", "マージン入力"));
var root = new node(new rect(0, 0, 2048, 2048));
for (var j = 0 ; j < objList.length ; j++) {
if (!root.insert(objList[j], margin)) {
$.writeln("insert failed : " + j);
}
}
for (var j = 0 ; j < objList.length ; j++) {
var dx = objList[j].x - objList[j].obj.position[0];
// y軸は上から下に向かってマイナス
var dy = (objList[j].y * -1) - objList[j].obj.position[1];
objList[j].obj.translate(dx, dy);
}
}
else{
throw new Error('ドキュメントが開かれていません。');
}
}
catch(e) {
alert( e.message, "スクリプト警告", true);
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment