Example #1
0
def main():
    colors = vtk.vtkNamedColors()

    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    style = vtk.vtkInteractorStyleTrackballActor()
    iren.SetInteractorStyle(style)

    # create source
    sphereSource = vtk.vtkSphereSource()

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(sphereSource.GetOutputPort())

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

    # assign actor to the renderer
    ren.AddActor(actor)
    ren.SetBackground(colors.GetColor3d('PaleGoldenrod'))

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
Example #2
0
    def __init__(self):
        """Init."""
        # Interactor responsible for moving the camera.
        self.trackball_camera = vtk.vtkInteractorStyleTrackballCamera()
        # Interactor responsible for moving/rotating a selected actor.
        self.trackball_actor = vtk.vtkInteractorStyleTrackballActor()
        # Interactor responsible for panning/zooming the camera.
        self.image = vtk.vtkInteractorStyleImage()

        # The picker allows us to know which object/actor is under the mouse.
        self.picker = vtk.vtkPropPicker()
        self.chosen_element = None
        self.event = Event()
        self.event2id = {}  # To map an event's name to an ID.

        # Define some interaction states
        self.left_button_down = False
        self.right_button_down = False
        self.middle_button_down = False
        self.active_props = set()

        self.history = deque(maxlen=10)  # Events history.

        self.selected_props = {"left_button": set(),
                               "right_button": set(),
                               "middle_button": set()}
    def __init__(self, background_file, model_file, camera_file):
        super(ManualRegistrationMainWidget, self).__init__()

        if not background_file:
            raise ValueError("Background image must be specified")
        if not model_file:
            raise ValueError("VTK model must be specified")
        if not camera_file:
            raise ValueError("Camera matrix must be specified")

        self.setContentsMargins(0, 0, 0, 0)
        self.viewer = ow.VTKOverlayWindow()
        self.viewer_size_policy = \
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.viewer.setSizePolicy(self.viewer_size_policy)

        self.interactor_style = vtk.vtkInteractorStyleTrackballActor()
        self.viewer.SetInteractorStyle(self.interactor_style)

        self.vertical_layout = QtWidgets.QVBoxLayout(self)
        self.vertical_layout.setContentsMargins(0, 0, 0, 0)
        self.vertical_layout.addWidget(self.viewer)

        background = cv2.imread(background_file)
        model = sm.VTKSurfaceModel(model_file, [1.0, 1.0, 1.0], opacity=0.5)
        camera_matrix = np.loadtxt(camera_file)

        self.viewer.set_video_image(background)
        self.viewer.set_camera_matrix(camera_matrix)
        self.viewer.add_vtk_models([model])
Example #4
0
    def __init__(self,
                 camera,
                 tfBuffer,
                 markerTopic,
                 robotFrame,
                 tipFrame,
                 cameraFrame,
                 masterWidget=None,
                 parent=None):
        super(GpOverlayWidget, self).__init__(parent=parent)
        # Load in variables
        self.tfBuffer = tfBuffer
        self.robotFrame = robotFrame
        self.tipFrame = tipFrame
        self.markerTopic = markerTopic
        self.cameraFrame = cameraFrame
        self.masterWidget = masterWidget

        uiPath = cleanResourcePath(
            "package://dvrk_vision/src/dvrk_vision/overlay_widget.ui")
        # Get CV image from path
        uic.loadUi(uiPath, self)
        self.vtkWidget = QVTKStereoViewer(camera, parent=self)
        self.vtkWidget.renderSetup = self.renderSetup

        # Add vtk widget
        self.vl = QVBoxLayout()
        self.vl.addWidget(self.vtkWidget)
        self.vtkFrame.setLayout(self.vl)

        self.otherWindows = []
        if self.masterWidget is not None:
            self.masterWidget.otherWindows.append(self)
            self.otherWindows.append(self.masterWidget)

        # Set up QT slider for opacity
        self.opacitySlider.valueChanged.connect(self.sliderChanged)
        self.textureCheckBox.stateChanged.connect(self.checkBoxChanged)

        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballActor())

        self.organFrame = None

        self.textureCheckBox.setText("Show GP mesh")

        self.POICheckBox = QCheckBox("Show markers", self)
        self.POICheckBox.setChecked(True)
        self.POICheckBox.stateChanged.connect(self.checkBoxChanged)
        self.horizontalLayout.addWidget(self.POICheckBox)

        self.clearButton = QPushButton("Clear markers", self)
        self.clearButton.pressed.connect(self.clearPOI)
        self.horizontalLayout.addWidget(self.clearButton)

        self.vtkWidget.Initialize()
        self.vtkWidget.start()
