Пример #1
0
def clipping_plane(v, interactor, event):
    if interactor.GetKeyCode() == "c":
        planew = vtk.vtkImplicitPlaneWidget()
        planew.SetInteractor(v.getInteractor())
        plane = vtk.vtkPlane()
        planew.GetPlane(plane)
        planew.PlaceWidget()
        v.volume_mapper.AddClippingPlane(plane)
        v.plane = plane
        v.planew = planew
Пример #2
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self)

        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()

        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.Mesh != None:

            self.MeshCutFilter = vtk.vtkCutter()
            self.MeshCutFilter.SetInputData(self.Mesh)
            cutPlane = vtk.vtkPlane()
            self.PlaneWidget.GetPlane(cutPlane)
            self.MeshCutFilter.SetCutFunction(cutPlane)
            self.MeshCutFilter.Update()
            self.Surface = self.MeshCutFilter.GetOutput()

            self.PlaneWidget.AddObserver("StartInteractionEvent",
                                         self.StartPlaneCallback)
            self.PlaneWidget.AddObserver("EndInteractionEvent",
                                         self.EndPlaneCallback)

            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.Mesh)

            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)
            self.Actor.GetProperty().SetOpacity(self.Opacity)

        self.PlaneWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOn()
        self.PlaneWidget.GetPlaneProperty().SetOpacity(0.1)
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())
        self.PlaneWidget.On()

        if (self.Display == 1):
            self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Пример #3
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self) 

        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()
        
        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.Mesh != None:

            self.MeshCutFilter = vtk.vtkCutter()
            self.MeshCutFilter.SetInputData(self.Mesh)
            cutPlane = vtk.vtkPlane()
            self.PlaneWidget.GetPlane(cutPlane)
            self.MeshCutFilter.SetCutFunction(cutPlane)
            self.MeshCutFilter.Update()
            self.Surface = self.MeshCutFilter.GetOutput()
 
            self.PlaneWidget.AddObserver("StartInteractionEvent",self.StartPlaneCallback)
            self.PlaneWidget.AddObserver("EndInteractionEvent",self.EndPlaneCallback)

            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.Mesh)
            
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            
         
        self.PlaneWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOn()
        self.PlaneWidget.GetPlaneProperty().SetOpacity(0.1)
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())
        self.PlaneWidget.On()
        
        if (self.Display == 1):
            self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Пример #4
0
def createPlaneWidget(ugrid):
    planeWidget = vtk.vtkImplicitPlaneWidget()
    planeWidget.SetPlaceFactor(1.25)
    planeWidget.SetInput(ugrid)
    planeWidget.PlaceWidget(ugrid.GetBounds())
    planeWidget.NormalToXAxisOn()
    planeWidget.DrawPlaneOff()
    planeWidget.TubingOn()
    planeWidget.OutlineTranslationOff()
    planeWidget.ScaleEnabledOff()
    planeWidget.GetNormalProperty().SetColor(.6, .1, 1)
    planeWidget.GetSelectedNormalProperty().SetColor(.4, .4, 4)
    planeWidget.GetEdgesProperty().SetLineWidth(.6)
    planeWidget.SetHandleSize(.01)
    return planeWidget
Пример #5
0
    def update_pipeline(self):

        if self.isoActor is not None:
            self.renderer.RemoveActor(self.isoActor)

        
        
        pipe = self.marchingCubes


        if self.useConnect:
            self.connect.SetInput( pipe.GetOutput())
            pipe = self.connect

        if self.useDecimate:
            self.deci.SetInput( pipe.GetOutput())
            pipe = self.deci

        if 0:
            plane = vtk.vtkPlane()
            clipper = vtk.vtkClipPolyData()
            polyData = pipe.GetOutput()

            clipper.SetInput(polyData)
            clipper.SetClipFunction(plane)
            clipper.InsideOutOff()
            pipe = clipper

            def callback(pw, event):
                pw.GetPlane(plane)
                self.interactor.Render()
            self.planeWidget = vtk.vtkImplicitPlaneWidget()
            self.planeWidget.SetInteractor(self.interactor)
            self.planeWidget.On()
            self.planeWidget.SetPlaceFactor(1.0)
            self.planeWidget.SetInput(polyData)
            self.planeWidget.PlaceWidget()
            self.planeWidget.AddObserver("InteractionEvent", callback)
        
        
        self.isoMapper = vtk.vtkPolyDataMapper()
        self.isoMapper.SetInput(pipe.GetOutput())
        self.isoMapper.ScalarVisibilityOff()

        self.isoActor = vtk.vtkActor()
        self.isoActor.SetMapper(self.isoMapper)
        self.renderer.AddActor(self.isoActor)
        self.update_properties()
Пример #6
0
    def update_pipeline(self):

        if self.isoActor is not None:
            self.renderer.RemoveActor(self.isoActor)

        
        
        pipe = self.marchingCubes


        if self.useConnect:
            self.connect.SetInput( pipe.GetOutput())
            pipe = self.connect

        if self.useDecimate:
            self.deci.SetInput( pipe.GetOutput())
            pipe = self.deci

        if 0:
            plane = vtk.vtkPlane()
            clipper = vtk.vtkClipPolyData()
            polyData = pipe.GetOutput()

            clipper.SetInput(polyData)
            clipper.SetClipFunction(plane)
            clipper.InsideOutOff()
            pipe = clipper

            def callback(pw, event):
                pw.GetPlane(plane)
                self.interactor.Render()
            self.planeWidget = vtk.vtkImplicitPlaneWidget()
            self.planeWidget.SetInteractor(self.interactor)
            self.planeWidget.On()
            self.planeWidget.SetPlaceFactor(1.0)
            self.planeWidget.SetInput(polyData)
            self.planeWidget.PlaceWidget()
            self.planeWidget.AddObserver("InteractionEvent", callback)
        
        
        self.isoMapper = vtk.vtkPolyDataMapper()
        self.isoMapper.SetInput(pipe.GetOutput())
        self.isoMapper.ScalarVisibilityOff()

        self.isoActor = vtk.vtkActor()
        self.isoActor.SetMapper(self.isoMapper)
        self.renderer.AddActor(self.isoActor)
        self.update_properties()
