Loading

[CG从零开始] 1. 安装 pyopengl

因为只是为了验证原理和想法,实在不愿意折腾 C++ 去编译、链接找库......,并且为了配合今后一系列关于 CG 的文章,决定用 python 的 opengl wrapper 来进行实践,所以第一步就是安装 pyopengl 了。

pip install PyOpenGL PyOpenGL-accelerate

我的电脑是 Mac, 安装以后可以验证一下,粘贴下面这个代码,然后运行这个脚本,看看是否可以正常打开窗口,并且可以绘制一个粉色的正方形。

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

w,h= 500,500
def square():
    glBegin(GL_QUADS)
    glVertex2f(100, 100)
    glVertex2f(200, 100)
    glVertex2f(200, 200)
    glVertex2f(100, 200)
    glEnd()

def iterate():
    glViewport(0, 0, 500, 500)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0.0, 500, 0.0, 500, 0.0, 1.0)
    glMatrixMode (GL_MODELVIEW)
    glLoadIdentity()

def showScreen():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    iterate()
    glColor3f(1.0, 0.0, 3.0)
    square()
    glutSwapBuffers()

glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
glutInitWindowPosition(0, 0)
wind = glutCreateWindow("OpenGL Coding Practice")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutMainLoop()

我用的是 Mac ,可能会遇到了找不到 opengl 和 glut 库的问题,如下:

找不到 opengl

...
...
raise ImportError("Unable to load OpenGL library", *err.args)
ImportError: ('Unable to load OpenGL library', "dlopen(OpenGL, 0x000A): tried

找不到 glut

...
...
    _base_glutInit(ctypes.byref(count), holder)
  File "/usr/local/anaconda3/envs/opengl/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 423, in __call__
    raise error.NullFunctionError(
OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling

找到 OpenGL/platform/ctypesloader.py 这个文件,在你 python 环境中的 lib 中,将下面的第一行,改为下面的代码,这样就可以顺利找到 opengl 和 glut 的库了。

# -----------
fullName = util.find_library( name )
# -----------
# |
# v
# ------------
if name == 'OpenGL':
    fullName = '/System/Library/Frameworks/OpenGL.framework/OpenGL'
elif name == 'GLUT':
    fullName = '/System/Library/Frameworks/GLUT.framework/GLUT'
# -------------
posted @ 2022-09-27 01:07  芒果和小猫  阅读(203)  评论(0编辑  收藏  举报