opengl textures not rendering correctly - java

The problem i am encountering is that i cannot get my texture to render in the correct proportions and for some reason the texture is also repeating itself with a space inbetween.
this is the texture im using(i am trzing to fill the screen with this texture):
When rendered it looks like this(red outline is the entire screen and texture is rendered with a 1 px border):
and here is the code:
package game;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.Timer;
import org.lwjgl.util.glu.GLU;
import org.newdawn.slick.opengl.TextureLoader;
public class WarZone {
private boolean done = false;
private String windowTitle = "War Zone";
private DisplayMode displayMode;
private Timer timer;
private float dt;
public static void main(String[] args) {
new WarZone().run(false);
}
public void run(boolean fullscreen) {
try {
init();
switchToOrtho();
while (!done) {
timer.tick();
update();
render();
Display.update();
}
cleanup();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
private void update() {
// Exit if Escape is pressed or window is closed
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) || Display.isCloseRequested()) {
done = true;
return;
}
}
private boolean render() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear the screen and the depth buffer
GL11.glLoadIdentity(); // Reset the current modelview matrix
int w = displayMode.getWidth();
int h = displayMode.getHeight();
GL11.glColor3f(1, 0, 0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2i(0, 0);
GL11.glVertex2i(w, 0);
GL11.glVertex2i(w, h);
GL11.glVertex2i(0, h);
GL11.glEnd();
//if(true)return false;
GL11.glColor3f(0, 1, 1);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 1);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2i(1, 1);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2i(w - 1, 1);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2i(w - 1, h - 1);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2i(1, h - 1);
GL11.glEnd();
return true; // Rendered correctly
}
public static void switchToOrtho() {
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GL11.glOrtho(0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight(), -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
}
public static void switchToFrustum() {
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
}
private void init() throws Exception {
createWindow();
initGL();
load();
}
private void load() throws FileNotFoundException, IOException {
TextureLoader.getTexture("BMP", new FileInputStream("res/temp/Main_Menu_Play_Button.bmp"), true).getTextureID();
}
private void createWindow() throws Exception {
DisplayMode availibleDisplayModes[] = Display.getAvailableDisplayModes();
for (DisplayMode d:availibleDisplayModes) {
if (d.getWidth() == 640 && d.getHeight() == 480 && d.getBitsPerPixel() == 32) {
displayMode = d;
break;
}
}
Display.setDisplayMode(displayMode);
Display.setTitle(windowTitle);
Display.create();
}
private void initGL() {
GL11.glEnable(GL11.GL_TEXTURE_2D); // Enable texture mapping
GL11.glShadeModel(GL11.GL_SMOOTH); // Enable smooth shading
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black background
GL11.glClearDepth(1.0f); // Depth buffer setup
GL11.glEnable(GL11.GL_DEPTH_TEST); // Enables depth testing
GL11.glDepthFunc(GL11.GL_LEQUAL); // Type of depth testing
GL11.glMatrixMode(GL11.GL_PROJECTION); // Select projection matrix
GL11.glLoadIdentity(); // Reset the projection matrix
// Calculate the aspect ratio of the window
GLU.gluPerspective(45.0f, (float)displayMode.getWidth() / (float)displayMode.getHeight(), 0.1f, 100.0f);
GL11.glMatrixMode(GL11.GL_MODELVIEW);// Select the modelview matrix
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);// Most precise perspective calculations
}
public void requestFinish() {
done = true;
}
private void cleanup() {
Display.destroy();
}
}
I would reallz appreciate it if someone could tell me what i had done wrong.

First, I don't know what TextureLoader or newdawn.slick.opengl are, so there is only limited information I can give about this.
However, it is very possible that your texture loading code does not know how to handle non-power-of-two textures. Which means it is likely padding the texture's size out to the nearest power of two.
More importantly is this:
GL11.glColor3f(0, 1, 1);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 1);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2i(1, 1);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2i(w - 1, 1);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2i(w - 1, h - 1);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2i(1, h - 1);
GL11.glEnd();
This will draw a screen-sized quad (assuming that w and h are screen sizes). This quad maps the entire area of the texture to this quad. OpenGL is only doing what you told it to do: take the texture and map it to the quad.
If you want to draw a texture with pixel accuracy (1:1 texel to pixel), then you need to provide a width and height to the vertex positions that is equal to the texture's size, not the screen size.
Also, you set the color to (0, 1, 1). The default texture environment will multiply the per-vertex color by the texel values fetched from the texture. So you should either set the color to white, or change the texture environment.