Пример #7
0
	def makePlaneWidget(vtkObj,iren):
		"""Make an interactive planeWidget"""

		# Associate the line widget with the interactor
		planeWidget = vtk.vtkImplicitPlaneWidget()
		planeWidget.SetInteractor(iren)
		planeWidget.SetInput(vtkObj )
		planeWidget.SetPlaceFactor(1.05) # Increases the size of the widget bounds
		planeWidget.PlaceWidget(vtkObj.GetBounds())
		b1,b2,b3 = vtkObj.GetBounds()[::2]
		planeWidget.SetOrigin(b1,b2,b3)
		#planeWidget.AddObserver("InteractionEvent", movePlane)
		planeWidget.SetOutsideBounds(0) # Not allow the widget to move outside the input bounds
		planeWidget.SetScaleEnabled(0) # Ability to scale with the mouse
		planeWidget.SetEnabled(1) # Starts the widget
		planeWidget.SetOutlineTranslation(0) # Abiltiy to move the widget with the mouse
		planeWidget.GetPlaneProperty().SetOpacity(0.1)
		return planeWidget
Пример #8
0
	def makePlaneWidget(vtkObj,iren,plane,actor):
		"""Make an interactive planeWidget"""

		# Callback function
		def movePlane(obj, events):
		    obj.GetPlane(intPlane)
		    intActor.VisibilityOn()

		# Associate the line widget with the interactor
		planeWidget = vtk.vtkImplicitPlaneWidget()
		planeWidget.SetInteractor(iren)
		planeWidget.SetPlaceFactor(1.25)
		planeWidget.SetInput(vtkObj)
		planeWidget.PlaceWidget()
		#planeWidget.AddObserver("InteractionEvent", movePlane)
		planeWidget.SetScaleEnabled(0)
		planeWidget.SetEnabled(1)
		planeWidget.SetOutlineTranslation(0)
		planeWidget.GetPlaneProperty().SetOpacity(0.1)
		return planeWidget
Пример #9
0
	def initPlaneWidget(self):
		
		"""Sets up vtkImplicitPlaneWidget for plane selection.
		
		Sets also up necessary actor and mapper.
		
		Returns:
			vtk.vtkImplicitPlaneWidget: Widget.
		
		"""
		
		# Initialize a plane widget
		self.planeWidget = vtk.vtkImplicitPlaneWidget()
		self.planeWidget.SetInteractor(self.iren)
		self.planeWidget.SetPlaceFactor(1.25)
		self.planeWidget.SetInput(self.grid)
		self.planeWidget.PlaceWidget()
		
		# Callback connection of interaction event
		self.planeWidget.AddObserver("InteractionEvent", self.StartPlaneCallback)
		self.planeWidget.AddObserver("EndInteractionEvent",self.EndPlaneCallback)
		
		# Mapper
		self.selectMapper = vtk.vtkDataSetMapper()
		self.selectMapper.SetInput(self.grid)
		
		# Actor
		self.selectActor = vtk.vtkLODActor()
		self.selectActor.SetMapper(self.selectMapper)
		self.selectActor.GetProperty().SetColor(0, 1, 0)
		self.selectActor.VisibilityOff()
		self.selectActor.SetScale(1.01, 1.01, 1.01)
		
		self.ren.AddActor(self.selectActor)
		
		# Place widget at right position
		self.planeWidget.SetNormal(0,0,1)
		self.planeWidget.SetOrigin(self.grid.GetCenter())
		
		
		return self.planeWidget
Пример #10
0
    def initPlaneWidget(self):
        """Sets up vtkImplicitPlaneWidget for plane selection.
		
		Sets also up necessary actor and mapper.
		
		Returns:
			vtk.vtkImplicitPlaneWidget: Widget.
		
		"""

        # Initialize a plane widget
        self.planeWidget = vtk.vtkImplicitPlaneWidget()
        self.planeWidget.SetInteractor(self.iren)
        self.planeWidget.SetPlaceFactor(1.25)
        self.planeWidget.SetInput(self.grid)
        self.planeWidget.PlaceWidget()

        # Callback connection of interaction event
        self.planeWidget.AddObserver("InteractionEvent",
                                     self.StartPlaneCallback)
        self.planeWidget.AddObserver("EndInteractionEvent",
                                     self.EndPlaneCallback)

        # Mapper
        self.selectMapper = vtk.vtkDataSetMapper()
        self.selectMapper.SetInput(self.grid)

        # Actor
        self.selectActor = vtk.vtkLODActor()
        self.selectActor.SetMapper(self.selectMapper)
        self.selectActor.GetProperty().SetColor(0, 1, 0)
        self.selectActor.VisibilityOff()
        self.selectActor.SetScale(1.01, 1.01, 1.01)

        self.ren.AddActor(self.selectActor)

        # Place widget at right position
        self.planeWidget.SetNormal(0, 0, 1)
        self.planeWidget.SetOrigin(self.grid.GetCenter())

        return self.planeWidget
Пример #11
0
    def Plane(self):
        if(self.planew != None):
            self.info_text.appendPlainText (_fromUtf8("Nelze použít více rovin najednou. Nejdříve proveďte řez"))
        else:
            planeWidget = vtk.vtkImplicitPlaneWidget()
            # předaní interaktoru objektu roviny
            planeWidget.SetInteractor(self.iren)
            # nastavení velikosti prostoru ve kterém se může rovina pohybovat
            planeWidget.SetPlaceFactor(1.5)
            # nastavení vstupních dat
            planeWidget.SetInput(surface.GetOutput())
            planeWidget.PlaceWidget()
            planeWidget.TubingOff()
            planeWidget.OutsideBoundsOff()
            planeWidget.ScaleEnabledOff()
            planeWidget.OutlineTranslationOff()
            planeWidget.AddObserver("InteractionEvent", self.Cutter)

            planeWidget.On()
            self.planew = planeWidget
            self.planew.SetNormal(2.0,0.0,0.0)
