def __init__(self, poly_src: vtkPolyDataAlgorithm, parent: Optional['QObject'] = None) -> None: super().__init__(parent=parent) self._poly_src = poly_src self.id = QUuid.createUuid().toString() self.actor = vtkActor() mapper = vtkPolyDataMapper() mapper.SetInputConnection(poly_src.GetOutputPort()) self.actor.SetMapper(mapper) user_transform = vtkTransform() user_transform.Identity() user_transform.PostMultiply() self.actor.SetUserTransform(user_transform) self.actor.ComputeMatrix() transform = vtkTransform() transform.SetMatrix(self.actor.GetMatrix()) self._coord_converter = vtkTransformPolyDataFilter() self._coord_converter.SetTransform(transform) self._coord_converter.AddInputData(poly_src.GetOutput()) self._coord_converter.Update() self._voxelizer = VoxelSlicer() self._voxelizer.SetInputConnection( self._coord_converter.GetOutputPort()) self.results = vtkActor() self._init_input_id_key() self._init_output_id_key(self.results)
def testObjectNameNotCopied(self): foo = vtkActor() foo.SetObjectName("foo") bar = vtkActor() bar.SetObjectName("bar") foo.ShallowCopy(bar) self.assertNotEqual(foo.GetObjectName(),bar.GetObjectName())
def main(): colors = vtkNamedColors() renderer = vtkRenderer() renWin = vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) sphere = vtkSphereSource() sphere.SetPhiResolution(100) sphere.SetThetaResolution(16) sphere.SetCenter(2, 0, 0) sphere.SetRadius(69) sphere.Update() sphereGeom = sphere.GetOutput() cone = vtkConeSource() cone.SetRadius(40) cone.SetHeight(100) cone.SetResolution(50) cone.Update() coneGeom = cone.GetOutput() print('Number of points in sphere = ', sphereGeom.GetNumberOfPoints()) print('Number of triangles in sphere = ', sphereGeom.GetNumberOfCells()) print('Number of points in cone = ', coneGeom.GetNumberOfPoints()) print('Number of triangles in cone = ', coneGeom.GetNumberOfCells()) mapperS = vtkDataSetMapper() mapperS.SetInputData(sphereGeom) actorS = vtkActor() actorS.SetMapper(mapperS) actorS.GetProperty().SetColor(1.0, 0.0, 0.0) actorS.GetProperty().SetOpacity(0.5) renderer.AddActor(actorS) mapperC = vtkDataSetMapper() mapperC.SetInputData(coneGeom) actorC = vtkActor() actorC.SetMapper(mapperC) actorC.GetProperty().SetOpacity(0.5) renderer.AddActor(actorC) renderer.SetBackground(colors.GetColor3d('SlateGray')) renWin.SetSize(640, 480) renWin.SetWindowName('Aarya\'s First VTK Program') renWin.Render() # Interact with the data. iren.Start()
def CreateVisualization(geom): mapper = vtkDataSetMapper() mapper.SetInputData(geom) actor = vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor) return actor
def vtkRenderWidgetConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWidget(root,width=300,height=300) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack() # start the tk mainloop root.mainloop()
def slice_obj(self, printer: PrintSetting, printhead: PixelPrinthead, print_param: GenericPrintParameter) -> None: # TODO not taking advantage of pipeline check later why self.actor.ComputeMatrix() full_trs = vtkTransform() full_trs.SetMatrix(self.actor.GetMatrix()) self._coord_converter.SetTransform(full_trs) self._coord_converter.Update() self._voxelizer.set_settings(printer, printhead, print_param) self._voxelizer.Update() surf = vtkMarchingCubes() surf.SetValue(0, 255) surf.AddInputData(self._voxelizer.GetOutputDataObject(0)) surf.Update() polymap = vtkPolyDataMapper() polymap.SetInputData(surf.GetOutput()) actor = vtkActor() actor.SetMapper(polymap) self._init_output_id_key(actor) self.results.ShallowCopy(actor) self.render_res_sig.emit(self.id)
def toVTK( assy: AssemblyProtocol, renderer: vtkRenderer = vtkRenderer(), loc: Location = Location(), color: Tuple[float, float, float, float] = (1.0, 1.0, 1.0, 1.0), tolerance: float = 1e-3, ) -> vtkRenderer: loc = loc * assy.loc trans, rot = loc.toTuple() if assy.color: color = assy.color.toTuple() if assy.shapes: data = Compound.makeCompound(assy.shapes).toVtkPolyData(tolerance) mapper = vtkMapper() mapper.SetInputData(data) actor = vtkActor() actor.SetMapper(mapper) actor.SetPosition(*trans) actor.SetOrientation(*rot) actor.GetProperty().SetColor(*color[:3]) actor.GetProperty().SetOpacity(color[3]) renderer.AddActor(actor) for child in assy.children: renderer = toVTK(child, renderer, loc, color, tolerance) return renderer
def wxVTKRenderWindowConeExample(): """Like it says, just a simple example. """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # every wx app needs an app app = wx.App(False) # create the widget frame = wx.Frame(None, -1, "wxVTKRenderWindow", size=(400,400)) widget = wxVTKRenderWindow(frame, -1) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the window frame.Show() app.MainLoop()
def QVTKRenderWidgetConeExample(): """A simple example that uses the QVTKRenderWindowInteractor class.""" from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # every QT app needs an app app = QApplication(['QVTKRenderWindowInteractor']) # create the widget widget = QVTKRenderWindowInteractor() widget.Initialize() widget.Start() # if you don't want the 'q' key to exit comment this. widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit()) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the widget widget.show() # start event processing app.exec_()
def main(): ren = vtkRenderer() for item in glob.iglob(pattern, recursive=True): reader = vtk.vtkPolyDataReader() reader.SetFileName(item) reader.Update() polydata = reader.GetOutput() mapper = vtkPolyDataMapper() mapper.SetInputData(polydata) actor = vtkActor() actor.SetMapper(mapper) ren.AddActor(actor) renWin = vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName('DDD') iren = vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renWin.Render() iren.Start()
def create_cone_actor(vertex: Tuple[float, float, float], angle: float, h: float): # TODO maybe it is not good to pass cone object destructed (hard to add new parameters) """ :param angle: angle between z-axis and generaxis """ sign = lambda x: 0 if not x else int(x / abs(x)) coneSource = vtkConeSource() coneSource.SetHeight(h) # coneSource.SetAngle(angle) coneSource.SetResolution(120) # coneSource.SetHeight(vertex[2]) import math coneSource.SetRadius(h * math.tan(math.radians(math.fabs(angle)))) coneSource.SetCenter(vertex[0], vertex[1], (vertex[2] - (h / 2) if angle > 0 else vertex[2] + h / 2)) coneSource.SetDirection(0, 0, 1 * sign(angle)) # update parameters mapper = vtkPolyDataMapper() mapper.SetInputConnection(coneSource.GetOutputPort()) actor = vtkActor() actor.SetMapper(mapper) # create a checkbox for visualization actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetColor(get_color(sett().colors.splane)) return actor
def make_sgrid_actor(sgrid, color='Peacock', edges_on=True, grid_only=True): sgridMapper = vtkDataSetMapper() sgridMapper.SetInputData(sgrid) sgridActor = vtkActor() sgridActor.SetMapper(sgridMapper) sgridActor.GetProperty().SetColor(vtkNamedColors().GetColor3d(color)) if edges_on and not grid_only: sgridActor.GetProperty().EdgeVisibilityOn() if grid_only: sgridActor.GetProperty().SetRepresentationToWireframe() return sgridActor
def SetInput(self, imagedata): axes = PLANE_DATA[self.orientation][0] # "x", "y" or "z" colour = PLANE_DATA[self.orientation][1] #if self.orientation == SAGITAL: # spacing = min(imagedata.GetSpacing()) # permute = vtk.vtkImagePermute() # permute.SetInput(imagedata) # permute.GetOutput().ReleaseDataFlagOn() # permute.SetOutputSpacing(spacing, spacing, spacing) # imagedata = permute.GetOutput() # Picker for enabling plane motion. # Allows selection of a cell by shooting a ray into graphics window picker = vtkCellPicker() picker.SetTolerance(0.005) picker.PickFromListOn() # 3D widget for reslicing image data. # This 3D widget defines a plane that can be interactively placed in an image volume. widget = vtkImagePlaneWidget() widget.SetInput(imagedata) widget.SetSliceIndex(self.index) widget.SetPicker(picker) widget.SetKeyPressActivationValue(axes) widget.SetInteractor(self.iren) widget.TextureVisibilityOff() widget.DisplayTextOff() widget.RestrictPlaneToVolumeOff() exec("widget.SetPlaneOrientationTo" + axes.upper() + "Axes()") widget.AddObserver("InteractionEvent", self.Update) self.widget = widget prop = widget.GetPlaneProperty() prop.SetColor(colour) # Syncronize coloured outline with texture appropriately source = vtkPlaneSource() source.SetOrigin(widget.GetOrigin()) source.SetPoint1(widget.GetPoint1()) source.SetPoint2(widget.GetPoint2()) source.SetNormal(widget.GetNormal()) self.source = source mapper = vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) actor = vtkActor() actor.SetMapper(mapper) actor.SetTexture(widget.GetTexture()) actor.VisibilityOff() self.actor = actor self.render.AddActor(actor)
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # The main window window = gtk.GtkWindow(gtk.WINDOW_TOPLEVEL) window.set_title("A GtkVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) # A VBox into which widgets are packed. vbox = gtk.GtkVBox(spacing=3) window.add(vbox) vbox.show() # The GtkVTKRenderWindow gvtk = GtkVTKRenderWindowInteractor() #gvtk.SetDesiredUpdateRate(1000) gvtk.set_usize(400, 400) vbox.pack_start(gvtk) gvtk.show() gvtk.Initialize() gvtk.Start() # prevents 'q' from exiting the app. gvtk.AddObserver("ExitEvent", lambda o, e, x=None: x) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() gvtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # A simple quit button quit = gtk.GtkButton("Quit!") quit.connect("clicked", gtk.mainquit) vbox.pack_start(quit) quit.show() # show the main window and start event processing. window.show() gtk.mainloop()
def wxVTKRenderWindowInteractorConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # every wx app needs an app app = wx.App(False) # create the top-level frame, sizer and wxVTKRWI frame = wx.Frame(None, -1, "wxVTKRenderWindowInteractor", size=(400, 400)) widget = wxVTKRenderWindowInteractor(frame, -1) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(widget, 1, wx.EXPAND) frame.SetSizer(sizer) frame.Layout() # It would be more correct (API-wise) to call widget.Initialize() and # widget.Start() here, but Initialize() calls RenderWindow.Render(). # That Render() call will get through before we can setup the # RenderWindow() to render via the wxWidgets-created context; this # causes flashing on some platforms and downright breaks things on # other platforms. Instead, we call widget.Enable(). This means # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE, # that doesn't matter. widget.Enable(1) widget.AddObserver("ExitEvent", lambda o, e, f=frame: f.Close()) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the window frame.Show() app.MainLoop()
def stick(molecule, colormode='discrete', bond_thickness=0.1): """Create an actor for stick molecular representation. Parameters ---------- molecule : Molecule The molecule to be rendered. colormode : string, optional Set the colormode for coloring the bonds. Two valid color modes: * 'discrete': Bonds are colored using CPK coloring convention. * 'single': All bonds are colored with the same color (dark grey) RGB tuple used for coloring the bonds when 'single' colormode is selected: (50, 50, 50) Default: 'discrete' bond_thickness : float, optional Used to manipulate the thickness of bonds (i.e. thickness of tubes which are used to render bonds). Default: 0.1 (Optimal range: 0.1 - 0.5). Returns ------- molecule_actor : vtkActor Actor created to render the stick representation of the molecule to be visualized. """ if molecule.total_num_bonds == 0: raise ValueError('No bonding data available for the molecule! Stick ' 'model cannot be made!') colormode = colormode.lower() mst_mapper = dcovtk.vtkOpenGLMoleculeMapper() mst_mapper.SetInputData(molecule) mst_mapper.SetRenderAtoms(True) mst_mapper.SetRenderBonds(True) mst_mapper.SetBondRadius(bond_thickness) mst_mapper.SetAtomicRadiusTypeToUnitRadius() mst_mapper.SetAtomicRadiusScaleFactor(bond_thickness) if colormode == 'discrete': mst_mapper.SetAtomColorMode(1) mst_mapper.SetBondColorMode(1) elif colormode == 'single': mst_mapper.SetAtomColorMode(0) mst_mapper.SetBondColorMode(0) else: mst_mapper.SetAtomColorMode(1) warnings.warn("Incorrect colormode specified! Using discrete.") molecule_actor = rcvtk.vtkActor() molecule_actor.SetMapper(mst_mapper) return molecule_actor
class SampleTest(vtkTest): from vtkmodules.vtkRenderingCore import vtkActor obj = vtkActor() def testParse(self): "Test if class is parseable" self._testParse(self.obj) def testGetSet(self): "Testing Get/Set methods" self._testGetSet(self.obj) def testBoolean(self): "Testing Boolean methods" self._testBoolean(self.obj)
def sphere_cpk(molecule, colormode='discrete'): """Create an actor for sphere molecular representation. It's also referred to as CPK model and space-filling model. Parameters ---------- molecule : Molecule The molecule to be rendered. colormode : string, optional Set the colormode for coloring the atoms. Two valid color modes: * 'discrete': Atoms are colored using CPK coloring convention. * 'single': All atoms are colored with same color (grey). RGB tuple used for coloring the atoms when 'single' colormode is selected: (150, 150, 150). Default: 'discrete' Returns ------- molecule_actor : vtkActor Actor created to render the space filling representation of the molecule to be visualized. References ---------- Corey R.B.; Pauling L. Molecular Models of Amino Acids, Peptides, and Proteins `Review of Scientific Instruments 1953, 24 (8), 621-627. <https://doi.org/10.1063/1.1770803>`_ """ colormode = colormode.lower() msp_mapper = dcovtk.vtkOpenGLMoleculeMapper() msp_mapper.SetInputData(molecule) msp_mapper.SetRenderAtoms(True) msp_mapper.SetRenderBonds(False) msp_mapper.SetAtomicRadiusTypeToVDWRadius() msp_mapper.SetAtomicRadiusScaleFactor(1) if colormode == 'discrete': msp_mapper.SetAtomColorMode(1) elif colormode == 'single': msp_mapper.SetAtomColorMode(0) else: msp_mapper.SetAtomColorMode(1) warnings.warn("Incorrect colormode specified! Using discrete.") # To-Do manipulate shading properties to make it look aesthetic molecule_actor = rcvtk.vtkActor() molecule_actor.SetMapper(msp_mapper) return molecule_actor
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # The main window window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("A GtkVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) # A VBox into which widgets are packed. vbox = gtk.VBox(spacing=3) window.add(vbox) vbox.show() # The GtkVTKRenderWindow gvtk = GtkGLExtVTKRenderWindowInteractor() #gvtk.SetDesiredUpdateRate(1000) gvtk.set_size_request(400, 400) vbox.pack_start(gvtk) gvtk.show() gvtk.Initialize() gvtk.Start() # prevents 'q' from exiting the app. gvtk.AddObserver("ExitEvent", lambda o,e,x=None: x) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() gvtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # A simple quit button quit = gtk.Button("Quit!") quit.connect("clicked", gtk.mainquit) vbox.pack_start(quit) quit.show() # show the main window and start event processing. window.show() gtk.mainloop()
def QVTKRenderWidgetConeExample(): """A simple example that uses the QVTKRenderWindowInteractor class.""" from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # every QT app needs an app app = QApplication(['QVTKRenderWindowInteractor']) window = QMainWindow() # create the widget widget = QVTKRenderWindowInteractor(window) window.setCentralWidget(widget) # if you don't want the 'q' key to exit comment this. widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit()) ren = vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the widget window.show() widget.Initialize() widget.Start() # start event processing # Source: https://doc.qt.io/qtforpython/porting_from2.html # 'exec_' is deprecated and will be removed in the future. # Use 'exec' instead. try: app.exec() except AttributeError: app.exec_()
def OnLoadSurfaceDict(self, surface_dict): for key in surface_dict: surface = surface_dict[key] # Map polygonal data (vtkPolyData) to graphics primitives. normals = vtkPolyDataNormals() normals.SetInputData(surface.polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() # Improve performance stripper = vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) stripper.PassThroughCellIdsOn() stripper.PassThroughPointIdsOn() mapper = vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) mapper.ScalarVisibilityOff() # mapper.ImmediateModeRenderingOn() # improve performance # Represent an object (geometry & properties) in the rendered scene actor = vtkActor() actor.GetProperty().SetBackfaceCulling(1) actor.SetMapper(mapper) # Set actor colour and transparency actor.GetProperty().SetColor(surface.colour[:3]) actor.GetProperty().SetOpacity(1 - surface.transparency) self.actors_dict[surface.index] = actor # Send actor by pubsub to viewer's render Publisher.sendMessage('Load surface actor into viewer', actor=actor) Publisher.sendMessage('Update status text in GUI', label=_("Ready")) # The following lines have to be here, otherwise all volumes disappear Publisher.sendMessage('Update surface info in GUI', surface=surface) if not surface.is_shown: self.ShowActor(key, False)
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # The main window window = gtk.Window() window.set_title("A GtkGLExtVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) vtkgtk = GtkGLExtVTKRenderWindow() vtkgtk.show() vbox = gtk.VBox(spacing=3) vbox.show() vbox.pack_start(vtkgtk) button = gtk.Button('My Button') button.show() vbox.pack_start(button) window.add(vbox) window.set_size_request(400, 400) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() vtkgtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # show the main window and start event processing. window.show() gtk.mainloop()
def vtkRenderWindowInteractorConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # load implementations for rendering and interaction factory classes import vtkmodules.vtkRenderingOpenGL2 import vtkmodules.vtkInteractionStyle # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWindowInteractor(root, width=300, height=300) pane.Initialize() def quit(obj=root): obj.quit() pane.AddObserver("ExitEvent", lambda o, e, q=quit: q()) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack(fill='both', expand=1) pane.Start() # start the tk mainloop root.mainloop()
def createLine(point1: tuple, point2: tuple, color: str = "Black") -> vtkActor: """ :param point1: :param point2: :param color: :return: """ line = vtkLineSource() line.SetPoint1(*point1) line.SetPoint2(*point2) mapper = vtkPolyDataMapper() mapper.SetInputConnection(line.GetOutputPort()) actor = vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(vtkNamedColors().GetColor3d(color)) return actor
def main(): from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # The main window window = gtk.Window() window.set_title("A GtkGLExtVTKRenderWindow Demo!") window.connect("destroy", gtk.mainquit) window.connect("delete_event", gtk.mainquit) window.set_border_width(10) vtkgtk = GtkGLExtVTKRenderWindow() vtkgtk.show() vbox = gtk.VBox(spacing=3) vbox.show() vbox.pack_start(vtkgtk) button = gtk.Button('My Button') button.show() vbox.pack_start(button) window.add(vbox) window.set_size_request(400, 400) # The VTK stuff. cone = vtkConeSource() cone.SetResolution(80) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) #coneActor = vtkLODActor() coneActor = vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(0.5, 0.5, 1.0) ren = vtkRenderer() vtkgtk.GetRenderWindow().AddRenderer(ren) ren.AddActor(coneActor) # show the main window and start event processing. window.show() gtk.mainloop()
def vtkRenderWindowInteractorConeExample(): """Like it says, just a simple example https://gitlab.kitware.com/vtk/vtk/-/blob/master/Wrapping/Python/vtkmodules/tk/vtkTkRenderWindowInteractor.py """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer from vtkmodules.tk.vtkTkRenderWindowInteractor import vtkTkRenderWindowInteractor # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWindowInteractor(root, width=300, height=300) pane.Initialize() def quit(obj=root): obj.quit() pane.AddObserver("ExitEvent", lambda o,e,q=quit: q()) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack(fill='both', expand=1) pane.Start() # start the tk mainloop root.mainloop()
def Create(self): self.plane_widget = plane_widget = vtkImagePlaneWidget() plane_widget.SetInputData(self.img) plane_widget.SetPlaneOrientationToXAxes() #plane_widget.SetResliceInterpolateToLinear() plane_widget.TextureVisibilityOff() #Set left mouse button to move and rotate plane plane_widget.SetLeftButtonAction(1) #SetColor margin to green margin_property = plane_widget.GetMarginProperty() margin_property.SetColor(0, 0.8, 0) #Disable cross cursor_property = plane_widget.GetCursorProperty() cursor_property.SetOpacity(0) self.plane_source = plane_source = vtkPlaneSource() plane_source.SetOrigin(plane_widget.GetOrigin()) plane_source.SetPoint1(plane_widget.GetPoint1()) plane_source.SetPoint2(plane_widget.GetPoint2()) plane_source.SetNormal(plane_widget.GetNormal()) plane_mapper = self.plane_mapper = vtkPolyDataMapper() plane_mapper.SetInputData(plane_source.GetOutput()) self.plane_actor = plane_actor = vtkActor() plane_actor.SetMapper(plane_mapper) plane_actor.GetProperty().BackfaceCullingOn() plane_actor.GetProperty().SetOpacity(0) plane_widget.AddObserver("InteractionEvent", self.Update) Publisher.sendMessage('AppendActor', actor=self.plane_actor) Publisher.sendMessage('Set Widget Interactor', widget=self.plane_widget) plane_actor.SetVisibility(1) plane_widget.On() self.plane = plane = vtkPlane() plane.SetNormal(self.plane_source.GetNormal()) plane.SetOrigin(self.plane_source.GetOrigin()) self.volume_mapper.AddClippingPlane(plane) #Storage First Position self.origin = plane_widget.GetOrigin() self.p1 = plane_widget.GetPoint1() self.p2 = plane_widget.GetPoint2() self.normal = plane_widget.GetNormal()
def vtkRenderWindowInteractorConeExample(): """Like it says, just a simple example """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer # create root window root = tkinter.Tk() # create vtkTkRenderWidget pane = vtkTkRenderWindowInteractor(root, width=300, height=300) pane.Initialize() def quit(obj=root): obj.quit() pane.AddObserver("ExitEvent", lambda o,e,q=quit: q()) ren = vtkRenderer() pane.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # pack the pane into the tk root pane.pack(fill='both', expand=1) pane.Start() # start the tk mainloop root.mainloop()
def _do_surface_creation(self, mask, mask_sFormMatrix=None): if mask_sFormMatrix is None: mask_sFormMatrix = vtkMatrix4x4() value = np.mean(mask.GetScalarRange()) # Use the mask to create isosurface mc = vtkContourFilter() mc.SetInputData(mask) mc.SetValue(0, value) mc.ComputeNormalsOn() mc.Update() # Mask isosurface refSurface = mc.GetOutput() # Create a uniformly meshed surface tmpPeel = downsample(refSurface) # Standard space coordinates # Apply coordinate transform to the meshed mask mask_ijk2xyz = vtkTransform() mask_ijk2xyz.SetMatrix(mask_sFormMatrix) mask_ijk2xyz_filter = vtkTransformPolyDataFilter() mask_ijk2xyz_filter.SetInputData(tmpPeel) mask_ijk2xyz_filter.SetTransform(mask_ijk2xyz) mask_ijk2xyz_filter.Update() # Smooth the mesh tmpPeel = smooth(mask_ijk2xyz_filter.GetOutput()) # Configure calculation of normals tmpPeel = fixMesh(tmpPeel) # Remove duplicate points etc # tmpPeel = cleanMesh(tmpPeel) # Generate triangles tmpPeel = upsample(tmpPeel) tmpPeel = smooth(tmpPeel) tmpPeel = fixMesh(tmpPeel) tmpPeel = cleanMesh(tmpPeel) refImageSpace2_xyz_transform = vtkTransform() refImageSpace2_xyz_transform.SetMatrix(vtk_utils.numpy_to_vtkMatrix4x4(np.linalg.inv(self.affine))) self.refImageSpace2_xyz = vtkTransformPolyDataFilter() self.refImageSpace2_xyz.SetTransform(refImageSpace2_xyz_transform) xyz2_refImageSpace_transform = vtkTransform() xyz2_refImageSpace_transform.SetMatrix(vtk_utils.numpy_to_vtkMatrix4x4(self.affine)) self.xyz2_refImageSpace = vtkTransformPolyDataFilter() self.xyz2_refImageSpace.SetTransform(xyz2_refImageSpace_transform) currentPeel = tmpPeel self.currentPeelNo = 0 currentPeel= self.MapImageOnCurrentPeel(currentPeel) newPeel = vtkPolyData() newPeel.DeepCopy(currentPeel) newPeel.DeepCopy(currentPeel) self.peel_normals = vtkFloatArray() self.peel_centers = vtkFloatArray() self.peel.append(newPeel) self.currentPeelActor = vtkActor() if not np.all(np.equal(self.affine, np.eye(4))): affine_vtk = self.CreateTransformedVTKAffine() self.currentPeelActor.SetUserMatrix(affine_vtk) self.GetCurrentPeelActor(currentPeel) self.peelActors.append(self.currentPeelActor) # locator will later find the triangle on the peel surface where the coil's normal intersect self.locator = vtkCellLocator() self.PeelDown(currentPeel)
def main(): colors = vtkNamedColors() operation = "intersection" reader = vtkUnstructuredGridReader() reader.SetFileName(ATRIA_VTK_FILE) geo_filter = vtkGeometryFilter() geo_filter.SetInputConnection(reader.GetOutputPort()) geo_filter.Update() poly1 = geo_filter.GetOutput() tri1 = vtkTriangleFilter() tri1.SetInputData(poly1) clean1 = vtkCleanPolyData() clean1.SetInputConnection(tri1.GetOutputPort()) clean1.Update() input1 = clean1.GetOutput() sphereSource1 = vtkSphereSource() sphereSource1.SetCenter(20.43808060942321, 18.333007878470767, 34.5753857481471) sphereSource1.SetRadius(0.5) # sphereSource1.SetPhiResolution(21) # sphereSource1.SetThetaResolution(21) sphereSource1.Update() input2 = sphereSource1.GetOutput() input1Mapper = vtkPolyDataMapper() input1Mapper.SetInputData(input1) input1Mapper.ScalarVisibilityOff() input1Actor = vtkActor() input1Actor.SetMapper(input1Mapper) input1Actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Tomato")) input1Actor.GetProperty().SetSpecular(0.6) input1Actor.GetProperty().SetSpecularPower(20) # input1Actor.SetPosition(input1.GetBounds()[1] - input1.GetBounds()[0], 0, 0) input2Mapper = vtkPolyDataMapper() input2Mapper.SetInputData(input2) input2Mapper.ScalarVisibilityOff() input2Actor = vtkActor() input2Actor.SetMapper(input2Mapper) input2Actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Mint")) input2Actor.GetProperty().SetSpecular(0.6) input2Actor.GetProperty().SetSpecularPower(20) # input2Actor.SetPosition(-(input1.GetBounds()[1] - input1.GetBounds()[0]), 0, 0) booleanOperation = vtkBooleanOperationPolyDataFilter() if operation.lower() == "union": booleanOperation.SetOperationToUnion() elif operation.lower() == "intersection": booleanOperation.SetOperationToIntersection() elif operation.lower() == "difference": booleanOperation.SetOperationToDifference() else: print("Unknown operation:", operation) return booleanOperation.SetInputData(0, input1) booleanOperation.SetInputData(1, input2) booleanOperationMapper = vtkPolyDataMapper() booleanOperationMapper.SetInputConnection(booleanOperation.GetOutputPort()) booleanOperationMapper.ScalarVisibilityOff() booleanOperationActor = vtkActor() booleanOperationActor.SetMapper(booleanOperationMapper) booleanOperationActor.GetProperty().SetDiffuseColor( colors.GetColor3d("Banana")) booleanOperationActor.GetProperty().SetSpecular(0.6) booleanOperationActor.GetProperty().SetSpecularPower(20) renderer = vtkRenderer() renderer.AddViewProp(input1Actor) renderer.AddViewProp(input2Actor) renderer.AddViewProp(booleanOperationActor) renderer.SetBackground(colors.GetColor3d("Silver")) renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetSize(640, 480) renderWindow.SetWindowName("BooleanOperationPolyDataFilter") viewUp = [0.0, 0.0, 1.0] position = [0.0, -1.0, 0.0] PositionCamera(renderer, viewUp, position) renderer.GetActiveCamera().Dolly(1.4) renderer.ResetCameraClippingRange() renWinInteractor = vtkRenderWindowInteractor() renWinInteractor.SetRenderWindow(renderWindow) renderWindow.Render() renWinInteractor.Start()
def _actor(self, mapper=None): actor = vtkActor() if mapper is not None: actor.SetMapper(mapper) _hide_testing_actor(actor) return actor
def wxVTKRenderWindowInteractorConeExample(): """Like it says, just a simple example https://discourse.vtk.org/t/interactor-start-blocking-execution/1095/2 https://gitlab.kitware.com/vtk/vtk/-/blob/master/Wrapping/Python/vtkmodules/wx/wxVTKRenderWindowInteractor.py ipython --gui=wx #gui wx run learn_vtk.py """ from vtkmodules.vtkFiltersSources import vtkConeSource from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer from vtkmodules.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor import wx colors = vtk.vtkNamedColors() # every wx app needs an app app = wx.App(False) # create the top-level frame, sizer and wxVTKRWI frame = wx.Frame(None, -1, "wxVTKRenderWindowInteractor", size=(400,400)) widget = wxVTKRenderWindowInteractor(frame, -1) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(widget, 1, wx.EXPAND) frame.SetSizer(sizer) frame.Layout() # It would be more correct (API-wise) to call widget.Initialize() and # widget.Start() here, but Initialize() calls RenderWindow.Render(). # That Render() call will get through before we can setup the # RenderWindow() to render via the wxWidgets-created context; this # causes flashing on some platforms and downright breaks things on # other platforms. Instead, we call widget.Enable(). This means # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE, # that doesn't matter. widget.Enable(1) widget.AddObserver("ExitEvent", lambda o,e,f=frame: f.Close()) ren = vtkRenderer() renwin = widget.GetRenderWindow() widget.GetRenderWindow().AddRenderer(ren) cone = vtkConeSource() cone.SetResolution(8) coneMapper = vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the window frame.Show() # It works! # wx.CallLater(1000*5, lambda : ren.SetBackground(colors.GetColor3d('Blue'))) # wx.CallLater(1000*8, lambda : renwin.Render()) # colors = vtk.vtkNamedColors() # wx.CallAfter(lambda : ren.SetBackground(colors.GetColor3d('Blue'))) # wx.CallAfter(lambda : renwin.Render()) def fn(): ren.SetBackground(colors.GetColor3d('Blue')) renwin.Render() wx.CallLater(1000*3, fn) #app.MainLoop() # comment out to interact in ipython return app, ren, renwin
interp = vtkAdaptiveTemporalInterpolator() interp.SetInputConnection(reader.GetOutputPort()) geom = vtkCompositeDataGeometryFilter() geom.SetInputConnection(interp.GetOutputPort()) # map them mapper = vtkCompositePolyDataMapper() mapper.SetInputConnection(geom.GetOutputPort()) mapper.SetScalarModeToUsePointFieldData() mapper.SelectColorArray('point_poly') mapper.SetScalarRange(1.0, 6.0) mapper.InterpolateScalarsBeforeMappingOn() mapper.SetScalarVisibility(1) actor = vtkActor() actor.SetMapper(mapper) renderer = vtkRenderer() renWin = vtkRenderWindow() iren = vtkRenderWindowInteractor() renderer.AddActor(actor) renderer.SetBackground(0.0, 0.0, 0.0) renWin.AddRenderer(renderer) renWin.SetSize(300, 300) iren.SetRenderWindow(renWin) # ask for some specific data points info = geom.GetOutputInformation(0)