示例#1
1
文件: tests.py 项目: aevum/moonstone
            def __init__(self, parent=None):
                logging.debug("In SimpleTest::_QVtkWidgetCone::__init__()")
                super(_QVtkWidgetCone, self).__init__(parent)

                self.setWindowTitle("Test QVtkWidget with QMainWindow")
                self.setGeometry(QtCore.QRect(500, 500, 200, 200))

                centralwidget = QtGui.QWidget(self)
                centralwidget.setObjectName("centralwidget")
                gridLayout = QtGui.QGridLayout(centralwidget)
                gridLayout.setObjectName("gridLayout")
                self.setCentralWidget(centralwidget)

                ren = vtk.vtkRenderer()

                widget = QVtkWidget(centralwidget)
                widget.setWindowTitle("Test QVtkWidget with QMainWindow")
                widget.setGeometry(QtCore.QRect(1, 30, 200, 200))
                widget.GetRenderWindow().AddRenderer(ren)
                widget.GetRenderWindow().SetSize(200, 200)

                cone = vtk.vtkConeSource()
                cone.SetResolution(8)

                coneMapper = vtk.vtkPolyDataMapper()
                coneMapper.SetInput(cone.GetOutput())

                coneActor = vtk.vtkActor()
                coneActor.SetMapper(coneMapper)

                ren.AddActor(coneActor)
示例#2
1
def makeTextCaption(text,size,labPos,attPos):
    coneGlyph = vtk.vtkConeSource()
    coneGlyph.SetResolution(10)
    coneGlyph.SetHeight(150)
    coneGlyph.SetRadius(50)
    coneGlyph.Update()
    glyphMaxSize = 50
    glyphSize = .1

    capt = vtk.vtkCaptionActor2D()
    capt.BorderOff()
    capt.SetCaption(text)
    capt.GetCaptionTextProperty().SetFontSize(size)
    capt.GetCaptionTextProperty().BoldOn()
    capt.GetCaptionTextProperty().ItalicOff()
    capt.GetCaptionTextProperty().ShadowOff()
    capt.SetAttachmentPoint(attPos)
    capt.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
    capt.GetPositionCoordinate().SetReferenceCoordinate(None)
    capt.GetPositionCoordinate().SetValue(labPos)
    capt.SetWidth(0.013*(len(text)+1))
    capt.SetHeight(0.1)
    capt.ThreeDimensionalLeaderOff()
    capt.SetLeaderGlyph(coneGlyph.GetOutput())
    capt.SetMaximumLeaderGlyphSize(glyphMaxSize)
    capt.SetLeaderGlyphSize(glyphSize)
    capt.GetProperty().SetColor(0,0,0)
    capt.GetProperty().SetLineWidth(5)

    return capt
def vtkRenderWindowInteractorConeExample():
    """Like it says, just a simple example
    """
    # create root window
    root = Tkinter.Tk()

    # create vtkTkRenderWidget
    pane = vtkTkRenderWindowInteractor(root, width=300, height=300)
    pane.Initialize()

    def quit(obj=root):
        obj.quit()

    pane.AddObserver("ExitEvent", lambda o,e,q=quit: q())

    ren = vtk.vtkRenderer()
    pane.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())
    
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # pack the pane into the tk root
    pane.pack(fill='both', expand=1)
    pane.Start()

    # start the tk mainloop
    root.mainloop()
示例#4
0
 def OnInit(self):
     frame = wx.Frame(None, -1, u'RenderWindowPanel demo',
                      size=(400, 400))
     aspect_radio = wx.RadioBox(
         frame, -1,
         choices=['%s:%s' %ar for ar in self.ASPECT_RATIOS])
     render_window_panel = RenderWindowPanel(frame, -1)
     frame.Bind(wx.EVT_RADIOBOX, self.OnRadioSelect)
     sizer = wx.BoxSizer(wx.VERTICAL)
     sizer.Add(aspect_radio, 0, wx.ALL|wx.EXPAND, 5)
     sizer.Add(render_window_panel, 1, wx.ALL|wx.EXPAND, 5)
     frame.SetSizer(sizer)
     frame.Layout()
     frame.Show(True)
     self.render_window_panel = render_window_panel
     self.SetTopWindow(frame)
     renderer = vtk.vtkRenderer()
     # stuff to be rendererd
     source = vtk.vtkConeSource()
     source.SetResolution(8)
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInput(source.GetOutput())
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     renderer.AddActor(actor)
     render_window_panel.add_renderer(renderer)
     return True
    def __init__(self):
        ActorFactory.ActorFactory.__init__(self)

        colors = ((1, 0, 0), (0, 1, 0), (0, 0, 1))
        self._Properties = []
        for i in range(3):
            property = vtk.vtkProperty()
            property.SetColor(colors[i])
            property.SetAmbient(1.0)
            property.SetOpacity(0.3)
            self._Properties.append(property)

        self._ConeProperties = []
        for i in range(3):
            property = vtk.vtkProperty()
            property.SetColor(colors[i])
            property.SetAmbient(1.0)
            # property.SetOpacity(0.3)
            self._ConeProperties.append(property)

        self._Planes = []
        self._Cutters = []
        self._LineActorsIndex = []
        self._ConeActorsIndex = []

        self._ConeSize = 24.0
        self._Cones = []
        for i in range(6):
            cone = vtk.vtkConeSource()
            cone.SetResolution(2)
            cone.SetHeight(self._ConeSize)
            cone.SetRadius(self._ConeSize)
            self._Cones.append(cone)
示例#6
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
        source = vtk.vtkConeSource()
        source.SetHeight(3.0)
        source.SetRadius(1.0)
        source.SetResolution(20)
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
示例#7
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            # VTK specific code
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

            cone = vtk.vtkConeSource()
            mapper = vtk.vtkPolyDataMapper()
            actor = vtk.vtkActor()

            mapper.SetInputConnection(cone.GetOutputPort())
            actor.SetMapper(mapper)

            renderer.AddActor(actor)
            renderer.ResetCamera()
            renderWindow.Render()

            # VTK Web application specific
            _WebCone.view = renderWindow
            self.Application.GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
def QVTKRenderWidgetConeExample():
    """A simple example that uses the QVTKRenderWindowInteractor
    class.  """

    # every QT app needs an app
    app = qt.QApplication(['QVTKRenderWindowInteractor'])

    # create the widget
    widget = QVTKRenderWindowInteractor()
    widget.Initialize()
    widget.Start()
    # if you dont want the 'q' key to exit comment this.
    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget
    widget.show()
    # close the application when window is closed
    app.setMainWidget(widget)
    # start event processing
    app.exec_loop()
示例#9
0
def initialize(self, VTKWebApp, args):
    if not VTKWebApp.view:
        # VTK specific code
        renderer = vtk.vtkRenderer()
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.AddRenderer(renderer)

        renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        renderWindowInteractor.SetRenderWindow(renderWindow)
        renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

        cone = vtk.vtkConeSource()
        mapper = vtk.vtkPolyDataMapper()
        actor = vtk.vtkActor()

        mapper.SetInputConnection(cone.GetOutputPort())
        actor.SetMapper(mapper)

        renderer.AddActor(actor)
        renderer.ResetCamera()
        renderWindow.Render()

        # VTK Web application specific
        VTKWebApp.view = renderWindow
        self.Application.GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
示例#10
0
def wxVTKRenderWindowConeExample():
    """Like it says, just a simple example.
    """
    # every wx app needs an app
    app = wx.PySimpleApp()

    # create the widget
    frame = wx.Frame(None, -1, "wxVTKRenderWindow", size=(400,400))
    widget = wxVTKRenderWindow(frame, -1)

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the window

    frame.Show()

    app.MainLoop()
示例#11
0
 def __init__(self,  center=(-2,0,0), radius = 1, angle=45, height=0.4, color=(1,1,0) , resolution=60):
     """ cone"""
     self.src = vtk.vtkConeSource()
     self.src.SetResolution(resolution)
     self.src.SetRadius( radius ) 
     #self.src.SetAngle( angle )
     self.src.SetHeight( height )
     #self.src.SetCenter(center)
     
     transform = vtk.vtkTransform()
     transform.Translate(center[0], center[1], center[2] - self.src.GetHeight()/2)
     #transform.RotateX(rotXYZ[0])
     transform.RotateY( -90 )
     #transform.RotateZ(rotXYZ[2])
     transformFilter=vtk.vtkTransformPolyDataFilter()
     transformFilter.SetTransform(transform)
     transformFilter.SetInputConnection(self.src.GetOutputPort())
     transformFilter.Update()
     
     self.mapper = vtk.vtkPolyDataMapper()
     self.mapper.SetInput(transformFilter.GetOutput())
     
     
     #self.mapper = vtk.vtkPolyDataMapper()
     #self.mapper.SetInput(self.src.GetOutput())
     self.SetMapper(self.mapper)
     self.SetColor(color)
示例#12
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkConeSource(), 'Processing.',
         (), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
示例#13
0
文件: wv.py 项目: SpartacusVipul/U.I.
    def renderthis(self):
            # open a window and create a renderer
            ren = vtk.vtkRenderer()
            self.widget.GetRenderWindow().AddRenderer(ren)
  
            # to generate polygonal data for a cone.
            cone = vtk.vtkConeSource()
            cone.SetResolution(25)

            # o take the polygonal data from the vtkConeSource and
            # create a rendering for the renderer.
            coneMapper = vtk.vtkPolyDataMapper()
            coneMapper.SetInput(cone.GetOutput())

            # create an actor for our scene
            coneActor = vtk.vtkActor()
            coneActor.SetMapper(coneMapper)
            # Add actor
            ren.AddActor(coneActor)

            axes = vtk.vtkAxesActor()
            self.marker = vtk.vtkOrientationMarkerWidget()
            self.marker.SetInteractor( self.widget._Iren )
            self.marker.SetOrientationMarker( axes )
            self.marker.SetViewport(0.75,0,1,0.25)
            self.marker.SetEnabled(1)

            ren.ResetCamera()
            ren.ResetCameraClippingRange()
            cam = ren.GetActiveCamera()
            cam.Elevation(10)
            cam.Azimuth(70)
            self.isploted = True
def ex():
    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    WIDTH=640
    HEIGHT=480
    renWin.SetSize(WIDTH,HEIGHT)
 
    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
 
    # create cone
    cone = vtk.vtkConeSource()
    cone.SetResolution(60)
    cone.SetCenter(-2,0,0)
 
    # mapper
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())
 
    # actor
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
 
    # assign actor to the renderer
    ren.AddActor(coneActor)

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
示例#15
0
  def testQVTKWidget(self):

    w2 = vtk.QVTKWidget()
    w2.resize(500,500)

    ren = vtk.vtkRenderer()
    ren.SetBackground(0,0,0)
    ren.SetBackground2(1,1,1)
    ren.SetGradientBackground(1)
    win2 = vtk.vtkRenderWindow()
    win2.AddRenderer(ren)
    w2.SetRenderWindow(win2)

    renwin = w2.GetRenderWindow()
    cone = vtk.vtkConeSource()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(cone.GetOutput())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    ren.AddViewProp(actor)
    ren.ResetCamera()

    w2.show()
    if Testing.isInteractive():
      PyQt4.QtGui.qApp.exec_()
示例#16
0
文件: utilsVtk.py 项目: lcpt/xc_utils
def drawVtkSymb(symbType,renderer, RGBcolor, vPos, vDir, scale):
    '''Adds to the renderer a symbol of type 'arrow', 'doubleArrow',
    'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' , 'doubleCube',
    'cylinder', 'doubleCylinder'

    :param symbType: type of symbol (available types: 'arrow', 'doubleArrow',
           'cone', 'doubleCone', 'sphere', 'doubleSphere','cube' ,
           'doubleCube', 'cylinder', 'doubleCylinder')
    :param renderer: vtk renderer
    :param RGBcolor: list [R,G,B] with the 3 components of color
    :param vPos: list [x,y,z] with the 3 coordinates of the point where
           to place the symbol.
    :param vDir: director vector to orient the symbol
    :param scale: scale to be applied to the symbol representation
    '''
    symTpLow=symbType.lower()
    if 'arrow' in symTpLow:
        symbSource=vtk.vtkArrowSource()
    elif 'cone' in symTpLow:
        symbSource=vtk.vtkConeSource()
    elif 'sphere' in symTpLow:
        symbSource=vtk.vtkSphereSource()
    elif 'cube' in symTpLow:
        symbSource=vtk.vtkCubeSource()
    elif 'cylinder' in symTpLow:
        symbSource=vtk.vtkCylinderSource()
    vPosVx=[vPos[i]-scale/2.0*vDir[i] for i in range(3)] #vertex position
    addSymb(symbSource,renderer, RGBcolor, vPosVx, vDir, scale)
    if 'double' in symTpLow:
        vPosVx=[vPosVx[i]-scale*vDir[i] for i in range(3)] #vertex position
        addSymb(symbSource,renderer, RGBcolor, vPosVx, vDir, scale)
示例#17
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 ()
示例#18
0
文件: page.py 项目: ecell/ecell4-vis
 def OnInit(self):
     """Initializer.
     """
     frame = wx.Frame(None, -1, u'DatasourcePanel Demo')
     # Node provides vtkRenderer.
     visualizer_node = Vtk3dVisualizerNode()
     # Panel provides wxVtkRenderWindowInteractor.
     visualizer_panel = Vtk3dVisualizerPage(frame, -1, target=visualizer_node)
     sizer = wx.BoxSizer()
     sizer.Add(visualizer_panel, 1, wx.ALL|wx.EXPAND, 5)
     frame.SetSizer(sizer)
     frame.Layout()
     frame.Show(True)
     self.SetTopWindow(frame)
     # configure renderer.
     renderer = visualizer_node.renderer
     source = vtk.vtkConeSource()
     source.SetResolution(64)
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInput(source.GetOutput())
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     renderer.AddActor(actor)
     # add renderer to the window.
     visualizer_panel.add_renderer(renderer)
     return True
示例#19
0
def QVTKRenderWidgetConeExample():
    """Like it says, just a simple example
    """
    # every QT app needs an app
    app = QApplication(['QVTKRenderWidget'])

    # create the widget
    widget = QVTKRenderWidget()

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget
    widget.show()
    # close the application when window is closed
    qApp.setMainWidget(widget)
    # start event processing
    app.exec_loop()
示例#20
0
 def ConeSource(self, currentElement):
     source = vtk.vtkConeSource()
     try:
         source.SetHeight( float(currentElement.get('SetHeight')) )
     except:
         self.logger.error('  .. <ConeSource> failed to SetHeight')
     try:
         source.SetRadius( float(currentElement.get('SetRadius')) )
     except:
         self.logger.error('  .. <ConeSource> failed to SetRadius')
     if 'SetResolution' in currentElement.keys():
         try:
             source.SetResolution( int(currentElement.get('SetResolution')) )
         except:
             self.logger.error('  .. <ConeSource> failed to SetResolution')
     if 'SetCenter' in currentElement.keys():
         try:
             source.SetCenter( coordsFromString(currentElement.get('SetCenter')) )
         except:
             self.logger.error('  .. <ConeSource> failed to SetCenter')
     if 'SetDirection' in currentElement.keys():
         try:
             source.SetDirection( coordsFromString(currentElement.get('SetDirection')) )
         except:
             self.logger.error('  .. <ConeSource> failed to SetDirection')
     return source
def vtkRenderWidgetConeExample():
    """Like it says, just a simple example
    """
    # create root window
    root = Tkinter.Tk()

    # create vtkTkRenderWidget
    pane = vtkTkRenderWidget(root,width=300,height=300)

    ren = vtk.vtkRenderer()
    pane.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())
    
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # pack the pane into the tk root
    pane.pack()

    # start the tk mainloop
    root.mainloop()
