Click here to Skip to main content
15,885,910 members
Articles / Mobile Apps / Android

Texture Atlas Maker

Rate me:
Please Sign up or sign in to vote.
4.94/5 (16 votes)
1 Apr 2012BSD6 min read 142.2K   7K   55  
A utility to create texture atlases for 2D OpenGL games
/*
Copyright (c) 2012, Ed Welch
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

*    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*    Redistributions in binary form must reproduce the above copyright notice, this list of conditions 
     and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.*;
import java.util.*;

public class AtlasMaker
{
	private String strErr;
	
	public AtlasMaker()
	{
	}

	
	public boolean create(DirNode dirNode, 
			String strOutFile, ArrayList<TexturePiece> listReturn, OptionsDialog optionsDialog)
	{
		strErr = "";
        File dir = new File(dirNode.getFileSpec());
        File[] files = null;
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".png");
            }
        };
        files = dir.listFiles(filter);
        
        int maxWidth = 0;
        int maxHeight = 0;
        int totalPixels = 0;
        int n;
        if (files == null || files.length == 0) return false;
        TextureSize textureSize;
        if (dirNode.getImageFormat() == ImageFormat.PVR)
        {
        	textureSize = new TextureSizeSq(32, 32);
        }
        else
        {
        	textureSize = new TextureSize(32, 32);
        }
        TexturePuzzle texturePuzzle = new TexturePuzzle(textureSize); 
        
    	AtlasImage atlasImage = null;
    	ArrayList<AtlasImage> listImage;
    	listImage = new ArrayList<AtlasImage>();
        try 
        {
            for (n = 0; n < files.length; n++) 
            {
                atlasImage = new AtlasImage();
                if (dirNode.getImageFormat() == ImageFormat.PVR)
                	atlasImage.setBorder(2);
                atlasImage.Load(dirNode.getFileSpec(), files[n].getName());
                atlasImage.CropTransparent(optionsDialog.getAlphaThresh());
                listImage.add(atlasImage);
                if (maxWidth < atlasImage.getWidth()) maxWidth = atlasImage.getWidth();
                if (maxHeight < atlasImage.getHeight()) maxHeight = atlasImage.getHeight();
                totalPixels += atlasImage.getNumPixels();
            }
        } catch (Exception e) 
        {
        	strErr = "error: "+atlasImage.getFileName()+": " +e.toString();
            return false;
        }
    	texturePuzzle.getNextSizeFits(totalPixels, maxWidth, maxHeight);
        TexturePiece[] listTexturePiece;
        // sort by biggest image first
        do
        {
            Collections.sort(listImage, new CompareArea());
            listTexturePiece = treeBinPack(listImage, texturePuzzle);
        	if (listTexturePiece != null) break;
        	texturePuzzle.incTextureSize();
        } while (true);
        for (n = 0; n < listTexturePiece.length; n++) 
        {
        	listTexturePiece[n].createStuff(dirNode, strOutFile, n, optionsDialog);
        	listReturn.add(listTexturePiece[n]);
        }

        return true;
	}
	
	public String getStrErr()
	{
		return strErr;
	}


	private TexturePiece[] treeBinPack(ArrayList<AtlasImage> listImage, TexturePuzzle texturePuzzle)
	{
		TreeNode[] listTreeNode = new TreeNode[texturePuzzle.getNumTextures()];
		TexturePiece[] listTexturePiece = new TexturePiece[texturePuzzle.getNumTextures()];
        for (int n = 0; n < listTreeNode.length; n++) 
        {
        	listTreeNode[n] = new TreeNode(0, 0, 
        			texturePuzzle.getWidth(n), texturePuzzle.getHeight(n), "");
        	listTexturePiece[n] = new TexturePiece(texturePuzzle.getWidth(n), 
        			texturePuzzle.getHeight(n));
        }
		int ixImage, ixTexture;
		boolean added;
		for (ixImage = 0; ixImage < listImage.size(); ixImage++)
		{
			added = false;
			for (ixTexture = 0; ixTexture< listTreeNode.length; ixTexture++)
			{
				if (listTreeNode[ixTexture].add(listImage.get(ixImage))) 
				{
					listTexturePiece[ixTexture].add(listImage.get(ixImage));
					added = true;
					break;
				}
			}
			if (!added) return null;
		} 
		return listTexturePiece;
	}	

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer Astronautz
Spain Spain
After working in the software industry for many years, I've started my own games company that specialises in strategy games for mobile platforms.

Comments and Discussions