final double BORDER_SCALE_FACTOR = 1.1;
double smallX, bigX, smallY, bigY, scaleX, scaleY;
/* Init values */
{
Position pos = motes[0].getInterfaces().getPosition();
smallX = bigX = pos.getXCoordinate();
smallY = bigY = pos.getYCoordinate();
}
/* Extremes */
for (Mote mote : motes) {
Position pos = mote.getInterfaces().getPosition();
smallX = Math.min(smallX, pos.getXCoordinate());
bigX = Math.max(bigX, pos.getXCoordinate());
smallY = Math.min(smallY, pos.getYCoordinate());
bigY = Math.max(bigY, pos.getYCoordinate());
}
/* Scale viewport */
if (smallX == bigX) {
scaleX = 1;
}
else {
scaleX = (bigX - smallX) / (canvas.getWidth());
}
if (smallY == bigY) {
scaleY = 1;
}
else {
scaleY = (bigY - smallY) / (canvas.getHeight());
}
viewportTransform.setToIdentity();
double newZoom = (1.0 / (BORDER_SCALE_FACTOR * Math.max(scaleX, scaleY)));
viewportTransform.setToScale(
newZoom,
newZoom
);
/* Center visible motes */
final double smallXfinal = smallX, bigXfinal = bigX, smallYfinal = smallY, bigYfinal = bigY;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Position viewMid
= transformPixelToPosition(canvas.getWidth() / 2, canvas.getHeight() / 2);
double motesMidX = (smallXfinal + bigXfinal) / 2.0;
double motesMidY = (smallYfinal + bigYfinal) / 2.0;
viewportTransform.translate(
viewMid.getXCoordinate() - motesMidX,
viewMid.getYCoordinate() - motesMidY);
canvas.repaint();
}
});
}