コード例 #1
0
ファイル: show3d.py プロジェクト: nibill/BME-CAS
def extract(color, isovalue):
    skinExtractor = vtk.vtkDiscreteMarchingCubes()
    skinExtractor.SetInputConnection(dataImporter.GetOutputPort())
    skinExtractor.SetValue(0, isovalue)

    smooth = vtk.vtkSmoothPolyDataFilter()
    smooth.SetInputConnection(skinExtractor.GetOutputPort())
    smooth.SetNumberOfIterations(15)
    smooth.SetRelaxationFactor(0.2)
    smooth.FeatureEdgeSmoothingOff()
    smooth.BoundarySmoothingOn()
    smooth.Update()

    skinStripper = vtk.vtkStripper()
    skinStripper.SetInputConnection(smooth.GetOutputPort())

    skinMapper = vtk.vtkOpenGLPolyDataMapper()
    skinMapper.SetInputConnection(skinStripper.GetOutputPort())
    skinMapper.ScalarVisibilityOff()

    skin = vtk.vtkOpenGLActor()
    skin.SetMapper(skinMapper)
    skin.GetProperty().SetDiffuseColor(colors.GetColor3d(color))
    skin.GetProperty().SetSpecular(.3)
    skin.GetProperty().SetSpecularPower(20)
    return skin
コード例 #2
0
 def make_actor(self):
     self.mapper = vtk.vtkOpenGLPolyDataMapper()
     # normals
     normals = vtk.vtkPolyDataNormals()
     normals.SetInputData(self.vtk_obj)
     normals.ComputePointNormalsOn()
     normals.SplittingOff()
     normals.AutoOrientNormalsOn()
     normals.ConsistencyOn()
     normals.Update()
     self.mapper.SetInputData(normals.GetOutput())
     self.actor = vtk.vtkOpenGLActor()
     self.actor.SetMapper(self.mapper)
     self.actor.GetProperty().SetColor(self.colour)
     if self.vtk_args.wireframe:
         self.actor.GetProperty().SetRepresentationToWireframe()
     if self.alpha:
         self.actor.GetProperty().SetOpacity(self.alpha)
     if self.vtk_args.view_edges:
         self.actor.GetProperty().EdgeVisibilityOn()
         self.actor.GetProperty().SetEdgeColor(*self.edge_colour)
     # lighting and shading
     # self.actor.GetProperty().SetInterpolationToPhong()
     # self.actor.GetProperty().SetDiffuse(0.7)
     # self.actor.GetProperty().SetSpecular(0.5)
     # self.actor.GetProperty().SetSpecularPower(40)
     # self.actor.GetProperty().BackfaceCullingOn()
     # self.actor.GetProperty().FrontfaceCullingOn()
     return self.actor
コード例 #3
0
    def getCurrentPeelActor(self):
        colors = vtk.vtkNamedColors()

        # Create the color map
        colorLookupTable = vtk.vtkLookupTable()
        colorLookupTable.SetNumberOfColors(512)
        colorLookupTable.SetSaturationRange(0, 0)
        colorLookupTable.SetHueRange(0, 0)
        colorLookupTable.SetValueRange(0, 1)
        # colorLookupTable.SetTableRange(0, 1000)
        # colorLookupTable.SetTableRange(0, 250)
        colorLookupTable.SetTableRange(0, 200)
        # colorLookupTable.SetTableRange(0, 150)
        colorLookupTable.Build()

        # Set mapper auto
        mapper = vtk.vtkOpenGLPolyDataMapper()
        mapper.SetInputData(self.currentPeel)
        # mapper.SetScalarRange(0, 1000)
        # mapper.SetScalarRange(0, 250)
        mapper.SetScalarRange(0, 200)
        # mapper.SetScalarRange(0, 150)
        mapper.SetLookupTable(colorLookupTable)
        mapper.InterpolateScalarsBeforeMappingOn()

        # Set actor
        self.currentPeelActor.SetMapper(mapper)
        self.currentPeelActor.GetProperty().SetBackfaceCulling(1)
        self.currentPeelActor.GetProperty().SetOpacity(0.5)

        return self.currentPeelActor
コード例 #4
0
 def render(self, renderer):
     assert isinstance(renderer, vtk.vtkRenderer)
     if any([
             self._vtk_args.all_contours, self._vtk_args.x_contours,
             self._vtk_args.y_contours, self._vtk_args.z_contours
     ]):
         _d = list()
         if self._vtk_args.all_contours:
             _d = ['x', 'y', 'z']
         else:
             if self._vtk_args.x_contours:
                 _d += ['x']
             if self._vtk_args.y_contours:
                 _d += ['y']
             if self._vtk_args.z_contours:
                 _d += ['z']
     for d in _d:
         self.mapper = vtk.vtkOpenGLPolyDataMapper()
         self.mapper.SetInputData(getattr(self, '{}_vtkcontours'.format(d)))
         self.actor = vtk.vtkOpenGLActor()
         self.actor.SetMapper(self.mapper)
         self.actor.GetProperty().SetColor(1, 1, 0)
         self.actor.GetProperty().SetOpacity(1)
         renderer.AddActor(self.actor)
     return renderer
コード例 #5
0
def MakeActor(polydata):
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(polydata)

    #Disable VBO shfit and scale
    mapper.SetVBOShiftScaleMethod(0)
    actor = vtk.vtkOpenGLActor()
    actor.SetMapper(mapper)

    return actor
コード例 #6
0
def MakeActor(polydata):

    #Visualize
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(polydata)
    # mapper.SetFragmentShaderCode(frag)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
コード例 #7
0
 def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):
     self.maxNumPoints = maxNumPoints
     self.vtkPolyData = vtk.vtkPolyData()
     self.clearPoints()
     # mapper = vtk.vtkPolyDataMapper()
     mapper = vtk.vtkOpenGLPolyDataMapper()
     mapper.SetInputData(self.vtkPolyData)
     mapper.SetColorModeToDefault()
     mapper.SetScalarRange(zMin, zMax)
     mapper.SetScalarVisibility(1)
     self.vtkActor = vtk.vtkActor()
     self.vtkActor.SetMapper(mapper)
コード例 #8
0
def MakeActor(polydata):
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(polydata)

    # mapper.SetVertexShaderCode(VertexShaderText)
    # mapper.SetFragmentShaderCode(FragmentShaderText)
    polydata.GetPointData().RemoveArray("Normals")

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
コード例 #9
0
def load_maps(mol,rendmod,gfx,atomcol):
	mol.reader = vtk.vtkStructuredPointsReader()
	mol.reader.SetFileName(mol.mod.dfn)
	mol.reader.Update() #by calling Update() we read the file
	mol.iso = vtk.vtkMarchingContourFilter()
	mol.iso.UseScalarTreeOn()
	mol.iso.ComputeNormalsOn()
	mol.iso.SetInputConnection(mol.reader.GetOutputPort())
	mol.iso.SetValue(0,mol.mod.isov*mol.mod.sigavg[0]+mol.mod.sigavg[1])
	clean = vtk.vtkCleanPolyData()
  	clean.SetInputConnection(mol.iso.GetOutputPort())
 	clean.ConvertStripsToPolysOn()
	smooth = vtk.vtkWindowedSincPolyDataFilter()
 	smooth.SetInputConnection(clean.GetOutputPort())
 	smooth.BoundarySmoothingOn()
 	smooth.GenerateErrorVectorsOn()
  	smooth.GenerateErrorScalarsOn()
  	smooth.NormalizeCoordinatesOn()
  	smooth.NonManifoldSmoothingOn()
  	smooth.FeatureEdgeSmoothingOn()
  	smooth.SetEdgeAngle(90)
	smooth.SetFeatureAngle(90)
	smooth.Update()
	mol.mapper = vtk.vtkOpenGLPolyDataMapper()
	mol.mapper.SetInputConnection(smooth.GetOutputPort()) ### <- connection here
	mol.mapper.ScalarVisibilityOff()
	mol.mapper.Update()
	mol.acteur= vtk.vtkOpenGLActor()
	mol.acteur.SetMapper(mol.mapper)
	mol.acteur.GetProperty().SetColor(mol.col)
	if rendmod==5:
		mol.acteur.GetProperty().SetRepresentationToSurface()
	elif rendmod==6:
		mol.acteur.GetProperty().SetRepresentationToWireframe()
	elif rendmod==7:
		mol.acteur.GetProperty().SetRepresentationToPoints()
	else :
		mol.acteur.GetProperty().SetRepresentationToSurface()
	mol.acteur.GetProperty().SetInterpolationToGouraud()
	mol.acteur.GetProperty().SetSpecular(.4)
	mol.acteur.GetProperty().SetSpecularPower(10)
	gfx.renderer.AddActor(mol.acteur)
	gfx.renwin.Render()
