예제 #1
0
파일: cad_mesh.py 프로젝트: lcpt/xc
def VtkDefineActorKPoint(recordGrid, renderer, radius):
  '''Returns a vtkActor to represent key-points in a rendering scene.
  It defines the scale, orientation, rendering properties, textures, ...
  
  :ivar recordGrid: unstructured grid (generic data set) to which incorporate
                    the actor KPoint
  :ivar renderer:   name of the renderer (lights, views, ...) to be used in the
                    display
  :ivar radius:     radius of the spheres to be employed in the KPoints 
                    representation
  '''
  sphereSource= vtk.vtkSphereSource()
  sphereSource.SetRadius(radius)
  sphereSource.SetThetaResolution(5)
  sphereSource.SetPhiResolution(5)
  
  markKPts= vtk.vtkGlyph3D()
  markKPts.SetInputData(recordGrid.uGrid) 
  markKPts.SetSourceData(sphereSource.GetOutput())
  markKPts.ScalingOff()
  markKPts.OrientOff()
    
  mappKPts= vtk.vtkPolyDataMapper()
  mappKPts.SetInputData(markKPts.GetOutput())

  visKPts= vtk.vtkActor()
  visKPts.SetMapper(mappKPts)
  visKPts.GetProperty().SetColor(.7, .5, .5)
    
  renderer.AddActor(visKPts)
    def create_glyph(self,plane_mapper):
        #in here we do the arrows
        arrows = vtk.vtkArrowSource()


        ptMask = vtk.vtkMaskPoints()
        ptMask.SetInputConnection(plane_mapper.GetOutputPort())
        ptMask.SetOnRatio(10)
        ptMask.RandomModeOn()

        #in here we do the glyohs
        glyph = vtk.vtkGlyph3D()
        glyph.SetSourceConnection(arrows.GetOutputPort())
        glyph.SetInputConnection(ptMask.GetOutputPort())
        glyph.SetColorModeToColorByVector()
        glyph.SetScaleFactor(20)


        #Glyph mapper
        gly_mapper = vtk.vtkPolyDataMapper()
        gly_mapper.SetInputConnection(glyph.GetOutputPort())
        gly_mapper.SetLookupTable(self.arrowColor)


        #glyph actor
        gly_actor = vtk.vtkActor()
        gly_actor.SetMapper(gly_mapper)

        return gly_actor
예제 #3
0
    def get_actor(self):

        # cone.SetResolution(5)
        # cone.SetHeight(2)


        self.glyphs = vtk.vtkGlyph3D()
        self.glyphs.SetSourceConnection(self.e_glyph_shape.GetOutputPort())
        self.glyphs.SetColorModeToColorByScalar()

        self.centroidsPD = vtk.vtkPolyData()
        self.centroidsPD.SetPoints(self.electrode_points)
        self.centroidsPD.GetPointData().SetScalars(self.electrode_colors)

        if vtk_major_version == 5:

            self.glyphs.SetInput(self.centroidsPD)


        else:
            self.glyphs.SetInputData(self.centroidsPD)

        self.glyphsMapper = vtk.vtkPolyDataMapper()
        self.glyphsMapper.SetInputConnection(self.glyphs.GetOutputPort())

        self.glyphs.ScalingOff()  # IMPORTANT
        self.glyphs.Update()

        self.electrodes_actor = vtk.vtkActor()
        self.electrodes_actor.SetMapper(self.glyphsMapper)

        return self.electrodes_actor
예제 #4
0
def get_electrode_glyphs(e_pts, e_colors):
    e_glyph_shape = vtk.vtkSphereSource()

    # cone.SetResolution(5)
    # cone.SetHeight(2)
    e_glyph_shape.SetRadius(3.0)

    glyphs = vtk.vtkGlyph3D()
    glyphs.SetSourceConnection(e_glyph_shape.GetOutputPort())
    glyphs.SetColorModeToColorByScalar()

    centroidsPD = vtk.vtkPolyData()
    centroidsPD.SetPoints(e_pts)
    centroidsPD.GetPointData().SetScalars(e_colors)

    if vtk_major_version == 5:

        glyphs.SetInput(centroidsPD)


    else:
        glyphs.SetInputData(centroidsPD)

    glyphs.ScalingOff()  # IMPORTANT
    glyphs.Update()

    glyphs.ScalingOff()  # IMPORTANT
    glyphs.Update()

    return glyphs
예제 #5
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkGlyph3D(), 'Processing.',
         ('vtkDataSet', 'vtkPolyData'), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
예제 #6
0
 def __init__ (self, mod_m): 
     debug ("In VelocityVector::__init__ ()")
     Common.state.busy ()
     Base.Objects.Module.__init__ (self, mod_m)
     self.glyph2d_src = vtk.vtkGlyphSource2D ()
     self.cone = vtk.vtkConeSource ()
     self.arrow = vtk.vtkArrowSource ()
     self.glyph_src = self.cone
     self.glyph3d = vtk.vtkGlyph3D ()
     self.mapper = self.map = vtk.vtkPolyDataMapper ()
     self.actor = self.act = vtk.vtkActor ()
     # used to orient the cone properly
     self.glph_trfm = vtk.vtkTransformFilter ()
     self.glph_trfm.SetTransform (vtk.vtkTransform ())
     self.data_out = self.mod_m.GetOutput ()
     
     # Point of glyph that is attached -- -1 is tail, 0 is center,
     # 1 is head.
     self.glyph_pos = -1 
     self.scale = 1.0
     self.color_mode = 2 #2 is vector, 1 is scalar, -1 none
     self._initialize ()
     self._gui_init ()
     self.renwin.Render ()
     Common.state.idle ()
예제 #7
0
    def render(self, pointsData, scalarsArray, radiusArray, nspecies, colouringOptions, atomScaleFactor, lut):
        """
        Render the given antisites (wire frame).
        
        """
        self._logger.debug("Rendering antisites: colour by '%s'", colouringOptions.colourBy)

        # points
        points = vtk.vtkPoints()
        points.SetData(pointsData.getVTK())

        # poly data
        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.GetPointData().AddArray(scalarsArray.getVTK())
        polydata.GetPointData().SetScalars(radiusArray.getVTK())

        # source
        cubeSource = vtk.vtkCubeSource()
        edges = vtk.vtkExtractEdges()
        edges.SetInputConnection(cubeSource.GetOutputPort())
        glyphSource = vtk.vtkTubeFilter()
        glyphSource.SetInputConnection(edges.GetOutputPort())
        glyphSource.SetRadius(0.05)
        glyphSource.SetVaryRadius(0)
        glyphSource.SetNumberOfSides(5)
        glyphSource.UseDefaultNormalOn()
        glyphSource.SetDefaultNormal(0.577, 0.577, 0.577)

        # glyph
        glyph = vtk.vtkGlyph3D()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            glyph.SetSource(glyphSource.GetOutput())
            glyph.SetInput(polydata)
        else:
            glyph.SetSourceConnection(glyphSource.GetOutputPort())
            glyph.SetInputData(polydata)
        glyph.SetScaleFactor(atomScaleFactor * 2.0)
        glyph.SetScaleModeToScaleByScalar()
        glyph.ClampingOff()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph.GetOutputPort())
        mapper.SetLookupTable(lut)
        mapper.SetScalarModeToUsePointFieldData()
        mapper.SelectColorArray("colours")
        utils.setMapperScalarRange(mapper, colouringOptions, nspecies)

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

        # store attributes
        self._actor = utils.ActorObject(actor)
        self._data["Points"] = pointsData
        self._data["Scalars"] = scalarsArray
        self._data["Radius"] = radiusArray
        self._data["LUT"] = lut
        self._data["Scale factor"] = atomScaleFactor
예제 #8
0
파일: pdb_viewer.py 프로젝트: alinar/Molar
 def __init__(self,ext_actors=None): #ext_actors is a list of any external vtkActors.
     #initializations:
     self.renderer  = vtk.vtkRenderer()
     self.window    = vtk.vtkRenderWindow()
     self.window.SetSize(1000,1000)
     self.mapper    = vtk.vtkPolyDataMapper()
     self.points    = vtk.vtkPoints()
     self.poly_data = vtk.vtkPolyData()
     self.glyph3d   = vtk.vtkGlyph3D()
     self.actor     = vtk.vtkActor()
     self.point_s   = vtk.vtkPointSource()
     self.sphere    = vtk.vtkSphereSource() 
     self.interactor= vtk.vtkRenderWindowInteractor()
     self.inter_sty = PdbInteractorStyle()
     self.axes_actor= vtk.vtkAxesActor()
     #configurations:
     self.point_s.SetNumberOfPoints(1)
     self.sphere.SetRadius(1.0)
     self.interactor.SetInteractorStyle(self.inter_sty)
     self.interactor.SetRenderWindow(self.window)
     self.axes_actor.SetTotalLength(100,100,100)
     if ext_actors:
         self.ex_actors = ext_actors
     else:
         self.ex_actors=[]