示例#22
0
def QVTKRenderWidgetConeExample():
    """A simple example that uses the QVTKRenderWindowInteractor class."""
    # every QT app needs an app
    app = QApplication(['QVTKRenderWindowInteractor'])

    # create the widget

    frame, widget = QFramedVTK()
    # for PyQt4, no automatic retina handling
    # frame, widget = QFramedVTK(retina=True)
    widget.Initialize()
    widget.Start()

    # if you dont want the 'q' key to exit comment this.
    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget
    frame.show()
    # start event processing
    app.exec_()
示例#23
0
 def initPicker(self):
     coneSource = vtk.vtkConeSource()
     coneSource.CappingOn()
     coneSource.SetHeight(2)
     coneSource.SetRadius(1)
     coneSource.SetResolution(10)
     coneSource.SetCenter(1,0,0)
     coneSource.SetDirection(-1,0,0)
     
     coneMapper = vtk.vtkDataSetMapper()
     coneMapper.SetInputConnection(coneSource.GetOutputPort())
     
     self.redCone = vtk.vtkActor()
     self.redCone.PickableOff()
     self.redCone.SetMapper(coneMapper)
     self.redCone.GetProperty().SetColor(1,0,0)
     
     self.greenCone = vtk.vtkActor()
     self.greenCone.PickableOff()
     self.greenCone.SetMapper(coneMapper)
     self.greenCone.GetProperty().SetColor(0,1,0)
     
     # Add the two cones (or just one, if you want)
     self.renderer.AddViewProp(self.redCone)
     self.renderer.AddViewProp(self.greenCone)
     
     self.picker = vtk.vtkVolumePicker()
     self.picker.SetTolerance(1e-6)
     self.picker.SetVolumeOpacityIsovalue(0.1)
示例#24
0
def QVTKRenderWidgetConeExample():
    """Like it says, just a simple example
    """
    # every QT app needs an app
    app = QtGui.QApplication(['QVTKRenderWidget'])

    # create the widget
    widget = QVTKRenderWidget()

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    
    coneMapper = vtk.vtkPolyDataMapper()
    
    VTK_MAJOR_VERSION=vtk.vtkVersion.GetVTKMajorVersion()
    if VTK_MAJOR_VERSION>=6:
        coneMapper.SetInputData(cone.GetOutput())
    else:    
        coneMapper.SetInput(cone.GetOutput()) 
    
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget
    widget.show()
    # close the application when window is closed
    #qApp.setMainWidget(widget)
    #app.setMainWidget(widget)
    # start event processing
    sys.exit(app.exec_())
示例#25
0
文件: tests.py 项目: aevum/moonstone
 def setUp(self):
     logging.debug("In VtkSceneTest::setUp()")
     self.cone = vtk.vtkConeSource()
     self.cone.SetResolution(8)
     self.coneMapper = vtk.vtkPolyDataMapper()
     self.coneMapper.SetInput(self.cone.GetOutput())
     self.coneActor = vtk.vtkActor()
     self.coneActor.SetMapper(self.coneMapper)
示例#26
0
 def setup(self):
     self.axes = self.addPart(ObjectBase(vtk.vtkAxes()))
     self.xcone = self.addPart(ObjectBase(vtk.vtkConeSource()))
     self.xcone._actor.SetScale(0.1,0.05,0.05)
     self.xcone._actor.AddPosition(1.0,0.0,0.0)
     self.xcone._actor.GetProperty().SetColor(1.0,0.3,0.3)
     self.ycone = self.addPart(ObjectBase(vtk.vtkConeSource()))
     self.ycone._actor.SetScale(0.1,0.05,0.05)
     self.ycone._actor.RotateZ(90.0)
     self.ycone._actor.AddPosition(0.0,1.0,0.0)
     self.ycone._actor.GetProperty().SetColor(1.0,1.0,0.0)
     self.zcone = self.addPart(ObjectBase(vtk.vtkConeSource()))
     self.zcone._actor.SetScale(0.1,0.05,0.05)
     self.zcone._actor.RotateY(-90.0)
     self.zcone._actor.AddPosition(0.0,0.0,1.0)
     self.zcone._actor.GetProperty().SetColor(0.3,1.0,0.3)
     self.balls = self.addPart(ObjectBase(vtk.vtkSphereSource()))
     self.balls._actor.SetScale(0.05,0.05,0.05)
     self.balls._actor.GetProperty().SetColor(0.3,0.3,1.0)
     self.xtxt = ObjectBase(vtk.vtkVectorText(),
                                         actorType=vtk.vtkFollower)
     self.xtxt._source.SetText('X')
     self.xtxt._actor.SetScale(0.1,0.1,0.1)
     self.xtxt._actor.AddPosition(1.0,0.0,0.0)
     self.xtxt._actor.GetProperty().SetColor(1.0,0.3,0.3)
     self.addPart(self.xtxt)
     self.ytxt = ObjectBase(vtk.vtkVectorText(),
                                         actorType=vtk.vtkFollower)
     self.ytxt._source.SetText('Y')
     self.ytxt._actor.SetScale(0.1,0.1,0.1)
     self.ytxt._actor.AddPosition(0.0,1.0,0.0)
     self.ytxt._actor.GetProperty().SetColor(1.0,1.0,0.0)
     self.addPart(self.ytxt)
     self.ztxt = ObjectBase(vtk.vtkVectorText(),
                                         actorType=vtk.vtkFollower)
     self.ztxt._source.SetText('Z')
     self.ztxt._actor.SetScale(0.1,0.1,0.1)
     self.ztxt._actor.AddPosition(0.0,0.0,1.0)
     self.ztxt._actor.GetProperty().SetColor(0.3,1.0,0.3)
     self.addPart(self.ztxt)
     self.ntxt = ObjectBase(vtk.vtkVectorText(),
                                         actorType=vtk.vtkFollower)
     self.ntxt._source.SetText('0')
     self.ntxt._actor.SetScale(0.1,0.1,0.1)
     self.ntxt._actor.GetProperty().SetColor(0.3,0.3,1.0)
     self.addPart(self.ntxt)
示例#27
0
 def draw_sample_cone(self):
     "For testing"
     cone = vtk.vtkConeSource()
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(cone.GetOutputPort())
     actor = vtk.vtkActor()
     actor.SetMapper(mapper)
     self.ren.AddActor(actor)
     self.ren_win.Render()
    def __init__(self):
        cone = vtk.vtkConeSource()
        cone.SetResolution(8)

        coneMapper = vtk.vtkPolyDataMapper()
        coneMapper.SetInput(cone.GetOutput())

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(coneMapper)
示例#29
0
文件: visualizer.py 项目: ecell/newio
 def _create_actors(self):
     """Creates demo cone actors.
     """
     cone = vtk.vtkConeSource()
     cone.SetResolution(8)
     coneMapper = vtk.vtkPolyDataMapper()
     coneMapper.SetInput(cone.GetOutput())
     coneActor = vtk.vtkActor()
     coneActor.SetMapper(coneMapper)
     self._actors['Cone'] = coneActor
示例#30
0
 def __init__(self, *args, **kwargs):
     super(DemoConeVisualizerNode, self).__init__(*args, **kwargs)
     self.renderer
     source = vtk.vtkConeSource()
     source.SetResolution(64)
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInput(source.GetOutput())
     self.actor = vtk.vtkActor()
     self.actor.SetMapper(mapper)
     self.renderer.AddActor(self.actor)
     self.renderer
示例#31
0
ga.SetMapper(gm)
s1Mapper.SetScalarRange(g.GetOutput().GetScalarRange())
#
# Create outline around data
#
outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(ptLoad.GetOutputPort())
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
outlineActor.GetProperty().SetColor(0, 0, 0)
#
# Create cone indicating application of load
#
coneSrc = vtk.vtkConeSource()
coneSrc.SetRadius(.5)
coneSrc.SetHeight(2)
coneMap = vtk.vtkPolyDataMapper()
coneMap.SetInputConnection(coneSrc.GetOutputPort())
coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMap)
coneActor.SetPosition(0, 0, 11)
coneActor.RotateY(90)
coneActor.GetProperty().SetColor(1, 0, 0)
camera = vtk.vtkCamera()
camera.SetFocalPoint(0.113766, -1.13665, -1.01919)
camera.SetPosition(-29.4886, -63.1488, 26.5807)
camera.SetViewAngle(24.4617)
camera.SetViewUp(0.17138, 0.331163, 0.927879)
camera.SetClippingRange(1, 100)
示例#32
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the RenderWindow, Renderer and Interactor.
    #
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Generate the tensors.
    ptLoad = vtk.vtkPointLoad()
    ptLoad.SetLoadValue(100.0)
    ptLoad.SetSampleDimensions(20, 20, 20)
    ptLoad.ComputeEffectiveStressOn()
    ptLoad.SetModelBounds(-10, 10, -10, 10, -10, 10)
    ptLoad.Update()

    # Generate the hyperstreamlines.
    s1 = vtk.vtkHyperStreamline()
    s1.SetInputData(ptLoad.GetOutput())
    s1.SetStartPosition(9, 9, -9)
    s1.IntegrateMinorEigenvector()
    s1.SetMaximumPropagationDistance(18.0)
    s1.SetIntegrationStepLength(0.1)
    s1.SetStepLength(0.01)
    s1.SetRadius(0.25)
    s1.SetNumberOfSides(18)
    s1.SetIntegrationDirectionToIntegrateBothDirections()
    s1.Update()

    # Map the hyperstreamlines.
    lut = vtk.vtkLogLookupTable()
    lut.SetHueRange(.6667, 0.0)

    s1Mapper = vtk.vtkPolyDataMapper()
    s1Mapper.SetInputConnection(s1.GetOutputPort())
    s1Mapper.SetLookupTable(lut)
    s1Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s1Actor = vtk.vtkActor()
    s1Actor.SetMapper(s1Mapper)

    s2 = vtk.vtkHyperStreamline()
    s2.SetInputData(ptLoad.GetOutput())
    s2.SetStartPosition(-9, -9, -9)
    s2.IntegrateMinorEigenvector()
    s2.SetMaximumPropagationDistance(18.0)
    s2.SetIntegrationStepLength(0.1)
    s2.SetStepLength(0.01)
    s2.SetRadius(0.25)
    s2.SetNumberOfSides(18)
    s2.SetIntegrationDirectionToIntegrateBothDirections()
    s2.Update()

    s2Mapper = vtk.vtkPolyDataMapper()
    s2Mapper.SetInputConnection(s2.GetOutputPort())
    s2Mapper.SetLookupTable(lut)
    s2Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s2Actor = vtk.vtkActor()
    s2Actor.SetMapper(s2Mapper)

    s3 = vtk.vtkHyperStreamline()
    s3.SetInputData(ptLoad.GetOutput())
    s3.SetStartPosition(9, -9, -9)
    s3.IntegrateMinorEigenvector()
    s3.SetMaximumPropagationDistance(18.0)
    s3.SetIntegrationStepLength(0.1)
    s3.SetStepLength(0.01)
    s3.SetRadius(0.25)
    s3.SetNumberOfSides(18)
    s3.SetIntegrationDirectionToIntegrateBothDirections()
    s3.Update()

    s3Mapper = vtk.vtkPolyDataMapper()
    s3Mapper.SetInputConnection(s3.GetOutputPort())
    s3Mapper.SetLookupTable(lut)
    s3Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s3Actor = vtk.vtkActor()
    s3Actor.SetMapper(s3Mapper)

    s4 = vtk.vtkHyperStreamline()
    s4.SetInputData(ptLoad.GetOutput())
    s4.SetStartPosition(-9, 9, -9)
    s4.IntegrateMinorEigenvector()
    s4.SetMaximumPropagationDistance(18.0)
    s4.SetIntegrationStepLength(0.1)
    s4.SetStepLength(0.01)
    s4.SetRadius(0.25)
    s4.SetNumberOfSides(18)
    s4.SetIntegrationDirectionToIntegrateBothDirections()
    s4.Update()

    s4Mapper = vtk.vtkPolyDataMapper()
    s4Mapper.SetInputConnection(s4.GetOutputPort())
    s4Mapper.SetLookupTable(lut)
    s4Mapper.SetScalarRange(ptLoad.GetOutput().GetScalarRange())

    s4Actor = vtk.vtkActor()
    s4Actor.SetMapper(s4Mapper)

    # A plane for context.
    #
    g = vtk.vtkImageDataGeometryFilter()
    g.SetInputData(ptLoad.GetOutput())
    g.SetExtent(0, 100, 0, 100, 0, 0)
    g.Update()  # for scalar range

    gm = vtk.vtkPolyDataMapper()
    gm.SetInputConnection(g.GetOutputPort())
    gm.SetScalarRange(g.GetOutput().GetScalarRange())

    ga = vtk.vtkActor()
    ga.SetMapper(gm)

    # Create an outline around the data.
    #
    outline = vtk.vtkOutlineFilter()
    outline.SetInputData(ptLoad.GetOutput())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d("Black"))

    # Create a cone indicating the application of the load.
    #
    coneSrc = vtk.vtkConeSource()
    coneSrc.SetRadius(.5)
    coneSrc.SetHeight(2)

    coneMap = vtk.vtkPolyDataMapper()
    coneMap.SetInputConnection(coneSrc.GetOutputPort())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMap)
    coneActor.SetPosition(0, 0, 11)
    coneActor.RotateY(90)
    coneActor.GetProperty().SetColor(colors.GetColor3d("Tomato"))

    camera = vtk.vtkCamera()
    camera.SetFocalPoint(0.113766, -1.13665, -1.01919)
    camera.SetPosition(-29.4886, -63.1488, 26.5807)
    camera.SetViewAngle(24.4617)
    camera.SetViewUp(0.17138, 0.331163, 0.927879)
    camera.SetClippingRange(1, 100)

    ren1.AddActor(s1Actor)
    ren1.AddActor(s2Actor)
    ren1.AddActor(s3Actor)
    ren1.AddActor(s4Actor)
    ren1.AddActor(outlineActor)
    ren1.AddActor(coneActor)
    ren1.AddActor(ga)
    ren1.SetBackground(colors.GetColor3d("SlateGray"))
    ren1.SetActiveCamera(camera)

    renWin.SetSize(640, 480)
    renWin.Render()
    iren.Start()
示例#33
0
    def quiver3d(self,
                 x,
                 y,
                 z,
                 u,
                 v,
                 w,
                 color,
                 scale,
                 mode,
                 resolution=8,
                 glyph_height=None,
                 glyph_center=None,
                 glyph_resolution=None,
                 opacity=1.0,
                 scale_mode='none',
                 scalars=None,
                 backface_culling=False,
                 line_width=2.,
                 name=None):
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=FutureWarning)
            factor = scale
            vectors = np.c_[u, v, w]
            points = np.vstack(np.c_[x, y, z])
            n_points = len(points)
            cell_type = np.full(n_points, vtk.VTK_VERTEX)
            cells = np.c_[np.full(n_points, 1), range(n_points)]
            args = (cells, cell_type, points)
            if not VTK9:
                args = (np.arange(n_points) * 3, ) + args
            grid = UnstructuredGrid(*args)
            grid.point_arrays['vec'] = vectors
            if scale_mode == 'scalar':
                grid.point_arrays['mag'] = np.array(scalars)
                scale = 'mag'
            else:
                scale = False
            if mode == '2darrow':
                return _arrow_glyph(grid, factor)
            elif mode == 'arrow' or mode == '3darrow':
                _add_mesh(self.plotter,
                          grid.glyph(orient='vec', scale=scale, factor=factor),
                          color=color,
                          opacity=opacity,
                          backface_culling=backface_culling)
            elif mode == 'cone':
                cone = vtk.vtkConeSource()
                if glyph_height is not None:
                    cone.SetHeight(glyph_height)
                if glyph_center is not None:
                    cone.SetCenter(glyph_center)
                if glyph_resolution is not None:
                    cone.SetResolution(glyph_resolution)
                cone.Update()

                geom = cone.GetOutput()
                _add_mesh(self.plotter,
                          grid.glyph(orient='vec',
                                     scale=scale,
                                     factor=factor,
                                     geom=geom),
                          color=color,
                          opacity=opacity,
                          backface_culling=backface_culling)
            elif mode == 'cylinder':
                cylinder = vtk.vtkCylinderSource()
                cylinder.SetHeight(glyph_height)
                cylinder.SetRadius(0.15)
                cylinder.SetCenter(glyph_center)
                cylinder.SetResolution(glyph_resolution)
                cylinder.Update()

                # fix orientation
                tr = vtk.vtkTransform()
                tr.RotateWXYZ(90, 0, 0, 1)
                trp = vtk.vtkTransformPolyDataFilter()
                trp.SetInputData(cylinder.GetOutput())
                trp.SetTransform(tr)
                trp.Update()

                geom = trp.GetOutput()
                _add_mesh(self.plotter,
                          grid.glyph(orient='vec',
                                     scale=scale,
                                     factor=factor,
                                     geom=geom),
                          color=color,
                          opacity=opacity,
                          backface_culling=backface_culling)