コード例 #10
0
ファイル: dbsElectrode.py プロジェクト: behollis/DBSViewer
    def __init__(self, data, app=None):
        self.patient_data = data
        self.app = app
        self.centroid = None
        self.principal_dir = None
        self.vtavoxels = None
        self.polygonActor = None
        self.clabel = -1

        self.linethickness = 1.0
        self.falloff = 10.0

        self.gl_mapper = vtk.vtkOpenGLPolyDataMapper()
        self.actor = vtk.vtkOpenGLActor()
        self.polydata = vtk.vtkPolyData()

        self.findVTAVoxels()
        self.computeDataCentroid()
        self.computePrincipalDirection()
        self.generateVolumetricLine()
コード例 #11
0
def drawBrain(brain):
    colors = vtk.vtkNamedColors()

    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(brain)
    mapper.ScalarVisibilityOff()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    actor.GetProperty().SetColor(colors.GetColor4d("Pink").GetData())
    actor.GetProperty().SetOpacity(0.25)
    actor.GetProperty().SetShading(1)
    actor.GetProperty().SetSpecular(1)
    actor.GetProperty().SetSpecularPower(100)
    actor.GetProperty().SetAmbient(0)
    actor.GetProperty().SetDiffuse(1)
    actor.GetProperty().SetSpecularColor(colors.GetColor4d("White").GetData())
    actor.GetProperty().SetInterpolationToGouraud()
    actor.GetProperty().SetBackfaceCulling(1)

    return actor
コード例 #12
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the geometry of a point (the coordinate)
    points = vtk.vtkPoints()
    p = [65.0, -65.0, 0.0]
    q = [65.0, 65.0, 0.0]
    r = [-65.0, 65.0, 0.0]
    s = [-65.0, -65.0, 0.0]

    # Create the topology of the point (a vertex)
    vertices = vtk.vtkCellArray()
    # We need an an array of point id's for InsertNextCell.
    pid = [0, 1000, 0, 0]
    pid[0] = points.InsertNextPoint(p)
    pid[1] = points.InsertNextPoint(q)
    pid[2] = points.InsertNextPoint(r)
    pid[3] = points.InsertNextPoint(s)
    vertices.InsertNextCell(4, pid)

    # Create a polydata object
    point = vtk.vtkPolyData()

    # Set the points and vertices we created as the geometry and topology of the polydata
    point.SetPoints(points)
    point.SetVerts(vertices)

    # Visualize
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(point)

    mapper.SetGeometryShaderCode("""
        //VTK::System::Dec
        //VTK::PositionVC::Dec
        //VTK::PrimID::Dec
        //VTK::Color::Dec
        //VTK::Normal::Dec
        //VTK::Light::Dec
        //VTK::TCoord::Dec
        //VTK::Picking::Dec
        //VTK::DepthPeeling::Dec
        //VTK::Clip::Dec
        //VTK::Output::Dec
        layout(points) in;
        layout(line_strip, max_vertices = 11) out;
        const float PI = 3.1415926;
        void main() {
            for (int i = 0; i <= 10; i++) {
            float ang = PI * 2.0 / 10.0 * i;
            
            vec4 offset = vec4(cos(ang)*60, -sin(ang) * 80, 0.0, 0.0);
            gl_Position = gl_in[0].gl_Position + offset;
            EmitVertex();
            }
            EndPrimitive();
        }
    """)

    #    mapper.SetVertexShaderCode("""
    #        //VTK::System::Dec
    #        in vec2 pos;
    #        in vec3 color;
    #
    #        out vec3 vColor;
    #        //VTK::Normal::Dec
    #        void main()
    #        {
    #            gl_Position = vec4(pos, 0.0, 1.0);
    #            vColor = color;
    #        }
    #
    #    """)

    #

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    #    actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))
    actor.GetProperty().SetPointSize(2)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Point")
    renderWindow.SetSize(500, 500)
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Black"))

    renderWindow.Render()
    renderWindowInteractor.Start()
コード例 #13
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the geometry of a point (the coordinate)
    points = vtk.vtkPoints()
    p = [65.0, -65.0, 0.0]
    q = [65.0, 65.0, 0.0]
    r = [-65.0, 65.0, 0.0]
    s = [-65.0, -65.0, 0.0]

    # Create the topology of the point (a vertex)
    vertices = vtk.vtkCellArray()
    # We need an an array of point id's for InsertNextCell.
    pid = [0, 1000, 0, 0]
    pid[0] = points.InsertNextPoint(p)
    pid[1] = points.InsertNextPoint(q)
    pid[2] = points.InsertNextPoint(r)
    pid[3] = points.InsertNextPoint(s)
    vertices.InsertNextCell(4, pid)

    # Create a polydata object
    point = vtk.vtkPolyData()

    # Set the points and vertices we created as the geometry and
    # topology of the polydata
    point.SetPoints(points)
    point.SetVerts(vertices)

    # Create array of vertex colors
    colorArray = vtk.vtkUnsignedCharArray()
    colorArray.SetNumberOfTuples(4)
    colorArray.SetNumberOfComponents(3)
    colorArray.InsertTuple(0, (255, 0, 0))
    colorArray.InsertTuple(1, (0, 255, 0))
    colorArray.InsertTuple(2, (0, 0, 255))
    colorArray.InsertTuple(3, (255, 255, 255))
    point.GetPointData().SetScalars(colorArray)

    # Visualize
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(point)

    mapper.SetGeometryShaderCode("""
        //VTK::System::Dec
        //VTK::PositionVC::Dec
        //VTK::PrimID::Dec
        // declarations below aren't necessary because
        // they are already injected by PrimID template
        //in vec4 vertexColorVSOutput[];
        //out vec4 vertexColorGSOutput;
        //VTK::Color::Dec
        //VTK::Normal::Dec
        //VTK::Light::Dec
        //VTK::TCoord::Dec
        //VTK::Picking::Dec
        //VTK::DepthPeeling::Dec
        //VTK::Clip::Dec
        //VTK::Output::Dec
        layout(points) in;
        layout(line_strip, max_vertices = 11) out;
        const float PI = 3.1415926;
        void main() {
            vertexColorGSOutput = vertexColorVSOutput[0];

            for (int i = 0; i <= 10; i++) {
                float ang = PI * 2.0 / 10.0 * i;

                vec4 offset = vec4(cos(ang)*60, -sin(ang) * 60, 0.0, 0.0);
                gl_Position = gl_in[0].gl_Position + offset;

                EmitVertex();
            }
            EndPrimitive();
        }
    """)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    # actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))
    actor.GetProperty().SetPointSize(2)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Point")
    renderWindow.SetSize(500, 500)
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Black"))

    renderWindow.Render()
    renderWindowInteractor.Start()
コード例 #14
0
# This simple example shows how to do basic rendering and pipeline
# creation.

import vtk
# The colors module defines various useful colors.
from vtk.util.colors import tomato

# This creates a polygonal cylinder model with eight circumferential
# facets.
cylinder = vtk.vtkCylinderSource()
cylinder.SetResolution(8)

# The mapper is responsible for pushing the geometry into the graphics
# library. It may also do color mapping, if scalars or other
# attributes are defined.
cylinderMapper = vtk.vtkOpenGLPolyDataMapper()
cylinderMapper.SetInputConnection(cylinder.GetOutputPort())

# The actor is a grouping mechanism: besides the geometry (mapper), it
# also has a property, transformation matrix, and/or texture map.
# Here we set its color and rotate it -22.5 degrees.
cylinderActor = vtk.vtkActor()
cylinderActor.SetMapper(cylinderMapper)
cylinderActor.GetProperty().SetColor(tomato)
cylinderActor.RotateX(30.0)
cylinderActor.RotateY(-45.0)

shaderProperty = cylinderActor.GetShaderProperty()