Пример #12
0
    def Plane(self):
        if(self.planew != None):
            self.info_text.appendPlainText (_fromUtf8("Nelze použít více rovin najednou. Nejdříve proveďte řez"))
        else:
            planeWidget = vtk.vtkImplicitPlaneWidget()
            # předaní interaktoru objektu roviny
            planeWidget.SetInteractor(self.iren)
            # nastavení velikosti prostoru ve kterém se může rovina pohybovat
            planeWidget.SetPlaceFactor(1.5)
            # nastavení vstupních dat
            planeWidget.SetInput(surface.GetOutput())
            planeWidget.PlaceWidget()
            planeWidget.TubingOff()
            planeWidget.OutsideBoundsOff()
            planeWidget.ScaleEnabledOff()
            planeWidget.OutlineTranslationOff()
            planeWidget.AddObserver("InteractionEvent", self.Cutter)

            planeWidget.On()
            self.planew = planeWidget
            self.planew.SetNormal(2.0,0.0,0.0)
Пример #13
0
    def plot(self, struct):

        # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision
        if not self.call_config(struct):
            return

        # creates self.src
        if not self.call_src():
            return

# postponed widget processing
        if self.has_field:
            self.add_scalarbar_1()
            self.add_abs_rel_1()
        self.add_outline_1()
        self.add_plane_1()
        self.add_sw_1()
        self.add_opacity_1(selection=0)  # Opacity: 100%/75%/50%/25%/0%

        # vector
        self.plane = vtk.vtkPlane()
        self.origin = self.src.GetOutput().GetCenter()
        print 'center', self.origin
        #        self.plane.SetOrigin(self.origin) #xml
        #        self.plane.SetNormal(1, 1, 1) #xml

        self.clipper = vtk.vtkExtractGeometry()
        self.clipper.SetInputConnection(self.src.GetOutputPort())
        self.clipper.SetImplicitFunction(self.plane)
        self.clipper.ExtractInsideOn()  # +/-
        #        self.clipper.ExtractBoundaryCellsOn() # inclue as que estan parcialmente dentro
        #        self.clipper.ExtractOnlyBoundaryCellsOn()

        self.pdM = vtk.vtkDataSetMapper()
        self.pdM.SetInputConnection(self.clipper.GetOutputPort())
        if self.has_field:
            self.pdM.ScalarVisibilityOn()
        else:
            self.pdM.ScalarVisibilityOff()

        self.scalarrange.local_set(self.src.GetOutput().GetScalarRange())

        # reverse rainbow [red->blue] -> [blue->red]
        look = self.pdM.GetLookupTable()
        #        self.add_scalarbar_2(look)

        self.add_outline_2(self.src)

        self.cutA = vtk.vtkActor()
        self.cutA.SetMapper(self.pdM)
        self.cutA.GetProperty().SetRepresentationToSurface()
        self.cutA.GetProperty().SetColor(Plot.mesh_color)

        self.rens[0].AddActor(self.cutA)

        # poñendo a scalarbar aquí e non antes, queda ben dibuxada desde o primeiro (non negra)
        if self.has_field:
            self.add_scalarbar_2(look)
            self.add_abs_rel_2(self.src, self.clipper)

        self.add_sw_2(self.cutA)
        self.add_opacity_2([self.cutA])  # Opacity: 100%/75%/50%/25%/0%

        # mover plano interactivamente
        #self.planeI = vtk.vtkPlaneWidget()
        self.planeI = vtk.vtkImplicitPlaneWidget()
        seeds = vtk.vtkPolyData()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            self.planeI.SetInput(self.src.GetOutput())
        else:
            self.planeI.SetInputConnection(self.src.GetOutputPort())

        self.add_plane_2(self.planeI)

        self.planeI.SetOrigin(self.origin[0], self.origin[1], self.origin[2])
        #self.planeI.SetResolution(20)
        #planeWidget.NormalToXAxisOn()
        #planeWidget.SetRepresentationToOutline()
        #self.planeI.PlaceWidget()
        self.planeI.GetPolyData(seeds)
        self.planeI.SetPlaceFactor(1.0)  # factor * bounds
        self.planeI.OutsideBoundsOn()  # not on PlaneWidget
        self.planeI.OutlineTranslationOff()
        self.planeI.DrawPlaneOff()
        self.planeI.ScaleEnabledOff()
        self.planeI.PlaceWidget()
        #self.planeI.PlaceWidget(self.src.GetOutput().GetBounds())
        self.planeI.AddObserver("EndInteractionEvent", self.event_end)

        self.set_iren()
        self.planeI.SetInteractor(self.iren)
        self.planeI.On()

        #        self.lineI.AddObserver("StartInteractionEvent", self.event_start)
        #        self.lineI.AddObserver("InteractionEvent", self.event)
        #        self.lineI.AddObserver("EndInteractionEvent", self.event_end)
        # /mover plano interactivamente

        if interactive2 and self.has_field:
            #self.set_iren() #necesario ^
            self.clicker = ClickLabel.ClickLabel()
            self.clicker.set_point_cell(self.data1.get('fielddomain'))
            self.clicker.set_objects(self.clipper, self.rens[0], self.iren,
                                     self.widget)
            self.clicker.set_props([self.cutA])
            self.clicker.setup()

        o = self.planeI.GetOrigin()
        n = self.planeI.GetNormal()
        print 'initial: o,n', o, n
        self.set_params(struct, o, n)  # not force first time

        self.copy_params(struct)

        self.done = True
Пример #14
0
renderer.RemoveViewProp(actoriso)
# Clip the data
cf = vtk.vtkClipDataSet()
# Set the clipping plane
plane = vtk.vtkPlane()
cf.SetClipFunction(plane)
print plane
# Set the plane origin
plane.SetOrigin(560000, 5120000, 2000)
# Connect the pipeline
cf.SetInputConnection(warp.GetOutputPort())
mapper.SetInputConnection(cf.GetOutputPort())

