1

我最近决定开始学习 OpenGL,并给自己买了一本关于 OpenGL Core 3.3 的书。这本书通常是关于 C++ 的。

所以,经过一番寻找,我找到了一个我更擅长的语言库,它提供了几乎相同的功能:lwjgl

我按照书上的步骤将 C++ 语法翻译成 java 语法,直到它实际绘制一些东西。

在那里,无论我对代码进行什么更改,JVM 都一直在崩溃。在做了一些调试之后,我发现当我调用glVertexAttribPointeror时 JVM 崩溃了glDrawArrays

我对 OpenGL 很陌生,我假设这个问题对于更有经验的人来说听起来很愚蠢,但是:我需要对这段代码进行哪些更改?

        

        float[] vertices = {
                -0.5f, -0.5f, -0.0f,    
                0.5f, 0.5f, 0.0f,
                0.0f,0.5f,0.0f
        };
        FloatBuffer b = BufferUtils.createFloatBuffer(9);
        b.put(vertices);
        int VBO = glGenBuffers();
        int VAO = glGenVertexArrays();
        log.info("VBO:" + VBO + "VAO: " + VAO);
        // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
        glBindVertexArray(VAO);

            
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 12,  0);
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
        glBindVertexArray(0);       

            

        // Run the rendering loop until the user has attempted to close
        // the window or has pressed the ESCAPE key.
        while (!glfwWindowShouldClose(window))
            {
                // input
                // -----

                // render
                // ------
                glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
                glClear(GL_COLOR_BUFFER_BIT);

                // draw our first triangle
                glUseProgram(shaderProgram);
                glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
                glDrawArrays(GL_TRIANGLES, 0, 3);
                 glBindVertexArray(0); // no need to unbind it every time 
         
                // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
                // -------------------------------------------------------------------------------
                glfwSwapBuffers(window);
                glfwPollEvents();
            }

I would be very thankful for any help i can get, if you need more info/ need to see more of my code please let me know. Thanks in advance

4

1 回答 1

2

You have to bind the vertex buffer object to the target GL_ARRAY_BUFFER, before specifying the vertex attribute:

glBindBuffer(GL_ARRAY_BUFFER, VBO); 
glVertexAttribPointer(0, 3, GL_FLOAT, false, 12,  0);

When glVertexAttribPointer is called, the buffer object currently bound to the ARRAY_BUFFER target is associated to the attribute (index) and a reference to the buffer object is stored in the state vector of the Vertex Array Object.

于 2020-10-19T11:49:44.223 回答