Example #5
0
    def __init__(self):

        self.scene = Scene()
        self.frame = MainWindow(self.scene)

        self.camera_style = vtk.vtkInteractorStyleTrackballCamera()
        self.camera_style.AddObserver('LeftButtonPressEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('LeftButtonReleaseEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MiddleButtonPressEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MiddleButtonReleaseEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('RightButtonPressEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('RightButtonReleaseEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MouseWheelForwardEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MouseWheelBackwardEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('KeyPressEvent', lambda a, b: None)

        self.actor_style = vtk.vtkInteractorStyleTrackballActor()
        self.actor_style.AddObserver('LeftButtonPressEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('LeftButtonReleaseEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MiddleButtonPressEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MiddleButtonReleaseEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('RightButtonPressEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('RightButtonReleaseEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MouseWheelForwardEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MouseWheelBackwardEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('KeyPressEvent', lambda a, b: None)

        self.frame.iren.SetInteractorStyle(self.camera_style)
        self.frame.iren.AddObserver('KeyPressEvent', self.keypress_handler)
        self.frame.ren.SetBackground(name_to_rgb_float(MAIN_WIN_BG_COLOR))
        self.scene.frame = self.frame

        axes = vtk.vtkAxes()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(axes.GetOutputPort())
        self.frame.axes_actor = vtk.vtkActor()
        self.frame.axes_actor.SetMapper(mapper)
        self.frame.axes_actor.GetProperty().SetLineWidth(1)
        self.frame.axes_actor.SetVisibility(START_WITH_AXES)
        self.frame.ren.AddActor(self.frame.axes_actor)
Example #6
0
    def __init__(self):

        self.scene = Scene()
        self.frame = MainWindow(self.scene)

        self.camera_style = vtk.vtkInteractorStyleTrackballCamera()
        self.camera_style.AddObserver('LeftButtonPressEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('LeftButtonReleaseEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MiddleButtonPressEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MiddleButtonReleaseEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('RightButtonPressEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('RightButtonReleaseEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MouseWheelForwardEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('MouseWheelBackwardEvent',
                                      self.bimodal_mouse_handler)
        self.camera_style.AddObserver('KeyPressEvent', lambda a, b: None)

        self.actor_style = vtk.vtkInteractorStyleTrackballActor()
        self.actor_style.AddObserver('LeftButtonPressEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('LeftButtonReleaseEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MiddleButtonPressEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MiddleButtonReleaseEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('RightButtonPressEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('RightButtonReleaseEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MouseWheelForwardEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('MouseWheelBackwardEvent',
                                     self.bimodal_mouse_handler)
        self.actor_style.AddObserver('KeyPressEvent', lambda a, b: None)

        self.frame.iren.SetInteractorStyle(self.camera_style)
        self.frame.iren.AddObserver('KeyPressEvent', self.keypress_handler)
        self.frame.ren.SetBackground(name_to_rgb_float(MAIN_WIN_BG_COLOR))
        self.scene.frame = self.frame

        axes = vtk.vtkAxes()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(axes.GetOutputPort())
        self.frame.axes_actor = vtk.vtkActor()
        self.frame.axes_actor.SetMapper(mapper)
        self.frame.axes_actor.GetProperty().SetLineWidth(1)
        self.frame.axes_actor.SetVisibility(START_WITH_AXES)
        self.frame.ren.AddActor(self.frame.axes_actor)
Example #7
0
    def __init__(self, width=1400, height=1000, title='VTK Viewer'):

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)

        self.render_window = vtk.vtkRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.render_window.SetSize(width, height)

        self.root = Tkinter.Tk()
        self.root.title(title)
        self.render_window_interactor = vtkTkRenderWindowInteractorNoCharEvent(
            self.root, rw=self.render_window, width=width, height=height)
        self.render_window_interactor.Initialize()
        self.render_window_interactor.pack(fill='both', expand=1)

        self.cam_trackball = vtk.vtkInteractorStyleTrackballCamera()
        self.cam_trackball.SetCurrentRenderer(self.renderer)
        self.render_window_interactor.SetInteractorStyle(self.cam_trackball)
        self.cam_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.key_callbacks = {}

        self.act_trackball = vtk.vtkInteractorStyleTrackballActor()
        self.act_trackball.SetCurrentRenderer(self.renderer)
        self.act_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.act_trackball.AddObserver('InteractionEvent', self.on_actor_move)
        self.actor_move_callbacks = []

        self.mouse_pick_interactor = vtk.vtkInteractorStyleUser()
        self.mouse_pick_interactor.SetCurrentRenderer(self.renderer)
        self.mouse_pick_interactor.AddObserver('KeyPressEvent',
                                               self.on_key_press)
        self.mouse_pick_interactor.AddObserver('LeftButtonPressEvent',
                                               lambda x, y: self.pick(True))

        self.rubber_band_interactor = vtk.vtkInteractorStyleRubberBand3D()
        self.rubber_band_interactor.SetCurrentRenderer(self.renderer)
        self.rubber_band_interactor.AddObserver('KeyPressEvent',
                                                self.on_key_press)
        self.rubber_band_interactor.AddObserver('SelectionChangedEvent',
                                                self.on_box_select)
        self.box_select_callbacks = []

        # Create pickers
        self.cell_picker = vtk.vtkCellPicker()
        self.cell_picker.AddObserver("EndPickEvent", self.on_pick)
        self.point_picker = vtk.vtkPointPicker()
        self.point_picker.AddObserver("EndPickEvent", self.on_pick)
        self.pick_callbacks = []
Example #8
0
 def renderSetup(self):
     super(ManualRegistrationWidget, self).renderSetup()
     self.actor_moving.VisibilityOn()
     self.actor_moving.SetPosition(0, 0, .1)
     self.vtkWidget.ren.ResetCameraClippingRange()
     self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
     self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballActor())
     self.iren.AddObserver("StartInteractionEvent", self.interactionChange)
     self.iren.AddObserver("EndInteractionEvent", self.interactionChange)
     self.iren.RemoveObservers(
         "RightButtonPressEvent")  #, self.buttonEvent)
     self.iren.RemoveObservers(
         "RightButtonReleaseEvent")  #, self.buttonEvent)
     self.iren.AddObserver("RightButtonPressEvent", self.interactionChange)
     self.iren.AddObserver("RightButtonReleaseEvent",
                           self.interactionChange)
     self.iren.AddObserver("InteractionEvent", self.interactionEvent)
     self.iren.AddObserver("MouseMoveEvent", self.interactionEvent)
Example #9
0
    def __init__(self, width=1400, height=1000, title='VTK Viewer'):
        
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)
        
        self.render_window = vtk.vtkRenderWindow()
        self.render_window.AddRenderer(self.renderer)
        self.render_window.SetSize(width, height)

        self.root = Tkinter.Tk()
        self.root.title(title)
        self.render_window_interactor = vtkTkRenderWindowInteractorNoCharEvent(self.root, rw=self.render_window, width=width, height=height)
        self.render_window_interactor.Initialize()
        self.render_window_interactor.pack(fill='both', expand=1)

        self.cam_trackball = vtk.vtkInteractorStyleTrackballCamera()
        self.cam_trackball.SetCurrentRenderer(self.renderer)
        self.render_window_interactor.SetInteractorStyle(self.cam_trackball)
        self.cam_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.key_callbacks = {}

        self.act_trackball = vtk.vtkInteractorStyleTrackballActor()
        self.act_trackball.SetCurrentRenderer(self.renderer)
        self.act_trackball.AddObserver('KeyPressEvent', self.on_key_press)
        self.act_trackball.AddObserver('InteractionEvent', self.on_actor_move)
        self.actor_move_callbacks = []

        self.mouse_pick_interactor = vtk.vtkInteractorStyleUser()
        self.mouse_pick_interactor.SetCurrentRenderer(self.renderer)
        self.mouse_pick_interactor.AddObserver('KeyPressEvent', self.on_key_press)
        self.mouse_pick_interactor.AddObserver('LeftButtonPressEvent', lambda x, y: self.pick(True))

        self.rubber_band_interactor = vtk.vtkInteractorStyleRubberBand3D()
        self.rubber_band_interactor.SetCurrentRenderer(self.renderer)
        self.rubber_band_interactor.AddObserver('KeyPressEvent', self.on_key_press)
        self.rubber_band_interactor.AddObserver('SelectionChangedEvent', self.on_box_select)
        self.box_select_callbacks = []

        # Create pickers
        self.cell_picker = vtk.vtkCellPicker()
        self.cell_picker.AddObserver("EndPickEvent", self.on_pick)
        self.point_picker = vtk.vtkPointPicker()
        self.point_picker.AddObserver("EndPickEvent", self.on_pick)
        self.pick_callbacks = []
Example #10
0
mapper2 = vtk.vtkPolyDataMapper()
mapper2.SetInputConnection(sphereSource2.GetOutputPort())

# Create an actor
actor2 = vtk.vtkActor()
actor2.SetMapper(mapper2)

# A renderer and render window
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)

# An interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

# Add the actors to the scene
renderer.AddActor(actor1)
renderer.AddActor(actor2)
renderer.SetBackground(1, 1, 1)  # Background color white

# Render an image (lights and cameras are created automatically)
renderWindow.Render()

style = vtk.vtkInteractorStyleTrackballActor()

renderWindowInteractor.SetInteractorStyle(style)

# Begin mouse interaction
renderWindowInteractor.Start()
Example #11
0
light.SetLightTypeToSceneLight()
light.SetAmbientColor(1, 1, 1)
light.SetDiffuseColor(1, 1, 1)
light.SetSpecularColor(1, 1, 1)
light.SetPosition(-100, 100, 25)
light.SetFocalPoint(0, 0, 0)
light.SetIntensity(0.8)

# Add the light to the renderer
ren1.AddLight(light)
ren2.AddLight(light)
ren3.AddLight(light)
ren4.AddLight(light)

renWin = vtk.vtkRenderWindow()
renWin.SetSize(800, 800)

renWin.AddRenderer(ren1)
renWin.AddRenderer(ren2)
renWin.AddRenderer(ren3)
renWin.AddRenderer(ren4)

iren = vtk.vtkRenderWindowInteractor()
iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballActor())

iren.SetRenderWindow(renWin)

renWin.Render()
iren.Initialize()
iren.Start()
Example #12
0
 def __init__(self,parent):
     wx.Panel.__init__(self, parent)
     # Default object to display 
     self.stlObject = vtk.vtkSTLReader()
 
     # Use \\ for the path name instead of \ for vtk to recognise the default file
     self.stlObject.SetFileName("C:\\Users\\user\\workspace\\arrow.stl")
  
     # Create a mapper and an actor 
     self.mainMapper = vtk.vtkPolyDataMapper()        
     self.mainMapper.SetInputConnection(self.stlObject.GetOutputPort())
     self.mainActor = vtk.vtkActor()
     self.mainActor.SetMapper(self.mainMapper)
     self.mainActor.GetProperty().BackfaceCullingOff()
 
     self.widget = wxVTKRenderWindowInteractor(self, -1)
     self.widget.Enable(1)
     self.widget.AddObserver("ExitEvent", lambda o,e,f=self: f.Close())
     self.style = vtk.vtkInteractorStyleTrackballActor()
     self.widget.SetInteractorStyle(self.style)
     
     # Binds events to the functions created 
     self.widget.Bind(wx.EVT_LEFT_DOWN, self.onLeftDown)
     self.widget.Bind(wx.EVT_MIDDLE_DOWN, self.onMiddleDown)
     self.widget.Bind(wx.EVT_MOTION, self.onMotion)
     self.widget.Bind(wx.EVT_LEFT_UP, self.onLeftUp)
     self.widget.Bind(wx.EVT_MIDDLE_UP, self.onMiddleUp)
     self.widget.Bind(wx.EVT_KEY_DOWN, self.kDown)
     self.widget.Bind(wx.EVT_RIGHT_UP, self.onRightUp)
     self.widget.Bind(wx.EVT_RIGHT_DOWN, self.onRightDown)        
     self.trackMotion = False
     self.trackpos = False        
     self.sizer = wx.BoxSizer(wx.VERTICAL)
     self.sizer.Add(self.widget, 1, wx.EXPAND)
     self.SetSizer(self.sizer)
     self.Layout()
     self.isploted = False  
       
     # Open window and create a renderer
     # to interact with the scene using the mouse use an instance of vtkRenderWindowInteractor.
     self.renderer = vtk.vtkRenderer()
     self.renderer.SetBackground(.1, .2, .3) # Background colour dark blue         
     self.widget.GetRenderWindow().AddRenderer(self.renderer)
     
     # Add actor to render window 
     #self.renderer.GetActors().AddActor(self.mainActor)
     self.renderer.AddActor(self.mainActor)
    
     # Setup orientation markers 
     self.axes = vtk.vtkAxesActor()
     self.marker = vtk.vtkOrientationMarkerWidget()
     self.marker.SetInteractor(self.widget._Iren)
     self.marker.SetOrientationMarker(self.axes)
     self.marker.SetViewport(0.75,0,1,0.25)
     self.marker.SetEnabled(1)
     
     self.renderer.ResetCamera()
     self.renderer.ResetCameraClippingRange()
     self.isploted = True
     
     # Getting points when the actor is moved with the mouse 
     self.pointcatcher = self.linedrawer()
     self.linesPolyData = vtk.vtkPolyData()
Example #13
0
    def show(
        self, *actors, **options
        #        at=None,
        #        axes=None,
        #        c=None,
        #        alpha=None,
        #        wire=False,
        #        bc=None,
        #        resetcam=True,
        #        zoom=False,
        #        interactive=None,
        #        rate=None,
        #        viewup="",
        #        azimuth=0,
        #        elevation=0,
        #        roll=0,
        #        interactorStyle=0,
        #        q=False,
    ):
        """
        Render a list of actors.

        Allowed input objects are: ``filename``, ``vtkPolyData``, ``vtkActor``,
        ``vtkActor2D``, ``vtkImageActor``, ``vtkAssembly`` or ``vtkVolume``.

        If filename is given, its type is guessed based on its extension.
        Supported formats are:
        `vtu, vts, vtp, ply, obj, stl, 3ds, xml, neutral, gmsh, pcd, xyz, txt, byu,
        tif, slc, vti, mhd, png, jpg`.

        :param int at: number of the renderer to plot to, if more than one exists
        :param int axes: set the type of axes to be shown

              - 0,  no axes,
              - 1,  draw three gray grid walls
              - 2,  show cartesian axes from (0,0,0)
              - 3,  show positive range of cartesian axes from (0,0,0)
              - 4,  show a triad at bottom left
              - 5,  show a cube at bottom left
              - 6,  mark the corners of the bounding box
              - 7,  draw a simple ruler at the bottom of the window
              - 8,  show the ``vtkCubeAxesActor`` object,
              - 9,  show the bounding box outLine,
              - 10, show three circles representing the maximum bounding box

        :param c:     surface color, in rgb, hex or name formats
        :param bc:    set a color for the internal surface face
        :param bool wire:  show actor in wireframe representation
        :param float azimuth/elevation/roll:  move camera accordingly
        :param str viewup:  either ['x', 'y', 'z'] or a vector to set vertical direction
        :param bool resetcam:  re-adjust camera position to fit objects
        :param bool interactive:  pause and interact with window (True)
            or continue execution (False)
        :param float rate:  maximum rate of `show()` in Hertz
        :param int interactorStyle: set the type of interaction

            - 0, TrackballCamera
            - 1, TrackballActor
            - 2, JoystickCamera
            - 3, Unicam
            - 4, Flight
            - 5, RubberBand3D
            - 6, RubberBandZoom

        :param bool q:  force program to quit after `show()` command returns.
        """
        if not hasattr(self, 'window'):
            return

        at = options.pop("at", None)
        axes = options.pop("axes", None)
        c = options.pop("c", None)
        alpha = options.pop("alpha", None)
        wire = options.pop("wire", False)
        bc = options.pop("bc", None)
        resetcam = options.pop("resetcam", True)
        zoom = options.pop("zoom", False)
        interactive = options.pop("interactive", None)
        rate = options.pop("rate", None)
        viewup = options.pop("viewup", "")
        azimuth = options.pop("azimuth", 0)
        elevation = options.pop("elevation", 0)
        roll = options.pop("roll", 0)
        interactorStyle = options.pop("interactorStyle", 0)
        q = options.pop("q", False)

        if self.offscreen:
            interactive = False
            self.interactive = False

        def scan(wannabeacts):
            scannedacts = []
            if not utils.isSequence(wannabeacts):
                wannabeacts = [wannabeacts]
            for a in wannabeacts:  # scan content of list
                if isinstance(a, vtk.vtkActor):
                    scannedacts.append(a)
                    if hasattr(a, 'trail'
                               ) and a.trail and not a.trail in self.actors:
                        scannedacts.append(a.trail)
                elif isinstance(a, vtk.vtkAssembly):
                    scannedacts.append(a)
                    if a.trail and not a.trail in self.actors:
                        scannedacts.append(a.trail)
                elif isinstance(a, vtk.vtkActor2D):
                    if isinstance(a, vtk.vtkCornerAnnotation):
                        for a2 in settings.collectable_actors:
                            if isinstance(a2, vtk.vtkCornerAnnotation):
                                if at in a2.renderedAt:  # remove old message
                                    self.removeActor(a2)
                        scannedacts.append(a)
                elif isinstance(a, vtk.vtkImageActor):
                    scannedacts.append(a)
                elif isinstance(a, vtk.vtkVolume):
                    scannedacts.append(a)
                elif isinstance(a, vtk.vtkImageData):
                    scannedacts.append(Volume(a))
                elif isinstance(a, vtk.vtkPolyData):
                    scannedacts.append(Actor(a, c, alpha, wire, bc))
                elif isinstance(a, str):  # assume a filepath was given
                    out = vtkio.load(a, c, alpha, wire, bc)
                    if isinstance(out, str):
                        colors.printc("~times File not found:", out, c=1)
                        scannedacts.append(None)
                    else:
                        scannedacts.append(out)
                elif "dolfin" in str(type(a)):  # assume a dolfin.Mesh object
                    from vtkplotter.dolfin import MeshActor
                    out = MeshActor(a, c=c, alpha=alpha, wire=True, bc=bc)
                    scannedacts.append(out)
                elif a is None:
                    pass
                elif isinstance(a, vtk.vtkUnstructuredGrid):
                    gf = vtk.vtkGeometryFilter()
                    gf.SetInputData(a)
                    gf.Update()
                    scannedacts.append(
                        Actor(gf.GetOutput(), c, alpha, wire, bc))
                elif isinstance(a, vtk.vtkStructuredGrid):
                    gf = vtk.vtkGeometryFilter()
                    gf.SetInputData(a)
                    gf.Update()
                    scannedacts.append(
                        Actor(gf.GetOutput(), c, alpha, wire, bc))
                elif isinstance(a, vtk.vtkRectilinearGrid):
                    gf = vtk.vtkRectilinearGridGeometryFilter()
                    gf.SetInputData(a)
                    gf.Update()
                    scannedacts.append(
                        Actor(gf.GetOutput(), c, alpha, wire, bc))
                elif isinstance(a, vtk.vtkMultiBlockDataSet):
                    for i in range(a.GetNumberOfBlocks()):
                        b = a.GetBlock(i)
                        if isinstance(b, vtk.vtkPolyData):
                            scannedacts.append(Actor(b, c, alpha, wire, bc))
                        elif isinstance(b, vtk.vtkImageData):
                            scannedacts.append(Volume(b))
                else:
                    colors.printc("~!? Cannot understand input in show():",
                                  type(a),
                                  c=1)
                    scannedacts.append(None)
            return scannedacts

        if len(actors) == 0:
            actors = None
        elif len(actors) == 1:
            actors = actors[0]
        else:
            actors = utils.flatten(actors)

        if actors is not None:
            self.actors = []
            actors2show = scan(actors)
            for a in actors2show:
                if a not in self.actors:
                    self.actors.append(a)
        else:
            actors2show = scan(self.actors)
            self.actors = list(actors2show)

        if axes is not None:
            self.axes = axes

        if interactive is not None:
            self.interactive = interactive

        if at is None and len(self.renderers) > 1:
            # in case of multiple renderers a call to show w/o specifing
            # at which renderer will just render the whole thing and return
            if self.interactor:
                if zoom:
                    self.camera.Zoom(zoom)
                self.interactor.Render()
                if self.interactive:
                    self.interactor.Start()
                return

        if at is None:
            at = 0

        if at < len(self.renderers):
            self.renderer = self.renderers[at]
        else:
            colors.printc("~times Error in show(): wrong renderer index",
                          at,
                          c=1)
            return

        if not self.camera:
            self.camera = self.renderer.GetActiveCamera()

        self.camera.SetParallelProjection(self.infinity)

        if self.camThickness:
            self.camera.SetThickness(self.camThickness)

        if self.sharecam:
            for r in self.renderers:
                r.SetActiveCamera(self.camera)

        if len(self.renderers) == 1:
            self.renderer.SetActiveCamera(self.camera)

        # rendering
        for ia in actors2show:  # add the actors that are not already in scene
            if ia:
                if isinstance(ia, vtk.vtkVolume):
                    self.renderer.AddVolume(ia)
                else:
                    self.renderer.AddActor(ia)
                if hasattr(ia, 'renderedAt'):
                    ia.renderedAt.add(at)
            else:
                colors.printc(
                    "~lightning Warning: Invalid actor in actors list, skip.",
                    c=5)

        # remove the ones that are not in actors2show
        for ia in self.getActors(at):
            if ia not in actors2show:
                self.renderer.RemoveActor(ia)
                if hasattr(ia, 'renderedAt'):
                    ia.renderedAt.discard(at)

        for c in self.scalarbars:
            self.renderer.RemoveActor(c)
            if hasattr(c, 'renderedAt'):
                c.renderedAt.discard(at)

        if self.axes is not None:
            addons.addAxes()

        addons.addLegend()

        if self.showFrame and len(self.renderers) > 1:
            addons.addFrame()

        if resetcam or self.initializedIren == False:
            self.renderer.ResetCamera()

        if not self.initializedIren and self.interactor:
            self.initializedIren = True
            self.interactor.Initialize()
            self.interactor.RemoveObservers("CharEvent")

            if self.verbose and self.interactive:
                docs.onelinetip()

        self.initializedPlotter = True

        if zoom:
            self.camera.Zoom(zoom)
        if azimuth:
            self.camera.Azimuth(azimuth)
        if elevation:
            self.camera.Elevation(elevation)
        if roll:
            self.camera.Roll(roll)

        if len(viewup):
            if viewup == "x":
                viewup = [1, 0, 0]
            elif viewup == "y":
                viewup = [0, 1, 0]
            elif viewup == "z":
                viewup = [0, 0, 1]
                self.camera.Azimuth(60)
                self.camera.Elevation(30)
            self.camera.Azimuth(0.01)  # otherwise camera gets locked
            self.camera.SetViewUp(viewup)

        self.renderer.ResetCameraClippingRange()

        self.window.Render()

        scbflag = False
        for a in self.actors:
            if (hasattr(a, "scalarbar") and a.scalarbar is not None
                    and utils.isSequence(a.scalarbar)):
                if len(a.scalarbar) == 5:  # addScalarBar
                    s1, s2, s3, s4, s5 = a.scalarbar
                    sb = addons.addScalarBar(a, s1, s2, s3, s4, s5)
                    scbflag = True
                    a.scalarbar = sb  # save scalarbar actor
                elif len(a.scalarbar) == 10:  # addScalarBar3D
                    s0, s1, s2, s3, s4, s5, s6, s7, s8 = a.scalarbar
                    sb = addons.addScalarBar3D(a, at, s0, s1, s2, s3, s4, s5,
                                               s6, s7, s8)
                    scbflag = True
                    a.scalarbar = sb  # save scalarbar actor
        if scbflag:
            self.window.Render()

        if settings.allowInteraction and not self.offscreen:
            self.allowInteraction()

        if settings.interactorStyle is not None:
            interactorStyle = settings.interactorStyle

        if interactorStyle == 0 or interactorStyle == "TrackballCamera":
            pass  # do nothing
        elif interactorStyle == 1 or interactorStyle == "TrackballActor":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleTrackballActor())
        elif interactorStyle == 2 or interactorStyle == "JoystickCamera":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleJoystickCamera())
        elif interactorStyle == 3 or interactorStyle == "Unicam":
            self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleUnicam())
        elif interactorStyle == 4 or interactorStyle == "Flight":
            self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleFlight())
        elif interactorStyle == 5 or interactorStyle == "RubberBand3D":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleRubberBand3D())
        elif interactorStyle == 6 or interactorStyle == "RubberBandZoom":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleRubberBandZoom())

        if self.interactor and self.interactive:
            self.interactor.Start()

        if rate:
            if self.clock is None:  # set clock and limit rate
                self._clockt0 = time.time()
                self.clock = 0.0
            else:
                t = time.time() - self._clockt0
                elapsed = t - self.clock
                mint = 1.0 / rate
                if elapsed < mint:
                    time.sleep(mint - elapsed)
                self.clock = time.time() - self._clockt0

        if q:  # gracefully exit
            if self.verbose:
                print("q flag set to True. Exit.")
            sys.exit(0)
