如何使用VBO和Pyglet更新数据

时间:2012-04-08 19:14:00

标签: python opengl vbo pyglet

我想用Pyglet创建一个正在改变每一帧的网格。因此我需要经常更新顶点,我认为VBO将是最快的方式(如果我错了,请纠正我)。以下是Points的示例。这是正确的做法吗?我读到glBindBuffer调用的数量应该被最小化,但是在这里它被称为每帧。 GL_DYNAMIC_DRAW也已启用,但如果我将其更改为GL_STATIC_DRAW,它仍然有效。这让我想知道这是否是一个快速计算的正确设置

import pyglet
import numpy as np
from pyglet.gl import *
from ctypes import pointer, sizeof

vbo_id = GLuint()
glGenBuffers(1, pointer(vbo_id))

window = pyglet.window.Window(width=800, height=800)

glClearColor(0.2, 0.4, 0.5, 1.0)

glEnableClientState(GL_VERTEX_ARRAY)

c = 0

def update(dt):
    global c
    c+=1
    data = (GLfloat*4)(*[500+c, 100+c,300+c,200+c])
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
    glBufferData(GL_ARRAY_BUFFER, sizeof(data), 0, GL_DYNAMIC_DRAW)
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data), data)


pyglet.clock.schedule(update)

glPointSize(10)

@window.event
def on_draw():

    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(0, 0, 0)

    glVertexPointer(2, GL_FLOAT, 0, 0)
    glDrawArrays(GL_POINTS, 0, 2)


pyglet.app.run()

1 个答案:

答案 0 :(得分:10)

您无需每次都在更新时调用glBufferData - 创建并填充VBO一次(请参阅setup_initial_points)并仅使用glBufferSubData进行更新。如果您只使用单个VBO,还可以在glBindBuffer中注释掉update()来电(请参阅下面的代码)。 GL_DYNAMIC_DRAW vs GL_STATIC_DRAW在此示例中不会产生很大的影响,因为您只需将极少的数据推送到GPU上。

import pyglet
from pyglet.gl import *
from ctypes import pointer, sizeof

window = pyglet.window.Window(width=800, height=800)

''' update function  '''
c = 0
def update(dt):
    global c
    c+=1
    data = calc_point(c)
    # if there's only on VBO, you can comment out the 'glBindBuffer' call
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data), data)

pyglet.clock.schedule(update)


''' draw function  '''
@window.event
def on_draw():

    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(0, 0, 0)

    glVertexPointer(2, GL_FLOAT, 0, 0)
    glDrawArrays(GL_POINTS, 0, 2)


''' calculate coordinates given counter 'c' '''
def calc_point(c):
    data = (GLfloat*4)(*[500+c, 100+c, 300+c, 200+c])
    return data


''' setup points '''
def setup_initial_points(c):
    vbo_id = GLuint()
    glGenBuffers(1, pointer(vbo_id))

    data = calc_point(c)
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
    glBufferData(GL_ARRAY_BUFFER, sizeof(data), 0, GL_DYNAMIC_DRAW)

    return vbo_id


############################################

vbo_id = setup_initial_points(c)

glClearColor(0.2, 0.4, 0.5, 1.0)
glEnableClientState(GL_VERTEX_ARRAY)

glPointSize(10)
pyglet.app.run()