# Step 8 - Clipping Widget interaction
# Creates an implicit plane widget
widget = vtk.vtkImplicitPlaneWidget()
widget.PlaceWidget(warp.GetOutput().GetBounds())
widget.SetOrigin([plane.GetOrigin()[x] for x in 0, 1, 2])
widget.SetNormal([plane.GetNormal()[x] for x in 0, 1, 2])
widget.SetInteractor(iren)


# Connects the interaction event to the plane
def cb(obj, event):
    global plane
    obj.GetPlane(plane)


widget.AddObserver("InteractionEvent", cb)
widget.SetEnabled(1)
widget.DrawPlaneOn()
Пример #15
0
import misc

'''
Používané globální proměnné
'''
plane = vtk.vtkPlane()
normal = None
coordinates = None
iren = vtk.vtkRenderWindowInteractor()
surface = vtk.vtkDataSetSurfaceFilter()
app = QApplication(sys.argv)
label = QtGui.QLabel()
myLayout = QGridLayout()
widget = vtk.vtkSphereSource()
planeWidget = vtk.vtkImplicitPlaneWidget()


'''
Kód grafického editoru resekční linie. Tento kód byl automaticky vygenerován pomocí programu Qt Designer
'''
##------------------------------------------------------------------------------------------
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
Пример #16
0
    def BuildView(self):

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

        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.ScalarBarActor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)

        if self.Mesh != None:
            self.InitialMesh = self.Mesh
            self.DisplayMesh = self.Mesh
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.DisplayMesh)
            array = None
            if (self.ArrayName != ''):
                if self.DisplayCellData == 0:
                    self.Mesh.GetPointData().SetActiveScalars(self.ArrayName)
                    array = self.Mesh.GetPointData().GetScalars()
                else:
                    self.Mesh.GetCellData().SetActiveScalars(self.ArrayName)
                    array = self.Mesh.GetCellData().GetScalars()
                    mapper.SetScalarModeToUseCellData()
            if (array != None):
                if (self.ScalarRange[1] > self.ScalarRange[0]):
                    mapper.SetScalarRange(self.ScalarRange)
                else:
                    mapper.SetScalarRange(array.GetRange(0))
                if (self.Grayscale == 1):
                    lut = vtk.vtkLookupTable()
                    lut.SetValueRange(0.0, 1.0)
                    lut.SetSaturationRange(0.0, 0.0)
                    mapper.SetLookupTable(lut)

            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            if (self.Color[0] >= 0.0):
                self.Actor.GetProperty().SetColor(self.Color)
            if (self.FlatInterpolation == 1):
                self.Actor.GetProperty().SetInterpolationToFlat()
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if (self.Legend == 1) & (self.Actor != None):
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(
                self.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
            ##             self.ScalarBarActor.GetLabelTextProperty().SetColor(0.0,0.0,0.0)
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        #self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('i', 'Interact.',
                                        self.InteractCallback)
        self.vmtkRenderer.AddKeyBinding('c', 'Clip.', self.ClipCallback)
        self.vmtkRenderer.AddKeyBinding('e', 'Extract.', self.ExtractCallback)
        self.vmtkRenderer.AddKeyBinding('n', 'Show clipped area.',
                                        self.NCallback)
        self.vmtkRenderer.AddKeyBinding('d', 'Switch clipped/unclipped area.',
                                        self.DCallback)
        self.vmtkRenderer.AddKeyBinding('t', 'Redo.', self.TCallback)
        self.vmtkRenderer.AddKeyBinding('u', 'Undo.', self.UndoCallback)
        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()
        self.PlaneWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOff()
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        #Work around bug/strange behaviour in vtk
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())

        if (self.Display == 1):
            self.vmtkRenderer.Render()

        self.Mesh = self.InitialMesh

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Пример #17
0
    def add_plane_widget(self,
                         callback,
                         normal='x',
                         origin=None,
                         bounds=None,
                         factor=1.25,
                         color=None,
                         assign_to_axis=None,
                         tubing=False,
                         outline_translation=False,
                         origin_translation=True,
                         implicit=True,
                         pass_widget=False,
                         test_callback=True):
        """Add a plane widget to the scene.

        This is useless without a callback function. You can pass a callable
        function that takes two arguments, the normal and origin of the plane
        in that order output from this widget, and performs a task with that
        plane.

        Parameters
        ----------
        callback : callable
            The method called every time the plane is updated. Takes two
            arguments, the normal and origin of the plane in that order.

        normal : str or tuple(float)
            The starting normal vector of the plane

        origin : tuple(float)
            The starting coordinate of the center of the place

        bounds : tuple(float)
            Length 6 tuple of the bounding box where the widget is placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing

        color : string or 3 item list, optional, defaults to white
            Either a string, rgb list, or hex color string.

        assign_to_axis : str or int
            Assign the normal of the plane to be parallel with a given axis:
            options are (0, 'x'), (1, 'y'), or (2, 'z').

        tubing : bool
            When using an implicit plane wiget, this controls whether or not
            tubing is shown around the plane's boundaries.

        outline_translation : bool
            If ``False``, the plane widget cannot be translated and is strictly
            placed at the given bounds. Only valid when using an implicit
            plane.

        origin_translation : bool
            If ``False``, the plane widget cannot be translated by its origin
            and is strictly placed at the given origin. Only valid when using
            an implicit plane.

        implicit : bool
            When ``True``, a ``vtkImplicitPlaneWidget`` is ued and when
            ``False``, a ``vtkPlaneWidget`` is used.

        pass_widget : bool
            If true, the widget will be passed as the last argument of the
            callback

        test_callback: bool
            if true, run the callback function after the widget is created.

        """
        if hasattr(self, 'notebook') and self.notebook:
            raise AssertionError(
                'Plane widget not available in notebook plotting')
        if not hasattr(self, 'iren'):
            raise AttributeError(
                'Widgets must be used with an intereactive renderer. No off screen plotting.'
            )
        if not hasattr(self, "plane_widgets"):
            self.plane_widgets = []

        if origin is None:
            origin = self.center
        if bounds is None:
            bounds = self.bounds

        if isinstance(normal, str):
            normal = NORMALS[normal.lower()]

        if color is None:
            color = rcParams['font']['color']

        def _the_callback(widget, event_id):
            the_plane = vtk.vtkPlane()
            widget.GetPlane(the_plane)
            normal = the_plane.GetNormal()
            origin = the_plane.GetOrigin()
            if hasattr(callback, '__call__'):
                if pass_widget:
                    try_callback(callback, normal, origin, widget)
                else:
                    try_callback(callback, normal, origin)
            return

        if implicit:
            plane_widget = vtk.vtkImplicitPlaneWidget()
            plane_widget.GetNormalProperty().SetColor(parse_color(color))
            plane_widget.GetOutlineProperty().SetColor(parse_color(color))
            plane_widget.GetOutlineProperty().SetColor(parse_color(color))
            plane_widget.SetTubing(tubing)
            plane_widget.SetOutlineTranslation(outline_translation)
            plane_widget.SetOriginTranslation(origin_translation)

            _start_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(
                True)
            _stop_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(
                False)

            plane_widget.SetDrawPlane(False)
            plane_widget.AddObserver(vtk.vtkCommand.StartInteractionEvent,
                                     _start_interact)
            plane_widget.AddObserver(vtk.vtkCommand.EndInteractionEvent,
                                     _stop_interact)
            plane_widget.SetPlaceFactor(factor)
            plane_widget.PlaceWidget(bounds)
            plane_widget.SetOrigin(origin)

        else:
            # Position of the small plane
            source = vtk.vtkPlaneSource()
            source.SetNormal(normal)
            source.SetCenter(origin)
            source.SetPoint1(origin[0] + (bounds[1] - bounds[0]) * 0.01,
                             origin[1] - (bounds[3] - bounds[2]) * 0.01,
                             origin[2])
            source.SetPoint2(origin[0] - (bounds[1] - bounds[0]) * 0.01,
                             origin[1] + (bounds[3] - bounds[2]) * 0.01,
                             origin[2])
            source.Update()
            plane_widget = vtk.vtkPlaneWidget()
            plane_widget.SetHandleSize(.01)
            # Position of the widget
            plane_widget.SetInputData(source.GetOutput())
            plane_widget.SetRepresentationToOutline()
            plane_widget.SetPlaceFactor(factor)
            plane_widget.PlaceWidget(bounds)
            plane_widget.SetCenter(origin)  # Necessary
            plane_widget.GetPlaneProperty().SetColor(
                parse_color(color))  # self.C_LOT[fn])
            plane_widget.GetHandleProperty().SetColor(parse_color(color))

        plane_widget.GetPlaneProperty().SetOpacity(0.5)
        plane_widget.SetInteractor(self.iren)
        plane_widget.SetCurrentRenderer(self.renderer)

        if assign_to_axis:
            # TODO: how do we now disable/hide the arrow?
            if assign_to_axis in [0, "x", "X"]:
                plane_widget.NormalToXAxisOn()
                plane_widget.SetNormal(NORMALS["x"])
            elif assign_to_axis in [1, "y", "Y"]:
                plane_widget.NormalToYAxisOn()
                plane_widget.SetNormal(NORMALS["y"])
            elif assign_to_axis in [2, "z", "Z"]:
                plane_widget.NormalToZAxisOn()
                plane_widget.SetNormal(NORMALS["z"])
            else:
                raise RuntimeError("assign_to_axis not understood")
        else:
            plane_widget.SetNormal(normal)

        plane_widget.Modified()
        plane_widget.UpdatePlacement()
        plane_widget.On()
        plane_widget.AddObserver(vtk.vtkCommand.EndInteractionEvent,
                                 _the_callback)
        if test_callback:
            _the_callback(plane_widget, None)  # Trigger immediate update

        self.plane_widgets.append(plane_widget)
        return plane_widget