示例#34
0
    def quiver3d(self, x, y, z, u, v, w, color, scale, mode, resolution=8,
                 glyph_height=None, glyph_center=None, glyph_resolution=None,
                 opacity=1.0, scale_mode='none', scalars=None,
                 backface_culling=False):
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=FutureWarning)
            factor = scale
            vectors = np.c_[u, v, w]
            points = np.vstack(np.c_[x, y, z])
            n_points = len(points)
            offset = np.arange(n_points) * 3
            cell_type = np.full(n_points, vtk.VTK_VERTEX)
            cells = np.c_[np.full(n_points, 1), range(n_points)]
            grid = UnstructuredGrid(offset, cells, cell_type, points)
            grid.point_arrays['vec'] = vectors
            if scale_mode == "scalar":
                grid.point_arrays['mag'] = np.array(scalars)
                scale = 'mag'
            else:
                scale = False
            if mode == "arrow":
                self.plotter.add_mesh(grid.glyph(orient='vec',
                                                 scale=scale,
                                                 factor=factor),
                                      color=color,
                                      opacity=opacity,
                                      backface_culling=backface_culling,
                                      smooth_shading=self.figure.
                                      smooth_shading)
            elif mode == "cone":
                cone = vtk.vtkConeSource()
                if glyph_height is not None:
                    cone.SetHeight(glyph_height)
                if glyph_center is not None:
                    cone.SetCenter(glyph_center)
                if glyph_resolution is not None:
                    cone.SetResolution(glyph_resolution)
                cone.Update()

                geom = cone.GetOutput()
                self.plotter.add_mesh(grid.glyph(orient='vec',
                                                 scale=scale,
                                                 factor=factor,
                                                 geom=geom),
                                      color=color,
                                      opacity=opacity,
                                      backface_culling=backface_culling,
                                      smooth_shading=self.figure.
                                      smooth_shading)

            elif mode == "cylinder":
                cylinder = vtk.vtkCylinderSource()
                cylinder.SetHeight(glyph_height)
                cylinder.SetRadius(0.15)
                cylinder.SetCenter(glyph_center)
                cylinder.SetResolution(glyph_resolution)
                cylinder.Update()

                # fix orientation
                tr = vtk.vtkTransform()
                tr.RotateWXYZ(90, 0, 0, 1)
                trp = vtk.vtkTransformPolyDataFilter()
                trp.SetInputData(cylinder.GetOutput())
                trp.SetTransform(tr)
                trp.Update()

                geom = trp.GetOutput()
                self.plotter.add_mesh(grid.glyph(orient='vec',
                                                 scale=scale,
                                                 factor=factor,
                                                 geom=geom),
                                      color=color,
                                      opacity=opacity,
                                      backface_culling=backface_culling,
                                      smooth_shading=self.figure.
                                      smooth_shading)
def main():
    colors = vtk.vtkNamedColors()

    # Create polydata to slice the grid with. In this case, use a cone. This could
    # be any polydata including a stl file.
    cone = vtk.vtkConeSource()
    cone.SetResolution(20)
    cone.Update()

    # implicit function that will be used to slice the mesh
    implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance()
    implicitPolyDataDistance.SetInput(cone.GetOutput())

    # create a grid
    xCoords = vtk.vtkFloatArray()
    for x, i in enumerate(np.linspace(-1.0, 1.0, 15)):
        xCoords.InsertNextValue(i)

    yCoords = vtk.vtkFloatArray()
    for y, i in enumerate(np.linspace(-1.0, 1.0, 15)):
        yCoords.InsertNextValue(i)

    zCoords = vtk.vtkFloatArray()
    for z, i in enumerate(np.linspace(-1.0, 1.0, 15)):
        zCoords.InsertNextValue(i)

    # The coordinates are assigned to the rectilinear grid. Make sure that
    # the number of values in each of the XCoordinates, YCoordinates,
    # and ZCoordinates is equal to what is defined in SetDimensions().
    rgrid = vtk.vtkRectilinearGrid()
    rgrid.SetDimensions(x + 1, y + 1, z + 1)
    rgrid.SetXCoordinates(xCoords)
    rgrid.SetYCoordinates(yCoords)
    rgrid.SetZCoordinates(zCoords)

    # Create an array to hold distance information
    signedDistances = vtk.vtkFloatArray()
    signedDistances.SetNumberOfComponents(1)
    signedDistances.SetName("SignedDistances")

    # Evaluate the signed distance function at all of the grid points
    for pointId in range(rgrid.GetNumberOfPoints()):
        p = rgrid.GetPoint(pointId)
        signedDistance = implicitPolyDataDistance.EvaluateFunction(p)
        signedDistances.InsertNextValue(signedDistance)

    # add the SignedDistances to the grid
    rgrid.GetPointData().SetScalars(signedDistances)

    # use vtkClipDataSet to slice the grid with the polydata
    clipper = vtk.vtkClipDataSet()
    clipper.SetInputData(rgrid)
    clipper.InsideOutOn()
    clipper.SetValue(0.0)
    clipper.Update()

    # --- mappers, actors, render, etc. ---
    # mapper and actor to view the cone
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    # geometry filter to view the background grid
    geometryFilter = vtk.vtkRectilinearGridGeometryFilter()
    geometryFilter.SetInputData(rgrid)
    geometryFilter.SetExtent(0, x + 1, 0, y + 1, (z + 1) // 2, (z + 1) // 2)
    geometryFilter.Update()

    rgridMapper = vtk.vtkPolyDataMapper()
    rgridMapper.SetInputConnection(geometryFilter.GetOutputPort())

    wireActor = vtk.vtkActor()
    wireActor.SetMapper(rgridMapper)
    wireActor.GetProperty().SetRepresentationToWireframe()
    wireActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # mapper and actor to view the clipped mesh
    clipperMapper = vtk.vtkDataSetMapper()
    clipperMapper.SetInputConnection(clipper.GetOutputPort())

    clipperActor = vtk.vtkActor()
    clipperActor.SetMapper(clipperMapper)
    clipperActor.GetProperty().SetRepresentationToWireframe()
    clipperActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('White'))

    # add the actors
    # renderer.AddActor(coneActor)
    renderer.AddActor(wireActor)
    renderer.AddActor(clipperActor)

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

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # Start
    interactor.Initialize()
    renwin.Render()
    renderer.GetActiveCamera().SetPosition(0, -1, 0)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0, 0, 1)
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)
    renderer.ResetCamera()
    renwin.Render()
    interactor.Start()
示例#36
0
import vtk


cone_source = vtk.vtkConeSource()
cone_source.SetHeight(3)
cone_source.SetRadius(1)
cone_source.SetResolution(10)

cone_mapper = vtk.vtkPolyDataMapper()
cone_mapper.SetInputConnection(cone_source.GetOutputPort())

cone_actor = vtk.vtkActor()
cone_actor.SetMapper(cone_mapper)
cone_properties = cone_actor.GetProperty()
cone_properties.SetColor(1.0, 0.3882, 0.2784)
cone_properties.SetDiffuse(0.7)
cone_properties.SetSpecular(0.4)
cone_properties.SetSpecularPower(20)


# linear transform matrix
t1 = vtk.vtkMatrixToLinearTransform()
m1 = vtk.vtkMatrix4x4()
t1.SetInput(m1)
m1.SetElement(0, 0, 1)
m1.SetElement(0, 1, 0)
m1.SetElement(0, 2, 0)
m1.SetElement(0, 3, 0)
m1.SetElement(1, 0, 0)
m1.SetElement(1, 1, 1)
示例#37
0
rt.SetWholeExtent(-2,2,-2,2,0,0)

# Take the gradient of the only scalar 'RTData' to get a vector attribute
grad = vtk.vtkImageGradient()
grad.SetDimensionality(3)
grad.SetInputConnection(rt.GetOutputPort())

# Elevation just to generate another scalar attribute that varies nicely over the data range
elev = vtk.vtkElevationFilter()
# Elevation values will range from 0 to 1 between the Low and High Points
elev.SetLowPoint(-2,0,0)
elev.SetHighPoint(2,0,0)
elev.SetInputConnection(grad.GetOutputPort())

# Generate the cone for the glyphs
sph = vtk.vtkConeSource()
sph.SetRadius(0.1)
sph.SetHeight(0.5)

# Set up the glyph filter
glyph = vtk.vtkGlyph3D()
glyph.SetInputConnection(elev.GetOutputPort())
glyph.SetSourceConnection(sph.GetOutputPort())
glyph.ScalingOn()
glyph.SetScaleModeToScaleByScalar()
glyph.SetVectorModeToUseVector()
glyph.OrientOn()

# Tell the filter to "clamp" the scalar range
glyph.ClampingOn()  
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

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

        # Create source
        geometricObjects = list()
        geometricObjects.append(vtk.vtkArrowSource())
        geometricObjects.append(vtk.vtkConeSource())
        geometricObjects.append(vtk.vtkCubeSource())
        geometricObjects.append(vtk.vtkCylinderSource())
        geometricObjects.append(vtk.vtkDiskSource())
        geometricObjects.append(vtk.vtkLineSource())
        geometricObjects.append(vtk.vtkRegularPolygonSource())
        geometricObjects.append(vtk.vtkSphereSource())

        renderers = list()
        mappers = list()
        actors = list()
        textmappers = list()
        textactors = list()

        # Create a common text property.
        textProperty = vtk.vtkTextProperty()
        textProperty.SetFontSize(10)
        textProperty.SetJustificationToCentered()

        # Create a parametric function source, renderer, mapper
        # and actor for each object.
        for idx, item in enumerate(geometricObjects):
            geometricObjects[idx].Update()

            mappers.append(vtk.vtkPolyDataMapper())
            mappers[idx].SetInputConnection(
                geometricObjects[idx].GetOutputPort())

            actors.append(vtk.vtkActor())
            actors[idx].SetMapper(mappers[idx])

            textmappers.append(vtk.vtkTextMapper())
            textmappers[idx].SetInput(item.GetClassName())
            textmappers[idx].SetTextProperty(textProperty)

            textactors.append(vtk.vtkActor2D())
            textactors[idx].SetMapper(textmappers[idx])
            textactors[idx].SetPosition(150, 16)

            renderers.append(vtk.vtkRenderer())

        gridDimensions = 3

        for idx in range(len(geometricObjects)):
            if idx < gridDimensions * gridDimensions:
                renderers.append(vtk.vtkRenderer())

        rendererSize = 300

        # Setup the RenderWindow
        self.vtkWidget.GetRenderWindow().SetSize(rendererSize * gridDimensions,
                                                 rendererSize * gridDimensions)

        # Add and position the renders to the render window.
        viewport = list()
        for row in range(gridDimensions):
            for col in range(gridDimensions):
                idx = row * gridDimensions + col

                viewport[:] = []
                viewport.append(
                    float(col) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - (row + 1)) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(col + 1) * rendererSize /
                    (gridDimensions * rendererSize))
                viewport.append(
                    float(gridDimensions - row) * rendererSize /
                    (gridDimensions * rendererSize))

                if idx > (len(geometricObjects) - 1):
                    continue

                renderers[idx].SetViewport(viewport)
                self.vtkWidget.GetRenderWindow().AddRenderer(renderers[idx])

                renderers[idx].AddActor(actors[idx])
                renderers[idx].AddActor(textactors[idx])
                renderers[idx].SetBackground(0.4, 0.3, 0.2)

        self._initialized = False
示例#39
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.frame = QFrame()
        self.vl = QHBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)

        self.vpoints_list = []
        self.vpoints_dict = {}

        sphere = vtk.vtkSphereSource()
        ndiv = 8
        sphere.SetThetaResolution(ndiv)
        sphere.SetPhiResolution(ndiv)
        #this sets the original radius of
        #the sphere for the glyph
        sphere.SetRadius(.5)

        cube = vtk.vtkCubeSource()
        cube.SetXLength(.75)

        cone = vtk.vtkConeSource()
        cone.SetRadius(.5)
        cone.SetHeight(1.0)

        self.src_list = [sphere, cone, cube]

        #set up text widget
        font = QFont()

        font.setFamily("Courier")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(16)

        txt = QPlainTextEdit()
        txt.setFont(font)
        txt.setMaximumWidth(400)

        #p = txt.palette()

        #ok this works to set txt back color
        txt.setStyleSheet("background-color: #999999")

        self.txt = txt

        c0 = canvas0()
        self.c0 = c0

        self.vl.addWidget(txt)
        self.vl.addWidget(self.vtkWidget)
        self.vl.addWidget(c0)

        self.c0.draw()

        #vtk window setup
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)

        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        self.ren.SetBackground(.8, .8, .8)

        self.renderer = self.ren
        self.frame.setLayout(self.vl)

        self.setCentralWidget(self.frame)

        self.iren.Start()

        #self.statusBar().showMessage('vtk editor')
        self.createActions()
        self.createMenus()

        self.vtkWidget.GetRenderWindow().Render()

        self.mlist = []
        self.mcolor = ""

        #this is necessary
        self.show()