Example #14
0
    def __init__(self):
        """
        Constructor, puts OverlayMainWidget in window.
        """

        super().__init__()

        self.mode = "circle"
        self.model = None

        self.layout = QtWidgets.QVBoxLayout()
        self.frame = QtWidgets.QFrame()
        self.frame.setLayout(self.layout)
        self.setCentralWidget(self.frame)

        self.h_box = QtWidgets.QHBoxLayout()
        self.vtk_overlay_window = ow.VTKOverlayWindow()
        self.controls_box = QtWidgets.QHBoxLayout()

        self.h_box.addWidget(self.vtk_overlay_window)
        self.layout.addLayout(self.h_box)
        self.layout.addLayout(self.controls_box)

        self.add_group_box()
        self.add_opacity_slider()

        # Reset button
        self.button = QtWidgets.QPushButton('Move Target', self)
        self.button.clicked.connect(self.reset_models)
        self.layout.addWidget(self.button)

        self.target_actor = None

        self.window_width = 800
        self.window_height = 600
        self.setFixedSize(self.window_width, self.window_height)

        style = vtk.vtkInteractorStyleTrackballActor()
        self.vtk_overlay_window.SetInteractorStyle(style)

        # Setup text labels
        self.txtPosition = vtk.vtkTextActor()
        self.txtPosition.SetDisplayPosition(30, 60)
        self.txtPosition.GetTextProperty().SetFontSize(25)

        self.txtScale = vtk.vtkTextActor()
        self.txtScale.SetDisplayPosition(30, 30)
        self.txtScale.GetTextProperty().SetFontSize(25)

        self.reset_text_labels()

        self.vtk_overlay_window.foreground_renderer.AddActor(self.txtScale)
        self.vtk_overlay_window.foreground_renderer.AddActor(self.txtPosition)

        self.setup_target()
        self.setup_overlay()

        self.update()
        self.setContentsMargins(0, 0, 0, 0)

        def interactionChange(_, event):
            """
            Mouse callbacks
            """
            if event == "EndInteractionEvent":

                # position
                pos_error = self.check_position()
                self.txtPosition.SetInput(f"Alignment Error: {pos_error:.2f}")

                # scale
                scale_error = self.check_scale()
                self.txtScale.SetInput(f"Size Error: {scale_error:.2f}")

        # pylint:disable=protected-access
        self.vtk_overlay_window._Iren.AddObserver("EndInteractionEvent",
                                                  interactionChange)
