到目前爲止,我已經創建了一個窗口和一個方法來繪製一個窗口的圖像。但是,當我在我的渲染函數中調用它來繪製屏幕時,它什麼都不做,只是顯示黑屏。爲什麼我的圖像不能在窗口繪製?
這裏是我的代碼:
package io.rkshah;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.imageio.ImageIO;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWVidMode; // again used for primary monitor stuff.
import org.lwjgl.opengl.GL;
public class PixelGame implements Runnable
{
public static final String TITLE = "PixelGame";
private Thread mainThread;
private boolean isRunning = true;
private long window;
private int width = 600, height = 400;
public void start() {
isRunning = true;
mainThread = new Thread(this, TITLE);
mainThread.start();
}
public void init() {
if(glfwInit() != GL_TRUE)
System.err.println("GLFW initialization failed!");
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
window = glfwCreateWindow(width, height, TITLE, NULL, NULL);
if(window == NULL)
System.err.println("Could not create our Window!");
GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, (vidMode.width()/2) - (width/2), (vidMode.height()/2) - (height/2));
glfwMakeContextCurrent(window);
glfwShowWindow(window);
GL.createCapabilities();
}
public void update() {
glfwPollEvents(); // Polls for window events such as closing
}
public void render() {
drawBackgroundLayer();
glfwSwapBuffers(window); // Swaps out our buffers
}
@Override
public void run() {
init();
while(isRunning) {
update();
render();
if(glfwWindowShouldClose(window) == GL_TRUE)
isRunning = false;
}
}
public void drawBackgroundLayer() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("res/bg.png"));
drawImage(img);
} catch(IOException e) {
e.printStackTrace();
}
}
public void drawImage(BufferedImage image) {
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); // 4 bytes per pixel for rgba
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)); // Red component
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component
buffer.put((byte) (pixel & 0xFF)); // Blue component
buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component
}
}
buffer.flip(); // Flip the byte buffer for OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
}
public static void main(String args[]) {
PixelGame pg = new PixelGame();
pg.start();
}
}
我所有的進口工作和形象肯定是有的,否則錯誤將會被拋出。