示例#40
0
def main():
    nc = vtk.vtkNamedColors()
    # We can print out the variables.
    # The color name and RGBA values are displayed.
    print(nc)

    # Here we just print out the colors and any
    # synonyms.
    PrintColors(nc)
    PrintSynonyms(nc)

    """
    Create a cone, contour it using the banded contour filter and
        color it with the primary additive and subtractive colors.
    """
    # Create a cone
    coneSource = vtk.vtkConeSource()
    coneSource.SetCenter(0.0, 0.0, 0.0)
    coneSource.SetRadius(5.0)
    coneSource.SetHeight(10)
    coneSource.SetDirection(0, 1, 0)
    coneSource.SetResolution(6)
    coneSource.Update()

    bounds = [1.0, -1.0, 1.0, -1.0, 1.0, -1.0]
    coneSource.GetOutput().GetBounds(bounds)

    elevation = vtk.vtkElevationFilter()
    elevation.SetInputConnection(coneSource.GetOutputPort())
    elevation.SetLowPoint(0, bounds[2], 0)
    elevation.SetHighPoint(0, bounds[3], 0)

    bcf = vtk.vtkBandedPolyDataContourFilter()
    bcf.SetInputConnection(elevation.GetOutputPort())
    bcf.SetScalarModeToValue()
    bcf.GenerateContourEdgesOn()
    bcf.GenerateValues(7, elevation.GetScalarRange())

    # Test setting and getting a color here.
    # We are also modifying alpha.
    # Convert to a list so that
    # SetColor(name,rgba) works.
    rgba = list(nc.GetColor4d("Red"))
    rgba[3] = 0.5
    nc.SetColor("My Red", rgba)
    # Does "My Red" match anything?
    match = FindSynonyms(nc, "My Red")
    print("Matching colors to My Red:", ', '.join(match))
    # Build a simple lookup table of
    # primary additive and subtractive colors.
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfTableValues(7)
    lut.SetTableValue(0, nc.GetColor4d("My Red"))
    # Let's make the dark green one partially transparent.
    rgba = nc.GetColor4d("Lime")
    rgba[3] = 0.3
    lut.SetTableValue(1, rgba)
    lut.SetTableValue(2, nc.GetColor4d("Blue"))
    lut.SetTableValue(3, nc.GetColor4d("Cyan"))
    lut.SetTableValue(4, nc.GetColor4d("Magenta"))
    lut.SetTableValue(5, nc.GetColor4d("Yellow"))
    lut.SetTableValue(6, nc.GetColor4d("White"))
    lut.SetTableRange(elevation.GetScalarRange())
    lut.Build()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(bcf.GetOutputPort())
    mapper.SetLookupTable(lut)
    mapper.SetScalarModeToUseCellData()

    contourLineMapper = vtk.vtkPolyDataMapper()
    contourLineMapper.SetInputData(bcf.GetContourEdgesOutput())
    contourLineMapper.SetScalarRange(elevation.GetScalarRange())
    contourLineMapper.SetResolveCoincidentTopologyToPolygonOffset()

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

    contourLineActor = vtk.vtkActor()
    actor.SetMapper(mapper)
    contourLineActor.SetMapper(contourLineMapper)
    contourLineActor.GetProperty().SetColor(
        nc.GetColor3d("black"))

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

    renderer.AddActor(actor)
    renderer.AddActor(contourLineActor)
    renderer.SetBackground2(nc.GetColor3d('RoyalBlue'))
    renderer.SetBackground(nc.GetColor3d('MistyRose'))
    renderer.GradientBackgroundOn()
    renderWindow.SetSize(600, 600)
    renderWindow.Render()
    renderWindow.SetWindowName('NamedColors')
    renderWindow.Render()
    renderWindow.Render()

    renderWindowInteractor.Start()
示例#41
0
    def testMassProperties(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        cone = vtk.vtkConeSource()
        cone.SetResolution(50)

        sphere = vtk.vtkSphereSource()
        sphere.SetPhiResolution(50)
        sphere.SetThetaResolution(50)

        cube = vtk.vtkCubeSource()
        cube.SetXLength(1)
        cube.SetYLength(1)
        cube.SetZLength(1)

        sphereMapper = vtk.vtkPolyDataMapper()
        sphereMapper.SetInputConnection(sphere.GetOutputPort())
        sphereMapper.GlobalImmediateModeRenderingOn()

        sphereActor = vtk.vtkActor()
        sphereActor.SetMapper(sphereMapper)
        sphereActor.GetProperty().SetDiffuseColor(1, .2, .4)
        coneMapper = vtk.vtkPolyDataMapper()
        coneMapper.SetInputConnection(cone.GetOutputPort())
        coneMapper.GlobalImmediateModeRenderingOn()

        coneActor = vtk.vtkActor()
        coneActor.SetMapper(coneMapper)
        coneActor.GetProperty().SetDiffuseColor(.2, .4, 1)

        cubeMapper = vtk.vtkPolyDataMapper()
        cubeMapper.SetInputConnection(cube.GetOutputPort())
        cubeMapper.GlobalImmediateModeRenderingOn()

        cubeActor = vtk.vtkActor()
        cubeActor.SetMapper(cubeMapper)
        cubeActor.GetProperty().SetDiffuseColor(.2, 1, .4)

        #Add the actors to the renderer, set the background and size
        #
        sphereActor.SetPosition(-5, 0, 0)
        ren.AddActor(sphereActor)
        coneActor.SetPosition(0, 0, 0)
        ren.AddActor(coneActor)
        coneActor.SetPosition(5, 0, 0)
        ren.AddActor(cubeActor)

        tf = dict()
        mp = dict()
        vt = dict()
        pdm = dict()
        ta = dict()

        def MakeText(primitive):

            tf.update({primitive: vtk.vtkTriangleFilter()})
            tf[primitive].SetInputConnection(primitive.GetOutputPort())

            mp.update({primitive: vtk.vtkMassProperties()})
            mp[primitive].SetInputConnection(tf[primitive].GetOutputPort())

            # here we capture stdout and write it to a variable for processing.
            summary = StringIO.StringIO()
            # save the original stdout
            old_stdout = sys.stdout
            sys.stdout = summary

            print mp[primitive]
            summary = summary.getvalue()

            startSum = summary.find("  VolumeX")
            endSum = len(summary)
            print summary[startSum:]
            # Restore stdout
            sys.stdout = old_stdout

            vt.update({primitive: vtk.vtkVectorText()})
            vt[primitive].SetText(summary[startSum:])

            pdm.update({primitive: vtk.vtkPolyDataMapper()})
            pdm[primitive].SetInputConnection(vt[primitive].GetOutputPort())

            ta.update({primitive: vtk.vtkActor()})
            ta[primitive].SetMapper(pdm[primitive])
            ta[primitive].SetScale(.2, .2, .2)
            return ta[primitive]


        ren.AddActor(MakeText(sphere))
        ren.AddActor(MakeText(cube))
        ren.AddActor(MakeText(cone))

        ta[sphere].SetPosition(sphereActor.GetPosition())
        ta[sphere].AddPosition(-2, -1, 0)
        ta[cube].SetPosition(cubeActor.GetPosition())
        ta[cube].AddPosition(-2, -1, 0)
        ta[cone].SetPosition(coneActor.GetPosition())
        ta[cone].AddPosition(-2, -1, 0)

        ren.SetBackground(0.1, 0.2, 0.4)
        renWin.SetSize(786, 256)

        # render the image
        #
        ren.ResetCamera()
        cam1 = ren.GetActiveCamera()
        cam1.Dolly(3)
        ren.ResetCameraClippingRange()

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "MassProperties.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
示例#42
0
    def ChangeSpinGlyph(self, renWin, keyword):
        if keyword == 'Cubes':
            try:
                del ASDMomActors.spinarrow
            except:
                pass
            try:
                del self.spinsphere
            except:
                pass
            try:
                del self.spincone
            except:
                pass

            self.spincube = vtk.vtkCubeSource()
            self.spincube.SetXLength(1.0)
            self.spincube.SetYLength(1.0)
            self.spincube.SetZLength(1.0)
            ASDMomActors.SpinMapper.SetSourceConnection(
                self.spincube.GetOutputPort())
            ASDMomActors.SpinMapper.ClampingOn()
            ASDMomActors.SpinMapper.OrientOff()
            renWin.Render()
        if keyword == 'Spheres':
            try:
                del ASDMomActors.spinarrow
            except:
                pass
            try:
                del self.spincube
            except:
                pass
            try:
                del self.spincone
            except:
                pass
            self.spinsphere = vtk.vtkSphereSource()
            self.spinsphere.SetRadius(1.00)
            self.spinsphere.SetThetaResolution(20)
            self.spinsphere.SetPhiResolution(20)
            ASDMomActors.SpinMapper.SetSourceConnection(
                self.spinsphere.GetOutputPort())
            ASDMomActors.SpinMapper.ClampingOn()
            ASDMomActors.SpinMapper.OrientOff()
            renWin.Render()
        if keyword == 'Arrows':
            try:
                del self.spinsphere
            except:
                pass
            try:
                del self.spincube
            except:
                pass
            try:
                del self.spincone
            except:
                pass
            ASDMomActors.spinarrow = vtk.vtkArrowSource()
            ASDMomActors.spinarrow.SetTipRadius(0.20)
            ASDMomActors.spinarrow.SetShaftRadius(0.10)
            ASDMomActors.spinarrow.SetTipResolution(10)
            ASDMomActors.spinarrow.SetShaftResolution(10)
            ASDMomActors.SpinMapper.SetSourceConnection(
                ASDMomActors.spinarrow.GetOutputPort())
            ASDMomActors.SpinMapper.OrientOn()
            renWin.Render()
        if keyword == 'Cones':
            self.spincones = vtk.vtkConeSource()
            self.spincones.SetRadius(0.50)
            self.spincones.SetHeight(1.00)
            self.spincones.SetResolution(10)
            ASDMomActors.SpinMapper.SetSourceConnection(
                self.spincones.GetOutputPort())
            ASDMomActors.SpinMapper.OrientOn()
            renWin.Render()
示例#43
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the background color.
    colors.SetColor('BkgColor', [51, 77, 102, 255])

    sourceObjects = list()
    sourceObjects.append(vtk.vtkSphereSource())
    sourceObjects[-1].SetPhiResolution(21)
    sourceObjects[-1].SetThetaResolution(21)

    sourceObjects.append(vtk.vtkConeSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCylinderSource())
    sourceObjects[-1].SetResolution(51)

    sourceObjects.append(vtk.vtkCubeSource())
    sourceObjects.append(vtk.vtkPlaneSource())
    sourceObjects.append(vtk.vtkTextSource())
    sourceObjects[-1].SetText('Hello')
    sourceObjects[-1].BackingOff()

    sourceObjects.append(vtk.vtkPointSource())
    sourceObjects[-1].SetNumberOfPoints(500)

    sourceObjects.append(vtk.vtkDiskSource())
    sourceObjects[-1].SetCircumferentialResolution(51)

    sourceObjects.append(vtk.vtkLineSource())

    renderers = list()
    mappers = list()
    actors = list()
    textmappers = list()
    textactors = list()

    # Create one text property for all.
    textProperty = vtk.vtkTextProperty()
    textProperty.SetFontSize(16)
    textProperty.SetJustificationToCentered()
    textProperty.SetColor(colors.GetColor3d('LightGoldenrodYellow'))

    backProperty = vtk.vtkProperty()
    backProperty.SetColor(colors.GetColor3d('Tomato'))

    # Create a source, renderer, mapper, and actor
    # for each object.
    for i in range(0, len(sourceObjects)):
        mappers.append(vtk.vtkPolyDataMapper())
        mappers[i].SetInputConnection(sourceObjects[i].GetOutputPort())

        actors.append(vtk.vtkActor())
        actors[i].SetMapper(mappers[i])
        actors[i].GetProperty().SetColor(colors.GetColor3d('PeachPuff'))
        actors[i].SetBackfaceProperty(backProperty)

        textmappers.append(vtk.vtkTextMapper())
        textmappers[i].SetInput(sourceObjects[i].GetClassName())
        textmappers[i].SetTextProperty(textProperty)

        textactors.append(vtk.vtkActor2D())
        textactors[i].SetMapper(textmappers[i])
        textactors[i].SetPosition(120, 16)
        renderers.append(vtk.vtkRenderer())

    gridDimensions = 3

    # We need a renderer even if there is no actor.
    for i in range(len(sourceObjects), gridDimensions**2):
        renderers.append(vtk.vtkRenderer())

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName('SourceObjectsDemo')
    rendererSize = 300
    renderWindow.SetSize(rendererSize * gridDimensions,
                         rendererSize * gridDimensions)

    for row in range(0, gridDimensions):
        for col in range(0, gridDimensions):
            index = row * gridDimensions + col
            x0 = float(col) / gridDimensions
            y0 = float(gridDimensions - row - 1) / gridDimensions
            x1 = float(col + 1) / gridDimensions
            y1 = float(gridDimensions - row) / gridDimensions
            renderWindow.AddRenderer(renderers[index])
            renderers[index].SetViewport(x0, y0, x1, y1)

            if index > (len(sourceObjects) - 1):
                continue

            renderers[index].AddActor(actors[index])
            renderers[index].AddActor(textactors[index])
            renderers[index].SetBackground(colors.GetColor3d('BkgColor'))
            renderers[index].ResetCamera()
            renderers[index].GetActiveCamera().Azimuth(30)
            renderers[index].GetActiveCamera().Elevation(30)
            renderers[index].GetActiveCamera().Zoom(0.8)
            renderers[index].ResetCameraClippingRange()

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    renderWindow.Render()
    interactor.Start()
示例#44
0
def main():
    colors = vtk.vtkNamedColors()

    # Set the colors.
    colors.SetColor('AzimuthArrowColor', [255, 77, 77, 255])
    colors.SetColor('ElevationArrowColor', [77, 255, 77, 255])
    colors.SetColor('RollArrowColor', [255, 255, 77, 255])
    colors.SetColor('SpikeColor', [255, 77, 255, 255])
    colors.SetColor('BkgColor', [26, 51, 102, 255])

    # Create a rendering window, renderer and interactor.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Create a camera model.
    camCS = vtk.vtkConeSource()
    camCS.SetHeight(1.5)
    camCS.SetResolution(12)
    camCS.SetRadius(0.4)

    camCBS = vtk.vtkCubeSource()
    camCBS.SetXLength(1.5)
    camCBS.SetZLength(0.8)
    camCBS.SetCenter(0.4, 0, 0)

    camAPD = vtk.vtkAppendFilter()
    camAPD.AddInputConnection(camCBS.GetOutputPort())
    camAPD.AddInputConnection(camCS.GetOutputPort())

    camMapper = vtk.vtkPolyDataMapper()
    camMapper.SetInputConnection(camAPD.GetOutputPort())
    camActor = vtk.vtkLODActor()
    camActor.SetMapper(camMapper)
    camActor.SetScale(2, 2, 2)

    # Draw the arrows.
    pd = vtk.vtkPolyData()
    ca = vtk.vtkCellArray()
    fp = vtk.vtkPoints()
    fp.InsertNextPoint(0, 1, 0)
    fp.InsertNextPoint(8, 1, 0)
    fp.InsertNextPoint(8, 2, 0)
    fp.InsertNextPoint(10, 0.01, 0)
    fp.InsertNextPoint(8, -2, 0)
    fp.InsertNextPoint(8, -1, 0)
    fp.InsertNextPoint(0, -1, 0)
    ca.InsertNextCell(7)
    ca.InsertCellPoint(0)
    ca.InsertCellPoint(1)
    ca.InsertCellPoint(2)
    ca.InsertCellPoint(3)
    ca.InsertCellPoint(4)
    ca.InsertCellPoint(5)
    ca.InsertCellPoint(6)
    pd.SetPoints(fp)
    pd.SetPolys(ca)

    pd2 = vtk.vtkPolyData()
    ca2 = vtk.vtkCellArray()
    fp2 = vtk.vtkPoints()
    fp2.InsertNextPoint(0, 1, 0)
    fp2.InsertNextPoint(8, 1, 0)
    fp2.InsertNextPoint(8, 2, 0)
    fp2.InsertNextPoint(10, 0.01, 0)
    ca2.InsertNextCell(4)
    ca2.InsertCellPoint(0)
    ca2.InsertCellPoint(1)
    ca2.InsertCellPoint(2)
    ca2.InsertCellPoint(3)
    pd2.SetPoints(fp2)
    pd2.SetLines(ca2)

    arrowIM = vtk.vtkImplicitModeller()
    arrowIM.SetInputData(pd)
    arrowIM.SetSampleDimensions(50, 20, 8)

    arrowCF = vtk.vtkContourFilter()
    arrowCF.SetInputConnection(arrowIM.GetOutputPort())
    arrowCF.SetValue(0, 0.2)

    arrowWT = vtk.vtkWarpTo()
    arrowWT.SetInputConnection(arrowCF.GetOutputPort())
    arrowWT.SetPosition(5, 0, 5)
    arrowWT.SetScaleFactor(0.85)
    arrowWT.AbsoluteOn()

    arrowT = vtk.vtkTransform()
    arrowT.RotateY(60)
    arrowT.Translate(-1.33198, 0, -1.479)
    arrowT.Scale(1, 0.5, 1)

    arrowTF = vtk.vtkTransformFilter()
    arrowTF.SetInputConnection(arrowWT.GetOutputPort())
    arrowTF.SetTransform(arrowT)

    arrowMapper = vtk.vtkDataSetMapper()
    arrowMapper.SetInputConnection(arrowTF.GetOutputPort())
    arrowMapper.ScalarVisibilityOff()

    # Draw the azimuth arrows.
    a1Actor = vtk.vtkLODActor()
    a1Actor.SetMapper(arrowMapper)
    a1Actor.RotateZ(180)
    a1Actor.SetPosition(1, 0, -1)
    a1Actor.GetProperty().SetColor(colors.GetColor3d('AzimuthArrowColor'))
    a1Actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    a1Actor.GetProperty().SetSpecular(0.3)
    a1Actor.GetProperty().SetSpecularPower(20)
    a1Actor.GetProperty().SetAmbient(0.2)
    a1Actor.GetProperty().SetDiffuse(0.8)

    a2Actor = vtk.vtkLODActor()
    a2Actor.SetMapper(arrowMapper)
    a2Actor.RotateZ(180)
    a2Actor.RotateX(180)
    a2Actor.SetPosition(1, 0, 1)
    a2Actor.GetProperty().SetColor(colors.GetColor3d('AzimuthArrowColor'))
    a2Actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    a2Actor.GetProperty().SetSpecular(0.3)
    a2Actor.GetProperty().SetSpecularPower(20)
    a2Actor.GetProperty().SetAmbient(0.2)
    a2Actor.GetProperty().SetDiffuse(0.8)

    # Draw the elevation arrows.
    a3Actor = vtk.vtkLODActor()
    a3Actor.SetMapper(arrowMapper)
    a3Actor.RotateZ(180)
    a3Actor.RotateX(90)
    a3Actor.SetPosition(1, -1, 0)
    a3Actor.GetProperty().SetColor(colors.GetColor3d('ElevationArrowColor'))
    a3Actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    a3Actor.GetProperty().SetSpecular(0.3)
    a3Actor.GetProperty().SetSpecularPower(20)
    a3Actor.GetProperty().SetAmbient(0.2)
    a3Actor.GetProperty().SetDiffuse(0.8)

    a4Actor = vtk.vtkLODActor()
    a4Actor.SetMapper(arrowMapper)
    a4Actor.RotateZ(180)
    a4Actor.RotateX(-90)
    a4Actor.SetPosition(1, 1, 0)
    a4Actor.GetProperty().SetColor(colors.GetColor3d('ElevationArrowColor'))
    a4Actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    a4Actor.GetProperty().SetSpecular(0.3)
    a4Actor.GetProperty().SetSpecularPower(20)
    a4Actor.GetProperty().SetAmbient(0.2)
    a4Actor.GetProperty().SetDiffuse(0.8)

    # Draw the DOP.
    arrowT2 = vtk.vtkTransform()
    arrowT2.Scale(1, 0.6, 1)
    arrowT2.RotateY(90)

    arrowTF2 = vtk.vtkTransformPolyDataFilter()
    arrowTF2.SetInputData(pd2)
    arrowTF2.SetTransform(arrowT2)

    arrowREF = vtk.vtkRotationalExtrusionFilter()
    arrowREF.SetInputConnection(arrowTF2.GetOutputPort())
    arrowREF.CappingOff()
    arrowREF.SetResolution(30)

    spikeMapper = vtk.vtkPolyDataMapper()
    spikeMapper.SetInputConnection(arrowREF.GetOutputPort())

    a5Actor = vtk.vtkLODActor()
    a5Actor.SetMapper(spikeMapper)
    a5Actor.SetScale(.3, .3, .6)
    a5Actor.RotateY(90)
    a5Actor.SetPosition(-2, 0, 0)
    a5Actor.GetProperty().SetColor(colors.GetColor3d('SpikeColor'))
    a5Actor.GetProperty().SetAmbient(0.2)
    a5Actor.GetProperty().SetDiffuse(0.8)

    # Focal point.
    fps = vtk.vtkSphereSource()
    fps.SetRadius(0.5)
    fpMapper = vtk.vtkPolyDataMapper()
    fpMapper.SetInputConnection(fps.GetOutputPort())
    fpActor = vtk.vtkLODActor()
    fpActor.SetMapper(fpMapper)
    fpActor.SetPosition(-9, 0, 0)
    fpActor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    fpActor.GetProperty().SetSpecular(0.3)
    fpActor.GetProperty().SetAmbient(0.2)
    fpActor.GetProperty().SetDiffuse(0.8)
    fpActor.GetProperty().SetSpecularPower(20)

    # Create the roll arrows.
    arrowWT2 = vtk.vtkWarpTo()
    arrowWT2.SetInputConnection(arrowCF.GetOutputPort())
    arrowWT2.SetPosition(5, 0, 2.5)
    arrowWT2.SetScaleFactor(0.95)
    arrowWT2.AbsoluteOn()

    arrowT3 = vtk.vtkTransform()
    arrowT3.Translate(-2.50358, 0, -1.70408)
    arrowT3.Scale(0.5, 0.3, 1)

    arrowTF3 = vtk.vtkTransformFilter()
    arrowTF3.SetInputConnection(arrowWT2.GetOutputPort())
    arrowTF3.SetTransform(arrowT3)

    arrowMapper2 = vtk.vtkDataSetMapper()
    arrowMapper2.SetInputConnection(arrowTF3.GetOutputPort())
    arrowMapper2.ScalarVisibilityOff()

    # Draw the roll arrows.
    a6Actor = vtk.vtkLODActor()
    a6Actor.SetMapper(arrowMapper2)
    a6Actor.RotateZ(90)
    a6Actor.SetPosition(-4, 0, 0)
    a6Actor.SetScale(1.5, 1.5, 1.5)
    a6Actor.GetProperty().SetColor(colors.GetColor3d('RollArrowColor'))
    a6Actor.GetProperty().SetSpecularColor(colors.GetColor3d('White'))
    a6Actor.GetProperty().SetSpecular(0.3)
    a6Actor.GetProperty().SetSpecularPower(20)
    a6Actor.GetProperty().SetAmbient(0.2)
    a6Actor.GetProperty().SetDiffuse(0.8)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(camActor)
    ren.AddActor(a1Actor)
    ren.AddActor(a2Actor)
    ren.AddActor(a3Actor)
    ren.AddActor(a4Actor)
    ren.AddActor(a5Actor)
    ren.AddActor(a6Actor)
    ren.AddActor(fpActor)
    ren.SetBackground(colors.GetColor3d('BkgColor'))
    ren.SetBackground(colors.GetColor3d('SlateGray'))
    renWin.SetSize(640, 480)
    renWin.SetWindowName('CameraModel1')

    # Render the image.

    cam1 = (ren.GetActiveCamera())
    ren.ResetCamera()
    cam1.Azimuth(150)
    cam1.Elevation(30)
    cam1.Dolly(1.5)
    ren.ResetCameraClippingRange()

    # Create a TextActor for azimuth  (a1 and a2 actor's color).
    text = vtk.vtkTextActor()
    text.SetInput('Azimuth')
    tprop = text.GetTextProperty()
    tprop.SetFontFamilyToArial()
    tprop.ShadowOff()
    tprop.SetLineSpacing(1.0)
    tprop.SetFontSize(36)
    tprop.SetColor(a1Actor.GetProperty().GetColor())
    text.SetDisplayPosition(20, 50)
    ren.AddActor2D(text)

    # Create a TextActor for elevation  (a3 and a4 actor's color).
    text2 = vtk.vtkTextActor()
    text2.SetInput('Elevation')
    tprop = text2.GetTextProperty()
    tprop.SetFontFamilyToArial()
    tprop.ShadowOff()
    tprop.SetLineSpacing(1.0)
    tprop.SetFontSize(36)
    tprop.SetColor(a3Actor.GetProperty().GetColor())
    text2.SetDisplayPosition(20, 100)
    ren.AddActor2D(text2)

    # Create a TextActor for roll (a6 actor's color).
    text3 = vtk.vtkTextActor()
    text3.SetInput('Roll')
    tprop = text3.GetTextProperty()
    tprop.SetFontFamilyToArial()
    tprop.ShadowOff()
    tprop.SetLineSpacing(1.0)
    tprop.SetFontSize(36)
    tprop.SetColor(a6Actor.GetProperty().GetColor())
    text3.SetDisplayPosition(20, 150)
    ren.AddActor2D(text3)

    iren.Initialize()
    iren.Start()
示例#45
0
def main(argv):
    colors = vtk.vtkNamedColors()

    #
    # Next we create an instance of vtkConeSource and set some of its
    # properties. The instance of vtkConeSource 'cone' is part of a
    # visualization pipeline (it is a source process object) it produces data
    # (output type is vtkPolyData) which other filters may process.
    #
    cone = vtk.vtkConeSource()
    cone.SetHeight(3.0)
    cone.SetRadius(1.0)
    cone.SetResolution(10)

    #
    # In this example we terminate the pipeline with a mapper process object.
    # (Intermediate filters such as vtkShrinkPolyData could be inserted in
    # between the source and the mapper.)  We create an instance of
    # vtkPolyDataMapper to map the polygonal data into graphics primitives. We
    # connect the output of the cone source to the input of this mapper.
    #
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())

    #
    # Create an actor to represent the cone. The actor orchestrates rendering
    # of the mapper's graphics primitives. An actor also refers to properties
    # via a vtkProperty instance, and includes an internal transformation
    # matrix. We set this actor's mapper to be coneMapper which we created
    # above.
    #
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.GetProperty().SetColor(colors.GetColor3d('MistyRose'))

    #
    # Create two renderers and assign actors to them. A renderer renders into
    # a viewport within the vtkRenderWindow. It is part or all of a window on
    # the screen and it is responsible for drawing the actors it has.  We also
    # set the background color here. In this example we are adding the same
    # actor to two different renderers it is okay to add different actors to
    # different renderers as well.
    #
    ren1 = vtk.vtkRenderer()
    ren1.AddActor(coneActor)
    ren1.SetBackground(colors.GetColor3d('RoyalBlue'))

    ren1.SetViewport(0.0, 0.0, 0.5, 1.0)

    ren2 = vtk.vtkRenderer()
    ren2.AddActor(coneActor)
    ren2.SetBackground(colors.GetColor3d('DodgerBlue'))
    ren2.SetViewport(0.5, 0.0, 1.0, 1.0)

    #
    # Finally we create the render window which will show up on the screen.
    # We put our renderer into the render window using AddRenderer. We also
    # set the size to be 300 pixels by 300.
    #
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    renWin.AddRenderer(ren2)
    renWin.SetSize(600, 300)
    renWin.SetWindowName('Tutorial_Step3')

    #
    # Make one view 90 degrees from other.
    #
    ren1.ResetCamera()
    ren1.GetActiveCamera().Azimuth(90)

    #
    # Now we loop over 360 degrees and render the cones each time.
    #
    for i in range(0, 360):  # render the image
        renWin.Render()
        # rotate the active camera by one degree
        ren1.GetActiveCamera().Azimuth(1)
        ren2.GetActiveCamera().Azimuth(1)
