Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
GameNoodle/src/game/graphics/Texture.java
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
61 lines (49 sloc)
1.61 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package game.graphics; | |
import static org.lwjgl.opengl.GL11.*; | |
import java.awt.image.BufferedImage; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import javax.imageio.ImageIO; | |
import game.utils.BufferUtils; | |
public class Texture { | |
private int width, height; | |
private int texture; | |
public Texture(String path) { | |
texture = load(path); | |
} | |
// Loads the image at the given path and binds the texture to the target | |
private int load(String path) { | |
int[] pixels = null; | |
try { | |
BufferedImage image = ImageIO.read(new FileInputStream(path)); | |
width = image.getWidth(); | |
height = image.getHeight(); | |
pixels = new int[width * height]; | |
image.getRGB(0, 0, width, height, pixels, 0, width); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
int[] data = new int[width * height]; | |
//Bit shifting in order to get the correct rgba values | |
for (int i = 0; i < width * height; i++) { | |
int a = (pixels[i] & 0xff000000) >> 24; | |
int r = (pixels[i] & 0xff0000) >> 16; | |
int g = (pixels[i] & 0xff00) >> 8; | |
int b = (pixels[i] & 0xff); | |
data[i] = a << 24 | b << 16 | g << 8 | r; | |
} | |
int result = glGenTextures(); | |
glBindTexture(GL_TEXTURE_2D, result); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); | |
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, BufferUtils.createIntBuffer(data)); | |
glBindTexture(result, 0); | |
return result; | |
} | |
public void bind() { | |
glBindTexture(GL_TEXTURE_2D, texture); | |
} | |
public void unbind() { | |
glBindTexture(GL_TEXTURE_2D, 0); | |
} | |
} |