Example #15
0
def _keypress(iren, event):
    # qt creates and passes a vtkGenericRenderWindowInteractor

    vp = settings.plotter_instance
    key = iren.GetKeySym()
    #print('Pressed key:', key, [vp])

    if key in ["q", "Q", "space", "Return"]:
        iren.ExitCallback()
        return

    elif key == "Escape":
        sys.stdout.flush()
        settings.plotter_instance.closeWindow()

    elif key in ["F1", "Pause"]:
        sys.stdout.flush()
        colors.printc('\n[F1] Execution aborted. Exiting python now.')
        settings.plotter_instance.closeWindow()
        sys.exit(0)

    elif key == "m":
        if vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetOpacity(0.02)
            bfp = vp.clickedActor.GetBackfaceProperty()
            if bfp and hasattr(vp.clickedActor, "_bfprop"):
                vp.clickedActor._bfprop = bfp  # save it
                vp.clickedActor.SetBackfaceProperty(None)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    a.GetProperty().SetOpacity(0.02)
                    bfp = a.GetBackfaceProperty()
                    if bfp and hasattr(a, "_bfprop"):
                        a._bfprop = bfp
                        a.SetBackfaceProperty(None)

    elif key == "comma":
        if vp.clickedActor in vp.getActors():
            ap = vp.clickedActor.GetProperty()
            aal = max([ap.GetOpacity() * 0.75, 0.01])
            ap.SetOpacity(aal)
            bfp = vp.clickedActor.GetBackfaceProperty()
            if bfp and hasattr(vp.clickedActor, "_bfprop"):
                vp.clickedActor._bfprop = bfp
                vp.clickedActor.SetBackfaceProperty(None)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    ap = a.GetProperty()
                    aal = max([ap.GetOpacity() * 0.75, 0.01])
                    ap.SetOpacity(aal)
                    bfp = a.GetBackfaceProperty()
                    if bfp and hasattr(a, "_bfprop"):
                        a._bfprop = bfp
                        a.SetBackfaceProperty(None)

    elif key == "period":
        if vp.clickedActor in vp.getActors():
            ap = vp.clickedActor.GetProperty()
            aal = min([ap.GetOpacity() * 1.25, 1.0])
            ap.SetOpacity(aal)
            if aal == 1 and hasattr(vp.clickedActor,
                                    "_bfprop") and vp.clickedActor._bfprop:
                # put back
                vp.clickedActor.SetBackfaceProperty(vp.clickedActor._bfprop)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    ap = a.GetProperty()
                    aal = min([ap.GetOpacity() * 1.25, 1.0])
                    ap.SetOpacity(aal)
                    if aal == 1 and hasattr(a, "_bfprop") and a._bfprop:
                        a.SetBackfaceProperty(a._bfprop)

    elif key == "slash":
        if vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetOpacity(1)
            if hasattr(vp.clickedActor, "_bfprop") and vp.clickedActor._bfprop:
                vp.clickedActor.SetBackfaceProperty(vp.clickedActor._bfprop)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    a.GetProperty().SetOpacity(1)
                    if hasattr(a, "_bfprop") and a._bfprop:
                        a.clickedActor.SetBackfaceProperty(a._bfprop)

    elif key == "P":
        if vp.clickedActor in vp.getActors():
            acts = [vp.clickedActor]
        else:
            acts = vp.getActors()
        for ia in acts:
            if ia.GetPickable():
                try:
                    ps = ia.GetProperty().GetPointSize()
                    if ps > 1:
                        ia.GetProperty().SetPointSize(ps - 1)
                    ia.GetProperty().SetRepresentationToPoints()
                except AttributeError:
                    pass

    elif key == "p":
        if vp.clickedActor in vp.getActors():
            acts = [vp.clickedActor]
        else:
            acts = vp.getActors()
        for ia in acts:
            if ia.GetPickable():
                try:
                    ps = ia.GetProperty().GetPointSize()
                    ia.GetProperty().SetPointSize(ps + 2)
                    ia.GetProperty().SetRepresentationToPoints()
                except AttributeError:
                    pass

    elif key == "w":
        if vp.clickedActor and vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetRepresentationToWireframe()
        else:
            for a in vp.getActors():
                if a and a.GetPickable():
                    if a.GetProperty().GetRepresentation() == 1:  # toggle
                        a.GetProperty().SetRepresentationToSurface()
                    else:
                        a.GetProperty().SetRepresentationToWireframe()

    elif key == "r":
        vp.renderer.ResetCamera()

    #############################################################
    ### now intercept custom observer ###########################
    #############################################################
    if vp.keyPressFunction:
        if key not in ["Shift_L", "Control_L", "Super_L", "Alt_L"]:
            if key not in ["Shift_R", "Control_R", "Super_R", "Alt_R"]:
                vp.verbose = False
                vp.keyPressFunction(key)
                return

    if key == "h":
        from vtkplotter.docs import tips

        tips()
        return

    if key == "a":
        iren.ExitCallback()
        cur = iren.GetInteractorStyle()
        if isinstance(cur, vtk.vtkInteractorStyleTrackballCamera):
            print("\nInteractor style changed to TrackballActor")
            print("  you can now move and rotate individual meshes:")
            print("  press X twice to save the repositioned mesh,")
            print("  press 'a' to go back to normal style.")
            iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballActor())
        else:
            iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        iren.Start()
        return

    if key == "j":
        iren.ExitCallback()
        cur = iren.GetInteractorStyle()
        if isinstance(cur, vtk.vtkInteractorStyleJoystickCamera):
            iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        else:
            print("\nInteractor style changed to Joystick,", end="")
            print(" press j to go back to normal.")
            iren.SetInteractorStyle(vtk.vtkInteractorStyleJoystickCamera())
        iren.Start()
        return

    if key == "S":
        screenshot("screenshot.png")
        colors.printc("~camera Saved rendering window as screenshot.png",
                      c="blue")
        return

    if key == "C":
        cam = vp.renderer.GetActiveCamera()
        print('\n### Example code to position this vtkCamera:')
        print('vp = vtkplotter.Plotter()\n...')
        print('vp.camera.SetPosition(',
              [round(e, 3) for e in cam.GetPosition()], ')')
        print('vp.camera.SetFocalPoint(',
              [round(e, 3) for e in cam.GetFocalPoint()], ')')
        print('vp.camera.SetViewUp(', [round(e, 3) for e in cam.GetViewUp()],
              ')')
        print('vp.camera.SetDistance(', round(cam.GetDistance(), 3), ')')
        print('vp.camera.SetClippingRange(',
              [round(e, 3) for e in cam.GetClippingRange()], ')')
        return

    if key == "s":
        if vp.clickedActor and vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetRepresentationToSurface()
        else:
            for a in vp.getActors():
                if a and a.GetPickable():
                    a.GetProperty().SetRepresentationToSurface()

    elif key == "V":
        if not (vp.verbose):
            vp._tips()
        vp.verbose = not (vp.verbose)
        print("Verbose: ", vp.verbose)

    elif key == "1":
        vp.icol += 1
        if vp.clickedActor and hasattr(vp.clickedActor, "GetProperty"):
            vp.clickedActor.GetMapper().ScalarVisibilityOff()
            vp.clickedActor.GetProperty().SetColor(colors.colors1[(vp.icol) %
                                                                  10])
        else:
            for i, ia in enumerate(vp.getActors()):
                if not ia.GetPickable():
                    continue
                ia.GetProperty().SetColor(colors.colors1[(i + vp.icol) % 10])
                ia.GetMapper().ScalarVisibilityOff()
        addons.addLegend()

    elif key == "2":
        vp.icol += 1
        if vp.clickedActor and hasattr(vp.clickedActor, "GetProperty"):
            vp.clickedActor.GetMapper().ScalarVisibilityOff()
            vp.clickedActor.GetProperty().SetColor(colors.colors2[(vp.icol) %
                                                                  10])
        else:
            for i, ia in enumerate(vp.getActors()):
                if not ia.GetPickable():
                    continue
                ia.GetProperty().SetColor(colors.colors2[(i + vp.icol) % 10])
                ia.GetMapper().ScalarVisibilityOff()
        addons.addLegend()

    elif key == "3":
        c = colors.getColor("gold")
        acs = vp.getActors()
        if len(acs) == 0: return
        alpha = 1.0 / len(acs)
        for ia in acs:
            if not ia.GetPickable():
                continue
            ia.GetProperty().SetColor(c)
            ia.GetProperty().SetOpacity(alpha)
            ia.GetMapper().ScalarVisibilityOff()
        addons.addLegend()

    elif key == "4":
        for ia in vp.getActors():
            if not ia.GetPickable():
                continue
            if isinstance(ia, Actor):
                iascals = ia.scalars()
                if len(iascals):
                    stype, sname = iascals[ia._scals_idx]
                    if "ormal" not in sname:  # exclude normals
                        ia.scalars(ia._scals_idx)
                        ia.GetMapper().ScalarVisibilityOn()
                        colors.printc("..active scalars set to:",
                                      sname,
                                      "\ttype:",
                                      stype,
                                      c='g',
                                      bold=0)
                    ia._scals_idx += 1
                    if ia._scals_idx >= len(iascals):
                        ia._scals_idx = 0
        addons.addLegend()

    elif key == "5":
        bgc = numpy.array(vp.renderer.GetBackground()).sum() / 3
        if bgc <= 0:
            bgc = 0.223
        elif 0 < bgc < 1:
            bgc = 1
        else:
            bgc = 0
        vp.renderer.SetBackground(bgc, bgc, bgc)

    elif "KP_" in key:  # change axes style
        asso = {
            "KP_Insert": 0,
            "KP_0": 0,
            "KP_End": 1,
            "KP_1": 1,
            "KP_Down": 2,
            "KP_2": 2,
            "KP_Next": 3,
            "KP_3": 3,
            "KP_Left": 4,
            "KP_4": 4,
            "KP_Begin": 5,
            "KP_5": 5,
            "KP_Right": 6,
            "KP_6": 6,
            "KP_Home": 7,
            "KP_7": 7,
            "KP_Up": 8,
            "KP_8": 8,
            "KP_Prior": 9,
            "KP_9": 9,
        }
        clickedr = vp.renderers.index(vp.renderer)
        if key in asso.keys():
            if vp.axes_instances[clickedr]:
                if hasattr(vp.axes_instances[clickedr],
                           "EnabledOff"):  # widget
                    vp.axes_instances[clickedr].EnabledOff()
                else:
                    vp.renderer.RemoveActor(vp.axes_instances[clickedr])
                vp.axes_instances[clickedr] = None
            addons.addAxes(axtype=asso[key], c=None)
            vp.interactor.Render()

    elif key in ["k", "K"]:
        for a in vp.getActors():
            ptdata = a.GetMapper().GetInput().GetPointData()
            cldata = a.GetMapper().GetInput().GetCellData()

            arrtypes = dict()
            arrtypes[vtk.VTK_UNSIGNED_CHAR] = "UNSIGNED_CHAR"
            arrtypes[vtk.VTK_UNSIGNED_INT] = "UNSIGNED_INT"
            arrtypes[vtk.VTK_FLOAT] = "FLOAT"
            arrtypes[vtk.VTK_DOUBLE] = "DOUBLE"
            foundarr = 0

            if key == "k":
                for i in range(ptdata.GetNumberOfArrays()):
                    name = ptdata.GetArrayName(i)
                    if name == "Normals":
                        continue
                    ptdata.SetActiveScalars(name)
                    foundarr = 1
                if not foundarr:
                    print("No vtkArray is associated to points", end="")
                    if hasattr(a, "_legend"):
                        print(" for actor:", a._legend)
                    else:
                        print()

            if key == "K":
                for i in range(cldata.GetNumberOfArrays()):
                    name = cldata.GetArrayName(i)
                    if name == "Normals":
                        continue
                    cldata.SetActiveScalars(name)
                    foundarr = 1
                if not foundarr:
                    print("No vtkArray is associated to cells", end="")
                    if hasattr(a, "_legend"):
                        print(" for actor:", a._legend)
                    else:
                        print()

            a.GetMapper().ScalarVisibilityOn()

    elif key == "l":
        if vp.clickedActor in vp.getActors():
            acts = [vp.clickedActor]
        else:
            acts = vp.getActors()
        for ia in acts:
            if not ia.GetPickable():
                continue
            try:
                ev = ia.GetProperty().GetEdgeVisibility()
                ia.GetProperty().SetEdgeVisibility(not ev)
                ia.GetProperty().SetRepresentationToSurface()
                ia.GetProperty().SetLineWidth(0.1)
            except AttributeError:
                pass

    elif key == "n":  # show normals to an actor
        from vtkplotter.analysis import normalLines

        if vp.clickedActor in vp.getActors():
            if vp.clickedActor.GetPickable():
                vp.renderer.AddActor(normalLines(vp.clickedActor))
                iren.Render()
        else:
            print("Click an actor and press n to add normals.")

    elif key == "x":
        if vp.justremoved is None:
            if vp.clickedActor in vp.getActors() or isinstance(
                    vp.clickedActor, vtk.vtkAssembly):
                vp.justremoved = vp.clickedActor
                vp.renderer.RemoveActor(vp.clickedActor)
            if hasattr(vp.clickedActor, '_legend') and vp.clickedActor._legend:
                print('...removing actor: ' + str(vp.clickedActor._legend) +
                      ', press x to put it back')
            else:
                print("Click an actor and press x to toggle it.")
        else:
            vp.renderer.AddActor(vp.justremoved)
            vp.renderer.Render()
            vp.justremoved = None
        addons.addLegend()

    elif key == "X":
        if vp.clickedActor:
            if not vp.cutterWidget:
                addons.addCutterTool(vp.clickedActor)
            else:
                fname = "clipped.vtk"
                confilter = vtk.vtkPolyDataConnectivityFilter()
                if isinstance(vp.clickedActor, vtk.vtkActor):
                    confilter.SetInputData(
                        vp.clickedActor.GetMapper().GetInput())
                elif isinstance(vp.clickedActor, vtk.vtkAssembly):
                    act = vp.clickedActor.getActors()[0]
                    confilter.SetInputData(act.GetMapper().GetInput())
                else:
                    confilter.SetInputData(vp.clickedActor.polydata(True))
                confilter.SetExtractionModeToLargestRegion()
                confilter.Update()
                cpd = vtk.vtkCleanPolyData()
                cpd.SetInputData(confilter.GetOutput())
                cpd.Update()
                w = vtk.vtkPolyDataWriter()
                w.SetInputData(cpd.GetOutput())
                w.SetFileName(fname)
                w.Write()
                colors.printc("~save Saved file:", fname, c="m")
                vp.cutterWidget.Off()
                vp.cutterWidget = None
        else:
            for a in vp.actors:
                if isinstance(a, vtk.vtkVolume):
                    addons.addCutterTool(a)
                    return

            colors.printc(
                "Click an actor and press X to open the cutter box widget.",
                c=4)

    elif key == "i":  # print info
        if vp.clickedActor:
            utils.printInfo(vp.clickedActor)
        else:
            utils.printInfo(vp)

    if iren:
        iren.Render()