示例#46
0
import vtk
import time
import serial

cone = vtk.vtkConeSource()

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

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

# create coordinate axes in the render window
axes = vtk.vtkAxesActor()
axes.SetTotalLength(10, 20, 30)
axes.SetShaftType(0)
axes.SetAxisLabels(0)
axes.SetCylinderRadius(0.02)

filename = "arm.stl"

reader = vtk.vtkSTLReader()
reader.SetFileName(filename)

mapper1 = vtk.vtkPolyDataMapper()
mapper1.SetInputConnection(reader.GetOutputPort())

actor1 = vtk.vtkActor()
actor1.SetMapper(mapper1)

window = vtk.vtkRenderWindow()  # Sets the pixel width, length of the window.
示例#47
0
# Elevation just to generate another scalar attribute that varies nicely over the data range
elev = vtk.vtkElevationFilter()
# Elevation values will range from 0 to 1 between the Low and High Points
elev.SetLowPoint(-2, -2, 0)
elev.SetHighPoint(2, 2, 0)
elev.SetInputConnection(grad.GetOutputPort())

# Create simple PolyData for glyph table
cs = vtk.vtkCubeSource()
cs.SetXLength(0.5)
cs.SetYLength(1)
cs.SetZLength(2)
ss = vtk.vtkSphereSource()
ss.SetRadius(0.25)
cs2 = vtk.vtkConeSource()
cs2.SetRadius(0.25)
cs2.SetHeight(0.5)

# Set up the glyph filter
glyph = vtk.vtkGlyph3D()
glyph.SetInputConnection(elev.GetOutputPort())

# Here is where we build the glyph table
# that will be indexed into according to the IndexMode
glyph.SetSource(0, cs.GetOutput())
glyph.SetSource(1, ss.GetOutput())
glyph.SetSource(2, cs2.GetOutput())

glyph.ScalingOn()
glyph.SetScaleModeToScaleByScalar()
示例#48
0
def main():
    colors = vtk.vtkNamedColors()

    # The Wavelet Source is nice for generating a test vtkImageData set
    rt = vtk.vtkRTAnalyticSource()
    rt.SetWholeExtent(-2, 2, -2, 2, 0, 0)

    # Take the gradient of the only scalar 'RTData' to get a vector attribute
    grad = vtk.vtkImageGradient()
    grad.SetDimensionality(3)
    grad.SetInputConnection(rt.GetOutputPort())

    # Elevation just to generate another scalar attribute that varies nicely over the data range
    elev = vtk.vtkElevationFilter()
    # Elevation values will range from 0 to 1 between the Low and High Points
    elev.SetLowPoint(-2, -2, 0)
    elev.SetHighPoint(2, 2, 0)
    elev.SetInputConnection(grad.GetOutputPort())

    # Create simple PolyData for glyph table
    cs = vtk.vtkCubeSource()
    cs.SetXLength(0.5)
    cs.SetYLength(1)
    cs.SetZLength(2)
    ss = vtk.vtkSphereSource()
    ss.SetRadius(0.25)
    cs2 = vtk.vtkConeSource()
    cs2.SetRadius(0.25)
    cs2.SetHeight(0.5)

    # Set up the glyph filter
    glyph = vtk.vtkGlyph3D()
    glyph.SetInputConnection(elev.GetOutputPort())

    # Here is where we build the glyph table
    # that will be indexed into according to the IndexMode
    glyph.SetSourceConnection(0, cs.GetOutputPort())
    glyph.SetSourceConnection(1, ss.GetOutputPort())
    glyph.SetSourceConnection(2, cs2.GetOutputPort())

    glyph.ScalingOn()
    glyph.SetScaleModeToScaleByScalar()
    glyph.SetVectorModeToUseVector()
    glyph.OrientOn()
    glyph.SetScaleFactor(1)  # Overall scaling factor
    glyph.SetRange(0, 1)  # Default is (0,1)

    # Tell it to index into the glyph table according to scalars
    glyph.SetIndexModeToScalar()

    # Tell glyph which attribute arrays to use for what
    glyph.SetInputArrayToProcess(0, 0, 0, 0, 'Elevation')  # scalars
    glyph.SetInputArrayToProcess(1, 0, 0, 0, 'RTDataGradient')  # vectors

    coloring_by = 'Elevation'
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())
    mapper.SetScalarModeToUsePointFieldData()
    mapper.SetColorModeToMapScalars()
    mapper.ScalarVisibilityOn()

    # GetRange() call doesn't work because attributes weren't copied to glyphs
    # as they should have been...
    # mapper.SetScalarRange(glyph.GetOutputDataObject(0).GetPointData().GetArray(coloring_by).GetRange())

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

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(colors.GetColor3d("DarkGray"))

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetWindowName('GlyphTable')

    iren = vtk.vtkRenderWindowInteractor()
    istyle = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(istyle)
    iren.SetRenderWindow(renWin)
    ren.ResetCamera()
    renWin.Render()
    iren.Start()
