【发布时间】:2021-02-10 19:59:15
【问题描述】:
我正在尝试使用 Pygame 创建一个 2D python 游戏。
但我意识到我可以使用 PyOpengl,所以我尝试学习如何使用它。我可以在我的屏幕上用顶点创建一个三角形条带。但是,我想使用索引来渲染这些三角形。在下面的代码中,我尝试渲染一个简单的正方形,其中包含 2 个三角形、一个列表中的 4 个顶点和另一个列表中的索引。不幸的是,我不明白为什么没有出现正方形。我可能对缓冲区、vaos、vbos 甚至 pyopengl 本身的处理有误解。 (我用 cmets 来解释我认为代码行的作用)
import numpy as np
import pygame
from OpenGL.GL import *
vaos = []
vbos = []
pygame.init()
screen = pygame.display.set_mode((512, 512), pygame.OPENGL | pygame.DOUBLEBUF)
pygame.display.set_caption("With OpenGl")
glViewport(0, 0, 512, 512)
# Creating vertices and indices
vertices = [-0.5, 0.5,
-0.5, -0.5,
0.5, -0.5,
0.5, 0.5]
indices = [0, 1, 3,
3, 1, 2]
# Creating VAO and binding it
vaoID = glGenVertexArrays(1)
vaos.append(vaoID)
glBindVertexArray(vaoID)
# Creating VBO for verticices and binding it
verticesID = glGenBuffers(1)
vbos.append(verticesID)
glBindBuffer(GL_ARRAY_BUFFER, verticesID)
# Creating bufferData to store vertices position
verticesBuffer = np.array(vertices, dtype='f')
glBufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW)
glVertexAttribPointer(0, 2, GL_FLOAT, False, 0, None)
glBindBuffer(GL_ARRAY_BUFFER, 0)
# Creating VBO for indices and binding it
indicesID = glGenBuffers(1)
vbos.append(indicesID)
# Creating bufferData to store indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesID)
indicesBuffer = np.array(indices, dtype='uint16')
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW)
# unbind VAO because I finished to use it
glBindVertexArray(0)
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for e in pygame.event.get():
if e.type == pygame.QUIT:
run = False
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_o:
run = False
# Preparing screen
glClear(GL_COLOR_BUFFER_BIT)
glClearColor(1, 0, 0, 1)
# Rendering
# binding VAO
glBindVertexArray(vaoID)
# enabling VertexAttribArray to get vertices
glEnableVertexAttribArray(0)
# draw elements
glDrawElements(GL_TRIANGLES, len(vertices) * 4, GL_UNSIGNED_INT, 0)
# disabling VertexAttribArray and unbind VAO because I finished to use them
glDisableVertexAttribArray(0)
glBindVertexArray(0)
pygame.display.flip()
# Cleanup
for vao in vaos:
glDeleteVertexArrays(1, vao)
for vbo in vbos:
glDeleteBuffers(1, vbo)
pygame.quit()
【问题讨论】:
标签: python opengl pygame pyopengl