# METHOD #1
# Modify the shader to color based on model normal
コード例 #15
0
ファイル: MeshSlice.py プロジェクト: abdullahsikder/VTK-Files
    def __init__(self, data_dir,reader):
        planes = vtk.vtkPlane()
        planeC = vtk.vtkPlaneCollection()
        planeC.AddItem(planes)
        # Stripper for getting smooth poly outlines,
        # gives circle and not random triangles
        stripper = vtk.vtkStripper()
        stripper.SetInputConnection(reader.GetOutputPort())
        # Clipper for PLANE
        
        clipper = vtk.vtkClipClosedSurface()
        clipper.SetInputConnection(stripper.GetOutputPort())
        clipper.SetClippingPlanes(planeC)
        clipMapper = vtk.vtkImageFlip()
        clipMapper = vtk.vtkPolyDataMapper()
        clipMapper.SetInputConnection(clipper.GetOutputPort())
        clipActor = vtk.vtkActor()
        clipActor.SetMapper(clipMapper)
        clipActor.GetProperty().SetColor(0.5,0.5,0.5)
        clipActor.GetProperty().SetOpacity(0.5)
        clipActor.SetPosition(0.001,0.001,0.001)

        clipperOutline = vtk.vtkClipClosedSurface()
        clipperOutline.SetInputConnection(stripper.GetOutputPort())
        clipperOutline.SetClippingPlanes(planeC)
        clipperOutline.GenerateFacesOff()
        clipperOutline.GenerateOutlineOn()
        innerNorms = vtk.vtkTriangleMeshPointNormals()
        innerNorms.SetInputConnection(reader.GetOutputPort())
        innerMapper = vtk.vtkOpenGLPolyDataMapper()
        innerMapper.SetInputConnection(innerNorms.GetOutputPort())
        innerActor = vtk.vtkActor()
        innerActor.SetMapper(innerMapper)

        clipperOutlineMapper = vtk.vtkPolyDataMapper()
        clipperOutlineMapper.SetInputConnection(clipperOutline.GetOutputPort())
        clipOutlineActor = vtk.vtkActor()
        clipOutlineActor.SetMapper(clipperOutlineMapper)
        clipOutlineActor.GetProperty().SetColor(0,1,0)
        clipOutlineActor.SetPosition(0.001,0.001,0.001)


        planeWidget = vtk.vtkImagePlaneWidget()
        planeWidget.SetInputConnection(reader.GetOutputPort())
        planeWidget.RestrictPlaneToVolumeOn()
        planeWidget.GetResliceOutput()
        rsx = planeWidget.GetResliceAxes()
        #planeWidget.SetSliceIndex(52)
        #planeWidget.SetOrigin(1,-1,-1)
        planeWidget.SetResliceInterpolateToLinear()
        self.clipActor = clipActor

        self.planes = planes
        self.planeWidget = planeWidget
        self.innerActor = innerActor
        self.clipOutlineActor = clipOutlineActor
        


        px = planeWidget.GetSlicePosition()
        #Cut(px)
            
            #clipActor.VisibilityOn()
        def UpdateMesh(obj, event):
            obj.GetNormal()
            self.planes.SetNormal(obj.GetNormal())
            self.planes.SetOrigin(obj.GetOrigin())
            self.clipActor.VisibilityOn()
            
        #planeWidget.AddObserver("EndInteractionEvent", CutMesh) 
        planeWidget.AddObserver("InteractionEvent", UpdateMesh)
        self.planeWidget = planeWidget
コード例 #16
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the geometry of a point (the coordinate)
    points = vtk.vtkPoints()
    p = [45.0, -45.0, 10.0]
    q = [45.0, 45.0, 10.0]
    r = [-45.0, 45.0, 10.0]
    s = [-45.0, -45.0, 10.0]

    # Create the topology of the point (a vertex)
    vertices = vtk.vtkCellArray()
    # We need an an array of point id's for InsertNextCell.
    pid = [0, 1000, 0, 0]
    pid[0] = points.InsertNextPoint(p)
    pid[1] = points.InsertNextPoint(q)
    pid[2] = points.InsertNextPoint(r)
    pid[3] = points.InsertNextPoint(s)
    vertices.InsertNextCell(4, pid)

    # Create a polydata object
    point = vtk.vtkPolyData()

    # Set the points and vertices we created as the geometry and topology of the polydata
    point.SetPoints(points)
    point.SetVerts(vertices)

    # Visualize
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(point)

    # mapper.AddShaderReplacement(
    # vtk.vtkShader.Geometry,
    # "//VTK::Normal::Dec", # replace the normal block
    # True, # before the standard replacements
    # "//VTK::Normal::Dec\n" # we still want the default
    # "  layout(points) in;\n"
    # "  layout(line_strip, max_vertices=2);\n", #but we add this
    # False # only do it once
    # )
    # mapper.AddShaderReplacement(
    # vtk.vtkShader.Geometry,
    # "//VTK::Normal::Impl", # replace the normal block
    # True, # before the standard replacements
    # "//VTK::Normal::Impl\n" # we still want the default
    # "  gl_Position = gl_in[0].gl_Position + vec4(-20.0, 0.0, 0.0, 0.0);\n", #but we add this
    # False # only do it once
    # )

    # # mapper.SetGeometryShaderCode(
    # # "//VTK::System::Dec\n"  # always start with this line
    # # "layout(points) in;\n"
    # # "layout(line_strip, max_vertices = 64) out;\n"
    # # "//VTK::Normal::Dec\n"
    # # "void main () {\n"
    # # "  gl_Position = gl_in[0].gl_Position + vec4(-80.0, 0.0, 0.0, 0.0);\n"
    # # " EmitVertex();\n"
    # # "EndPrimitive;\n"
    # # "}\n"
    # # )

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))
    actor.GetProperty().SetPointSize(2)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Point")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Black"))

    renderWindow.Render()
    renderWindowInteractor.Start()