예제 #9
0
  def setupGlyph(self,fUnitConv= 1.0):
    self.polydata= self.getPolydata(fUnitConv)
    # Generate the arrow for the glyphs
    arrow = vtk.vtkArrowSource()
    #arrow.SetRadius(0.1)
    #arrow.SetHeight(0.5)
    self.glyph = vtk.vtkGlyph3D()
    self.glyph.SetInputData(self.polydata)
    self.glyph.SetSourceConnection(arrow.GetOutputPort())
    self.glyph.ScalingOn()
    self.glyph.SetScaleModeToScaleByScalar()
    self.glyph.SetVectorModeToUseVector()
    self.glyph.OrientOn()
    # Tell the filter to "clamp" the scalar range
    #self.glyph.ClampingOn()  
    # Set the overall (multiplicative) scaling factor
    self.glyph.SetScaleFactor(self.scaleFactor)

    # Set the Range to "clamp" the data to 
    #   -- see equations above for nonintuitive definition of "clamping"
    # The fact that I'm setting the minimum value of the range below
    #   the minimum of my data (real min=0.0) with the equations above
    #   forces a minimum non-zero glyph size.

    #self.glyph.SetRange(-10, 10)    # Change these values to see effect on cone sizes

    # Tell glyph which attribute arrays to use for what
    self.glyph.SetInputArrayToProcess(0,0,0,0,self.lenghtsName)	# scalars
    self.glyph.SetInputArrayToProcess(1,0,0,0,self.vectorsName) # vectors
    # self.glyph.SetInputArrayToProcess(2,0,0,0,'nothing')	# normals
    #self.glyph.SetInputArrayToProcess(3,0,0,0,self.lenghtsName) # colors

    # Calling update because I'm going to use the scalar range to set the color map range
    self.glyph.Update()
예제 #10
0
    def __init__(self, profile=0, radius=2):

        if not radius:
            self.radius = Globals.renderProps["sphereSize"] * 1.1
        else: self.radius = radius
        self.z = 0

        self.data = vtk.vtkPolyData()


        self.sphere = vtk.vtkSphereSource()
        self.sphere.SetRadius( Globals.referenceSize * self.radius )
        self.sphere.SetPhiResolution( Globals.renderProps["spherePhiResolution"] )
        self.sphere.SetThetaResolution( Globals.renderProps["sphereThetaResolution"] )

        self.glyphPoints = vtk.vtkGlyph3D()
        self.glyphPoints.SetInput( self.data )
        self.glyphPoints.SetSource( self.sphere.GetOutput() )

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection( self.glyphPoints.GetOutputPort() )

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        if profile:
            self.actor.GetProperty().SetColor(0,0,1)
        else:
            self.actor.GetProperty().SetColor(1,1,0)

        Globals.ren.AddActor(self.actor)
예제 #11
0
파일: plotter.py 프로젝트: trianam/voropath
    def addPoints(self, points, color, thick=False, thickness=_DEFAULT_POINT_THICKNESS):
        vtkPoints = vtk.vtkPoints()
        for point in points:
            vtkPoints.InsertNextPoint(point[0], point[1], point[2])

        pointsPolyData = vtk.vtkPolyData()
        pointsPolyData.SetPoints(vtkPoints)

        if thick:
            sphereSource = vtk.vtkSphereSource()
            sphereSource.SetRadius(thickness)
            
            glyph3D = vtk.vtkGlyph3D()
            glyph3D.SetSourceConnection(sphereSource.GetOutputPort())
            glyph3D.SetInputData(pointsPolyData)
            glyph3D.Update()
 
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(glyph3D.GetOutputPort())
        else:
            vertexFilter = vtk.vtkVertexGlyphFilter()
            vertexFilter.SetInputData(pointsPolyData)
            vertexFilter.Update()                          

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputData(vertexFilter.GetOutput())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(color)

        self._rendererScene.AddActor(actor)
예제 #12
0
    def Glyph3D(self, currentElement):
        glyph = vtk.vtkGlyph3D()
        # Datatype(s) I need for input: Algorithm
        AlgorithmElement = ''
        for childElement in currentElement.getchildren():
            if childElement.tag in vtkTypes['Algorithm']:
                AlgorithmElement = childElement
        if AlgorithmElement != '':
            dataset = self.namesToFunctions[AlgorithmElement.tag](AlgorithmElement)
            try:
                glyph.SetInputConnection(dataset.GetOutputPort())
            except:
                self.logger.error('  .. <Glyph3D> failed to SetInputConnection')
        else:
            self.logger.error('  .. <Glyph3D> needs an Algorithm-type childElement')
        if 'SetSource' in currentElement.keys():
            gsourceName = currentElement.get('SetSource')
            try:
                self.logger.debug('  .. <Glyph3D> SetSource(%s)' % gsourceName)
                glyph.SetSource( self.glyphsources[gsourceName].GetOutput() )
            except:
                self.logger.error('  .. <Glyph3D> failed to SetSource')
        glyph.SetScaleModeToScaleByVector ()
        glyph.SetColorModeToColorByVector ()
        glyph.SetRange(0.0, 0.11445075055913652)
        glyph.SetScaleFactor(3.0)

        return glyph
    def create_glyphs (self, poly):    
        if self.glyph_type == 'sphere':
            glyph = vtk.vtkSphereSource()
            glyph.SetRadius(1)
            glyph.SetPhiResolution(8)
            glyph.SetThetaResolution(8)
        elif self.glyph_type == 'cylinder':
            glyph = vtk.vtkCylinderSource()
            glyph.SetHeight(self.height)
            glyph.SetRadius(self.radius)
            glyph.SetCenter(0,0,0)
            glyph.SetResolution(10)
            glyph.CappingOn()

        tt = vtk.vtkTransform()
        tt.RotateZ(90)
        tf = vtk.vtkTransformPolyDataFilter()
        tf.SetInput(glyph.GetOutput())
        tf.SetTransform(tt)
        tf.Update()

        glypher = vtk.vtkGlyph3D()
        glypher.SetInput(poly)
        glypher.SetSource(tf.GetOutput())
        glypher.SetVectorModeToUseNormal()
        glypher.SetScaleModeToScaleByScalar()
        glypher.SetScaleFactor(self.glyph_scale_factor)
        glypher.Update()

        return glypher
예제 #14
0
파일: stvis-vtk.py 프로젝트: kichiki/stokes
def make_sphereActor (x, r, rgb, opacity):
    points = vtk.vtkPoints()
    points.InsertNextPoint(x[0], x[1], x[2])

    diameter = vtk.vtkDoubleArray()
    diameter.SetNumberOfComponents(1)
    diameter.InsertNextTuple1(2.0*r)

    pData = vtk.vtkPolyData()
    pData.SetPoints(points)
    pData.GetPointData().SetScalars(diameter)

    pSource = vtk.vtkSphereSource()
    pSource.SetPhiResolution(16)
    pSource.SetThetaResolution(16)

    pGlyph = vtk.vtkGlyph3D()
    pGlyph.SetSource(pSource.GetOutput())
    pGlyph.SetInput(pData)
    pGlyph.ScalingOn()
    pGlyph.SetScaleModeToScaleByScalar()

    pMapper = vtk.vtkPolyDataMapper()
    pMapper.ScalarVisibilityOff()
    pMapper.SetInput(pGlyph.GetOutput())

    pActor = vtk.vtkActor()
    pActor.SetMapper(pMapper)
    pActor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2])
    pActor.GetProperty().SetOpacity(opacity)

    return pActor
예제 #15
0
파일: troupe.py 프로젝트: gbaydin/autodiff
    def __init__(self, scale=0.01, **kwargs):
        kwargs["scale"] = scale

        self.poly_data = vtk.vtkPolyData()

        self.arrow_source = vtk.vtkArrowSource()

        self.transform = vtk.vtkTransform()
        
        self.transform_poly_data_filter = vtk.vtkTransformPolyDataFilter()
        self.transform_poly_data_filter.SetTransform(self.transform)
        self.transform_poly_data_filter.SetInputConnection(self.arrow_source.GetOutputPort())

        self.glyph = vtk.vtkGlyph3D()
        self.glyph.OrientOn()
        self.glyph.SetVectorModeToUseNormal()
        self.glyph.SetInput(self.poly_data)
        self.glyph.SetSourceConnection(self.transform_poly_data_filter.GetOutputPort())

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.glyph.GetOutputPort())

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

        self._process_kwargs(**kwargs)
    def __init__(self,data_reader):
        self.lut=vtk.vtkLookupTable()
        self.lut.SetNumberOfColors(256)

        self.lut.SetTableRange(data_reader.get_scalar_range())
        self.lut.SetHueRange(0,1)
        self.lut.SetRange(data_reader.get_scalar_range())
        self.lut.SetRange(data_reader.get_scalar_range())
        self.lut.Build()

        self.arrow=vtk.vtkArrowSource()
        self.arrow.SetTipResolution(6)
        self.arrow.SetTipRadius(0.1)
        self.arrow.SetTipLength(0.35)
        self.arrow.SetShaftResolution(6)
        self.arrow.SetShaftRadius(0.03)
        
        self.glyph=vtk.vtkGlyph3D()

        self.glyph.SetInput(data_reader.get_data_set())
        self.glyph.SetSource(self.arrow.GetOutput())
        self.glyph.SetVectorModeToUseVector()
        self.glyph.SetColorModeToColorByScalar()
        self.glyph.SetScaleModeToScaleByVector()
        self.glyph.OrientOn()
        self.glyph.SetScaleFactor(0.002)
		
        mapper=vtk.vtkPolyDataMapper()
        mapper.SetInput(self.glyph.GetOutput())
        mapper.SetLookupTable(self.lut)
        mapper.ScalarVisibilityOn()
        mapper.SetScalarRange(data_reader.get_scalar_range())
        self.actor=vtk.vtkActor()
        self.actor.SetMapper(mapper)	