Пример #18
0
    def BuildView(self):

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

        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.ScalarBarActor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)

        if self.Mesh != None:
            self.InitialMesh = self.Mesh
            self.DisplayMesh = self.Mesh
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.DisplayMesh)
            array = None
            if (self.ArrayName != ''):
                if self.DisplayCellData == 0:
                  self.Mesh.GetPointData().SetActiveScalars(self.ArrayName)
                  array = self.Mesh.GetPointData().GetScalars()
                else:
                  self.Mesh.GetCellData().SetActiveScalars(self.ArrayName)
                  array = self.Mesh.GetCellData().GetScalars()
                  mapper.SetScalarModeToUseCellData()
            if (array != None):
                if (self.ScalarRange[1] > self.ScalarRange[0]):
                    mapper.SetScalarRange(self.ScalarRange)
                else:
                    mapper.SetScalarRange(array.GetRange(0))
                if (self.Grayscale == 1):
                    lut = vtk.vtkLookupTable()
                    lut.SetValueRange(0.0,1.0)
                    lut.SetSaturationRange(0.0,0.0)
                    mapper.SetLookupTable(lut)
                
            
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            if (self.Color[0] >= 0.0):
                self.Actor.GetProperty().SetColor(self.Color)
            if (self.FlatInterpolation == 1):
                self.Actor.GetProperty().SetInterpolationToFlat()
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if (self.Legend == 1) & (self.Actor != None):
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(self.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
##             self.ScalarBarActor.GetLabelTextProperty().SetColor(0.0,0.0,0.0)
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        #self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('i','Interact.',self.InteractCallback)
        self.vmtkRenderer.AddKeyBinding('c','Clip.',self.ClipCallback)
        self.vmtkRenderer.AddKeyBinding('e','Extract.',self.ExtractCallback)
        self.vmtkRenderer.AddKeyBinding('n','Show clipped area.',self.NCallback)
        self.vmtkRenderer.AddKeyBinding('d','Switch clipped/unclipped area.',self.DCallback)
        self.vmtkRenderer.AddKeyBinding('t','Redo.',self.TCallback)
        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()
        self.PlaneWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOff()
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        #Work around bug/strange behaviour in vtk
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())
          
        
        if (self.Display == 1):
            self.vmtkRenderer.Render()

        self.Mesh = self.InitialMesh
        
        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Пример #19