コード例 #17
0
    def __init__(self, data_dir, Mreader, Vreader):
        # inv,inc,iniv,inxi,inxc Volume
        # in9,in99,inim,ins Actors
        planes = vtk.vtkPlane()
        #planes.SetOrigin(0,-1,0)
        #planes.SetNormal(1,0,0)
        planeC = vtk.vtkPlaneCollection()
        planeC.AddItem(planes)
        ######################################################
        # Strip, Clip, Mapper, Actor

        # Stripper for getting smooth poly outlines,
        # gives circle and not random triangles
        stripper = vtk.vtkStripper()
        stripper.SetInputConnection(Mreader.GetOutputPort())
        # Clipper for PLANE 1 Stripper 1
        clipper = vtk.vtkClipClosedSurface()
        clipper.SetInputConnection(stripper.GetOutputPort())

        #clip.Update()

        clipperOutline = vtk.vtkClipClosedSurface()
        clipperOutline.SetInputConnection(stripper.GetOutputPort())
        clipperOutline.SetClippingPlanes(planeC)
        clipperOutline.GenerateFacesOff()
        clipperOutline.GenerateOutlineOn()

        innerNorms = vtk.vtkTriangleMeshPointNormals()
        innerNorms.SetInputConnection(Mreader.GetOutputPort())
        innerMapper = vtk.vtkOpenGLPolyDataMapper()
        innerMapper.SetInputConnection(innerNorms.GetOutputPort())
        innerActor = vtk.vtkActor()
        innerActor.SetMapper(innerMapper)

        clipMapper = vtk.vtkImageFlip()
        clipMapper = vtk.vtkPolyDataMapper()
        clipMapper.SetInputConnection(clipper.GetOutputPort())
        clipActor = vtk.vtkActor()
        clipActor.SetMapper(clipMapper)
        clipActor.GetProperty().SetColor(1, 0.5, 0.5)
        clipActor.GetProperty().SetOpacity(0.5)
        clipActor.SetPosition(0.001, 0.001, 0.001)

        clipperOutlineMapper = vtk.vtkPolyDataMapper()
        clipperOutlineMapper.SetInputConnection(clipperOutline.GetOutputPort())
        clipOutlineActor = vtk.vtkActor()
        clipOutlineActor.SetMapper(clipperOutlineMapper)
        clipOutlineActor.GetProperty().SetColor(0, 1, 0)
        clipOutlineActor.SetPosition(0.001, 0.001, 0.001)

        tfun = vtk.vtkPiecewiseFunction()
        tfun.AddPoint(0, 0)
        tfun.AddPoint(1600, 0.05)
        tfun.AddPoint(2500, 0.15)
        tfun.AddPoint(2400, 0.0)
        tfun.AddPoint(2540, 0.97)

        volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
        volumeMapper.SetInputConnection(Vreader.GetOutputPort())
        volumeMapper.SetBlendModeToComposite()

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetScalarOpacity(tfun)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOn()

        newvol = vtk.vtkVolume()
        newvol.SetMapper(volumeMapper)
        newvol.SetProperty(volumeProperty)
        #######################
        planeWidget = vtk.vtkImagePlaneWidget()
        planeWidget.RestrictPlaneToVolumeOn()
        planeWidget.SetInputConnection(Mreader.GetOutputPort())
        planeWidget.RestrictPlaneToVolumeOn()
        planeWidget.GetResliceOutput()
        rsx = planeWidget.GetResliceAxes()
        #planeWidget.SetSliceIndex(52)
        #planeWidget.SetOrigin(1,-1,-1)
        planeWidget.SetResliceInterpolateToLinear()
        planeWidget.PlaceWidget()
        #planeWidget.SetInteractor(iren)

        px = planeWidget.GetSlicePosition()

        #Cut(px)

        #clipActor.VisibilityOn()
        def UpdateMesh(obj, event):
            #global planes, clipActor
            obj.GetNormal()
            planes.SetNormal(obj.GetNormal())
            planes.SetOrigin(obj.GetOrigin())
            clipper.SetClippingPlanes(planeC)
            clipActor.VisibilityOn()

        planesS = vtk.vtkPlanes()

        def ClipVolumeRender(obj, event):
            #global planes, volumeMapper
            planes.SetOrigin(obj.GetOrigin())
            x2 = obj.GetOrigin()[0]
            y2 = obj.GetOrigin()[1]
            z2 = obj.GetOrigin()[2]
            x3 = obj.GetPoint1()[0]
            y3 = obj.GetPoint1()[1]
            z3 = obj.GetPoint1()[2]
            x1 = obj.GetPoint2()[0]
            y1 = obj.GetPoint2()[1]
            z1 = obj.GetPoint2()[2]
            a1 = x2 - x1
            b1 = y2 - y1
            c1 = z2 - z1
            a2 = x3 - x1
            b2 = y3 - y1
            c2 = z3 - z1
            a = b1 * c2 - b2 * c1
            b = a2 * c1 - a1 * c2
            c = a1 * b2 - b1 * a2
            d = (-a * x1 - b * y1 - c * z1)

            #level1 = list([x,y,z,0,x,y,z,0,x,y,z,0,x,y,z,0,x,y,z,0,x,y,z,0])
            level1 = list([
                -a, -b, -c, -d, -a, -b, -c, -d, -a, -b, -c, -d, -a, -b, -c, -d,
                -a, -b, -c, -d, -a, -b, -c, -d
            ])
            print(a, b, c, d)
            planesS.SetFrustumPlanes(level1)

            #level2 = list([xMin,xMax, yMin,yMax,zMin,zMax])
            #planesS.SetBounds(level2)
            #planesS.SetNormals(obj.GetNormal())
            #planesS.GetPlane(0,planes)
            volumeMapper.SetClippingPlanes(planesS)
            #print(planesS.GetPoints())
            newvol.VisibilityOn()

        ClipVolumeRender(planeWidget, "STR")
        UpdateMesh(planeWidget, "STR")
        #planeWidget.AddObserver("EndInteractionEvent", CutMesh)
        #planeWidget.AddObserver("StartInteractionEvent", StartInteraction)
        planeWidget.AddObserver("InteractionEvent", UpdateMesh)
        #planeWidget.AddObserver("EndInteractionEvent", CutMesh)
        planeWidget.AddObserver("InteractionEvent", ClipVolumeRender)
        #planeWidget.AddObserver("EndInteractionEvent", EndInteraction)
        self.planeWidget = planeWidget
        #self.reader = reader
        self.clipActor = clipActor
        #ren1.AddActor(VActor)
        self.newvol = newvol
        self.clipOutlineActor = clipOutlineActor