예제 #17
0
    def Execute(self):

        if (self._Surface == None):
            self.PrintError('vmtkPickPointSeedSelector Error: Surface not set.')
            return

        self._SourceSeedIds.Initialize()
        self._TargetSeedIds.Initialize()

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInput(self.PickedSeeds)
        glyphs.SetSource(glyphSource.GetOutput())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInput(glyphs.GetOutput())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SeedActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)

        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInput(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1.0)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.OutputText('Please position the mouse and press space to add source points, \'u\' to undo\n')

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._SourceSeedIds.DeepCopy(self.PickedSeedIds)

        self.OutputText('Please position the mouse and press space to add target points, \'u\' to undo\n')

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._TargetSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
예제 #18
0
def visualize():
    A = initPoints(particleA)
    B = initPoints(particleB)
    C = initPoints(particleC)
    displayDict = {}
    # Set up the renderer and redering window
    renderer = vtk.vtkRenderer()
    renwin = vtk.vtkRenderWindow()
    renwin.SetSize(1600, 1400)
    renwin.StereoCapableWindowOn()
    renwin.StereoRenderOn()
    renwin.SetStereoTypeToCrystalEyes()
    renwin.AddRenderer(renderer)
    ptsComp = vtk.vtkPoints()
    posComp = vnp.numpy_to_vtk(np.array([[0, 0, 0]], order='C'), deep=True)
    ptsComp.SetData(posComp)
    polyDataComp = vtk.vtkPolyData()
    polyDataComp.SetPoints(ptsComp)
    sourceComp = vtk.vtkCylinderSource()
    sourceComp.SetResolution(20)
    sourceComp.SetRadius(compartment['radius'] + particleScale)
    sourceComp.SetHeight(compartment['length'] + 2 * particleScale)
    sourceComp.SetCenter(0, -compartment['length']/2, 0)
    glyphComp = vtk.vtkGlyph3D()
    glyphComp.SetSource(sourceComp.GetOutput())
    glyphComp.SetInput(polyDataComp)
    glyphComp.ScalingOff()
    # glyphComp.SetScaleModeToDefault()
    # glyphComp.SetScaleFactor(particleScale)
    mapperComp = vtk.vtkPolyDataMapper()
    mapperComp.SetInput(glyphComp.GetOutput())
    mapperComp.ImmediateModeRenderingOn()
    actorComp = vtk.vtkActor()
    actorComp.SetMapper(mapperComp)
    actorComp.GetProperty().SetOpacity(0.2)
    actorComp.GetProperty().SetColor(1, 1, 1)
    actorComp.SetOrientation(0, 90, 90)
    renderer.AddActor(actorComp)
    renderer.AddActor(A['actor'])
    renderer.AddActor(B['actor'])
    renderer.AddActor(C['actor'])
    print 'Create camera'
    camera = vtk.vtkCamera()
    camera.SetPosition(300e-6, 200.0e-6, -300.0e-6)
    camera.SetFocalPoint(0, 0, 0)
    camera.ComputeViewPlaneNormal()    
    renderer.SetActiveCamera(camera)
    renderer.ResetCamera()
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)
    callback = TimerCallback(A, B, C)
    interactor.Initialize()
    interactor.AddObserver('TimerEvent', callback.execute)
    timerId = interactor.CreateRepeatingTimer(1)
    print 'Here'
    # renwin.FullScreenOn()
    interactor.Start()
예제 #19
0
 def render(self, pointsData, scalarsArray, radiusArray, nspecies, colouringOptions, atomScaleFactor, lut, settings):
     """
     Render the given antisites (wire frame).
     
     """
     self._logger.debug("Rendering vacancies: colour by '%s'", colouringOptions.colourBy)
     
     # points
     points = vtk.vtkPoints()
     points.SetData(pointsData.getVTK())
     
     # poly data
     polydata = vtk.vtkPolyData()
     polydata.SetPoints(points)
     polydata.GetPointData().AddArray(scalarsArray.getVTK())
     polydata.GetPointData().SetScalars(radiusArray.getVTK())
     
     # source
     glyphSource = vtk.vtkCubeSource()
     
     # glyph
     glyph = vtk.vtkGlyph3D()
     if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
         glyph.SetSource(glyphSource.GetOutput())
         glyph.SetInput(polydata)
     else:
         glyph.SetSourceConnection(glyphSource.GetOutputPort())
         glyph.SetInputData(polydata)
     scaleVacs = 2.0 * settings.getSetting("vacScaleSize")
     glyph.SetScaleFactor(atomScaleFactor * scaleVacs)
     glyph.SetScaleModeToScaleByScalar()
     glyph.ClampingOff()
       
     # mapper
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(glyph.GetOutputPort())
     mapper.SetLookupTable(lut)
     mapper.SetScalarModeToUsePointFieldData()
     mapper.SelectColorArray("colours")
     utils.setMapperScalarRange(mapper, colouringOptions, nspecies)
     
     # actor
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     actor.GetProperty().SetSpecular(settings.getSetting("vacSpecular"))
     actor.GetProperty().SetSpecularPower(settings.getSetting("vacSpecularPower"))
     actor.GetProperty().SetOpacity(settings.getSetting("vacOpacity"))
     
     # store attributes
     self._actor = utils.ActorObject(actor)
     self._data["Points"] = pointsData
     self._data["Scalars"] = scalarsArray
     self._data["Radius"] = radiusArray
     self._data["LUT"] = lut
     self._data["Scale factor"] = atomScaleFactor
     self._data["Vacancy opacity"] = settings.getSetting("vacOpacity")
예제 #20
0
파일: seedselector.py 프로젝트: catactg/SUM
    def Execute(self):

        self._SourceSeedIds.Initialize()

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInputData(self.PickedSeeds)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SeedActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space','Add points.',self.PickCallback)
        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        # create a text actor
        txt = vtk.vtkTextActor()
        info = "Position mouse and press space. "
        info += "Select seeds in this order: RSpv, RIpv, LIpv, LSpv. "
        info += "Fifth seed requires --use_laa_seed command."
        txt.SetInput(info)
        txtprop=txt.GetTextProperty()
        txtprop.SetFontFamilyToArial()
        txtprop.SetFontSize(13)
        txtprop.SetColor(1, 1, 1)
        txt.SetDisplayPosition(0, 10)
        self.vmtkRenderer.Renderer.AddActor(txt)

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._SourceSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
예제 #21
0
파일: glyphs.py 프로젝트: fvpolpeta/devide
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)
        InputArrayChoiceMixin.__init__(self)

        self._config.scaling = True
        self._config.scaleFactor = 1
        self._config.scaleMode = glyphScaleMode.index('SCALE_BY_VECTOR')
        self._config.colourMode = glyphColourMode.index('COLOUR_BY_VECTOR')
        self._config.vectorMode = glyphVectorMode.index('USE_VECTOR')
        self._config.mask_on_ratio = 5
        self._config.mask_random = True


        configList = [
            ('Scale glyphs:', 'scaling', 'base:bool', 'checkbox',
             'Should the size of the glyphs be scaled?'),
            ('Scale factor:', 'scaleFactor', 'base:float', 'text',
             'By how much should the glyph size be scaled if scaling is '
             'active?'),
            ('Scale mode:', 'scaleMode', 'base:int', 'choice',
             'Should scaling be performed by vector, scalar or only factor?',
             glyphScaleModeTexts),
            ('Colour mode:', 'colourMode', 'base:int', 'choice',
             'Colour is determined based on scalar or vector magnitude.',
             glyphColourModeTexts),
            ('Vector mode:', 'vectorMode', 'base:int', 'choice',
             'Should vectors or normals be used for scaling and orientation?',
             glyphVectorModeTexts),
            ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
             'The attribute that will be used as vectors for the warping.',
             (input_array_choice_mixin.DEFAULT_SELECTION_STRING,)),
            ('Mask on ratio:', 'mask_on_ratio', 'base:int', 'text',
             'Every Nth point will be glyphed.'),
            ('Random masking:', 'mask_random', 'base:bool', 'checkbox',
             'Pick random distribution of Nth points.')]

        self._mask_points = vtk.vtkMaskPoints()
        module_utils.setup_vtk_object_progress(self,
                self._mask_points, 'Masking points.')

        self._glyphFilter = vtk.vtkGlyph3D()
        asrc = vtk.vtkArrowSource()
        self._glyphFilter.SetSource(0, asrc.GetOutput())

        self._glyphFilter.SetInput(self._mask_points.GetOutput())
        
        module_utils.setup_vtk_object_progress(self, self._glyphFilter,
                                           'Creating glyphs.')

        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self,
             'vtkGlyph3D' : self._glyphFilter})

        self.sync_module_logic_with_config()
예제 #22
0
def load_octomap(octomap_h5_file, conf=0.9, wireframe=False):
    h5f = h5py.File(octomap_h5_file, 'r')
    octree_data = h5f['octree'][...]

    octree_data = octree_data[octree_data[:, 4] > conf]
    pts = vtk.vtkPoints()
    #vtk_pt_data = converter.numpy_to_vtk(np.ascontiguousarray(octree_data[:, 0:3]))
    #pts.SetData(vtk_pt_data)

    use_colors = octree_data.shape[1] > 5
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    #color_data = np.ascontiguousarray(octree_data[:, 5:8])
    #colors = converter.numpy_to_vtk(color_data)
    #colors.SetName('ColorArray')
    #polydata.GetPointData().SetActiveScalars('ColorArray')

    for k in range(octree_data.shape[0]):
        pts.InsertNextPoint(*octree_data[k, 0:3])
        if use_colors:
            r = int(octree_data[k, 5])
            g = int(octree_data[k, 6])
            b = int(octree_data[k, 7])
            colors.InsertNextTupleValue((r, g, b))

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(pts)
    if use_colors:
        polydata.GetPointData().SetScalars(colors)

    cube = vtk.vtkCubeSource()
    cube.SetXLength(octree_data[0, 3])
    cube.SetYLength(octree_data[0, 3])
    cube.SetZLength(octree_data[0, 3])

    glyph = vtk.vtkGlyph3D()
    if use_colors:
        glyph.SetColorModeToColorByScalar()
    glyph.SetSourceConnection(cube.GetOutputPort())
    glyph.SetInput(polydata)
    glyph.ScalingOff()
    glyph.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    if wireframe:
        actor.GetProperty().SetRepresentationToWireframe()
        actor.GetProperty().SetLineWidth(1)
        actor.GetProperty().SetOpacity(0.2)
    actor.GetProperty().LightingOff()

    return actor
