首页 > 解决方案 > 如何用OpenGL绘制一个线立方体?

问题描述

我试图用线条画一个立方体。

这是我的代码。它只是给了我一个白色的框架,里面什么都没有。没发生什么事。我在这里做错了什么?是调用函数的顺序有问题还是投影有问题?


def myInit():
    glClearColor(0.0, 0.0, 0.0, 1.0) 
    glColor3f(0.2, 0.5, 0.4)
    gluPerspective(45, 1.33, 0.1, 50.0)


vertices= (
    (100, -100, -100),
    (100, 100, -100),
    (-100, 100, -100),
    (-100, -100, -100),
    (100, -100, 100),
    (100, 100, 100),
    (-100, -100, 100),
    (-100, 100, 100)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )


def Display():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)   
glutInitWindowSize(800, 600)  
myInit()
glutDisplayFunc(Display) 
glutMainLoop()

标签: pythonopenglglutpyopenglopengl-compat

解决方案


所有不在视锥体中的几何都会被剪裁。立方体的大小为 200x200x200。您必须创建一个足够大的视锥体。

例如,设置gluPerspective一个远平面为 1000.0 的透视投影矩阵。投影矩阵旨在设置为当前投影矩阵 ( GL_PROJECTION)。见glMatrixMode

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.33, 0.1, 1000.0) 


Translate ([`glTranslate`](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml)) the model along the negative z axis, in between the near plane (0.1) and far (plane). The model or view matrix has to be set to the current model view matrix (`GL_MODELVIEW`):

```py
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslate(0, 0, -500)

清除每一帧的显示glClear

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # [...]

通过调用交换当前双缓冲窗口的缓冲区glutSwapBuffers并不断更新显示glutPostRedisplay

def Display():
    # [...]

    glutSwapBuffers()
    glutPostRedisplay()

另请参阅立即模式和旧版 OpenGL

请参阅示例:

def init():
    glClearColor(0.0, 0.0, 0.0, 1.0) 
    
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, 1.33, 0.1, 1000.0)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslate(0, 0, -500)

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glColor3f(0.2, 0.5, 0.4)
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

    glutSwapBuffers()
    glutPostRedisplay()

推荐阅读