コード例 #18
0
ファイル: Map.py プロジェクト: ggoret/VEDA
def load_map(gfx,mapfile,root,status,scale,rendtype,isov,opct,cropentry,nfv,vardeci,varsmooth,color,caller):
	if caller != 'fit':
		root.configure(cursor='watch')
		status.set('Map loading ... please wait')
	if mapfile =='' or mapfile == None or mapfile ==() :
		MB.showwarning('Info','Select map file')
		status.clear()
		root.configure(cursor='arrow')
		return
	try:
		gfx.renderer.RemoveActor(gfx.map[0].acteur)
		gfx.renderer.RemoveActor(gfx.map[0].box)
	except:
		pass
	if mapfile == 0:
		mapfile = gfx.map[0].fn
	if gfx.map == []:
		gfx.map = [Map()]
		gfx.map[0].id=0
	if 'map' in caller :
		clean_map(gfx) #supression des fichiers sort.s xudi et iudi
	if '.vtk' in mapfile:
		chdir(gfx.tmpdir)
		v2v_out='info_map'
		if caller != 'crop':
			gfx.map[0].sigma,gfx.map[0].avg = map_sigma_avg(v2v_out)
		if scale != gfx.map[0].scale:
			spc = None
			o = None
			f = open(mapfile,'r')
			for l in f:
				if l.startswith('SPACING'):
					spc = l.split()[1:4]
				if l.startswith('ORIGIN'):
					o = l.split()[1:4]
				if spc != None and o != None:
					break
			f.close()
			gfx.map[0].ratio = scale/gfx.map[0].scale
			if spc != None and o != None:
				system("sed -i -e /^SPACING/s/.*/'SPACING %f %f %f'/ %s"%(float(spc[0])*gfx.map[0].ratio,float(spc[1])*gfx.map[0].ratio,float(spc[2])*gfx.map[0].ratio,mapfile))
				system("sed -i -e /^ORIGIN/s/.*/'ORIGIN %f %f %f'/ %s"%(float(o[0])*gfx.map[0].ratio,float(o[1])*gfx.map[0].ratio,float(o[2])*gfx.map[0].ratio,mapfile))
		chdir(gfx.workdir)
	if '.ezd' in mapfile:
		chdir(gfx.tmpdir)
		mapfileout = extract_file_from_path(mapfile)[:-4]+'.vtk'
		e2v_out='info_map'
		system(gfx.vedabin+'/e2v.exe >> %s <<ENDOF\n%s  \n%f  \n%s  \nENDOF'%(e2v_out,mapfile,scale,mapfileout))
		mapfile = gfx.tmpdir + '/' + mapfileout
		gfx.map[0].sigma,gfx.map[0].avg = map_sigma_avg(e2v_out)
		chdir(gfx.workdir)
	gfx.map[0].fn = mapfile
	gfx.map[0].id = set_map_id(gfx)
	gfx.map[0].color = color
	gfx.map[0].oldscale = gfx.map[0].scale
	gfx.map[0].scale = scale
	if nfv !=None:
		nfv.set(extract_file_from_path(gfx.map[0].fn))
	reader = vtk.vtkStructuredPointsReader()
	reader.SetFileName(mapfile)
	reader.Update() #by calling Update() we read the file
	gfx.map[0].reader=reader
	iso = vtk.vtkMarchingContourFilter()
	iso.UseScalarTreeOn()
	iso.ComputeNormalsOn()
	iso.SetInputConnection(reader.GetOutputPort())
	iso.SetValue(0,isov*gfx.map[0].sigma+gfx.map[0].avg)
	gfx.map[0].iso=iso
	gfx.map[0].isov=isov
	if varsmooth == '1':
		#generate vectors
		clean = vtk.vtkCleanPolyData()
	  	clean.SetInputConnection(iso.GetOutputPort())
	 	clean.ConvertStripsToPolysOn()
		smooth = vtk.vtkWindowedSincPolyDataFilter()
	 	smooth.SetInputConnection(clean.GetOutputPort())
	 	smooth.BoundarySmoothingOn()
	 	smooth.GenerateErrorVectorsOn()
	  	smooth.GenerateErrorScalarsOn()
	  	smooth.NormalizeCoordinatesOn()
	  	smooth.NonManifoldSmoothingOn()
	  	smooth.FeatureEdgeSmoothingOn()
	  	smooth.SetEdgeAngle(90)
		smooth.SetFeatureAngle(90)
		smooth.Update()
	if vardeci=='1':
		deci = vtk.vtkDecimatePro()
		if varsmooth == '0':
			deci.SetInput(iso.GetOutput())
		else :
			deci.SetInput(smooth.GetOutput())
		deci.PreserveTopologyOn()
		deci.BoundaryVertexDeletionOn()
		deci.SplittingOn()
		deci.PreSplitMeshOn()
		deci.SetTargetReduction(0.97)
		gfx.map[0].isdeci='1'
		mapper = vtk.vtkOpenGLPolyDataMapper()
		mapper.SetInputConnection(deci.GetOutputPort())
	else :
		mapper = vtk.vtkOpenGLPolyDataMapper()
		if varsmooth == '1':
			mapper.SetInputConnection(smooth.GetOutputPort()) ### <- connection here
		else :
			mapper.SetInputConnection(iso.GetOutputPort())
		#mapper.SetInput(newpd) ### <- newpd connect there
		gfx.map[0].isdeci='0'
	mapper.ScalarVisibilityOff()
	mapper.Update()
	gfx.map[0].mapper=mapper
	actor = vtk.vtkOpenGLActor()
	actor.SetMapper(mapper)
	gfx.map[0].acteur=actor
	#actor.SetScale(scale,scale,scale) gerer differament
	actor.GetProperty().SetColor(gfx.map[0].color)
	actor.PickableOff()
	#definition de la box
	outline = vtk.vtkOutlineFilter()
        outline.SetInput(reader.GetOutput())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInput(outline.GetOutput())
	box=vtk.vtkActor()
        box.SetMapper( outlineMapper )
        box.GetProperty().SetColor((invcolor(gfx.map[0].color)))
        box.PickableOff()
	#box.SetScale(scale,scale,scale)
	gfx.map[0].box = box
	#get boxwidget bounds and set axes lenth
	(xmin,xmax,ymin,ymax,zmin,zmax)=box.GetBounds()
        x=abs(xmin-xmax)/2.0
	y=abs(ymin-ymax)/2.0
	z=abs(zmin-zmax)/2.0
	gfx.axes.SetTotalLength( x, y , z ) #defini la longeurs des axe
	init_cam_slab(gfx,(xmin,xmax,ymin,ymax,zmin,zmax)) #defini le slab correct
	gfx.map[0].rendtype=rendtype
	if rendtype=='Wireframe':
		actor.GetProperty().SetRepresentationToWireframe()
	elif rendtype=='Surface':
		actor.GetProperty().SetRepresentationToSurface()
	elif rendtype=='Points':
		actor.GetProperty().SetRepresentationToPoints()
		actor.GetProperty().SetPointSize(5)
	else :
		actor.GetProperty().SetRepresentationToWireframe()
	gfx.map[0].opct=opct
	actor.GetProperty().SetOpacity(opct)
	actor.GetProperty().SetInterpolationToGouraud()
	actor.GetProperty().SetSpecular(.4)
	actor.GetProperty().SetSpecularPower(10)
	if cropentry!=None:
		if gfx.crop==None:
			gfx.crop=Crop(gfx,iso,cropentry,None) #here entryval = None
	rendermap(gfx)
	#ajustement pour la symetry helicoidale
	if gfx.map[0].scale != gfx.map[0].oldscale:#changement de scale
		gfx.itf.propagate_scale(gfx,scale,caller)
		if gfx.ps != None:
			if gfx.ps.solidtype == 'Helicoidal':
				gfx.ps.display_tube(gfx,caller)
			elif gfx.ps.solidtype == 'Icosahedral' or gfx.ps.solidtype =='Octahedral' or gfx.ps.solidtype == 'Tetrahedral':
				gfx.ps.display_platonic(gfx,gfx.ps.ori)
			elif gfx.ps.solidtype =='Cn' or gfx.ps.solidtype == 'Dn':
				gfx.ps.display_Xn(gfx)
	if caller == 'crop':#crop uniquement helicoidal
		if gfx.ps != None:
			if gfx.ps.solidtype == 'Helicoidal':
				gfx.ps.display_tube(gfx,caller)
	if caller != 'fit':
		status.clear()
		root.configure(cursor='arrow')
コード例 #19
0
def display(volumes, args):
    """Display the volumes provided in the iterable

    This function relies on VTK to do the visualisation.

    :param list volumes: a list of either MAP, STA or TransformedSTA object
    :param args: command-line arguments
    :type args: argparse.Namespace
    """
    # display data
    # create an actor for each datum
    actors = list()
    for volume in volumes:
        # source
        vol = vtk.vtkImageData()
        z_size, y_size, x_size = volume.data.shape
        x_origin, y_origin, z_origin = volume.origin
        # this is a weirdly complex calculation
        # suppose I have a distance of size D (distance)
        # the index of the first position is S (start)
        # the index of the last position is E (end)
        # the relationship between these three values is
        # E - S + 1 = D
        # therefore, E = D + S - 1
        vol.SetExtent(
            x_origin, x_size + x_origin - 1,
            y_origin, y_size + y_origin - 1,
            z_origin, z_size + z_origin - 1,
        )
        vol.SetOrigin(x_origin, y_origin, z_origin)
        sp_x = volume.x_voxel_size
        sp_y = volume.y_voxel_size
        sp_z = volume.z_voxel_size
        vol.SetSpacing(sp_x, sp_y, sp_z)
        vol.AllocateScalars(vtk.VTK_FLOAT, 1)
        # voxel data
        print(f"Inserting voxel data...", end="")
        # numpy to vtk; https://pyscience.wordpress.com/2014/09/06/numpy-to-vtk-converting-your-numpy-arrays-to-vtk-arrays-and-files/
        voxels = vtk.util.numpy_support.numpy_to_vtk(volume.data.ravel(), deep=1, array_type=vtk.VTK_FLOAT)
        print(f"done!")
        vol.GetPointData().SetScalars(voxels)
        # contour
        contours = vtk.vtkContourFilter()
        contours.SetInputData(vol)
        contours.SetValue(0, args.contour_level)
        contours.Update()
        contoursOutput = contours.GetOutput()
        # data
        obj = vtk.vtkPolyData()
        obj.SetPoints(contoursOutput.GetPoints())
        obj.SetPolys(contoursOutput.GetPolys())
        # mapper
        mapper = vtk.vtkOpenGLPolyDataMapper()
        mapper.SetInputData(obj)
        # actor & transform
        actor = vtk.vtkOpenGLActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(volume.colour)
        actor.GetProperty().SetOpacity(volume.opacity)
        if isinstance(volume, TransformedSTA):
            transform = vtk.vtkTransform()
            matrix = vtk.vtkMatrix4x4()
            for i in range(4):
                for j in range(4):
                    matrix.SetElement(i, j, volume.transform[i, j])
            transform.SetMatrix(matrix)
            print(transform)
            actor.SetUserTransform(transform)
        actors += [actor]
    # renderer
    renderer = vtk.vtkOpenGLRenderer()
    [renderer.AddActor(actor) for actor in actors]
    # cube axes
    cubeAxesActor = vtk.vtkCubeAxesActor()
    cubeAxesActor.SetBounds(renderer.ComputeVisiblePropBounds())
    cubeAxesActor.SetCamera(renderer.GetActiveCamera())
    cubeAxesActor.SetFlyMode(4)
    cubeAxesActor.SetFlyModeToStaticEdges()  # how the cube axes will appear
    cubeAxesActor.GetTitleTextProperty(0).SetColor(1.0, 1.0, 1.0)
    cubeAxesActor.GetTitleTextProperty(1).SetColor(1.0, 1.0, 1.0)
    cubeAxesActor.GetTitleTextProperty(2).SetColor(1.0, 1.0, 1.0)
    cubeAxesActor.XAxisMinorTickVisibilityOff()
    cubeAxesActor.YAxisMinorTickVisibilityOff()
    cubeAxesActor.ZAxisMinorTickVisibilityOff()
    renderer.AddActor(cubeAxesActor)
    # rendererwindow
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    # render window interactor
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)
    render_window_interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
    axes_actor = vtk.vtkAxesActor()
    axes_widget = vtk.vtkOrientationMarkerWidget()
    axes_widget.SetOrientationMarker(axes_actor)
    axes_widget.SetViewport(0, 0, 0.2, 0.2)
    axes_widget.SetInteractor(render_window_interactor)
    axes_widget.SetEnabled(1)
    renderer.ResetCamera()
    # display
    render_window_interactor.Initialize()
    render_window_interactor.Start()
    return os.EX_OK