예제 #23
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(1, 1, 1)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create points
        points = vtk.vtkPoints()
        points.InsertNextPoint(0, 0, 0)
        points.InsertNextPoint(5, 0, 0)
        points.InsertNextPoint(10, 0, 0)

        # Setup scales. This can also be an Int array
        # char is used since it takes the least memory
        colors = vtk.vtkUnsignedCharArray()
        colors.SetName("colors")
        colors.SetNumberOfComponents(3)
        colors.InsertNextTupleValue((255, 0, 0))
        colors.InsertNextTupleValue((0, 255, 0))
        colors.InsertNextTupleValue((0, 0, 255))

        # Combine into a polydata
        polyData = vtk.vtkPolyData()
        polyData.SetPoints(points)
        polyData.GetPointData().SetScalars(colors)

        # Create anything you want here, we will use a cube for the demo.
        cubeSource = vtk.vtkCubeSource()
        
        glyph3D = vtk.vtkGlyph3D()
        glyph3D.SetColorModeToColorByScalar()
        glyph3D.SetSourceConnection(cubeSource.GetOutputPort())
        glyph3D.SetInput(polyData)
        glyph3D.ScalingOff() #Needed, otherwise only the red cube is visible
        glyph3D.Update()

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph3D.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
예제 #24
0
    def attach_pos(self):

        pos = self._pos
        rad = self._rad

        if pos is not None and rad is not None:
            positions_vtk = numpy_support.numpy_to_vtk(num_array=pos.ravel(), deep=True, array_type=vtk.VTK_FLOAT)
            positions_vtk.SetName("positions")

            radius_vtk = numpy_support.numpy_to_vtk(num_array=rad.ravel(), deep=True, array_type=vtk.VTK_FLOAT)
            radius_vtk.SetName("radius")

            sphere = vtk.vtkSphereSource()
            sphere.SetRadius(1.0)

            ballGlyph = vtk.vtkGlyph3D()

            if vtk.VTK_MAJOR_VERSION <= 5:
                ballGlyph.SetSource(sphere.GetOutput())
            else:
                ballGlyph.SetSourceConnection(sphere.GetOutputPort())

            polydata = vtk.vtkPolyData()
            polydata.SetPoints(self._points)
            polydata.GetPointData().AddArray(radius_vtk)
            polydata.GetPointData().SetActiveScalars("radius") # this scales the source (sphere) radius (1.0)
            
            ballGlyph.SetInputData(polydata)

            #ballGlyph.SetScaleModeToDataScalingOn() 
            mapper = vtk.vtkPolyDataMapper()

            if vtk.VTK_MAJOR_VERSION <= 5:
               mapper.SetInput(ballGlyph.GetOutput())
            else:
               mapper.SetInputConnection(ballGlyph.GetOutputPort())

            # Set colors depending on the color transfer functions
            # mapper.SetLookupTable(self.colorTransferFunction)

            # actor
            ballActor = vtk.vtkActor()
            ballActor.GetProperty().SetColor(0,0,1)
            ballActor.SetMapper(mapper)

            #self._ren.AddActor(ballActor)
            self._marker2 = vtk.vtkOrientationMarkerWidget()
            self._marker2.SetInteractor( self.widget._Iren )
            self._marker2.SetOrientationMarker( ballActor )
            self._marker2.SetViewport(0.75,0,1,0.25)
            self._marker2.SetEnabled(1)

        else:
            print("No particles found. Make sure the particles loaded have positions and radii.")
예제 #25
0
    def BuildView(self):

        if (self.ArrayName != ''):
            self.Image.GetPointData().SetActiveScalars(self.ArrayName)
        wholeExtent = self.Image.GetWholeExtent()

#        self.PlaneWidgetX.SetResliceInterpolateToNearestNeighbour()
        self.PlaneWidgetX.SetResliceInterpolateToLinear()
        self.PlaneWidgetX.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetX.SetInput(self.Image)
        self.PlaneWidgetX.SetPlaneOrientationToXAxes()
        self.PlaneWidgetX.SetSliceIndex(wholeExtent[0])
        self.PlaneWidgetX.DisplayTextOn()
        self.PlaneWidgetX.KeyPressActivationOff()
        
#        self.PlaneWidgetY.SetResliceInterpolateToNearestNeighbour()
        self.PlaneWidgetY.SetResliceInterpolateToLinear()
        self.PlaneWidgetY.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetY.SetInput(self.Image)
        self.PlaneWidgetY.SetPlaneOrientationToYAxes()
        self.PlaneWidgetY.SetSliceIndex(wholeExtent[2])
        self.PlaneWidgetY.DisplayTextOn()
        self.PlaneWidgetY.KeyPressActivationOff()
        self.PlaneWidgetY.SetLookupTable(self.PlaneWidgetX.GetLookupTable())

#        self.PlaneWidgetZ.SetResliceInterpolateToNearestNeighbour()
        self.PlaneWidgetZ.SetResliceInterpolateToLinear()
        self.PlaneWidgetZ.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetZ.SetInput(self.Image)
        self.PlaneWidgetZ.SetPlaneOrientationToZAxes()
        self.PlaneWidgetZ.SetSliceIndex(wholeExtent[4])
        self.PlaneWidgetZ.DisplayTextOn()
        self.PlaneWidgetZ.KeyPressActivationOff()
        self.PlaneWidgetZ.SetLookupTable(self.PlaneWidgetX.GetLookupTable())

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInput(self.Seeds)
        glyphs.SetSource(glyphSource.GetOutput())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self.Image.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInput(glyphs.GetOutput())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        self.WidgetsOn()

        if (self.Display == 1):
            self.vmtkRenderer.AddKeyBinding('Ctrl','Add Seed.')

            self.vmtkRenderer.Render()
예제 #26
0
def generateglyph(polyIn,scalefactor=2):
    vertexGlyphFilter = vtk.vtkGlyph3D()
    sphereSource = vtk.vtkSphereSource()
    vertexGlyphFilter.SetSourceData(sphereSource.GetOutput())
    vertexGlyphFilter.SetInputData(polyIn)
    vertexGlyphFilter.SetColorModeToColorByScalar()
    vertexGlyphFilter.SetSourceConnection(sphereSource.GetOutputPort())
    vertexGlyphFilter.ScalingOn()
    vertexGlyphFilter.SetScaleFactor(scalefactor)
    vertexGlyphFilter.Update()
    return vertexGlyphFilter.GetOutput()
예제 #27
0
    def attach_vel(self):

        vel = self._vel * 1e-2
        rad = self._rad

        if vel is not None and rad is not None:

            velMag = norm(vel, axis=1)
            velMag_vtk = numpy_support.numpy_to_vtk(num_array=velMag.ravel(), deep=True, array_type=vtk.VTK_FLOAT)
            velMag_vtk.SetName("veloMag")

            vecVel = vtk.vtkFloatArray()
            vecVel.SetNumberOfComponents(3)

            for i, v in enumerate(vel):
                vecVel.InsertTuple3(i, v[0], v[1], v[2])

            #Put an arrow (vector) at each ball
            arrow = vtk.vtkArrowSource()
            arrow.SetTipRadius(rad.mean() * 10)
            arrow.SetShaftRadius(rad.mean() * 10)

            poly = vtk.vtkPolyData()
            poly.SetPoints(self._points)

            poly.GetPointData().AddArray(velMag_vtk)
            poly.GetPointData().SetActiveScalars("veloMag")

            arrowGlyph = vtk.vtkGlyph3D()
            
            arrowGlyph.SetInputData(poly)
            arrowGlyph.SetSourceConnection(arrow.GetOutputPort())
            arrowGlyph.SetVectorModeToUseVector()

            poly.GetPointData().SetVectors(vecVel)

            # If we do not want the Arrow's size to depend on the Scalar
            # then arrowGlyph.SetScaleModeToDataScalingOff() must be called
            arrowMapper = vtk.vtkPolyDataMapper()
            arrowMapper.SetInputConnection(arrowGlyph.GetOutputPort())

            self._addScalarBar(velMag)
            arrowMapper.SetLookupTable(self._colorTransferFunction)

            arrowActor = vtk.vtkActor()
            arrowActor.SetMapper(arrowMapper)
            arrowActor.GetProperty().SetColor(1,1,0)

            self._ren.AddActor(arrowActor)
        else:
            print("No particles found. Make sure the particles loaded have velocities and radii.")
예제 #28
0
    def ReadPDB(file_name):
        pdb = vtk.vtkPDBReader()
        pdb.SetFileName(file_name)
        pdb.SetHBScale(1.0)
        pdb.SetBScale(1.0)
        pdb.Update()

        sphere = vtk.vtkSphereSource()
        sphere.SetCenter(0, 0, 0)
        sphere.SetRadius(1)

        glyph = vtk.vtkGlyph3D()
        glyph.SetInputConnection(pdb.GetOutputPort())
        glyph.SetSourceConnection(sphere.GetOutputPort())
        glyph.SetOrient(1)
        glyph.SetColorMode(1)
        glyph.SetScaleMode(2)
        glyph.SetScaleFactor(.25)
        glyph.Update()

        tube = vtk.vtkTubeFilter()
        tube.SetInputConnection(pdb.GetOutputPort())
        tube.SetNumberOfSides(6)
        tube.CappingOff()
        tube.SetRadius(0.2)
        tube.SetVaryRadius(0)
        tube.SetRadiusFactor(10)
        tube.Update()

        tubeMesh = vtk.vtkPolyData()
        tubeMesh.ShallowCopy(tube.GetOutput())
        N = tubeMesh.GetNumberOfPoints()

        rgb_colors = tubeMesh.GetPointData().GetArray("rgb_colors")
        if rgb_colors is not None:
            if rgb_colors.GetNumberOfComponents() == 3:
                for i in range(N):
                    rgb_colors.SetTupleValue(i, (127, 127, 127))

        appendFilter = vtk.vtkAppendPolyData()
        appendFilter.AddInputConnection(glyph.GetOutputPort())
        try:
            appendFilter.AddInputData(tubeMesh)
        except:
            appendFilter.AddInput(tubeMesh)
        appendFilter.Update()

        polyData = vtk.vtkPolyData()
        polyData.ShallowCopy(appendFilter.GetOutput())
        return polyData
