Anonymous
Почему мой рендеринг openGL не работает, Python OpenGL
Сообщение
Anonymous » 05 янв 2025, 06:57
Я использую код Visual Studio для рендеринга игры с использованием Python, pygame и openGL. Расположение файлов правильное, и объект с текстурой правильно загрузился в блендер, но при экспорте объекта возникло сообщение об ошибке. Могу предоставить любую дополнительную информацию.
Код: Выделить всё
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy
class ObjLoader:
def __init__(self, filename):
self.vertices = []
self.faces = []
self.texture_coords = []
self.normals = []
self.texture_id = None
self.load_model(filename)
def load_model(self, filename):
with open(filename, 'r') as f:
for line in f:
if line.startswith('v '):
#vertex coordinates
coords = line.split()[1:]
self.vertices.append([float(coord) for coord in coords])
elif line.startswith('vt '):
#texture coordinates
coords = line.split()[1:]
self.texture_coords.append([float(coord) for coord in coords])
elif line.startswith('vn '):
#normal vectors
coords = line.split()[1:]
self.normals.append([float(coord) for coord in coords])
elif line.startswith('f '):
#face indices
face = line.split()[1:]
face = [[int(v.split('/')[0]) - 1,
int(v.split('/')[1]) - 1,
int(v.split('/')[2]) - 1] for v in face]
self.faces.append(face)
def load_texture(self, texture_filename):
self.texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.texture_id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
image = pygame.image.load(texture_filename).convert_alpha()
image_width, image_height = image.get_rect().size
image_data = pygame.image.tostring(image, "RGBA", 1)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height,
0, GL_RGBA, GL_UNSIGNED_BYTE, image_data)
glGenerateMipmap(GL_TEXTURE_2D)
def render(self):
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.texture_id)
glBegin(GL_TRIANGLES)
for face in self.faces:
for i in range(3):
vertex_index = face[i][0]
texture_coord_index = face[i][1]
normal_index = face[i][2]
glTexCoord2f(*self.texture_coords[texture_coord_index])
glNormal3f(*self.normals[normal_index])
glVertex3f(*self.vertices[vertex_index])
glEnd()
if self.texture_id:
glDisable(GL_TEXTURE_2D)
class Board(ObjLoader):
def __init__(self, filename):
super().__init__(filename)
class ShogiWindow:
def __init__(self):
pygame.init()
self.display = (800, 600)
self.screen = pygame.display.set_mode(self.display, DOUBLEBUF|OPENGL)
self.board = Board('object_reasoures/shogiBoard.obj')
self.board.load_texture('photos/shogiDefaultTexture.png')
self.setup_scene()
def setup_scene(self):
gluPerspective(45, (self.display[0]/self.display[1]), 0.1, 45.0)
vertices = numpy.array(self.board.vertices)
x_center = numpy.mean(vertices[:, 0])
y_center = numpy.mean(vertices[:, 1])
z_center = numpy.mean(vertices[:, 2])
gluLookAt(x_center, y_center + 1, -1, # Camera position
x_center, y_center, z_center, # Look at point
0, 1, 0) # Up vector
def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
self.board.render()
pygame.display.flip()
pygame.time.wait(10)
if __name__ == '__main__':
window = ShogiWindow()
window.run()
Я просто ожидал увидеть простое окно, отображенное сверху, но получил неожиданный результат. Введите описание изображения здесь.
Подробнее здесь:
https://stackoverflow.com/questions/793 ... hon-opengl
1736049461
Anonymous
Я использую код Visual Studio для рендеринга игры с использованием Python, pygame и openGL. Расположение файлов правильное, и объект с текстурой правильно загрузился в блендер, но при экспорте объекта возникло сообщение об ошибке. Могу предоставить любую дополнительную информацию. [code]import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * import numpy class ObjLoader: def __init__(self, filename): self.vertices = [] self.faces = [] self.texture_coords = [] self.normals = [] self.texture_id = None self.load_model(filename) def load_model(self, filename): with open(filename, 'r') as f: for line in f: if line.startswith('v '): #vertex coordinates coords = line.split()[1:] self.vertices.append([float(coord) for coord in coords]) elif line.startswith('vt '): #texture coordinates coords = line.split()[1:] self.texture_coords.append([float(coord) for coord in coords]) elif line.startswith('vn '): #normal vectors coords = line.split()[1:] self.normals.append([float(coord) for coord in coords]) elif line.startswith('f '): #face indices face = line.split()[1:] face = [[int(v.split('/')[0]) - 1, int(v.split('/')[1]) - 1, int(v.split('/')[2]) - 1] for v in face] self.faces.append(face) def load_texture(self, texture_filename): self.texture_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.texture_id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = pygame.image.load(texture_filename).convert_alpha() image_width, image_height = image.get_rect().size image_data = pygame.image.tostring(image, "RGBA", 1) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data) glGenerateMipmap(GL_TEXTURE_2D) def render(self): glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.texture_id) glBegin(GL_TRIANGLES) for face in self.faces: for i in range(3): vertex_index = face[i][0] texture_coord_index = face[i][1] normal_index = face[i][2] glTexCoord2f(*self.texture_coords[texture_coord_index]) glNormal3f(*self.normals[normal_index]) glVertex3f(*self.vertices[vertex_index]) glEnd() if self.texture_id: glDisable(GL_TEXTURE_2D) class Board(ObjLoader): def __init__(self, filename): super().__init__(filename) class ShogiWindow: def __init__(self): pygame.init() self.display = (800, 600) self.screen = pygame.display.set_mode(self.display, DOUBLEBUF|OPENGL) self.board = Board('object_reasoures/shogiBoard.obj') self.board.load_texture('photos/shogiDefaultTexture.png') self.setup_scene() def setup_scene(self): gluPerspective(45, (self.display[0]/self.display[1]), 0.1, 45.0) vertices = numpy.array(self.board.vertices) x_center = numpy.mean(vertices[:, 0]) y_center = numpy.mean(vertices[:, 1]) z_center = numpy.mean(vertices[:, 2]) gluLookAt(x_center, y_center + 1, -1, # Camera position x_center, y_center, z_center, # Look at point 0, 1, 0) # Up vector def run(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) self.board.render() pygame.display.flip() pygame.time.wait(10) if __name__ == '__main__': window = ShogiWindow() window.run() [/code] Я просто ожидал увидеть простое окно, отображенное сверху, но получил неожиданный результат. Введите описание изображения здесь. Подробнее здесь: [url]https://stackoverflow.com/questions/79330147/why-is-my-opengl-render-failing-python-opengl[/url]