コード例 #20
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the geometry of a point (the coordinate)
    points = vtk.vtkPoints()
    p = [65.0, -65.0, 0.0]
    q = [65.0, 65.0, 0.0]
    r = [-65.0, 65.0, 0.0]
    s = [-65.0, -65.0, 0.0]

    # Create the topology of the point (a vertex)
    polys = vtk.vtkCellArray()
    # We need an an array of point id's for InsertNextCell.
    pid = [0, 1000, 0, 0]
    pid[0] = points.InsertNextPoint(p)
    pid[1] = points.InsertNextPoint(q)
    pid[2] = points.InsertNextPoint(r)
    pid[3] = points.InsertNextPoint(s)
    polys.InsertNextCell(4, pid)

    # Create a polydata object
    polydata = vtk.vtkPolyData()

    # Set the points and polys we created as the geometry and
    # topology of the polydata
    polydata.SetPoints(points)
    polydata.SetPolys(polys)

    # Create array of vertex colors
    colorArray = vtk.vtkUnsignedCharArray()
    colorArray.SetNumberOfTuples(4)
    colorArray.SetNumberOfComponents(3)
    colorArray.InsertTuple(0, (255, 0, 0))
    colorArray.InsertTuple(1, (0, 255, 0))
    colorArray.InsertTuple(2, (0, 0, 255))
    colorArray.InsertTuple(3, (255, 255, 255))
    polydata.GetPointData().SetScalars(colorArray)

    # Visualize
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(polydata)

    mapper.SetGeometryShaderCode("""
        //VTK::System::Dec
        //VTK::PositionVC::Dec
        uniform mat4 MCDCMatrix;
        uniform mat4 MCVCMatrix;
        //VTK::PrimID::Dec
        // declarations below aren't necessary because
        // they are already injected by PrimID template
        //in vec4 vertexColorVSOutput[];
        //out vec4 vertexColorGSOutput;
        //in vec4 vertexVCVSOutput[];
        //out vec4 vertexVCVSOutput;
        //VTK::Color::Dec
        //VTK::Normal::Dec
        //VTK::Light::Dec
        //VTK::TCoord::Dec
        //VTK::Picking::Dec
        //VTK::DepthPeeling::Dec
        //VTK::Clip::Dec
        //VTK::Output::Dec

        layout(lines) in;
        layout(triangle_strip, max_vertices = 5) out;

        void build_house(vec4 position)
        {
            vec4 point1 = vec4(-6.0, -6.0, 0.0, 0.0);
            vec4 point2 = vec4(6.0, -6.0, 0.0, 0.0);
            vec4 point3 = vec4(-6.0, 6.0, 0.0, 0.0);
            vec4 point4 = vec4(6.0, 6.0, 0.0, 0.0);
            vec4 point5 = vec4(0.0, 12.0, 0.0, 0.0);

            gl_Position = position + (MCDCMatrix * point1);
            vertexVCGSOutput = vertexVCVSOutput[0] + (MCVCMatrix * point1);
            EmitVertex();
            gl_Position = position + (MCDCMatrix * point2);
            vertexVCGSOutput = vertexVCVSOutput[0] + (MCVCMatrix * point2);
            EmitVertex();
            gl_Position = position + (MCDCMatrix * point3);
            vertexVCGSOutput = vertexVCVSOutput[0] + (MCVCMatrix * point3);
            EmitVertex();
            gl_Position = position + (MCDCMatrix * point4);
            vertexVCGSOutput = vertexVCVSOutput[0] + (MCVCMatrix * point4);
            EmitVertex();
            gl_Position = position + (MCDCMatrix * point5);
            vertexVCGSOutput = vertexVCVSOutput[0] + (MCVCMatrix * point5);
            EmitVertex();
            EndPrimitive();
        }

        void main() {
            vertexColorGSOutput = vertexColorVSOutput[0];
            build_house(gl_in[0].gl_Position);
        }
    """)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetRepresentationToWireframe()
    actor.GetProperty().SetPointSize(10)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Point")
    renderWindow.SetSize(500, 500)
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Black"))

    renderWindow.Render()
    renderWindowInteractor.Start()
コード例 #21
0
	def display_mod(self,mod):
		self.renderer.RemoveAllViewProps()
		if mod.type == 'mol':
			if mod.dspmodtype == 'CA':
				reader = vtk.vtkPDBReader()
				reader.SetFileName(mod.dfn)
				reader.SetHBScale(0)
				reader.SetBScale(4.0)
				mapper = vtk.vtkPolyDataMapper()
				mapper.SetInputConnection(reader.GetOutputPort())
				mapper.SetScalarModeToDefault()
				acteur = vtk.vtkActor()
				acteur.SetMapper(mapper)
			else: #all atoms or backbone case
				reader = vtk.vtkPDBReader()
				reader.SetFileName(mod.dfn)
				mapper = vtk.vtkPolyDataMapper()
				mapper.SetInputConnection(reader.GetOutputPort())
				mapper.SetScalarModeToDefault()
				acteur = vtk.vtkActor()
				acteur.SetMapper(mapper)
			self.camera.SetFocalPoint(0, 0, 0)
			self.camera.SetPosition(0, 0, 250)
		elif mod.type=='map':
			reader = vtk.vtkStructuredPointsReader()
			reader.SetFileName(mod.dfn)
			reader.Update() #by calling Update() we read the file
			iso = vtk.vtkMarchingContourFilter()
			iso.UseScalarTreeOn()
			iso.ComputeNormalsOn()
			iso.SetInputConnection(reader.GetOutputPort())
			iso.SetValue(0,mod.isov*mod.sigavg[0]+mod.sigavg[1])
			mapper = vtk.vtkOpenGLPolyDataMapper()
			mapper.SetInputConnection(iso.GetOutputPort()) ### <- connection here
			mapper.ScalarVisibilityOff()
			mapper.Update()
			acteur= vtk.vtkOpenGLActor()
			acteur.SetMapper(mapper)
			acteur.GetProperty().SetColor(0,0.35,1)
			if mod.rep=='Wireframe':
				acteur.GetProperty().SetRepresentationToWireframe()
			elif mod.rep=='Surface':
				acteur.GetProperty().SetRepresentationToSurface()
			else :
				acteur.GetProperty().SetRepresentationToWireframe()
			acteur.GetProperty().SetInterpolationToGouraud()
			acteur.GetProperty().SetSpecular(.4)
			acteur.GetProperty().SetSpecularPower(10)
			(xmin,xmax,ymin,ymax,zmin,zmax)=acteur.GetBounds()
			maxi=max(xmax-xmin,ymax-ymin,zmax-zmin)
			mini=min(xmax-xmin,ymax-ymin,zmax-zmin)
			fp=((xmax+xmin)/2.,(ymax+ymin)/2.,(zmax+zmin)/2.)
			self.camera.SetFocalPoint(fp[0],fp[1],fp[2])
			self.camera.SetPosition(fp[0],fp[1],fp[2]+(zmax-zmin)*4.)
		else :
			print 'strange Error in mod.type'
		(xl, xu, yl, yu, zl, zu)=acteur.GetBounds()
		mod.coldist = min(xu-xl,yu-yl,zu-zl)/2.
		mod.sphdist = max(xu-xl,yu-yl,zu-zl)/2.
		self.renderer.AddActor(acteur)
		self.renderer.ResetCameraClippingRange()
		self.renwin.Render()
