Skip to main content
 首页 » 编程设计

python之如何在已经加载的 OpenGL 场景中添加顶点

2024年11月24日8birdshome

我正在使用 python 通过 OpenGL 和 pyGame 制作魔方应用程序。我可以看到立方体,我想按下一个按钮并加载颜色,但没有显示颜色。 (我单独给每个小立方体上色,但我认为这不重要)。

如果我在绘制立方体顶点的函数中调用为立方体着色的函数(在程序开始时),颜色会完美显示,但如果我按下一个键调用颜色函数(使用 pyGame)当应用程序已经运行时它们不会。

给小立方体上色的函数:

def color_cubie(self): 
    surfaces = ( 
        (0, 1, 2, 3), 
        (4, 5, 6, 7), 
        (0, 3, 7, 4), 
        (1, 2, 6, 5), 
        (2, 3, 7, 6), 
        (0, 1, 5, 4) 
        ) 
    colors = [ 
        (1, 0, 0), (1, 0.5, 0),    
        (0, 1, 0), (0, 0, 1),           
        (1, 1, 1), (1, 1, 0)      
        ] 
 
    #faces 
    glBegin(GL_QUADS) 
    index=0 
    for surface in surfaces: 
        glColor3fv(colors[index]) 
        for vertex  in surface: 
            glVertex3fv(self.verticies[vertex]) 
        index+=1 
    glEnd() 

我调用函数的部分(当我按下键盘上的 c 键时 if 语句为真)。立方体也是一个 3x3x3 numpy 数组,其中填充了立方体对象。

if move == "c": 
    for row in self.cube[2]: 
        for cubie in row: 
            cubie.color_cubie() 

主要/渲染功能:

 
def render(): 
    pygame.init() 
    display = (WIDTH, HEIGHT) 
    screen = pygame.display.set_mode(display, DOUBLEBUF|OPENGL) 
    pygame.display.set_caption("Rubiks Cube") 
 
    glEnable(GL_DEPTH_TEST) 
    glClearColor(1, 1, 1, 1) 
    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) 
    glTranslatef(0.0, 0.0, -7) 
    glLineWidth(10) 
 
    while True:               
        mouse_pos = pygame.mouse.get_rel() 
        glRotatef(1, mouse_pos[1], mouse_pos[0], 0) 
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) 
 
        #create cube object 
        new_cube = Cube() 
        new_cube.show_cube() 
 
        pygame.display.flip() 
        pygame.time.wait(10) 
 
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT: 
                pygame.quit() 
                quit() 
            if event.type == pygame.KEYDOWN: 
                if event.key == K_c: 
                    new_cube.rotate_cube("c") 
 

当我阅读时,我必须重新绘制屏幕才能看到彩色立方体。但是 glClear(...) 不会那样做?

请您参考如下方法:

new_cube.rotate_cube("c") 仅在按下键时执行一次。这会导致颜色仅短暂闪烁。

您必须向类 Cube 添加一个状态 (self.colored),它指示是否必须绘制彩色立方体或线条。当 new_cube.color_cubie 被调用时,改变变量的状态:

例如

class Cube: 
 
    def __init__(self): 
        self.colored = False 
        # [...] 
 
    def color_cubie(self): 
        self.colored = True # change state, from now on draw colored  
 
    def show_cube(self) 
        if self.colored: 
            self.drawColored() 
        else: 
            self.drawLines() 
 
 
    def drawLines(slef): 
        # draw the lines here 
        # [...] 
 
 
    def drawColored(self): 
        # draw the colored cube here 
         # [...]