LWJGL代码生成黑屏

时间:2012-02-01 00:15:50

标签: java opengl glsl lwjgl

我一直试图弄清楚如何移植these tutorials的第2章。

代码只生成黑屏,我无法弄清楚原因。没有产生错误。

package modern.opengl;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.GL_BGR;
import static org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import org.lwjgl.util.Timer;

public class Lesson01 {

    public static final Logger logger = Logger.getLogger(Lesson01.class.getName());

    static {
        try {
            logger.addHandler(new FileHandler("errors.log", true));
        } catch (IOException ex) {
            logger.log(Level.WARNING, ex.toString(), ex);
        }
    }
    private int displayWidth;
    private int displayHeight;
    private String displayTitle;
    private int vertexBuffer;
    private int elementBuffer;
    private int texture0;
    private int texture1;
    private int program;
    private int uniformFadeFactor;
    private int uniformTexture0;
    private int uniformTexture1;
    private int attributePosition;
    private float fadeFactor;
    private Timer timer;

    public static void main(String[] args) {
        Lesson01 lesson01 = null;
        try {
            lesson01 = new Lesson01();
            lesson01.setup();
            lesson01.run();
        } catch (Exception ex) {
            logger.log(Level.SEVERE, ex.toString(), ex);
        } finally {
            if (lesson01 != null) {
                lesson01.teardown();
            }
        }
    }

    public Lesson01() {
        timer = new Timer();
        timer.resume();
        displayWidth = 400;
        displayHeight = 300;
        displayTitle = "Lesson 01";
    }

    public void makeResources() throws Exception {
        float[] vertexBufferDataArray = {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f};
        FloatBuffer vertexBufferData = ByteBuffer.allocateDirect(vertexBufferDataArray.length * 4).asFloatBuffer();
        vertexBufferData.put(vertexBufferDataArray);
        vertexBufferData.rewind();
        vertexBuffer = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
        glBufferData(GL_ARRAY_BUFFER, vertexBufferData, GL_STATIC_DRAW);

        short[] elementBufferDataArray = {0, 1, 2, 3};
        ShortBuffer elementBufferData = ByteBuffer.allocateDirect(elementBufferDataArray.length * 2).asShortBuffer();
        elementBufferData.put(elementBufferDataArray);
        elementBufferData.rewind();
        elementBuffer = glGenBuffers();
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementBufferData, GL_STATIC_DRAW);

        texture0 = makeTexture("hello1.png");
        texture1 = makeTexture("hello2.png");
        if (texture0 == 0 || texture1 == 0) {
            throw new Exception("Failed to allocate textures!");
        }

        String vertexShaderSource =
                "#version 110                                     \n"
                + "attribute vec2 position;                       \n"
                + "varying vec2 texcoord;                         \n"
                + "void main()                                    \n"
                + "{                                              \n"
                + "gl_Position = vec4(position, 0.0, 1.0);        \n"
                + "texcoord = position * vec2(0.5) + vec2(0.5);   \n"
                + "}                                              \n";
        int vertexShader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexShader, vertexShaderSource);
        glCompileShader(vertexShader);
        if (glGetShader(vertexShader, GL_COMPILE_STATUS) == 0) {
            logger.log(Level.SEVERE, glGetShaderInfoLog(vertexShader, 10240));
            throw new Exception("Failed to compile vertex shader!");
        }

        String fragmentShaderSource =
                "#version 110                                 \n"
                + "uniform float fade_factor;                 \n"
                + "uniform sampler2D textures[2];             \n"
                + "varying vec2 texcoord;                     \n"
                + "void main()                                \n"
                + "{                                          \n"
                + "    gl_FragColor = mix(                    \n"
                + "        texture2D(textures[0], texcoord),  \n"
                + "        texture2D(textures[1], texcoord),  \n"
                + "        fade_factor                        \n"
                + "    );                                     \n"
                + "}                                          \n";
        int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragmentShader, fragmentShaderSource);
        glCompileShader(fragmentShader);
        if (glGetShader(fragmentShader, GL_COMPILE_STATUS) == 0) {
            logger.log(Level.SEVERE, glGetShaderInfoLog(fragmentShader, 10240));
            throw new Exception("Failed to compule vertex shader!");
        }

        program = glCreateProgram();
        glAttachShader(program, vertexShader);
        glAttachShader(program, fragmentShader);
        glLinkProgram(program);
        if (glGetProgram(program, GL_LINK_STATUS) == 0) {
            logger.log(Level.SEVERE, glGetProgramInfoLog(program, 10240));
            throw new Exception("Failed to link shader program.");
        }

        uniformFadeFactor = glGetUniformLocation(program, "fade_factor");
        uniformTexture0 = glGetUniformLocation(program, "textures[0]");
        uniformTexture1 = glGetUniformLocation(program, "textures[1]");
        attributePosition = glGetAttribLocation(program, "position");
    }

    public void setup() throws LWJGLException, Exception {
        Display.setDisplayMode(new DisplayMode(displayWidth, displayHeight));
        Display.setFullscreen(false);
        Display.setTitle(displayTitle);
        Display.create();
        Keyboard.create();
        Mouse.create();
        makeResources();
    }

    public void teardown() {
        Mouse.destroy();
        Keyboard.destroy();
        Display.destroy();
    }

    public void run() {
        while (!Display.isCloseRequested()) {
            Timer.tick();
            if (Display.isVisible()) {
                fadeFactor = (float) (Math.sin(timer.getTime()) * 0.5 + 0.5);
                render();
            } else {
                if (Display.isDirty()) {
                    render();
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    // Pass
                }
            }
            Display.update();
            Display.sync(60);
        }
    }

    public void render() {
        glUseProgram(program);
        glUniform1f(uniformFadeFactor, fadeFactor);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture0);
        glUniform1i(uniformTexture0, 0);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture1);
        glUniform1i(uniformTexture1, 1);

        glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
        glVertexAttribPointer(attributePosition, 2, GL_FLOAT, false, 8, 0);
        glEnableVertexAttribArray(attributePosition);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
        glDrawElements(GL_TRIANGLE_STRIP, 4, GL_SHORT, 0);
        glDisableVertexAttribArray(attributePosition);
    }

    public static int makeTexture(String filename) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(new File(filename));
        byte[] textureBufferArray = ((DataBufferByte) (bufferedImage.getRaster().getDataBuffer())).getData();
        ByteBuffer textureBuffer = ByteBuffer.allocateDirect(textureBufferArray.length);
        textureBuffer.put(textureBufferArray);
        textureBuffer.rewind();
        int textureId = glGenTextures();
        glBindTexture(GL_TEXTURE_2D, textureId);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexImage2D(
            GL_TEXTURE_2D, 
            0, 
            GL_RGB8, 
            bufferedImage.getWidth(), 
            bufferedImage.getHeight(), 
            0, 
            GL_BGR, 
            GL_UNSIGNED_BYTE, 
            textureBuffer
        );
        return textureId;
    }
}

1 个答案:

答案 0 :(得分:0)

我猜你已经找到了。 添加选项-Dorg.lwjgl.util.Debug = true 我尝试了同样的事情,我认为错误就行了 glDrawElements(GL_TRIANGLE_STRIP,4,GL_SHORT,0); 从规范http://www.opengl.org/sdk/docs/man/xhtml/glDrawElements.xml,类型不能是GL_SHORT。