一:主要的知识点
1、说明
本文只是教程内容的一小段,因博客字数限制,故进行拆分。主教程链接:vtk教程——逐行解析官网所有Python示例-CSDN博客
2、知识点纪要
本段代码主要涉及的有①如何通过设置材料的环境光系数来控制3D的着色效果
二:代码及注释
import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle from vtkmodules.vtkCommonColor import vtkNamedColors from vtkmodules.vtkFiltersSources import vtkSphereSource from vtkmodules.vtkRenderingCore import vtkActor, vtkLight, vtkPolyDataMapper, vtkRenderWindow, \ vtkRenderWindowInteractor, vtkRenderer def main(): colors = vtkNamedColors() colors.SetColor("bkg", [26, 51, 102, 255]) sphere = vtkSphereSource() sphere.SetThetaResolution(100) sphere.SetPhiResolution(50) sphereMapper = vtkPolyDataMapper() sphereMapper.SetInputConnection(sphere.GetOutputPort()) numberOfSpheres = 8 spheres = [] ambient = 0.125 diffuse = 0.0 specular = 0.0 position = [0, 0, 0] for i in range(numberOfSpheres): spheres.append(vtkActor()) spheres[i].SetMapper(sphereMapper) spheres[i].GetProperty().SetColor(colors.GetColor3d("Red")) """ SetAmbient 设置环境光 环境光无方向性,无位置性,无衰减,计算简单 I_ambienet = 物体的环境反射系数*环境光强度 """ spheres[i].GetProperty().SetAmbient(ambient) """ SetDiffuse 设置漫反射 描述的是粗糙表面把光线向各个方向均匀地反射的现象 漫反射与光线方向有关(表面越正对光线,反射光越强),与观察方向无关(无论从哪个角度看,亮度相同) 由表面法线决定(入射角越小(光越正),照亮越强) 直观理解: 想象阳光照在一堵墙上 墙面正对太阳 → 很亮; 墙面倾斜 → 变暗; 背对太阳 → 完全阴影。 漫反射是最主要的亮度来源 漫反射方程I_d = 物体表面的漫反射系数(材质属性) * 光源的强度 * max(0,光线与法线的夹角余弦值) """ spheres[i].GetProperty().SetDiffuse(diffuse) """ SetSpecular 设置镜面反射,其描述的是光在光滑表面上按特定方向反射的现象 镜面反射依赖于光源位置,表面法向量和相机位置 表面看起来有高光,像金属、玻璃或者水面上的光斑 镜面反射=材质的镜面反射系数*光源强度*(max(0, 光线关于法向量的反射方向*表面指向相机的方向))**2 """ spheres[i].GetProperty().SetSpecular(specular) spheres[i].AddPosition(position) ambient += 0.125 position[0] += 1.25 if i == 3: position[0] = 0 position[1] = 1.25 ren = vtkRenderer() renWin = vtkRenderWindow() renWin.AddRenderer(ren) iren = vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) for i in range(0, numberOfSpheres): ren.AddActor(spheres[i]) ren.SetBackground(colors.GetColor3d('bkg')) renWin.SetSize(640, 480) renWin.SetWindowName('AmbientSpheres') """ vtkLight 用于在渲染场景中添加光照,render可以有多个光源 可以设置光源的位置和方向 调整光的类型(点光源、方向光源、聚光灯等) 设置光的颜色、强度和衰减 与材质结合,产生漫反射和镜面反射效果 """ light = vtkLight() light.SetFocalPoint(1.875, 0.6125, 0) light.SetPosition(0.875, 1.6125, 1) ren.AddLight(light) ren.GetActiveCamera().SetFocalPoint(0, 0, 0) ren.GetActiveCamera().SetPosition(0, 0, 1) ren.GetActiveCamera().SetViewUp(0, 1, 0) ren.GetActiveCamera().ParallelProjectionOn() ren.ResetCamera() ren.GetActiveCamera().SetParallelScale(2.0) iren.Initialize() renWin.Render() iren.Start() if __name__ == '__main__': main()