OpenGL Doesn't like textures that are not powers of two if I recall. Is your texture a power of 2 for both height and width?
http://www.gamedev.net/topic/466904-opengl-textures-only-power-of-two/

Related

LWJGL Flickering Output When Attempting to Draw Triangle

I've been trying to get into OpenGL with LWJGL and I've run into an issue that I cannot find a solution to. When trying to draw a triangle with the code below, the window opens correctly and begins flashing a shape that isn't necessarily the intended triangle (sometimes it appears briefly, but often there are rectangles in one of the quadrants of the window).
Part of my hesitation is in how OpenGL, by my reading of various posts and docs online, has changed within recent memory to use a less functional and more an object-oriented approach (VBOs and GLSL?) with GL4. Am I correct in this understanding and what are the preferred resources for learning this newer OpenGL for LWJGL?
Thank you in advance!
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;
import java.nio.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
public class Main {
private long windowID;
private float[] tri = {0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f};
public static void main(String[] args) {
new Main().run();
}
public void run() { // Useful for making an instance class as opposed to a static main class?
init();
loop();
glfwFreeCallbacks(windowID);
glfwDestroyWindow(windowID);
glfwTerminate();
glfwSetErrorCallback(null).free();
}
public void init() { // Initializes all LWJGL components
GLFWErrorCallback.createPrint(System.err).set(); // Create error callback route for GL
if (!glfwInit()) { // Init GLFW
throw new IllegalStateException("Failed to initialize GLFW!");
} else {
System.out.println("GLFW successfully initialized!");
}
windowID = glfwCreateWindow(640, 480, "Creating Window", NULL, NULL);
if (windowID == NULL) { // Verify window creation
throw new IllegalStateException("Failed to create window!");
} else {
System.out.println("Successfully created window!");
}
glfwDefaultWindowHints(); // Set window Proporties
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwSetKeyCallback(windowID, (window, key, scancode, action, mods) -> { // Key callback for closing the window
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
glfwSetWindowShouldClose(window, true);
});
try (MemoryStack stack = stackPush()) { // Center the window
IntBuffer pWidth = stack.mallocInt(1);
IntBuffer pHeight = stack.mallocInt(1);
glfwGetWindowSize(windowID, pWidth, pHeight);
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos( // Center the window
windowID,
(vidmode.width() - pWidth.get(0)) / 2,
(vidmode.height() - pHeight.get(0)) / 2
);
}
glfwMakeContextCurrent(windowID); // Make the window current
glfwSwapInterval(0); // Sets the min num of pushed frames before buffers are swaped (Likely prevents horizontal tearing)
glfwShowWindow(windowID); // Unhides the window
}
private void loop() {
GL.createCapabilities();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // The color to clear the buffers with
while(!glfwWindowShouldClose(windowID)) { // If the window is allowed to live
glClear(GL_COLOR_BUFFER_BIT); // The OR is nessesary for some reason
FloatBuffer vBuff = BufferUtils.createFloatBuffer(6);
vBuff.put(tri);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vBuff);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
glfwSwapBuffers(windowID);
glfwPollEvents();
}
}
}
You missed vBuff.flip() after the buffer was crated and filled.
vBuff.put(tri) transfers the the data to the buffer, beginning at the current position (which is the start of the buffer in this case). The buffer position is incremented by the size of the data. So the new buffer position is at the end of the new data.
flip() sets the limit (length) of the buffer to the current position and then the position is set to zero.
Further, it is not necessary to create and fill the buffer continuously in the loop, it would be sufficient to do that once before the loop:
FloatBuffer vBuff = BufferUtils.createFloatBuffer(6);
vBuff.put(tri);
vBuff.flip();
while(!glfwWindowShouldClose(windowID)) {
glClear(GL_COLOR_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vBuff);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
glfwSwapBuffers(windowID);
glfwPollEvents();
}