예제 #29
0
파일: Glyph.py 프로젝트: sldion/DNACC
 def __init__ (self, mod_m): 
     debug ("In Glyph::__init__ ()")
     Common.state.busy ()
     Base.Objects.Module.__init__ (self, mod_m)
     self.glyph_src = vtk.vtkGlyphSource2D ()
     self.glyph = vtk.vtkGlyph3D ()
     self.mapper = self.map = vtk.vtkPolyDataMapper ()
     self.actor = self.act = vtk.vtkActor ()
     self.data_out = self.mod_m.GetOutput ()
     
     self._initialize ()
     self._gui_init ()
     self.renwin.Render ()
     Common.state.idle ()
예제 #30
0
파일: fos.py 프로젝트: arokem/Fos
def point(points,colors,opacity=1,point_radius=0.001):
    
    if np.array(colors).ndim==1:
        return dots(points,colors,opacity)
    
       
    scalars=vtk.vtkUnsignedCharArray()
    scalars.SetNumberOfComponents(3)
    
    pts=vtk.vtkPoints()
    cnt_colors=0
    
    for p in points:
        
        pts.InsertNextPoint(p[0],p[1],p[2])
        scalars.InsertNextTuple3(round(255*colors[cnt_colors][0]),round(255*colors[cnt_colors][1]),round(255*colors[cnt_colors][2]))
        #scalars.InsertNextTuple3(255,255,255)
        cnt_colors+=1
     
    '''   
    src = vtk.vtkDiskSource()
    src.SetRadialResolution(1)
    src.SetCircumferentialResolution(10)
    src.SetInnerRadius(0.0)
    src.SetOuterRadius(0.001)
    '''
    #src = vtk.vtkPointSource()
    src = vtk.vtkSphereSource()
    src.SetRadius(point_radius)
    src.SetThetaResolution(3)
    src.SetPhiResolution(3)
    
    polyData = vtk.vtkPolyData()
    polyData.SetPoints(pts)
    polyData.GetPointData().SetScalars(scalars)

    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(src.GetOutputPort())
    glyph.SetInput(polyData)
    glyph.SetColorModeToColorByScalar()
    glyph.SetScaleModeToDataScalingOff() 

    mapper=vtk.vtkPolyDataMapper()
    mapper.SetInput(glyph.GetOutput())    
    
    actor=vtk.vtkActor()
    actor.SetMapper(mapper)
            
    return actor
예제 #31
0
파일: filters.py 프로젝트: mmagnuski/vtki
    def glyph(dataset, orient=True, scale=True, factor=1.0, geom=None):
        """
        Copies a geometric representation (called a glyph) to every
        point in the input dataset.  The glyph may be oriented along
        the input vectors, and it may be scaled according to scalar
        data or vector magnitude.

        Parameters
        ----------
        orient : bool
            Use the active vectors array to orient the the glyphs

        scale : bool
            Use the active scalars to scale the glyphs

        factor : float
            Scale factor applied to sclaing array

        geom : vtk.vtkDataSet
            The geometry to use for the glyph
        """
        if geom is None:
            arrow = vtk.vtkArrowSource()
            arrow.Update()
            geom = arrow.GetOutput()
        alg = vtk.vtkGlyph3D()
        alg.SetSourceData(geom)
        if isinstance(scale, str):
            dataset.active_scalar_name = scale
            scale = True
        if scale:
            if dataset.active_scalar is not None:
                if dataset.active_scalar.ndim > 1:
                    alg.SetScaleModeToScaleByVector()
                else:
                    alg.SetScaleModeToScaleByScalar()
        if isinstance(orient, str):
            dataset.active_vectors_name = orient
            orient = True
        alg.SetOrient(orient)
        alg.SetInputData(dataset)
        alg.SetVectorModeToUseVector()
        alg.SetScaleFactor(factor)
        alg.Update()
        return _get_output(alg)
예제 #32
0
def MakeGlyphs(src, reverseNormals):
    """
    Glyph the normals on the surface.

    You may need to adjust the parameters for maskPts, arrow and glyph for a
    nice appearance.

    :param: src - the surface to glyph.
    :param: reverseNormals - if True the normals on the surface are reversed.
    :return: The glyph object.

    """
    # Sometimes the contouring algorithm can create a volume whose gradient
    # vector and ordering of polygon (using the right hand rule) are
    # inconsistent. vtkReverseSense cures this problem.
    reverse = vtk.vtkReverseSense()

    # Choose a random subset of points.
    maskPts = vtk.vtkMaskPoints()
    maskPts.SetOnRatio(5)
    maskPts.RandomModeOn()
    if reverseNormals:
        reverse.SetInputData(src)
        reverse.ReverseCellsOn()
        reverse.ReverseNormalsOn()
        maskPts.SetInputConnection(reverse.GetOutputPort())
    else:
        maskPts.SetInputData(src)

    # Source for the glyph filter
    arrow = vtk.vtkArrowSource()
    arrow.SetTipResolution(16)
    arrow.SetTipLength(0.3)
    arrow.SetTipRadius(0.1)

    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(arrow.GetOutputPort())
    glyph.SetInputConnection(maskPts.GetOutputPort())
    glyph.SetVectorModeToUseNormal()
    glyph.SetScaleFactor(1)
    glyph.SetColorModeToColorByVector()
    glyph.SetScaleModeToScaleByVector()
    glyph.OrientOn()
    glyph.Update()
    return glyph
    def create_vectorfield_actor(self, idx=None, num_elec=None, source=None, field=None, colour=None):
        # vectors location
        points = vtk.vtkPoints()
        for p in range(len(source)):
            x = source[p]
            points.InsertPoint(p, x[0], x[1], x[2])

        sourcePolyData = vtk.vtkPolyData()
        sourcePolyData.SetPoints(points)

        # direction
        directionArray = vtk.vtkDoubleArray()
        directionArray.SetName("direction")
        directionArray.SetNumberOfComponents(3)
        directionArray.SetNumberOfTuples(sourcePolyData.GetNumberOfPoints())
        for i in range(sourcePolyData.GetNumberOfPoints()):
            vector = field[i]
            directionArray.SetTuple3(i, vector[0], vector[1], vector[2])
        sourcePolyData.GetPointData().AddArray(directionArray)
        sourcePolyData.GetPointData().SetActiveVectors("direction")

        # glyphs
        arrow = vtk.vtkArrowSource()
        glyphs = vtk.vtkGlyph3D()
        glyphs.SetSourceConnection(arrow.GetOutputPort())
        glyphs.SetInputData(sourcePolyData)
        glyphs.ScalingOn()
        glyphs.SetScaleModeToScaleByVector()
        glyphs.SetVectorModeToUseVector()
        # glyphs.OrientOn()
        # glyphs.SetScaleFactor(1)
        # glyphs.SetRange(0, 1)
        glyphs.Update()

        directionMapper = vtk.vtkPolyDataMapper()
        directionMapper.SetInputConnection(glyphs.GetOutputPort())

        directionActor = vtk.vtkActor()
        directionActor.SetMapper(directionMapper)

        if len(colour):
            directionActor.GetProperty().SetColor(colour[0], colour[1], colour[2])

        self.actors.append(directionActor)
        self.ids.append(idx)
예제 #34
0
    def update(self):
        # Source for the glyph filter
        arrow = vtkArrowSource()
        arrow.SetTipResolution(8)
        arrow.SetTipLength(0.3)
        arrow.SetTipRadius(0.1)

        glyph = vtkGlyph3D()
        glyph.SetSourceConnection(arrow.GetOutputPort())
        glyph.SetInput(self.input_)
        glyph.SetVectorModeToUseNormal()
        glyph.SetScaleFactor(0.1)
        #glyph.SetColorModeToColorByVector()
        #glyph.SetScaleModeToScaleByVector()
        glyph.OrientOn()
        glyph.Update()

        self.output_ = glyph.GetOutput()
예제 #35
0
    def CreateArrowsGlyphs(self):

        # Source for the glyph filter
        self.arrow = vtk.vtkArrowSource()
        self.arrow.SetTipResolution(16)
        self.arrow.SetTipLength(0.3)
        self.arrow.SetTipRadius(0.1)

        self.glyph = vtk.vtkGlyph3D()
        self.glyph.SetSourceConnection(self.arrow.GetOutputPort())
        self.glyph.AddInputData(self.vtkVectPolyData)
        self.glyph.SetVectorModeToUseVector()
        self.glyph.SetScaleFactor(1)
        # glyph.SetColorModeToColorByScalar()

        self.glyph.SetScaleModeToScaleByVector()
        self.glyph.OrientOn()
        self.glyph.Update()
