Archived
0

create Texture

This commit is contained in:
2015-09-18 12:27:16 +03:00
parent f0c24650d2
commit 905bc6e7fc

View File

@@ -0,0 +1,120 @@
package ru.dmitriymx.lwjgl.tools;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
public class Texture {
private static boolean set_blend = false;
private int bind_id;
private BufferedImage image;
private float one_pixel_w, one_pixel_h;
public Texture(BufferedImage bufferedImage) {
bind_id = glGenTextures();
this.image = bufferedImage;
prepare_opengl(bind_id);
prepare_image(image);
prepare_onePixel();
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public void bind() {
Texture.bindTexture(bind_id);
}
public static void bindTexture(int texture_id) {
glBindTexture(GL_TEXTURE_2D, texture_id);
}
public int getBindId() {
return bind_id;
}
public float floatX(int x) {
return x * one_pixel_w;
}
public float floatY(int y) {
return y * one_pixel_h;
}
public void updateTexture() {
bind();
prepare_image(image);
prepare_onePixel();
}
public int getWidth() {
return getImage().getWidth();
}
public int getHeight() {
return getImage().getHeight();
}
public static int singleTexture(BufferedImage bufferedImage) {
int bindId = glGenTextures();
prepare_opengl(bindId);
prepare_image(bufferedImage);
return bindId;
}
public static void Enable() {
glEnable(GL_TEXTURE_2D);
}
public static void Disable() {
glDisable(GL_TEXTURE_2D);
}
public static void setAlpha(boolean alpha) {
if (alpha) {
glEnable(GL_BLEND);
if (!set_blend){
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
set_blend = true;
}
} else {
glDisable(GL_BLEND);
}
}
private static void prepare_opengl(int bindId) {
glBindTexture(GL_TEXTURE_2D, bindId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
private static void prepare_image(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int rgb_array_size = width * height;
IntBuffer imageData = ByteBuffer.allocateDirect(rgb_array_size * 4).order(ByteOrder.nativeOrder()).asIntBuffer();
int[] rgb_array = new int[rgb_array_size];
image.getRGB(0, 0, width, height, rgb_array, 0, width);
imageData.put(rgb_array);
imageData.position(0).limit(rgb_array_size);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA,
GL_UNSIGNED_INT_8_8_8_8_REV, imageData);
}
private void prepare_onePixel() {
one_pixel_w = (100F / image.getWidth()) / 100F;
one_pixel_h = (100F / image.getHeight()) / 100F;
}
}