示例#49
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()

    fran = vtk.vtkPolyDataReader()
    fran.SetFileName(fileName)

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(fran.GetOutputPort())
    normals.FlipNormalsOn()

    franMapper = vtk.vtkPolyDataMapper()
    franMapper.SetInputConnection(normals.GetOutputPort())

    franActor = vtk.vtkActor()
    franActor.SetMapper(franMapper)
    franActor.GetProperty().SetColor(colors.GetColor3d('Flesh'))

    # We subsample the dataset because we want to glyph just a subset of
    # the points. Otherwise the display is cluttered and cannot be easily
    # read. The RandomModeOn and SetOnRatio combine to random select one out
    # of every 10 points in the dataset.
    #
    ptMask = vtk.vtkMaskPoints()
    ptMask.SetInputConnection(normals.GetOutputPort())
    ptMask.SetOnRatio(10)
    ptMask.RandomModeOn()

    # In this case we are using a cone as a glyph. We transform the cone so
    # its base is at 0,0,0. This is the point where glyph rotation occurs.
    cone = vtk.vtkConeSource()
    cone.SetResolution(6)

    transform = vtk.vtkTransform()
    transform.Translate(0.5, 0.0, 0.0)

    transformF = vtk.vtkTransformPolyDataFilter()
    transformF.SetInputConnection(cone.GetOutputPort())
    transformF.SetTransform(transform)

    # vtkGlyph3D takes two inputs: the input point set (SetInputConnection)
    # which can be any vtkDataSet and the glyph (SetSourceConnection) which
    # must be a vtkPolyData.  We are interested in orienting the glyphs by the
    # surface normals that we previously generated.
    glyph = vtk.vtkGlyph3D()
    glyph.SetInputConnection(ptMask.GetOutputPort())
    glyph.SetSourceConnection(transformF.GetOutputPort())
    glyph.SetVectorModeToUseNormal()
    glyph.SetScaleModeToScaleByVector()
    glyph.SetScaleFactor(0.004)

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

    spikeActor = vtk.vtkActor()
    spikeActor.SetMapper(spikeMapper)
    spikeActor.GetProperty().SetColor(colors.GetColor3d('Emerald_Green'))

    # Create the RenderWindow, Renderer and Interactor.
    #
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size.
    #
    ren1.AddActor(franActor)
    ren1.AddActor(spikeActor)

    renWin.SetSize(640, 480)
    renWin.SetWindowName('SpikeFran')

    ren1.SetBackground(colors.GetColor3d('SlateGray'))

    # Render the image.
    #
    renWin.Render()

    ren1.GetActiveCamera().Zoom(1.4)
    ren1.GetActiveCamera().Azimuth(110)
    renWin.Render()
    iren.Start()
#coding:utf-8
import vtk
cone_a = vtk.vtkConeSource()
coneMapper = vtk.vtkPolyDataMapper()
coneMapper.SetInputConnection(cone_a.GetOutputPort())
coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMapper)
ren1 = vtk.vtkRenderer()
ren1.AddActor(coneActor)
ren1.SetBackground(0.1, 0.2, 0.4)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetSize(300, 300)
renWin.Render()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
iren.Start()
def GenerateAndDisplayCubeAndSphere():
    colors = vtk.vtkNamedColors()

    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetXLength(4.0)
    cubeSource.SetYLength(9.0)
    cubeSource.SetZLength(1.0)
    cubeSource.SetCenter(0.0, 0.0, 0.0)

    # Render the cube
    cubeMapper = vtk.vtkPolyDataMapper()
    cubeMapper.SetInputConnection(cubeSource.GetOutputPort())

    cubeActor = vtk.vtkActor()
    cubeActor.GetProperty().SetDiffuseColor(colors.GetColor3d("DarkGreen"))
    cubeActor.SetMapper(cubeMapper)

    coneSource = vtk.vtkConeSource()
    coneSource.SetCenter(0.0, 0.0, 0.0)
    coneSource.SetHeight(1.0)
    coneSource.SetRadius(0.25)
    coneSource.SetDirection(0.0, 1.0, 0.0)
    coneSource.SetResolution(60)
    coneSource.CappingOn()

    # Render the cone
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(coneSource.GetOutputPort())

    coneActor = vtk.vtkActor()
    coneActor.GetProperty().SetDiffuseColor(colors.GetColor3d("DarkTurquoise"))
    # Make the cone slightly transparent for fun
    coneActor.GetProperty().SetOpacity(0.75)
    coneActor.SetMapper(coneMapper)

    # The renderers, render window and interactor
    renderers = list()
    renWin = vtk.vtkRenderWindow()
    for i in range(0, 2):
        renderers.append(vtk.vtkRenderer())
        renWin.AddRenderer(renderers[i])
    renWin.SetSize(800, 800)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Layer 0 - background not transparent
    renderers[0].SetBackground(colors.GetColor3d("Silver"))
    renderers[0].AddActor(cubeActor)
    renderers[0].SetLayer(0)
    # Layer 1 - the background is transparent
    #           so we only see the layer 0 background color
    renderers[1].AddActor(coneActor)
    renderers[1].SetLayer(1)
    renderers[1].SetBackground(colors.GetColor3d("MidnightBlue"))

    #  We have two layers
    renWin.SetNumberOfLayers(2)
    renWin.Render()
    renWin.SetWindowName('TransparentBackground')

    iren.AddObserver('KeyPressEvent', KeypressCallbackFunction)

    iren.Start()
示例#52
0
def main(argv):
    colors = vtk.vtkNamedColors()

    #
    # Next we create an instance of vtkConeSource and set some of its
    # properties. The instance of vtkConeSource 'cone' is part of a
    # visualization pipeline (it is a source process object) it produces data
    # (output type is vtkPolyData) which other filters may process.
    #
    cone = vtk.vtkConeSource()
    cone.SetHeight(3.0)
    cone.SetRadius(1.0)
    cone.SetResolution(10)

    #
    # In this example we terminate the pipeline with a mapper process object.
    # (Intermediate filters such as vtkShrinkPolyData could be inserted in
    # between the source and the mapper.)  We create an instance of
    # vtkPolyDataMapper to map the polygonal data into graphics primitives. We
    # connect the output of the cone source to the input of this mapper.
    #
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())

    #
    # Create an actor to represent the cone. The actor orchestrates rendering
    # of the mapper's graphics primitives. An actor also refers to properties
    # via a vtkProperty instance, and includes an internal transformation
    # matrix. We set this actor's mapper to be coneMapper which we created
    # above.
    #
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.GetProperty().SetColor(colors.GetColor3d('Bisque'))

    #
    # Create the Renderer and assign actors to it. A renderer is like a
    # viewport. It is part or all of a window on the screen and it is
    # responsible for drawing the actors it has.  We also set the background
    # color here.
    #
    ren1 = vtk.vtkRenderer()
    ren1.AddActor(coneActor)
    ren1.SetBackground(colors.GetColor3d('MidnightBlue'))

    #
    # Finally we create the render window which will show up on the screen.
    # We put our renderer into the render window using AddRenderer. We also
    # set the size to be 300 pixels by 300.
    #
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    renWin.SetSize(300, 300)
    renWin.SetWindowName('Tutorial_Step6')

    #
    # The vtkRenderWindowInteractor class watches for events (e.g., keypress,
    # mouse) in the vtkRenderWindow. These events are translated into
    # event invocations that VTK understands (see VTK/Common/vtkCommand.h
    # for all events that VTK processes). Then observers of these VTK
    # events can process them as appropriate.
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    #
    # By default the vtkRenderWindowInteractor instantiates an instance
    # of vtkInteractorStyle. vtkInteractorStyle translates a set of events
    # it observes into operations on the camera, actors, and/or properties
    # in the vtkRenderWindow associated with the vtkRenderWinodwInteractor.
    # Here we specify a particular interactor style.
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)

    #
    # Here we use a vtkBoxWidget to transform the underlying coneActor (by
    # manipulating its transformation matrix). Many other types of widgets
    # are available for use, see the documentation for more details.
    #
    # The SetInteractor method is how 3D widgets are associated with the render
    # window interactor. Internally, SetInteractor sets up a bunch of callbacks
    # using the Command/Observer mechanism (AddObserver()). The place factor
    # controls the initial size of the widget with respect to the bounding box
    # of the input to the widget.
    boxWidget = vtk.vtkBoxWidget()
    boxWidget.SetInteractor(iren)
    boxWidget.SetPlaceFactor(1.25)
    boxWidget.GetOutlineProperty().SetColor(colors.GetColor3d('Gold'))

    #
    # Place the interactor initially. The input to a 3D widget is used to
    # initially position and scale the widget. The EndInteractionEvent is
    # observed which invokes the SelectPolygons callback.
    #
    boxWidget.SetProp3D(coneActor)
    boxWidget.PlaceWidget()
    callback = vtkMyCallback()
    boxWidget.AddObserver('InteractionEvent', callback)

    #
    # Normally the user presses the 'i' key to bring a 3D widget to life. Here
    # we will manually enable it so it appears with the cone.
    #
    boxWidget.On()

    #
    # Start the event loop.
    #
    iren.Initialize()
    iren.Start()
示例#53
0
 def __init__(self):
     self.cone = vtk.vtkConeSource()
示例#54
0
    def __init__(self, node, textHeight=5, color=None):

        # Create a 'vtkPolyData' object to represent the node
        polyData = vtk.vtkPolyData()

        # Create a 'vtkAppendPolyData' filter to append the node and it's supports together into a single dataset
        appendFilter = vtk.vtkAppendPolyData()

        # Get the node's position
        X = node.X  # Global X coordinate
        Y = node.Y  # Global Y coordinate
        Z = node.Z  # Global Z coordinate

        # Generate a sphere for the node
        sphere = vtk.vtkSphereSource()
        sphere.SetCenter(X, Y, Z)
        sphere.SetRadius(0.6 * textHeight)
        sphere.Update()

        polyData.ShallowCopy(sphere.GetOutput())
        appendFilter.AddInputData(polyData)

        # Create the text for the node label
        label = vtk.vtkVectorText()
        label.SetText(node.Name)

        # Set up a mapper for the node label
        lblMapper = vtk.vtkPolyDataMapper()
        lblMapper.SetInputConnection(label.GetOutputPort())

        # Set up an actor for the node label
        self.lblActor = vtk.vtkFollower()
        self.lblActor.SetMapper(lblMapper)
        self.lblActor.SetScale(textHeight, textHeight, textHeight)
        self.lblActor.SetPosition(X + 0.6 * textHeight, Y + 0.6 * textHeight,
                                  Z)

        # Generate any supports that occur at the node
        # Check for a fixed suppport
        if node.SupportDX == True and node.SupportDY == True and node.SupportDZ == True \
          and node.SupportRX == True and node.SupportRY == True and node.SupportRZ == True:

            # Create the fixed support
            support = vtk.vtkCubeSource()
            support.SetCenter(node.X, node.Y, node.Z)
            support.SetXLength(textHeight * 1.2)
            support.SetYLength(textHeight * 1.2)
            support.SetZLength(textHeight * 1.2)

            # Copy and append the support data to the append filter
            support.Update()
            polyData = vtk.vtkPolyData()
            polyData.ShallowCopy(support.GetOutput())
            appendFilter.AddInputData(polyData)

        # Check for a pinned support
        elif node.SupportDX == True and node.SupportDY == True and node.SupportDZ == True \
          and node.SupportRX == False and node.SupportRY == False and node.SupportRZ == False:

            # Create the pinned support
            support = vtk.vtkConeSource()
            support.SetCenter(node.X, node.Y - 0.6 * textHeight, node.Z)
            support.SetDirection((0, 1, 0))
            support.SetHeight(textHeight * 1.2)
            support.SetRadius(textHeight * 1.2)

            # Copy and append the support data to the append filter
            support.Update()
            polyData = vtk.vtkPolyData()
            polyData.ShallowCopy(support.GetOutput())
            appendFilter.AddInputData(polyData)

        # Other support conditions
        else:

            # Restrained against X translation
            if node.SupportDX == True:

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X - textHeight, node.Y, node.Z)
                support1.SetPoint2(node.X + textHeight, node.Y, node.Z)

                # Copy and append the support data to the append filter
                support1.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support1.GetOutput())
                appendFilter.AddInputData(polyData)

                support2 = vtk.vtkConeSource()
                support2.SetCenter(node.X - textHeight, node.Y, node.Z)
                support2.SetDirection((1, 0, 0))
                support2.SetHeight(textHeight * 0.6)
                support2.SetRadius(textHeight * 0.3)

                # Copy and append the support data to the append filter
                support2.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support2.GetOutput())
                appendFilter.AddInputData(polyData)

                support3 = vtk.vtkConeSource()
                support3.SetCenter(node.X + textHeight, node.Y, node.Z)
                support3.SetDirection((-1, 0, 0))
                support3.SetHeight(textHeight * 0.6)
                support3.SetRadius(textHeight * 0.3)

                # Copy and append the support data to the append filter
                support3.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support3.GetOutput())
                appendFilter.AddInputData(polyData)

            # Restrained against Y translation
            if node.SupportDY == True:

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y - textHeight, node.Z)
                support1.SetPoint2(node.X, node.Y + textHeight, node.Z)

                # Copy and append the support data to the append filter
                support1.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support1.GetOutput())
                appendFilter.AddInputData(polyData)

                support2 = vtk.vtkConeSource()
                support2.SetCenter(node.X, node.Y - textHeight, node.Z)
                support2.SetDirection((0, 1, 0))
                support2.SetHeight(textHeight * 0.6)
                support2.SetRadius(textHeight * 0.3)

                # Copy and append the support data to the append filter
                support2.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support2.GetOutput())
                appendFilter.AddInputData(polyData)

                support3 = vtk.vtkConeSource()
                support3.SetCenter(node.X, node.Y + textHeight, node.Z)
                support3.SetDirection((0, -1, 0))
                support3.SetHeight(textHeight * 0.6)
                support3.SetRadius(textHeight * 0.3)

                # Copy and append the support data to the append filter
                support3.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support3.GetOutput())
                appendFilter.AddInputData(polyData)

            # Restrained against Z translation
            if node.SupportDZ == True:

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y, node.Z - textHeight)
                support1.SetPoint2(node.X, node.Y, node.Z + textHeight)

                # Copy and append the support data to the append filter
                support1.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support1.GetOutput())
                appendFilter.AddInputData(polyData)

                support2 = vtk.vtkConeSource()
                support2.SetCenter(node.X, node.Y, node.Z - textHeight)
                support2.SetDirection((0, 0, 1))
                support2.SetHeight(textHeight * 0.6)
                support2.SetRadius(textHeight * 0.3)

                # Copy and append the support data to the append filter
                support2.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support2.GetOutput())
                appendFilter.AddInputData(polyData)

                support3 = vtk.vtkConeSource()
                support3.SetCenter(node.X, node.Y, node.Z + textHeight)
                support3.SetDirection((0, 0, -1))
                support3.SetHeight(textHeight * 0.6)
                support3.SetRadius(textHeight * 0.3)

                # Copy and append the support data to the append filter
                support3.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support3.GetOutput())
                appendFilter.AddInputData(polyData)

            # Restrained against rotation about the X-axis
            if node.SupportRX == True:

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X - 1.6 * textHeight, node.Y, node.Z)
                support1.SetPoint2(node.X + 1.6 * textHeight, node.Y, node.Z)

                # Copy and append the support data to the append filter
                support1.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support1.GetOutput())
                appendFilter.AddInputData(polyData)

                support2 = vtk.vtkCubeSource()
                support2.SetCenter(node.X - 1.9 * textHeight, node.Y, node.Z)
                support2.SetXLength(textHeight * 0.6)
                support2.SetYLength(textHeight * 0.6)
                support2.SetZLength(textHeight * 0.6)

                # Copy and append the support data to the append filter
                support2.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support2.GetOutput())
                appendFilter.AddInputData(polyData)

                support3 = vtk.vtkCubeSource()
                support3.SetCenter(node.X + 1.9 * textHeight, node.Y, node.Z)
                support3.SetXLength(textHeight * 0.6)
                support3.SetYLength(textHeight * 0.6)
                support3.SetZLength(textHeight * 0.6)

                # Copy and append the support data to the append filter
                support3.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support3.GetOutput())
                appendFilter.AddInputData(polyData)

            # Restrained against rotation about the Y-axis
            if node.SupportRY == True:

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y - 1.6 * textHeight, node.Z)
                support1.SetPoint2(node.X, node.Y + 1.6 * textHeight, node.Z)

                # Copy and append the support data to the append filter
                support1.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support1.GetOutput())
                appendFilter.AddInputData(polyData)

                support2 = vtk.vtkCubeSource()
                support2.SetCenter(node.X, node.Y - 1.9 * textHeight, node.Z)
                support2.SetXLength(textHeight * 0.6)
                support2.SetYLength(textHeight * 0.6)
                support2.SetZLength(textHeight * 0.6)

                # Copy and append the support data to the append filter
                support2.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support2.GetOutput())
                appendFilter.AddInputData(polyData)

                support3 = vtk.vtkCubeSource()
                support3.SetCenter(node.X, node.Y + 1.9 * textHeight, node.Z)
                support3.SetXLength(textHeight * 0.6)
                support3.SetYLength(textHeight * 0.6)
                support3.SetZLength(textHeight * 0.6)

                # Copy and append the support data to the append filter
                support3.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support3.GetOutput())
                appendFilter.AddInputData(polyData)

            # Restrained against rotation about the Z-axis
            if node.SupportRZ == True:

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y, node.Z - 1.6 * textHeight)
                support1.SetPoint2(node.X, node.Y, node.Z + 1.6 * textHeight)

                # Copy and append the support data to the append filter
                support1.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support1.GetOutput())
                appendFilter.AddInputData(polyData)

                support2 = vtk.vtkCubeSource()
                support2.SetCenter(node.X, node.Y, node.Z - 1.9 * textHeight)
                support2.SetXLength(textHeight * 0.6)
                support2.SetYLength(textHeight * 0.6)
                support2.SetZLength(textHeight * 0.6)

                # Copy and append the support data to the append filter
                support2.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support2.GetOutput())
                appendFilter.AddInputData(polyData)

                support3 = vtk.vtkCubeSource()
                support3.SetCenter(node.X, node.Y, node.Z + 1.9 * textHeight)
                support3.SetXLength(textHeight * 0.6)
                support3.SetYLength(textHeight * 0.6)
                support3.SetZLength(textHeight * 0.6)

                # Copy and append the support data to the append filter
                support3.Update()
                polyData = vtk.vtkPolyData()
                polyData.ShallowCopy(support3.GetOutput())
                appendFilter.AddInputData(polyData)

        # Update the append filter
        appendFilter.Update()

        # Create a mapper and actor
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(appendFilter.GetOutputPort())
        self.actor = vtk.vtkActor()

        # Add color to the actors
        if color == 'red':
            self.actor.GetProperty().SetColor(255, 0, 0)  # Red
            self.lblActor.GetProperty().SetColor(255, 0, 0)  # Red
        elif color == 'yellow':
            self.actor.GetProperty().SetColor(255, 255, 0)  # Yellow
            self.lblActor.GetProperty().SetColor(255, 255, 0)  # Yellow

        # Set the mapper for the node's actor
        self.actor.SetMapper(mapper)
