为什么我的 OpenGL 程序无法加载 GLUT 位图字体?

Why is my OpenGL program unable to load the GLUT bitmap fonts?

我想在 OpenGL 3D 环境的 HUD 上显示一些简单的文本。 所有消息来源都说我应该使用 GLUT 中包含的位图字体,但是,我的程序似乎无法使用 find/load 字体。

我已经包含了所有正确的库,并仔细检查了 fonts.py 文件确实在 ...\Python37\...\OpenGL\GLUT\ 目录中,但是当我键入 GLUT_BITMAP_TIMES_ROMAN_24(或任何其他位图字体)时,它在我的代码中突出显示为错误。

这是我调用来显示文本的函数:

def text(self, x, y, r, g, b, text):

    glColor3f(r, g, b)

    glRasterPos2f(x, y)

    for i in range(len(text)):
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, text[i])

这就是我调用函数的方式:

epoch_str = "Epoch: {0}".format(self.epoch)

self.text(x, y, 1.0, 1.0, 1.0, epoch_str)

如前所述,GLUT_BITMAP_TIMES_ROMAN_24 在我的 IDE (PyCharm) 中突出显示为错误,如果我尝试 运行 它会出现以下错误:

C:\Users\mickp\AppData\Local\Programs\Python\Python37\python.exe C:/Users/mickp/PycharmProjects/Test/U_Matrix.py
Traceback (most recent call last):
  File "C:\Users\mickp\AppData\Local\Programs\Python\Python37\lib\site-packages\OpenGL\GLUT\special.py", line 130, in safeCall
    return function( *args, **named )
  File "C:/Users/mickp/PycharmProjects/Test/U_Matrix.py", line 142, in render
    self.text(x, y, 1.0, 1.0, 1.0, epoch_str)
  File "C:/Users/mickp/PycharmProjects/Test/U_Matrix.py", line 79, in text
    glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, text[i])
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type
GLUT Display callback <bound method U_MATRIX.render of <__main__.U_MATRIX object at 0x000002877FF45438>> with (),{} failed: returning None argument 2: <class 'TypeError'>: wrong type

Process finished with exit code 1

我真的不明白这可能是什么问题?

编辑:以上错误已修复,它是一个单独的问题。 GLUT_BITMAP_TIMES_ROMAN_24 的潜在问题仍然存在。看: IDE shows an error for GLUT_BITMAP_TIMES_ROMAN_24

编辑 2:完整代码(不太长):

编辑 3:删除了完整代码(太长了)。添加以下内容解决了我的问题:

# added before
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
gluOrtho2D(0.0, width, 0.0, height)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()

# these two lines were here
epoch_str = "Epoch: {0}".format(self.epoch)
self.text(x+10, y+10, 0.0, 1.0, 0.0, epoch_str)

# added after
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glEnable(GL_TEXTURE_2D)

文本实际上只是隐藏了,因为我将它渲染到对象后面的 3D 环境中,而不是在 3D 环境前面。

问题不是第一个参数 GLUT_BITMAP_TIMES_ROMAN_24,而是第二个参数 text[i]glutBitmapCharacter 的参数必须是整数值 (int),表示字符。
字符必须通过 ord:

转换为普通数字 (int)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, ord(text[i]))

for c in text:
    glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, ord(c))

如果文本没有出现在屏幕上,则重置投影和模型视图矩阵并将文本绘制在位置 (0, 0) 以进行调试:

glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()

glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()

self.text(0.0, 0.0, 1.0, 1.0, 1.0, epoch_str)

glMatrixMode(GL_PROJECTION)
glPopMatrix()

glMatrixMode(GL_MODELVIEW)
glPopMatrix()

另见 Immediate mode and legacy OpenGL