예제 #36
0
 def ReturnGlyphActorFromPoints(self, MyPoints, View, SphereRadius, color):
     inputDataGlyph = vtk.vtkPolyData()
     glyphMapper = vtk.vtkPolyDataMapper()
     glyphPoints = vtk.vtkGlyph3D()
     balls = vtk.vtkSphereSource()
     inputDataGlyph.SetPoints(MyPoints)
     balls.SetRadius(SphereRadius)
     balls.SetPhiResolution(10)
     balls.SetThetaResolution(10)
     glyphPoints.SetInputData(inputDataGlyph)
     glyphPoints.SetSourceConnection(balls.GetOutputPort())
     glyphMapper.SetInputConnection(glyphPoints.GetOutputPort())
     glyphActor = vtk.vtkActor()
     glyphActor.SetMapper(glyphMapper)
     glyphActor.GetProperty().SetDiffuseColor(color)
     glyphActor.GetProperty().SetSpecular(.3)
     glyphActor.GetProperty().SetSpecularPower(30)
     return glyphActor
예제 #37
0
 def defineActorNode(self, radius):
   sphereSource= vtk.vtkSphereSource()
   sphereSource.SetRadius(radius)
   sphereSource.SetThetaResolution(5)
   sphereSource.SetPhiResolution(5)
   
   markNodos= vtk.vtkGlyph3D()
   markNodos.SetInput(self.gridRecord.uGrid)
   markNodos.SetSource(sphereSource.GetOutput())
   markNodos.ScalingOff()
   markNodos.OrientOff()
   
   mappNodos= vtk.vtkPolyDataMapper()
   mappNodos.SetInput(markNodos.GetOutput())
   visNodos= vtk.vtkActor()
   visNodos.SetMapper(mappNodos)
   visNodos.GetProperty().SetColor(.7, .5, .5)
   self.renderer.AddActor(visNodos)
예제 #38
0
def normals(actor, ratio=5, c=(0.6, 0.6, 0.6), alpha=0.8, legend=None):
    '''
    Build a vtkActor made of the normals at vertices shown as arrows

    [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/tutorial.py)    
    [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/fatlimb.py)    
    '''
    maskPts = vtk.vtkMaskPoints()
    maskPts.SetOnRatio(ratio)
    maskPts.RandomModeOff()
    src = actor.polydata()
    maskPts.SetInputData(src)
    arrow = vtk.vtkLineSource()
    arrow.SetPoint1(0,0,0)
    arrow.SetPoint2(.75,0,0)
    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(arrow.GetOutputPort())
    glyph.SetInputConnection(maskPts.GetOutputPort())
    glyph.SetVectorModeToUseNormal()
    b = src.GetBounds()
    sc = max([b[1]-b[0], b[3]-b[2], b[5]-b[4]])/20.
    glyph.SetScaleFactor(sc)
    glyph.SetColorModeToColorByVector()
    glyph.SetScaleModeToScaleByVector()
    glyph.OrientOn()
    glyph.Update()
    glyphMapper = vtk.vtkPolyDataMapper()
    glyphMapper.SetInputConnection(glyph.GetOutputPort())
    glyphMapper.SetScalarModeToUsePointFieldData()
    glyphMapper.SetColorModeToMapScalars()
    glyphMapper.ScalarVisibilityOn()
    glyphMapper.SelectColorArray("Elevation")
    glyphActor = vtk.vtkActor()
    glyphActor.SetMapper(glyphMapper)
    glyphActor.GetProperty().EdgeVisibilityOff()
    glyphActor.GetProperty().SetColor(vc.getColor(c))
    # check if color string contains a float, in this case ignore alpha
    al = vc.getAlpha(c)
    if al:
        alpha = al
    glyphActor.GetProperty().SetOpacity(alpha)
    glyphActor.PickableOff()
    aactor = Assembly([actor, glyphActor], legend=legend)
    return aactor
예제 #39
0
    def __init__(self, mainwindow, num_points):
        self.mainwindow = mainwindow
        self.emitted = False
        self.points = self.mainwindow.pycgm_data.Data['Markers']
        self.marker_names = [*self.points]
        self.num_points = num_points
        self.size = vtk.vtkUnsignedCharArray()
        self.size.SetNumberOfComponents(3)
        self.size.SetNumberOfTuples(self.num_points)
        self.colours = vtk.vtkUnsignedCharArray()
        self.colours.SetNumberOfComponents(3)
        self.colours.SetNumberOfTuples(self.num_points)

        for i in range(0, self.num_points):
            self.colours.SetTuple(i, (192, 192, 192))
            self.size.SetTuple(i, (1, 1, 1))

        # point cloud
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(12)
        sphere.SetThetaResolution(8)
        sphere.SetPhiResolution(8)
        sphere.Update()
        self.cloud_points = vtk.vtkPoints()
        self.cloud_points.SetNumberOfPoints(self.num_points)
        self.poly_data = vtk.vtkPolyData()
        self.poly_data.SetPoints(self.cloud_points)
        self.poly_data.GetPointData().SetScalars(self.size)
        self.poly_data.GetPointData().AddArray(self.colours)
        self.glyph = vtk.vtkGlyph3D()
        self.glyph.SetGeneratePointIds(True)
        self.glyph.SetInputData(self.poly_data)
        self.glyph.SetSourceConnection(sphere.GetOutputPort())
        self.glyph.SetScaleModeToScaleByScalar()
        self.glyph.Update()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(self.glyph.GetOutputPort())
        mapper.SetScalarModeToUsePointFieldData()
        mapper.SelectColorArray(1)
        mapper.SetScalarRange(0, self.num_points)
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(mapper)
        self.vtk_markers_source = []
예제 #40
0
    def __init__(self, person_id, feature, frequency_count, radius):
        self.sphereSource = vtk.vtkSphereSource()
        # sphereSource.SetCenter(0.0, 0.0, 0.0)
        self.sphereSource.SetRadius(radius)
        self.person_id = person_id
        self.points = vtk.vtkPoints()
        self.points.SetDataTypeToFloat()
        self.frequency_count = frequency_count
        if person_id >= -1:
            self.frequency = frequency_count[person_id][-1]
        else:
            self.frequency = 0

        if person_id == -1:
            num_points = len(feature)
            self.feature = feature

            self.points.SetNumberOfPoints(num_points)
            for i in range(num_points):

                self.points.SetPoint(i, feature[i])
            self.sphereSource.SetRadius(radius)
        elif person_id < -1:
            num_points = len(feature)
            self.points.SetNumberOfPoints(num_points)
            for i in range(num_points):
                self.points.SetPoint(i, 0, 0, 0)
        else:
            self.points.SetNumberOfPoints(max_record)
            self.points.SetPoint(0, point_xyz[person_id])

        self.graph = vtk.vtkPolyData()
        self.graph.SetPoints(self.points)

        self.glyph3D = vtk.vtkGlyph3D()
        self.glyph3D.SetSourceConnection(self.sphereSource.GetOutputPort())
        self.glyph3D.SetInputData(self.graph)
        self.glyph3D.Update()

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.glyph3D.GetOutputPort())
        self.mapper.Update()
예제 #41
0
    def displayPointCloud(self, polydata, pointRadius, nodeName, nodeColor):
        #set up glyph for visualizing point cloud
        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetRadius(pointRadius)
        glyph = vtk.vtkGlyph3D()
        glyph.SetSourceConnection(sphereSource.GetOutputPort())
        glyph.SetInputData(polydata)
        glyph.ScalingOff()
        glyph.Update()

        #display
        modelNode = slicer.mrmlScene.GetFirstNodeByName(nodeName)
        if modelNode is None:  # if there is no node with this name, create with display node
            modelNode = slicer.mrmlScene.AddNewNodeByClass(
                'vtkMRMLModelNode', nodeName)
            modelNode.CreateDefaultDisplayNodes()

        modelNode.SetAndObservePolyData(glyph.GetOutput())
        modelNode.GetDisplayNode().SetColor(nodeColor)
        return modelNode
예제 #42
0
    def __init__(self):

        # Default Options
        self.use_heights_as_scalars = True

        # References to the converted numpy arrays to avoid seg faults
        self.np_to_vtk_points = None
        self.np_to_vtk_cells = None
        self.scalar_dict = {}

        # VTK Data
        self.vtk_poly_data = vtk.vtkPolyData()
        self.vtk_points = vtk.vtkPoints()
        self.vtk_cells = vtk.vtkCellArray()

        self.vtk_poly_data.SetPoints(self.vtk_points)
        self.vtk_poly_data.SetVerts(self.vtk_cells)
        self.vtk_poly_data.Modified()

        # Cube Source
        self.vtk_cube_source = vtk.vtkCubeSource()

        # Glyph 3D
        self.vtk_glyph_3d = vtk.vtkGlyph3D()
        self.vtk_glyph_3d.SetSourceConnection(
            self.vtk_cube_source.GetOutputPort())
        self.vtk_glyph_3d.SetInputData(self.vtk_poly_data)
        self.vtk_glyph_3d.ScalingOff()
        self.vtk_glyph_3d.Update()

        # Mapper
        self.vtk_poly_data_mapper = vtk.vtkPolyDataMapper()
        self.vtk_poly_data_mapper.SetColorModeToDefault()
        self.vtk_poly_data_mapper.SetScalarRange(0, 1.0)
        self.vtk_poly_data_mapper.SetScalarVisibility(True)
        self.vtk_poly_data_mapper.SetInputConnection(
            self.vtk_glyph_3d.GetOutputPort())

        # Voxel Grid Actor
        self.vtk_actor = vtk.vtkActor()
        self.vtk_actor.SetMapper(self.vtk_poly_data_mapper)