示例#55
0
    def __init__(self, node, textHeight=5):

        # Get the node's position
        X = node.X  # Global X coordinate
        Y = node.Y  # Global Y coordinate
        Z = node.Z  # Global Z coordinate

        # Generate a sphere for the node
        sphere = vtk.vtkSphereSource()
        sphere.SetCenter(X, Y, Z)
        sphere.SetRadius(0.6 * textHeight)

        # Set up a mapper for the node
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphere.GetOutputPort())

        # Set up an actor for the node
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(mapper)

        # Create the text for the node label
        label = vtk.vtkVectorText()
        label.SetText(node.Name)

        # Set up a mapper for the node label
        lblMapper = vtk.vtkPolyDataMapper()
        lblMapper.SetInputConnection(label.GetOutputPort())

        # Set up an actor for the node label
        self.lblActor = vtk.vtkFollower()
        self.lblActor.SetMapper(lblMapper)
        self.lblActor.SetScale(textHeight, textHeight, textHeight)
        self.lblActor.SetPosition(X + 0.6 * textHeight, Y + 0.6 * textHeight,
                                  Z)

        # Generate any supports that occur at the node
        supportMappers = []
        self.supportActors = []

        # Check for a fixed suppport
        if (node.SupportDX == True) and (node.SupportDY == True) and (node.SupportDZ == True) \
          and (node.SupportRX == True) and (node.SupportRY == True) and (node.SupportRZ == True):

            # Create the fixed support
            support = vtk.vtkCubeSource()
            support.SetCenter(node.X, node.Y, node.Z)
            support.SetXLength(textHeight * 1.2)
            support.SetYLength(textHeight * 1.2)
            support.SetZLength(textHeight * 1.2)

            # Change the node's mapper to the fixed support
            mapper.SetInputConnection(support.GetOutputPort())

        # Check for a pinned support
        elif (node.SupportDX == True) and (node.SupportDY == True) and (node.SupportDZ == True) \
          and (node.SupportRX == False) and (node.SupportRY == False) and (node.SupportRZ == False):

            # Create the pinned support
            support = vtk.vtkConeSource()
            support.SetCenter(node.X, node.Y - 0.6 * textHeight, node.Z)
            support.SetDirection((0, 1, 0))
            support.SetHeight(textHeight * 1.2)
            support.SetRadius(textHeight * 1.2)

            # Change the node's mapper to the pinned support
            mapper.SetInputConnection(support.GetOutputPort())

        # Other support conditions
        else:

            # Restrained against X translation
            if (node.SupportDX == True):

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X - textHeight, node.Y, node.Z)
                support1.SetPoint2(node.X + textHeight, node.Y, node.Z)

                support2 = vtk.vtkConeSource()
                support2.SetCenter(node.X - textHeight, node.Y, node.Z)
                support2.SetDirection((1, 0, 0))
                support2.SetHeight(textHeight * 0.6)
                support2.SetRadius(textHeight * 0.3)

                support3 = vtk.vtkConeSource()
                support3.SetCenter(node.X + textHeight, node.Y, node.Z)
                support3.SetDirection((-1, 0, 0))
                support3.SetHeight(textHeight * 0.6)
                support3.SetRadius(textHeight * 0.3)

                # Set up mappers for the support
                supportMapper1 = vtk.vtkPolyDataMapper()
                supportMapper2 = vtk.vtkPolyDataMapper()
                supportMapper3 = vtk.vtkPolyDataMapper()
                supportMapper1.SetInputConnection(support1.GetOutputPort())
                supportMapper2.SetInputConnection(support2.GetOutputPort())
                supportMapper3.SetInputConnection(support3.GetOutputPort())
                supportMappers.append(supportMapper1)
                supportMappers.append(supportMapper2)
                supportMappers.append(supportMapper3)

                # Set up actors for the support
                supportActor1 = vtk.vtkActor()
                supportActor2 = vtk.vtkActor()
                supportActor3 = vtk.vtkActor()
                supportActor1.SetMapper(supportMapper1)
                supportActor2.SetMapper(supportMapper2)
                supportActor3.SetMapper(supportMapper3)
                self.supportActors.append(supportActor1)
                self.supportActors.append(supportActor2)
                self.supportActors.append(supportActor3)

            # Restrained against Y translation
            if (node.SupportDY == True):

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y - textHeight, node.Z)
                support1.SetPoint2(node.X, node.Y + textHeight, node.Z)

                support2 = vtk.vtkConeSource()
                support2.SetCenter(node.X, node.Y - textHeight, node.Z)
                support2.SetDirection((0, 1, 0))
                support2.SetHeight(textHeight * 0.6)
                support2.SetRadius(textHeight * 0.3)

                support3 = vtk.vtkConeSource()
                support3.SetCenter(node.X, node.Y + textHeight, node.Z)
                support3.SetDirection((0, -1, 0))
                support3.SetHeight(textHeight * 0.6)
                support3.SetRadius(textHeight * 0.3)

                # Set up mappers for the support
                supportMapper1 = vtk.vtkPolyDataMapper()
                supportMapper2 = vtk.vtkPolyDataMapper()
                supportMapper3 = vtk.vtkPolyDataMapper()
                supportMapper1.SetInputConnection(support1.GetOutputPort())
                supportMapper2.SetInputConnection(support2.GetOutputPort())
                supportMapper3.SetInputConnection(support3.GetOutputPort())
                supportMappers.append(supportMapper1)
                supportMappers.append(supportMapper2)
                supportMappers.append(supportMapper3)

                # Set up actors for the support
                supportActor1 = vtk.vtkActor()
                supportActor2 = vtk.vtkActor()
                supportActor3 = vtk.vtkActor()
                supportActor1.SetMapper(supportMapper1)
                supportActor2.SetMapper(supportMapper2)
                supportActor3.SetMapper(supportMapper3)
                self.supportActors.append(supportActor1)
                self.supportActors.append(supportActor2)
                self.supportActors.append(supportActor3)

            # Restrained against Z translation
            if (node.SupportDZ == True):

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y, node.Z - textHeight)
                support1.SetPoint2(node.X, node.Y, node.Z + textHeight)

                support2 = vtk.vtkConeSource()
                support2.SetCenter(node.X, node.Y, node.Z - textHeight)
                support2.SetDirection((0, 0, 1))
                support2.SetHeight(textHeight * 0.6)
                support2.SetRadius(textHeight * 0.3)

                support3 = vtk.vtkConeSource()
                support3.SetCenter(node.X, node.Y, node.Z + textHeight)
                support3.SetDirection((0, 0, -1))
                support3.SetHeight(textHeight * 0.6)
                support3.SetRadius(textHeight * 0.3)

                # Set up mappers for the support
                supportMapper1 = vtk.vtkPolyDataMapper()
                supportMapper2 = vtk.vtkPolyDataMapper()
                supportMapper3 = vtk.vtkPolyDataMapper()
                supportMapper1.SetInputConnection(support1.GetOutputPort())
                supportMapper2.SetInputConnection(support2.GetOutputPort())
                supportMapper3.SetInputConnection(support3.GetOutputPort())
                supportMappers.append(supportMapper1)
                supportMappers.append(supportMapper2)
                supportMappers.append(supportMapper3)

                # Set actors for the support
                supportActor1 = vtk.vtkActor()
                supportActor2 = vtk.vtkActor()
                supportActor3 = vtk.vtkActor()
                supportActor1.SetMapper(supportMapper1)
                supportActor2.SetMapper(supportMapper2)
                supportActor3.SetMapper(supportMapper3)
                self.supportActors.append(supportActor1)
                self.supportActors.append(supportActor2)
                self.supportActors.append(supportActor3)

            # Restrained against rotation about the X-axis
            if (node.SupportRX == True):

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X - 1.6 * textHeight, node.Y, node.Z)
                support1.SetPoint2(node.X + 1.6 * textHeight, node.Y, node.Z)

                support2 = vtk.vtkCubeSource()
                support2.SetCenter(node.X - 1.9 * textHeight, node.Y, node.Z)
                support2.SetXLength(textHeight * 0.6)
                support2.SetYLength(textHeight * 0.6)
                support2.SetZLength(textHeight * 0.6)

                support3 = vtk.vtkCubeSource()
                support3.SetCenter(node.X + 1.9 * textHeight, node.Y, node.Z)
                support3.SetXLength(textHeight * 0.6)
                support3.SetYLength(textHeight * 0.6)
                support3.SetZLength(textHeight * 0.6)

                # Set up mappers for the support
                supportMapper1 = vtk.vtkPolyDataMapper()
                supportMapper2 = vtk.vtkPolyDataMapper()
                supportMapper3 = vtk.vtkPolyDataMapper()
                supportMapper1.SetInputConnection(support1.GetOutputPort())
                supportMapper2.SetInputConnection(support2.GetOutputPort())
                supportMapper3.SetInputConnection(support3.GetOutputPort())
                supportMappers.append(supportMapper1)
                supportMappers.append(supportMapper2)
                supportMappers.append(supportMapper3)

                # Set up actors for the support
                supportActor1 = vtk.vtkActor()
                supportActor2 = vtk.vtkActor()
                supportActor3 = vtk.vtkActor()
                supportActor1.SetMapper(supportMapper1)
                supportActor2.SetMapper(supportMapper2)
                supportActor3.SetMapper(supportMapper3)
                self.supportActors.append(supportActor1)
                self.supportActors.append(supportActor2)
                self.supportActors.append(supportActor3)

            # Restrained against rotation about the Y-axis
            if (node.SupportRY == True):

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y - 1.6 * textHeight, node.Z)
                support1.SetPoint2(node.X, node.Y + 1.6 * textHeight, node.Z)

                support2 = vtk.vtkCubeSource()
                support2.SetCenter(node.X, node.Y - 1.9 * textHeight, node.Z)
                support2.SetXLength(textHeight * 0.6)
                support2.SetYLength(textHeight * 0.6)
                support2.SetZLength(textHeight * 0.6)

                support3 = vtk.vtkCubeSource()
                support3.SetCenter(node.X, node.Y + 1.9 * textHeight, node.Z)
                support3.SetXLength(textHeight * 0.6)
                support3.SetYLength(textHeight * 0.6)
                support3.SetZLength(textHeight * 0.6)

                # Set up mappers for the support
                supportMapper1 = vtk.vtkPolyDataMapper()
                supportMapper2 = vtk.vtkPolyDataMapper()
                supportMapper3 = vtk.vtkPolyDataMapper()
                supportMapper1.SetInputConnection(support1.GetOutputPort())
                supportMapper2.SetInputConnection(support2.GetOutputPort())
                supportMapper3.SetInputConnection(support3.GetOutputPort())
                supportMappers.append(supportMapper1)
                supportMappers.append(supportMapper2)
                supportMappers.append(supportMapper3)

                # Set up actors for the support
                supportActor1 = vtk.vtkActor()
                supportActor2 = vtk.vtkActor()
                supportActor3 = vtk.vtkActor()
                supportActor1.SetMapper(supportMapper1)
                supportActor2.SetMapper(supportMapper2)
                supportActor3.SetMapper(supportMapper3)
                self.supportActors.append(supportActor1)
                self.supportActors.append(supportActor2)
                self.supportActors.append(supportActor3)

            # Restrained against rotation about the Z-axis
            if (node.SupportRZ == True):

                # Create the support
                support1 = vtk.vtkLineSource(
                )  # The line showing the support direction
                support1.SetPoint1(node.X, node.Y, node.Z - 1.6 * textHeight)
                support1.SetPoint2(node.X, node.Y, node.Z + 1.6 * textHeight)

                support2 = vtk.vtkCubeSource()
                support2.SetCenter(node.X, node.Y, node.Z - 1.9 * textHeight)
                support2.SetXLength(textHeight * 0.6)
                support2.SetYLength(textHeight * 0.6)
                support2.SetZLength(textHeight * 0.6)

                support3 = vtk.vtkCubeSource()
                support3.SetCenter(node.X, node.Y, node.Z + 1.9 * textHeight)
                support3.SetXLength(textHeight * 0.6)
                support3.SetYLength(textHeight * 0.6)
                support3.SetZLength(textHeight * 0.6)

                # Set up mappers for the support
                supportMapper1 = vtk.vtkPolyDataMapper()
                supportMapper2 = vtk.vtkPolyDataMapper()
                supportMapper3 = vtk.vtkPolyDataMapper()
                supportMapper1.SetInputConnection(support1.GetOutputPort())
                supportMapper2.SetInputConnection(support2.GetOutputPort())
                supportMapper3.SetInputConnection(support3.GetOutputPort())
                supportMappers.append(supportMapper1)
                supportMappers.append(supportMapper2)
                supportMappers.append(supportMapper3)

                # Set up actors for the support
                supportActor1 = vtk.vtkActor()
                supportActor2 = vtk.vtkActor()
                supportActor3 = vtk.vtkActor()
                supportActor1.SetMapper(supportMapper1)
                supportActor2.SetMapper(supportMapper2)
                supportActor3.SetMapper(supportMapper3)
                self.supportActors.append(supportActor1)
                self.supportActors.append(supportActor2)
                self.supportActors.append(supportActor3)
