我正在尝试画一个基本的立方体;在这一点上,我甚至不打扰透视投影,只是试图在屏幕上得到一些没有崩溃的东西。当我使用以下错误消息调用glDrawElements()
时发生崩溃:
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007fff838fdbdd, pid=683, tid=1811
#
# JRE version: Java(TM) SE Runtime Environment (8.0_51-b16) (build 1.8.0_51-b16)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.51-b03 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C [GLEngine+0x159bdd] gleRunVertexSubmitImmediate+0x42d
...
# The crash happened outside the Java Virtual Machine in native code.
我的立方体顶点和元素存储在文字数组中:
val cubeVertices = Array[Float] (
// Front face
-1.0f, -1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f, 1.0f,
... // Other faces also defined in same manner
)
val cubeElements = Array[Short] (
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // back
8, 9, 10, 8, 10, 11, // top
12, 13, 14, 12, 14, 15, // bottom
16, 17, 18, 16, 18, 19, // right
20, 21, 22, 20, 22, 23 // left
)
我的窗口创建代码如下:
glfwInit()
glfwDefaultWindowHints()
glfwWindowHint(GLFW_VISIBLE, GL_FALSE)
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
val window = glfwCreateWindow(1024, 768, "Hello!", NULL, NULL)
glfwMakeContextCurrent(window)
glfwSwapInterval(1)
glfwShowWindow(window)
GLContext.createFromCurrent()
initDraw()
while (glfwWindowShouldClose(window) == GL_FALSE) {
glfwWaitEvents()
draw()
glfwSwapBuffers(window)
}
initDraw()
定义如下:
val cubeVertexNIOBuffer = createFloatBuffer(cubeVertices.length)
cubeVertexNIOBuffer.put(cubeVertices)
val cubeVertexBuffer = glGenBuffers()
glBindBuffer(GL_ARRAY_BUFFER, cubeVertexBuffer)
glBufferData(GL_ARRAY_BUFFER, cubeVertexNIOBuffer, GL_STATIC_DRAW)
val cubeElementNIOBuffer = createShortBuffer(cubeElements.length)
cubeElementNIOBuffer.put(cubeElements)
val cubeElementBuffer = glGenBuffers()
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cubeElementBuffer)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, cubeElementNIOBuffer, GL_STATIC_DRAW)
cubeVertexArray = glGenVertexArrays()
glBindVertexArray(cubeVertexArray)
glEnableVertexAttribArray(0)
glBindBuffer(GL_ARRAY_BUFFER, cubeVertexBuffer)
glVertexAttribPointer(0, 4, GL_FLOAT, false, 0, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cubeElementBuffer)
... // Shader compilation and linking stuff
最后,draw()
的定义如下:
glClearColor(0.0f, 0.0f, 0.0f, 1.0f)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glUseProgram(shaderProgram)
glBindVertexArray(cubeVertexArray)
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0)
我已经确认glDrawElements()
是罪魁祸首,因为代码会在呼叫被注释掉的时候运行而不会崩溃。我也非常确定着色器代码不应该受到指责,因为调用glUseProgram()
不会产生OpenGL错误。
我还应该注意,定期调用glDrawArrays()
会以同样的方式崩溃。