예제 #43
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        sphereSource = vtk.vtkSphereSource()
        sphereSource.Update()

        input_ = vtk.vtkPolyData()
        input_.ShallowCopy(sphereSource.GetOutput())

        arrowSource = vtk.vtkArrowSource()

        glyph3D = vtk.vtkGlyph3D()
        glyph3D.SetSourceConnection(arrowSource.GetOutputPort())
        glyph3D.SetVectorModeToUseNormal()
        glyph3D.SetInput(input_)
        glyph3D.SetScaleFactor(0.2)
        glyph3D.Update()

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph3D.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
예제 #44
0
def CreateLineSegmentsActor(pdata):
    
    # Create arrow object
    lines_source = vtk.vtkLineSource()
    lines_source.Update()
    glyph3D = vtk.vtkGlyph3D()
    glyph3D.SetSourceData(lines_source.GetOutput())
    glyph3D.SetInputData(pdata)
    glyph3D.SetVectorModeToUseVector()
    glyph3D.Update()
    
    # Create mapper    
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(glyph3D.GetOutputPort())
    
    # Create actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().LightingOff()

    return actor, mapper
예제 #45
0
def _check_landmarks_3d(mesh, landmarks_3d):
    points = vtk.vtkPoints()
    for point_3d in landmarks_3d:
        points.InsertNextPoint(point_3d[0], point_3d[1], point_3d[2])

    landmarks = vtk.vtkPolyData()
    landmarks.SetPoints(points)

    sphere = vtk.vtkSphereSource()
    sphere.SetRadius(1)

    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(sphere.GetOutputPort())
    glyph.SetInputData(landmarks)

    sphere_mapper = vtk.vtkPolyDataMapper()
    sphere_mapper.SetInputConnection(glyph.GetOutputPort())

    sphere_actor = vtk.vtkActor()
    sphere_actor.SetMapper(sphere_mapper)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(mesh)

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

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.AddActor(sphere_actor)

    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(render_window)
    renderWindowInteractor.Initialize()

    render_window.Render()
    renderWindowInteractor.Start()
예제 #46
0
def GlyphActor(source, glyphPoints, scalarRange, scaleFactor, lut):
    """   
    Create the actor for glyphing the normals.
    
    :param: source: the surface.
    :param: glyphPoints: The number of points used by the mask filter.
    :param: scalarRange: The range in terms of scalar minimum and maximum.
    :param: scaleFactor: The scaling factor for the glyph.
    :param: lut: The lookup table to use.
    
    :return: The glyph actor.
    """
    arrowSource = vtk.vtkArrowSource()
    # Subsample the dataset.
    maskPts = vtk.vtkMaskPoints()
    maskPts.SetInputConnection(source.GetOutputPort())
    maskPts.SetOnRatio(source.GetOutput().GetNumberOfPoints() // glyphPoints)
    maskPts.SetRandomMode(1)

    arrowGlyph = vtk.vtkGlyph3D()
    arrowGlyph.SetScaleFactor(scaleFactor)
    arrowGlyph.SetVectorModeToUseNormal()
    arrowGlyph.SetColorModeToColorByScalar()
    arrowGlyph.SetScaleModeToScaleByVector()
    arrowGlyph.OrientOn()
    arrowGlyph.SetSourceConnection(arrowSource.GetOutputPort())
    arrowGlyph.SetInputConnection(maskPts.GetOutputPort())
    arrowGlyph.Update()

    arrowGlyphMapper = vtk.vtkDataSetMapper()
    # Colour by scalars.
    arrowGlyphMapper.SetScalarRange(scalarRange)
    arrowGlyphMapper.SetColorModeToMapScalars()
    arrowGlyphMapper.ScalarVisibilityOn()
    arrowGlyphMapper.SetLookupTable(lut)
    arrowGlyphMapper.SetInputConnection(arrowGlyph.GetOutputPort())

    glyphActor = vtk.vtkActor()
    glyphActor.SetMapper(arrowGlyphMapper)
    return glyphActor
    def create_glyphs (self, poly):
        if self.glyph_type == 'sphere':
            glyph = vtk.vtkSphereSource()
            glyph.SetRadius(1)
            glyph.SetPhiResolution(8)
            glyph.SetThetaResolution(8)
        elif self.glyph_type == 'cylinder':
            glyph = vtk.vtkCylinderSource()
            glyph.SetHeight(self.height)
            glyph.SetRadius(self.radius)
            glyph.SetCenter(0,0,0)
            glyph.SetResolution(10)
            glyph.CappingOn()

        tt = vtk.vtkTransform()
        tt.RotateZ(90)
        tf = vtk.vtkTransformPolyDataFilter()
        tf.SetInput(glyph.GetOutput())
        tf.SetTransform(tt)
        tf.Update()

        glypher = vtk.vtkGlyph3D()
        glypher.SetInput(poly)
        glypher.SetSource(tf.GetOutput())
        glypher.SetVectorModeToUseNormal()
        glypher.SetScaleModeToScaleByScalar()
        glypher.SetScaleFactor(self.glyph_scale_factor)
        print "Scale factor %f" % self.glyph_scale_factor
        glypher.Update()

        # Color the glyph according to whatever other value is in the vtk file
        


        glypher.GetOutput().GetPointData().SetScalars(glypher.GetOutput().GetPointData().GetArray("h2"))
        
        # print(glypher.GetOutput())

        return glypher
예제 #48
0
def main():
    colors = vtk.vtkNamedColors()

    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(1, 1, 1)
    points.InsertNextPoint(2, 2, 2)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    # Create anything you want here, we will use a cube for the demo.
    cubeSource = vtk.vtkCubeSource()

    glyph3D = vtk.vtkGlyph3D()
    glyph3D.SetSourceConnection(cubeSource.GetOutputPort())
    glyph3D.SetInputData(polydata)
    glyph3D.Update()

    # Visualize
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph3D.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Salmon'))

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

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))  # Background Slate Gray

    renderWindow.SetWindowName('Glyph2D');
    renderWindow.Render()
    renderWindowInteractor.Start()
예제 #49
0
def main():
    colors = vtk.vtkNamedColors()

    sphereSource = vtk.vtkSphereSource()
    sphereSource.Update()

    input_data = vtk.vtkPolyData()
    input_data.ShallowCopy(sphereSource.GetOutput())

    arrowSource = vtk.vtkArrowSource()

    glyph3D = vtk.vtkGlyph3D()
    glyph3D.SetSourceConnection(arrowSource.GetOutputPort())
    glyph3D.SetVectorModeToUseNormal()
    glyph3D.SetInputData(input_data)
    glyph3D.SetScaleFactor(.2)
    glyph3D.Update()

    # Visualize
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph3D.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Yellow'))

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

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('DarkGreen'))

    renderWindow.Render()
    renderer.GetActiveCamera().Zoom(1.5)
    renderWindow.Render()
    renderWindowInteractor.Start()
예제 #50
0
    def VtkDefineNodesActor(self, radius):
        '''Define the actor to display nodes.

        :param radius: radius of the sphere used as symbol to represent nodes.
        '''
        sphereSource= vtk.vtkSphereSource()
        sphereSource.SetRadius(radius)
        sphereSource.SetThetaResolution(5)
        sphereSource.SetPhiResolution(5)

        markNodos= vtk.vtkGlyph3D()
        markNodos.SetInput(self.gridRecord.uGrid)
        markNodos.SetSource(sphereSource.GetOutput())
        markNodos.ScalingOff()
        markNodos.OrientOff()

        mappNodos= vtk.vtkPolyDataMapper()
        mappNodos.SetInput(markNodos.GetOutput())
        visNodos= vtk.vtkActor()
        visNodos.SetMapper(mappNodos)
        visNodos.GetProperty().SetColor(.7, .5, .5)
        self.renderer.AddActor(visNodos)
예제 #51
0
def build_glyph(grid):
    """builds the glyph actor"""
    glyphs = vtk.vtkGlyph3D()
    #if filter_small_forces:
    #glyphs.SetRange(0.5, 1.)

    glyphs.SetVectorModeToUseVector()
    #apply_color_to_glyph = False
    #if apply_color_to_glyph:
    #glyphs.SetScaleModeToScaleByScalar()
    glyphs.SetScaleModeToScaleByVector()
    glyphs.SetColorModeToColorByScale()
    #glyphs.SetColorModeToColorByScalar()  # super tiny
    #glyphs.SetColorModeToColorByVector()  # super tiny

    glyphs.ScalingOn()
    glyphs.ClampingOn()
    #glyphs.Update()

    glyph_source = vtk.vtkArrowSource()
    #glyph_source.InvertOn()  # flip this arrow direction
    glyphs.SetInputData(grid)

    glyphs.SetSourceConnection(glyph_source.GetOutputPort())
    #glyphs.SetScaleModeToDataScalingOff()
    #glyphs.SetScaleFactor(10.0)  # bwb
    #glyphs.SetScaleFactor(1.0)  # solid-bending
    glyph_mapper = vtk.vtkPolyDataMapper()
    glyph_mapper.SetInputConnection(glyphs.GetOutputPort())
    glyph_mapper.ScalarVisibilityOff()

    arrow_actor = vtk.vtkLODActor()
    arrow_actor.SetMapper(glyph_mapper)

    prop = arrow_actor.GetProperty()
    prop.SetColor(1., 0., 0.)
    #self.grid.GetPointData().SetActiveVectors(None)
    arrow_actor.SetVisibility(False)
    return glyph_source, glyphs, glyph_mapper, arrow_actor
예제 #52
0
 def VisVertices(self):
     actor = vtk.vtkActor()
     glyph3d = vtk.vtkGlyph3D()
     point_s = vtk.vtkPointSource()
     mapper = vtk.vtkPolyDataMapper()
     window = vtk.vtkRenderWindow()
     renderer = vtk.vtkRenderer()
     interactor = vtk.vtkRenderWindowInteractor()
     poly_data = vtk.vtkPolyData()
     point_s.SetNumberOfPoints(1)
     interactor.SetRenderWindow(window)
     poly_data.SetPoints(self.points)
     glyph3d.SetSourceConnection(point_s.GetOutputPort())
     glyph3d.SetInputData(poly_data)
     mapper.SetInputConnection(glyph3d.GetOutputPort())
     actor.SetMapper(mapper)
     window.AddRenderer(renderer)
     renderer.AddActor(actor)
     renderer.SetBackground(0.1, 0.2, 0.3)
     renderer.ResetCamera()
     window.Render()
     interactor.Start()
