Code: Select all
{
// SortByZ.jsx
//version 4 - by Christopher R. Green
// This script reorders layers in the active comp, sorted by Z Position. C'est RAPIDE!
//NOTE: It always moves locked layers*
//NOTE: It sorts the layers according to their z positions at FIRST FRAME OF COMP**
//NOTE: It ignores expressions***
var proj = app.project;
var undoStr = "Sort Layers By Z Position";
function compareNums(a, b) {return a - b;}
function sortByZ(comp_layers) {
zz = new Array;
//collect all the z positions into an array:
for (o = 1; o <= comp_layers.length; o++) {
//**value at time zero
//***false means ignore expression
zz[zz.length] = comp_layers[o].property("Position").valueAtTime(0, false)[2];
}
//sort those z positions using built-in javascript 1.1 sort method (compareNums function makes sorting numerical)
zz = zz.sort(compareNums);
allZs = zz.length;
for (n = 0;n < allZs;n++) {
clearOutput();
writeLn("Positions sorted ...");
write("Finding & moving layer " + n + " of " + allZs);
foundOne = false;
itsLocked = false;
thisZ = zz[n];
// r is always one ahead of n because the array's first element is zero,
// but the layers object's first element is one;
r=(n+1);
// we increment r below because we need to ignore previous layers,
// shorten the list on every pass
//now move layers with matching Z positions to top, in order of sorted array,
while( !foundOne ) {
if (thisZ == comp_layers[r].property("Position").valueAtTime(0, false)[2]) {
foundOne = true;
if (comp_layers[r].locked) {
itsLocked = true;//*
comp_layers[r].locked = false;//* unlocks locked layer
}
if (n == 0) {
comp_layers[r].moveToBeginning();
}else{
comp_layers[r].moveAfter(comp_layers[n]);
}
if (itsLocked) {comp_layers[n+1].locked = true;}//* re-locks layer
}else{
r=(r+1);
//just a safeguard in case, for some bizarre reason, no match is found between thisZ and all layers' z positions
if (r > allZs) {
foundOne=true;
}
}
}
}
clearOutput();
}//function sortByZ
if(proj){
var activeItem = app.project.activeItem;
if (activeItem != null && (activeItem instanceof CompItem)){
app.beginUndoGroup(undoStr);
var activeCompLayers = activeItem.layers;
sortByZ(activeCompLayers);
app.endUndoGroup();
clearOutput();
write("Sorting Complete.");
} else {
alert("Please select an active comp to use this script");
}
} else {
alert("Please open a project first to use this script.");
}
}