コード例 #22
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the geometry of a point (the coordinate)
    points = vtk.vtkPoints()
    p = [65.0, -65.0, 0.0]
    q = [65.0, 65.0, 0.0]
    r = [-65.0, 65.0, 0.0]
    s = [-65.0, -65.0, 0.0]

    # Create the topology of the point (a vertex)
    vertices = vtk.vtkCellArray()
    # We need an an array of point id's for InsertNextCell.
    pid = [0, 1000, 0, 0]
    pid[0] = points.InsertNextPoint(p)
    pid[1] = points.InsertNextPoint(q)
    pid[2] = points.InsertNextPoint(r)
    pid[3] = points.InsertNextPoint(s)
    vertices.InsertNextCell(4, pid)

    # Create a polydata object
    point = vtk.vtkPolyData()

    # Set the points and vertices we created as the geometry and
    # topology of the polydata
    point.SetPoints(points)
    point.SetVerts(vertices)

    # Create array of vertex colors
    colorArray = vtk.vtkUnsignedCharArray()
    colorArray.SetNumberOfTuples(4)
    colorArray.SetNumberOfComponents(3)
    colorArray.InsertTuple(0, (255, 0, 0))
    colorArray.InsertTuple(1, (0, 255, 0))
    colorArray.InsertTuple(2, (0, 0, 255))
    colorArray.InsertTuple(3, (255, 255, 255))
    point.GetPointData().SetScalars(colorArray)

    # Visualize
    mapper = vtk.vtkOpenGLPolyDataMapper()
    mapper.SetInputData(point)

    mapper.SetGeometryShaderCode("""
        //VTK::System::Dec
        //VTK::PositionVC::Dec
        uniform mat4 MCDCMatrix;
        //VTK::PrimID::Dec
        // declarations below aren't necessary because
        // they are already injected by PrimID template
        //in vec4 vertexColorVSOutput[];
        //out vec4 vertexColorGSOutput;
        //VTK::Color::Dec
        //VTK::Normal::Dec
        //VTK::Light::Dec
        //VTK::TCoord::Dec
        //VTK::Picking::Dec
        //VTK::DepthPeeling::Dec
        //VTK::Clip::Dec
        //VTK::Output::Dec
        layout(points) in;
        layout(triangle_strip, max_vertices = 256) out;
        int resolution=4;
        int radius = 20;
        void build_house(vec4 position, vec4 vert1, vec4 vert2, vec4 vert3)
        {
            gl_Position = position + (MCDCMatrix * vert1);
            EmitVertex();
            gl_Position = position + (MCDCMatrix * vert2);
            EmitVertex();
            gl_Position = position + (MCDCMatrix * vert3);
            EmitVertex();
            EndPrimitive();
        }
        void main() {
            vertexColorGSOutput = vertexColorVSOutput[0];
            for(int i=0; i<resolution; i++){
                for(int j=0; j<resolution; j++){
                    float theta_1 = (3.1415 * 2.0)/(resolution) * i;
                    float theta_2 = (3.1415 * 2.0)/(resolution) * (i+1);
                    float phi_1 = (3.1415)/(resolution) * j;
                    float phi_2 = (3.1415)/(resolution) * (j+1);
                    vec4 a = vec4(radius*sin(phi_1)*cos(theta_1), radius*sin(phi_1)*sin(theta_1), radius*cos(phi_1), 0);
                    vec4 b = vec4(radius*sin(phi_1)*cos(theta_2), radius*sin(phi_1)*sin(theta_2), radius*cos(phi_1), 0);
                    vec4 c = vec4(radius*sin(phi_2)*cos(theta_1), radius*sin(phi_2)*sin(theta_1), radius*cos(phi_2), 0);
                    vec4 d = vec4(radius*sin(phi_2)*cos(theta_2), radius*sin(phi_2)*sin(theta_2), radius*cos(phi_2), 0);
                    //vec4 a = vec4(60.0, 60.0, 0.0, 0.0);
                    //vec4 b = vec4(0.0, 60.0, 0.0, 0.0);
                    //vec4 c = vec4(60.0, 0.0, 0.0, 0.0);
                    build_house(gl_in[0].gl_Position, a, b, c);
                    build_house(gl_in[0].gl_Position, b, d, c);
                }
            }
            //build_house(gl_in[0].gl_Position, vec4(60.0, 60.0, 60.0, 0.0), vec4(61.0, 60.0, 0.0, 0.0), vec4(60.0, 0.0, 0.0, 0.0));
            //build_house(gl_in[0].gl_Position, vec4(80.0, -80.0, 0.0, 0.0));
        }
    """)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    # actor.GetProperty().SetColor(colors.GetColor3d("Tomato"))
    actor.GetProperty().SetPointSize(2)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
#    renderWindow.SetWindowName("Point")
    renderWindow.SetSize(500, 500)
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Black"))

    renderWindow.Render()
    renderWindowInteractor.Start()
コード例 #23
0
ファイル: TestUserShader2.py プロジェクト: Kitware/VTK
renWin = vtk.vtkRenderWindow()
renWin.SetSize(400, 400)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
ren = vtk.vtkRenderer()
ren.SetBackground(0.0, 0.0, 0.0)
ren.GradientBackgroundOn()
renWin.AddRenderer(ren)
actor = vtk.vtkActor()
ren.AddActor(actor)
reader = vtk.vtkPLYReader()
reader.SetFileName("" + str(vtkGetDataRoot()) + "/Data/dragon.ply")
norms = vtk.vtkTriangleMeshPointNormals()
norms.SetInputConnection(reader.GetOutputPort())
mapper = vtk.vtkOpenGLPolyDataMapper()
mapper.SetInputConnection(norms.GetOutputPort())
actor.SetMapper(mapper)
actor.GetProperty().SetAmbientColor(0.2, 0.2, 1.0)
actor.GetProperty().SetDiffuseColor(1.0, 0.65, 0.7)
actor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
actor.GetProperty().SetSpecular(0.5)
actor.GetProperty().SetDiffuse(0.7)
actor.GetProperty().SetAmbient(0.5)
actor.GetProperty().SetSpecularPower(20.0)
actor.GetProperty().SetOpacity(1.0)