示例#56
0
 def quiver3d(self,
              x,
              y,
              z,
              u,
              v,
              w,
              color,
              scale,
              mode,
              resolution=8,
              glyph_height=None,
              glyph_center=None,
              glyph_resolution=None,
              opacity=1.0,
              scale_mode='none',
              scalars=None,
              backface_culling=False,
              line_width=2.,
              name=None):
     _check_option('mode', mode, ALLOWED_QUIVER_MODES)
     with warnings.catch_warnings():
         warnings.filterwarnings("ignore", category=FutureWarning)
         factor = scale
         vectors = np.c_[u, v, w]
         points = np.vstack(np.c_[x, y, z])
         n_points = len(points)
         cell_type = np.full(n_points, vtk.VTK_VERTEX)
         cells = np.c_[np.full(n_points, 1), range(n_points)]
         args = (cells, cell_type, points)
         if not VTK9:
             args = (np.arange(n_points) * 3, ) + args
         grid = UnstructuredGrid(*args)
         grid.point_arrays['vec'] = vectors
         if scale_mode == 'scalar':
             grid.point_arrays['mag'] = np.array(scalars)
             scale = 'mag'
         else:
             scale = False
         if mode == '2darrow':
             return _arrow_glyph(grid, factor), grid
         elif mode == 'arrow':
             alg = _glyph(grid, orient='vec', scalars=scale, factor=factor)
             mesh = pyvista.wrap(alg.GetOutput())
         else:
             if mode == 'cone':
                 glyph = vtk.vtkConeSource()
                 glyph.SetCenter(0.5, 0, 0)
                 glyph.SetRadius(0.15)
             elif mode == 'cylinder':
                 glyph = vtk.vtkCylinderSource()
                 glyph.SetRadius(0.15)
             else:
                 assert mode == 'sphere', mode  # guaranteed above
                 glyph = vtk.vtkSphereSource()
             if mode == 'cylinder':
                 if glyph_height is not None:
                     glyph.SetHeight(glyph_height)
                 if glyph_center is not None:
                     glyph.SetCenter(glyph_center)
                 if glyph_resolution is not None:
                     glyph.SetResolution(glyph_resolution)
                 # fix orientation
                 glyph.Update()
                 tr = vtk.vtkTransform()
                 tr.RotateWXYZ(90, 0, 0, 1)
                 trp = vtk.vtkTransformPolyDataFilter()
                 trp.SetInputData(glyph.GetOutput())
                 trp.SetTransform(tr)
                 glyph = trp
             glyph.Update()
             geom = glyph.GetOutput()
             mesh = grid.glyph(orient='vec',
                               scale=scale,
                               factor=factor,
                               geom=geom)
         _add_mesh(self.plotter,
                   mesh=mesh,
                   color=color,
                   opacity=opacity,
                   backface_culling=backface_culling)
示例#57
0
    def DisplayCone(self):
        ''' 
            Create a cone, contour it using the banded contour filter and
                color it with the primary additive and subtractive colors.
        '''
        #print namedColors

        # Create a cone
        coneSource = vtk.vtkConeSource()
        coneSource.SetCenter(0.0, 0.0, 0.0)
        coneSource.SetRadius(5.0)
        coneSource.SetHeight(10)
        coneSource.SetDirection(0, 1, 0)
        coneSource.Update()

        bounds = [1.0, -1.0, 1.0, -1.0, 1.0, -1.0]
        coneSource.GetOutput().GetBounds(bounds)

        elevation = vtk.vtkElevationFilter()
        elevation.SetInputConnection(coneSource.GetOutputPort())
        elevation.SetLowPoint(0, bounds[2], 0)
        elevation.SetHighPoint(0, bounds[3], 0)

        bcf = vtk.vtkBandedPolyDataContourFilter()
        bcf.SetInputConnection(elevation.GetOutputPort())
        bcf.SetScalarModeToValue()
        bcf.GenerateContourEdgesOn()
        bcf.GenerateValues(7, elevation.GetScalarRange())

        # Build a simple lookup table of
        # primary additive and subtractive colors.
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfTableValues(7)
        # Test setting and getting a color here.
        # We are also modifying alpha.
        rgba = self.GetRGBAColor("Red")
        rgba[3] = 0.5
        self.namedColors.SetColor("My Red", rgba)
        rgba = self.GetRGBAColor("My Red")
        lut.SetTableValue(0, rgba)
        # Does "My Red" match anything?
        match = self.FindSynonyms("My Red")
        print "Matching colors to My Red:", match

        rgba = self.GetRGBAColor("DarkGreen")
        rgba[3] = 0.3
        lut.SetTableValue(1, rgba)
        #  Alternatively we can use our wrapper functions:
        lut.SetTableValue(2, self.GetRGBAColor("Blue"))
        lut.SetTableValue(3, self.GetRGBAColor("Cyan"))
        lut.SetTableValue(4, self.GetRGBAColor("Magenta"))
        lut.SetTableValue(5, self.GetRGBAColor("Yellow"))
        lut.SetTableValue(6, self.GetRGBAColor("White"))
        lut.SetTableRange(elevation.GetScalarRange())
        lut.Build()

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(bcf.GetOutputPort())
        mapper.SetLookupTable(lut)
        mapper.SetScalarModeToUseCellData()

        contourLineMapper = vtk.vtkPolyDataMapper()
        contourLineMapper.SetInputData(bcf.GetContourEdgesOutput())
        contourLineMapper.SetScalarRange(elevation.GetScalarRange())
        contourLineMapper.SetResolveCoincidentTopologyToPolygonOffset()

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

        contourLineActor = vtk.vtkActor()
        actor.SetMapper(mapper)
        contourLineActor.SetMapper(contourLineMapper)
        contourLineActor.GetProperty().SetColor(self.GetRGBColor("black"))

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

        renderer.AddActor(actor)
        renderer.AddActor(contourLineActor)
        renderer.SetBackground(self.GetRGBColor("SteelBlue"))

        renderWindow.Render()

        fnsave = "TestNamedColorsIntegration.png"
        renLgeIm = vtk.vtkRenderLargeImage()
        imgWriter = vtk.vtkPNGWriter()
        renLgeIm.SetInput(renderer)
        renLgeIm.SetMagnification(1)
        imgWriter.SetInputConnection(renLgeIm.GetOutputPort())
        imgWriter.SetFileName(fnsave)
        imgWriter.Write()

        renderWindowInteractor.Start()
示例#58
0
    def updateAffectiveZone(self, caller=None, event=None):
        targetingNode = self.targetingPlugin.targetTablePlugin.currentTargets
        if self.targetingPlugin.fiducialsWidget.visible:
            targetingNode = self.targetingPlugin.fiducialsWidget.currentNode
        if self.needleModelNode and self.affectedAreaModelNode and self.approvedCoverTemplate and targetingNode.GetNumberOfFiducials(
        ):
            needleModelAppend = vtk.vtkAppendPolyData()
            affectedBallAreaAppend = vtk.vtkAppendPolyData()
            zFrameTransformMatrix = self.data.zFrameRegistrationResult.transform.GetMatrixTransformToParent(
            )
            # The offset and ellipsoid parameters are taken from the following source code
            # http://viewvc.slicer.org/viewvc.cgi/NAMICSandBox/trunk/IGTLoadableModules/ProstateNav/TransPerinealProstateCryoTemplate/vtkMRMLTransPerinealProstateCryoTemplateNode.cxx?revision=8043&view=markup
            offsetFromTip = 5.0  #unit mm
            coneHeight = 5.0
            for targetIndex in range(targetingNode.GetNumberOfFiducials()):
                if self.displayForTargets.get(
                        targetingNode.GetNthMarkupID(
                            targetIndex)) == qt.Qt.Checked:
                    affectedBallAreaRadius = self.GetIceBallRadius(
                        self.needleTypeForTargets.get(
                            targetingNode.GetNthMarkupID(
                                targetIndex)))  # unit mm
                    targetPosition = [0.0, 0.0, 0.0]
                    targetingNode.GetNthFiducialPosition(
                        targetIndex, targetPosition)
                    (start, end, indexX, indexY, depth,
                     inRange) = self.needlePathCaculator.computeNearestPath(
                         targetPosition)
                    needleDirection = (numpy.array(end) -
                                       numpy.array(start)) / numpy.linalg.norm(
                                           numpy.array(end) -
                                           numpy.array(start))
                    cone = vtk.vtkConeSource()
                    cone.SetRadius(1.5)
                    cone.SetResolution(6)
                    cone.SetHeight(coneHeight)
                    cone.CappingOff()
                    cone.Update()
                    transform = vtk.vtkTransform()
                    transform.RotateY(-90)
                    transform.RotateX(30)
                    transform.Translate(-coneHeight / 2, 0.0, 0.0)
                    tFilter0 = vtk.vtkTransformPolyDataFilter()
                    tFilter0.SetInputData(cone.GetOutput())
                    tFilter0.SetTransform(transform)
                    tFilter0.Update()
                    translatePart = start + depth * needleDirection
                    for index, posElement in enumerate(translatePart):
                        zFrameTransformMatrix.SetElement(index, 3, posElement)
                    transform.SetMatrix(zFrameTransformMatrix)
                    tFilter1 = vtk.vtkTransformPolyDataFilter()
                    tFilter1.SetTransform(transform)
                    tFilter1.SetInputData(tFilter0.GetOutput())
                    tFilter1.Update()
                    needleModelAppend.AddInputData(tFilter1.GetOutput())
                    needleModelAppend.Update()
                    pathTubeFilter = ModuleLogicMixin.createVTKTubeFilter(
                        start,
                        start + (depth - coneHeight) * needleDirection,
                        radius=1.5,
                        numSides=6)
                    needleModelAppend.AddInputData(pathTubeFilter.GetOutput())
                    needleModelAppend.Update()
                    #End of needle model
                    #--------------
                    #--------------
                    #Begin of affectedBallArea
                    affectedBallArea = vtk.vtkParametricEllipsoid()
                    affectedBallArea.SetXRadius(
                        float(affectedBallAreaRadius[0]))
                    affectedBallArea.SetYRadius(
                        float(affectedBallAreaRadius[1]))
                    affectedBallArea.SetZRadius(
                        float(affectedBallAreaRadius[2]))
                    affectedBallAreaSource = vtk.vtkParametricFunctionSource()
                    affectedBallAreaSource.SetParametricFunction(
                        affectedBallArea)
                    affectedBallAreaSource.SetScalarModeToV()
                    affectedBallAreaSource.Update()
                    translatePart = start + (depth + offsetFromTip - float(
                        affectedBallAreaRadius[2])) * needleDirection
                    for index, posElement in enumerate(translatePart):
                        zFrameTransformMatrix.SetElement(index, 3, posElement)
                    transform.SetMatrix(zFrameTransformMatrix)
                    tFilter2 = vtk.vtkTransformPolyDataFilter()
                    tFilter2.SetTransform(transform)
                    tFilter2.SetInputData(affectedBallAreaSource.GetOutput())
                    tFilter2.Update()
                    affectedBallAreaAppend.AddInputData(tFilter2.GetOutput())
                    affectedBallAreaAppend.Update()

            self.needleModelNode.SetAndObservePolyData(
                needleModelAppend.GetOutput())
            self.affectedAreaModelNode.SetAndObservePolyData(
                affectedBallAreaAppend.GetOutput())
            ModuleLogicMixin.setNodeVisibility(self.needleModelNode, True)
            ModuleLogicMixin.setNodeVisibility(self.affectedAreaModelNode,
                                               True)
            ModuleLogicMixin.setNodeSliceIntersectionVisibility(
                self.needleModelNode, True)
            ModuleLogicMixin.setNodeSliceIntersectionVisibility(
                self.affectedAreaModelNode, True)
        pass
示例#59
0
    def __init__(self, ren, renWin, iren):

        self.ren = ren
        self.renWin = renWin
        self.iren = iren

        colors = self.Colors()

        self.renWin.AddRenderer(self.ren)

        self.iren.SetRenderWindow(self.renWin)
        self.iren.SetDesiredUpdateRate(.00001)

        # Create a sphere source and actor

        sphere = vtk.vtkSphereSource()

        sphereMapper = vtk.vtkPolyDataMapper()
        sphereMapper.SetInputConnection(sphere.GetOutputPort())

        sphereActor = vtk.vtkLODActor()
        sphereActor.SetMapper(sphereMapper)

        sphereActor.GetProperty().SetDiffuseColor(colors.GetRGBColor('banana'))
        sphereActor.GetProperty().SetSpecular(.4)
        sphereActor.GetProperty().SetSpecularPower(20)

        # Create the spikes using a cone source and the sphere source

        cone = vtk.vtkConeSource()
        cone.SetResolution(20)

        glyph = vtk.vtkGlyph3D()
        glyph.SetInputConnection(sphere.GetOutputPort())
        glyph.SetSourceConnection(cone.GetOutputPort())
        glyph.SetVectorModeToUseNormal()
        glyph.SetScaleModeToScaleByVector()
        glyph.SetScaleFactor(0.25)

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

        spikeActor = vtk.vtkLODActor()
        spikeActor.SetMapper(spikeMapper)

        spikeActor.GetProperty().SetDiffuseColor(colors.GetRGBColor('tomato'))
        spikeActor.GetProperty().SetSpecular(.4)
        spikeActor.GetProperty().SetSpecularPower(20)

        # Add the actors to the renderer, set the background and size

        self.ren.AddActor(sphereActor)
        self.ren.AddActor(spikeActor)
        self.ren.SetBackground(0.1, 0.2, 0.4)

        self.renWin.SetSize(300, 300)

        # Render the image

        self.ren.ResetCamera()
        cam1 = ren.GetActiveCamera()
        cam1.Zoom(1.4)
        cam1.Azimuth(30)
        cam1.Elevation(30)

        self.renWin.Render()
示例#60
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# create a rendering window and renderer
ren1 = vtk.vtkRenderer()
ren1.AutomaticLightCreationOff()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create cones of varying resolution
cone0 = vtk.vtkConeSource()
cone0.SetResolution(0)
cone1 = vtk.vtkConeSource()
cone1.SetResolution(1)
cone2 = vtk.vtkConeSource()
cone2.SetResolution(2)
cone8 = vtk.vtkConeSource()
cone8.SetResolution(8)
cone8.SetDirection(0, 0, 10)
cone8.SetCenter(5, 0, 0)
cone0Mapper = vtk.vtkPolyDataMapper()
cone0Mapper.SetInputConnection(cone0.GetOutputPort())
cone0Actor = vtk.vtkActor()
cone0Actor.SetMapper(cone0Mapper)
cone1Mapper = vtk.vtkPolyDataMapper()
cone1Mapper.SetInputConnection(cone1.GetOutputPort())
cone1Actor = vtk.vtkActor()