0
    def _createImplicit(self, implicitType, implicitName, bounds, primaryInput):
        if implicitType in self._implicitTypes and \
               implicitName not in self._implicitsDict:

            pi = primaryInput
            rwi = self.slice3dVWR.threedFrame.threedRWI
            implicitInfoBounds = None
            
            if implicitType == "Plane":
                implicitWidget = vtk.vtkImplicitPlaneWidget()
                implicitWidget.SetPlaceFactor(1.25)
                if pi != None:
                    implicitWidget.SetInput(pi)
                    implicitWidget.PlaceWidget()
                    b = pi.GetBounds()
                    implicitWidget.SetOrigin(b[0], b[2], b[4])
                    implicitInfoBounds = b
                elif bounds != None:
                    implicitWidget.PlaceWidget(bounds)
                    implicitWidget.SetOrigin(bounds[0], bounds[2], bounds[4])
                    implicitInfoBounds = bounds
                else:
                    # this can never happen
                    pass

                implicitWidget.SetInteractor(rwi)
                implicitWidget.On()

                # create the implicit function
                implicitFunction = vtk.vtkPlane()
                # sync it to the initial widget
                self._syncPlaneFunctionToWidget(implicitWidget)
                # add it to the output
                self.outputImplicitFunction.AddFunction(implicitFunction)

                # now add an observer to the widget
                def observerImplicitPlaneWidget(widget, eventName):
                    # sync it to the initial widget
                    ret = self._syncPlaneFunctionToWidget(widget)
                    # also select the correct grid row
                    if ret != None:
                        name, ii = ret
                        row = self.findGridRowByName(name)
                        if row >= 0:
                            self._grid.SelectRow(row)

                oId = implicitWidget.AddObserver('EndInteractionEvent',
                                                 observerImplicitPlaneWidget)
                    
            elif implicitType == "Sphere":
                implicitWidget = vtk.vtkSphereWidget()
                implicitWidget.SetPlaceFactor(1.25)
                implicitWidget.TranslationOn()
                implicitWidget.ScaleOn()
                #implicitWidget.HandleVisibilityOn()
                
                if pi != None:
                    implicitWidget.SetInput(pi)
                    implicitWidget.PlaceWidget()
                    b = pi.GetBounds()
                    implicitInfoBounds = b
                    #implicitWidget.SetOrigin(b[0], b[2], b[4])
                elif bounds != None:
                    implicitWidget.PlaceWidget(bounds)
                    implicitInfoBounds = bounds
                    #implicitWidget.SetOrigin(bounds[0], bounds[2], bounds[4])
                else:
                    # this can never happen
                    pass

                implicitWidget.SetInteractor(rwi)
                implicitWidget.On()

                # create the implicit function
                implicitFunction = vtk.vtkSphere()
                # sync it to the initial widget
                self._syncSphereFunctionToWidget(implicitWidget)
                # add it to the output
                self.outputImplicitFunction.AddFunction(implicitFunction)

                # now add an observer to the widget
                def observerImplicitSphereWidget(widget, eventName):
                    # sync it to the initial widget
                    ret = self._syncSphereFunctionToWidget(widget)
                    # also select the correct grid row
                    if ret != None:
                        name, ii = ret
                        row = self.findGridRowByName(name)
                        if row >= 0:
                            self._grid.SelectRow(row)

                oId = implicitWidget.AddObserver('EndInteractionEvent',
                                                 observerImplicitSphereWidget)



            if implicitWidget:
                # set the priority so it gets interaction before the
                # ImagePlaneWidget.  3D widgets have default priority 0.5,
                # so we assign our widgets just a tad higher. (voiwidget
                # has 0.6 for example)
                # NB: in a completely weird twist of events, only slices
                # added AFTER this widget will act like they have lower
                # priority.  The initial slice still takes events from us!
                implicitWidget.SetPriority(0.7)
                
                # add to our internal thingy
                ii = implicitInfo()
                ii.name = implicitName
                ii.type = implicitType
                ii.widget = implicitWidget
                ii.bounds = implicitInfoBounds
                ii.oId = oId
                ii.function = implicitFunction
                
                self._implicitsDict[implicitName] = ii

                # now add to the grid
                nrGridRows = self._grid.GetNumberRows()
                self._grid.AppendRows()
                self._grid.SetCellValue(nrGridRows, self._gridNameCol,
                                        implicitName)
                self._grid.SetCellValue(nrGridRows, self._gridTypeCol,
                                       implicitType)

                # set the relevant cells up for Boolean
                for col in [self._gridEnabledCol]:

                    self._grid.SetCellRenderer(nrGridRows, col,
                                               wx.grid.GridCellBoolRenderer())
                    self._grid.SetCellAlignment(nrGridRows, col,
                                                wx.ALIGN_CENTRE,
                                                wx.ALIGN_CENTRE)

                self._setImplicitEnabled(ii.name, True)