예제 #53
0
def create_ground_positions(tel_coords, list_tel_ids):
    # lut = MakeLUTFromCTF(image_cal)
    points = vtk.vtkPoints()

    for tel_id in list_tel_ids:
        tel_x_pos = tel_coords[tel_id].x.to_value(u.m)
        tel_y_pos = tel_coords[tel_id].y.to_value(u.m)
        tel_z_pos = tel_coords[tel_id].z.to_value(u.m)
        points.InsertNextPoint(tel_x_pos, tel_y_pos, tel_z_pos)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)

    tel_source = vtk.vtkSphereSource()
    tel_source.SetRadius(10)
    tel_source.SetThetaResolution(20)
    tel_source.SetPhiResolution(20)
    tel_source.Update()

    glyph = vtk.vtkGlyph3D()

    glyph.SetInputData(polydata)
    glyph.SetSourceConnection(tel_source.GetOutputPort())
    glyph.SetColorModeToColorByScalar()
    glyph.SetVectorModeToUseNormal()
    glyph.ScalingOff()
    glyph.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor([255, 0, 0])

    return actor
예제 #54
0
def CreateArrowsActor(pdata):
    """ Creates an actor composed of arrows """
    
    # Create arrow object
    arrow = vtk.vtkArrowSource()
    arrow.Update()
    glyph3D = vtk.vtkGlyph3D()
    glyph3D.SetSourceData(arrow.GetOutput())
    glyph3D.SetInputData(pdata)
    glyph3D.SetVectorModeToUseVector()
    glyph3D.Update()
    
    # Create mapper    
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(glyph3D.GetOutputPort())
    
    # Create actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().LightingOff()

    return actor
예제 #55
0
def getParticleActorJanus(ptcldata, colour, opacity, StartTheta, EndTheta):

    # Set particle size and angular resolution
    particles = vtk.vtkSphereSource()
    particles.SetThetaResolution(options.particleresolution)
    particles.SetPhiResolution(options.particleresolution)
    particles.SetStartTheta(StartTheta)
    particles.SetEndTheta(EndTheta)
    particles.SetStartPhi(0)
    particles.SetEndPhi(180)
    if (ellipsoids):
        particles.SetRadius(1.0)
    else:
        particles.SetRadius(options.particleradius)

    # Different glyphs for spheres and ellipsoids
    if (ellipsoids):
        ptclGlyph = vtk.vtkTensorGlyph()
        ptclGlyph.ExtractEigenvaluesOff()
        if (not particlecolourbydata): ptclGlyph.ColorGlyphsOff()
    else:
        ptclGlyph = vtk.vtkGlyph3D()
    ptclGlyph.SetInput(ptcldata)
    ptclGlyph.SetSource(particles.GetOutput())

    # Mapper
    ptclMapper = vtk.vtkPolyDataMapper()
    ptclMapper.SetInput(ptclGlyph.GetOutput())
    ptclMapper.GlobalImmediateModeRenderingOn()

    # Actor
    ptclActor = vtk.vtkLODActor()
    ptclActor.SetMapper(ptclMapper)
    ptclActor.GetProperty().SetColor(colour)
    ptclActor.GetProperty().SetOpacity(opacity)

    # Add to global renderer
    return ptclActor
def normals(actor, ratio=5, c=(0.6, 0.6, 0.6), alpha=0.8, legend=None):
    '''
    Build a vtkActor made of the normals at vertices shown as arrows
    '''
    maskPts = vtk.vtkMaskPoints()
    maskPts.SetOnRatio(ratio)
    maskPts.RandomModeOff()
    src = vu.polydata(actor)
    vu.setInput(maskPts, src)
    arrow = vtk.vtkArrowSource()
    arrow.SetTipRadius(0.075)
    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(arrow.GetOutputPort())
    glyph.SetInputConnection(maskPts.GetOutputPort())
    glyph.SetVectorModeToUseNormal()
    b = src.GetBounds()
    sc = max([b[1] - b[0], b[3] - b[2], b[5] - b[4]]) / 20.
    glyph.SetScaleFactor(sc)
    glyph.SetColorModeToColorByVector()
    glyph.SetScaleModeToScaleByVector()
    glyph.OrientOn()
    glyph.Update()
    glyphMapper = vtk.vtkPolyDataMapper()
    glyphMapper.SetInputConnection(glyph.GetOutputPort())
    glyphMapper.SetScalarModeToUsePointFieldData()
    glyphMapper.SetColorModeToMapScalars()
    glyphMapper.ScalarVisibilityOn()
    glyphMapper.SelectColorArray("Elevation")
    glyphActor = vtk.vtkActor()
    glyphActor.SetMapper(glyphMapper)
    glyphActor.GetProperty().EdgeVisibilityOff()
    glyphActor.GetProperty().SetColor(vc.getColor(c))
    # check if color string contains a float, in this case ignore alpha
    al = vc.getAlpha(c)
    if al: alpha = al
    glyphActor.GetProperty().SetOpacity(alpha)
    aactor = vu.makeAssembly([actor, glyphActor], legend=legend)
    return aactor
예제 #57
0
def make_point_cloud_actor(xyz,
                           size=100,
                           color=(0, 0, 0),
                           opacity=0.5):

    points = vtk.vtkPoints()
    points.SetData(numpy_to_vtk(xyz, deep=True))

    pc = vtk.vtkPolyData()
    pc.SetPoints(points)

    if np.isscalar(size):
        size = np.full(len(xyz), size)
    elif len(size) != len(xyz):
        raise ValueError('Size must be either a scalar or an len(xyz) x 1 array')
    pc.GetPointData().SetScalars(numpy_to_vtk(size))

    ss = vtk.vtkSphereSource()
    ss.SetRadius(1)

    glyph = vtk.vtkGlyph3D()
    glyph.SetInputData(pc)

    glyph.SetSourceConnection(ss.GetOutputPort())
    glyph.SetScaleModeToScaleByScalar()
    glyph.ScalingOn()
    glyph.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())

    actor = vtk.vtkActor()
    mapper.ScalarVisibilityOff()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)
    actor.GetProperty().SetOpacity(opacity)

    return actor
예제 #58
0
def add_actors(w, ren, source):
    ren.SetBackground(0.2, 0.3, 0.4)

    L = max(w.edge_lengths())
    shift = w.edge_lengths() / L * 0.5

    for cnt, sp in enumerate(list_species(w)):
        particles = w.list_particles(sp)
        points = vtk.vtkPoints()
        points.SetNumberOfPoints(len(particles))
        for i, (pid, p) in enumerate(particles):
            pos = tuple(p.position() / L - shift)
            points.SetPoint(i, pos[0], pos[1], pos[2])

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)

        atoms = vtk.vtkGlyph3D()
        atoms.SetInput(polydata)
        atoms.SetSource(source.GetOutput())
        atoms.SetScaleFactor(1.0)
        atoms.SetScaleModeToScaleByScalar()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        if vtk.VTK_MAJOR_VERSION <= 5:
            mapper.SetInput(atoms.GetOutput())
        else:
            mapper.SetInputConnection(atoms.GetOutputPort())

        # actor
        actor = vtk.vtkActor()
        actor.GetProperty().SetColor(*colors[cnt % len(colors)][1])
        actor.SetMapper(mapper)

        # assign actor to the renderer
        ren.AddActor(actor)
예제 #59
0
def add_tilted_positions(tilted_positions, array_pointing):
    points = vtk.vtkPoints()

    for tel_id in tilted_positions.keys():
        tel_pos = tilted_positions[tel_id]
        points.InsertNextPoint(tel_pos[0], tel_pos[1], tel_pos[2])

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)

    tel_source = vtk.vtkSphereSource()
    tel_source.SetRadius(10)
    tel_source.SetThetaResolution(20)
    tel_source.SetPhiResolution(20)
    tel_source.Update()

    glyph = vtk.vtkGlyph3D()
    glyph.SetInputData(polydata)
    glyph.SetSourceConnection(tel_source.GetOutputPort())
    glyph.SetColorModeToColorByScalar()
    glyph.SetVectorModeToUseNormal()
    glyph.ScalingOff()
    glyph.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor([0, 255, 0])
    actor.RotateZ(-array_pointing.az.value)
    actor.RotateY(90 - array_pointing.alt.value)

    return actor
예제 #60
0
파일: scene.py 프로젝트: pradal/phenomenal
    def get_actor_from_voxels(voxels_position, voxels_size, color=None):

        if color is None:
            color = (random.uniform(0, 1), random.uniform(0, 1),
                     random.uniform(0, 1))

        points = vtk.vtkPoints()
        for v in voxels_position:
            points.InsertNextPoint(v[0], v[1], v[2])

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)

        cube_source = vtk.vtkCubeSource()
        cube_source.SetXLength(voxels_size)
        cube_source.SetYLength(voxels_size)
        cube_source.SetZLength(voxels_size)

        glyph3D = vtk.vtkGlyph3D()

        if vtk.VTK_MAJOR_VERSION <= 5:
            glyph3D.SetSource(cube_source.GetOutput())
            glyph3D.SetInput(polydata)
        else:
            glyph3D.SetSourceConnection(cube_source.GetOutputPort())
            glyph3D.SetInputData(polydata)

        glyph3D.Update()

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph3D.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(color[0], color[1], color[2])

        return actor