com.redthirddivision.quad.rendering.materials.Texture.java Source code

Java tutorial

Introduction

Here is the source code for com.redthirddivision.quad.rendering.materials.Texture.java

Source

/*   Copyright 2015 Matthew Rogers "BossLetsPlays"
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/
package com.redthirddivision.quad.rendering.materials;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;

import com.redthirddivision.quad.utils.Util;
import com.redthirddivision.quad.utils.managers.TextureManager;

/**
 * <strong>Project:</strong> QuadEngine <br>
 * <strong>File:</strong> Texture.java
 *
 * @author <a href = "http://redthirddivision.com/team/blp"> Matthew Rogers</a>
 */
public class Texture {

    private static Map<String, TextureManager> textures = new HashMap<String, TextureManager>();
    private TextureManager manager;
    private String file;

    public static final String MISSING_TEXTURE_FILE = "missing_texture";
    public static final Texture MISSING_TEXTURE = new Texture(MISSING_TEXTURE_FILE, "assets/system");

    public Texture(String file, String root) {
        this.file = file;
        TextureManager oldTexture = textures.get(file);
        if (oldTexture != null) {
            manager = oldTexture;
            manager.addReference();
        } else {
            this.manager = loadTexture(file, root);
            textures.put(file, manager);
        }
    }

    public Texture(String file) {
        this(file, "assets/textures");
    }

    @Override
    protected void finalize() throws Throwable {
        if (manager.removeReference() && !file.isEmpty())
            textures.remove(file);
        super.finalize();
    }

    public void bind(int samplerSlot) {
        try {
            assert (samplerSlot >= 0 && samplerSlot <= 31);
            GL13.glActiveTexture(GL13.GL_TEXTURE0 + samplerSlot);
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, manager.getID());
        } catch (Exception e) {
            System.err.println("Could not bind texture: " + file);
            System.exit(1);
        }
    }

    public void bind() {
        bind(0);
    }

    public int getID() {
        return manager.getID();
    }

    private TextureManager loadTexture(String path, String root) {

        //        String[] splitArray = path.split("\\.");
        //        String extension = splitArray[splitArray.length - 1];
        File file = null;
        BufferedImage image = null;
        System.out.println("Attempting to load a new texture: <" + root + "/" + path + ">");
        file = new File(root + "/" + path + ".png");
        try {
            image = ImageIO.read(file);
        } catch (IOException e) {
            System.err.println("Could not find texture: <" + root + "/" + path + ">");
            return textures.get(MISSING_TEXTURE_FILE);
        }
        try {
            int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
            ByteBuffer buffer = Util.createByteBuffer(image.getWidth() * image.getHeight() * 4);
            boolean hasAlpha = image.getColorModel().hasAlpha();
            for (int y = 0; y < image.getHeight(); y++) {
                for (int x = 0; x < image.getWidth(); x++) {
                    int pixel = pixels[y * image.getWidth() + x];
                    buffer.put((byte) ((pixel >> 16) & 0xFF));
                    buffer.put((byte) ((pixel >> 8) & 0xFF));
                    buffer.put((byte) ((pixel) & 0xFF));
                    if (hasAlpha)
                        buffer.put((byte) ((pixel >> 24) & 0xFF));
                    else
                        buffer.put((byte) 0xFF);
                }
            }
            buffer.flip();
            System.out.println("Succesfully loaded texture from file: <" + file.getPath() + ">");

            TextureManager result = new TextureManager();
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, result.getID());

            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
            GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
            GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);

            GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0,
                    GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
            return result;
        } catch (Exception e) {
            System.err.println("Could not load texture: <" + path + ".png>");
            System.exit(1);
        }
        return null;

    }

    public String getFile() {
        return file;
    }

}