Пример #20
0
    def testSlice(self):
        global plane, filter, args
        writefiles = "SaveData" in args

        renderer = vtk.vtkRenderer()
        renwin = vtk.vtkRenderWindow()
        renwin.AddRenderer(renderer)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renwin)
        renwin.Render()

        if "GPURender" in args:
            vtk.vtkPistonMapper.InitCUDAGL(renwin)

        src = vtk.vtkImageMandelbrotSource()
        src.SetWholeExtent(0, 20, 0, 20, 0, 20)

        #scale and bias until piston understands origin and spacing
        src.Update()
        inputdata = src.GetOutput()
        if "Normalize" in args:
            testdata1 = inputdata.NewInstance()
            testdata1.ShallowCopy(inputdata)
            testdata1.SetSpacing(1, 1, 1)
            testdata1.SetOrigin(0, 0, 0)
            inputdata = testdata1

        bounds = inputdata.GetBounds()
        center = [(bounds[1] - bounds[0]) / 2 + bounds[0],
                  (bounds[3] - bounds[2]) / 2 + bounds[2],
                  (bounds[5] - bounds[4]) / 2 + bounds[4]]

        d2p = vtk.vtkDataSetToPiston()
        d2p.SetInputData(inputdata)
        #d2p.SetInputConnection(src.GetOutputPort())

        plane = vtk.vtkPlane()
        plane.SetOrigin(center)
        plane.SetNormal(0, 0, 1)

        filter = vtk.vtkPistonSlice()
        filter.SetInputConnection(d2p.GetOutputPort())
        filter.SetClippingPlane(plane)
        filter.SetOffset(0.0)

        p2d = vtk.vtkPistonToDataSet()
        p2d.SetOutputDataSetType(vtk.VTK_POLY_DATA)
        p2d.SetInputConnection(filter.GetOutputPort())
        if writefiles:
            writeFile(p2d, "piston_slice.vtk")

        mapper = vtk.vtkPistonMapper()
        mapper.SetInputConnection(filter.GetOutputPort())
        mapper.Update()  #TODO why is this necessary

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

        renderer.AddActor(actor)

        widget = vtk.vtkImplicitPlaneWidget()
        widget.PlaceWidget(bounds)
        widget.SetOrigin([plane.GetOrigin()[x] for x in 0, 1, 2])
        widget.SetNormal([plane.GetNormal()[x] for x in 0, 1, 2])
        widget.SetInteractor(iren)
        widget.AddObserver("InteractionEvent", widgetCallBack)
        widget.SetEnabled(1)
        widget.DrawPlaneOff()

        renderer.ResetCamera()
        renwin.Render()

        img_file = "TestSlice.png"
        Testing.compareImage(renwin, Testing.getAbsImagePath(img_file))

        if Testing.isInteractive():
            widget.DrawPlaneOn()
            iren.Start()
Пример #21
0
    def add_plane_widget(self,
                         callback,
                         normal='x',
                         origin=None,
                         bounds=None,
                         factor=1.25,
                         color=None,
                         assign_to_axis=None,
                         tubing=False,
                         outline_translation=False,
                         origin_translation=True,
                         **kwargs):
        """Add a plane widget to the scene. This is useless without a callback
        function. You can pass a callable function that takes two
        arguments, the normal and origin of the plane in that order output
        from this widget, and performs a task with that plane.

        Parameters
        ----------
        callback : callable
            The method called everytime the plane is updated. Takes two
            arguments, the normal and origin of the plane in that order.

        noraml : str or tuple(flaot)
            The starting normal vector of the plane

        origin : tuple(float)
            The starting coordinate of the center of the place

        bounds : tuple(float)
            Length 6 tuple of the bounding box where the widget is placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing

        color : string or 3 item list, optional, defaults to white
            Either a string, rgb list, or hex color string.

        translation_enabled : bool
            If ``False``, the box widget cannot be translated and is strictly
            placed at the given bounds.

        """
        if hasattr(self, 'notebook') and self.notebook:
            raise AssertionError(
                'Plane widget not available in notebook plotting')
        if not hasattr(self, 'iren'):
            raise AttributeError(
                'Widgets must be used with an intereactive renderer. No off screen plotting.'
            )
        if not hasattr(self, "plane_widgets"):
            self.plane_widgets = []

        if origin is None:
            origin = self.center
        if bounds is None:
            bounds = self.bounds

        if isinstance(normal, str):
            normal = NORMALS[normal.lower()]

        if color is None:
            color = rcParams['font']['color']

        def _the_callback(plane_widget, event_id):
            the_plane = vtk.vtkPlane()
            plane_widget.GetPlane(the_plane)
            normal = the_plane.GetNormal()
            origin = the_plane.GetOrigin()
            if hasattr(callback, '__call__'):
                try_callback(callback, normal, origin)
            return

        plane_widget = vtk.vtkImplicitPlaneWidget()
        plane_widget.GetNormalProperty().SetColor(parse_color(color))
        plane_widget.GetOutlineProperty().SetColor(parse_color(color))
        plane_widget.GetOutlineProperty().SetColor(parse_color(color))
        plane_widget.GetPlaneProperty().SetOpacity(0.5)
        plane_widget.SetTubing(tubing)
        plane_widget.SetInteractor(self.iren)
        plane_widget.SetCurrentRenderer(self.renderer)
        plane_widget.SetPlaceFactor(factor)
        plane_widget.PlaceWidget(bounds)
        plane_widget.SetOrigin(origin)
        plane_widget.SetOutlineTranslation(outline_translation)
        plane_widget.SetOriginTranslation(origin_translation)
        if assign_to_axis:
            # TODO: how do we now disable/hide the arrow?
            if assign_to_axis in [0, "x", "X"]:
                plane_widget.NormalToXAxisOn()
                plane_widget.SetNormal(NORMALS["x"])
            elif assign_to_axis in [1, "y", "Y"]:
                plane_widget.NormalToYAxisOn()
                plane_widget.SetNormal(NORMALS["y"])
            elif assign_to_axis in [2, "z", "Z"]:
                plane_widget.NormalToZAxisOn()
                plane_widget.SetNormal(NORMALS["z"])
            else:
                raise RuntimeError("assign_to_axis not understood")
        else:
            plane_widget.SetNormal(normal)
        plane_widget.Modified()
        plane_widget.UpdatePlacement()
        plane_widget.On()
        plane_widget.AddObserver(vtk.vtkCommand.EndInteractionEvent,
                                 _the_callback)
        _the_callback(plane_widget, None)  # Trigger immediate update

        _start_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(
            True)
        _stop_interact = lambda plane_widget, event: plane_widget.SetDrawPlane(
            False)

        plane_widget.SetDrawPlane(False)
        plane_widget.AddObserver(vtk.vtkCommand.StartInteractionEvent,
                                 _start_interact)
        plane_widget.AddObserver(vtk.vtkCommand.EndInteractionEvent,
                                 _stop_interact)

        self.plane_widgets.append(plane_widget)
        return plane_widget
