import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.HashMap;
public class AtlasMaker {
private final static int MAX_IMAGE_SIZE = 4096 * 4;
private final static int DEFAULT_IMAGE_COUNT = 9;
private final static int DEFAULT_IMAGE_SIZE = 32;
private final int imageCount;
private final int imageSize;
private final HashMap<String, Integer> items = new HashMap<>();
private final Graphics2D g2d;
private final BufferedImage image;
private int counter = 0;
public AtlasMaker() {
this(DEFAULT_IMAGE_SIZE, DEFAULT_IMAGE_COUNT);
}
public AtlasMaker(int imageSize) {
this(imageSize, DEFAULT_IMAGE_COUNT);
}
public AtlasMaker(int imageSize, int imageCount) {
if (imageSize > MAX_IMAGE_SIZE) {
throw new Error("Max image size: " + MAX_IMAGE_SIZE);
}
if (imageSize < 2) {
throw new Error("Min image size: 2");
}
if (imageSize < 1) {
throw new Error("Min count size: 1");
}
this.imageSize = imageSize;
this.imageCount = imageCount;
image = new BufferedImage(imageSize * imageCount, imageSize, BufferedImage.TYPE_INT_RGB);
g2d = image.createGraphics();
}
public BufferedImage addImage(String key, Image image) {
if (counter == imageCount) {
throw new Error("Je zaplnený celý atlas");
}
BufferedImage newImage = resize(image, imageSize, imageSize);
items.put(key, counter);
g2d.drawImage(newImage, imageSize * counter++, 0, null);
return newImage;
}
public BufferedImage getSubImage(String key) {
return getSubImage(items.get(key));
}
public BufferedImage getSubImage(int key) {
return image.getSubimage(key * imageSize, 0, imageSize, imageSize);
}
public void renderImage(Graphics2D g2, String key, int x, int y) {
renderImage(g2, items.get(key), x, y, imageSize, imageSize);
}
public void renderImage(Graphics2D g2, String key, int x, int y, int w, int h) {
renderImage(g2, items.get(key), x, y, w, h);
}
public void renderImage(Graphics2D g2, int key, int x, int y, int w, int h) {
g2.drawImage(image, x, y, w, h, key * imageSize, 0, imageSize, imageSize, null);
}
public BufferedImage getImage() {
return image;
}
private static BufferedImage resize(Image img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
}