• python实现简单的三维建模学习记录


    课程来源与蓝桥云课Python 实现三维建模工具_Python - 蓝桥云课500 Lines or LessA 3D Modeller

    说明

    个人估计这是一个值得花一个礼拜左右时间去琢磨的一个小项目。上述网址中的代码直接拿来不一定能跑,需要后期自己去修改甚至在上面继续优化,会在其中加入一些个人理解。存在的一些问题:不能通过鼠标滚轮缩放,不能通过cs创建新的物体。后期自己去进行修改。肯定是没有现成的三维建模软件好使,比如solidworks 和 ug这些成熟的软件。

    首先是环境问题,我试过在ubuntu20.04中进行搭建环境,和Windows中进行搭建,发现Ubuntu中始终不能成功,主要问题就是其中的OpenGL的版本问题,网上教程大部分指向的一个网址已经没有效果了。这里建议根据自己python版本去GitHub - Ultravioletrayss/OpenGLfile下载对应的opengl进行离线安装:

    pip install --user .\Downloads\PyOpenGL-3.1.7-cp311-cp311-win_amd64.whl

    环境问题解决了。

    目的梳理:想要建立一个界面,界面需要能够显示三维的物体,能够通过鼠标进行选取,通过键盘进行放大缩小,能够通过鼠标左键进行移动,右键进行整个视角的旋转,能够通过键盘c的输入生成一个立方体,通过键盘s的输入生成一个球体。

    显示三维物体:

    能够通过鼠标选中物体(选中的是蓝色方块):

    摁键盘上键进行物体放大:

    鼠标左键拖住物体进行移动:

    右键进行视角的旋转:

    鼠标滚轮进行视角的推进与拉远

    通过键盘输入cs创建立方体与球体:

    先新建一个Viewer类,包括初始化界面,初始化OpenGL的配置,初始化交互的操作,以及渲染部分,尤其是渲染,后续很多地方都要在这里修改。

    首先新建文件 viewer.py,导入项目所需的库与方法:

    1. from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable,glFlush,glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, glPushMatrix, glTranslated, glViewport, GL_AMBIENT_AND_DIFFUSE, GL_BACK, GL_CULL_FACE, GL_COLOR_BUFFER_BIT, GL_COLOR_MATERIAL, GL_DEPTH_BUFFER_BIT, GL_DEPTH_TEST, GL_FRONT_AND_BACK, GL_LESS, GL_LIGHT0, GL_LIGHTING, GL_MODELVIEW, GL_MODELVIEW_MATRIX, GL_POSITION, GL_PROJECTION, GL_SPOT_DIRECTION
    2. from OpenGL.constants import GLfloat_3, GLfloat_4
    3. from OpenGL.GLU import gluPerspective, gluUnProject
    4. from OpenGL.GLUT import glutCreateWindow, glutDisplayFunc, glutGet, glutInit, glutInitDisplayMode, glutInitWindowSize, glutMainLoop, GLUT_SINGLE, GLUT_RGB, GLUT_WINDOW_HEIGHT, GLUT_WINDOW_WIDTH
    5. import numpy
    6. from numpy.linalg import norm, inv

    在 viewer.py 中实现 Viewer 类,Viewer 类控制并管理整个程序的流程,它的 main_loop 方法是我们程序的入口。

    Viewer 的初始代码如下:

    1. class Viewer(object):
    2. def __init__(self):
    3. """ Initialize the viewer. """
    4. #初始化接口,创建窗口并注册渲染函数
    5. self.init_interface()
    6. #初始化 opengl 的配置
    7. self.init_opengl()
    8. #初始化3d场景
    9. self.init_scene()
    10. #初始化交互操作相关的代码
    11. self.init_interaction()
    12. def init_interface(self):
    13. """ 初始化窗口并注册渲染函数 """
    14. glutInit()
    15. glutInitWindowSize(640, 480)
    16. glutCreateWindow(b"3D Modeller")
    17. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    18. #注册窗口渲染函数
    19. glutDisplayFunc(self.render)
    20. def init_opengl(self):
    21. """ 初始化opengl的配置 """
    22. #模型视图矩阵
    23. self.inverseModelView = numpy.identity(4)
    24. #模型视图矩阵的逆矩阵
    25. self.modelView = numpy.identity(4)
    26. #开启剔除操作效果
    27. glEnable(GL_CULL_FACE)
    28. #取消对多边形背面进行渲染的计算(看不到的部分不渲染)
    29. glCullFace(GL_BACK)
    30. #开启深度测试
    31. glEnable(GL_DEPTH_TEST)
    32. #测试是否被遮挡,被遮挡的物体不予渲染
    33. glDepthFunc(GL_LESS)
    34. #启用0号光源
    35. glEnable(GL_LIGHT0)
    36. #设置光源的位置
    37. glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(0, 0, 1, 0))
    38. #设置光源的照射方向
    39. glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, GLfloat_3(0, 0, -1))
    40. #设置材质颜色
    41. glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
    42. glEnable(GL_COLOR_MATERIAL)
    43. #设置清屏的颜色
    44. glClearColor(0.4, 0.4, 0.4, 0.0)
    45. def init_scene(self):
    46. #初始化场景,之后实现
    47. pass
    48. def init_interaction(self):
    49. #初始化交互操作相关的代码,之后实现
    50. pass
    51. def main_loop(self):
    52. #程序主循环开始
    53. glutMainLoop()
    54. def render(self):
    55. #程序进入主循环后每一次循环调用的渲染函数
    56. pass
    57. if __name__ == "__main__":
    58. viewer = Viewer()
    59. viewer.main_loop()

     render 函数的补完:

    1. def render(self):
    2. #初始化投影矩阵
    3. self.init_view()
    4. #启动光照
    5. glEnable(GL_LIGHTING)
    6. #清空颜色缓存与深度缓存
    7. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    8. #设置模型视图矩阵,目前为止用单位矩阵就行了。
    9. glMatrixMode(GL_MODELVIEW)
    10. glPushMatrix()
    11. glLoadIdentity()
    12. #渲染场景
    13. #self.scene.render()
    14. #每次渲染后复位光照状态
    15. glDisable(GL_LIGHTING)
    16. glPopMatrix()
    17. #把数据刷新到显存上
    18. glFlush()
    19. def init_view(self):
    20. """ 初始化投影矩阵 """
    21. xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
    22. #得到屏幕宽高比
    23. aspect_ratio = float(xSize) / float(ySize)
    24. #设置投影矩阵
    25. glMatrixMode(GL_PROJECTION)
    26. glLoadIdentity()
    27. #设置视口,应与窗口重合
    28. glViewport(0, 0, xSize, ySize)
    29. #设置透视,摄像机上下视野幅度70度
    30. #视野范围到距离摄像机1000个单位为止。
    31. gluPerspective(70, aspect_ratio, 0.1, 1000.0)
    32. #摄像机镜头从原点后退15个单位
    33. glTranslated(0, 0, -15)

    将 self.scene.render() 的注释取消。

    scene 实例在 init_scene 方法中创建的。除了要得到 scene 实例,我们现在还希望在最初的场景中能有些看得见的东西。比如一个球体,它刚好在世界坐标系的正中央。就依照这个思路来实现最初的 init_scene 代码,设计需要的接口。这里用到了场景类,所以新开一个py文件进行场景类的实现(为了方便管理和修改,后续的节点类,球类,立方体类和雪人类,交互类,变换类,颜色等都是会新开一个文件进行管理)

    1. def init_scene(self):
    2. #创建一个场景实例
    3. self.scene = Scene()
    4. #初始化场景内的对象
    5. self.create_sample_scene()
    6. def create_sample_scene(self):
    7. #创建一个球体
    8. sphere_node = Sphere()
    9. #设置球体的颜色
    10. sphere_node.color_index = 2
    11. #将球体放进场景中,默认在正中央
    12. self.scene.add_node(sphere_node)

    实现场景类,在工作目录下新建 scene.py,初始代码如下,在viewer中的render后续会用到scene中的渲染,感觉跟c++中的继承有点类似。

    1. class Scene(object):
    2. #放置节点的深度,放置的节点距离摄像机15个单位
    3. PLACE_DEPTH = 15.0
    4. def __init__(self):
    5. #场景下的节点队列
    6. self.node_list = list()
    7. def add_node(self, node):
    8. """ 在场景中加入一个新节点 """
    9. self.node_list.append(node)
    10. def render(self):
    11. """ 遍历场景下所有节点并渲染 """
    12. for node in self.node_list:
    13. node.render()

    场景下的对象皆为节点,因此需要抽象出所有类型的对象的基类:Node 类(节点类)。在工作目录下创建 node.py 文件,导入需要的库:

    1. import random
    2. from OpenGL.GL import glCallList, glColor3f, glMaterialfv, glMultMatrixf, glPopMatrix, glPushMatrix, GL_EMISSION, GL_FRONT
    3. import numpy

    实现节点类的初始代码:

    1. class Node(object):
    2. def __init__(self):
    3. #该节点的颜色序号
    4. self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR)
    5. #该节点的平移矩阵,决定了该节点在场景中的位置
    6. self.translation_matrix = numpy.identity(4)
    7. #该节点的缩放矩阵,决定了该节点的大小
    8. self.scaling_matrix = numpy.identity(4)
    9. def render(self):
    10. """ 渲染节点 """
    11. glPushMatrix()
    12. #实现平移
    13. glMultMatrixf(numpy.transpose(self.translation_matrix))
    14. #实现缩放
    15. glMultMatrixf(self.scaling_matrix)
    16. cur_color = color.COLORS[self.color_index]
    17. #设置颜色
    18. glColor3f(cur_color[0], cur_color[1], cur_color[2])
    19. #渲染对象模型
    20. self.render_self()
    21. glPopMatrix()
    22. def render_self(self):
    23. raise NotImplementedError("The Abstract Node Class doesn't define 'render_self'")

    注意到对象的平移与缩放操作都在基类 Node 的 render 方法中完成,当我们实现一个子类时,不需要再实现一遍平移与缩放,只需要专心考虑如何渲染模型本身就可以了,即子类必须实现 render_self 方法。

    每一个节点都有自己的颜色属性,我们新建一个 color.py 文件,保存颜色信息

    1. MAX_COLOR = 9
    2. MIN_COLOR = 0
    3. COLORS = { # RGB Colors
    4. 0: (1.0, 1.0, 1.0),
    5. 1: (0.05, 0.05, 0.9),
    6. 2: (0.05, 0.9, 0.05),
    7. 3: (0.9, 0.05, 0.05),
    8. 4: (0.9, 0.9, 0.0),
    9. 5: (0.1, 0.8, 0.7),
    10. 6: (0.7, 0.2, 0.7),
    11. 7: (0.7, 0.7, 0.7),
    12. 8: (0.4, 0.4, 0.4),
    13. 9: (0.0, 0.0, 0.0),
    14. }

    同时在 node.py 中引入 color

    import color

    接着实现具体的球形类 Sphere

    1. class Primitive(Node):
    2. def __init__(self):
    3. super(Primitive, self).__init__()
    4. self.call_list = None
    5. def render_self(self):
    6. glCallList(self.call_list)
    7. class Sphere(Primitive):
    8. """ 球形图元 """
    9. def __init__(self):
    10. super(Sphere, self).__init__()
    11. self.call_list = G_OBJ_SPHERE

    为什么球形类与节点类之间又多了一个 Primitive 类呢?primitive 又称作图元,在这里,它是组成模型的基本单元,像是球体,立方体,三角等都属于图元。这些类的共通点在于它们的渲染都可以使用短小的 OpenGL 代码完成,同时对这些元素进行组合就可以组合出复杂的模型来,因此我们抽象出了 Primitive 这个类。

    观察 Primitive 的渲染函数,发现它调用了 glCallList 方法,glCallList 是 OpenGL 中一个使用起来非常便利的函数,正如它的名字,它会按序调用一个函数列表中的一系列函数,我们使用 glNewList(CALL_LIST_NUMBER, GL_COMPILE) 与 glEndList() 来标识一段代码的开始与结束,这段代码作为一个新的函数列表与一个数字关联起来,之后希望执行相同的操作时只需调用 glCallList(关联的数字) 就可以了,这样说也许有些抽象,在这个项目中,我们会这样应用:

    1. #标识代码段的数字
    2. G_OBJ_SPHERE = 2
    3. def make_sphere():
    4. #代码段的开始
    5. glNewList(G_OBJ_SPHERE, GL_COMPILE)
    6. #渲染球体模型
    7. quad = gluNewQuadric()
    8. gluSphere(quad, 0.5, 30, 30)
    9. gluDeleteQuadric(quad)
    10. #代码段的结束
    11. glEndList()
    12. make_sphere()

    这样每一次只要调用 glCallList(G_OBJ_SPHERE) 就能够生成球形了,新建一个文件 primitive.py,将渲染图元的函数列表写入文件中。

    1. from OpenGL.GL import glBegin, glColor3f, glEnd, glEndList, glLineWidth, glNewList, glNormal3f, glVertex3f, \
    2. GL_COMPILE, GL_LINES, GL_QUADS
    3. from OpenGL.GLU import gluDeleteQuadric, gluNewQuadric, gluSphere
    4. G_OBJ_SPHERE = 2
    5. def make_sphere():
    6. """ 创建球形的渲染函数列表 """
    7. glNewList(G_OBJ_SPHERE, GL_COMPILE)
    8. quad = gluNewQuadric()
    9. gluSphere(quad, 0.5, 30, 30)
    10. gluDeleteQuadric(quad)
    11. glEndList()
    12. def init_primitives():
    13. """ 初始化所有的图元渲染函数列表 """
    14. make_sphere()

    init_primitives() 添加到Viewer

    1. from primitive import init_primitives
    2. class Viewer(object):
    3. def __init__(self):
    4. self.init_interface()
    5. self.init_opengl()
    6. self.init_scene()
    7. self.init_interaction()
    8. init_primitives()

    在 node.py 中加入:

    from primitive import G_OBJ_SPHERE

    确保 viewer.py 中导入了以下内容:

    1. import color
    2. from scene import Scene
    3. from primitive import init_primitives
    4. from node import Sphere

    这时候就会有个小球在中间。

    平移与改变大小

    设计实现能够平移或者改变节点大小的接口,新建 transformation.py,实现生成平移矩阵与缩放矩阵的方法,(后期试着加一个旋转)

    1. import numpy
    2. def translation(displacement):
    3. """ 生成平移矩阵 """
    4. t = numpy.identity(4)
    5. t[0, 3] = displacement[0]
    6. t[1, 3] = displacement[1]
    7. t[2, 3] = displacement[2]
    8. return t
    9. def scaling(scale):
    10. """ 生成缩放矩阵 """
    11. s = numpy.identity(4)
    12. s[0, 0] = scale[0]
    13. s[1, 1] = scale[1]
    14. s[2, 2] = scale[2]
    15. s[3, 3] = 1
    16. return s

    在 Node 类中编写相应的平移与缩放的接口:

    1. from transformation import scaling, translation
    2. ...
    3. class Node(object)
    4. ...
    5. def translate(self, x, y, z):
    6. self.translation_matrix = numpy.dot(self.translation_matrix, translation([x, y, z]))
    7. def scale(self, s):
    8. self.scaling_matrix = numpy.dot(self.scaling_matrix, scaling([s,s,s]))

    更新 Viewer 的 create_sample_scene

    1. def create_sample_scene(self):
    2. sphere_node = Sphere()
    3. sphere_node.color_index = 2
    4. sphere_node.translate(2,2,0)
    5. sphere_node.scale(4)
    6. self.scene.add_node(sphere_node)

    组合节点

    复杂的模型能够从简单的图元通过组合得到,组合后的模型也应该作为一个节点来看待。所以引入组合节点。

    我们在 node.py 中创建 HierarchicalNode 类,这是一个包含子节点的的节点,它将子节点存储在 child_nodes 中,同时作为 Node 的子类,它也必须实现 render_self, 它的 render_self 函数就是简单地遍历调用子节点的 render_self

    1. class HierarchicalNode(Node):
    2. def __init__(self):
    3. super(HierarchicalNode, self).__init__()
    4. self.child_nodes = []
    5. def render_self(self):
    6. for child in self.child_nodes:
    7. child.render()

    为了展示组合的效果,我们以小雪人 SnowFigure 类为例,小雪人是由 3 个不同大小球体组成的模型。self.child_nodes列表中包括三个球体,然后循环对其节点颜色进行赋值。

    1. class SnowFigure(HierarchicalNode):
    2. def __init__(self):
    3. super(SnowFigure, self).__init__()
    4. self.child_nodes = [Sphere(), Sphere(), Sphere()]
    5. self.child_nodes[0].translate(0, -0.6, 0)
    6. self.child_nodes[1].translate(0, 0.1, 0)
    7. self.child_nodes[1].scale(0.8)
    8. self.child_nodes[2].translate(0, 0.75, 0)
    9. self.child_nodes[2].scale(0.7)
    10. for child_node in self.child_nodes:
    11. child_node.color_index = color.MIN_COLOR

    更新 create_sample_scene,实例化一个球类,颜色选取索引为2的颜色,放大四倍,场景节点列表中加入一个新节点,添加小雪人,移动缩放,并添加到场景节点列表中

    1. from node import SnowFigure
    2. ...
    3. class Viewer(object):
    4. def create_sample_scene(self):
    5. sphere_node = Sphere()
    6. sphere_node.color_index = 2
    7. sphere_node.translate(2,2,0)
    8. sphere_node.scale(4)
    9. self.scene.add_node(sphere_node)
    10. #添加小雪人
    11. hierarchical_node = SnowFigure()
    12. hierarchical_node.translate(-2, 0, -2)
    13. hierarchical_node.scale(2)
    14. self.scene.add_node(hierarchical_node)

    这种组合会形成一种树形的的数据结构,叶子节点就是图元节点,每次渲染都会深度遍历这棵树,这就是设计模式中的组合模式了。一言以蔽之,节点的集合仍旧是节点,它们实现相同的接口,组合节点会在接口中遍历所有子节点的接口。后续的类实现都是继承了Node类中的一部分实现,在场景渲染中就是通过一个for循环遍历node_list,调用节点自身的渲染函数实现。

    完整代码

    viewer.py 代码(这个时候还没有加入交互部分代码):

    1. #-*- coding:utf-8 -*-
    2. from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable,\
    3. glFlush, glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, \
    4. glPushMatrix, glTranslated, glViewport, \
    5. GL_AMBIENT_AND_DIFFUSE, GL_BACK, GL_CULL_FACE, GL_COLOR_BUFFER_BIT, GL_COLOR_MATERIAL, \
    6. GL_DEPTH_BUFFER_BIT, GL_DEPTH_TEST, GL_FRONT_AND_BACK, GL_LESS, GL_LIGHT0, GL_LIGHTING, \
    7. GL_MODELVIEW, GL_MODELVIEW_MATRIX, GL_POSITION, GL_PROJECTION, GL_SPOT_DIRECTION
    8. from OpenGL.constants import GLfloat_3, GLfloat_4
    9. from OpenGL.GLU import gluPerspective, gluUnProject
    10. from OpenGL.GLUT import glutCreateWindow, glutDisplayFunc, glutGet, glutInit, glutInitDisplayMode, \
    11. glutInitWindowSize, glutMainLoop, \
    12. GLUT_SINGLE, GLUT_RGB, GLUT_WINDOW_HEIGHT, GLUT_WINDOW_WIDTH, glutCloseFunc
    13. import numpy
    14. from numpy.linalg import norm, inv
    15. import random
    16. from OpenGL.GL import glBegin, glColor3f, glEnd, glEndList, glLineWidth, glNewList, glNormal3f, glVertex3f, \
    17. GL_COMPILE, GL_LINES, GL_QUADS
    18. from OpenGL.GLU import gluDeleteQuadric, gluNewQuadric, gluSphere
    19. import color
    20. from scene import Scene
    21. from primitive import init_primitives, G_OBJ_PLANE
    22. from node import Sphere, Cube, SnowFigure
    23. class Viewer(object):
    24. def __init__(self):
    25. """ Initialize the viewer. """
    26. #初始化接口,创建窗口并注册渲染函数
    27. self.init_interface()
    28. #初始化opengl的配置
    29. self.init_opengl()
    30. #初始化3d场景
    31. self.init_scene()
    32. #初始化交互操作相关的代码
    33. self.init_interaction()
    34. init_primitives()
    35. def init_interface(self):
    36. """ 初始化窗口并注册渲染函数 """
    37. glutInit()
    38. glutInitWindowSize(640, 480)
    39. glutCreateWindow("3D Modeller")
    40. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    41. #注册窗口渲染函数
    42. glutDisplayFunc(self.render)
    43. def init_opengl(self):
    44. """ 初始化opengl的配置 """
    45. #模型视图矩阵
    46. self.inverseModelView = numpy.identity(4)
    47. #模型视图矩阵的逆矩阵
    48. self.modelView = numpy.identity(4)
    49. #开启剔除操作效果
    50. glEnable(GL_CULL_FACE)
    51. #取消对多边形背面进行渲染的计算(看不到的部分不渲染)
    52. glCullFace(GL_BACK)
    53. #开启深度测试
    54. glEnable(GL_DEPTH_TEST)
    55. #测试是否被遮挡,被遮挡的物体不予渲染
    56. glDepthFunc(GL_LESS)
    57. #启用0号光源
    58. glEnable(GL_LIGHT0)
    59. #设置光源的位置
    60. glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(0, 0, 1, 0))
    61. #设置光源的照射方向
    62. glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, GLfloat_3(0, 0, -1))
    63. #设置材质颜色
    64. glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
    65. glEnable(GL_COLOR_MATERIAL)
    66. #设置清屏的颜色
    67. glClearColor(0.4, 0.4, 0.4, 0.0)
    68. def init_scene(self):
    69. #创建一个场景实例
    70. self.scene = Scene()
    71. #初始化场景内的对象
    72. self.create_sample_scene()
    73. def create_sample_scene(self):
    74. cube_node = Cube()
    75. cube_node.translate(2, 0, 2)
    76. cube_node.color_index = 1
    77. self.scene.add_node(cube_node)
    78. sphere_node = Sphere()
    79. sphere_node.translate(-2, 0, 2)
    80. sphere_node.color_index = 3
    81. self.scene.add_node(sphere_node)
    82. hierarchical_node = SnowFigure()
    83. hierarchical_node.translate(-2, 0, -2)
    84. self.scene.add_node(hierarchical_node)
    85. def init_interaction(self):
    86. #初始化交互操作相关的代码,之后实现
    87. pass
    88. def main_loop(self):
    89. #程序主循环开始
    90. glutMainLoop()
    91. def render(self):
    92. #初始化投影矩阵
    93. self.init_view()
    94. #启动光照
    95. glEnable(GL_LIGHTING)
    96. #清空颜色缓存与深度缓存
    97. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    98. #设置模型视图矩阵,这节课先用单位矩阵就行了。
    99. glMatrixMode(GL_MODELVIEW)
    100. glPushMatrix()
    101. glLoadIdentity()
    102. #渲染场景
    103. self.scene.render()
    104. #每次渲染后复位光照状态
    105. glDisable(GL_LIGHTING)
    106. glCallList(G_OBJ_PLANE)
    107. glPopMatrix()
    108. #把数据刷新到显存上
    109. glFlush()
    110. def init_view(self):
    111. """ 初始化投影矩阵 """
    112. xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
    113. #得到屏幕宽高比
    114. aspect_ratio = float(xSize) / float(ySize)
    115. #设置投影矩阵
    116. glMatrixMode(GL_PROJECTION)
    117. glLoadIdentity()
    118. #设置视口,应与窗口重合
    119. glViewport(0, 0, xSize, ySize)
    120. #设置透视,摄像机上下视野幅度70度
    121. #视野范围到距离摄像机1000个单位为止。
    122. gluPerspective(70, aspect_ratio, 0.1, 1000.0)
    123. #摄像机镜头从原点后退15个单位
    124. glTranslated(0, 0, -15)
    125. if __name__ == "__main__":
    126. viewer = Viewer()
    127. viewer.main_loop()

    scene.py代码:

    1. #-*- coding:utf-8 -*-
    2. class Scene(object):
    3. #放置节点的深度,放置的节点距离摄像机15个单位
    4. PLACE_DEPTH = 15.0
    5. def __init__(self):
    6. #场景下的节点队列
    7. self.node_list = list()
    8. def add_node(self, node):
    9. """ 在场景中加入一个新节点 """
    10. self.node_list.append(node)
    11. def render(self):
    12. """ 遍历场景下所有节点并渲染 """
    13. for node in self.node_list:
    14. node.render()

    node.py代码:

    1. #-*- coding:utf-8 -*-
    2. import random
    3. from OpenGL.GL import glCallList, glColor3f, glMaterialfv, glMultMatrixf, glPopMatrix, glPushMatrix, \
    4. GL_EMISSION, GL_FRONT
    5. import numpy
    6. from primitive import G_OBJ_CUBE, G_OBJ_SPHERE
    7. from transformation import scaling, translation
    8. import color
    9. class Node(object):
    10. def __init__(self):
    11. #该节点的颜色序号
    12. self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR)
    13. #该节点的平移矩阵,决定了该节点在场景中的位置
    14. self.translation_matrix = numpy.identity(4)
    15. #该节点的缩放矩阵,决定了该节点的大小
    16. self.scaling_matrix = numpy.identity(4)
    17. def render(self):
    18. """ 渲染节点 """
    19. glPushMatrix()
    20. #实现平移
    21. glMultMatrixf(numpy.transpose(self.translation_matrix))
    22. #实现缩放
    23. glMultMatrixf(self.scaling_matrix)
    24. cur_color = color.COLORS[self.color_index]
    25. #设置颜色
    26. glColor3f(cur_color[0], cur_color[1], cur_color[2])
    27. #渲染对象模型
    28. self.render_self()
    29. glPopMatrix()
    30. def render_self(self):
    31. raise NotImplementedError(
    32. "The Abstract Node Class doesn't define 'render_self'")
    33. def translate(self, x, y, z):
    34. self.translation_matrix = numpy.dot(self.translation_matrix, translation([x, y, z]))
    35. def scale(self, s):
    36. self.scaling_matrix = numpy.dot(self.scaling_matrix, scaling([s,s,s]))
    37. class Primitive(Node):
    38. def __init__(self):
    39. super(Primitive, self).__init__()
    40. self.call_list = None
    41. def render_self(self):
    42. glCallList(self.call_list)
    43. class Sphere(Primitive):
    44. """ 球形图元 """
    45. def __init__(self):
    46. super(Sphere, self).__init__()
    47. self.call_list = G_OBJ_SPHERE
    48. class Cube(Primitive):
    49. """ 立方体图元 """
    50. def __init__(self):
    51. super(Cube, self).__init__()
    52. self.call_list = G_OBJ_CUBE
    53. class HierarchicalNode(Node):
    54. def __init__(self):
    55. super(HierarchicalNode, self).__init__()
    56. self.child_nodes = []
    57. def render_self(self):
    58. for child in self.child_nodes:
    59. child.render()
    60. class SnowFigure(HierarchicalNode):
    61. def __init__(self):
    62. super(SnowFigure, self).__init__()
    63. self.child_nodes = [Sphere(), Sphere(), Sphere()]
    64. self.child_nodes[0].translate(0, -0.6, 0)
    65. self.child_nodes[1].translate(0, 0.1, 0)
    66. self.child_nodes[1].scale(0.8)
    67. self.child_nodes[2].translate(0, 0.75, 0)
    68. self.child_nodes[2].scale(0.7)
    69. for child_node in self.child_nodes:
    70. child_node.color_index = color.MIN_COLOR

    primitive.py 代码:

    1. from OpenGL.GL import glBegin, glColor3f, glEnd, glEndList, glLineWidth, glNewList, glNormal3f, glVertex3f, \
    2. GL_COMPILE, GL_LINES, GL_QUADS
    3. from OpenGL.GLU import gluDeleteQuadric, gluNewQuadric, gluSphere
    4. G_OBJ_PLANE = 1
    5. G_OBJ_SPHERE = 2
    6. G_OBJ_CUBE = 3
    7. def make_plane():
    8. glNewList(G_OBJ_PLANE, GL_COMPILE)
    9. glBegin(GL_LINES)
    10. glColor3f(0, 0, 0)
    11. for i in range(41):
    12. glVertex3f(-10.0 + 0.5 * i, 0, -10)
    13. glVertex3f(-10.0 + 0.5 * i, 0, 10)
    14. glVertex3f(-10.0, 0, -10 + 0.5 * i)
    15. glVertex3f(10.0, 0, -10 + 0.5 * i)
    16. # Axes
    17. glEnd()
    18. glLineWidth(5)
    19. glBegin(GL_LINES)
    20. glColor3f(0.5, 0.7, 0.5)
    21. glVertex3f(0.0, 0.0, 0.0)
    22. glVertex3f(5, 0.0, 0.0)
    23. glEnd()
    24. glBegin(GL_LINES)
    25. glColor3f(0.5, 0.7, 0.5)
    26. glVertex3f(0.0, 0.0, 0.0)
    27. glVertex3f(0.0, 5, 0.0)
    28. glEnd()
    29. glBegin(GL_LINES)
    30. glColor3f(0.5, 0.7, 0.5)
    31. glVertex3f(0.0, 0.0, 0.0)
    32. glVertex3f(0.0, 0.0, 5)
    33. glEnd()
    34. # Draw the Y.
    35. glBegin(GL_LINES)
    36. glColor3f(0.0, 0.0, 0.0)
    37. glVertex3f(0.0, 5.0, 0.0)
    38. glVertex3f(0.0, 5.5, 0.0)
    39. glVertex3f(0.0, 5.5, 0.0)
    40. glVertex3f(-0.5, 6.0, 0.0)
    41. glVertex3f(0.0, 5.5, 0.0)
    42. glVertex3f(0.5, 6.0, 0.0)
    43. # Draw the Z.
    44. glVertex3f(-0.5, 0.0, 5.0)
    45. glVertex3f(0.5, 0.0, 5.0)
    46. glVertex3f(0.5, 0.0, 5.0)
    47. glVertex3f(-0.5, 0.0, 6.0)
    48. glVertex3f(-0.5, 0.0, 6.0)
    49. glVertex3f(0.5, 0.0, 6.0)
    50. # Draw the X.
    51. glVertex3f(5.0, 0.0, 0.5)
    52. glVertex3f(6.0, 0.0, -0.5)
    53. glVertex3f(5.0, 0.0, -0.5)
    54. glVertex3f(6.0, 0.0, 0.5)
    55. glEnd()
    56. glLineWidth(1)
    57. glEndList()
    58. def make_sphere():
    59. glNewList(G_OBJ_SPHERE, GL_COMPILE)
    60. quad = gluNewQuadric()
    61. gluSphere(quad, 0.5, 30, 30)
    62. gluDeleteQuadric(quad)
    63. glEndList()
    64. def make_cube():
    65. glNewList(G_OBJ_CUBE, GL_COMPILE)
    66. vertices = [((-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5), (-0.5, 0.5, -0.5)),
    67. ((-0.5, -0.5, -0.5), (-0.5, 0.5, -0.5), (0.5, 0.5, -0.5), (0.5, -0.5, -0.5)),
    68. ((0.5, -0.5, -0.5), (0.5, 0.5, -0.5), (0.5, 0.5, 0.5), (0.5, -0.5, 0.5)),
    69. ((-0.5, -0.5, 0.5), (0.5, -0.5, 0.5), (0.5, 0.5, 0.5), (-0.5, 0.5, 0.5)),
    70. ((-0.5, -0.5, 0.5), (-0.5, -0.5, -0.5), (0.5, -0.5, -0.5), (0.5, -0.5, 0.5)),
    71. ((-0.5, 0.5, -0.5), (-0.5, 0.5, 0.5), (0.5, 0.5, 0.5), (0.5, 0.5, -0.5))]
    72. normals = [(-1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0), (0.0, 1.0, 0.0)]
    73. glBegin(GL_QUADS)
    74. for i in range(6):
    75. glNormal3f(normals[i][0], normals[i][1], normals[i][2])
    76. for j in range(4):
    77. glVertex3f(vertices[i][j][0], vertices[i][j][1], vertices[i][j][2])
    78. glEnd()
    79. glEndList()
    80. def init_primitives():
    81. make_plane()
    82. make_sphere()
    83. make_cube()

    transformation.py 代码:

    1. import numpy
    2. def translation(displacement):
    3. t = numpy.identity(4)
    4. t[0, 3] = displacement[0]
    5. t[1, 3] = displacement[1]
    6. t[2, 3] = displacement[2]
    7. return t
    8. def scaling(scale):
    9. s = numpy.identity(4)
    10. s[0, 0] = scale[0]
    11. s[1, 1] = scale[1]
    12. s[2, 2] = scale[2]
    13. s[3, 3] = 1
    14. return s

    color.py 代码:

    1. MAX_COLOR = 9
    2. MIN_COLOR = 0
    3. COLORS = { # RGB Colors
    4. 0: (1.0, 1.0, 1.0),
    5. 1: (0.05, 0.05, 0.9),
    6. 2: (0.05, 0.9, 0.05),
    7. 3: (0.9, 0.05, 0.05),
    8. 4: (0.9, 0.9, 0.0),
    9. 5: (0.1, 0.8, 0.7),
    10. 6: (0.7, 0.2, 0.7),
    11. 7: (0.7, 0.7, 0.7),
    12. 8: (0.4, 0.4, 0.4),
    13. 9: (0.0, 0.0, 0.0),
    14. }

    用户接口

    我们希望与场景实现两种交互,一种是你可以操纵场景从而能够从不同的角度观察模型,一种是你拥有添加与操作修改模型对象的能力。为了实现交互,我们需要得到键盘与鼠标的输入,GLUT 允许我们在键盘或鼠标事件上注册对应的回调函数

    新建 interaction.py 文件,用户接口在 Interaction 类中实现。

    1. from collections import defaultdict
    2. from OpenGL.GLUT import glutGet, glutKeyboardFunc, glutMotionFunc, glutMouseFunc, glutPassiveMotionFunc, \
    3. glutPostRedisplay, glutSpecialFunc
    4. from OpenGL.GLUT import GLUT_LEFT_BUTTON, GLUT_RIGHT_BUTTON, GLUT_MIDDLE_BUTTON, \
    5. GLUT_WINDOW_HEIGHT, GLUT_WINDOW_WIDTH, \
    6. GLUT_DOWN, GLUT_KEY_UP, GLUT_KEY_DOWN, GLUT_KEY_LEFT, GLUT_KEY_RIGHT
    7. import trackball

    初始化 Interaction 类,注册 glut 的事件回调函数

    1. class Interaction(object):
    2. def __init__(self):
    3. """ 处理用户接口 """
    4. #被按下的键
    5. self.pressed = None
    6. #轨迹球,会在之后进行说明
    7. self.trackball = trackball.Trackball(theta = -25, distance=15)
    8. #当前鼠标位置
    9. self.mouse_loc = None
    10. #回调函数词典
    11. self.callbacks = defaultdict(list)
    12. self.register()
    13. def register(self):
    14. """ 注册glut的事件回调函数 """
    15. glutMouseFunc(self.handle_mouse_button)
    16. glutMotionFunc(self.handle_mouse_move)
    17. glutKeyboardFunc(self.handle_keystroke)
    18. glutSpecialFunc(self.handle_keystroke)

    回调函数的实现,(提示下面代码有点问题):

    1. def handle_mouse_button(self, button, mode, x, y):
    2. """ 当鼠标按键被点击或者释放的时候调用 """
    3. xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
    4. y = ySize - y # OpenGL原点在窗口左下角,窗口原点在左上角,所以需要这种转换。
    5. self.mouse_loc = (x, y)
    6. if mode == GLUT_DOWN:
    7. #鼠标按键按下的时候
    8. self.pressed = button
    9. if button == GLUT_RIGHT_BUTTON:
    10. pass
    11. elif button == GLUT_LEFT_BUTTON:
    12. self.trigger('pick', x, y)
    13. else: # 鼠标按键被释放的时候
    14. self.pressed = None
    15. #标记当前窗口需要重新绘制
    16. glutPostRedisplay()
    17. def handle_mouse_move(self, x, screen_y):
    18. """ 鼠标移动时调用 """
    19. xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
    20. y = ySize - screen_y
    21. if self.pressed is not None:
    22. dx = x - self.mouse_loc[0]
    23. dy = y - self.mouse_loc[1]
    24. if self.pressed == GLUT_RIGHT_BUTTON and self.trackball is not None:
    25. # 变化场景的角度
    26. self.trackball.drag_to(self.mouse_loc[0], self.mouse_loc[1], dx, dy)
    27. elif self.pressed == GLUT_LEFT_BUTTON:
    28. self.trigger('move', x, y)
    29. elif self.pressed == GLUT_MIDDLE_BUTTON:
    30. self.translate(dx/60.0, dy/60.0, 0)
    31. else:
    32. pass
    33. glutPostRedisplay()
    34. self.mouse_loc = (x, y)
    35. def handle_keystroke(self, key, x, screen_y):
    36. """ 键盘输入时调用 """
    37. xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
    38. y = ySize - screen_y
    39. if key == 's':
    40. self.trigger('place', 'sphere', x, y)
    41. elif key == 'c':
    42. self.trigger('place', 'cube', x, y)
    43. elif key == GLUT_KEY_UP:
    44. self.trigger('scale', up=True)
    45. elif key == GLUT_KEY_DOWN:
    46. self.trigger('scale', up=False)
    47. elif key == GLUT_KEY_LEFT:
    48. self.trigger('rotate_color', forward=True)
    49. elif key == GLUT_KEY_RIGHT:
    50. self.trigger('rotate_color', forward=False)
    51. glutPostRedisplay()

    内部回调

    针对用户行为会调用 self.trigger 方法,它的第一个参数指明行为期望的效果,后续参数为该效果的参数,trigger 的实现如下:

    1. def trigger(self, name, *args, **kwargs):
    2. for func in self.callbacks[name]:
    3. func(*args, **kwargs)

    从代码可以看出 trigger 会取得 callbacks 词典下该效果对应的所有方法逐一调用。

    那么如何将方法添加进 callbacks 呢?我们需要实现一个注册回调函数的方法:

    1. def register_callback(self, name, func):
    2. self.callbacks[name].append(func)

    还记得 Viewer 中未实现的 self.init_interaction() 吗,我们就是在这里注册回调函数的,下面补完 init_interaction,后续功能添加就在这里添加

    1. from interaction import Interaction
    2. ...
    3. class Viewer(object):
    4. ...
    5. def init_interaction(self):
    6. self.interaction = Interaction()
    7. self.interaction.register_callback('pick', self.pick)
    8. self.interaction.register_callback('move', self.move)
    9. self.interaction.register_callback('place', self.place)
    10. self.interaction.register_callback('rotate_color', self.rotate_color)
    11. self.interaction.register_callback('scale', self.scale)
    12. def pick(self, x, y):
    13. """ 鼠标选中一个节点 """
    14. pass
    15. def move(self, x, y):
    16. """ 移动当前选中的节点 """
    17. pass
    18. def place(self, shape, x, y):
    19. """ 在鼠标的位置上新放置一个节点 """
    20. pass
    21. def rotate_color(self, forward):
    22. """ 更改选中节点的颜色 """
    23. pass
    24. def scale(self, up):
    25. """ 改变选中节点的大小 """
    26. pass

    pickmove 等函数的说明如下表所示:

    我们将在之后实现这些函数。

    Interaction 类抽象出了应用层级别的用户输入接口,这意味着当我们希望将 glut 更换为别的工具库的时候,只要照着抽象出来的接口重新实现一遍底层工具的调用就行了,也就是说仅需改动Interaction 类内的代码,实现了模块与模块之间的低耦合。

    这个简单的回调系统已满足了我们的项目所需。在真实的生产环境中,用户接口对象常常是动态生成和销毁的,所以真实生产中还需要实现解除注册的方法,我们这里就不用啦。

    场景交互

    旋转场景

    在这个项目中摄像机是固定的,我们主要靠移动场景来观察不同角度下的 3D 模型。摄像机固定在距离原点 15 个单位的位置,面对世界坐标系的原点。感观上是这样,但其实这种说法不准确,真实情况是在世界坐标系里摄像机是在原点的,但在摄像机坐标系中,摄像机后退了 15 个单位,这就等价于前者说的那种情况了。

    使用轨迹球

    我们使用轨迹球算法来完成场景的旋转,旋转的方法理解起来很简单,想象一个可以向任意角度围绕球心旋转的地球仪,你的视线是不变的,但是通过你的手在拨这个球,你可以想看哪里拨哪里。在我们的项目中,这个拨球的手就是鼠标右键,你点着右键拖动就能实现这个旋转场景的效果了。

    想要更多的理解轨迹球可以参考 OpenGL Wiki

    下载 trackball.py 文件,并将其置于工作目录下:,完整代码如下

    1. #! /usr/bin/env python
    2. # -*- coding: utf-8 -*-
    3. #
    4. # Copyright (c) 2009 Nicolas Rougier
    5. # 2008 Roger Allen
    6. # 1993, 1994, Silicon Graphics, Inc.
    7. # ALL RIGHTS RESERVED
    8. # Permission to use, copy, modify, and distribute this software for
    9. # any purpose and without fee is hereby granted, provided that the above
    10. # copyright notice appear in all copies and that both the copyright notice
    11. # and this permission notice appear in supporting documentation, and that
    12. # the name of Silicon Graphics, Inc. not be used in advertising
    13. # or publicity pertaining to distribution of the software without specific,
    14. # written prior permission.
    15. #
    16. # THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
    17. # AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
    18. # INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
    19. # FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
    20. # GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
    21. # SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
    22. # KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
    23. # LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
    24. # THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
    25. # ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
    26. # ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
    27. # POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
    28. #
    29. # US Government Users Restricted Rights
    30. # Use, duplication, or disclosure by the Government is subject to
    31. # restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
    32. # (c)(1)(ii) of the Rights in Technical Data and Computer Software
    33. # clause at DFARS 252.227-7013 and/or in similar or successor
    34. # clauses in the FAR or the DOD or NASA FAR Supplement.
    35. # Unpublished-- rights reserved under the copyright laws of the
    36. # United States. Contractor/manufacturer is Silicon Graphics,
    37. # Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
    38. #
    39. # Originally implemented by Gavin Bell, lots of ideas from Thant Tessman
    40. # and the August '88 issue of Siggraph's "Computer Graphics," pp. 121-129.
    41. # and David M. Ciemiewicz, Mark Grossman, Henry Moreton, and Paul Haeberli
    42. #
    43. # Note: See the following for more information on quaternions:
    44. #
    45. # - Shoemake, K., Animating rotation with quaternion curves, Computer
    46. # Graphics 19, No 3 (Proc. SIGGRAPH'85), 245-254, 1985.
    47. # - Pletinckx, D., Quaternion calculus as a basic tool in computer
    48. # graphics, The Visual Computer 5, 2-13, 1989.
    49. # -----------------------------------------------------------------------------
    50. ''' Provides a virtual trackball for 3D scene viewing
    51. Example usage:
    52. trackball = Trackball(45,45)
    53. @window.event
    54. def on_mouse_drag(x, y, dx, dy, button, modifiers):
    55. x = (x*2.0 - window.width)/float(window.width)
    56. dx = 2*dx/float(window.width)
    57. y = (y*2.0 - window.height)/float(window.height)
    58. dy = 2*dy/float(window.height)
    59. trackball.drag(x,y,dx,dy)
    60. @window.event
    61. def on_resize(width,height):
    62. glViewport(0, 0, window.width, window.height)
    63. glMatrixMode(GL_PROJECTION)
    64. glLoadIdentity()
    65. gluPerspective(45, window.width / float(window.height), .1, 1000)
    66. glMatrixMode (GL_MODELVIEW)
    67. glLoadIdentity ()
    68. glTranslatef (0, 0, -3)
    69. glMultMatrixf(trackball.matrix)
    70. You can also set trackball orientation directly by setting theta and phi value
    71. expressed in degrees. Theta relates to the rotation angle around X axis while
    72. phi relates to the rotation angle around Z axis.
    73. '''
    74. __docformat__ = 'restructuredtext'
    75. __version__ = '1.0'
    76. import math
    77. import OpenGL.GL as gl
    78. from OpenGL.GL import GLfloat
    79. # Some useful functions on vectors
    80. # -----------------------------------------------------------------------------
    81. def _v_add(v1, v2):
    82. return [v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]]
    83. def _v_sub(v1, v2):
    84. return [v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]]
    85. def _v_mul(v, s):
    86. return [v[0]*s, v[1]*s, v[2]*s]
    87. def _v_dot(v1, v2):
    88. return v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]
    89. def _v_cross(v1, v2):
    90. return [(v1[1]*v2[2]) - (v1[2]*v2[1]),
    91. (v1[2]*v2[0]) - (v1[0]*v2[2]),
    92. (v1[0]*v2[1]) - (v1[1]*v2[0])]
    93. def _v_length(v):
    94. return math.sqrt(_v_dot(v,v))
    95. def _v_normalize(v):
    96. try: return _v_mul(v,1.0/_v_length(v))
    97. except ZeroDivisionError: return v
    98. # Some useful functions on quaternions
    99. # -----------------------------------------------------------------------------
    100. def _q_add(q1,q2):
    101. t1 = _v_mul(q1, q2[3])
    102. t2 = _v_mul(q2, q1[3])
    103. t3 = _v_cross(q2, q1)
    104. tf = _v_add(t1, t2)
    105. tf = _v_add(t3, tf)
    106. tf.append(q1[3]*q2[3]-_v_dot(q1,q2))
    107. return tf
    108. def _q_mul(q, s):
    109. return [q[0]*s, q[1]*s, q[2]*s, q[3]*s]
    110. def _q_dot(q1, q2):
    111. return q1[0]*q2[0] + q1[1]*q2[1] + q1[2]*q2[2] + q1[3]*q2[3]
    112. def _q_length(q):
    113. return math.sqrt(_q_dot(q,q))
    114. def _q_normalize(q):
    115. try: return _q_mul(q,1.0/_q_length(q))
    116. except ZeroDivisionError: return q
    117. def _q_from_axis_angle(v, phi):
    118. q = _v_mul(_v_normalize(v), math.sin(phi/2.0))
    119. q.append(math.cos(phi/2.0))
    120. return q
    121. def _q_rotmatrix(q):
    122. m = [0.0]*16
    123. m[0*4+0] = 1.0 - 2.0*(q[1]*q[1] + q[2]*q[2])
    124. m[0*4+1] = 2.0 * (q[0]*q[1] - q[2]*q[3])
    125. m[0*4+2] = 2.0 * (q[2]*q[0] + q[1]*q[3])
    126. m[0*4+3] = 0.0
    127. m[1*4+0] = 2.0 * (q[0]*q[1] + q[2]*q[3])
    128. m[1*4+1] = 1.0 - 2.0*(q[2]*q[2] + q[0]*q[0])
    129. m[1*4+2] = 2.0 * (q[1]*q[2] - q[0]*q[3])
    130. m[1*4+3] = 0.0
    131. m[2*4+0] = 2.0 * (q[2]*q[0] - q[1]*q[3])
    132. m[2*4+1] = 2.0 * (q[1]*q[2] + q[0]*q[3])
    133. m[2*4+2] = 1.0 - 2.0*(q[1]*q[1] + q[0]*q[0])
    134. m[3*4+3] = 1.0
    135. return m
    136. class Trackball(object):
    137. ''' Virtual trackball for 3D scene viewing. '''
    138. def __init__(self, theta=0, phi=0, zoom=1, distance=3):
    139. ''' Build a new trackball with specified view '''
    140. self._rotation = [0,0,0,1]
    141. self.zoom = zoom
    142. self.distance = distance
    143. self._count = 0
    144. self._matrix=None
    145. self._RENORMCOUNT = 97
    146. self._TRACKBALLSIZE = 0.8
    147. self._set_orientation(theta,phi)
    148. self._x = 0.0
    149. self._y = 0.0
    150. def drag_to (self, x, y, dx, dy):
    151. ''' Move trackball view from x,y to x+dx,y+dy. '''
    152. viewport = gl.glGetIntegerv(gl.GL_VIEWPORT)
    153. width,height = float(viewport[2]), float(viewport[3])
    154. x = (x*2.0 - width)/width
    155. dx = (2.*dx)/width
    156. y = (y*2.0 - height)/height
    157. dy = (2.*dy)/height
    158. q = self._rotate(x,y,dx,dy)
    159. self._rotation = _q_add(q,self._rotation)
    160. self._count += 1
    161. if self._count > self._RENORMCOUNT:
    162. self._rotation = _q_normalize(self._rotation)
    163. self._count = 0
    164. m = _q_rotmatrix(self._rotation)
    165. self._matrix = (GLfloat*len(m))(*m)
    166. def zoom_to (self, x, y, dx, dy):
    167. ''' Zoom trackball by a factor dy '''
    168. viewport = gl.glGetIntegerv(gl.GL_VIEWPORT)
    169. height = float(viewport[3])
    170. self.zoom = self.zoom-5*dy/height
    171. def pan_to (self, x, y, dx, dy):
    172. ''' Pan trackball by a factor dx,dy '''
    173. self.x += dx*0.1
    174. self.y += dy*0.1
    175. def push(self):
    176. viewport = gl.glGetIntegerv(gl.GL_VIEWPORT)
    177. gl.glMatrixMode(gl.GL_PROJECTION)
    178. gl.glPushMatrix()
    179. gl.glLoadIdentity ()
    180. aspect = viewport[2]/float(viewport[3])
    181. aperture = 35.0
    182. near = 0.1
    183. far = 100.0
    184. top = math.tan(aperture*3.14159/360.0) * near * self._zoom
    185. bottom = -top
    186. left = aspect * bottom
    187. right = aspect * top
    188. gl.glFrustum (left, right, bottom, top, near, far)
    189. gl.glMatrixMode (gl.GL_MODELVIEW)
    190. gl.glPushMatrix()
    191. gl.glLoadIdentity ()
    192. # gl.glTranslate (0.0, 0, -self._distance)
    193. gl.glTranslate (self._x, self._y, -self._distance)
    194. gl.glMultMatrixf (self._matrix)
    195. def pop(void):
    196. gl.glMatrixMode(gl.GL_MODELVIEW)
    197. gl.glPopMatrix()
    198. gl.glMatrixMode(gl.GL_PROJECTION)
    199. gl.glPopMatrix()
    200. def _get_matrix(self):
    201. return self._matrix
    202. matrix = property(_get_matrix,
    203. doc='''Model view matrix transformation (read-only)''')
    204. def _get_zoom(self):
    205. return self._zoom
    206. def _set_zoom(self, zoom):
    207. self._zoom = zoom
    208. if self._zoom < .25: self._zoom = .25
    209. if self._zoom > 10: self._zoom = 10
    210. zoom = property(_get_zoom, _set_zoom,
    211. doc='''Zoom factor''')
    212. def _get_distance(self):
    213. return self._distance
    214. def _set_distance(self, distance):
    215. self._distance = distance
    216. if self._distance < 1: self._distance= 1
    217. distance = property(_get_distance, _set_distance,
    218. doc='''Scene distance from point of view''')
    219. def _get_theta(self):
    220. self._theta, self._phi = self._get_orientation()
    221. return self._theta
    222. def _set_theta(self, theta):
    223. self._set_orientation(math.fmod(theta,360.0),
    224. math.fmod(self._phi,360.0))
    225. theta = property(_get_theta, _set_theta,
    226. doc='''Angle (in degrees) around the z axis''')
    227. def _get_phi(self):
    228. self._theta, self._phi = self._get_orientation()
    229. return self._phi
    230. def _set_phi(self, phi):
    231. self._set_orientation(math.fmod(self._theta,360.),
    232. math.fmod(phi,360.0))
    233. phi = property(_get_phi, _set_phi,
    234. doc='''Angle around x axis''')
    235. def _get_orientation(self):
    236. ''' Return current computed orientation (theta,phi). '''
    237. q0,q1,q2,q3 = self._rotation
    238. ax = math.atan(2*(q0*q1+q2*q3)/(1-2*(q1*q1+q2*q2)))*180.0/math.pi
    239. az = math.atan(2*(q0*q3+q1*q2)/(1-2*(q2*q2+q3*q3)))*180.0/math.pi
    240. return -az,ax
    241. def _set_orientation(self, theta, phi):
    242. ''' Computes rotation corresponding to theta and phi. '''
    243. self._theta = theta
    244. self._phi = phi
    245. angle = self._theta*(math.pi/180.0)
    246. sine = math.sin(0.5*angle)
    247. xrot = [1*sine, 0, 0, math.cos(0.5*angle)]
    248. angle = self._phi*(math.pi/180.0)
    249. sine = math.sin(0.5*angle);
    250. zrot = [0, 0, sine, math.cos(0.5*angle)]
    251. self._rotation = _q_add(xrot, zrot)
    252. m = _q_rotmatrix(self._rotation)
    253. self._matrix = (GLfloat*len(m))(*m)
    254. def _project(self, r, x, y):
    255. ''' Project an x,y pair onto a sphere of radius r OR a hyperbolic sheet
    256. if we are away from the center of the sphere.
    257. '''
    258. d = math.sqrt(x*x + y*y)
    259. if (d < r * 0.70710678118654752440): # Inside sphere
    260. z = math.sqrt(r*r - d*d)
    261. else: # On hyperbola
    262. t = r / 1.41421356237309504880
    263. z = t*t / d
    264. return z
    265. def _rotate(self, x, y, dx, dy):
    266. ''' Simulate a track-ball.
    267. Project the points onto the virtual trackball, then figure out the
    268. axis of rotation, which is the cross product of x,y and x+dx,y+dy.
    269. Note: This is a deformed trackball-- this is a trackball in the
    270. center, but is deformed into a hyperbolic sheet of rotation away
    271. from the center. This particular function was chosen after trying
    272. out several variations.
    273. '''
    274. if not dx and not dy:
    275. return [ 0.0, 0.0, 0.0, 1.0]
    276. last = [x, y, self._project(self._TRACKBALLSIZE, x, y)]
    277. new = [x+dx, y+dy, self._project(self._TRACKBALLSIZE, x+dx, y+dy)]
    278. a = _v_cross(new, last)
    279. d = _v_sub(last, new)
    280. t = _v_length(d) / (2.0*self._TRACKBALLSIZE)
    281. if (t > 1.0): t = 1.0
    282. if (t < -1.0): t = -1.0
    283. phi = 2.0 * math.asin(t)
    284. return _q_from_axis_angle(a,phi)
    285. def __str__(self):
    286. phi = str(self.phi)
    287. theta = str(self.theta)
    288. zoom = str(self.zoom)
    289. return 'Trackball(phi=%s,theta=%s,zoom=%s)' % (phi,theta,zoom)
    290. def __repr__(self):
    291. phi = str(self.phi)
    292. theta = str(self.theta)
    293. zoom = str(self.zoom)
    294. return 'Trackball(phi=%s,theta=%s,zoom=%s)' % (phi,theta,zoom)

    drag_to 方法实现与轨迹球的交互,它会比对之前的鼠标位置和移动后的鼠标位置来更新旋转矩阵(有意思的部分,可以回头多看看)。

    self.trackball.drag_to(self.mouse_loc[0], self.mouse_loc[1], dx, dy)

    得到的旋转矩阵保存在 viewer 的 trackball.matrix 中。更新 viewer.py 下的 ModelView 矩阵:

    1. class Viewer(object):
    2. ...
    3. def render(self):
    4. self.init_view()
    5. glEnable(GL_LIGHTING)
    6. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    7. # 将ModelView矩阵设为轨迹球的旋转矩阵
    8. glMatrixMode(GL_MODELVIEW)
    9. glPushMatrix()
    10. glLoadIdentity()
    11. glMultMatrixf(self.interaction.trackball.matrix)
    12. # 存储ModelView矩阵与其逆矩阵之后做坐标系转换用
    13. currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX))
    14. self.modelView = numpy.transpose(currentModelView)
    15. self.inverseModelView = inv(numpy.transpose(currentModelView))
    16. self.scene.render()
    17. glDisable(GL_LIGHTING)
    18. glCallList(G_OBJ_PLANE)
    19. glPopMatrix()
    20. glFlush()

    选择场景中的对象

    既然要操作场景中的对象,那么必然得先能够选中对象,要怎么才能选中呢?想象你有一只指哪打哪的激光笔,当激光与对象相交时就相当于选中了对象。

    我们如何判定激光穿透了对象呢?

    想要真正实现对复杂形状物体进行选择判定是非常考验算法和性能的,所以在这里我们简化问题,对对象使用包围盒(axis-aligned bounding box, 简称 AABB),包围盒可以想象成一个为对象量身定做的盒子,你刚刚好能将模型放进去。这样做的好处就是对于不同形状的对象你都可以使用同一段代码处理选中判定,并能保证较好的性能。(三维的boundingbox就联想到bevfusion检测出的bounding box,是不是可以进一步优化?)是否可以参考实例分割?做三维的分割?高斯泼浅?

    新建 aabb.py,编写包围盒类:

    1. from OpenGL.GL import glCallList, glMatrixMode, glPolygonMode, glPopMatrix, glPushMatrix, glTranslated, \
    2. GL_FILL, GL_FRONT_AND_BACK, GL_LINE, GL_MODELVIEW
    3. from primitive import G_OBJ_CUBE
    4. import numpy
    5. import math
    6. #判断误差
    7. EPSILON = 0.000001
    8. class AABB(object):
    9. def __init__(self, center, size):
    10. self.center = numpy.array(center)
    11. self.size = numpy.array(size)
    12. def scale(self, scale):
    13. self.size *= scale
    14. def ray_hit(self, origin, direction, modelmatrix):
    15. """ 返回真则表示激光射中了包盒
    16. 参数说明: origin, distance -> 激光源点与方向
    17. modelmatrix -> 世界坐标到局部对象坐标的转换矩阵 """
    18. aabb_min = self.center - self.size
    19. aabb_max = self.center + self.size
    20. tmin = 0.0
    21. tmax = 100000.0
    22. obb_pos_worldspace = numpy.array([modelmatrix[0, 3], modelmatrix[1, 3], modelmatrix[2, 3]])
    23. delta = (obb_pos_worldspace - origin)
    24. # test intersection with 2 planes perpendicular to OBB's x-axis
    25. xaxis = numpy.array((modelmatrix[0, 0], modelmatrix[0, 1], modelmatrix[0, 2]))
    26. e = numpy.dot(xaxis, delta)
    27. f = numpy.dot(direction, xaxis)
    28. if math.fabs(f) > 0.0 + EPSILON:
    29. t1 = (e + aabb_min[0])/f
    30. t2 = (e + aabb_max[0])/f
    31. if t1 > t2:
    32. t1, t2 = t2, t1
    33. if t2 < tmax:
    34. tmax = t2
    35. if t1 > tmin:
    36. tmin = t1
    37. if tmax < tmin:
    38. return (False, 0)
    39. else:
    40. if (-e + aabb_min[0] > 0.0 + EPSILON) or (-e+aabb_max[0] < 0.0 - EPSILON):
    41. return False, 0
    42. yaxis = numpy.array((modelmatrix[1, 0], modelmatrix[1, 1], modelmatrix[1, 2]))
    43. e = numpy.dot(yaxis, delta)
    44. f = numpy.dot(direction, yaxis)
    45. # intersection in y
    46. if math.fabs(f) > 0.0 + EPSILON:
    47. t1 = (e + aabb_min[1])/f
    48. t2 = (e + aabb_max[1])/f
    49. if t1 > t2:
    50. t1, t2 = t2, t1
    51. if t2 < tmax:
    52. tmax = t2
    53. if t1 > tmin:
    54. tmin = t1
    55. if tmax < tmin:
    56. return (False, 0)
    57. else:
    58. if (-e + aabb_min[1] > 0.0 + EPSILON) or (-e+aabb_max[1] < 0.0 - EPSILON):
    59. return False, 0
    60. # intersection in z
    61. zaxis = numpy.array((modelmatrix[2, 0], modelmatrix[2, 1], modelmatrix[2, 2]))
    62. e = numpy.dot(zaxis, delta)
    63. f = numpy.dot(direction, zaxis)
    64. if math.fabs(f) > 0.0 + EPSILON:
    65. t1 = (e + aabb_min[2])/f
    66. t2 = (e + aabb_max[2])/f
    67. if t1 > t2:
    68. t1, t2 = t2, t1
    69. if t2 < tmax:
    70. tmax = t2
    71. if t1 > tmin:
    72. tmin = t1
    73. if tmax < tmin:
    74. return (False, 0)
    75. else:
    76. if (-e + aabb_min[2] > 0.0 + EPSILON) or (-e+aabb_max[2] < 0.0 - EPSILON):
    77. return False, 0
    78. return True, tmin
    79. def render(self):
    80. """ 渲染显示包围盒,可在调试的时候使用 """
    81. glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
    82. glMatrixMode(GL_MODELVIEW)
    83. glPushMatrix()
    84. glTranslated(self.center[0], self.center[1], self.center[2])
    85. glCallList(G_OBJ_CUBE)
    86. glPopMatrix()
    87. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

    更新 Node 类与 Scene 类,加入与选中节点有关的内容。更新 Node 类

    1. from aabb import AABB
    2. ...
    3. class Node(object):
    4. def __init__(self):
    5. self.color_index = random.randint(color.MIN_COLOR, color.MAX_COLOR)
    6. self.aabb = AABB([0.0, 0.0, 0.0], [0.5, 0.5, 0.5])
    7. self.translation_matrix = numpy.identity(4)
    8. self.scaling_matrix = numpy.identity(4)
    9. self.selected = False
    10. ...
    11. def render(self):
    12. glPushMatrix()
    13. glMultMatrixf(numpy.transpose(self.translation_matrix))
    14. glMultMatrixf(self.scaling_matrix)
    15. cur_color = color.COLORS[self.color_index]
    16. glColor3f(cur_color[0], cur_color[1], cur_color[2])
    17. if self.selected: # 选中的对象会发光
    18. glMaterialfv(GL_FRONT, GL_EMISSION, [0.3, 0.3, 0.3])
    19. self.render_self()
    20. if self.selected:
    21. glMaterialfv(GL_FRONT, GL_EMISSION, [0.0, 0.0, 0.0])
    22. glPopMatrix()
    23. def select(self, select=None):
    24. if select is not None:
    25. self.selected = select
    26. else:
    27. self.selected = not self.selected

    更新 Scene 类:

    1. class Scene(object):
    2. def __init__(self):
    3. self.node_list = list()
    4. self.selected_node = None

    在 Viewer 类中通过get_ray(), pick() 实现通过鼠标位置获取激光的函数以及 pick 函数

    1. # class Viewer
    2. def get_ray(self, x, y):
    3. """
    4. 返回光源和激光方向
    5. """
    6. self.init_view()
    7. glMatrixMode(GL_MODELVIEW)
    8. glLoadIdentity()
    9. # 得到激光的起始点
    10. start = numpy.array(gluUnProject(x, y, 0.001))
    11. end = numpy.array(gluUnProject(x, y, 0.999))
    12. # 得到激光的方向
    13. direction = end - start
    14. direction = direction / norm(direction)
    15. return (start, direction)
    16. def pick(self, x, y):
    17. """ 是否被选中以及哪一个被选中交由Scene下的pick处理 """
    18. start, direction = self.get_ray(x, y)
    19. self.scene.pick(start, direction, self.modelView)

    为了确定是哪个对象被选中,我们会遍历场景下的所有对象,检查激光是否与该对象相交,取离摄像机最近的对象为选中对象。

    1. # Scene 下实现
    2. def pick(self, start, direction, mat):
    3. """
    4. 参数中的mat为当前ModelView的逆矩阵,作用是计算激光在局部(对象)坐标系中的坐标
    5. """
    6. import sys
    7. if self.selected_node is not None:
    8. self.selected_node.select(False)
    9. self.selected_node = None
    10. # 找出激光击中的最近的节点。
    11. mindist = sys.maxsize
    12. closest_node = None
    13. for node in self.node_list:
    14. hit, distance = node.pick(start, direction, mat)
    15. if hit and distance < mindist:
    16. mindist, closest_node = distance, node
    17. # 如果找到了,选中它
    18. if closest_node is not None:
    19. closest_node.select()
    20. closest_node.depth = mindist
    21. closest_node.selected_loc = start + direction * mindist
    22. self.selected_node = closest_node
    23. # Node下的实现
    24. def pick(self, start, direction, mat):
    25. # 将modelview矩阵乘上节点的变换矩阵
    26. newmat = numpy.dot(
    27. numpy.dot(mat, self.translation_matrix),
    28. numpy.linalg.inv(self.scaling_matrix)
    29. )
    30. results = self.aabb.ray_hit(start, direction, newmat)
    31. return results

    检测包围盒也有其缺点,如下图所示,我们希望能点中球背后的立方体,然而却选中了立方体前的球体,因为我们的激光射中了球体的包围盒。为了效率我们牺牲了这部分功能。在性能,代码复杂度与功能准确度之间之间进行衡量与抉择是在计算机图形学与软件工程中常常会遇见的。

    操作场景中的对象

    对对象的操作主要包括在场景中加入新对象,移动对象、改变对象的颜色与改变对象的大小。因为这部分的实现较为简单,所以仅实现加入新对象与移动对象的操作。

    加入新对象的代码如下:

    1. # Viewer下的实现
    2. def place(self, shape, x, y):
    3. start, direction = self.get_ray(x, y)
    4. self.scene.place(shape, start, direction, self.inverseModelView)
    5. # Scene下的实现
    6. import numpy
    7. from node import Sphere, Cube, SnowFigure
    8. ...
    9. def place(self, shape, start, direction, inv_modelview):
    10. new_node = None
    11. if shape == 'sphere': new_node = Sphere()
    12. elif shape == 'cube': new_node = Cube()
    13. elif shape == 'figure': new_node = SnowFigure()
    14. self.add_node(new_node)
    15. # 得到在摄像机坐标系中的坐标
    16. translation = (start + direction * self.PLACE_DEPTH)
    17. # 转换到世界坐标系
    18. pre_tran = numpy.array([translation[0], translation[1], translation[2], 1])
    19. translation = inv_modelview.dot(pre_tran)
    20. new_node.translate(translation[0], translation[1], translation[2])

    移动目标对象的代码如下:

    1. # Viewer下的实现
    2. def move(self, x, y):
    3. start, direction = self.get_ray(x, y)
    4. self.scene.move_selected(start, direction, self.inverseModelView)
    5. # Scene下的实现
    6. def move_selected(self, start, direction, inv_modelview):
    7. if self.selected_node is None: return
    8. # 找到选中节点的坐标与深度(距离)
    9. node = self.selected_node
    10. depth = node.depth
    11. oldloc = node.selected_loc
    12. # 新坐标的深度保持不变
    13. newloc = (start + direction * depth)
    14. # 得到世界坐标系中的移动坐标差
    15. translation = newloc - oldloc
    16. pre_tran = numpy.array([translation[0], translation[1], translation[2], 0])
    17. translation = inv_modelview.dot(pre_tran)
    18. # 节点做平移变换
    19. node.translate(translation[0], translation[1], translation[2])
    20. node.selected_loc = newloc

    后续思考提升

    到这里我们就已经实现了一个简单的 3D 建模工具了,想一下这个程序还能在什么地方进行改进,或是增加一些新的功能?比如说:

    • 编写新的节点类,支持三角形网格能够组合成任意形状。
    • 增加一个撤销栈,支持撤销命令功能。
    • 能够保存/加载 3D 设计,比如保存为 DXF 3D 文件格式
    • 改进程序,选中目标更精准。

    你也可以从开源的 3D 建模软件汲取灵感,学习他人的技巧,比如参考三维动画制作软件 Blender 的建模部分,或是三维建模工具 OpenSCAD

  • 相关阅读:
    文举论金:黄金原油全面走势分析
    Python和Jupyter简介
    【无标题】
    用正则表达式简单解析JSON字符串
    经典双栈实现队列,注意遍历栈的判定条件修改。
    API 接口的安全设计验证:ticket,签名,时间戳
    python+django+vue图书馆选座系统pycharm源码lw
    python 使用enumerate()函数详解
    java:逆序排序的三种方法
    Pytorch学习系列--01基础&安装
  • 原文地址:https://blog.csdn.net/Swiss__Roll/article/details/140059893