Weird white border inside of image when it should be transparent

I have this code:
public class Main {
private BoardHandler boardHandler;
Main() {
Display.setTitle(Cons.WINDOW_TITLE);
try {
Display.setDisplayMode(new DisplayMode(Cons.SCREEN_WIDTH, Cons.SCREEN_HEIGHT));
Display.create();
}
catch (LWJGLException e) {
e.printStackTrace();
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, Cons.SCREEN_WIDTH, Cons.SCREEN_HEIGHT, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glClearColor(0, 0, 0, 0);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
boardHandler = new BoardHandler();
while (!Display.isCloseRequested()) {
glClear(GL_COLOR_BUFFER_BIT);
Clock.update();
// game:
boardHandler.update();
Display.update();
Display.sync(60);
}
Display.destroy();
}
public static void main(String[] args) {
new Main();
}
}
I load textures using this function:
public static Texture loadTexture(String path, String fileType) {
Texture tex = null;
InputStream in = ResourceLoader.getResourceAsStream(path);
try {
tex = TextureLoader.getTexture(fileType, in);
}
catch (IOException e) {
e.printStackTrace();
}
return tex;
}
I draw stuff with this function:
public static void drawTile(Texture tex, float x, float y, float radius) {
tex.bind();
glTranslated(x - radius / 2, y - radius / 2, 0);
glBegin(GL_QUADS);
glTexCoord2d(0, 0);
glVertex2d(0, 0);
glTexCoord2d(1, 0);
glVertex2d(radius, 0);
glTexCoord2d(1, 1);
glVertex2d(radius, radius);
glTexCoord2d(0, 1);
glVertex2d(0, radius);
glEnd();
glLoadIdentity();
}
I draw these images:
http://imgur.com/4IZO9CC,gmpPfMM,gF1EeBs,nrv6NRR,OwLgHoM,wfGvAvr,CVEagHD,6ij24M4,pheIjuI#0
And get this as a result:
http://imgur.com/pgExbTE,liEJ01d#0
The X'es are drawn the exact same way as all the other tiles, yet the X'es has these ugly white borders around them. Do note that these white borders are "inside" of the image I'm trying to draw. The blackness inside the white borders is the background showing through like how it's supposed to look.
What is the problem? Why are the white borders present when those parts are transparent in the image? Is there a solution to this?
This is my first attempt at using any 2D/3D engine to draw stuff, I'm just searching for a quick fix if possible.
I fixed it! It seems like openGL (or at least the way I set it up) does not like semi-transparent images for some reason. All I had to do in order for the white borders to disappear was to make every pixel in the image either fully transparent or fully opaque.

OpenGL transparency not working

I am trying to draw my font texture atlas to the screen using LWJGL, but OpenGL instead draws a solid white square.
A working example using my drawing code:
import java.awt.image.*;
import java.io.*;
import java.nio.*;
import javax.imageio.*;
import org.lwjgl.*;
import org.lwjgl.opengl.*;
public class OpenGLImageTest
{
private static int textureID;
public static void main(String[] args) throws Exception
{
Display.setTitle("OpenGL Image Test");
Display.setDisplayMode(new DisplayMode(640, 480));
Display.create();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, 640, 0, 480, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
textureID = bindTextureFile("textures/font.png");
while(!Display.isCloseRequested())
{
Display.sync(60);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glClearColor(0, 0, 0, 1);
GL11.glColor4f(1, 0, 0, 1);
drawFontAtlas(0, 0);
Display.update();
}
Display.destroy();
}
private static void drawFontAtlas(int x, int y)
{
GL11.glPushMatrix();
GL11.glTranslatef(x, y, 0);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2i(0, 0);
GL11.glVertex2i(0, 256);
GL11.glVertex2i(256, 256);
GL11.glVertex2i(256, 0);
GL11.glEnd();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glPopMatrix();
}
private static int bindTextureFile(String file)
{
try
{
BufferedImage image = ImageIO.read(new FileInputStream(file));
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
for(int y = 0; y < image.getWidth(); y++)
{
for(int x = 0; x < image.getHeight(); 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));
buffer.put((byte)((pixel >> 24) & 0xFF));
}
}
buffer.flip();
int textureID = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
return textureID;
}
catch(Exception e)
{
e.printStackTrace();
}
return -1;
}
}
Can anyone tell me what I am doing wrong and how to fix it?
Edit: font.png is white on transparent white. It's the default Minecraft font for testing purposes.
Your problem can be fixed by adding texture coordinates:
{
GL11.glTexCoord2f(0, 1); // added texture coordinate
GL11.glVertex2i(0, 0);
GL11.glTexCoord2f(0, 0); // added texture coordinate
GL11.glVertex2i(0, 256);
GL11.glTexCoord2f(1, 0); // added texture coordinate
GL11.glVertex2i(256, 256);
GL11.glTexCoord2f(1, 1); // added texture coordinate
GL11.glVertex2i(256, 0);
}
I actually used slick-util.jar to load your texture, but it will work with your code just the same... you can find a working example of my code bellow... slick-util.jar can be found here
In order to get actual transparency, you also need to change this line in your code: GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer); and what needs to be changed is GL11.GL_RGB8 into GL11.GL_RGBA
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
public class OpenGLImageTest {
private static Texture tex; //private static int textureID;
public static void main(String[] args) throws Exception {
Display.setTitle("OpenGL Image Test");
Display.setDisplayMode(new DisplayMode(640, 480));
Display.create();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, 640, 0, 480, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
tex = loadTexture("textures/font.png"); //textureID = bindTextureFile("textures/font.png");
while (!Display.isCloseRequested()) {
Display.sync(60);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glClearColor(0, 0, 0, 1);
GL11.glColor4f(1, 1, 1, 1);
drawFontAtlas(0, 0);
Display.update();
}
Display.destroy();
}
private static void drawFontAtlas(int x, int y) {
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glPushMatrix();
GL11.glTranslatef(x, y, 0);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
tex.bind(); //GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2f(0, 1); // added texture coordinate
GL11.glVertex2i(0, 0);
GL11.glTexCoord2f(0, 0); // added texture coordinate
GL11.glVertex2i(0, 256);
GL11.glTexCoord2f(1, 0); // added texture coordinate
GL11.glVertex2i(256, 256);
GL11.glTexCoord2f(1, 1); // added texture coordinate
GL11.glVertex2i(256, 0);
}
GL11.glEnd();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glPopMatrix();
}
public static Texture loadTexture(String texturePath) {
try {
return TextureLoader.getTexture("png", new FileInputStream(new File(texturePath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

gluPerspective() displaying a black screen?

I have a simple application that displays a 3D cube that rotates on all axes, and a camera controlled via mouse that allows you to adjust the angle you're looking at the cube.
The entire application works exactly as I want when I use glOrtho, but once I change it to gluPerspective I only get a black screen.
Here is my method to initialize openGL:
public void initializeOpenGL()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, ((float)WIDTH) / ((float)HEIGHT), 0.01f, 500f);
//glOrtho(0, 640, 480, 0, 600, -1); //displays everything correctly
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
}
And then here is my loop method:
public void begin()
{
float degrees = 0;
Mouse.setGrabbed(false);
while(!Display.isCloseRequested())
{
moveCamera(); //calculates the changes in mouse position
GL11.glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
camera.lookThrough(); //applies the changes
glTranslatef((float)WIDTH/2,(float)HEIGHT/2,10f);
glRotatef(degrees++,1f,1f,1f);
glScalef(100,100,100);
drawQuad();
Display.update();
Display.sync(60);
}
Display.destroy();
System.exit(0);
}
I created an image displaying where the camera looks: http://i.imgur.com/9NVSyqj.png
As you can see the camera looks along the -z axis
-> you should try translating the quad to something like:
glTranslatef(0,0, -10f );
Instead of moving the quad to the middle of the Display you move it half the size of the Display in the nowhere of your Landscape
SHORT VERSION: Gist: https://gist.github.com/Chronove/11da12b2635bfc040981
package me.tutorial;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.gluPerspective;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
/**
* #author Chronove
*/
public class Example {
public static void main(String[] args) throws Exception {
int WIDTH = 600;
int HEIGHT = 400;
// INIT
Display.setDisplayMode(new DisplayMode(WIDTH,HEIGHT));
Display.create();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(float)(WIDTH / HEIGHT),0.1f,500f);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
float degrees = 0;
while(!(Display.isCloseRequested())){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0,0,-10f);
glRotatef(degrees++,0f,0f,1f);
// drawQuad();
{
glBegin(GL_QUADS);
glVertex3f(-1f,-1f,0f);
glVertex3f( 1f,-1f,0f);
glVertex3f( 1f, 1f,0f);
glVertex3f(-1f, 1f,0f);
glEnd();
}
Display.update();
Display.sync(60);
}
Display.destroy();
System.exit(0);
}
}

LWJGL and Slick textures display as black...?

I use eclipse. so in my workspace, under my project, i create a new folder "res" with a subfolder "images" that have all my png's for use as textures. so here is the method im using for loading the textures:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
import org.lwjgl.input.Mouse;
import java.util.Random;
public class TextureDemo
{
public int count = 0;
private static Texture wood;
Random random = new Random();
public TextureDemo()
{
initGL(640, 480, "SLICK TEXTURES");
loadTexture("mozilla");
int x = 100, y = 100, count = 0, width = 0, height = 0, counter = 10;
while(true)
{
count++;
if(count == counter)
{
x--; y--; width++; height++; counter += random.nextInt(50) + 1;
}
render(x, y, width, height);
Display.update();
Display.sync(60);
if(Display.isCloseRequested())
{
Display.destroy();
System.exit(0);
}
}
}
private void initGL(int width, int height, String title)
{
try
{
Display.setDisplayMode(new DisplayMode(width, height));
Display.setTitle(title);
Display.create();
}
catch(LWJGLException e)
{
e.printStackTrace();
Display.destroy();
System.exit(1);
}
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
GL11.glDisable(GL11.GL_COLOR_MATERIAL);
GL11.glLoadIdentity();
GL11.glOrtho(0, width, height, 0, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
public void loadTexture(String key)
{
try
{
wood = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("./res/images/"+key+".png"));
System.out.println("working." + wood.getTextureID());
}
catch(FileNotFoundException e)
{
e.printStackTrace();
Display.destroy();
System.exit(1);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void render(int x, int y, int width, int height)
{
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
System.out.println("working." + wood.getTextureID());
GL11.glBindTexture(GL11.GL_TEXTURE_2D, wood.getTextureID());
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(x, y);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(x + wood.getImageWidth(), y);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(x + wood.getImageWidth(), y + wood.getImageHeight());
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(x, y + wood.getImageHeight());
GL11.glEnd();
GL11.glDisable(GL11.GL_BLEND);
System.out.println(wood.getHeight()+ " " +wood.getWidth());
}
public static void main (String[] args)
{
new TextureDemo();
}
}
WHY WHY WHY are my textures black lol? I really don't understand how my code did this. Is it possible that my computer could have problems that are causing that?
Asking the same question twice won't help. However, you should make sure you first call glBindTexture, before you start glBegin.
I'm sorry, however there are many problems with your code. I would recommend taking a look at some opengl tutorials. The arcsynthesis one is very in-depth.
Your problem is that the texture "wood" is never bound to opengl.
In order to bind your texture to the opengl context you must call
glBindTexture(GL_TEXTURE_2D, id);
before glbegin()
The id is the texture id generated by glGentextures or in your case the slick util method.
Also what is wood? In the first code block it is the texture id but in the second block you are calling 'getHeght()' on type wood. I am confused as to what 'wood' is.
Either way, you need to bind the texture for opengl to use it and I again recommending looking at a few tutorials on the opengl basics.
You haven't enabled textures!
In your initGL method call GL11.glEnable(GL11.GL_TEXTURE_2D).

Categories

Resources