Example #16
0
"""
VTK render model
"""

import logging

from atom.api import Atom, Dict, Str, observe, Value, Int, Tuple, List
from functools import partial
import vtk


logging.basicConfig(format="%(asctime)s: %(levelname)s: %(message)s", level=logging.DEBUG)


INTERACTION_STYLES = {
    "TrackBallActor": vtk.vtkInteractorStyleTrackballActor(),
    "TrackBallCamera": vtk.vtkInteractorStyleTrackballCamera(),  # default style
    "JoystickCamera": vtk.vtkInteractorStyleJoystickCamera(),
    "JoystickActor": vtk.vtkInteractorStyleJoystickActor(),
    "Terrain": vtk.vtkInteractorStyleTerrain(),
}


class VTKRenderController(Atom):
    """ vtk render controller - supply renderers to VTKCanvas  """

    zoomFactor = Value()
    numOfRenderers = Int()
    callbacks = Dict()
    customPorts = Dict()
    customBackgrounds = Dict()
import vtk
 
# create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
 
# create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
 
style = vtk.vtkInteractorStyleTrackballActor()
iren.SetInteractorStyle(style)
 
# create source
sphereSource = vtk.vtkSphereSource()
sphereSource.Update()
  
# mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(sphereSource.GetOutput())
 
# actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)

# assign actor to the renderer
ren.AddActor(actor)
 
# enable user interface interactor
iren.Initialize()
Example #18
0
"""
VTK render model
"""

import logging

from atom.api import Atom, Dict, Str, observe, Value, Int, Tuple, List
from functools import partial
import vtk

logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',
                    level=logging.DEBUG)

INTERACTION_STYLES = {
    'TrackBallActor': vtk.vtkInteractorStyleTrackballActor(),
    'TrackBallCamera':
    vtk.vtkInteractorStyleTrackballCamera(),  # default style
    'JoystickCamera': vtk.vtkInteractorStyleJoystickCamera(),
    'JoystickActor': vtk.vtkInteractorStyleJoystickActor(),
    'Terrain': vtk.vtkInteractorStyleTerrain(),
}


class VTKRenderController(Atom):
    """ vtk render controller - supply renderers to VTKCanvas  """

    zoomFactor = Value()
    numOfRenderers = Int()
    callbacks = Dict()
    customPorts = Dict()
    customBackgrounds = Dict()
transformFilter.Update()

#print("applying transform",transformFilter.GetScale())

mapper2 = vtk.vtkPolyDataMapper()
mapper2.SetInputData(transformFilter.GetOutput())
actor2 = vtk.vtkActor()
actor2.SetMapper(mapper2)




renderer = vtk.vtkRenderer()
renderWin = vtk.vtkRenderWindow()
interactor = vtk.vtkRenderWindowInteractor()
renderWin.AddRenderer(renderer)
interactor.SetRenderWindow(renderWin)
interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballActor())

#
renderer.AddActor(actor1)
renderer.AddActor(actor2)
renderer.SetBackground(1,1,1)

renderWin.Render()
interactor.Start()