1

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

我已经包含了所有正确的库,并仔细检查了 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 显示错误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 环境前面。

4

1 回答 1

0

问题不是第一个参数GLUT_BITMAP_TIMES_ROMAN_24,而是第二个参数text[i]。to 的参数glutBitmapCharacter必须是一个整数值 ( int),它表示字符。
字符必须通过以下方式转换为普通数字 ( int) ord

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()

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

于 2019-05-02T17:16:49.840 回答