def __init__(self): ActorFactory.ActorFactory.__init__(self) colors = ((1, 0, 0), (0, 1, 0), (0, 0, 1)) self._Properties = [] for i in range(3): property = vtk.vtkProperty() property.SetColor(colors[i]) property.SetAmbient(1.0) property.SetOpacity(0.3) self._Properties.append(property) self._ConeProperties = [] for i in range(3): property = vtk.vtkProperty() property.SetColor(colors[i]) property.SetAmbient(1.0) # property.SetOpacity(0.3) self._ConeProperties.append(property) self._Planes = [] self._Cutters = [] self._LineActorsIndex = [] self._ConeActorsIndex = [] self._ConeSize = 24.0 self._Cones = [] for i in range(6): cone = vtk.vtkConeSource() cone.SetResolution(2) cone.SetHeight(self._ConeSize) cone.SetRadius(self._ConeSize) self._Cones.append(cone)
def build_constelation(self,mol): if mol.acteur == None : MB.showwarning('Info','Select a molecule in the list') return if mol.symobs !=None: mol.acteur.RemoveObserver(mol.symobs) if mol.lsm!=[]: for sm in mol.lsm: self.gfx.renderer.RemoveActor(sm) mol.lsm=[] (xmin, xmax, ymin, ymax, zmin, zmax)= self.bounds sym=open(self.symlistfile,'r') for l in sym: ms = l.split() nbl = int(ms[6][1:]) if nbl not in mol.lnbsm: continue ang = [float(ms[0]),float(ms[1]),float(ms[2])] tra = array([float(ms[3]),float(ms[4]),float(ms[5])]) sm=symmate() #on cree un symmate vide sm.SetPosition(mol.acteur.GetPosition()) #on assigne la partie translationelle des pv sm.SetOrientation(mol.acteur.GetOrientation()) #on assigne la partie rotationelle des pv self.RotaEuler(sm.ut,ang[0],ang[1],ang[2]) #on defini la partie rotationelle de la transformation sm.ut.Translate(tra[0],tra[1],tra[2]) #on defini la partie translationelle de la transformation sm.SetUserTransform(sm.ut) #on assigne la transformation a notre symmate pip = [sm.GetMatrix().GetElement(0,3),sm.GetMatrix().GetElement(1,3),sm.GetMatrix().GetElement(2,3)]#on recupere la partie translationelle de la combinaison de pv et de la transformation (ut) if (xmin + self.mdbe < pip[0]) and (pip[0] < xmax - self.mdbe) and (ymin + self.mdbe < pip[1]) and (pip[1] < ymax - self.mdbe) and (zmin + self.mdbe < pip[2]) and (pip[2] < zmax - self.mdbe):# on test si pip est dans la boite sm.nbsym=nbl if mol.acteur.GetClassName()=='vtkAssembly':# dans le cas ou la molecule independante est un assembly for i in range(mol.acteur.GetNumberOfPaths()): tmp=vtk.vtkActor() tmp.SetMapper(mol.acteur.GetParts().GetItemAsObject(i).GetMapper()) p=vtk.vtkProperty() #p.SetColor(mol.acteur.GetParts().GetItemAsObject(i).GetProperty().GetColor()) p.SetColor(Map.invcolor(mol.acteur.GetParts().GetItemAsObject(i).GetProperty().GetColor())) tmp.SetProperty(p) if mol.mod.type=='mol': tmp.GetProperty().SetLineWidth(4) tmp.DragableOff() tmp.PickableOff() sm.AddPart(tmp) else:#cas simple ou la mol ind est composer d un seul objet tmp=vtk.vtkActor() tmp.SetMapper(mol.acteur.GetMapper()) p=vtk.vtkProperty() #p.SetColor(mol.acteur.GetParts().GetItemAsObject(i).GetProperty().GetColor()) p.SetColor(Map.invcolor(mol.acteur.GetProperty().GetColor())) tmp.SetProperty(p) if mol.mod.type=='mol': tmp.GetProperty().SetLineWidth(4) tmp.DragableOff() tmp.PickableOff() sm.AddPart(tmp) mol.lsm+=[sm]# on ajoute le symmate a la liste des symmate sym.close() self.move_sym(mol)
def __init__(self): ActorFactory.__init__(self) self._Property = vtk.vtkProperty() self._Plane = None self._Line = [] for i in range(4): self._Line.append(vtk.vtkLineSource())
def __addNucleiToScene(self, reader): av = self.active_vol self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection( reader.GetOutputPort() ) # Create an actor self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) #center = self.actor.GetCenter() #cent = self._vdata[av]._electrodes[1].centroid #self._cameras[av].SetFocalPoint(cent) self.prop = vtk.vtkProperty() self.prop.ShadingOn() self.prop.SetInterpolationToGouraud() self.prop.EdgeVisibilityOff() #self.prop.EdgeVisibilityOn() self.prop.SetDiffuse(0.7) self.prop.SetSpecular(0.4) self.prop.SetSpecularPower(20) self.prop.SetColor(1.0, 1.0, 0) self.actor.SetProperty(self.prop) self._renderers[av].AddActor(self.actor) actv = self.active_vol self.vol_qvtk_widgets[actv].update()
def test_method_signature(self): """Check if VTK method signatures are parsed correctly.""" p = self.p # Simple tests. o = vtk.vtkProperty() self.assertEqual([(["string"], None)], p.get_method_signature(o.GetClassName)) if hasattr(vtk, "vtkArrayCoordinates"): self.assertEqual( [ ([("float", "float", "float")], None), ([None], (["float", "float", "float"],)), ([None], ("float", "float", "float")), ], p.get_method_signature(o.GetColor), ) else: self.assertEqual( [([("float", "float", "float")], None), ([None], (("float", "float", "float"),))], p.get_method_signature(o.GetColor), ) if hasattr(vtk, "vtkArrayCoordinates"): self.assertEqual( [([None], ("float", "float", "float")), ([None], (["float", "float", "float"],))], p.get_method_signature(o.SetColor), ) else: self.assertEqual( [([None], ("float", "float", "float")), ([None], (("float", "float", "float"),))], p.get_method_signature(o.SetColor), ) # Get VTK version to handle changed APIs. vtk_ver = vtk.vtkVersion().GetVTKVersion() # Test vtkObjects args. o = vtk.vtkContourFilter() sig = p.get_method_signature(o.SetInput) if len(sig) == 1: self.assertEqual([([None], ["vtkDataSet"])], sig) elif vtk_ver[:3] in ["4.2", "4.4"]: self.assertEqual( [ ([None], ["vtkDataObject"]), ([None], ("int", "vtkDataObject")), ([None], ["vtkDataSet"]), ([None], ("int", "vtkDataSet")), ], sig, ) elif vtk_ver[:2] == "5." or vtk_ver[:3] == "4.5": self.assertEqual([([None], ["vtkDataObject"]), ([None], ("int", "vtkDataObject"))], sig) self.assertEqual([(["vtkPolyData"], None), (["vtkPolyData"], ["int"])], p.get_method_signature(o.GetOutput)) # Test if function arguments work. self.assertEqual([(["int"], ("int", "function"))], p.get_method_signature(o.AddObserver)) # This one's for completeness. self.assertEqual([([None], ["int"])], p.get_method_signature(o.RemoveObserver))
def SetPlanes(self, planes): """Set a set of SlicePlaneFactory.""" self._Planes = planes self._properties = [] for i in range(len(self._Planes)): self._properties.append(vtk.vtkProperty()) self._UpdateIntersections()
def __init__(self, *args, **kwargs): VtkRenderArea.__init__(self, *args, **kwargs) self._CurrentRenderer = None self._CurrentCamera = None self._CurrentZoom = 1.0 self._CurrentLight = None self._ViewportCenterX = 0 self._ViewportCenterY = 0 self._Picker = vtk.vtkCellPicker() self._PickedAssembly = None self._PickedProperty = vtk.vtkProperty() self._PickedProperty.SetColor(1, 0, 0) self._PrePickedProperty = None self._OldFocus = None # need this to be able to handle key_press events. self.set_flags(gtk.CAN_FOCUS) # these record the previous mouse position self._LastX = 0 self._LastY = 0 self.connect('button_press_event', self.OnButtonDown) self.connect('button_release_event', self.OnButtonUp) self.connect('motion_notify_event', self.OnMouseMove) self.connect('key_press_event', self.OnKeyPress) self.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.KEY_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)
def SetElectrodeColor(self, r, g, b): """ Set the color for a channel actor """ tempProperty = vtk.vtkProperty() tempProperty.SetColor(r, g, b) self.channelActors.ApplyProperty(tempProperty)
def __build_cross_lines(self): renderer = self.slice_data.overlay_renderer cross = vtk.vtkCursor3D() cross.AllOff() cross.AxesOn() self.cross = cross c = vtk.vtkCoordinate() c.SetCoordinateSystemToWorld() cross_mapper = vtk.vtkPolyDataMapper() cross_mapper.SetInput(cross.GetOutput()) #cross_mapper.SetTransformCoordinate(c) p = vtk.vtkProperty() p.SetColor(1, 0, 0) cross_actor = vtk.vtkActor() cross_actor.SetMapper(cross_mapper) cross_actor.SetProperty(p) cross_actor.VisibilityOff() # Only the slices are pickable cross_actor.PickableOff() self.cross_actor = cross_actor renderer.AddActor(cross_actor)
def __init__(self): ActorFactory.ActorFactory.__init__(self) # Create a green line self._Points = vtk.vtkPoints() self._Lines = vtk.vtkCellArray() self._Poly = vtk.vtkPolyData() self._Poly.SetPoints(self._Points) self._Poly.SetLines(self._Lines) self._PathProperty = vtk.vtkProperty() self._PathProperty.SetColor(0, 1, 0) self._PathProperty.SetOpacity(0.0) # turn the line into a cylinder self._tube = vtk.vtkTubeFilter() # VTK-6 if vtk.vtkVersion().GetVTKMajorVersion() > 5: self._tube.SetInputData(self._Poly) else: self._tube.SetInput(self._Poly) self._tube.SetNumberOfSides(3) self._tube.SetRadius(2.5)
def __init__(self, brain_data, isoval=34): # Setup Surface Rendering # Gaussian smoothing of surface rendering for aesthetics # Adds significant delay to rendering self.cortexSmoother = vtk.vtkImageGaussianSmooth() self.cortexSmoother.SetDimensionality(3) self.cortexSmoother.SetRadiusFactors(0.5, 0.5, 0.5) self.cortexSmoother.SetInput(brain_data.GetOutput()) # Apply a marching cubes algorithm to extract surface contour with # isovalue of 30 (can change to adjust proper rendering of tissue self.cortexExtractor = vtk.vtkMarchingCubes() self.cortexExtractor.SetInput(self.cortexSmoother.GetOutput()) self.cortexExtractor.SetValue(0, isoval) self.cortexExtractor.ComputeNormalsOn() # Map/Paint the polydata associated with the surface rendering self.cortexMapper = vtk.vtkPolyDataMapper() self.cortexMapper.SetInput(self.cortexExtractor.GetOutput()) self.cortexMapper.ScalarVisibilityOff() # Color the cortex (RGB) self.cortexProperty = vtk.vtkProperty() self.cortexProperty.SetColor(1, 1, 1) self.cortexProperty.SetOpacity(1); # Set the actor to adhere to mapped surface and inherit properties self.SetMapper(self.cortexMapper) self.SetProperty(self.cortexProperty) self.cortexExtractor.Update()
def CreateSphereMarkers(self, pubsub_evt): ball_id = pubsub_evt.data[0] ballsize = pubsub_evt.data[1] ballcolour = pubsub_evt.data[2] coord = pubsub_evt.data[3] x, y, z = bases.flip_x(coord) ball_ref = vtk.vtkSphereSource() ball_ref.SetRadius(ballsize) ball_ref.SetCenter(x, y, z) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(ball_ref.GetOutput()) prop = vtk.vtkProperty() prop.SetColor(ballcolour) #adding a new actor for the present ball self.staticballs.append(vtk.vtkActor()) self.staticballs[ball_id].SetMapper(mapper) self.staticballs[ball_id].SetProperty(prop) self.ren.AddActor(self.staticballs[ball_id]) ball_id = ball_id + 1 self.UpdateRender()
def __init__(self): ActorFactory.ActorFactory.__init__(self) self.SetName("RectROI") # colors self._ActiveColor = (0, 1, 0) self._HandleColor = tomato self._LineColor = banana # Mode 0: Click and Drag to set ROI; # 1: Control-Click and drag to set ROI self._Mode = 1 # 4 corner squares self._Corners = [] for i in range(4): corner = RectangleSource() self._Corners.append(corner) self._CornerProperty = vtk.vtkProperty() self._CornerProperty.SetOpacity(0) self._CornerProperty.SetColor(self._HandleColor) # center cross self._Center = CrossSource() self._CenterProperty = vtk.vtkProperty() self._CenterProperty.SetColor(self._HandleColor) self._CenterProperty.SetOpacity(0) # rectangle ROI self._ROI = RectangleSource() self._ROIProperty = vtk.vtkProperty() self._ROIProperty.SetColor(self._LineColor) self._ROIProperty.SetOpacity(0) # hack for VCT project: we need to pick the active viewport self._viewportManager = None # listener method self._listenerMethods = [] # x or y translate only for fixed size ROI, used by VCT scanner self._XOnly = False self._YOnly = False self._clearROI = False
def vtkKWSurfaceMaterialPropertyWidgetEntryPoint(parent, win): app = parent.GetApplication() # ----------------------------------------------------------------------- # Create the surface property that will be modified by the widget sprop1 = vtkProperty() # ----------------------------------------------------------------------- # Create the material widget # Assign our surface property to the editor sprop1_widget = vtkKWSurfaceMaterialPropertyWidget() sprop1_widget.SetParent(parent) sprop1_widget.Create() sprop1_widget.SetBalloonHelpString( "A surface material property widget.") sprop1_widget.SetProperty(sprop1) app.Script( "pack %s -side top -anchor nw -expand n -padx 2 -pady 2", sprop1_widget.GetWidgetName()) # ----------------------------------------------------------------------- # Create another material widget, in popup mode # Assign our surface property to the editor sprop2_widget = vtkKWSurfaceMaterialPropertyWidget() sprop2_widget.SetParent(parent) sprop2_widget.PopupModeOn() sprop2_widget.Create() sprop2_widget.SetBalloonHelpString( "A surface material property widget, created in popup mode. Note that " "it edits the same surface property object as the first widget.") sprop2_widget.SetProperty(sprop1) app.Script( "pack %s -side top -anchor nw -expand n -padx 2 -pady 15", sprop2_widget.GetWidgetName()) # Both editor are linked to the same surface prop, so they should notify # each other of any changes to refresh the preview nicely sprop2_widget.SetPropertyChangingCommand(sprop1_widget, "Update") sprop2_widget.SetPropertyChangedCommand(sprop1_widget, "Update") sprop1_widget.SetPropertyChangingCommand(sprop2_widget, "Update") sprop1_widget.SetPropertyChangedCommand(sprop2_widget, "Update") return "TypeVTK"
def __init__(self): self.AddObserver('LeftButtonPressEvent', self.onLeftButtonPressEvent) self.AddObserver('MouseMoveEvent', self.onMouseMoveEvent) self.AddObserver('LeftButtonReleaseEvent', self.onLeftButtonReleaseEvent) self._lastPickedActor = None self._lastPickedProperty = vtk.vtkProperty() self._mouseMoved = False
def getLine(self,roi, mrsDefFilePath ): xr=roi[1]-roi[0] yr=roi[3]-roi[2] r=max(xr,yr) ##checks roi and determines the resolution of requested file if r<50: resFile="high" if r>=50 and r<=100: resFile="medium" else: resFile="high" directory=self._reader.openFile(resFile,mrsDefFilePath) print(directory) print('1') #rel_coastFilePath=self._reader.read(resFile, mrsDefFilePath) root_path=os.path.abspath( os.path.dirname( mrsDefFilePath ) ) print(root_path) #combines two directories together full_coastFilePath=os.path.join( root_path, directory) sf = shapefile.Reader(full_coastFilePath) shapes = sf.shapes() points = vtk.vtkPoints() lines = vtk.vtkCellArray() for x in range(len(shapes)): shape = shapes[x] nPts = len( shape.points ) idList=vtk.vtkIdList() for iPt in range(nPts): pt = shape.points[iPt] if pt[0]>roi[0] and pt[0]<roi[1]: if pt[1]>roi[2] and pt[1]<roi[3]: ptIndex=points.InsertNextPoint(pt[0], pt[1], 0.0 ) idList.InsertNextId(ptIndex) lines.InsertNextCell(idList) polygon = vtk.vtkPolyData() polygon.SetPoints(points) polygon.SetLines(lines) polygonMapper = vtk.vtkPolyDataMapper() polygonMapper.SetInputConnection(polygon.GetProducerPort()) polygonActor = vtk.vtkActor() polygonActor.SetMapper(polygonMapper) property = vtk.vtkProperty() property.SetColor(self._rgb) property.SetLineWidth(self._linewidth) polygonActor.SetProperty(property) return polygonActor
def test_method_signature(self): """Check if VTK method signatures are parsed correctly.""" p = self.p # Simple tests. o = vtk.vtkProperty() self.assertEqual([(['string'], None)], p.get_method_signature(o.GetClassName)) if hasattr(vtk, 'vtkArrayCoordinates'): self.assertEqual([([('float', 'float', 'float')], None), ([None], (['float', 'float', 'float'],)), ([None], ('float', 'float', 'float'))], p.get_method_signature(o.GetColor)) else: self.assertEqual([([('float', 'float', 'float')], None), ([None], (('float', 'float', 'float'),))], p.get_method_signature(o.GetColor)) if hasattr(vtk, 'vtkArrayCoordinates'): self.assertEqual([([None], ('float', 'float', 'float')), ([None], (['float', 'float', 'float'],))], p.get_method_signature(o.SetColor)) else: self.assertEqual([([None], ('float', 'float', 'float')), ([None], (('float', 'float', 'float'),))], p.get_method_signature(o.SetColor)) # Get VTK version to handle changed APIs. vtk_ver = vtk.vtkVersion().GetVTKVersion() # Test vtkObjects args. o = vtk.vtkContourFilter() sig = p.get_method_signature(o.SetInput) if len(sig) == 1: self.assertEqual([([None], ['vtkDataSet'])], sig) elif vtk_ver[:3] in ['4.2', '4.4']: self.assertEqual([([None], ['vtkDataObject']), ([None], ('int', 'vtkDataObject')), ([None], ['vtkDataSet']), ([None], ('int', 'vtkDataSet')) ], sig) elif vtk_ver[:2] == '5.' or vtk_ver[:3] == '4.5': self.assertEqual([([None], ['vtkDataObject']), ([None], ('int', 'vtkDataObject')), ], sig) self.assertEqual([(['vtkPolyData'], None), (['vtkPolyData'], ['int'])], p.get_method_signature(o.GetOutput)) # Test if function arguments work. self.assertEqual([(['int'], ('int', 'function'))], p.get_method_signature(o.AddObserver)) # This one's for completeness. self.assertEqual([([None], ['int'])], p.get_method_signature(o.RemoveObserver))
def __init__(self, parent, ident): self.ren = None # The Renderer self.rwi = None # The reneder Windows self.action = "" # No action # create wx.Frame and wxVTKRenderWindowInteractor to put in it wx.Frame.__init__(self, parent, ident, "DRE wxVTK demo", size=(400,400)) # create a menuBar menuBar = wx.MenuBar() # add a File Menu menuFile = wx.Menu() itemQuit = menuFile.Append(-1, "&Quit", "Quit application") self.Bind(wx.EVT_MENU, self.OnQuit, itemQuit) menuBar.Append(menuFile, "&File") # add an Action Menu # menuAction = wx.Menu() # itemSelect = menuAction.AppendCheckItem(-1, "&Select\tS", "Select an object") # self.Bind(wx.EVT_MENU, self.OnSelect, itemSelect) # menuBar.Append(menuAction, "&File") self.SetMenuBar(menuBar) self.statusBar = self.CreateStatusBar() self.statusBar.SetFieldsCount(2) self.statusBar.SetStatusWidths([-4, -1]) # the render is a 3D Scene self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.2, 0.5, 0.7) # create the world self.CreateWorld(self.ren) #make sure the RWI sizes to fill the frame self.rwi = wxVTKRenderWindow(self, -1) self.rwi.GetRenderWindow().AddRenderer(self.ren) # trap mouse events self.rwi.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.rwi.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self.rwi.Bind(wx.EVT_LEFT_DCLICK, self.OnSelect) self.rwi.Bind(wx.EVT_MOTION, self.OnMotion) # store the Picker self.picker = vtk.vtkCellPicker() self.pickedActor = None self.pickedProperty = None self.selectProperty = vtk.vtkProperty() self.selectProperty.SetColor(1,0,0)
def Initialize(self): ''' @rtype: None ''' vtkPythonMetaDataSet.Initialize(self) if not self.getDataSet(): return if not isinstance(self.getProperty(), vtk.vtkObject): return property = vtk.vtkProperty.SafeDownCast(self.getProperty()) if not property: property = vtk.vtkProperty() self.setProperty(property)
def Sphere(self, x, y, z): ''' create a cylinder and return the actor ''' obj = vtk.vtkSphereSource() obj.SetThetaResolution(16) obj.SetPhiResolution(16) self.MapObject(obj) prop = vtk.vtkProperty() prop.SetColor(0.3, 0.5, 0.8) prop.SetAmbientColor(0.5, 0.5, 0) prop.SetDiffuseColor(0, 0.8, 0.5) prop.SetSpecular(0.5) self.actor.SetProperty(prop) self.actor.SetPosition(x, y, z)
def __init__(self): ActorFactory.ActorFactory.__init__(self) # share property across all the actors self._sphere = vtk.vtkSphereSource() self._sphere.SetThetaResolution(40) self._sphere.SetPhiResolution(40) self._visibility = True self._Property = vtk.vtkProperty() self._Property.SetColor(1, 1, 0) self._bounds = (-1, 1, -1, 1, -1, 1)
def Sphere(self, x, y, z): ''' create a cylinder and return the actor ''' obj = vtk.vtkSphereSource() obj.SetThetaResolution(16) obj.SetPhiResolution(16) actor = self.MapObject(obj) prop = vtk.vtkProperty() prop.SetColor(0.5, 0.5, 0.5) prop.SetAmbientColor(0.5, 0.5, 0) prop.SetDiffuseColor(0.8, 0.3, 0.3) prop.SetSpecular(0.5) actor.SetProperty(prop) actor.SetPosition(x, y, z)
def CreateBallReference(self): self.ball_reference = vtk.vtkSphereSource() self.ball_reference.SetRadius(5) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.ball_reference.GetOutput()) p = vtk.vtkProperty() p.SetColor(1, 0, 0) self.ball_actor = vtk.vtkActor() self.ball_actor.SetMapper(mapper) self.ball_actor.SetProperty(p)
def __init__(self, VolumneRendererWindow, selectedColor, PixX, PixY, PixZ): super(MouseInteractorHighLightActor, self).__init__(self) self.selectedColor = selectedColor self.VolumneRendererWindow = VolumneRendererWindow self.AddObserver("LeftButtonPressEvent", self.leftButtonPressEvent) self.PixX = PixX self.PixY = PixY self.PixZ = PixZ self.LastPickedActor = None self.LastPickedProperty = vtk.vtkProperty()
def Disc(pos=(0, 0, 0), normal=(0, 0, 1), r1=0.5, r2=1, c="coral", bc="darkgreen", lw=1, alpha=1, res=12): """ Build a 2D disc of internal radius `r1` and outer radius `r2`, oriented perpendicular to `normal`. |Disk| """ ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) ps.SetCircumferentialResolution(res * 6) # ~2pi ps.Update() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(ps.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(pd) actor = Actor() # vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) return actor
def __init__(self, render, label, color): self.render = render self.colors = { 'Marine Blue': [0.1, 0.2, 0.4], 'Deep Blue': [0.2, 0.2, 1.0], 'Red': [1.0, 0.0, 0.0], 'Yellow': [1.0, 1.0, 0.0], 'Green': [0.0, 1.0, 0.0], 'Orange': [1.0, 0.5, 0.0], 'Magenta': [1.0, 0.0, 1.0], 'Grey': [0.5, 0.5, 0.5], 'Black': [0.0, 0.0, 0.0], 'Cyan': [0.0, 1.0, 1.0], 'Turquoise': [0.0, 0.5, 0.5], 'White': [1.0, 1.0, 1.0], 'Light green': [0.5, 1.0, 0.5], } if color: self.color = color else: self.color = "Yellow" self.__isSelected = False self.points = vtk.vtkPoints() self.points.SetDataTypeToFloat() self.property = vtk.vtkProperty() self.actor = vtk.vtkActor() self.actor.SetProperty(self.property) self.label = label self.labels = vtk.vtkVectorText() self.labels.SetText(label) self.labelProp = vtk.vtkProperty() self.labelActor = vtk.vtkFollower()
def Cone(self, x, y, z): ''' create a cylinder and return the actor ''' obj = vtk.vtkConeSource() self.MapObject(obj) # self.actor.GetProperty().SetColor(0.3, 0.8, 0.5) # self.actor.GetProperty().SetOpacity(0.35) # self.actor.GetProperty().SetSpecular(0.5) prop = vtk.vtkProperty() prop.SetColor(0.3, 0.8, 0.5) prop.SetAmbientColor(1, 1, 0) prop.SetOpacity(0.35) prop.SetSpecular(0.5) self.actor.SetProperty(prop) self.actor.SetPosition(x, y, z)
def __init__(self, parent=None): #self.AddObserver("LeftButtonPressEvent", self.leftButtonPressEvent) #self.AddObserver("KeyPressEvent", self.onKeyPress) #self.AddObserver("OnChar", self.onChar) self.AddObserver("CharEvent", self.onChar) self.LastPickedActor = None self.LastPickedProperty = vtk.vtkProperty() self.currentactor = None self.leftag = None self.txt_target = None self.txt_startp = None self.startp = None self.target = None
def Cone(self, x, y, z): ''' create a cylinder and return the actor ''' obj = vtk.vtkConeSource() actor = self.MapObject(obj) # self.actor.GetProperty().SetColor(0.3, 0.8, 0.5) # self.actor.GetProperty().SetOpacity(0.35) # self.actor.GetProperty().SetSpecular(0.5) prop = vtk.vtkProperty() prop.SetColor(0.3, 0.8, 0.5) prop.SetAmbientColor(1, 1, 0) prop.SetOpacity(0.35) prop.SetSpecular(0.5) actor.SetProperty(prop) actor.SetPosition(x, y, z)
def __init__(self, plugin): super().__init__(plugin) self._file_name = None self._load_thread = None self._components = None self._component_color = {} self._component_bounds = {} self._actors = {} self._silhouette_actors = {} self._caption_actors = {} self._show_captions = False self._actor_to_comp_name = {} self._render_mode = self.plugin.settings.value("window/render_mode", self.SHADED) self._bnds = None self._pps_actors = {} self._pps_caption_actors = {} self._last_picked_actor = None self._last_picked_property = vtk.vtkProperty() self.setupWidgets() self.setupMenuBar() self.setAcceptDrops(True) self.setCentralWidget(self._frame) self.updateWindowTitle() self._vtk_render_window = self._vtk_widget.GetRenderWindow() self._vtk_interactor = self._vtk_render_window.GetInteractor() self._style = OtterInteractorStyle3D(self) self._vtk_interactor.SetInteractorStyle(self._style) # TODO: set background from preferences/templates self._vtk_renderer.SetBackground([0.98, 0.98, 0.98]) # set anti-aliasing on self._vtk_renderer.SetUseFXAA(True) self._vtk_render_window.SetMultiSamples(1) self._vtk_interactor.Initialize() self._vtk_interactor.Start() self._setupOrientationMarker() self._setupCubeAxisActor() self.show() self._update_timer = QtCore.QTimer() self._update_timer.timeout.connect(self.onUpdateWindow) self._update_timer.start(250)
def main(): colors = vtk.vtkNamedColors() bounds = [-10.0, 10.0, 10.0, 20.0, -5.0, 5.0] boxSource = vtk.vtkTessellatedBoxSource() boxSource.SetLevel(3) boxSource.QuadsOn() boxSource.SetBounds(bounds) boxSource.SetOutputPointsPrecision(vtk.vtkAlgorithm.SINGLE_PRECISION) shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(boxSource.GetOutputPort()) shrink.SetShrinkFactor(.8) # Create a mapper and actor. mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(shrink.GetOutputPort()) back = vtk.vtkProperty() back.SetColor(colors.GetColor3d('Tomato')) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetColor(colors.GetColor3d('Banana')) actor.SetBackfaceProperty(back) # Create a renderer, render window, and interactor. renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene. renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('Silver')) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.ResetCameraClippingRange() # Render and interact. renderWindow.SetSize(640, 480) renderWindow.SetWindowName('TessellatedBoxSource') renderWindow.Render() renderWindowInteractor.Start()
def __init__(self): ActorFactory.ActorFactory.__init__(self) # share property across all the actors self._cylinder = vtk.vtkCylinderSource() self._cylinder.SetResolution(40) self._cylinder.CappingOn() self._Property = vtk.vtkProperty() self._Property.SetColor(1, 1, 0) self._bounds = (-1, 1, -1, 1, -1, 1) self._orientation = 'z' # self.GetTransform().RotateX(90) self._visibility = True
def __init__(self): ActorFactory.ActorFactory.__init__(self) self._WireFrameCube = WireFrameCubeFactory.WireFrameCubeFactory() self._SolidCube = EVSSolidCubeFactory.EVSSolidCubeFactory() self._CubePropertiesAreSet = 0 self._SphereMark1 = SphereMarkFactory.SphereMarkFactory() self._SphereMark1IsSet = 0 self._SphereMark2 = SphereMarkFactory.SphereMarkFactory() self._SphereMark2IsSet = 0 self._Property = vtk.vtkProperty()
def __init__(self): ActorFactory.ActorFactory.__init__(self) # the default is not apply any transforms self._t = None # Create the line self._Line = vtk.vtkLineSource() self._Line.SetResolution(25) self._LineProperty = vtk.vtkProperty() self._LineProperty.SetColor( 0.933, 0.505, 0.0) # default to orange self.SetLineOpacity(0.0) self._LineLength = 0 self._MarkersEnabled = True # Create the spheres self._Mark1 = ConeMarkerFactory2.ConeMarkerFactory2() self._Mark2 = ConeMarkerFactory2.ConeMarkerFactory2() self._Mark1.SetSize(16) self._Mark2.SetSize(16) self._Mark1.SetColor(0.0, 0.6, 1.0) # default to blue self._Mark2.SetColor(0.0, 1.0, 0.0) # default to green # Add them as children of this factory self.AddChild(self._Mark1) self.AddChild(self._Mark2) self.HideEndMarkers() # Set opacity of balls to 0.0 self._Mark1IsSet = 0 self._Mark2IsSet = 0 self._Mark1Position = None self._Mark2Position = None self._ElementSize = 1 # Brad made this one instead of zero self._SelectedActor = None self._lastSelectedMark = None self._sMeasurementUnit = 'pixels' self.BindEvent("<ButtonPress>", self.StartMoveMark) self.BindEvent("<ButtonRelease>", self.StopMoveMark) self.BindEvent("<B2-Motion>", self.DoMoveMark) self.BindEvent("<B1-Motion>", self.DoMoveMark) self.BindEvent("<Key-Delete>", self.ClearLineSegment)
def makeCustomAxes(self, outline, outlinefilter): """ create custom axes """ prop = vtk.vtkProperty() prop.SetColor(self.fgColor) x = vtk.vtkAxisActor() x.SetAxisTypeToX() # x.SetAxisPositionToMinMin() x.SetCamera(self.renderer.GetActiveCamera()) x.SetBounds(outline.GetBounds()) x.SetProperty(prop) x.SetRange(self.XLimit) x.SetPoint1(outline.GetBounds()[0], outline.GetBounds()[2], outline.GetBounds()[4]) x.SetPoint2(outline.GetBounds()[1], outline.GetBounds()[2], outline.GetBounds()[4]) return x
def __init__(self): self.colour = (0.0, 0.0, 1.0) self.opacity = 1 self.radius = 15.0 #self.position = (0.5,0.5, 1) self.points = [] self.orientation = "AXIAL" self.spacing = (1, 1, 1) self.mapper = vtk.vtkPolyDataMapper() self.actor = vtk.vtkActor() self.property = vtk.vtkProperty() self.__build_actor() self.__calculate_area_pixels()
def setElectrodeNoiseVisible(self): ''' Set actor properties based on electrodes selected for viewing. ''' self.electrode_centroid_clustering.getLabelsForElectrodes(self._electrodes) # assign electrode colors for elect in self._electrodes: prop = vtk.vtkProperty() if elect.clabel == -1: prop.SetColor(1, 1, 1) elect.polygonActor.VisibilityOn() elect.polygonActor.SetProperty(prop) else: elect.polygonActor.VisibilityOff() self.appwin.updateRenderQVTKWin()
def highlight(self, actors): for actor in actors: try: self.__renderer.pointsActors[actor] #if except: try: self.__renderer.elementsActors[actor] except: continue if actor in self.__selectedActorsProperties: continue current_property = vtk.vtkProperty() current_property.DeepCopy(actor.GetProperty()) self.__selectedActorsProperties[actor] = current_property actor.GetProperty().SetColor(255,0,0) self.GetInteractor().GetRenderWindow().Render()
def main(argv): if len(argv) < 2: print "usage:", argv[0], " data.vtk" exit(1) data_fn = argv[1] reader = vtk.vtkStructuredPointsReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() skin = vtk.vtkMarchingCubes() skin.ComputeNormalsOn() skin.ComputeGradientsOn() skin.SetValue(0, rgb[0][0]) skin.SetInput(data) skin_mapper = vtk.vtkPolyDataMapper() skin_mapper.SetInputConnection(skin.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin_actor = vtk.vtkActor() skin_property = vtk.vtkProperty() skin_property.SetColor(rgb[0][1], rgb[0][2], rgb[0][3]) skin_property.SetOpacity(opacity[0][1]) skin_actor.SetProperty(skin_property) skin_actor.SetMapper(skin_mapper) bone = vtk.vtkMarchingCubes() bone.ComputeNormalsOn() bone.ComputeGradientsOn() bone.SetValue(0, rgb[1][0]) bone.SetInput(data) bone_mapper = vtk.vtkPolyDataMapper() bone_mapper.SetInputConnection(bone.GetOutputPort()) bone_mapper.ScalarVisibilityOff() bone_actor = vtk.vtkActor() bone_actor.GetProperty().SetColor(rgb[1][1], rgb[1][2], rgb[1][3]) bone_actor.GetProperty().SetOpacity(opacity[1][1]) bone_actor.SetMapper(bone_mapper) renderer = vtk.vtkRenderer() renderWin = vtk.vtkRenderWindow() renderWin.AddRenderer(renderer) renderInteractor = vtk.vtkRenderWindowInteractor() renderInteractor.SetRenderWindow(renderWin) renderer.AddActor(skin_actor) #renderer.AddActor(bone_actor) renderer.SetBackground(0, 0, 0) renderWin.SetSize(400, 400) renderInteractor.Initialize() renderWin.Render() renderInteractor.Start()
def main(argv): if len(argv) < 2: print "usage:",argv[0]," data.vtk" exit(1) data_fn = argv[1] reader = vtk.vtkStructuredPointsReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() skin = vtk.vtkMarchingCubes() skin.ComputeNormalsOn() skin.ComputeGradientsOn() skin.SetValue(0, rgb[0][0]) skin.SetInput(data) skin_mapper = vtk.vtkPolyDataMapper() skin_mapper.SetInputConnection(skin.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin_actor = vtk.vtkActor() skin_property = vtk.vtkProperty() skin_property.SetColor(rgb[0][1], rgb[0][2], rgb[0][3]) skin_property.SetOpacity(opacity[0][1]) skin_actor.SetProperty(skin_property) skin_actor.SetMapper(skin_mapper) bone = vtk.vtkMarchingCubes() bone.ComputeNormalsOn() bone.ComputeGradientsOn() bone.SetValue(0, rgb[1][0]) bone.SetInput(data) bone_mapper = vtk.vtkPolyDataMapper() bone_mapper.SetInputConnection(bone.GetOutputPort()) bone_mapper.ScalarVisibilityOff() bone_actor = vtk.vtkActor() bone_actor.GetProperty().SetColor(rgb[1][1], rgb[1][2], rgb[1][3]) bone_actor.GetProperty().SetOpacity(opacity[1][1]) bone_actor.SetMapper(bone_mapper) renderer = vtk.vtkRenderer() renderWin = vtk.vtkRenderWindow() renderWin.AddRenderer(renderer) renderInteractor = vtk.vtkRenderWindowInteractor() renderInteractor.SetRenderWindow(renderWin) renderer.AddActor(skin_actor) #renderer.AddActor(bone_actor) renderer.SetBackground(0,0,0) renderWin.SetSize(400, 400) renderInteractor.Initialize() renderWin.Render() renderInteractor.Start()
def actors_step_2(contour_filter_leg): """ Creates the visualization actors for step 2 :param contour_filter_leg: The data SLC from the leg :return: A list with the leg actor """ # Clipping the knee skin with a sphere actor_leg, _ = clipping_skin_with_sphere(contour_filter_leg) # transparency and backface property prop = vtk.vtkProperty() prop.SetColor(colors.GetColor3d("SkinColor")) actor_leg.GetProperty().SetOpacity(0.666) actor_leg.SetBackfaceProperty(prop) return [actor_leg]
def main(): colors = vtk.vtkNamedColors() file_name = get_program_parameters() # Read the source file. reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(file_name) reader.Update() # Needed because of GetScalarRange output = reader.GetOutput() # scalar_range = output.GetScalarRange() # Create the mapper that corresponds the objects of the vtk.vtk file # into graphics elements mapper = vtk.vtkDataSetMapper() mapper.SetInputData(output) # mapper.SetScalarRange(scalar_range) mapper.ScalarVisibilityOff() # Create the Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetLineWidth(2.0) actor.GetProperty().SetColor(colors.GetColor3d("MistyRose")) backface = vtk.vtkProperty() backface.SetColor(colors.GetColor3d('Tomato')) actor.SetBackfaceProperty(backface) # Create the Renderer renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('Wheat')) # Create the RendererWindow renderer_window = vtk.vtkRenderWindow() renderer_window.SetSize(640, 480) renderer_window.AddRenderer(renderer) renderer_window.SetWindowName('ReadUnstructuredGrid') # Create the RendererWindowInteractor and display the vtk_file interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderer_window) interactor.Initialize() interactor.Start()
class STLComponent: prop = vtk.vtkProperty() @classmethod def SetProperty(self, color, diffuse, specular, specularPower): self.prop.SetColor(color[0], color[1], color[2]) self.prop.SetDiffuse(diffuse) self.prop.SetSpecular(specular) self.prop.SetSpecularPower(specularPower) def __init__(self, name): self.reader = vtk.vtkSTLReader() self.reader.SetFileName(name) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.reader.GetOutputPort()) self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self.actor.SetProperty(self.prop)
def box(self, scale=1): """Return the bounding box as a new ``Mesh``. :param float scale: box size can be scaled by a factor .. hint:: |latex.py|_ """ b = self.GetBounds() from vtkplotter.shapes import Box pos = (b[0] + b[1]) / 2, (b[3] + b[2]) / 2, (b[5] + b[4]) / 2 length, width, height = b[1] - b[0], b[3] - b[2], b[5] - b[4] oa = Box(pos, length * scale, width * scale, height * scale, c='gray') if isinstance(self.GetProperty(), vtk.vtkProperty): pr = vtk.vtkProperty() pr.DeepCopy(self.GetProperty()) oa.SetProperty(pr) oa.wireframe() return oa
def sphere(radius, center, resolution, color, position): sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(center) sphereSource.SetRadius(radius) sphereSource.SetThetaResolution(resolution) sphereMapper = vtk.vtkPolyDataMapper() sphereMapper.SetInputConnection(sphereSource.GetOutputPort()) property = vtk.vtkProperty() property.SetColor(color) sphereActor = vtk.vtkActor() sphereActor.SetMapper(sphereMapper) sphereActor.SetProperty(property) sphereActor.SetPosition(position) return sphereActor
def main(): colors = vtk.vtkNamedColors() # Create a cube. cubeSource = vtk.vtkCubeSource() shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(cubeSource.GetOutputPort()) shrink.SetShrinkFactor(0.9) # Create a mapper and actor. mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(shrink.GetOutputPort()) back = vtk.vtkProperty() back.SetColor(colors.GetColor3d('Tomato')) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetColor(colors.GetColor3d('Banana')) actor.SetBackfaceProperty(back) # Create a renderer, render window, and interactor. renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('Silver')) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.ResetCameraClippingRange() # Render and interact renderWindow.SetWindowName('ShrinkCube') renderWindow.Render() renderWindowInteractor.Start()
def CreateBallReference(self): MRAD = 3.0 proj = prj.Project() s = proj.spacing # The sphere's radius will be MRAD times bigger than the media of the # spacing values. r = (s[0] + s[1] + s[2]) / 3.0 * MRAD self.ball_reference = vtk.vtkSphereSource() self.ball_reference.SetRadius(r) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.ball_reference.GetOutput()) p = vtk.vtkProperty() p.SetColor(1, 0, 0) self.ball_actor = vtk.vtkActor() self.ball_actor.SetMapper(mapper) self.ball_actor.SetProperty(p)
def extractLargestRegion(actor, legend=None): '''Keep only the largest connected part of a mesh and discard all the smaller pieces. [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/largestregion.py) ''' conn = vtk.vtkConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.ScalarConnectivityOff() poly = actor.polydata(True) conn.SetInputData(poly) conn.Update() epoly = conn.GetOutput() if legend is True: legend = actor.legend eact = Actor(epoly, legend) pr = vtk.vtkProperty() pr.DeepCopy(actor.GetProperty()) eact.SetProperty(pr) return eact
def cone(height, center, radius, resolution, color, position): coneSource = vtk.vtkConeSource() coneSource.SetCenter(center) coneSource.SetHeight(height) coneSource.SetRadius(radius) coneSource.SetResolution(resolution) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(coneSource.GetOutputPort()) property = vtk.vtkProperty() property.SetColor(color) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.SetProperty(property) coneActor.SetPosition(position) return coneActor
def __init__(self, item_actor, plane, lut): self.cutter = vtkCutter() self.cutter.SetCutFunction(plane) self.cutter.SetInputConnection(item_actor.reader.GetOutputPort()) self.cutter.Update() self.mapper = vtkDataSetMapper() self.mapper.ScalarVisibilityOn() self.mapper.SetLookupTable(lut) self.mapper.SetInputConnection(self.cutter.GetOutputPort()) back = vtkProperty() back.SetColor(100, 100, 100) self.GetProperty().SetColor(1, 0, 0) self.GetProperty().EdgeVisibilityOff() self.GetProperty().SetLineWidth(3) self.SetMapper(self.mapper) self.SetBackfaceProperty(back)
def triangleFilter(actor, verts=True, lines=True): ''' Convert actor polygons and strips to triangles. Returns a new vtkActor. ''' from vtkplotter.actors import Actor poly = actor.polydata(False) tf = vtk.vtkTriangleFilter() tf.SetPassLines(lines) tf.SetPassVerts(verts) tf.SetInputData(poly) tf.Update() prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) tfa = Actor(tf.GetOutput()) tfa.SetProperty(prop) return tfa
def add_marker(coord, ren, color, radius, opacity=1.): ball_ref = vtk.vtkSphereSource() ball_ref.SetRadius(radius) ball_ref.SetCenter(coord) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(ball_ref.GetOutputPort()) prop = vtk.vtkProperty() prop.SetColor(color) prop.SetOpacity(opacity) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.SetProperty(prop) ren.AddActor(actor) return actor
def cone_gen(): vtk_property = vtk.vtkProperty() vtk_property.SetColor(0.0, .3, 1.0) vtk_property.SetDiffuse(0.7) vtk_property.SetSpecular(0.4) vtk_property.SetSpecularPower(20) cone = vtk.vtkConeSource() mapper = vtk.vtkPolyDataMapper() actor = vtk.vtkActor() cone.SetResolution(60) cone.SetRadius(12.0) cone.SetHeight(36.0) mapper.SetInputConnection(cone.GetOutputPort()) actor.SetMapper(mapper) actor.SetProperty(vtk_property) return cone, actor
def render_pvtu(file_prefix, img_prefix, step, imgCount, window=[400, 400]): filename = file_prefix + '_' + str(step) + '.pvtu' pvtuReader = vtkio.ReadPVTUFile(filename) pvtuReader.GetOutput().GetPointData().SetActiveAttribute("U_CHI", 0) colors = vtk.vtkNamedColors() output = pvtuReader.GetOutput() # Create the mapper that corresponds the objects of the vtk.vtk file # into graphics elements mapper = vtk.vtkDataSetMapper() mapper.SetInputData(output) # mapper.SetScalarRange(scalar_range) mapper.ScalarVisibilityOff() # Create the Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetLineWidth(2.0) actor.GetProperty().SetColor(colors.GetColor3d("MistyRose")) backface = vtk.vtkProperty() backface.SetColor(colors.GetColor3d('Tomato')) actor.SetBackfaceProperty(backface) # Create the Renderer renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('Wheat')) # Create the RendererWindow renderer_window = vtk.vtkRenderWindow() renderer_window.SetSize(640, 480) renderer_window.AddRenderer(renderer) renderer_window.SetWindowName('ReadUnstructuredGrid') # Create the RendererWindowInteractor and display the vtk_file interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderer_window) interactor.Initialize() interactor.Start()
def clone(self): """Clone the UGrid object to yield an exact copy.""" ugCopy = vtk.vtkUnstructuredGrid() ugCopy.DeepCopy(self._data) cloned = UGrid(ugCopy) pr = self.GetProperty() if isinstance(pr, vtk.vtkVolumeProperty): prv = vtk.vtkVolumeProperty() else: prv = vtk.vtkProperty() prv.DeepCopy(pr) cloned.SetProperty(prv) #assign the same transformation to the copy cloned.SetOrigin(self.GetOrigin()) cloned.SetScale(self.GetScale()) cloned.SetOrientation(self.GetOrientation()) cloned.SetPosition(self.GetPosition()) cloned.name = self.name return cloned