首页 > 解决方案 > 即使 glBufferData 中的数据发生变化,点位置也不会改变

问题描述

代码:

import glfw
import numpy as np
from OpenGL.GL import *

def main():
    if not glfw.init():
        raise RuntimeError('Can not initialize glfw library')
    window = glfw.create_window(500, 500, 'Demo', None, None)
    if not window:
        glfw.terminate()
        raise RuntimeError('Can not create glfw window')
    glfw.make_context_current(window)

    glClearColor(0, 0, 0, 1)
    glColor(1, 0, 0, 1)
    glPointSize(10.0)

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)

    # The result of following two lines are looks the same
    # glBufferData(GL_ARRAY_BUFFER, np.array([0, 0, 0], dtype='float32'), GL_STATIC_DRAW)
    glBufferData(GL_ARRAY_BUFFER, np.array([999999999, 999999999, 999999999], dtype='float32'), GL_STATIC_DRAW)

    while not glfw.window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT)

        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0)
        glDrawArrays(GL_POINTS, 0, 1)
        glDisableVertexAttribArray(0)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()

if __name__ == "__main__":
    main()

我正在学习 OpenGL,并且正在尝试按照此处的教程进行操作。但是,我发现即使更改“glBufferData”中的数据,该点的位置也不会改变。

我不知道这是怎么发生的。函数 glBufferData 不起作用吗?或者,也许我犯了一些低级错误。

标签: pythonopenglpyopengl

解决方案


如果绑定了命名缓冲区对象,则第 6 个参数glVertexAttribPointer被视为缓冲区对象数据存储中的字节偏移量。但是参数的类型是c_void_p.

因此,如果偏移量为 0,则第 6 个参数可以是Nonec_void_p(0)否则必须将偏移量强制转换为c_void_p(0)

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0)

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)

最小的例子:

import glfw
import numpy as np
from OpenGL.GL import *

def main():
    if not glfw.init():
        raise RuntimeError('Can not initialize glfw library')
    window = glfw.create_window(500, 500, 'Demo', None, None)
    if not window:
        glfw.terminate()
        raise RuntimeError('Can not create glfw window')
    glfw.make_context_current(window)

    glClearColor(0, 0, 0, 1)
    glColor(1, 0, 0, 1)
    glPointSize(10.0)

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, np.array([0.2, -0.2, 0, -0.2, -0.2, 0, 0, 0.2, 0], dtype='float32'), GL_STATIC_DRAW)

    while not glfw.window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT)

        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glDrawArrays(GL_POINTS, 0, 3)
        glDisableVertexAttribArray(0)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()

if __name__ == "__main__":
    main()

推荐阅读