GLUT Display callback <function render at 0x0000021F3ABA3E20> with (),{} failed: returning None 'Wavefront' object has no attribute 'groups'你的代码报了这个错
时间: 2023-12-14 09:03:53 浏览: 32
非常抱歉,我之前的代码有误。在PyWavefront库中,我们需要使用`model.mesh_list`而不是`model.groups`来遍历每个面和顶点。另外,为了正确地渲染材质,我们需要在绘制每个面之前调用`glMaterial`函数来设置材质属性。下面是修正后的代码:
```python
import pywavefront
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
# 初始化OpenGL
glutInit()
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(800, 600)
glutCreateWindow("OBJ Model Viewer")
# 加载OBJ模型
model = pywavefront.Wavefront('model.obj')
# 渲染函数
def render():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0)
glRotatef(0.1, 0, 1, 0)
glRotatef(0.1, 1, 0, 0)
# 遍历每个面和顶点
for mesh in model.mesh_list:
material = mesh.material
glMaterial(GL_FRONT_AND_BACK, GL_AMBIENT, material.ambient)
glMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE, material.diffuse)
glMaterial(GL_FRONT_AND_BACK, GL_SPECULAR, material.specular)
glMaterial(GL_FRONT_AND_BACK, GL_SHININESS, material.shininess)
glBegin(GL_TRIANGLES)
for face in mesh.faces:
for vertex_i in face:
vertex = mesh.vertices[vertex_i]
glNormal3f(*mesh.normals[vertex.normal_index])
glVertex3f(*vertex.vertex)
glEnd()
glutSwapBuffers()
# 注册OpenGL回调函数
glutDisplayFunc(render)
glutIdleFunc(render)
# 启动OpenGL主循环
glutMainLoop()
```
在上面的代码中,我们首先遍历每个mesh对象,并使用`material`属性设置OpenGL的材质属性。然后,我们使用`glBegin`和`glEnd`函数来绘制每个三角形面,并在循环中遍历每个顶点。在每个顶点处,我们使用`glNormal3f`函数设置法向量,使用`glVertex3f`函数设置顶点坐标。最后,我们使用`glutMainLoop`函数启动OpenGL的主循环,使程序一直运行直到用户关闭窗口。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)