sp = actor.GetShaderProperty()
sp.SetVertexShaderCode(
    "//VTK::System::Dec\n"
    "in vec4 vertexMC;\n"
コード例 #24
0
def load_map(gfx, mapfile, root, status, scale, rendtype, isov, opct,
             cropentry, nfv, vardeci, varsmooth, color, caller):
    if caller != 'fit':
        root.configure(cursor='watch')
        status.set('Map loading ... please wait')
    if mapfile == '' or mapfile == None or mapfile == ():
        MB.showwarning('Info', 'Select map file')
        status.clear()
        root.configure(cursor='arrow')
        return
    try:
        gfx.renderer.RemoveActor(gfx.map[0].acteur)
        gfx.renderer.RemoveActor(gfx.map[0].box)
    except:
        pass
    if mapfile == 0:
        mapfile = gfx.map[0].fn
    if gfx.map == []:
        gfx.map = [Map()]
        gfx.map[0].id = 0
    if 'map' in caller:
        clean_map(gfx)  #supression des fichiers sort.s xudi et iudi
    if '.vtk' in mapfile:
        chdir(gfx.tmpdir)
        v2v_out = 'info_map'
        if caller != 'crop':
            gfx.map[0].sigma, gfx.map[0].avg = map_sigma_avg(v2v_out)
        if scale != gfx.map[0].scale:
            spc = None
            o = None
            f = open(mapfile, 'r')
            for l in f:
                if l.startswith('SPACING'):
                    spc = l.split()[1:4]
                if l.startswith('ORIGIN'):
                    o = l.split()[1:4]
                if spc != None and o != None:
                    break
            f.close()
            gfx.map[0].ratio = scale / gfx.map[0].scale
            if spc != None and o != None:
                system("sed -i -e /^SPACING/s/.*/'SPACING %f %f %f'/ %s" %
                       (float(spc[0]) * gfx.map[0].ratio,
                        float(spc[1]) * gfx.map[0].ratio,
                        float(spc[2]) * gfx.map[0].ratio, mapfile))
                system("sed -i -e /^ORIGIN/s/.*/'ORIGIN %f %f %f'/ %s" %
                       (float(o[0]) * gfx.map[0].ratio,
                        float(o[1]) * gfx.map[0].ratio,
                        float(o[2]) * gfx.map[0].ratio, mapfile))
        chdir(gfx.workdir)
    if '.ezd' in mapfile:
        chdir(gfx.tmpdir)
        mapfileout = extract_file_from_path(mapfile)[:-4] + '.vtk'
        e2v_out = 'info_map'
        system(gfx.vedabin +
               '/e2v.exe >> %s <<ENDOF\n%s  \n%f  \n%s  \nENDOF' %
               (e2v_out, mapfile, scale, mapfileout))
        mapfile = gfx.tmpdir + '/' + mapfileout
        gfx.map[0].sigma, gfx.map[0].avg = map_sigma_avg(e2v_out)
        chdir(gfx.workdir)
    gfx.map[0].fn = mapfile
    gfx.map[0].id = set_map_id(gfx)
    gfx.map[0].color = color
    gfx.map[0].oldscale = gfx.map[0].scale
    gfx.map[0].scale = scale
    if nfv != None:
        nfv.set(extract_file_from_path(gfx.map[0].fn))
    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(mapfile)
    reader.Update()  #by calling Update() we read the file
    gfx.map[0].reader = reader
    iso = vtk.vtkMarchingContourFilter()
    iso.UseScalarTreeOn()
    iso.ComputeNormalsOn()
    iso.SetInputConnection(reader.GetOutputPort())
    iso.SetValue(0, isov * gfx.map[0].sigma + gfx.map[0].avg)
    gfx.map[0].iso = iso
    gfx.map[0].isov = isov
    if varsmooth == '1':
        #generate vectors
        clean = vtk.vtkCleanPolyData()
        clean.SetInputConnection(iso.GetOutputPort())
        clean.ConvertStripsToPolysOn()
        smooth = vtk.vtkWindowedSincPolyDataFilter()
        smooth.SetInputConnection(clean.GetOutputPort())
        smooth.BoundarySmoothingOn()
        smooth.GenerateErrorVectorsOn()
        smooth.GenerateErrorScalarsOn()
        smooth.NormalizeCoordinatesOn()
        smooth.NonManifoldSmoothingOn()
        smooth.FeatureEdgeSmoothingOn()
        smooth.SetEdgeAngle(90)
        smooth.SetFeatureAngle(90)
        smooth.Update()
    if vardeci == '1':
        deci = vtk.vtkDecimatePro()
        if varsmooth == '0':
            deci.SetInput(iso.GetOutput())
        else:
            deci.SetInput(smooth.GetOutput())
        deci.PreserveTopologyOn()
        deci.BoundaryVertexDeletionOn()
        deci.SplittingOn()
        deci.PreSplitMeshOn()
        deci.SetTargetReduction(0.97)
        gfx.map[0].isdeci = '1'
        mapper = vtk.vtkOpenGLPolyDataMapper()
        mapper.SetInputConnection(deci.GetOutputPort())
    else:
        mapper = vtk.vtkOpenGLPolyDataMapper()
        if varsmooth == '1':
            mapper.SetInputConnection(
                smooth.GetOutputPort())  ### <- connection here
        else:
            mapper.SetInputConnection(iso.GetOutputPort())
        #mapper.SetInput(newpd) ### <- newpd connect there
        gfx.map[0].isdeci = '0'
    mapper.ScalarVisibilityOff()
    mapper.Update()
    gfx.map[0].mapper = mapper
    actor = vtk.vtkOpenGLActor()
    actor.SetMapper(mapper)
    gfx.map[0].acteur = actor
    #actor.SetScale(scale,scale,scale) gerer differament
    actor.GetProperty().SetColor(gfx.map[0].color)
    actor.PickableOff()
    #definition de la box
    outline = vtk.vtkOutlineFilter()
    outline.SetInput(reader.GetOutput())
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInput(outline.GetOutput())
    box = vtk.vtkActor()
    box.SetMapper(outlineMapper)
    box.GetProperty().SetColor((invcolor(gfx.map[0].color)))
    box.PickableOff()
    #box.SetScale(scale,scale,scale)
    gfx.map[0].box = box
    #get boxwidget bounds and set axes lenth
    (xmin, xmax, ymin, ymax, zmin, zmax) = box.GetBounds()
    x = abs(xmin - xmax) / 2.0
    y = abs(ymin - ymax) / 2.0
    z = abs(zmin - zmax) / 2.0
    gfx.axes.SetTotalLength(x, y, z)  #defini la longeurs des axe
    init_cam_slab(
        gfx, (xmin, xmax, ymin, ymax, zmin, zmax))  #defini le slab correct
    gfx.map[0].rendtype = rendtype
    if rendtype == 'Wireframe':
        actor.GetProperty().SetRepresentationToWireframe()
    elif rendtype == 'Surface':
        actor.GetProperty().SetRepresentationToSurface()
    elif rendtype == 'Points':
        actor.GetProperty().SetRepresentationToPoints()
        actor.GetProperty().SetPointSize(5)
    else:
        actor.GetProperty().SetRepresentationToWireframe()
    gfx.map[0].opct = opct
    actor.GetProperty().SetOpacity(opct)
    actor.GetProperty().SetInterpolationToGouraud()
    actor.GetProperty().SetSpecular(.4)
    actor.GetProperty().SetSpecularPower(10)
    if cropentry != None:
        if gfx.crop == None:
            gfx.crop = Crop(gfx, iso, cropentry, None)  #here entryval = None
    rendermap(gfx)
    #ajustement pour la symetry helicoidale
    if gfx.map[0].scale != gfx.map[0].oldscale:  #changement de scale
        gfx.itf.propagate_scale(gfx, scale, caller)
        if gfx.ps != None:
            if gfx.ps.solidtype == 'Helicoidal':
                gfx.ps.display_tube(gfx, caller)
            elif gfx.ps.solidtype == 'Icosahedral' or gfx.ps.solidtype == 'Octahedral' or gfx.ps.solidtype == 'Tetrahedral':
                gfx.ps.display_platonic(gfx, gfx.ps.ori)
            elif gfx.ps.solidtype == 'Cn' or gfx.ps.solidtype == 'Dn':
                gfx.ps.display_Xn(gfx)
    if caller == 'crop':  #crop uniquement helicoidal
        if gfx.ps != None:
            if gfx.ps.solidtype == 'Helicoidal':
                gfx.ps.display_tube(gfx, caller)
    if caller != 'fit':
        status.clear()
        root.configure(cursor='arrow')
コード例 #25
0
# files = ["wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg"]

for i in range(6):
    imgReader = vtk.vtkJPEGReader()
    imgReader.SetFileName(files[i])

    flip = vtk.vtkImageFlip()
    flip.SetInputConnection(imgReader.GetOutputPort())
    flip.SetFilteredAxis(1)
    texture.SetInputConnection(i, flip.GetOutputPort())

# imgReader = vtk.vtkJPEGReader()
# imgReader.SetFileName(file)
# texture.SetInputConnection(0, imgReader.GetOutputPort())

s_mapper = vtk.vtkOpenGLPolyDataMapper()
s_mapper.SetInputConnection(norms.GetOutputPort())

h_actor = vtk.vtkActor()
scene.add(h_actor)
h_actor.SetTexture(texture)
h_actor.SetMapper(s_mapper)

# // Add new code in default VTK vertex shader
s_mapper.AddShaderReplacement(
    vtk.vtkShader.Vertex,
    "//VTK::PositionVC::Dec",  #// replace the normal block
    True,  #// before the standard replacements
    "//VTK::PositionVC::Dec\n"  #// we still want the default
    "out vec3 TexCoords;\n",
    False  #// only do it once
# Set the points and polys we created as the geometry and
# topology of the polydata
polydata.SetPoints(points)
polydata.SetPolys(polys)

# Create array of vertex colors
colorArray = vtk.vtkUnsignedCharArray()
colorArray.SetNumberOfTuples(number_of_Spheres)
colorArray.SetNumberOfComponents(3)
for h in range(number_of_Spheres):
    colorArray.InsertTuple(h, (random.uniform(0, 255), random.uniform(
        0, 255), random.uniform(0, 255)))
polydata.GetPointData().SetScalars(colorArray)

# Visualize
mapper = vtk.vtkOpenGLPolyDataMapper()
mapper.SetInputData(polydata)

mapper2 = vtk.vtkOpenGLPolyDataMapper()
mapper2.SetInputData(polydata)

mapper3 = vtk.vtkOpenGLPolyDataMapper()
mapper3.SetInputData(polydata)

mapper4 = vtk.vtkOpenGLPolyDataMapper()
mapper4.SetInputData(polydata)

#LOAD THE DIPY 100 Repulsion FILE
sphere = np.load('/home/geek-at-work/dipy/dipy/data/files/repulsion100.npz')
faces = sphere['faces'].astype('i8')
vertices = sphere['vertices']