Пример #22
0
    def __init__(self, slider_x, slider_y, slider_z, parent=None):

        super(VTK_Widget1, self).__init__(parent)
        self.source_is_connected = False

        self.slider_x = slider_x
        self.slider_y = slider_y
        self.slider_z = slider_z

        # vtk to point data
        self.c2p = vtk.vtkCellDataToPointData()
        self.opacityTransferFunction = vtk.vtkPiecewiseFunction()
        self.colorTransferFunction = vtk.vtkColorTransferFunction()

        # clip plane
        self.clip_plane = vtk.vtkPlane()
        self.clip_plane.SetNormal(0, 0, 1)

        self.clipper = vtk.vtkClipDataSet()
        self.clipper.SetClipFunction(self.clip_plane)
        self.clipper.SetInputConnection(self.c2p.GetOutputPort())

        # create a volume property for describing how the data will look
        self.volumeProperty = vtk.vtkVolumeProperty()
        self.volumeProperty.SetColor(self.colorTransferFunction)
        self.volumeProperty.SetScalarOpacity(self.opacityTransferFunction)
        self.volumeProperty.ShadeOn()
        self.volumeProperty.SetInterpolationTypeToLinear()

        # convert to unstructured grid volume
        self.triangleFilter = vtk.vtkDataSetTriangleFilter()
        self.triangleFilter.TetrahedraOnlyOn()
        self.triangleFilter.SetInputConnection(self.clipper.GetOutputPort())

        # create a ray cast mapper
        self.compositeFunction = vtk.vtkUnstructuredGridBunykRayCastFunction()
        self.volumeMapper = vtk.vtkUnstructuredGridVolumeRayCastMapper()
        self.volumeMapper.SetRayCastFunction(self.compositeFunction)
        self.volumeMapper.SetInputConnection(self.triangleFilter.GetOutputPort())

        # create a volume
        self.volume = vtk.vtkVolume()
        self.volume.SetMapper(self.volumeMapper)
        self.volume.SetProperty(self.volumeProperty)
        self.volume.VisibilityOff()

        # create the VTK widget for rendering
        self.vtkw = QVTKRenderWindowInteractor(self)
        self.ren = vtk.vtkRenderer()
        self.vtkw.GetRenderWindow().AddRenderer(self.ren)
        self.ren.AddVolume(self.volume)

        self.alphaSlider = QSlider(Qt.Horizontal)
        self.alphaSlider.setValue(33)
        self.alphaSlider.setRange(0, 100)
        self.alphaSlider.setTickPosition(QSlider.NoTicks)
        self.connect(self.alphaSlider, SIGNAL("valueChanged(int)"), self.AdjustAlpha)

        self.alphaLabel = QLabel("alpha: ")

        # layout manager
        self.layout = QVBoxLayout()
        self.layout2 = QHBoxLayout()
        self.layout2.addWidget(self.alphaLabel)
        self.layout2.addWidget(self.alphaSlider)
        self.layout.addWidget(self.vtkw)
        self.layout.addSpacing(34)
        self.layout.addLayout(self.layout2)

        self.setLayout(self.layout)

        # initialize the interactor
        self.vtkw.Initialize()
        self.vtkw.Start()

        # Associate the line widget with the interactor
        self.planeWidget = vtk.vtkImplicitPlaneWidget()
        self.planeWidget.SetInteractor(self.vtkw)
        self.planeWidget.AddObserver("InteractionEvent", self.PlaneWidgetCallback)
        self.planeWidget.DrawPlaneOff()
        self.planeWidget.TubingOn()
Пример #23
0
  def testSlice(self):
    global plane, filter, args
    writefiles = "SaveData" in args

    renderer = vtk.vtkRenderer()
    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    renwin.Render()

    if "GPURender" in args:
        vtk.vtkPistonMapper.InitCUDAGL(renwin)

    src = vtk.vtkImageMandelbrotSource()
    src.SetWholeExtent(0,20,0,20,0,20)

    #scale and bias until piston understands origin and spacing
    src.Update()
    inputdata = src.GetOutput()
    if "Normalize" in args:
         testdata1 = inputdata.NewInstance()
         testdata1.ShallowCopy(inputdata)
         testdata1.SetSpacing(1,1,1)
         testdata1.SetOrigin(0,0,0)
         inputdata = testdata1

    bounds = inputdata.GetBounds()
    center = [(bounds[1]-bounds[0])/2+bounds[0],
              (bounds[3]-bounds[2])/2+bounds[2],
              (bounds[5]-bounds[4])/2+bounds[4]]

    d2p = vtk.vtkDataSetToPiston()
    d2p.SetInputData(inputdata)
    #d2p.SetInputConnection(src.GetOutputPort())

    plane = vtk.vtkPlane()
    plane.SetOrigin(center)
    plane.SetNormal(0,0,1)

    filter = vtk.vtkPistonSlice()
    filter.SetInputConnection(d2p.GetOutputPort())
    filter.SetClippingPlane(plane)
    filter.SetOffset(0.0)

    p2d = vtk.vtkPistonToDataSet()
    p2d.SetOutputDataSetType(vtk.VTK_POLY_DATA)
    p2d.SetInputConnection(filter.GetOutputPort())
    if writefiles:
        writeFile(p2d, "piston_slice.vtk")

    mapper = vtk.vtkPistonMapper()
    mapper.SetInputConnection(filter.GetOutputPort())
    mapper.Update() #TODO why is this necessary

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

    renderer.AddActor(actor)

    widget = vtk.vtkImplicitPlaneWidget()
    widget.PlaceWidget(bounds)
    widget.SetOrigin([plane.GetOrigin()[x] for x in 0,1,2])